n, $ty, usize);
        wrap_shifts!($trait_wrap, $trait_assign_wrap, $fn_wrap, $fn_assign_wrap, $wrapping_fn, $ty, i8);
        wrap_shifts!($trait_wrap, $trait_assign_wrap, $fn_wrap, $fn_assign_wrap, $wrapping_fn, $ty, i16);
        wrap_shifts!($trait_wrap, $trait_assign_wrap, $fn_wrap, $fn_assign_wrap, $wrapping_fn, $ty, i32);
        wrap_shifts!($trait_wrap, $trait_assign_wrap, $fn_wrap, $fn_assign_wrap, $wrapping_fn, $ty, i64);
        wrap_shifts!($trait_wrap, $trait_assign_wrap, $fn_wrap, $fn_assign_wrap, $wrapping_fn, $ty, isize);
    };
    ($trait_wrap:ident, $trait_assign_wrap:ident, $fn_wrap:ident, $fn_assign_wrap:ident, $wrapping_fn:ident, $ty:ty, $rty:ty) => {
        impl $trait_wrap<$rty> for $ty {
            #[cfg(not(feature = "specialization"))]
            type Output = $ty;

            fn $fn_wrap(self, rhs: $rty) -> Self::Output {
                self.$wrapping_fn(rhs as u32)
            }
        }

        impl $trait_assign_wrap<$rty> for $ty {
            fn $fn_assign_wrap(&mut self, rhs: $rty) {
                *self = self.$wrapping_fn(rhs as u32)
            }
        }
    }
}

wrap_shifts!(@Shl, ShlAssign, ShlWrap, ShlAssignWrap, shl, shl_assign, shl_wrap, shl_assign_wrap, wrapping_shl);
wrap_shifts!(@Shr, ShrAssign, ShrWrap, ShrAssignWrap, shr, shr_assign, shr_wrap, shr_assign_wrap, wrapping_shr);

/// Shift right, return 0 if the number of bits shifted are higher than the
/// width of the type
///
/// This does the same as the `std::ops::Shr` trait for most types.
/// it is specialized for integer types to return zero on over- or underflow.
pub trait ShrSaturate<RHS=usize> {
    /// the return type of our shift operation
    type Output;
    /// shift right, return 0 if the number of bits shifted are higher than the
    /// width of the type
    fn shr_saturate(self, rhs: RHS) -> Self::Output;
}

/// Shift right in place, set self to 0 if the number of bits shifted are
/// higher than the width of the type
///
/// This does the same as the `std::ops::ShrAssign` trait for most types.
/// it is specialized for integer types to return zero on over- or underflow.
pub trait ShrSaturateAssign<RHS=usize> {
    /// shift right in place, set self to 0 if the number of bits shifted are
    /// higher than the width of the type
    fn shr_assign_saturate(&mut self, rhs: RHS);
}

#[cfg(feature = "specialization")]
impl<R, T: Shr<R>> ShrSaturate<R> for T {
    type Output = <T as Shr<R>>::Output;
    default fn shr_saturate(self, rhs: R) -> Self::Output { self >> rhs }
}

#[cfg(feature = "specialization")]
impl<R, T: ShrAssign<R>> ShrSaturateAssign<R> for T {
    default fn shr_assign_saturate(&mut self, rhs: R


1), ratio128));
	// if (channelMax > 2) out->c2 = _mm_add_ps(a->c2, _mm_mul_ps(_mm_sub_ps(b->c2, a->c2), ratio128));
	// if (channelMax > 3) out->c3 = _mm_add_ps(a->c3, _mm_mul_ps(_mm_sub_ps(b->c3, a->c3), ratio128));

	// https://devblogs.nvidia.com/lerp-faster-cuda/
	// fma(t, b, fnma(t, a, a));
	// // b*t - a*t + a
	out->c0 = _mm_fmadd_ps(ratio128, b->c0, _mm_fnmadd_ps(ratio128, a->c0, a->c0));

	__m128 w128 = _mm_set1_ps(1.0f / out->pos.w);

	if (channelMax > 1) out->c1 = _mm_mul_ps(w128, _mm_fmadd_ps(ratio128, b->c1, _mm_fnmadd_ps(ratio128, a->c1, a->c1)));
	if (channelMax > 2) out->c2 = _mm_mul_ps(w128, _mm_fmadd_ps(ratio128, b->c2, _mm_fnmadd_ps(ratio128, a->c2, a->c2)));
	if (channelMax > 3) out->c3 = _mm_mul_ps(w128, _mm_fmadd_ps(ratio128, b->c3, _mm_fnmadd_ps(ratio128, a->c3, a->c3)));
	//
	// __m256 w256 = _mm256_set1_ps(1.0f / out->pos.w);
	// out->c1_2 = _mm256_mul_ps(w256, _mm256_fmadd_ps(ratio256, b->c1_2, _mm256_fnmadd_ps(ratio256, a->c1_2, a->c1_2)));
}

#endif

inline void FixedRasterize( void* rOut, const void* rInRef0, const void* rInRef1, const void* rInRef2, float ratio, const SrShaderContext* context, uint8 channel, bool final = false )
{

	// 对于scanline扫描的，将透视插值坐标，插值回正常值
	if (final)
	{
		FastRasterizeFinalSSE((SrRendVertexSSE*)rOut, (SrRendVertexSSE*)rInRef0, (SrRendVertexSSE*)rInRef1, ratio, channel);
	}
	else
	{
		FastRasterizeSSE((SrRendVertexSSE*)rOut, (SrRendVertexSSE*)rInRef0, (SrRendVertexSSE*)rInRef1, ratio, channel);
	}
};

/**
 *@brief 渲染primitive
 */
SR_ALIGN struct SrRendPrimitve
{
	SrVertexBuffer*		vb;					///< vertex buffer
	SrIndexBuffer*		ib;
	SrShaderContext		shaderConstants;
	const SrSwShader*			shader;

	void * operator new(size_t size);
	void operator delete(void *memoryToBeDeallocated);
};

/**
 *@brief 光栅化处理器
 */
SR_ALIGN class SrRasterizer
{
public:
	/**
	 *@brief 光栅化用三角形，引用渲染顶点
	 */
	SR_ALIGN struct SrRastTriangle
	{
		SrRendVertex p[3];
		SrRendPrimitve* primitive;
	};

public:
	SrRasterizer(void);
	virtual ~SrRasterizer(void);

	/**
	 *@brief 初始化光栅化处理器
	 */
	void Init(SrSoftRenderer* renderer);

	// 接受外界来自primitive的渲染调用，缓存
	bool DrawPrimitive( SrPrimitve* primitive );
	bool DrawLine(const float3& from, const float3& to);
	bool DrawRHZPrimitive( SrRendPrimitve& rendPrimitive );

	// 帧末尾，对缓存的primitive进行渲染
	void Flush();

	// 光栅化primitive入口
	static void ProcessRasterizer( SrRendPrimitve* in_primitive, SrFragment* out_gBuffer );

	// 对三角形进行针对视锥的裁剪，并提交
	static void RasterizeTriangle_Clip( SrRastTriangle& tri, float zNear, float zFar );
	// 光栅化处理后的三角形入口
	static void RasterizeTriangle( SrRastTriangle& tri, bool subtri = false );
	static void WriteLine(const void* vertA, const void* vertB, SrRendPrimitve* primitive, uint32 count,
	                      float ratio_step,
	                      float ratio_start, uint32 address_start);

	//////////////////////////////////////////////////////////////////////////
	// 内部光栅化函数

	// 光栅化平顶三角形
	static void Rasterize_Top_Tri_F( SrRastTriangle& tri );
	// 光栅化平底三角形
	static void Rasterize_Bottom_Tri_F( SrRastTriangle& tri );
	// 光栅化扫描线
	static void Rasterize_ScanLine( uint32 line, float fstart, float fcount, const void* vertA, const void* vertB, SrRendPrimitve* primitive, ERasterizeMode rMode = eRm_WireFrame, bool toptri = true );
	// 光栅化 需要裁剪的 扫描线
	static void Rasterize_ScanLine_Clipped( uint32 line, float fstart, float fcount, float clipStart, float clipCount, const void* vertA, const void* vertB, SrRendPrimitve* primitive, ERasterizeMode rMode = eRm_Solid );
	// 光栅化并写pixel
	static void Rasterize_WritePixel( const void* vertA, const void* vertB, float ratio, SrFragment* thisBuffer, SrRendPrimitve* primitive, uint32 address );

	static int Draw_Line(int x0, int y0, int x1, int y1, int color, uint32 *vb_start, int lpitch);
	static int Clip_Line(int &x1,int &y1,int &x2, int &y2);
	static int Draw_Clip_Line(int x0,int y0, int x1, int y1, int color, uint32 *dest_buffer, int lpitch);
public:
	std::list<SrRendPrimitve*> m_rendPrimitives;			///< 渲染Primitive队列，每帧接受DrawPrimitive调用后缓存在这里，flush结束时删除

	std::list<SrRendPrimitve*> m_rendPrimitivesRHZ;		///< 渲染Primitive队列，每帧接受DrawPrimitive调用后缓存在这里，flush结束时删除

	std::vector<float4> m_rendDynamicVertex;

	SrTexture* m_MemSBuffer;								///< 动态纹理，当前帧
	SrTexture* m_BackS1Buffer;								///< 动态纹理，用于缓存jitAA开启时的上一帧
	SrTexture* m_BackS2Buffer;								///< 动态纹理，用于缓存jitAA开启时的上一帧

	SrRasTaskDispatcher* m_rasTaskDispatcher;				///< Task分发器，用于任务动态调度
	class SrSoftRenderer* m_renderer;
};

#endif // SrRasterizer_


b fn day2(input_lines: &[String]) -> (u64, u64) {
    let passwords: Vec<PasswordAndPolicy> = input_lines.iter().map(|line| PasswordAndPolicy::new(line)).collect();
    let part1 = passwords.iter().filter(|password| password.valid_for_part_one()).count() as u64;
    let part2 = passwords.iter().filter(|password| password.valid_for_part_two()).count() as u64;
    (part1, part2)
}<reponame>U007D/block_chain
#![warn(clippy::all, clippy::nursery, clippy::pedantic, rust_2018_idioms)]
#![forbid(bare_trait_objects)]
#![allow(clippy::match_bool)]
// To use the `unsafe` keyword, change to `#![allow(unsafe_code)]` (do not remove); aids auditing.
#![allow(unsafe_code)]
// Safety-critical application lints
#![deny(
    clippy::pedantic,
    clippy::float_cmp_const,
    clippy::indexing_slicing,
    clippy::integer_arithmetic,
    clippy::option_unwrap_used,
    clippy::result_unwrap_used
)]
// Uncomment before ship to reconcile use of possibly redundant crates, debug remnants, missing license files and more
//#![warn(clippy::cargo, clippy::restriction, missing_docs, warnings)]
//#![deny(warnings)]

mod args;
mod block;
mod consts;
mod error;
mod hasher;
#[cfg(test)]
mod worlds_worst_hasher;

pub use block::Block;
pub use hasher::Hasher;
use std::result::Result as StdResult;
use structopt::StructOpt;

pub use {args::Args, consts::*, error::Error};

pub type Result<T> = StdResult<T, Error>;

fn main() -> Result<()> {
    let _args = Args::from_args();
    println!("Hello, blockchain!");
    Ok(())
}
// not used//! # bstr_parse
//!
//! Adds the ability to parse numbers out of `&[u8]`s. Like so:
//!
//! ```
//! use bstr_parse::*;
//!
//! let text: &[u8] = b"1234";
//! let num: u32 = text.parse().unwrap();
//! assert_eq!(num, 1234);
//! ```

#![warn(missing_docs)]
#![warn(missing_crate_level_docs)]
#![warn(private_doc_tests)]
#![warn(clippy::all)]
#![warn(clippy::cargo)]
#![forbid(unsafe_code)]

/// An extension trait for `parse`.
pub trait BStrParse {
    /// Parses this string slice into another type.
    ///
    /// Because `parse` is so general, it can cause problems with type
    /// inference. As such, `parse` is one of the few times you'll see
    /// the syntax affectionately known as the 'turbofish': `::<>`. This
    /// helps the inference algorithm understand specifically which type
    /// you're trying to parse into.
    ///
    /// `parse` can parse any type that implements the [`FromBStr`] trait.

    ///
    /// # Errors
    ///
    /// Will return [`Err`] if it's not possible to parse this string slice into
    /// the desired type.
    ///
    /// [`Err`]: FromBStr::Err
    ///
    /// # Examples
    ///
    /// Basic usage
    ///
    /// ```
    /// use bstr_parse::*;
    /// let four: u32 = b"4".parse().unwrap();
    ///
    /// assert_eq!(4, four);
    /// ```
    ///
    /// Using the 'turbofish' instead of annotating `four`:
    ///
    /// ```
    /// use bstr_parse::*;
    /// let four = b"4".parse::<u32>();
    ///
    /// assert_eq!(Ok(4), four);
    /// ```
    ///
    /// Failing to parse:
    ///
    /// ```
    /// use bstr_parse::*;
    /// let nope = b"j".parse::<u32>();
    ///
    /// assert!(nope.is_err());
    /// ```
    fn parse<F: From


ry selected cell giving its row
 * and its previous value.
 *  - [Update per col][org.jetbrains.kotlinx.dataframe.api.Update.perCol] to provide a new value for every selected cell giving its column.
 * @param [expression] The [Row Column Expression][org.jetbrains.kotlinx.dataframe.documentation.ExpressionsGivenRowAndColumn.RowColumnExpression] to provide a new value for every selected cell giving its row and column.
 */
@Refine
@Interpretable("UpdatePerRowCol")
public inline fun <T, C> Update<T, C>.perRowCol(crossinline expression: RowColumnExpression<T, C, C>): DataFrame<T> =
    updateImpl { row, column, _ -> expression(row, column) }

/**
 * ## Update Expression
 * @see ExpressionsGivenRow.RowValueExpression.WithExample
 * @see ExpressionsGivenRow.AddDataRowNote
 */
public typealias UpdateExpression<T, C, R> = AddDataRow<T>.(C) -> R

/** ## With
 * Provide a new value for every selected cell given its row and its previous value using a
 * [row value expression][org.jetbrains.kotlinx.dataframe.RowValueExpression].
 *
 * For example:
 *
 * `df.`[update][update]` { city }.`[with][with]` { name.firstName + " from " + it }`
 *
 * `df.`[update][update]` { city }.`[with][with]` { it.uppercase() }`
 *
 *
 *
 * ## Note
 * [update with][org.jetbrains.kotlinx.dataframe.api.Update.with]-,
 * [convert with][org.jetbrains.kotlinx.dataframe.api.Convert.with]-
 * and [add][org.jetbrains.kotlinx.dataframe.api.add]-like expressions use [AddDataRow][org.jetbrains.kotlinx.dataframe.api.AddDataRow] instead of [DataRow][org.jetbrains.kotlinx.dataframe.DataRow] as the DSL's receiver type.
 * This is an extension to [RowValueExpression][org.jetbrains.kotlinx.dataframe.RowValueExpression] and
 * [RowExpression][org.jetbrains.kotlinx.dataframe.RowExpression] that provides access to
 * the modified/generated value of the preceding row ([AddDataRow.newValue][org.jetbrains.kotlinx.dataframe.api.AddDataRow.newValue]).
 * ## See Also
 * - [Update per col][org.jetbrains.kotlinx.dataframe.api.Update.perCol] to provide a new value for every selected cell giving its column.
 * - [Update per row col][org.jetbrains.kotlinx.dataframe.api.Update.perRowCol] to provide a new value for every selected cell giving its row and column.
 * @param [expression] The [Row Value Expression][org.jetbrains.kotlinx.dataframe.documentation.ExpressionsGivenRow.RowValueExpression.WithExample] to update the rows with.
 */
@Refine
@Interpretable("UpdateWith0")
public inline fun <T, C, R : C?> Update<T, C>.with(crossinline expression: UpdateExpression<T, C, R>): DataFrame<T> =
    updateImpl { row, _, value ->
        expression(row, value)
    }

/** ## As Frame
 *
 * Updates selected [column group][ColumnGroup] as a [DataFrame] with the given [expression].
 *
 * Provide a new value for every selected dataframe using a [dataframe expression][org.jetbrains.kotlinx.dataframe.DataFrameExpression].
 *
 * For example:
 *
 * `df.`[update][update]` { name


b_p/2+g_p/10)/(g_p-jb_p)+math.sqrt((v0+jb_p/2+g_p/10)^2/(g_p-jb_p)^2+2*y/(g_p-jb_p))
end
-- </Abschnitt 2>

-- <Abschnitt 3> - Komplizierte Funktionen die die Game-Engine nachbilden und so Einschlagpunkte, etc. berechnen.

function collide(x,y,vx,vy,x2,y2,r2)
-- Berechnet, ob und nach welcher Zeit der Ball im Zustand (x,y,vx,vy) mit der Kugel an (x2,y2) mit Radius r2 kollidiert
local leftb=x2-r2-r1
local rightb=x2+r2+r1
local lowerb=y2-r2-r1
local upperb=y2+r2+r1

local txlb=time((leftb-x)/vx) -- Zeit zur linken Begrenzung
local txrb=time((rightb-x)/vx) -- Zeit zur rechten Begrenzung
local tyla=time(t1_y(y,vy,lowerb)) --untere Grenze steigend (ascending)
local tyld=time(t2_y(y,vy,lowerb)) --untere Grenze fallend (descending)
local tyua=time(t1_y(y,vy,upperb)) --obere Grenze steigend (ascending)
local tyud=time(t2_y(y,vy,upperb)) --obere Grenze fallend (descending)
local tp=time(vy/g-1/10) -- Zeit bis die Ballkurve auf dem Höhepunkt ist (kann in der Vergangenheit liegen)

local t1,t2,t_coll=0,0,-1

if (vx>0) then
		t1=max(max(txlb,tyla),0)
		t2=min(txrb,tyld)
	else
		t1=max(max(txrb,tyla),0)
		t2=min(txlb,tyld)
end

if (t1<t2) and (t1<300) and (math.abs(t1-t2)<100) then
	for t=t1,t2,0.2 do
		local xnew,ynew=x+vx*t,y_b(y,vy,t)
		if ((xnew-x2)^2+(ynew-y2)^2<(r1+r2)^2) then
			t_coll=t
			break
		end
	end
end

return t_coll
end

function estimate_t(x,y,vx,vy,height)
-- schätzt den Ort des Balles bei der Höhe height fallend und die Zeit bis dahin

local collision=1
local t_wall,t_net,t_netsphere=0,0,0
local t_ret,x_ret,y_ret,vx_ret,vy_ret=0,0,0,0,0
local t_height=0
while(collision==1) do
	t_netsphere=collide(x,y,vx,vy,400,316,7)
	if (vx>0)
		then
		t_wall=time((768.5-x)/vx)
		t_net=time((361.5-x)/vx)
		else
		t_wall=time((31.5-x)/vx)
		t_net=time((438.5-x)/vx)
	end
	local t=10000
	if ((t_netsphere>0) and (t_netsphere<t)) then t=t_netsphere end
	if (((t_net>0) and (t_net<t)) and (y_b(y,vy,t_net)<316)) then t=t_net end
	if ((t_wall>0) and (t_wall<t)) then t=t_wall end
	t_height=time(t2_y(y,vy,height))
	if (t_height>t) then
		if (t==t_netsphere) then
			t_ret=t_ret+t
			vx_ret=0
			vy


e2D)
		{
			return new XElement (X_table2D,
				new XAttribute (X_category, table2D.Category),
				new XAttribute (X_name, table2D.Title),
				new XAttribute (X_address, HexNum (table2D.Location)),
				Table.CommentValuesStats (table2D.Xmin, table2D.Xmax),
				GetAxisXElement (X_axisX, table2D.RangeX.Pos, table2D.NameX, table2D.UnitX),
				Table.CommentValuesStats (table2D.Ymin, table2D.Ymax, table2D.Yavg),
				GetValuesElement (table2D.RangeY.Pos, table2D.UnitY, table2D.TableType), new XElement (X_description, table2D.Description));
		}

		static XElement GetXElement (Table3D table3D)
		{
			return new XElement (X_table3D,
				new XAttribute (X_category, table3D.Category),
				new XAttribute (X_name, table3D.Title),
				new XAttribute (X_address, HexNum (table3D.Location)),
				Table.CommentValuesStats (table3D.Xmin, table3D.Xmax),
				GetAxisXElement (X_axisX, table3D.RangeX.Pos, table3D.NameX, table3D.UnitX),
				Table.CommentValuesStats (table3D.Ymin, table3D.Ymax),
				GetAxisXElement (X_axisY, table3D.RangeY.Pos, table3D.NameY, table3D.UnitY),
				Table.CommentValuesStats (table3D.Zmin, table3D.Zmax, table3D.Zavg),
				GetValuesElement (table3D.RangeZ.Pos, table3D.UnitZ, table3D.TableType),
				new XElement (X_description, table3D.Description));
		}

		static XElement GetAxisXElement (string axisType, int address, string name, string unit)
		{
			return new XElement (axisType,
				new XAttribute (X_address, HexNum (address)),
				new XAttribute (X_name, name),
				new XAttribute (X_unit, unit));
		}

		static XElement GetValuesElement (int address, string unit, TableType tableType)
		{
			return new XElement (X_values,
				new XAttribute (X_address, HexNum (address)),
				new XAttribute (X_unit, unit),
				new XAttribute (X_tableType, tableType.ToStr ()));
		}

		static string HexNum (int num)
		{
			return "0x" + num.ToString ("X");
		}
	}
}


ewFactor );

protected:
	float					maxMagnitude;
	float					minMagnitude;
};

class hhVelocityZone : public hhZone {
public:
	CLASS_PROTOTYPE( hhVelocityZone );

	void					Spawn( void );
	void					Save( idSaveGame *savefile ) const;
	void					Restore( idRestoreGame *savefile );
	virtual void			Think( void );
	virtual void			EntityEncroaching(idEntity *ent);
	virtual void			EntityLeaving(idEntity *ent);

protected:
	void					Event_SetNewVelocity( idVec3 &newvel );

protected:
	idInterpolate<idVec3>	velocityInterpolator;
	bool					bKillsMonsters;
	bool					bReorient;
	bool					bShowVector;
	int						interpolationTime;
};

class hhShuttleRecharge : public hhZone {
public:
	CLASS_PROTOTYPE( hhShuttleRecharge );

	void					Spawn(void);
	void					Save( idSaveGame *savefile ) const;
	void					Restore( idRestoreGame *savefile );
	virtual bool			ValidEntity(idEntity *ent);
	virtual void			EntityEntered(idEntity *ent);
	virtual void			EntityLeaving(idEntity *ent);
	virtual void			EntityEncroaching(idEntity *ent);

protected:
	int						amountHealth;
	int						amountPower;
};

class hhDockingZone : public hhZone {
public:
	CLASS_PROTOTYPE( hhDockingZone );

	void					Spawn(void);
	void					Save( idSaveGame *savefile ) const;
	void					Restore( idRestoreGame *savefile );
	virtual bool			ValidEntity(idEntity *ent);
	virtual void			EntityEntered(idEntity *ent);
	virtual void			EntityEncroaching(idEntity *ent);
	virtual void			EntityLeaving(idEntity *ent);
	void					RegisterDock(hhDock *d);

	//rww - network code
	virtual void			WriteToSnapshot( idBitMsgDelta &msg ) const;
	virtual void			ReadFromSnapshot( const idBitMsgDelta &msg );
	virtual void			ClientPredictionThink( void );

protected:
	idEntityPtr<hhDock>		dock;
};

class hhShuttleDisconnect : public hhZone {
public:
	CLASS_PROTOTYPE( hhShuttleDisconnect );

	void					Spawn(void);
	virtual bool			ValidEntity(idEntity *ent);
	virtual void			EntityEntered(idEntity *ent);
	virtual void			EntityEncroaching(idEntity *ent);
	virtual void			EntityLeaving(idEntity *ent);

protected:
};

class hhShuttleSlingshot : public hhZone {
public:
	CLASS_PROTOTYPE( hhShuttleSlingshot );

	void					Spawn(void);
	virtual bool			ValidEntity(idEntity *ent);
	virtual void			EntityEntered(idEntity *ent);
	virtual void			EntityEncroaching(idEntity *ent);
	virtual void			EntityLeaving(idEntity *ent);

protected:
};

class hhRemovalVolume : public hhZone {
public:
	CLASS_PROTOTYPE( hhRemovalVolume );

	void					Spawn(void);
	virtual bool			ValidEntity(idEntity *ent);
	virtual void			EntityEntered(idEntity *ent);
	virtual void			EntityEncroaching(idEntity *ent);
	virtual void			EntityLeaving(idEntity *ent);

protected:
};

#endif /* __GAME_GRAVITYZONE_H__ */


_G.16b
	//G = ROTL32(F,19)
	rol32	dig_G,dig_F,19
	//F = E
	mov	vdig_F.16b,vdig_E.16b
	// E=Target, TT2=src, TT1,SS1,SS2 is free
	// E = P0(TT2);
	ushr	vSS2.4s, vTT2.4s, 32 - 9
	ushr	vSS1.4s, vTT2.4s, 32 - 17
	sli	vSS2.4s, vTT2.4s, 9
	sli	vSS1.4s, vTT2.4s, 17
	eor	vdig_E.16b, vTT2.16b, vSS1.16b
	eor	vdig_E.16b, vdig_E.16b, vSS2.16b

.endm

.macro sm3_round_4	round:req,wp:req

	ushr	vtmp0.4s,vdig_A.4s,32 - 12
	add	vSS1.4s,vdig_E.4s,vTj.4s
	sli	vtmp0.4s,vdig_A.4s,12
	rev32	vmsg\wp\().16b,vmsg\wp\().16b
	add	vTT1.4s,vSS1.4s,vtmp0.4s	//SS1 Done
	rol32	SS1,TT1,7
	eor	vSS2.16b,vSS1.16b,vtmp0.16b	//SS2 Done
	eor	vword_pair.16b,vmsg\round\().16b,vmsg\wp\().16b
	eor	vTT1.16b,vdig_A.16b,vdig_B.16b
	eor	vTT2.16b,vdig_E.16b,vdig_F.16b
	eor	vTT1.16b,vTT1.16b,vdig_C.16b
	eor	vTT2.16b,vTT2.16b,vdig_G.16b
	add	vSS1.4s,vSS1.4s,vmsg\round\().4s
	add	vSS2.4s,vSS2.4s,vword_pair.4s
	add	vTT1.4s,vTT1.4s,vdig_D.4s
	add	vTT2.4s,vTT2.4s,vdig_H.4s
	ushr	vtmp0.4s,vTj.4s,32-1
	add	vTT1.4s,vTT1.4s,vSS2.4s	//TT1 Done
	sli	vtmp0.4s,vTj.4s,1
	add	vTT2.4s,vTT2.4s,vSS1.4s //TT2 Done
	mov	vTj.16b,vtmp0.16b
	//D=C
	mov	vdig_D.16b,vdig_C.16b
	//C = ROTL32(B, 9);
	ushr	vdig_C.4s,vdig_B.4s,32 - 9
	sli	vdig_C.4s,vdig_B.4s,9
	//B=A
	mov	vdig_B.16b,vdig_A.16b
	//A=TT1
	mov	vdig_A.16b,vTT1.16b
	//	H=G
	mov	vdig_H.16b,vdig_G.16b
	//G = ROTL32(F,19)
	rol32	dig_G,dig_F,19
	//F = E
	mov	vdig_F.16b,vdig_E.16b
	// E=Target, TT2=src, TT1,SS1,SS2 is free
	// E = P0(TT2);
	ushr	vSS2.4


,b))-(d+f)/2-n)):(g=C1(a.K,vR(a.G,b)),l[0]<l[2]?(l[0]+=10,h=D1(a.K,wR(a.G,b))-a.o):(l[2]+=10,h=D1(a.K,wR(a.G,b))+a.o)),0<n&&(c=h+~~((4*a.o+4)/8),T1(a,g+(f+n)/2,c,e,!0),W1(a,a.Q)),T1(a,g,h,We,!0));e=0;if(0!=r){n=50;for(c=g=0;4>c;++c)h=1<c?c-2:c+2,l[c]<n?(e=c,n=l[c],g=l[h]):l[c]==n&&l[h]>g&&(e=c,g=l[h]);switch(e){case 0:g=C1(a.K,vR(a.G,b));h=D1(a.K,wR(a.G,b))-a.O-d/2;break;case 1:g=C1(a.K,vR(a.G,b))+\na.O+d/2;h=D1(a.K,wR(a.G,b));break;case 2:g=C1(a.K,vR(a.G,b));h=D1(a.K,wR(a.G,b))+a.O+d/2;break;default:g=C1(a.K,vR(a.G,b))-a.O-d/2,h=D1(a.K,wR(a.G,b))}if(1==r)Qm(a.T,new U1(g-a.O,h-a.O,2*a.O,2*a.O)),a.F||Qm(a.N,new V1(g,h,H1(a,b)?-3:a.r[b]));else{switch(e){case 2:case 0:r=2*a.O;e=0;g-=a.O;break;case 1:r=0;e=2*a.O;h-=a.O;break;default:r=0,e=2*a.O,h-=a.O}Qm(a.T,new U1(g-a.O,h-a.O,2*a.O,2*a.O));a.F||Qm(a.N,new V1(g,h,H1(a,b)?-3:a.r[b]));Qm(a.T,new U1(g+r-a.O,h+e-a.O,2*a.O,2*a.O));a.F||Qm(a.N,new V1(g+\nr,h+e,H1(a,b)?-3:a.r[b]))}}}-8==a.z&&v1(a,-9)}\nfunction Z1(a,b){var c,d,e,f,g,h,j,l,n,o,r,t;n=new t1;c=new t1;f=new t1;j=new M1;h=new M1;d=Y(a.G,0,b);e=Y(a.G,1,b);var y=D1(a.K,wR(a.G,d)),v=C1(a.K,vR(a.G,e)),s=D1(a.K,wR(a.G,e)),y=\'<line id="\'+(null!=a.k?a.k:Ki+R1)+":Bond:"+d+ub+e+\'" class="event" x1="\'+Fw(100*C1(a.K,vR(a.G,d)))/100+xa+Fw(100*y)/100+wa+Fw(100


1": {Type: vo.DataTypeArray, ElemTypeInfo: &vo.TypeInfo{Type: vo.DataTypeString}},
				"key2": {Type: vo.DataTypeArray, ElemTypeInfo: &vo.TypeInfo{Type: vo.DataTypeNumber}},
				"key3": {Type: vo.DataTypeObject, Properties: map[string]*vo.TypeInfo{
					"key31": {Type: vo.DataTypeString},
					"key32": {Type: vo.DataTypeString},
					"key33": {Type: vo.DataTypeArray, ElemTypeInfo: &vo.TypeInfo{Type: vo.DataTypeNumber}},
					"key34": {Type: vo.DataTypeObject, Properties: map[string]*vo.TypeInfo{
						"key341": {Type: vo.DataTypeString},
						"key342": {Type: vo.DataTypeString},
					}},
				}},
				"key4": {Type: vo.DataTypeObject, Properties: map[string]*vo.TypeInfo{
					"key31": {Type: vo.DataTypeString},
					"key32": {Type: vo.DataTypeString},
					"key33": {Type: vo.DataTypeArray, ElemTypeInfo: &vo.TypeInfo{Type: vo.DataTypeNumber}},
					"key34": {Type: vo.DataTypeObject, Properties: map[string]*vo.TypeInfo{
						"key341": {Type: vo.DataTypeString},
						"key342": {Type: vo.DataTypeString},
					},
					}},
				},
			},
			runner: mockRunner,
		}
		ret, err := c.Invoke(ctx, map[string]any{
			"input": "1123",
		})

		assert.NoError(t, err)
		assert.Equal(t, int64(11231123), ret["key0"])
		assert.Equal(t, []any{"hello", "world"}, ret["key1"])
		assert.Equal(t, []any{float64(123), float64(345)}, ret["key2"])
		assert.Equal(t, nil, ret["key4"])
		assert.Equal(t, nil, ret["key3"].(map[string]any)["key33"])
	})
	t.Run("field convert failed", func(t *testing.T) {
		codeTpl = `
async def main(args:Args)->Output:
    params = args.params
    ret: Output = {
        "key0": params['input'] + params['input'],
        "key1": ["hello", "world"],
  		"key2": [123, "345"],
        "key3": {
            "key31": "hi",
			"key32": "hello",
			"key34": {
				"key341":"123",
				"key343": ["hello", "world"],
				}
        },
    }
    return ret
`
		ctx := t.Context()
		ctx = ctxcache.Init(ctx)
		ret := map[string]any{
			"key0": int64(11231123),
			"key1": []any{"hello", "world"},
			"key2": []interface{}{int64(123), "345"},
			"key3": map[string]interface{}{"key31": "hi", "key32": "hello", "key34": map[string]interface{}{"key341": "123", "key343": []any{"hello", "world"}}},
		}
		response := &coderunner.RunResponse{
			Result: ret,
		}
		mockRunner.EXPECT().Run(gomock.Any(), gomock.Any()).Return(response, nil)

		c := &Runner{
			code:     codeTpl,
			language: coderunner.Python,
			outputConfig: map[string]*vo.TypeInfo{
				"key0": {Type: vo.DataTypeInteger},
				"key1": {Type: vo.DataTypeArray, ElemTypeInfo: &vo.TypeInfo{Type: vo.DataTypeNumber}},
				"key2": {Type: vo.DataTypeArray, ElemTypeInfo: &vo.TypeInfo{Type: vo.DataTypeNumber}},
				"key3": {Type: vo.DataTypeObject, Properties: map[string]*v


(nestedState.key == auth.States.credentialsRegistration);

  await currentState
      .post(auth.SubmitCredentials('phoebes@smellycat.com', 'imnotursala'));
  assert(nestedState.key == auth.States.demographicsRegistration);

  var sb = StringBuffer();
  declBuilder.format(sb, DotFormatter());
  print(sb.toString());

  // await currentState.post(SubmitDemographics('Phoebe', 'Buffay'));

  // authService.doRegister = (req) async {
  //   return Result.value(AuthorizedUser('Phoebe', 'Buffay', 'phoebes@smellycat.com'));
  // };
  // await currentState.post(Messages.submitRegistration);

  // assert(currentState.key == States.userHome);
  // assert(currentState.isInState(States.authenticated));
  // assert(currentState.dataValue<AuthenticatedData>()!.user.email == 'phoebes@smellycat.com');
}

// Example of enabling logging output from tree_state_machine library.
void initLogging() {
  hierarchicalLoggingEnabled = true;
  Logger('tree_state_machine').level = Level.ALL;
  Logger.root.onRecord.listen((record) {
    print(
        '${record.level.name}: ${record.time}: ${record.loggerName}: ${record.message}');
  });
}
import 'dart:typed_data';
import 'dart:ui' as ui;

import 'package:flutter/widgets.dart';

import 'package:flutter_hbb/common.dart';

Future<ui.Image?> decodeImageFromPixels(
  Uint8List pixels,
  int width,
  int height,
  ui.PixelFormat format, {
  int? rowBytes,
  int? targetWidth,
  int? targetHeight,
  bool allowUpscaling = true,
}) async {
  if (targetWidth != null) {
    assert(allowUpscaling || targetWidth <= width);
    if (!(allowUpscaling || targetWidth <= width)) {
      print("not allow upscaling but targetWidth > width");
      return null;
    }
  }
  if (targetHeight != null) {
    assert(allowUpscaling || targetHeight <= height);
    if (!(allowUpscaling || targetHeight <= height)) {
      print("not allow upscaling but targetHeight > height");
      return null;
    }
  }

  final ui.ImmutableBuffer buffer;
  try {
    buffer = await ui.ImmutableBuffer.fromUint8List(pixels);
  } catch (e) {
    return null;
  }

  final ui.ImageDescriptor descriptor;
  try {
    descriptor = ui.ImageDescriptor.raw(
      buffer,
      width: width,
      height: height,
      rowBytes: rowBytes,
      pixelFormat: format,
    );
    if (!allowUpscaling) {
      if (targetWidth != null && targetWidth > descriptor.width) {
        targetWidth = descriptor.width;
      }
      if (targetHeight != null && targetHeight > descriptor.height) {
        targetHeight = descriptor.height;
      }
    }
  } catch (e) {
    print("ImageDescriptor.raw failed: $e");
    buffer.dispose();
    return null;
  }

  final ui.Codec codec;
  try {
    codec = await descriptor.instantiateCodec(
      targetWidth: targetWidth,
      targetHeight: targetHeight,
    );
  } catch (e) {
    print("instantiateCodec failed: $e");
    buffer.dispose();
    descriptor.dispose();
    return null;
  }

  final ui.FrameInfo frameInfo;
  try {
    frameInfo = await codec.getNextFrame();
  } catch (e) {
    print("getNextFrame failed: $e");
    codec.dispose


LR_W<'a> {
    w: &'a mut W,
}
impl<'a> CLR_W<'a> {
    #[doc = r"Writes `variant` to the field"]
    #[inline(always)]
    pub fn variant(self, variant: CLR_AW) -> &'a mut W {
        unsafe { self.bits(variant.into()) }
    }
    #[doc = "No effect. Use the DMA_USEBURST_SET Register to disable dma_sreq from generating requests."]
    #[inline(always)]
    pub fn clr_0(self) -> &'a mut W {
        self.variant(CLR_AW::CLR_0)
    }
    #[doc = "Enables dma_sreq\\[C\\]
to generate DMA requests. Writing to a bit where a DMA channel is not implemented has no effect."]
    #[inline(always)]
    pub fn clr_1(self) -> &'a mut W {
        self.variant(CLR_AW::CLR_1)
    }
    #[doc = r"Writes raw bits to the field"]
    #[inline(always)]
    pub unsafe fn bits(self, value: u32) -> &'a mut W {
        self.w.bits = (self.w.bits & !0xffff_ffff) | ((value as u32) & 0xffff_ffff);
        self.w
    }
}
impl W {
    #[doc = "Bits 0:31 - Set the appropriate bit to enable dma_sreq to generate requests."]
    #[inline(always)]
    pub fn clr(&mut self) -> CLR_W {
        CLR_W { w: self }
    }
}
#[cfg(test)]
mod tests {
    use crate::insertion_sort;

    #[test]
    fn sort() {
        let mut data = vec![5, 4, 3, 2, 1];
        insertion_sort(&mut data);
        assert_eq!(data, [1, 2, 3, 4, 5]);
    }
}

pub fn insertion_sort<T: PartialOrd>(v: &mut [T]) {
    for i in 1..=v.len() {
        let mut j = i - 1;
        while j > 0 && v[j - 1] > v[j] {
            v.swap(j - 1, j);
            j -= 1;
        }
    }
}
<reponame>tareksalem/Gotcha
use iced::{container, Background, Color, button, Vector, text_input};

pub const PRIMARY_COLOR: Color = Color::from_rgba(34 as f32 / 255.0, 40 as f32 / 255.0, 49 as f32 / 255.0, 1.0);
pub const LIGHT_PRIMARY_COLOR: Color = Color::from_rgba(57 as f32 / 255.0, 62 as f32 / 255.0, 70 as f32 / 255.0, 0.8);
pub const LIGHT_COLOR: Color = Color::from_rgba(238 as f32 / 255.0, 238 as f32 / 255.0, 238 as f32 / 255.0, 1.0);
pub const TEXT_COLOR: Color =  LIGHT_COLOR;
const BORDER_COLOR: Color =
    Color::from_rgba(0 as f32 / 255.0, 0 as f32 / 255.0, 17 as f32 / 255.0, 0.29);
pub const PINK: Color = Color::from_rgba(245 as f32 / 255.0, 40 as f32 / 255.0,145 as f32 / 255.0,0.8);
pub const SECONDARY_COLOR: Color =  Color::from_rgba(255 as f32 / 255.0, 255 as f32 / 255.0, 145 as f32 / 255.0, 0.8);
pub const GREEN: Color = Color::from_rgba(0 as f32 / 255.0,174 as f32 / 255.0,145 as f32 / 255.0,0.8);
pub const LIGHT_GREEN: Color = Color::from_rgba(0 as f32 / 255.0,199 as f32 / 255.0,0 as f32 / 255.0,0.34);
pub const LIGHT_SECONDARY_COLOR: Color = Color::from_rgba(177 as f32 / 255.0,199 as f32 / 255.0,0 as f32 / 255.0,0.34);
pub const LIGHT_ACCUA: Color = Color::from_rgba(60 as f32 / 255.0, 252 as f32 / 255.0, 255 as f32 / 255.0, 0.66);
pub const ACCENT: Color = Color::from_rgba(
    31 as f32 / 255.0,


"field-thu-narrow-relative+1": "下周四",
	"field-tue-narrow-relative+0": "本周二",
	"field-mon-relative+0": "本周一",
	"field-tue-narrow-relative+1": "下周二",
	"field-mon-relative+1": "下周一",
	"field-tue-narrow-relative+-1": "上周二",
	"field-second-short": "秒",
	"field-second": "秒",
	"field-fri-short-relative+0": "本周五",
	"field-sat-relative+-1": "上周六",
	"field-fri-short-relative+1": "下周五",
	"field-sun-relative+-1": "上周日",
	"field-month-relative+0": "本月",
	"field-month-relative+1": "下个月",
	"field-week": "周",
	"field-sat-short-relative+0": "本周六",
	"field-sat-short-relative+1": "下周六",
	"field-year-relative+0": "今年",
	"field-week-relative+-1": "上周",
	"field-year-relative+1": "明年",
	"field-quarter-short": "季",
	"field-sun-short-relative+-1": "上周日",
	"field-thu-short-relative+-1": "上周四",
	"field-tue-short-relative+-1": "上周二",
	"field-mon-relative+-1": "上周一",
	"field-sat-narrow-relative+-1": "上周六",
	"field-month-narrow": "月",
	"field-week-relative+0": "本周",
	"field-sun-short-relative+0": "本周日",
	"field-week-relative+1": "下周",
	"field-sun-short-relative+1": "下周日"
}
//end v1.x content
);function update(source) {
    var duration = d3.event && d3.event.altKey ? 5000 : 500;

    // Compute the new tree layout.
    var nodes = tree.nodes(root).reverse();

    // Normalize for fixed-depth.
    nodes.forEach(function(d) { d.y = d.depth * 180; });

    // Update the nodes…
    var node = vis.selectAll("g.node")
            .data(nodes, function(d) { return d.id || (d.id = ++i); });

    // Enter any new nodes at the parent's previous position.
    var nodeEnter = node.enter().append("svg:g")
            .attr("class", "node")
            .attr("transform", function(d) { return "translate(" + source.y0 + "," + source.x0 + ")"; })
            .on("click", function(d) { toggle(d); update(d); });

    nodeEnter.append("svg:circle")
            .attr("r", 1e-6)
            .style("fill", function(d) { return d._children ? "lightsteelblue" : "#fff"; });

    nodeEnter.append("svg:text")
            .attr("x", function(d) { return d.children || d._children ? -10 : 10; })
            .attr("dy", ".35em")
            .attr("


;
    localStorage.setItem("time", selectedTime);
    localStorage.removeItem("game_id");
    window.location.href = "/chess.html";
};

const formatLastPlayed = ts => new Date(ts).toLocaleString("en-US", { hour: "2-digit", minute: "2-digit" });

const showLoadGameMenu = async () => {
    const resp = await fetch(`/get_active_games/?user_id=${currentUser.id}`);
    const data = await resp.json();
    const app = document.getElementById("app");
    app.innerHTML = `<div class="saved-games-container"></div>`;
    const container = app.querySelector(".saved-games-container");
    if (!data?.length) container.innerHTML = `<div class="saved-game-card no-game"><span>No saved games found</span></div>`;
    else data.forEach(g => {
        const card = document.createElement("div");
        card.className = "saved-game-card";
        card.innerHTML = `
Game #${g.game_id}${g.player_color}

Difficulty: ${g.difficulty}

Last Played: ${formatLastPlayed(g.last_played)} (UTC)

`;
        card.addEventListener("click", () => { playClickSound(); localStorage.setItem("game_id", g.game_id); window.location.href = "/chess.html"; });
        container.appendChild(card);
    });
    const backBtn = document.createElement("button");
    backBtn.className = "btn btn-exit";
    backBtn.textContent = "Back";
    backBtn.addEventListener("click", () => { playClickSound(); showMainMenu(currentUser); });
    app.appendChild(backBtn);
};

const actions = {
    "new": () => { localStorage.removeItem("game_id"); showModeMenu(); },
    "mode-vs-bot": () => showVsBotMenu(),
    "mode-vs-user": () => { },
    "load-game": () => showLoadGameMenu(),
    "back-main": () => showMainMenu(currentUser),
    "back-mode": () => showModeMenu(),
    "back-vsbot": () => showVsBotMenu(),
    "choose-difficulty": () => showDifficultyMenu(),
    "choose-color": () => showColorMenu(),
    "choose-time": () => showTimeMenu(),
    "start-game": () => startGame()
};

const handleAction = a => {
    if (a.startsWith("select-difficulty-")) { selectedDifficulty = a.split("-")[2]; showDifficultyMenu(); return; }
    if (a.startsWith("select-color-")) { selectedColor = a.split("-")[2]; showColorMenu(); return; }
    if (a.startsWith("select-time-")) { selectedTime = parseInt(a.split("-")[2]); showTimeMenu(); return; }
    if (actions[a]) actions[a]();
};

const init = async () => {
    const app = document.getElementById("app");
    const user = tg.initDataUnsafe.user;
    if (!user) { app.innerHTML = "
❌ Could not get user info
"; return; }
    currentUser = user;
    localStorage.setItem("user_id", user.id);
    try {
        const resp = await fetch("/check_user/", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ user_id: user.id }) });
        const result = await resp.json();
        if (!result.allowed) { app.innerHTML = `
❌ ${


    pub transport: String,
    /// Allowed Ip's list.
    pub allowlist: Vec<SocketAddr>,
    /// Blocked Ip's list.
    pub blocklist: Vec<IpAddr>,
    /// Allowed peer's `PeerId` list.
    pub allow_peer_list: Vec<PeerId>,
    /// Blocked peers's `PeerId` list.
    pub block_peer_list: Vec<PeerId>,
    /// If set permission is true, that server is permissioned,
    /// not receive DHT's peer message, only stable connect.
    /// if set permission is false, that server is permissionless,
    /// receive DHT's peer message and stable's peer message.
    /// if you use a permissionless server, but only receive stable's message,
    /// you can set `only_stable_data` is true.
    /// Recommend use `permission = false & only_stable_data = true` replace permissioned.
    pub permission: bool,
    /// If `only_stable_data` is true, only receive stable connected peer's data.
    pub only_stable_data: bool,
    /// When delivery feedback has set length, it will split length of data to return.
    /// For example. set `delivery_length = 8`,
    /// and when a `Data(1u64, PeerId, vec![1u8, 2u8, ..., 100u8]),
    /// if send success, will return:
    /// `Delivery(DeliveryType::Data, 1u64, true, vec![1u8, 2u8, ..., 8u8])`
    /// if send failure, will return:
    /// `Delivery(DeliveryType::Data, 1u64, false, vec![1u8, 2u8, ..., 8u8])`
    pub delivery_length: usize,
}

impl Config {
    pub fn default(addr: SocketAddr) -> Self {
        Self {
            db_dir: PathBuf::from("./"),
            addr: addr,
            transport: "quic".to_owned(), // TODO Default
            allowlist: vec![],
            blocklist: vec![],
            allow_peer_list: vec![],
            block_peer_list: vec![],
            permission: false,
            only_stable_data: false,
            delivery_length: 0,
        }
    }

    pub fn new(
        db_dir: PathBuf,
        addr: SocketAddr,
        transport: String,
        allowlist: Vec<SocketAddr>,
        blocklist: Vec<IpAddr>,
        allow_peer_list: Vec<PeerId>,
        block_peer_list: Vec<PeerId>,
        permission: bool,
        only_stable_data: bool,
        delivery_length: usize,
    ) -> Self {
        Self {
            db_dir,
            addr,
            transport,
            allowlist,
            blocklist,
            allow_peer_list,
            block_peer_list,
            permission,
            only_stable_data,
            delivery_length,
        }
    }
}
pub mod tx;
pub mod boundednum;
pub mod note;
pub mod params;
pub mod account;
pub mod cipher;
pub mod key;
pub mod tree;

mod borsh;
mod sample;
<filename>src/content/mod.rs
#[doc(hidden)]
pub mod polyfill;
pub use error::{FromContentError, ToContentError};
pub use mime_ext::MimeExt;

#[cfg(feature = "encoding")]
mod encoding;
mod error;
mod mime_ext;
#[cfg(any(feature = "serde-base", feature = "serde-full"))]
mod serde_support;
#[cfg(feature = "unhtml-html")]
mod unhtml_support;

use crate::mime::Mime;

// TODO: use T: AsyncRead as type of data
// TODO: declare mime as generics when const generics is stable
/// deserialize from response body by `Content-Type` of `Response`.
/// target type of `http_service` method should implement FromContent.
pub trait FromContent: Sized {
    fn from_content(data: Vec<u8>, content_type: &Mime) -> Result<Self, FromContentError>;
}

// TODO: use T: AsyncRead as ty


recursively\\n\\t\\t\\t$tw.utils.each(Object.keys(item).sort(),function(key) {\\n\\t\\t\\t\\tt = convertDataItemValueToStrings(item[key]);\\n\\t\\t\\t\\tif(t !== undefined) {\\n\\t\\t\\t\\t\\tresults.push.apply(results,t);\\n\\t\\t\\t\\t}\\n\\t\\t\\t});\\n\\t\\t}\\n\\t\\treturn results;\\n\\t}\\n\\treturn [item.toString()];\\n}\\n\\n/*\\nReturn an array of the string representation of the keys of a data item, or \\\"undefined\\\" if the item is undefined\\n*/\\nfunction convertDataItemKeysToStrings(item) {\\n\\t// Return the item as a string\\n\\tif(item === undefined) {\\n\\t\\treturn item;\\n\\t} else if(typeof item === \\\"object\\\") {\\n\\t\\tif(item === null) {\\n\\t\\t\\treturn [];\\n\\t\\t}\\n\\t\\tvar results = [];\\n\\t\\tif($tw.utils.isArray(item)) {\\n\\t\\t\\tfor(var i=0; i\u003Citem.length; i++) {\\n\\t\\t\\t\\tresults.push(i.toString());\\n\\t\\t\\t}\\n\\t\\t\\treturn results;\\n\\t\\t} else {\\n\\t\\t\\t$tw.utils.each(Object.keys(item).sort(),function(key) {\\n\\t\\t\\t\\tresults.push(key);\\n\\t\\t\\t});\\n\\t\\t\\treturn results;\\n\\t\\t}\\n\\t}\\n\\treturn [];\\n}\\n\\nfunction getDataItemType(data,indexes) {\\n\\t// Get the item\\n\\tvar item = getDataItem(data,indexes);\\n\\t// Return the item type\\n\\tif(item === undefined) {\\n\\t\\treturn item;\\n\\t} else if(item === null) {\\n\\t\\treturn \\\"null\\\";\\n\\t} else if($tw.utils.isArray(item)) {\\n\\t\\treturn \\\"array\\\";\\n\\t} else if(typeof item === \\\"object\\\") {\\n\\t\\treturn \\\"object\\\";\\n\\t} else {\\n\\t\\treturn typeof item;\\n\\t}\\n}\\n\\nfunction getItemAtIndex(item,index) {\\n\\tif($tw.utils.hop(item,index)) {\\n\\t\\treturn item[index];\\n\\t} else if($tw.utils.isArray(item)) {\\n\\t\\tindex = $tw.utils.parseInt(index);\\n\\t\\tif(index \u003C 0) { index = index + item.length };\\n\\t\\treturn item[index]; // Will be undefined if index was out-of-bounds\\n\\t} else {\\n\\t\\treturn undefined;\\n\\t}\\n}\\n\\n/*\\nGiven a JSON data structure and an array of index strings, return the value at the end of the index chain, or \\\"undefined\\\" if any of the index strings are invalid\\n*/\\nfunction getDataItem(data,indexes) {\\n\\tif(indexes.length === 0 || (indexes.length === 1 && indexes[0] === \\\"\\\")) {\\n\\t\\treturn data;\\n\\t}\\n\\t// Get the item\\n\\tvar item = data;\\n\\tfor(var i=0; i\u003Cindexes.length; i++) {\\n\\t\\tif(item !== undefined) {\\n\\t\\t\\tif(item !== null && [\\\"number\\\",\\\"string\\\",\\\"boolean\\\"].indexOf(typeof item) === -1) {\\n\\t\\t\\t\\titem = getItemAtIndex(item,indexes[i]);\\n\\t\\t\\t} else {\\n\\t\\t\\t\\titem = undefined;\\n\\t\\t\\t}\\n\\t\\t}\\n\\t}\\n\\treturn item;\\n}\\n\\n/*\\nGiven a JSON data structure, an array of index strings and a value, return the data structure with the value added at the end of the


() const TIGHTDB_NOEXCEPT;

    Array* release() TIGHTDB_NOEXCEPT;

private:
    Array* m_ptr;
};

/// Calls `Array::destroy_deep(ref, alloc)` if the guarded 'ref'
/// (`ref`) is not zero when the guard is destroyed.
class DeepArrayRefDestroyGuard {
public:
    DeepArrayRefDestroyGuard(Allocator&) TIGHTDB_NOEXCEPT;

    DeepArrayRefDestroyGuard(ref_type, Allocator&) TIGHTDB_NOEXCEPT;

    ~DeepArrayRefDestroyGuard() TIGHTDB_NOEXCEPT;

    void reset(ref_type) TIGHTDB_NOEXCEPT;

    ref_type get() const TIGHTDB_NOEXCEPT;

    ref_type release() TIGHTDB_NOEXCEPT;

private:
    ref_type m_ref;
    Allocator& m_alloc;
};

// Implementation:

// DestroyGuard<T>

template<class T> inline DestroyGuard<T>::DestroyGuard() TIGHTDB_NOEXCEPT:
    m_ptr(0)
{
}

template<class T> inline DestroyGuard<T>::DestroyGuard(T* ptr) TIGHTDB_NOEXCEPT:
    m_ptr(ptr)
{
}

template<class T> inline DestroyGuard<T>::~DestroyGuard() TIGHTDB_NOEXCEPT
{
    if (m_ptr)
        m_ptr->destroy();
}

template<class T> inline void DestroyGuard<T>::reset(T* ptr) TIGHTDB_NOEXCEPT
{
    if (m_ptr)
        m_ptr->destroy();
    m_ptr = ptr;
}

template<class T> inline T* DestroyGuard<T>::get() const TIGHTDB_NOEXCEPT
{
    return m_ptr;
}

template<class T> inline T* DestroyGuard<T>::release() TIGHTDB_NOEXCEPT
{
    T* ptr = m_ptr;
    m_ptr = 0;
    return ptr;
}

// DeepArrayDestroyGuard

inline DeepArrayDestroyGuard::DeepArrayDestroyGuard() TIGHTDB_NOEXCEPT:
    m_ptr(0)
{
}

inline DeepArrayDestroyGuard::DeepArrayDestroyGuard(Array* ptr) TIGHTDB_NOEXCEPT:
    m_ptr(ptr)
{
}

inline DeepArrayDestroyGuard::~DeepArrayDestroyGuard() TIGHTDB_NOEXCEPT
{
    if (m_ptr)
        m_ptr->destroy_deep();
}

inline void DeepArrayDestroyGuard::reset(Array* ptr) TIGHTDB_NOEXCEPT
{
    if (m_ptr)
        m_ptr->destroy_deep();
    m_ptr = ptr;
}

inline Array* DeepArrayDestroyGuard::get() const TIGHTDB_NOEXCEPT
{
    return m_ptr;
}

inline Array* DeepArrayDestroyGuard::release() TIGHTDB_NOEXCEPT
{
    Array* ptr = m_ptr;
    m_ptr = 0;
    return ptr;
}

// DeepArrayRefDestroyGuard

inline DeepArrayRefDestroyGuard::DeepArrayRefDestroyGuard(Allocator& alloc) TIGHTDB_NOEXCEPT:
    m_ref(0),
    m_alloc(alloc)
{
}

inline DeepArrayRefDestroyGuard::DeepArrayRefDestroyGuard(ref_type ref,
                                                          Allocator& alloc) TIGHTDB_NOEXCEPT:
    m_ref(ref),
    m_alloc(alloc)
{
}

inline DeepArrayRefDestroyGuard::~DeepArrayRefDestroyGuard() TIGHTDB_NOEXCEPT
{
    if (m_ref)
        Array::destroy_deep(m_ref, m_alloc);
}

inline void DeepArrayRefDestroyGuard::reset(ref_type ref) TIGHTDB_NOEXCEPT
{
    if (m_ref)
        Array::destroy_deep(m_ref, m_alloc);
    m_ref = ref;
}

inline ref_type DeepArrayRefDestroyGuard::get() const TIGHTDB_NOEXCEPT
{
    return m_ref;
}

inline ref_type DeepArrayRefDestroyGuard::release() TIGHTDB_NOEXCEPT
{
    ref_type ref = m_ref;
    m_ref = 0;
    return ref;
}

} // namespace _impl
} // namespace tightdb

#endif // TIGHTDB_IMPL_DESTROY_GUARD_HPP
/*
 * Copyright (C) 2016 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not us


r.c<0)){x=r.a
w=s.y
w===$&&A.a()
w=x>w.a
x=w}else x=!0
if(x)return
v=s.d.h(0,e.gem(e).toLowerCase())
x=v.r
x===$&&A.a()
if(!x)return
x=v.b
x===$&&A.a()
if(x<1)r=A.uB(r,-0.0,-((1-x)*(r.d-r.b)/2))
if(r.c-r.a<1.5)r=A.uB(r,0.5,0)
x=v.e
x===$&&A.a()
u=x>0?new A.aF(x,x):null
x=s.RG
w=e.gem(e).toLowerCase()
if(x.h(0,w)==null)x.m(0,w,$.a6().aP())
x=v.d
x===$&&A.a()
if(x>0&&!J.n(v.f,C.L)&&!J.n(v.f,C.L)){x=s.p2
x===$&&A.a()
x.sa7(0,C.K)
x.sb_(v.d)
w=v.f
w.toString
x.sS(0,w)
x=!1
if(g)if(e.gjV()!==0){x=e.x
x=x.c-x.a>5}w=v.d/2
if(x)d.bi(s.Po(A.uB(r,-w,-0.0),e.gjV()),s.p2)
else s.m_(d,A.uB(r,-w,-0.0),s.p2,u)}t=v.gC6()
if(!t.k(0,C.L)){x=s.p2
x===$&&A.a()
x.sa7(0,C.V)
x.sS(0,t)
if(g&&e.gjV()!==0&&r.c-r.a>5){d.bi(s.Po(r,e.gjV()),s.p2)
if(e.gem(e)==="intron")s.Kc(d,e,f,g)}else s.m_(d,r,s.p2,u)}if(!g&&r.c-r.a>200&&e.gem(e)==="intron")s.Kc(d,e,f,g)},
bzU(d,e,f){return this.aaq(d,e,f,!1)},
Kc(d,e,f,g){var x,w,v,u,t,s,r,q,p,o,n,m,l=this,k=e.x,j=k.c-k.a
if(j<4||e.gjV()===0)return
x=e.x.gbk()
w=C.c.aE((f.d-f.b)/2,3,8)
v=e.gjV()>0?1:-1
k=l.k4
k===$&&A.a()
k.sa7(0,C.K)
k.sb_(1.2)
u=l.d.r
u.toString
k.sS(0,u)
if(j<500){t=$.a6().aP()
t.bN(0,x.a-3*v,x.b-w)
t.xJ(6*v,w)
t.xJ(-6*v,w)
d.bi(t,l.k4)}else{s=C.c.ba(j,500)
r=(j-s*500)/2
t=$.a6().aP()
for(k=x.b-w,u=6*v,q=-6*v,


692](https://github.com/vuejs/composition-api/issues/692)) ([8c27d80](https://github.com/vuejs/composition-api/commit/8c27d80))

# [1.0.0-rc.8](https://github.com/vuejs/composition-api/compare/v1.0.0-rc.7...v1.0.0-rc.8) (2021-04-29)

### Bug Fixes

* **reactive:** align behavior with vue-next ([#689](https://github.com/vuejs/composition-api/issues/689)) ([37fcbaa](https://github.com/vuejs/composition-api/commit/37fcbaa))
* Memory leak caused by global variables. ([#686](https://github.com/vuejs/composition-api/issues/686)) ([badff82](https://github.com/vuejs/composition-api/commit/badff82))

# [1.0.0-rc.7](https://github.com/vuejs/composition-api/compare/v1.0.0-rc.6...v1.0.0-rc.7) (2021-04-18)

### Bug Fixes

* **types:** optional Boolean prop types [#636](https://github.com/vuejs/composition-api/issues/636) ([#678](https://github.com/vuejs/composition-api/issues/678)) ([a081227](https://github.com/vuejs/composition-api/commit/a081227))

### Features

* **types:** export ComponentInternalInstance, close [#677](https://github.com/vuejs/composition-api/issues/677), close [#675](https://github.com/vuejs/composition-api/issues/675) ([ccae670](https://github.com/vuejs/composition-api/commit/ccae670))

# [1.0.0-rc.6](https://github.com/vuejs/composition-api/compare/v1.0.0-rc.5...v1.0.0-rc.6) (2021-03-29)

### Bug Fixes

* **types:** allow any object in toRefs ([#668](https://github.com/vuejs/composition-api/issues/668)) ([7284ad9](https://github.com/vuejs/composition-api/commit/7284ad9))

# [1.0.0-rc.5](https://github.com/vuejs/composition-api/compare/v1.0.0-rc.4...v1.0.0-rc.5) (2021-03-11)

# [1.0.0-rc.4](https://github.com/vuejs/composition-api/compare/v1.0.0-rc.3...v1.0.0-rc.4) (2021-03-11)

### Bug Fixes

* **types:** RequiredKeys type ([#655](https://github.com/vuejs/composition-api/issues/655)) ([0677a18](https://github.com/vuejs/composition-api/commit/0677a18))

# [1.0.0-rc.3](https://github.com/vuejs/composition-api/compare/v1.0.0-rc.2...v1.0.0-rc.3) (2021-03-03)

### Bug Fixes

* update types to algin with vue-next ([#653](https://github.com/vuejs/composition-api/issues/653)) ([24eaa56](https://github.com/vuejs/composition-api/commit/24eaa56))

# [1.0.0-rc.2](https://github.com/vuejs/co


/***************************************************************************************

  Xceed Toolkit for MAUI is a multiplatform toolkit offered by Xceed Software Inc.,
  makers of the popular WPF Toolkit.

  COPYRIGHT (C) 2023 Xceed Software Inc. ALL RIGHTS RESERVED.

  This program is provided to you under the terms of a Xceed Community License
  For more details about the Xceed Community License please visit the products GitHub or NuGet page .

  DISCLAIMER: This code is provided as-is and without warranty of any kind, express or implied. The
  author(s) and owner(s) of this code shall not be liable for any damages or losses resulting from
  the use or inability to use the code.

  ***************************************************************************


graph paragraph = paragraphForBoundsTest(TextAlign.start);
      paragraph.layout(const ParagraphConstraints(width: double.infinity));
      underTest.drawParagraph(paragraph, Offset.zero);
      underTest.endRecording();
      expect(paragraph.width, double.infinity);
      expect(paragraph.height, 20);
      expect(underTest.pictureBounds, const Rect.fromLTRB(0, 0, 220, 20));
    });
  });

  group('drawDRRect', () {
    final RRect rrect = RRect.fromLTRBR(10, 10, 50, 50, const Radius.circular(3));
    final SurfacePaint somePaint = SurfacePaint()
      ..color = const Color(0xFFFF0000);

    test('Happy case', () {
      underTest.drawDRRect(rrect, rrect.deflate(1), somePaint);
      underTest.endRecording();
      underTest.apply(mockCanvas, screenRect);

      _expectDrawDRRectCall(mockCanvas, <String, dynamic>{
        'path':
          'Path('
            'MoveTo(${10.0}, ${47.0}) '
            'LineTo(${10.0}, ${13.0}) '
            'Conic(${10.0}, ${10.0}, ${10.0}, ${13.0}, w = ${0.7071067690849304}) '
            'LineTo(${47.0}, ${10.0}) '
            'Conic(${50.0}, ${10.0}, ${10.0}, ${50.0}, w = ${0.7071067690849304}) '
            'LineTo(${50.0}, ${47.0}) '
            'Conic(${50.0}, ${50.0}, ${50.0}, ${47.0}, w = ${0.7071067690849304}) '
            'LineTo(${13.0}, ${50.0}) '
            'Conic(${10.0}, ${50.0}, ${50.0}, ${10.0}, w = ${0.7071067690849304}) '
            'Close() '
            'MoveTo(${11.0}, ${47.0}) '
            'LineTo(${11.0}, ${13.0}) '
            'Conic(${11.0}, ${11.0}, ${11.0}, ${13.0}, w = ${0.7071067690849304}) '
            'LineTo(${47.0}, ${11.0}) '
            'Conic(${49.0}, ${11.0}, ${11.0}, ${49.0}, w = ${0.7071067690849304}) '
            'LineTo(${49.0}, ${47.0}) '
            'Conic(${49.0}, ${49.0}, ${49.0}, ${47.0}, w = ${0.7071067690849304}) '
            'LineTo(${13.0}, ${49.0}) '
            'Conic(${11.0}, ${49.0}, ${49.0}, ${11.0}, w = ${0.7071067690849304}) '
            'Close()'
          ')',
        'paint': somePaint.paintData,
      });
    });

    test('Inner RRect > Outer RRect', () {
      underTest.drawDRRect(rrect, rrect.inflate(1), somePaint);
      underTest.endRecording();
      underTest.apply(mockCanvas, screenRect);
      // Expect nothing to be called
      expect(mockCanvas.methodCallLog.length, equals(1));
      expect(mockCanvas.methodCallLog.single.methodName, 'endOfPaint');
    });

    test('Inner RRect not completely inside Outer RRect', () {
      underTest.drawDRRect(
          rrect, rrect.deflate(1).shift(const Offset(0.0, 10)), somePaint);
      underTest.endRecording();
      underTest.apply(mockCanvas, screenRect);
      // Expect nothing to be called
      expect(mockCanvas.methodCallLog.length, equals(1));
      expect(mockCanvas.methodCallLog.single.methodName, 'endOfPaint');
    });

    test('Inner RRect same as Outer RRect', () {
      underTest.drawDRRect(rrect, rrect, somePaint);
      underTest.endRecording();
      underTest.apply(mockCanvas, screenRect);
      // Expect nothing to be called
      expect(mockCanvas.methodCallLog.length, equals(1));
      expect(mockCanvas.method


= library.getOldestBookByAuthor("J.R.R. Tolkien")
        println("Oldest book by J.R.R. Tolkien: ${oldestByTolkien?.title} (${oldestByTolkien?.year})")

        println("Library has Fantasy books: ${library.hasGenre("Fantasy")}")
        println("Library has Horror books: ${library.hasGenre("Horror")}")

        println("\nBooks sorted by year:")
        library.getBooksSortedByYear().forEach {
            println("  - ${it.title} (${it.year})")
        }

        println("\nTop 3 most expensive books:")
        library.getTopExpensiveBooks(3).forEach {
            println("  - ${it.title}: $${it.price}")
        }

        println("\nAverage price of books by J.R.R. Tolkien: $${library.getAveragePriceByAuthor("J.R.R. Tolkien")}")

        println("Most prolific author: ${library.getMostProlificAuthor()}")

        println("\nGenres sorted by average book price:")
        library.getGenresByAveragePrice().forEach { println("  - $it") }
    }
}package misc

import kotlin.collections.average
import kotlin.collections.map
import kotlin.collections.sumOf
import kotlin.text.format
import kotlin.text.trimIndent

object ValueClass {
    // Basic value classes for fitness metrics
    @JvmInline
    value class HeartRate(val value: Int) {
        fun display(): String {
            return "$value BPM"
        }

        val isElevated: Boolean
            get() = value > 100
    }

    @JvmInline
    value class StepCount(val value: Int) {
        fun estimateCaloriesBurned(): Double {
            // Simple estimation: 0.04 calories per step on average
            return value * 0.04
        }

        fun display(): String {
            return "$value steps"
        }
    }

    @JvmInline
    value class Calories(val value: Double) {
        fun toKilojoules(): Double {
            return value * 4.184
        }

        fun display(): String {
            return "%.1f calories".format(value)
        }
    }

    // Define an interface for displayable metrics
    interface Displayable {
        fun display(): String
    }

    // Create a value class implementing the interface
    @JvmInline
    value class Distance(val value: Double) : Displayable {
        override fun display(): String {
            return "%.2f meters".format(value)
        }

        fun toKilometers(): Double {
            return value / 1000
        }

        fun toMiles(): Double {
            return value / 1609.34
        }
    }

    // Creating a class that uses our value classes
    data class FitnessActivity(
        val duration: Int, // in minutes
        val averageHeartRate: HeartRate,
        val steps: StepCount,
        val distance: Distance,
        val caloriesBurned: Calories
    )

    // Creating a service that works with our value classes
    class FitnessTracker {
        private val activities = mutableListOf<FitnessActivity>()

        fun recordActivity(
            duration: Int,
            averageHeartRate: HeartRate,
            steps: StepCount,
            distance: Distance,
            caloriesBurned: Calories
        ) {
            val activity = FitnessActivity(
                duration,
                averageHeartRate,
                steps,
                distance,
                caloriesBurned
            )
            activities.add(activity)
            println("Activity recorded: ${activity.distance.display()} at ${activity.averageHeartRate.display()}")
        }

        fun totalDistance(): Distance {
            val sum = activities.sumOf { it.distance.value }
            return Distance(sum)
        }

        fun averageHeartRate(): HeartRate {
            if (act


�் ஹைப்ரிட் கிளவுட் கட்டமைப்புகள் வரை ஆபரேஷன் மற்றும் பரவலான AI டெவலப்பர் வாழ்க்கைச்சுழற்சியை ஆதரிக்கும் ஒருங்கிணைந்த, நம்பகமான மற்றும் பாதுகாப்பான தளத்தை பிரதிநிதித்துவம் செய்கிறது. இந்த தளம் AI மேம்பாட்டை எளிமையாக்குகிறது:

- **ஹார்ட்வேரின் சுருக்கம்**: AMD, Intel, NVIDIA மற்றும் Qualcomm சில்லிகான் முழுவதும் எளிதாக பரவல்
- **சாதனத்தில் உள்ள புத்திசாலி**: முழுமையாக உள்ளூர் ஹார்ட்வேரில் இயங்கும் தனியுரிமை பாதுகாக்கும் AI
- **மேம்பட்ட செயல்திறன்**: விண்டோஸ் ஹார்ட்வேரின் அமைப்புகளுக்கு முன்கூட்டியே மேம்படுத்தப்பட்ட மாடல்கள்
- **நிறுவனத்துக்கு உகந்தது**: உற்பத்தி தரமான பாதுகாப்பு மற்றும் இணக்கத்தன்மை அம்சங்கள்

### விண்டோஸ் ML
விண்டோஸ் மெஷின் லெர்னிங் (ML) C#, C++ மற்றும் Python டெவலப்பர்களுக்கு ONNX Runtime மூலம் ONNX AI மாடல்களை உள்ளூர் விண்டோஸ் PC-களில் இயக்க அனுமதிக்கிறது, இது CPU, GPU, NPU போன்ற பல்வேறு ஹார்ட்வேர்களுக்கான தானியங்கி


as defined in:
     * [RFC8011](http://www.iana.org/go/rfc8011).
     * May contain any keyword from [Media] or a name.
     */
    @JvmField val mediaSupported = KeywordOrNameType.Set("media-supported")
    /**
     * "media-thickness-supported" type as defined in:
     * [PWG5100.7](https://ftp.pwg.org/pub/pwg/candidates/cs-ippjobext21-20230210-5100.7.pdf).
     */
    @JvmField val mediaThicknessSupported = IntRangeType("media-thickness-supported")
    /**
     * "media-tooth-supported" type as defined in:
     * [PWG5100.7](https://ftp.pwg.org/pub/pwg/candidates/cs-ippjobext21-20230210-5100.7.pdf).
     * May contain any keyword from [MediaTooth] or a name.
     */
    @JvmField val mediaToothSupported = KeywordOrNameType.Set("media-tooth-supported")
    /**
     * "media-top-margin-supported" type as defined in:
     * [PWG5100.7](https://ftp.pwg.org/pub/pwg/candidates/cs-ippjobext21-20230210-5100.7.pdf).
     */
    @JvmField val mediaTopMarginSupported = IntType.Set("media-top-margin-supported")
    /**
     * "media-top-offset-supported" type as defined in:
     * [IPPLABEL](https://ftp.pwg.org/pub/pwg/ipp/registrations/reg-ipplabel10-20200213.pdf).
     */
    @JvmField val mediaTopOffsetSupported = IntOrIntRangeType.Set("media-top-offset-supported")
    /**
     * "media-tracking-supported" type as defined in:
     * [IPPLABEL](https://ftp.pwg.org/pub/pwg/ipp/registrations/reg-ipplabel10-20200213.pdf).
     * May contain any keyword from [MediaTracking].
     */
    @JvmField val mediaTrackingSupported = KeywordType.Set("media-tracking-supported")
    /**
     * "media-type-supported" type as defined in:
     * [PWG5100.7](https://ftp.pwg.org/pub/pwg/candidates/cs-ippjobext21-20230210-5100.7.pdf).
     * May contain any keyword from [MediaType] or a name.
     */
    @JvmField val mediaTypeSupported = KeywordOrNameType.Set("media-type-supported")
    /**
     * "media-weight-metric-supported" type as defined in:
     * [PWG5100.7](https://ftp.pwg.org/pub/pwg/candidates/cs-ippjobext21-20230210-5100.7.pdf).
     */
    @JvmField val mediaWeightMetricSupported = IntRangeType.Set("media-weight-metric-supported")
    /**
     * "message" type as defined in:
     * [RFC8011](http://www.iana.org/go/rfc8011).
     */
    @JvmField val message = TextType("message")
    /**
     * "message-supported" type as defined in:
     * [PWG5100.15](https://ftp.pwg.org/pub/pwg/candidates/cs-ippfaxout10-20131115-5100.15.pdf).
     */
    @JvmField val messageSupported = IntType("message-supported")
    /**
     * "more-info" type as defined in:
     * [PWG5100.5](https://ftp.pwg.org/pub/pwg/candidates/cs-ippdocobject12-20240517-5100.5.pdf).
     */
    @JvmField val moreInfo = UriType("more-info")
    /**
     * "multiple-destination


mat4x3, aligned_f32mat4x3, 16)'],['../a00364.html#gacc429b3b0b49921e12713b6d31e14e1d',1,'glm::GLM_ALIGNED_TYPEDEF(f32mat4x4, aligned_f32mat4x4, 16)'],['../a00364.html#ga88f6c6fa06e6e64479763e69444669cf',1,'glm::GLM_ALIGNED_TYPEDEF(f64mat2x2, aligned_f64mat2, 32)'],['../a00364.html#gaae8e4639c991e64754145ab8e4c32083',1,'glm::GLM_ALIGNED_TYPEDEF(f64mat3x3, aligned_f64mat3, 32)'],['../a00364.html#ga6e9094f3feb3b5b49d0f83683a101fde',1,'glm::GLM_ALIGNED_TYPEDEF(f64mat4x4, aligned_f64mat4, 32)'],['../a00364.html#gadbd2c639c03de1c3e9591b5a39f65559',1,'glm::GLM_ALIGNED_TYPEDEF(f64mat2x2, aligned_f64mat2x2, 32)'],['../a00364.html#gab059d7b9fe2094acc563b7223987499f',1,'glm::GLM_ALIGNED_TYPEDEF(f64mat2x3, aligned_f64mat2x3, 32)'],['../a00364.html#gabbc811d1c52ed2b8cfcaff1378f75c69',1,'glm::GLM_ALIGNED_TYPEDEF(f64mat2x4, aligned_f64mat2x4, 32)'],['../a00364.html#ga9ddf5212777734d2fd841a84439f3bdf',1,'glm::GLM_ALIGNED_TYPEDEF(f64mat3x2, aligned_f64mat3x2, 32)'],['../a00364.html#gad1dda32ed09f94bfcf0a7d8edfb6cf13',1,'glm::GLM_ALIGNED_TYPEDEF(f64mat3x3, aligned_f64mat3x3, 32)'],['../a00364.html#ga5875e0fa72f07e271e7931811cbbf31a',1,'glm::GLM_ALIGNED_TYPEDEF(f64mat3x4, aligned_f64mat3x4, 32)'],['../a00364.html#ga41e82cd6ac07f912ba2a2d45799dcf0d',1,'glm::GLM_ALIGNED_TYPEDEF(f64mat4x2, aligned_f64mat4x2, 32)'],['../a00364.html#ga0892638d6ba773043b3d63d1d092622e',1,'glm::GLM_ALIGNED_TYPEDEF(f64mat4x3, aligned_f64mat4x3, 32)'],['../a00364.html#ga912a16432608b822f1e13607529934c1',1,'glm::GLM_ALIGNED_TYPEDEF(f64mat4x4, aligned_f64mat4x4, 32)'],['../a00364.html#gafd945a8ea86b042aba410e0560df9a3d',1,'glm::GLM_ALIGNED_TYPEDEF(quat, aligned_quat, 16)'],['../a00364.html#ga19c2ba545d1f2f36bcb7b60c9a228622',1,'glm::GLM_ALIGNED_TYPEDEF(quat, aligned_fquat, 16)'],['../a00364.html#gaabc28c84a3288b697605d4688686f9a9',1,'glm::GLM_ALIGNED_TYPEDEF(dquat, aligned_dquat, 32)'],['../a00364.html#ga1ed8aeb5ca67fade269a46105f1bf273',1,'glm::GLM_ALIGNED_TYPEDEF


');
    const seconds = time.getSeconds().toString().padStart(2, '0');
    return `${minutes}:${seconds}`;
}import { Node } from '../../stretch-layout/stretch_layout';
import LayoutCtx from '../index';
import { Style, style2StretchStyle } from '../style';

class BaseNode {
  stretchNode: Node;
  style: Style;
  constructor() {
    if (!LayoutCtx.CTX) {
      console.error("LayoutCtx need initialize")
    }
    this.stretchNode = new Node(LayoutCtx.CTX.allocator, {})
  }
  // add style
  addStyle(style: Style) {
    let _style: Style = {
      ...this.style,
      ...style,
    };
    this.style = _style;
    this.stretchNode.setStyle(style2StretchStyle(_style))
  }
  // set style
  setStyle(style: Style) {
    this.style = style;
    this.stretchNode.setStyle(style2StretchStyle(style))
  }
  // remove style
  removeStyle(styleKey: string[]) {
    styleKey.forEach((key) => {
      delete this.style[key];
    })
    this.stretchNode.setStyle(style2StretchStyle(this.style))
  }
}

export default BaseNode;/*
 * Copyright 2018. University of Southern California
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

// import {log} from "../controller/Logger";

const hex = (x: number): string => {
  const h = "000000" + Number(Math.floor(x * 255)).toString(16)
  return h.substr(h.length - 2, 2)
}

const clip = (x: number | undefined): number => {
  if (x === undefined) {
    return 0
  }
  return Math.max(0, Math.min(1, x))
}

export interface IRGBColor {
  readonly red: number
  readonly green: number
  readonly blue: number
}

export interface IHSLColor {
  readonly hue: number
  readonly saturation: number
  readonly lightness: number
}

const expandRGB = (color: Partial<IRGBColor>): IRGBColor => {
  return {
    blue: clip(color.blue),
    green: clip(color.green),
    red: clip(color.red),
  }
}

const expandHSL = (color: Partial<IHSLColor>): IHSLColor => {
  return {
    hue: clip(color.hue),
    lightness: clip(color.lightness),
    saturation: clip(color.saturation),
  }
}

const hsl2rgb = (color: IHSLColor): IRGBColor => {

  if (color.saturation === 0) {
    return {
      blue: color.lightness,
      green: color.lightness,
      red: color.lightness,
    }
  }

  const hue2rgb = (t: number): number => {
    if (t < 0) {
      t += 1
    }
    if (t > 1) {
      t -= 1
    }
    if (t < 1 / 6) {
      return p + (q - p) * 6 * t
    }
    if (t < 1 / 2) {
      return q
    }
    if (t < 2 / 3) {
      return p + (q - p) * (2 / 3 - t) * 6
    }


; Above laddering takes care of XCHG access (both R and W)

	; By now, r2 setup with all the Flags we need to check in PTE
	and     r3, r0, r2              ; Mask out NON Flag bits from PTE
	brne.d  r3, r2, do_slow_path_pf ; is ((pte & flags_test) == flags_test)

	;----------------------------------------------------------------
	; UPDATE_PTE: Let Linux VM know that page was accessed/dirty
	lr      r3, [ecr]
	or      r0, r0, _PAGE_ACCESSED        ; Accessed bit always
	btst_s  r3,  ECR_C_BIT_DTLB_ST_MISS   ; See if it was a Write Access ?
	or.nz   r0, r0, _PAGE_DIRTY           ; if Write, set Dirty bit as well
	st_s    r0, [r1]                      ; Write back PTE

	CONV_PTE_TO_TLB

#if (CONFIG_ARC_MMU_VER == 1)
	; MMU with 2 way set assoc J-TLB, needs some help in pathetic case of
	; memcpy where 3 parties contend for 2 ways, ensuing a livelock.
	; But only for old MMU or one with Metal Fix
	TLB_WRITE_HEURISTICS
#endif

	COMMIT_ENTRY_TO_MMU
	TLBMISS_RESTORE_REGS
EV_TLBMissD_fast_ret:	; additional label for VDK OS-kit instrumentation
	rtie

;-------- Common routine to call Linux Page Fault Handler -----------
do_slow_path_pf:

	; Restore the 4-scratch regs saved by fast path miss handler
	TLBMISS_RESTORE_REGS

	; Slow path TLB Miss handled as a regular ARC Exception
	; (stack switching / save the complete reg-file).
	b  call_do_page_fault
END(EV_TLBMissD)


s of points, we handle both.
pub fn linestrings_to_paths(line_strings: &[String]) -> Vec<Path> {
    let mut paths : Vec<Path> = Vec::new();
    for line_string in line_strings {
        match serde_json::from_str::<Vec<(f64, f64)>>(&line_string) {
            Ok(raw_path) => paths.push(raw_path.iter().map(|&(lon, lat)| Point::new(lat, lon)).collect()),
            Err(err) => {
                match serde_json::from_str::<Vec<Vec<(f64, f64)>>>(&line_string) {
                    Ok(raw_paths) => {
                        for raw_path in raw_paths {
                            paths.push(raw_path.iter().map(|&(lon, lat)| Point::new(lat, lon)).collect());
                        }
                    },
                    Err(err2) => println!("Errors decoding line string, single line {}, multi line {}", err, err2),
                }
            },
        }
    }
    paths
}

impl RouteGraph {
    /// New Route Graph
    pub fn new() -> RouteGraph {
        RouteGraph {
            vertices: HashSet::new(),
            edges: HashMap::new(),
            paths: HashMap::new(),
        }
    }

    /// Add many paths
    pub fn add_paths(&mut self, paths: &[Path]) {
        for path in paths {
            self.add_path(path);
        }
    }

    /// Add single path to the graph
    pub fn add_path(&mut self, path: &Path) {
        // add points
        let first = path.first().unwrap();
        let last = path.last().unwrap();
        self.vertices.insert(*first);
        self.vertices.insert(*last);

        // add bidirectional edges
        self.edges.entry(*first).or_insert_with(|| vec![*last]).push(*last);
        self.edges.entry(*last).or_insert_with(|| vec![*first]).push(*first);

        // add paths
        self.paths.insert((*first, *last), path.clone());
        self.paths.insert((*last, *first), path.iter().rev().cloned().collect());
        assert!(self.paths.contains_key(&(first.clone(), last.clone())));
        assert!(self.paths.contains_key(&(last.clone(), first.clone())));
    }

    /// Find the closest actual point (vertex) in our graph since they are not
    /// going to be exact matches
    fn closest_point(&self, pt: &Point) -> (Point, f64) {
        let far_pt = Point::new(pt.lat() + 90.0, pt.lon() + 90.0);
        let far_dist = far_pt.geo_distance(pt);
        let (min_pt, min_dist) = self.edges.keys().fold((&far_pt, far_dist), |(min_pt, min_dist), vert| {
            let vert_dist = vert.geo_distance(pt);
            if vert_dist < min_dist {
                (vert, vert_dist)
            } else {
                (min_pt, min_dist)
            }
        });

        (*min_pt, min_dist)
    }

    /// Find a path between two points if one exists
    pub fn path(&self, p0: Point, p1: Point) -> Option<Path> {
        let (start, start_dist) = self.closest_point(&p0);
        if start_dist > 2000.0 {
            println!("start point {} to closest {} distance is {} > 2000", p0, start, start_dist);
            return None;
        }
        let (end, end_dist) = self.closest_point(&p1);
        if end_dist > 2000.0 {
            println!("end point {} to closest {} distance is {} > 2000", p1,


ch::riscv::trap::riscv_trap_handler];
    F --> G;
    G -- "Trap::Exception(E::Breakpoint)" --> H["handle_breakpoint(&mut tf.sepc)"];
    H --> I["debug!(Exception(Breakpoint) @ {:#x} , sepc);*sepc += 2;"];
    I -- "from U mode" --> J["Ltrap_entry_u: RESTORE_REGS 1"];
    I -- "from S mode" --> K["Ltrap_entry_s: RESTORE_REGS 0"];
    J --> L[sret];
    K --> L;
```
gcc测例运行方法：
1. 下载riscv64-linux-musl-native库，内含gcc可执行文件，源码网址为[(musl.cc)](https://musl.cc/riscv64-linux-musl-native.tgz)，将其解压到testcases目录下。

2. 在本目录下执行如下指令

   ```shell
   $ ./gcc.sh
   ```

   在gcc文件夹生成了gcc测例，另外gcc文件夹原有lib文件，带有动态链接器，请勿删除

3. 在根目录下执行指令

   ```shell
   $ ./build_img.sh gcc
   ```

   即可生成gcc测例镜像。

ZLM测例运行方法：将本地编译好的 ZLM 可执行文件放入 `testcases/ZLM` 目录下，然后在项目根目录生成镜像即可。# Week 12

## Maturin运行决赛测例指令

### 生成对应文件镜像并运行

目前可以加载 `libc` 测例或 `busybox/lua/lmbench` 测例，默认为 `libc`。

生成文件测例方式：

```shell
cd kernel
make clean
DISK_DIR=busybox make testcases-img
```

或直接在`/kernel/Makefile` 里第 12 行直接修改 `DISK_DIR ?= libc` 一项。

当前应当可以执行两类测例：`libc`与`busybox`。

之后直接执行`make run `即可。

### 代码中执行流程：

1. `kernel/src/file/device/test.rs`中`lazy_static`部分，`TESTCASES_ITER`指明了当前运行的测例，`TEST_STATUS`指明了所有即将运行的测例，

2. `kernel/src/task/scheduler.rs`中`lazy_static`部分。`IS_TEST_ENV`指明了是在测试环境下。此时会通过执行`load_next_testcase`来读取测例。

3. `load_next_testcase`会读取一条指令并利用该指令执行对应的程序。当前的默认`TESTCASES`为

   ```rust
   "busybox sh lua_testcode.sh",     // lua 测例
   "busybox sh busybox_testcode.sh", // busybox 测例
   "busybox sh lmbench_testcode.sh", // lmbench 测例
   ```

4. 在上述例子中，会启动`busybox`应用程序，并将`sh`以及后续的文件名传递给该应用程序。在`busybox`支持下会执行`sh`指令，进而去执行一系列的测试指令。

### 测例说明

#### busybox

##### busy说明

BusyBox 是一个开源项目，它提供了大约 400 个常见 UNIX/Linux 命令的精简实现。

##### busybox测试过程

* 通过上述`testcases`执行`busybox_testcode.sh`

* 真正执行的指令在`busybox_cmd.txt`中，包括了很多条指令。这些指令是linux对应指令的子集，所需要支持的操作也是linux


lasses.write(') : super("$name", type);\n\n');
        newClasses.writeln("@override");
        newClasses.write("Map<String, Object?> get deprecatedArguments => {");
        for (int i = 0; i < parameters.length; i++) {
          Parameter param = parameters[i];
          newClasses.write('"');
          newClasses.write(param.name);
          newClasses.write('": ');
          newClasses.write(param.name);
          newClasses.write(',');
        }
        newClasses.write("};\n");
        newClasses.write("}\n");
      }

      sb.write("}");
      sb.write("\n\n");

      out.write(sb.toString());
    }
    end();
  }

  @override
  void handleNoType(Token lastConsumed) {
    latestSeenParameterTypeToken = null;
    latestSeenParameterTypeTokenQuestion = null;
  }

  @override
  void handleType(Token beginToken, Token? questionMark) {
    latestSeenParameterTypeToken = beginToken.lexeme;
    latestSeenParameterTypeTokenQuestion = questionMark?.lexeme;
  }

  @override
  void endFormalParameter(
      Token? thisKeyword,
      Token? superKeyword,
      Token? periodAfterThisOrSuper,
      Token nameToken,
      Token? initializerStart,
      Token? initializerEnd,
      FormalParameterKind kind,
      MemberKind memberKind) {
    parameters.add(new Parameter(
        nameToken.lexeme,
        latestSeenParameterTypeToken ?? 'dynamic',
        latestSeenParameterTypeTokenQuestion == null ? false : true));
  }
}

class Parameter {
  final String name;
  final String type;
  final bool hasQuestion;

  Parameter(this.name, this.type, this.hasQuestion);
}
// Copyright (c) 2016, the Dart project authors.  Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.

library fasta.tool.command_line;

import 'dart:io' show exit;

import 'package:_fe_analyzer_shared/src/messages/severity.dart' show Severity;
import 'package:_fe_analyzer_shared/src/util/options.dart';

import 'package:build_integration/file_system/single_root.dart'
    show SingleRootFileSystem;

import 'package:front_end/src/api_prototype/compiler_options.dart';

import 'package:front_end/src/api_prototype/experimental_flags.dart'
    show ExperimentalFlag, isExperimentEnabled;

import 'package:front_end/src/api_prototype/file_system.dart' show FileSystem;

import 'package:front_end/src/api_prototype/standard_file_system.dart'
    show StandardFileSystem;
import 'package:front_end/src/api_prototype/terminal_color_support.dart';
import 'package:front_end/src/base/nnbd_mode.dart';

import 'package:front_end/src/base/processed_options.dart'
    show ProcessedOptions;

import 'package:front_end/src/compute_platform_binaries_location.dart'
    show computePlatformBinariesLocation, computePlatformDillName;

import 'package:front_end/src/fasta/compiler_context.dart' show CompilerContext;

import 'package:front_end/src/base/command_line_options.dart';

import 'package:front_end/src/fasta/fasta_codes.dart'
    show
        Message,
        PlainAndColorizedString,
        messageFastaUsageLong,
        messageFastaUsageShort,
        templateUnspecified;

import 'package:front_end/src/fasta/problems.dart' show DebugAbort;

import 'package:_fe_analyzer_shared/src/util/resolve_input_uri.dart'
    show resolveInputUri;

import 'package:front_end/src/scheme_based_file_system.dart'
    show SchemeBasedFileSystem;

import 'package:kernel/target/targets.dart'


/*
* 7. Write a program to convert from any numeral system of given base x
* to any other numeral system of base y (2 ≤ x, y ≤  16).
*/

using System;
using System.Linq;

class BaseXtoBaseY
{
    // Number System Conversion Calculator: http://www.cleavebooks.co.uk/scol/calnumba.htm

    static void Main()
    {
        Console.Write("Number's base X: ");
        int baseX = int.Parse(Console.ReadLine());
        if (baseX < 2) throw new ArgumentOutOfRangeException();

        Console.Write("\nEnter a non-negative integer number [base {0}]: ", baseX);
        string number = StringParse();

        Console.Write("\nConvert to base Y: ");
        int baseY = int.Parse(Console.ReadLine());
        if (baseY < 2 || baseY > 16) throw new ArgumentOutOfRangeException();

        string result = ConvertFromDecimalToBaseY(ConvertToDecimal(number.ToArray(), baseX), baseY);

        if (IsValidInput(number, result, baseX, baseY))
        {
            Console.Write("\nResult -> {0} [base {1}] converted to [base {2}] => {3}\n\n", number, baseX, baseY, result);
        }
        else
        {
            Console.WriteLine("\n-> You have entered an invalid number!\n");
        }
    }

    static string StringParse()
    {
        string number = Console.ReadLine();

        // Check for incorrect number
        for (int i = 0; i < number.Length; i++)
            if (number[i] < 'A' && number[i] > 'Z' && number[i] < 'a' && number[i] > 'z' && number[i] < '0' && number[i] > '9')
                throw new ArgumentExcepti


 gameboy LCD.
  static const int LCD_HEIGHT = 144;

  /// Draw layer priority constants.
  ///
  /// We can only draw over pixels with equal or greater priority.
  static const int P_0 = 0 << 24;
  static const int P_1 = 1 << 24;
  static const int P_2 = 2 << 24;
  static const int P_3 = 3 << 24;
  static const int P_4 = 4 << 24;
  static const int P_5 = 5 << 24;
  static const int P_6 = 6 << 24;

  /// The Emulator on which to operate.
  CPU cpu;

  /// A buffer to hold the current rendered frame that can be directly copied to the canvas on the widget.
  ///
  /// Each position stores RGB encoded color value. The data is stored by rows.
  List<int> buffer;

  /// Current rendered image to be displayed on screen.
  ///
  /// This buffer is swapped with the main drawing buffer.
  List<int> current;

  /// Background palettes. On CGB, 0-7 are used. On GB, only 0 is used.
  List<Palette> bgPalettes;

  /// Sprite palettes. 0-7 used on CGB, 0-1 used on GB.
  List<Palette> spritePalettes;

  /// Background palette memory on the CGB, indexed through $FF69.
  List<int> gbcBackgroundPaletteMemory;

  /// Sprite palette memory on the CGB, indexed through $FF6B.
  List<int> gbcSpritePaletteMemory;

  /// Stores number of sprites drawn per each of the 144 scanlines this frame.
  ///
  /// Actual Gameboy hardware can only draw 10 sprites/line, so we artificially introduce this limitation using this array.
  List<int> spritesDrawnPerLine;

  /// A counter for the number of cycles elapsed since the last LCD event.
  int lcdCycles = 0;

  /// Accumulator for how many VBlanks have been performed since the last reset.
  int currentVBlankCount = 0;

  /// The timestamp of the last second, in nanoseconds.
  int lastSecondTime = 0;

  /// The last measured Emulator.cycle.
  int lastCoreCycle = 0;

  PPU(CPU cpu)
  {
    this.cpu = cpu;
  }

  /// Initializes all palette RAM to the default on Gameboy boot.
  void reset()
  {
    this.lcdCycles = 0;
    this.currentVBlankCount = 0;
    this.lastSecondTime = -1;

    this.bgPalettes = new List<Palette>(8);
    this.spritePalettes = new List<Palette>(8);
    this.gbcBackgroundPaletteMemory = new List<int>(0x40);

    this.buffer = new List<int>(PPU.LCD_WIDTH * PPU.LCD_HEIGHT);
    this.buffer.fillRange(0, this.buffer.length, 0);

    this.current = new List<int>(PPU.LCD_WIDTH * PPU.LCD_HEIGHT);
    this.current.fillRange(0, this.current.length, 0);

    this.gbcSpritePaletteMemory = new List<int>(0x40);
    this.gbcSpritePaletteMemory.fillRange(0, this.gbcSpritePaletteMemory.length, 0);

    this.spritesDrawnPerLine = new List<int>(PPU.LCD_HEIGHT);
    this.spritesDrawnPerLine.fillRange(0, this.spritesDrawnPerLine.length, 0);

    if(this.cpu.cartridge.gameboyType == GameboyType.COLOR)
    {
      this.gbcBackgroundPaletteMemory.fillRange(0, this.gbcBackgroundPaletteMemory.length, 0x1f);

      for(int i = 0; i < this.spritePalettes.length; i++)
      {
        List<int> colors = new List<int>(4);
        colors.fillRange


',	'讨厌的臭小鬼'},
{'13931',	'童娃',	'童娃'},
{'13932',	'ETIM',	'ETIM'},
{'13933',	'屁股好大',	'屁股好大'},
{'13934',	'哥哥不要',	'哥哥不要'},
{'13935',	'插那里',	'插那里'},
{'13936',	'耽',	'耽'},
{'13937',	'我被爸爸控制了',	'我被爸爸控制了'},
{'13938',	'被爸爸控制',	'被爸爸控制'},
{'13939',	'爸爸控制',	'爸爸控制'},
{'13940',	'你的主人',	'你的主人'},
{'13941',	'我的玩物',	'我的玩物'},
{'13942',	'来我房间',	'来我房间'},
{'13943',	'你的胸',	'你的胸'},
{'13944',	'你胸',	'你胸'},
{'13945',	'胸真软',	'胸真软'},
{'13946',	'奶真好喝',	'奶真好喝'},
{'13947',	'屁股真大',	'屁股真大'},
{'13948',	'暖床的玩具',	'暖床的玩具'},
{'13949',	'我的腊肠',	'我的腊肠'},
{'13950',	'舔我',	'舔我'},
{'13951',	'变骚药水',	'变骚药水'},
{'13952',	'变骚',	'变骚'},
{'13953',	'控制药水',	'控制药水'},
{'13954',	'变热药水',	'变热药水'},
{'13955',	'很露的衣服',	'很露的衣服'},
{'13956',	'作者不污',	'作者不污'},
{'13957',	'发育得不错',	'发育得不错'},
{'13958',	'发育的不错',	'发育的不错'},
{'13959',	'我好热',	'我好热'},
{'13960',	'胸挺大',	'胸挺大'},
{'13961',	'社区菌',	'社区菌'},
{'13962',	'素材姬',	'素材姬'},
{'13963',	'游戏菌',	'游戏菌'},
{'13964',	'浅浅(｡･ω･｡)',	'浅浅(｡･ω･｡)'},
{'13965',	'恶心的人',	'恶心的人'},
{'13966',	'EX的人',	'EX的人'},
{'13967',	'受受',	'受受'},
{'13968',	'找个受',	'找个受'},
{'13969',	'找个攻',	'找个攻'},
{'13970',	'我是攻',	'我是攻'},
{'13971',	'我是受',	'我是受'},
{'13972',	'开车',	'开车'},
{'13973',	'J人',	'J人'},


local end_radius = 360
    local distance = 650
    local percent = 50

    -- get the attacker's damage
    local damage = event.original_damage

    -- get the damage modifier
    local actual_damage = damage*percent*0.01

    DoCleaveAttack(parent, target, nil, actual_damage, start_radius, end_radius, distance, "particles/items_fx/battlefury_cleave.vpcf")
  end
end

---------------------------------------------------------------------------------------------------

modifier_azazel_summon_scout_innate = class(ModifierBaseClass)

-- old flying vision
--[[
function modifier_azazel_summon_scout_innate:OnCreated()
  self:StartIntervalThink(0.1)
end

function modifier_azazel_summon_scout_innate:OnIntervalThink()
  if IsServer() then
    local parent = self:GetParent()
    -- unobstructed vision
    AddFOWViewer(parent:GetTeam(), parent:GetAbsOrigin(), parent:GetCurrentVisionRange(), 0.1, false)
  end
end
]]

function modifier_azazel_summon_scout_innate:IsHidden()
  return true
end

function modifier_azazel_summon_scout_innate:IsDebuff()
  return false
end

function modifier_azazel_summon_scout_innate:IsPurgable()
  return false
end

function modifier_azazel_summon_scout_innate:IsAura()
  return true
end

function modifier_azazel_summon_scout_innate:GetModifierAura()
  return "modifier_truesight"
end

function modifier_azazel_summon_scout_innate:GetAuraRadius()
  local parent = self:GetParent()
  return parent:GetCurrentVisionRange() or 1200
end

function modifier_azazel_summon_scout_innate:GetAuraSearchTeam()
  return DOTA_UNIT_TARGET_TEAM_ENEMY
end

function modifier_azazel_


itos: se você puder comprar as duas, melhor para você. A do Alexandre Correa tem imprecisões, mas é de uma elegância verbal fora do comum; e a outra também tem imprecisões e não é tão bonita assim, embora seja, em certos pontos, mais exata que a do Alexandre Correa. Eu sugiro que, se você vai ler em português, use as duas. Vários livros do Padre Antonin Sertillanges estão traduzidos para o português. Agora, eu sugiro: mantenha distância do Jacques Maritain. Jacques Maritain foi o líder do movimento neotomista, mas é uma mente meio torta. Ele é um dos grandes responsáveis por esta confusão modernista que entra na igreja, no Concílio Vaticano II e, às vezes, Maritain é francamente burro em certos momentos. Sobretudo nos momentos em que se mete a baixar normas para o Estado: o Estado deve ser assim ou assado. Ora, baixar normas, conceber uma sociedade ideal, conceber um governo perfeito, é fazer buraco n'água. Qualquer que seja o governo tem que ter uma intelectualidade, incluindo o clero, capaz de criticá-lo e de limitá-lo. Eu ainda estou com Lao-Tsé: "o melhor governo é o que não faz nada". Ele apenas defende o território e mantém aquele mínimo de ordem e deixa a sociedade se virar. O filme de Ridley Scott ― Robin Hood ― é uma lição sobre isso, para jamais se esquecer ― se bem que em outros filmes ele tenha passado outras mensagens ideológicas catastróficas.

*Aluno: O filme Alexandre o grande\...*

Olavo: Eu não assisti. O que eu assisti foi aquele sobre as Cruzadas ― *O Reino dos Céus* (Kingdom of Heaven) ― e o *Gladiador*. O *Gladiador* também é a apologia do governo limitado: então não se pode negar que neste ponto ele é sincero; mas no *Reino dos Céus* ele cria uma concepção que parece a da ONU e implica na burocratização enorme. Ele não percebeu a incoerência disso. É claro que ele não é um pensador sistemático: ele é apenas, como todo o artista, um elaborador de imagens que, às vezes, faz as coisas de maneira totalmente contraditória. Mas eu creio que este filme do Robin Hood não tem como ser interpretado de outra maneira: é a clara apologia, é a poética da Magna Carta. E a Magna Carta é a carta dos direitos que estabelece certas liberdades fundamentais.

*Aluno: Professor Olavo, sinceramente, estou com medo que minha pergunta seja ridícula, mas vamos lá. O Sr., na aula passada, descreveu três meios de fazer uma pessoa obedecer a outra. São eles: a pessoa obedecer por medo de sofrer algum dano, a pessoa ganha alguma coisa obedecendo ou a pessoa obedece por não saber como não fazer isso. Mas não existiria um quarto meio, a de a pessoa fazer por estar hipnotizada?*

Olavo: Eu disse que há três meios: o primeiro, a ameaça de um dano: faça isso senão eu te mato; ou faça isso senão eu queimo a sua casa; ou alguma coisa assim. O segundo é a promessa de um benefício: faça isso que eu lhe pago tanto. E o terceiro é você forçar a obediência porque você modela a mente do sujeito e a cosmovisão dele, de maneira que ele não consegue imaginar nada fora daquilo que você sugeriu. A hipnose se inclui necessariamente neste caso. Inclusive, modalidades de hipnose coletiva são as mais usadas na chama


: app.Namespace, phase: string(app.Status.Phase), createTime: app.CreationTimestamp.String()}
		appList[index].service = serviceNum(app)
		appList[index].workflow = workflowStepNum(app)
		appList[index].workflowMode = workflowMode(app)
	}
	return appList, nil
}

// LoadApplication load the corresponding application according to name and namespace
func LoadApplication(c client.Client, name, ns string) (*v1beta1.Application, error) {
	app := new(v1beta1.Application)
	err := c.Get(context.Background(), client.ObjectKey{
		Name:      name,
		Namespace: ns,
	}, app)
	if err != nil {
		return nil, err
	}
	return app, nil
}

// ApplicationResourceTopology return the applied resource of the app in tree form
func ApplicationResourceTopology(c client.Client, name, ns string) ([]types.AppliedResource, error) {
	opt := query.Option{
		Name:       name,
		Namespace:  ns,
		WithStatus: true,
		WithTree:   true,
	}
	collector := query.NewAppCollector(c, opt)
	app := new(v1beta1.Application)
	appKey := client.ObjectKey{Name: opt.Name, Namespace: opt.Namespace}
	if err := c.Get(context.Background(), appKey, app); err != nil {
		return nil, err
	}
	appResList, err := collector.ListApplicationResources(context.Background(), app)
	if err != nil {
		return nil, err
	}
	return appResList, nil
}

// applicationNum return the num of application
func applicationNum(ctx context.Context, c client.Client) (int, error) {
	apps := v1beta1.ApplicationList{}
	if err := c.List(ctx, &apps); err != nil {
		return 0, err
	}
	return len(apps.Items), nil
}

// runningApplicationNum return the num of running application
func runningApplicationNum(ctx context.Context, c client.Client) (int, error) {
	num := 0
	apps := v1beta1.ApplicationList{}
	if err := c.List(ctx, &apps); err != nil {
		return num, err
	}
	for _, app := range apps.Items {
		if app.Status.Phase == common.ApplicationRunning {
			num++
		}
	}
	return num, nil
}

func serviceNum(app v1beta1.Application) string {
	total, healthy := len(app.Status.Services), 0
	for _, service := range app.Status.Services {
		if service.Healthy {
			healthy++
		}
	}
	return fmt.Sprintf("%d/%d", healthy, total)
}

func workflowMode(app v1beta1.Application) string {
	if app.Status.Workflow == nil {
		return Unknown
	}
	return app.Status.Workflow.Mode
}

func workflowStepNum(app v1beta1.Application) string {
	if app.Status.Workflow == nil {
		return clicommon.MetricsNA
	}
	total, succeed := len(app.Status.Workflow.Steps), 0
	for _, step := range app.Status.Workflow.Steps {
		if step.Phase == workflowv1alpha1.WorkflowStepPhaseSucceeded {
			succeed++
		}
	}
	return fmt.Sprintf("%d/%d", succeed, total)
}
/*
Copyright 2023 The KubeVela Authors.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in wr


o an 1MiB boundary for the L1
	 * mapping the head code makes. We keep the UART virtual address
	 * aligned and add in the offset when we load the value here.
	 */

	.macro addruart, rp, rv
		ldr	\rp, = S3C_PA_UART
		ldr	\rv, = S3C_VA_UART
#if CONFIG_DEBUG_S3C_UART != 0
		add	\rp, \rp, #(0x400 * CONFIG_DEBUG_S3C_UART)
		add	\rv, \rv, #(0x400 * CONFIG_DEBUG_S3C_UART)
#endif
	.endm

/* include the reset of the code which will do the work, we're only
 * compiling for a single cpu processor type so the default of s3c2440
 * will be fine with us.
 */

#include <plat/debug-macro.S>


  ///   // Now wait until we know those events are done.
  ///   await _waitUntilZoneStable();
  ///   return true;
  /// }
  /// ```
  Future<bool> update([void Function()? runAndTrackSideEffects]) {
    return Future<bool>.sync(() {
      if (runAndTrackSideEffects != null) {
        runAndTrackSideEffects();
      }
      return false;
    });
  }

  /// Runs [update] until it completes with `false`, reporting stabilized.
  ///
  /// If more then [threshold] attempts occur, throws [WillNeverStabilizeError].
  Future<void> stabilize({
    void Function()? runAndTrackSideEffects,
    int threshold = 100,
  }) async {
    if (runAndTrackSideEffects != null) {
      await update(runAndTrackSideEffects);
    }
    return stabilizeWithThreshold(threshold);
  }

  /// Run [update] until the stabilizer is stable or threshold exceeds.
  ///
  /// **NOTE:** `[update] is guaranteed to run at least once.
  @protected
  Future<void> stabilizeWithThreshold(int threshold) async {
    if (threshold < 1) {
      throw ArgumentError.value(threshold, 'threshold', 'Must be >= 1');
    }

    var count = 0;
    bool thresholdExceeded() => count++ > threshold;

    // ... and once update says there is no more work to do, we will bail out.
    while (!await update()) {
      if (thresholdExceeded()) {
        throw WillNeverStabilizeError(threshold);
      }
    }
  }
}

class _AlwaysStableNgTestStabilizer extends NgTestStabilizer {
  const _AlwaysStableNgTestStabilizer();

  @override
  bool get isStable => true;
}

class _DelegatingNgTestStabilizer extends NgTestStabilizer {
  final List<NgTestStabilizer> _delegates;

  bool _updatedAtLeastOnce = false;

  _DelegatingNgTestStabilizer(Iterable<NgTestStabilizer> stabilizers)
      : _delegates = stabilizers.toList(growable: false);

  @override
  bool get isStable => _delegates.every((delegate) => delegate.isStable);

  @override
  Future<bool> update([void Function()? runAndTrackSideEffects]) async {
    if (_delegates.isEmpty) {
      return false;
    }

    if (runAndTrackSideEffects == null && _updatedAtLeastOnce) {
      // Only run the "update" function if the delegate is not stable.
      //
      // When a delegate is stable, call the "update" function may cause other
      // delegates to never stabilize. For example, calling "update" on the
      // NgZoneStabilizer will trigger an NgZone's "onEventDone" event. Another
      // service that listens on this event may trigger other events.
      await _updateAll(runAndTrackSideEffects, (d) => !d.isStable);
    } else {
      await _updateAll(runAndTrackSideEffects);
    }

    _updatedAtLeastOnce = true;
    return isStable;
  }

  /// Runs [update] where [test] is satisfied.
  Future<void> _updateAll(
    void Function()? runAndTrackSideEffects, [
    bool Function(NgTestStabilizer)? test,
  ]) async {
    for (final delegate in _delegates) {
      if (test == null || test(delegate)) {
        await delegate.update(runAndTrackSideEffects);
      }
    }
  }

  @override
  Future<void> stabilizeWithThreshold(int threshold) async {
    try {
      _updatedAtLeastOnce = false;
      return super.stabilizeWithThreshold(threshold);
    } finally {
      _updatedAtLeastOnce = false;
    }
  }
}
// Copyright (c) 2016, the Dart project authors.  Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style licen


row : 행)는 내부적으로 순서가 없이 뒤죽박죽으로 저장이 됩니다. 이렇게 되면 WHERE절에 특정 조건에 맞는 데이터들을 찾아낼 때도 레코드의 처음부터 끝까지 다 읽어서 검색 조건과 맞는지 비교해야 합니다.  이것을 풀 스캔(Full Scan)이라고 합니다. 반면에 인덱스 테이블 스캔(Index Table Scan) 시 인덱스 테이블은 데이터들이 정렬되어 저장되어 있기 때문에 해당 조건(WHERE)에 맞는 데이터들을 빠르게 찾아낼 수 있습니다.

2)

인덱스를 사용하면 ORDER BY에 의한 정렬(Sort) 과정을 피할 수 있습니다(ORDER BY는 굉장히 부하가 많이 걸리는 작업입니다.) 정렬과 동시에 1차적으로 메모리에서 정렬이 이루어지고 메모리보다 큰 작업이 필요하다면 디스크 I/O도 추가적으로 발생되기 때문입니다. 하지만 인덱스를 사용하면 이러한 전반적인 자원의 소모를 하지 않아도 된다. 그 이유는 이미 정렬이 되어 있기 때문에 가져오기만 하면 되기 때문입니다.

## 🎾 5. 인덱스의 단점

1) DML에 취약

INSERT, UPDATE, DELETE를 통해 데이터가 추가되거나 값이 바뀐다면 인덱스 테이블 내에 있는 값들을 다시 정렬을 해야 합니다. 그리고 위에 사진처럼 인덱스 테이블, 원본 테이블 이렇게 두 군데의 데이터 수정 작업을 해줘야 한다는 단점도 발생합니다.  그렇기 때문에 DML이 빈번한 테이블보다 검색을 위주로 하는 테이블에 인덱스를 생성하는 것이 좋습니다.

2) 상황에 맞게 사용하지 않으면 독

검색을 위주로 하는 테이블에 인


pectRatio="xMidYMid meet" viewBox="0 0 512 512"><path fill="currentColor" d="M447.68 220.78a16 16 0 00-1-3.08l-37.78-88.16C400.19 109.17 379 96 354.89 96H157.11c-24.09 0-45.3 13.17-54 33.54L65.29 217.7A15.72 15.72 0 0064 224v176a16 16 0 0016 16h32a16 16 0 0016-16v-16h256v16a16 16 0 0016 16h32a16 16 0 0016-16V224a16.15 16.15 0 00-.32-3.22ZM144 320a32 32 0 1132-32 32 32 0 01-32 32Zm224 0a32 32 0 1132-32 32 32 0 01-32 32ZM104.26 208l28.23-65.85C136.11 133.69 146 128 157.11 128h197.78c11.1 0 21 5.69 24.62 14.15L407.74 208Z"/></svg>';
  static const String car_outline =
      '<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="512" height="512" preserveAspectRatio="xMidYMid meet" viewBox="0 0 512 512"><path fill="currentColor" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="32" d="m80 224 37.78-88.15C123.93 121.5 139.6 112 157.11 112h197.78c17.51 0 33.18 9.5 39.33 23.85L432 224m-352 0h352v144H80zm32 144v32H80v-32m352 0v32h-32v-32"/><circle cx="144" cy="288" r="16" fill="currentColor" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="32"/><circle cx="368" cy="288" r="16" fill="currentColor" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="32"/></svg>';
  static const String car_sharp =
      '<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="512" height="512" preserveAspectRatio="xMidYMid meet" viewBox="0 0 512 512"><path fill="currentColor" d="M447.68 220.78a16.44 16.44 0 00-1-3.1l-48-112A16 16 0 00384 96H128a16 16 0 00-14.71 9.7l-48 112a16.44 16.44 0 00-1 3.1A16.15 16.15 0 0064 224v184a8 8 0 008 8h32a8 8 0 008-8v-24h288v24a8 8 0 008 8h32a8 8 0 008-8V224a16.15 16.15 0 00-.32-3.22ZM144 320a32 32 0 1132-32 32 32 0 01-32 32Zm224 0a32 32 0 1132-32 32 32 0 01-32 32ZM104.26 208l34.29-80h234.9l34.29 80Z"/></svg>';
  static const String car_sport =
      '<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink=


uthors & contributors
// SPDX-License-Identifier: Apache-2.0

/// <reference types="@polkadot/dev-test/globals.d.ts" />

import { u8aToString } from './index.js';

describe('u8aToString', (): void => {
  it('decodes to an empty string for undefined', (): void => {
    expect(
      u8aToString()
    ).toEqual('');
  });

  it('decodes to an empty string for empty buffer', (): void => {
    expect(
      u8aToString(new Uint8Array())
    ).toEqual('');
  });

  it('decodes the Uint8Array correctly (ru)', (): void => {
    expect(
      u8aToString(
        new Uint8Array([208, 159, 209, 128, 208, 184, 208, 178, 208, 181, 209, 130, 44, 32, 208, 188, 208, 184, 209, 128, 33])
      )
    ).toEqual('Привет, мир!');
  });

  it('decodes the Uint8Array correctly (en)', (): void => {
    expect(
      u8aToString(
        new Uint8Array([0x68, 0x65, 0x6c, 0x6c, 0x6f, 0x20, 0x77, 0x6f, 0x72, 0x6c, 0x64])
      )
    ).toEqual('hello world');
  });
});
import type { HttpException } from '@nestjs/common';
import { ValidationErrors } from '@angular/forms';

type Payload = {
  internalMessage: string;
  externalMessage: string;
  errorCode: string;
  validationCodes: ValidationErrors[];
};

type ErrorClass = { new (msg: string): HttpException };

export class Exception<
  E extends ErrorClass = { new (msg: string): HttpException },
> extends Error {
  constructor(public exceptionType: E, public payload: Payload) {
    super();
  }
}
'use strict';

/*
 * This example demonstrates using custom operators.
 *
 * A custom operator is created for detecting whether the word starts with a particular letter,
 * and a 'word' fact is defined for providing the test string
 *
 * In this example, Facts are passed to run() as constants known at runtime.  For a more
 * complex example demonstrating asynchronously computed facts, see the fact-dependency example.
 *
 * Usage:
 *   node ./examples/06-custom-operators.js
 *
 * For detailed output:
 *   DEBUG=json-rules-engine node ./examples/06-custom-operators.js
 */

require('colors');
import { Engine } from '../src/engine';

/**
 * Setup a new engine
 */
let engine = new Engine();

/**
 * Define a 'startsWith' custom operator, for use in later rules
 */
engine.addOperator('startsWith', (factValue, jsonValue) => {
  if (!factValue.length) return false;
  return factValue[0].toLowerCase() === jsonValue.toLowerCase();
});

/**
 * Add rule for detecting words that start with 'a'
 */
let ruleA = {
  conditions: {
    all: [
      {
        fact: 'word',
        operator: 'startsWith',
        value: 'a'
      }
    ]
  },
  event: {
    type: 'start-with-a'
  }
};
engine.addRule(ruleA);

/*
 * Add rule for detecting words that start with 'b'
 */
let ruleB = {
  conditions: {
    all: [
      {
        fact: 'word',
        operator: 'startsWith',
        value: 'b'
      }
    ]
  },
  event: {
    type: 'start-with-b'
  }
};
engine.addRule(ruleB);

// utility for printing output
let printEventType = {
  'start-with-a': 'start with "a"',
  'start-with-b': 'start with "b"'
};

/**
 * Register listeners with the engine for rule success and failure
 */
let facts: any;
engine
  .on('success', event => {


# This code is part of a Qiskit project.
#
# (C) Copyright IBM 2021, 2023.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.

"""
Quadratic program translators (:mod:`qiskit_optimization.translators`)
======================================================================

.. currentmodule:: qiskit_optimization.translators

Translators between :class:`~qiskit_optimization.problems.QuadraticProgram` and
other optimization models or other objects.

Translators
----------------------
.. autosummary::
   :toctree: ../stubs/
   :nosignatures:

   from_ising
   to_ising
"""

from .ising import from_ising, to_ising

__all__ = [
    "from_ising",
    "to_ising",
]