text
stringlengths
2
1.04M
meta
dict
// Generated by typings // Source: https://raw.githubusercontent.com/DefinitelyTyped/DefinitelyTyped/7de6c3dd94feaeb21f20054b9f30d5dabc5efabd/box2d/box2dweb.d.ts export namespace Box2D { /** * Color for debug drawing. Each value has the range [0, 1]. **/ export class b2Color { /** * Red **/ public r: number; /** * Green **/ public g: number; /** * Blue **/ public b: number; /** * RGB color as hex. * @type uint **/ public color: number; /** * Constructor * @param rr Red value * @param gg Green value * @param bb Blue value **/ constructor(rr: number, gg: number, bb: number); /** * Sets the Color to new RGB values. * @param rr Red value * @param gg Green value * @param bb Blue value **/ public Set(rr: number, gg: number, bb: number): void; } /** * Controls Box2D global settings. **/ export class b2Settings { /** * b2Assert is used internally to handle assertions. By default, calls are commented out to save performance, so they serve more as documentation than anything else. * @param a Asset an expression is true. **/ public static b2Assert(a: boolean): void; /** * Friction mixing law. Feel free to customize this. * Friction values are usually set between 0 and 1. (0 = no friction, 1 = high friction) * By default this is `return Math.sqrt(friction1, friction2);` * @param friction1 Friction 1 to mix. * @param friction2 Friction 2 to mix. * @return The two frictions mixed as one value. **/ public static b2MixFriction(friction1: number, friction2: number): number; /** * Restitution mixing law. Feel free to customize this. Restitution is used to make objects bounce. * Restitution values are usually set between 0 and 1. (0 = no bounce (inelastic), 1 = perfect bounce (perfectly elastic)) * By default this is `return Math.Max(restitution1, restitution2);` * @param restitution1 Restitution 1 to mix. * @param restitution2 Restitution 2 to mix. * @return The two restitutions mixed as one value. **/ public static b2MixRestitution(restitution1: number, restitution2: number): number; /** * This is used to fatten AABBs in the dynamic tree. This allows proxies to move by a small amount without triggering a tree adjustment. This is in meters. **/ public static b2_aabbExtension: number; /** * This is used to fatten AABBs in the dynamic tree. This is used to predict the future position based on the current displacement. This is a dimensionless multiplier. **/ public static b2_aabbMultiplier: number; /** * A body cannot sleep if its angular velocity is above this tolerance. **/ public static b2_angularSleepTolerance: number; /** * A small angle used as a collision and constraint tolerance. Usually it is chosen to be numerically significant, but visually insignificant. **/ public static b2_angularSlop: number; /** * This scale factor controls how fast overlap is resolved. Ideally this would be 1 so that overlap is removed in one time step. However using values close to 1 often lead to overshoot. **/ public static b2_contactBaumgarte: number; /** * A body cannot sleep if its linear velocity is above this tolerance. **/ public static b2_linearSleepTolerance: number; /** * A small length used as a collision and constraint tolerance. Usually it is chosen to be numerically significant, but visually insignificant. **/ public static b2_linearSlop: number; /** * The maximum angular position correction used when solving constraints. This helps to prevent overshoot. **/ public static b2_maxAngularCorrection: number; /** * The maximum linear position correction used when solving constraints. This helps to prevent overshoot. **/ public static b2_maxLinearCorrection: number; /** * Number of manifold points in a b2Manifold. This should NEVER change. **/ public static b2_maxManifoldPoints: number; /** * The maximum angular velocity of a body. This limit is very large and is used to prevent numerical problems. You shouldn't need to adjust this. **/ public static b2_maxRotation: number; /** * b2_maxRotation squared **/ public static b2_maxRotationSquared: number; /** * Maximum number of contacts to be handled to solve a TOI island. **/ public static b2_maxTOIContactsPerIsland: number; /** * Maximum number of joints to be handled to solve a TOI island. **/ public static b2_maxTOIJointsPerIsland: number; /** * The maximum linear velocity of a body. This limit is very large and is used to prevent numerical problems. You shouldn't need to adjust this. **/ public static b2_maxTranslation: number; /** * b2_maxTranslation squared **/ public static b2_maxTranslationSquared: number; /** * 3.141592653589793 **/ public static b2_pi: number; /** * The radius of the polygon/edge shape skin. This should not be modified. Making this smaller means polygons will have and insufficient for continuous collision. Making it larger may create artifacts for vertex collision. **/ public static b2_polygonRadius: number; /** * The time that a body must be still before it will go to sleep. **/ public static b2_timeToSleep: number; /** * Continuous collision detection (CCD) works with core, shrunken shapes. This is the amount by which shapes are automatically shrunk to work with CCD. This must be larger than b2_linearSlop. * @see also b2_linearSlop **/ public static b2_toiSlop: number; /** * A velocity threshold for elastic collisions. Any collision with a relative linear velocity below this threshold will be treated as inelastic. **/ public static b2_velocityThreshold: number; /** * Maximum unsigned short value. **/ public static USHRT_MAX: number; /** * The current version of Box2D. **/ public static VERSION: string; } /** * A 2-by-2 matrix. Stored in column-major order. **/ export class b2Mat22 { /** * Column 1 **/ public col1: b2Vec2; /** * Column 2 **/ public col2: b2Vec2; /** * Empty constructor **/ constructor(); /** * Sets all internal matrix values to absolute values. **/ public Abs(): void; /** * Adds the two 2x2 matricies together and stores the result in this matrix. * @param m 2x2 matrix to add. **/ public AddM(m: b2Mat22): void; /** * Creates a copy of the matrix. * @return Copy of this 2x2 matrix. **/ public Copy(): b2Mat22; /** * Creates a rotation 2x2 matrix from the given angle. * R(theta) = [ cos(theta) -sin(theta) ] * [ sin(theta) cos(theta) ] * @param angle Matrix angle (theta). * @return 2x2 matrix. **/ public static FromAngle(angle: number): b2Mat22; /** * Creates a 2x2 matrix from two columns. * @param c1 Column 1 vector. * @param c2 Column 2 vector. * @return 2x2 matrix. **/ public static FromVV(c1: b2Vec2, c2: b2Vec2): b2Mat22; /** * Gets the rotation matrix angle. * R(theta) = [ cos(theta) -sin(theta) ] * [ sin(theta) cos(theta) ] * @return The rotation matrix angle (theta). **/ public GetAngle(): number; /** * Compute the inverse of this matrix, such that inv(A) A = identity. * @param out Inverse matrix. * @return Inverse matrix. **/ public GetInverse(out: b2Mat22): b2Mat22; /** * Sets the 2x2 rotation matrix from the given angle. * R(theta) = [ cos(theta) -sin(theta) ] * [ sin(theta) cos(theta) ] * @param angle Matrix angle (theta). **/ public Set(angle: number): void; /** * Sets the 2x2 matrix to identity. **/ public SetIdentity(): void; /** * Sets the 2x2 matrix from a 2x2 matrix. * @param m 2x2 matrix values. **/ public SetM(m: b2Mat22): void; /** * Sets the 2x2 matrix from 2 column vectors. * @param c1 Column 1 vector. * @param c2 Column 2 vector. **/ public SetVV(c1: b2Vec2, c2: b2Vec2): void; /** * Sets the 2x2 matrix to all zeros. **/ public SetZero(): void; /** * TODO, has something to do with the determinant * @param out Solved vector * @param bX * @param bY * @return Solved vector **/ public Solve(out: b2Vec2, bX: number, bY: number): b2Vec2; } /** * A 3-by3 matrix. Stored in column-major order. **/ export class b2Mat33 { /** * Column 1 **/ public col1: b2Vec3; /** * Column 2 **/ public col2: b2Vec3; /** * Column 3 **/ public col3: b2Vec3; /** * Constructor * @param c1 Column 1 * @param c2 Column 2 * @param c3 Column 3 **/ constructor(c1: b2Vec3, c2: b2Vec3, c3: b2Vec3); /** * Adds the two 3x3 matricies together and stores the result in this matrix. * @param m 3x3 matrix to add. **/ public AddM(m: b2Mat33): void; /** * Creates a copy of the matrix. * @return Copy of this 3x3 matrix. **/ public Copy(): b2Mat33; /** * Sets the 3x3 matrix to identity. **/ public SetIdentity(): void; /** * Sets the 3x3 matrix from a 3x3 matrix. * @param m 3x3 matrix values. **/ public SetM(m: b2Mat33): void; /** * Sets the 3x3 matrix from 3 column vectors. * @param c1 Column 1 vector. * @param c2 Column 2 vector. * @param c3 Column 2 vector. **/ public SetVVV(c1: b2Vec3, c2: b2Vec3, c3: b2Vec3): void; /** * Sets the 3x3 matrix to all zeros. **/ public SetZero(): void; /** * TODO, has something to do with the determinant * @param out Solved vector * @param bX * @param bY * @return Solved vector **/ public Solve22(out: b2Vec2, bX: number, bY: number): b2Vec2; /** * TODO, has something to do with the determinant * @param out Solved vector * @param bX * @param bY * @param bZ * @return Solved vector **/ public Solve33(out: b2Vec3, bX: number, bY: number, bZ: number): b2Vec3; } /** * Math utility functions. **/ export class b2Math { /** * Determines if a number is valid. A number is valid if it is finite. * @param x Number to check for validity. * @return True if x is valid, otherwise false. **/ public static IsValid(x: number): boolean; /** * Dot product of two vector 2s. * @param a Vector 2 to use in dot product. * @param b Vector 2 to use in dot product. * @return Dot product of a and b. **/ public static Dot(a: b2Vec2, b: b2Vec2): number; /** * Cross product of two vector 2s. * @param a Vector 2 to use in cross product. * @param b Vector 2 to use in cross product. * @return Cross product of a and b. **/ public static CrossVV(a: b2Vec2, b: b2Vec2): number; /** * Cross product of vector 2 and s. * @param a Vector 2 to use in cross product. * @param s s value. * @return Cross product of a and s. **/ public static CrossVF(a: b2Vec2, s: number): b2Vec2; /** * Cross product of s and vector 2. * @param s s value. * @param a Vector 2 to use in cross product. * @return Cross product of s and a. **/ public static CrossFV(s: number, a: b2Vec2): b2Vec2; /** * Multiply matrix and vector. * @param A Matrix. * @param v Vector. * @return Result. **/ public static MulMV(A: b2Mat22, v: b2Vec2): b2Vec2; /** * * @param A * @param v * @return **/ public static MulTMV(A: b2Mat22, v: b2Vec2): b2Vec2; /** * * @param T * @param v * @return **/ public static MulX(T: b2Transform, v: b2Vec2): b2Vec2; /** * * @param T * @param v * @return **/ public static MulXT(T: b2Transform, v: b2Vec2): b2Vec2; /** * Adds two vectors. * @param a First vector. * @param b Second vector. * @return a + b. **/ public static AddVV(a: b2Vec2, b: b2Vec2): b2Vec2; /** * Subtracts two vectors. * @param a First vector. * @param b Second vector. * @return a - b. **/ public static SubtractVV(a: b2Vec2, b: b2Vec2): b2Vec2; /** * Calculates the distance between two vectors. * @param a First vector. * @param b Second vector. * @return Distance between a and b. **/ public static Distance(a: b2Vec2, b: b2Vec2): number; /** * Calculates the squared distance between two vectors. * @param a First vector. * @param b Second vector. * @return dist^2 between a and b. **/ public static DistanceSquared(a: b2Vec2, b: b2Vec2): number; /** * * @param s * @param a * @return **/ public static MulFV(s: number, a: b2Vec2): b2Vec2; /** * * @param A * @param B * @return **/ public static AddMM(A: b2Mat22, B: b2Mat22): b2Mat22; /** * * @param A * @param B * @return **/ public static MulMM(A: b2Mat22, B: b2Mat22): b2Mat22; /** * * @param A * @param B * @return **/ public static MulTMM(A: b2Mat22, B: b2Mat22): b2Mat22; /** * Creates an ABS number. * @param a Number to ABS. * @return Absolute value of a. **/ public static Abs(a: number): number; /** * Creates an ABS vector. * @param a Vector to ABS all values. * @return Vector with all positive values. **/ public static AbsV(a: b2Vec2): b2Vec2; /** * Creates an ABS matrix. * @param A Matrix to ABS all values. * @return Matrix with all positive values. **/ public static AbsM(A: b2Mat22): b2Mat22; /** * Determines the minimum number. * @param a First number. * @param b Second number. * @return a or b depending on which is the minimum. **/ public static Min(a: number, b: number): number; /** * Determines the minimum vector. * @param a First vector. * @param b Second vector. * @return a or b depending on which is the minimum. **/ public static MinV(a: b2Vec2, b: b2Vec2): b2Vec2; /** * Determines the max number. * @param a First number. * @param b Second number. * @return a or b depending on which is the maximum. **/ public static Max(a: number, b: number): number; /** * Determines the max vector. * @param a First vector. * @param b Second vector. * @return a or b depending on which is the maximum. **/ public static MaxV(a: b2Vec2, b: b2Vec2): b2Vec2; /** * Clamp a number to the range of low to high. * @param a Number to clamp. * @param low Low range. * @param high High range. * @return Number a clamped to range of low to high. **/ public static Clamp(a: number, low: number, high: number): number; /** * Clamps a vector to the range of low to high. * @param a Vector to clamp. * @param low Low range. * @param high High range. * @return Vector a clamped to range of low to high. **/ public static ClampV(a: b2Vec2, low: b2Vec2, high: b2Vec2): b2Vec2; /** * Swaps a and b objects. * @param a a -> b. * @param b b -> a. **/ public static Swap(a: any, b: any): void; /** * Generates a random number. * @param return Random number. **/ public static Random(): number; /** * Returns a random number between lo and hi. * @param lo Lowest random number. * @param hi Highest random number. * @return Number between lo and hi. **/ public static RandomRange(lo: number, hi: number): number; /** * Calculates the next power of 2 after the given number. * @param x Number to start search for the next power of 2. * @return The next number that is a power of 2. **/ public static NextPowerOfTwo(x: number): number; /** * Check if a number is a power of 2. * @param x Number to check if it is a power of 2. * @return True if x is a power of 2, otherwise false. **/ public static IsPowerOfTwo(x: number): boolean; /** * Global instance of a zero'ed vector. Use as read-only. **/ public static b2Vec2_zero: b2Vec2; /** * Global instance of a 2x2 identity matrix. Use as read-only. **/ public static b2Mat22_identity: b2Mat22; /** * Global instance of an identity transform. Use as read-only. **/ public static b2Transform_identity: b2Transform; } /** * This describes the motion of a body/shape for TOI computation. Shapes are defined with respect to the body origin, which may no coincide with the center of mass. However, to support dynamics we must interpolate the center of mass position. **/ export class b2Sweep { /** * World angle. **/ public a: number; /** * World angle. **/ public a0: number; /** * Center world position. **/ public c: b2Vec2; /** * Center world position. **/ public c0: b2Vec2; /** * Local center of mass position. **/ public localCenter: b2Vec2; /** * Time interval = [t0,1], where t0 is in [0,1]. **/ public t0: b2Vec2; /** * Advance the sweep forward, yielding a new initial state. * @t The new initial time. **/ public Advance(t: number): void; /** * Creates a copy of the sweep. **/ public Copy(): b2Sweep; /** * Get the interpolated transform at a specific time. * @param xf Transform at specified time, this is an out parameter. * @param alpha Is a factor in [0,1], where 0 indicates t0. **/ public GetTransform(xf: b2Transform, alpha: number): void; /** * Sets the sweep from a sweep. * @param other Sweep values to copy from. **/ public Set(other: b2Sweep): void; } /** * A transform contains translation and rotation. It is used to represent the position and orientation of rigid frames. **/ export class b2Transform { /** * Transform position. **/ public position: b2Vec2; /** * Transform rotation. **/ public R: b2Mat22; /** * The default constructor does nothing (for performance). * @param pos Position * @param r Rotation **/ constructor(pos: b2Vec2, r: b2Mat22); /** * Calculate the angle that the rotation matrix represents. * @return Rotation matrix angle. **/ public GetAngle(): number; /** * Initialize using a position vector and rotation matrix. * @param pos Position * @param r Rotation **/ public Initialize(pos: b2Vec2, r: b2Mat22): void; /** * Sets the transfrom from a transfrom. * @param x Transform to copy values from. **/ public Set(x: b2Transform): void; /** * Set this to the identity transform. **/ public SetIdentity(): void; } /** * A 2D column vector. **/ export class b2Vec2 { /** * x value **/ public x: number; /** * y value **/ public y: number; /** * Creates a new vector 2. * @param x x value, default = 0. * @param y y value, default = 0. **/ constructor(x?: number, y?: number); /** * Sets x and y to absolute values. **/ public Abs(): void; /** * Adds the vector 2 to this vector 2. The result is stored in this vector 2. * @param v Vector 2 to add. **/ public Add(v: b2Vec2): void; /** * Creates a copy of the vector 2. * @return Copy of this vector 2. **/ public Copy(): b2Vec2; /** * Cross F V * @param s **/ public CrossFV(s: number): void; /** * Cross V F * @param s **/ public CrossVF(s: number): void; /** * Gets the negative of this vector 2. * @return Negative copy of this vector 2. **/ public GetNegative(): b2Vec2; /** * True if the vector 2 is valid, otherwise false. A valid vector has finite values. * @return True if the vector 2 is valid, otherwise false. **/ public IsValid(): boolean; /** * Calculates the length of the vector 2. * @return The length of the vector 2. **/ public Length(): number; /** * Calculates the length squared of the vector2. * @return The length squared of the vector 2. **/ public LengthSquared(): number; /** * Creates a new vector 2 from the given values. * @param x x value. * @param y y value. **/ public static Make(x: number, y: number): b2Vec2; /** * Calculates which vector has the maximum values and sets this vector to those values. * @param b Vector 2 to compare for maximum values. **/ public MaxV(b: b2Vec2): void; /** * Calculates which vector has the minimum values and sets this vector to those values. * @param b Vector 2 to compare for minimum values. **/ public MinV(b: b2Vec2): void; /** * Matrix multiplication. Stores the result in this vector 2. * @param A Matrix to muliply by. **/ public MulM(A: b2Mat22): void; /** * Vector multiplication. Stores the result in this vector 2. * @param a Value to multiple the vector's values by. **/ public Multiply(a: number): void; /** * Dot product multiplication. Stores the result in this vector 2. * @param A Matrix to multiply by. **/ public MulTM(A: b2Mat22): void; /** * Sets this vector 2 to its negative. **/ public NegativeSelf(): void; /** * Normalizes the vector 2 [0,1]. * @return Length. **/ public Normalize(): number; /** * Sets the vector 2. * @param x x value, default is 0. * @param y y value, default is 0. **/ public Set(x?: number, y?: number): void; /** * Sets the vector 2 from a vector 2. * @param v Vector 2 to copy values from. **/ public SetV(v: b2Vec2): void; /** * Sets the vector 2 to zero values. **/ public SetZero(): void; /** * Subtracts the vector 2 from this vector 2. The result is stored in this vector 2. * @param v Vector 2 to subtract. **/ public Subtract(v: b2Vec2): void; } /** * A 2D column vector with 3 elements. **/ export class b2Vec3 { /** * x value. **/ public x: number; /** * y value. **/ public y: number; /** * z value. **/ public z: number; /** * Construct using coordinates x,y,z. * @param x x value, default = 0. * @param y y value, default = 0. * @param z z value, default = 0. **/ constructor(x?: number, y?: number, z?: number); /** * Adds the vector 3 to this vector 3. The result is stored in this vector 3. * @param v Vector 3 to add. **/ public Add(v: b2Vec3): void; /** * Creates a copy of the vector 3. * @return Copy of this vector 3. **/ public Copy(): b2Vec3; /** * Gets the negative of this vector 3. * @return Negative copy of this vector 3. **/ public GetNegative(): b2Vec3; /** * Vector multiplication. Stores the result in this vector 3. * @param a Value to multiple the vector's values by. **/ public Multiply(a: number): void; /** * Sets this vector 3 to its negative. **/ public NegativeSelf(): void; /** * Sets the vector 3. * @param x x value, default is 0. * @param y y value, default is 0. * @param z z value, default is 0. **/ public Set(x?: number, y?: number, z?: number): void; /** * Sets the vector 3 from a vector 3. * @param v Vector 3 to copy values from. **/ public SetV(v: b2Vec3): void; /** * Sets the vector 3 to zero values. **/ public SetZero(): void; /** * Subtracts the vector 3 from this vector 3. The result is stored in this vector 3. * @param v Vector 3 to subtract. **/ public Subtract(v: b2Vec3): void; } /** * Axis aligned bounding box. **/ export class b2AABB { /** * Lower bound. **/ public lowerBound: b2Vec2; /** * Upper bound. **/ public upperBound: b2Vec2; /** * Combines two AABBs into one with max values for upper bound and min values for lower bound. * @param aabb1 First AABB to combine. * @param aabb2 Second AABB to combine. * @return New AABB with max values from aabb1 and aabb2. **/ public static Combine(aabb1: b2AABB, aabb2: b2AABB): b2AABB; /** * Combines two AABBs into one with max values for upper bound and min values for lower bound. The result is stored in this AABB. * @param aabb1 First AABB to combine. * @param aabb2 Second AABB to combine. **/ public Combine(aabb1: b2AABB, aabb2: b2AABB): void; /** * Determines if an AABB is contained within this one. * @param aabb AABB to see if it is contained. * @return True if aabb is contained, otherwise false. **/ public Contains(aabb: b2AABB): boolean; /** * Gets the center of the AABB. * @return Center of this AABB. **/ public GetCenter(): b2Vec2; /** * Gets the extents of the AABB (half-widths). * @return Extents of this AABB. **/ public GetExtents(): b2Vec2; /** * Verify that the bounds are sorted. * @return True if the bounds are sorted, otherwise false. **/ public IsValid(): boolean; /** * Perform a precise raycast against this AABB. * @param output Ray cast output values. * @param input Ray cast input values. * @return True if the ray cast hits this AABB, otherwise false. **/ public RayCast(output: b2RayCastOutput, input: b2RayCastInput): boolean; /** * Tests if another AABB overlaps this AABB. * @param other Other AABB to test for overlap. * @return True if other overlaps this AABB, otherwise false. **/ public TestOverlap(other: b2AABB): boolean; } /** * We use contact ids to facilitate warm starting. **/ export class b2ContactID { /** * Features **/ public features: Features; /** * ID Key **/ public Key: number; /** * Creates a new Contact ID. **/ constructor(); /** * Copies the Contact ID. * @return Copied Contact ID. **/ public Copy(): b2ContactID; /** * Sets the Contact ID from a Contact ID. * @param id The Contact ID to copy values from. **/ public Set(id: b2ContactID): void; } /** * This structure is used to report contact points. **/ export class b2ContactPoint { /** * The combined friction coefficient. **/ public friction: number; /** * The contact id identifies the features in contact. **/ public id: b2ContactID; /** * Points from shape1 to shape2. **/ public normal: b2Vec2; /** * Position in world coordinates. **/ public position: b2Vec2; /** * The combined restitution coefficient. **/ public restitution: number; /** * The separation is negative when shapes are touching. **/ public separation: number; /** * The first shape. **/ public shape1: b2Shape; /** * The second shape. **/ public shape2: b2Shape; /** * Velocity of point on body2 relative to point on body1 (pre-solver). **/ public velocity: b2Vec2; } /** * Input for b2Distance. You have to option to use the shape radii in the computation. Even **/ export class b2DistanceInput { /** * Proxy A **/ public proxyA: b2DistanceProxy; /** * Proxy B **/ public proxyB: b2DistanceProxy; /** * Transform A **/ public transformA: b2Transform; /** * Transform B **/ public transformB: b2Transform; /** * Use shape radii in computation? **/ public useRadii: boolean; } /** * Output calculation for b2Distance. **/ export class b2DistanceOutput { /** * Calculated distance. **/ public distance: number; /** * Number of gjk iterations used in calculation. **/ public iterations: number; /** * Closest point on shape A. **/ public pointA: b2Vec2; /** * Closest point on shape B. **/ public pointB: b2Vec2; } /** * A distance proxy is used by the GJK algorithm. It encapsulates any shape. **/ export class b2DistanceProxy { /** * Count **/ public m_count: number; /** * Radius **/ public m_radius: number; /** * Verticies **/ public m_vertices: b2Vec2[]; /** * Get the supporting vertex index in the given direction. * @param d Direction to look for the supporting vertex. * @return Supporting vertex index. **/ public GetSupport(d: b2Vec2): number; /** * Get the supporting vertex in the given direction. * @param d Direction to look for the supporting vertex. * @return Supporting vertex. **/ public GetSupportVertex(d: b2Vec2): b2Vec2; /** * Get a vertex by index. Used by b2Distance. * @param index Vetex's index. * @return Vertex at the given index. **/ public GetVertex(index: number): b2Vec2; /** * Get the vertex count. * @return The number of vertices. (m_vertices.length) **/ public GetVertexCount(): number; /** * Initialize the proxy using the given shape. The shape must remain in scope while the proxy is in use. * @param shape Shape to initialize the distance proxy. **/ public Set(shape: b2Shape): void; } /** * A dynamic tree arranges data in a binary tree to accelerate queries such as volume queries and ray casts. Leafs are proxies with an AABB. In the tree we expand the proxy AABB by b2_fatAABBFactor so that the proxy AABB is bigger than the client object. This allows the client object to move by small amounts without triggering a tree update. Nodes are pooled. **/ export class b2DynamicTree { /** * Constructing the tree initializes the node pool. **/ constructor(); /** * Create a proxy. Provide a tight fitting AABB and a userData. * @param aabb AABB. * @param userDate User defined data for this proxy. * @return Dynamic tree node. **/ public CreateProxy(aabb: b2AABB, userData: any): b2DynamicTreeNode; /** * Destroy a proxy. This asserts if the id is invalid. * @param proxy Proxy to destroy. **/ public DestroyProxy(proxy: b2DynamicTreeNode): void; /** * Gets the Fat AABB for the proxy. * @param proxy Proxy to retrieve Fat AABB. * @return Fat AABB for proxy. **/ public GetFatAABB(proxy: b2DynamicTreeNode): b2AABB; /** * Get user data from a proxy. Returns null if the proxy is invalid. * Cast to your type on return. * @param proxy Proxy to retrieve user data from. * @return User data for proxy or null if proxy is invalid. **/ public GetUserData(proxy: b2DynamicTreeNode): any; /** * Move a proxy with a swept AABB. If the proxy has moved outside of its fattened AABB, then the proxy is removed from the tree and re-inserted. Otherwise the function returns immediately. * @param proxy Proxy to move. * @param aabb Swept AABB. * @param displacement Extra AABB displacement. **/ public MoveProxy(proxy: b2DynamicTreeNode, aabb: b2AABB, displacement: b2Vec2): boolean; /** * Query an AABB for overlapping proxies. The callback is called for each proxy that overlaps the supplied AABB. The callback should match function signature fuction callback(proxy:b2DynamicTreeNode):Boolean and should return false to trigger premature termination. * @param callback Called for each proxy that overlaps the supplied AABB. * param proxy Proxy overlapping the supplied AABB. * @aabb Proxies are query for overlap on this AABB. **/ public Query(callback: (proxy: b2DynamicTreeNode) => boolean, aabb: b2AABB): void; /** * Ray-cast against the proxies in the tree. This relies on the callback to perform a exact ray-cast in the case were the proxy contains a shape. The callback also performs the any collision filtering. This has performance roughly equal to k log(n), where k is the number of collisions and n is the number of proxies in the tree. * @param callback Called for each proxy that is hit by the ray. * param input Ray cast input data. * param proxy The proxy hit by the ray cast. * return Return value is the new value for maxFraction. * @param input Ray cast input data. Query all proxies along this ray cast. **/ public RayCast(callback: (input: b2RayCastInput, proxy: b2DynamicTreeNode) => number, input: b2RayCastInput): void; /** * Perform some iterations to re-balance the tree. * @param iterations Number of rebalance iterations to perform. **/ public Rebalance(iterations: number): void; } /** * The broad-phase is used for computing pairs and performing volume queries and ray casts. This broad-phase does not persist pairs. Instead, this reports potentially new pairs. It is up to the client to consume the new pairs and to track subsequent overlap. **/ export class b2DynamicTreeBroadPhase implements IBroadPhase { /** * Creates the dynamic tree broad phase. **/ constructor(); /** * @see IBroadPhase.CreateProxy **/ public CreateProxy(aabb: b2AABB, userData: any): b2DynamicTreeNode; /** * @see IBroadPhase.DestroyProxy **/ public DestroyProxy(proxy: b2DynamicTreeNode): void; /** * @see IBroadPhase.GetFatAABB **/ public GetFatAABB(proxy: b2DynamicTreeNode): b2AABB; /** * @see IBroadPhase.GetProxyCount **/ public GetProxyCount(): number; /** * @see IBroadPhase.GetUserData **/ public GetUserData(proxy: b2DynamicTreeNode): any; /** * @see IBroadPhase.MoveProxy **/ public MoveProxy(proxy: b2DynamicTreeNode, aabb: b2AABB, displacement: b2Vec2): void; /** * @see IBroadPhase.Query **/ public Query(callback: (proxy: b2DynamicTreeNode) => boolean, aabb: b2AABB): void; /** * @see IBroadPhase.RayCast **/ public RayCast(callback: (input: b2RayCastInput, proxy: b2DynamicTreeNode) => number, input: b2RayCastInput): void; /** * @see IBroadPhase.Rebalance **/ public Rebalance(iterations: number): void; /** * Tests if two proxies overlap. * @param proxyA First proxy to test. * @param proxyB Second proxy to test. * @return True if the proxyA and proxyB overlap with Fat AABBs, otherwise false. **/ public TestOverlap(proxyA: b2DynamicTreeNode, proxyB: b2DynamicTreeNode): boolean; /** * Update the pairs. This results in pair callbacks. This can only add pairs. * @param callback Called for all new proxy pairs. * param userDataA Proxy A in the pair user data. * param userDataB Proxy B in the pair user data. **/ public UpdatePairs(callback: (userDataA: any, userDataB: any) => void ): void; /** * Validates the dynamic tree. * NOTE: this says "todo" in the current Box2DFlash code. **/ public Validate(): void; } /** * Empty declaration, used in many callbacks within b2DynamicTree. * Use the b2DynamicTree functions to extract data from this shell. **/ export class b2DynamicTreeNode { } /** * A manifold for two touching convex shapes. Box2D supports multiple types of contact: - clip point versus plane with radius - point versus point with radius (circles) The local point usage depends on the manifold type: -e_circles: the local center of circleA -e_faceA: the center of faceA -e_faceB: the center of faceB Similarly the local normal usage: -e_circles: not used -e_faceA: the normal on polygonA -e_faceB: the normal on polygonB We store contacts in this way so that position correction can account for movement, which is critical for continuous physics. All contact scenarios must be expressed in one of these types. This structure is stored across time steps, so we keep it small. **/ export class b2Manifold { /** * Circles **/ public static e_circles: number; /** * Face A **/ public static e_faceA: number; /** * Face B **/ public static e_faceB: number; /** * Not used for Type e_points **/ public m_localPlaneNormal: b2Vec2; /** * Usage depends on manifold type **/ public m_localPoint: b2Vec2; /** * The number of manifold points **/ public m_pointCount: number; /** * The points of contact **/ public m_points: b2ManifoldPoint[]; /** * Manifold type. **/ public m_type: number; /** * Creates a new manifold. **/ constructor(); /** * Copies the manifold. * @return Copy of this manifold. **/ public Copy(): b2Manifold; /** * Resets this manifold. **/ public Reset(): void; /** * Sets this manifold from another manifold. * @param m Manifold to copy values from. **/ public Set(m: b2Manifold): void; } /** * A manifold point is a contact point belonging to a contact manifold. It holds details related to the geometry and dynamics of the contact points. The local point usage depends on the manifold type: -e_circles: the local center of circleB -e_faceA: the local center of cirlceB or the clip point of polygonB -e_faceB: the clip point of polygonA This structure is stored across time steps, so we keep it small. Note: the impulses are used for internal caching and may not provide reliable contact forces, especially for high speed collisions. **/ export class b2ManifoldPoint { /** * Contact ID. **/ public m_id: b2ContactID; /** * Local contact point. **/ public m_localpoint: b2Vec2; /** * Normal impluse for this contact point. **/ public m_normalImpulse: number; /** * Tangent impulse for contact point. **/ public m_tangentImpulse: number; /** * Creates a new manifold point. **/ constructor(); /** * Resets this manifold point. **/ public Reset(): void; /** * Sets this manifold point from a manifold point. * @param m The manifold point to copy values from. **/ public Set(m: b2ManifoldPoint): void; } /** * An oriented bounding box. **/ export class b2OBB { /** * The local centroid. **/ public center: b2Vec2; /** * The half-widths. **/ public extents: b2Vec2; /** * The rotation matrix. **/ public R: b2Mat22; } /** * Ray cast input data. **/ export class b2RayCastInput { /** * Truncate the ray to reach up to this fraction from p1 to p2 **/ public maxFraction: number; /** * The start point of the ray. **/ public p1: b2Vec2; /** * The end point of the ray. **/ public p2: b2Vec2; /** * Creates a new ray cast input. * @param p1 Start point of the ray, default = null. * @param p2 End point of the ray, default = null. * @param maxFraction Truncate the ray to reach up to this fraction from p1 to p2. **/ constructor(p1?: b2Vec2, p2?: b2Vec2, maxFraction?: number); } /** * Results of a ray cast. **/ export class b2RayCastOutput { /** * The fraction between p1 and p2 that the collision occurs at. **/ public fraction: number; /** * The normal at the point of collision. **/ public normal: b2Vec2; } /** * A line in space between two given vertices. **/ export class b2Segment { /** * The starting point. **/ public p1: b2Vec2; /** * The ending point. **/ public p2: b2Vec2; /** * Extends or clips the segment so that it's ends lie on the boundary of the AABB. * @param aabb AABB to extend/clip the segement. **/ public Extend(aabb: b2AABB): void; /** * See Extend, this works on the ending point. * @param aabb AABB to extend/clip the ending point. **/ public ExtendBackward(aabb: b2AABB): void; /** * See Extend, this works on the starting point. * @param aabb AABB to extend/clip the starting point. **/ public ExtendForward(aabb: b2AABB): void; /** * Ray cast against this segment with another segment. * @param lambda returns the hit fraction. You can use this to compute the contact point * p = (1 - lambda) * segment.p1 + lambda * segment.p2 * @normal Normal at the contact point. If there is no intersection, the normal is not set. * @param segment Defines the begining and end point of the ray cast. * @param maxLambda a number typically in the range [0,1]. * @return True if there is an intersection, otherwise false. **/ public TestSegment( lambda: number[], normal: b2Vec2, segment: b2Segment, maxLambda: number): boolean; } /** * Used to warm start b2Distance. Set count to zero on first call. **/ export class b2SimplexCache { /** * Number in cache. **/ public count: number; /** * Vertices on shape a. **/ public indexA: number[]; /** * Vertices on shape b. **/ public indexB: number[]; /** * Length or area. **/ public metric: number; } /** * Inpute parameters for b2TimeOfImpact **/ export class b2TOIInput { /** * Proxy A **/ public proxyA: b2DistanceProxy; /** * Proxy B **/ public proxyB: b2DistanceProxy; /** * Sweep A **/ public sweepA: b2Sweep; /** * Sweep B **/ public sweepB: b2Sweep; /** * Tolerance **/ public tolerance: number; } /** * This is used to compute the current state of a contact manifold. **/ export class b2WorldManifold { /** * World vector pointing from A to B. **/ public m_normal: b2Vec2; /** * World contact point (point of intersection). **/ public m_points: b2Vec2[]; /** * Creates a new b2WorldManifold. **/ constructor(); /** * Evaluate the manifold with supplied transforms. This assumes modest motion from the original state. This does not change the point count, impulses, etc. The radii must come from the shapes that generated the manifold. * @param manifold Manifold to evaluate. * @param xfA A transform. * @param radiusA A radius. * @param xfB B transform. * @param radiusB B radius. **/ public Initialize( manifold: b2Manifold, xfA: b2Transform, radiusA: number, xfB: b2Transform, radiusB: number): void; } /** * We use contact ids to facilitate warm starting. **/ export class Features { /** * A value of 1 indicates that the reference edge is on shape2. **/ public flip: number; /** * The edge most anti-parallel to the reference edge. **/ public incidentEdge: number; /** * The vertex (0 or 1) on the incident edge that was clipped. **/ public incidentVertex: number; /** * The edge that defines the outward contact normal. **/ public referenceEdge: number; } /** * Interface for objects tracking overlap of many AABBs. **/ export interface IBroadPhase { /** * Create a proxy with an initial AABB. Pairs are not reported until UpdatePairs is called. * @param aabb Proxy Fat AABB. * @param userData User defined data. * @return Proxy created from aabb and userData. **/ CreateProxy(aabb: b2AABB, userData: any): b2DynamicTreeNode; /** * Destroy a proxy. It is up to the client to remove any pairs. * @param proxy Proxy to destroy. **/ DestroyProxy(proxy: b2DynamicTreeNode): void; /** * Get the Fat AABB for a proxy. * @param proxy Proxy to retrieve the Fat AABB. **/ GetFatAABB(proxy: b2DynamicTreeNode): b2AABB; /** * Get the number of proxies. * @return Number of proxies. **/ GetProxyCount(): number; /** * Get user data from a proxy. Returns null if the proxy is invalid. * @param proxy Proxy to retrieve user data from. * @return Gets the user data from proxy, or null if the proxy is invalid. **/ GetUserData(proxy: b2DynamicTreeNode): any; /** * Call MoveProxy as many times as you like, then when you are done call UpdatePairs to finalized the proxy pairs (for your time step). * @param proxy Proxy to move. * @param aabb Swept AABB. * @param displacement Extra AABB displacement. **/ MoveProxy(proxy: b2DynamicTreeNode, aabb: b2AABB, displacement: b2Vec2): void; /** * Query an AABB for overlapping proxies. The callback is called for each proxy that overlaps the supplied AABB. The callback should match function signature fuction callback(proxy:b2DynamicTreeNode):Boolean and should return false to trigger premature termination. * @param callback Called for each proxy that overlaps the supplied AABB. * param proxy Proxy overlapping the supplied AABB. * @param aabb Proxies are query for overlap on this AABB. **/ Query(callback: (proxy: b2DynamicTreeNode) => boolean, aabb: b2AABB): void; /** * Ray-cast against the proxies in the tree. This relies on the callback to perform a exact ray-cast in the case were the proxy contains a shape. The callback also performs the any collision filtering. This has performance roughly equal to k log(n), where k is the number of collisions and n is the number of proxies in the tree. * @param callback Called for each proxy that is hit by the ray. * param input Ray cast input data. * param proxy The proxy hit by the ray cast. * param return Return value is the new value for maxFraction. * @param input Ray cast input data. Query all proxies along this ray cast. **/ RayCast(callback: (input: b2RayCastInput, proxy: b2DynamicTreeNode) => number, input: b2RayCastInput): void; /** * Perform some iterations to re-balance the tree. * @param iterations Number of rebalance iterations to perform. **/ Rebalance(iterations: number): void; } /** * A circle shape. **/ export class b2CircleShape extends b2Shape { /** * Creates a new circle shape. * @param radius Circle radius. **/ constructor(radius?: number); /** * Given a transform, compute the associated axis aligned bounding box for this shape. * @param aabb Calculated AABB, this argument is `out`. * @param xf Transform to calculate the AABB. **/ public ComputeAABB(aabb: b2AABB, xf: b2Transform): void; /** * Compute the mass properties of this shape using its dimensions and density. The inertia tensor is computed about the local origin, not the centroid. * @param massData Calculate the mass, this argument is `out`. * @param density **/ public ComputeMass(massData: b2MassData, density: number): void; /** * Compute the volume and centroid of this shape intersected with a half plane * @param normal The surface normal. * @param offset The surface offset along the normal. * @param xf The shape transform. * @param c The centroid, this argument is `out`. **/ public ComputeSubmergedArea( normal: b2Vec2, offset: number, xf: b2Transform, c: b2Vec2): number; /** * Copies the circle shape. * @return Copy of this circle shape. **/ public Copy(): b2CircleShape; /** * Get the local position of this circle in its parent body. * @return This circle's local position. **/ public GetLocalPosition(): b2Vec2; /** * Get the radius of the circle. * @return This circle's radius. **/ public GetRadius(): number; /** * Cast a ray against this shape. * @param output Ray cast results, this argument is `out`. * @param input Ray cast input parameters. * @param transform The transform to be applied to the shape. * @return True if the ray hits the shape, otherwise false. **/ public RayCast( output: b2RayCastOutput, input: b2RayCastInput, transform: b2Transform): boolean; /** * Set the circle shape values from another shape. * @param other The other circle shape to copy values from. **/ public Set(other: b2CircleShape): void; /** * Set the local position of this circle in its parent body. * @param position The new local position of this circle. **/ public SetLocalPosition(position: b2Vec2): void; /** * Set the radius of the circle. * @param radius The new radius of the circle. **/ public SetRadius(radius: number): void; /** * Test a point for containment in this shape. This only works for convex shapes. * @param xf Shape world transform. * @param p Point to test against, in world coordinates. * @return True if the point is in this shape, otherwise false. **/ public TestPoint(xf: b2Transform, p: b2Vec2): boolean; } /** * This structure is used to build edge shapes. **/ export class b2EdgeChainDef { /** * Whether to create an extra edge between the first and last vertices. **/ public isALoop: boolean; /** * The number of vertices in the chain. **/ public vertexCount: number; /** * The vertices in local coordinates. **/ public vertices: b2Vec2; /** * Creates a new edge chain def. **/ constructor(); } /** * An edge shape. **/ export class b2EdgeShape extends b2Shape { /** * Creates a new edge shape. * @param v1 First vertex * @param v2 Second vertex **/ constructor(v1: b2Vec2, v2: b2Vec2); /** * Given a transform, compute the associated axis aligned bounding box for this shape. * @param aabb Calculated AABB, this argument is `out`. * @param xf Transform to calculate the AABB. **/ public ComputeAABB(aabb: b2AABB, xf: b2Transform): void; /** * Compute the mass properties of this shape using its dimensions and density. The inertia tensor is computed about the local origin, not the centroid. * @param massData Calculate the mass, this argument is `out`. **/ public ComputeMass(massData: b2MassData, density: number): void; /** * Compute the volume and centroid of this shape intersected with a half plane * @param normal The surface normal. * @param offset The surface offset along the normal. * @param xf The shape transform. * @param c The centroid, this argument is `out`. **/ public ComputeSubmergedArea( normal: b2Vec2, offset: number, xf: b2Transform, c: b2Vec2): number; /** * Get the distance from vertex1 to vertex2. * @return Distance from vertex1 to vertex2. **/ public GetLength(): number; /** * Get the local position of vertex1 in the parent body. * @return Local position of vertex1 in the parent body. **/ public GetVertex1(): b2Vec2; /** * Get the local position of vertex2 in the parent body. * @return Local position of vertex2 in the parent body. **/ public GetVertex2(): b2Vec2; /** * Get a core vertex 1 in local coordinates. These vertices represent a smaller edge that is used for time of impact. * @return core vertex 1 in local coordinates. **/ public GetCoreVertex1(): b2Vec2; /** * Get a core vertex 2 in local coordinates. These vertices represent a smaller edge that is used for time of impact. * @return core vertex 2 in local coordinates. **/ public GetCoreVertex2(): b2Vec2; /** * Get a perpendicular unit vector, pointing from the solid side to the empty side. * @return Normal vector. **/ public GetNormalVector(): b2Vec2; /** * Get a parallel unit vector, pointing from vertex 1 to vertex 2. * @return Vertex 1 to vertex 2 directional vector. **/ public GetDirectionVector(): b2Vec2; /** * Returns a unit vector halfway between direction and previous direction. * @return Halfway unit vector between direction and previous direction. **/ public GetCorner1Vector(): b2Vec2; /** * Returns a unit vector halfway between direction and previous direction. * @return Halfway unit vector between direction and previous direction. **/ public GetCorner2Vector(): b2Vec2; /** * Determines if the first corner of this edge bends towards the solid side. * @return True if convex, otherwise false. **/ public Corner1IsConvex(): boolean; /** * Determines if the second corner of this edge bends towards the solid side. * @return True if convex, otherwise false. **/ public Corner2IsConvex(): boolean; /** * Get the first vertex and apply the supplied transform. * @param xf Transform to apply. * @return First vertex with xf transform applied. **/ public GetFirstVertex(xf: b2Transform): b2Vec2; /** * Get the next edge in the chain. * @return Next edge shape or null if there is no next edge shape. **/ public GetNextEdge(): b2EdgeShape; /** * Get the previous edge in the chain. * @return Previous edge shape or null if there is no previous edge shape. **/ public GetPrevEdge(): b2EdgeShape; /** * Get the support point in the given world direction with the supplied transform. * @param xf Transform to apply. * @param dX X world direction. * @param dY Y world direction. * @return Support point. **/ public Support(xf: b2Transform, dX: number, dY: number): b2Vec2; /** * Cast a ray against this shape. * @param output Ray cast results, this argument is `out`. * @param input Ray cast input parameters. * @param transform The transform to be applied to the shape. * @return True if the ray hits the shape, otherwise false. **/ public RayCast( output: b2RayCastOutput, input: b2RayCastInput, transform: b2Transform): boolean; /** * Test a point for containment in this shape. This only works for convex shapes. * @param xf Shape world transform. * @param p Point to test against, in world coordinates. * @return True if the point is in this shape, otherwise false. **/ public TestPoint(xf: b2Transform, p: b2Vec2): boolean; } /** * This holds the mass data computed for a shape. **/ export class b2MassData { /** * The position of the shape's centroid relative to the shape's origin. **/ public center: b2Vec2; /** * The rotational inertia of the shape. This may be about the center or local origin, depending on usage. **/ public I: number; /** * The mass of the shape, usually in kilograms. **/ public mass: number; } /** * Convex polygon. The vertices must be in CCW order for a right-handed coordinate system with the z-axis coming out of the screen. **/ export class b2PolygonShape extends b2Shape { /** * Creates a b2PolygonShape from a vertices list. This assumes the vertices define a convex polygon. It is assumed that the exterior is the the right of each edge. * @param vertices List of vertices to create the polygon shape from. * @param vertexCount Number of vertices in the shape, default value is 0 and in the box2dweb.js code it is ignored. * @return Convex polygon shape. **/ public static AsArray(vertices: b2Vec2[], vertexCount?: number): b2PolygonShape; /** * Build vertices to represent an axis-aligned box. * @param hx The half-width. * @param hy The half-height. * @return Box polygon shape. **/ public static AsBox(hx: number, hy: number): b2PolygonShape; /** * Creates a single edge from two vertices. * @param v1 First vertex. * @param v2 Second vertex. * @return Edge polygon shape. **/ public static AsEdge(v1: b2Vec2, b2: b2Vec2): b2PolygonShape; /** * Build vertices to represent an oriented box. * @param hx The half-width. * @param hy The half-height. * @param center The center of the box in local coordinates, default is null (no center?) * @param angle The rotation of the box in local coordinates, default is 0.0. * @return Oriented box shape. **/ public static AsOrientedBox(hx: number, hy: number, center?: b2Vec2, angle?: number): b2PolygonShape; /** * This assumes the vertices define a convex polygon. It is assumed that the exterior is the the right of each edge. * @param vertices List of vertices to create the polygon shape from. * @param vertexCount The number of vertices, default is 0 and in the box2dweb.js code it is ignored. * @return Convex polygon shape. **/ public static AsVector(vertices: b2Vec2[], vertexCount?: number): b2PolygonShape; /** * Given a transform, compute the associated axis aligned bounding box for this shape. * @param aabb Calculated AABB, this argument is `out`. * @param xf Transform to calculate the AABB. **/ public ComputeAABB(aabb: b2AABB, xf: b2Transform): void; /** * Compute the mass properties of this shape using its dimensions and density. The inertia tensor is computed about the local origin, not the centroid. * @param massData Calculate the mass, this argument is `out`. **/ public ComputeMass(massData: b2MassData, density: number): void; /** * Compute the volume and centroid of this shape intersected with a half plane * @param normal The surface normal. * @param offset The surface offset along the normal. * @param xf The shape transform. * @param c The centroid, this argument is `out`. **/ public ComputeSubmergedArea( normal: b2Vec2, offset: number, xf: b2Transform, c: b2Vec2): number; /** * Clone the shape. **/ public Copy(): b2PolygonShape; /** * Get the edge normal vectors. There is one for each vertex. * @return List of edge normal vectors for each vertex. **/ public GetNormals(): b2Vec2[]; /** * Get the supporting vertex index in the given direction. * @param d Direction to look. * @return Vertex index supporting the direction. **/ public GetSupport(d: b2Vec2): number; /** * Get the supporting vertex in the given direction. * @param d Direciton to look. * @return Vertex supporting the direction. **/ public GetSupportVertex(d: b2Vec2): b2Vec2; /** * Get the vertex count. * @return Vertex count. **/ public GetVertexCount(): number; /** * Get the vertices in local coordinates. * @return List of the vertices in local coordinates. **/ public GetVertices(): b2Vec2[]; /** * Cast a ray against this shape. * @param output Ray cast results, this argument is `out`. * @param input Ray cast input parameters. * @param transform The transform to be applied to the shape. * @return True if the ray hits the shape, otherwise false. **/ public RayCast( output: b2RayCastOutput, input: b2RayCastInput, transform: b2Transform): boolean; /** * Set the shape values from another shape. * @param other The other shape to copy values from. **/ public Set(other: b2Shape): void; /** * Copy vertices. This assumes the vertices define a convex polygon. It is assumed that the exterior is the the right of each edge. * @param vertices List of vertices to create the polygon shape from. * @param vertexCount Number of vertices in the shape, default value is 0 and in the box2dweb.js code it is ignored. * @return Convex polygon shape. **/ public SetAsArray(vertices: b2Vec2[], vertexCount?: number): void; /** * Build vertices to represent an axis-aligned box. * @param hx The half-width. * @param hy The half-height. * @return Box polygon shape. **/ public SetAsBox(hx: number, hy: number): void; /** * Creates a single edge from two vertices. * @param v1 First vertex. * @param v2 Second vertex. * @return Edge polygon shape. **/ public SetAsEdge(v1: b2Vec2, b2: b2Vec2): void; /** * Build vertices to represent an oriented box. * @param hx The half-width. * @param hy The half-height. * @param center The center of the box in local coordinates, default is null (no center?) * @param angle The rotation of the box in local coordinates, default is 0.0. * @return Oriented box shape. **/ public SetAsOrientedBox(hx: number, hy: number, center?: b2Vec2, angle?: number): void; /** * This assumes the vertices define a convex polygon. It is assumed that the exterior is the the right of each edge. * @param vertices List of vertices to create the polygon shape from. * @param vertexCount The number of vertices, default is 0 and in the box2dweb.js code it is ignored. * @return Convex polygon shape. **/ public SetAsVector(vertices: any[], vertexCount?: number): void; /** * Test a point for containment in this shape. This only works for convex shapes. * @param xf Shape world transform. * @param p Point to test against, in world coordinates. * @return True if the point is in this shape, otherwise false. **/ public TestPoint(xf: b2Transform, p: b2Vec2): boolean; } /** * A shape is used for collision detection. Shapes are created in b2Body. You can use shape for collision detection before they are attached to the world. * Warning: you cannot reuse shapes. **/ export class b2Shape { /** * Return value for TestSegment indicating a hit. **/ public static e_hitCollide: number; /** * Return value for TestSegment indicating a miss. **/ public static e_missCollide: number; /** * Return value for TestSegment indicating that the segment starting point, p1, is already inside the shape. **/ public static startsInsideCollide: number; // Note: these enums are public in the source but no referenced by the documentation public static e_unknownShape: number; public static e_circleShape: number; public static e_polygonShape: number; public static e_edgeShape: number; public static e_shapeTypeCount: number; /** * Creates a new b2Shape. **/ constructor(); /** * Given a transform, compute the associated axis aligned bounding box for this shape. * @param aabb Calculated AABB, this argument is `out`. * @param xf Transform to calculate the AABB. **/ public ComputeAABB(aabb: b2AABB, xf: b2Transform): void; /** * Compute the mass properties of this shape using its dimensions and density. The inertia tensor is computed about the local origin, not the centroid. * @param massData Calculate the mass, this argument is `out`. * @param density Density. **/ public ComputeMass(massData: b2MassData, density: number): void; /** * Compute the volume and centroid of this shape intersected with a half plane * @param normal The surface normal. * @param offset The surface offset along the normal. * @param xf The shape transform. * @param c The centroid, this argument is `out`. **/ public ComputeSubmergedArea( normal: b2Vec2, offset: number, xf: b2Transform, c: b2Vec2): number; /** * Clone the shape. **/ public Copy(): b2Shape; /** * Get the type of this shape. You can use this to down cast to the concrete shape. **/ public GetType(): number; /** * Cast a ray against this shape. * @param output Ray cast results, this argument is `out`. * @param input Ray cast input parameters. * @param transform The transform to be applied to the shape. * @param return True if the ray hits the shape, otherwise false. **/ public RayCast( output: b2RayCastOutput, input: b2RayCastInput, transform: b2Transform): boolean; /** * Set the shape values from another shape. * @param other The other shape to copy values from. **/ public Set(other: b2Shape): void; /** * Test if two shapes overlap with the applied transforms. * @param shape1 shape to test for overlap with shape2. * @param transform1 shape1 transform to apply. * @param shape2 shape to test for overlap with shape1. * @param transform2 shape2 transform to apply. * @return True if shape1 and shape2 overlap, otherwise false. **/ public static TestOverlap( shape1: b2Shape, transform1: b2Transform, shape2: b2Shape, transform2: b2Transform): boolean; /** * Test a point for containment in this shape. This only works for convex shapes. * @param xf Shape world transform. * @param p Point to test against, in world coordinates. * @return True if the point is in this shape, otherwise false. **/ public TestPoint(xf: b2Transform, p: b2Vec2): boolean; } /** * A rigid body. **/ export class b2Body { /** * Dynamic Body **/ public static b2_dynamicBody: number; /** * Kinematic Body **/ public static b2_kinematicBody: number; /** * Static Body **/ public static b2_staticBody: number; /** * Apply a force at a world point. If the force is not applied at the center of mass, it will generate a torque and affect the angular velocity. This wakes up the body. * @param force The world force vector, usually in Newtons (N). * @param point The world position of the point of application. **/ public ApplyForce(force: b2Vec2, point: b2Vec2): void; /** * Apply an impulse at a point. This immediately modifies the velocity. It also modifies the angular velocity if the point of application is not at the center of mass. This wakes up the body. * @param impules The world impulse vector, usually in N-seconds or kg-m/s. * @param point The world position of the point of application. **/ public ApplyImpulse(impulse: b2Vec2, point: b2Vec2): void; /** * Apply a torque. This affects the angular velocity without affecting the linear velocity of the center of mass. This wakes up the body. * @param torque Force applied about the z-axis (out of the screen), usually in N-m. **/ public ApplyTorque(torque: number): void; /** * Creates a fixture and attach it to this body. Use this function if you need to set some fixture parameters, like friction. Otherwise you can create the fixture directly from a shape. If the density is non-zero, this function automatically updates the mass of the body. Contacts are not created until the next time step. * @warning This function is locked during callbacks. * @param def The fixture definition; * @return The created fixture. **/ public CreateFixture(def: b2FixtureDef): b2Fixture; /** * Creates a fixture from a shape and attach it to this body. This is a convenience function. Use b2FixtureDef if you need to set parameters like friction, restitution, user data, or filtering. This function automatically updates the mass of the body. * @warning This function is locked during callbacks. * @param shape The shaped of the fixture (to be cloned). * @param density The shape density, default is 0.0, set to zero for static bodies. * @return The created fixture. **/ public CreateFixture2(shape: b2Shape, density?: number): b2Fixture; /** * Destroy a fixture. This removes the fixture from the broad-phase and destroys all contacts associated with this fixture. This will automatically adjust the mass of the body if the body is dynamic and the fixture has positive density. All fixtures attached to a body are implicitly destroyed when the body is destroyed. * @warning This function is locked during callbacks. * @param fixture The fixed to be removed. **/ public DestroyFixture(fixture: b2Fixture): void; /** * Get the angle in radians. * @return The current world rotation angle in radians **/ public GetAngle(): number; /** * Get the angular damping of the body. * @return Angular damping of the body. **/ public GetAngularDamping(): number; /** * Get the angular velocity. * @return The angular velocity in radians/second. **/ public GetAngularVelocity(): number; /** * Get the list of all contacts attached to this body. * @return List of all contacts attached to this body. **/ public GetContactList(): b2ContactEdge; /** * Get the list of all controllers attached to this body. * @return List of all controllers attached to this body. **/ public GetControllerList(): b2ControllerEdge; /** * Get the definition containing the body properties. * @note This provides a feature specific to this port. * @return The body's definition. **/ public GetDefinition(): b2BodyDef; /** * Get the list of all fixtures attached to this body. * @return List of all fixtures attached to this body. **/ public GetFixtureList(): b2Fixture; /** * Get the central rotational inertia of the body. * @return The rotational inertia, usually in kg-m^2. **/ public GetInertia(): number; /** * Get the list of all joints attached to this body. * @return List of all joints attached to this body. **/ public GetJointList(): b2JointEdge; /** * Get the linear damping of the body. * @return The linear damping of the body. **/ public GetLinearDamping(): number; /** * Get the linear velocity of the center of mass. * @return The linear velocity of the center of mass. **/ public GetLinearVelocity(): b2Vec2; /** * Get the world velocity of a local point. * @param localPoint Point in local coordinates. * @return The world velocity of the point. **/ public GetLinearVelocityFromLocalPoint(localPoint: b2Vec2): b2Vec2; /** * Get the world linear velocity of a world point attached to this body. * @param worldPoint Point in world coordinates. * @return The world velocity of the point. **/ public GetLinearVelocityFromWorldPoint(worldPoint: b2Vec2): b2Vec2; /** * Get the local position of the center of mass. * @return Local position of the center of mass. **/ public GetLocalCenter(): b2Vec2; /** * Gets a local point relative to the body's origin given a world point. * @param worldPoint Pointin world coordinates. * @return The corresponding local point relative to the body's origin. **/ public GetLocalPoint(worldPoint: b2Vec2): b2Vec2; /** * Gets a local vector given a world vector. * @param worldVector World vector. * @return The corresponding local vector. **/ public GetLocalVector(worldVector: b2Vec2): b2Vec2; /** * Get the total mass of the body. * @return The body's mass, usually in kilograms (kg). **/ public GetMass(): number; /** * Get the mass data of the body. The rotational inertial is relative to the center of mass. * @param data Body's mass data, this argument is `out`. **/ public GetMassData(data: b2MassData): void; /** * Get the next body in the world's body list. * @return Next body in the world's body list. **/ public GetNext(): b2Body; /** * Get the world body origin position. * @return World position of the body's origin. **/ public GetPosition(): b2Vec2; /** * Get the body transform for the body's origin. * @return World transform of the body's origin. **/ public GetTransform(): b2Transform; /** * Get the type of this body. * @return Body type as uint. **/ public GetType(): number; /** * Get the user data pointer that was provided in the body definition. * @return User's data, cast to the correct type. **/ public GetUserData(): any; /** * Get the parent world of this body. * @return Body's world. **/ public GetWorld(): b2World; /** * Get the world position of the center of mass. * @return World position of the center of mass. **/ public GetWorldCenter(): b2Vec2; /** * Get the world coordinates of a point given the local coordinates. * @param localPoint Point on the body measured relative to the body's origin. * @return localPoint expressed in world coordinates. **/ public GetWorldPoint(localPoint: b2Vec2): b2Vec2; /** * Get the world coordinates of a vector given the local coordinates. * @param localVector Vector fixed in the body. * @return localVector expressed in world coordinates. **/ public GetWorldVector(localVector: b2Vec2): b2Vec2; /** * Get the active state of the body. * @return True if the body is active, otherwise false. **/ public IsActive(): boolean; /** * Get the sleeping state of this body. * @return True if the body is awake, otherwise false. **/ public IsAwake(): boolean; /** * Is the body treated like a bullet for continuous collision detection? * @return True if the body is treated like a bullet, otherwise false. **/ public IsBullet(): boolean; /** * Does this body have fixed rotation? * @return True for fixed, otherwise false. **/ public IsFixedRotation(): boolean; /** * Is this body allowed to sleep? * @return True if the body can sleep, otherwise false. **/ public IsSleepingAllowed(): boolean; /** * Merges another body into this. Only fixtures, mass and velocity are effected, Other properties are ignored. * @note This provides a feature specific to this port. **/ public Merge(other: b2Body): void; /** * This resets the mass properties to the sum of the mass properties of the fixtures. This normally does not need to be called unless you called SetMassData to override the mass and later you want to reset the mass. **/ public ResetMassData(): void; /** * Set the active state of the body. An inactive body is not simulated and cannot be collided with or woken up. If you pass a flag of true, all fixtures will be added to the broad-phase. If you pass a flag of false, all fixtures will be removed from the broad-phase and all contacts will be destroyed. Fixtures and joints are otherwise unaffected. You may continue to create/destroy fixtures and joints on inactive bodies. Fixtures on an inactive body are implicitly inactive and will not participate in collisions, ray-casts, or queries. Joints connected to an inactive body are implicitly inactive. An inactive body is still owned by a b2World object and remains in the body list. * @param flag True to activate, false to deactivate. **/ public SetActive(flag: boolean): void; /** * Set the world body angle * @param angle New angle of the body. **/ public SetAngle(angle: number): void; /** * Set the angular damping of the body. * @param angularDamping New angular damping value. **/ public SetAngularDamping(angularDamping: number): void; /** * Set the angular velocity. * @param omega New angular velocity in radians/second. **/ public SetAngularVelocity(omega: number): void; /** * Set the sleep state of the body. A sleeping body has vety low CPU cost. * @param flag True to set the body to awake, false to put it to sleep. **/ public SetAwake(flag: boolean): void; /** * Should this body be treated like a bullet for continuous collision detection? * @param flag True for bullet, false for normal. **/ public SetBullet(flag: boolean): void; /** * Set this body to have fixed rotation. This causes the mass to be reset. * @param fixed True for no rotation, false to allow for rotation. **/ public SetFixedRotation(fixed: boolean): void; /** * Set the linear damping of the body. * @param linearDamping The new linear damping for this body. **/ public SetLinearDamping(linearDamping: number): void; /** * Set the linear velocity of the center of mass. * @param v New linear velocity of the center of mass. **/ public SetLinearVelocity(v: b2Vec2): void; /** * Set the mass properties to override the mass properties of the fixtures Note that this changes the center of mass position. Note that creating or destroying fixtures can also alter the mass. This function has no effect if the body isn't dynamic. * @warning The supplied rotational inertia should be relative to the center of mass. * @param massData New mass data properties. **/ public SetMassData(massData: b2MassData): void; /** * Set the world body origin position. * @param position New world body origin position. **/ public SetPosition(position: b2Vec2): void; /** * Set the position of the body's origin and rotation (radians). This breaks any contacts and wakes the other bodies. * @param position New world body origin position. * @param angle New world rotation angle of the body in radians. **/ public SetPositionAndAngle(position: b2Vec2, angle: number): void; /** * Is this body allowed to sleep * @param flag True if the body can sleep, false if not. **/ public SetSleepingAllowed(flag: boolean): void; /** * Set the position of the body's origin and rotation (radians). This breaks any contacts and wakes the other bodies. Note this is less efficient than the other overload - you should use that if the angle is available. * @param xf Body's origin and rotation (radians). **/ public SetTransform(xf: b2Transform): void; /** * Set the type of this body. This may alter the mass and velocity * @param type Type enum. **/ public SetType(type: number): void; /** * Set the user data. Use this to store your application specific data. * @param data The user data for this body. **/ public SetUserData(data: any): void; /** * Splits a body into two, preserving dynamic properties * @note This provides a feature specific to this port. * @param callback * @return The newly created bodies from the split. **/ public Split(callback: (fixture: b2Fixture) => boolean): b2Body; } /** * A body definition holds all the data needed to construct a rigid body. You can safely re-use body definitions. **/ export class b2BodyDef { /** * Does this body start out active? **/ public active: boolean; /** * Set this flag to false if this body should never fall asleep. Note that this increases CPU usage. **/ public allowSleep: boolean; /** * The world angle of the body in radians. **/ public angle: number; /** * Angular damping is use to reduce the angular velocity. The damping parameter can be larger than 1.0f but the damping effect becomes sensitive to the time step when the damping parameter is large. **/ public angularDamping: number; /** * The angular velocity of the body. **/ public angularVelocity: number; /** * Is this body initially awake or sleeping? **/ public awake: boolean; /** * Is this a fast moving body that should be prevented from tunneling through other moving bodies? Note that all bodies are prevented from tunneling through static bodies. * @warning You should use this flag sparingly since it increases processing time. **/ public bullet: boolean; /** * Should this body be prevented from rotating? Useful for characters. **/ public fixedRotation: boolean; /** * Scales the inertia tensor. * @warning Experimental **/ public inertiaScale: number; /** * Linear damping is use to reduce the linear velocity. The damping parameter can be larger than 1.0f but the damping effect becomes sensitive to the time step when the damping parameter is large. **/ public linearDamping: number; /** * The linear velocity of the body's origin in world co-ordinates. **/ public linearVelocity: b2Vec2; /** * The world position of the body. Avoid creating bodies at the origin since this can lead to many overlapping shapes. **/ public position: b2Vec2; /** * The body type: static, kinematic, or dynamic. A member of the b2BodyType class . * @note If a dynamic body would have zero mass, the mass is set to one. **/ public type: number; /** * Use this to store application specific body data. **/ public userData: any; } /** * Implement this class to provide collision filtering. In other words, you can implement this class if you want finer control over contact creation. **/ export class b2ContactFilter { /** * Return true if the given fixture should be considered for ray intersection. By default, userData is cast as a b2Fixture and collision is resolved according to ShouldCollide. * @note This function is not in the box2dweb.as code -- might not work. * @see b2World.Raycast() * @see b2ContactFilter.ShouldCollide() * @param userData User provided data. Comments indicate that this might be a b2Fixture. * @return True if the fixture should be considered for ray intersection, otherwise false. **/ public RayCollide(userData: any): boolean; /** * Return true if contact calculations should be performed between these two fixtures. * @warning For performance reasons this is only called when the AABBs begin to overlap. * @param fixtureA b2Fixture potentially colliding with fixtureB. * @param fixtureB b2Fixture potentially colliding with fixtureA. * @return True if fixtureA and fixtureB probably collide requiring more calculations, otherwise false. **/ public ShouldCollide(fixtureA: b2Fixture, fixtureB: b2Fixture): boolean; } /** * Contact impulses for reporting. Impulses are used instead of forces because sub-step forces may approach infinity for rigid body collisions. These match up one-to-one with the contact points in b2Manifold. **/ export class b2ContactImpulse { /** * Normal impulses. **/ public normalImpulses: b2Vec2; /** * Tangent impulses. **/ public tangentImpulses: b2Vec2; } /** * Implement this class to get contact information. You can use these results for things like sounds and game logic. You can also get contact results by traversing the contact lists after the time step. However, you might miss some contacts because continuous physics leads to sub-stepping. Additionally you may receive multiple callbacks for the same contact in a single time step. You should strive to make your callbacks efficient because there may be many callbacks per time step. * @warning You cannot create/destroy Box2D entities inside these callbacks. **/ export class b2ContactListener { /** * Called when two fixtures begin to touch. * @param contact Contact point. **/ public BeginContact(contact: b2Contact): void; /** * Called when two fixtures cease to touch. * @param contact Contact point. **/ public EndContact(contact: b2Contact): void; /** * This lets you inspect a contact after the solver is finished. This is useful for inspecting impulses. Note: the contact manifold does not include time of impact impulses, which can be arbitrarily large if the sub-step is small. Hence the impulse is provided explicitly in a separate data structure. Note: this is only called for contacts that are touching, solid, and awake. * @param contact Contact point. * @param impulse Contact impulse. **/ public PostSolve(contact: b2Contact, impulse: b2ContactImpulse): void; /** * This is called after a contact is updated. This allows you to inspect a contact before it goes to the solver. If you are careful, you can modify the contact manifold (e.g. disable contact). A copy of the old manifold is provided so that you can detect changes. Note: this is called only for awake bodies. Note: this is called even when the number of contact points is zero. Note: this is not called for sensors. Note: if you set the number of contact points to zero, you will not get an EndContact callback. However, you may get a BeginContact callback the next step. * @param contact Contact point. * @param oldManifold Old manifold. **/ public PreSolve(contact: b2Contact, oldManifold: b2Manifold): void; } /** * Implement and register this class with a b2World to provide debug drawing of physics entities in your game. * @example Although Box2D is a physics engine and therefore has nothing to do with drawing, Box2dFlash provides such methods for debugging which are defined in the b2DebugDraw class. In Box2dWeb, a b2DebugDraw takes a canvas-context instead of a Sprite: * * var debugDraw = new b2DebugDraw(); * debugDraw.SetSprite(document.GetElementsByTagName("canvas")[0].getContext("2d")); **/ export class b2DebugDraw { /** * Draw axis aligned bounding boxes. **/ public static e_aabbBit: number; /** * Draw center of mass frame. **/ public static e_centerOfMassBit: number; /** * Draw controllers. **/ public static e_controllerBit: number; /** * Draw joint connections. **/ public static e_jointBit: number; /** * Draw broad-phase pairs. **/ public static e_pairBit: number; /** * Draw shapes. **/ public static e_shapeBit: number; /** * Constructor. **/ constructor(); /** * Append flags to the current flags. * @param flags Flags to add. **/ public AppendFlags(flags: number): void; /** * Clear flags from the current flags. * @param flags flags to clear. **/ public ClearFlags(flags: number): void; /** * Draw a circle. * @param center Circle center point. * @param radius Circle radius. * @param color Circle draw color. **/ public DrawCircle(center: b2Vec2, radius: number, color: b2Color): void; /** * Draw a closed polygon provided in CCW order. * @param vertices Polygon verticies. * @param vertexCount Number of vertices in the polygon, usually vertices.length. * @param color Polygon draw color. **/ public DrawPolygon(vertices: b2Vec2[], vertexCount: number, color: b2Color): void; /** * Draw a line segment. * @param p1 Line beginpoint. * @param p2 Line endpoint. * @param color Line color. **/ public DrawSegment(p1: b2Vec2, p2: b2Vec2, color: b2Color): void; /** * Draw a solid circle. * @param center Circle center point. * @param radius Circle radius. * @param axis Circle axis. * @param color Circle color. **/ public DrawSolidCircle(center: b2Vec2, radius: number, axis: b2Vec2, color: b2Color): void; /** * Draw a solid closed polygon provided in CCW order. * @param vertices Polygon verticies. * @param vertexCount Number of vertices in the polygon, usually vertices.length. * @param color Polygon draw color. **/ public DrawSolidPolygon(vertices: b2Vec2[], vertexCount: number, color: b2Color): void; /** * Draw a transform. Choose your own length scale. * @param xf Transform to draw. **/ public DrawTransform(xf: b2Transform): void; /** * Get the alpha value used for lines. * @return Alpha value used for drawing lines. **/ public GetAlpha(): number; /** * Get the draw scale. * @return Draw scale ratio. **/ public GetDrawScale(): number; /** * Get the alpha value used for fills. * @return Alpha value used for drawing fills. **/ public GetFillAlpha(): number; /** * Get the drawing flags. * @return Drawing flags. **/ public GetFlags(): number; /** * Get the line thickness. * @return Line thickness. **/ public GetLineThickness(): number; /** * Get the HTML Canvas Element for drawing. * @note box2dflash uses Sprite object, box2dweb uses CanvasRenderingContext2D, that is why this function is called GetSprite(). * @return The HTML Canvas Element used for debug drawing. **/ public GetSprite(): CanvasRenderingContext2D; /** * Get the scale used for drawing XForms. * @return Scale for drawing transforms. **/ public GetXFormScale(): number; /** * Set the alpha value used for lines. * @param alpha Alpha value for drawing lines. **/ public SetAlpha(alpha: number): void; /** * Set the draw scale. * @param drawScale Draw scale ratio. **/ public SetDrawScale(drawScale: number): void; /** * Set the alpha value used for fills. * @param alpha Alpha value for drawing fills. **/ public SetFillAlpha(alpha: number): void; /** * Set the drawing flags. * @param flags Sets the drawing flags. **/ public SetFlags(flags: number): void; /** * Set the line thickness. * @param lineThickness The new line thickness. **/ public SetLineThickness(lineThickness: number): void; /** * Set the HTML Canvas Element for drawing. * @note box2dflash uses Sprite object, box2dweb uses CanvasRenderingContext2D, that is why this function is called SetSprite(). * @param canvas HTML Canvas Element to draw debug information to. **/ public SetSprite(canvas: CanvasRenderingContext2D): void; /** * Set the scale used for drawing XForms. * @param xformScale The transform scale. **/ public SetXFormScale(xformScale: number): void; } /** * Joints and shapes are destroyed when their associated body is destroyed. Implement this listener so that you may nullify references to these joints and shapes. **/ export class b2DestructionListener { /** * Called when any fixture is about to be destroyed due to the destruction of its parent body. * @param fixture b2Fixture being destroyed. **/ public SayGoodbyeFixture(fixture: b2Fixture): void; /** * Called when any joint is about to be destroyed due to the destruction of one of its attached bodies. * @param joint b2Joint being destroyed. **/ public SayGoodbyeJoint(joint: b2Joint): void; } /** * This holds contact filtering data. **/ export class b2FilterData { /** * The collision category bits. Normally you would just set one bit. **/ public categoryBits: number; /** * Collision groups allow a certain group of objects to never collide (negative) or always collide (positive). Zero means no collision group. Non-zero group filtering always wins against the mask bits. **/ public groupIndex: number; /** * The collision mask bits. This states the categories that this shape would accept for collision. **/ public maskBits: number; /** * Creates a copy of the filter data. * @return Copy of this filter data. **/ public Copy(): b2FilterData; } /** * A fixture is used to attach a shape to a body for collision detection. A fixture inherits its transform from its parent. Fixtures hold additional non-geometric data such as friction, collision filters, etc. Fixtures are created via b2Body::CreateFixture. * @warning you cannot reuse fixtures. **/ export class b2Fixture { /** * Get the fixture's AABB. This AABB may be enlarge and/or stale. If you need a more accurate AABB, compute it using the shape and the body transform. * @return Fiture's AABB. **/ public GetAABB(): b2AABB; /** * Get the parent body of this fixture. This is NULL if the fixture is not attached. * @return The parent body. **/ public GetBody(): b2Body; /** * Get the density of this fixture. * @return Density **/ public GetDensity(): number; /** * Get the contact filtering data. * @return Filter data. **/ public GetFilterData(): b2FilterData; /** * Get the coefficient of friction. * @return Friction. **/ public GetFriction(): number; /** * Get the mass data for this fixture. The mass data is based on the density and the shape. The rotational inertia is about the shape's origin. This operation may be expensive. * @param massData This is a reference to a valid b2MassData, if it is null a new b2MassData is allocated and then returned. Default = null. * @return Mass data. **/ public GetMassData(massData?: b2MassData): b2MassData; /** * Get the next fixture in the parent body's fixture list. * @return Next fixture. **/ public GetNext(): b2Fixture; /** * Get the coefficient of restitution. * @return Restitution. **/ public GetRestitution(): number; /** * Get the child shape. You can modify the child shape, however you should not change the number of vertices because this will crash some collision caching mechanisms. * @return Fixture shape. **/ public GetShape(): b2Shape; /** * Get the type of the child shape. You can use this to down cast to the concrete shape. * @return Shape type enum. **/ public GetType(): number; /** * Get the user data that was assigned in the fixture definition. Use this to store your application specific data. * @return User provided data. Cast to your object type. **/ public GetUserData(): any; /** * Is this fixture a sensor (non-solid)? * @return True if the shape is a sensor, otherwise false. **/ public IsSensor(): boolean; /** * Perform a ray cast against this shape. * @param output Ray cast results. This argument is out. * @param input Ray cast input parameters. * @return True if the ray hits the shape, otherwise false. **/ public RayCast(output: b2RayCastOutput, input: b2RayCastInput): boolean; /** * Set the density of this fixture. This will _not_ automatically adjust the mass of the body. You must call b2Body::ResetMassData to update the body's mass. * @param density The new density. **/ public SetDensity(density: number): void; /** * Set the contact filtering data. This will not update contacts until the next time step when either parent body is active and awake. * @param filter The new filter data. **/ public SetFilterData(filter: any): void; /** * Set the coefficient of friction. * @param friction The new friction coefficient. **/ public SetFriction(friction: number): void; /** * Get the coefficient of restitution. * @param resitution The new restitution coefficient. **/ public SetRestitution(restitution: number): void; /** * Set if this fixture is a sensor. * @param sensor True to set as a sensor, false to not be a sensor. **/ public SetSensor(sensor: boolean): void; /** * Set the user data. Use this to store your application specific data. * @param data User provided data. **/ public SetUserData(data: any): void; /** * Test a point for containment in this fixture. * @param p Point to test against, in world coordinates. * @return True if the point is in this shape, otherwise false. **/ public TestPoint(p: b2Vec2): boolean; } /** * A fixture definition is used to create a fixture. This class defines an abstract fixture definition. You can reuse fixture definitions safely. **/ export class b2FixtureDef { /** * The density, usually in kg/m^2. **/ public density: number; /** * Contact filtering data. **/ public filter: b2FilterData; /** * The friction coefficient, usually in the range [0,1]. **/ public friction: number; /** * A sensor shape collects contact information but never generates a collision response. **/ public isSensor: boolean; /** * The restitution (elasticity) usually in the range [0,1]. **/ public restitution: number; /** * The shape, this must be set. The shape will be cloned, so you can create the shape on the stack. **/ public shape: b2Shape; /** * Use this to store application specific fixture data. **/ public userData: any; /** * The constructor sets the default fixture definition values. **/ constructor(); } /** * The world class manages all physics entities, dynamic simulation, and asynchronous queries. **/ export class b2World { /** * Locked **/ public static e_locked: number; /** * New Fixture **/ public static e_newFixture: number; /** * Creates a new world. * @param gravity The world gravity vector. * @param doSleep Improvie performance by not simulating inactive bodies. **/ constructor(gravity: b2Vec2, doSleep: boolean); /** * Add a controller to the world list. * @param c Controller to add. * @return Controller that was added to the world. **/ public AddController(c: b2Controller): b2Controller; /** * Call this after you are done with time steps to clear the forces. You normally call this after each call to Step, unless you are performing sub-steps. **/ public ClearForces(): void; /** * Create a rigid body given a definition. No reference to the definition is retained. * @param def Body's definition. * @return Created rigid body. **/ public CreateBody(def: b2BodyDef): b2Body; /** * Creates a new controller. * @param controller New controller. * @return New controller. **/ public CreateController(controller: b2Controller): b2Controller; /** * Create a joint to constrain bodies together. No reference to the definition is retained. This may cause the connected bodies to cease colliding. * @warning This function is locked during callbacks. * @param def Joint definition. * @return New created joint. **/ public CreateJoint(def: b2JointDef): b2Joint; /** * Destroy a rigid body given a definition. No reference to the definition is retained. This function is locked during callbacks. * @param b Body to destroy. * @warning This function is locked during callbacks. **/ public DestroyBody(b: b2Body): void; /** * Destroy a controller given the controller instance. * @warning This function is locked during callbacks. * @param controller Controller to destroy. **/ public DestroyController(controller: b2Controller): void; /** * Destroy a joint. This may cause the connected bodies to begin colliding. * @param j Joint to destroy. **/ public DestroyJoint(j: b2Joint): void; /** * Call this to draw shapes and other debug draw data. **/ public DrawDebugData(): void; /** * Get the number of bodies. * @return Number of bodies in this world. **/ public GetBodyCount(): number; /** * Get the world body list. With the returned body, use b2Body::GetNext to get the next body in the world list. A NULL body indicates the end of the list. * @return The head of the world body list. **/ public GetBodyList(): b2Body; /** * Get the number of contacts (each may have 0 or more contact points). * @return Number of contacts. **/ public GetContactCount(): number; /** * Get the world contact list. With the returned contact, use b2Contact::GetNext to get the next contact in the world list. A NULL contact indicates the end of the list. * @return The head of the world contact list. **/ public GetContactList(): b2Contact; /** * Get the global gravity vector. * @return Global gravity vector. **/ public GetGravity(): b2Vec2; /** * The world provides a single static ground body with no collision shapes. You can use this to simplify the creation of joints and static shapes. * @return The ground body. **/ public GetGroundBody(): b2Body; /** * Get the number of joints. * @return The number of joints in the world. **/ public GetJointCount(): number; /** * Get the world joint list. With the returned joint, use b2Joint::GetNext to get the next joint in the world list. A NULL joint indicates the end of the list. * @return The head of the world joint list. **/ public GetJointList(): b2Joint; /** * Get the number of broad-phase proxies. * @return Number of borad-phase proxies. **/ public GetProxyCount(): number; /** * Is the world locked (in the middle of a time step). * @return True if the world is locked and in the middle of a time step, otherwise false. **/ public IsLocked(): boolean; /** * Query the world for all fixtures that potentially overlap the provided AABB. * @param callback A user implemented callback class. It should match signature function Callback(fixture:b2Fixture):Boolean. Return true to continue to the next fixture. * @param aabb The query bounding box. **/ public QueryAABB(callback: (fixutre: b2Fixture) => boolean, aabb: b2AABB): void; /** * Query the world for all fixtures that contain a point. * @note This provides a feature specific to this port. * @param callback A user implemented callback class. It should match signature function Callback(fixture:b2Fixture):Boolean. Return true to continue to the next fixture. * @param p The query point. **/ public QueryPoint(callback: (fixture: b2Fixture) => boolean, p: b2Vec2): void; /** * Query the world for all fixtures that precisely overlap the provided transformed shape. * @note This provides a feature specific to this port. * @param callback A user implemented callback class. It should match signature function Callback(fixture:b2Fixture):Boolean. Return true to continue to the next fixture. * @param shape The query shape. * @param transform Optional transform, default = null. **/ public QueryShape(callback: (fixture: b2Fixture) => boolean, shape: b2Shape, transform?: b2Transform): void; /** * Ray-cast the world for all fixtures in the path of the ray. Your callback Controls whether you get the closest point, any point, or n-points The ray-cast ignores shapes that contain the starting point. * @param callback A callback function which must be of signature: * function Callback( * fixture:b2Fixture, // The fixture hit by the ray * point:b2Vec2, // The point of initial intersection * normal:b2Vec2, // The normal vector at the point of intersection * fraction:Number // The fractional length along the ray of the intersection * ):Number * Callback should return the new length of the ray as a fraction of the original length. By returning 0, you immediately terminate. By returning 1, you continue wiht the original ray. By returning the current fraction, you proceed to find the closest point. * @param point1 The ray starting point. * @param point2 The ray ending point. **/ public RayCast(callback: (fixture: b2Fixture, point: b2Vec2, normal: b2Vec2, fraction: number) => number, point1: b2Vec2, point2: b2Vec2): void; /** * Ray-cast the world for all fixture in the path of the ray. * @param point1 The ray starting point. * @param point2 The ray ending point. * @return Array of all the fixtures intersected by the ray. **/ public RayCastAll(point1: b2Vec2, point2: b2Vec2): b2Fixture[]; /** * Ray-cast the world for the first fixture in the path of the ray. * @param point1 The ray starting point. * @param point2 The ray ending point. * @return First fixture intersected by the ray. **/ public RayCastOne(point1: b2Vec2, point2: b2Vec2): b2Fixture; /** * Removes the controller from the world. * @param c Controller to remove. **/ public RemoveController(c: b2Controller): void; /** * Use the given object as a broadphase. The old broadphase will not be cleanly emptied. * @warning This function is locked during callbacks. * @param broadphase: Broad phase implementation. **/ public SetBroadPhase(broadPhase: IBroadPhase): void; /** * Register a contact filter to provide specific control over collision. Otherwise the default filter is used (b2_defaultFilter). * @param filter Contact filter'er. **/ public SetContactFilter(filter: b2ContactFilter): void; /** * Register a contact event listener. * @param listener Contact event listener. **/ public SetContactListener(listener: b2ContactListener): void; /** * Enable/disable continuous physics. For testing. * @param flag True for continuous physics, otherwise false. **/ public SetContinuousPhysics(flag: boolean): void; /** * Register a routine for debug drawing. The debug draw functions are called inside the b2World::Step method, so make sure your renderer is ready to consume draw commands when you call Step(). * @param debugDraw Debug drawing instance. **/ public SetDebugDraw(debugDraw: b2DebugDraw): void; /** * Destruct the world. All physics entities are destroyed and all heap memory is released. * @param listener Destruction listener instance. **/ public SetDestructionListener(listener: b2DestructionListener): void; /** * Change the global gravity vector. * @param gravity New global gravity vector. **/ public SetGravity(gravity: b2Vec2): void; /** * Enable/disable warm starting. For testing. * @param flag True for warm starting, otherwise false. **/ public SetWarmStarting(flag: boolean): void; /** * Take a time step. This performs collision detection, integration, and constraint solution. * @param dt The amout of time to simulate, this should not vary. * @param velocityIterations For the velocity constraint solver. * @param positionIterations For the position constraint solver. **/ public Step(dt: number, velocityIterations: number, positionIterations: number): void; /** * Perform validation of internal data structures. **/ public Validate(): void; } /** * The class manages contact between two shapes. A contact exists for each overlapping AABB in the broad-phase (except if filtered). Therefore a contact object may exist that has no contact points. **/ export class b2Contact { /** * Constructor **/ constructor(); /** * Flag this contact for filtering. Filtering will occur the next time step. **/ public FlagForFiltering(): void; /** * Get the first fixture in this contact. * @return First fixture in this contact. **/ public GetFixtureA(): b2Fixture; /** * Get the second fixture in this contact. * @return Second fixture in this contact. **/ public GetFixtureB(): b2Fixture; /** * Get the contact manifold. Do not modify the manifold unless you understand the internals of * @return Contact manifold. **/ public GetManifold(): b2Manifold; /** * Get the next contact in the world's contact list. * @return Next contact in the world's contact list. **/ public GetNext(): b2Contact; /** * Get the world manifold. * @param worldManifold World manifold out. * @return World manifold. **/ public GetWorldManifold(worldManifold: b2WorldManifold): void; /** * Does this contact generate TOI events for continuous simulation. * @return True for continous, otherwise false. **/ public IsContinuous(): boolean; /** * Has this contact been disabled? * @return True if disabled, otherwise false. **/ public IsEnabled(): boolean; /** * Is this contact a sensor? * @return True if sensor, otherwise false. **/ public IsSensor(): boolean; /** * Is this contact touching. * @return True if contact is touching, otherwise false. **/ public IsTouching(): boolean; /** * Enable/disable this contact. This can be used inside the pre-solve contact listener. The contact is only disabled for the current time step (or sub-step in continuous collision). * @param flag True to enable, false to disable. **/ public SetEnabled(flag: boolean): void; /** * Change this to be a sensor or-non-sensor contact. * @param sensor True to be sensor, false to not be a sensor. **/ public SetSensor(sensor: boolean): void; } /** * A contact edge is used to connect bodies and contacts together in a contact graph where each body is a node and each contact is an edge. A contact edge belongs to a doubly linked list maintained in each attached body. Each contact has two contact nodes, one for each attached body. **/ export class b2ContactEdge { /** * Contact. **/ public contact: b2Contact; /** * Next contact edge. **/ public next: b2ContactEdge; /** * Contact body. **/ public other: b2Body; /** * Previous contact edge. **/ public prev: b2ContactEdge; } /** * This structure is used to report contact point results. **/ export class b2ContactResult { /** * The contact id identifies the features in contact. **/ public id: b2ContactID; /** * Points from shape1 to shape2. **/ public normal: b2Vec2; /** * The normal impulse applied to body2. **/ public normalImpulse: number; /** * Position in world coordinates. **/ public position: b2Vec2; /** * The first shape. **/ public shape1: b2Shape; /** * The second shape. **/ public shape2: b2Shape; /** * The tangent impulse applied to body2. **/ public tangentImpulse: number; } /** * Base class for controllers. Controllers are a convience for encapsulating common per-step functionality. **/ export class b2Controller { /** * Body count. **/ public m_bodyCount: number; /** * List of bodies. **/ public m_bodyList: b2ControllerEdge; /** * Adds a body to the controller. * @param body Body to add. **/ public AddBody(body: b2Body): void; /** * Removes all bodies from the controller. **/ public Clear(): void; /** * Debug drawing. * @param debugDraw Handle to drawer. **/ public Draw(debugDraw: b2DebugDraw): void; /** * Gets the body list. * @return Body list. **/ public GetBodyList(): b2ControllerEdge; /** * Gets the next controller. * @return Next controller. **/ public GetNext(): b2Controller; /** * Gets the world. * @return World. **/ public GetWorld(): b2World; /** * Removes a body from the controller. * @param body Body to remove from this controller. **/ public RemoveBody(body: b2Body): void; /** * Step * @param step b2TimeStep -> Private internal class. Not sure why this is exposed. **/ public Step(step: any/*b2TimeStep*/): void; } /** * Controller Edge. **/ export class b2ControllerEdge { /** * Body. **/ public body: b2Body; /** * Provides quick access to the other end of this edge. **/ public controller: b2Controller; /** * The next controller edge in the controller's body list. **/ public nextBody: b2ControllerEdge; /** * The next controller edge in the body's controller list. **/ public nextController: b2ControllerEdge; /** * The previous controller edge in the controller's body list. **/ public prevBody: b2ControllerEdge; /** * The previous controller edge in the body's controller list. **/ public prevController: b2ControllerEdge; } /** * Calculates buoyancy forces for fluids in the form of a half plane. **/ export class b2BuoyancyController extends b2Controller { /** * Linear drag co-efficient. * @default = 1 **/ public angularDrag: number; /** * The fluid density. * @default = 0 **/ public density: number; /** * Gravity vector, if the world's gravity is not used. * @default = null **/ public gravity: b2Vec2; /** * Linear drag co-efficient. * @default = 2 **/ public linearDrag: number; /** * The outer surface normal. **/ public normal: b2Vec2; /** * The height of the fluid surface along the normal. * @default = 0 **/ public offset: number; /** * If false, bodies are assumed to be uniformly dense, otherwise use the shapes densities. * @default = false. **/ public useDensity: boolean; /** * If true, gravity is taken from the world instead of the gravity parameter. * @default = true. **/ public useWorldGravity: boolean; /** * Fluid velocity, for drag calculations. **/ public velocity: b2Vec2; } /** * Applies an acceleration every frame, like gravity **/ export class b2ConstantAccelController extends b2Controller { /** * The acceleration to apply. **/ public A: b2Vec2; /** * @see b2Controller.Step **/ public Step(step: any/* b2TimeStep*/): void; } /** * Applies an acceleration every frame, like gravity. **/ export class b2ConstantForceController extends b2Controller { /** * The acceleration to apply. **/ public A: b2Vec2; /** * @see b2Controller.Step **/ public Step(step: any/* b2TimeStep*/): void; } /** * Applies simplified gravity between every pair of bodies. **/ export class b2GravityController extends b2Controller { /** * Specifies the strength of the gravitation force. * @default = 1 **/ public G: number; /** * If true, gravity is proportional to r^-2, otherwise r^-1. **/ public invSqr: boolean; /** * @see b2Controller.Step **/ public Step(step: any/* b2TimeStep*/): void; } /** * Applies top down linear damping to the controlled bodies The damping is calculated by multiplying velocity by a matrix in local co-ordinates. **/ export class b2TensorDampingController extends b2Controller { /** * Set this to a positive number to clamp the maximum amount of damping done. * @default = 0 **/ public maxTimeStep: number; /** * Tensor to use in damping model. **/ public T: b2Mat22; /** * Helper function to set T in a common case. * @param xDamping x * @param yDamping y **/ public SetAxisAligned(xDamping: number, yDamping: number): void; /** * @see b2Controller.Step **/ public Step(step: any/* b2TimeStep*/): void; } /** * The base joint class. Joints are used to constraint two bodies together in various fashions. Some joints also feature limits and motors. **/ export class b2Joint { /** * Get the anchor point on bodyA in world coordinates. * @return Anchor A point. **/ public GetAnchorA(): b2Vec2; /** * Get the anchor point on bodyB in world coordinates. * @return Anchor B point. **/ public GetAnchorB(): b2Vec2; /** * Get the first body attached to this joint. * @return Body A. **/ public GetBodyA(): b2Body; /** * Get the second body attached to this joint. * @return Body B. **/ public GetBodyB(): b2Body; /** * Get the next joint the world joint list. * @return Next joint. **/ public GetNext(): b2Joint; /** * Get the reaction force on body2 at the joint anchor in Newtons. * @param inv_dt * @return Reaction force (N) **/ public GetReactionForce(inv_dt: number): b2Vec2; /** * Get the reaction torque on body2 in N. * @param inv_dt * @return Reaction torque (N). **/ public GetReactionTorque(inv_dt: number): number; /** * Get the type of the concrete joint. * @return Joint type. **/ public GetType(): number; /** * Get the user data pointer. * @return User data. Cast to your data type. **/ public GetUserData(): any; /** * Short-cut function to determine if either body is inactive. * @return True if active, otherwise false. **/ public IsActive(): boolean; /** * Set the user data pointer. * @param data Your custom data. **/ public SetUserData(data: any): void; } /** * Joint definitions are used to construct joints. **/ export class b2JointDef { /** * The first attached body. **/ public bodyA: b2Body; /** * The second attached body. **/ public bodyB: b2Body; /** * Set this flag to true if the attached bodies should collide. **/ public collideConnected: boolean; /** * The joint type is set automatically for concrete joint types. **/ public type: number; /** * Use this to attach application specific data to your joints. **/ public userData: any; /** * Constructor. **/ constructor(); } /** * A joint edge is used to connect bodies and joints together in a joint graph where each body is a node and each joint is an edge. A joint edge belongs to a doubly linked list maintained in each attached body. Each joint has two joint nodes, one for each attached body. **/ export class b2JointEdge { /** * The joint. **/ public joint: b2Joint; /** * The next joint edge in the body's joint list. **/ public next: b2JointEdge; /** * Provides quick access to the other body attached. **/ public other: b2Body; /** * The previous joint edge in the body's joint list. **/ public prev: b2JointEdge; } /** * A distance joint constrains two points on two bodies to remain at a fixed distance from each other. You can view this as a massless, rigid rod. **/ export class b2DistanceJoint extends b2Joint { /** * Get the anchor point on bodyA in world coordinates. * @return Body A anchor. **/ public GetAnchorA(): b2Vec2; /** * Get the anchor point on bodyB in world coordinates. * @return Body B anchor. **/ public GetAnchorB(): b2Vec2; /** * Gets the damping ratio. * @return Damping ratio. **/ public GetDampingRatio(): number; /** * Gets the frequency. * @return Frequency. **/ public GetFrequency(): number; /** * Gets the length of distance between the two bodies. * @return Length. **/ public GetLength(): number; /** * Get the reaction force on body2 at the joint anchor in N. * @param inv_dt * @return Reaction force in N. **/ public GetReactionForce(inv_dt: number): b2Vec2; /** * Get the reaction torque on body 2 in N. * @param inv_dt * @return Reaction torque in N. **/ public GetReactionTorque(inv_dt: number): number; /** * Sets the damping ratio. * @param ratio New damping ratio. **/ public SetDampingRatio(ratio: number): void; /** * Sets the frequency. * @param hz New frequency (hertz). **/ public SetFrequency(hz: number): void; /** * Sets the length of distance between the two bodies. * @param length New length. **/ public SetLength(length: number): void; } /** * Distance joint definition. This requires defining an anchor point on both bodies and the non-zero length of the distance joint. The definition uses local anchor points so that the initial configuration can violate the constraint slightly. This helps when saving and loading a game. * @warning Do not use a zero or short length. **/ export class b2DistanceJointDef extends b2JointDef { /** * The damping ratio. 0 = no damping, 1 = critical damping. **/ public dampingRatio: number; /** * The mass-spring-damper frequency in Hertz. **/ public frequencyHz: number; /** * The natural length between the anchor points. **/ public length: number; /** * The local anchor point relative to body1's origin. **/ public localAnchorA: b2Vec2; /** * The local anchor point relative to body2's origin. **/ public localAnchorB: b2Vec2; /** * Constructor. **/ constructor(); /** * Initialize the bodies, anchors, and length using the world anchors. * @param bA Body A. * @param bB Body B. * @param anchorA Anchor A. * @param anchorB Anchor B. **/ public Initialize(bA: b2Body, bB: b2Body, anchorA: b2Vec2, anchorB: b2Vec2): void; } /** * Friction joint. This is used for top-down friction. It provides 2D translational friction and angular friction. **/ export class b2FrictionJoint extends b2Joint { /** * Angular mass. **/ public m_angularMass: number; /** * Linear mass. **/ public m_linearMass: b2Mat22; /** * Get the anchor point on bodyA in world coordinates. * @return Body A anchor. **/ public GetAnchorA(): b2Vec2; /** * Get the anchor point on bodyB in world coordinates. * @return Body B anchor. **/ public GetAnchorB(): b2Vec2; /** * Gets the max force. * @return Max force. **/ public GetMaxForce(): number; /** * Gets the max torque. * @return Max torque. **/ public GetMaxTorque(): number; /** * Get the reaction force on body2 at the joint anchor in N. * @param inv_dt * @return Reaction force in N. **/ public GetReactionForce(inv_dt: number): b2Vec2; /** * Get the reaction torque on body 2 in N. * @return Reaction torque in N. **/ public GetReactionTorque(inv_dt: number): number; /** * Sets the max force. * @param force New max force. **/ public SetMaxForce(force: number): void; /** * Sets the max torque. * @param torque New max torque. **/ public SetMaxTorque(torque: number): void; } /** * Friction joint defintion. **/ export class b2FrictionJointDef extends b2JointDef { /** * The local anchor point relative to body1's origin. **/ public localAnchorA: b2Vec2; /** * The local anchor point relative to body2's origin. **/ public localAnchorB: b2Vec2; /** * The maximum force in N. **/ public maxForce: number; /** * The maximum friction torque in N-m. **/ public maxTorque: number; /** * Constructor. **/ constructor(); /** * Initialize the bodies, anchors, axis, and reference angle using the world anchor and world axis. * @param bA Body A. * @param bB Body B. * @param anchor World anchor. **/ public Initialize(bA: b2Body, bB: b2Body, anchor: b2Vec2): void; } /** * A gear joint is used to connect two joints together. Either joint can be a revolute or prismatic joint. You specify a gear ratio to bind the motions together: coordinate1 + ratio coordinate2 = constant The ratio can be negative or positive. If one joint is a revolute joint and the other joint is a prismatic joint, then the ratio will have units of length or units of 1/length. * @warning The revolute and prismatic joints must be attached to fixed bodies (which must be body1 on those joints). **/ export class b2GearJoint extends b2Joint { /** * Get the anchor point on bodyA in world coordinates. * @return Body A anchor. **/ public GetAnchorA(): b2Vec2; /** * Get the anchor point on bodyB in world coordinates. * @return Body B anchor. **/ public GetAnchorB(): b2Vec2; /** * Get the gear ratio. * @return Gear ratio. **/ public GetRatio(): number; /** * Get the reaction force on body2 at the joint anchor in N. * @param inv_dt * @return Reaction force in N. **/ public GetReactionForce(inv_dt: number): b2Vec2; /** * Get the reaction torque on body 2 in N. * @param inv_dt * @return Reaction torque in N. **/ public GetReactionTorque(inv_dt: number): number; /** * Set the gear ratio. * @param force New gear ratio. **/ public SetRatio(ratio: number): void; } /** * Gear joint definition. This definition requires two existing revolute or prismatic joints (any combination will work). The provided joints must attach a dynamic body to a static body. **/ export class b2GearJointDef extends b2JointDef { /** * The first revolute/prismatic joint attached to the gear joint. **/ public joint1: b2Joint; /** * The second revolute/prismatic joint attached to the gear joint. **/ public joint2: b2Joint; /** * The gear ratio. **/ public ratio: number; /** * Constructor. **/ constructor(); } /** * A line joint. This joint provides one degree of freedom: translation along an axis fixed in body1. You can use a joint limit to restrict the range of motion and a joint motor to drive the motion or to model joint friction. **/ export class b2LineJoint extends b2Joint { /** * Enable/disable the joint limit. * @param flag True to enable, false to disable limits **/ public EnableLimit(flag: boolean): void; /** * Enable/disable the joint motor. * @param flag True to enable, false to disable the motor. **/ public EnableMotor(flag: boolean): void; /** * Get the anchor point on bodyA in world coordinates. * @return Body A anchor. **/ public GetAnchorA(): b2Vec2; /** * Get the anchor point on bodyB in world coordinates. * @return Body B anchor. **/ public GetAnchorB(): b2Vec2; /** * Get the current joint translation speed, usually in meters per second. * @return Joint speed. **/ public GetJointSpeed(): number; /** * Get the current joint translation, usually in meters. * @return Joint translation. **/ public GetJointTranslation(): number; /** * Get the lower joint limit, usually in meters. * @return Lower limit. **/ public GetLowerLimit(): number; /** * Get the maximum motor force, usually in N. * @return Max motor force. **/ public GetMaxMotorForce(): number; /** * Get the current motor force, usually in N. * @return Motor force. **/ public GetMotorForce(): number; /** * Get the motor speed, usually in meters per second. * @return Motor speed. **/ public GetMotorSpeed(): number; /** * Get the reaction force on body2 at the joint anchor in N. * @param inv_dt * @return Reaction force in N. **/ public GetReactionForce(inv_dt: number): b2Vec2; /** * Get the reaction torque on body 2 in N. * @param inv_dt * @return Reaction torque in N. **/ public GetReactionTorque(inv_dt: number): number; /** * Get the upper joint limit, usually in meters. * @return Upper limit. **/ public GetUpperLimit(): number; /** * Is the joint limit enabled? * @return True if enabled otherwise false. **/ public IsLimitEnabled(): boolean; /** * Is the joint motor enabled? * @return True if enabled, otherwise false. **/ public IsMotorEnabled(): boolean; /** * Set the joint limits, usually in meters. * @param lower Lower limit. * @param upper Upper limit. **/ public SetLimits(lower: number, upper: number): void; /** * Set the maximum motor force, usually in N. * @param force New max motor force. **/ public SetMaxMotorForce(force: number): void; /** * Set the motor speed, usually in meters per second. * @param speed New motor speed. **/ public SetMotorSpeed(speed: number): void; } /** * Line joint definition. This requires defining a line of motion using an axis and an anchor point. The definition uses local anchor points and a local axis so that the initial configuration can violate the constraint slightly. The joint translation is zero when the local anchor points coincide in world space. Using local anchors and a local axis helps when saving and loading a game. **/ export class b2LineJointDef extends b2JointDef { /** * Enable/disable the joint limit. **/ public enableLimit: boolean; /** * Enable/disable the joint motor. **/ public enableMotor: boolean; /** * The local anchor point relative to body1's origin. **/ public localAnchorA: b2Vec2; /** * The local anchor point relative to body2's origin. **/ public localAnchorB: b2Vec2; /** * The local translation axis in bodyA. **/ public localAxisA: b2Vec2; /** * The lower translation limit, usually in meters. **/ public lowerTranslation: number; /** * The maximum motor torque, usually in N-m. **/ public maxMotorForce: number; /** * The desired motor speed in radians per second. **/ public motorSpeed: number; /** * The upper translation limit, usually in meters. **/ public upperTranslation: number; /** * Constructor. **/ constructor(); /** * Initialize the bodies, anchors, and length using the world anchors. * @param bA Body A. * @param bB Body B. * @param anchor Anchor. * @param axis Axis. **/ public Initialize(bA: b2Body, bB: b2Body, anchor: b2Vec2, axis: b2Vec2): void; } /** * A mouse joint is used to make a point on a body track a specified world point. This a soft constraint with a maximum force. This allows the constraint to stretch and without applying huge forces. Note: this joint is not fully documented as it is intended primarily for the testbed. See that for more instructions. **/ export class b2MouseJoint extends b2Joint { /** * Get the anchor point on bodyA in world coordinates. * @return Body A anchor. **/ public GetAnchorA(): b2Vec2; /** * Get the anchor point on bodyB in world coordinates. * @return Body B anchor. **/ public GetAnchorB(): b2Vec2; /** * Gets the damping ratio. * @return Damping ratio. **/ public GetDampingRatio(): number; /** * Gets the frequency. * @return Frequency. **/ public GetFrequency(): number; /** * Gets the max force. * @return Max force. **/ public GetMaxForce(): number; /** * Get the reaction force on body2 at the joint anchor in N. * @param inv_dt * @return Reaction force in N. **/ public GetReactionForce(inv_dt: number): b2Vec2; /** * Get the reaction torque on body 2 in N. * @param inv_dt * @return Reaction torque in N. **/ public GetReactionTorque(inv_dt: number): number; /** * Gets the target. * @return Target. **/ public GetTarget(): b2Vec2; /** * Sets the damping ratio. * @param ratio New damping ratio. **/ public SetDampingRatio(ratio: number): void; /** * Sets the frequency. * @param hz New frequency (hertz). **/ public SetFrequency(hz: number): void; /** * Sets the max force. * @param maxForce New max force. **/ public SetMaxForce(maxForce: number): void; /** * Use this to update the target point. * @param target New target. **/ public SetTarget(target: b2Vec2): void; } /** * Mouse joint definition. This requires a world target point, tuning parameters, and the time step. **/ export class b2MouseJointDef extends b2JointDef { /** * The damping ratio. 0 = no damping, 1 = critical damping. **/ public dampingRatio: number; /** * The response speed. **/ public frequencyHz: number; /** * The maximum constraint force that can be exerted to move the candidate body. **/ public maxForce: number; /** * Constructor. **/ constructor(); } /** * A prismatic joint. This joint provides one degree of freedom: translation along an axis fixed in body1. Relative rotation is prevented. You can use a joint limit to restrict the range of motion and a joint motor to drive the motion or to model joint friction. **/ export class b2PrismaticJoint extends b2Joint { /** * Enable/disable the joint limit. * @param flag True to enable, false to disable. **/ public EnableLimit(flag: boolean): void; /** * Enable/disable the joint motor. * @param flag True to enable, false to disable. **/ public EnableMotor(flag: boolean): void; /** * Get the anchor point on bodyA in world coordinates. * @return Body A anchor. **/ public GetAnchorA(): b2Vec2; /** * Get the anchor point on bodyB in world coordinates. * @return Body B anchor. **/ public GetAnchorB(): b2Vec2; /** * Get the current joint translation speed, usually in meters per second. * @return Joint speed. **/ public GetJointSpeed(): number; /** * Get the current joint translation, usually in meters. * @return Joint translation. **/ public GetJointTranslation(): number; /** * Get the lower joint limit, usually in meters. * @return Lower limit. **/ public GetLowerLimit(): number; /** * Get the current motor force, usually in N. * @return Motor force. **/ public GetMotorForce(): number; /** * Get the motor speed, usually in meters per second. * @return Motor speed. **/ public GetMotorSpeed(): number; /** * Get the reaction force on body2 at the joint anchor in N. * @param inv_dt * @return Reaction force in N. **/ public GetReactionForce(inv_dt: number): b2Vec2; /** * Get the reaction torque on body 2 in N. * @param inv_dt * @return Reaction torque in N. **/ public GetReactionTorque(inv_dt: number): number; /** * Get the upper joint limit, usually in meters. * @return Upper limit. **/ public GetUpperLimit(): number; /** * Is the joint limit enabled? * @return True if enabled otherwise false. **/ public IsLimitEnabled(): boolean; /** * Is the joint motor enabled? * @return True if enabled, otherwise false. **/ public IsMotorEnabled(): boolean; /** * Set the joint limits, usually in meters. * @param lower Lower limit. * @param upper Upper limit. **/ public SetLimits(lower: number, upper: number): void; /** * Set the maximum motor force, usually in N. * @param force New max force. **/ public SetMaxMotorForce(force: number): void; /** * Set the motor speed, usually in meters per second. * @param speed New motor speed. **/ public SetMotorSpeed(speed: number): void; } /** * Prismatic joint definition. This requires defining a line of motion using an axis and an anchor point. The definition uses local anchor points and a local axis so that the initial configuration can violate the constraint slightly. The joint translation is zero when the local anchor points coincide in world space. Using local anchors and a local axis helps when saving and loading a game. **/ export class b2PrismaticJointDef extends b2JointDef { /** * Enable/disable the joint limit. **/ public enableLimit: boolean; /** * Enable/disable the joint motor. **/ public enableMotor: boolean; /** * The local anchor point relative to body1's origin. **/ public localAnchorA: b2Vec2; /** * The local anchor point relative to body2's origin. **/ public localAnchorB: b2Vec2; /** * The local translation axis in body1. **/ public localAxisA: b2Vec2; /** * The lower translation limit, usually in meters. **/ public lowerTranslation: number; /** * The maximum motor torque, usually in N-m. **/ public maxMotorForce: number; /** * The desired motor speed in radians per second. **/ public motorSpeed: number; /** * The constrained angle between the bodies: bodyB_angle - bodyA_angle. **/ public referenceAngle: number; /** * The upper translation limit, usually in meters. **/ public upperTranslation: number; /** * Constructor. **/ constructor(); /** * Initialize the joint. * @param bA Body A. * @param bB Body B. * @param anchor Anchor. * @param axis Axis. **/ public Initialize(bA: b2Body, bB: b2Body, anchor: b2Vec2, axis: b2Vec2): void; } /** * The pulley joint is connected to two bodies and two fixed ground points. The pulley supports a ratio such that: length1 + ratio length2 <= constant Yes, the force transmitted is scaled by the ratio. The pulley also enforces a maximum length limit on both sides. This is useful to prevent one side of the pulley hitting the top. **/ export class b2PullyJoint extends b2Joint { /** * Get the anchor point on bodyA in world coordinates. * @return Body A anchor. **/ public GetAnchorA(): b2Vec2; /** * Get the anchor point on bodyB in world coordinates. * @return Body B anchor. **/ public GetAnchorB(): b2Vec2; /** * Get the first ground anchor. **/ public GetGroundAnchorA(): b2Vec2; /** * Get the second ground anchor. **/ public GetGroundAnchorB(): b2Vec2; /** * Get the current length of the segment attached to body1. **/ public GetLength1(): number; /** * Get the current length of the segment attached to body2. **/ public GetLength2(): number; /** * Get the pulley ratio. **/ public GetRatio(): number; /** * Get the reaction force on body2 at the joint anchor in N. * @param inv_dt * @return Reaction force in N. **/ public GetReactionForce(inv_dt: number): b2Vec2; /** * Get the reaction torque on body 2 in N. * @param inv_dt * @return Reaction torque in N. **/ public GetReactionTorque(inv_dt: number): number; } /** * Pulley joint definition. This requires two ground anchors, two dynamic body anchor points, max lengths for each side, and a pulley ratio. **/ export class b2PullyJointDef extends b2JointDef { /** * The first ground anchor in world coordinates. This point never moves. **/ public groundAnchorA: b2Vec2; /** * The second ground anchor in world coordinates. This point never moves. **/ public groundAnchorB: b2Vec2; /** * The a reference length for the segment attached to bodyA. **/ public lengthA: number; /** * The a reference length for the segment attached to bodyB. **/ public lengthB: number; /** * The local anchor point relative to body1's origin. **/ public localAnchorA: b2Vec2; /** * The local anchor point relative to body2's origin. **/ public localAnchorB: b2Vec2; /** * The maximum length of the segment attached to bodyA. **/ public maxLengthA: number; /** * The maximum length of the segment attached to bodyB. **/ public maxLengthB: number; /** * The pulley ratio, used to simulate a block-and-tackle. **/ public ratio: number; /** * Constructor. **/ constructor(); /** * Initialize the bodies, anchors, and length using the world anchors. * @param bA Body A. * @param bB Body B. * @param gaA Ground anchor A. * @param gaB Ground anchor B. * @param anchorA Anchor A. * @param anchorB Anchor B. **/ public Initialize(bA: b2Body, bB: b2Body, gaA: b2Vec2, gaB: b2Vec2, anchorA: b2Vec2, anchorB: b2Vec2): void; } /** * A revolute joint constrains to bodies to share a common point while they are free to rotate about the point. The relative rotation about the shared point is the joint angle. You can limit the relative rotation with a joint limit that specifies a lower and upper angle. You can use a motor to drive the relative rotation about the shared point. A maximum motor torque is provided so that infinite forces are not generated. **/ export class b2RevoluteJoint extends b2Joint { /** * Enable/disable the joint limit. * @param flag True to enable, false to disable. **/ public EnableLimit(flag: boolean): void; /** * Enable/disable the joint motor. * @param flag True to enable, false to diasable. **/ public EnableMotor(flag: boolean): void; /** * Get the anchor point on bodyA in world coordinates. * @return Body A anchor. **/ public GetAnchorA(): b2Vec2; /** * Get the anchor point on bodyB in world coordinates. * @return Body B anchor. **/ public GetAnchorB(): b2Vec2; /** * Get the current joint angle in radians. * @return Joint angle. **/ public GetJointAngle(): number; /** * Get the current joint angle speed in radians per second. * @return Joint speed. **/ public GetJointSpeed(): number; /** * Get the lower joint limit in radians. * @return Lower limit. **/ public GetLowerLimit(): number; /** * Get the motor speed in radians per second. * @return Motor speed. **/ public GetMotorSpeed(): number; /** * Get the current motor torque, usually in N-m. * @return Motor torque. **/ public GetMotorTorque(): number; /** * Get the reaction force on body2 at the joint anchor in N. * @param inv_dt * @return Reaction force in N. **/ public GetReactionForce(inv_dt: number): b2Vec2; /** * Get the reaction torque on body 2 in N. * @param inv_dt * @return Reaction torque in N. **/ public GetReactionTorque(inv_dt: number): number; /** * Get the upper joint limit in radians. * @return Upper limit. **/ public GetUpperLimit(): number; /** * Is the joint limit enabled? * @return True if enabled, false if disabled. **/ public IsLimitEnabled(): boolean; /** * Is the joint motor enabled? * @return True if enabled, false if disabled. **/ public IsMotorEnabled(): boolean; /** * Set the joint limits in radians. * @param lower New lower limit. * @param upper New upper limit. **/ public SetLimits(lower: number, upper: number): void; /** * Set the maximum motor torque, usually in N-m. * @param torque New max torque. **/ public SetMaxMotorTorque(torque: number): void; /** * Set the motor speed in radians per second. * @param speed New motor speed. **/ public SetMotorSpeed(speed: number): void; } /** * Revolute joint definition. This requires defining an anchor point where the bodies are joined. The definition uses local anchor points so that the initial configuration can violate the constraint slightly. You also need to specify the initial relative angle for joint limits. This helps when saving and loading a game. The local anchor points are measured from the body's origin rather than the center of mass because: 1. you might not know where the center of mass will be. 2. if you add/remove shapes from a body and recompute the mass, the joints will be broken. **/ export class b2RevoluteJointDef extends b2JointDef { /** * A flag to enable joint limits. **/ public enableLimit: boolean; /** * A flag to enable the joint motor. **/ public enableMotor: boolean; /** * The local anchor point relative to body1's origin. **/ public localAnchorA: b2Vec2; /** * The local anchor point relative to body2's origin. **/ public localAnchorB: b2Vec2; /** * The lower angle for the joint limit (radians). **/ public lowerAngle: number; /** * The maximum motor torque used to achieve the desired motor speed. Usually in N-m. **/ public maxMotorTorque: number; /** * The desired motor speed. Usually in radians per second. **/ public motorSpeed: number; /** * The bodyB angle minus bodyA angle in the reference state (radians). **/ public referenceAngle: number; /** * The upper angle for the joint limit (radians). **/ public upperAngle: number; /** * Constructor. **/ constructor(); /** * Initialize the bodies, achors, and reference angle using the world anchor. * @param bA Body A. * @param bB Body B. * @param anchor Anchor. **/ public Initialize(bA: b2Body, bB: b2Body, anchor: b2Vec2): void; } /** * A weld joint essentially glues two bodies together. A weld joint may distort somewhat because the island constraint solver is approximate. **/ export class b2WeldJoint extends b2Joint { /** * Get the anchor point on bodyA in world coordinates. * @return Body A anchor. **/ public GetAnchorA(): b2Vec2; /** * Get the anchor point on bodyB in world coordinates. * @return Body B anchor. **/ public GetAnchorB(): b2Vec2; /** * Get the reaction force on body2 at the joint anchor in N. * @param inv_dt * @return Reaction force in N. **/ public GetReactionForce(inv_dt: number): b2Vec2; /** * Get the reaction torque on body 2 in N. * @param inv_dt * @return Reaction torque in N. **/ public GetReactionTorque(inv_dt: number): number; } /** * Weld joint definition. You need to specify local anchor points where they are attached and the relative body angle. The position of the anchor points is important for computing the reaction torque. **/ export class b2WeldJointDef extends b2JointDef { /** * The local anchor point relative to body1's origin. **/ public localAnchorA: b2Vec2; /** * The local anchor point relative to body2's origin. **/ public localAnchorB: b2Vec2; /** * The body2 angle minus body1 angle in the reference state (radians). **/ public referenceAngle: number; /** * Constructor. **/ constructor(); /** * Initialize the bodies, anchors, axis, and reference angle using the world anchor and world axis. * @param bA Body A. * @param bB Body B. * @param anchor Anchor. **/ public Initialize(bA: b2Body, bB: b2Body, anchor: b2Vec2): void; } }
{ "content_hash": "3db0b670006a827122250527ac4fde7c", "timestamp": "", "source": "github", "line_count": 5348, "max_line_length": 695, "avg_line_length": 26.041884816753928, "alnum_prop": 0.6774513182836464, "repo_name": "BrianMacIntosh/bmacSdk", "id": "d8a57c5e48f60a03afe5efcbbbd0d812c33e6f61", "size": "139272", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "thirdparty/box2d/index.d.ts", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "114" }, { "name": "JavaScript", "bytes": "145245" }, { "name": "TypeScript", "bytes": "110863" } ], "symlink_target": "" }
package org.apache.synapse.mediators.throttle; import org.apache.synapse.mediators.AbstractTestCase; /** * * */ public class ThrottleMediatorSerializationTest extends AbstractTestCase { ThrottleMediatorFactory throttleMediatorFactory; ThrottleMediatorSerializer throttleMediatorSerializer; public ThrottleMediatorSerializationTest() { throttleMediatorFactory = new ThrottleMediatorFactory(); throttleMediatorSerializer = new ThrottleMediatorSerializer(); } public void testThrottleMediatorSerializationSenarioOne() throws Exception { String inputXml = "<throttle id=\"A\" xmlns=\"http://ws.apache.org/ns/synapse\" >" + "<policy key=\"thottleKey\"/></throttle>"; assertTrue(serialization(inputXml, throttleMediatorFactory, throttleMediatorSerializer)); assertTrue(serialization(inputXml, throttleMediatorSerializer)); } }
{ "content_hash": "5b127558270dd46621f0f77cf48d5313", "timestamp": "", "source": "github", "line_count": 28, "max_line_length": 97, "avg_line_length": 32.57142857142857, "alnum_prop": 0.7467105263157895, "repo_name": "laki88/carbon-apimgt", "id": "637b69afe3d2bf8ae55fe49143f1f29aff883c63", "size": "1735", "binary": false, "copies": "8", "ref": "refs/heads/master", "path": "dependencies/synapse/modules/extensions/src/test/java/org/apache/synapse/mediators/throttle/ThrottleMediatorSerializationTest.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "ApacheConf", "bytes": "72417" }, { "name": "Batchfile", "bytes": "7251" }, { "name": "CSS", "bytes": "1696265" }, { "name": "HTML", "bytes": "343902" }, { "name": "Java", "bytes": "3655355" }, { "name": "JavaScript", "bytes": "14540961" }, { "name": "PLSQL", "bytes": "88321" }, { "name": "PLpgSQL", "bytes": "29272" }, { "name": "Shell", "bytes": "19726" }, { "name": "Thrift", "bytes": "1730" }, { "name": "XSLT", "bytes": "94760" } ], "symlink_target": "" }
// // NSString+Time.h // LXFCommonCode // // Created by 林洵锋 on 2017/3/2. // Copyright © 2017年 LXF. All rights reserved. // // GitHub: https://github.com/LinXunFeng // 简书: http://www.jianshu.com/users/31e85e7a22a2 #import <Foundation/Foundation.h> /** * 从时间戳转为显示时间 */ @interface NSString (Time) /** 通过时间戳计算时间差(几小时前、几天前) */ + (NSString *) compareCurrentTime:(NSTimeInterval) compareDate; /** 通过时间戳得出显示时间 */ + (NSString *) getDateStringWithTimestamp:(NSTimeInterval)timestamp; /** 通过时间戳和格式显示时间 */ + (NSString *) getStringWithTimestamp:(NSTimeInterval)timestamp formatter:(NSString*)formatter; @end
{ "content_hash": "8d81bf95efc381aaffcfce22cbc0e840", "timestamp": "", "source": "github", "line_count": 27, "max_line_length": 95, "avg_line_length": 22.59259259259259, "alnum_prop": 0.7114754098360656, "repo_name": "LinXunFeng/LXFCommonCode", "id": "14565233aad2b9215b3db809e8c15ea2883a37bd", "size": "729", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "LXFCommonCode/LXFCommonCode/CommonCode/Category/NSString/NSString+Time.h", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "413" }, { "name": "Objective-C", "bytes": "2154138" } ], "symlink_target": "" }
package com.amlinv.mbus.util; import javax.jms.JMSException; import javax.jms.Message; import javax.jms.TextMessage; public class MessageUtil { public static String formatMessage (Message msg) throws JMSException { if ( msg instanceof TextMessage ) { return "TEXT [" + ((TextMessage) msg).getText() + "]"; } return msg.toString(); } }
{ "content_hash": "3615d5e794b3f92d77f363b6e11532de", "timestamp": "", "source": "github", "line_count": 17, "max_line_length": 71, "avg_line_length": 20.647058823529413, "alnum_prop": 0.7150997150997151, "repo_name": "amlinv/amq-tools", "id": "358e9b71bd0f14c349cef05f06e4b16cb1526bce", "size": "1191", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/main/java/com/amlinv/mbus/util/MessageUtil.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "105035" }, { "name": "Shell", "bytes": "2941" } ], "symlink_target": "" }
namespace Krav { using System; using System.Diagnostics; /// <summary> /// Requirements for <see cref="T:Krav.Argument"/>s of <see cref="T:System.Guid"/> /// </summary> public static class GuidArgumentExtensions { /// <summary> /// Requires that the <paramref name="argument"/> is not the Empty Guid. Throws an exception /// if the requirement is not met. /// </summary> /// <param name="argument">The <see cref="T:Krav.Argument"/> to verify.</param> /// <returns>The verified <see cref="T:Krav.Argument"/>.</returns> /// <exception cref="T:System.ArgumentException">Thrown if the requirement is not met.</exception> [DebuggerStepThrough] public static Argument<Guid> IsNotEmpty(this Argument<Guid> argument) { if (Guid.Empty.Equals(argument.Value)) { throw ExceptionFactory.CreateArgumentException(argument, ExceptionMessages.Current.EmptyGuid); } return argument; } } }
{ "content_hash": "0161c22c5602ee8418fe7f648eb13311", "timestamp": "", "source": "github", "line_count": 29, "max_line_length": 110, "avg_line_length": 36.6551724137931, "alnum_prop": 0.6039510818438382, "repo_name": "pmacn/Krav", "id": "6c3108c72cb64bae10ee8afe46940121c80a0f15", "size": "1063", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/Krav/GuidArgumentExtensions.cs", "mode": "33188", "license": "mit", "language": [ { "name": "C#", "bytes": "91726" }, { "name": "F#", "bytes": "2640" }, { "name": "Shell", "bytes": "263" } ], "symlink_target": "" }
import FauxtonAPI from '../../core/api'; import replication from './route'; import './assets/less/replication.less'; import Actions from './actions'; replication.initialize = function () { FauxtonAPI.addHeaderLink({ title: 'Replication', href: '#/replication', icon: 'fonticon-replicate' }); FauxtonAPI.session.isAuthenticated().then(() => { Actions.checkForNewApi(); }); }; FauxtonAPI.registerUrls('replication', { app: (db) => { return '#/replication/_create/' + db; }, api: () => { return window.location.origin + '/_replicator'; } }); export default replication;
{ "content_hash": "9c70c427e5bdd685d8082efad8b199f2", "timestamp": "", "source": "github", "line_count": 22, "max_line_length": 104, "avg_line_length": 27.09090909090909, "alnum_prop": 0.662751677852349, "repo_name": "popojargo/couchdb-fauxton", "id": "54c8f85cbedc2f6a98caa7ae6b3fd3083e08af5c", "size": "1150", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "app/addons/replication/base.js", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "149307" }, { "name": "HTML", "bytes": "254979" }, { "name": "JavaScript", "bytes": "1525174" }, { "name": "Ruby", "bytes": "124" }, { "name": "Shell", "bytes": "3030" } ], "symlink_target": "" }
namespace gfx { class Rect; class Size; } namespace cc { class Layer; } namespace viz { class SurfaceId; } namespace content { class PictureInPictureWindowController; // This window will always float above other windows. The intention is to show // content perpetually while the user is still interacting with the other // browser windows. class OverlayWindow { public: enum PlaybackState { kPlaying = 0, kPaused, kEndOfVideo, }; OverlayWindow() = default; virtual ~OverlayWindow() = default; // Returns a created OverlayWindow. This is defined in the platform-specific // implementation for the class. static std::unique_ptr<OverlayWindow> Create( PictureInPictureWindowController* controller); virtual bool IsActive() = 0; virtual void Close() = 0; virtual void ShowInactive() = 0; virtual void Hide() = 0; virtual bool IsVisible() = 0; virtual bool IsAlwaysOnTop() = 0; // Retrieves the window's current bounds, including its window. virtual gfx::Rect GetBounds() = 0; virtual void UpdateVideoSize(const gfx::Size& natural_size) = 0; virtual void SetPlaybackState(PlaybackState playback_state) = 0; virtual void SetAlwaysHidePlayPauseButton(bool is_visible) = 0; virtual void SetSkipAdButtonVisibility(bool is_visible) = 0; virtual void SetNextTrackButtonVisibility(bool is_visible) = 0; virtual void SetPreviousTrackButtonVisibility(bool is_visible) = 0; virtual void SetSurfaceId(const viz::SurfaceId& surface_id) = 0; virtual cc::Layer* GetLayerForTesting() = 0; private: DISALLOW_COPY_AND_ASSIGN(OverlayWindow); }; } // namespace content #endif // CONTENT_PUBLIC_BROWSER_OVERLAY_WINDOW_H_
{ "content_hash": "8e03c91f265f030e8e49b8f4bb6b9472", "timestamp": "", "source": "github", "line_count": 60, "max_line_length": 78, "avg_line_length": 27.95, "alnum_prop": 0.7394156231365534, "repo_name": "endlessm/chromium-browser", "id": "361f8e10162ca154c1f0ee74d0fbf9f80f53cf2e", "size": "2027", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "content/public/browser/overlay_window.h", "mode": "33188", "license": "bsd-3-clause", "language": [], "symlink_target": "" }
package com.javarush.task.task23.task2309.vo; /** * Created by Alexey on 12.05.2017. */ public class Server extends NamedItem{ }
{ "content_hash": "03dca4bfe253eba3aa5ee3d7314c492b", "timestamp": "", "source": "github", "line_count": 7, "max_line_length": 45, "avg_line_length": 18.857142857142858, "alnum_prop": 0.7272727272727273, "repo_name": "avedensky/JavaRushTasks", "id": "9f3340fdd5af31ca260db3e5d37cb4ecf35c387f", "size": "132", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "3.JavaMultithreading/src/com/javarush/task/task23/task2309/vo/Server.java", "mode": "33188", "license": "mit", "language": [ { "name": "HTML", "bytes": "133687" }, { "name": "Java", "bytes": "1314718" } ], "symlink_target": "" }
> Tip : > In this article, if a term is vital to describing cameras in Gaffer, its first occurence will be highlighted in **bold**. The camera in Gaffer is designed to accommodate two related but sometimes divergent conceptions of a camera: the idealized "CG" cameras that we use in software, and the real cameras used in photography and cinematography. ![](images/illustrationCamerasRealCG.png "A real camera and CG camera") Fundamentally, current mainstream renderers use the CG camera model. However, many users are well-versed in the operating principles of real cameras, in particular the properties of aperture and focal length. Some DCC and scene format developers have made an effort to integrate these properties into their projects, to make camera construction easier for this audience. Gaffer does the same. Therefore, when using Gaffer, and in its scene data, a camera can be thought in terms of, and defined by, aperture and focal length. Cameras in Gaffer are also fully compatible with the Alembic and USD scene formats. Within a scene, a camera's properties are stored as special values known as **parameters**. ## Camera model ## ### Projection ### By default, Gaffer supports cameras with either perspective or orthographic projection. Perspective projection can be thought of as a horizontal and a vertical field of view that form a viewing frustum. Orthographic projection can be thought of as collimating light to create parallel projection lines. Three parameters determine camera projection: - **projection** - **aperture** - **focalLength** ```eval_rst .. figure:: images/illustrationPerspectiveOrthographic.png :scale: 100% :alt: Perspective and orthographic cameras in Gaffer **Figure 1.** The projection parameters of the two default camera types. ``` When the projection parameter is set to `perspective`, the angle of view can be controlled in the application by either the Field of View plug (as for a CG camera), or the Aperture and Focal Length plugs (as for a real camera). These latter two plugs replicate camera film back/sensor size, and lens focal length, respectively. When using these plugs, the user does not need to convert camera/lens projection into an angle, making it straightforward to replicate a real camera that was used in a shot. In the scene data, perspective is always stored as the aperture and focalLength parameters, even if the Field of View plug is used. When the projection parameter is set to `orthographic`, the size of the orthographic view is controlled by the Orthographic Aperture plug. In this mode, the corresponding aperture parameter defines the width and height of the film back/sensor, in world space units. Keep in mind that even though the scene describes projection with optical analogues, the result is still an approximation of a real camera. As with any CG camera, the implementation breaks with reality: - With perspective projection, the aperture and focalLength parameters are dimensionless – numbers without units of measure. They are interoperable with values that define equivalent horizontal and vertical fields of view. - As mentioned earlier, the term _aperture_ does not refer to an opening in a lens, but rather a rectangular region in 3D space that receives the image. It is, for practical purposes, equivalent to the film back/sensor. Since there is no lens, the image does not flip vertically before "hitting" this aperture. - Other than focal length, lenses are not truly accounted for, except for when adding depth of field blur to the final image. ### Aperture offset ### The **apertureOffset** parameter represents the amount by which the aperture is shifted parallel to the image plane. ```eval_rst .. figure:: images/illustrationApertureOffset.png :scale: 100% :alt: Aperture offset in Gaffer **Figure 2.** The aperture offset parameters, applicable to either projection type. ``` The scale of the offset depends on the projection. With perspective projection, the offset is proportional to the field of view (when the Field of View plug is used) or to the camera's unit of measure (e.g. millimeter; when the Aperture and Focal Length plugs are used). ### Depth of field blur ### Four parameters determine depth of field blur: - **focalDistance** - **fStop** - **focalLengthWorldScale** - focalLength In order to simulate depth of field blur, the camera needs a virtual opening: a circle in 3D space on a plane perpendicular to the camera's direction. In effect, this is a **lens aperture**. From this circle, Gaffer calculates the angle of incidence of light coming from objects at a distance greater or less than the focalDistance. The larger the circle, the stronger the depth of field blur. The smaller the circle, the weaker. ```eval_rst .. figure:: images/illustrationDepthOfField.png :scale: 100% :alt: Depth of field blur in Gaffer **Figure 3.** An approximation of depth of field blur in Gaffer. ``` > Important : > The term _lens aperture_ has a meaning near to its real-world counterpart – it really can be thought of as a round opening in space. The fStop and focalDistance parameters are identical to f-number and focus distance in real lenses. They allow easy replication of real lens settings. The third parameter, focalLengthWorldScale, sets the scale between the camera's unit of measure and the world space's unit of measure. Because the circle occupies 3D space, the circle must be measured in world space units. Complicating things is the fact that the world space units might not be measured in millimeters. The scene could use any scale – centimeter, meter, foot, kilometer, etc. Therefore, the scale factor between them must be defined. For depth of field, lens aperture is calculated with the formula: ``` lens aperture = (focalLength × focalLengthWorldScale) / fStop ``` For example, assume a lens with a focalLength of 50mm, an fStop of 4, and a world space measured in centimeters (default for Alembic/USD). First, we need to scale the focal length from mm to cm. Using a focalLengthWorldScale of 0.1 yields `50mm × 0.1 = 0.5cm`. This is the lens aperture at its widest. Dividing by the fStop of 4 results in the stopped-down lens aperture of `0.5cm / 4 = 0.125cm`. ## Cameras in the scene ## ### Camera data ### Within the [scene paradigm](../../../AnatomyOfAScene/index.html#scene-hierarchy), a camera, just like any other scene component, starts with a location in the scene hierarchy. To define a camera, the location must have the following data: - **Transform:** The vectors that define the position and orientation of the camera. - **Object:** A special camera object at the location. Instead of geometry, the object stores camera data, called parameters. - **Parameters:** The crucial values that define a camera, such as the perspective type, field of view/aperture, and depth of field settings. If defined, a special kind of optional parameter, called a **render override**, will supercede one of the scene's **[render options](../../../AnatomyOfAScene/index.html#options)** during computation and rendering.<br> ![](images/interfaceCameraParameters.png "Camera parameters in the Scene Inspector") - **Sets:** A list of sets the location belongs to. By default, every camera is assigned to an automatic "Cameras" set, accessible in the API by the `__cameras` variable.<br> ![](images/interfaceCameraSets.png "Camera sets in the Scene Inspector") ### Data flow ### Like geometry, cameras are represented as objects at locations in the scene hierarchy. To actually look through a camera (either in a Viewer, or during a render), Gaffer needs additional information, such as the resolution and film fit. This information is provided in the scene globals as render options, and combined with the camera's data at the point of use. Below is a description of this data flow, with a demonstration of how a camera can optionally override these render options. ```eval_rst .. figure:: images/illustrationCameraDataFlow.png :scale: 100% :alt: Camera data flow in a node graph **Figure 4.** The camera data flow through a node graph, with data passing between a Camera node, CameraTweaks node, and a StandardOptions node. ``` Each Camera node creates a camera, appearing in the scene hierarchy as its own location (by default called `/camera`). Each location will have its respective data. The locations and their data are passed to downstream scene nodes, like normal. A downstream CameraTweaks node can add, remove, modify, or replace parameters of one or more cameras in the scene. Standard camera parameters can be removed: strictly speaking, there are no mandatory camera parameters, as Gaffer will supply fallback defaults. The addition of parameters with custom names and values is supported. Camera and CameraTweaks nodes can add render overrides, which are a special kind of camera parameter. When a Viewer or a renderer looks through the camera, if a parameter has the same name as a render option, its value will take precedence over that option. An override can be added before its equivalent render option exists in the scene. At a later point in the graph, a StandardOptions node selects the camera to use, and defines the scene's render options. If the camera has any render overrides, their values will supercede those of their equivalent render options. Finally, all camera parameters and render options are passed to the renderer. All these data are used in combination by the renderer to calculate the image projection map, the image size, the motion blur, and the depth of field blur in the render. ## See also ## - [Camera](../Camera/index.md) - [Camera node reference](../../Reference/NodeReference/GafferScene/Camera.md) - [Anatomy of a Scene](../AnatomyOfAScene/index.md)
{ "content_hash": "91daf44a0d3765d513bf2887f14fbf94", "timestamp": "", "source": "github", "line_count": 136, "max_line_length": 633, "avg_line_length": 72.30882352941177, "alnum_prop": 0.7751677852348994, "repo_name": "lucienfostier/gaffer", "id": "974c7b136a74167089b1653875b9226b32b4a1cf", "size": "9867", "binary": false, "copies": "4", "ref": "refs/heads/master", "path": "doc/source/WorkingWithScenes/AnatomyOfACamera/index.md", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "C", "bytes": "41979" }, { "name": "C++", "bytes": "7610953" }, { "name": "CMake", "bytes": "85201" }, { "name": "GLSL", "bytes": "6236" }, { "name": "Python", "bytes": "7892655" }, { "name": "Shell", "bytes": "15031" } ], "symlink_target": "" }
// Copyright 2015 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. package org.chromium.chrome.browser.infobar; import android.text.SpannableString; import android.text.Spanned; import android.text.TextUtils; import android.text.style.ClickableSpan; import android.view.View; import org.chromium.base.annotations.CalledByNative; import org.chromium.chrome.browser.ResourceId; /** * The Save Password infobar offers the user the ability to save a password for the site. * Appearance and behaviour of infobar buttons depends on from where infobar was * triggered. */ public class SavePasswordInfoBar extends ConfirmInfoBar { private final int mTitleLinkRangeStart; private final int mTitleLinkRangeEnd; private final String mTitle; private final String mFirstRunExperienceMessage; @CalledByNative private static InfoBar show(int enumeratedIconId, String message, int titleLinkStart, int titleLinkEnd, String primaryButtonText, String secondaryButtonText, String firstRunExperienceMessage) { return new SavePasswordInfoBar(ResourceId.mapToDrawableId(enumeratedIconId), message, titleLinkStart, titleLinkEnd, primaryButtonText, secondaryButtonText, firstRunExperienceMessage); } private SavePasswordInfoBar(int iconDrawbleId, String message, int titleLinkStart, int titleLinkEnd, String primaryButtonText, String secondaryButtonText, String firstRunExperienceMessage) { super(iconDrawbleId, null, message, null, primaryButtonText, secondaryButtonText); mTitleLinkRangeStart = titleLinkStart; mTitleLinkRangeEnd = titleLinkEnd; mTitle = message; mFirstRunExperienceMessage = firstRunExperienceMessage; } @Override public void createContent(InfoBarLayout layout) { super.createContent(layout); if (mTitleLinkRangeStart != 0 && mTitleLinkRangeEnd != 0) { SpannableString title = new SpannableString(mTitle); title.setSpan(new ClickableSpan() { @Override public void onClick(View view) { onLinkClicked(); } }, mTitleLinkRangeStart, mTitleLinkRangeEnd, Spanned.SPAN_INCLUSIVE_INCLUSIVE); layout.setMessage(title); } if (!TextUtils.isEmpty(mFirstRunExperienceMessage)) { InfoBarControlLayout controlLayout = layout.addControlLayout(); controlLayout.addDescription(mFirstRunExperienceMessage); } } }
{ "content_hash": "afa9a66cacb7d41bf96da97d6af74044", "timestamp": "", "source": "github", "line_count": 65, "max_line_length": 93, "avg_line_length": 40.84615384615385, "alnum_prop": 0.7156308851224106, "repo_name": "ds-hwang/chromium-crosswalk", "id": "74bb57faef8eb3cc5ca7e047699644a60af3de55", "size": "2655", "binary": false, "copies": "10", "ref": "refs/heads/master", "path": "chrome/android/java/src/org/chromium/chrome/browser/infobar/SavePasswordInfoBar.java", "mode": "33188", "license": "bsd-3-clause", "language": [], "symlink_target": "" }
#include <linux/kernel.h> #include <linux/sched.h> #include <linux/kthread.h> #include <linux/wait.h> #include <linux/delay.h> #include <linux/mmc/core.h> #include <linux/mmc/host.h> #include <linux/mmc/card.h> #include <linux/mmc/sdio.h> #include <linux/mmc/sdio_func.h> #include "sdio_ops.h" static int process_sdio_pending_irqs(struct mmc_card *card) { int i, ret, count; unsigned char pending; struct sdio_func *func; /* * Optimization, if there is only 1 function interrupt registered * call irq handler directly */ func = card->sdio_single_irq; if (func) { func->irq_handler(func); return 1; } ret = mmc_io_rw_direct(card, 0, 0, SDIO_CCCR_INTx, 0, &pending); if (ret) { printk(KERN_DEBUG "%s: error %d reading SDIO_CCCR_INTx\n", mmc_card_id(card), ret); return ret; } count = 0; for (i = 1; i <= 7; i++) { if (pending & (1 << i)) { func = card->sdio_func[i - 1]; if (!func) { printk(KERN_WARNING "%s: pending IRQ for " "non-existent function\n", mmc_card_id(card)); ret = -EINVAL; } else if (func->irq_handler) { func->irq_handler(func); count++; } else { printk(KERN_WARNING "%s: pending IRQ with no handler\n", sdio_func_id(func)); ret = -EINVAL; } } } if (count) return count; return ret; } static int sdio_irq_thread(void *_host) { struct mmc_host *host = _host; struct sched_param param = { .sched_priority = 1 }; unsigned long period, idle_period; int ret; sched_setscheduler(current, SCHED_FIFO, &param); /* * We want to allow for SDIO cards to work even on non SDIO * aware hosts. One thing that non SDIO host cannot do is * asynchronous notification of pending SDIO card interrupts * hence we poll for them in that case. */ idle_period = msecs_to_jiffies(10); period = (host->caps & MMC_CAP_SDIO_IRQ) ? MAX_SCHEDULE_TIMEOUT : idle_period; pr_debug("%s: IRQ thread started (poll period = %lu jiffies)\n", mmc_hostname(host), period); do { /* * We claim the host here on drivers behalf for a couple * reasons: * * 1) it is already needed to retrieve the CCCR_INTx; * 2) we want the driver(s) to clear the IRQ condition ASAP; * 3) we need to control the abort condition locally. * * Just like traditional hard IRQ handlers, we expect SDIO * IRQ handlers to be quick and to the point, so that the * holding of the host lock does not cover too much work * that doesn't require that lock to be held. */ ret = __mmc_claim_host(host, &host->sdio_irq_thread_abort); if (ret) break; ret = process_sdio_pending_irqs(host->card); mmc_release_host(host); /* * Give other threads a chance to run in the presence of * errors. */ if (ret < 0) { set_current_state(TASK_INTERRUPTIBLE); if (!kthread_should_stop()) schedule_timeout(HZ); set_current_state(TASK_RUNNING); } /* * Adaptive polling frequency based on the assumption * that an interrupt will be closely followed by more. * This has a substantial benefit for network devices. */ if (!(host->caps & MMC_CAP_SDIO_IRQ)) { if (ret > 0) period /= 2; else { period++; if (period > idle_period) period = idle_period; } } set_current_state(TASK_INTERRUPTIBLE); if (host->caps & MMC_CAP_SDIO_IRQ) host->ops->enable_sdio_irq(host, 1); if (!kthread_should_stop()) schedule_timeout(period); set_current_state(TASK_RUNNING); } while (!kthread_should_stop()); if (host->caps & MMC_CAP_SDIO_IRQ) host->ops->enable_sdio_irq(host, 0); pr_debug("%s: IRQ thread exiting with code %d\n", mmc_hostname(host), ret); return ret; } static int sdio_card_irq_get(struct mmc_card *card) { struct mmc_host *host = card->host; WARN_ON(!host->claimed); if (!host->sdio_irqs++) { atomic_set(&host->sdio_irq_thread_abort, 0); host->sdio_irq_thread = kthread_run(sdio_irq_thread, host, "ksdioirqd/%s", mmc_hostname(host)); if (IS_ERR(host->sdio_irq_thread)) { int err = PTR_ERR(host->sdio_irq_thread); host->sdio_irqs--; return err; } } return 0; } static int sdio_card_irq_put(struct mmc_card *card) { struct mmc_host *host = card->host; WARN_ON(!host->claimed); BUG_ON(host->sdio_irqs < 1); if (!--host->sdio_irqs) { atomic_set(&host->sdio_irq_thread_abort, 1); kthread_stop(host->sdio_irq_thread); } return 0; } /* If there is only 1 function registered set sdio_single_irq */ static void sdio_single_irq_set(struct mmc_card *card) { struct sdio_func *func; int i; card->sdio_single_irq = NULL; if ((card->host->caps & MMC_CAP_SDIO_IRQ) && card->host->sdio_irqs == 1) for (i = 0; i < card->sdio_funcs; i++) { func = card->sdio_func[i]; if (func && func->irq_handler) { card->sdio_single_irq = func; break; } } } /** * sdio_claim_irq - claim the IRQ for a SDIO function * @func: SDIO function * @handler: IRQ handler callback * * Claim and activate the IRQ for the given SDIO function. The provided * handler will be called when that IRQ is asserted. The host is always * claimed already when the handler is called so the handler must not * call sdio_claim_host() nor sdio_release_host(). */ int sdio_claim_irq(struct sdio_func *func, sdio_irq_handler_t *handler) { int ret; unsigned char reg; BUG_ON(!func); BUG_ON(!func->card); pr_debug("SDIO: Enabling IRQ for %s...\n", sdio_func_id(func)); if (func->irq_handler) { pr_debug("SDIO: IRQ for %s already in use.\n", sdio_func_id(func)); return -EBUSY; } ret = mmc_io_rw_direct(func->card, 0, 0, SDIO_CCCR_IENx, 0, &reg); if (ret) return ret; reg |= 1 << func->num; reg |= 1; /* Master interrupt enable */ ret = mmc_io_rw_direct(func->card, 1, 0, SDIO_CCCR_IENx, reg, NULL); if (ret) return ret; func->irq_handler = handler; ret = sdio_card_irq_get(func->card); if (ret) func->irq_handler = NULL; sdio_single_irq_set(func->card); return ret; } EXPORT_SYMBOL_GPL(sdio_claim_irq); /** * sdio_release_irq - release the IRQ for a SDIO function * @func: SDIO function * * Disable and release the IRQ for the given SDIO function. */ int sdio_release_irq(struct sdio_func *func) { int ret; unsigned char reg; BUG_ON(!func); BUG_ON(!func->card); pr_debug("SDIO: Disabling IRQ for %s...\n", sdio_func_id(func)); if (func->irq_handler) { func->irq_handler = NULL; sdio_card_irq_put(func->card); sdio_single_irq_set(func->card); } ret = mmc_io_rw_direct(func->card, 0, 0, SDIO_CCCR_IENx, 0, &reg); if (ret) return ret; reg &= ~(1 << func->num); /* Disable master interrupt with the last function interrupt */ if (!(reg & 0xFE)) reg = 0; ret = mmc_io_rw_direct(func->card, 1, 0, SDIO_CCCR_IENx, reg, NULL); if (ret) return ret; return 0; } EXPORT_SYMBOL_GPL(sdio_release_irq);
{ "content_hash": "cf7a003facc78c25cbfa39e32e869271", "timestamp": "", "source": "github", "line_count": 291, "max_line_length": 72, "avg_line_length": 23.50171821305842, "alnum_prop": 0.6400058488083054, "repo_name": "sahdman/rpi_android_kernel", "id": "03ead028d2ce147ac9a33387814b040ec1e91e53", "size": "7276", "binary": false, "copies": "796", "ref": "refs/heads/master", "path": "linux-3.1.9/drivers/mmc/core/sdio_irq.c", "mode": "33188", "license": "mit", "language": [], "symlink_target": "" }
using Cubic2dGrids = ::testing::Types<YASP_2D_EQUIDISTANT_OFFSET #if HAVE_DUNE_ALUGRID , ALU_2D_CUBE #endif #if HAVE_DUNE_UGGRID , UG_2D #endif >; template <class G> using InterpolationTest = Dune::GDT::Test::DefaultInterpolationOnLeafViewTest<G>; TYPED_TEST_SUITE(InterpolationTest, Cubic2dGrids); TYPED_TEST(InterpolationTest, interpolates_correctly) { this->interpolates_correctly(4e-14); }
{ "content_hash": "21b28fcc17c6ac8b93e4b4af042e8e7a", "timestamp": "", "source": "github", "line_count": 19, "max_line_length": 81, "avg_line_length": 30.94736842105263, "alnum_prop": 0.5255102040816326, "repo_name": "pymor/dune-gdt", "id": "6272528a7aabaa3d42e524c4e5c38ce7389bf342", "size": "1197", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "dune/gdt/test/interpolations/interpolations_default__cubic_2d_grids.cc", "mode": "33188", "license": "bsd-2-clause", "language": [ { "name": "C++", "bytes": "1214423" }, { "name": "CMake", "bytes": "10605" } ], "symlink_target": "" }
struct Bullet : public entityx::Component<Bullet> { Bullet(); Bullet(entityx::Entity::Id _ownerId, double _lifeTime, long _damage); entityx::Entity::Id ownerId; double lifeTime; double age; double producedHeat; long damage; }; #endif // BULLET_H
{ "content_hash": "fc1b1d453ad7be6d1a8aaed38f21a675", "timestamp": "", "source": "github", "line_count": 20, "max_line_length": 49, "avg_line_length": 14.7, "alnum_prop": 0.6224489795918368, "repo_name": "TransNeptunianStudios/Triangulum", "id": "7adc13e4ac7d9fe83373cbfba8d060b4f9ca76c6", "size": "358", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "include/components/Bullet.h", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "2943" }, { "name": "C++", "bytes": "136664" }, { "name": "Objective-C++", "bytes": "1895" } ], "symlink_target": "" }
**Type:** Distributed **Requires CredSSP:** No This resource is responsible for configuring the Diagnostics Provider within the local SharePoint farm. Using Ensure equals to Absent is not supported. This resource can only apply configuration, not ensure they don't exist.
{ "content_hash": "4061c815997fdadfde92027e6a74b8f7", "timestamp": "", "source": "github", "line_count": 6, "max_line_length": 76, "avg_line_length": 45.5, "alnum_prop": 0.8021978021978022, "repo_name": "MikeLacher448/xSharePoint", "id": "3bc2cbd30ec14192f45ff7ccfafbb04f53e9f14f", "size": "288", "binary": false, "copies": "2", "ref": "refs/heads/dev", "path": "Modules/SharePointDsc/DSCResources/MSFT_SPDiagnosticsProvider/readme.md", "mode": "33188", "license": "mit", "language": [ { "name": "C#", "bytes": "13147308" }, { "name": "JavaScript", "bytes": "788" }, { "name": "PowerShell", "bytes": "5135277" } ], "symlink_target": "" }
/**************************************************************************//** * @file efm32wg_lesense_buf.h * @brief EFM32WG_LESENSE_BUF register and bit field definitions * @version 5.1.2 ****************************************************************************** * @section License * <b>Copyright 2017 Silicon Laboratories, Inc. http://www.silabs.com</b> ****************************************************************************** * * Permission is granted to anyone to use this software for any purpose, * including commercial applications, and to alter it and redistribute it * freely, subject to the following restrictions: * * 1. The origin of this software must not be misrepresented; you must not * claim that you wrote the original software.@n * 2. Altered source versions must be plainly marked as such, and must not be * misrepresented as being the original software.@n * 3. This notice may not be removed or altered from any source distribution. * * DISCLAIMER OF WARRANTY/LIMITATION OF REMEDIES: Silicon Laboratories, Inc. * has no obligation to support this Software. Silicon Laboratories, Inc. is * providing the Software "AS IS", with no express or implied warranties of any * kind, including, but not limited to, any implied warranties of * merchantability or fitness for any particular purpose or warranties against * infringement of any proprietary rights of a third party. * * Silicon Laboratories, Inc. will not be liable for any consequential, * incidental, or special damages, or any other relief, or for any claim by * any third party, arising from your use of this Software. * *****************************************************************************/ /**************************************************************************//** * @addtogroup Parts * @{ ******************************************************************************/ /**************************************************************************//** * @brief LESENSE_BUF EFM32WG LESENSE BUF *****************************************************************************/ typedef struct { __IOM uint32_t DATA; /**< Scan results */ } LESENSE_BUF_TypeDef; /** @} End of group Parts */
{ "content_hash": "da6ffc3722a65dfa5e89dc2ca5e907c3", "timestamp": "", "source": "github", "line_count": 46, "max_line_length": 79, "avg_line_length": 49.45652173913044, "alnum_prop": 0.5195604395604395, "repo_name": "zephyriot/zephyr", "id": "2c8ddf33b010675e1cf879ed209d36c850a2b43a", "size": "2275", "binary": false, "copies": "5", "ref": "refs/heads/master", "path": "ext/hal/silabs/gecko/Device/SiliconLabs/EFM32WG/Include/efm32wg_lesense_buf.h", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Assembly", "bytes": "403733" }, { "name": "Batchfile", "bytes": "209" }, { "name": "C", "bytes": "269965416" }, { "name": "C++", "bytes": "2684580" }, { "name": "CMake", "bytes": "398770" }, { "name": "Makefile", "bytes": "2793" }, { "name": "Objective-C", "bytes": "33385" }, { "name": "Perl", "bytes": "202119" }, { "name": "Python", "bytes": "723350" }, { "name": "Shell", "bytes": "22632" }, { "name": "Verilog", "bytes": "6394" } ], "symlink_target": "" }
namespace nuPickers.PropertyEditors.XmlTypeaheadListPicker { using nuPickers.EmbeddedResource; using Umbraco.Core.PropertyEditors; internal class XmlTypeaheadListPickerPreValueEditor : PreValueEditor { [PreValueField("dataSource", "", EmbeddedResource.ROOT_URL + "XmlDataSource/XmlDataSourceConfig.html", HideLabel = true)] public string DataSource { get; set; } [PreValueField("customLabel", "Label Macro", EmbeddedResource.ROOT_URL + "CustomLabel/CustomLabelConfig.html", HideLabel = true)] public string CustomLabel { get; set; } [PreValueField("typeaheadListPicker", "", EmbeddedResource.ROOT_URL + "TypeaheadListPicker/TypeaheadListPickerConfig.html", HideLabel = true)] public string TypeaheadListPicker { get; set; } [PreValueField("listPicker", "", EmbeddedResource.ROOT_URL + "ListPicker/ListPickerConfig.html", HideLabel = true)] public string ListPicker { get; set; } [PreValueField("relationMapping", "", EmbeddedResource.ROOT_URL + "RelationMapping/RelationMappingConfig.html", HideLabel = true)] public string RelationMapping { get; set; } [PreValueField("saveFormat", "Save Format", EmbeddedResource.ROOT_URL + "SaveFormat/SaveFormatConfig.html")] public string SaveFormat { get; set; } } }
{ "content_hash": "c9bb19ecc850c109fc8d1e26a72a575c", "timestamp": "", "source": "github", "line_count": 26, "max_line_length": 150, "avg_line_length": 51.11538461538461, "alnum_prop": 0.7178329571106095, "repo_name": "uComponents/nuPickers", "id": "b9bb447c7698197273842bf3b2f57b1740357324", "size": "1331", "binary": false, "copies": "1", "ref": "refs/heads/develop", "path": "source/nuPickers/PropertyEditors/XmlTypeaheadListPicker/XmlTypeaheadListPickerPreValueEditor.cs", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "1737" }, { "name": "C#", "bytes": "308605" }, { "name": "CSS", "bytes": "6325" }, { "name": "HTML", "bytes": "25301" }, { "name": "JavaScript", "bytes": "42539" }, { "name": "PowerShell", "bytes": "2820" } ], "symlink_target": "" }
[![SensioLabsInsight](https://insight.sensiolabs.com/projects/b5fc2c5b-f3b9-4a5a-b2b0-15c7ddd1aa7b/big.png)](https://insight.sensiolabs.com/projects/b5fc2c5b-f3b9-4a5a-b2b0-15c7ddd1aa7b) [![Build Status](https://api.travis-ci.org/xtress/UncleemptyMaintenanceBundle.svg)](https://travis-ci.org/xtress/UncleemptyMaintenanceBundle)
{ "content_hash": "b679332f0b8084a1fe0907e161495901", "timestamp": "", "source": "github", "line_count": 4, "max_line_length": 186, "avg_line_length": 82.75, "alnum_prop": 0.8096676737160121, "repo_name": "xtress/UncleemptyMaintenanceBundle", "id": "cbb5da31def391cccc148c17afd395b5533270b6", "size": "364", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "README.md", "mode": "33188", "license": "mit", "language": [ { "name": "HTML", "bytes": "20" }, { "name": "PHP", "bytes": "14260" } ], "symlink_target": "" }
title: About permalink: "/about/" excerpt: Find out more about Brightly Colored. layout: page --- _Brightly Colored_ is designed and developed by me, [Tim Smith](http://ttimsmith.com), in beautiful [St. Paul, Minnesota](https://www.stpaul.gov/). This publication covers a whole range of things including, but not limited to: design, development, technology, Geek culture, and Apple. <figure class="extendout"> {% include imgic.html src="/tim-02-16x9.jpg" alt="Tim Smith's Photo" %} <figcaption>Photo by <a href="https://www.jaimielaurenphoto.com/">Jaimie Lauren</a>.</figcaption> </figure> Just as a person goes through different phases of life, so has this site. There have been periods where I write a lot about a particular topic, then move on to another. There was also a time when I wasn't the only one to write here, which you can learn more about below. The constant, however, has always been me. Most of _Brightly Colored_ is a reflection of my life, my personal growth, my successes, and my sorrows. ## Why "Brightly Colored"? I felt the name _Brightly Colored_ matched my personality. You'll typically find me wearing bright and vibrant things like yellow shorts, bright-patterned socks, and red shoes. ## About Tim Writing about yourself is tough, but here we go. I live in Saint Paul, MN with my beautiful and amazing wife, Kelly. We have two cats: Izzy and Minnie. I'm very opinionated and picky about certain things, but I strive to lace kindness and empathy into everything I do. I've messed up a lot in life, but as Yoda once said, "The greatest teacher, failure is." Some of the failures have been painful—both to me and others. I've always tried to take responsibility for it and learn. I started my adventure into design and development in 2006 when I was fifteen. I took some community college classes, but I'm mostly self-taught. My early career was tough—no one took me seriously as soon as I told them how old I was. Since then, I've had the chance to work with some pretty amazing people. Some of those amazing people work for companies like [Relay FM](https://www.relay.fm/), [Carbon Ads](https://carbonads.net/), [&Yet](https://andyet.com/), [Lullabot](https://www.lullabot.com/), [Crush & Lovely](http://crushlovely.com/), and The Clinton Foundation. In 2018, I decided I no longer wanted to work as a designer and developer for the web and became the Senior Producer for [Changelog Media](https://changelog.com/). I now make audio and video things for a living, and I love it. I originally started this site thinking I'd be the next [John Gruber](https://en.wikipedia.org/wiki/John_Gruber), but quickly realized I didn't actually want that (not to mention, I'm not nearly as great a writer). Ever since this fantastic place is where I write about all that interests me. ## Contact Send me an email anytime. I love getting an email from actual people. If you have a product you'd like me to review, feel free to reach out. - Email: [[email protected]](mailto:[email protected]?subject=[brightlycolored.org] Hey Tim!) - Follow me on Micro.blog: [@smith](https://micro.blog/smith) - Follow me on [Flickr](https://www.flickr.com/photos/smithtimmytim/) - Follow me on Twitter: [@smithtimmytim](https://twitter.com/smithtimmytim) ## How It's Made ### Hardware - 2018 15" MacBook Pro with Touch Bar - Apple iPad Pro 10.5" - Apple iPhone XS Max ### Software - [Siteleaf](https://www.siteleaf.com/) - [Visual Studio Code](https://code.visualstudio.com/) - [Adobe Lightroom Classic CC](https://www.adobe.com/products/photoshop-lightroom-classic.html) - [VSCO](https://itunes.apple.com/app/vsco-cam/id588013838?ls=1&mt=8) ### Camera - [Sony α7 III](https://amzn.to/2QSa7GG) ### Lenses - [Sigma 18-35mm ƒ/1.8](http://amzn.to/2DlWGYu) - [Sony FE 24-70mm ƒ/2.8 GM](https://amzn.to/2xBLPZy) - [Sony FE 50mm ƒ/1.8](https://amzn.to/2NCmYyP) - [Sony FE 85mm ƒ/1.8](https://amzn.to/2I9zNLf) The site is hosted by [Netlify](https://www.netlify.com/), and powered by [Jekyll](http://jekyllrb.com). Type is set in Whitney and Operator by [Hoefler & Co.](https://www.typography.com/) A huge thanks to the friends who've contributed to this site: [TJ Draper](/authors/tjdraper) and [Keaton Taylor](/authors/keatontaylor). Also thanks to [Sonya Mann](https://twitter.com/sonyaellenmann) for editing a few articles here and there, making me sound much better. Of course, a huge thank you to my partner in crime, [Kelly Smith](/authors/kellysmith), who reads drafts and sometimes writes herself. ## Affiliate Links Some of the links on this site are affiliate links. When you use them, _Brightly Colored_ gets a small commission for what you buy at no cost to you. Thank you for your support of _Brightly Colored_.
{ "content_hash": "ba34fae4ee08e7692130372088578282", "timestamp": "", "source": "github", "line_count": 78, "max_line_length": 418, "avg_line_length": 60.94871794871795, "alnum_prop": 0.7458981909970551, "repo_name": "smithtimmytim/brightlycolored.org", "id": "913c2addef1987298b5b7c85d102fe3af292d651", "size": "4767", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "about.md", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "41991" }, { "name": "HTML", "bytes": "69363" }, { "name": "JavaScript", "bytes": "6430" }, { "name": "Ruby", "bytes": "3694" } ], "symlink_target": "" }
from __future__ import absolute_import from zerver.lib.actions import check_send_message from zerver.lib.response import json_success from zerver.decorator import REQ, has_request_variables, api_key_only_webhook_view import pprint import ujson from typing import Dict, Any PAGER_DUTY_EVENT_NAMES = { 'incident.trigger': 'triggered', 'incident.acknowledge': 'acknowledged', 'incident.unacknowledge': 'unacknowledged', 'incident.resolve': 'resolved', 'incident.assign': 'assigned', 'incident.escalate': 'escalated', 'incident.delegate': 'delineated', } def build_pagerduty_formatdict(message): # Normalize the message dict, after this all keys will exist. I would # rather some strange looking messages than dropping pages. format_dict = {} # type: Dict[str, Any] format_dict['action'] = PAGER_DUTY_EVENT_NAMES[message['type']] format_dict['incident_id'] = message['data']['incident']['id'] format_dict['incident_num'] = message['data']['incident']['incident_number'] format_dict['incident_url'] = message['data']['incident']['html_url'] format_dict['service_name'] = message['data']['incident']['service']['name'] format_dict['service_url'] = message['data']['incident']['service']['html_url'] # This key can be missing on null if message['data']['incident'].get('assigned_to_user', None): format_dict['assigned_to_email'] = message['data']['incident']['assigned_to_user']['email'] format_dict['assigned_to_username'] = message['data']['incident']['assigned_to_user']['email'].split('@')[0] format_dict['assigned_to_url'] = message['data']['incident']['assigned_to_user']['html_url'] else: format_dict['assigned_to_email'] = 'nobody' format_dict['assigned_to_username'] = 'nobody' format_dict['assigned_to_url'] = '' # This key can be missing on null if message['data']['incident'].get('resolved_by_user', None): format_dict['resolved_by_email'] = message['data']['incident']['resolved_by_user']['email'] format_dict['resolved_by_username'] = message['data']['incident']['resolved_by_user']['email'].split('@')[0] format_dict['resolved_by_url'] = message['data']['incident']['resolved_by_user']['html_url'] else: format_dict['resolved_by_email'] = 'nobody' format_dict['resolved_by_username'] = 'nobody' format_dict['resolved_by_url'] = '' trigger_message = [] trigger_subject = message['data']['incident']['trigger_summary_data'].get('subject', '') if trigger_subject: trigger_message.append(trigger_subject) trigger_description = message['data']['incident']['trigger_summary_data'].get('description', '') if trigger_description: trigger_message.append(trigger_description) format_dict['trigger_message'] = u'\n'.join(trigger_message) return format_dict def send_raw_pagerduty_json(user_profile, client, stream, message, topic): subject = topic or 'pagerduty' body = ( u'Unknown pagerduty message\n' u'``` py\n' u'%s\n' u'```') % (pprint.pformat(message),) check_send_message(user_profile, client, 'stream', [stream], subject, body) def send_formated_pagerduty(user_profile, client, stream, message_type, format_dict, topic): if message_type in ('incident.trigger', 'incident.unacknowledge'): template = (u':imp: Incident ' u'[{incident_num}]({incident_url}) {action} by ' u'[{service_name}]({service_url}) and assigned to ' u'[{assigned_to_username}@]({assigned_to_url})\n\n>{trigger_message}') elif message_type == 'incident.resolve' and format_dict['resolved_by_url']: template = (u':grinning: Incident ' u'[{incident_num}]({incident_url}) resolved by ' u'[{resolved_by_username}@]({resolved_by_url})\n\n>{trigger_message}') elif message_type == 'incident.resolve' and not format_dict['resolved_by_url']: template = (u':grinning: Incident ' u'[{incident_num}]({incident_url}) resolved\n\n>{trigger_message}') else: template = (u':no_good: Incident [{incident_num}]({incident_url}) ' u'{action} by [{assigned_to_username}@]({assigned_to_url})\n\n>{trigger_message}') subject = topic or u'incident {incident_num}'.format(**format_dict) body = template.format(**format_dict) check_send_message(user_profile, client, 'stream', [stream], subject, body) @api_key_only_webhook_view('PagerDuty') @has_request_variables def api_pagerduty_webhook(request, user_profile, client, payload=REQ(argument_type='body'), stream=REQ(default='pagerduty'), topic=REQ(default=None)): for message in payload['messages']: message_type = message['type'] if message_type not in PAGER_DUTY_EVENT_NAMES: send_raw_pagerduty_json(user_profile, client, stream, message, topic) try: format_dict = build_pagerduty_formatdict(message) except: send_raw_pagerduty_json(user_profile, client, stream, message, topic) else: send_formated_pagerduty(user_profile, client, stream, message_type, format_dict, topic) return json_success()
{ "content_hash": "7703ff5477dc5f95588136dee2239dd5", "timestamp": "", "source": "github", "line_count": 119, "max_line_length": 116, "avg_line_length": 44.33613445378151, "alnum_prop": 0.6432903714935557, "repo_name": "peiwei/zulip", "id": "ad33a8c1b9b8b8beecbfb668fd01e324795e4e6f", "size": "5314", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "zerver/views/webhooks/pagerduty.py", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "164" }, { "name": "CSS", "bytes": "183830" }, { "name": "CoffeeScript", "bytes": "18435" }, { "name": "Groovy", "bytes": "5516" }, { "name": "HTML", "bytes": "397966" }, { "name": "JavaScript", "bytes": "1588795" }, { "name": "Nginx", "bytes": "1228" }, { "name": "PHP", "bytes": "18930" }, { "name": "Pascal", "bytes": "1113" }, { "name": "Perl", "bytes": "383634" }, { "name": "Puppet", "bytes": "96085" }, { "name": "Python", "bytes": "2010761" }, { "name": "Ruby", "bytes": "255867" }, { "name": "Shell", "bytes": "33341" } ], "symlink_target": "" }
/** * */ package com.browseengine.bobo.search.section; import java.io.IOException; /** * UNARY-NOT operator node * (this node is not supported by SectionSearchQueryPlan) */ public class UnaryNotNode extends SectionSearchQueryPlan { private SectionSearchQueryPlan _subquery; public UnaryNotNode(SectionSearchQueryPlan subquery) { super(); _subquery = subquery; } public SectionSearchQueryPlan getSubquery() { return _subquery; } @Override public int fetchDoc(int targetDoc) throws IOException { throw new UnsupportedOperationException("UnaryNotNode does not support fetchDoc"); } @Override public int fetchSec(int targetSec) throws IOException { throw new UnsupportedOperationException("UnaryNotNode does not support fetchSec"); } }
{ "content_hash": "1548d705ad69a457585fcbe334042bf4", "timestamp": "", "source": "github", "line_count": 33, "max_line_length": 86, "avg_line_length": 23.818181818181817, "alnum_prop": 0.7493638676844784, "repo_name": "javasoze/bobo", "id": "05f92686b39fb9b22261aa915339156d437df1ef", "size": "786", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "bobo-browse/src/main/java/com/browseengine/bobo/search/section/UnaryNotNode.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "992125" } ], "symlink_target": "" }
const assert = require('assert'); describe('Array', function () { describe('#indexOf()', function () { it('should return -1 when the value is not present', function () { assert.equal(-1, [1, 2, 3].indexOf(4)); }); }); });
{ "content_hash": "493bccda99014c2b590d9aece97532df", "timestamp": "", "source": "github", "line_count": 9, "max_line_length": 70, "avg_line_length": 26.77777777777778, "alnum_prop": 0.5726141078838174, "repo_name": "opensource-cards/binary-ui-auth", "id": "66fb322761d00c251c58061f7c497a08f6c34da1", "size": "241", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "test/test.js", "mode": "33188", "license": "mit", "language": [ { "name": "HTML", "bytes": "110" }, { "name": "JavaScript", "bytes": "56674" } ], "symlink_target": "" }
package com.flipkart.connekt.busybees.xmpp import java.util.concurrent.ConcurrentLinkedQueue import java.util.concurrent.atomic.AtomicInteger import akka.actor.{ActorRef, ActorSystem, Terminated, _} import akka.stream.FanOutShape2 import akka.stream.stage.GraphStageLogic.StageActor import akka.stream.stage.{GraphStageLogic, InHandler, OutHandler} import com.flipkart.connekt.busybees.models.GCMRequestTracker import com.flipkart.connekt.busybees.xmpp.Internal.FreeConnectionAvailable import com.flipkart.connekt.busybees.xmpp.XmppConnectionActor.PendingUpstreamMessage import com.flipkart.connekt.commons.factories.{ConnektLogger, LogFile} import com.flipkart.connekt.commons.iomodels.{FCMXmppRequest, XmppDownstreamResponse, XmppUpstreamResponse} import com.flipkart.connekt.commons.services.ConnektConfig import scala.collection.JavaConverters._ import scala.util.{Failure, Success, Try} private[busybees] class XMPPStageLogic(val shape: FanOutShape2[(FCMXmppRequest, GCMRequestTracker), (Try[XmppDownstreamResponse], GCMRequestTracker), XmppUpstreamResponse])(implicit actorSystem: ActorSystem) extends GraphStageLogic(shape) { var self: StageActor = _ private def outDownstream = shape.out0 private def outUpstream = shape.out1 implicit val executionContext = actorSystem.dispatcher type DownStreamResponse = (Try[XmppDownstreamResponse], GCMRequestTracker) private val maxStageBufferCount = ConnektConfig.getInt("fcm.xmpp.stageBuffer").getOrElse(10) private val inFlightRequestCount = new AtomicInteger(0) private val downstreamBuffer: ConcurrentLinkedQueue[DownStreamResponse] = new ConcurrentLinkedQueue[DownStreamResponse]() /** * This is discardable during shutdown, google will send back all messages which aren't acked yet */ private val pendingUpstreamMessages: scala.collection.mutable.Queue[PendingUpstreamMessage] = collection.mutable.Queue[PendingUpstreamMessage]() private var xmppGateway: XMPPGateway = _ override def preStart(): Unit = { super.preStart() ConnektLogger(LogFile.CLIENTS).trace("XMPPStageLogic: IN preStart") self = getStageActor { case (_, message: PendingUpstreamMessage) => //ConnektLogger(LogFile.CLIENTS).trace(s"XMPPStageLogic: Inbound Message: PendingUpstreamMessage : $message") if (isAvailable(outUpstream)) _pushUpstream(message) else pendingUpstreamMessages.enqueue(message) case (_, FreeConnectionAvailable) => ConnektLogger(LogFile.CLIENTS).trace("XMPPStageLogic: Inbound Message: FreeConnectionAvailable") if (!hasBeenPulled(shape.in)) pull(shape.in) //Auto Back-pressured by this. case (_, message: DownStreamResponse) => //ConnektLogger(LogFile.CLIENTS).trace(s"XMPPStageLogic: Inbound Message: DownStreamResponse: $message") if (isAvailable(outDownstream)) push(outDownstream, message) else downstreamBuffer.add(message) case (_, Terminated(ref)) => ConnektLogger(LogFile.CLIENTS).error(s"XMPPStageLogic: Inbound Message: Terminated: $ref") failStage(new Exception("XMPP Router terminated : " + ref)) } xmppGateway = new XMPPGateway(self)(actorSystem) } override def postStop(): Unit = { ConnektLogger(LogFile.CLIENTS).trace("XMPPStageLogic: IN postStop") } setHandler(shape.in, new InHandler { override def onPush(): Unit = { val requestPair: (FCMXmppRequest, GCMRequestTracker) = grab(shape.in) ConnektLogger(LogFile.CLIENTS).trace(s"XMPPStageLogic: IN InHandler $requestPair") inFlightRequestCount.incrementAndGet() xmppGateway(new XmppOutStreamRequest(requestPair)).andThen { case _ => inFlightRequestCount.decrementAndGet() }.onComplete(result => self.ref ! Tuple2(result, requestPair._2)) /** * Why bound with inFlightRequestCount ? * When the application starts up or say the there is issue with XMPP Connections and there are nothing in buffer * this pull(in) will cause to trigger unbounded input port pull and fill up the buffer of XMPPRouter RequestQueue * finally causing OOM, or in any-case loosing the message. Hence back-pressuring in that case. */ if ((downstreamBuffer.size + inFlightRequestCount.get()) < maxStageBufferCount) pull(shape.in) } override def onUpstreamFinish(): Unit = { ConnektLogger(LogFile.CLIENTS).trace("GcmXmppDispatcher: upstream finished :shutting down") xmppGateway.shutdown() ConnektLogger(LogFile.CLIENTS).trace("GcmXmppDispatcher :upstream finished :downstreamcount: " + downstreamBuffer.size()) emitMultiple[DownStreamResponse](outDownstream, downstreamBuffer.iterator.asScala, () => { ConnektLogger(LogFile.CLIENTS).trace("GcmXmppDispatcher :emitted all: " + downstreamBuffer.size()) completeStage() //Mark stage as completed when the emit current buffer completes. }) ConnektLogger(LogFile.CLIENTS).trace("GcmXmppDispatcher :shutdown complete") } }) //downstream act setHandler(outDownstream, new OutHandler { override def onPull(): Unit = { if (!downstreamBuffer.isEmpty) { push(outDownstream, downstreamBuffer.poll()) } if (!hasBeenPulled(shape.in)){ ConnektLogger(LogFile.CLIENTS).trace("GcmXmppDispatcher :outDownstream PULL") pull(shape.in) //TODO : This should have a check that there are free routess } } }) //upstream setHandler(outUpstream, new OutHandler { override def onPull(): Unit = { if (pendingUpstreamMessages.nonEmpty) { val upstreamMessage = pendingUpstreamMessages.dequeue() _pushUpstream(upstreamMessage) } } }) private def _pushUpstream(upstreamMessage:PendingUpstreamMessage): Unit ={ upstreamMessage.actTo ! upstreamMessage.message push(outUpstream, upstreamMessage.message) } }
{ "content_hash": "92e0549f8bccf84f7cb56b9272c2f69a", "timestamp": "", "source": "github", "line_count": 141, "max_line_length": 240, "avg_line_length": 42.07801418439716, "alnum_prop": 0.7379066239676386, "repo_name": "Flipkart/connekt", "id": "509667763c42472914e842f87e3eeb2c633e7993", "size": "6541", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "busybees/src/main/scala/com/flipkart/connekt/busybees/xmpp/XMPPStageLogic.scala", "mode": "33188", "license": "mit", "language": [ { "name": "Java", "bytes": "27427" }, { "name": "Scala", "bytes": "1414084" }, { "name": "Shell", "bytes": "12148" } ], "symlink_target": "" }
package org.spongycastle.asn1; import java.io.IOException; import org.spongycastle.util.Arrays; import org.spongycastle.util.Strings; /** * DER VisibleString object encoding ISO 646 (ASCII) character code points 32 to 126. * <p> * Explicit character set escape sequences are not allowed. * </p> */ public class DERVisibleString extends ASN1Primitive implements ASN1String { private byte[] string; /** * Return a Visible String from the passed in object. * * @param obj a DERVisibleString or an object that can be converted into one. * @exception IllegalArgumentException if the object cannot be converted. * @return a DERVisibleString instance, or null */ public static DERVisibleString getInstance( Object obj) { if (obj == null || obj instanceof DERVisibleString) { return (DERVisibleString)obj; } if (obj instanceof byte[]) { try { return (DERVisibleString)fromByteArray((byte[])obj); } catch (Exception e) { throw new IllegalArgumentException("encoding error in getInstance: " + e.toString()); } } throw new IllegalArgumentException("illegal object in getInstance: " + obj.getClass().getName()); } /** * Return a Visible String from a tagged object. * * @param obj the tagged object holding the object we want * @param explicit true if the object is meant to be explicitly * tagged false otherwise. * @exception IllegalArgumentException if the tagged object cannot * be converted. * @return a DERVisibleString instance, or null */ public static DERVisibleString getInstance( ASN1TaggedObject obj, boolean explicit) { ASN1Primitive o = obj.getObject(); if (explicit || o instanceof DERVisibleString) { return getInstance(o); } else { return new DERVisibleString(ASN1OctetString.getInstance(o).getOctets()); } } /** * Basic constructor - byte encoded string. */ DERVisibleString( byte[] string) { this.string = string; } /** * Basic constructor */ public DERVisibleString( String string) { this.string = Strings.toByteArray(string); } public String getString() { return Strings.fromByteArray(string); } public String toString() { return getString(); } public byte[] getOctets() { return Arrays.clone(string); } boolean isConstructed() { return false; } int encodedLength() { return 1 + StreamUtil.calculateBodyLength(string.length) + string.length; } void encode( ASN1OutputStream out) throws IOException { out.writeEncoded(BERTags.VISIBLE_STRING, this.string); } boolean asn1Equals( ASN1Primitive o) { if (!(o instanceof DERVisibleString)) { return false; } return Arrays.areEqual(string, ((DERVisibleString)o).string); } public int hashCode() { return Arrays.hashCode(string); } }
{ "content_hash": "6af99c0fbd8fb2f5e76879f8e3c3a471", "timestamp": "", "source": "github", "line_count": 141, "max_line_length": 105, "avg_line_length": 23.81560283687943, "alnum_prop": 0.5863609291244789, "repo_name": "savichris/spongycastle", "id": "b44ddb79c211a531150e50a4b7bf18d3f7d17740", "size": "3358", "binary": false, "copies": "5", "ref": "refs/heads/spongy-master", "path": "core/src/main/java/org/spongycastle/asn1/DERVisibleString.java", "mode": "33188", "license": "mit", "language": [ { "name": "HTML", "bytes": "54207" }, { "name": "Java", "bytes": "22605685" }, { "name": "Shell", "bytes": "74632" } ], "symlink_target": "" }
SYNONYM #### According to The Catalogue of Life, 3rd January 2011 #### Published in null #### Original name null ### Remarks null
{ "content_hash": "910c601944fa66ca4ef8bf28ddfbfb3e", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 39, "avg_line_length": 10.23076923076923, "alnum_prop": 0.6917293233082706, "repo_name": "mdoering/backbone", "id": "ba4f5e1ab0715585e2d2a0ed9c975b3f5ba163da", "size": "201", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "life/Plantae/Magnoliophyta/Liliopsida/Poales/Cyperaceae/Capitularina/Capitularina involucrata/ Syn. Chorizandra involucrata/README.md", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
from django.conf.urls import include, url from django.contrib import admin urlpatterns = [ # Examples: # url(r'^$', 'aboyunapp.views.home', name='home'), # url(r'^blog/', include('blog.urls')), url(r'^admin/', include(admin.site.urls)), ]
{ "content_hash": "258624370627307113bd7ef5e36da35d", "timestamp": "", "source": "github", "line_count": 10, "max_line_length": 54, "avg_line_length": 25.7, "alnum_prop": 0.6342412451361867, "repo_name": "markessien/aboyun", "id": "f924c5d64fed4730fdbef0dc5b9b91b43d9a4867", "size": "257", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "aboyunapp/urls.py", "mode": "33188", "license": "mit", "language": [ { "name": "Python", "bytes": "6796" } ], "symlink_target": "" }
class Picture < ActiveRecord::Base has_attached_file :picture, styles: { medium: "300x300>", thumb: "100x100>" }, default_url: "/images/:style/missing.png" validates_attachment_content_type :picture, content_type: /\Aimage\/.*\Z/ belongs_to :work end
{ "content_hash": "6ec14b40c353da1a48f3c17ca17b580b", "timestamp": "", "source": "github", "line_count": 6, "max_line_length": 122, "avg_line_length": 43, "alnum_prop": 0.7093023255813954, "repo_name": "arseniy96/foreman_site", "id": "215c18ab9b0aeb13a0c1d122bc7b2814692d5e19", "size": "258", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "app/models/picture.rb", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "5105" }, { "name": "CoffeeScript", "bytes": "873" }, { "name": "HTML", "bytes": "10212" }, { "name": "JavaScript", "bytes": "1935" }, { "name": "Ruby", "bytes": "69869" } ], "symlink_target": "" }
require 'chef/provider' require 'chef/resource' require 'poise_application_ruby/service_mixin' module PoiseApplicationRuby module Resources # (see Unicorn::Resource) # @since 4.0.0 module Unicorn # An `application_unicorn` resource to manage a unicorn web application # server. # # @since 4.0.0 # @provides application_unicorn # @action enable # @action disable # @action start # @action stop # @action restart # @action reload # @example # application '/srv/myapp' do # git '...' # bundle_install # unicorn do # port 8080 # end # end class Resource < Chef::Resource include PoiseApplicationRuby::ServiceMixin provides(:application_unicorn) # @!attribute port # Port to bind to. attribute(:port, kind_of: [String, Integer], default: 80) end # Provider for `application_unicorn`. # # @since 4.0.0 # @see Resource # @provides application_unicorn class Provider < Chef::Provider include PoiseApplicationRuby::ServiceMixin provides(:application_unicorn) private # Find the path to the config.ru. If the resource path was to a # directory, apparent /config.ru. # # @return [String] def configru_path @configru_path ||= if ::File.directory?(new_resource.path) ::File.join(new_resource.path, 'config.ru') else new_resource.path end end # Set service resource options. def service_options(resource) super resource.ruby_command("unicorn --port #{new_resource.port} #{configru_path}") end end end end end
{ "content_hash": "db37cefce6fc71f2e4d72667d6efb8df", "timestamp": "", "source": "github", "line_count": 71, "max_line_length": 87, "avg_line_length": 25.760563380281692, "alnum_prop": 0.5724439584472389, "repo_name": "poise/application_ruby", "id": "0728b51b4bbc7c9726830153b6df8277b2f5f857", "size": "2415", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "lib/poise_application_ruby/resources/unicorn.rb", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "HTML", "bytes": "287" }, { "name": "Ruby", "bytes": "53843" } ], "symlink_target": "" }
<!-- saved from url=(0014)about:internet --><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN"> <html> <!-- Standard Head Part --> <head> <title>NUnit - VsTestAdapterReleaseNotes</title> <meta http-equiv="Content-Type" content="text/html; charset=windows-1252"> <meta http-equiv="Content-Language" content="en-US"> <meta name="norton-safeweb-site-verification" content="tb6xj01p4hgo5x-8wscsmq633y11-e6nhk-bnb5d987bseanyp6p0uew-pec8j963qlzj32k5x9h3r2q7wh-vmy8bbhek5lnpp5w4p8hocouuq39e09jrkihdtaeknua" /> <link rel="stylesheet" type="text/css" href="nunit.css"> <link rel="shortcut icon" href="favicon.ico"> </head> <!-- End Standard Head Part --> <body> <!-- Standard Header for NUnit.org --> <div id="header"> <a id="logo" href="http://www.nunit.org"><img src="img/logo.gif" alt="NUnit.org" title="NUnit.org"></a> <div id="nav"> <a href="http://www.nunit.org">NUnit</a> <a class="active" href="index.html">Documentation</a> </div> </div> <!-- End of Header --> <div id="content"> <style><!-- li { padding-bottom: .5em; } ul ul li { padding-bottom: 0; } dt { font-weight: bold } --></style> <h3>NUnit Test Adapter for Visual Studio (Beta 4) - Version 0.94 - December 22, 2012</h3> <h4>Features</h4> <ul> <li>Works with Visual Studio 2012 Update 1 as well as the RTM. <li>Supports filtering and sorting tests by Traits under Update 1. <li>Supports use of standard filter expressions when running under TFS Update 1. <li>NUnit Categories specified on the fixture class are now recognized and honored. </ul> <h4>Bug Fixes</h4> <ul> <li>1074891 Can't test multiple assemblies referencing different NUnit versions <li>1075893 Test execution fails if solution contains native C++ project <li>1076012 No source information found for async test methods <li>1087629 TestFixture Category not being recognised as traits in VS2012 update 1 <li>1091020 Adapter doesnt support TFS Build traits/test case filtering </ul> <h3>NUnit Test Adapter for Visual Studio (Beta 3-2) - Version 0.93.2 - November 2, 2012</h3> <h4>Bug Fixes</h4> <ul> <li>1074544 Failures in Test Discovery not reporting sufficient information </ul> <h3>NUnit Test Adapter for Visual Studio (Beta 3-1) - Version 0.93.1 - October 26, 2012</h3> <h4>Bug Fixes</h4> <ul> <li>1072150 NUnit adapter 0.93 won't run selected tests </ul> <h3>NUnit Test Adapter for Visual Studio (Beta 3) - Version 0.93 - October 24, 2012</h3> <h4>Features</h4> <ul> <li>Works with Visual Studio 2012 RTM. Some features require the November CTP update. <li>The adapter now uses NUnit 2.6.2. Among other things, this allows us to support async test methods. See the NUnit <a href="releaseNotes.html">Release Notes</a> for more info. <li>Source file and line number can now be found for test cases that have an alternate name set. <li>Console output from tests is now displayed in the Visual Studio Output window. <li>TestFixtureSetUp and TestFixtureTearDown errors are now displayed in the Output window. <li>The caret line (------^) is no longer displayed in the IDE since it depends on use of a fixed font. <li>Tests may now be grouped and filtered by Category (only under the November CTP update for VS2012). </ul> <h4>Bug Fixes</h4> <ul> <li>1021144 Text output from tests not displayed in Visual Studio IDE <li>1033623 Not possible to include or exclude tests based on [Category] attribute Released <li>1040779 Null reference exception on generic test fixtures <li>1064620 Support async test methods <li>1065209 Should call both RecordEnd and RecordResult at end of a test <li>1065212 Upgrade NUnit to 2.6.2 <li>1065223 Error messages assume a fixed font, but don't get one <li>1065225 No display for TestFixtureSetUp/TearDown or SetUpFixture errors <li>1065254 Cannot open test from Test Explorer for tests in a Parameterized Test Fixture <li>1065306 Generic Fixtures aren't discovered. <li>1066393 Unable to display source for testcases with an alternate name set <li>1066518 Executed fast test appears in Not Run category in Test Explorer </ul> <h3>NUnit Test Adapter for Visual Studio (Beta 2) - Version 0.92 - May 3, 2012 <h4>Features</h4> <ul> <li>Works with Visual Studio 2012 Release Candidate <li>Uses NUnit 2.6 </ul> <h4>Bug Fixes</h4> <ul> <li>992837 Unable to Debug using VS Test Adapter <li>994146 Can't run tests under .NET 2.0/3.5 </ul> <h3>NUnit Test Adapter for Visual Studio (Beta 1) - Version 0.91 - February 29, 2012 <h4>Features</h4> <ul> <li>Built against Visual Studio 11 Beta 1 <li>Uses NUnit 2.6 </ul> <h3>NUnit Test Adapter for Visual Studio (Alpha) - Version 0.90 - February 21, 2012 <h4>Features</h4> <ul> <li>First release of the test adapter. Compatible with the Visual Studio 11 Developer Preview. <li>Uses NUnit 2.6. </ul> </div> <!-- Submenu --> <div id="subnav"> <ul> <li><a href="index.html">NUnit 2.6.3</a></li> <ul> <li><a href="getStarted.html">Getting&nbsp;Started</a></li> <li><a href="writingTests.html">Writing&nbsp;Tests</a></li> <li><a href="runningTests.html">Running&nbsp;Tests</a></li> <li><a href="extensibility.html">Extensibility</a></li> <li><a href="releaseNotes.html">Release&nbsp;Notes</a></li> <li><a href="samples.html">Samples</a></li> <li><a href="license.html">License</a></li> </ul> <li><a href="vsTestAdapter.html">NUnit&nbsp;Test&nbsp;Adapter</a></li> <ul> <li><a href="vsTestAdapterLicense.html">License</a></li> <li id="current"><a href="vsTestAdapterReleaseNotes.html">Release&nbsp;Notes</a></li> </ul> <li><a href="&r=2.6.3.html"></a></li> <li><a href="&r=2.6.3.html"></a></li> </ul> </div> <!-- End of Submenu --> <!-- Standard Footer for NUnit.org --> <div id="footer"> Copyright &copy; 2012 Charlie Poole. All Rights Reserved. </div> <!-- End of Footer --> </body> </html>
{ "content_hash": "f9aa991036b84dd5085e96810a769a70", "timestamp": "", "source": "github", "line_count": 171, "max_line_length": 187, "avg_line_length": 34.24561403508772, "alnum_prop": 0.7069672131147541, "repo_name": "google-code-export/elmah-loganalyzer", "id": "14dc14d63e5e05da255003d4f0ea5d67d33a8fe5", "size": "5856", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "tools/NUnit-2.6.3/doc/vsTestAdapterReleaseNotes.html", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C#", "bytes": "367057" }, { "name": "HTML", "bytes": "1856" }, { "name": "Shell", "bytes": "117" } ], "symlink_target": "" }
/* * 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. */ package io.prestosql.plugin.hive.metastore.alluxio; import alluxio.ClientContext; import alluxio.client.table.RetryHandlingTableMasterClient; import alluxio.client.table.TableMasterClient; import alluxio.conf.InstancedConfiguration; import alluxio.conf.PropertyKey; import alluxio.master.MasterClientContext; import alluxio.util.ConfigurationUtils; import com.google.inject.Binder; import com.google.inject.Provides; import com.google.inject.Scopes; import io.airlift.configuration.AbstractConfigurationAwareModule; import io.prestosql.plugin.hive.metastore.HiveMetastore; import static io.airlift.configuration.ConfigBinder.configBinder; import static org.weakref.jmx.guice.ExportBinder.newExporter; /** * Module for an Alluxio metastore implementation of the {@link HiveMetastore} interface. */ public class AlluxioMetastoreModule extends AbstractConfigurationAwareModule { @Override protected void setup(Binder binder) { configBinder(binder).bindConfig(AlluxioHiveMetastoreConfig.class); binder.bind(HiveMetastore.class).to(AlluxioHiveMetastore.class).in(Scopes.SINGLETON); newExporter(binder).export(HiveMetastore.class).as(generator -> generator.generatedNameOf(AlluxioHiveMetastore.class)); } @Provides public TableMasterClient provideCatalogMasterClient(AlluxioHiveMetastoreConfig config) { return createCatalogMasterClient(config); } public static TableMasterClient createCatalogMasterClient(AlluxioHiveMetastoreConfig config) { InstancedConfiguration conf = new InstancedConfiguration(ConfigurationUtils.defaults()); String addr = config.getMasterAddress(); String[] parts = addr.split(":", 2); conf.set(PropertyKey.MASTER_HOSTNAME, parts[0]); if (parts.length > 1) { conf.set(PropertyKey.MASTER_RPC_PORT, parts[1]); } MasterClientContext context = MasterClientContext .newBuilder(ClientContext.create(conf)).build(); return new RetryHandlingTableMasterClient(context); } }
{ "content_hash": "183c2a359dcd3cef610442bfd65f9762", "timestamp": "", "source": "github", "line_count": 66, "max_line_length": 127, "avg_line_length": 39.833333333333336, "alnum_prop": 0.7599847850893876, "repo_name": "treasure-data/presto", "id": "add4e4b877643f9b8c2981a253464b64210b3e65", "size": "2629", "binary": false, "copies": "4", "ref": "refs/heads/master", "path": "presto-hive/src/main/java/io/prestosql/plugin/hive/metastore/alluxio/AlluxioMetastoreModule.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "ANTLR", "bytes": "30916" }, { "name": "CSS", "bytes": "17830" }, { "name": "Dockerfile", "bytes": "1490" }, { "name": "Groovy", "bytes": "1547" }, { "name": "HTML", "bytes": "24210" }, { "name": "Java", "bytes": "42427369" }, { "name": "JavaScript", "bytes": "219883" }, { "name": "PLSQL", "bytes": "85" }, { "name": "Python", "bytes": "9315" }, { "name": "Ruby", "bytes": "4592" }, { "name": "Shell", "bytes": "33906" }, { "name": "Thrift", "bytes": "12598" } ], "symlink_target": "" }
from __future__ import (unicode_literals, division, absolute_import, print_function) from powerline.lib.watcher import create_file_watcher def list_segment_key_values(segment, theme_configs, segment_data, key, function_name=None, name=None, module=None, default=None): try: yield segment[key] except KeyError: pass found_module_key = False for theme_config in theme_configs: try: segment_data = theme_config['segment_data'] except KeyError: pass else: if function_name and not name: if module: try: yield segment_data[module + '.' + function_name][key] found_module_key = True except KeyError: pass if not found_module_key: try: yield segment_data[function_name][key] except KeyError: pass if name: try: yield segment_data[name][key] except KeyError: pass if segment_data is not None: try: yield segment_data[key] except KeyError: pass yield default def get_segment_key(merge, *args, **kwargs): if merge: ret = None for value in list_segment_key_values(*args, **kwargs): if ret is None: ret = value elif isinstance(ret, dict) and isinstance(value, dict): old_ret = ret ret = value.copy() ret.update(old_ret) else: return ret return ret else: return next(list_segment_key_values(*args, **kwargs)) def get_function(data, segment): function_name = segment['function'] if '.' in function_name: module, function_name = function_name.rpartition('.')[::2] else: module = data['default_module'] function = data['get_module_attr'](module, function_name, prefix='segment_generator') if not function: raise ImportError('Failed to obtain segment function') return None, function, module, function_name, segment.get('name') def get_string(data, segment): name = segment.get('name') return data['get_key'](False, segment, None, None, name, 'contents'), None, None, None, name segment_getters = { 'function': get_function, 'string': get_string, 'segment_list': get_function, } def get_attr_func(contents_func, key, args, is_space_func=False): try: func = getattr(contents_func, key) except AttributeError: return None else: if is_space_func: def expand_func(pl, amount, segment): try: return func(pl=pl, amount=amount, segment=segment, **args) except Exception as e: pl.exception('Exception while computing {0} function: {1}', key, str(e)) return segment['contents'] + (' ' * amount) return expand_func else: return lambda pl, shutdown_event: func(pl=pl, shutdown_event=shutdown_event, **args) def process_segment_lister(pl, segment_info, parsed_segments, side, mode, colorscheme, lister, subsegments, patcher_args): subsegments = [ subsegment for subsegment in subsegments if subsegment['display_condition'](pl, segment_info, mode) ] for subsegment_info, subsegment_update in lister(pl=pl, segment_info=segment_info, **patcher_args): draw_inner_divider = subsegment_update.pop('draw_inner_divider', False) old_pslen = len(parsed_segments) for subsegment in subsegments: if subsegment_update: subsegment = subsegment.copy() subsegment.update(subsegment_update) if 'priority_multiplier' in subsegment_update and subsegment['priority']: subsegment['priority'] *= subsegment_update['priority_multiplier'] process_segment( pl, side, subsegment_info, parsed_segments, subsegment, mode, colorscheme, ) new_pslen = len(parsed_segments) while parsed_segments[new_pslen - 1]['literal_contents'][1]: new_pslen -= 1 if new_pslen > old_pslen + 1 and draw_inner_divider is not None: for i in range(old_pslen, new_pslen - 1) if side == 'left' else range(old_pslen + 1, new_pslen): parsed_segments[i]['draw_soft_divider'] = draw_inner_divider return None def set_segment_highlighting(pl, colorscheme, segment, mode): if segment['literal_contents'][1]: return True try: highlight_group_prefix = segment['highlight_group_prefix'] except KeyError: hl_groups = lambda hlgs: hlgs else: hl_groups = lambda hlgs: [highlight_group_prefix + ':' + hlg for hlg in hlgs] + hlgs try: segment['highlight'] = colorscheme.get_highlighting( hl_groups(segment['highlight_groups']), mode, segment.get('gradient_level') ) if segment['divider_highlight_group']: segment['divider_highlight'] = colorscheme.get_highlighting( hl_groups([segment['divider_highlight_group']]), mode ) else: segment['divider_highlight'] = None except Exception as e: pl.exception('Failed to set highlight group: {0}', str(e)) return False else: return True def process_segment(pl, side, segment_info, parsed_segments, segment, mode, colorscheme): segment = segment.copy() pl.prefix = segment['name'] if segment['type'] in ('function', 'segment_list'): try: if segment['type'] == 'function': contents = segment['contents_func'](pl, segment_info) else: contents = segment['contents_func'](pl, segment_info, parsed_segments, side, mode, colorscheme) except Exception as e: pl.exception('Exception while computing segment: {0}', str(e)) return if contents is None: return if isinstance(contents, list): # Needs copying here, but it was performed at the very start of the # function segment_base = segment if contents: draw_divider_position = -1 if side == 'left' else 0 for key, i, newval in ( ('before', 0, ''), ('after', -1, ''), ('draw_soft_divider', draw_divider_position, True), ('draw_hard_divider', draw_divider_position, True), ): try: contents[i][key] = segment_base.pop(key) segment_base[key] = newval except KeyError: pass draw_inner_divider = None if side == 'right': append = parsed_segments.append else: pslen = len(parsed_segments) append = lambda item: parsed_segments.insert(pslen, item) for subsegment in (contents if side == 'right' else reversed(contents)): segment_copy = segment_base.copy() segment_copy.update(subsegment) if draw_inner_divider is not None: segment_copy['draw_soft_divider'] = draw_inner_divider draw_inner_divider = segment_copy.pop('draw_inner_divider', None) if set_segment_highlighting(pl, colorscheme, segment_copy, mode): append(segment_copy) else: segment['contents'] = contents if set_segment_highlighting(pl, colorscheme, segment, mode): parsed_segments.append(segment) elif segment['width'] == 'auto' or (segment['type'] == 'string' and segment['contents'] is not None): if set_segment_highlighting(pl, colorscheme, segment, mode): parsed_segments.append(segment) always_true = lambda pl, segment_info, mode: True get_fallback_segment = { 'name': 'fallback', 'type': 'string', 'highlight_groups': ['background'], 'divider_highlight_group': None, 'before': None, 'after': None, 'contents': '', 'literal_contents': (0, ''), 'priority': None, 'draw_soft_divider': True, 'draw_hard_divider': True, 'draw_inner_divider': True, 'display_condition': always_true, 'width': None, 'align': None, 'expand': None, 'truncate': None, 'startup': None, 'shutdown': None, '_rendered_raw': '', '_rendered_hl': '', '_len': None, '_contents_len': None, }.copy def gen_segment_getter(pl, ext, common_config, theme_configs, default_module, get_module_attr, top_theme): data = { 'default_module': default_module or 'powerline.segments.' + ext, 'get_module_attr': get_module_attr, 'segment_data': None, } def get_key(merge, segment, module, function_name, name, key, default=None): return get_segment_key(merge, segment, theme_configs, data['segment_data'], key, function_name, name, module, default) data['get_key'] = get_key def get_selector(function_name): if '.' in function_name: module, function_name = function_name.rpartition('.')[::2] else: module = 'powerline.selectors.' + ext function = get_module_attr(module, function_name, prefix='segment_generator/selector_function') if not function: pl.error('Failed to get segment selector, ignoring it') return function def get_segment_selector(segment, selector_type): try: function_name = segment[selector_type + '_function'] except KeyError: function = None else: function = get_selector(function_name) try: modes = segment[selector_type + '_modes'] except KeyError: modes = None if modes: if function: return lambda pl, segment_info, mode: ( mode in modes or function(pl=pl, segment_info=segment_info, mode=mode) ) else: return lambda pl, segment_info, mode: mode in modes else: if function: return lambda pl, segment_info, mode: ( function(pl=pl, segment_info=segment_info, mode=mode) ) else: return None def gen_display_condition(segment): include_function = get_segment_selector(segment, 'include') exclude_function = get_segment_selector(segment, 'exclude') if include_function: if exclude_function: return lambda *args: ( include_function(*args) and not exclude_function(*args)) else: return include_function else: if exclude_function: return lambda *args: not exclude_function(*args) else: return always_true def get(segment, side): segment_type = segment.get('type', 'function') try: get_segment_info = segment_getters[segment_type] except KeyError: pl.error('Unknown segment type: {0}', segment_type) return None try: contents, _contents_func, module, function_name, name = get_segment_info(data, segment) except Exception as e: pl.exception('Failed to generate segment from {0!r}: {1}', segment, str(e), prefix='segment_generator') return None if not get_key(False, segment, module, function_name, name, 'display', True): return None segment_datas = getattr(_contents_func, 'powerline_segment_datas', None) if segment_datas: try: data['segment_data'] = segment_datas[top_theme] except KeyError: pass if segment_type == 'function': highlight_groups = [function_name] else: highlight_groups = segment.get('highlight_groups') or [name] if segment_type in ('function', 'segment_list'): args = dict(( (str(k), v) for k, v in get_key(True, segment, module, function_name, name, 'args', {}).items() )) display_condition = gen_display_condition(segment) if segment_type == 'segment_list': # Handle startup and shutdown of _contents_func? subsegments = [ subsegment for subsegment in ( get(subsegment, side) for subsegment in segment['segments'] ) if subsegment ] return { 'name': name or function_name, 'type': segment_type, 'highlight_groups': None, 'divider_highlight_group': None, 'before': None, 'after': None, 'contents_func': lambda pl, segment_info, parsed_segments, side, mode, colorscheme: ( process_segment_lister( pl, segment_info, parsed_segments, side, mode, colorscheme, patcher_args=args, subsegments=subsegments, lister=_contents_func, ) ), 'contents': None, 'literal_contents': None, 'priority': None, 'draw_soft_divider': None, 'draw_hard_divider': None, 'draw_inner_divider': None, 'side': side, 'display_condition': display_condition, 'width': None, 'align': None, 'expand': None, 'truncate': None, 'startup': None, 'shutdown': None, '_rendered_raw': '', '_rendered_hl': '', '_len': None, '_contents_len': None, } if segment_type == 'function': startup_func = get_attr_func(_contents_func, 'startup', args) shutdown_func = getattr(_contents_func, 'shutdown', None) expand_func = get_attr_func(_contents_func, 'expand', args, True) truncate_func = get_attr_func(_contents_func, 'truncate', args, True) if hasattr(_contents_func, 'powerline_requires_filesystem_watcher'): create_watcher = lambda: create_file_watcher(pl, common_config['watcher']) args[str('create_watcher')] = create_watcher if hasattr(_contents_func, 'powerline_requires_segment_info'): contents_func = lambda pl, segment_info: _contents_func(pl=pl, segment_info=segment_info, **args) else: contents_func = lambda pl, segment_info: _contents_func(pl=pl, **args) else: startup_func = None shutdown_func = None contents_func = None expand_func = None truncate_func = None return { 'name': name or function_name, 'type': segment_type, 'highlight_groups': highlight_groups, 'divider_highlight_group': None, 'before': get_key(False, segment, module, function_name, name, 'before', ''), 'after': get_key(False, segment, module, function_name, name, 'after', ''), 'contents_func': contents_func, 'contents': contents, 'literal_contents': (0, ''), 'priority': segment.get('priority', None), 'draw_hard_divider': segment.get('draw_hard_divider', True), 'draw_soft_divider': segment.get('draw_soft_divider', True), 'draw_inner_divider': segment.get('draw_inner_divider', False), 'side': side, 'display_condition': display_condition, 'width': segment.get('width'), 'align': segment.get('align', 'l'), 'expand': expand_func, 'truncate': truncate_func, 'startup': startup_func, 'shutdown': shutdown_func, '_rendered_raw': '', '_rendered_hl': '', '_len': None, '_contents_len': None, } return get
{ "content_hash": "eb57ff897bfe8617ebb04e23b3633172", "timestamp": "", "source": "github", "line_count": 449, "max_line_length": 129, "avg_line_length": 29.971046770601337, "alnum_prop": 0.669242773277848, "repo_name": "prvnkumar/powerline", "id": "e48689b58de69f05690863d8ae87055cb11579d2", "size": "13487", "binary": false, "copies": "2", "ref": "refs/heads/develop", "path": "powerline/segment.py", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "3781" }, { "name": "Lua", "bytes": "400" }, { "name": "Python", "bytes": "731291" }, { "name": "Shell", "bytes": "49776" }, { "name": "VimL", "bytes": "16969" } ], "symlink_target": "" }
<?xml version="1.0" encoding="UTF-8" ?> <rss version="2.0" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:wikidot="http://www.wikidot.com/rss-namespace"> <channel> <title>Item Trade</title> <link>http://bvs.wikidot.com/forum/t-81652/item-trade</link> <description>Posts in the discussion thread &quot;Item Trade&quot; - Because we really need one of these. (Item Mail)</description> <copyright></copyright> <lastBuildDate>Sun, 10 Jul 2022 05:54:21 +0000</lastBuildDate> <item> <guid>http://bvs.wikidot.com/forum/t-81652#post-247272</guid> <title>Re: Item Trade</title> <link>http://bvs.wikidot.com/forum/t-81652/item-trade#post-247272</link> <description></description> <pubDate>Wed, 27 Aug 2008 20:02:47 +0000</pubDate> <wikidot:authorName>KazeNR</wikidot:authorName> <wikidot:authorUserId>87475</wikidot:authorUserId> <content:encoded> <![CDATA[ <p>Hello, here again, I offer a Stealth Suit and a Necklace of the First HoCage in exchange of a Codec.<br /> And a Necklace of the First HoCage along a Billy Bucket for a Love Love Paradise.<br /> I am willing to negotiate for a good Monster Drop.</p> <img src="http://www.animecubed.com/billy/pics/sigs/KazeNR.jpg" alt="KazeNR.jpg" class="image" /><br /> Be the Ultimate Ninja! Play <a href="http://www.animecubed.com/billy/?KazeNR" >Billy Vs. SNAKEMAN</a> today ]]> </content:encoded> </item> <item> <guid>http://bvs.wikidot.com/forum/t-81652#post-240528</guid> <title>Re: Item Trade</title> <link>http://bvs.wikidot.com/forum/t-81652/item-trade#post-240528</link> <description></description> <pubDate>Fri, 15 Aug 2008 16:38:57 +0000</pubDate> <wikidot:authorName>KazeNR</wikidot:authorName> <wikidot:authorUserId>87475</wikidot:authorUserId> <content:encoded> <![CDATA[ <p>Er.. I am only willing to trade one of each, those are from before I looped, and I will need them when I have access to Wasteland, so I can't negotiate 'em. Sorry, the only important thing that I feel that I would trade would be billy buckets, and not all of them, that's why I offered two, 'cause I'll need the others to level up emosuke, with one as a spare.</p> <img src="http://www.animecubed.com/billy/pics/sigs/KazeNR.jpg" alt="KazeNR.jpg" class="image" /><br /> Be the Ultimate Ninja! Play <a href="http://www.animecubed.com/billy/?KazeNR" >Billy Vs. SNAKEMAN</a> today ]]> </content:encoded> </item> <item> <guid>http://bvs.wikidot.com/forum/t-81652#post-240493</guid> <title>Re: Item Trade</title> <link>http://bvs.wikidot.com/forum/t-81652/item-trade#post-240493</link> <description></description> <pubDate>Fri, 15 Aug 2008 15:18:58 +0000</pubDate> <wikidot:authorName>rash92</wikidot:authorName> <wikidot:authorUserId>136343</wikidot:authorUserId> <content:encoded> <![CDATA[ <p>what do you want for ash-covered tiles? i haven't got any spare perms but i can give something else. maybe a CRW? that'd be for like 5-10 of them though.<br /> its still negotiable, so if you want something else, let me know.</p> ]]> </content:encoded> </item> <item> <guid>http://bvs.wikidot.com/forum/t-81652#post-240138</guid> <title>Re: Item Trade</title> <link>http://bvs.wikidot.com/forum/t-81652/item-trade#post-240138</link> <description></description> <pubDate>Thu, 14 Aug 2008 20:25:16 +0000</pubDate> <wikidot:authorName>KazeNR</wikidot:authorName> <wikidot:authorUserId>87475</wikidot:authorUserId> <content:encoded> <![CDATA[ <p>I forgot, I have an additional Billy Bucket, as well as Crumbling Minerals, Ash-Covered Tile, Broken Spyglass and a Threadbare Robes, in case you wish to negotiate rare monster drops (Regalia comes to mind).</p> <img src="http://www.animecubed.com/billy/pics/sigs/KazeNR.jpg" alt="KazeNR.jpg" class="image" /><br /> Be the Ultimate Ninja! Play <a href="http://www.animecubed.com/billy/?KazeNR" >Billy Vs. SNAKEMAN</a> today ]]> </content:encoded> </item> <item> <guid>http://bvs.wikidot.com/forum/t-81652#post-240134</guid> <title>Item Trade</title> <link>http://bvs.wikidot.com/forum/t-81652/item-trade#post-240134</link> <description></description> <pubDate>Thu, 14 Aug 2008 20:10:41 +0000</pubDate> <wikidot:authorName>KazeNR</wikidot:authorName> <wikidot:authorUserId>87475</wikidot:authorUserId> <content:encoded> <![CDATA[ <p>Alright first thing, I offer a Necklace of the First HoCage, and a Billy Bucket in exchange of a Codec or a Monster Drop (except Perfect Hair or similars), so, any takers?</p> ]]> </content:encoded> </item> </channel> </rss>
{ "content_hash": "68d65b8ba1964cfd134537bc6a374126", "timestamp": "", "source": "github", "line_count": 68, "max_line_length": 586, "avg_line_length": 70.1029411764706, "alnum_prop": 0.6872246696035242, "repo_name": "tn5421/tn5421.github.io", "id": "1c26c4ee157bc3722533ac32b6b10bf83a3a7335", "size": "4767", "binary": false, "copies": "1", "ref": "refs/heads/main", "path": "bvs.wikidot.com/feed/forum/t-81652.xml", "mode": "33188", "license": "mit", "language": [ { "name": "HTML", "bytes": "400301089" } ], "symlink_target": "" }
package it.unibz.inf.ontop.ontology.impl; import it.unibz.inf.ontop.model.Constant; import it.unibz.inf.ontop.model.ObjectConstant; import it.unibz.inf.ontop.model.ValueConstant; import it.unibz.inf.ontop.ontology.*; /** * factory for ABox assertions * * IMPORTANT: this factory does NOT check whether the class / property has been declared * * USES: OntologyFactoryImpl (and so, checks for top / bottom concept / property * see rules [C4], [O4], [D4]) * * @author Roman Kontchakov * */ public class AssertionFactoryImpl implements AssertionFactory { private static final AssertionFactoryImpl instance = new AssertionFactoryImpl(); private final OntologyFactory ofac = OntologyFactoryImpl.getInstance(); private AssertionFactoryImpl() { // NO-OP to make the default constructor private } public static AssertionFactory getInstance() { return instance; } /** * creates a class assertion (without checking any vocabulary) * * @return null if it is top class ([C4], @see OntologyFactoryImpl) * @throws InconsistentOntologyException if it is the bottom class ([C4], @see OntologyFactoryImpl) */ @Override public ClassAssertion createClassAssertion(String className, ObjectConstant o) throws InconsistentOntologyException { OClass oc = new ClassImpl(className); return ofac.createClassAssertion(oc, o); } /** * creates an object property assertion (without checking any vocabulary) * * @return null if it is top object property ([O4], @see OntologyFactoryImpl) * @throws InconsistentOntologyException if it is the bottom object property ([O4], @see OntologyFactoryImpl) */ @Override public ObjectPropertyAssertion createObjectPropertyAssertion(String propertyName, ObjectConstant o1, ObjectConstant o2) throws InconsistentOntologyException { ObjectPropertyExpression ope = new ObjectPropertyExpressionImpl(propertyName); return ofac.createObjectPropertyAssertion(ope, o1, o2); } /** * creates a data property assertion (without checking any vocabulary) * * @return null if it is top data property ([D4], @see OntologyFactoryImpl) * @throws InconsistentOntologyException if it is the bottom data property ([D4], @see OntologyFactoryImpl) */ @Override public DataPropertyAssertion createDataPropertyAssertion(String propertyName, ObjectConstant o1, ValueConstant o2) throws InconsistentOntologyException { DataPropertyExpression dpe = new DataPropertyExpressionImpl(propertyName); return ofac.createDataPropertyAssertion(dpe, o1, o2); } /** * creates an annotation property assertion (without checking any vocabulary) * * */ @Override public AnnotationAssertion createAnnotationAssertion(String propertyName, ObjectConstant o, Constant v) { AnnotationProperty ap = new AnnotationPropertyImpl(propertyName); return ofac.createAnnotationAssertion(ap, o, v); } }
{ "content_hash": "de1cce2d3ae4ecabc026f7fadfcd92a8", "timestamp": "", "source": "github", "line_count": 88, "max_line_length": 159, "avg_line_length": 32.71590909090909, "alnum_prop": 0.767280305661688, "repo_name": "srapisarda/ontop", "id": "54c9e27c9867adb05ce31e8621817d2cb7f632ad", "size": "3553", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "obdalib-core/src/main/java/it/unibz/inf/ontop/ontology/impl/AssertionFactoryImpl.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "444" }, { "name": "CSS", "bytes": "2676" }, { "name": "GAP", "bytes": "43820" }, { "name": "HTML", "bytes": "2860408" }, { "name": "Java", "bytes": "4959949" }, { "name": "Ruby", "bytes": "52622" }, { "name": "Shell", "bytes": "18940" }, { "name": "TeX", "bytes": "10376" }, { "name": "Web Ontology Language", "bytes": "76424123" } ], "symlink_target": "" }
<?php /* * To change this template, choose Tools | Templates * and open the template in the editor. */ class AdvancedMarketplace_Component_Block_RecentViewListing extends Phpfox_Component { public function process() { $bIsNoRecent = $this->getParam("bIsNoRecent"); $bIsViewMore = false; list($iCnt, $aRecentViewListing) = PHPFOX::getService("advancedmarketplace")->frontend_getRecentViewListings(phpfox::getUserId(), NULL, 3); if(empty($aRecentViewListing) || $bIsNoRecent) { return false; } if($iCnt > phpfox::getParam('advancedmarketplace.total_listing_more_from')) { $bIsViewMore = true; } $this->template()->assign(array( 'sHeader' => Phpfox::getPhrase('advancedmarketplace.recent_viewed_listing'), 'corepath' => phpfox::getParam('core.path'), 'aRecentViewListing' => $aRecentViewListing, 'advancedmarketplace_url_image' => Phpfox::getParam('core.url_pic') . "advancedmarketplace/", 'bIsViewMore' => $bIsViewMore )); return 'block'; } } ?>
{ "content_hash": "a94b3427d0169fa6a2494f0e8b1a15a4", "timestamp": "", "source": "github", "line_count": 33, "max_line_length": 141, "avg_line_length": 33.878787878787875, "alnum_prop": 0.6288014311270125, "repo_name": "edbiler/BazaarCorner", "id": "52fd588b9d5933d550ba638308331b9f75f5c01a", "size": "1118", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "module/advancedmarketplace/include/component/block/recentviewlisting.class.php", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "1407330" }, { "name": "JavaScript", "bytes": "1999377" }, { "name": "PHP", "bytes": "23310671" }, { "name": "Visual Basic", "bytes": "1274" } ], "symlink_target": "" }
@implementation SimpleKMLPolyStyle @synthesize fill; @synthesize outline; - (id)initWithXMLNode:(CXMLNode *)node sourceURL:sourceURL error:(NSError **)error { self = [super initWithXMLNode:node sourceURL:sourceURL error:error]; if (self != nil) { fill = YES; outline = YES; for (CXMLNode *child in [node children]) { if ([[child name] isEqualToString:@"fill"]) fill = [[child stringValue] boolValue]; else if ([[child name] isEqualToString:@"outline"]) outline = [[child stringValue] boolValue]; } } return self; } @end
{ "content_hash": "e4f8b526eca3ddc37ac63bc52d7b7609", "timestamp": "", "source": "github", "line_count": 28, "max_line_length": 82, "avg_line_length": 23.5, "alnum_prop": 0.5775075987841946, "repo_name": "maxbritto/Simple-KML", "id": "66d4ef0a084a09d3d84b6df4d0b810c17e04a62b", "size": "2379", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "source/SimpleKMLPolyStyle.m", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "Objective-C", "bytes": "166130" }, { "name": "Ruby", "bytes": "1111" } ], "symlink_target": "" }
/** * Created by joyer on 17/10/11. */ const TestUtl = require('@hasaki-ui/hsk-alistar'); TestUtl.useShould(); describe("/lulu",function () { it("函数完整性检测",function () { const Lulu = require('../../src/index'); Object.keys(Lulu).should.be.include.members([ // ArrayUtl 'wrapArray','paddingLeftLastValue', // AsyncUtl 'flatPromise','syncExecMultiplePromiseFunction', // FileUtl 'rmrf','rmrfSync','mkdirp','mkdirpSync', // LangUtl 'withCatch', // PathUtl 'WORKSPACE','projectPath','resolve', // ProcessUtl 'exec','execScript' ]) }); });
{ "content_hash": "2ab923fb93faa008be23eb1b97ceeab3", "timestamp": "", "source": "github", "line_count": 26, "max_line_length": 60, "avg_line_length": 27.423076923076923, "alnum_prop": 0.5161290322580645, "repo_name": "HasakiUI/hsk-garen", "id": "4a97945aafcf7e914397e4362a13e7ed63dbebc3", "size": "727", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "test/workspace/builder-test/node_modules/_@[email protected]@@hasaki-ui/hsk-lulu/test/e2e/index.spec.js", "mode": "33188", "license": "mit", "language": [ { "name": "HTML", "bytes": "373" }, { "name": "JavaScript", "bytes": "210357" }, { "name": "Vue", "bytes": "1813" } ], "symlink_target": "" }
<?xml version="1.0" ?><!DOCTYPE TS><TS language="hr" version="2.1"> <context> <name>AboutDialog</name> <message> <location filename="../forms/aboutdialog.ui" line="+14"/> <source>About Fuelcoin</source> <translation type="unfinished"/> </message> <message> <location line="+39"/> <source>&lt;b&gt;Fuelcoin&lt;/b&gt; version</source> <translation type="unfinished"/> </message> <message> <location line="+41"/> <source>Copyright © 2009-2014 The Bitcoin developers Copyright © 2012-2014 The NovaCoin developers Copyright © 2014 The Fuelcoin developers</source> <translation type="unfinished"/> </message> <message> <location line="+15"/> <source> This is experimental software. Distributed under the MIT/X11 software license, see the accompanying file COPYING or http://www.opensource.org/licenses/mit-license.php. This product includes software developed by the OpenSSL Project for use in the OpenSSL Toolkit (http://www.openssl.org/) and cryptographic software written by Eric Young ([email protected]) and UPnP software written by Thomas Bernard.</source> <translation type="unfinished"/> </message> </context> <context> <name>AddressBookPage</name> <message> <location filename="../forms/addressbookpage.ui" line="+14"/> <source>Address Book</source> <translation type="unfinished"/> </message> <message> <location line="+22"/> <source>Double-click to edit address or label</source> <translation>Dvostruki klik za uređivanje adrese ili oznake</translation> </message> <message> <location line="+27"/> <source>Create a new address</source> <translation>Dodajte novu adresu</translation> </message> <message> <location line="+14"/> <source>Copy the currently selected address to the system clipboard</source> <translation>Kopiraj trenutno odabranu adresu u međuspremnik</translation> </message> <message> <location line="-11"/> <source>&amp;New Address</source> <translation type="unfinished"/> </message> <message> <location line="-46"/> <source>These are your Fuelcoin addresses for receiving payments. You may want to give a different one to each sender so you can keep track of who is paying you.</source> <translation type="unfinished"/> </message> <message> <location line="+60"/> <source>&amp;Copy Address</source> <translation>&amp;Kopirati adresu</translation> </message> <message> <location line="+11"/> <source>Show &amp;QR Code</source> <translation type="unfinished"/> </message> <message> <location line="+11"/> <source>Sign a message to prove you own a Fuelcoin address</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Sign &amp;Message</source> <translation type="unfinished"/> </message> <message> <location line="+25"/> <source>Delete the currently selected address from the list</source> <translation type="unfinished"/> </message> <message> <location line="-14"/> <source>Verify a message to ensure it was signed with a specified Fuelcoin address</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>&amp;Verify Message</source> <translation type="unfinished"/> </message> <message> <location line="+14"/> <source>&amp;Delete</source> <translation>&amp;Brisanje</translation> </message> <message> <location filename="../addressbookpage.cpp" line="+65"/> <source>Copy &amp;Label</source> <translation>Kopirati &amp;oznaku</translation> </message> <message> <location line="+2"/> <source>&amp;Edit</source> <translation>&amp;Izmjeniti</translation> </message> <message> <location line="+250"/> <source>Export Address Book Data</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Comma separated file (*.csv)</source> <translation>Datoteka vrijednosti odvojenih zarezom (*. csv)</translation> </message> <message> <location line="+13"/> <source>Error exporting</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>Could not write to file %1.</source> <translation type="unfinished"/> </message> </context> <context> <name>AddressTableModel</name> <message> <location filename="../addresstablemodel.cpp" line="+144"/> <source>Label</source> <translation>Oznaka</translation> </message> <message> <location line="+0"/> <source>Address</source> <translation>Adresa</translation> </message> <message> <location line="+36"/> <source>(no label)</source> <translation>(bez oznake)</translation> </message> </context> <context> <name>AskPassphraseDialog</name> <message> <location filename="../forms/askpassphrasedialog.ui" line="+26"/> <source>Passphrase Dialog</source> <translation type="unfinished"/> </message> <message> <location line="+21"/> <source>Enter passphrase</source> <translation>Unesite lozinku</translation> </message> <message> <location line="+14"/> <source>New passphrase</source> <translation>Nova lozinka</translation> </message> <message> <location line="+14"/> <source>Repeat new passphrase</source> <translation>Ponovite novu lozinku</translation> </message> <message> <location line="+33"/> <source>Serves to disable the trivial sendmoney when OS account compromised. Provides no real security.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>For staking only</source> <translation type="unfinished"/> </message> <message> <location filename="../askpassphrasedialog.cpp" line="+35"/> <source>Enter the new passphrase to the wallet.&lt;br/&gt;Please use a passphrase of &lt;b&gt;10 or more random characters&lt;/b&gt;, or &lt;b&gt;eight or more words&lt;/b&gt;.</source> <translation>Unesite novi lozinku za novčanik. &lt;br/&gt; Molimo Vas da koristite zaporku od &lt;b&gt;10 ili više slučajnih znakova,&lt;/b&gt; ili &lt;b&gt;osam ili više riječi.&lt;/b&gt;</translation> </message> <message> <location line="+1"/> <source>Encrypt wallet</source> <translation>Šifriranje novčanika</translation> </message> <message> <location line="+7"/> <source>This operation needs your wallet passphrase to unlock the wallet.</source> <translation>Ova operacija treba lozinku vašeg novčanika kako bi se novčanik otključao.</translation> </message> <message> <location line="+5"/> <source>Unlock wallet</source> <translation>Otključaj novčanik</translation> </message> <message> <location line="+3"/> <source>This operation needs your wallet passphrase to decrypt the wallet.</source> <translation>Ova operacija treba lozinku vašeg novčanika kako bi se novčanik dešifrirao.</translation> </message> <message> <location line="+5"/> <source>Decrypt wallet</source> <translation>Dešifriranje novčanika.</translation> </message> <message> <location line="+3"/> <source>Change passphrase</source> <translation>Promjena lozinke</translation> </message> <message> <location line="+1"/> <source>Enter the old and new passphrase to the wallet.</source> <translation>Unesite staru i novu lozinku za novčanik.</translation> </message> <message> <location line="+46"/> <source>Confirm wallet encryption</source> <translation>Potvrdi šifriranje novčanika</translation> </message> <message> <location line="+1"/> <source>Warning: If you encrypt your wallet and lose your passphrase, you will &lt;b&gt;LOSE ALL OF YOUR COINS&lt;/b&gt;!</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>Are you sure you wish to encrypt your wallet?</source> <translation>Jeste li sigurni da želite šifrirati svoj novčanik?</translation> </message> <message> <location line="+15"/> <source>IMPORTANT: Any previous backups you have made of your wallet file should be replaced with the newly generated, encrypted wallet file. For security reasons, previous backups of the unencrypted wallet file will become useless as soon as you start using the new, encrypted wallet.</source> <translation type="unfinished"/> </message> <message> <location line="+103"/> <location line="+24"/> <source>Warning: The Caps Lock key is on!</source> <translation>Upozorenje: Tipka Caps Lock je uključena!</translation> </message> <message> <location line="-133"/> <location line="+60"/> <source>Wallet encrypted</source> <translation>Novčanik šifriran</translation> </message> <message> <location line="-58"/> <source>Fuelcoin will close now to finish the encryption process. Remember that encrypting your wallet cannot fully protect your coins from being stolen by malware infecting your computer.</source> <translation type="unfinished"/> </message> <message> <location line="+13"/> <location line="+7"/> <location line="+44"/> <location line="+6"/> <source>Wallet encryption failed</source> <translation>Šifriranje novčanika nije uspjelo</translation> </message> <message> <location line="-56"/> <source>Wallet encryption failed due to an internal error. Your wallet was not encrypted.</source> <translation>Šifriranje novčanika nije uspjelo zbog interne pogreške. Vaš novčanik nije šifriran.</translation> </message> <message> <location line="+7"/> <location line="+50"/> <source>The supplied passphrases do not match.</source> <translation>Priložene lozinke se ne podudaraju.</translation> </message> <message> <location line="-38"/> <source>Wallet unlock failed</source> <translation>Otključavanje novčanika nije uspjelo</translation> </message> <message> <location line="+1"/> <location line="+12"/> <location line="+19"/> <source>The passphrase entered for the wallet decryption was incorrect.</source> <translation>Lozinka za dešifriranje novčanika nije točna.</translation> </message> <message> <location line="-20"/> <source>Wallet decryption failed</source> <translation>Dešifriranje novčanika nije uspjelo</translation> </message> <message> <location line="+14"/> <source>Wallet passphrase was successfully changed.</source> <translation>Lozinka novčanika je uspješno promijenjena.</translation> </message> </context> <context> <name>BitcoinGUI</name> <message> <location filename="../bitcoingui.cpp" line="+282"/> <source>Sign &amp;message...</source> <translation>&amp;Potpišite poruku...</translation> </message> <message> <location line="+251"/> <source>Synchronizing with network...</source> <translation>Usklađivanje s mrežom ...</translation> </message> <message> <location line="-319"/> <source>&amp;Overview</source> <translation>&amp;Pregled</translation> </message> <message> <location line="+1"/> <source>Show general overview of wallet</source> <translation>Prikaži opći pregled novčanika</translation> </message> <message> <location line="+17"/> <source>&amp;Transactions</source> <translation>&amp;Transakcije</translation> </message> <message> <location line="+1"/> <source>Browse transaction history</source> <translation>Pretraži povijest transakcija</translation> </message> <message> <location line="+5"/> <source>&amp;Address Book</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Edit the list of stored addresses and labels</source> <translation type="unfinished"/> </message> <message> <location line="-13"/> <source>&amp;Receive coins</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Show the list of addresses for receiving payments</source> <translation type="unfinished"/> </message> <message> <location line="-7"/> <source>&amp;Send coins</source> <translation type="unfinished"/> </message> <message> <location line="+35"/> <source>E&amp;xit</source> <translation>&amp;Izlaz</translation> </message> <message> <location line="+1"/> <source>Quit application</source> <translation>Izlazak iz programa</translation> </message> <message> <location line="+6"/> <source>Show information about Fuelcoin</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>About &amp;Qt</source> <translation>Više o &amp;Qt</translation> </message> <message> <location line="+1"/> <source>Show information about Qt</source> <translation>Prikaži informacije o Qt</translation> </message> <message> <location line="+2"/> <source>&amp;Options...</source> <translation>&amp;Postavke</translation> </message> <message> <location line="+4"/> <source>&amp;Encrypt Wallet...</source> <translation>&amp;Šifriraj novčanik...</translation> </message> <message> <location line="+3"/> <source>&amp;Backup Wallet...</source> <translation>&amp;Backup novčanika...</translation> </message> <message> <location line="+2"/> <source>&amp;Change Passphrase...</source> <translation>&amp;Promijena lozinke...</translation> </message> <message numerus="yes"> <location line="+259"/> <source>~%n block(s) remaining</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform></translation> </message> <message> <location line="+6"/> <source>Downloaded %1 of %2 blocks of transaction history (%3% done).</source> <translation type="unfinished"/> </message> <message> <location line="-256"/> <source>&amp;Export...</source> <translation type="unfinished"/> </message> <message> <location line="-64"/> <source>Send coins to a Fuelcoin address</source> <translation type="unfinished"/> </message> <message> <location line="+47"/> <source>Modify configuration options for Fuelcoin</source> <translation type="unfinished"/> </message> <message> <location line="+18"/> <source>Export the data in the current tab to a file</source> <translation type="unfinished"/> </message> <message> <location line="-14"/> <source>Encrypt or decrypt wallet</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Backup wallet to another location</source> <translation>Napravite sigurnosnu kopiju novčanika na drugoj lokaciji</translation> </message> <message> <location line="+2"/> <source>Change the passphrase used for wallet encryption</source> <translation>Promijenite lozinku za šifriranje novčanika</translation> </message> <message> <location line="+10"/> <source>&amp;Debug window</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Open debugging and diagnostic console</source> <translation type="unfinished"/> </message> <message> <location line="-5"/> <source>&amp;Verify message...</source> <translation>&amp;Potvrdite poruku...</translation> </message> <message> <location line="-202"/> <source>Fuelcoin</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>Wallet</source> <translation>Novčanik</translation> </message> <message> <location line="+180"/> <source>&amp;About Fuelcoin</source> <translation type="unfinished"/> </message> <message> <location line="+9"/> <source>&amp;Show / Hide</source> <translation type="unfinished"/> </message> <message> <location line="+9"/> <source>Unlock wallet</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>&amp;Lock Wallet</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Lock wallet</source> <translation type="unfinished"/> </message> <message> <location line="+35"/> <source>&amp;File</source> <translation>&amp;Datoteka</translation> </message> <message> <location line="+8"/> <source>&amp;Settings</source> <translation>&amp;Konfiguracija</translation> </message> <message> <location line="+8"/> <source>&amp;Help</source> <translation>&amp;Pomoć</translation> </message> <message> <location line="+12"/> <source>Tabs toolbar</source> <translation>Traka kartica</translation> </message> <message> <location line="+8"/> <source>Actions toolbar</source> <translation type="unfinished"/> </message> <message> <location line="+13"/> <location line="+9"/> <source>[testnet]</source> <translation>[testnet]</translation> </message> <message> <location line="+0"/> <location line="+60"/> <source>Fuelcoin client</source> <translation type="unfinished"/> </message> <message numerus="yes"> <location line="+75"/> <source>%n active connection(s) to Fuelcoin network</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform></translation> </message> <message> <location line="+40"/> <source>Downloaded %1 blocks of transaction history.</source> <translation type="unfinished"/> </message> <message> <location line="+413"/> <source>Staking.&lt;br&gt;Your weight is %1&lt;br&gt;Network weight is %2&lt;br&gt;Expected time to earn reward is %3</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <source>Not staking because wallet is locked</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Not staking because wallet is offline</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Not staking because wallet is syncing</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Not staking because you don&apos;t have mature coins</source> <translation type="unfinished"/> </message> <message numerus="yes"> <location line="-403"/> <source>%n second(s) ago</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform></translation> </message> <message> <location line="-312"/> <source>About Fuelcoin card</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Show information about Fuelcoin card</source> <translation type="unfinished"/> </message> <message> <location line="+18"/> <source>&amp;Unlock Wallet...</source> <translation type="unfinished"/> </message> <message numerus="yes"> <location line="+297"/> <source>%n minute(s) ago</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform></translation> </message> <message numerus="yes"> <location line="+4"/> <source>%n hour(s) ago</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform></translation> </message> <message numerus="yes"> <location line="+4"/> <source>%n day(s) ago</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform></translation> </message> <message> <location line="+6"/> <source>Up to date</source> <translation>Ažurno</translation> </message> <message> <location line="+7"/> <source>Catching up...</source> <translation>Ažuriranje...</translation> </message> <message> <location line="+10"/> <source>Last received block was generated %1.</source> <translation type="unfinished"/> </message> <message> <location line="+59"/> <source>This transaction is over the size limit. You can still send it for a fee of %1, which goes to the nodes that process your transaction and helps to support the network. Do you want to pay the fee?</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Confirm transaction fee</source> <translation type="unfinished"/> </message> <message> <location line="+27"/> <source>Sent transaction</source> <translation>Poslana transakcija</translation> </message> <message> <location line="+1"/> <source>Incoming transaction</source> <translation>Dolazna transakcija</translation> </message> <message> <location line="+1"/> <source>Date: %1 Amount: %2 Type: %3 Address: %4 </source> <translation>Datum:%1 Iznos:%2 Tip:%3 Adresa:%4 </translation> </message> <message> <location line="+100"/> <location line="+15"/> <source>URI handling</source> <translation type="unfinished"/> </message> <message> <location line="-15"/> <location line="+15"/> <source>URI can not be parsed! This can be caused by an invalid Fuelcoin address or malformed URI parameters.</source> <translation type="unfinished"/> </message> <message> <location line="+18"/> <source>Wallet is &lt;b&gt;encrypted&lt;/b&gt; and currently &lt;b&gt;unlocked&lt;/b&gt;</source> <translation>Novčanik je &lt;b&gt;šifriran&lt;/b&gt; i trenutno &lt;b&gt;otključan&lt;/b&gt;</translation> </message> <message> <location line="+10"/> <source>Wallet is &lt;b&gt;encrypted&lt;/b&gt; and currently &lt;b&gt;locked&lt;/b&gt;</source> <translation>Novčanik je &lt;b&gt;šifriran&lt;/b&gt; i trenutno &lt;b&gt;zaključan&lt;/b&gt;</translation> </message> <message> <location line="+25"/> <source>Backup Wallet</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>Wallet Data (*.dat)</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Backup Failed</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>There was an error trying to save the wallet data to the new location.</source> <translation type="unfinished"/> </message> <message numerus="yes"> <location line="+76"/> <source>%n second(s)</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform></translation> </message> <message numerus="yes"> <location line="+4"/> <source>%n minute(s)</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform></translation> </message> <message numerus="yes"> <location line="+4"/> <source>%n hour(s)</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform></translation> </message> <message numerus="yes"> <location line="+4"/> <source>%n day(s)</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform></translation> </message> <message> <location line="+18"/> <source>Not staking</source> <translation type="unfinished"/> </message> <message> <location filename="../bitcoin.cpp" line="+109"/> <source>A fatal error occurred. Fuelcoin can no longer continue safely and will quit.</source> <translation type="unfinished"/> </message> </context> <context> <name>ClientModel</name> <message> <location filename="../clientmodel.cpp" line="+90"/> <source>Network Alert</source> <translation type="unfinished"/> </message> </context> <context> <name>CoinControlDialog</name> <message> <location filename="../forms/coincontroldialog.ui" line="+14"/> <source>Coin Control</source> <translation type="unfinished"/> </message> <message> <location line="+31"/> <source>Quantity:</source> <translation type="unfinished"/> </message> <message> <location line="+32"/> <source>Bytes:</source> <translation type="unfinished"/> </message> <message> <location line="+48"/> <source>Amount:</source> <translation>Iznos:</translation> </message> <message> <location line="+32"/> <source>Priority:</source> <translation type="unfinished"/> </message> <message> <location line="+48"/> <source>Fee:</source> <translation type="unfinished"/> </message> <message> <location line="+35"/> <source>Low Output:</source> <translation type="unfinished"/> </message> <message> <location filename="../coincontroldialog.cpp" line="+551"/> <source>no</source> <translation type="unfinished"/> </message> <message> <location filename="../forms/coincontroldialog.ui" line="+51"/> <source>After Fee:</source> <translation type="unfinished"/> </message> <message> <location line="+35"/> <source>Change:</source> <translation type="unfinished"/> </message> <message> <location line="+69"/> <source>(un)select all</source> <translation type="unfinished"/> </message> <message> <location line="+13"/> <source>Tree mode</source> <translation type="unfinished"/> </message> <message> <location line="+16"/> <source>List mode</source> <translation type="unfinished"/> </message> <message> <location line="+45"/> <source>Amount</source> <translation>Iznos</translation> </message> <message> <location line="+5"/> <source>Label</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Address</source> <translation>Adresa</translation> </message> <message> <location line="+5"/> <source>Date</source> <translation>Datum</translation> </message> <message> <location line="+5"/> <source>Confirmations</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Confirmed</source> <translation>Potvrđeno</translation> </message> <message> <location line="+5"/> <source>Priority</source> <translation type="unfinished"/> </message> <message> <location filename="../coincontroldialog.cpp" line="-515"/> <source>Copy address</source> <translation>Kopirati adresu</translation> </message> <message> <location line="+1"/> <source>Copy label</source> <translation>Kopirati oznaku</translation> </message> <message> <location line="+1"/> <location line="+26"/> <source>Copy amount</source> <translation>Kopiraj iznos</translation> </message> <message> <location line="-25"/> <source>Copy transaction ID</source> <translation type="unfinished"/> </message> <message> <location line="+24"/> <source>Copy quantity</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Copy fee</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Copy after fee</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Copy bytes</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Copy priority</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Copy low output</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Copy change</source> <translation type="unfinished"/> </message> <message> <location line="+317"/> <source>highest</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>high</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>medium-high</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>medium</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>low-medium</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>low</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>lowest</source> <translation type="unfinished"/> </message> <message> <location line="+155"/> <source>DUST</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>yes</source> <translation type="unfinished"/> </message> <message> <location line="+10"/> <source>This label turns red, if the transaction size is bigger than 10000 bytes. This means a fee of at least %1 per kb is required. Can vary +/- 1 Byte per input.</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Transactions with higher priority get more likely into a block. This label turns red, if the priority is smaller than &quot;medium&quot;. This means a fee of at least %1 per kb is required.</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>This label turns red, if any recipient receives an amount smaller than %1. This means a fee of at least %2 is required. Amounts below 0.546 times the minimum relay fee are shown as DUST.</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>This label turns red, if the change is smaller than %1. This means a fee of at least %2 is required.</source> <translation type="unfinished"/> </message> <message> <location line="+37"/> <location line="+66"/> <source>(no label)</source> <translation>(bez oznake)</translation> </message> <message> <location line="-9"/> <source>change from %1 (%2)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>(change)</source> <translation type="unfinished"/> </message> </context> <context> <name>EditAddressDialog</name> <message> <location filename="../forms/editaddressdialog.ui" line="+14"/> <source>Edit Address</source> <translation>Izmjeni adresu</translation> </message> <message> <location line="+11"/> <source>&amp;Label</source> <translation>&amp;Oznaka</translation> </message> <message> <location line="+10"/> <source>The label associated with this address book entry</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>&amp;Address</source> <translation>&amp;Adresa</translation> </message> <message> <location line="+10"/> <source>The address associated with this address book entry. This can only be modified for sending addresses.</source> <translation type="unfinished"/> </message> <message> <location filename="../editaddressdialog.cpp" line="+20"/> <source>New receiving address</source> <translation>Nova adresa za primanje</translation> </message> <message> <location line="+4"/> <source>New sending address</source> <translation>Nova adresa za slanje</translation> </message> <message> <location line="+3"/> <source>Edit receiving address</source> <translation>Uredi adresu za primanje</translation> </message> <message> <location line="+4"/> <source>Edit sending address</source> <translation>Uredi adresu za slanje</translation> </message> <message> <location line="+76"/> <source>The entered address &quot;%1&quot; is already in the address book.</source> <translation>Upisana adresa &quot;%1&quot; je već u adresaru.</translation> </message> <message> <location line="-5"/> <source>The entered address &quot;%1&quot; is not a valid Fuelcoin address.</source> <translation type="unfinished"/> </message> <message> <location line="+10"/> <source>Could not unlock wallet.</source> <translation>Ne mogu otključati novčanik.</translation> </message> <message> <location line="+5"/> <source>New key generation failed.</source> <translation>Stvaranje novog ključa nije uspjelo.</translation> </message> </context> <context> <name>GUIUtil::HelpMessageBox</name> <message> <location filename="../guiutil.cpp" line="+420"/> <location line="+12"/> <source>Fuelcoin-Qt</source> <translation type="unfinished"/> </message> <message> <location line="-12"/> <source>version</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Usage:</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>command-line options</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>UI options</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Set language, for example &quot;de_DE&quot; (default: system locale)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Start minimized</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Show splash screen on startup (default: 1)</source> <translation type="unfinished"/> </message> </context> <context> <name>OptionsDialog</name> <message> <location filename="../forms/optionsdialog.ui" line="+14"/> <source>Options</source> <translation>Postavke</translation> </message> <message> <location line="+16"/> <source>&amp;Main</source> <translation>&amp;Glavno</translation> </message> <message> <location line="+6"/> <source>Optional transaction fee per kB that helps make sure your transactions are processed quickly. Most transactions are 1 kB. Fee 0.01 recommended.</source> <translation type="unfinished"/> </message> <message> <location line="+15"/> <source>Pay transaction &amp;fee</source> <translation>Plati &amp;naknadu za transakciju</translation> </message> <message> <location line="+31"/> <source>Reserved amount does not participate in staking and is therefore spendable at any time.</source> <translation type="unfinished"/> </message> <message> <location line="+15"/> <source>Reserve</source> <translation type="unfinished"/> </message> <message> <location line="+31"/> <source>Automatically start Fuelcoin after logging in to the system.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>&amp;Start Fuelcoin on system login</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Detach block and address databases at shutdown. This means they can be moved to another data directory, but it slows down shutdown. The wallet is always detached.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>&amp;Detach databases at shutdown</source> <translation type="unfinished"/> </message> <message> <location line="+21"/> <source>&amp;Network</source> <translation>&amp;Mreža</translation> </message> <message> <location line="+6"/> <source>Automatically open the Fuelcoin client port on the router. This only works when your router supports UPnP and it is enabled.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Map port using &amp;UPnP</source> <translation>Mapiraj port koristeći &amp;UPnP</translation> </message> <message> <location line="+7"/> <source>Connect to the Fuelcoin network through a SOCKS proxy (e.g. when connecting through Tor).</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>&amp;Connect through SOCKS proxy:</source> <translation type="unfinished"/> </message> <message> <location line="+9"/> <source>Proxy &amp;IP:</source> <translation>Proxy &amp;IP:</translation> </message> <message> <location line="+19"/> <source>IP address of the proxy (e.g. 127.0.0.1)</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>&amp;Port:</source> <translation type="unfinished"/> </message> <message> <location line="+19"/> <source>Port of the proxy (e.g. 9050)</source> <translation>Port od proxy-a (npr. 9050)</translation> </message> <message> <location line="+7"/> <source>SOCKS &amp;Version:</source> <translation>SOCKS &amp;Verzija:</translation> </message> <message> <location line="+13"/> <source>SOCKS version of the proxy (e.g. 5)</source> <translation type="unfinished"/> </message> <message> <location line="+36"/> <source>&amp;Window</source> <translation>&amp;Prozor</translation> </message> <message> <location line="+6"/> <source>Show only a tray icon after minimizing the window.</source> <translation>Prikaži samo ikonu u sistemskoj traci nakon minimiziranja prozora</translation> </message> <message> <location line="+3"/> <source>&amp;Minimize to the tray instead of the taskbar</source> <translation>&amp;Minimiziraj u sistemsku traku umjesto u traku programa</translation> </message> <message> <location line="+7"/> <source>Minimize instead of exit the application when the window is closed. When this option is enabled, the application will be closed only after selecting Quit in the menu.</source> <translation>Minimizirati umjesto izaći iz aplikacije kada je prozor zatvoren. Kada je ova opcija omogućena, aplikacija će biti zatvorena tek nakon odabira Izlaz u izborniku.</translation> </message> <message> <location line="+3"/> <source>M&amp;inimize on close</source> <translation>M&amp;inimiziraj kod zatvaranja</translation> </message> <message> <location line="+21"/> <source>&amp;Display</source> <translation>&amp;Prikaz</translation> </message> <message> <location line="+8"/> <source>User Interface &amp;language:</source> <translation type="unfinished"/> </message> <message> <location line="+13"/> <source>The user interface language can be set here. This setting will take effect after restarting Fuelcoin.</source> <translation type="unfinished"/> </message> <message> <location line="+11"/> <source>&amp;Unit to show amounts in:</source> <translation>&amp;Jedinica za prikazivanje iznosa:</translation> </message> <message> <location line="+13"/> <source>Choose the default subdivision unit to show in the interface and when sending coins.</source> <translation>Izaberite željeni najmanji dio bitcoina koji će biti prikazan u sučelju i koji će se koristiti za plaćanje.</translation> </message> <message> <location line="+9"/> <source>Whether to show Fuelcoin addresses in the transaction list or not.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>&amp;Display addresses in transaction list</source> <translation>&amp;Prikaži adrese u popisu transakcija</translation> </message> <message> <location line="+7"/> <source>Whether to show coin control features or not.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Display coin &amp;control features (experts only!)</source> <translation type="unfinished"/> </message> <message> <location line="+71"/> <source>&amp;OK</source> <translation>&amp;U redu</translation> </message> <message> <location line="+7"/> <source>&amp;Cancel</source> <translation>&amp;Odustani</translation> </message> <message> <location line="+10"/> <source>&amp;Apply</source> <translation type="unfinished"/> </message> <message> <location filename="../optionsdialog.cpp" line="+55"/> <source>default</source> <translation>standardne vrijednosti</translation> </message> <message> <location line="+149"/> <location line="+9"/> <source>Warning</source> <translation type="unfinished"/> </message> <message> <location line="-9"/> <location line="+9"/> <source>This setting will take effect after restarting Fuelcoin.</source> <translation type="unfinished"/> </message> <message> <location line="+29"/> <source>The supplied proxy address is invalid.</source> <translation type="unfinished"/> </message> </context> <context> <name>OverviewPage</name> <message> <location filename="../forms/overviewpage.ui" line="+14"/> <source>Form</source> <translation>Oblik</translation> </message> <message> <location line="+33"/> <location line="+231"/> <source>The displayed information may be out of date. Your wallet automatically synchronizes with the Fuelcoin network after a connection is established, but this process has not completed yet.</source> <translation type="unfinished"/> </message> <message> <location line="-160"/> <source>Stake:</source> <translation type="unfinished"/> </message> <message> <location line="+29"/> <source>Unconfirmed:</source> <translation type="unfinished"/> </message> <message> <location line="-107"/> <source>Wallet</source> <translation>Novčanik</translation> </message> <message> <location line="+49"/> <source>Spendable:</source> <translation type="unfinished"/> </message> <message> <location line="+16"/> <source>Your current spendable balance</source> <translation type="unfinished"/> </message> <message> <location line="+71"/> <source>Immature:</source> <translation type="unfinished"/> </message> <message> <location line="+13"/> <source>Mined balance that has not yet matured</source> <translation type="unfinished"/> </message> <message> <location line="+20"/> <source>Total:</source> <translation>Ukupno:</translation> </message> <message> <location line="+16"/> <source>Your current total balance</source> <translation type="unfinished"/> </message> <message> <location line="+46"/> <source>&lt;b&gt;Recent transactions&lt;/b&gt;</source> <translation>&lt;b&gt;Nedavne transakcije&lt;/b&gt;</translation> </message> <message> <location line="-108"/> <source>Total of transactions that have yet to be confirmed, and do not yet count toward the current balance</source> <translation type="unfinished"/> </message> <message> <location line="-29"/> <source>Total of coins that was staked, and do not yet count toward the current balance</source> <translation type="unfinished"/> </message> <message> <location filename="../overviewpage.cpp" line="+113"/> <location line="+1"/> <source>out of sync</source> <translation type="unfinished"/> </message> </context> <context> <name>QRCodeDialog</name> <message> <location filename="../forms/qrcodedialog.ui" line="+14"/> <source>QR Code Dialog</source> <translation type="unfinished"/> </message> <message> <location line="+59"/> <source>Request Payment</source> <translation type="unfinished"/> </message> <message> <location line="+56"/> <source>Amount:</source> <translation type="unfinished"/> </message> <message> <location line="-44"/> <source>Label:</source> <translation type="unfinished"/> </message> <message> <location line="+19"/> <source>Message:</source> <translation type="unfinished"/> </message> <message> <location line="+71"/> <source>&amp;Save As...</source> <translation type="unfinished"/> </message> <message> <location filename="../qrcodedialog.cpp" line="+62"/> <source>Error encoding URI into QR Code.</source> <translation type="unfinished"/> </message> <message> <location line="+40"/> <source>The entered amount is invalid, please check.</source> <translation type="unfinished"/> </message> <message> <location line="+23"/> <source>Resulting URI too long, try to reduce the text for label / message.</source> <translation type="unfinished"/> </message> <message> <location line="+25"/> <source>Save QR Code</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>PNG Images (*.png)</source> <translation type="unfinished"/> </message> </context> <context> <name>RPCConsole</name> <message> <location filename="../forms/rpcconsole.ui" line="+46"/> <source>Client name</source> <translation>Ime klijenta</translation> </message> <message> <location line="+10"/> <location line="+23"/> <location line="+26"/> <location line="+23"/> <location line="+23"/> <location line="+36"/> <location line="+53"/> <location line="+23"/> <location line="+23"/> <location filename="../rpcconsole.cpp" line="+348"/> <source>N/A</source> <translation>N/A</translation> </message> <message> <location line="-217"/> <source>Client version</source> <translation>Verzija klijenta</translation> </message> <message> <location line="-45"/> <source>&amp;Information</source> <translation>&amp;Informacija</translation> </message> <message> <location line="+68"/> <source>Using OpenSSL version</source> <translation>Koristim OpenSSL verziju</translation> </message> <message> <location line="+49"/> <source>Startup time</source> <translation type="unfinished"/> </message> <message> <location line="+29"/> <source>Network</source> <translation>Mreža</translation> </message> <message> <location line="+7"/> <source>Number of connections</source> <translation>Broj konekcija</translation> </message> <message> <location line="+23"/> <source>On testnet</source> <translation type="unfinished"/> </message> <message> <location line="+23"/> <source>Block chain</source> <translation>Lanac blokova</translation> </message> <message> <location line="+7"/> <source>Current number of blocks</source> <translation>Trenutni broj blokova</translation> </message> <message> <location line="+23"/> <source>Estimated total blocks</source> <translation>Procjenjeni ukupni broj blokova</translation> </message> <message> <location line="+23"/> <source>Last block time</source> <translation>Posljednje vrijeme bloka</translation> </message> <message> <location line="+52"/> <source>&amp;Open</source> <translation>&amp;Otvori</translation> </message> <message> <location line="+16"/> <source>Command-line options</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Show the Fuelcoin-Qt help message to get a list with possible Fuelcoin command-line options.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>&amp;Show</source> <translation type="unfinished"/> </message> <message> <location line="+24"/> <source>&amp;Console</source> <translation>&amp;Konzola</translation> </message> <message> <location line="-260"/> <source>Build date</source> <translation type="unfinished"/> </message> <message> <location line="-104"/> <source>Fuelcoin - Debug window</source> <translation type="unfinished"/> </message> <message> <location line="+25"/> <source>Fuelcoin Core</source> <translation type="unfinished"/> </message> <message> <location line="+279"/> <source>Debug log file</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Open the Fuelcoin debug log file from the current data directory. This can take a few seconds for large log files.</source> <translation type="unfinished"/> </message> <message> <location line="+102"/> <source>Clear console</source> <translation>Očisti konzolu</translation> </message> <message> <location filename="../rpcconsole.cpp" line="-33"/> <source>Welcome to the Fuelcoin RPC console.</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Use up and down arrows to navigate history, and &lt;b&gt;Ctrl-L&lt;/b&gt; to clear screen.</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Type &lt;b&gt;help&lt;/b&gt; for an overview of available commands.</source> <translation type="unfinished"/> </message> </context> <context> <name>SendCoinsDialog</name> <message> <location filename="../forms/sendcoinsdialog.ui" line="+14"/> <location filename="../sendcoinsdialog.cpp" line="+182"/> <location line="+5"/> <location line="+5"/> <location line="+5"/> <location line="+6"/> <location line="+5"/> <location line="+5"/> <source>Send Coins</source> <translation>Slanje novca</translation> </message> <message> <location line="+76"/> <source>Coin Control Features</source> <translation type="unfinished"/> </message> <message> <location line="+20"/> <source>Inputs...</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>automatically selected</source> <translation type="unfinished"/> </message> <message> <location line="+19"/> <source>Insufficient funds!</source> <translation type="unfinished"/> </message> <message> <location line="+77"/> <source>Quantity:</source> <translation type="unfinished"/> </message> <message> <location line="+22"/> <location line="+35"/> <source>0</source> <translation type="unfinished"/> </message> <message> <location line="-19"/> <source>Bytes:</source> <translation type="unfinished"/> </message> <message> <location line="+51"/> <source>Amount:</source> <translation>Iznos:</translation> </message> <message> <location line="+22"/> <location line="+86"/> <location line="+86"/> <location line="+32"/> <source>0.00 hack</source> <translation type="unfinished"/> </message> <message> <location line="-191"/> <source>Priority:</source> <translation type="unfinished"/> </message> <message> <location line="+19"/> <source>medium</source> <translation type="unfinished"/> </message> <message> <location line="+32"/> <source>Fee:</source> <translation type="unfinished"/> </message> <message> <location line="+35"/> <source>Low Output:</source> <translation type="unfinished"/> </message> <message> <location line="+19"/> <source>no</source> <translation type="unfinished"/> </message> <message> <location line="+32"/> <source>After Fee:</source> <translation type="unfinished"/> </message> <message> <location line="+35"/> <source>Change</source> <translation type="unfinished"/> </message> <message> <location line="+50"/> <source>custom change address</source> <translation type="unfinished"/> </message> <message> <location line="+106"/> <source>Send to multiple recipients at once</source> <translation>Pošalji k nekoliko primatelja odjednom</translation> </message> <message> <location line="+3"/> <source>Add &amp;Recipient</source> <translation>&amp;Dodaj primatelja</translation> </message> <message> <location line="+20"/> <source>Remove all transaction fields</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Clear &amp;All</source> <translation>Obriši &amp;sve</translation> </message> <message> <location line="+28"/> <source>Balance:</source> <translation>Stanje:</translation> </message> <message> <location line="+16"/> <source>123.456 hack</source> <translation type="unfinished"/> </message> <message> <location line="+31"/> <source>Confirm the send action</source> <translation>Potvrdi akciju slanja</translation> </message> <message> <location line="+3"/> <source>S&amp;end</source> <translation>&amp;Pošalji</translation> </message> <message> <location filename="../sendcoinsdialog.cpp" line="-173"/> <source>Enter a Fuelcoin address (e.g. FuelcoinfwYhBmGXcFP2Po1NpRUEiK8km2)</source> <translation type="unfinished"/> </message> <message> <location line="+15"/> <source>Copy quantity</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Copy amount</source> <translation>Kopiraj iznos</translation> </message> <message> <location line="+1"/> <source>Copy fee</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Copy after fee</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Copy bytes</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Copy priority</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Copy low output</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Copy change</source> <translation type="unfinished"/> </message> <message> <location line="+86"/> <source>&lt;b&gt;%1&lt;/b&gt; to %2 (%3)</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Confirm send coins</source> <translation>Potvrdi slanje novca</translation> </message> <message> <location line="+1"/> <source>Are you sure you want to send %1?</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source> and </source> <translation type="unfinished"/> </message> <message> <location line="+29"/> <source>The recipient address is not valid, please recheck.</source> <translation>Adresa primatelja je nevaljala, molimo provjerite je ponovo.</translation> </message> <message> <location line="+5"/> <source>The amount to pay must be larger than 0.</source> <translation>Iznos mora biti veći od 0.</translation> </message> <message> <location line="+5"/> <source>The amount exceeds your balance.</source> <translation>Iznos je veći od stanja računa.</translation> </message> <message> <location line="+5"/> <source>The total exceeds your balance when the %1 transaction fee is included.</source> <translation>Iznos je veći od stanja računa kad se doda naknada za transakcije od %1.</translation> </message> <message> <location line="+6"/> <source>Duplicate address found, can only send to each address once per send operation.</source> <translation>Pronašli smo adresu koja se ponavlja. U svakom plaćanju program može svaku adresu koristiti samo jedanput.</translation> </message> <message> <location line="+5"/> <source>Error: Transaction creation failed.</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Error: The transaction was rejected. This might happen if some of the coins in your wallet were already spent, such as if you used a copy of wallet.dat and coins were spent in the copy but not marked as spent here.</source> <translation type="unfinished"/> </message> <message> <location line="+251"/> <source>WARNING: Invalid Fuelcoin address</source> <translation type="unfinished"/> </message> <message> <location line="+13"/> <source>(no label)</source> <translation>(bez oznake)</translation> </message> <message> <location line="+4"/> <source>WARNING: unknown change address</source> <translation type="unfinished"/> </message> </context> <context> <name>SendCoinsEntry</name> <message> <location filename="../forms/sendcoinsentry.ui" line="+14"/> <source>Form</source> <translation type="unfinished"/> </message> <message> <location line="+15"/> <source>A&amp;mount:</source> <translation>&amp;Iznos:</translation> </message> <message> <location line="+13"/> <source>Pay &amp;To:</source> <translation>&amp;Primatelj plaćanja:</translation> </message> <message> <location line="+24"/> <location filename="../sendcoinsentry.cpp" line="+25"/> <source>Enter a label for this address to add it to your address book</source> <translation>Unesite oznaku za ovu adresu kako bi ju dodali u vaš adresar</translation> </message> <message> <location line="+9"/> <source>&amp;Label:</source> <translation>&amp;Oznaka:</translation> </message> <message> <location line="+18"/> <source>The address to send the payment to (e.g. FuelcoinfwYhBmGXcFP2Po1NpRUEiK8km2)</source> <translation type="unfinished"/> </message> <message> <location line="+10"/> <source>Choose address from address book</source> <translation type="unfinished"/> </message> <message> <location line="+10"/> <source>Alt+A</source> <translation>Alt+A</translation> </message> <message> <location line="+7"/> <source>Paste address from clipboard</source> <translation>Zalijepi adresu iz međuspremnika</translation> </message> <message> <location line="+10"/> <source>Alt+P</source> <translation>Alt+P</translation> </message> <message> <location line="+7"/> <source>Remove this recipient</source> <translation type="unfinished"/> </message> <message> <location filename="../sendcoinsentry.cpp" line="+1"/> <source>Enter a Fuelcoin address (e.g. FuelcoinfwYhBmGXcFP2Po1NpRUEiK8km2)</source> <translation type="unfinished"/> </message> </context> <context> <name>SignVerifyMessageDialog</name> <message> <location filename="../forms/signverifymessagedialog.ui" line="+14"/> <source>Signatures - Sign / Verify a Message</source> <translation type="unfinished"/> </message> <message> <location line="+13"/> <location line="+124"/> <source>&amp;Sign Message</source> <translation>&amp;Potpišite poruku</translation> </message> <message> <location line="-118"/> <source>You can sign messages with your addresses to prove you own them. Be careful not to sign anything vague, as phishing attacks may try to trick you into signing your identity over to them. Only sign fully-detailed statements you agree to.</source> <translation>Možete potpisati poruke sa svojom adresom kako bi dokazali da ih posjedujete. Budite oprezni da ne potpisujete ništa mutno, jer bi vas phishing napadi mogli na prevaru natjerati da prepišete svoj identitet njima. Potpisujte samo detaljno objašnjene izjave sa kojima se slažete.</translation> </message> <message> <location line="+18"/> <source>The address to sign the message with (e.g. FuelcoinfwYhBmGXcFP2Po1NpRUEiK8km2)</source> <translation type="unfinished"/> </message> <message> <location line="+10"/> <location line="+203"/> <source>Choose an address from the address book</source> <translation type="unfinished"/> </message> <message> <location line="-193"/> <location line="+203"/> <source>Alt+A</source> <translation>Alt+A</translation> </message> <message> <location line="-193"/> <source>Paste address from clipboard</source> <translation>Zalijepi adresu iz međuspremnika</translation> </message> <message> <location line="+10"/> <source>Alt+P</source> <translation>Alt+P</translation> </message> <message> <location line="+12"/> <source>Enter the message you want to sign here</source> <translation>Upišite poruku koju želite potpisati ovdje</translation> </message> <message> <location line="+24"/> <source>Copy the current signature to the system clipboard</source> <translation type="unfinished"/> </message> <message> <location line="+21"/> <source>Sign the message to prove you own this Fuelcoin address</source> <translation type="unfinished"/> </message> <message> <location line="+17"/> <source>Reset all sign message fields</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <location line="+146"/> <source>Clear &amp;All</source> <translation>Obriši &amp;sve</translation> </message> <message> <location line="-87"/> <location line="+70"/> <source>&amp;Verify Message</source> <translation>&amp;Potvrdite poruku</translation> </message> <message> <location line="-64"/> <source>Enter the signing address, message (ensure you copy line breaks, spaces, tabs, etc. exactly) and signature below to verify the message. Be careful not to read more into the signature than what is in the signed message itself, to avoid being tricked by a man-in-the-middle attack.</source> <translation type="unfinished"/> </message> <message> <location line="+21"/> <source>The address the message was signed with (e.g. FuelcoinfwYhBmGXcFP2Po1NpRUEiK8km2)</source> <translation type="unfinished"/> </message> <message> <location line="+40"/> <source>Verify the message to ensure it was signed with the specified Fuelcoin address</source> <translation type="unfinished"/> </message> <message> <location line="+17"/> <source>Reset all verify message fields</source> <translation type="unfinished"/> </message> <message> <location filename="../signverifymessagedialog.cpp" line="+27"/> <location line="+3"/> <source>Enter a Fuelcoin address (e.g. FuelcoinfwYhBmGXcFP2Po1NpRUEiK8km2)</source> <translation type="unfinished"/> </message> <message> <location line="-2"/> <source>Click &quot;Sign Message&quot; to generate signature</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Enter Fuelcoin signature</source> <translation type="unfinished"/> </message> <message> <location line="+82"/> <location line="+81"/> <source>The entered address is invalid.</source> <translation type="unfinished"/> </message> <message> <location line="-81"/> <location line="+8"/> <location line="+73"/> <location line="+8"/> <source>Please check the address and try again.</source> <translation type="unfinished"/> </message> <message> <location line="-81"/> <location line="+81"/> <source>The entered address does not refer to a key.</source> <translation type="unfinished"/> </message> <message> <location line="-73"/> <source>Wallet unlock was cancelled.</source> <translation>Otključavanje novčanika je otkazano.</translation> </message> <message> <location line="+8"/> <source>Private key for the entered address is not available.</source> <translation type="unfinished"/> </message> <message> <location line="+12"/> <source>Message signing failed.</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Message signed.</source> <translation>Poruka je potpisana.</translation> </message> <message> <location line="+59"/> <source>The signature could not be decoded.</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <location line="+13"/> <source>Please check the signature and try again.</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>The signature did not match the message digest.</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Message verification failed.</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Message verified.</source> <translation type="unfinished"/> </message> </context> <context> <name>TransactionDesc</name> <message> <location filename="../transactiondesc.cpp" line="+19"/> <source>Open until %1</source> <translation>Otvoren do %1</translation> </message> <message numerus="yes"> <location line="-2"/> <source>Open for %n block(s)</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform></translation> </message> <message> <location line="+8"/> <source>conflicted</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>%1/offline</source> <translation>%1 nije dostupan</translation> </message> <message> <location line="+2"/> <source>%1/unconfirmed</source> <translation>%1/nepotvrđeno</translation> </message> <message> <location line="+2"/> <source>%1 confirmations</source> <translation>%1 potvrda</translation> </message> <message> <location line="+18"/> <source>Status</source> <translation>Status</translation> </message> <message numerus="yes"> <location line="+7"/> <source>, broadcast through %n node(s)</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform></translation> </message> <message> <location line="+4"/> <source>Date</source> <translation>Datum</translation> </message> <message> <location line="+7"/> <source>Source</source> <translation>Izvor</translation> </message> <message> <location line="+0"/> <source>Generated</source> <translation>Generiran</translation> </message> <message> <location line="+5"/> <location line="+17"/> <source>From</source> <translation>Od</translation> </message> <message> <location line="+1"/> <location line="+22"/> <location line="+58"/> <source>To</source> <translation>Za</translation> </message> <message> <location line="-77"/> <location line="+2"/> <source>own address</source> <translation>vlastita adresa</translation> </message> <message> <location line="-2"/> <source>label</source> <translation>oznaka</translation> </message> <message> <location line="+37"/> <location line="+12"/> <location line="+45"/> <location line="+17"/> <location line="+30"/> <source>Credit</source> <translation>Uplaćeno</translation> </message> <message numerus="yes"> <location line="-102"/> <source>matures in %n more block(s)</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform></translation> </message> <message> <location line="+2"/> <source>not accepted</source> <translation>Nije prihvaćeno</translation> </message> <message> <location line="+44"/> <location line="+8"/> <location line="+15"/> <location line="+30"/> <source>Debit</source> <translation>Zaduženje</translation> </message> <message> <location line="-39"/> <source>Transaction fee</source> <translation>Naknada za transakciju</translation> </message> <message> <location line="+16"/> <source>Net amount</source> <translation>Neto iznos</translation> </message> <message> <location line="+6"/> <source>Message</source> <translation>Poruka</translation> </message> <message> <location line="+2"/> <source>Comment</source> <translation>Komentar</translation> </message> <message> <location line="+2"/> <source>Transaction ID</source> <translation>ID transakcije</translation> </message> <message> <location line="+3"/> <source>Generated coins must mature 510 blocks before they can be spent. When you generated this block, it was broadcast to the network to be added to the block chain. If it fails to get into the chain, its state will change to &quot;not accepted&quot; and it won&apos;t be spendable. This may occasionally happen if another node generates a block within a few seconds of yours.</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Debug information</source> <translation type="unfinished"/> </message> <message> <location line="+8"/> <source>Transaction</source> <translation>Transakcija</translation> </message> <message> <location line="+5"/> <source>Inputs</source> <translation>Unosi</translation> </message> <message> <location line="+23"/> <source>Amount</source> <translation>Iznos</translation> </message> <message> <location line="+1"/> <source>true</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>false</source> <translation type="unfinished"/> </message> <message> <location line="-211"/> <source>, has not been successfully broadcast yet</source> <translation>, još nije bio uspješno emitiran</translation> </message> <message> <location line="+35"/> <source>unknown</source> <translation>nepoznato</translation> </message> </context> <context> <name>TransactionDescDialog</name> <message> <location filename="../forms/transactiondescdialog.ui" line="+14"/> <source>Transaction details</source> <translation>Detalji transakcije</translation> </message> <message> <location line="+6"/> <source>This pane shows a detailed description of the transaction</source> <translation>Ova panela prikazuje detaljni opis transakcije</translation> </message> </context> <context> <name>TransactionTableModel</name> <message> <location filename="../transactiontablemodel.cpp" line="+226"/> <source>Date</source> <translation>Datum</translation> </message> <message> <location line="+0"/> <source>Type</source> <translation>Tip</translation> </message> <message> <location line="+0"/> <source>Address</source> <translation>Adresa</translation> </message> <message> <location line="+0"/> <source>Amount</source> <translation>Iznos</translation> </message> <message> <location line="+60"/> <source>Open until %1</source> <translation>Otvoren do %1</translation> </message> <message> <location line="+12"/> <source>Confirmed (%1 confirmations)</source> <translation>Potvrđen (%1 potvrda)</translation> </message> <message numerus="yes"> <location line="-15"/> <source>Open for %n more block(s)</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform></translation> </message> <message> <location line="+6"/> <source>Offline</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Unconfirmed</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Confirming (%1 of %2 recommended confirmations)</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <source>Conflicted</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Immature (%1 confirmations, will be available after %2)</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>This block was not received by any other nodes and will probably not be accepted!</source> <translation>Generirano - Upozorenje: ovaj blok nije bio primljen od strane bilo kojeg drugog noda i vjerojatno neće biti prihvaćen!</translation> </message> <message> <location line="+3"/> <source>Generated but not accepted</source> <translation>Generirano, ali nije prihvaćeno</translation> </message> <message> <location line="+42"/> <source>Received with</source> <translation>Primljeno s</translation> </message> <message> <location line="+2"/> <source>Received from</source> <translation>Primljeno od</translation> </message> <message> <location line="+3"/> <source>Sent to</source> <translation>Poslano za</translation> </message> <message> <location line="+2"/> <source>Payment to yourself</source> <translation>Plaćanje samom sebi</translation> </message> <message> <location line="+2"/> <source>Mined</source> <translation>Rudareno</translation> </message> <message> <location line="+38"/> <source>(n/a)</source> <translation>(n/d)</translation> </message> <message> <location line="+190"/> <source>Transaction status. Hover over this field to show number of confirmations.</source> <translation>Status transakcije</translation> </message> <message> <location line="+2"/> <source>Date and time that the transaction was received.</source> <translation>Datum i vrijeme kad je transakcija primljena</translation> </message> <message> <location line="+2"/> <source>Type of transaction.</source> <translation>Vrsta transakcije.</translation> </message> <message> <location line="+2"/> <source>Destination address of transaction.</source> <translation>Odredište transakcije</translation> </message> <message> <location line="+2"/> <source>Amount removed from or added to balance.</source> <translation>Iznos odbijen od ili dodan k saldu.</translation> </message> </context> <context> <name>TransactionView</name> <message> <location filename="../transactionview.cpp" line="+55"/> <location line="+16"/> <source>All</source> <translation>Sve</translation> </message> <message> <location line="-15"/> <source>Today</source> <translation>Danas</translation> </message> <message> <location line="+1"/> <source>This week</source> <translation>Ovaj tjedan</translation> </message> <message> <location line="+1"/> <source>This month</source> <translation>Ovaj mjesec</translation> </message> <message> <location line="+1"/> <source>Last month</source> <translation>Prošli mjesec</translation> </message> <message> <location line="+1"/> <source>This year</source> <translation>Ove godine</translation> </message> <message> <location line="+1"/> <source>Range...</source> <translation>Raspon...</translation> </message> <message> <location line="+11"/> <source>Received with</source> <translation>Primljeno s</translation> </message> <message> <location line="+2"/> <source>Sent to</source> <translation>Poslano za</translation> </message> <message> <location line="+2"/> <source>To yourself</source> <translation>Tebi</translation> </message> <message> <location line="+1"/> <source>Mined</source> <translation>Rudareno</translation> </message> <message> <location line="+1"/> <source>Other</source> <translation>Ostalo</translation> </message> <message> <location line="+7"/> <source>Enter address or label to search</source> <translation>Unesite adresu ili oznaku za pretraživanje</translation> </message> <message> <location line="+7"/> <source>Min amount</source> <translation>Min iznos</translation> </message> <message> <location line="+34"/> <source>Copy address</source> <translation>Kopirati adresu</translation> </message> <message> <location line="+1"/> <source>Copy label</source> <translation>Kopirati oznaku</translation> </message> <message> <location line="+1"/> <source>Copy amount</source> <translation>Kopiraj iznos</translation> </message> <message> <location line="+1"/> <source>Copy transaction ID</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Edit label</source> <translation>Izmjeniti oznaku</translation> </message> <message> <location line="+1"/> <source>Show transaction details</source> <translation type="unfinished"/> </message> <message> <location line="+144"/> <source>Export Transaction Data</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Comma separated file (*.csv)</source> <translation>Datoteka podataka odvojenih zarezima (*.csv)</translation> </message> <message> <location line="+8"/> <source>Confirmed</source> <translation>Potvrđeno</translation> </message> <message> <location line="+1"/> <source>Date</source> <translation>Datum</translation> </message> <message> <location line="+1"/> <source>Type</source> <translation>Tip</translation> </message> <message> <location line="+1"/> <source>Label</source> <translation>Oznaka</translation> </message> <message> <location line="+1"/> <source>Address</source> <translation>Adresa</translation> </message> <message> <location line="+1"/> <source>Amount</source> <translation>Iznos</translation> </message> <message> <location line="+1"/> <source>ID</source> <translation>ID</translation> </message> <message> <location line="+4"/> <source>Error exporting</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>Could not write to file %1.</source> <translation type="unfinished"/> </message> <message> <location line="+100"/> <source>Range:</source> <translation>Raspon:</translation> </message> <message> <location line="+8"/> <source>to</source> <translation>za</translation> </message> </context> <context> <name>WalletModel</name> <message> <location filename="../walletmodel.cpp" line="+206"/> <source>Sending...</source> <translation type="unfinished"/> </message> </context> <context> <name>bitcoin-core</name> <message> <location filename="../bitcoinstrings.cpp" line="+33"/> <source>Fuelcoin version</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Usage:</source> <translation>Upotreba:</translation> </message> <message> <location line="+1"/> <source>Send command to -server or Fuelcoind</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>List commands</source> <translation>Prikaži komande</translation> </message> <message> <location line="+1"/> <source>Get help for a command</source> <translation>Potraži pomoć za komandu</translation> </message> <message> <location line="+2"/> <source>Options:</source> <translation>Postavke:</translation> </message> <message> <location line="+2"/> <source>Specify configuration file (default: Fuelcoin.conf)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Specify pid file (default: Fuelcoind.pid)</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Specify wallet file (within data directory)</source> <translation type="unfinished"/> </message> <message> <location line="-1"/> <source>Specify data directory</source> <translation>Odredi direktorij za datoteke</translation> </message> <message> <location line="+2"/> <source>Set database cache size in megabytes (default: 25)</source> <translation>Postavi cache za bazu podataka u MB (zadano:25)</translation> </message> <message> <location line="+1"/> <source>Set database disk log size in megabytes (default: 100)</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <source>Listen for connections on &lt;port&gt; (default: 15714 or testnet: 25714)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Maintain at most &lt;n&gt; connections to peers (default: 125)</source> <translation>Održavaj najviše &lt;n&gt; veza sa članovima (default: 125)</translation> </message> <message> <location line="+3"/> <source>Connect to a node to retrieve peer addresses, and disconnect</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Specify your own public address</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Bind to given address. Use [host]:port notation for IPv6</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Stake your coins to support network and gain reward (default: 1)</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Threshold for disconnecting misbehaving peers (default: 100)</source> <translation>Prag za odspajanje članova koji se čudno ponašaju (default: 100)</translation> </message> <message> <location line="+1"/> <source>Number of seconds to keep misbehaving peers from reconnecting (default: 86400)</source> <translation>Broj sekundi koliko se članovima koji se čudno ponašaju neće dopustiti da se opet spoje (default: 86400)</translation> </message> <message> <location line="-44"/> <source>An error occurred while setting up the RPC port %u for listening on IPv4: %s</source> <translation type="unfinished"/> </message> <message> <location line="+51"/> <source>Detach block and address databases. Increases shutdown time (default: 0)</source> <translation type="unfinished"/> </message> <message> <location line="+109"/> <source>Error: The transaction was rejected. This might happen if some of the coins in your wallet were already spent, such as if you used a copy of wallet.dat and coins were spent in the copy but not marked as spent here.</source> <translation type="unfinished"/> </message> <message> <location line="-5"/> <source>Error: This transaction requires a transaction fee of at least %s because of its amount, complexity, or use of recently received funds </source> <translation type="unfinished"/> </message> <message> <location line="-87"/> <source>Listen for JSON-RPC connections on &lt;port&gt; (default: 15715 or testnet: 25715)</source> <translation type="unfinished"/> </message> <message> <location line="-11"/> <source>Accept command line and JSON-RPC commands</source> <translation>Prihvati komande iz tekst moda i JSON-RPC</translation> </message> <message> <location line="+101"/> <source>Error: Transaction creation failed </source> <translation type="unfinished"/> </message> <message> <location line="-5"/> <source>Error: Wallet locked, unable to create transaction </source> <translation type="unfinished"/> </message> <message> <location line="-8"/> <source>Importing blockchain data file.</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Importing bootstrap blockchain data file.</source> <translation type="unfinished"/> </message> <message> <location line="-88"/> <source>Run in the background as a daemon and accept commands</source> <translation>Izvršavaj u pozadini kao uslužnik i prihvaćaj komande</translation> </message> <message> <location line="+1"/> <source>Use the test network</source> <translation>Koristi test mrežu</translation> </message> <message> <location line="-24"/> <source>Accept connections from outside (default: 1 if no -proxy or -connect)</source> <translation type="unfinished"/> </message> <message> <location line="-38"/> <source>An error occurred while setting up the RPC port %u for listening on IPv6, falling back to IPv4: %s</source> <translation type="unfinished"/> </message> <message> <location line="+117"/> <source>Error initializing database environment %s! To recover, BACKUP THAT DIRECTORY, then remove everything from it except for wallet.dat.</source> <translation type="unfinished"/> </message> <message> <location line="-20"/> <source>Set maximum size of high-priority/low-fee transactions in bytes (default: 27000)</source> <translation type="unfinished"/> </message> <message> <location line="+11"/> <source>Warning: -paytxfee is set very high! This is the transaction fee you will pay if you send a transaction.</source> <translation>Upozorenje: -paytxfee je podešen na preveliki iznos. To je iznos koji ćete platiti za obradu transakcije.</translation> </message> <message> <location line="+61"/> <source>Warning: Please check that your computer&apos;s date and time are correct! If your clock is wrong Fuelcoin will not work properly.</source> <translation type="unfinished"/> </message> <message> <location line="-31"/> <source>Warning: error reading wallet.dat! All keys read correctly, but transaction data or address book entries might be missing or incorrect.</source> <translation type="unfinished"/> </message> <message> <location line="-18"/> <source>Warning: wallet.dat corrupt, data salvaged! Original wallet.dat saved as wallet.{timestamp}.bak in %s; if your balance or transactions are incorrect you should restore from a backup.</source> <translation type="unfinished"/> </message> <message> <location line="-30"/> <source>Attempt to recover private keys from a corrupt wallet.dat</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>Block creation options:</source> <translation>Opcije za kreiranje bloka:</translation> </message> <message> <location line="-62"/> <source>Connect only to the specified node(s)</source> <translation>Poveži se samo sa određenim nodom</translation> </message> <message> <location line="+4"/> <source>Discover own IP address (default: 1 when listening and no -externalip)</source> <translation type="unfinished"/> </message> <message> <location line="+94"/> <source>Failed to listen on any port. Use -listen=0 if you want this.</source> <translation type="unfinished"/> </message> <message> <location line="-90"/> <source>Find peers using DNS lookup (default: 1)</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Sync checkpoints policy (default: strict)</source> <translation type="unfinished"/> </message> <message> <location line="+83"/> <source>Invalid -tor address: &apos;%s&apos;</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>Invalid amount for -reservebalance=&lt;amount&gt;</source> <translation type="unfinished"/> </message> <message> <location line="-82"/> <source>Maximum per-connection receive buffer, &lt;n&gt;*1000 bytes (default: 5000)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Maximum per-connection send buffer, &lt;n&gt;*1000 bytes (default: 1000)</source> <translation type="unfinished"/> </message> <message> <location line="-16"/> <source>Only connect to nodes in network &lt;net&gt; (IPv4, IPv6 or Tor)</source> <translation type="unfinished"/> </message> <message> <location line="+28"/> <source>Output extra debugging information. Implies all other -debug* options</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Output extra network debugging information</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Prepend debug output with timestamp</source> <translation type="unfinished"/> </message> <message> <location line="+35"/> <source>SSL options: (see the Bitcoin Wiki for SSL setup instructions)</source> <translation>SSL postavke: (za detalje o podešavanju SSL opcija vidi Bitcoin Wiki)</translation> </message> <message> <location line="-74"/> <source>Select the version of socks proxy to use (4-5, default: 5)</source> <translation type="unfinished"/> </message> <message> <location line="+41"/> <source>Send trace/debug info to console instead of debug.log file</source> <translation>Šalji trace/debug informacije na konzolu umjesto u debug.log datoteku</translation> </message> <message> <location line="+1"/> <source>Send trace/debug info to debugger</source> <translation type="unfinished"/> </message> <message> <location line="+28"/> <source>Set maximum block size in bytes (default: 250000)</source> <translation type="unfinished"/> </message> <message> <location line="-1"/> <source>Set minimum block size in bytes (default: 0)</source> <translation>Podesite minimalnu veličinu bloka u bajtovima (default: 0)</translation> </message> <message> <location line="-29"/> <source>Shrink debug.log file on client startup (default: 1 when no -debug)</source> <translation type="unfinished"/> </message> <message> <location line="-42"/> <source>Specify connection timeout in milliseconds (default: 5000)</source> <translation>Odredi vremenski prozor za spajanje na mrežu u milisekundama (ugrađeni izbor: 5000)</translation> </message> <message> <location line="+109"/> <source>Unable to sign checkpoint, wrong checkpointkey? </source> <translation type="unfinished"/> </message> <message> <location line="-80"/> <source>Use UPnP to map the listening port (default: 0)</source> <translation>Pokušaj koristiti UPnP da otvoriš port za uslugu (default: 0)</translation> </message> <message> <location line="-1"/> <source>Use UPnP to map the listening port (default: 1 when listening)</source> <translation>Pokušaj koristiti UPnP da otvoriš port za uslugu (default: 1 when listening)</translation> </message> <message> <location line="-25"/> <source>Use proxy to reach tor hidden services (default: same as -proxy)</source> <translation type="unfinished"/> </message> <message> <location line="+42"/> <source>Username for JSON-RPC connections</source> <translation>Korisničko ime za JSON-RPC veze</translation> </message> <message> <location line="+47"/> <source>Verifying database integrity...</source> <translation type="unfinished"/> </message> <message> <location line="+57"/> <source>WARNING: syncronized checkpoint violation detected, but skipped!</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Warning: Disk space is low!</source> <translation type="unfinished"/> </message> <message> <location line="-2"/> <source>Warning: This version is obsolete, upgrade required!</source> <translation type="unfinished"/> </message> <message> <location line="-48"/> <source>wallet.dat corrupt, salvage failed</source> <translation type="unfinished"/> </message> <message> <location line="-54"/> <source>Password for JSON-RPC connections</source> <translation>Lozinka za JSON-RPC veze</translation> </message> <message> <location line="-84"/> <source>%s, you must set a rpcpassword in the configuration file: %s It is recommended you use the following random password: rpcuser=Fuelcoinrpc rpcpassword=%s (you do not need to remember this password) The username and password MUST NOT be the same. If the file does not exist, create it with owner-readable-only file permissions. It is also recommended to set alertnotify so you are notified of problems; for example: alertnotify=echo %%s | mail -s &quot;Fuelcoin Alert&quot; [email protected] </source> <translation type="unfinished"/> </message> <message> <location line="+51"/> <source>Find peers using internet relay chat (default: 0)</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Sync time with other nodes. Disable if time on your system is precise e.g. syncing with NTP (default: 1)</source> <translation type="unfinished"/> </message> <message> <location line="+15"/> <source>When creating transactions, ignore inputs with value less than this (default: 0.01)</source> <translation type="unfinished"/> </message> <message> <location line="+16"/> <source>Allow JSON-RPC connections from specified IP address</source> <translation>Dozvoli JSON-RPC povezivanje s određene IP adrese</translation> </message> <message> <location line="+1"/> <source>Send commands to node running on &lt;ip&gt; (default: 127.0.0.1)</source> <translation>Pošalji komande nodu na adresi &lt;ip&gt; (ugrađeni izbor: 127.0.0.1)</translation> </message> <message> <location line="+1"/> <source>Execute command when the best block changes (%s in cmd is replaced by block hash)</source> <translation>Izvršite naredbu kada se najbolji blok promjeni (%s u cmd je zamjenjen sa block hash)</translation> </message> <message> <location line="+3"/> <source>Execute command when a wallet transaction changes (%s in cmd is replaced by TxID)</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Require a confirmations for change (default: 0)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Enforce transaction scripts to use canonical PUSH operators (default: 1)</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Execute command when a relevant alert is received (%s in cmd is replaced by message)</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Upgrade wallet to latest format</source> <translation>Nadogradite novčanik u posljednji format.</translation> </message> <message> <location line="+1"/> <source>Set key pool size to &lt;n&gt; (default: 100)</source> <translation>Podesi memorijski prostor za ključeve na &lt;n&gt; (ugrađeni izbor: 100)</translation> </message> <message> <location line="+1"/> <source>Rescan the block chain for missing wallet transactions</source> <translation>Ponovno pretraži lanac blokova za transakcije koje nedostaju</translation> </message> <message> <location line="+2"/> <source>How many blocks to check at startup (default: 2500, 0 = all)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>How thorough the block verification is (0-6, default: 1)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Imports blocks from external blk000?.dat file</source> <translation type="unfinished"/> </message> <message> <location line="+8"/> <source>Use OpenSSL (https) for JSON-RPC connections</source> <translation>Koristi OpenSSL (https) za JSON-RPC povezivanje</translation> </message> <message> <location line="+1"/> <source>Server certificate file (default: server.cert)</source> <translation>Uslužnikov SSL certifikat (ugrađeni izbor: server.cert)</translation> </message> <message> <location line="+1"/> <source>Server private key (default: server.pem)</source> <translation>Uslužnikov privatni ključ (ugrađeni izbor: server.pem)</translation> </message> <message> <location line="+1"/> <source>Acceptable ciphers (default: TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH)</source> <translation type="unfinished"/> </message> <message> <location line="+53"/> <source>Error: Wallet unlocked for staking only, unable to create transaction.</source> <translation type="unfinished"/> </message> <message> <location line="+18"/> <source>WARNING: Invalid checkpoint found! Displayed transactions may not be correct! You may need to upgrade, or notify developers.</source> <translation type="unfinished"/> </message> <message> <location line="-158"/> <source>This help message</source> <translation>Ova poruka za pomoć</translation> </message> <message> <location line="+95"/> <source>Wallet %s resides outside data directory %s.</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Cannot obtain a lock on data directory %s. Fuelcoin is probably already running.</source> <translation type="unfinished"/> </message> <message> <location line="-98"/> <source>Fuelcoin</source> <translation type="unfinished"/> </message> <message> <location line="+140"/> <source>Unable to bind to %s on this computer (bind returned error %d, %s)</source> <translation>Program ne može koristiti %s na ovom računalu (bind returned error %d, %s)</translation> </message> <message> <location line="-130"/> <source>Connect through socks proxy</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Allow DNS lookups for -addnode, -seednode and -connect</source> <translation>Dozvoli DNS upite za dodavanje nodova i povezivanje</translation> </message> <message> <location line="+122"/> <source>Loading addresses...</source> <translation>Učitavanje adresa...</translation> </message> <message> <location line="-15"/> <source>Error loading blkindex.dat</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Error loading wallet.dat: Wallet corrupted</source> <translation>Greška kod učitavanja wallet.dat: Novčanik pokvaren</translation> </message> <message> <location line="+4"/> <source>Error loading wallet.dat: Wallet requires newer version of Fuelcoin</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Wallet needed to be rewritten: restart Fuelcoin to complete</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Error loading wallet.dat</source> <translation>Greška kod učitavanja wallet.dat</translation> </message> <message> <location line="-16"/> <source>Invalid -proxy address: &apos;%s&apos;</source> <translation>Nevaljala -proxy adresa: &apos;%s&apos;</translation> </message> <message> <location line="-1"/> <source>Unknown network specified in -onlynet: &apos;%s&apos;</source> <translation type="unfinished"/> </message> <message> <location line="-1"/> <source>Unknown -socks proxy version requested: %i</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>Cannot resolve -bind address: &apos;%s&apos;</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Cannot resolve -externalip address: &apos;%s&apos;</source> <translation type="unfinished"/> </message> <message> <location line="-24"/> <source>Invalid amount for -paytxfee=&lt;amount&gt;: &apos;%s&apos;</source> <translation>Nevaljali iznos za opciju -paytxfee=&lt;amount&gt;: &apos;%s&apos;</translation> </message> <message> <location line="+44"/> <source>Error: could not start node</source> <translation type="unfinished"/> </message> <message> <location line="+11"/> <source>Sending...</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Invalid amount</source> <translation>Nevaljali iznos za opciju</translation> </message> <message> <location line="+1"/> <source>Insufficient funds</source> <translation>Nedovoljna sredstva</translation> </message> <message> <location line="-34"/> <source>Loading block index...</source> <translation>Učitavanje indeksa blokova...</translation> </message> <message> <location line="-103"/> <source>Add a node to connect to and attempt to keep the connection open</source> <translation>Unesite nod s kojim se želite spojiti and attempt to keep the connection open</translation> </message> <message> <location line="+122"/> <source>Unable to bind to %s on this computer. Fuelcoin is probably already running.</source> <translation type="unfinished"/> </message> <message> <location line="-97"/> <source>Fee per KB to add to transactions you send</source> <translation type="unfinished"/> </message> <message> <location line="+55"/> <source>Invalid amount for -mininput=&lt;amount&gt;: &apos;%s&apos;</source> <translation type="unfinished"/> </message> <message> <location line="+25"/> <source>Loading wallet...</source> <translation>Učitavanje novčanika...</translation> </message> <message> <location line="+8"/> <source>Cannot downgrade wallet</source> <translation>Nije moguće novčanik vratiti na prijašnju verziju.</translation> </message> <message> <location line="+1"/> <source>Cannot initialize keypool</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Cannot write default address</source> <translation>Nije moguće upisati zadanu adresu.</translation> </message> <message> <location line="+1"/> <source>Rescanning...</source> <translation>Rescaniranje</translation> </message> <message> <location line="+5"/> <source>Done loading</source> <translation>Učitavanje gotovo</translation> </message> <message> <location line="-167"/> <source>To use the %s option</source> <translation type="unfinished"/> </message> <message> <location line="+14"/> <source>Error</source> <translation>Greška</translation> </message> <message> <location line="+6"/> <source>You must set rpcpassword=&lt;password&gt; in the configuration file: %s If the file does not exist, create it with owner-readable-only file permissions.</source> <translation type="unfinished"/> </message> </context> </TS>
{ "content_hash": "b8ebbb6edc9bee32569a5d209acd876d", "timestamp": "", "source": "github", "line_count": 3289, "max_line_length": 395, "avg_line_length": 34.7187595013682, "alnum_prop": 0.6009720641036869, "repo_name": "FuelCoinTwo/Fuelcoin", "id": "03d1c5eb81a045bf4fab06b42d649d9b3a8f3340", "size": "114390", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/qt/locale/bitcoin_hr.ts", "mode": "33188", "license": "mit", "language": [ { "name": "Assembly", "bytes": "51312" }, { "name": "C", "bytes": "706674" }, { "name": "C++", "bytes": "2615419" }, { "name": "CSS", "bytes": "1127" }, { "name": "HTML", "bytes": "50615" }, { "name": "Makefile", "bytes": "11965" }, { "name": "NSIS", "bytes": "5914" }, { "name": "Objective-C", "bytes": "858" }, { "name": "Objective-C++", "bytes": "3536" }, { "name": "Python", "bytes": "2819" }, { "name": "QMake", "bytes": "15428" }, { "name": "Shell", "bytes": "8201" } ], "symlink_target": "" }
namespace ZooBurst.Core.Tiles { public abstract class BaseTile : ITile { } }
{ "content_hash": "4974e8f64674ee61078766e9d081174d", "timestamp": "", "source": "github", "line_count": 6, "max_line_length": 42, "avg_line_length": 14.833333333333334, "alnum_prop": 0.651685393258427, "repo_name": "MSigma/ZooBurst", "id": "9425c8552214edef4866a842a2d2204ad3409e4c", "size": "91", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Core/Tiles/BaseTile.cs", "mode": "33188", "license": "mit", "language": [ { "name": "C#", "bytes": "141789" } ], "symlink_target": "" }
/* ---------------------------------------------------------------------------- * This file was automatically generated by SWIG (http://www.swig.org). * Version 3.0.12 * * Do not make changes to this file unless you know what you are doing--modify * the SWIG interface file instead. * ----------------------------------------------------------------------------- */ package com.frostwire.jlibtorrent.swig; public class bitset_96 { private transient long swigCPtr; protected transient boolean swigCMemOwn; protected bitset_96(long cPtr, boolean cMemoryOwn) { swigCMemOwn = cMemoryOwn; swigCPtr = cPtr; } protected static long getCPtr(bitset_96 obj) { return (obj == null) ? 0 : obj.swigCPtr; } protected void finalize() { delete(); } public synchronized void delete() { if (swigCPtr != 0) { if (swigCMemOwn) { swigCMemOwn = false; libtorrent_jni.delete_bitset_96(swigCPtr); } swigCPtr = 0; } } public boolean test(long pos) { return libtorrent_jni.bitset_96_test(swigCPtr, this, pos); } public boolean all() { return libtorrent_jni.bitset_96_all(swigCPtr, this); } public boolean any() { return libtorrent_jni.bitset_96_any(swigCPtr, this); } public boolean none() { return libtorrent_jni.bitset_96_none(swigCPtr, this); } public long count() { return libtorrent_jni.bitset_96_count(swigCPtr, this); } public long size() { return libtorrent_jni.bitset_96_size(swigCPtr, this); } public boolean get(long pos) { return libtorrent_jni.bitset_96_get(swigCPtr, this, pos); } public bitset_96() { this(libtorrent_jni.new_bitset_96(), true); } }
{ "content_hash": "14726a2b0cba945cf3413670807d9691", "timestamp": "", "source": "github", "line_count": 70, "max_line_length": 83, "avg_line_length": 24.3, "alnum_prop": 0.599647266313933, "repo_name": "gubatron/frostwire-jlibtorrent", "id": "183c212cb97fc6e31921ff436f97de1a7ff144cc", "size": "1701", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "src/main/java/com/frostwire/jlibtorrent/swig/bitset_96.java", "mode": "33188", "license": "mit", "language": [ { "name": "C++", "bytes": "2641642" }, { "name": "Java", "bytes": "1672682" }, { "name": "SWIG", "bytes": "71375" }, { "name": "Shell", "bytes": "28446" } ], "symlink_target": "" }
package flog import ( "bufio" "net" "net/http" "net/http/httptest" "testing" "time" ) type closeNotifyingRecorder struct { *httptest.ResponseRecorder closed chan bool } func newCloseNotifyingRecorder() *closeNotifyingRecorder { return &closeNotifyingRecorder{ httptest.NewRecorder(), make(chan bool, 1), } } func (c *closeNotifyingRecorder) close() { c.closed <- true } func (c *closeNotifyingRecorder) CloseNotify() <-chan bool { return c.closed } type hijackableResponse struct { Hijacked bool } func newHijackableResponse() *hijackableResponse { return &hijackableResponse{} } func (h *hijackableResponse) Header() http.Header { return nil } func (h *hijackableResponse) Write(buf []byte) (int, error) { return 0, nil } func (h *hijackableResponse) WriteHeader(code int) {} func (h *hijackableResponse) Flush() {} func (h *hijackableResponse) Hijack() (net.Conn, *bufio.ReadWriter, error) { h.Hijacked = true return nil, nil, nil } func Test_ResponseWriter_WritingString(t *testing.T) { rec := httptest.NewRecorder() rw := NewResponseWriter(rec) rw.Write([]byte("Hello world")) expect(t, rec.Code, rw.Status()) expect(t, rec.Body.String(), "Hello world") expect(t, rw.Status(), http.StatusOK) expect(t, rw.Size(), 11) expect(t, rw.Written(), true) } func Test_ResponseWriter_WritingStrings(t *testing.T) { rec := httptest.NewRecorder() rw := NewResponseWriter(rec) rw.Write([]byte("Hello world")) rw.Write([]byte("foo bar bat baz")) expect(t, rec.Code, rw.Status()) expect(t, rec.Body.String(), "Hello worldfoo bar bat baz") expect(t, rw.Status(), http.StatusOK) expect(t, rw.Size(), 26) } func Test_ResponseWriter_WritingHeader(t *testing.T) { rec := httptest.NewRecorder() rw := NewResponseWriter(rec) rw.WriteHeader(http.StatusNotFound) expect(t, rec.Code, rw.Status()) expect(t, rec.Body.String(), "") expect(t, rw.Status(), http.StatusNotFound) expect(t, rw.Size(), 0) } func Test_ResponseWriter_Before(t *testing.T) { rec := httptest.NewRecorder() rw := NewResponseWriter(rec) result := "" rw.Before(func(ResponseWriter) { result += "foo" }) rw.Before(func(ResponseWriter) { result += "bar" }) rw.WriteHeader(http.StatusNotFound) expect(t, rec.Code, rw.Status()) expect(t, rec.Body.String(), "") expect(t, rw.Status(), http.StatusNotFound) expect(t, rw.Size(), 0) expect(t, result, "barfoo") } func Test_ResponseWriter_Hijack(t *testing.T) { hijackable := newHijackableResponse() rw := NewResponseWriter(hijackable) hijacker, ok := rw.(http.Hijacker) expect(t, ok, true) _, _, err := hijacker.Hijack() if err != nil { t.Error(err) } expect(t, hijackable.Hijacked, true) } func Test_ResponseWriter_CloseNotify(t *testing.T) { rec := newCloseNotifyingRecorder() rw := NewResponseWriter(rec) closed := false notifier := rw.(http.CloseNotifier).CloseNotify() rec.close() select { case <-notifier: closed = true case <-time.After(time.Second): } expect(t, closed, true) }
{ "content_hash": "145c3065f0c1d08fe3e99841269babad", "timestamp": "", "source": "github", "line_count": 132, "max_line_length": 77, "avg_line_length": 22.90909090909091, "alnum_prop": 0.6884920634920635, "repo_name": "fc-thrisp-hurrata-dlm-graveyard/flog", "id": "5f6e4c25fbeb42d3dbff155b0f0f3b3cafb8077d", "size": "3024", "binary": false, "copies": "1", "ref": "refs/heads/develop", "path": "response_writer_test.go", "mode": "33188", "license": "mit", "language": [ { "name": "Go", "bytes": "36935" } ], "symlink_target": "" }
<?php namespace WellCommerce\Extra\OrderBundle\Entity; trait OrderStatusHistoryExtraTrait { }
{ "content_hash": "4c32ef2835568ff100fc82eb0591b89f", "timestamp": "", "source": "github", "line_count": 8, "max_line_length": 48, "avg_line_length": 12.125, "alnum_prop": 0.8144329896907216, "repo_name": "diversantvlz/WellCommerce", "id": "2c53d085f82a14ad14849c7fddfe0d48b73a7e0f", "size": "97", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "src/WellCommerce/Extra/OrderBundle/Entity/OrderStatusHistoryExtraTrait.php", "mode": "33188", "license": "mit", "language": [ { "name": "ApacheConf", "bytes": "2766" }, { "name": "CSS", "bytes": "510559" }, { "name": "HTML", "bytes": "296382" }, { "name": "JavaScript", "bytes": "5595098" }, { "name": "PHP", "bytes": "2691745" } ], "symlink_target": "" }
 using System; using XenAdmin.Core; using XenAdmin.Diagnostics.Problems; using XenAdmin.Diagnostics.Problems.ConnectionProblem; using XenAPI; namespace XenAdmin.Diagnostics.Checks { public class UpgradingFromTampaAndOlderCheck : Check { public UpgradingFromTampaAndOlderCheck(Host host) : base(host) { } protected override Problem RunCheck() { bool licenseStatus = !Host.IsFreeLicense() || Host.InGrace; return !Helpers.ClearwaterOrGreater(Host) && licenseStatus ? new UpgradingFromTampaAndOlderWarning(this, Host) : null; } public override string Description { get { return String.Format(Messages.HOST_X, Host.Name); } } } }
{ "content_hash": "c94ff1700933cdc8577440fb79e6098c", "timestamp": "", "source": "github", "line_count": 28, "max_line_length": 130, "avg_line_length": 27.821428571428573, "alnum_prop": 0.6431322207958922, "repo_name": "Frezzle/xenadmin", "id": "2019279dd4f510d7e51d3b31fbb787e61cdb8e6e", "size": "2238", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "XenAdmin/Diagnostics/Checks/UpgradingFromTampaAndOlderCheck.cs", "mode": "33188", "license": "bsd-2-clause", "language": [ { "name": "Batchfile", "bytes": "608" }, { "name": "C", "bytes": "1955" }, { "name": "C#", "bytes": "16460939" }, { "name": "C++", "bytes": "21642" }, { "name": "CSS", "bytes": "11145" }, { "name": "HTML", "bytes": "4212" }, { "name": "JavaScript", "bytes": "829" }, { "name": "PowerShell", "bytes": "40" }, { "name": "Shell", "bytes": "89873" }, { "name": "Visual Basic", "bytes": "11647" } ], "symlink_target": "" }
package repository.mongo; import com.fasterxml.jackson.databind.JsonNode; import com.google.inject.Inject; import com.mongodb.BasicDBObject; import com.mongodb.Block; import com.mongodb.client.FindIterable; import com.mongodb.client.MongoCollection; import com.mongodb.client.model.CountOptions; import com.mongodb.client.model.Projections; import org.bson.Document; import org.bson.types.ObjectId; import play.libs.Json; import repository.ICollectionContentRepository; import repository.mongo.driver.IDbStore; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.Map; /** * Created by mitesh on 27/12/16. */ public class AlternateCollectionContentRepository extends BaseSlaveRepository implements ICollectionContentRepository { private static final String COLLECTION_NAME = "collection_contents"; @Inject public AlternateCollectionContentRepository(IDbStore dbStore) { super(dbStore); } @Override public String create(String collectionName, JsonNode jsonNode) { MongoCollection<Document> collection = this.nativeStore.getCollection(COLLECTION_NAME); Document document = getDocumentFromJsonNode(jsonNode); document.put("collectionName", collectionName); collection.insertOne(document); return document.toJson(); } @Override public String update(String collectionName, String contentId, JsonNode jsonNode) { MongoCollection<Document> collection = this.nativeStore.getCollection(COLLECTION_NAME); BasicDBObject filterQuery = new BasicDBObject(); filterQuery.put("_id", contentId); filterQuery.put("collectionName", collectionName); BasicDBObject updateParams = new BasicDBObject(); Iterator<Map.Entry<String, JsonNode>> nodes = jsonNode.fields(); while (nodes.hasNext()) { Map.Entry<String, JsonNode> entry = nodes.next(); if (entry.getKey().equals("id") || entry.getKey().equals("envId") || entry.getKey().equals("collectionName")) { continue; } if (entry.getValue() != null) { updateParams.put(entry.getKey(), entry.getValue().asText()); } } Document document = collection.findOneAndUpdate(filterQuery, updateParams); return document.toJson(); } @Override public String getByEnv(String collectionName, String envId, String userId, int offset, int limit, String sortBy, String orderBy, int isCountNeeded, String filters) { List<Document> responseJson = new ArrayList<>(); MongoCollection<Document> collection = this.nativeStore.getCollection(COLLECTION_NAME); BasicDBObject whereQuery = new BasicDBObject(); whereQuery.put("envId", envId); whereQuery.put("collectionName", collectionName); if (userId != null && !"".equals(userId)) { whereQuery.put("userId", userId); } if (isCountNeeded == 1) { CountOptions countOptions = new CountOptions(); if (offset != -1) { countOptions.skip(offset); } if (limit != -1) { countOptions.limit(limit); } long count = collection.count(whereQuery); return "{'count': "+count+"}"; } else { FindIterable<Document> iterable = collection.find(whereQuery); if (offset != -1) { iterable.skip(offset); } if (limit != -1) { iterable.limit(limit); } if (filters != null && !"".equals(filters)) { String[] filterArr = filters.split(","); iterable.projection(Projections.include(filterArr)); } if (sortBy != null) { BasicDBObject sortObject = new BasicDBObject(); int isAsc = 1; if (orderBy != null) { isAsc = orderBy.equals("ASC") ? 1 : -1; } sortObject.put(sortBy, isAsc); iterable.sort(sortObject); } iterable.forEach(new Block<Document>() { public void apply(final Document document) { document.remove("envId"); document.remove("userId"); document.remove("collectionName"); document.remove("contentState"); document.remove("contentVersion"); ObjectId _id = document.getObjectId("_id"); document.remove("_id"); document.put("id", _id.toString()); responseJson.add(document); } }); return Json.stringify(Json.toJson(responseJson)); } } @Override public String getById(String collectionName, String contentId) { Document document = getByIdWithDocument(collectionName, contentId); if (document != null) { return document.toJson(); } return ""; } @Override public Document getByIdWithDocument(String collectionName, String contentId) { List<Document> responseDocuments = new ArrayList<>(); MongoCollection<Document> collection = this.nativeStore.getCollection(COLLECTION_NAME); BasicDBObject whereQuery = new BasicDBObject(); whereQuery.put("_id", new ObjectId(contentId)); whereQuery.put("collectionName", collectionName); FindIterable<Document> iterable = collection.find(whereQuery); iterable.forEach(new Block<Document>() { public void apply(final Document document) { document.remove("envId"); document.remove("userId"); document.remove("collectionName"); document.remove("contentState"); document.remove("contentVersion"); ObjectId _id = document.getObjectId("_id"); document.remove("_id"); document.put("id", _id.toString()); responseDocuments.add(document); } }); if (responseDocuments.size() > 0) { return responseDocuments.get(0); } return null; } }
{ "content_hash": "c4f8abbea882545b28359de0fda97054", "timestamp": "", "source": "github", "line_count": 161, "max_line_length": 123, "avg_line_length": 39.2360248447205, "alnum_prop": 0.5996517334177616, "repo_name": "MiteshSharma/ContentApi", "id": "aa3302e86a4c88653a08bde88ae0e89176e24131", "size": "6317", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "app/repository/mongo/AlternateCollectionContentRepository.java", "mode": "33188", "license": "mit", "language": [ { "name": "Java", "bytes": "235775" }, { "name": "JavaScript", "bytes": "36666" }, { "name": "Scala", "bytes": "2878" } ], "symlink_target": "" }
name: install category: getstarted tags: guide index: 0 title: WebdriverIO - Install --- # Install You will need to have [Node.js](http://nodejs.org/) and [NPM](https://www.npmjs.org/) installed on your machine. Check out their project websites for more instructions. If you want to have WebdriverIO integrated into your test suite, then install it locally with: ```sh $ npm install webdriverio --save-dev ``` The test runner is called `wdio` and should be available after the install was successful: ```sh $ ./node_modules/.bin/wdio --help ``` ## Set up your Selenium environment There are two ways of setting up your Selenium environment: as a standalone package or by installing the server and browser driver separately. ### Use of existing standalone package The simplest way to get started is to use one of the NPM selenium standalone packages like: [vvo/selenium-standalone](https://github.com/vvo/selenium-standalone). After installing it (globally) you can run your server by executing: ```sh $ selenium-standalone start ``` To install the Selenium Server and Chromedriver (if necessary) separately: First you must run a selenium standalone server on your machine. You will get the newest version [here](http://docs.seleniumhq.org/download/). Just download the jar file somewhere on your system. After that start your terminal and execute the file via ```sh $ java -jar /your/download/directory/selenium-server-standalone-2.42.2.jar ``` The standalone server comes with some integrated drivers (for Firefox, Opera and Safari) which enhance your installed browser to get navigated through the server by the JSONWire protocol. ## Setup Chromedriver [Chromedriver](https://sites.google.com/a/chromium.org/chromedriver/home) is a standalone server which implements WebDriver's wire protocol for Chromium. It is being developed by members of the Chromium and WebDriver teams. For running Chrome browser tests on your local machine you need to download ChromeDriver from the project website and make it available on your machine by setting the PATH to the ChromeDriver executable.
{ "content_hash": "108187a6fa4ef015393687fc37528cf7", "timestamp": "", "source": "github", "line_count": 56, "max_line_length": 263, "avg_line_length": 37.5, "alnum_prop": 0.7814285714285715, "repo_name": "tim-mc/quill", "id": "065a2943554af3049412ad4230dc91b9f7f7438e", "size": "2100", "binary": false, "copies": "4", "ref": "refs/heads/develop", "path": "node_modules/webdriverio/docs/guide/getstarted/install.md", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "CSS", "bytes": "67266" }, { "name": "JavaScript", "bytes": "1468832" }, { "name": "Shell", "bytes": "1198" } ], "symlink_target": "" }
package br.org.piblimeira.util; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; import java.util.GregorianCalendar; import java.util.Locale; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.apache.commons.codec.EncoderException; import org.apache.commons.codec.binary.Base64; import org.apache.commons.lang3.StringUtils; public class Utils { /** * Metodo responsavel por verificar se o e-mail informado eh valido * @ param String email * @return boolean * */ public static boolean isEmailValido(final String email){ final Pattern ptt = Pattern.compile("^[\\w-]+(\\.[\\w-]+)*@([\\w-]+\\.)+[a-zA-Z]{2,3}$"); final Matcher mtc = ptt.matcher(email); return mtc.matches(); } public static String retornarPrimeiroNome(String nome){ if(StringUtils.isNotBlank(nome)){ String[] s = nome.trim().split(" "); return s[0]; } return null; } /** * Obter ano. * @param data * @return int */ public static Integer obterAno(final Date data) { final GregorianCalendar gcData = new GregorianCalendar(); gcData.setTime(data); return gcData.get(Calendar.YEAR); } public static final String StringData(final Date data) { final SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy"); if(data != null) { return formatter.format(data); } return ""; } /** * Obter dia. * * @param data * data * @return int */ public static int obterUltimoDia(Date dataInicial) { Calendar cal = GregorianCalendar.getInstance(); cal.setTime(dataInicial); return cal.getActualMaximum( Calendar.DAY_OF_MONTH ); } /** * Retira m�scara de telefone * */ public static String retirarMascaraTelefone(String telefone){ if (StringUtils.isNotBlank(telefone)) { return retirarEspacoBranco(telefone.replaceAll("[-()+]", "")); } return telefone; } /** * Retira os espacos em branco de uma String * * @param String * @return String */ public static String retirarEspacoBranco(String valor) { if (StringUtils.isNotBlank(valor)) { valor = valor.replaceAll("\\s", ""); } return valor; } /** * To date. * * @param data * the data * @return the date */ public static Date toDate(final String data) { String PATTERN_DATA = "dd/MM/yyyy"; java.util.Date retorno; try { final SimpleDateFormat simpleDateFormat = new SimpleDateFormat(PATTERN_DATA, Locale.getDefault()); retorno = simpleDateFormat.parse(data); } catch (ParseException e) { retorno = null; } return retorno; } /** * * @param conteudo * @return * @throws EncoderException */ public static String criptografarBase64(String conteudo) throws EncoderException { byte[] byteArray = Base64.encodeBase64(conteudo.getBytes()); return new String(byteArray); } /*public static void main(String[] args) throws EncoderException { System.out.println("senha: " + criptografarBase64("168543")); }*/ /** * * @param conteudo * @return * @throws EncoderException */ public static String decriptografarBase64(String conteudo) throws EncoderException { byte[] byteArray = Base64.decodeBase64(conteudo.getBytes()); return new String(byteArray); } /*public static String retornarPrimeiroNome(String nome){ String pattern = "\\S+"; Pattern r = Pattern.compile(pattern); Matcher m = r.matcher(nome); if (m.find( )) { return m.group(0) ; } return ""; }*/ }
{ "content_hash": "390ee03befefe29af0f5f20a0d25cd9a", "timestamp": "", "source": "github", "line_count": 150, "max_line_length": 110, "avg_line_length": 26.086666666666666, "alnum_prop": 0.6084845387170968, "repo_name": "regianemsms/pib", "id": "ea9b7781e72772870872802f4178e7ba922bd354", "size": "3915", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/main/java/br/org/piblimeira/util/Utils.java", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "3202" }, { "name": "HTML", "bytes": "78132" }, { "name": "Java", "bytes": "132213" }, { "name": "JavaScript", "bytes": "12321" }, { "name": "Shell", "bytes": "140" } ], "symlink_target": "" }
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("IronFoundry.VcapClient.Tests")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("IronFoundry.VcapClient.Tests")] [assembly: AssemblyCopyright("Copyright © 2012")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("a61d3ab4-e10a-4e7a-aa4a-85f820b91bda")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
{ "content_hash": "0d73396ec79abdc7d373efbba63d4731", "timestamp": "", "source": "github", "line_count": 36, "max_line_length": 84, "avg_line_length": 39.69444444444444, "alnum_prop": 0.748075577326802, "repo_name": "ironfoundry-attic/vcap-client", "id": "5e6b8867615211e0309da9e101e3747258b59290", "size": "1432", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/IronFoundry.VcapClient.Tests/Properties/AssemblyInfo.cs", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C#", "bytes": "135595" }, { "name": "JavaScript", "bytes": "213" } ], "symlink_target": "" }
Routing ======= This boilerplate uses [react-router-redux](https://github.com/reactjs/react-router-redux). All routes are described [src/routes.js](./src/routes/index.js). ```js route('/', App, index(Home), route('about', About) ) ```
{ "content_hash": "05fa80a4b7f72fd64f4a20557956b62c", "timestamp": "", "source": "github", "line_count": 12, "max_line_length": 90, "avg_line_length": 20.083333333333332, "alnum_prop": 0.6680497925311203, "repo_name": "stoeffel/react-redux-bp", "id": "51c5f70fc6fdafb4479115e49fe6037a2e6cfe3c", "size": "241", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "docs/routing.md", "mode": "33188", "license": "mit", "language": [ { "name": "HTML", "bytes": "211" }, { "name": "JavaScript", "bytes": "17999" } ], "symlink_target": "" }
package org.neo4j.test; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.PrintStream; import java.io.PrintWriter; import org.junit.rules.TestRule; import org.junit.runner.Description; import org.junit.runners.model.Statement; /** * Utility for capturing output and printing it on test failure only. */ public class FailureOutput implements TestRule { private final ByteArrayOutputStream output = new ByteArrayOutputStream(); private final PrintStream stream = new PrintStream( output ); private final PrintStream target; public FailureOutput() { this( System.out ); } public FailureOutput( PrintStream target ) { this.target = target; } @Override public Statement apply( final Statement base, Description description ) { return new Statement() { @Override public void evaluate() throws Throwable { try { base.evaluate(); } catch ( Throwable failure ) { printOutput(); throw failure; } } }; } private void printOutput() throws IOException { target.write( output.toByteArray() ); target.flush(); } public PrintStream stream() { return stream; } public PrintWriter writer() { return new PrintWriter( stream ); } }
{ "content_hash": "b84b3aa905bab3e84f6b010e5ce44919", "timestamp": "", "source": "github", "line_count": 68, "max_line_length": 77, "avg_line_length": 22.33823529411765, "alnum_prop": 0.5819618169848585, "repo_name": "HuangLS/neo4j", "id": "5d8d7611d3b44226757b286a424f79b4bfc2b6a6", "size": "2314", "binary": false, "copies": "1", "ref": "refs/heads/2.3", "path": "community/kernel/src/test/java/org/neo4j/test/FailureOutput.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "23732" }, { "name": "CSS", "bytes": "857344" }, { "name": "CoffeeScript", "bytes": "753075" }, { "name": "Cucumber", "bytes": "19027" }, { "name": "Elixir", "bytes": "2696" }, { "name": "Groff", "bytes": "74996" }, { "name": "HTML", "bytes": "486412" }, { "name": "Java", "bytes": "23514509" }, { "name": "JavaScript", "bytes": "1641699" }, { "name": "Makefile", "bytes": "8288" }, { "name": "PowerShell", "bytes": "160123" }, { "name": "Ruby", "bytes": "706" }, { "name": "Scala", "bytes": "5935401" }, { "name": "Shell", "bytes": "99251" } ], "symlink_target": "" }
package org.apache.jena.sparql.engine; import org.apache.jena.sparql.engine.binding.TestBindingStreams ; import org.apache.jena.sparql.engine.http.TestQueryEngineHTTP ; import org.apache.jena.sparql.engine.http.TestService ; import org.apache.jena.sparql.engine.iterator.TS_QueryIterators ; import org.apache.jena.sparql.engine.ref.TestTableJoin ; import org.junit.runner.RunWith ; import org.junit.runners.Suite ; @RunWith(Suite.class) @Suite.SuiteClasses( { TestBindingStreams.class , TestTableJoin.class , TS_QueryIterators.class , TestService.class , TestQueryEngineHTTP.class , TestQueryEngineMultiThreaded.class }) public class TS_Engine {}
{ "content_hash": "e4d2cac893d1941236ee3c2d5633146a", "timestamp": "", "source": "github", "line_count": 23, "max_line_length": 65, "avg_line_length": 30, "alnum_prop": 0.7695652173913043, "repo_name": "CesarPantoja/jena", "id": "d7b386c321107d0d3861115b1b17e772f74c1851", "size": "1495", "binary": false, "copies": "10", "ref": "refs/heads/master", "path": "jena-arq/src/test/java/org/apache/jena/sparql/engine/TS_Engine.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "ApacheConf", "bytes": "145" }, { "name": "AspectJ", "bytes": "3446" }, { "name": "Batchfile", "bytes": "16824" }, { "name": "C++", "bytes": "5037" }, { "name": "CSS", "bytes": "26180" }, { "name": "Elixir", "bytes": "2548" }, { "name": "HTML", "bytes": "100718" }, { "name": "Java", "bytes": "25062598" }, { "name": "JavaScript", "bytes": "918311" }, { "name": "Lex", "bytes": "82672" }, { "name": "Perl", "bytes": "37209" }, { "name": "Ruby", "bytes": "354871" }, { "name": "Shell", "bytes": "223592" }, { "name": "Smarty", "bytes": "17096" }, { "name": "Thrift", "bytes": "3201" }, { "name": "Web Ontology Language", "bytes": "518275" }, { "name": "XSLT", "bytes": "101830" } ], "symlink_target": "" }
package com.taobao.android.builder.tasks; /** * Created by wuzhong on 16/6/13. */ import com.android.build.gradle.api.BaseVariantOutput; import com.android.build.gradle.internal.api.ApContext; import com.android.build.gradle.internal.api.VariantContext; import com.android.build.gradle.internal.scope.ConventionMappingHelper; import com.android.build.gradle.internal.tasks.BaseTask; import com.android.utils.FileUtils; import com.google.common.collect.Iterables; import com.google.common.collect.Sets; import com.taobao.android.builder.AtlasBuildContext; import com.taobao.android.builder.dependency.AtlasDependencyTree; import com.taobao.android.builder.dependency.model.AwbBundle; import com.taobao.android.builder.extension.TBuildType; import com.taobao.android.builder.tasks.manager.MtlBaseTaskAction; import com.taobao.android.builder.tools.manifest.ManifestFileUtils; import com.taobao.android.builder.tools.zip.BetterZip; import org.apache.commons.io.FilenameUtils; import org.apache.commons.lang.StringUtils; import org.dom4j.DocumentException; import org.gradle.api.GradleException; import org.gradle.api.Nullable; import org.gradle.api.Project; import org.gradle.api.artifacts.Configuration; import org.gradle.api.artifacts.Dependency; import org.gradle.api.tasks.*; import java.io.File; import java.io.IOException; import java.util.Set; import java.util.concurrent.Callable; import java.util.concurrent.TimeUnit; import static com.android.SdkConstants.ANDROID_MANIFEST_XML; import static com.android.SdkConstants.FN_APK_CLASSES_DEX; import static com.android.build.gradle.internal.api.ApContext.*; import static com.android.builder.model.AndroidProject.FD_INTERMEDIATES; /** */ public class PrepareAPTask extends BaseTask { private ApContext apContext; private File apFile; private String apDependency; private File explodedDir; Set<String> awbBundles; @InputFile @Optional @Nullable public File getApFile() { return apFile; } public void setApFile(File apFile) { this.apFile = apFile; } @Input @Optional public String getApDependency() { return apDependency; } public void setApDependency(String apDependency) { this.apDependency = apDependency; } @OutputDirectory public File getExplodedDir() { return explodedDir; } public void setExplodedDir(File explodedDir) { this.explodedDir = explodedDir; } @Input @Optional public Set<String> getAwbBundles() { return awbBundles; } public void setAwbBundles(Set<String> awbBundles) { this.awbBundles = awbBundles; } /** * Directory of so */ @TaskAction void generate() throws IOException, DocumentException { Project project = getProject(); File apBaseFile = null; File apFile = getApFile(); if (null != apFile && apFile.exists()) { apBaseFile = apFile; } else { String apDependency = getApDependency(); if (StringUtils.isNotBlank(apContext.getApDependency())) { Dependency dependency = project.getDependencies().create(apDependency); Configuration configuration = project.getConfigurations().detachedConfiguration(dependency); configuration.setTransitive(false); configuration.getResolutionStrategy().cacheChangingModulesFor(0, TimeUnit.MILLISECONDS); configuration.getResolutionStrategy().cacheDynamicVersionsFor(0, TimeUnit.MILLISECONDS); for (File file : configuration.getFiles()) { if (file.getName().endsWith(".ap")) { apBaseFile = file; break; } } } } if (null != apBaseFile && apBaseFile.exists()) { try { explodedDir = getExplodedDir(); BetterZip.unzipDirectory(apBaseFile, explodedDir); apContext.setApExploredFolder(explodedDir); Set<String> awbBundles = getAwbBundles(); if (awbBundles != null) { // Unzip the baseline Bundle for (String awbBundle : awbBundles) { File awbFile = BetterZip.extractFile(new File(explodedDir, AP_INLINE_APK_FILENAME), "lib/armeabi/" + awbBundle, new File(explodedDir, AP_INLINE_AWB_EXTRACT_DIRECTORY)); File awbExplodedDir = new File(new File(explodedDir, AP_INLINE_AWB_EXPLODED_DIRECTORY), FilenameUtils.getBaseName(awbBundle)); BetterZip.unzipDirectory(awbFile, awbExplodedDir); FileUtils.renameTo(new File(awbExplodedDir, FN_APK_CLASSES_DEX), new File(awbExplodedDir, "classes2.dex")); } // Preprocessing increment androidmanifest.xml ManifestFileUtils.updatePreProcessBaseManifestFile( FileUtils.join(explodedDir, "manifest-modify", ANDROID_MANIFEST_XML), new File(explodedDir, ANDROID_MANIFEST_XML)); } if (explodedDir.listFiles().length == 0){ throw new RuntimeException("unzip ap exception, no files found"); } }catch (Throwable e){ FileUtils.deleteIfExists(apBaseFile); throw new GradleException(e.getMessage(),e); } } } public static class ConfigAction extends MtlBaseTaskAction<PrepareAPTask> { public ConfigAction(VariantContext variantContext, BaseVariantOutput baseVariantOutput) { super(variantContext, baseVariantOutput); } @Override public String getName() { return scope.getTaskName("prepare", "AP"); } @Override public Class<PrepareAPTask> getType() { return PrepareAPTask.class; } @Override public void execute(PrepareAPTask prepareAPTask) { super.execute(prepareAPTask); // TBuildType tBuildType = variantContext.getBuildType(); if (StringUtils.isNotEmpty(tBuildType.getBaseApDependency())) { variantContext.apContext.setApDependency(tBuildType.getBaseApDependency()); } variantContext.apContext.setApFile(tBuildType.getBaseApFile()); prepareAPTask.apContext = variantContext.apContext; File explodedDir = variantContext.getProject().file( variantContext.getProject().getBuildDir().getAbsolutePath() + "/" + FD_INTERMEDIATES + "/exploded-ap" + "/"); variantContext.apContext.setApExploredFolder(explodedDir); ConventionMappingHelper.map(prepareAPTask, "apFile", (Callable<File>) () -> { File apFile = variantContext.apContext.getApFile(); if (apFile != null) { return apFile.exists() ? apFile : null; } else { return null; } }); ConventionMappingHelper.map(prepareAPTask, "apDependency", (Callable<String>) () -> variantContext.apContext.getApDependency()); ConventionMappingHelper.map(prepareAPTask, "explodedDir", (Callable<File>) () -> explodedDir); if (variantContext.getAtlasExtension().getTBuildConfig().isIncremental()) { ConventionMappingHelper.map(prepareAPTask, "awbBundles", (Callable<Set<String>>) () -> { AtlasDependencyTree dependencyTree = AtlasBuildContext.androidDependencyTrees.get( variantContext.getVariantName()); Set<String> awbBundles = Sets.newHashSet( Iterables.transform(dependencyTree.getAwbBundles(), AwbBundle::getAwbSoName)); return awbBundles; }); } } } }
{ "content_hash": "ade803869a5c94e7437bc6247b332b06", "timestamp": "", "source": "github", "line_count": 222, "max_line_length": 140, "avg_line_length": 37.14414414414414, "alnum_prop": 0.621513461072035, "repo_name": "alibaba/atlas", "id": "4a0fbf596ea7e235a3d71a2df09402f2993af10f", "size": "20350", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "atlas-gradle-plugin/atlas-plugin/src/main/java/com/taobao/android/builder/tasks/PrepareAPTask.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Assembly", "bytes": "64906" }, { "name": "C", "bytes": "1975639" }, { "name": "C++", "bytes": "5114248" }, { "name": "CMake", "bytes": "3090" }, { "name": "CSS", "bytes": "87762" }, { "name": "HTML", "bytes": "628309" }, { "name": "Java", "bytes": "11894753" }, { "name": "JavaScript", "bytes": "37802" }, { "name": "Kotlin", "bytes": "2217" }, { "name": "Makefile", "bytes": "47196" }, { "name": "Python", "bytes": "1262" }, { "name": "Shell", "bytes": "11347" } ], "symlink_target": "" }
package com.thinkgem.jeesite.weixin.message.req; /** * 视频消息 * @author janson * */ public class VideoMessage extends BaseMessage{ //视频消息媒体id private String MediaId; private String ThumbMediaId; public String getMediaId() { return MediaId; } public void setMediaId(String mediaId) { MediaId = mediaId; } public String getThumbMediaId() { return ThumbMediaId; } public void setThumbMediaId(String thumbMediaId) { ThumbMediaId = thumbMediaId; } }
{ "content_hash": "d0b82d7fe694e793be72f0e61ecb95b0", "timestamp": "", "source": "github", "line_count": 28, "max_line_length": 51, "avg_line_length": 17.928571428571427, "alnum_prop": 0.6872509960159362, "repo_name": "jansonlwj/ordermanege", "id": "4b36e8b7339384b08fc2a531a0fc255a226bc309", "size": "522", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/main/java/com/thinkgem/jeesite/weixin/message/req/VideoMessage.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "ASP", "bytes": "3753" }, { "name": "ApacheConf", "bytes": "768" }, { "name": "Batchfile", "bytes": "2131" }, { "name": "CSS", "bytes": "2159251" }, { "name": "HTML", "bytes": "3352955" }, { "name": "Java", "bytes": "1697147" }, { "name": "JavaScript", "bytes": "15282731" }, { "name": "PHP", "bytes": "8060" } ], "symlink_target": "" }
<?php namespace PhpBrew\Command; use CLIFramework\Command as BaseCommand; use PhpBrew\BuildFinder; use PhpBrew\Config; class EnvCommand extends BaseCommand { public function brief() { return 'Export environment variables'; } public function arguments($args) { $args->add('PHP build') ->optional() ->validValues(function () { return BuildFinder::findInstalledBuilds(); }) ; } public function execute($buildName = null) { // get current version if (!$buildName) { $buildName = getenv('PHPBREW_PHP'); } $this->export('PHPBREW_ROOT', Config::getRoot()); $this->export('PHPBREW_HOME', Config::getHome()); $this->replicate('PHPBREW_LOOKUP_PREFIX'); if ($buildName !== false) { $targetPhpBinPath = Config::getVersionBinPath($buildName); // checking php version existence if (is_dir($targetPhpBinPath)) { $this->export('PHPBREW_PHP', $buildName); $this->export('PHPBREW_PATH', $targetPhpBinPath); } } $this->replicate('PHPBREW_SYSTEM_PHP'); $this->logger->writeln('# Run this command to configure your shell:'); $this->logger->writeln('# eval "$(phpbrew env)"'); } private function export($varName, $value) { $this->logger->writeln(sprintf('export %s=%s', $varName, $value)); } private function replicate($varName) { $value = getenv($varName); if ($value !== false && $value !== '') { $this->export($varName, $value); } } }
{ "content_hash": "a8e9bd7dbef2da5058b9cdd6222b25c3", "timestamp": "", "source": "github", "line_count": 67, "max_line_length": 78, "avg_line_length": 25.28358208955224, "alnum_prop": 0.5489964580873672, "repo_name": "phpbrew/phpbrew", "id": "4750356dc0503e5d68a85aaf8e056d6f02cc377f", "size": "1694", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "src/PhpBrew/Command/EnvCommand.php", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "291464" }, { "name": "M4", "bytes": "11808" }, { "name": "Makefile", "bytes": "621200" }, { "name": "PHP", "bytes": "413763" }, { "name": "Shell", "bytes": "300743" } ], "symlink_target": "" }
import {OpaqueToken} from '@angular/core'; import {toPromise} from 'rxjs/operator/toPromise'; import {AsyncValidatorFn, ValidatorFn} from './directives/validators'; import {StringMapWrapper} from './facade/collection'; import {isPresent} from './facade/lang'; import {AbstractControl} from './model'; import {isPromise} from './private_import_core'; function isEmptyInputValue(value: any) { return value == null || typeof value === 'string' && value.length === 0; } /** * Providers for validators to be used for {@link FormControl}s in a form. * * Provide this using `multi: true` to add validators. * * ### Example * * {@example core/forms/ts/ng_validators/ng_validators.ts region='ng_validators'} * @stable */ export const NG_VALIDATORS: OpaqueToken = new OpaqueToken('NgValidators'); /** * Providers for asynchronous validators to be used for {@link FormControl}s * in a form. * * Provide this using `multi: true` to add validators. * * See {@link NG_VALIDATORS} for more details. * * @stable */ export const NG_ASYNC_VALIDATORS: OpaqueToken = new OpaqueToken('NgAsyncValidators'); /** * Provides a set of validators used by form controls. * * A validator is a function that processes a {@link FormControl} or collection of * controls and returns a map of errors. A null map means that validation has passed. * * ### Example * * ```typescript * var loginControl = new FormControl("", Validators.required) * ``` * * @stable */ export class Validators { /** * Validator that requires controls to have a non-empty value. */ static required(control: AbstractControl): {[key: string]: boolean} { return isEmptyInputValue(control.value) ? {'required': true} : null; } /** * Validator that requires controls to have a value of a minimum length. */ static minLength(minLength: number): ValidatorFn { return (control: AbstractControl): {[key: string]: any} => { if (isEmptyInputValue(control.value)) { return null; // don't validate empty values to allow optional controls } const length = typeof control.value === 'string' ? control.value.length : 0; return length < minLength ? {'minlength': {'requiredLength': minLength, 'actualLength': length}} : null; }; } /** * Validator that requires controls to have a value of a maximum length. */ static maxLength(maxLength: number): ValidatorFn { return (control: AbstractControl): {[key: string]: any} => { const length = typeof control.value === 'string' ? control.value.length : 0; return length > maxLength ? {'maxlength': {'requiredLength': maxLength, 'actualLength': length}} : null; }; } /** * Validator that requires a control to match a regex to its value. */ static pattern(pattern: string): ValidatorFn { return (control: AbstractControl): {[key: string]: any} => { if (isEmptyInputValue(control.value)) { return null; // don't validate empty values to allow optional controls } const regex = new RegExp(`^${pattern}$`); const value: string = control.value; return regex.test(value) ? null : {'pattern': {'requiredPattern': `^${pattern}$`, 'actualValue': value}}; }; } /** * No-op validator. */ static nullValidator(c: AbstractControl): {[key: string]: boolean} { return null; } /** * Compose multiple validators into a single function that returns the union * of the individual error maps. */ static compose(validators: ValidatorFn[]): ValidatorFn { if (!validators) return null; var presentValidators = validators.filter(isPresent); if (presentValidators.length == 0) return null; return function(control: AbstractControl) { return _mergeErrors(_executeValidators(control, presentValidators)); }; } static composeAsync(validators: AsyncValidatorFn[]): AsyncValidatorFn { if (!validators) return null; var presentValidators = validators.filter(isPresent); if (presentValidators.length == 0) return null; return function(control: AbstractControl) { let promises = _executeAsyncValidators(control, presentValidators).map(_convertToPromise); return Promise.all(promises).then(_mergeErrors); }; } } function _convertToPromise(obj: any): Promise<any> { return isPromise(obj) ? obj : toPromise.call(obj); } function _executeValidators(control: AbstractControl, validators: ValidatorFn[]): any[] { return validators.map(v => v(control)); } function _executeAsyncValidators(control: AbstractControl, validators: AsyncValidatorFn[]): any[] { return validators.map(v => v(control)); } function _mergeErrors(arrayOfErrors: any[]): {[key: string]: any} { var res: {[key: string]: any} = arrayOfErrors.reduce((res: {[key: string]: any}, errors: {[key: string]: any}) => { return isPresent(errors) ? StringMapWrapper.merge(res, errors) : res; }, {}); return Object.keys(res).length === 0 ? null : res; }
{ "content_hash": "e715f15a64eba3f9c58546ca48597afa", "timestamp": "", "source": "github", "line_count": 154, "max_line_length": 99, "avg_line_length": 32.66233766233766, "alnum_prop": 0.6703777335984096, "repo_name": "laskoviymishka/angular", "id": "46fdd09efdd216c1bf8feab1c57a0f02f4cfcda2", "size": "5232", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "modules/@angular/forms/src/validators.ts", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "17054" }, { "name": "HTML", "bytes": "49684" }, { "name": "JavaScript", "bytes": "206044" }, { "name": "Python", "bytes": "3535" }, { "name": "Shell", "bytes": "40964" }, { "name": "TypeScript", "bytes": "4686954" } ], "symlink_target": "" }
package de.mygrades.main.events; /** * Simple event to indicate that the post request of an error report has successfully finished. */ public class ErrorReportDoneEvent { }
{ "content_hash": "767578d8eff6f54f18cb4cae583f26d4", "timestamp": "", "source": "github", "line_count": 7, "max_line_length": 95, "avg_line_length": 25.142857142857142, "alnum_prop": 0.7670454545454546, "repo_name": "MyGrades/mygrades-app", "id": "79d302fe1ee9b4b25df2914b44255b4df62d0f79", "size": "176", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "app/src/main/java/de/mygrades/main/events/ErrorReportDoneEvent.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Groovy", "bytes": "7121" }, { "name": "HTML", "bytes": "11270" }, { "name": "Java", "bytes": "708772" } ], "symlink_target": "" }
<?php namespace Symfony\Component\Config\Definition; use Symfony\Component\Config\Definition\Exception\ForbiddenOverwriteException; use Symfony\Component\Config\Definition\Exception\InvalidConfigurationException; use Symfony\Component\Config\Definition\Exception\DuplicateKeyException; use Symfony\Component\Config\Definition\Exception\InvalidTypeException; use Symfony\Component\Config\Definition\Exception\UnsetKeyException; use Symfony\Component\Config\Definition\Builder\NodeDefinition; /** * Represents an Array node in the config tree. * * @author Johannes M. Schmitt <[email protected]> */ class ArrayNode extends BaseNode implements PrototypeNodeInterface { protected $xmlRemappings; protected $children; protected $allowFalse; protected $allowNewKeys; protected $addIfNotSet; protected $performDeepMerging; protected $ignoreExtraKeys; /** * Constructor. * * @param string $name The Node's name * @param NodeInterface $parent The node parent */ public function __construct($name, NodeInterface $parent = null) { parent::__construct($name, $parent); $this->children = array(); $this->xmlRemappings = array(); $this->removeKeyAttribute = true; $this->allowFalse = false; $this->addIfNotSet = false; $this->allowNewKeys = true; $this->performDeepMerging = true; } /** * Sets the xml remappings that should be performed. * * @param array $remappings an array of the form array(array(string, string)) */ public function setXmlRemappings(array $remappings) { $this->xmlRemappings = $remappings; } /** * Sets whether to add default values for this array if it has not been * defined in any of the configuration files. * * @param Boolean $boolean */ public function setAddIfNotSet($boolean) { $this->addIfNotSet = (Boolean) $boolean; } /** * Sets whether false is allowed as value indicating that the array should * be unset. * * @param Boolean $allow */ public function setAllowFalse($allow) { $this->allowFalse = (Boolean) $allow; } /** * Sets whether new keys can be defined in subsequent configurations. * * @param Boolean $allow */ public function setAllowNewKeys($allow) { $this->allowNewKeys = (Boolean) $allow; } /** * Sets if deep merging should occur. * * @param Boolean $boolean */ public function setPerformDeepMerging($boolean) { $this->performDeepMerging = (Boolean) $boolean; } /** * Whether extra keys should just be ignore without an exception. * * @param Boolean $boolean To allow extra keys */ public function setIgnoreExtraKeys($boolean) { $this->ignoreExtraKeys = (Boolean) $boolean; } /** * Sets the node Name. * * @param string $name The node's name */ public function setName($name) { $this->name = $name; } /** * Checks if the node has a default value. * * @return Boolean */ public function hasDefaultValue() { return $this->addIfNotSet; } /** * Retrieves the default value. * * @return array The default value * @throws \RuntimeException if the node has no default value */ public function getDefaultValue() { if (!$this->hasDefaultValue()) { throw new \RuntimeException(sprintf('The node at path "%s" has no default value.', $this->getPath())); } $defaults = array(); foreach ($this->children as $name => $child) { if ($child->hasDefaultValue()) { $defaults[$name] = $child->getDefaultValue(); } } return $defaults; } /** * Adds a child node. * * @param NodeInterface $node The child node to add * @throws \InvalidArgumentException when the child node has no name * @throws \InvalidArgumentException when the child node's name is not unique */ public function addChild(NodeInterface $node) { $name = $node->getName(); if (empty($name)) { throw new \InvalidArgumentException('Child nodes must be named.'); } if (isset($this->children[$name])) { throw new \InvalidArgumentException(sprintf('A child node named "%s" already exists.', $name)); } $this->children[$name] = $node; } /** * Finalizes the value of this node. * * @param mixed $value * @return mixed The finalised value * @throws UnsetKeyException * @throws InvalidConfigurationException if the node doesn't have enough children */ protected function finalizeValue($value) { if (false === $value) { $msg = sprintf('Unsetting key for path "%s", value: %s', $this->getPath(), json_encode($value)); throw new UnsetKeyException($msg); } foreach ($this->children as $name => $child) { if (!array_key_exists($name, $value)) { if ($child->isRequired()) { $msg = sprintf('The child node "%s" at path "%s" must be configured.', $name, $this->getPath()); $ex = new InvalidConfigurationException($msg); $ex->setPath($this->getPath()); throw $ex; } if ($child->hasDefaultValue()) { $value[$name] = $child->getDefaultValue(); } continue; } try { $value[$name] = $child->finalize($value[$name]); } catch (UnsetKeyException $unset) { unset($value[$name]); } } return $value; } /** * Validates the type of the value. * * @param mixed $value * @throws InvalidTypeException */ protected function validateType($value) { if (!is_array($value) && (!$this->allowFalse || false !== $value)) { $ex = new InvalidTypeException(sprintf('Invalid type for path "%s". Expected array, but got %s', $this->getPath(), gettype($value))); $ex->setPath($this->getPath()); throw $ex; } } /** * Normalizes the value. * * @param mixed $value The value to normalize * @return mixed The normalized value */ protected function normalizeValue($value) { if (false === $value) { return $value; } $value = $this->remapXml($value); $normalized = array(); foreach ($this->children as $name => $child) { if (array_key_exists($name, $value)) { $normalized[$name] = $child->normalize($value[$name]); unset($value[$name]); } } // if extra fields are present, throw exception if (count($value) && !$this->ignoreExtraKeys) { $msg = sprintf('Unrecognized options "%s" under "%s"', implode(', ', array_keys($value)), $this->getPath()); $ex = new InvalidConfigurationException($msg); $ex->setPath($this->getPath() . '.' . reset($value)); throw $ex; } return $normalized; } /** * Remap multiple singular values to a single plural value * * @param array $value The source values * @return array The remapped values */ protected function remapXml($value) { foreach ($this->xmlRemappings as $transformation) { list($singular, $plural) = $transformation; if (!isset($value[$singular])) { continue; } $value[$plural] = Processor::normalizeConfig($value, $singular, $plural); unset($value[$singular]); } return $value; } /** * Merges values together. * * @param mixed $leftSide The left side to merge. * @param mixed $rightSide The right side to merge. * @return mixed The merged values * @throws InvalidConfigurationException * @throws \RuntimeException */ protected function mergeValues($leftSide, $rightSide) { if (false === $rightSide) { // if this is still false after the last config has been merged the // finalization pass will take care of removing this key entirely return false; } if (false === $leftSide || !$this->performDeepMerging) { return $rightSide; } foreach ($rightSide as $k => $v) { // no conflict if (!array_key_exists($k, $leftSide)) { if (!$this->allowNewKeys) { $ex = new InvalidConfigurationException( sprintf( 'You are not allowed to define new elements for path "%s". ' . 'Please define all elements for this path in one config file. ' . 'If you are trying to overwrite an element, make sure you redefine it ' . 'with the same name.', $this->getPath())); $ex->setPath($this->getPath()); throw $ex; } $leftSide[$k] = $v; continue; } if (!isset($this->children[$k])) { throw new \RuntimeException('merge() expects a normalized config array.'); } $leftSide[$k] = $this->children[$k]->merge($leftSide[$k], $v); } return $leftSide; } }
{ "content_hash": "db7c67a88680bbd16126890b5aa54648", "timestamp": "", "source": "github", "line_count": 316, "max_line_length": 254, "avg_line_length": 25.920886075949365, "alnum_prop": 0.6626785496276401, "repo_name": "flyingfeet/FlyingFeet", "id": "1e2e1f598fe6fd1dc7867fe836b1ebb21d13702e", "size": "8420", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "vendor/symfony/src/Symfony/Component/Config/Definition/ArrayNode.php", "mode": "33188", "license": "mit", "language": [ { "name": "JavaScript", "bytes": "18506" }, { "name": "PHP", "bytes": "48999" }, { "name": "Shell", "bytes": "192" } ], "symlink_target": "" }
/* Command line interface for Brotli library. */ #include <errno.h> #include <fcntl.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/stat.h> #include <sys/types.h> #include <time.h> #include "../common/constants.h" #include "../common/version.h" #include <brotli/decode.h> #include <brotli/encode.h> #if !defined(_WIN32) #include <unistd.h> #include <utime.h> #define MAKE_BINARY(FILENO) (FILENO) #else #include <io.h> #include <share.h> #include <sys/utime.h> #define MAKE_BINARY(FILENO) (_setmode((FILENO), _O_BINARY), (FILENO)) #if !defined(__MINGW32__) #define STDIN_FILENO _fileno(stdin) #define STDOUT_FILENO _fileno(stdout) #define S_IRUSR S_IREAD #define S_IWUSR S_IWRITE #endif #define fdopen _fdopen #define isatty _isatty #define unlink _unlink #define utimbuf _utimbuf #define utime _utime #define fopen ms_fopen #define open ms_open #define chmod(F, P) (0) #define chown(F, O, G) (0) #if defined(_MSC_VER) && (_MSC_VER >= 1400) #define fseek _fseeki64 #define ftell _ftelli64 #endif static FILE* ms_fopen(const char* filename, const char* mode) { FILE* result = 0; fopen_s(&result, filename, mode); return result; } static int ms_open(const char* filename, int oflag, int pmode) { int result = -1; _sopen_s(&result, filename, oflag | O_BINARY, _SH_DENYNO, pmode); return result; } #endif /* WIN32 */ typedef enum { COMMAND_COMPRESS, COMMAND_DECOMPRESS, COMMAND_HELP, COMMAND_INVALID, COMMAND_TEST_INTEGRITY, COMMAND_NOOP, COMMAND_VERSION } Command; #define DEFAULT_LGWIN 24 #define DEFAULT_SUFFIX ".br" #define MAX_OPTIONS 20 typedef struct { /* Parameters */ int quality; int lgwin; BROTLI_BOOL force_overwrite; BROTLI_BOOL junk_source; BROTLI_BOOL copy_stat; BROTLI_BOOL verbose; BROTLI_BOOL write_to_stdout; BROTLI_BOOL test_integrity; BROTLI_BOOL decompress; BROTLI_BOOL large_window; const char* output_path; const char* suffix; int not_input_indices[MAX_OPTIONS]; size_t longest_path_len; size_t input_count; /* Inner state */ int argc; char** argv; char* modified_path; /* Storage for path with appended / cut suffix */ int iterator; int ignore; BROTLI_BOOL iterator_error; uint8_t* buffer; uint8_t* input; uint8_t* output; const char* current_input_path; const char* current_output_path; int64_t input_file_length; /* -1, if impossible to calculate */ FILE* fin; FILE* fout; /* I/O buffers */ size_t available_in; const uint8_t* next_in; size_t available_out; uint8_t* next_out; } Context; /* Parse up to 5 decimal digits. */ static BROTLI_BOOL ParseInt(const char* s, int low, int high, int* result) { int value = 0; int i; for (i = 0; i < 5; ++i) { char c = s[i]; if (c == 0) break; if (s[i] < '0' || s[i] > '9') return BROTLI_FALSE; value = (10 * value) + (c - '0'); } if (i == 0) return BROTLI_FALSE; if (i > 1 && s[0] == '0') return BROTLI_FALSE; if (s[i] != 0) return BROTLI_FALSE; if (value < low || value > high) return BROTLI_FALSE; *result = value; return BROTLI_TRUE; } /* Returns "base file name" or its tail, if it contains '/' or '\'. */ static const char* FileName(const char* path) { const char* separator_position = strrchr(path, '/'); if (separator_position) path = separator_position + 1; separator_position = strrchr(path, '\\'); if (separator_position) path = separator_position + 1; return path; } /* Detect if the program name is a special alias that infers a command type. */ static Command ParseAlias(const char* name) { /* TODO: cast name to lower case? */ const char* unbrotli = "unbrotli"; size_t unbrotli_len = strlen(unbrotli); name = FileName(name); /* Partial comparison. On Windows there could be ".exe" suffix. */ if (strncmp(name, unbrotli, unbrotli_len) == 0) { char terminator = name[unbrotli_len]; if (terminator == 0 || terminator == '.') return COMMAND_DECOMPRESS; } return COMMAND_COMPRESS; } static Command ParseParams(Context* params) { int argc = params->argc; char** argv = params->argv; int i; int next_option_index = 0; size_t input_count = 0; size_t longest_path_len = 1; BROTLI_BOOL command_set = BROTLI_FALSE; BROTLI_BOOL quality_set = BROTLI_FALSE; BROTLI_BOOL output_set = BROTLI_FALSE; BROTLI_BOOL keep_set = BROTLI_FALSE; BROTLI_BOOL lgwin_set = BROTLI_FALSE; BROTLI_BOOL suffix_set = BROTLI_FALSE; BROTLI_BOOL after_dash_dash = BROTLI_FALSE; Command command = ParseAlias(argv[0]); for (i = 1; i < argc; ++i) { const char* arg = argv[i]; /* C99 5.1.2.2.1: "members argv[0] through argv[argc-1] inclusive shall contain pointers to strings"; NULL and 0-length are not forbidden. */ size_t arg_len = arg ? strlen(arg) : 0; if (arg_len == 0) { params->not_input_indices[next_option_index++] = i; continue; } /* Too many options. The expected longest option list is: "-q 0 -w 10 -o f -D d -S b -d -f -k -n -v --", i.e. 16 items in total. This check is an additional guard that is never triggered, but provides a guard for future changes. */ if (next_option_index > (MAX_OPTIONS - 2)) { fprintf(stderr, "too many options passed\n"); return COMMAND_INVALID; } /* Input file entry. */ if (after_dash_dash || arg[0] != '-' || arg_len == 1) { input_count++; if (longest_path_len < arg_len) longest_path_len = arg_len; continue; } /* Not a file entry. */ params->not_input_indices[next_option_index++] = i; /* '--' entry stop parsing arguments. */ if (arg_len == 2 && arg[1] == '-') { after_dash_dash = BROTLI_TRUE; continue; } /* Simple / coalesced options. */ if (arg[1] != '-') { size_t j; for (j = 1; j < arg_len; ++j) { char c = arg[j]; if (c >= '0' && c <= '9') { if (quality_set) { fprintf(stderr, "quality already set\n"); return COMMAND_INVALID; } quality_set = BROTLI_TRUE; params->quality = c - '0'; continue; } else if (c == 'c') { if (output_set) { fprintf(stderr, "write to standard output already set\n"); return COMMAND_INVALID; } output_set = BROTLI_TRUE; params->write_to_stdout = BROTLI_TRUE; continue; } else if (c == 'd') { if (command_set) { fprintf(stderr, "command already set when parsing -d\n"); return COMMAND_INVALID; } command_set = BROTLI_TRUE; command = COMMAND_DECOMPRESS; continue; } else if (c == 'f') { if (params->force_overwrite) { fprintf(stderr, "force output overwrite already set\n"); return COMMAND_INVALID; } params->force_overwrite = BROTLI_TRUE; continue; } else if (c == 'h') { /* Don't parse further. */ return COMMAND_HELP; } else if (c == 'j' || c == 'k') { if (keep_set) { fprintf(stderr, "argument --rm / -j or --keep / -n already set\n"); return COMMAND_INVALID; } keep_set = BROTLI_TRUE; params->junk_source = TO_BROTLI_BOOL(c == 'j'); continue; } else if (c == 'n') { if (!params->copy_stat) { fprintf(stderr, "argument --no-copy-stat / -n already set\n"); return COMMAND_INVALID; } params->copy_stat = BROTLI_FALSE; continue; } else if (c == 't') { if (command_set) { fprintf(stderr, "command already set when parsing -t\n"); return COMMAND_INVALID; } command_set = BROTLI_TRUE; command = COMMAND_TEST_INTEGRITY; continue; } else if (c == 'v') { if (params->verbose) { fprintf(stderr, "argument --verbose / -v already set\n"); return COMMAND_INVALID; } params->verbose = BROTLI_TRUE; continue; } else if (c == 'V') { /* Don't parse further. */ return COMMAND_VERSION; } else if (c == 'Z') { if (quality_set) { fprintf(stderr, "quality already set\n"); return COMMAND_INVALID; } quality_set = BROTLI_TRUE; params->quality = 11; continue; } /* o/q/w/D/S with parameter is expected */ if (c != 'o' && c != 'q' && c != 'w' && c != 'D' && c != 'S') { fprintf(stderr, "invalid argument -%c\n", c); return COMMAND_INVALID; } if (j + 1 != arg_len) { fprintf(stderr, "expected parameter for argument -%c\n", c); return COMMAND_INVALID; } i++; if (i == argc || !argv[i] || argv[i][0] == 0) { fprintf(stderr, "expected parameter for argument -%c\n", c); return COMMAND_INVALID; } params->not_input_indices[next_option_index++] = i; if (c == 'o') { if (output_set) { fprintf(stderr, "write to standard output already set (-o)\n"); return COMMAND_INVALID; } params->output_path = argv[i]; } else if (c == 'q') { if (quality_set) { fprintf(stderr, "quality already set\n"); return COMMAND_INVALID; } quality_set = ParseInt(argv[i], BROTLI_MIN_QUALITY, BROTLI_MAX_QUALITY, &params->quality); if (!quality_set) { fprintf(stderr, "error parsing quality value [%s]\n", argv[i]); return COMMAND_INVALID; } } else if (c == 'w') { if (lgwin_set) { fprintf(stderr, "lgwin parameter already set\n"); return COMMAND_INVALID; } lgwin_set = ParseInt(argv[i], 0, BROTLI_MAX_WINDOW_BITS, &params->lgwin); if (!lgwin_set) { fprintf(stderr, "error parsing lgwin value [%s]\n", argv[i]); return COMMAND_INVALID; } if (params->lgwin != 0 && params->lgwin < BROTLI_MIN_WINDOW_BITS) { fprintf(stderr, "lgwin parameter (%d) smaller than the minimum (%d)\n", params->lgwin, BROTLI_MIN_WINDOW_BITS); return COMMAND_INVALID; } } else if (c == 'S') { if (suffix_set) { fprintf(stderr, "suffix already set\n"); return COMMAND_INVALID; } suffix_set = BROTLI_TRUE; params->suffix = argv[i]; } } } else { /* Double-dash. */ arg = &arg[2]; if (strcmp("best", arg) == 0) { if (quality_set) { fprintf(stderr, "quality already set\n"); return COMMAND_INVALID; } quality_set = BROTLI_TRUE; params->quality = 11; } else if (strcmp("decompress", arg) == 0) { if (command_set) { fprintf(stderr, "command already set when parsing --decompress\n"); return COMMAND_INVALID; } command_set = BROTLI_TRUE; command = COMMAND_DECOMPRESS; } else if (strcmp("force", arg) == 0) { if (params->force_overwrite) { fprintf(stderr, "force output overwrite already set\n"); return COMMAND_INVALID; } params->force_overwrite = BROTLI_TRUE; } else if (strcmp("help", arg) == 0) { /* Don't parse further. */ return COMMAND_HELP; } else if (strcmp("keep", arg) == 0) { if (keep_set) { fprintf(stderr, "argument --rm / -j or --keep / -n already set\n"); return COMMAND_INVALID; } keep_set = BROTLI_TRUE; params->junk_source = BROTLI_FALSE; } else if (strcmp("no-copy-stat", arg) == 0) { if (!params->copy_stat) { fprintf(stderr, "argument --no-copy-stat / -n already set\n"); return COMMAND_INVALID; } params->copy_stat = BROTLI_FALSE; } else if (strcmp("rm", arg) == 0) { if (keep_set) { fprintf(stderr, "argument --rm / -j or --keep / -n already set\n"); return COMMAND_INVALID; } keep_set = BROTLI_TRUE; params->junk_source = BROTLI_TRUE; } else if (strcmp("stdout", arg) == 0) { if (output_set) { fprintf(stderr, "write to standard output already set\n"); return COMMAND_INVALID; } output_set = BROTLI_TRUE; params->write_to_stdout = BROTLI_TRUE; } else if (strcmp("test", arg) == 0) { if (command_set) { fprintf(stderr, "command already set when parsing --test\n"); return COMMAND_INVALID; } command_set = BROTLI_TRUE; command = COMMAND_TEST_INTEGRITY; } else if (strcmp("verbose", arg) == 0) { if (params->verbose) { fprintf(stderr, "argument --verbose / -v already set\n"); return COMMAND_INVALID; } params->verbose = BROTLI_TRUE; } else if (strcmp("version", arg) == 0) { /* Don't parse further. */ return COMMAND_VERSION; } else { /* key=value */ const char* value = strrchr(arg, '='); size_t key_len; if (!value || value[1] == 0) { fprintf(stderr, "must pass the parameter as --%s=value\n", arg); return COMMAND_INVALID; } key_len = (size_t)(value - arg); value++; if (strncmp("lgwin", arg, key_len) == 0) { if (lgwin_set) { fprintf(stderr, "lgwin parameter already set\n"); return COMMAND_INVALID; } lgwin_set = ParseInt(value, 0, BROTLI_MAX_WINDOW_BITS, &params->lgwin); if (!lgwin_set) { fprintf(stderr, "error parsing lgwin value [%s]\n", value); return COMMAND_INVALID; } if (params->lgwin != 0 && params->lgwin < BROTLI_MIN_WINDOW_BITS) { fprintf(stderr, "lgwin parameter (%d) smaller than the minimum (%d)\n", params->lgwin, BROTLI_MIN_WINDOW_BITS); return COMMAND_INVALID; } } else if (strncmp("large_window", arg, key_len) == 0) { /* This option is intentionally not mentioned in help. */ if (lgwin_set) { fprintf(stderr, "lgwin parameter already set\n"); return COMMAND_INVALID; } lgwin_set = ParseInt(value, 0, BROTLI_LARGE_MAX_WINDOW_BITS, &params->lgwin); if (!lgwin_set) { fprintf(stderr, "error parsing lgwin value [%s]\n", value); return COMMAND_INVALID; } if (params->lgwin != 0 && params->lgwin < BROTLI_MIN_WINDOW_BITS) { fprintf(stderr, "lgwin parameter (%d) smaller than the minimum (%d)\n", params->lgwin, BROTLI_MIN_WINDOW_BITS); return COMMAND_INVALID; } } else if (strncmp("output", arg, key_len) == 0) { if (output_set) { fprintf(stderr, "write to standard output already set (--output)\n"); return COMMAND_INVALID; } params->output_path = value; } else if (strncmp("quality", arg, key_len) == 0) { if (quality_set) { fprintf(stderr, "quality already set\n"); return COMMAND_INVALID; } quality_set = ParseInt(value, BROTLI_MIN_QUALITY, BROTLI_MAX_QUALITY, &params->quality); if (!quality_set) { fprintf(stderr, "error parsing quality value [%s]\n", value); return COMMAND_INVALID; } } else if (strncmp("suffix", arg, key_len) == 0) { if (suffix_set) { fprintf(stderr, "suffix already set\n"); return COMMAND_INVALID; } suffix_set = BROTLI_TRUE; params->suffix = value; } else { fprintf(stderr, "invalid parameter: [%s]\n", arg); return COMMAND_INVALID; } } } } params->input_count = input_count; params->longest_path_len = longest_path_len; params->decompress = (command == COMMAND_DECOMPRESS); params->test_integrity = (command == COMMAND_TEST_INTEGRITY); if (input_count > 1 && output_set) return COMMAND_INVALID; if (params->test_integrity) { if (params->output_path) return COMMAND_INVALID; if (params->write_to_stdout) return COMMAND_INVALID; } if (strchr(params->suffix, '/') || strchr(params->suffix, '\\')) { return COMMAND_INVALID; } return command; } static void PrintVersion(void) { int major = BROTLI_VERSION >> 24; int minor = (BROTLI_VERSION >> 12) & 0xFFF; int patch = BROTLI_VERSION & 0xFFF; fprintf(stdout, "brotli %d.%d.%d\n", major, minor, patch); } static void PrintHelp(const char* name, BROTLI_BOOL error) { FILE* media = error ? stderr : stdout; /* String is cut to pieces with length less than 509, to conform C90 spec. */ fprintf(media, "Usage: %s [OPTION]... [FILE]...\n", name); fprintf(media, "Options:\n" " -# compression level (0-9)\n" " -c, --stdout write on standard output\n" " -d, --decompress decompress\n" " -f, --force force output file overwrite\n" " -h, --help display this help and exit\n"); fprintf(media, " -j, --rm remove source file(s)\n" " -k, --keep keep source file(s) (default)\n" " -n, --no-copy-stat do not copy source file(s) attributes\n" " -o FILE, --output=FILE output file (only if 1 input file)\n"); fprintf(media, " -q NUM, --quality=NUM compression level (%d-%d)\n", BROTLI_MIN_QUALITY, BROTLI_MAX_QUALITY); fprintf(media, " -t, --test test compressed file integrity\n" " -v, --verbose verbose mode\n"); fprintf(media, " -w NUM, --lgwin=NUM set LZ77 window size (0, %d-%d)\n", BROTLI_MIN_WINDOW_BITS, BROTLI_MAX_WINDOW_BITS); fprintf(media, " window size = 2**NUM - 16\n" " 0 lets compressor choose the optimal value\n"); fprintf(media, " -S SUF, --suffix=SUF output file suffix (default:'%s')\n", DEFAULT_SUFFIX); fprintf(media, " -V, --version display version and exit\n" " -Z, --best use best compression level (11) (default)\n" "Simple options could be coalesced, i.e. '-9kf' is equivalent to '-9 -k -f'.\n" "With no FILE, or when FILE is -, read standard input.\n" "All arguments after '--' are treated as files.\n"); } static const char* PrintablePath(const char* path) { return path ? path : "con"; } static BROTLI_BOOL OpenInputFile(const char* input_path, FILE** f) { *f = NULL; if (!input_path) { *f = fdopen(MAKE_BINARY(STDIN_FILENO), "rb"); return BROTLI_TRUE; } *f = fopen(input_path, "rb"); if (!*f) { fprintf(stderr, "failed to open input file [%s]: %s\n", PrintablePath(input_path), strerror(errno)); return BROTLI_FALSE; } return BROTLI_TRUE; } static BROTLI_BOOL OpenOutputFile(const char* output_path, FILE** f, BROTLI_BOOL force) { int fd; *f = NULL; if (!output_path) { *f = fdopen(MAKE_BINARY(STDOUT_FILENO), "wb"); return BROTLI_TRUE; } fd = open(output_path, O_CREAT | (force ? 0 : O_EXCL) | O_WRONLY | O_TRUNC, S_IRUSR | S_IWUSR); if (fd < 0) { fprintf(stderr, "failed to open output file [%s]: %s\n", PrintablePath(output_path), strerror(errno)); return BROTLI_FALSE; } *f = fdopen(fd, "wb"); if (!*f) { fprintf(stderr, "failed to open output file [%s]: %s\n", PrintablePath(output_path), strerror(errno)); return BROTLI_FALSE; } return BROTLI_TRUE; } static int64_t FileSize(const char* path) { FILE* f = fopen(path, "rb"); int64_t retval; if (f == NULL) { return -1; } if (fseek(f, 0L, SEEK_END) != 0) { fclose(f); return -1; } retval = ftell(f); if (fclose(f) != 0) { return -1; } return retval; } /* Copy file times and permissions. TODO: this is a "best effort" implementation; honest cross-platform fully featured implementation is way too hacky; add more hacks by request. */ static void CopyStat(const char* input_path, const char* output_path) { struct stat statbuf; struct utimbuf times; int res; if (input_path == 0 || output_path == 0) { return; } if (stat(input_path, &statbuf) != 0) { return; } times.actime = statbuf.st_atime; times.modtime = statbuf.st_mtime; utime(output_path, &times); res = chmod(output_path, statbuf.st_mode & (S_IRWXU | S_IRWXG | S_IRWXO)); if (res != 0) { fprintf(stderr, "setting access bits failed for [%s]: %s\n", PrintablePath(output_path), strerror(errno)); } res = chown(output_path, (uid_t)-1, statbuf.st_gid); if (res != 0) { fprintf(stderr, "setting group failed for [%s]: %s\n", PrintablePath(output_path), strerror(errno)); } res = chown(output_path, statbuf.st_uid, (gid_t)-1); if (res != 0) { fprintf(stderr, "setting user failed for [%s]: %s\n", PrintablePath(output_path), strerror(errno)); } } static BROTLI_BOOL NextFile(Context* context) { const char* arg; size_t arg_len; /* Iterator points to last used arg; increment to search for the next one. */ context->iterator++; context->input_file_length = -1; /* No input path; read from console. */ if (context->input_count == 0) { if (context->iterator > 1) return BROTLI_FALSE; context->current_input_path = NULL; /* Either write to the specified path, or to console. */ context->current_output_path = context->output_path; return BROTLI_TRUE; } /* Skip option arguments. */ while (context->iterator == context->not_input_indices[context->ignore]) { context->iterator++; context->ignore++; } /* All args are scanned already. */ if (context->iterator >= context->argc) return BROTLI_FALSE; /* Iterator now points to the input file name. */ arg = context->argv[context->iterator]; arg_len = strlen(arg); /* Read from console. */ if (arg_len == 1 && arg[0] == '-') { context->current_input_path = NULL; context->current_output_path = context->output_path; return BROTLI_TRUE; } context->current_input_path = arg; context->input_file_length = FileSize(arg); context->current_output_path = context->output_path; if (context->output_path) return BROTLI_TRUE; if (context->write_to_stdout) return BROTLI_TRUE; strcpy(context->modified_path, arg); context->current_output_path = context->modified_path; /* If output is not specified, input path suffix should match. */ if (context->decompress) { size_t suffix_len = strlen(context->suffix); char* name = (char*)FileName(context->modified_path); char* name_suffix; size_t name_len = strlen(name); if (name_len < suffix_len + 1) { fprintf(stderr, "empty output file name for [%s] input file\n", PrintablePath(arg)); context->iterator_error = BROTLI_TRUE; return BROTLI_FALSE; } name_suffix = name + name_len - suffix_len; if (strcmp(context->suffix, name_suffix) != 0) { fprintf(stderr, "input file [%s] suffix mismatch\n", PrintablePath(arg)); context->iterator_error = BROTLI_TRUE; return BROTLI_FALSE; } name_suffix[0] = 0; return BROTLI_TRUE; } else { strcpy(context->modified_path + arg_len, context->suffix); return BROTLI_TRUE; } } static BROTLI_BOOL OpenFiles(Context* context) { BROTLI_BOOL is_ok = OpenInputFile(context->current_input_path, &context->fin); if (!context->test_integrity && is_ok) { is_ok = OpenOutputFile( context->current_output_path, &context->fout, context->force_overwrite); } return is_ok; } static BROTLI_BOOL CloseFiles(Context* context, BROTLI_BOOL success) { BROTLI_BOOL is_ok = BROTLI_TRUE; if (!context->test_integrity && context->fout) { if (!success && context->current_output_path) { unlink(context->current_output_path); } if (fclose(context->fout) != 0) { if (success) { fprintf(stderr, "fclose failed [%s]: %s\n", PrintablePath(context->current_output_path), strerror(errno)); } is_ok = BROTLI_FALSE; } /* TOCTOU violation, but otherwise it is impossible to set file times. */ if (success && is_ok && context->copy_stat) { CopyStat(context->current_input_path, context->current_output_path); } } if (context->fin) { if (fclose(context->fin) != 0) { if (is_ok) { fprintf(stderr, "fclose failed [%s]: %s\n", PrintablePath(context->current_input_path), strerror(errno)); } is_ok = BROTLI_FALSE; } } if (success && context->junk_source && context->current_input_path) { unlink(context->current_input_path); } context->fin = NULL; context->fout = NULL; return is_ok; } static const size_t kFileBufferSize = 1 << 19; static void InitializeBuffers(Context* context) { context->available_in = 0; context->next_in = NULL; context->available_out = kFileBufferSize; context->next_out = context->output; } static BROTLI_BOOL HasMoreInput(Context* context) { return feof(context->fin) ? BROTLI_FALSE : BROTLI_TRUE; } static BROTLI_BOOL ProvideInput(Context* context) { context->available_in = fread(context->input, 1, kFileBufferSize, context->fin); context->next_in = context->input; if (ferror(context->fin)) { fprintf(stderr, "failed to read input [%s]: %s\n", PrintablePath(context->current_input_path), strerror(errno)); return BROTLI_FALSE; } return BROTLI_TRUE; } /* Internal: should be used only in Provide-/Flush-Output. */ static BROTLI_BOOL WriteOutput(Context* context) { size_t out_size = (size_t)(context->next_out - context->output); if (out_size == 0) return BROTLI_TRUE; if (context->test_integrity) return BROTLI_TRUE; fwrite(context->output, 1, out_size, context->fout); if (ferror(context->fout)) { fprintf(stderr, "failed to write output [%s]: %s\n", PrintablePath(context->current_output_path), strerror(errno)); return BROTLI_FALSE; } return BROTLI_TRUE; } static BROTLI_BOOL ProvideOutput(Context* context) { if (!WriteOutput(context)) return BROTLI_FALSE; context->available_out = kFileBufferSize; context->next_out = context->output; return BROTLI_TRUE; } static BROTLI_BOOL FlushOutput(Context* context) { if (!WriteOutput(context)) return BROTLI_FALSE; context->available_out = 0; return BROTLI_TRUE; } static BROTLI_BOOL DecompressFile(Context* context, BrotliDecoderState* s) { BrotliDecoderResult result = BROTLI_DECODER_RESULT_NEEDS_MORE_INPUT; InitializeBuffers(context); for (;;) { if (result == BROTLI_DECODER_RESULT_NEEDS_MORE_INPUT) { if (!HasMoreInput(context)) { fprintf(stderr, "corrupt input [%s]\n", PrintablePath(context->current_input_path)); return BROTLI_FALSE; } if (!ProvideInput(context)) return BROTLI_FALSE; } else if (result == BROTLI_DECODER_RESULT_NEEDS_MORE_OUTPUT) { if (!ProvideOutput(context)) return BROTLI_FALSE; } else if (result == BROTLI_DECODER_RESULT_SUCCESS) { if (!FlushOutput(context)) return BROTLI_FALSE; if (context->available_in != 0 || HasMoreInput(context)) { fprintf(stderr, "corrupt input [%s]\n", PrintablePath(context->current_input_path)); return BROTLI_FALSE; } return BROTLI_TRUE; } else { fprintf(stderr, "corrupt input [%s]\n", PrintablePath(context->current_input_path)); return BROTLI_FALSE; } result = BrotliDecoderDecompressStream(s, &context->available_in, &context->next_in, &context->available_out, &context->next_out, 0); } } static BROTLI_BOOL DecompressFiles(Context* context) { while (NextFile(context)) { BROTLI_BOOL is_ok = BROTLI_TRUE; BrotliDecoderState* s = BrotliDecoderCreateInstance(NULL, NULL, NULL); if (!s) { fprintf(stderr, "out of memory\n"); return BROTLI_FALSE; } /* This allows decoding "large-window" streams. Though it creates fragmentation (new builds decode streams that old builds don't), it is better from used experience perspective. */ BrotliDecoderSetParameter(s, BROTLI_DECODER_PARAM_LARGE_WINDOW, 1u); is_ok = OpenFiles(context); if (is_ok && !context->current_input_path && !context->force_overwrite && isatty(STDIN_FILENO)) { fprintf(stderr, "Use -h help. Use -f to force input from a terminal.\n"); is_ok = BROTLI_FALSE; } if (is_ok) is_ok = DecompressFile(context, s); BrotliDecoderDestroyInstance(s); if (!CloseFiles(context, is_ok)) is_ok = BROTLI_FALSE; if (!is_ok) return BROTLI_FALSE; } return BROTLI_TRUE; } static BROTLI_BOOL CompressFile(Context* context, BrotliEncoderState* s) { BROTLI_BOOL is_eof = BROTLI_FALSE; InitializeBuffers(context); for (;;) { if (context->available_in == 0 && !is_eof) { if (!ProvideInput(context)) return BROTLI_FALSE; is_eof = !HasMoreInput(context); } if (!BrotliEncoderCompressStream(s, is_eof ? BROTLI_OPERATION_FINISH : BROTLI_OPERATION_PROCESS, &context->available_in, &context->next_in, &context->available_out, &context->next_out, NULL)) { /* Should detect OOM? */ fprintf(stderr, "failed to compress data [%s]\n", PrintablePath(context->current_input_path)); return BROTLI_FALSE; } if (context->available_out == 0) { if (!ProvideOutput(context)) return BROTLI_FALSE; } if (BrotliEncoderIsFinished(s)) { return FlushOutput(context); } } } static BROTLI_BOOL CompressFiles(Context* context) { while (NextFile(context)) { BROTLI_BOOL is_ok = BROTLI_TRUE; BrotliEncoderState* s = BrotliEncoderCreateInstance(NULL, NULL, NULL); if (!s) { fprintf(stderr, "out of memory\n"); return BROTLI_FALSE; } BrotliEncoderSetParameter(s, BROTLI_PARAM_QUALITY, (uint32_t)context->quality); if (context->lgwin > 0) { /* Specified by user. */ /* Do not enable "large-window" extension, if not required. */ if (context->lgwin > BROTLI_MAX_WINDOW_BITS) { BrotliEncoderSetParameter(s, BROTLI_PARAM_LARGE_WINDOW, 1u); } BrotliEncoderSetParameter(s, BROTLI_PARAM_LGWIN, (uint32_t)context->lgwin); } else { /* 0, or not specified by user; could be chosen by compressor. */ uint32_t lgwin = DEFAULT_LGWIN; /* Use file size to limit lgwin. */ if (context->input_file_length >= 0) { lgwin = BROTLI_MIN_WINDOW_BITS; while (BROTLI_MAX_BACKWARD_LIMIT(lgwin) < (uint64_t)context->input_file_length) { lgwin++; if (lgwin == BROTLI_MAX_WINDOW_BITS) break; } } BrotliEncoderSetParameter(s, BROTLI_PARAM_LGWIN, lgwin); } if (context->input_file_length > 0) { uint32_t size_hint = context->input_file_length < (1 << 30) ? (uint32_t)context->input_file_length : (1u << 30); BrotliEncoderSetParameter(s, BROTLI_PARAM_SIZE_HINT, size_hint); } is_ok = OpenFiles(context); if (is_ok && !context->current_output_path && !context->force_overwrite && isatty(STDOUT_FILENO)) { fprintf(stderr, "Use -h help. Use -f to force output to a terminal.\n"); is_ok = BROTLI_FALSE; } if (is_ok) is_ok = CompressFile(context, s); BrotliEncoderDestroyInstance(s); if (!CloseFiles(context, is_ok)) is_ok = BROTLI_FALSE; if (!is_ok) return BROTLI_FALSE; } return BROTLI_TRUE; } int main(int argc, char** argv) { Command command; Context context; BROTLI_BOOL is_ok = BROTLI_TRUE; int i; context.quality = 11; context.lgwin = -1; context.force_overwrite = BROTLI_FALSE; context.junk_source = BROTLI_FALSE; context.copy_stat = BROTLI_TRUE; context.test_integrity = BROTLI_FALSE; context.verbose = BROTLI_FALSE; context.write_to_stdout = BROTLI_FALSE; context.decompress = BROTLI_FALSE; context.large_window = BROTLI_FALSE; context.output_path = NULL; context.suffix = DEFAULT_SUFFIX; for (i = 0; i < MAX_OPTIONS; ++i) context.not_input_indices[i] = 0; context.longest_path_len = 1; context.input_count = 0; context.argc = argc; context.argv = argv; context.modified_path = NULL; context.iterator = 0; context.ignore = 0; context.iterator_error = BROTLI_FALSE; context.buffer = NULL; context.current_input_path = NULL; context.current_output_path = NULL; context.fin = NULL; context.fout = NULL; command = ParseParams(&context); if (command == COMMAND_COMPRESS || command == COMMAND_DECOMPRESS || command == COMMAND_TEST_INTEGRITY) { if (is_ok) { size_t modified_path_len = context.longest_path_len + strlen(context.suffix) + 1; context.modified_path = (char*)malloc(modified_path_len); context.buffer = (uint8_t*)malloc(kFileBufferSize * 2); if (!context.modified_path || !context.buffer) { fprintf(stderr, "out of memory\n"); is_ok = BROTLI_FALSE; } else { context.input = context.buffer; context.output = context.buffer + kFileBufferSize; } } } if (!is_ok) command = COMMAND_NOOP; switch (command) { case COMMAND_NOOP: break; case COMMAND_VERSION: PrintVersion(); break; case COMMAND_COMPRESS: is_ok = CompressFiles(&context); break; case COMMAND_DECOMPRESS: case COMMAND_TEST_INTEGRITY: is_ok = DecompressFiles(&context); break; case COMMAND_HELP: case COMMAND_INVALID: default: is_ok = (command == COMMAND_HELP); PrintHelp(FileName(argv[0]), is_ok); break; } if (context.iterator_error) is_ok = BROTLI_FALSE; free(context.modified_path); free(context.buffer); if (!is_ok) exit(1); return 0; }
{ "content_hash": "a03fe2a62f9781fde11dd5f9720dcb29", "timestamp": "", "source": "github", "line_count": 1057, "max_line_length": 80, "avg_line_length": 32.63576158940398, "alnum_prop": 0.5876623376623377, "repo_name": "ericstj/corefx", "id": "ce05b641b2bfa1b9354e9abc3864c89858580663", "size": "34662", "binary": false, "copies": "52", "ref": "refs/heads/master", "path": "src/Native/AnyOS/brotli/tools/brotli.c", "mode": "33188", "license": "mit", "language": [ { "name": "1C Enterprise", "bytes": "280724" }, { "name": "ASP", "bytes": "1687" }, { "name": "Batchfile", "bytes": "12277" }, { "name": "C", "bytes": "3790209" }, { "name": "C#", "bytes": "181917368" }, { "name": "C++", "bytes": "1521" }, { "name": "CMake", "bytes": "68305" }, { "name": "DIGITAL Command Language", "bytes": "26402" }, { "name": "Dockerfile", "bytes": "1332" }, { "name": "HTML", "bytes": "653" }, { "name": "Makefile", "bytes": "13780" }, { "name": "OpenEdge ABL", "bytes": "137969" }, { "name": "Perl", "bytes": "3895" }, { "name": "PowerShell", "bytes": "201656" }, { "name": "Python", "bytes": "1535" }, { "name": "Roff", "bytes": "9422" }, { "name": "Shell", "bytes": "131358" }, { "name": "TSQL", "bytes": "96941" }, { "name": "Visual Basic", "bytes": "2135386" }, { "name": "XSLT", "bytes": "514720" } ], "symlink_target": "" }
{{range $post := .posts}} <h4>名無しさん@Beego {{$post.Created|dateformatJst}}</h4> {{$post.Content|htmlquote|nl2br|str2html}} <hr /> {{end}} <div class="col-md-6"> <form action="/post/create" method="post" accept-charset="utf-8"> <div class="form-group"> <label>Content</label> <textarea name="content" class="form-control" required="required"></textarea> </div> <input class="btn btn-primary" type="submit" value="Post"/> </form> </div>
{ "content_hash": "d1443f6549f2aa9c9e0bd6eb2a266197", "timestamp": "", "source": "github", "line_count": 15, "max_line_length": 80, "avg_line_length": 30.133333333333333, "alnum_prop": 0.6548672566371682, "repo_name": "misfrog/beego-bbs", "id": "e7f8b870593f9193d1026f82fe34778bb0e8c11e", "size": "462", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "views/post/index.html", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "30" }, { "name": "Go", "bytes": "3766" }, { "name": "HTML", "bytes": "1826" } ], "symlink_target": "" }
Do similar datasets have similar formats?
{ "content_hash": "818ad3719ac36014d294b2b751f471d8", "timestamp": "", "source": "github", "line_count": 1, "max_line_length": 41, "avg_line_length": 42, "alnum_prop": 0.8333333333333334, "repo_name": "dguaderrama/bootcamp-pres", "id": "35ec14dae346410fb62cb44c47d9f6525c0ad5e6", "size": "68", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "slides/data-collection/4.md", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "273" }, { "name": "HTML", "bytes": "4495" }, { "name": "JavaScript", "bytes": "6571" } ], "symlink_target": "" }
package com.caucho.hessian.io; import java.util.*; import java.util.zip.*; import java.io.*; import com.caucho.hessian.io.*; public class Deflation extends HessianEnvelope { public Deflation() { } public Hessian2Output wrap(Hessian2Output out) throws IOException { OutputStream os = new DeflateOutputStream(out); Hessian2Output filterOut = new Hessian2Output(os); filterOut.setCloseStreamOnClose(true); return filterOut; } public Hessian2Input unwrap(Hessian2Input in) throws IOException { int version = in.readEnvelope(); String method = in.readMethod(); if (! method.equals(getClass().getName())) throw new IOException("expected hessian Envelope method '" + getClass().getName() + "' at '" + method + "'"); return unwrapHeaders(in); } public Hessian2Input unwrapHeaders(Hessian2Input in) throws IOException { InputStream is = new DeflateInputStream(in); Hessian2Input filter = new Hessian2Input(is); filter.setCloseStreamOnClose(true); return filter; } static class DeflateOutputStream extends OutputStream { private Hessian2Output _out; private OutputStream _bodyOut; private DeflaterOutputStream _deflateOut; DeflateOutputStream(Hessian2Output out) throws IOException { _out = out; _out.startEnvelope(Deflation.class.getName()); _out.writeInt(0); _bodyOut = _out.getBytesOutputStream(); _deflateOut = new DeflaterOutputStream(_bodyOut); } public void write(int ch) throws IOException { _deflateOut.write(ch); } public void write(byte []buffer, int offset, int length) throws IOException { _deflateOut.write(buffer, offset, length); } public void close() throws IOException { Hessian2Output out = _out; _out = null; if (out != null) { _deflateOut.close(); _bodyOut.close(); out.writeInt(0); out.completeEnvelope(); out.close(); } } } static class DeflateInputStream extends InputStream { private Hessian2Input _in; private InputStream _bodyIn; private InflaterInputStream _inflateIn; DeflateInputStream(Hessian2Input in) throws IOException { _in = in; int len = in.readInt(); if (len != 0) throw new IOException("expected no headers"); _bodyIn = _in.readInputStream(); _inflateIn = new InflaterInputStream(_bodyIn); } public int read() throws IOException { return _inflateIn.read(); } public int read(byte []buffer, int offset, int length) throws IOException { return _inflateIn.read(buffer, offset, length); } public void close() throws IOException { Hessian2Input in = _in; _in = null; if (in != null) { _inflateIn.close(); _bodyIn.close(); int len = in.readInt(); if (len != 0) throw new IOException("Unexpected footer"); in.completeEnvelope(); in.close(); } } } }
{ "content_hash": "6dbcca434e4026c652bf5fbc38830482", "timestamp": "", "source": "github", "line_count": 159, "max_line_length": 66, "avg_line_length": 19.68553459119497, "alnum_prop": 0.6230031948881789, "repo_name": "hhaip/langtaosha", "id": "0e3ae50ae3e4c66c76577020589df6a83c894640", "size": "5363", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "lts-hessian/src/main/java/com/caucho/hessian/io/Deflation.java", "mode": "33188", "license": "mit", "language": [ { "name": "HTML", "bytes": "3199" }, { "name": "Java", "bytes": "1241521" } ], "symlink_target": "" }
<?xml version="1.0" encoding="UTF-8"?> <!-- Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to You 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. --> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> <modelVersion>4.0.0</modelVersion> <parent> <groupId>org.apache.camel</groupId> <artifactId>components</artifactId> <version>3.1.0-SNAPSHOT</version> </parent> <artifactId>camel-twilio</artifactId> <packaging>jar</packaging> <name>Camel :: Twilio</name> <description>Camel Component for Twilio</description> <properties> <schemeName>twilio</schemeName> <componentName>Twilio</componentName> <componentPackage>org.apache.camel.component.twilio</componentPackage> <outPackage>org.apache.camel.component.twilio.internal</outPackage> <camel.osgi.private.pkg>${outPackage}</camel.osgi.private.pkg> </properties> <dependencies> <dependency> <groupId>org.apache.camel</groupId> <artifactId>camel-support</artifactId> </dependency> <!-- Twilio Java SDK --> <dependency> <groupId>com.twilio.sdk</groupId> <artifactId>twilio</artifactId> <version>${twilio-version}</version> </dependency> <!-- Camel annotations in provided scope to avoid compile errors in IDEs --> <dependency> <groupId>org.apache.camel</groupId> <artifactId>spi-annotations</artifactId> <version>${project.version}</version> <scope>provided</scope> </dependency> <!-- Component API javadoc in provided scope to read API signatures --> <dependency> <groupId>com.twilio.sdk</groupId> <artifactId>twilio</artifactId> <version>${twilio-version}</version> <type>javadoc</type> <scope>provided</scope> </dependency> <!-- logging --> <dependency> <groupId>org.apache.logging.log4j</groupId> <artifactId>log4j-api</artifactId> <scope>test</scope> </dependency> <dependency> <groupId>org.apache.logging.log4j</groupId> <artifactId>log4j-core</artifactId> <scope>test</scope> </dependency> <dependency> <groupId>org.apache.logging.log4j</groupId> <artifactId>log4j-slf4j-impl</artifactId> <scope>test</scope> </dependency> <!-- testing --> <dependency> <groupId>org.apache.camel</groupId> <artifactId>camel-test</artifactId> <scope>test</scope> </dependency> </dependencies> <build> <defaultGoal>install</defaultGoal> <plugins> <!-- generate Component source and test source --> <plugin> <groupId>org.apache.camel</groupId> <artifactId>camel-api-component-maven-plugin</artifactId> <executions> <execution> <id>generate-test-component-classes</id> <goals> <goal>fromApis</goal> </goals> <configuration> <apis> <api> <apiName>account</apiName> <proxyClass>com.twilio.rest.api.v2010.Account</proxyClass> <fromJavadoc> <includeMethods>creator|deleter|fetcher|reader|updater</includeMethods> <includeStaticMethods>true</includeStaticMethods> </fromJavadoc> </api> <!-- Package: com.twilio.rest.api.v2010.account --> <api> <apiName>address</apiName> <proxyClass>com.twilio.rest.api.v2010.account.Address</proxyClass> <fromJavadoc> <includeMethods>creator|deleter|fetcher|reader|updater</includeMethods> <includeStaticMethods>true</includeStaticMethods> </fromJavadoc> </api> <api> <apiName>application</apiName> <proxyClass>com.twilio.rest.api.v2010.account.Application</proxyClass> <fromJavadoc> <includeMethods>creator|deleter|fetcher|reader|updater</includeMethods> <includeStaticMethods>true</includeStaticMethods> </fromJavadoc> </api> <api> <apiName>available-phone-number-country</apiName> <proxyClass>com.twilio.rest.api.v2010.account.AvailablePhoneNumberCountry </proxyClass> <fromJavadoc> <includeMethods>creator|deleter|fetcher|reader|updater</includeMethods> <includeStaticMethods>true</includeStaticMethods> </fromJavadoc> </api> <api> <apiName>call</apiName> <proxyClass>com.twilio.rest.api.v2010.account.Call</proxyClass> <fromJavadoc> <includeMethods>creator|deleter|fetcher|reader|updater</includeMethods> <includeStaticMethods>true</includeStaticMethods> </fromJavadoc> </api> <api> <apiName>conference</apiName> <proxyClass>com.twilio.rest.api.v2010.account.Conference</proxyClass> <fromJavadoc> <includeMethods>creator|deleter|fetcher|reader|updater</includeMethods> <includeStaticMethods>true</includeStaticMethods> </fromJavadoc> </api> <api> <apiName>connect-app</apiName> <proxyClass>com.twilio.rest.api.v2010.account.ConnectApp</proxyClass> <fromJavadoc> <includeMethods>creator|deleter|fetcher|reader|updater</includeMethods> <includeStaticMethods>true</includeStaticMethods> </fromJavadoc> </api> <api> <apiName>incoming-phone-number</apiName> <proxyClass>com.twilio.rest.api.v2010.account.IncomingPhoneNumber</proxyClass> <fromJavadoc> <includeMethods>creator|deleter|fetcher|reader|updater</includeMethods> <includeStaticMethods>true</includeStaticMethods> </fromJavadoc> </api> <api> <apiName>key</apiName> <proxyClass>com.twilio.rest.api.v2010.account.Key</proxyClass> <fromJavadoc> <includeMethods>creator|deleter|fetcher|reader|updater</includeMethods> <includeStaticMethods>true</includeStaticMethods> </fromJavadoc> </api> <api> <apiName>message</apiName> <proxyClass>com.twilio.rest.api.v2010.account.Message</proxyClass> <fromJavadoc> <includeMethods>creator|deleter|fetcher|reader|updater</includeMethods> <includeStaticMethods>true</includeStaticMethods> </fromJavadoc> </api> <api> <apiName>new-key</apiName> <proxyClass>com.twilio.rest.api.v2010.account.NewKey</proxyClass> <fromJavadoc> <includeMethods>creator|deleter|fetcher|reader|updater</includeMethods> <includeStaticMethods>true</includeStaticMethods> </fromJavadoc> </api> <api> <apiName>new-signing-key</apiName> <proxyClass>com.twilio.rest.api.v2010.account.NewSigningKey</proxyClass> <fromJavadoc> <includeMethods>creator|deleter|fetcher|reader|updater</includeMethods> <includeStaticMethods>true</includeStaticMethods> </fromJavadoc> </api> <api> <apiName>notification</apiName> <proxyClass>com.twilio.rest.api.v2010.account.Notification</proxyClass> <fromJavadoc> <includeMethods>creator|deleter|fetcher|reader|updater</includeMethods> <includeStaticMethods>true</includeStaticMethods> </fromJavadoc> </api> <api> <apiName>outgoing-caller-id</apiName> <proxyClass>com.twilio.rest.api.v2010.account.OutgoingCallerId</proxyClass> <fromJavadoc> <includeMethods>creator|deleter|fetcher|reader|updater</includeMethods> <includeStaticMethods>true</includeStaticMethods> </fromJavadoc> </api> <api> <apiName>queue</apiName> <proxyClass>com.twilio.rest.api.v2010.account.Queue</proxyClass> <fromJavadoc> <includeMethods>creator|deleter|fetcher|reader|updater</includeMethods> <includeStaticMethods>true</includeStaticMethods> </fromJavadoc> </api> <api> <apiName>recording</apiName> <proxyClass>com.twilio.rest.api.v2010.account.Recording</proxyClass> <fromJavadoc> <includeMethods>creator|deleter|fetcher|reader|updater</includeMethods> <includeStaticMethods>true</includeStaticMethods> </fromJavadoc> </api> <api> <apiName>short-code</apiName> <proxyClass>com.twilio.rest.api.v2010.account.ShortCode</proxyClass> <fromJavadoc> <includeMethods>creator|deleter|fetcher|reader|updater</includeMethods> <includeStaticMethods>true</includeStaticMethods> </fromJavadoc> </api> <api> <apiName>signing-key</apiName> <proxyClass>com.twilio.rest.api.v2010.account.SigningKey</proxyClass> <fromJavadoc> <includeMethods>creator|deleter|fetcher|reader|updater</includeMethods> <includeStaticMethods>true</includeStaticMethods> </fromJavadoc> </api> <api> <apiName>token</apiName> <proxyClass>com.twilio.rest.api.v2010.account.Token</proxyClass> <fromJavadoc> <includeMethods>creator|deleter|fetcher|reader|updater</includeMethods> <includeStaticMethods>true</includeStaticMethods> </fromJavadoc> </api> <api> <apiName>transcription</apiName> <proxyClass>com.twilio.rest.api.v2010.account.Transcription</proxyClass> <fromJavadoc> <includeMethods>creator|deleter|fetcher|reader|updater</includeMethods> <includeStaticMethods>true</includeStaticMethods> </fromJavadoc> </api> <api> <apiName>validation-request</apiName> <proxyClass>com.twilio.rest.api.v2010.account.ValidationRequest</proxyClass> <fromJavadoc> <includeMethods>creator|deleter|fetcher|reader|updater</includeMethods> <includeStaticMethods>true</includeStaticMethods> </fromJavadoc> </api> <!-- Package: com.twilio.rest.api.v2010.account.address --> <api> <apiName>address-dependent-phone-number</apiName> <proxyClass>com.twilio.rest.api.v2010.account.address.DependentPhoneNumber </proxyClass> <fromJavadoc> <includeMethods>creator|deleter|fetcher|reader|updater</includeMethods> <includeStaticMethods>true</includeStaticMethods> </fromJavadoc> </api> <!-- Package: com.twilio.rest.api.v2010.account.availablephonenumbercountry --> <api> <apiName>available-phone-number-country-local</apiName> <proxyClass>com.twilio.rest.api.v2010.account.availablephonenumbercountry.Local </proxyClass> <fromJavadoc> <includeMethods>creator|deleter|fetcher|reader|updater</includeMethods> <includeStaticMethods>true</includeStaticMethods> </fromJavadoc> </api> <api> <apiName>available-phone-number-country-mobile</apiName> <proxyClass>com.twilio.rest.api.v2010.account.availablephonenumbercountry.Mobile </proxyClass> <fromJavadoc> <includeMethods>creator|deleter|fetcher|reader|updater</includeMethods> <includeStaticMethods>true</includeStaticMethods> </fromJavadoc> </api> <api> <apiName>available-phone-number-country-toll-free</apiName> <proxyClass>com.twilio.rest.api.v2010.account.availablephonenumbercountry.TollFree </proxyClass> <fromJavadoc> <includeMethods>creator|deleter|fetcher|reader|updater</includeMethods> <includeStaticMethods>true</includeStaticMethods> </fromJavadoc> </api> <!-- Package: com.twilio.rest.api.v2010.account.call --> <api> <apiName>call-feedback</apiName> <proxyClass>com.twilio.rest.api.v2010.account.call.Feedback</proxyClass> <fromJavadoc> <includeMethods>creator|deleter|fetcher|reader|updater</includeMethods> <includeStaticMethods>true</includeStaticMethods> </fromJavadoc> </api> <api> <apiName>call-feedback-summary</apiName> <proxyClass>com.twilio.rest.api.v2010.account.call.FeedbackSummary</proxyClass> <fromJavadoc> <includeMethods>creator|deleter|fetcher|reader|updater</includeMethods> <includeStaticMethods>true</includeStaticMethods> </fromJavadoc> </api> <api> <apiName>call-notification</apiName> <proxyClass>com.twilio.rest.api.v2010.account.call.Notification</proxyClass> <fromJavadoc> <includeMethods>creator|deleter|fetcher|reader|updater</includeMethods> <includeStaticMethods>true</includeStaticMethods> </fromJavadoc> </api> <api> <apiName>call-recording</apiName> <proxyClass>com.twilio.rest.api.v2010.account.call.Recording</proxyClass> <fromJavadoc> <includeMethods>creator|deleter|fetcher|reader|updater</includeMethods> <includeStaticMethods>true</includeStaticMethods> </fromJavadoc> </api> <!-- Package: com.twilio.rest.api.v2010.account.conference --> <api> <apiName>conference-participant</apiName> <proxyClass>com.twilio.rest.api.v2010.account.conference.Participant</proxyClass> <fromJavadoc> <includeMethods>creator|deleter|fetcher|reader|updater</includeMethods> <includeStaticMethods>true</includeStaticMethods> </fromJavadoc> </api> <!-- Package: com.twilio.rest.api.v2010.account.incomingphonenumber --> <api> <apiName>incoming-phone-number-local</apiName> <proxyClass>com.twilio.rest.api.v2010.account.incomingphonenumber.Local</proxyClass> <fromJavadoc> <includeMethods>creator|deleter|fetcher|reader|updater</includeMethods> <includeStaticMethods>true</includeStaticMethods> </fromJavadoc> </api> <api> <apiName>incoming-phone-number-mobile</apiName> <proxyClass>com.twilio.rest.api.v2010.account.incomingphonenumber.Mobile </proxyClass> <fromJavadoc> <includeMethods>creator|deleter|fetcher|reader|updater</includeMethods> <includeStaticMethods>true</includeStaticMethods> </fromJavadoc> </api> <api> <apiName>incoming-phone-number-toll-free</apiName> <proxyClass>com.twilio.rest.api.v2010.account.incomingphonenumber.TollFree </proxyClass> <fromJavadoc> <includeMethods>creator|deleter|fetcher|reader|updater</includeMethods> <includeStaticMethods>true</includeStaticMethods> </fromJavadoc> </api> <!-- Package: com.twilio.rest.api.v2010.account.message --> <api> <apiName>message-feedback</apiName> <proxyClass>com.twilio.rest.api.v2010.account.message.Feedback</proxyClass> <fromJavadoc> <includeMethods>creator|deleter|fetcher|reader|updater</includeMethods> <includeStaticMethods>true</includeStaticMethods> </fromJavadoc> </api> <api> <apiName>message-media</apiName> <proxyClass>com.twilio.rest.api.v2010.account.message.Media</proxyClass> <fromJavadoc> <includeMethods>creator|deleter|fetcher|reader|updater</includeMethods> <includeStaticMethods>true</includeStaticMethods> </fromJavadoc> </api> <!-- Package: com.twilio.rest.api.v2010.account.queue --> <api> <apiName>queue-member</apiName> <proxyClass>com.twilio.rest.api.v2010.account.queue.Member</proxyClass> <fromJavadoc> <includeMethods>creator|deleter|fetcher|reader|updater</includeMethods> <includeStaticMethods>true</includeStaticMethods> </fromJavadoc> </api> <!-- Package: com.twilio.rest.api.v2010.account.recording --> <api> <apiName>recording-add-on-result</apiName> <proxyClass>com.twilio.rest.api.v2010.account.recording.AddOnResult</proxyClass> <fromJavadoc> <includeMethods>creator|deleter|fetcher|reader|updater</includeMethods> <includeStaticMethods>true</includeStaticMethods> </fromJavadoc> </api> <api> <apiName>recording-transcription</apiName> <proxyClass>com.twilio.rest.api.v2010.account.recording.Transcription</proxyClass> <fromJavadoc> <includeMethods>creator|deleter|fetcher|reader|updater</includeMethods> <includeStaticMethods>true</includeStaticMethods> </fromJavadoc> </api> <!-- Package: com.twilio.rest.api.v2010.account.recording.addonresult --> <api> <apiName>recording-add-on-result-payload</apiName> <proxyClass>com.twilio.rest.api.v2010.account.recording.addonresult.Payload </proxyClass> <fromJavadoc> <includeMethods>creator|deleter|fetcher|reader|updater</includeMethods> <includeStaticMethods>true</includeStaticMethods> </fromJavadoc> </api> <!-- Package: com.twilio.rest.api.v2010.account.sip --> <api> <apiName>sip-credential-list</apiName> <proxyClass>com.twilio.rest.api.v2010.account.sip.CredentialList</proxyClass> <fromJavadoc> <includeMethods>creator|deleter|fetcher|reader|updater</includeMethods> <includeStaticMethods>true</includeStaticMethods> </fromJavadoc> </api> <api> <apiName>sip-domain</apiName> <proxyClass>com.twilio.rest.api.v2010.account.sip.Domain</proxyClass> <fromJavadoc> <includeMethods>creator|deleter|fetcher|reader|updater</includeMethods> <includeStaticMethods>true</includeStaticMethods> </fromJavadoc> </api> <api> <apiName>sip-ip-access-control-list</apiName> <proxyClass>com.twilio.rest.api.v2010.account.sip.IpAccessControlList</proxyClass> <fromJavadoc> <includeMethods>creator|deleter|fetcher|reader|updater</includeMethods> <includeStaticMethods>true</includeStaticMethods> </fromJavadoc> </api> <!-- Package: com.twilio.rest.api.v2010.account.sip.credentiallist --> <api> <apiName>sip-credential-list-credential</apiName> <proxyClass>com.twilio.rest.api.v2010.account.sip.credentiallist.Credential </proxyClass> <fromJavadoc> <includeMethods>creator|deleter|fetcher|reader|updater</includeMethods> <includeStaticMethods>true</includeStaticMethods> </fromJavadoc> </api> <!-- Package: com.twilio.rest.api.v2010.account.sip.domain --> <api> <apiName>sip-domain-credential-list-mapping</apiName> <proxyClass>com.twilio.rest.api.v2010.account.sip.domain.CredentialListMapping </proxyClass> <fromJavadoc> <includeMethods>creator|deleter|fetcher|reader|updater</includeMethods> <includeStaticMethods>true</includeStaticMethods> </fromJavadoc> </api> <api> <apiName>sip-domain-ip-access-control-list-mapping</apiName> <proxyClass> com.twilio.rest.api.v2010.account.sip.domain.IpAccessControlListMapping </proxyClass> <fromJavadoc> <includeMethods>creator|deleter|fetcher|reader|updater</includeMethods> <includeStaticMethods>true</includeStaticMethods> </fromJavadoc> </api> <!-- Package: com.twilio.rest.api.v2010.account.sip.ipaccesscontrollist --> <api> <apiName>sip-ip-access-control-list-ip-address</apiName> <proxyClass>com.twilio.rest.api.v2010.account.sip.ipaccesscontrollist.IpAddress </proxyClass> <fromJavadoc> <includeMethods>creator|deleter|fetcher|reader|updater</includeMethods> <includeStaticMethods>true</includeStaticMethods> </fromJavadoc> </api> <!-- Package: com.twilio.rest.api.v2010.account.usage --> <api> <apiName>usage-record</apiName> <proxyClass>com.twilio.rest.api.v2010.account.usage.Record</proxyClass> <fromJavadoc> <includeMethods>creator|deleter|fetcher|reader|updater</includeMethods> <includeStaticMethods>true</includeStaticMethods> </fromJavadoc> </api> <api> <apiName>usage-trigger</apiName> <proxyClass>com.twilio.rest.api.v2010.account.usage.Trigger</proxyClass> <fromJavadoc> <includeMethods>creator|deleter|fetcher|reader|updater</includeMethods> <includeStaticMethods>true</includeStaticMethods> </fromJavadoc> </api> <!-- Package: com.twilio.rest.api.v2010.account.usage.record --> <api> <apiName>usage-record-all-time</apiName> <proxyClass>com.twilio.rest.api.v2010.account.usage.record.AllTime</proxyClass> <fromJavadoc> <includeMethods>creator|deleter|fetcher|reader|updater</includeMethods> <includeStaticMethods>true</includeStaticMethods> </fromJavadoc> </api> <api> <apiName>usage-record-daily</apiName> <proxyClass>com.twilio.rest.api.v2010.account.usage.record.Daily</proxyClass> <fromJavadoc> <includeMethods>creator|deleter|fetcher|reader|updater</includeMethods> <includeStaticMethods>true</includeStaticMethods> </fromJavadoc> </api> <api> <apiName>usage-record-last-month</apiName> <proxyClass>com.twilio.rest.api.v2010.account.usage.record.LastMonth</proxyClass> <fromJavadoc> <includeMethods>creator|deleter|fetcher|reader|updater</includeMethods> <includeStaticMethods>true</includeStaticMethods> </fromJavadoc> </api> <api> <apiName>usage-record-monthly</apiName> <proxyClass>com.twilio.rest.api.v2010.account.usage.record.Monthly</proxyClass> <fromJavadoc> <includeMethods>creator|deleter|fetcher|reader|updater</includeMethods> <includeStaticMethods>true</includeStaticMethods> </fromJavadoc> </api> <api> <apiName>usage-record-this-month</apiName> <proxyClass>com.twilio.rest.api.v2010.account.usage.record.ThisMonth</proxyClass> <fromJavadoc> <includeMethods>creator|deleter|fetcher|reader|updater</includeMethods> <includeStaticMethods>true</includeStaticMethods> </fromJavadoc> </api> <api> <apiName>usage-record-today</apiName> <proxyClass>com.twilio.rest.api.v2010.account.usage.record.Today</proxyClass> <fromJavadoc> <includeMethods>creator|deleter|fetcher|reader|updater</includeMethods> <includeStaticMethods>true</includeStaticMethods> </fromJavadoc> </api> <api> <apiName>usage-record-yearly</apiName> <proxyClass>com.twilio.rest.api.v2010.account.usage.record.Yearly</proxyClass> <fromJavadoc> <includeMethods>creator|deleter|fetcher|reader|updater</includeMethods> <includeStaticMethods>true</includeStaticMethods> </fromJavadoc> </api> <api> <apiName>usage-record-yesterday</apiName> <proxyClass>com.twilio.rest.api.v2010.account.usage.record.Yesterday</proxyClass> <fromJavadoc> <includeMethods>creator|deleter|fetcher|reader|updater</includeMethods> <includeStaticMethods>true</includeStaticMethods> </fromJavadoc> </api> </apis> <aliases> <alias> <methodPattern>^creator$</methodPattern> <methodAlias>create</methodAlias> </alias> <alias> <methodPattern>^deleter$</methodPattern> <methodAlias>delete</methodAlias> </alias> <alias> <methodPattern>^fetcher$</methodPattern> <methodAlias>fetch</methodAlias> </alias> <alias> <methodPattern>^reader$</methodPattern> <methodAlias>read</methodAlias> </alias> <alias> <methodPattern>^updater$</methodPattern> <methodAlias>update</methodAlias> </alias> </aliases> </configuration> </execution> </executions> </plugin> <!-- add generated source and test source to build --> <plugin> <groupId>org.codehaus.mojo</groupId> <artifactId>build-helper-maven-plugin</artifactId> <executions> <execution> <id>add-generated-sources</id> <goals> <goal>add-source</goal> </goals> <configuration> <sources> <source>${project.build.directory}/generated-sources/camel-component</source> </sources> </configuration> </execution> <execution> <id>add-generated-test-sources</id> <goals> <goal>add-test-source</goal> </goals> <configuration> <sources> <source>${project.build.directory}/generated-test-sources/camel-component</source> </sources> </configuration> </execution> </executions> </plugin> </plugins> <pluginManagement> <plugins> <plugin> <groupId>org.apache.camel</groupId> <artifactId>camel-api-component-maven-plugin</artifactId> <version>${project.version}</version> <configuration> <scheme>${schemeName}</scheme> <componentName>${componentName}</componentName> <componentPackage>${componentPackage}</componentPackage> <outPackage>${outPackage}</outPackage> </configuration> </plugin> </plugins> </pluginManagement> </build> <reporting> <plugins> <plugin> <groupId>org.apache.camel</groupId> <artifactId>camel-api-component-maven-plugin</artifactId> <version>${project.version}</version> <configuration> <scheme>${schemeName}</scheme> <componentName>${componentName}</componentName> <componentPackage>${componentPackage}</componentPackage> <outPackage>${outPackage}</outPackage> </configuration> </plugin> </plugins> </reporting> <profiles> <profile> <id>twilio-test</id> <build> <plugins> <plugin> <artifactId>maven-surefire-plugin</artifactId> <version>${maven-surefire-plugin-version}</version> <configuration> <childDelegation>false</childDelegation> <useFile>true</useFile> <forkCount>1</forkCount> <reuseForks>true</reuseForks> <forkedProcessTimeoutInSeconds>300</forkedProcessTimeoutInSeconds> <excludes> <exclude>**/*XXXTest.java</exclude> </excludes> <includes> <include>**/*Test.java</include> </includes> </configuration> </plugin> </plugins> </build> </profile> </profiles> </project>
{ "content_hash": "b63924decb6cf4ae218bec1001cde9a3", "timestamp": "", "source": "github", "line_count": 714, "max_line_length": 201, "avg_line_length": 60.476190476190474, "alnum_prop": 0.4189207966651227, "repo_name": "objectiser/camel", "id": "2e11d0009da63ecbf514f48492b1092c99fd5bfb", "size": "43180", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "components/camel-twilio/pom.xml", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Apex", "bytes": "6521" }, { "name": "Batchfile", "bytes": "2353" }, { "name": "CSS", "bytes": "5472" }, { "name": "Elm", "bytes": "10852" }, { "name": "FreeMarker", "bytes": "8015" }, { "name": "Groovy", "bytes": "14479" }, { "name": "HTML", "bytes": "915679" }, { "name": "Java", "bytes": "84762041" }, { "name": "JavaScript", "bytes": "100326" }, { "name": "Makefile", "bytes": "513" }, { "name": "RobotFramework", "bytes": "8461" }, { "name": "Shell", "bytes": "17240" }, { "name": "TSQL", "bytes": "28835" }, { "name": "Tcl", "bytes": "4974" }, { "name": "Thrift", "bytes": "6979" }, { "name": "XQuery", "bytes": "546" }, { "name": "XSLT", "bytes": "280849" } ], "symlink_target": "" }
<?php namespace Bitpay\Resource; use Bitpay\Resource\Token; use Bitpay\Resource\Invoice; use Bitpay\Resource\Payout; use Bitpay\Crypto\PublicKey; use Bitpay\Crypto\PrivateKey; use Bitpay\Network\Network; use Bitpay\Network\Adapter; use Bitpay\Network\Request; use Bitpay\Network\Response; use Bitpay\Network\CurlAdapter; /** * Client used to send requests and receive responses for BitPay's Web API * * @package Bitpay */ class Client extends Resource { /** * @var Request */ private $request; /** * @var Response */ private $response; /** * @var AdapterInterface */ private $adapter; /** * @var PublicKey */ private $publicKey; /** * @var PrivateKey */ private $privateKey; /** * @var NetworkInterface */ private $network; /** * The network is either livenet or testnet and tells the client where to * send the requests. * * @param NetworkInterface */ public function setNetwork(Network $network) { $this->network = $network; } /** * Set the Public Key to use to help identify who you are to BitPay. Please * note that you must first pair your keys and get a token in return to use. * * @param PublicKey $key */ public function setPublicKey(PublicKey $key) { $this->publicKey = $key; } /** * Set the Private Key to use, this is used when signing request strings * * @param PrivateKey $key */ public function setPrivateKey(PrivateKey $key) { $this->privateKey = $key; } /** * @param Adapter $adapter */ public function setAdapter(Adapter $adapter) { $this->adapter = $adapter; } /** * @inheritdoc */ public function createInvoice(Invoice $invoice) { $request = $this->createNewRequest(); $request->setMethod(Request::METHOD_POST); $request->setPath('invoices'); $currency = $invoice->getCurrency(); $item = $invoice->getItem(); $buyer = $invoice->getBuyer(); $buyerAddress = $buyer->getAddress(); $body = array( 'price' => $item->getPrice(), 'currency' => $currency->getCode(), 'posData' => $invoice->getPosData(), 'notificationURL' => $invoice->getNotificationUrl(), 'transactionSpeed' => $invoice->getTransactionSpeed(), 'fullNotifications' => $invoice->isFullNotifications(), 'notificationEmail' => $invoice->getNotificationEmail(), 'redirectURL' => $invoice->getRedirectUrl(), 'orderID' => $invoice->getOrderId(), 'itemDesc' => $item->getDescription(), 'itemCode' => $item->getCode(), 'physical' => $item->isPhysical(), 'buyerName' => trim(sprintf('%s %s', $buyer->getFirstName(), $buyer->getLastName())), 'buyerAddress1' => isset($buyerAddress[0]) ? $buyerAddress[0] : '', 'buyerAddress2' => isset($buyerAddress[1]) ? $buyerAddress[1] : '', 'buyerCity' => $buyer->getCity(), 'buyerState' => $buyer->getState(), 'buyerZip' => $buyer->getZip(), 'buyerCountry' => $buyer->getCountry(), 'buyerEmail' => $buyer->getEmail(), 'buyerPhone' => $buyer->getPhone(), 'guid' => Network::guid(), 'nonce' => Network::nonce(), 'token' => $this->token->getToken(), ); $request->setBody(json_encode($body)); $this->addIdentityHeader($request); $this->addSignatureHeader($request); $this->request = $request; $this->response = $this->sendRequest($request); $body = json_decode($this->response->getBody(), true); if (isset($body['error']) || isset($body['errors'])) { throw new \Exception('[ERROR] In Client::createInvoice: The response to our invoice creation request contained errors. The actual response returned was: ' . var_export($this->response, true)); } $data = $body['data']; $invoice ->setId($data['id']) ->setUrl($data['url']) ->setStatus($data['status']) ->setBtcPrice($data['btcPrice']) ->setPrice($data['price']) ->setInvoiceTime($data['invoiceTime']) ->setExpirationTime($data['expirationTime']) ->setCurrentTime($data['currentTime']) ->setBtcPaid($data['btcPaid']) ->setRate($data['rate']) ->setExceptionStatus($data['exceptionStatus']); return $invoice; } /** * @inheritdoc */ public function getCurrencies() { $this->request = $this->createNewRequest(); $this->request->setMethod(Request::METHOD_GET); $this->request->setPath('currencies'); $this->response = $this->sendRequest($this->request); $body = json_decode($this->response->getBody(), true); if (true === empty($body['data'])) { throw new \Exception('[ERROR] In Client::getCurrencies: The data parameter in the response was empty. The actual response returned was: ' . var_export($this->response, true)); } $currencies = $body['data']; $currency = new Currency(); if (false === isset($currency) || true === empty($currency)) { throw new \Exception('[ERROR] In Client::getCurrencies: Could not create new Currency object.'); } array_walk($currencies, function (&$value, $key) { $currency ->setCode($value['code']) ->setSymbol($value['symbol']) ->setPrecision($value['precision']) ->setExchangePctFee($value['exchangePctFee']) ->setPayoutEnabled($value['payoutEnabled']) ->setName($value['name']) ->setPluralName($value['plural']) ->setAlts($value['alts']) ->setPayoutFields($value['payoutFields']); $value = $currency; }); return $currencies; } /** * @inheritdoc */ public function createPayout(Payout $payout) { $request = $this->createNewRequest(); $request->setMethod($request::METHOD_POST); $request->setPath('payouts'); $amount = $payout->getAmount(); $currency = $payout->getCurrency(); $effectiveDate = $payout->getEffectiveDate(); $token = $payout->getToken(); $body = array( 'token' => $token->getToken(), 'amount' => $amount, 'currency' => $currency->getCode(), 'instructions' => array(), 'effectiveDate' => $effectiveDate, 'pricingMethod' => $payout->getPricingMethod(), 'guid' => Network::guid(), 'nonce' => Network::nonce() ); // Optional foreach (array('reference','notificationURL','notificationEmail') as $value) { $function = 'get' . ucfirst($value); if ($payout->$function() != null) { $body[$value] = $payout->$function(); } } // Add instructions foreach ($payout->getInstructions() as $instruction) { $body['instructions'][] = array( 'label' => $instruction->getLabel(), 'address' => $instruction->getAddress(), 'amount' => $instruction->getAmount() ); } $request->setBody(json_encode($body)); $this->addIdentityHeader($request); $this->addSignatureHeader($request); $this->request = $request; $this->response = $this->sendRequest($request); $body = json_decode($this->response->getBody(), true); if (isset($body['error']) || isset($body['errors'])) { throw new \Exception('[ERROR] In Client::createPayout: The response to our payout request contained errors. The actual response returned was: ' . var_export($this->response, true)); } $data = $body['data']; $payout ->setId($data['id']) ->setAccountId($data['account']) ->setResponseToken($data['token']) ->setStatus($data['status']); foreach ($data['instructions'] as $c => $instruction) { $payout->updateInstruction($c, 'setId', $instruction['id']); } return $payout; } /** * @inheritdoc */ public function getPayouts($status = null) { $request = $this->createNewRequest(); $request->setMethod(Request::METHOD_GET); $path = 'payouts?token=' . $this->token->getToken() . (($status == null) ? '' : '&status=' . $status); $request->setPath($path); $this->addIdentityHeader($request); $this->addSignatureHeader($request); $this->request = $request; $this->response = $this->sendRequest($this->request); $body = json_decode($this->response->getBody(), true); if (isset($body['error']) || isset($body['errors'])) { throw new \Exception('[ERROR] In Client::getPayouts: The response to our payout request contained errors. The actual response returned was: ' . var_export($this->response, true)); } $payouts = array(); array_walk($body['data'], function ($value, $key) use (&$payouts) { $payout = new Payout(); $payout ->setId($value['id']) ->setAccountId($value['account']) ->setCurrency(new Currency($value['currency'])) ->setEffectiveDate($value['effectiveDate']) ->setRequestdate($value['requestDate']) ->setPricingMethod($value['pricingMethod']) ->setStatus($value['status']) ->setAmount($value['amount']) ->setResponseToken($value['token']) ->setRate(@$value['rate']) ->setBtcAmount(@$value['btc']) ->setReference(@$value['reference']) ->setNotificationURL(@$value['notificationURL']) ->setNotificationEmail(@$value['notificationEmail']); array_walk($value['instructions'], function ($value, $key) use (&$payout) { $instruction = new PayoutInstruction(); $instruction ->setId($value['id']) ->setLabel($value['label']) ->setAddress($value['address']) ->setAmount($value['amount']) ->setStatus($value['status']); array_walk($value['transactions'], function ($value, $key) use (&$instruction) { $transaction = new PayoutTransaction(); $transaction ->setTransactionId($value['txid']) ->setAmount($value['amount']) ->setDate($value['date']); $instruction->addTransaction($transaction); }); $payout->addInstruction($instruction); }); $payouts[] = $payout; }); return $payouts; } /** * @inheritdoc */ public function deletePayout(PayoutInterface $payout) { $request = $this->createNewRequest(); $request->setMethod(Request::METHOD_DELETE); $request->setPath(sprintf('payouts/%s?token=%s', $payout->getId(), $payout->getResponseToken())); $this->addIdentityHeader($request); $this->addSignatureHeader($request); $this->request = $request; $this->response = $this->sendRequest($this->request); $body = json_decode($this->response->getBody(), true); if (empty($body['data'])) { throw new \Exception('[ERROR] In Client::deletePayout: The response to our payout request contained errors. The actual response returned was: ' . var_export($this->response, true)); } $data = $body['data']; $payout->setStatus($data['status']); return $payout; } /** * @inheritdoc */ public function getPayout($payoutId) { $request = $this->createNewRequest(); $request->setMethod(Request::METHOD_GET); $request->setPath(sprintf('payouts/%s?token=%s', $payoutId, $this->token->getToken())); $this->addIdentityHeader($request); $this->addSignatureHeader($request); $this->request = $request; $this->response = $this->sendRequest($this->request); $body = json_decode($this->response->getBody(), true); if (empty($body['data'])) { throw new \Exception('[ERROR] In Client::getPayout: The response to our payout retrieval request contained errors. The actual response returned was: ' . var_export($this->response, true)); } $data = $body['data']; $payout = new Payout(); $payout ->setId($data['id']) ->setAccountId($data['account']) ->setStatus($data['status']) ->setCurrency(new Currency($data['currency'])) ->setRate(@$data['rate']) ->setAmount($data['amount']) ->setBtcAmount(@$data['btc']) ->setPricingMethod(@$data['pricingMethod']) ->setReference(@$data['reference']) ->setNotificationEmail(@$data['notificationEmail']) ->setNotificationUrl(@$data['notificationURL']) ->setRequestDate($data['requestDate']) ->setEffectiveDate($data['effectiveDate']) ->setResponseToken($data['token']); array_walk($data['instructions'], function ($value, $key) use (&$payout) { $instruction = new PayoutInstruction(); $instruction ->setId($value['id']) ->setLabel($value['label']) ->setAddress($value['address']) ->setStatus($value['status']) ->setAmount($value['amount']) ->setBtc($value['btc']); array_walk($value['transactions'], function ($value, $key) use (&$instruction) { $transaction = new PayoutTransaction(); $transaction ->setTransactionId($value['txid']) ->setAmount($value['amount']) ->setDate($value['date']); $instruction->addTransaction($transaction); }); $payout->addInstruction($instruction); }); return $payout; } /** * @inheritdoc */ public function getTokens() { $request = $this->createNewRequest(); $request->setMethod(Request::METHOD_GET); $request->setPath('tokens'); $this->addIdentityHeader($request); $this->addSignatureHeader($request); $this->request = $request; $this->response = $this->sendRequest($this->request); $body = json_decode($this->response->getBody(), true); if (empty($body['data'])) { throw new \Exception('[ERROR] In Client::getTokens: The response to our token retrieval request contained errors. The actual response returned was: ' . var_export($this->response, true)); } $tokens = array(); array_walk($body['data'], function ($value, $key) use (&$tokens) { $key = current(array_keys($value)); $value = current(array_values($value)); $token = new Token(); $token ->setFacade($key) ->setToken($value); $tokens[$token->getFacade()] = $token; }); return $tokens; } /** * @inheritdoc */ public function createToken(array $payload = array()) { if ($payload !== array()) { if (1 !== preg_match('/^[a-zA-Z0-9]{7}$/', $payload['pairingCode'])) { throw new \Exception('[ERROR] In Client::createToken: The pairing code value provided is missing or invalid.'); } } $payload['guid'] = Network::guid(); $this->request = $this->createNewRequest(); $this->request->setMethod(Request::METHOD_POST); $this->request->setPath('tokens'); $this->request->setBody(json_encode($payload)); $this->response = $this->sendRequest($this->request); $body = json_decode($this->response->getBody(), true); if (isset($body['error'])) { throw new \Exception('[ERROR] In Client::createToken: The response to our token creation request contained errors. The actual response returned was: ' . var_export($this->response, true)); } $tkn = $body['data'][0]; $token = new Token(); $token ->setPolicies($tkn['policies']) ->setResource($tkn['resource']) ->setToken($tkn['token']) ->setFacade($tkn['facade']) ->setCreatedAt($tkn['dateCreated']); return $token; } /** * Returns the Response object that BitPay returned from the request that * was sent * * @return ResponseInterface */ public function getResponse() { return $this->response; } /** * Returns the request object that was sent to BitPay * * @return RequestInterface */ public function getRequest() { return $this->request; } /** * @inheritdoc */ public function getInvoice($invoiceId) { $this->request = $this->createNewRequest(); $this->request->setMethod(Request::METHOD_GET); $this->request->setPath(sprintf('invoices/%s', $invoiceId)); $this->response = $this->sendRequest($this->request); $body = json_decode($this->response->getBody(), true); if (isset($body['error'])) { throw new \Exception('[ERROR] In Client::getInvoice: The response to our invoice retrieval request contained errors. The actual response returned was: ' . var_export($this->response, true)); } $data = $body['data']; $invoice = new Invoice(); $invoice //->setToken($data['token']) //->setBtcDue($data['btcDue']) //->setExRates($data['exRates']) ->setUrl($data['url']) ->setPosData($data['posData']) ->setStatus($data['status']) ->setBtcPrice($data['btcPrice']) ->setPrice($data['price']) ->setCurrency(new Currency($data['currency'])) ->setOrderId($data['orderId']) ->setInvoiceTime($data['invoiceTime']) ->setExpirationTime($data['expirationTime']) ->setCurrentTime($data['currentTime']) ->setId($data['id']) ->setBtcPaid($data['btcPrice']) ->setRate($data['rate']) ->setExceptionStatus($data['exceptionStatus']); return $invoice; } /** * @param Request * @return Response */ public function sendRequest(Request $request) { if (null === $this->adapter) { // Uses the default adapter $this->adapter = new CurlAdapter(); } return $this->adapter->sendRequest($request); } /** * @param Request * @throws \Exception */ public function addIdentityHeader(Request $request) { if (null === $this->publicKey) { throw new \Exception('Please set your Public Key.'); } $request->setHeader('x-identity', (string) $this->publicKey); } /** * @param Request */ public function addSignatureHeader(Request $request) { if (null === $this->privateKey) { throw new \Exception('Please set your Private Key'); } if (true == property_exists($this->network, 'isPortRequiredInUrl')) { if ($this->network->isPortRequiredInUrl === true) { $url = $request->getUriWithPort(); } else { $url = $request->getUri(); } } else { $url = $request->getUri(); } $message = sprintf( '%s%s', $url, $request->getBody() ); $signature = $this->privateKey->sign($message); $request->setHeader('x-signature', $signature); } /** * Creates new request object and prepares some networking * parameters. * * @return Request */ public function createNewRequest() { $request = new Request(); $request->setHost($this->network->getApiHost()); $request->setPort($this->network->getApiPort()); $this->prepareRequestHeaders($request); return $request; } /** * Prepares the request object by adding additional headers * * @param Request */ private function prepareRequestHeaders(Request $request) { // @see http://en.wikipedia.org/wiki/User_agent $request->setHeader( 'User-Agent', sprintf('%s/%s (PHP %s)', self::NAME, self::VERSION, phpversion()) ); $request->setHeader('X-BitPay-Plugin-Info', sprintf('%s/%s', self::NAME, self::VERSION)); $request->setHeader('Content-Type', 'application/json'); $request->setHeader('X-Accept-Version', '2.0.0'); } }
{ "content_hash": "d1634b83a0047b1eef6717d669d3b0c0", "timestamp": "", "source": "github", "line_count": 671, "max_line_length": 204, "avg_line_length": 32.478390461997016, "alnum_prop": 0.5301702381498646, "repo_name": "ionux/php-bitpay-client", "id": "794adb807c254e6f64ea3e760153749b40561086", "size": "21928", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/Bitpay/Resource/Client.php", "mode": "33188", "license": "mit", "language": [ { "name": "Cucumber", "bytes": "2748" }, { "name": "Makefile", "bytes": "145" }, { "name": "PHP", "bytes": "351163" }, { "name": "Shell", "bytes": "2086" } ], "symlink_target": "" }
package org.apache.hadoop.hdfs; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.FSDataOutputStream; import org.apache.hadoop.fs.Path; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; import java.io.IOException; /** This is a comprehensive append test that tries * all combinations of file length and number of appended bytes * In each iteration, it creates a file of len1. Then reopen * the file for append. It first append len2 bytes, calls hflush, * append len3 bytes and close the file. Afterwards, the content of * the file is validated. * Len1 ranges from [0, 2*BLOCK_SIZE+1], len2 ranges from [0, BLOCK_SIZE+1], * and len3 ranges from [0, BLOCK_SIZE+1]. * */ public class FileAppendTest4 { public static final Log LOG = LogFactory.getLog(FileAppendTest4.class); private static final int BYTES_PER_CHECKSUM = 4; private static final int PACKET_SIZE = BYTES_PER_CHECKSUM; private static final int BLOCK_SIZE = 2*PACKET_SIZE; private static final short REPLICATION = 3; private static final int DATANODE_NUM = 5; private static Configuration conf; private static MiniDFSCluster cluster; private static DistributedFileSystem fs; private static void init(Configuration conf) { conf.setInt(DFSConfigKeys.DFS_BYTES_PER_CHECKSUM_KEY, BYTES_PER_CHECKSUM); conf.setLong(DFSConfigKeys.DFS_BLOCK_SIZE_KEY, BLOCK_SIZE); conf.setInt(DFSConfigKeys.DFS_CLIENT_WRITE_PACKET_SIZE_KEY, PACKET_SIZE); conf.setBoolean(DFSConfigKeys.DFS_SUPPORT_APPEND_KEY, true); } @BeforeClass public static void startUp () throws IOException { conf = new HdfsConfiguration(); init(conf); cluster = new MiniDFSCluster.Builder(conf).numDataNodes(DATANODE_NUM).build(); fs = (DistributedFileSystem)cluster.getFileSystem(); } @AfterClass public static void tearDown() throws IOException { cluster.shutdown(); } /** * Comprehensive test for append * @throws IOException an exception might be thrown */ @Test public void testAppend() throws IOException { final int maxOldFileLen = 2*BLOCK_SIZE+1; final int maxFlushedBytes = BLOCK_SIZE; byte[] contents = AppendTestUtil.initBuffer( maxOldFileLen+2*maxFlushedBytes); for (int oldFileLen =0; oldFileLen <=maxOldFileLen; oldFileLen++) { for (int flushedBytes1=0; flushedBytes1<=maxFlushedBytes; flushedBytes1++) { for (int flushedBytes2=0; flushedBytes2 <=maxFlushedBytes; flushedBytes2++) { final int fileLen = oldFileLen + flushedBytes1 + flushedBytes2; // create the initial file of oldFileLen final Path p = new Path("foo"+ oldFileLen +"_"+ flushedBytes1 +"_"+ flushedBytes2); LOG.info("Creating file " + p); FSDataOutputStream out = fs.create(p, false, conf.getInt("io.file.buffer.size", 4096), REPLICATION, BLOCK_SIZE); out.write(contents, 0, oldFileLen); out.close(); // append flushedBytes bytes to the file out = fs.append(p); out.write(contents, oldFileLen, flushedBytes1); out.hflush(); // write another flushedBytes2 bytes to the file out.write(contents, oldFileLen + flushedBytes1, flushedBytes2); out.close(); // validate the file content AppendTestUtil.checkFullFile(fs, p, fileLen, contents, p.toString()); fs.delete(p, false); } } } } }
{ "content_hash": "5b6f3509a694d01362bb1f49373baee9", "timestamp": "", "source": "github", "line_count": 99, "max_line_length": 82, "avg_line_length": 36.96969696969697, "alnum_prop": 0.6792349726775956, "repo_name": "moreus/hadoop", "id": "7f2c1aecd67779c9cc55991dd0e0693f09b2854f", "size": "4466", "binary": false, "copies": "5", "ref": "refs/heads/master", "path": "hadoop-0.23.10/hadoop-hdfs-project/hadoop-hdfs/src/test/java/org/apache/hadoop/hdfs/FileAppendTest4.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "AspectJ", "bytes": "31146" }, { "name": "C", "bytes": "1067911" }, { "name": "C++", "bytes": "521803" }, { "name": "CSS", "bytes": "157107" }, { "name": "Erlang", "bytes": "232" }, { "name": "Java", "bytes": "43984644" }, { "name": "JavaScript", "bytes": "87848" }, { "name": "Perl", "bytes": "18992" }, { "name": "Python", "bytes": "32767" }, { "name": "Shell", "bytes": "1369281" }, { "name": "TeX", "bytes": "19322" }, { "name": "XSLT", "bytes": "185841" } ], "symlink_target": "" }
@interface ProjectSelectionViewController : UITableViewController { NSDictionary * projects; id target; SEL action; } @property (nonatomic, retain) NSDictionary * projects; @property (nonatomic, assign) id target; // Takes method with signature like: // - (void)selectedProject:(id)projectKey; @property(nonatomic) SEL action; @end
{ "content_hash": "5c9f0bdd5c18d23efce7355310bf1be9", "timestamp": "", "source": "github", "line_count": 17, "max_line_length": 65, "avg_line_length": 20.705882352941178, "alnum_prop": 0.7357954545454546, "repo_name": "highorderbit/bug-watch", "id": "2ffe15659e90a5e29aee5a706fe42f42c57e9317", "size": "445", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/Classes/shared/ProjectSelectionViewController.h", "mode": "33188", "license": "mit", "language": [ { "name": "Objective-C", "bytes": "516570" } ], "symlink_target": "" }
// ========================================================================== // SeqAn - The Library for Sequence Analysis // ========================================================================== // Copyright (c) 2006-2010, Knut Reinert, FU Berlin // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of Knut Reinert or the FU Berlin nor the names of // its contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL KNUT REINERT OR THE FU BERLIN BE LIABLE // FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL // DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR // SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER // CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT // LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY // OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH // DAMAGE. // // ========================================================================== #ifndef SEQAN_HEADER_MISC_DEQUEUE_H #define SEQAN_HEADER_MISC_DEQUEUE_H #include <algorithm> #include <seqan/sequence.h> ////////////////////////////////////////////////////////////////////////////// namespace SEQAN_NAMESPACE_MAIN { /** .Class.Dequeue: ..cat:Miscellaneous ..summary:A double-ended queue implementation on top of a @Class.String@. ..signature:Dequeue<TValue, TSpec> ..param.TValue:Type of the ungapped sequences. ...metafunction:Metafunction.Value ..param.TSpec:The specializing type of the underlying @Class.String@. ...metafunction:Metafunction.Spec ...default:$Alloc<>$, see @Spec.Alloc String@ ..include:seqan/misc.h */ template <typename TValue, typename TSpec = Alloc<> > class Dequeue { public: typedef String<TValue, TSpec> TString; typedef typename Iterator<TString, Standard>::Type TIter; String<TValue, TSpec> data_string; TIter data_begin; // string beginning TIter data_end; // string end TIter data_front; // front fifo character TIter data_back; // back fifo character bool data_empty; // fifo is empty //____________________________________________________________________________ public: inline Dequeue() { clear(*this); } }; ////////////////////////////////////////////////////////////////////////////// // Iterators ////////////////////////////////////////////////////////////////////////////// ///.Metafunction.Iterator.param.T.type:Class.Dequeue template<typename TValue, typename TSpec> struct Iterator<Dequeue<TValue, TSpec>, Standard> { typedef Iter<Dequeue<TValue, TSpec>, PositionIterator> Type; }; template<typename TValue, typename TSpec> struct Iterator<Dequeue<TValue, TSpec> const, Standard> { typedef Iter<Dequeue<TValue, TSpec> const, PositionIterator> Type; }; template<typename TValue, typename TSpec> struct Iterator<Dequeue<TValue, TSpec>, Rooted> { typedef Iter<Dequeue<TValue, TSpec>, PositionIterator> Type; }; template<typename TValue, typename TSpec> struct Iterator<Dequeue<TValue, TSpec> const, Rooted> { typedef Iter<Dequeue<TValue, TSpec> const, PositionIterator> Type; }; ////////////////////////////////////////////////////////////////////////////// template <typename TValue, typename TSpec> inline bool empty(Dequeue<TValue, TSpec> const &me) { return me.data_empty; } ////////////////////////////////////////////////////////////////////////////// template <typename TValue, typename TSpec> inline void clear(Dequeue<TValue, TSpec> &me) { clear(me.data_string); me.data_begin = begin(me.data_string, Standard()); me.data_end = end(me.data_string, Standard()); me.data_front = me.data_back = me.data_begin; me.data_empty = true; } ////////////////////////////////////////////////////////////////////////////// template <typename TValue, typename TSpec, typename TPos> inline TValue & value(Dequeue<TValue, TSpec> &me, TPos pos) { typedef typename Size<Dequeue<TValue, TSpec> >::Type TSize; TSize wrap = length(me.data_string) - (me.data_front - me.data_begin); if ((TSize)pos < wrap) return value(me.data_front + pos); else return value(me.data_begin + (pos - wrap)); } template <typename TValue, typename TSpec, typename TPos> inline TValue const & value(Dequeue<TValue, TSpec> const &me, TPos pos) { typedef typename Size<Dequeue<TValue, TSpec> >::Type TSize; TSize wrap = length(me.data_string) - (me.data_front - me.data_begin); if ((TSize)pos < wrap) return value(me.data_front + pos); else return value(me.data_begin + (pos - wrap)); } ////////////////////////////////////////////////////////////////////////////// template <typename TValue, typename TSpec> inline TValue & front(Dequeue<TValue, TSpec> &me) { return *me.data_front; } template <typename TValue, typename TSpec> inline TValue const & front(Dequeue<TValue, TSpec> const &me) { return *me.data_front; } ////////////////////////////////////////////////////////////////////////////// template <typename TValue, typename TSpec> inline TValue & back(Dequeue<TValue, TSpec> &me) { return *me.data_back; } template <typename TValue, typename TSpec> inline TValue const & back(Dequeue<TValue, TSpec> const &me) { return *me.data_back; } ////////////////////////////////////////////////////////////////////////////// template <typename TValue, typename TSpec> inline bool popFront(Dequeue<TValue, TSpec> &me) { if (me.data_empty) return false; if (me.data_front == me.data_back) me.data_empty = true; else { if (++me.data_front == me.data_end) me.data_front = me.data_begin; } return true; } template <typename TValue, typename TSpec> inline bool popBack(Dequeue<TValue, TSpec> &me) { if (me.data_empty) return false; if (me.data_front == me.data_back) me.data_empty = true; else { if (me.data_back == me.data_begin) me.data_back = me.data_end; --me.data_back; } return true; } ////////////////////////////////////////////////////////////////////////////// template <typename TValue, typename TSpec> inline void pushFront(Dequeue<TValue, TSpec> &me, TValue const & _value) { typedef typename Dequeue<TValue, TSpec>::TIter TIter; if (me.data_empty) { if (me.data_begin == me.data_end) reserve(me, computeGenerousCapacity(me, length(me.data_string) + 1), Generous()); me.data_empty = false; } else { TIter new_front = me.data_front; if (new_front == me.data_begin) new_front = me.data_end; --new_front; if (new_front == me.data_back) { reserve(me, computeGenerousCapacity(me, length(me.data_string) + 1), Generous()); if (me.data_front == me.data_begin) me.data_front = me.data_end; --me.data_front; } else me.data_front = new_front; } assign(*me.data_front, _value); } template <typename TValue, typename TSpec> inline void pushBack(Dequeue<TValue, TSpec> &me, TValue const & _value) { typedef typename Dequeue<TValue, TSpec>::TIter TIter; if (me.data_empty) { if (me.data_begin == me.data_end) reserve(me, computeGenerousCapacity(me, length(me.data_string) + 1), Generous()); me.data_empty = false; } else { TIter new_back = me.data_back; if (++new_back == me.data_end) new_back = me.data_begin; if (new_back == me.data_front) { reserve(me, computeGenerousCapacity(me, length(me.data_string) + 1), Generous()); // in this case reserve adds new space behind data_back ++me.data_back; } else me.data_back = new_back; } assign(*me.data_back, _value); } ////////////////////////////////////////////////////////////////////////////// template <typename TValue, typename TSpec> inline typename Size<Dequeue<TValue, TSpec> >::Type length(Dequeue<TValue, TSpec> const &me) { if (empty(me)) return 0; if (me.data_front <= me.data_back) return (me.data_back - me.data_front) + 1; else return (me.data_end - me.data_begin) - (me.data_front - me.data_back) + 1; } ////////////////////////////////////////////////////////////////////////////// template <typename TValue, typename TSpec, typename TSize_, typename TExpand> inline typename Size<Dequeue<TValue, TSpec> >::Type reserve(Dequeue<TValue, TSpec> &me, TSize_ new_capacity, Tag<TExpand> const tag) { typedef typename Size<Dequeue<TValue, TSpec> >::Type TSize; // ::std::cout << "resize to "<<new_capacity<<::std::endl; TSize len = length(me); if (len < new_capacity && length(me.data_string) != new_capacity) { TSize pos_front = me.data_front - me.data_begin; TSize pos_back = me.data_back - me.data_begin; TSize new_freeSpace = new_capacity - len; if (pos_front <= pos_back) { // |empty|data|empty| // 0 TSize freeSpace = length(me.data_string) - len; if (new_freeSpace > freeSpace) resize(me.data_string, new_capacity, tag); else { freeSpace -= new_freeSpace; // reduce the free space by <freeSpace> if (pos_front >= freeSpace) { resizeSpace(me.data_string, pos_front - freeSpace, (TSize)0, pos_front, tag); pos_back -= freeSpace; pos_front -= freeSpace; } else { freeSpace -= pos_front; resizeSpace(me.data_string, length(me.data_string) - freeSpace, pos_back + 1, length(me.data_string), tag); resizeSpace(me.data_string, (TSize)0, (TSize)0, pos_front, tag); pos_back -= pos_front; pos_front = 0; } } } else { // |data|empty|data| // 0 resizeSpace(me.data_string, new_freeSpace, pos_back + 1, pos_front, tag); pos_front += new_freeSpace; } me.data_begin = begin(me.data_string, Standard()); me.data_end = end(me.data_string, Standard()); me.data_front = me.data_begin + pos_front; me.data_back = me.data_begin + pos_back; } return length(me.data_string); } } #endif
{ "content_hash": "a916bdf86d78e73021b9515a330bb9cc", "timestamp": "", "source": "github", "line_count": 369, "max_line_length": 112, "avg_line_length": 28.533875338753386, "alnum_prop": 0.6144933042074271, "repo_name": "bkahlert/seqan-research", "id": "f9dc2bb161d167f9789e3fd27113867a4ca6e90a", "size": "10529", "binary": false, "copies": "6", "ref": "refs/heads/master", "path": "raw/workshop11/seqan-trunk/core/include/seqan/misc/misc_dequeue.h", "mode": "33188", "license": "mit", "language": [ { "name": "ApacheConf", "bytes": "39014" }, { "name": "Awk", "bytes": "44044" }, { "name": "Batchfile", "bytes": "37736" }, { "name": "C", "bytes": "1261223" }, { "name": "C++", "bytes": "277576131" }, { "name": "CMake", "bytes": "5546616" }, { "name": "CSS", "bytes": "271972" }, { "name": "GLSL", "bytes": "2280" }, { "name": "Groff", "bytes": "2694006" }, { "name": "HTML", "bytes": "15207297" }, { "name": "JavaScript", "bytes": "362928" }, { "name": "LSL", "bytes": "22561" }, { "name": "Makefile", "bytes": "6418610" }, { "name": "Objective-C", "bytes": "3730085" }, { "name": "PHP", "bytes": "3302" }, { "name": "Perl", "bytes": "10468" }, { "name": "PostScript", "bytes": "22762" }, { "name": "Python", "bytes": "9267035" }, { "name": "R", "bytes": "230698" }, { "name": "Rebol", "bytes": "283" }, { "name": "Shell", "bytes": "437340" }, { "name": "Tcl", "bytes": "15439" }, { "name": "TeX", "bytes": "738415" }, { "name": "VimL", "bytes": "12685" } ], "symlink_target": "" }
package org.apache.shardingsphere.elasticjob.cloud.scheduler.statistics; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertThat; import org.junit.Before; import org.junit.Test; public class TaskResultMetaDataTest { private TaskResultMetaData metaData; @Before public void setUp() { metaData = new TaskResultMetaData(); } @Test public void assertIncrementAndGet() { for (int i = 0; i < 100; i++) { assertThat(metaData.incrementAndGetSuccessCount(), is(i + 1)); assertThat(metaData.incrementAndGetFailedCount(), is(i + 1)); assertThat(metaData.getSuccessCount(), is(i + 1)); assertThat(metaData.getFailedCount(), is(i + 1)); } } @Test public void assertReset() { for (int i = 0; i < 100; i++) { metaData.incrementAndGetSuccessCount(); metaData.incrementAndGetFailedCount(); } metaData.reset(); assertThat(metaData.getSuccessCount(), is(0)); assertThat(metaData.getFailedCount(), is(0)); } }
{ "content_hash": "21c07f49a3bd5ba8fde5d326045dc518", "timestamp": "", "source": "github", "line_count": 41, "max_line_length": 74, "avg_line_length": 27.365853658536587, "alnum_prop": 0.6238859180035651, "repo_name": "elasticjob/elastic-job", "id": "0680293c7c89087c9f952359551264528c0e2c82", "size": "1923", "binary": false, "copies": "4", "ref": "refs/heads/master", "path": "elasticjob-cloud/elasticjob-cloud-scheduler/src/test/java/org/apache/shardingsphere/elasticjob/cloud/scheduler/statistics/TaskResultMetaDataTest.java", "mode": "33261", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "553" }, { "name": "CSS", "bytes": "102201" }, { "name": "HTML", "bytes": "189227" }, { "name": "Java", "bytes": "1743175" }, { "name": "JavaScript", "bytes": "704805" }, { "name": "Shell", "bytes": "1889" } ], "symlink_target": "" }
This folder contains the Main model, view and controller.
{ "content_hash": "80fa79fa2862991e6430b6ee075f6f8e", "timestamp": "", "source": "github", "line_count": 1, "max_line_length": 57, "avg_line_length": 57, "alnum_prop": 0.8245614035087719, "repo_name": "nohuhu/HTML5-StarterKit", "id": "cf18c6a41f6c82a3a5c2d87e7883267d1ad2ffbd", "size": "57", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "htdocs/app/view/main/Readme.md", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "357" }, { "name": "HTML", "bytes": "1302" }, { "name": "JavaScript", "bytes": "133767" }, { "name": "PLSQL", "bytes": "2754" }, { "name": "Perl", "bytes": "18455" }, { "name": "Ruby", "bytes": "56" } ], "symlink_target": "" }
<?php class Home_model extends CI_Model { public function __construct() { parent::__construct(); } function get_home_image() { return $this->db->get("home")->result(); } function get_front_works() { return $this->db->get("front_works")->result(); } }
{ "content_hash": "c484f06f80b70c29c55a27b979f8517b", "timestamp": "", "source": "github", "line_count": 17, "max_line_length": 55, "avg_line_length": 18, "alnum_prop": 0.5424836601307189, "repo_name": "christianlimanto95/ericwee", "id": "10c2f7a0fb5c09d9bb0f51f15d5fa54fb040f0cd", "size": "306", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "application/models/Home_model.php", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "58410" }, { "name": "HTML", "bytes": "5633" }, { "name": "JavaScript", "bytes": "39603" }, { "name": "PHP", "bytes": "1829270" } ], "symlink_target": "" }
A reactive forms library with Bootstrap
{ "content_hash": "39178f5349c590dd3ec91d91f55e6638", "timestamp": "", "source": "github", "line_count": 1, "max_line_length": 39, "avg_line_length": 40, "alnum_prop": 0.85, "repo_name": "intellifactory/websharper.forms.bootstrap", "id": "7b1f3cc46a7a42ecfbf404e35c1fae5886bfaee2", "size": "69", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "README.md", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "784" }, { "name": "F#", "bytes": "12867" }, { "name": "HTML", "bytes": "2408" }, { "name": "Shell", "bytes": "324" } ], "symlink_target": "" }
@protocol CardSelectedDelegate - (void) cardSelected:(PaymentCard*)card; @end @interface ListCardsViewController : UITableViewController<PaymentCardAddedDelegate> @property (strong) id<CardSelectedDelegate>cardSelectedDelegate; @property (strong) NSMutableArray *cardList; @end
{ "content_hash": "c1847e4ae3fc7b7a832761cd7ae6865f", "timestamp": "", "source": "github", "line_count": 9, "max_line_length": 84, "avg_line_length": 31.11111111111111, "alnum_prop": 0.8357142857142857, "repo_name": "paymentez/paymentez-ios", "id": "0e5dbfe85ac7886187f3257eedf58097729f7e20", "size": "499", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "PaymentSDKObjC/PaymentSDKObjC/ListCardsViewController.h", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "1001" }, { "name": "Objective-C", "bytes": "150727" }, { "name": "Shell", "bytes": "9571" }, { "name": "Swift", "bytes": "240141" } ], "symlink_target": "" }
require 'fileutils' module TwitterCldr module Resources class SegmentTestsImporter < Importer TEST_FILES = [ 'ucd/auxiliary/WordBreakTest.txt', 'ucd/auxiliary/SentenceBreakTest.txt' ] requirement :unicode, Versions.unicode_version, TEST_FILES output_path 'shared/segments/tests' ruby_engine :mri def execute TEST_FILES.each do |test_file| import_test_file(test_file) end end private def import_test_file(test_file) source_file = source_path_for(test_file) FileUtils.mkdir_p(File.dirname(source_file)) result = UnicodeFileParser.parse_standard_file(source_file).map(&:first) File.write(output_path_for(test_file), YAML.dump(result)) end def source_path_for(test_file) requirements[:unicode].source_path_for(test_file) end def output_path_for(test_file) file = underscore(File.basename(test_file).chomp(File.extname(test_file))) File.join(params.fetch(:output_path), "#{file}.yml") end def underscore(str) str.gsub(/(.)([A-Z])/, '\1_\2').downcase end end end end
{ "content_hash": "b619aff0e3608bbe94b6fcdee7c55584", "timestamp": "", "source": "github", "line_count": 46, "max_line_length": 82, "avg_line_length": 25.76086956521739, "alnum_prop": 0.6253164556962025, "repo_name": "surfdome/twitter-cldr-rb", "id": "c5cfe7cbf30c46a6e8123dcf3bfb062c22240aec", "size": "1280", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "lib/twitter_cldr/resources/segment_tests_importer.rb", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "HTML", "bytes": "1981" }, { "name": "Max", "bytes": "36457" }, { "name": "Ruby", "bytes": "868187" }, { "name": "Shell", "bytes": "1398" } ], "symlink_target": "" }
extern const char FILE_nitc__astbuilder[]; #define COLOR_nitc__astbuilder__ASTBuilder___anchor 1 val* NEW_nitc__AIntegerExpr(const struct type* type); extern const struct type type_nitc__AIntegerExpr; val* nitc__model___MModule___int_type(val* self); void nitc__astbuilder___AIntegerExpr___make(val* self, long p0, val* p1); val* NEW_nitc__ANewExpr(const struct type* type); extern const struct type type_nitc__ANewExpr; void nitc__astbuilder___ANewExpr___make(val* self, val* p0, val* p1); val* NEW_nitc__ACallExpr(const struct type* type); extern const struct type type_nitc__ACallExpr; void nitc__astbuilder___ACallExpr___make(val* self, val* p0, val* p1, val* p2); val* NEW_nitc__ABlockExpr(const struct type* type); extern const struct type type_nitc__ABlockExpr; void nitc__astbuilder___ABlockExpr___make(val* self); val* NEW_nitc__ALoopExpr(const struct type* type); extern const struct type type_nitc__ALoopExpr; void nitc__astbuilder___ALoopExpr___make(val* self); val* NEW_nitc__AVarExpr(const struct type* type); extern const struct type type_nitc__AVarExpr; void nitc__astbuilder___AVarExpr___make(val* self, val* p0, val* p1); val* NEW_nitc__AVarAssignExpr(const struct type* type); extern const struct type type_nitc__AVarAssignExpr; void nitc__astbuilder___AVarAssignExpr___make(val* self, val* p0, val* p1); #define COLOR_nitc__model__MProperty___intro 15 extern const char FILE_nitc__model[]; #define COLOR_nitc__model__MAttributeDef___static_mtype 15 #define COLOR_nitc__typing__AExpr__mtype 41 #define COLOR_nitc__model__MType__resolve_for 27 val* NEW_nitc__AAttrExpr(const struct type* type); extern const struct type type_nitc__AAttrExpr; void nitc__astbuilder___AAttrExpr___make(val* self, val* p0, val* p1, val* p2); val* NEW_nitc__AAttrAssignExpr(const struct type* type); extern const struct type type_nitc__AAttrAssignExpr; void nitc__astbuilder___AAttrAssignExpr___make(val* self, val* p0, val* p1, val* p2); val* NEW_nitc__ADoExpr(const struct type* type); extern const struct type type_nitc__ADoExpr; void nitc__astbuilder___ADoExpr___make(val* self); val* NEW_nitc__ABreakExpr(const struct type* type); extern const struct type type_nitc__ABreakExpr; void nitc__astbuilder___ABreakExpr___make(val* self, val* p0); val* NEW_nitc__AIfExpr(const struct type* type); extern const struct type type_nitc__AIfExpr; void nitc__astbuilder___AIfExpr___make(val* self, val* p0, val* p1); #define COLOR_nitc___nitc__ASTBuilder___core__kernel__Object__init 28 #define COLOR_nitc__astbuilder__AExpr___variable_cache 5 #define COLOR_nitc__parser_nodes__ANode___parent 2 #define COLOR_core__kernel__Object___61d_61d 4 val* nitc__astbuilder___AExpr___detach_with_placeholder(val* self); val* NEW_nitc__Variable(const struct type* type); extern const struct type type_nitc__Variable; val* core__flat___NativeString___to_s_full(char* self, long p0, long p1); #define COLOR_nitc__scope__Variable__name_61d 12 #define COLOR_core__kernel__Object__init 0 #define COLOR_nitc__typing__Variable___declared_type 0 void nitc__transform___AExpr___nitc__parser_nodes__ANode__replace_with(val* self, val* p0); val* NEW_nitc__APlaceholderExpr(const struct type* type); extern const struct type type_nitc__APlaceholderExpr; void nitc___nitc__APlaceholderExpr___make(val* self); val* NEW_core__NativeArray(int length, const struct type* type); extern const struct type type_core__NativeArray__core__String; val* core__abstract_text___Object___inspect(val* self); #define COLOR_core__abstract_text__NativeArray__native_to_s 12 void core__file___Sys___print(val* self, val* p0); #define COLOR_nitc__typing__AExpr___is_typed 7 #define COLOR_nitc__parser_nodes__ABlockExpr___n_expr 12 extern const char FILE_nitc__parser_nodes[]; void core___core__Sequence___SimpleCollection__add(val* self, val* p0); val* NEW_nitc__TKwloop(const struct type* type); extern const struct type type_nitc__TKwloop; #define COLOR_nitc__parser_nodes__ALoopExpr___n_kwloop 13 void nitc__parser_prod___ALoopExpr___n_block_61d(val* self, val* p0); #define COLOR_nitc__parser_nodes__ALoopExpr___n_block 14 extern const char FILE_nitc__typing[]; #define COLOR_nitc__astbuilder__AExpr__add 49 val* NEW_nitc__TKwdo(const struct type* type); extern const struct type type_nitc__TKwdo; #define COLOR_nitc__parser_nodes__ADoExpr___n_kwdo 13 void nitc__parser_prod___ADoExpr___n_block_61d(val* self, val* p0); #define COLOR_nitc__parser_nodes__ADoExpr___n_block 14 val* NEW_nitc__TKwbreak(const struct type* type); extern const struct type type_nitc__TKwbreak; #define COLOR_nitc__parser_nodes__ABreakExpr___n_kwbreak 15 #define COLOR_nitc__scope__AEscapeExpr___escapemark 14 #define COLOR_nitc__scope__EscapeMark___escapes 2 extern const char FILE_nitc__scope[]; void core___core__Array___core__abstract_collection__SimpleCollection__add(val* self, val* p0); val* NEW_nitc__TKwif(const struct type* type); extern const struct type type_nitc__TKwif; #define COLOR_nitc__parser_nodes__AIfExpr___n_kwif 12 #define COLOR_nitc__parser_nodes__AIfExpr___n_expr 13 val* NEW_nitc__TKwthen(const struct type* type); extern const struct type type_nitc__TKwthen; #define COLOR_nitc__parser_nodes__AIfExpr___n_kwthen 14 #define COLOR_nitc__parser_nodes__AIfExpr___n_then 15 val* NEW_nitc__TKwelse(const struct type* type); extern const struct type type_nitc__TKwelse; #define COLOR_nitc__parser_nodes__AIfExpr___n_kwelse 16 #define COLOR_nitc__parser_nodes__AIfExpr___n_else 17 #define COLOR_nitc__typing__AExpr___mtype 6 val* NEW_nitc__TClassid(const struct type* type); extern const struct type type_nitc__TClassid; val* NEW_nitc__AQclassid(const struct type* type); extern const struct type type_nitc__AQclassid; void nitc__parser_prod___AQclassid___n_id_61d(val* self, val* p0); #define COLOR_nitc__parser_nodes__AType___n_qid 8 #define COLOR_nitc__literal__AIntegerExpr___value 13 val* NEW_nitc__TInteger(const struct type* type); extern const struct type type_nitc__TInteger; #define COLOR_nitc__parser_nodes__AIntegerExpr___n_integer 12 val* NEW_nitc__TKwnew(const struct type* type); extern const struct type type_nitc__TKwnew; #define COLOR_nitc__parser_nodes__ANewExpr___n_kwnew 12 val* NEW_nitc__AType(const struct type* type); extern const struct type type_nitc__AType; void nitc__astbuilder___AType___make(val* self); #define COLOR_nitc__parser_nodes__ANewExpr___n_type 13 val* NEW_nitc__AListExprs(const struct type* type); extern const struct type type_nitc__AListExprs; #define COLOR_nitc__parser_nodes__ANewExpr___n_args 15 #define COLOR_nitc__parser_nodes__AExprs___n_exprs 5 void core___core__SimpleCollection___add_all(val* self, val* p0); #define COLOR_nitc__typing__ANewExpr___callsite 16 #define COLOR_nitc__typing__CallSite___recv 7 extern const struct type type_nitc__MClassType; #define COLOR_nitc__typing__ANewExpr___recvtype 17 #define COLOR_nitc__typing__CallSite___mproperty 11 #define COLOR_nitc__model__MMethod___is_new 21 #define COLOR_nitc__typing__CallSite___msignature 13 #define COLOR_nitc__model__MSignature___return_mtype 10 #define COLOR_nitc__parser_nodes__ASendExpr___n_expr 12 #define COLOR_nitc__parser_nodes__ACallFormExpr___n_args 19 val* NEW_nitc__AQid(const struct type* type); extern const struct type type_nitc__AQid; #define COLOR_nitc__parser_nodes__ACallFormExpr___n_qid 18 val* NEW_nitc__TId(const struct type* type); extern const struct type type_nitc__TId; void nitc__parser_prod___AQid___n_id_61d(val* self, val* p0); #define COLOR_nitc__typing__ASendExpr___callsite 13 #define COLOR_nitc__parser_nodes__AAttrFormExpr___n_expr 12 val* NEW_nitc__TAttrid(const struct type* type); extern const struct type type_nitc__TAttrid; #define COLOR_nitc__parser_nodes__AAttrFormExpr___n_id 13 #define COLOR_nitc__typing__AAttrFormExpr___mproperty 18 #define COLOR_nitc__parser_nodes__AAssignFormExpr___n_value 15 val* NEW_nitc__TAssign(const struct type* type); extern const struct type type_nitc__TAssign; #define COLOR_nitc__parser_nodes__AAssignFormExpr___n_assign 14 #define COLOR_nitc__parser_nodes__AVarFormExpr___n_id 12 #define COLOR_nitc__scope__AVarFormExpr___variable 13
{ "content_hash": "bb54314f33a8c3b17f8ceeb07ea220b3", "timestamp": "", "source": "github", "line_count": 150, "max_line_length": 95, "avg_line_length": 53.84, "alnum_prop": 0.7472758791480931, "repo_name": "ventilooo/nit", "id": "3abc135d5e3c153a4cced57d77d7779911af1263", "size": "8155", "binary": false, "copies": "8", "ref": "refs/heads/master", "path": "c_src/nitc__astbuilder.sep.0.h", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Brainfuck", "bytes": "4335" }, { "name": "C", "bytes": "25437399" }, { "name": "C++", "bytes": "84" }, { "name": "CSS", "bytes": "172541" }, { "name": "Go", "bytes": "350" }, { "name": "HTML", "bytes": "29881" }, { "name": "Haskell", "bytes": "770" }, { "name": "Java", "bytes": "34401" }, { "name": "JavaScript", "bytes": "351845" }, { "name": "Makefile", "bytes": "108733" }, { "name": "Nit", "bytes": "6984375" }, { "name": "Objective-C", "bytes": "545017" }, { "name": "Perl", "bytes": "21800" }, { "name": "Python", "bytes": "849" }, { "name": "Ruby", "bytes": "145" }, { "name": "Shell", "bytes": "126122" }, { "name": "VimL", "bytes": "24755" }, { "name": "XSLT", "bytes": "3225" } ], "symlink_target": "" }
/** * Yepnope CSS Force prefix * * Use a combination of any prefix, and they should work * Usage: ['css!genStyles.php?234', 'normal-styles.css' ] * * Official Yepnope Plugin * * WTFPL License * * by Alex Sexton | [email protected] */ ( function ( yepnope ) { // add each prefix yepnope.addPrefix( 'css', function ( resource ) { // Set the force flag resource.forceCSS = true; //carry on return resource; } ); } )( this.yepnope );
{ "content_hash": "9510ec081a8476a9055efd3ecb135daf", "timestamp": "", "source": "github", "line_count": 21, "max_line_length": 57, "avg_line_length": 22.142857142857142, "alnum_prop": 0.6344086021505376, "repo_name": "TheGiftsProject/isc_analytics", "id": "601a29cd5473d537cbbfc35ecdd125cc81eb89d8", "size": "465", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "vendor/assets/javascripts/isc_analytics/yepnope/css_prefix.js", "mode": "33261", "license": "mit", "language": [ { "name": "CoffeeScript", "bytes": "2256" }, { "name": "JavaScript", "bytes": "6997" }, { "name": "Ruby", "bytes": "33567" } ], "symlink_target": "" }
import {IApplication, IUser} from '../../../../db/interfaces'; import talksUnreadCount from '../../../../endpoints/talks/messages/unread/count'; export default function( app: IApplication, user: IUser, req: any, res: any ): void { talksUnreadCount( user ).then(count => { res(count); }, (err: any) => { res({error: err}).code(500); }); }
{ "content_hash": "4bbcf6988dda92cf317a8dc5e0f117a4", "timestamp": "", "source": "github", "line_count": 17, "max_line_length": 81, "avg_line_length": 20.764705882352942, "alnum_prop": 0.623229461756374, "repo_name": "sirotama/misskey-api", "id": "827517693ba442839ab4b78091d7af8fbfe6fc0c", "size": "353", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "src/rest-handlers/talks/messages/unread/count.ts", "mode": "33261", "license": "mit", "language": [ { "name": "JavaScript", "bytes": "158" }, { "name": "TypeScript", "bytes": "228256" } ], "symlink_target": "" }
<html> <head> <title>TestNG: Default test</title> <link href="../testng.css" rel="stylesheet" type="text/css" /> <link href="../my-testng.css" rel="stylesheet" type="text/css" /> <style type="text/css"> .log { display: none;} .stack-trace { display: none;} </style> <script type="text/javascript"> <!-- function flip(e) { current = e.style.display; if (current == 'block') { e.style.display = 'none'; return 0; } else { e.style.display = 'block'; return 1; } } function toggleBox(szDivId, elem, msg1, msg2) { var res = -1; if (document.getElementById) { res = flip(document.getElementById(szDivId)); } else if (document.all) { // this is the way old msie versions work res = flip(document.all[szDivId]); } if(elem) { if(res == 0) elem.innerHTML = msg1; else elem.innerHTML = msg2; } } function toggleAllBoxes() { if (document.getElementsByTagName) { d = document.getElementsByTagName('div'); for (i = 0; i < d.length; i++) { if (d[i].className == 'log') { flip(d[i]); } } } } // --> </script> </head> <body> <h2 align='center'>Default test</h2><table border='1' align="center"> <tr> <td>Tests passed/Failed/Skipped:</td><td>0/1/0</td> </tr><tr> <td>Started on:</td><td>Mon Sep 05 15:27:14 SAMT 2016</td> </tr> <tr><td>Total time:</td><td>79 seconds (79520 ms)</td> </tr><tr> <td>Included groups:</td><td></td> </tr><tr> <td>Excluded groups:</td><td></td> </tr> </table><p/> <small><i>(Hover the method name to see the test class name)</i></small><p/> <table width='100%' border='1' class='invocation-failed'> <tr><td colspan='4' align='center'><b>FAILED TESTS</b></td></tr> <tr><td><b>Test method</b></td> <td width="30%"><b>Exception</b></td> <td width="10%"><b>Time (seconds)</b></td> <td><b>Instance</b></td> </tr> <tr> <td title='clients.Link_visit_website.testUntitled8()'><b>testUntitled8</b><br>Test class: clients.Link_visit_website</td> <td><div><pre>java.lang.AssertionError: expected:&lt;true&gt; but was:&lt;false&gt; at org.junit.Assert.fail(Assert.java:88) at org.junit.Assert.failNotEquals(Assert.java:743) at org.junit.Assert.assertEquals(Assert.java:118) at org.junit.Assert.assertEquals(Assert.java:144) at clients.Link_visit_website.testUntitled8(Link_visit_website.java:58) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:497) at org.testng.internal.MethodInvocationHelper.invokeMethod(MethodInvocationHelper.java:84) at org.testng.internal.Invoker.invokeMethod(Invoker.java:714) at org.testng.internal.Invoker.invokeTestMethod(Invoker.java:901) at org.testng.internal.Invoker.invokeTestMethods(Invoker.java:1231) at org.testng.internal.TestMethodWorker.invokeTestMethods(TestMethodWorker.java:127) at org.testng.internal.TestMethodWorker.run(TestMethodWorker.java:111) at org.testng.TestRunner.privateRun(TestRunner.java:767) at org.testng.TestRunner.run(TestRunner.java:617) at org.testng.SuiteRunner.runTest(SuiteRunner.java:334) at org.testng.SuiteRunner.runSequentially(SuiteRunner.java:329) at org.testng.SuiteRunner.privateRun(SuiteRunner.java:291) at org.testng.SuiteRunner.run(SuiteRunner.java:240) at org.testng.SuiteRunnerWorker.runSuite(SuiteRunnerWorker.java:52) at org.testng.SuiteRunnerWorker.run(SuiteRunnerWorker.java:86) at org.testng.TestNG.runSuitesSequentially(TestNG.java:1224) at org.testng.TestNG.runSuitesLocally(TestNG.java:1149) at org.testng.TestNG.run(TestNG.java:1057) at org.testng.remote.RemoteTestNG.run(RemoteTestNG.java:111) at org.testng.remote.RemoteTestNG.initAndRun(RemoteTestNG.java:204) at org.testng.remote.RemoteTestNG.main(RemoteTestNG.java:175) </pre></div><a href='#' onClick='toggleBox("stack-trace1168019749", this, "Click to show all stack frames", "Click to hide stack frames")'>Click to show all stack frames</a> <div class='stack-trace' id='stack-trace1168019749'><pre>java.lang.AssertionError: expected:&lt;true&gt; but was:&lt;false&gt; at org.junit.Assert.fail(Assert.java:88) at org.junit.Assert.failNotEquals(Assert.java:743) at org.junit.Assert.assertEquals(Assert.java:118) at org.junit.Assert.assertEquals(Assert.java:144) at clients.Link_visit_website.testUntitled8(Link_visit_website.java:58) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:497) at org.testng.internal.MethodInvocationHelper.invokeMethod(MethodInvocationHelper.java:84) at org.testng.internal.Invoker.invokeMethod(Invoker.java:714) at org.testng.internal.Invoker.invokeTestMethod(Invoker.java:901) at org.testng.internal.Invoker.invokeTestMethods(Invoker.java:1231) at org.testng.internal.TestMethodWorker.invokeTestMethods(TestMethodWorker.java:127) at org.testng.internal.TestMethodWorker.run(TestMethodWorker.java:111) at org.testng.TestRunner.privateRun(TestRunner.java:767) at org.testng.TestRunner.run(TestRunner.java:617) at org.testng.SuiteRunner.runTest(SuiteRunner.java:334) at org.testng.SuiteRunner.runSequentially(SuiteRunner.java:329) at org.testng.SuiteRunner.privateRun(SuiteRunner.java:291) at org.testng.SuiteRunner.run(SuiteRunner.java:240) at org.testng.SuiteRunnerWorker.runSuite(SuiteRunnerWorker.java:52) at org.testng.SuiteRunnerWorker.run(SuiteRunnerWorker.java:86) at org.testng.TestNG.runSuitesSequentially(TestNG.java:1224) at org.testng.TestNG.runSuitesLocally(TestNG.java:1149) at org.testng.TestNG.run(TestNG.java:1057) at org.testng.remote.RemoteTestNG.run(RemoteTestNG.java:111) at org.testng.remote.RemoteTestNG.initAndRun(RemoteTestNG.java:204) at org.testng.remote.RemoteTestNG.main(RemoteTestNG.java:175) </pre></div></td> <td>74</td> <td>clients.Link_visit_website@3fb6a447</td></tr> </table><p> </body> </html>
{ "content_hash": "36f03b24e4fd0c74c99bf65b95e2e910", "timestamp": "", "source": "github", "line_count": 145, "max_line_length": 173, "avg_line_length": 42.206896551724135, "alnum_prop": 0.7545751633986928, "repo_name": "LanaVoit/turnkeye", "id": "2ee6d6670dd7acb1f4c4b6d89d811a7285035ed1", "size": "6120", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "test-output/Default suite/Default test.html", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "10674" }, { "name": "HTML", "bytes": "138173" }, { "name": "Java", "bytes": "99661" }, { "name": "JavaScript", "bytes": "7110" } ], "symlink_target": "" }
import { ICompilerOptions, State } from './host'; import * as fs from 'fs'; import * as path from 'path'; import * as _ from 'lodash'; import * as tsconfig from 'tsconfig'; import { loadLib, formatError } from './helpers'; import { ICompilerInfo } from './host'; import { createResolver } from './deps'; import { createChecker } from './checker'; import { rawToTsCompilerOptions, parseContent, tsconfigSuggestions } from './tsconfig-utils'; import makeResolver from './resolver'; let colors = require('colors/safe'); let pkg = require('../package.json'); export interface LoaderPlugin { processProgram?: (program: ts.Program) => void; } export interface LoaderPluginDef { file: string; options: any; } export interface ICompilerInstance { id: number; tsFlow: Promise<any>; tsState: State; babelImpl?: any; compiledFiles: {[key:string]: boolean}; options: ICompilerOptions; externalsInvoked: boolean; checker: any; cacheIdentifier: any; plugins: LoaderPluginDef[]; initedPlugins: LoaderPlugin[]; externalsInvocation: Promise<any>; shouldUpdateProgram: boolean; } interface ICompiler { inputFileSystem: typeof fs; _tsInstances: {[key:string]: ICompilerInstance}; _tsFork: boolean; options: { externals: { [ key: string ]: string } }; } export interface IWebPack { _compiler: ICompiler; cacheable: () => void; query: string; async: () => (err: Error, source?: string, map?: string) => void; resourcePath: string; resolve: () => void; addDependency: (dep: string) => void; clearDependencies: () => void; emitFile: (fileName: string, text: string) => void; options: { atl?: { plugins: LoaderPluginDef[] } }; } function getRootCompiler(compiler) { if (compiler.parentCompilation) { return getRootCompiler(compiler.parentCompilation.compiler); } else { return compiler; } } function getInstanceStore(compiler): { [key:string]: ICompilerInstance } { let store = getRootCompiler(compiler)._tsInstances; if (store) { return store; } else { throw new Error('Can not resolve instance store'); } } function ensureInstanceStore(compiler) { let rootCompiler = getRootCompiler(compiler); if (!rootCompiler._tsInstances) { rootCompiler._tsInstances = {}; } } function resolveInstance(compiler, instanceName) { return getInstanceStore(compiler)[instanceName]; } const COMPILER_ERROR = colors.red(`\n\nTypescript compiler cannot be found, please add it to your package.json file: npm install --save-dev typescript `); const BABEL_ERROR = colors.red(`\n\nBabel compiler cannot be found, please add it to your package.json file: npm install --save-dev babel-core `); /** * Creates compiler instance */ let id = 0; export function ensureInstance(webpack: IWebPack, options: ICompilerOptions, instanceName: string): ICompilerInstance { ensureInstanceStore(webpack._compiler); let exInstance = resolveInstance(webpack._compiler, instanceName); if (exInstance) { return exInstance; } let tsFlow = Promise.resolve(); let compilerPath = options.compiler || 'typescript'; let tsImpl: typeof ts; try { tsImpl = require(compilerPath); } catch (e) { console.error(e); console.error(COMPILER_ERROR); process.exit(1); } let libPath = path.join(compilerPath, 'lib', 'lib.d.ts'); let lib6Path = path.join(compilerPath, 'lib', 'lib.es6.d.ts'); try { require.resolve(libPath); } catch(e) { libPath = path.join(compilerPath, 'bin', 'lib.d.ts'); lib6Path = path.join(compilerPath, 'bin', 'lib.es6.d.ts'); } let compilerInfo: ICompilerInfo = { compilerPath, tsImpl, lib5: loadLib(libPath), lib6: loadLib(lib6Path) }; _.defaults(options, { resolveGlobs: true }); let configFilePath: string; let configFile: tsconfig.TSConfig; if (options.tsconfig && options.tsconfig.match(/\.json$/)) { configFilePath = options.tsconfig; } else { configFilePath = tsconfig.resolveSync(options.tsconfig || process.cwd()); } if (configFilePath) { let content = fs.readFileSync(configFilePath).toString(); configFile = parseContent(content, configFilePath); if (options.resolveGlobs) { tsconfigSuggestions(configFile); configFile = tsconfig.readFileSync(configFilePath, { filterDefinitions: true }); } } let tsFiles: string[] = []; if (configFile) { if (configFile.compilerOptions) { _.defaults(options, (configFile as any).awesomeTypescriptLoaderOptions); _.defaults(options, configFile.compilerOptions); options.exclude = configFile.exclude || []; tsFiles = configFile.files; } } let projDir = configFilePath ? path.dirname(configFilePath) : process.cwd(); options = rawToTsCompilerOptions(options, projDir, tsImpl); _.defaults(options, { externals: [], doTypeCheck: true, sourceMap: true, verbose: false, noLib: false, skipDefaultLibCheck: true, suppressOutputPathCheck: true, sourceRoot: options.sourceMap ? process.cwd() : undefined }); options = _.omit(options, 'outDir', 'files', 'out', 'noEmit') as any; options.externals.push.apply(options.externals, tsFiles); let babelImpl: any; if (options.useBabel) { try { let babelPath = options.babelCore || path.join(process.cwd(), 'node_modules', 'babel-core'); babelImpl = require(babelPath); } catch (e) { console.error(BABEL_ERROR); process.exit(1); } } let cacheIdentifier = null; if (options.useCache) { if (!options.cacheDirectory) { options.cacheDirectory = path.join(process.cwd(), '.awcache'); } if (!fs.existsSync(options.cacheDirectory)) { fs.mkdirSync(options.cacheDirectory); } cacheIdentifier = { 'typescript': tsImpl.version, 'awesome-typescript-loader': pkg.version, 'awesome-typescript-loader-query': webpack.query, 'babel-core': babelImpl ? babelImpl.version : null }; } let forkChecker = options.forkChecker && getRootCompiler(webpack._compiler)._tsFork; let resolver = makeResolver(webpack._compiler.options); let syncResolver = resolver.resolveSync.bind(resolver); let tsState = new State(options, webpack._compiler.inputFileSystem, compilerInfo, syncResolver); let compiler = (<any>webpack._compiler); setupWatchRun(compiler, instanceName); if (options.doTypeCheck) { setupAfterCompile(compiler, instanceName, forkChecker); } let webpackOptions = _.pick(webpack._compiler.options, 'resolve'); let atlOptions = webpack.options.atl; let plugins: LoaderPluginDef[] = []; if (atlOptions && atlOptions.plugins) { plugins = atlOptions.plugins; } let initedPlugins = []; if (!forkChecker) { initedPlugins = plugins.map(plugin => { return require(plugin.file)(plugin.options); }); } return getInstanceStore(webpack._compiler)[instanceName] = { id: ++id, tsFlow, tsState, babelImpl, compiledFiles: {}, options, externalsInvoked: false, checker: forkChecker ? createChecker(compilerInfo, options, webpackOptions, plugins) : null, cacheIdentifier, plugins, initedPlugins, externalsInvocation: null, shouldUpdateProgram: true }; } let EXTENSIONS = /\.tsx?$|\.jsx?$/; function setupWatchRun(compiler, instanceName: string) { compiler.plugin('watch-run', async function (watching, callback) { let compiler: ICompiler = watching.compiler; let instance = resolveInstance(watching.compiler, instanceName); let state = instance.tsState; let resolver = createResolver( compiler.options.externals, state.options.exclude || [], watching.compiler.resolvers.normal.resolve, watching.compiler.resolvers.normal ); let mtimes = watching.compiler.watchFileSystem.watcher.mtimes; let changedFiles = Object.keys(mtimes); changedFiles.forEach((changedFile) => { state.fileAnalyzer.validFiles.markFileInvalid(changedFile); }); try { let tasks = changedFiles.map(async function(changedFile) { if (EXTENSIONS.test(changedFile)) { if (state.hasFile(changedFile)) { await state.readFileAndUpdate(changedFile); await state.fileAnalyzer.checkDependenciesLocked(resolver, changedFile); } } }); await Promise.all(tasks); if (!state.options.forkChecker) { state.updateProgram(); } callback(); } catch (err) { console.error(err.toString()); callback(); } }); } let runChecker = (instance, payload) => { instance.checker.send({ messageType: 'compile', payload }); }; runChecker = _.debounce(runChecker, 200); function setupAfterCompile(compiler, instanceName, forkChecker = false) { compiler.plugin('after-compile', function(compilation, callback) { // Don't add errors for child compilations if (compilation.compiler.isChild()) { callback(); return; } let instance: ICompilerInstance = resolveInstance(compilation.compiler, instanceName); let state = instance.tsState; if (forkChecker) { let payload = { files: state.allFiles(), resolutionCache: state.host.moduleResolutionHost.resolutionCache }; runChecker(instance, payload); } else { if (!state.program || instance.shouldUpdateProgram) { // program may be undefined here, if all files // will be loaded by tsconfig state.updateProgram(); instance.shouldUpdateProgram = false; } let diagnostics = state.ts.getPreEmitDiagnostics(state.program); let emitError = (msg) => { if (compilation.bail) { console.error('Error in bail mode:', msg); process.exit(1); } compilation.errors.push(new Error(msg)); }; let { options: { ignoreDiagnostics } } = instance; diagnostics .filter(err => !ignoreDiagnostics || ignoreDiagnostics.indexOf(err.code) == -1) .map(err => `[${ instanceName }] ` + formatError(err)) .forEach(emitError); instance.initedPlugins.forEach(plugin => { plugin.processProgram(state.program); }); } let phantomImports = []; state.allFileNames().forEach((fileName) => { if (!instance.compiledFiles[fileName]) { phantomImports.push(fileName); } }); if (instance.options.declaration) { phantomImports.forEach(imp => { let output = instance.tsState.services.getEmitOutput(imp); let declarationFile = output.outputFiles.filter(filePath => !!filePath.name.match(/\.d.ts$/))[0]; if (declarationFile) { let assetPath = path.relative(process.cwd(), declarationFile.name); compilation.assets[assetPath] = { source: () => declarationFile.text, size: () => declarationFile.text.length }; } }); } instance.compiledFiles = {}; compilation.fileDependencies.push.apply(compilation.fileDependencies, phantomImports); compilation.fileDependencies = _.uniq(compilation.fileDependencies); callback(); }); }
{ "content_hash": "72cb73f1e1a5cb302d9e307e72256829", "timestamp": "", "source": "github", "line_count": 403, "max_line_length": 119, "avg_line_length": 30.88089330024814, "alnum_prop": 0.5978304539975894, "repo_name": "PaulMrn/TFC", "id": "9bee137cb872608f07c71ee111e753a852d73d44", "size": "12445", "binary": false, "copies": "4", "ref": "refs/heads/master", "path": "node_modules/awesome-typescript-loader/src/instance.ts", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "7520" }, { "name": "HTML", "bytes": "9300" }, { "name": "JavaScript", "bytes": "1649" }, { "name": "TypeScript", "bytes": "107063" } ], "symlink_target": "" }
<?xml version="1.0" encoding="utf-8"?> <set xmlns:android="http://schemas.android.com/apk/res/android" android:fillAfter="true"> <scale android:interpolator="@android:anim/accelerate_interpolator" android:duration="750" android:fromYScale="1.0" android:toYScale="0.0" android:fromXScale="1.0" android:toXScale="1.0" /> </set>
{ "content_hash": "004b09ebedf73f7e884f3204e6a50791", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 64, "avg_line_length": 27.307692307692307, "alnum_prop": 0.6845070422535211, "repo_name": "peter-tackage/open-secret-santa", "id": "c6fb43ed4a9be04d0662c6f95cfacda428056c05", "size": "355", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "open-secret-santa-app/src/main/res/anim/scale_down.xml", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Groovy", "bytes": "66" }, { "name": "Java", "bytes": "393941" }, { "name": "Shell", "bytes": "347" } ], "symlink_target": "" }
package org.zstack.network.service.eip; import org.zstack.header.vm.VmNicInventory; import org.zstack.network.service.vip.VipInventory; /** */ public class EipStruct { private EipInventory eip; private VmNicInventory nic; private VipInventory vip; private boolean snatInboundTraffic; public boolean isSnatInboundTraffic() { return snatInboundTraffic; } public void setSnatInboundTraffic(boolean snatInboundTraffic) { this.snatInboundTraffic = snatInboundTraffic; } public EipInventory getEip() { return eip; } public void setEip(EipInventory eip) { this.eip = eip; } public VmNicInventory getNic() { return nic; } public void setNic(VmNicInventory nic) { this.nic = nic; } public VipInventory getVip() { return vip; } public void setVip(VipInventory vip) { this.vip = vip; } }
{ "content_hash": "e0e98b66f19bfb47c65fe57ff2769c43", "timestamp": "", "source": "github", "line_count": 45, "max_line_length": 67, "avg_line_length": 21.711111111111112, "alnum_prop": 0.6274309109518935, "repo_name": "myxyz/zstack", "id": "e805964282450e5edf85c7b8384cb01e42b43edf", "size": "977", "binary": false, "copies": "10", "ref": "refs/heads/master", "path": "plugin/eip/src/main/java/org/zstack/network/service/eip/EipStruct.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "AspectJ", "bytes": "49286" }, { "name": "Batchfile", "bytes": "1132" }, { "name": "Groovy", "bytes": "16816" }, { "name": "Java", "bytes": "10085573" }, { "name": "Shell", "bytes": "148422" } ], "symlink_target": "" }
var express = require('express'); var router = express.Router(); var log = require(process.cwd() + '/lib/log')(module); var db = require(process.cwd() + '/lib/db'); // -------------------------------------------------------------------------------- // // /api/people/ // // -------------------------------------------------------------------------------- router.route('/people') .get(function(req, res) { db.Person.findAll(constructOptions(req.params)) .then(function(peopleArray){ res.statusCode = 200; log.info("people array size: %d", peopleArray.length); return res.json({ status: 'OK', size: peopleArray.length, // convert peopleArray to object people: peopleArray.reduce(function(object, person, index){ object[index] = person.dataValues; return object; }, {}) }); }) .catch( function(error){ res.statusCode = 500; log.error('Database error(%d): %s', res.statusCode, error.message); return res.json({ error: 'Not Found'}); }); }) .post(function(req, res) { log.info('post /people called'); res.statusCode = 200; return res.json({ message: 'post To be implemented later' }); }); // -------------------------------------------------------------------------------- // // /api/people/:people_id // // -------------------------------------------------------------------------------- router.route('/people/:person_id') .get(function(req, res) { log.info("params: %j", req.params); log.info("query: %j", req.query); db.Person.findById(req.params.person_id) .then(function(person) { try{ person_data = person.dataValues; res.statusCode = 200; return res.json({ status: 'OK', person: person_data }); } catch(error){ res.statusCode = 500; log.error('Internal error(%d): %s', res.statusCode, error.message); return res.json({ error: 'Server error' }); } }) .catch( function(error){ res.statusCode = 404; log.error('Database error(%d): %s', res.statusCode, error.message); return res.json({ error: 'Not Found' }); }); }) .post(function(req, res) { log.info('post /people/:person_id called'); res.statusCode = 200; return res.json({ message: 'post To be implemented later' }); }) .delete(function(req, res) { log.info('delete /people/:person_id called'); res.statusCode = 200; return res.json({ message: 'delete To be implemented later' }); }); // -------------------------------------------------------------------------------- // // Helper functions // // -------------------------------------------------------------------------------- constructOptions = function(params) { // TODO: to be implement // construct options, limit the number to 100 return {limit: 100}; }; module.exports = router;
{ "content_hash": "6f9e03d196d9e62ace5540f398fae657", "timestamp": "", "source": "github", "line_count": 100, "max_line_length": 83, "avg_line_length": 30.66, "alnum_prop": 0.4680365296803653, "repo_name": "CrazyAlvaro/API_for_CB_data", "id": "267174ebcb8a25cc9fa21c39fb97605aff4d7b10", "size": "3066", "binary": false, "copies": "1", "ref": "refs/heads/development", "path": "routes/sequelize.js", "mode": "33188", "license": "mit", "language": [ { "name": "JavaScript", "bytes": "43421" } ], "symlink_target": "" }
<?php namespace Admin\ArticleBundle\Tests\Controller; use Symfony\Bundle\FrameworkBundle\Test\WebTestCase; class PostControllerTest extends WebTestCase { /* public function testCompleteScenario() { // Create a new client to browse the application $client = static::createClient(); // Create a new entry in the database $crawler = $client->request('GET', '/post/'); $this->assertEquals(200, $client->getResponse()->getStatusCode(), "Unexpected HTTP status code for GET /post/"); $crawler = $client->click($crawler->selectLink('Create a new entry')->link()); // Fill in the form and submit it $form = $crawler->selectButton('Create')->form(array( 'admin_articlebundle_posttype[field_name]' => 'Test', // ... other fields to fill )); $client->submit($form); $crawler = $client->followRedirect(); // Check data in the show view $this->assertGreaterThan(0, $crawler->filter('td:contains("Test")')->count(), 'Missing element td:contains("Test")'); // Edit the entity $crawler = $client->click($crawler->selectLink('Edit')->link()); $form = $crawler->selectButton('Edit')->form(array( 'admin_articlebundle_posttype[field_name]' => 'Foo', // ... other fields to fill )); $client->submit($form); $crawler = $client->followRedirect(); // Check the element contains an attribute with value equals "Foo" $this->assertGreaterThan(0, $crawler->filter('[value="Foo"]')->count(), 'Missing element [value="Foo"]'); // Delete the entity $client->submit($crawler->selectButton('Delete')->form()); $crawler = $client->followRedirect(); // Check the entity has been delete on the list $this->assertNotRegExp('/Foo/', $client->getResponse()->getContent()); } */ }
{ "content_hash": "e8aeb12d8cfa57ee9266e0862b1b064a", "timestamp": "", "source": "github", "line_count": 55, "max_line_length": 125, "avg_line_length": 35.163636363636364, "alnum_prop": 0.6023784901758015, "repo_name": "azdevelop/uprava", "id": "934996eddeb127d599f9b558ed859eab1e69b939", "size": "1934", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/Admin/ArticleBundle/Tests/Controller/PostControllerTest.php", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "56070" }, { "name": "JavaScript", "bytes": "175447" }, { "name": "PHP", "bytes": "196870" }, { "name": "Perl", "bytes": "2729" } ], "symlink_target": "" }
<!DOCTYPE HTML> <html> <head> <meta http-equiv="Content-Type" content="html/html; charset=utf-8" /> <title>CCActionEaseInOut Class Reference</title> <meta id="xcode-display" name="xcode-display" content="render"/> <link rel="stylesheet" type="text/css" href="../css/styles.css" media="all" /> <link rel="stylesheet" type="text/css" media="print" href="../css/stylesPrint.css" /> <meta name="generator" content="appledoc 2.2 (build 963)" /> </head> <body> <header id="top_header"> <div id="library" class="hideInXcode"> <h1><a id="libraryTitle" href="../index.html">Cocos2D 3.0 </a></h1> <a id="developerHome" href="../index.html">Cocos2D</a> </div> <div id="title" role="banner"> <h1 class="hideInXcode">CCActionEaseInOut Class Reference</h1> </div> <ul id="headerButtons" role="toolbar"> <li id="toc_button"> <button aria-label="Show Table of Contents" role="checkbox" class="open" id="table_of_contents"><span class="disclosure"></span>Table of Contents</button> </li> <li id="jumpto_button" role="navigation"> <select id="jumpTo"> <option value="top">Jump To&#133;</option> <option value="overview">Overview</option> </select> </li> </ul> </header> <nav id="tocContainer" class="isShowingTOC"> <ul id="toc" role="tree"> <li role="treeitem"><span class="nodisclosure"></span><span class="sectionName"><a href="#overview">Overview</a></span></li> </ul> </nav> <article> <div id="contents" class="isShowingTOC" role="main"> <a title="CCActionEaseInOut Class Reference" name="top"></a> <div class="main-navigation navigation-top"> <ul> <li><a href="../index.html">Index</a></li> <li><a href="../hierarchy.html">Hierarchy</a></li> </ul> </div> <div id="header"> <div class="section-header"> <h1 class="title title-header">CCActionEaseInOut Class Reference</h1> </div> </div> <div id="container"> <div class="section section-specification"><table cellspacing="0"><tbody> <tr> <td class="specification-title">Inherits from</td> <td class="specification-value"><a href="../Classes/CCActionEaseRate.html">CCActionEaseRate</a> : <a href="../Classes/CCActionEase.html">CCActionEase</a> : <a href="../Classes/CCActionInterval.html">CCActionInterval</a> : CCActionFiniteTime : <a href="../Classes/CCAction.html">CCAction</a> : NSObject</td> </tr><tr> <td class="specification-title">Conforms to</td> <td class="specification-value">NSCopying</td> </tr><tr> <td class="specification-title">Declared in</td> <td class="specification-value">CCActionEase.h</td> </tr> </tbody></table></div> <div class="section section-overview"> <a title="Overview" name="overview"></a> <h2 class="subtitle subtitle-overview">Overview</h2> <p>This action will both accelerate and deccelerate the specified action with same rate.</p> </div> </div> <div class="main-navigation navigation-bottom"> <ul> <li><a href="../index.html">Index</a></li> <li><a href="../hierarchy.html">Hierarchy</a></li> </ul> </div> <div id="footer"> <hr /> <div class="footer-copyright"> <p><span class="copyright">&copy; 2014 Cocos2D. All rights reserved. (Last updated: 2014-01-13)</span><br /> <span class="generator">Generated by <a href="http://appledoc.gentlebytes.com">appledoc 2.2 (build 963)</a>.</span></p> </div> </div> </div> </article> <script type="text/javascript"> function jumpToChange() { window.location.hash = this.options[this.selectedIndex].value; } function toggleTOC() { var contents = document.getElementById('contents'); var tocContainer = document.getElementById('tocContainer'); if (this.getAttribute('class') == 'open') { this.setAttribute('class', ''); contents.setAttribute('class', ''); tocContainer.setAttribute('class', ''); window.name = "hideTOC"; } else { this.setAttribute('class', 'open'); contents.setAttribute('class', 'isShowingTOC'); tocContainer.setAttribute('class', 'isShowingTOC'); window.name = ""; } return false; } function toggleTOCEntryChildren(e) { e.stopPropagation(); var currentClass = this.getAttribute('class'); if (currentClass == 'children') { this.setAttribute('class', 'children open'); } else if (currentClass == 'children open') { this.setAttribute('class', 'children'); } return false; } function tocEntryClick(e) { e.stopPropagation(); return true; } function init() { var selectElement = document.getElementById('jumpTo'); selectElement.addEventListener('change', jumpToChange, false); var tocButton = document.getElementById('table_of_contents'); tocButton.addEventListener('click', toggleTOC, false); var taskTreeItem = document.getElementById('task_treeitem'); if (taskTreeItem.getElementsByTagName('li').length > 0) { taskTreeItem.setAttribute('class', 'children'); taskTreeItem.firstChild.setAttribute('class', 'disclosure'); } var tocList = document.getElementById('toc'); var tocEntries = tocList.getElementsByTagName('li'); for (var i = 0; i < tocEntries.length; i++) { tocEntries[i].addEventListener('click', toggleTOCEntryChildren, false); } var tocLinks = tocList.getElementsByTagName('a'); for (var i = 0; i < tocLinks.length; i++) { tocLinks[i].addEventListener('click', tocEntryClick, false); } if (window.name == "hideTOC") { toggleTOC.call(tocButton); } } window.onload = init; // If showing in Xcode, hide the TOC and Header if (navigator.userAgent.match(/xcode/i)) { document.getElementById("contents").className = "hideInXcode" document.getElementById("tocContainer").className = "hideInXcode" document.getElementById("top_header").className = "hideInXcode" } </script> </body> </html>
{ "content_hash": "65b5dbd73442c6661946bb172b092af7", "timestamp": "", "source": "github", "line_count": 229, "max_line_length": 307, "avg_line_length": 27.449781659388645, "alnum_prop": 0.616131084950684, "repo_name": "promlow/books-and-tutorials", "id": "ce66ced8fae4fc935a694f1b7dc9d73ba8434e83", "size": "6286", "binary": false, "copies": "8", "ref": "refs/heads/master", "path": "SpriteBuilder/FlappyFly.spritebuilder/Source/libs/cocos2d-iphone/api-docs/docset/Contents/Resources/Documents/Classes/CCActionEaseInOut.html", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "273257" }, { "name": "C++", "bytes": "96918" }, { "name": "CSS", "bytes": "37920" }, { "name": "Coq", "bytes": "1433619" }, { "name": "GLSL", "bytes": "15954" }, { "name": "HTML", "bytes": "8081454" }, { "name": "JavaScript", "bytes": "443" }, { "name": "Makefile", "bytes": "92898" }, { "name": "OCaml", "bytes": "37332" }, { "name": "Objective-C", "bytes": "4605758" }, { "name": "Objective-C++", "bytes": "12160" }, { "name": "Perl", "bytes": "24566" }, { "name": "Python", "bytes": "65877" }, { "name": "Scala", "bytes": "50526" }, { "name": "Shell", "bytes": "62765" }, { "name": "SuperCollider", "bytes": "7579" }, { "name": "TeX", "bytes": "48770" } ], "symlink_target": "" }
package java.awt.geom; import java.lang.annotation.Native; /** * The <code>PathIterator</code> interface provides the mechanism * for objects that implement the {@link java.awt.Shape Shape} * interface to return the geometry of their boundary by allowing * a caller to retrieve the path of that boundary a segment at a * time. This interface allows these objects to retrieve the path of * their boundary a segment at a time by using 1st through 3rd order * B&eacute;zier curves, which are lines and quadratic or cubic * B&eacute;zier splines. * <p> * Multiple subpaths can be expressed by using a "MOVETO" segment to * create a discontinuity in the geometry to move from the end of * one subpath to the beginning of the next. * <p> * Each subpath can be closed manually by ending the last segment in * the subpath on the same coordinate as the beginning "MOVETO" segment * for that subpath or by using a "CLOSE" segment to append a line * segment from the last point back to the first. * Be aware that manually closing an outline as opposed to using a * "CLOSE" segment to close the path might result in different line * style decorations being used at the end points of the subpath. * For example, the {@link java.awt.BasicStroke BasicStroke} object * uses a line "JOIN" decoration to connect the first and last points * if a "CLOSE" segment is encountered, whereas simply ending the path * on the same coordinate as the beginning coordinate results in line * "CAP" decorations being used at the ends. * * @see java.awt.Shape * @see java.awt.BasicStroke * * @author Jim Graham */ public interface PathIterator { /** * The winding rule constant for specifying an even-odd rule * for determining the interior of a path. * The even-odd rule specifies that a point lies inside the * path if a ray drawn in any direction from that point to * infinity is crossed by path segments an odd number of times. */ @Native public static final int WIND_EVEN_ODD = 0; /** * The winding rule constant for specifying a non-zero rule * for determining the interior of a path. * The non-zero rule specifies that a point lies inside the * path if a ray drawn in any direction from that point to * infinity is crossed by path segments a different number * of times in the counter-clockwise direction than the * clockwise direction. */ @Native public static final int WIND_NON_ZERO = 1; /** * The segment type constant for a point that specifies the * starting location for a new subpath. */ @Native public static final int SEG_MOVETO = 0; /** * The segment type constant for a point that specifies the * end point of a line to be drawn from the most recently * specified point. */ @Native public static final int SEG_LINETO = 1; /** * The segment type constant for the pair of points that specify * a quadratic parametric curve to be drawn from the most recently * specified point. * The curve is interpolated by solving the parametric control * equation in the range <code>(t=[0..1])</code> using * the most recently specified (current) point (CP), * the first control point (P1), * and the final interpolated control point (P2). * The parametric control equation for this curve is: * <pre> * P(t) = B(2,0)*CP + B(2,1)*P1 + B(2,2)*P2 * 0 &lt;= t &lt;= 1 * * B(n,m) = mth coefficient of nth degree Bernstein polynomial * = C(n,m) * t^(m) * (1 - t)^(n-m) * C(n,m) = Combinations of n things, taken m at a time * = n! / (m! * (n-m)!) * </pre> */ @Native public static final int SEG_QUADTO = 2; /** * The segment type constant for the set of 3 points that specify * a cubic parametric curve to be drawn from the most recently * specified point. * The curve is interpolated by solving the parametric control * equation in the range <code>(t=[0..1])</code> using * the most recently specified (current) point (CP), * the first control point (P1), * the second control point (P2), * and the final interpolated control point (P3). * The parametric control equation for this curve is: * <pre> * P(t) = B(3,0)*CP + B(3,1)*P1 + B(3,2)*P2 + B(3,3)*P3 * 0 &lt;= t &lt;= 1 * * B(n,m) = mth coefficient of nth degree Bernstein polynomial * = C(n,m) * t^(m) * (1 - t)^(n-m) * C(n,m) = Combinations of n things, taken m at a time * = n! / (m! * (n-m)!) * </pre> * This form of curve is commonly known as a B&eacute;zier curve. */ @Native public static final int SEG_CUBICTO = 3; /** * The segment type constant that specifies that * the preceding subpath should be closed by appending a line segment * back to the point corresponding to the most recent SEG_MOVETO. */ @Native public static final int SEG_CLOSE = 4; /** * Returns the winding rule for determining the interior of the * path. * @return the winding rule. * @see #WIND_EVEN_ODD * @see #WIND_NON_ZERO */ public int getWindingRule(); /** * Tests if the iteration is complete. * @return <code>true</code> if all the segments have * been read; <code>false</code> otherwise. */ public boolean isDone(); /** * Moves the iterator to the next segment of the path forwards * along the primary direction of traversal as long as there are * more points in that direction. */ public void next(); /** * Returns the coordinates and type of the current path segment in * the iteration. * The return value is the path-segment type: * SEG_MOVETO, SEG_LINETO, SEG_QUADTO, SEG_CUBICTO, or SEG_CLOSE. * A float array of length 6 must be passed in and can be used to * store the coordinates of the point(s). * Each point is stored as a pair of float x,y coordinates. * SEG_MOVETO and SEG_LINETO types returns one point, * SEG_QUADTO returns two points, * SEG_CUBICTO returns 3 points * and SEG_CLOSE does not return any points. * @param coords an array that holds the data returned from * this method * @return the path-segment type of the current path segment. * @see #SEG_MOVETO * @see #SEG_LINETO * @see #SEG_QUADTO * @see #SEG_CUBICTO * @see #SEG_CLOSE */ public int currentSegment(float[] coords); /** * Returns the coordinates and type of the current path segment in * the iteration. * The return value is the path-segment type: * SEG_MOVETO, SEG_LINETO, SEG_QUADTO, SEG_CUBICTO, or SEG_CLOSE. * A double array of length 6 must be passed in and can be used to * store the coordinates of the point(s). * Each point is stored as a pair of double x,y coordinates. * SEG_MOVETO and SEG_LINETO types returns one point, * SEG_QUADTO returns two points, * SEG_CUBICTO returns 3 points * and SEG_CLOSE does not return any points. * @param coords an array that holds the data returned from * this method * @return the path-segment type of the current path segment. * @see #SEG_MOVETO * @see #SEG_LINETO * @see #SEG_QUADTO * @see #SEG_CUBICTO * @see #SEG_CLOSE */ public int currentSegment(double[] coords); }
{ "content_hash": "18e0b017e5d19783fc4607045bb7f94b", "timestamp": "", "source": "github", "line_count": 194, "max_line_length": 73, "avg_line_length": 39.3041237113402, "alnum_prop": 0.6411803278688525, "repo_name": "itgeeker/jdk", "id": "af508173c7a05f943be6d9b2198b86a529437bee", "size": "7840", "binary": false, "copies": "6", "ref": "refs/heads/dev", "path": "src/java/awt/geom/PathIterator.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C", "bytes": "189890" }, { "name": "C++", "bytes": "6565" }, { "name": "Java", "bytes": "85554389" } ], "symlink_target": "" }
package org.apache.giraph.comm.requests; import java.io.IOException; import org.apache.giraph.master.MasterGlobalCommHandler; /** * Request to send final aggregated values from worker which owns * aggregators to the master */ public class SendReducedToMasterRequest extends ByteArrayRequest implements MasterRequest { /** * Constructor * * @param data Serialized aggregator data */ public SendReducedToMasterRequest(byte[] data) { super(data); } /** * Constructor used for reflection only */ public SendReducedToMasterRequest() { } @Override public void doRequest(MasterGlobalCommHandler commHandler) { try { commHandler.getAggregatorHandler(). acceptReducedValues(getUnsafeByteArrayInput()); } catch (IOException e) { throw new IllegalStateException("doRequest: " + "IOException occurred while processing request", e); } } @Override public RequestType getType() { return RequestType.SEND_AGGREGATORS_TO_MASTER_REQUEST; } }
{ "content_hash": "47eb4eeadc0cc548dd0b4d3ee846179d", "timestamp": "", "source": "github", "line_count": 46, "max_line_length": 65, "avg_line_length": 22.565217391304348, "alnum_prop": 0.708092485549133, "repo_name": "apache/giraph", "id": "0ea737fb96276843f816edd2c6915c19254377b3", "size": "1843", "binary": false, "copies": "2", "ref": "refs/heads/trunk", "path": "giraph-core/src/main/java/org/apache/giraph/comm/requests/SendReducedToMasterRequest.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "11661" }, { "name": "HTML", "bytes": "13020" }, { "name": "Java", "bytes": "6196135" }, { "name": "JavaScript", "bytes": "113085" }, { "name": "Python", "bytes": "1706" }, { "name": "Ruby", "bytes": "1973" }, { "name": "Shell", "bytes": "52603" } ], "symlink_target": "" }
<!doctype html> <!-- This file is generated by build.py. --> <title>video 240x160.ogv; overflow:hidden; -o-object-fit:contain; -o-object-position:50% 50%</title> <link rel="stylesheet" href="../../support/reftests.css"> <link rel='match' href='hidden_contain_50_50-ref.html'> <style> #test > * { overflow:hidden; -o-object-fit:contain; -o-object-position:50% 50% } </style> <div id="test"> <video src="../../support/240x160.ogv"></video> </div>
{ "content_hash": "6a674fd2dcbdd25ddc29da154bce24b3", "timestamp": "", "source": "github", "line_count": 11, "max_line_length": 100, "avg_line_length": 40.63636363636363, "alnum_prop": 0.668903803131991, "repo_name": "operasoftware/presto-testo", "id": "287117fc8ee40be82a4481e0b00c6e8a67c367f0", "size": "447", "binary": false, "copies": "4", "ref": "refs/heads/master", "path": "css/image-fit/reftests/video-ogg-wide/hidden_contain_50_50.html", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "ASP", "bytes": "2312" }, { "name": "ActionScript", "bytes": "23470" }, { "name": "AutoHotkey", "bytes": "8832" }, { "name": "Batchfile", "bytes": "5001" }, { "name": "C", "bytes": "116512" }, { "name": "C++", "bytes": "279128" }, { "name": "CSS", "bytes": "208905" }, { "name": "Groff", "bytes": "674" }, { "name": "HTML", "bytes": "106576719" }, { "name": "Haxe", "bytes": "3874" }, { "name": "Java", "bytes": "185827" }, { "name": "JavaScript", "bytes": "22531460" }, { "name": "Makefile", "bytes": "13409" }, { "name": "PHP", "bytes": "524372" }, { "name": "POV-Ray SDL", "bytes": "6542" }, { "name": "Perl", "bytes": "321672" }, { "name": "Python", "bytes": "954636" }, { "name": "Ruby", "bytes": "1006850" }, { "name": "Shell", "bytes": "12140" }, { "name": "Smarty", "bytes": "1860" }, { "name": "XSLT", "bytes": "2567445" } ], "symlink_target": "" }
//--------------------------------------------------------------------------- #ifndef TypesH #define TypesH #include <IniFiles.hpp> #include <SysUtils.hpp> #include <fstream> #include <stdio.h> #include <string.h> #include <time.h> #include <math.h> #include <cmath> #include <cstdlib> #ifndef RSHELLWEG_LINUX #include <system.hpp> #include <conio.h> #include <dir.h> #include <Vcl.Dialogs.hpp> #else #include <AnsiString.hpp> #define __fastcall using namespace std; #endif #include "ConstUnit.h" #include "Math.hpp" //#include "Matrix.h" //namespace HellwegTypes { enum TError {ERR_NO,ERR_NOFILE,ERR_OPENFILE,ERR_COUPLER,ERR_SOLENOID,ERR_BEAM,ERR_QUAD, ERR_CURRENT,ERR_DRIFT,ERR_CELL,ERR_CELLS,ERR_OPTIONS,ERR_DUMP,ERR_PARTICLE, ERR_FORMAT,ERR_IMPORT,ERR_SPCHARGE,ERR_ABORT,ERR_STRUCT,ERR_OTHER}; enum TBeamParameter {R_PAR,TH_PAR,BR_PAR,BTH_PAR,BZ_PAR,PHI_PAR,Z0_PAR,ZREL_PAR,BETA_PAR,X_PAR,Y_PAR,BX_PAR,BY_PAR, AR_PAR,ATH_PAR,AX_PAR,AY_PAR,AZ_PAR,W_PAR,RTH_PAR,NO_PAR,LIVE_PAR} ; enum TStructureParameter {KSI_PAR,Z_PAR,A_PAR,RP_PAR,ALPHA_PAR,SBETA_PAR,RA_PAR,RB_PAR,BZ_EXT_PAR,BR_EXT_PAR,NUM_PAR, E0_PAR,EREAL_PAR,PRF_PAR,PBEAM_PAR,BBETA_PAR,WAV_PAR,WMAX_PAR,XB_PAR,YB_PAR, ER_PAR,EX_PAR,EY_PAR,ENR_PAR,ENX_PAR,ENY_PAR,E4D_PAR,E4DN_PAR,ET_PAR,ENT_PAR} ; enum TSplineType {ZSPLINE,LSPLINE,CSPLINE,SSPLINE}; enum TChartType {CH_EMITTANCE,CH_SECTION,CH_PORTRAIT,CH_PHASE,CH_ENERGY,CH_BETA,CH_A,CH_B,CH_ELP,CH_ATT,CH_APP,CH_BEXT,CH_CLEAR}; enum TInputParameter {UNDEFINED,POWER,SOLENOID,BEAM,CURRENT,DRIFT,CELL,CELLS,OPTIONS,DUMP,COMMENT,SPCHARGE,QUAD,STRUCT,PARTICLES}; enum TTrig {SIN,COS,TG,CTG,SEC,CSC}; enum TDeviation {D_RMS,D_FWHM}; enum TLoss {LIVE,RADIUS_LOST,PHASE_LOST,BZ_LOST,BR_LOST,BTH_LOST,BETA_LOST,STEP_LOST}; enum TGraphType {TRANS_SEC,LONGT_SEC,TRANS_SPACE,LONGT_SPACE,LONGT_MOTION,PHASE_SLID,W_SPEC,F_SPEC,R_SPEC, R_TRACE,PHI_TRACE,W_TRACE,E_PLOT,EPS_PLOT,P_PLOT,W_PLOT,BETA_PLOT,R_PLOT,F_NONE}; enum TOptType {BUNCHER,ACCELERATOR}; enum TParseStage {DIM_STEP,PIV_STEP,DATA_STEP}; enum TBeamType {NOBEAM,ASTRA,CST_PID,CST_PIT,TWISS_2D,TWISS_4D,SPH_2D,ELL_2D,FILE_1D,FILE_2D,TWO_FILES_2D,FILE_4D,NORM_1D,NORM_2D,PARMELA_T2}; enum TImportType {NO_ELEMENT,ANALYTIC_0D,ANALYTIC_1D,IMPORT_1D,IMPORT_2DC,IMPORT_2DR,IMPORT_3DC,IMPORT_3DR}; enum TMagnetType {MAG_GENERAL,MAG_SOLENOID,MAG_DIPOLE,MAG_QUAD,MAG_NO}; enum TSpaceChargeType {SPCH_NO,SPCH_LPST,SPCH_ELL,SPCH_GW}; enum TParticleType {ELECTRON, PROTON, ION}; const int MaxParameters=14; //Maximum number of parameters after a keyword. Currently: BEAM const int NumBessel=6; #ifdef RSHELLWEG_LINUX typedef long double Extended; inline Extended DegToRad(const Extended Degrees) { return Degrees*M_PI/180; } #endif struct TInputLine{ TInputParameter P; int N; AnsiString S[MaxParameters]; }; struct TTwiss{ double alpha; double beta; double epsilon; double gamma; }; struct TGauss{ double mean; double sigma; double limit; double FWHM; double core; }; struct TSphere{ double Rcath; double Rsph; double kT; }; struct TEllipse{ double ax; double by; double x0; double y0; double phi; double h; double Rx; double Ry; }; struct TSpaceCharge { TSpaceChargeType Type; int NSlices; double Nrms; bool Train; double Ltrain; }; struct TParticlesSpecies { TParticleType Type; double A; int Q; }; struct TBeamInput { TBeamType RBeamType; TBeamType ZBeamType; AnsiString RFile; AnsiString YFile; AnsiString ZFile; TTwiss XTwiss; TTwiss YTwiss; TGauss XNorm; TGauss YNorm; TGauss ZNorm; TGauss WNorm; TSphere Sph; TEllipse Ell; TSpaceCharge SpaceCharge; double Current; int NParticles; bool ZCompress; bool Demagnetize; TParticlesSpecies Species; double W0; //MeV/u for beta double Wnorm; //A/Q for fields }; struct TStructData { bool Default; bool DataReady; double Phase; int N_bph; int N_akl; double *Bph; double *AKL; double **ELP; double **AL32; }; struct TDimensions { int Nx; int Ny; int Nz; }; struct TPivot { double *X; double *Y; double *Z; }; struct TField { double r; double th; double z; }; struct TFieldMap { TDimensions Dim; TPivot Piv; TField ***Field; }; struct TFieldMap2D { TDimensions Dim; TPivot Piv; TField **Field; }; struct TParticle { double r; //x/lmb (-Rb<x<Rb) - rename to r double th; TField beta; double phi; double z; double beta0; //full beta. distinguish beta from bz! TLoss lost; }; struct TPhaseSpace { double x; double px; double y; double py; }; struct TDump { std::string File;//char *File; int NElement; int Nmesh; int N1; //limits int N2; TBeamType SpecialFormat; bool Binary; bool LiveOnly; bool Phase; bool Energy; bool Radius; bool Azimuth; bool Divergence; }; struct TMagnetParameters { TMagnetType MagnetType; TImportType ImportType; double BField; double StartPos; double Length; double Lfringe; AnsiString File; }; struct TCell { double beta; double ELP; double AL32; double AkL; double Mode; double F0; double P0; double dF; int Mesh; bool Drift; bool First; TMagnetParameters Magnet; /* bool Dump; TDump DumpParameters; */ }; struct TStructure { double ksi; double lmb; double P; double dF; double E; double A; double Rp; double B; double alpha; double beta; double Ra; TFieldMap2D Bmap; //TField Hext; /* double Bz_ext; double Br_ext; */ //TFieldMap Hext; bool jump; bool drift; int CellNumber; /* bool Dump; TDump DumpParameters; */ }; struct TSectionParameters { double Frequency; //double Wavelength; double Power; double PhaseShift; double NCells; }; struct TStructureInput { int NSections; int NElements; int NMaps; int NStructData; int ElementsLimit; TSectionParameters *Sections; TCell *Cells; TStructData *StructData; TMagnetParameters SolenoidPar; bool Reverse; }; struct TResult { double Length; double MaximumEnergy; double InputCurrent; double BeamCurrent; double Captured; double BeamRadius; TGauss Energy; TGauss Phase; double BeamPower; double LoadPower; TTwiss RTwiss; TTwiss XTwiss; TTwiss YTwiss; double A; }; struct TOptResult { double x; TResult Result; }; struct TSplineCoef { double X; double Y; double A; double B; double C; double D; double W; double F; }; struct TGraph { double x; double y; bool draw; }; struct TSpectrumBar { double x; double phase; int N; double y; //envelope double P; double xAv; double xRMS; double yAv; double yRMS; }; struct TIntegration { double phi; TField E; TField H; TField beta; /*double Az; double Ar; double Hth; double br; double bth; double bz; */ double r; double th; double A; }; struct TIntParameters { double h; double bw; double w; double dL; double A; double dA; double B; double E; TFieldMap2D Hext; TFieldMap2D Hmap; //TField dHext; /*double Bz_ext; double Br_ext; */ double dH; //double Cmag; double SumSin; double SumCos; TField *Eq; /*double *Aqz; double *Aqr; */ double gamma; bool drift; }; //}; //--------------------------------------------------------------------------- #endif // TypesH
{ "content_hash": "72e3e7fdcc57892d74562c74b4aceeb5", "timestamp": "", "source": "github", "line_count": 412, "max_line_length": 142, "avg_line_length": 17.684466019417474, "alnum_prop": 0.6851496019763931, "repo_name": "radiasoft/rslinac", "id": "a1003712ce63cd13f9ca774dff24f8cd6f7c56e3", "size": "7286", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/physics/Types.h", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C", "bytes": "140228" }, { "name": "C++", "bytes": "439517" }, { "name": "CMake", "bytes": "1816" }, { "name": "Cython", "bytes": "2503" }, { "name": "MATLAB", "bytes": "155495" }, { "name": "Makefile", "bytes": "1435" }, { "name": "Pascal", "bytes": "77862" }, { "name": "Python", "bytes": "8892" }, { "name": "Shell", "bytes": "221" } ], "symlink_target": "" }
/** * @file RealFirFilter.h * * Definition of the template class RealFirFilter. */ #ifndef NimbleDSP_RealFirFilter_h #define NimbleDSP_RealFirFilter_h #include <complex> #include <math.h> #include "RealVector.h" #include "ParksMcClellan.h" namespace NimbleDSP { /** * \brief Class for real FIR filters. */ template <class T> class RealFirFilter : public RealVector<T> { protected: /** * \brief Saved data that is used for stream filtering. */ std::vector<char> savedData; /** * \brief Indicates how many samples are in \ref savedData. Used for stream filtering. */ int numSavedSamples; /** * \brief Indicates the filter phase. Used for stream filtering. */ int phase; /** * \brief Applies a Hamming window on the current contents of "this". */ void hamming(void); public: /** * \brief Determines how the filter should filter. * * NimbleDSP::ONE_SHOT_RETURN_ALL_RESULTS is equivalent to "trimTails = false" of the Vector convolution methods. * NimbleDSP::ONE_SHOT_TRIM_TAILS is equivalent to "trimTails = true" of the Vector convolution methods. * NimbleDSP::STREAMING maintains the filter state from call to call so it can produce results as if it had * filtered one continuous set of data. */ FilterOperationType filtOperation; /***************************************************************************************** Constructors *****************************************************************************************/ /** * \brief Basic constructor. * * Just sets the size of \ref buf and the pointer to the scratch buffer, if one is provided. * \param size Size of \ref buf. * \param scratch Pointer to a scratch buffer. The scratch buffer can be shared by multiple * objects (in fact, I recommend it), but if there are multiple threads then it should * be shared only by objects that are accessed by a single thread. Objects in other * threads should have a separate scratch buffer. If no scratch buffer is provided * then one will be created in methods that require one and destroyed when the method * returns. */ RealFirFilter<T>(unsigned size = DEFAULT_BUF_LEN, FilterOperationType operation = STREAMING, std::vector<T> *scratch = NULL) : RealVector<T>(size, scratch) {if (size > 0) {savedData.resize((size - 1) * sizeof(std::complex<T>)); numSavedSamples = size - 1;} else {savedData.resize(0); numSavedSamples = 0;} phase = 0; filtOperation = operation;} /** * \brief Vector constructor. * * Sets buf equal to the input "data" parameter and sets the pointer to the scratch buffer, * if one is provided. * \param data Vector that \ref buf will be set equal to. * \param scratch Pointer to a scratch buffer. The scratch buffer can be shared by multiple * objects (in fact, I recommend it), but if there are multiple threads then it should * be shared only by objects that are accessed by a single thread. Objects in other * threads should have a separate scratch buffer. If no scratch buffer is provided * then one will be created in methods that require one and destroyed when the method * returns. */ template <typename U> RealFirFilter<T>(std::vector<U> data, FilterOperationType operation = STREAMING, std::vector<T> *scratch = NULL) : RealVector<T>(data, scratch) {savedData.resize((data.size() - 1) * sizeof(std::complex<T>)); numSavedSamples = data.size() - 1; phase = 0; filtOperation = operation;} /** * \brief Array constructor. * * Sets buf equal to the input "data" array and sets the pointer to the scratch buffer, * if one is provided. * \param data Array that \ref buf will be set equal to. * \param dataLen Length of "data". * \param scratch Pointer to a scratch buffer. The scratch buffer can be shared by multiple * objects (in fact, I recommend it), but if there are multiple threads then it should * be shared only by objects that are accessed by a single thread. Objects in other * threads should have a separate scratch buffer. If no scratch buffer is provided * then one will be created in methods that require one and destroyed when the method * returns. */ template <typename U> RealFirFilter<T>(U *data, unsigned dataLen, FilterOperationType operation = STREAMING, std::vector<T> *scratch = NULL) : RealVector<T>(data, dataLen, scratch) {savedData.resize((dataLen - 1) * sizeof(std::complex<T>)); numSavedSamples = dataLen - 1; phase = 0; filtOperation = operation;} /** * \brief Copy constructor. */ RealFirFilter<T>(const RealFirFilter<T>& other) {this->vec = other.vec; savedData = other.savedData; numSavedSamples = other.numSavedSamples; phase = other.phase; filtOperation = other.filtOperation;} /***************************************************************************************** Operators *****************************************************************************************/ /** * \brief Assignment operator. */ RealFirFilter<T>& operator=(const Vector<T>& rhs) {this->vec = rhs.vec; savedData.resize(this->size() - 1); phase = 0; filtOperation = STREAMING; return *this;} /***************************************************************************************** Methods *****************************************************************************************/ /** * \brief Convolution method. * * \param data The buffer that will be filtered. * \param trimTails This parameter is ignored. The operation of the filter is determined by how * \ref filtOperation is set. * \return Reference to "data", which holds the result of the convolution. */ virtual RealVector<T> & conv(RealVector<T> & data, bool trimTails = false); /** * \brief Convolution method for complex data. * * \param data The buffer that will be filtered. * \param trimTails This parameter is ignored. The operation of the filter is determined by how * \ref filtOperation is set. * \return Reference to "data", which holds the result of the convolution. */ virtual ComplexVector<T> & convComplex(ComplexVector<T> & data, bool trimTails = false); /** * \brief Decimate method. * * This method is equivalent to filtering with the \ref conv method and downsampling * with the \ref downsample method, but much more efficient. * * \param data The buffer that will be filtered. * \param rate Indicates how much to downsample. * \param trimTails This parameter is ignored. The operation of the filter is determined by how * \ref filtOperation is set. * \return Reference to "data", which holds the result of the decimation. */ virtual RealVector<T> & decimate(RealVector<T> & data, int rate, bool trimTails = false); /** * \brief Decimate method for complex data. * * This method is equivalent to filtering with the \ref conv method and downsampling * with the \ref downsample method, but much more efficient. * * \param data The buffer that will be filtered. * \param rate Indicates how much to downsample. * \param trimTails This parameter is ignored. The operation of the filter is determined by how * \ref filtOperation is set. * \return Reference to "data", which holds the result of the decimation. */ virtual ComplexVector<T> & decimateComplex(ComplexVector<T> & data, int rate, bool trimTails = false); /** * \brief Interpolation method. * * This method is equivalent to upsampling followed by filtering, but is much more efficient. * * \param data The buffer that will be filtered. * \param rate Indicates how much to upsample. * \param trimTails This parameter is ignored. The operation of the filter is determined by how * \ref filtOperation is set. * \return Reference to "data", which holds the result of the interpolation. */ virtual RealVector<T> & interp(RealVector<T> & data, int rate, bool trimTails = false); /** * \brief Interpolation method for complex data. * * This method is equivalent to upsampling followed by filtering, but is much more efficient. * * \param data The buffer that will be filtered. * \param rate Indicates how much to upsample. * \param trimTails This parameter is ignored. The operation of the filter is determined by how * \ref filtOperation is set. * \return Reference to "data", which holds the result of the interpolation. */ virtual ComplexVector<T> & interpComplex(ComplexVector<T> & data, int rate, bool trimTails = false); /** * \brief Resample method. * * This method is equivalent to upsampling by "interpRate", filtering, and downsampling * by "decimateRate", but is much more efficient. * * \param data The buffer that will be filtered. * \param interpRate Indicates how much to upsample. * \param decimateRate Indicates how much to downsample. * \param trimTails This parameter is ignored. The operation of the filter is determined by how * \ref filtOperation is set. * \return Reference to "data", which holds the result of the resampling. */ virtual RealVector<T> & resample(RealVector<T> & data, int interpRate, int decimateRate, bool trimTails = false); /** * \brief Resample method for complex data. * * This method is equivalent to upsampling by "interpRate", filtering, and downsampling * by "decimateRate", but is much more efficient. * * \param data The buffer that will be filtered. * \param interpRate Indicates how much to upsample. * \param decimateRate Indicates how much to downsample. * \param trimTails This parameter is ignored. The operation of the filter is determined by how * \ref filtOperation is set. * \return Reference to "data", which holds the result of the resampling. */ virtual ComplexVector<T> & resampleComplex(ComplexVector<T> & data, int interpRate, int decimateRate, bool trimTails = false); /** * \brief Parks-McClellan algorithm for generating equiripple FIR filter coefficients. * * Application of the remez algorithm to producing equiripple FIR filter coefficients. It has issues with * convergence. It can generally converge up to 128 taps- more than that and it gets iffy. * * The PM algorithm implementation is a somewhat modified version of Iowa Hills Software's port of the * PM algorithm from the original Fortran to C. Much appreciation to them for their work. * * \param filterOrder Indicates that the number of taps should be filterOrder + 1. * \param numBands The number of pass and stop bands. Maximum of 10 bands. * \param freqPoints Pairs of points specify the boundaries of the bands, thus the length of this array * must be 2 * numBands. The frequencies in between the bands are the transition bands. "0" * corresponds to 0 Hz, and "1" corresponds to the Nyquist frequency. Example: "0.0 0.3 .5 1.0" * specifies two bands, one from 0 Hz to .3 * Nyquist and the other from 0.5 Nyquist to Nyquist. * .3 * Nyquist to .5 * Nyquist is the transition band. * \param desiredBandResponse Indicates what the desired amplitude response is in the corresponding band. * This array must have "numBands" elements. * \param weight Indicates how much weight should be given the performance of the filter in that band. If * all of the elements are "1" then they will have equal weight which will produce a true * equiripple filter (same amount of ripple in the pass and stop bands). If the stop bands are * assigned more weight than the passbands then the attenuation in the stop bands will be increased * at the expense of more ripple in the pass bands. * \param lGrid Grid density. Defaults to 16. This value should generally not be set lower than 16. * Setting it higher than 16 can produce a filter with a better fit to the desired response at * the cost of increased computations. * \return Boolean that indicates whether the filter converged or not. */ bool firpm(int filterOrder, int numBands, double *freqPoints, double *desiredBandResponse, double *weight, int lGrid = 16); /** * \brief Generates a filter that can delay signals by an arbitrary sub-sample time. * * \param numTaps Number of taps to use in the filter. If the only purpose of the filter is to delay * the signal then the number of taps is not crucial. If it is doing actual stop-band filtering * too then the number of taps is important. * \param bandwidth The approximate bandwidth of the filter, normalized to the range 0.0 to 1.0, where * 1.0 is the Nyquist frequency. The bandwidth must be greater than 0 and less than 1. * \param delay Amount of sample time to delay. For example, a delay value of 0.1 would indicate to delay * by one tenth of a sample. "delay" can be positive or negative. */ void fractionalDelayFilter(int numTaps, double bandwidth, double delay); /** * \brief Correlation method. * * \param data The buffer that will be correlated. * \return Reference to "data", which holds the result of the convolution. */ virtual RealVector<T> & corr(RealVector<T> & data); /** * \brief Generates a Hamming window. * * \param len The window length. */ void hamming(unsigned len); /** * \brief Generates a Hann window. * * \param len The window length. */ void hann(unsigned len); /** * \brief Generates a generalized Hamming window. * * \param len The window length. * \param alpha * \param beta */ void generalizedHamming(unsigned len, double alpha, double beta); /** * \brief Generates a Blackman window. * * \param len The window length. */ void blackman(unsigned len); /** * \brief Generates a Blackman-harris window. * * \param len The window length. */ void blackmanHarris(unsigned len); }; template <class T> RealVector<T> & RealFirFilter<T>::conv(RealVector<T> & data, bool trimTails) { int resultIndex; int filterIndex; int dataIndex; std::vector<T> scratch; std::vector<T> *dataTmp; T *savedDataArray = (T *) VECTOR_TO_ARRAY(savedData); if (data.scratchBuf == NULL) { dataTmp = &scratch; } else { dataTmp = data.scratchBuf; } switch (filtOperation) { case STREAMING: dataTmp->resize((this->size() - 1) + data.size()); for (int i=0; i<this->size()-1; i++) { (*dataTmp)[i] = savedDataArray[i]; } for (int i=0; i<data.size(); i++) { (*dataTmp)[i + this->size() - 1] = data[i]; } for (resultIndex=0; resultIndex<(int)data.size(); resultIndex++) { data[resultIndex] = 0; for (dataIndex=resultIndex, filterIndex=this->size()-1; filterIndex>=0; dataIndex++, filterIndex--) { data[resultIndex] += (*dataTmp)[dataIndex] * this->vec[filterIndex]; } } for (int i=0; i<this->size()-1; i++) { savedDataArray[i] = (*dataTmp)[i + data.size()]; } break; case ONE_SHOT_RETURN_ALL_RESULTS: *dataTmp = data.vec; data.resize(data.size() + this->size() - 1); // Initial partial overlap for (resultIndex=0; resultIndex<(int)this->size()-1; resultIndex++) { data[resultIndex] = 0; for (dataIndex=0, filterIndex=resultIndex; filterIndex>=0; dataIndex++, filterIndex--) { data[resultIndex] += (*dataTmp)[dataIndex] * this->vec[filterIndex]; } } // Middle full overlap for (; resultIndex<(int)dataTmp->size(); resultIndex++) { data[resultIndex] = 0; for (dataIndex=resultIndex - (this->size()-1), filterIndex=this->size()-1; filterIndex>=0; dataIndex++, filterIndex--) { data[resultIndex] += (*dataTmp)[dataIndex] * this->vec[filterIndex]; } } // Final partial overlap for (; resultIndex<(int)data.size(); resultIndex++) { data[resultIndex] = 0; for (dataIndex=resultIndex - (this->size()-1), filterIndex=this->size()-1; dataIndex<(int)dataTmp->size(); dataIndex++, filterIndex--) { data[resultIndex] += (*dataTmp)[dataIndex] * this->vec[filterIndex]; } } break; case ONE_SHOT_TRIM_TAILS: *dataTmp = data.vec; // Initial partial overlap int initialTrim = (this->size() - 1) / 2; for (resultIndex=0; resultIndex<((int)this->size()-1) - initialTrim; resultIndex++) { data[resultIndex] = 0; for (dataIndex=0, filterIndex=initialTrim + resultIndex; filterIndex>=0; dataIndex++, filterIndex--) { data[resultIndex] += (*dataTmp)[dataIndex] * this->vec[filterIndex]; } } // Middle full overlap for (; resultIndex<(int)dataTmp->size() - initialTrim; resultIndex++) { data[resultIndex] = 0; for (dataIndex=resultIndex - ((this->size()-1) - initialTrim), filterIndex=this->size()-1; filterIndex>=0; dataIndex++, filterIndex--) { data[resultIndex] += (*dataTmp)[dataIndex] * this->vec[filterIndex]; } } // Final partial overlap for (; resultIndex<(int)data.size(); resultIndex++) { data[resultIndex] = 0; for (dataIndex=resultIndex - ((this->size()-1) - initialTrim), filterIndex=this->size()-1; dataIndex<(int)dataTmp->size(); dataIndex++, filterIndex--) { data[resultIndex] += (*dataTmp)[dataIndex] * this->vec[filterIndex]; } } break; } return data; } template <class T> ComplexVector<T> & RealFirFilter<T>::convComplex(ComplexVector<T> & data, bool trimTails) { int resultIndex; int filterIndex; int dataIndex; std::vector< std::complex<T> > scratch; std::vector< std::complex<T> > *dataTmp; std::complex<T> *savedDataArray = (std::complex<T> *) VECTOR_TO_ARRAY(savedData); if (data.scratchBuf == NULL) { dataTmp = &scratch; } else { dataTmp = data.scratchBuf; } switch (filtOperation) { case STREAMING: dataTmp->resize((this->size() - 1) + data.size()); for (int i=0; i<this->size()-1; i++) { (*dataTmp)[i] = savedDataArray[i]; } for (int i=0; i<data.size(); i++) { (*dataTmp)[i + this->size() - 1] = data[i]; } for (resultIndex=0; resultIndex<(int)data.size(); resultIndex++) { data[resultIndex] = 0; for (dataIndex=resultIndex, filterIndex=this->size()-1; filterIndex>=0; dataIndex++, filterIndex--) { data[resultIndex] += (*dataTmp)[dataIndex] * this->vec[filterIndex]; } } for (int i=0; i<this->size()-1; i++) { savedDataArray[i] = (*dataTmp)[i + data.size()]; } break; case ONE_SHOT_RETURN_ALL_RESULTS: *dataTmp = data.vec; data.resize(data.size() + this->size() - 1); // Initial partial overlap for (resultIndex=0; resultIndex<(int)this->size()-1; resultIndex++) { data[resultIndex] = 0; for (dataIndex=0, filterIndex=resultIndex; filterIndex>=0; dataIndex++, filterIndex--) { data[resultIndex] += (*dataTmp)[dataIndex] * this->vec[filterIndex]; } } // Middle full overlap for (; resultIndex<(int)dataTmp->size(); resultIndex++) { data[resultIndex] = 0; for (dataIndex=resultIndex - (this->size()-1), filterIndex=this->size()-1; filterIndex>=0; dataIndex++, filterIndex--) { data[resultIndex] += (*dataTmp)[dataIndex] * this->vec[filterIndex]; } } // Final partial overlap for (; resultIndex<(int)data.size(); resultIndex++) { data[resultIndex] = 0; for (dataIndex=resultIndex - (this->size()-1), filterIndex=this->size()-1; dataIndex<(int)dataTmp->size(); dataIndex++, filterIndex--) { data[resultIndex] += (*dataTmp)[dataIndex] * this->vec[filterIndex]; } } break; case ONE_SHOT_TRIM_TAILS: *dataTmp = data.vec; // Initial partial overlap int initialTrim = (this->size() - 1) / 2; for (resultIndex=0; resultIndex<((int)this->size()-1) - initialTrim; resultIndex++) { data[resultIndex] = 0; for (dataIndex=0, filterIndex=initialTrim + resultIndex; filterIndex>=0; dataIndex++, filterIndex--) { data[resultIndex] += (*dataTmp)[dataIndex] * this->vec[filterIndex]; } } // Middle full overlap for (; resultIndex<(int)dataTmp->size() - initialTrim; resultIndex++) { data[resultIndex] = 0; for (dataIndex=resultIndex - ((this->size()-1) - initialTrim), filterIndex=this->size()-1; filterIndex>=0; dataIndex++, filterIndex--) { data[resultIndex] += (*dataTmp)[dataIndex] * this->vec[filterIndex]; } } // Final partial overlap for (; resultIndex<(int)data.size(); resultIndex++) { data[resultIndex] = 0; for (dataIndex=resultIndex - ((this->size()-1) - initialTrim), filterIndex=this->size()-1; dataIndex<(int)dataTmp->size(); dataIndex++, filterIndex--) { data[resultIndex] += (*dataTmp)[dataIndex] * this->vec[filterIndex]; } } break; } return data; } template <class T> RealVector<T> & RealFirFilter<T>::decimate(RealVector<T> & data, int rate, bool trimTails) { int resultIndex; int filterIndex; int dataIndex; std::vector<T> scratch; std::vector<T> *dataTmp; T *savedDataArray = (T *) VECTOR_TO_ARRAY(savedData); if (data.scratchBuf == NULL) { dataTmp = &scratch; } else { dataTmp = data.scratchBuf; } switch (filtOperation) { case STREAMING: { dataTmp->resize(numSavedSamples + data.size()); for (int i=0; i<numSavedSamples; i++) { (*dataTmp)[i] = savedDataArray[i]; } for (int i=0; i<data.size(); i++) { (*dataTmp)[i + numSavedSamples] = data[i]; } data.resize((data.size() + numSavedSamples - (this->size() - 1) + rate - 1)/rate); for (resultIndex=0; resultIndex<(int)data.size(); resultIndex++) { data[resultIndex] = 0; for (dataIndex=resultIndex*rate, filterIndex=this->size()-1; filterIndex>=0; dataIndex++, filterIndex--) { data[resultIndex] += (*dataTmp)[dataIndex] * this->vec[filterIndex]; } } int nextResultDataPoint = resultIndex * rate; numSavedSamples = (unsigned) dataTmp->size() - nextResultDataPoint; for (int i=0; i<numSavedSamples; i++) { savedDataArray[i] = (*dataTmp)[i + nextResultDataPoint]; } } break; case ONE_SHOT_RETURN_ALL_RESULTS: *dataTmp = data.vec; data.resize(((data.size() + this->size() - 1) + (rate - 1)) / rate); // Initial partial overlap for (resultIndex=0; resultIndex<((int)this->size()-1+rate-1)/rate; resultIndex++) { data[resultIndex] = 0; for (dataIndex=0, filterIndex=resultIndex*rate; filterIndex>=0; dataIndex++, filterIndex--) { data[resultIndex] += (*dataTmp)[dataIndex] * this->vec[filterIndex]; } } // Middle full overlap for (; resultIndex<((int)dataTmp->size()+rate-1)/rate; resultIndex++) { data[resultIndex] = 0; for (dataIndex=resultIndex*rate - (this->size()-1), filterIndex=this->size()-1; filterIndex>=0; dataIndex++, filterIndex--) { data[resultIndex] += (*dataTmp)[dataIndex] * this->vec[filterIndex]; } } // Final partial overlap for (; resultIndex<(int)data.size(); resultIndex++) { data[resultIndex] = 0; for (dataIndex=resultIndex*rate - (this->size()-1), filterIndex=this->size()-1; dataIndex<(int)dataTmp->size(); dataIndex++, filterIndex--) { data[resultIndex] += (*dataTmp)[dataIndex] * this->vec[filterIndex]; } } break; case ONE_SHOT_TRIM_TAILS: *dataTmp = data.vec; data.resize((data.size() + rate - 1) / rate); // Initial partial overlap int initialTrim = (this->size() - 1) / 2; for (resultIndex=0; resultIndex<(((int)this->size()-1) - initialTrim + rate - 1)/rate; resultIndex++) { data[resultIndex] = 0; for (dataIndex=0, filterIndex=initialTrim + resultIndex*rate; filterIndex>=0; dataIndex++, filterIndex--) { data[resultIndex] += (*dataTmp)[dataIndex] * this->vec[filterIndex]; } } // Middle full overlap for (; resultIndex<((int)dataTmp->size() - initialTrim + rate - 1)/rate; resultIndex++) { data[resultIndex] = 0; for (dataIndex=resultIndex*rate - ((this->size()-1) - initialTrim), filterIndex=this->size()-1; filterIndex>=0; dataIndex++, filterIndex--) { data[resultIndex] += (*dataTmp)[dataIndex] * this->vec[filterIndex]; } } // Final partial overlap for (; resultIndex<(int)data.size(); resultIndex++) { data[resultIndex] = 0; for (dataIndex=resultIndex*rate - ((this->size()-1) - initialTrim), filterIndex=this->size()-1; dataIndex<(int)dataTmp->size(); dataIndex++, filterIndex--) { data[resultIndex] += (*dataTmp)[dataIndex] * this->vec[filterIndex]; } } break; } return data; } template <class T> ComplexVector<T> & RealFirFilter<T>::decimateComplex(ComplexVector<T> & data, int rate, bool trimTails) { int resultIndex; int filterIndex; int dataIndex; std::vector< std::complex<T> > scratch; std::vector< std::complex<T> > *dataTmp; std::complex<T> *savedDataArray = (std::complex<T> *) VECTOR_TO_ARRAY(savedData); if (data.scratchBuf == NULL) { dataTmp = &scratch; } else { dataTmp = data.scratchBuf; } switch (filtOperation) { case STREAMING: { dataTmp->resize(numSavedSamples + data.size()); for (int i=0; i<numSavedSamples; i++) { (*dataTmp)[i] = savedDataArray[i]; } for (int i=0; i<data.size(); i++) { (*dataTmp)[i + numSavedSamples] = data[i]; } data.resize((data.size() + numSavedSamples - (this->size() - 1) + rate - 1)/rate); for (resultIndex=0; resultIndex<(int)data.size(); resultIndex++) { data[resultIndex] = 0; for (dataIndex=resultIndex*rate, filterIndex=this->size()-1; filterIndex>=0; dataIndex++, filterIndex--) { data[resultIndex] += (*dataTmp)[dataIndex] * this->vec[filterIndex]; } } int nextResultDataPoint = resultIndex * rate; numSavedSamples = ((int) dataTmp->size()) - nextResultDataPoint; for (int i=0; i<numSavedSamples; i++) { savedDataArray[i] = (*dataTmp)[i + nextResultDataPoint]; } } break; case ONE_SHOT_RETURN_ALL_RESULTS: *dataTmp = data.vec; data.resize(((data.size() + this->size() - 1) + (rate - 1)) / rate); // Initial partial overlap for (resultIndex=0; resultIndex<((int)this->size()-1+rate-1)/rate; resultIndex++) { data[resultIndex] = 0; for (dataIndex=0, filterIndex=resultIndex*rate; filterIndex>=0; dataIndex++, filterIndex--) { data[resultIndex] += (*dataTmp)[dataIndex] * this->vec[filterIndex]; } } // Middle full overlap for (; resultIndex<((int)dataTmp->size()+rate-1)/rate; resultIndex++) { data[resultIndex] = 0; for (dataIndex=resultIndex*rate - (this->size()-1), filterIndex=this->size()-1; filterIndex>=0; dataIndex++, filterIndex--) { data[resultIndex] += (*dataTmp)[dataIndex] * this->vec[filterIndex]; } } // Final partial overlap for (; resultIndex<(int)data.size(); resultIndex++) { data[resultIndex] = 0; for (dataIndex=resultIndex*rate - (this->size()-1), filterIndex=this->size()-1; dataIndex<(int)dataTmp->size(); dataIndex++, filterIndex--) { data[resultIndex] += (*dataTmp)[dataIndex] * this->vec[filterIndex]; } } break; case ONE_SHOT_TRIM_TAILS: *dataTmp = data.vec; data.resize((data.size() + rate - 1) / rate); // Initial partial overlap int initialTrim = (this->size() - 1) / 2; for (resultIndex=0; resultIndex<(((int)this->size()-1) - initialTrim + rate - 1)/rate; resultIndex++) { data[resultIndex] = 0; for (dataIndex=0, filterIndex=initialTrim + resultIndex*rate; filterIndex>=0; dataIndex++, filterIndex--) { data[resultIndex] += (*dataTmp)[dataIndex] * this->vec[filterIndex]; } } // Middle full overlap for (; resultIndex<((int)dataTmp->size() - initialTrim + rate - 1)/rate; resultIndex++) { data[resultIndex] = 0; for (dataIndex=resultIndex*rate - ((this->size()-1) - initialTrim), filterIndex=this->size()-1; filterIndex>=0; dataIndex++, filterIndex--) { data[resultIndex] += (*dataTmp)[dataIndex] * this->vec[filterIndex]; } } // Final partial overlap for (; resultIndex<(int)data.size(); resultIndex++) { data[resultIndex] = 0; for (dataIndex=resultIndex*rate - ((this->size()-1) - initialTrim), filterIndex=this->size()-1; dataIndex<(int)dataTmp->size(); dataIndex++, filterIndex--) { data[resultIndex] += (*dataTmp)[dataIndex] * this->vec[filterIndex]; } } break; } return data; } template <class T> RealVector<T> & RealFirFilter<T>::interp(RealVector<T> & data, int rate, bool trimTails) { int resultIndex; int filterIndex; int dataIndex; int dataStart, filterStart; std::vector<T> scratch; std::vector<T> *dataTmp; T *savedDataArray = (T *) VECTOR_TO_ARRAY(savedData); if (data.scratchBuf == NULL) { dataTmp = &scratch; } else { dataTmp = data.scratchBuf; } switch (filtOperation) { case STREAMING: { int numTaps = (this->size() + rate - 1) / rate; if (numSavedSamples >= numTaps) { // First call to interp, have too many "saved" (really just the initial zeros) samples numSavedSamples = numTaps - 1; phase = (numTaps - 1) * rate; } dataTmp->resize(numSavedSamples + data.size()); for (int i=0; i<numSavedSamples; i++) { (*dataTmp)[i] = savedDataArray[i]; } for (int i=0; i<data.size(); i++) { (*dataTmp)[i + numSavedSamples] = data[i]; } data.resize((unsigned) dataTmp->size() * rate); bool keepGoing = true; for (resultIndex=0, dataStart=0, filterStart=phase; keepGoing; ++resultIndex) { data[resultIndex] = 0; for (dataIndex=dataStart, filterIndex=filterStart; filterIndex>=0; dataIndex++, filterIndex-=rate) { data[resultIndex] += (*dataTmp)[dataIndex] * this->vec[filterIndex]; } ++filterStart; if (filterStart >= (int)this->size()) { // Filter no longer overlaps with this data sample, so the first overlap sample is the next one. We thus // increment the data index and decrement the filter index. filterStart -= rate; ++dataStart; if (dataTmp->size() - dataStart == numSavedSamples) { keepGoing = false; phase = filterStart; } } } data.resize(resultIndex); int i; for (i=0; dataStart<dataTmp->size(); i++, dataStart++) { savedDataArray[i] = (*dataTmp)[dataStart]; } numSavedSamples = i; } break; case ONE_SHOT_RETURN_ALL_RESULTS: *dataTmp = data.vec; data.resize(data.size() * rate + this->size() - 1 - (rate - 1)); // Initial partial overlap for (resultIndex=0, dataStart=0; resultIndex<(int)this->size()-1; resultIndex++) { data[resultIndex] = 0; for (dataIndex=0, filterIndex=resultIndex; filterIndex>=0; dataIndex++, filterIndex-=rate) { data[resultIndex] += (*dataTmp)[dataIndex] * this->vec[filterIndex]; } } // Middle full overlap for (dataStart=0, filterStart=resultIndex; resultIndex<(int)dataTmp->size()*rate; resultIndex++) { data[resultIndex] = 0; for (dataIndex=dataStart, filterIndex=filterStart; filterIndex>=0; dataIndex++, filterIndex-=rate) { data[resultIndex] += (*dataTmp)[dataIndex] * this->vec[filterIndex]; } ++filterStart; if (filterStart >= (int)this->size()) { // Filter no longer overlaps with this data sample, so the first overlap sample is the next one. We thus // increment the data index and decrement the filter index. filterStart -= rate; ++dataStart; } } // Final partial overlap for (; resultIndex<(int)data.size(); resultIndex++) { data[resultIndex] = 0; for (dataIndex=dataStart, filterIndex=filterStart; dataIndex<(int)dataTmp->size(); dataIndex++, filterIndex-=rate) { data[resultIndex] += (*dataTmp)[dataIndex] * this->vec[filterIndex]; } ++filterStart; if (filterStart >= (int) this->size()) { // Filter no longer overlaps with this data sample, so the first overlap sample is the next one. We thus // increment the data index and decrement the filter index. filterStart -= rate; ++dataStart; } } break; case ONE_SHOT_TRIM_TAILS: *dataTmp = data.vec; data.resize(data.size() * rate); // Initial partial overlap int initialTrim = (this->size() - 1) / 2; for (resultIndex=0, dataStart=0; resultIndex<(int)this->size()-1 - initialTrim; resultIndex++) { data[resultIndex] = 0; for (dataIndex=0, filterIndex=initialTrim + resultIndex; filterIndex>=0; dataIndex++, filterIndex-=rate) { data[resultIndex] += (*dataTmp)[dataIndex] * this->vec[filterIndex]; } } // Middle full overlap for (dataStart=0, filterStart=(int)this->size()-1; resultIndex<(int)dataTmp->size()*rate - initialTrim; resultIndex++) { data[resultIndex] = 0; for (dataIndex=dataStart, filterIndex=filterStart; filterIndex>=0; dataIndex++, filterIndex-=rate) { data[resultIndex] += (*dataTmp)[dataIndex] * this->vec[filterIndex]; } ++filterStart; if (filterStart >= (int)this->size()) { // Filter no longer overlaps with this data sample, so the first overlap sample is the next one. We thus // increment the data index and decrement the filter index. filterStart -= rate; ++dataStart; } } // Final partial overlap for (; resultIndex<(int)data.size(); resultIndex++) { data[resultIndex] = 0; for (dataIndex=dataStart, filterIndex=filterStart; dataIndex<(int)dataTmp->size(); dataIndex++, filterIndex-=rate) { data[resultIndex] += (*dataTmp)[dataIndex] * this->vec[filterIndex]; } ++filterStart; if (filterStart >= (int)this->size()) { // Filter no longer overlaps with this data sample, so the first overlap sample is the next one. We thus // increment the data index and decrement the filter index. filterStart -= rate; ++dataStart; } } break; } return data; } template <class T> ComplexVector<T> & RealFirFilter<T>::interpComplex(ComplexVector<T> & data, int rate, bool trimTails) { int resultIndex; int filterIndex; int dataIndex; int dataStart, filterStart; std::vector< std::complex<T> > scratch; std::vector< std::complex<T> > *dataTmp; std::complex<T> *savedDataArray = (std::complex<T> *) VECTOR_TO_ARRAY(savedData); if (data.scratchBuf == NULL) { dataTmp = &scratch; } else { dataTmp = data.scratchBuf; } switch (filtOperation) { case STREAMING: { int numTaps = (this->size() + rate - 1) / rate; if (numSavedSamples >= numTaps) { // First call to interp, have too many "saved" (really just the initial zeros) samples numSavedSamples = numTaps - 1; phase = (numTaps - 1) * rate; } dataTmp->resize(numSavedSamples + data.size()); for (int i=0; i<numSavedSamples; i++) { (*dataTmp)[i] = savedDataArray[i]; } for (int i=0; i<data.size(); i++) { (*dataTmp)[i + numSavedSamples] = data[i]; } data.resize((unsigned) dataTmp->size() * rate); bool keepGoing = true; for (resultIndex=0, dataStart=0, filterStart=phase; keepGoing; ++resultIndex) { data[resultIndex] = 0; for (dataIndex=dataStart, filterIndex=filterStart; filterIndex>=0; dataIndex++, filterIndex-=rate) { data[resultIndex] += (*dataTmp)[dataIndex] * this->vec[filterIndex]; } ++filterStart; if (filterStart >= (int)this->size()) { // Filter no longer overlaps with this data sample, so the first overlap sample is the next one. We thus // increment the data index and decrement the filter index. filterStart -= rate; ++dataStart; if (dataTmp->size() - dataStart == numSavedSamples) { keepGoing = false; phase = filterStart; } } } data.resize(resultIndex); int i; for (i=0; dataStart<dataTmp->size(); i++, dataStart++) { savedDataArray[i] = (*dataTmp)[dataStart]; } numSavedSamples = i; } break; case ONE_SHOT_RETURN_ALL_RESULTS: *dataTmp = data.vec; data.resize(data.size() * rate + this->size() - 1 - (rate - 1)); // Initial partial overlap for (resultIndex=0, dataStart=0; resultIndex<(int)this->size()-1; resultIndex++) { data[resultIndex] = 0; for (dataIndex=0, filterIndex=resultIndex; filterIndex>=0; dataIndex++, filterIndex-=rate) { data[resultIndex] += (*dataTmp)[dataIndex] * this->vec[filterIndex]; } } // Middle full overlap for (dataStart=0, filterStart=resultIndex; resultIndex<(int)dataTmp->size()*rate; resultIndex++) { data[resultIndex] = 0; for (dataIndex=dataStart, filterIndex=filterStart; filterIndex>=0; dataIndex++, filterIndex-=rate) { data[resultIndex] += (*dataTmp)[dataIndex] * this->vec[filterIndex]; } ++filterStart; if (filterStart >= (int)this->size()) { // Filter no longer overlaps with this data sample, so the first overlap sample is the next one. We thus // increment the data index and decrement the filter index. filterStart -= rate; ++dataStart; } } // Final partial overlap for (; resultIndex<(int)data.size(); resultIndex++) { data[resultIndex] = 0; for (dataIndex=dataStart, filterIndex=filterStart; dataIndex<(int)dataTmp->size(); dataIndex++, filterIndex-=rate) { data[resultIndex] += (*dataTmp)[dataIndex] * this->vec[filterIndex]; } ++filterStart; if (filterStart >= (int) this->size()) { // Filter no longer overlaps with this data sample, so the first overlap sample is the next one. We thus // increment the data index and decrement the filter index. filterStart -= rate; ++dataStart; } } break; case ONE_SHOT_TRIM_TAILS: *dataTmp = data.vec; data.resize(data.size() * rate); // Initial partial overlap int initialTrim = (this->size() - 1) / 2; for (resultIndex=0, dataStart=0; resultIndex<(int)this->size()-1 - initialTrim; resultIndex++) { data[resultIndex] = 0; for (dataIndex=0, filterIndex=initialTrim + resultIndex; filterIndex>=0; dataIndex++, filterIndex-=rate) { data[resultIndex] += (*dataTmp)[dataIndex] * this->vec[filterIndex]; } } // Middle full overlap for (dataStart=0, filterStart=(int)this->size()-1; resultIndex<(int)dataTmp->size()*rate - initialTrim; resultIndex++) { data[resultIndex] = 0; for (dataIndex=dataStart, filterIndex=filterStart; filterIndex>=0; dataIndex++, filterIndex-=rate) { data[resultIndex] += (*dataTmp)[dataIndex] * this->vec[filterIndex]; } ++filterStart; if (filterStart >= (int)this->size()) { // Filter no longer overlaps with this data sample, so the first overlap sample is the next one. We thus // increment the data index and decrement the filter index. filterStart -= rate; ++dataStart; } } // Final partial overlap for (; resultIndex<(int)data.size(); resultIndex++) { data[resultIndex] = 0; for (dataIndex=dataStart, filterIndex=filterStart; dataIndex<(int)dataTmp->size(); dataIndex++, filterIndex-=rate) { data[resultIndex] += (*dataTmp)[dataIndex] * this->vec[filterIndex]; } ++filterStart; if (filterStart >= (int)this->size()) { // Filter no longer overlaps with this data sample, so the first overlap sample is the next one. We thus // increment the data index and decrement the filter index. filterStart -= rate; ++dataStart; } } break; } return data; } template <class T> RealVector<T> & RealFirFilter<T>::resample(RealVector<T> & data, int interpRate, int decimateRate, bool trimTails) { int resultIndex; int filterIndex; int dataIndex; int dataStart, filterStart; int interpLen, resampLen; std::vector<T> scratch; std::vector<T> *dataTmp; T *savedDataArray = (T *) VECTOR_TO_ARRAY(savedData); if (data.scratchBuf == NULL) { dataTmp = &scratch; } else { dataTmp = data.scratchBuf; } switch (filtOperation) { case STREAMING: { int numTaps = (this->size() + interpRate - 1) / interpRate; if (numSavedSamples >= numTaps) { // First call to interp, have too many "saved" (really just the initial zeros) samples numSavedSamples = numTaps - 1; phase = (numTaps - 1) * interpRate; } dataTmp->resize(numSavedSamples + data.size()); for (int i=0; i<numSavedSamples; i++) { (*dataTmp)[i] = savedDataArray[i]; } for (int i=0; i<data.size(); i++) { (*dataTmp)[i + numSavedSamples] = data[i]; } interpLen = (unsigned) dataTmp->size() * interpRate; resampLen = (interpLen + decimateRate - 1) / decimateRate; data.resize(resampLen); bool keepGoing = true; for (resultIndex=0, dataStart=0, filterStart=phase; keepGoing; ++resultIndex) { data[resultIndex] = 0; for (dataIndex=dataStart, filterIndex=filterStart; filterIndex>=0; dataIndex++, filterIndex-=interpRate) { data[resultIndex] += (*dataTmp)[dataIndex] * this->vec[filterIndex]; } filterStart += decimateRate; while (filterStart >= (int)this->size()) { // Filter no longer overlaps with this data sample, so the first overlap sample is the next one. We thus // increment the data index and decrement the filter index. filterStart -= interpRate; ++dataStart; } if (dataTmp->size() - dataStart == numSavedSamples) { keepGoing = false; phase = filterStart; } } data.resize(resultIndex); int i; for (i=0; dataStart<dataTmp->size(); i++, dataStart++) { savedDataArray[i] = (*dataTmp)[dataStart]; } numSavedSamples = i; } break; case ONE_SHOT_RETURN_ALL_RESULTS: *dataTmp = data.vec; interpLen = data.size() * interpRate + this->size() - 1 - (interpRate - 1); resampLen = (interpLen + decimateRate - 1) / decimateRate; data.resize(resampLen); // Initial partial overlap for (resultIndex=0, dataStart=0, filterStart=0; resultIndex<((int)this->size()-1+decimateRate-1)/decimateRate; resultIndex++) { data[resultIndex] = 0; for (dataIndex=0, filterIndex=filterStart; filterIndex>=0; dataIndex++, filterIndex-=interpRate) { data[resultIndex] += (*dataTmp)[dataIndex] * this->vec[filterIndex]; } filterStart += decimateRate; while (filterStart >= (int)this->size()) { // Filter no longer overlaps with this data sample, so the first overlap sample is the next one. We thus // increment the data index and decrement the filter index. filterStart -= interpRate; ++dataStart; } } // Middle full overlap for (; resultIndex<((int)dataTmp->size()*interpRate + decimateRate-1)/decimateRate; resultIndex++) { data[resultIndex] = 0; for (dataIndex=dataStart, filterIndex=filterStart; filterIndex>=0; dataIndex++, filterIndex-=interpRate) { data[resultIndex] += (*dataTmp)[dataIndex] * this->vec[filterIndex]; } filterStart += decimateRate; while (filterStart >= (int)this->size()) { // Filter no longer overlaps with this data sample, so the first overlap sample is the next one. We thus // increment the data index and decrement the filter index. filterStart -= interpRate; ++dataStart; } } // Final partial overlap for (; resultIndex<(int)data.size(); resultIndex++) { data[resultIndex] = 0; for (dataIndex=dataStart, filterIndex=filterStart; dataIndex<(int)dataTmp->size(); dataIndex++, filterIndex-=interpRate) { data[resultIndex] += (*dataTmp)[dataIndex] * this->vec[filterIndex]; } filterStart += decimateRate; while (filterStart >= (int)this->size()) { // Filter no longer overlaps with this data sample, so the first overlap sample is the next one. We thus // increment the data index and decrement the filter index. filterStart -= interpRate; ++dataStart; } } break; case ONE_SHOT_TRIM_TAILS: *dataTmp = data.vec; interpLen = data.size() * interpRate; resampLen = (interpLen + decimateRate - 1) / decimateRate; data.resize(resampLen); // Initial partial overlap int initialTrim = (this->size() - 1) / 2; for (resultIndex=0, dataStart=0, filterStart=initialTrim; resultIndex<((int)this->size()-1 - initialTrim + decimateRate-1)/decimateRate; resultIndex++) { data[resultIndex] = 0; for (dataIndex=0, filterIndex=filterStart; filterIndex>=0; dataIndex++, filterIndex-=interpRate) { data[resultIndex] += (*dataTmp)[dataIndex] * this->vec[filterIndex]; } filterStart += decimateRate; while (filterStart >= (int)this->size()) { // Filter no longer overlaps with this data sample, so the first overlap sample is the next one. We thus // increment the data index and decrement the filter index. filterStart -= interpRate; ++dataStart; } } // Middle full overlap for (; resultIndex<((int)dataTmp->size()*interpRate - initialTrim + decimateRate-1)/decimateRate; resultIndex++) { data[resultIndex] = 0; for (dataIndex=dataStart, filterIndex=filterStart; filterIndex>=0; dataIndex++, filterIndex-=interpRate) { data[resultIndex] += (*dataTmp)[dataIndex] * this->vec[filterIndex]; } filterStart += decimateRate; while (filterStart >= (int)this->size()) { // Filter no longer overlaps with this data sample, so the first overlap sample is the next one. We thus // increment the data index and decrement the filter index. filterStart -= interpRate; ++dataStart; } } // Final partial overlap for (; resultIndex<(int)data.size(); resultIndex++) { data[resultIndex] = 0; for (dataIndex=dataStart, filterIndex=filterStart; dataIndex<(int)dataTmp->size(); dataIndex++, filterIndex-=interpRate) { data[resultIndex] += (*dataTmp)[dataIndex] * this->vec[filterIndex]; } filterStart += decimateRate; while (filterStart >= (int)this->size()) { // Filter no longer overlaps with this data sample, so the first overlap sample is the next one. We thus // increment the data index and decrement the filter index. filterStart -= interpRate; ++dataStart; } } break; } return data; } template <class T> ComplexVector<T> & RealFirFilter<T>::resampleComplex(ComplexVector<T> & data, int interpRate, int decimateRate, bool trimTails) { int resultIndex; int filterIndex; int dataIndex; int dataStart, filterStart; int interpLen, resampLen; std::vector< std::complex<T> > scratch; std::vector< std::complex<T> > *dataTmp; std::complex<T> *savedDataArray = (std::complex<T> *) VECTOR_TO_ARRAY(savedData); if (data.scratchBuf == NULL) { dataTmp = &scratch; } else { dataTmp = data.scratchBuf; } switch (filtOperation) { case STREAMING: { int numTaps = (this->size() + interpRate - 1) / interpRate; if (numSavedSamples >= numTaps) { // First call to interp, have too many "saved" (really just the initial zeros) samples numSavedSamples = numTaps - 1; phase = (numTaps - 1) * interpRate; } dataTmp->resize(numSavedSamples + data.size()); for (int i=0; i<numSavedSamples; i++) { (*dataTmp)[i] = savedDataArray[i]; } for (int i=0; i<data.size(); i++) { (*dataTmp)[i + numSavedSamples] = data[i]; } interpLen = (unsigned) dataTmp->size() * interpRate; resampLen = (interpLen + decimateRate - 1) / decimateRate; data.resize(resampLen); bool keepGoing = true; for (resultIndex=0, dataStart=0, filterStart=phase; keepGoing; ++resultIndex) { data[resultIndex] = 0; for (dataIndex=dataStart, filterIndex=filterStart; filterIndex>=0; dataIndex++, filterIndex-=interpRate) { data[resultIndex] += (*dataTmp)[dataIndex] * this->vec[filterIndex]; } filterStart += decimateRate; while (filterStart >= (int)this->size()) { // Filter no longer overlaps with this data sample, so the first overlap sample is the next one. We thus // increment the data index and decrement the filter index. filterStart -= interpRate; ++dataStart; } if (dataTmp->size() - dataStart == numSavedSamples) { keepGoing = false; phase = filterStart; } } data.resize(resultIndex); int i; for (i=0; dataStart<dataTmp->size(); i++, dataStart++) { savedDataArray[i] = (*dataTmp)[dataStart]; } numSavedSamples = i; } break; case ONE_SHOT_RETURN_ALL_RESULTS: *dataTmp = data.vec; interpLen = data.size() * interpRate + this->size() - 1 - (interpRate - 1); resampLen = (interpLen + decimateRate - 1) / decimateRate; data.resize(resampLen); // Initial partial overlap for (resultIndex=0, dataStart=0, filterStart=0; resultIndex<((int)this->size()-1+decimateRate-1)/decimateRate; resultIndex++) { data[resultIndex] = 0; for (dataIndex=0, filterIndex=filterStart; filterIndex>=0; dataIndex++, filterIndex-=interpRate) { data[resultIndex] += (*dataTmp)[dataIndex] * this->vec[filterIndex]; } filterStart += decimateRate; while (filterStart >= (int)this->size()) { // Filter no longer overlaps with this data sample, so the first overlap sample is the next one. We thus // increment the data index and decrement the filter index. filterStart -= interpRate; ++dataStart; } } // Middle full overlap for (; resultIndex<((int)dataTmp->size()*interpRate + decimateRate-1)/decimateRate; resultIndex++) { data[resultIndex] = 0; for (dataIndex=dataStart, filterIndex=filterStart; filterIndex>=0; dataIndex++, filterIndex-=interpRate) { data[resultIndex] += (*dataTmp)[dataIndex] * this->vec[filterIndex]; } filterStart += decimateRate; while (filterStart >= (int)this->size()) { // Filter no longer overlaps with this data sample, so the first overlap sample is the next one. We thus // increment the data index and decrement the filter index. filterStart -= interpRate; ++dataStart; } } // Final partial overlap for (; resultIndex<(int)data.size(); resultIndex++) { data[resultIndex] = 0; for (dataIndex=dataStart, filterIndex=filterStart; dataIndex<(int)dataTmp->size(); dataIndex++, filterIndex-=interpRate) { data[resultIndex] += (*dataTmp)[dataIndex] * this->vec[filterIndex]; } filterStart += decimateRate; while (filterStart >= (int)this->size()) { // Filter no longer overlaps with this data sample, so the first overlap sample is the next one. We thus // increment the data index and decrement the filter index. filterStart -= interpRate; ++dataStart; } } break; case ONE_SHOT_TRIM_TAILS: *dataTmp = data.vec; interpLen = data.size() * interpRate; resampLen = (interpLen + decimateRate - 1) / decimateRate; data.resize(resampLen); // Initial partial overlap int initialTrim = (this->size() - 1) / 2; for (resultIndex=0, dataStart=0, filterStart=initialTrim; resultIndex<((int)this->size()-1 - initialTrim + decimateRate-1)/decimateRate; resultIndex++) { data[resultIndex] = 0; for (dataIndex=0, filterIndex=filterStart; filterIndex>=0; dataIndex++, filterIndex-=interpRate) { data[resultIndex] += (*dataTmp)[dataIndex] * this->vec[filterIndex]; } filterStart += decimateRate; while (filterStart >= (int)this->size()) { // Filter no longer overlaps with this data sample, so the first overlap sample is the next one. We thus // increment the data index and decrement the filter index. filterStart -= interpRate; ++dataStart; } } // Middle full overlap for (; resultIndex<((int)dataTmp->size()*interpRate - initialTrim + decimateRate-1)/decimateRate; resultIndex++) { data[resultIndex] = 0; for (dataIndex=dataStart, filterIndex=filterStart; filterIndex>=0; dataIndex++, filterIndex-=interpRate) { data[resultIndex] += (*dataTmp)[dataIndex] * this->vec[filterIndex]; } filterStart += decimateRate; while (filterStart >= (int)this->size()) { // Filter no longer overlaps with this data sample, so the first overlap sample is the next one. We thus // increment the data index and decrement the filter index. filterStart -= interpRate; ++dataStart; } } // Final partial overlap for (; resultIndex<(int)data.size(); resultIndex++) { data[resultIndex] = 0; for (dataIndex=dataStart, filterIndex=filterStart; dataIndex<(int)dataTmp->size(); dataIndex++, filterIndex-=interpRate) { data[resultIndex] += (*dataTmp)[dataIndex] * this->vec[filterIndex]; } filterStart += decimateRate; while (filterStart >= (int)this->size()) { // Filter no longer overlaps with this data sample, so the first overlap sample is the next one. We thus // increment the data index and decrement the filter index. filterStart -= interpRate; ++dataStart; } } break; } return data; } template <class T> bool RealFirFilter<T>::firpm(int filterOrder, int numBands, double *freqPoints, double *desiredBandResponse, double *weight, int lGrid) { bool converged; this->resize(filterOrder + 1); std::vector<double> temp(filterOrder + 1); // Need to renormalize the frequency points because for us the Nyquist frequency is 1.0, but for the // Iowa Hills code it is 0.5. for (int i=0; i<numBands*2; i++) { freqPoints[i] /= 2; } // Move the pointers back 1 (i.e. subtract one) because the ParksMcClellan code was ported from Fortran, // which apparently uses 1-based arrays, not 0-based arrays. converged = ParksMcClellan2(&(temp[0]), filterOrder + 1, PASSBAND_FILTER, numBands, freqPoints-1, desiredBandResponse-1, weight-1, lGrid); for (int i=0; i<= filterOrder; i++) { (*this)[i] = (T) temp[i]; } return converged; } template <class T> void RealFirFilter<T>::fractionalDelayFilter(int numTaps, double bandwidth, double delay) { assert(bandwidth > 0 && bandwidth < 1.0); assert(numTaps > 0); int index; double tapTime; double timeIncrement = bandwidth * M_PI; if (numTaps % 2) { tapTime = (numTaps / 2 + delay) * -timeIncrement; } else { tapTime = (((int) numTaps / 2) - 0.5 + delay) * -timeIncrement; } this->resize(numTaps); // Create the delayed sinc filter for (index = 0; index < numTaps; index++, tapTime += timeIncrement) { if (tapTime != 0.0) { (*this)[index] = (T) (sin(tapTime) / tapTime); } else { (*this)[index] = (T) 1.0; } } // Window the filter hamming(); } template <class T> void RealFirFilter<T>::hamming() { T phase = -M_PI; T phaseIncrement = 2 * M_PI / (this->size() - 1); T alpha = 0.54; T beta = 0.46; unsigned start, end; for (start=0, end=this->size()-1; start < end; start++, end--, phase += phaseIncrement) { double hammingVal = alpha + beta * cos(phase); (*this)[start] *= hammingVal; (*this)[end] *= hammingVal; } } template <class T> RealVector<T> & RealFirFilter<T>::corr(RealVector<T> & data) { this->reverse(); this->conv(data); this->reverse(); return data; } /** * \brief Correlation function. * * \param data Buffer to operate on. * \param filter The filter that will correlate with "data". * \return Reference to "data", which holds the result of the convolution. */ template <class T> inline RealVector<T> & corr(RealVector<T> & data, RealFirFilter<T> & filter) { return filter.corr(data); } template <class T> void RealFirFilter<T>::hamming(unsigned len) { generalizedHamming(len, 0.54, 0.46); } template <class T> void RealFirFilter<T>::hann(unsigned len) { generalizedHamming(len, 0.5, 0.5); } template <class T> void RealFirFilter<T>::generalizedHamming(unsigned len, double alpha, double beta) { this->resize(len); double N = len - 1; for (unsigned index=0; index<len; index++) { this->vec[index] = (T) (alpha - beta * cos(2 * M_PI * ((double) index) / N)); } } template <class T> void RealFirFilter<T>::blackman(unsigned len) { const double alpha[] = {0.42, 0.5, 0.08}; this->resize(len); double N = len - 1; for (unsigned index=0; index<len; index++) { this->vec[index] = (T) (alpha[0] - alpha[1] * cos(2 * M_PI * ((double) index) / N) + alpha[2] * cos(4 * M_PI * ((double) index) / N)); } } template <class T> void RealFirFilter<T>::blackmanHarris(unsigned len) { const double alpha[] = {0.35875, 0.48829, 0.14128, 0.01168}; this->resize(len); double N = len - 1; for (unsigned index=0; index<len; index++) { this->vec[index] = (T) (alpha[0] - alpha[1] * cos(2 * M_PI * ((double) index) / N) + alpha[2] * cos(4 * M_PI * ((double) index) / N) - alpha[3] * cos(6 * M_PI * ((double) index) / N)); } } }; #endif
{ "content_hash": "42da40fdf76be878502e338a5cb68366", "timestamp": "", "source": "github", "line_count": 1577, "max_line_length": 164, "avg_line_length": 41.01014584654407, "alnum_prop": 0.5672382601703957, "repo_name": "JimClay/NimbleDSP", "id": "0cab28e963c08e04633486fa3b8fb57006c36630", "size": "65733", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "src/RealFirFilter.h", "mode": "33188", "license": "mit", "language": [ { "name": "C++", "bytes": "553988" }, { "name": "CMake", "bytes": "811" } ], "symlink_target": "" }
/* ======================================================================== * B-JUI: bjui-datagrid.js v1.2 - beta * @author K'naan ([email protected]) * http://git.oschina.net/xknaan/B-JUI/blob/master/BJUI/js/bjui-datagrid.js * ======================================================================== * Copyright 2014 K'naan. * Licensed under Apache (http://www.apache.org/licenses/LICENSE-2.0) * ======================================================================== */ +function ($) { 'use strict'; // DATAGRID CLASS DEFINITION // ====================== var Datagrid = function(element, options) { this.$element = $(element) this.options = options this.tools = this.TOOLS() this.datanames = { tbody : 'bjui.datagrid.tbody.dom', td_html : 'bjui.datagrid.td.html', changeData : 'bjui.datagrid.tr.changeData' } this.classnames = { s_checkbox : 'datagrid-checkbox', s_linenumber : 'datagrid-linenumber', s_edit : 'datagrid-column-edit', s_lock : 'datagrid-lock', s_menu : 'datagrid-menu-box', s_filter : 'datagrid-filter-box', s_showhide : 'datagrid-showhide-box', th_cell : 'datagrid-cell', th_menu : 'datagrid-column-menu', btn_menu : 'datagrid-column-menu-btn', th_col : 'datagrid-col', th_field : 'datagrid-col-field', th_sort : 'datagrid-sortable', th_resize : 'datagrid-resize-head', th_resizemark : 'datagrid-column-resizemark', tr_edit : 'datagrid-edit-tr', tr_add : 'datagrid-add-tr', tr_selected : 'datagrid-selected-tr', td_edit : 'datagrid-edit-td', td_changed : 'datagrid-changed', td_linenumber : 'datagrid-linenumber-td', td_checkbox : 'datagrid-checkbox-td', li_asc : 'datagrid-li-asc', li_desc : 'datagrid-li-desc', li_filter : 'datagrid-li-filter', li_showhide : 'datagrid-li-showhide', li_lock : 'datagrid-li-lock', li_unlock : 'datagrid-li-unlock' } } Datagrid.DEFAULTS = { gridTitle : '', columns : null, // Thead column module data : null, // Data source dataUrl : null, // Request data source url, for processing (filtering / sorting / paging) results loadType : 'POST', // Ajax load request type dataType : 'json', // Data type of data source local : 'remote', // Optional 'local' | 'remote' fieldSortable : true, // Click the field to sort filterThead : true, // Filter in the thead sortAll : false, // Sort scope, false = this page, true = all filterAll : false, // Filter scope, false = this page, true = all filterMult : true, // Filter multiple fileds, false = single, true = multiple linenumberAll : false, // All data together numbers showLinenumber : true, // Display linenumber column, Optional 'true' | 'false' | 'lock', (Optional 'true, false' is a boolean) showCheckboxcol : false, // Display checkbox column, Optional 'true' | 'false' | 'lock', (Optional 'true, false' is a boolean) showEditbtnscol : false, // Display edit buttons column showTfoot : false, // Display the tfoot, Optional 'true' | 'false' | 'lock', (Optional 'true, false' is a boolean) showToolbar : false, // Display datagrid toolbar toolbarItem : '', // Displayed on the toolbar elements, Optional 'all, add, edit, cancel, save, del, import, export, |' toolbarCustom : '', // Html code || function || jQuery dom object, custom elements, displayed on the toolbar columnResize : true, // Allow adjust the column width columnMenu : true, // Display the menu button on the column columnShowhide : true, // On the menu display (show / hide columns) columnFilter : true, // On the menu display (filter form) columnLock : true, // On the menu display (lock / unlock columns) paging : true, // Display pagination component pagingAlign : 'center', // The pagination component alignment editUrl : null, // An action URL, for processing (update / save), return results (json) editCallback : null, // Callback for save editMode : 'inline', // Editing mode, Optional 'false' | 'inline' | 'dialog', (Optional 'false' is a boolean) editDialogOp : null, // For dialog edit, the dialog init options inlineEditMult : true, // Can inline edit multiple rows saveAll : true, // For inline edit, true = save current row, false = save all editing rows addLocation : 'first', // Add rows to datagrid location, Optional 'first' | 'last' | 'prev' | 'next' delUrl : null, // The delete URL, return delete tr results (json) delType : 'POST', // Delete URL of ajax request method delPK : null, // Ajax delete request to send only the primary key delConfirm : true, // Delete confirmation message, Optional 'true' | 'false' | 'message', (Optional 'true, false' is a boolean) delCallback : null, // Callback for delete jsonPrefix : '', // JSON object key prefix, for post data contextMenuH : true, // Right-click on the thead, display the context menu contextMenuB : false, // Right-click on the tbody tr, display the context menu hScrollbar : false, // Allowed horizontal scroll bar fullGrid : false, // If the table width below gridbox width, stretching table width importOption : null, // Import btn options exportOption : null, // Export btn options beforeEdit : null, // Function - before edit method, return true execute edit method beforeDelete : null, // Function - before delete method, return true execute delete method afterSave : null, // Function - after save method, arguments($trs, datas) afterDelete : null // Function - after delete method } Datagrid.renderItem = function(value, items) { if (!items || !items.length) return '' var label = '' $.each(items, function(i, n) { if (typeof n[value] != 'undefined') { label = n[value] return false } }) return label } Datagrid.prototype.TOOLS = function() { var that = this, options = that.options var tools = { getPageCount: function(pageSize, total) { return Math.ceil(total / pageSize) }, getPageInterval: function(count, pageCurrent, showPageNum) { var half = Math.ceil(showPageNum / 2), limit = count - showPageNum, start = pageCurrent > half ? Math.max(Math.min(pageCurrent - half, limit), 0) : 0, end = pageCurrent > half ? Math.min((pageCurrent + half), count) : Math.min(showPageNum, count) if (end - start == showPageNum) end = end + 1 if (end < showPageNum) end = end + 1 return {start:start + 1, end:end} }, getRight: function($obj) { var width = 0, index = $obj.data('index'), $firstTds = that.$tbody.find('> tr:first > td:lt('+ (index + 1) +')') if (!$firstTds || !$firstTds.length) $firstTds = that.$colgroupH.find('> col:lt('+ (index + 1) +')') $firstTds.each(function() { var $td = $(this), w = $td.is(':hidden') ? 0 : $td.outerWidth() width += w }) return width }, getRight4Lock: function(index) { var width = 0, $td = that.$lockTbody.find('> tr:first > td:eq('+ index +')'), $firstTds = $td && $td.prevAll().add($td) if (!$firstTds || !$firstTds.length) $firstTds = that.$lockColgroupH.filter(':lt('+ (index + 1) +')') $firstTds.each(function() { var $td = $(this), w = $td.is(':hidden') ? 0 : $td.outerWidth() width += w }) return width }, beforeEdit: function($trs, datas) { var beforeEdit = options.beforeEdit if (beforeEdit) { if (typeof beforeEdit == 'string') beforeEdit = beforeEdit.toFunc() if (typeof beforeEdit == 'function') { return beforeEdit.call(that, $trs, datas) } } return true }, afterSave: function($trs, data) { var afterSave = options.afterSave if (afterSave) { if (typeof afterSave == 'string') afterSave = afterSave.toFunc() if (typeof afterSave == 'function') { afterSave.call(that, $trs, data) } } }, afterDelete: function() { var afterDelete = options.afterDelete if (afterDelete) { if (typeof afterDelete == 'string') afterDelete = afterDelete.toFunc() if (typeof afterDelete == 'function') { afterDelete.call(that) } } }, // Correct colspan setColspan: function(column, colspanNum) { if (column.colspan) column.colspan = column.colspan + colspanNum - 1 column.index = column.index + colspanNum - 1 if (column.parent) this.setColspan(column.parent, colspanNum) }, // transform columns to array columns2Arr: function(columns, rowArr, index, parent) { var tools = this if (!rowArr) rowArr = [] if (!index) index = 0 if (!rowArr[index]) rowArr[index] = [] $.each(columns, function(i, n) { var len = rowArr[index].length, colspan if (parent) n.parent = parent if (n.columns) { colspan = n.columns.length if (index && n.parent) { tools.setColspan(n.parent, colspan) } n.index = that.columnModel.length + colspan - 1 n.colspan = colspan n.quicksort = false rowArr[index][len++] = n return tools.columns2Arr(n.columns, rowArr, index + 1, n) } else { n.rowspan = index n.index = that.columnModel.length n.menu = (typeof n.menu == 'undefined') ? true : n.menu n.lock = (typeof n.lock == 'undefined') ? true : n.lock n.hide = (typeof n.hide == 'undefined') ? false : n.hide n.edit = (typeof n.edit == 'undefined') ? true : n.edit n.add = (typeof n.add == 'undefined') ? true : n.add n.quicksort = (typeof n.quicksort == 'undefined') ? true : n.quicksort rowArr[index][len++] = n that.columnModel.push(n) } }) return rowArr }, // create trs by data source createTrsByData: function(data, refreshFlag) { var list if (!that.$tbody) that.$tbody = $('<tbody></tbody>') if (data) { if (data.list) list = data.list else list = data that.paging.total = list.length if (typeof data == 'object') { if (data[BJUI.pageInfo.total]) that.paging.total = parseInt(data[BJUI.pageInfo.total]) if (data[BJUI.pageInfo.pageSize]) { if (refreshFlag && that.paging.pageSize != data[BJUI.pageInfo.pageSize]) { that.$selectpage.trigger('bjui.datagrid.paging.pageSize', data[BJUI.pageInfo.pageSize]) } that.paging.pageSize = parseInt(data[BJUI.pageInfo.pageSize]) } } that.paging.pageCount = tools.getPageCount(that.paging.pageSize, that.paging.total) if (that.paging.pageCurrent > that.paging.pageCount) that.paging.pageCurrent = that.paging.pageCount this.initTbody(list, refreshFlag) } if (!that.init_tbody) that.$tbody.appendTo(that.$element) if (!that.init_thead) that.initThead() }, // initTbody initTbody: function(data, refreshFlag) { var tools = this, allData = that.allData, type = options.dataType || 'json', model = that.columnModel, hiddenFields = that.hiddenFields, regional = that.regional, newData = [], attach = that.attach, json var paging = that.paging, start = 0, end = paging.pageSize var doInit = function() { type = type.toLowerCase() if (data) allData = that.allData = data if (!allData.length) { end = 0 } else { if (options.local == 'local') { start = (paging.pageSize * (paging.pageCurrent - 1)) end = start + paging.pageSize if (paging.total != allData.length) paging.total = allData.length if (start > allData.length) start = paging.pageSize * (paging.pageCount - 1) } else { if (allData.length > paging.pageSize) end = paging.pageSize } } if (end > allData.length) end = allData.length // array to json if (type == 'array' && data && data.length && $.type(data[0]) == 'array') { var a1 = start, a2 = end, arrData = [], _index if (options.local == 'local') { a1 = 0 a2 = allData.length } for (var i = a1; i < a2; i++) { json = {} _index = 0 $.each(allData[i], function(k, v) { var obj, val = v if (model[_index] && model[_index].gridNumber) _index ++ if (model[_index] && model[_index].gridCheckbox) _index ++ if (typeof val == 'string') val = '"'+ val +'"' if (model[_index] && !model[_index].gridEdit) { obj = '{"'+ model[_index].name +'":'+ val +'}' $.extend(json, JSON.parse(obj)) } else { // init hidden fields if (model[_index] && model[_index].gridEdit) _index ++ if (_index >= model.length && hiddenFields) { if (hiddenFields[k - model.length]) { obj = '{"'+ hiddenFields[k - model.length] +'":'+ val +'}' $.extend(json, JSON.parse(obj)) } } } _index ++ }) arrData.push(json) } allData = that.allData = arrData } // create cuttent page data for (var i = start; i < end; i++) { json = $.extend({}, that.allData[i], attach) newData.push(json) } tools.createTrs(newData, refreshFlag) that.data = newData } if (refreshFlag && that.$boxM) { that.$boxM.show().trigger('bjui.ajaxEnd').trigger('bjui.ajaxStart', [50, doInit]) } else { doInit() } }, // create tbody - tr createTrs: function(datas, refreshFlag) { var tools = this, model = that.columnModel, paging = that.paging, editFrag = BJUI.doRegional(FRAG.gridEditBtn, that.regional), lockedCols = [] if (refreshFlag) { // remebered lock columns $.each(model, function(i, n) { if (n.locked) { that.colLock(n.th, false) n.lock_refresh = true } }) that.$tbody.empty() that.$lockTableH && that.$lockTableH.empty() that.$lockTableB && that.$lockTableB.empty() } $.each(datas, function(i, trData) { var $tr = $('<tr></tr>'), $td, linenumber = options.linenumberAll ? ((paging.pageCurrent - 1) * paging.pageSize + (i + 1)) : (i + 1) $.extend(trData, {gridNumber:linenumber, gridIndex:i}) $.each(model, function(j, n) { var name = n.name || 'datagrid-noname', label = trData[name], align = '', cls = '', _label if (typeof label == 'undefined') label = '' _label = label if (n.align) align = ' align="'+ n.align +'"' if (n.gridCheckbox) label = '<div><input type="checkbox" data-toggle="icheck" name="datagrid.checkbox" value="true"></div>' if (n.gridEdit) { label = editFrag cls = ' class="'+ that.classnames.s_edit +'"' } /* for tfoot */ if (n.calc) { if (!n.calc_count) n.calc_count = datas.length var number = label ? (String(label).isNumber() ? label * 1 : 0) : 0 if (n.calc == 'sum' || n.calc == 'avg') n.calc_sum = (n.calc_sum || 0) + number else if (n.calc == 'max') n.calc_max = n.calc_max ? (n.calc_max < number ? number : n.calc_max) : number else if (n.calc == 'min') n.calc_min = n.calc_min ? (n.calc_min > number ? number : n.calc_min) : number } /* append */ $td = $('<td'+ align + cls +'><div>'+ label +'</div></td>') $td.data('val', label).appendTo($tr) if (n.gridNumber) $td.addClass(that.classnames.td_linenumber) if (n.gridCheckbox) $td.addClass(that.classnames.td_checkbox) if (refreshFlag && n.hidden) $td.css('display', 'none') /* render */ if (n.items && !n.render) n.render = $.datagrid.renderItem if (n.render && typeof n.render == 'string') n.render = n.render.toFunc() if (n.render && typeof n.render == 'function') { var render_label = '', render_items = false if (n.items) { if (typeof n.items == 'string') { if (n.render.trim().startsWith('[')) n.render = n.render.toObj() else n.render = n.render.toFunc() } if (!n.renderTds) n.renderTds = [] var delayRender = function($td, label) { $.when(n.items.call(that)).then(function(item) { n.items = item render_label = n.render.call(that, label, item) $td.html(render_label) $.each(n.renderTds, function(ii, nn) { render_label = n.render.call(that, nn.text(), item) nn.html(render_label) if (ii == n.renderTds.length - 1) n.renderTds = null }) that.delayRender -- }) } if (typeof n.items == 'function') { if (i == 0) { if (!that.delayRender) that.delayRender = 0 that.delayRender ++ delayRender($td, _label) } else { n.renderTds.push($td) } } else { render_label = n.render.call(that, _label, n.items) $td.html(render_label) } } else { render_label = n.render.call(that, _label) $td.html(render_label) } } }) $tr.appendTo(that.$tbody) if (refreshFlag) $tr.initui() }) if (refreshFlag) { that.initEvents() if (options.editMode) that.edit() that.$paging && that.$paging.trigger('bjui.datagrid.paging.jump') // locked $.each(model, function(i, n) { if (n.lock_refresh) { that.colLock(n.th, true) delete n.lock_refresh } }) } if (that.$boxM) { that.$boxM.trigger('bjui.ajaxStop').hide() } }, // ajax load data by url loadData: function(data, refreshFlag) { var tools = this, url = options.dataUrl, dataType = options.dataType || 'json', model = that.columnModel if (that.$tbody) { that.$boxM.show().trigger('bjui.ajaxStart', [50]) } dataType = dataType.toLowerCase() if (dataType == 'array') dataType = 'text' $.ajax({url:url, data:data || {}, type:options.loadType, cache:options.cache || false, dataType:dataType, success:function(response) { if (dataType == 'xml') { var xmlData = [], obj $(response).find('row').each(function() { obj = {} $(this).find('cell').each(function(i) { var $cell = $(this), label = $cell.text(), name = $cell.attr('name') obj[name] = label }) xmlData.push(obj) }) if (xmlData) tools.createTrsByData(xmlData, refreshFlag) } else if (dataType == 'json') { tools.createTrsByData(response, refreshFlag) } else { tools.createTrsByData(response.toObj(), refreshFlag) } } }) }, // append columns appendColumns: function() { that.linenumberColumn = {name:'gridNumber', gridNumber:true, width:30, minWidth:30, label:'No.', align:'center', menu:false, edit:false, quicksort:false} that.checkboxColumn = {name:'gridCheckbox', gridCheckbox:true, width:40, minWidth:40, label:'Checkbox', align:'center', menu:false, edit:false, quicksort:false} that.editBtnsColumn = {name:'gridEdit', gridEdit:true, width:110, minWidth:110, label:'Edit', align:'center', menu:false, edit:false, hide:false, quicksort:false} }, // create Thead createThead: function() { var tools = this, columns = options.columns, rowArr = [], rows = [], label, align, width, colspan, rowspan, resize, menu tools.appendColumns() if (options.showCheckboxcol) { columns.unshift(that.checkboxColumn) if (options.showCheckboxcol == 'lock') that.checkboxColumn.initLock = true } if (options.showLinenumber) { columns.unshift(that.linenumberColumn) if (options.showLinenumber == 'lock') that.linenumberColumn.initLock = true } if (options.showEditbtnscol) columns.push(that.editBtnsColumn) rowArr = tools.columns2Arr(columns, rowArr) // the last model can't lock that.columnModel[that.columnModel.length - (options.showEditbtnscol ? 2 : 1)].lock = false // hidden fields if (options.hiddenFields) that.hiddenFields = options.hiddenFields // create thead that.$thead = $('<thead></thead>') $.each(rowArr, function(i, arr) { var $tr = $('<tr style="height:25px;"></tr>'), $num = '<th class="datagrid-number"></th>', $th $.each(arr, function(k, n) { label = n.label || n.name align = n.align ? (' align="'+ n.align +'"') : '' width = n.width ? (' width="'+ n.width +'"') : '' colspan = n.colspan ? ' colspan="'+ n.colspan +'"' : '' rowspan = (rowArr.length - n.rowspan > 1) ? ' rowspan="'+ (rowArr.length - n.rowspan) +'"' : '' resize = '<div class="'+ that.classnames.th_resizemark +'"></div>' menu = '' if (n.gridCheckbox) label = '<input type="checkbox" data-toggle="icheck">' if (n.colspan) align = ' align="center"' if (n.thalign) align = ' align="'+ n.thalign +'"' if (n.menu && options.columnMenu) menu = ' class="'+ that.classnames.th_menu +'"' $th = $('<th'+ menu + width + align + colspan + rowspan +'><div><div class="datagrid-space"></div><div class="datagrid-label">'+ label +'</div><div class="'+ that.classnames.th_cell +'">'+ resize +'</div></div></th>') $th.data('index', n.index).appendTo($tr) $th.find('> div').css('height', (rowArr.length - n.rowspan > 1) ? (24 * (rowArr.length - n.rowspan)) +'px' : '24px') if (!rowspan) $th.addClass('single-row') if (n.gridNumber) $th.addClass(that.classnames.td_linenumber) if (options.fieldSortable && n.quicksort) $th.addClass('datagrid-quicksort-th') n.th = $th }) $tr.appendTo(that.$thead) }) that.$thead.appendTo(that.$element) }, // create Tbody createTbody: function() { var tools = this, data = options.data, model = that.columnModel, cols = [] if (data) { if (typeof data == 'string') { if (data.trim().startsWith('[') || data.trim().startsWith('{')) { data = data.toObj() } else { data = data.toFunc() } } if (typeof data == 'function') { data = data.call() } tools.createTrsByData(data) } else if (options.dataUrl) { tools.loadData() } }, // setBoxb - height setBoxbH: function(height) { var boxH = height || options.height, topM = 0, h if (boxH < 100) return if (isNaN(boxH)) boxH = that.$grid.height() if (that.$boxT) { h = that.$boxT.outerHeight() boxH -= h topM += h } if (that.$toolbar) { h = that.$toolbar.outerHeight() boxH -= h topM += h } if (that.$box_paging) boxH -= that.$box_paging.outerHeight() if (that.$boxF) boxH -= that.$boxF.outerHeight() topM += that.$tableH.outerHeight() boxH -= that.$boxH.outerHeight() if (boxH < 0) boxH = 0 that.$boxB.height(boxH) that.$boxM.height(boxH).css({top:topM}) }, // fixed h fixedH: function(height) { this.setBoxbH(height) }, // column menu - toggle show submenu showSubMenu: function($li, $menu, $submenu) { var left, width = $menu.outerWidth(), submenu_width = $submenu.data('width') || $submenu.outerWidth(), animate_op, boxWidth = that.$boxH.width() var hidesubmenu = function($li, $menu, $submenu) { left = $menu.offset().left - that.$grid.offset().left - 1 animate_op = {left:'50%'} $li.removeClass('active') if ($menu.hasClass('position-right') || (boxWidth - left < width + submenu_width)) { $submenu.css({left:'auto', right:'100%'}) animate_op = {right:'50%'} } else { $submenu.css({left:'100%', right:'auto'}) } animate_op.opacity = 0.2 $submenu.stop().animate(animate_op, 'fast', function() { $(this).hide() }) } $li.hover(function() { $submenu.appendTo($li) if ($li.hasClass(that.classnames.li_filter) && $submenu.is(':visible')) { return false } else { var $filterli = $li.siblings('.'+ that.classnames.li_filter) if ($filterli.length && $filterli.hasClass('active')) { hidesubmenu($filterli, $menu, $filterli.find('> .'+ that.classnames.s_filter)) } } left = $menu.offset().left - that.$grid.offset().left - 1 animate_op = {left:'100%'} if ($menu.hasClass('position-right') || (boxWidth - left < width + submenu_width)) { $submenu.css({left:'auto', right:'50%'}) animate_op = {right:'100%'} } else { $submenu.css({left:'50%', right:'auto'}) } animate_op.opacity = 1 $li.addClass('active') $submenu.show().stop().animate(animate_op, 'fast') }, function() { if ($li.hasClass(that.classnames.li_filter)) { return false } hidesubmenu($li, $menu, $submenu) }) $li.on('bjui.datagrid.th.submenu.hide', function(e, menu, submenu) { hidesubmenu($(this), menu, submenu) }) }, // column menu - lock/unlock locking: function($th) { var index= $th.data('index'), columnModel = that.columnModel[index], lockFlag = columnModel.lock, locked = columnModel.locked, $menu = that.$menu, $ul = $menu.find('> ul'), $lockli = $ul.find('> li.'+ that.classnames.li_lock), $unlockli = $lockli.next() if (locked) { $lockli.addClass('disable') $unlockli.removeClass('disable') } else { $unlockli.addClass('disable') $lockli.removeClass('disable') } if (lockFlag) { $lockli.show().off('click').on('click', function() { if ($lockli.hasClass('disable')) return $menu.hide().data('bjui.datagrid.menu.btn').removeClass('active') that.colLock($th, true) }) $unlockli.show().off('click').on('click', function() { if ($unlockli.hasClass('disable')) return $menu.hide().data('bjui.datagrid.menu.btn').removeClass('active') that.colLock($th, false) }) } else { $lockli.hide().off('click') $unlockli.hide().off('click') } }, // create show/hide column panel createShowhide: function() { var $showhide if (!that.$showhide) { that.col_showhide_count = that.columnModel.length $showhide = $('<ul class="'+ that.classnames.s_showhide +'" role="menu"></ul>') $.each(that.columnModel, function(i, n) { if (n.gridNumber || n.gridCheckbox || n.gridEdit) that.col_showhide_count -- var $col = $(FRAG.gridShowhide.replaceAll('#index#', n.index).replaceAll('#label#', (n.label || ''))).toggleClass('nodisable', !!(n.gridNumber || n.gridCheckbox || n.gridEdit)) var colClick = function(n) { $col.click(function() { if ($(this).hasClass('disable')) return false var $this = $(this), check = !$this.find('i').hasClass('fa-check-square-o'), index = n.index $this.toggleClass('datagrid-col-check') .find('i').attr('class', 'fa fa'+ (check ? '-check' : '') +'-square-o') that.showhideColumn(n.th, check) if (!(n.gridNumber || n.gridCheckbox || n.gridEdit)) { that.col_showhide_count = check ? that.col_showhide_count + 1 : that.col_showhide_count - 1 } if (that.col_showhide_count == 1) $showhide.find('> li.datagrid-col-check').addClass('disable') else $showhide.find('> li.disable').removeClass('disable') $showhide.find('> li.nodisable').removeClass('disable') }) } colClick(n) $col.appendTo($showhide) if (n.hide) $col.trigger('click') }) $showhide.appendTo(that.$grid) $showhide.data('width', $showhide.outerWidth()) that.$showhide = $showhide } }, // column - display/hide showhide: function(model, showFlag) { var index = model.index, $th = model.th, $trs = that.$tbody.find('> tr'), display = showFlag ? '' : 'none' var setColspan = function(column) { var _colspan = column.colspan if (showFlag) _colspan ++ else _colspan -- if (!_colspan) column.th.css('display', 'none') else column.th.css('display', '') column.th.attr('colspan', _colspan) column.colspan = _colspan if (column.parent) setColspan(column.parent) } if (typeof model.hidden == 'undefined') model.hidden = false if (model.hidden == !showFlag) return model.hidden = !showFlag $th.css('display', display) $trs.find('> td:eq('+ index +')').css('display', display) that.$colgroupH.find('> col').eq(index).css('display', display) that.$colgroupB.find('> col').eq(index).css('display', display) that.$thead.find('> tr.datagrid-filter > th:eq('+ index +')').css('display', display) if (that.$boxF) { that.$tableF.find('> thead > tr > th:eq('+ index +')').css('display', display) that.$colgroupF.find('> col').eq(index).css('display', display) } if (model.calc) { that.$tfoot && that.$tfoot.trigger('bjui.datagrid.tfoot.resizeH') } if (model.parent) setColspan(model.parent) }, // jump to page jumpPage: function(pageCurrent, pageSize) { var allData = that.allData, filterDatas if (pageCurrent) that.paging.pageCurrent = pageCurrent if (pageSize) { that.paging.pageSize = pageSize that.paging.pageCount = this.getPageCount(pageSize, that.paging.total) if (that.paging.pageCurrent > that.paging.pageCount) that.paging.pageCurrent = that.paging.pageCount } if (options.local == 'remote') { filterDatas = this.getRemoteFilterData(true) this.loadData(filterDatas, true) } else { this.initTbody(allData, true) } }, // column - quicksort quickSort: function(model) { if (that.isDom) { if (options.local == 'local') return options.sortAll = true } if (that.$tbody.find('> tr.'+ that.classnames.tr_edit).length) { that.$tbody.alertmsg('info', BJUI.getRegional('datagrid.editMsg')) return } var $th = model.th, data = that.data, allData = that.allData, postData, direction, name = model.name, type = model.type, $ths = that.$thead.find('> tr > th.datagrid-quicksort-th') if (!name) name = 'datagrid-noname' var sortData = function(data) { data.sort(function(a, b) { var typeA = (typeof a[name]), typeB = (typeof b[name]) if (type == 'boolean' || type == 'number' || (typeA = typeB == 'number') || (typeA = typeB == 'boolean')) { return model.sortAsc ? (a[name] - b[name]) : (b[name] - a[name]) } else { return model.sortAsc ? String(a[name]).localeCompare(b[name]) : String(b[name]).localeCompare(a[name]) } }) } $ths.find('> div > .datagrid-label > i').remove() if (model.sortAsc) { direction = 'desc' model.sortAsc = false } else { direction = 'asc' model.sortAsc = true } $th.find('> div > .datagrid-label').prepend('<i class="fa fa-long-arrow-'+ (model.sortAsc ? 'up' : 'down') +'"></i>') //that.$menu && that.$menu.trigger('bjui.datagrid.th.sort', [model.sortAsc]) if (options.sortAll) { if (options.local == 'remote') { postData = {} postData[BJUI.pageInfo.orderField] = name postData[BJUI.pageInfo.orderDirection] = direction postData[BJUI.pageInfo.pageSize] = that.paging.pageSize postData[BJUI.pageInfo.pageCurrent] = that.paging.pageCurrent this.loadData(postData, true) } else { sortData(allData) this.initTbody(allData, true) } } else { sortData(data) this.createTrs(data, true) } }, quickFilter: function(model, filterDatas) { if (that.isDom) { if (options.local != 'remote') { BJUI.debug('Datagrid Plugin: Please change the local option is remote!') return } if (!options.dataUrl) { BJUI.debug('Datagrid Plugin: Not Set the dataUrl option!') return } } var tools = this, $th = model.th, data = that.data, allData = that.allData, name = model.name, postData, fDatas var switchOperator = function(operator, val1, val2) { var compare = false switch (operator) { case '=': compare = String(val1) == String(val2) break case '!=': compare = String(val1) != String(val2) break case '>': compare = parseFloat(val2) > parseFloat(val1) break case '<': compare = parseFloat(val2) < parseFloat(val1) break case 'like': if (model.type == 'select') { compare = String(val1) == String(val2) } else { compare = (String(val2).indexOf(String(val1)) >= 0) } break default: break } return compare } var filterData = function(data, filterDatas) { var grepFun = function(n) { var count = 0 $.each(filterDatas, function(name, v) { var op = v.datas count ++ if (!op) { count -- v.model.isFiltered = false v.model.th.trigger('bjui.datagrid.th.filter', [false]) if (v.model.quickfilter) v.model.quickfilter.trigger('bjui.datagrid.thead.clearfilter') return true } v.model.isFiltered = true v.model.th.trigger('bjui.datagrid.th.filter', [true]) if (op.andor) { if (op.andor == 'and') { if (switchOperator(op.operatorA, op.valA, n[name]) && switchOperator(op.operatorB, op.valB, n[name])) { count -- } } else if (op.andor == 'or') { if (switchOperator(op.operatorA, op.valA, n[name]) || switchOperator(op.operatorB, op.valB, n[name])) { count -- } } } else { if (op.operatorB) { if (switchOperator(op.operatorB, op.valB, n[name])) { count -- } } else { if (switchOperator(op.operatorA, op.valA, n[name])) { count -- } } } }) return !count ? true : false } return $.grep(data, function(n, i) { return grepFun(n) }) } if (!that.filterDatas) that.filterDatas = {} if (options.filterMult) { that.filterDatas[name] = {datas:filterDatas, model:model} } else { that.filterDatas = {} that.filterDatas[name] = {datas:filterDatas, model:model} } if (options.local != 'remote' && allData) { if (!that.oldAllData) that.oldAllData = allData.concat() else allData = that.oldAllData.concat() } if (options.filterAll) { if (options.local == 'remote') { tools.loadData(tools.getRemoteFilterData(), true) } else { fDatas = filterData(allData, that.filterDatas) that.paging.pageCurrent = 1 that.paging.pageCount = this.getPageCount(that.paging.pageSize, fDatas.length) this.initTbody(fDatas, true) } } else { if (that.isDom) { tools.loadData(tools.getRemoteFilterData(), true) } else { fDatas = filterData(data, that.filterDatas) this.createTrs(fDatas, true) } } }, getRemoteFilterData: function(isPaging) { var filterDatas = [] if (that.filterDatas && !$.isEmptyObject(that.filterDatas)) { $.each(that.filterDatas, function(name, v) { if (!v.datas) { v.model.isFiltered = false v.model.th.trigger('bjui.datagrid.th.filter', [false]) if (v.model.quickfilter) v.model.quickfilter.trigger('bjui.datagrid.thead.clearfilter') return true } v.model.isFiltered = true v.model.th.trigger('bjui.datagrid.th.filter', [true]) if (options.jsonPrefix) name = options.jsonPrefix +'.'+ name if (v.datas.andor) filterDatas.push({name:'andor', value:v.datas.andor}) if (v.datas.operatorA) { filterDatas.push({name:name, value:v.datas.valA}) filterDatas.push({name:name +'.operator', value:v.datas.operatorA}) } if (v.datas.operatorB) { filterDatas.push({name:name, value:v.datas.valB}) filterDatas.push({name:name +'.operator', value:v.datas.operatorB}) } }) if (!isPaging) that.paging.pageCurrent = 1 } // paging filterDatas.push({name:BJUI.pageInfo.pageSize, value:that.paging.pageSize}) filterDatas.push({name:BJUI.pageInfo.pageCurrent, value:that.paging.pageCurrent}) return filterDatas }, // set data for Dom setDomData: function(tr) { var columnModel = that.columnModel, data = {}, hideDatas = tr.attr('data-hidden-datas'), attach = that.attach tr.find('> td').each(function(i) { var $td = $(this), model = columnModel[i], val = $td.attr('data-val') || $td.text() if (!model.name) data['datagrid-noname'+ i] = val else data[model.name] = val }) if (hideDatas) hideDatas = hideDatas.toObj() $.extend(data, attach, {gridNumber:(tr.index() + 1)}, hideDatas) tr.data('initData', data) return data }, // init inputs array for edit initEditInputs: function() { var columnModel = that.columnModel that.inputs = [] $.each(columnModel, function(i, op) { var name = op.name, rule = '', pattern = '', selectoptions = [], attrs = '' if (!op) return if (op.attrs && typeof op.attrs == 'object') { $.each(op.attrs, function(i, n) { attrs += ' '+ i +'='+ n }) } if (op == that.linenumberColumn || op == that.checkboxColumn || op == that.editBtnsColumn) { that.inputs.push('') } else if (name) { if (op.rule) rule = ' data-rule="'+ op.label +':'+ op.rule +'"' else if (op.type == 'date') rule = ' data-rule="pattern('+ (op.pattern || 'yyyy-MM-dd') +')"'; if (op.type) { switch (op.type) { case 'date': if (!op.pattern) op.pattern = 'yyyy-MM-dd' pattern = ' data-pattern="'+ op.pattern +'"' that.inputs.push('<input type="text" name="'+ name +'" data-toggle="datepicker"'+ pattern + rule + attrs +'>') break case 'select': if (!op.items) return $.each(op.items, function(i, n) { $.each(n, function(key, value) { selectoptions.push('<option value="'+ key +'">'+ value +'</option>') }) }) that.inputs.push('<select name="'+ name +'" data-toggle="selectpicker"'+ rule + attrs +' data-width="100%">'+ selectoptions.join('') +'</select>') break case 'boolean': that.inputs.push('<input type="checkbox" name="'+ name +'" data-toggle="icheck"'+ rule + attrs +' value="true">') break case 'lookup': that.inputs.push('<input type="text" name="'+ name +'" data-toggle="lookup" data-custom-event="true"'+ rule + attrs +'>') break case 'spinner': that.inputs.push('<input type="text" name="'+ name +'" data-toggle="spinner"'+ rule + attrs +'>') break case 'textarea': that.inputs.push('<textarea data-toggle="autoheight" rows="1"'+ rule + attrs +'></textarea>') break default: that.inputs.push('<input type="text" name="'+ name +'"'+ rule + attrs +'>') break } } else { that.inputs.push('<input type="text" name="'+ name +'"'+ rule + attrs +'>') } } else { that.inputs.push('') } }) return that.inputs }, contextmenuH: function() { var tools = this that.$tableH.on('contextmenu', function(e) { if (!that.$showhide) tools.createShowhide() var posX = e.pageX var posY = e.pageY if ($(window).width() < posX + that.$showhide.width()) posX -= that.$showhide.width() if ($(window).height() < posY + that.$showhide.height()) posY -= that.$showhide.height() if (that.$menu) { that.$grid.trigger('click.bjui.datagrid.filter') } that.$showhide .appendTo('body') .css({left:posX, top:posY, opacity:1, 'z-index':9999}).show() $(document).on('click', function(e) { var $showhide = $(e.target).closest('.'+ that.classnames.s_showhide) if (!$showhide.length) that.$showhide.css({left:'50%', top:0, opacity:0.2, 'z-index':''}).hide().appendTo(that.$grid) }) e.preventDefault() e.stopPropagation() }) }, contextmenuB: function($tr, isLock) { $tr.contextmenu('show', { exclude : 'input, .bootstrap-select', items:[ { icon : 'refresh', title : BJUI.getRegional('datagrid.refresh'), func : function(parent, menu) { that.refresh() } }, { title : 'diver' }, { icon : 'plus', title : BJUI.getRegional('datagrid.add'), func : function(parent, menu) { that.add() } }, { icon : 'edit', title : BJUI.getRegional('datagrid.edit'), func : function(parent, menu) { var $tr = parent if (isLock) $tr = that.$tbody.find('> tr:eq('+ $tr.index() +')') that.doEditRow($tr) } }, { icon : 'undo', title : BJUI.getRegional('datagrid.cancel'), func : function(parent, menu) { var $tr = parent if (isLock) $tr = that.$tbody.find('> tr:eq('+ $tr.index() +')') if (!$tr.hasClass(that.classnames.tr_edit)) { $tr = that.$tbody.find('> tr.'+ that.classnames.tr_edit) } that.doCancelEditRow($tr) } }, { icon : 'remove', title : BJUI.getRegional('datagrid.del'), func : function(parent, menu) { var $tr = parent if (isLock) $tr = that.$tbody.find('> tr:eq('+ $tr.index() +')') that.delRows($tr) } } ] } ) } } return tools } Datagrid.prototype.createTable = function() { var that = this, options = that.options, tools = that.tools if (options.columns) tools.createThead() if (options.data || options.dataUrl) tools.createTbody() } // DOM to datagrid - setColumnModel Datagrid.prototype.setColumnModel = function() { var that = this, options = that.options, $trs = that.$thead.find('> tr'), rows = [], ths = [], trLen = $trs.length if (!that.isDom) { that.tools.appendColumns() var $th, _rowspan = trLen > 1 ? ' rowspan="'+ trLen +'"' : '' if (options.showCheckboxcol) { that.columnModel.push(that.checkboxColumn) if (options.showCheckboxcol == 'lock') that.checkboxColumn.initLock = true $th = $('<th'+ _rowspan +'><input type="checkbox" data-toggle="icheck"></th>') $th.prependTo($trs.first()) if (_rowspan) $th.data('datagrid.column', that.checkboxColumn) } if (options.showLinenumber) { that.columnModel.unshift(that.linenumberColumn) if (options.showLinenumber == 'lock') that.linenumberColumn.initLock = true $th = $('<th class="datagrid-linenumber-td"'+ _rowspan +'>No.</th>') $th.prependTo($trs.first()) if (_rowspan) $th.data('datagrid.column', that.linenumberColumn) } if (options.showEditbtnscol) { that.columnModel[$th.index()] = that.editBtnsColumn $th = $('<th'+ _rowspan +'>Edit</th>') $th.appendTo($trs.first()) if (_rowspan) $th.data('datagrid.column', that.editBtnsColumn) } } if ($trs.length && trLen == 1) { $trs.height(25) $trs.find('> th').each(function(i) { var $th = $(this).addClass('single-row'), op = $th.data('options'), oW = $th.attr('width') || $th.outerWidth(), label = $th.html() if (that.columnModel.length && that.columnModel[i]) { op = that.columnModel[i] } else { if (op && typeof op == 'string') op = op.toObj() if (typeof op != 'object') op = {} op.index = i op.label = label op.width = (typeof op.width == 'undefined') ? oW : op.width op.menu = (typeof op.menu == 'undefined') ? true : op.menu op.lock = (typeof op.lock == 'undefined') ? true : op.lock op.hide = (typeof op.hide == 'undefined') ? false : op.hide op.edit = (typeof op.edit == 'undefined') ? true : op.edit op.add = (typeof op.add == 'undefined') ? true : op.add op.quicksort = (typeof op.quicksort == 'undefined') ? true : op.quicksort that.columnModel[i] = op } op.th = $th $th.html('<div><div class="datagrid-space"></div><div class="datagrid-label">'+ label +'</div><div class="'+ that.classnames.th_cell +'"><div class="'+ that.classnames.th_resizemark +'"></div></div></div>') if (op.menu && options.columnMenu) $th.addClass(that.classnames.th_menu) if (options.fieldSortable && op.quicksort) $th.addClass('datagrid-quicksort-th') if (op.align) $th.attr('align', op.align) $th.data('index', i).find('> div').css('height', '24px') }) } else { // multi headers $trs.each(function(len) { var next_rows = [], next_ths = [], index = -1, next_index = 0 if (rows.length) { next_rows = rows.concat() next_ths = ths.concat() } rows = [] ths = [] $(this).height(25).find('> th').each(function(i) { var $th = $(this), op = $th.data('options') || $th.data('datagrid.column') || {}, colspan = parseInt($th.attr('colspan') || 0), rowspan = parseInt($th.attr('rowspan') || 0), oW = $th.attr('width') || $th.outerWidth(), label = $th.html() if (op && typeof op == 'string') op = op.toObj() if (typeof op != 'object') op = {} if ( !-[1,] && colspan == 1) colspan = 0 op.label = label op.th = $th if (op.gridCheckbox) op.label = 'Checkbox' index++ if (colspan) { op.colspan = colspan for (var start_index = (next_rows.length ? next_rows[index] : index), k = start_index; k < (start_index + colspan); k++) { rows[next_index++] = k ths[next_index - 1] = op } index += (colspan - 1) $th.data('index', index) if (next_rows.length) { op.parent = next_ths[index] } } if (!rowspan || rowspan == 1) $th.addClass('single-row') if (!colspan) { op.width = (typeof op.width == 'undefined') ? oW : op.width op.menu = (typeof op.menu == 'undefined') ? true : op.menu op.lock = (typeof op.lock == 'undefined') ? true : op.lock op.hide = (typeof op.hide == 'undefined') ? false : op.hide op.edit = (typeof op.edit == 'undefined') ? true : op.edit op.add = (typeof op.add == 'undefined') ? true : op.add op.quicksort = (typeof op.quicksort == 'undefined') ? true : op.quicksort $th.html('<div style="height:'+ (rowspan ? rowspan * 24 : 24) +'px;"><div class="datagrid-space"></div><div class="datagrid-label">'+ label +'</div><div class="'+ that.classnames.th_cell +'"><div class="'+ that.classnames.th_resizemark +'"></div></div></div>') if (op.menu && options.columnMenu) $th.addClass(that.classnames.th_menu) if (options.fieldSortable && op.quicksort) $th.addClass('datagrid-quicksort-th') if (op.align) $th.attr('align', op.align) if (!next_rows.length) { op.index = index that.columnModel[index] = op } else { op.index = next_rows[index] op.parent = next_ths[index] that.columnModel[next_rows[index]] = op } $th.data('index', op.index) } else { $th.html('<div style="height:'+ (rowspan ? rowspan * 24 : 24) +'px;"><div class="datagrid-space"></div><div class="datagrid-label">'+ label +'</div><div class="'+ that.classnames.th_cell +'"><div class="'+ that.classnames.th_resizemark +'"></div></div></div>') } }) }) } } Datagrid.prototype.init = function() { if (!this.$element.isTag('table')) return if (this.$element.data('bjui.datagrid.init')) return var that = this, options, tools = that.tools, $parent = that.$element.parent(), boxWidth if (that.options.options) { if (typeof that.options.options == 'string') that.options.options = that.options.options.toObj() $.extend(that.options, typeof that.options.options == 'object' && that.options.options) } that.parentH = $parent.height() options = that.options that.$element.data('bjui.datagrid.init', true) if (!options.width) boxWidth = $parent.width() if (String(options.width).endsWith('%')) boxWidth = Math.round($parent.width() * parseInt(String(options.width).replace('%', '')) / 100) options.height = options.height || 300 that.isDom = false that.columnModel = [] that.inputs = [] that.$grid = $('<div class="bjui-datagrid"></div>').width(options.width).height(options.height) that.$boxH = $('<div class="datagrid-box-h"></div>') that.$boxB = $('<div class="datagrid-box-b"></div>') that.$boxM = $('<div class="datagrid-box-m"></div>').appendTo(that.$grid) that.regional = BJUI.regional.datagrid that.$element.before(that.$grid) if (typeof options.paging == 'string') options.paging = options.paging.toObj() that.paging = $.extend({}, {pageSize:30, selectPageSize:'30,60,90', pageCurrent:1, total:0, showPagenum:5}, (typeof options.paging == 'object') && options.paging) that.attach = {gridNumber:0, gridCheckbox:'#checkbox#', gridEdit:'#edit#'} that.$thead = that.$element.find('> thead') that.$tbody = that.$element.find('> tbody') if (that.$tbody && that.$tbody.find('> tr').length) that.isDom = true if (options.columns) { if (typeof options.columns == 'string') { if (options.columns.trim().startsWith('[')) { options.columns = options.columns.toObj() } else { options.columns = options.columns.toFunc() } } if (typeof options.columns == 'function') { options.columns = options.columns.call() } that.$thead = null tools.createThead() } else { if (that.$thead && that.$thead.length && that.$thead.find('> tr').length) { that.setColumnModel() } } that.initTop() that.$grid.data('bjui.datagrid.table', that.$element.clone()) if (that.isDom) { tools.appendColumns() that.$tbody.find('> tr > td').each(function() { var $td = $(this), html = $td.html() $td.html('<div>'+ html +'</div>') }) if (!that.paging.total) { that.paging.total = that.$tbody.find('> tr').length that.paging.pageCount = 1 } else { that.paging.pageCount = tools.getPageCount(that.paging.pageSize, that.paging.total) } that.paging.pageCurrent = 1 that.initThead() } else { that.$tbody = null if (options.data || options.dataUrl) tools.createTbody() } } Datagrid.prototype.refresh = function() { var that = this, options = that.options, tools = that.tools, isDom = that.isDom, pageInfo = BJUI.pageInfo, paging = that.paging, postData = {} if (!options.dataUrl) { if (options.data && options.data.length) { tools.initTbody(that.allData, true) return } BJUI.debug('Datagrid Plugin: Not Set the dataUrl option!') return } postData[pageInfo.pageSize] = paging.pageSize postData[pageInfo.pageCurrent] = paging.pageCurrent tools.loadData(postData, true) // clear fiter that.filterDatas = null $.each(that.columnModel, function(i, n) { n.th.trigger('bjui.datagrid.th.filter', [false]) n.isFiltered = false if (n.quickfilter) n.quickfilter.trigger('bjui.datagrid.thead.clearfilter') }) // clear sort that.$thead.find('> tr > th.datagrid-quicksort-th').find('> div > .datagrid-label > i').remove() } Datagrid.prototype.destroy = function() { var that = this, $element = that.$grid.data('bjui.datagrid.table') if ($element) { that.$element.html($element.html()).insertBefore(that.$grid) that.$grid.remove() } } Datagrid.prototype.initTop = function() { var that = this, options = that.options, regional = that.regional, hastoolbaritem = false, $group, groupHtml = '<div class="btn-group" role="group"></div>', btnHtml = '<button type="button" class="btn" data-icon=""></button>' if (options.gridTitle) { that.$boxT = $('<div class="datagrid-title">'+ options.gridTitle +'</div>') that.$boxT.appendTo(that.$grid) } if (options.showToolbar) { if (options.toolbarItem || options.toolbarCustom) { that.$toolbar = $('<div class="datagrid-toolbar"></div') if (options.toolbarItem) { hastoolbaritem = true if (options.toolbarItem.indexOf('all') >= 0) options.toolbarItem = 'add, edit, cancel, save, |, del, |, refresh, |, import, export' $.each(options.toolbarItem.split(','), function(i, n) { n = n.trim().toLocaleLowerCase() if (!$group || n == '|') { $group = $(groupHtml).appendTo(that.$toolbar) if (n == '|') return true } if (n == 'add') { that.$toolbar_add = $(btnHtml).attr('data-icon', 'plus').addClass('btn-blue').text(BJUI.getRegional('datagrid.add')) .appendTo($group) .on('click', function(e) { that.add() }) } else if (n == 'edit') { that.$toolbar_edit = $(btnHtml).attr('data-icon', 'edit').addClass('btn-green').text(BJUI.getRegional('datagrid.edit')) .appendTo($group) .on('click', function(e) { var $selectTrs = that.$tbody.find('> tr.'+ that.classnames.tr_selected) if (!$selectTrs.length) { $(this).alertmsg('info', BJUI.getRegional('datagrid.selectMsg')) } else { if (options.inlineEditMult) { that.doEditRow($selectTrs) } else { if (that.$lastSelect) that.doEditRow(that.$lastSelect) else that.doEditRow($selectTrs.first()) } } }) } else if (n == 'cancel') { that.$toolbar_calcel = $(btnHtml).attr('data-icon', 'undo').addClass('btn-orange').text(BJUI.getRegional('datagrid.cancel')) .appendTo($group) .on('click', function(e) { that.doCancelEditRow(that.$tbody.find('> tr.'+ that.classnames.tr_edit)) }) } else if (n == 'save') { that.$toolbar_save = $(btnHtml).attr('data-icon', 'save').addClass('btn-default').text(BJUI.getRegional('datagrid.save')) .appendTo($group) .on('click', function(e) { that.doSaveEditRow() }) } else if (n == 'del') { that.$toolbar_del = $(btnHtml).attr('data-icon', 'times').addClass('btn-red').text(BJUI.getRegional('datagrid.del')) .appendTo($group) .on('click', function(e) { var $selectTrs = that.$tbody.find('> tr.'+ that.classnames.tr_selected) if ($selectTrs.length) { that.delRows($selectTrs) } else { $(this).alertmsg('info', BJUI.getRegional('datagrid.selectMsg')) } }) } else if (n == 'refresh') { that.$toolbar_refresh = $(btnHtml).attr('data-icon', 'refresh').addClass('btn-green').text(BJUI.getRegional('datagrid.refresh')) .appendTo($group) .on('click', function(e) { that.refresh() }) } else if (n == 'import') { that.$toolbar_add = $(btnHtml).attr('data-icon', 'sign-in').addClass('btn-blue').text(BJUI.getRegional('datagrid.import')) .appendTo($group) .on('click', function(e) { if (options.importOption) { var opts = options.importOption if (typeof opts == 'string') opts = opts.toObj() if (opts.options && opts.options.url) { if (opts.type == 'dialog') { that.$grid.dialog(opts.options) } else if (opts.type == 'navtab') { that.$grid.navtab(opts.options) } else { that.$grid.bjuiajax('doAjax', opts.options) } } } }) } else if (n == 'export') { that.$toolbar_add = $(btnHtml).attr('data-icon', 'sign-out').addClass('btn-green').text(BJUI.getRegional('datagrid.export')) .appendTo($group) .on('click', function(e) { if (options.exportOption) { var opts = options.exportOption if (typeof opts == 'string') opts = opts.toObj() if (opts.options && opts.options.url) { if (opts.type == 'dialog') { that.$grid.dialog(opts.options) } else if (opts.type == 'navtab') { that.$grid.navtab(opts.options) } else if (opts.type == 'file') { $.fileDownload(opts.options.url, { failCallback: function(responseHtml, url) { if (responseHtml.trim().startsWith('{')) responseHtml = responseHtml.toObj() that.$grid.bjuiajax('ajaxDone', responseHtml) } }) } else { that.$grid.bjuiajax('doAjax', opts.options) } } } }) } }) } if (options.toolbarCustom) { var $custom, $custombox = $('<div style="display:inline-block;"></div>') if (typeof options.toolbarCustom == 'string') { var custom = $(options.toolbarCustom) if (custom && custom.length) { $custom = custom } else { custom = custom.toFunc() if (custom) { $custom = custom.call(that) if (typeof $custom == 'string') $custom = $($custom) } } } else if (typeof options.toolbarCustom == 'function') { $custom = options.toolbarCustom.call(that) if (typeof $custom == 'string') $custom = $($custom) } else { $custom = options.toolbarCustom } if ($custom && $custom.length && typeof $custom != 'string') { if (hastoolbaritem) { $custombox.css('margin-left', '5px') } $custombox.appendTo(that.$toolbar) $custom.appendTo($custombox) } } that.$toolbar.appendTo(that.$grid) } } } Datagrid.prototype.initThead = function() { var that = this, options = that.options, tools = that.tools, columnModel = that.columnModel, width, cols = [], $firstTds = that.$tbody.find('> tr:first-child > td') that.init_thead = true that.$colgroupH = $('<colgroup></colgroup>') that.$tableH = $('<table class="table table-bordered"></table>').append(that.$thead) that.$trsH = that.$thead.find('> tr') that.table_width = 0 $.each(that.columnModel, function(i, n) { width = n.width ? n.width : ($firstTds.eq(i).outerWidth() || 50) cols.push('<col style="width:'+ width +'px;">') n.width = width that.table_width += width }) that.$thead.before(that.$colgroupH.append(cols.join(''))) that.$grid.append(that.$boxH.append($('<div class="datagrid-wrap-h"></div>').append(that.$tableH))) // thead - events var $ths = that.$trsH.find('> th') // events - quicksort $ths.filter('.datagrid-quicksort-th') .on('click.bjui.datagrid.quicksort', function(e) { var $target = $(e.target) if (!$target.closest('.'+ that.classnames.th_cell).length && !that.isResize) tools.quickSort(columnModel[$(this).data('index')]) }) // events - filter $ths.filter('.datagrid-column-menu') .on('bjui.datagrid.th.filter', function(e, flag) { var $th = $(this), $btn = $th.find('> div > .'+ that.classnames.th_cell +'> .'+ that.classnames.btn_menu +'> .btn') if (flag) { $th.addClass('filter-active') $btn.find('> i').attr('class', 'fa fa-filter') } else { $th.removeClass('filter-active') $btn.find('> i').attr('class', 'fa fa-bars') } }) // events - contextmenu if (options.contextMenuH) { tools.contextmenuH() } that.initTbody() if (options.columnResize) that.colResize() if (options.columnMenu) that.colMenu() if (options.paging) that.initPaging() if (options.editMode) that.edit() that.resizeGrid() var delayFunc = function() { if (options.showTfoot) that.initTfoot() that.initLock() that.$grid.initui() if (options.height) tools.fixedH() setTimeout(function() { that.fixedWidth('init') }, 500) that.initEvents() } if (options.filterThead) { if (that.delayRender) { that.delayFilterTimeout = setInterval(function() { if (!that.delayRender) { clearInterval(that.delayFilterTimeout) that.filterInThead() delayFunc() } }, 100) } else { that.filterInThead() delayFunc() } } else { delayFunc() } } Datagrid.prototype.fixedWidth = function(isInit) { var that = this, options = that.options, bW, excludeW = 0, fixedW, width, columnModel = that.columnModel, length = columnModel.length if (isInit && that.initFixedW) return that.initFixedW = true var setNewWidth = function() { that.$boxH.find('> div').css('width', '') that.$boxB.find('> div').css('width', '') that.$boxF && that.$boxF.find('> div').css('width', '') that.$pagingCon && that.$pagingCon.css('width', '') bW = that.$boxB.find('> div').width() if (bW) { that.$boxB.find('> div').width(bW) that.$boxH.find('> div').width(bW) that.$boxF && that.$boxF.find('> div').width(bW) if (that.table_width > bW) that.$pagingCon && that.$pagingCon.width(bW) else that.$pagingCon && that.$pagingCon.width(that.table_width) } } var doFixedW = function() { if (bW && bW < that.table_width) { if (columnModel[length - 1] == that.editBtnsColumn) { excludeW += that.editBtnsColumn.width length -- } if (columnModel[0] == that.linenumberColumn) { excludeW += that.linenumberColumn.width length -- } if (columnModel[0] == that.checkboxColumn || columnModel[1] == that.checkboxColumn) { excludeW += that.checkboxColumn.width length -- } fixedW = parseInt((bW - that.table_width - excludeW) / length) if (!fixedW) fixedW = -1 else fixedW -- $.each(columnModel, function(i, n) { if (n == that.linenumberColumn || n == that.checkboxColumn || n == that.editBtnsColumn) return true width = n.width + fixedW if (width <= 0) width = 1 that.$colgroupH.find('> col:eq('+ n.index +')').width(width) that.$colgroupB.find('> col:eq('+ n.index +')').width(width) that.$colgroupF && that.$colgroupF.find('> col:eq('+ n.index +')').width(width) n.new_width = width }) } } if (options.fullGrid) { setNewWidth() doFixedW() } else { setNewWidth() } } Datagrid.prototype.initTbody = function() { var that = this, options = that.options, tools = that.tools, $trs = that.$tbody.find('> tr'), $tds = $trs.find('> td'), width = '0' that.init_tbody = true that.$colgroupB = that.$colgroupH.clone() that.$tableB = that.$element that.$tableB.removeAttr('data-toggle width').empty().append(that.$tbody) that.$tbody.before(that.$colgroupB) that.$grid.append(that.$boxB.append($('<div class="datagrid-wrap-b"></div>').append(that.$tableB))) if ( !-[1,] ) width = 'auto' //for ie8 if (options.fullGrid) width = '100%' that.$tableH.width(width) that.$tableB.width(width) // add class that.$tableB.addClass('table table-bordered').removeClass('table-hover') that.$boxB .scroll(function() { that.$boxH.find('> div').prop('scrollLeft', this.scrollLeft) that.$boxF && that.$boxF.find('> div').prop('scrollLeft', this.scrollLeft) that.$lockB && that.$lockB.prop('scrollTop', this.scrollTop) }) // if DOM to datagrid if (that.isDom) { if (options.showLinenumber) { that.showLinenumber(options.showLinenumber) } if (options.showCheckboxcol) { that.showCheckboxcol(options.showCheckboxcol) } if (options.showEditbtnscol) { that.showEditCol(options.showEditbtnscol) } that.$grid.data(that.datanames.tbody, that.$tbody.clone()) } } // init events(only tbody) Datagrid.prototype.initEvents = function($trs) { var that = this, options = that.options, trs = that.$tbody.find('> tr') if (!$trs) $trs = trs $trs .on('click.bjui.datagrid.tr', function(e, checkbox) { var $tr = $(this), index = $tr.index(), $selectedTrs = that.$tbody.find('> tr.'+ that.classnames.tr_selected), $last = that.$lastSelect, checked, $lockTrs = that.$lockTbody && that.$lockTbody.find('> tr') if (checkbox) { checked = checkbox.is(':checked') if (!checked) that.$lastSelect = $tr that.selectedRows($tr, !checked) } else { if ($tr.hasClass(that.classnames.tr_edit)) return if (!BJUI.KeyPressed.ctrl && !BJUI.KeyPressed.shift) { if ($selectedTrs.length > 1 && $tr.hasClass(that.classnames.tr_selected)) { that.selectedRows($selectedTrs.not($tr)) that.$lastSelect = $tr } else { if ($selectedTrs.length && $selectedTrs[0] != this) that.selectedRows(null) if (!$tr.hasClass(that.classnames.tr_selected)) that.$lastSelect = $tr that.selectedRows($tr) } } else { window.getSelection ? window.getSelection().removeAllRanges() : document.selection.empty() //clear selection if (BJUI.KeyPressed.ctrl) { if (!$tr.hasClass(that.classnames.tr_selected)) that.$lastSelect = $tr that.selectedRows($tr) } else if (BJUI.KeyPressed.shift) { if (!$last) $last = that.$lastSelect = $tr if ($last.length) { that.selectedRows(null) if ($last.index() != index) { if ($last.index() > index) { that.selectedRows($tr.nextUntil($last).add($tr).add($last), true) } else { that.selectedRows($tr.prevUntil($last).add($tr).add($last), true) } } else { that.selectedRows(index) } } } } } }) .on('mouseenter.bjui.datagrid', function(e) { var $tr = $(this), index = $tr.index() $tr.addClass('datagrid-hover') that.$lockTbody && that.$lockTbody.find('> tr:eq('+ index +')').addClass('datagrid-hover') }) .on('mouseleave.bjui.datagrid', function(e) { var $tr = $(this), index = $tr.index() $tr.removeClass('datagrid-hover') that.$lockTbody && that.$lockTbody.find('> tr:eq('+ index +')').removeClass('datagrid-hover') }) // custom event - delete .on('bjui.datagrid.tr.delete', function(e) { var $tr = $(this), index = $tr.index(), data = that.data, gridIndex, allData = that.allData, $lockTrs = that.$lockTbody && that.$lockTbody.find('> tr') if (!that.isDom) { gridIndex = data[index].gridIndex that.data = data.remove(index) // remove data in the current page data that.allData = allData.remove(gridIndex) // remove data in allData } /* update gridNumber */ if (that.columnModel[0] == that.linenumberColumn) { $tr.nextAll().each(function() { var $td = $(this).find('> td:eq(0)'), num = parseInt($td.text()) $td.text(num - 1) }) $lockTrs && $lockTrs.eq(index).trigger('bjui.datagrid.tr.delete', [index]) } $tr.remove() // remove dom }) //contextmenu if (options.contextMenuB) { $trs.each(function() { that.tools.contextmenuB($(this)) }) } // checkbox $trs.each(function() { var $tr = $(this) $tr.find('> td.'+ that.classnames.td_checkbox).find('input').on('ifClicked', function() { $tr.trigger('click.bjui.datagrid.tr', [$(this)]) }) }) // checkall || deselect all if (that.checkboxColumn && that.checkboxColumn.th) { that.checkboxColumn.th.find('input').on('ifChanged', function() { var checked = $(this).is(':checked'), $trs = that.$tbody.find('> tr') that.selectedRows($trs, checked) }) } } Datagrid.prototype.initTfoot = function() { var that = this, options = that.options, tools = that.tools, columnModel = that.columnModel, $tr = $('<tr></tr>') that.$boxF = $('<div class="datagrid-box-f"></div>') that.$colgroupF = that.$colgroupH.clone() that.$tableF = that.$tableH.clone().empty() that.$tableF.append(that.$colgroupF) that.$boxF.append($('<div class="datagrid-wrap-h"></div>').append(that.$tableF)) that.$boxF.insertAfter(that.$boxB) that.$tfoot = $('<thead></thead>') $.each(columnModel, function(i, n) { var $th = $('<th><div></div></th>') if (n.calc) { var calc_html = '<div><div class="datagrid-calcbox">#tit#</div>#number#</div>' if (n.calc == 'avg') $th.html(calc_html.replace('#tit#', (n.calcTit || 'AVG')).replace('#number#', (n.calc_sum / n.calc_count).toFixed(n.calcDecimal || 2))) else if (n.calc == 'count') $th.html(calc_html.replace('#tit#', (n.calcTit || 'COUNT')).replace('#number#', (n.calc_count))) else if (n.calc == 'sum') $th.html(calc_html.replace('#tit#', (n.calcTit || 'SUM')).replace('#number#', (n.calc_sum))) else if (n.calc == 'max') $th.html(calc_html.replace('#tit#', (n.calcTit || 'MAX')).replace('#number#', (n.calc_max))) else if (n.calc == 'min') $th.html(calc_html.replace('#tit#', (n.calcTit || 'MIN')).replace('#number#', (n.calc_min))) } if (n.hidden) $th.css('display', 'none') $th.appendTo($tr) }) that.$tfoot.append($tr).appendTo(that.$tableF) // events that.$tfoot.on('bjui.datagrid.tfoot.resizeH', function() { tools.setBoxbH(options.height) }) } // selected row Datagrid.prototype.selectedRows = function(rows, selected) { var that = this, $lockTrs = that.$lockTbody && that.$lockTbody.find('> tr'), $trs = that.$tbody.find('> tr'), n var selectedTr = function(n) { if (typeof selected == 'undefined') selected = true $trs.eq(n) .toggleClass(that.classnames.tr_selected, selected) .find('> td.'+ that.classnames.td_checkbox +' input').iCheck(selected ? 'check' : 'uncheck') $lockTrs && $lockTrs.eq(n) .toggleClass(that.classnames.tr_selected, selected) .find('> td.'+ that.classnames.td_checkbox +' input').iCheck(selected ? 'check' : 'uncheck') } if (rows == null) { $trs.removeClass(that.classnames.tr_selected) .find('> td.'+ that.classnames.td_checkbox +' input').iCheck('uncheck') $lockTrs && $lockTrs.removeClass(that.classnames.tr_selected) .find('> td.'+ that.classnames.td_checkbox +' input').iCheck('uncheck') } else if (typeof rows == 'object') { rows.each(function() { var $row = $(this), index = $row.index() if (typeof selected != 'undefined') { selectedTr(index) } else { $row.toggleClass(that.classnames.tr_selected) .trigger('bjui.datagrid.tr.selected') .find('> td.'+ that.classnames.td_checkbox +' input').iCheck(($row.hasClass(that.classnames.tr_selected) ? 'check' : 'uncheck')) $lockTrs && $lockTrs.eq(index) .toggleClass(that.classnames.tr_selected) .trigger('bjui.datagrid.tr.selected') .find('> td.'+ that.classnames.td_checkbox +' input').iCheck(($row.hasClass(that.classnames.tr_selected) ? 'check' : 'uncheck')) } }) } else if (isNaN(rows)) { $.each(rows.split(','), function(i, n) { selectedTr(parseInt(n.trim())) }) } else if (!isNaN(rows)) { selectedTr(parseInt(rows)) } if (that.$lastSelect && !that.$lastSelect.hasClass(that.classnames.tr_selected)) { that.$lastSelect = null } // selectedTrs that.$element.data('selectedTrs', that.$tbody.find('> tr.'+ that.classnames.tr_selected)) } //lock Datagrid.prototype.initLock = function() { var that = this, columnModel = that.columnModel that.col_lock_count = 0 $.each(that.columnModel, function(i, n) { if (n.initLock) that.col_lock_count ++ }) if (that.col_lock_count) that.doLock() } //api - colLock Datagrid.prototype.colLock = function(column, lockFlag) { var that = this, $th, index, columnModel if ($.type(column) == 'number') { index = parseInt(column) if (index < 0 || index > that.columnModel.length - 1) return columnModel = that.columnModel[index] $th = columnModel.th } else { $th = column index = $th.data('index') columnModel = that.columnModel[index] } if (columnModel == that.editBtnsColumn) return // edit btn column else if (columnModel.index == that.columnModel.length - 1) return // last column if (typeof columnModel.locked == 'undefined') columnModel.locked = false if (columnModel.locked == lockFlag) return columnModel.initLock = lockFlag if (lockFlag) { that.col_lock_count ++ } else { that.col_lock_count -- } if (that.col_lock_count < 0) that.col_lock_count = 0 that.doLock() } Datagrid.prototype.fixedLockItem = function(type) { var that = this, columnModel = that.columnModel, $filterThs = that.$thead.find('> tr.datagrid-filter > th'), $lockTrs = that.$lockTbody && that.$lockTbody.find('> tr') // out if (!type) { // filterThead if ($filterThs && $filterThs.length) { that.$lockThead && that.$lockThead.find('> tr.datagrid-filter > th:visible').each(function() { var $lockTh = $(this), index = $lockTh.index(), $th = $filterThs.eq(index) $lockTh.clone().insertAfter($lockTh) $lockTh.hide().insertAfter($th) $th.remove() }) } // inline edit if ($lockTrs && $lockTrs.length) { $lockTrs.filter('.'+ that.classnames.tr_edit).each(function() { var $lockTr = $(this), $lockTd = $lockTr.find('> td:eq('+ columnModel.lockIndex +')'), tr_index = $lockTr.index(), $tr, $td if ($lockTd.hasClass(that.classnames.td_edit)) { $tr = that.$tbody.find('> tr:eq('+ tr_index +')'), $td = $tr.find('> td:eq('+ index +')') $lockTd.clone().insertAfter($lockTd) $lockTd.hide().insertAfter($td) $td.remove() } }) } } else { //in // filterThead if ($filterThs && $filterThs.length) { that.$lockThead.find('> tr.datagrid-filter > th:visible').each(function() { var $lockTh = $(this), index = $lockTh.index(), $th = $filterThs.eq(index) $th.clone().html('').insertAfter($th) $th.show().insertAfter($lockTh) $lockTh.remove() }) } // inline edit if ($lockTrs && $lockTrs.length) { $lockTrs.filter('.'+ that.classnames.tr_edit).each(function() { var $lockTr = $(this), tr_index = $lockTr.index() $lockTr.find('> td.'+ that.classnames.td_edit +':visible').each(function() { var $lockTd = $(this), td_index = $lockTd.index(), model = columnModel[td_index], $tr, $td if (model.locked) { $tr = that.$tbody.find('> tr:eq('+ tr_index +')') $td = $tr.find('> td:eq('+ td_index +')') $td.clone().insertAfter($td) $td.show().insertAfter($lockTd) $lockTd.remove() } }) }) } } } //locking Datagrid.prototype.doLock = function() { var that = this, options = that.options, tools = that.tools, columnModel = that.columnModel, tableW = that.$tableH.width(), width = 0, $trs, $lockTrs, lockedLen = 0 var hasFoot = that.$boxF && true, top = 0 if (!that.$lockBox || !that.$lockBox.length) { that.$lockBox = $('<div class="datagrid-box-l"></div>') that.$lockH = $('<div class="datagrid-box-h"></div>') that.$lockB = $('<div class="datagrid-box-b"></div>') that.$lockF = $('<div class="datagrid-box-f"></div>') that.$lockTableH = $('<table class="table table-bordered"></table>') that.$lockTableB = $('<table></table>').addClass(that.$tableB.attr('class')) that.$lockTableF = $('<table class="table table-bordered"></table>') that.$lockH.append(that.$lockTableH) that.$lockB.append(that.$lockTableB) that.$lockF.append(that.$lockTableF) that.$lockBox.append(that.$lockH).append(that.$lockB).prependTo(that.$grid) if (hasFoot) { that.$lockBox.append(that.$lockF) that.$lockF.css('margin-top', (that.$boxB.outerHeight() - that.$boxB[0].clientHeight)).height(that.$boxF.outerHeight()) } } else { that.fixedLockItem() that.$lockTableH.empty() that.$lockTableB.empty() that.$lockTableF && that.$lockTableF.empty() } if (that.$boxT) top += that.$boxT.outerHeight() if (that.$toolbar) top += that.$toolbar.outerHeight() if (top) that.$lockBox.css({top:top}) // display initLock columns, hide other $.each(columnModel, function(i, n) { n.lockShow = false n.lockHide = false if (n.initLock) { if (n.hidden) tools.showhide(n, true) n.lockHide = true n.locked = true n.lockIndex = lockedLen ++ width += n.width } else { n.lockShow = true if (!n.hidden) tools.showhide(n, false) else n.lockShow = false if (n.locked) n.lockShow = true n.locked = false } }) that.$lockThead = that.$thead.clone(true) that.$lockTbody = that.$tbody.clone() that.$lockColgroupH = that.$colgroupH.clone() that.$lockColgroupB = that.$colgroupB.clone() that.$lockTableH.append(that.$lockColgroupH).append(that.$lockThead).css('width', width) that.$lockTableB.append(that.$lockColgroupB).append(that.$lockTbody).css('width', width) if (hasFoot) { that.$lockTfoot = that.$tableF.find('> thead').clone() that.$lockColgroupF = that.$colgroupF.clone() that.$lockTableF.append(that.$lockColgroupF).append(that.$lockTfoot).css('width', width) } // display unlock columns, hide locked columns $.each(that.columnModel, function(i, n) { if (n.lockShow) tools.showhide(n, true) if (n.lockHide) tools.showhide(n, false) }) that.$boxH.find('> div').css('width', '') that.$boxB.find('> div').css('width', '') that.$boxF && that.$boxF.find('> div').css('width', '') setTimeout(function() { var bw = that.$boxB.find('> div').width() that.$boxB.find('> div').width(bw) that.$boxH.find('> div').width(bw) that.$boxF && that.$boxF.find('> div').width(bw) }, 50) if (that.col_lock_count == 0) that.$lockBox.hide() else that.$lockBox.show() if (width > 1) width = width - 1 that.$boxH.css('margin-left', width) that.$boxB.css('margin-left', width) if (hasFoot) that.$boxF.css('margin-left', width) // fixed height that.$lockB.height(that.$boxB[0].clientHeight) that.$lockB.prop('scrollTop', that.$boxB[0].scrollTop) var lockH = that.$lockTableH.height(), H = that.$thead.height(), lockFH = that.$lockTableF && that.$lockTableF.height(), HF = that.$tableF && that.$tableF.height() if (lockH != H) { if (lockH < H) that.$lockTableH.height(H) else that.$tableH.height(lockH) } if (lockFH && HF && (lockFH != HF)) { if (lockFH < HF) that.$lockTableF.find('> thead > tr:first-child > th:visible:first').height(HF) else that.$tableF.find('> thead > tr:first-child > th:visible:first').height(lockFH) } $lockTrs = that.$lockTbody.find('> tr') $trs = that.$tbody.find('> tr') setTimeout(function() { var lockBH = that.$lockTableB.height(), HB = that.$tableB.height() if (lockBH != HB) { if (lockBH > HB) { $lockTrs.each(function(tr_index) { var $lockTr = $(this), $lockTd = $lockTr.find('> td:visible:first'), newH = $lockTd.outerHeight() if (newH > 30) { $lockTr.height(newH) $trs.eq(tr_index).height(newH) } }) } else { $trs.each(function(tr_index) { var $tr = $(this), $td = $tr.find('> td:visible:first'), newH = $td.outerHeight() if (newH > 30) { $tr.height(newH) $lockTrs.eq(tr_index).height(newH) } }) } } }, 20) that.fixedLockItem(1) // remove hidden tds $lockTrs.find('> td:hidden').remove() // events that.initLockEvents($lockTrs) } // init lockTr Events Datagrid.prototype.initLockEvents = function($locktrs) { if (!this.$lockTbody) return var that = this, options = that.options if (!$locktrs) $locktrs = that.$lockTbody.find('> tr') $locktrs .on('click.bjui.datagrid.tr', function() { var index = $(this).index() that.$tbody.find('> tr:eq('+ index +')').trigger('click.bjui.datagrid.tr') }) .on('bjui.datagrid.tr.delete', function(e, index) { var $tr = $(this) if (that.linenumberColumn && that.linenumberColumn.locked) { $tr.nextAll().each(function() { var $td = $(this).find('> td:eq(0)'), num = parseInt($td.text()) $td.text(num - 1) }) } $tr.remove() }) .find('> td.'+ that.classnames.td_checkbox +' input') .on('ifChanged', function() { var $this = $(this), $tr = $this.closest('tr'), index = $tr.index() if ($this.is(':checked')) { $tr.addClass(that.classnames.tr_selected) $trs.eq(index).addClass(that.classnames.tr_selected) } else { $tr.removeClass(that.classnames.tr_selected) $trs.eq(index).removeClass(that.classnames.tr_selected) } }) //contextmenu if (options.contextMenuB) { $locktrs.each(function() { that.tools.contextmenuB($(this), true) }) } } //api - filterInThead Datagrid.prototype.filterInThead = function() { var that = this, options = that.options, tools = that.tools, regional = that.regional, columnModel = that.columnModel, filterData = {} var $tr = $('<tr class="datagrid-filter"></tr>') var onFilter = function($input, model, $th) { var type = model.type if (type == 'date') { $input .on('afterchange.bjui.datepicker', function(e, data) { doFilter(model, $input.val()) }) .change(function() { doFilter(model, $input.val()) }) } else if (type == 'lookup'){ $th.on('customEvent.bjui.lookup', '[data-toggle="lookupbtn"]', function(e, args) { for (var key in args) { if (model.name == key) { $input.val(args[key]) doFilter(model, args[key]) } } }) $input.change(function() { doFilter(model, $input.val()) }) } else { $input.change(function() { doFilter(model, $input.val()) }) } } var doFilter = function(model, val) { tools.quickFilter(model, val ? {operatorA:'like', valA:val} : null) } if (!that.inputs || !that.inputs.length) tools.initEditInputs() $.each(columnModel, function(i, n) { var $input = $(that.inputs[i]), $th = $('<th></th>') if (n.type == 'spinner') $input = $('<input type="text" name="'+ n.name +'">') else if (n.type == 'boolean') $input = $(BJUI.doRegional('<select name="'+ n.name +'" data-toggle="selectpicker"><option value="">#all#</option><option value="true">#true#</option><option value="false">#false#</option></select>', regional)) else if (n.type == 'select') { if ($input.find('> option:first-child').val()) { $input = $('<select name="'+ n.name +'" data-toggle="selectpicker"></select>') .append(BJUI.doRegional('<option value="">#all#</option>', regional)) .append($input.html()) } } $th.append($input) if (n.hidden) $th.hide() if (n.type == 'boolean') $th.attr('align', 'center') $th.appendTo($tr) $input.data('clearFilter', false) onFilter($input, n, $th) // events - clear filter $input.on('bjui.datagrid.thead.clearfilter', function() { $input.val('') if (n.type == 'boolean' || n.type == 'select') $input.selectpicker('refresh') }) n.quickfilter = $input }) $tr.appendTo(that.$thead).initui() } //api - showhide linenumber column Datagrid.prototype.showLinenumber = function(flag) { var that = this, options = that.options, model = that.columnModel, numberModel = model[0], data = that.data if (numberModel == that.linenumberColumn) { if (typeof flag === 'string' && (flag == 'lock' || flag == 'unlock')) { that.colLock(numberModel.th, flag == 'lock' ? true : false) } else { that.showhideColumn(numberModel.th, flag ? true : false) } } else if (flag) { var $trsH = that.$thead.find('> tr'), col = '<col style="width:30px;">', $th, $filterTr = $trsH.filter('.datagrid-filter'), rowspan = $trsH.length - $filterTr.length numberModel = that.linenumberColumn model.unshift(numberModel) that.$colgroupH.prepend(col) that.$colgroupB.prepend(col) that.$colgroupF && that.$colgroupF.prepend(col) $th = $('<th align="center" rowspan="'+ rowspan +'" class="'+ that.classnames.td_linenumber +'">'+ that.linenumberColumn.label +'</th>') $trsH.first().prepend($th) $filterTr.length && $filterTr.prepend('<th></th>') numberModel.th = $th numberModel.index = 0 numberModel.width = 30 that.$tbody.find('> tr').each(function(i) { $(this).prepend('<td align="center" class="'+ that.classnames.td_linenumber +'">'+ (i + 1) +'</td>') }) that.$tableF && that.$tableF.find('> thead > tr').prepend('<th></th>') $.each(model, function(i, n) { n.index = i if (n.th) n.th.data('index', i) }) if (flag == 'lock') { that.colLock($th, true) } if (that.$showhide) { that.$showhide.remove() that.colShowhide(options.columnShowhide) } } } //api - showhide checkbox column Datagrid.prototype.showCheckboxcol = function(flag) { var that = this, options = that.options, model = that.columnModel, numberModel = model[0], checkModel, data = that.data if (model[0] == that.checkboxColumn) checkModel = model[0] if (model[1] == that.checkboxColumn) checkModel = model[1] if (checkModel) { if (typeof flag === 'string' && (flag == 'lock' || flag == 'unlock')) { that.colLock(checkModel.th, flag == 'lock' ? true : false) } else { that.showhideColumn(checkModel.th, flag) } } else if (flag) { var $trsH = that.$thead.find('> tr'), col = '<col style="width:26px;">', $th, $td, $filterTr = $trsH.filter('.datagrid-filter'), rowspan = $trsH.length - $filterTr.length checkModel = that.checkboxColumn $th = $('<th align="center" rowspan="'+ rowspan +'" class="'+ that.classnames.td_checkbox +'"><div><input type="checkbox" data-toggle="icheck"></div></th>') if (numberModel == that.linenumberColumn) { model.splice(1, 0, checkModel) data && data.splice(1, 0, {name:checkModel.name}) checkModel.index = 1 that.$colgroupH.find('> col:first').after(col) that.$colgroupB.find('> col:first').after(col) that.$colgroupF && that.$colgroupF.find('> col:first').after(col) $filterTr.length && $filterTr.find('> th:first').after('<th></th>') $trsH.first().find('> th:first').after($th) that.$tableF && that.$tableF.find('> thead > tr > th:first').after('<th></th>') } else { model.unshift(checkModel) data && data.unshift({name:checkModel.name}) checkModel.index = 0 that.$colgroupH.prepend(col) that.$colgroupB.prepend(col) that.$colgroupF && that.$colgroupF.prepend(col) $filterTr.length && $filterTr.prepend('<th></th>') $trsH.first().prepend($th) that.$tableF && that.$tableF.find('> thead > tr').prepend('<th></th>') } $th.initui() checkModel.th = $th checkModel.width = 26 that.$tbody.find('> tr').each(function(i) { $td = $('<td align="center" class="'+ that.classnames.td_checkbox +'"><input type="checkbox" data-toggle="icheck" name="datagrid.checkbox"></td>') if (checkModel.index == 0) $(this).prepend($td) else $(this).find('> td:first').after($td) $td.initui() }) $.each(model, function(i, n) { n.index = i if (n.th) n.th.data('index', i) }) if (flag == 'lock') { that.colLock($th, true) } if (that.$showhide) { that.$showhide.remove() that.colShowhide(options.columnShowhide) } } } //api - showhide checkbox column Datagrid.prototype.showEditCol = function(flag) { var that = this, options = that.options, model = that.columnModel, editModel = model[model.length - 1], data = that.data if (editModel == that.editBtnsColumn) { that.showhideColumn(editModel.th, flag ? true : false) } else if (flag) { var $trsH = that.$thead.find('> tr'), col = '<col style="width:110px;">', $th, $td, $filterTr = $trsH.filter('.datagrid-filter'), rowspan = $trsH.length - $filterTr.length editModel = that.editBtnsColumn model.push(editModel) that.$colgroupH.append(col) that.$colgroupB.append(col) that.$colgroupF && that.$colgroupF.append(col) $th = $('<th align="center" rowspan="'+ rowspan +'">Edit</th>') $trsH.first().append($th) $filterTr.length && $filterTr.append('<th></th>') $th.initui().data('index', model.length - 1) editModel.th = $th editModel.width = 110 editModel.index = model.length - 1 that.$tbody.find('> tr').each(function(i) { $td = $('<td align="center" class="'+ that.classnames.s_edit +'">'+ BJUI.doRegional(FRAG.gridEditBtn, that.regional) +'</td>') $(this).append($td) $td.initui() }) that.edit(that.$tbody.find('> tr')) that.$tableF && that.$tableF.find('> thead > tr').append('<th></th>') if (that.$showhide) { that.$showhide.remove() that.colShowhide(options.columnShowhide) } } } //resize Datagrid.prototype.colResize = function() { var that = this, tools = that.tools, columnModel = that.columnModel, $thead = that.$thead, $resizeMark = that.$grid.find('> .resizeProxy') if (!$resizeMark.length) { $resizeMark = $('<div class="resizeProxy" style="left:0; display:none;"></div>') $resizeMark.appendTo(that.$grid) } $thead.find('> tr > th').each(function(i) { var $th = $(this), $resize = $th.find('> div > .'+ that.classnames.th_cell +'> .'+ that.classnames.th_resizemark) $resize.on('mousedown.bjui.datagrid.resize', function(e) { var ofLeft = that.$boxH.scrollLeft(), marginLeft = parseInt(that.$boxH.css('marginLeft') || 0), left = tools.getRight($th) - ofLeft + marginLeft, index = $th.data('index'), model = columnModel[index], width = model.th.width(), $trs = that.$tbody.find('> tr'), $lockTrs = that.$lockTbody && that.$lockTbody.find('> tr'), lockH = that.$lockTableB && that.$lockTableB.height(), H = that.$tableB.height(), lockH_new, H_new that.isResize = true if (model.locked) { left = tools.getRight4Lock(model.lockIndex) if (model.lockWidth) width = model.lockWidth } $resizeMark .show() .css({ left : left, bottom : (that.$box_paging ? that.$box_paging.outerHeight() : 0), cursor : 'col-resize' }) .basedrag({ scop : true, cellMinW:20, relObj:$resizeMark, move : 'horizontal', event : e, stop : function() { var new_left = $resizeMark.position().left, move = new_left - left, newWidth = move + width, tableW = that.$tableH.width() + move, lockW = that.$lockTableH && that.$lockTableH.width() + move if (newWidth < 5) newWidth = 20 if (model.minWidth && newWidth < model.minWidth) newWidth = model.minWidth if (newWidth != width + move) { tableW = tableW - move + (newWidth - width) lockW = lockW - move + (newWidth - width) } model.width = newWidth if (model.locked) { if (lockW < (that.$grid.width() * 0.75)) { model.lockWidth = newWidth that.$lockColgroupH.find('> col:eq('+ index +')').width(newWidth) that.$lockColgroupB.find('> col:eq('+ index +')').width(newWidth) that.$lockColgroupF && that.$lockColgroupF.find('> col:eq('+ index +')').width(newWidth) that.$lockTableH.width(lockW) that.$lockTableB.width(lockW) that.$lockTableF && that.$lockTableF.width(lockW) var margin = that.$lockBox.width() that.$boxH.css('margin-left', margin - 1) that.$boxB.css('margin-left', margin - 1) that.$boxF && that.$boxF.css('margin-left', margin - 1) that.$colgroupH.find('> col:eq('+ index +')').width(newWidth) that.$colgroupB.find('> col:eq('+ index +')').width(newWidth) that.$colgroupF && that.$colgroupF.find('> col:eq('+ index +')').width(newWidth) } } else { setTimeout(function() { that.$colgroupH.find('> col:eq('+ index +')').width(newWidth) that.$colgroupB.find('> col:eq('+ index +')').width(newWidth) that.$colgroupF && that.$colgroupF.find('> col:eq('+ index +')').width(newWidth) }, 1) //setTimeout for chrome } /* fixed height */ setTimeout(function() { $trs.css('height', '') H_new = that.$tableB.height() if (that.$lockTbody) { $lockTrs.css('height', '') lockH_new = that.$lockTableB.height() if (lockH_new != lockH || H_new != H) { if (lockH_new > H_new) { $lockTrs.each(function(tr_index) { var $lockTr = $(this), $lockTd = $lockTr.find('> td:eq('+ model.lockIndex +')'), newH = $lockTd.outerHeight() if (newH > 30) { $lockTr.height(newH) $trs.eq(tr_index).height(newH) } }) } else { $trs.each(function(tr_index) { var $tr = $(this), $td = $tr.find('> td:eq('+ index +')'), newH = $td.outerHeight() if (newH > 30) { $tr.height(newH) $lockTrs.eq(tr_index).height(newH) } }) } } that.$lockB.height(that.$boxB[0].clientHeight) } if (model.calc) that.$tfoot && that.$tfoot.trigger('bjui.datagrid.tfoot.resizeH') that.isResize = false }, 10) $resizeMark.hide() that.resizeFlag = true } }) }) }) } //column - add menu button Datagrid.prototype.colMenu = function() { var that = this, options = that.options, tools = that.tools, regional = that.regional, $ths = that.$trsH.find('> th.'+ that.classnames.th_menu), $menu = that.$grid.find('> .'+ that.classnames.s_menu) if (!$menu.legnth) { $menu = $(BJUI.doRegional(FRAG.gridMenu, regional)) $menu.hide().appendTo(that.$grid) that.$menu = $menu } that.colShowhide(options.columnShowhide) $ths.each(function() { var $th = $(this), index = $th.data('index'), model = that.columnModel[index], $cell = $th.find('> div > .'+ that.classnames.th_cell), $btnBox = $cell.find('> .'+ that.classnames.btn_menu), $btn if (!$btnBox.length) { $btn = $('<button class="btn btn-default"><i class="fa fa-bars"></button>'), $btnBox = $('<div class="'+ that.classnames.btn_menu +'"></div>').append($btn) $btnBox.appendTo($cell) $btn.click(function() { var $tr = $th.closest('tr'), rowspan = parseInt($th.attr('rowspan') || 1), left = $(this).offset().left - that.$grid.offset().left - 1, top = (that.$trsH.length - rowspan) * 25 + (13 * rowspan) + 11, $showhide = $menu.find('> ul > li.datagrid-li-showhide'), menu_width, submenu_width var $otherBtn = $menu.data('bjui.datagrid.menu.btn') if ($otherBtn && $otherBtn.length) $otherBtn.removeClass('active') $(this).addClass('active') if ($showhide.length && that.$showhide) { that.$showhide.appendTo($showhide) submenu_width = that.$showhide.data('width') } $menu .css({'position':'absolute', 'top':top, left:left}) .show() .data('bjui.datagrid.menu.btn', $btn) .siblings('.'+ that.classnames.s_menu).hide() menu_width = $menu.outerWidth() var position = function(left) { if (that.$boxH.width() - left < menu_width) { $menu.css({left:left - menu_width + 18}).addClass('position-right') } else { $menu.css({left:left}).removeClass('position-right') } } var fixedLeft = function($btn) { that.$boxB.scroll(function() { var left = $btn.offset().left - that.$grid.offset().left - 1 position(left) }) } position(left) fixedLeft($btn) that.colFilter($th, true) tools.locking($th) // quick sort var $asc = $menu.find('> ul > li.'+ that.classnames.li_asc), $desc = $asc.next() $asc.click(function() { model.sortAsc = false tools.quickSort(model) }) $desc.click(function() { model.sortAsc = true tools.quickSort(model) }) $menu.on('bjui.datagrid.th.sort', function(e, asc) { $asc.toggleClass('sort-active', asc) $desc.toggleClass('sort-active', !asc) }) }) } }) /* hide filterbox */ that.$grid.on('click.bjui.datagrid.filter', function(e) { var $target = $(e.target), $menu = that.$grid.find('.'+ that.classnames.s_menu +':visible') if ($menu.length && !$target.closest('.'+ that.classnames.btn_menu).length) { if (!$target.closest('.'+ that.classnames.s_menu).length) { $menu.hide().data('bjui.datagrid.menu.btn').removeClass('active') } } }) } // show or hide columns on btn menu Datagrid.prototype.colShowhide = function(showFlag) { var that = this, options = that.options, tools = that.tools, $menu = that.$menu, $ul = $menu.find('> ul'), $showhideli = $ul.find('> li.'+ that.classnames.li_showhide) if (showFlag) { if (!that.$showhide) { tools.createShowhide() tools.showSubMenu($showhideli, $menu, that.$showhide) } } else { $showhideli.hide() } } // api - show or hide column Datagrid.prototype.showhideColumn = function(column, showFlag) { var that = this, tools = that.tools, index, model if ($.type(column) == 'number') { index = parseInt(column) if (index < 0) return } else { index = column.data('index') } model = that.columnModel[index] if (model) { if (model.locked) { if (showFlag) return else that.colLock(model.th, showFlag) } tools.showhide(model, showFlag) } } // filter Datagrid.prototype.colFilter = function($th, filterFlag) { var that = this, options = that.options, tools = that.tools, regional = that.regional, $filter = $th.data('bjui.datagrid.filter'), $menu = that.$menu, $filterli = $menu.find('> ul > li.'+ that.classnames.li_filter) if (!that.inputs || !that.inputs.length) tools.initEditInputs() if (filterFlag) { $filterli.find('.'+ that.classnames.s_filter).addClass('hide') if (!$filter || !$filter.length) { $filter = $(BJUI.doRegional(FRAG.gridFilter.replaceAll('#label#', $th.text()), regional)).hide().appendTo(that.$grid) var index = $th.data('index'), model = that.columnModel[index], type = model.type || 'string', operator = model.operator || [], $filterA = $filter.find('span.filter-a'), $filterB = $filter.find('span.filter-b'), $select = $('<select data-toggle="selectpicker" data-container="true"></select>'), $input = $(that.inputs[index]), $valA, $valB $input.removeAttr('data-rule').attr('size', 10).addClass('filter-input') if (type == 'string' || type == 'lookup') { if (!operator.length) operator = ['=', '!=', 'like'] } else if (type == 'number' || type == 'int' || type == 'spinner') { if (type == 'spinner') $input.removeAttr('data-toggle') if (!operator.length) operator = ['=', '!=', '>', '<', '>=', '<='] } else if (type == 'date') { if (!operator.length) operator = ['=', '!='] } else if (type == 'boolean') { if (!operator.length) operator = ['=', '!='] $input = $(BJUI.doRegional('<select name="'+ model.name +'" data-toggle="selectpicker"><option value="">#all#</option><option value="true">#true#</option><option value="false">#false#</option></select>', regional)) } else if (type == 'select') { if (!operator.length) operator = ['=', '!='] $input.attr('data-width', '80') if ($input.find('> option:first-child').val()) { $input = $('<select name="'+ model.name +'" data-toggle="selectpicker" data-width="80"></select>') .append(BJUI.doRegional('<option value="">#all#</option>', regional)) .append($input.html()) } } for (var i = 0; i < operator.length; i++) { $select.append('<option value="'+ (operator[i]) +'">'+ (operator[i]) +'</option>') } $valA = $input $valB = $valA.clone() $filterA.append($select).append($input) $filterB.append($select.clone()).append($valB) $th.data('bjui.datagrid.filter', $filter) $filter.appendTo($filterli) $filter.data('width', $filter.outerWidth()).hide().initui() // lookup - events $filter.on('customEvent.bjui.lookup', '[data-toggle="lookupbtn"]', function(e, args) { for (var key in args) { if (model.name == key) { $input.val(args[key]) } } }) /* events */ var $ok = $filter.find('button.ok'), $clear = $filter.find('button.clear'), $selects = $filter.find('select'), $selA = $selects.first(), $selB = $selects.last(), $andOr = $selects.eq(1) $ok.click(function() { var operatorA = $selA.val(), valA = $valA.val().trim(), operatorB = $selB.val(), valB = $valB.val().trim(), andor = $andOr.val() var filterDatas = {} if (valA.length) { $.extend(filterDatas, {operatorA:operatorA, valA:valA}) } if (valB.length) { if (valA.length) $.extend(filterDatas, {andor:andor}) $.extend(filterDatas, {operatorB:operatorB, valB:valB}) } if (!$.isEmptyObject(filterDatas)) { tools.quickFilter(that.columnModel[$th.data('index')], filterDatas) that.$grid.trigger('click') $filterli.trigger('bjui.datagrid.th.submenu.hide', [$menu, $filter]) } }) $clear.click(function() { var model = that.columnModel[$th.data('index')] $selects.find('> option:first').prop('selected', true) $selects.selectpicker('refresh') $valA.val('') $valB.val('') if (model.isFiltered) { tools.quickFilter(model, null) that.$grid.trigger('click') $filterli.trigger('bjui.datagrid.th.submenu.hide', [$menu, $filter]) } }) } tools.showSubMenu($filterli, $menu, $filter.removeClass('hide')) $menu.find('> ul > li:not(".'+ that.classnames.li_filter +'")').on('mouseover', function() { if ($filterli.hasClass('active')) $filterli.trigger('bjui.datagrid.th.submenu.hide', [$menu, $filter]) }) } else { $filterli.hide() } } // paging Datagrid.prototype.initPaging = function() { var that = this, tools = that.tools, options = that.options, paging = that.paging, pr = BJUI.regional.pagination, btnpaging = FRAG.gridPaging, pageNums = [], pageCount = paging.pageCount, interval, selectPages = [] if (paging.total == 0) return interval = tools.getPageInterval(pageCount, paging.pageCurrent, paging.showPagenum) for (var i = interval.start; i < interval.end; i++) { pageNums.push(FRAG.gridPageNum.replace('#num#', i).replace('#active#', (paging.pageCurrent == i ? ' active' : ''))) } btnpaging = BJUI.doRegional(btnpaging.replaceAll('#pageCurrent#', paging.pageCurrent).replaceAll('#count#', paging.total +'/'+ parseInt(pageCount || 0)), pr) that.$box_paging = $('<div class="datagrid-paging-box"></div>') that.$pagingCon = $('<div class="paging-content"></div>').width(that.$boxB.width()) that.$refreshBtn = $('<button class="btn-default btn-refresh" title="'+ pr.refresh +'" data-icon="refresh"></button>') that.$paging = $('<div class="datagrid-paging"></div>') that.$btnpaging = $(btnpaging) that.$pagenum = $(pageNums.join('')) that.$pagesize = $('<div class="datagrid-pagesize"><span></span></div>') that.$selectpage = $('<select data-toggle="selectpicker"></select>') that.$pagingCon.appendTo(that.$box_paging) that.$box_paging.appendTo(that.$grid) that.$pagesize.appendTo(that.$pagingCon) that.$refreshBtn.appendTo(that.$pagesize) that.$selectpage.appendTo(that.$pagesize) that.$paging.appendTo(that.$pagingCon) that.$btnpaging.appendTo(that.$paging) that.$pagenum.insertAfter(that.$btnpaging.find('> li.page-prev')) that.$box_paging.initui() //events var $jumpto = that.$btnpaging.find('> li.page-jumpto'), $first = $jumpto.next(), $prev = $first.next(), $next = that.$btnpaging.find('> li.page-next'), $last = $next.next() var disablePrev = function() { $first.addClass('disabled') $prev.addClass('disabled') } var enablePrev = function() { $first.removeClass('disabled') $prev.removeClass('disabled') } var disableNext = function() { $next.addClass('disabled') $last.addClass('disabled') } var enableNext = function() { $next.removeClass('disabled') $last.removeClass('disabled') } var pageFirst = function() { disablePrev() enableNext() } var pageLast = function() { enablePrev() disableNext() } var setPageSize = function(pageSize) { that.$selectpage.empty() if (!pageSize) pageSize = that.paging.pageSize selectPages = paging.selectPageSize.split(',') selectPages.push(String(pageSize)) $.unique(selectPages).sort(function(a, b) { return a - b }) $.each(selectPages, function(i, n) { var $option = $('<option value="'+ n +'">'+ n +'/'+ pr.page +'</option>') if (n == paging.pageSize) $option.prop('selected', true) that.$selectpage.append($option) }) that.$selectpage.selectpicker('refresh') } if (paging.pageCurrent == 1) pageFirst() if (paging.pageCurrent == paging.pageCount) { pageLast() if (paging.pageCurrent == 1) disablePrev() } setPageSize() that.$paging.on('click', '.page-num', function(e) { var $num = $(this) if (!$num.hasClass('active')) { that.jumpPage($num.text()) } e.preventDefault() }).on('bjui.datagrid.paging.jump', function(e) { var pageCurrent = that.paging.pageCurrent, interval = tools.getPageInterval(that.paging.pageCount, pageCurrent, paging.showPagenum), pageNums = [] for (var i = interval.start; i < interval.end; i++) { pageNums.push(FRAG.gridPageNum.replace('#num#', i).replace('#active#', (pageCurrent == i ? ' active' : ''))) } that.$pagenum.empty() that.$pagenum = $(pageNums.join('')) that.$pagenum.insertAfter($prev) if (pageCurrent == 1) { pageFirst() if (pageCurrent == that.paging.pageCount) disableNext() } else if (pageCurrent == that.paging.pageCount) { pageLast() } else { enablePrev() enableNext() } $jumpto.find('input').val(pageCurrent) that.$btnpaging.find('> li.page-total > span').html(that.paging.total +'/'+ that.paging.pageCount) }) that.$selectpage.on('bjui.datagrid.paging.pageSize', function(e, pageSize) { setPageSize(pageSize) }) $jumpto.find('input').on('keyup', function(e) { if (e.which == BJUI.keyCode.ENTER) { var page = $(this).val() if (page) that.jumpPage(page) } }) $first.on('click', function() { if (that.paging.pageCurrent > 1) that.jumpPage(1) }) $prev.on('click', function() { if (that.paging.pageCurrent > 1) that.jumpPage(that.paging.pageCurrent - 1) }) $next.on('click', function() { if (that.paging.pageCurrent < that.paging.pageCount) that.jumpPage(that.paging.pageCurrent + 1) }) $last.on('click', function() { if (that.paging.pageCurrent < that.paging.pageCount) that.jumpPage(that.paging.pageCount) }) that.$refreshBtn.on('click', function() { that.refresh() }) that.$selectpage.on('change', function() { var pageSize = $(this).val() that.jumpPage(null, pageSize) }) } Datagrid.prototype.jumpPage = function(pageCurrent, pageSize) { var that = this, paging = that.paging, pageCount = paging.pageCount if (pageCurrent && isNaN(pageCurrent)) return if (pageSize && isNaN(pageSize)) return if (pageCurrent) { pageCurrent = parseInt(pageCurrent) if (pageCurrent < 1) pageCurrent = 1 if (pageCurrent > pageCount) pageCurrent = pageCount if (pageCurrent == paging.pageCurrent) return } if (pageSize) { pageSize = parseInt(pageSize) if (pageSize > paging.total) return } that.tools.jumpPage(pageCurrent, pageSize) } // api - add Datagrid.prototype.add = function(addLocation) { if (!this.tools.beforeEdit()) return if (!this.options.editUrl) { BJUI.debug('Datagrid Plugin: Edit url is not set!') return } if (!this.options.editMode) return if (!this.options.inlineEditMult) { this.doCancelEditRow(this.$tbody.find('> tr.'+ this.classnames.tr_edit)) } var that = this, options = that.options, tools = that.tools, paging = that.paging, trs, obj = {}, data = [], addObj, startNumber = (paging.pageCurrent - 1) * paging.pageSize, linenumber var addTr = function(linenumber) { var $tr = $('<tr></tr>').addClass(that.classnames.tr_add), $lockTr = $tr.clone() $.each(that.columnModel, function(i, n) { var label = '', $td = $('<td></td>') if (n.gridNumber) $td.addClass(that.classnames.td_linenumber).text(0) else if (n.gridCheckbox) $td.addClass(that.classnames.td_checkbox).html('<div><input type="checkbox" data-toggle="icheck" name="datagrid.checkbox" value="true"></div>') else if (n.gridEdit) $td.addClass(that.classnames.s_edit).data('isAdd', true).html(BJUI.doRegional(FRAG.gridEditBtn, that.regional)) else $td.text('') if (n.hidden) $td.css('display', 'none') if (n.align) $td.attr('align', n.align) obj[n.name] = '' if (n.locked) { $td.clone().show().appendTo($lockTr) $td.hide().appendTo($tr) } else { $td.appendTo($tr) } }) obj = $.extend({}, that.attach, obj) if (!that.emptyData) that.emptyData = obj return {tr:$tr, lockTr:$lockTr.find('> td').length ? $lockTr : null} } if (!addLocation) addLocation = options.addLocation || 'first' if (!that.$lastSelect) { if (addLocation == 'prev') addLocation = 'first' else if (addLocation == 'next') addLocation = 'last' } if (addLocation == 'first') { linenumber = 0 trs = addTr(linenumber) trs.tr.prependTo(that.$tbody) if (trs.lockTr) trs.lockTr.prependTo(that.$lockTbody) } else if (addLocation == 'last') { linenumber = that.data ? that.data.length : 0 trs = addTr(linenumber) trs.tr.appendTo(that.$tbody) if (trs.lockTr) trs.lockTr.appendTo(that.$lockTbody) } else if (addLocation == 'prev') { linenumber = that.$lastSelect.index() trs = addTr(linenumber) trs.tr.insertBefore(that.$lastSelect) if (trs.lockTr) trs.lockTr.insertBefore(that.$lockTbody.find('> tr:eq('+ that.$lastSelect.index() +')')) } else if (addLocation == 'next') { linenumber = that.$lastSelect.index() + 1 trs = addTr(linenumber) trs.tr.insertAfter(that.$lastSelect) if (trs.lockTr) trs.lockTr.insertAfter(that.$lockTbody.find('> tr:eq('+ that.$lastSelect.index() +')')) } var addData = $.extend({}, that.emptyData, {addFlag:true}) if (!that.data) that.data = [] if (!that.allData) that.allData = [] if (that.allData.length) { that.allData.splice(linenumber + startNumber, 0, addData) } else { that.allData.push(addData) } if (that.data.length) { that.data.splice(linenumber, 0, addData) } else { that.data.push(addData) } $.each(that.data, function(i, data) { var linenumber = options.linenumberAll ? (startNumber + (i + 1)) : (i + 1) $.extend(data, {gridNumber:linenumber, gridIndex:i}) }) trs.tr.initui() setTimeout(function() { that.initEvents(trs.tr) }, 20) if (trs.lockTr) that.initLockEvents(trs.lockTr) that.edit(trs.tr) if (options.editMode != 'dialog') { that.doEditRow(trs.tr, 'inline', true) } else { that.dialogEdit(trs.tr, true) } } // edit Datagrid.prototype.edit = function($trs) { var that = this, options = that.options, tools = that.tools, type = options.editMode, columnModel = that.columnModel, $editTd if (type != 'dialog') type = 'inline' if (!$trs) $trs = that.$tbody.find('> tr') $editTd = $trs.find('> td.'+ that.classnames.s_edit) /* events */ $editTd.each(function() { var $td = $(this), $btns = $td.find('button'), $edit = $btns.first(), $update = $edit.next(), $save = $update.next(), $cancel = $save.next(), $delete = $cancel.next() $edit.on('click', function(e, data) { var $btn = $(this), $tr = $btn.closest('tr'), isAdd = $td.data('isAdd') if (!data) { if (that.isDom) data = $tr.data('initData') || tools.setDomData($tr) else data = that.data[$tr.index()] } if (!tools.beforeEdit($tr, data)) { return false } if (type != 'dialog') { that.inlineEdit($tr, isAdd) $btns.hide() $update.show() $cancel.show() if (isAdd) { $update.hide() $save.show() } } else { that.dialogEdit($tr, isAdd) } e.stopPropagation() }) $save.on('click', function(e) { var $btn = $(this), $tr = $btn.closest('tr') that.updateEdit($tr, $btn) e.stopPropagation() }).on('bjui.datagrid.update.tr', function() { $btns.hide() $edit.show() $delete.show() }) $update.on('click', function(e) { var $btn = $(this), $tr = $btn.closest('tr') that.updateEdit($tr, $btn) e.stopPropagation() }).on('bjui.datagrid.update.tr', function() { $btns.hide() $edit.show() $delete.show() }) $cancel.on('click', function(e) { var $btn = $(this), $tr = $btn.closest('tr') that.cancelEdit($tr) $btns.hide() $edit.show() $delete.show() e.stopPropagation() }) $delete.on('click', function(e) { var $btn = $(this), $tr = $btn.closest('tr') that.delRows($tr) e.stopPropagation() }) }) } // Api - inline edit tr Datagrid.prototype.doEditRow = function(rows, type, isAdd) { var that = this, $trs, $editBtn, datas = [] type = type || that.options.editMode if (typeof rows == 'object') { $trs = rows } else if (isNaN(rows)) { var $myTrs = that.$tbody.find('> tr'), $editTrs, rows = rows.split(',') rows = rows.unique() rows.sort(function(a, b) {return a.trim() - b.trim()}) $.each(rows, function(i, n) { var tr = $myTrs.eq(parseInt(n.trim())) if (tr && tr.length) { if (!$editTrs) $editTrs = tr else $editTrs = $editTrs.add(tr) } }) $trs = $editTrs } else if (!isNaN(rows)) { $trs = that.$tbody.find('> tr').eq(rows) } if (!$trs.length) return $trs.each(function() { var $tr = $(this), tr_index = $tr.index(), data if (that.isDom) data = $tr.data('initData') || tools.setDomData($tr) else data = that.data[tr_index] datas.push(data) }) if (!that.tools.beforeEdit($trs, datas)) { return } if (!that.options.editUrl) { BJUI.debug('Datagrid Plugin: Edit url is not set!') return } $trs.each(function(i) { var $tr = $(this) $editBtn = $tr.find('> td.'+ that.classnames.s_edit +' > button.edit') if (type != 'dialog') { if ($editBtn.length) $editBtn.trigger('click', [datas[i]]) else that.inlineEdit($tr, isAdd, datas[i]) } else { that.dialogEdit($tr, isAdd, datas[i]) } }) } // Api - cancel edit Datagrid.prototype.doCancelEditRow = function(row) { var that = this, $trs if ($.type(row) == 'number') { $trs = this.$tbody.find('> tr').eq(row) } else { $trs = row } $trs.each(function() { var $tr = $(this), $cancelBtn = $tr.find('> td.'+ that.classnames.s_edit +' > button.cancel') if ($cancelBtn.length) { $cancelBtn.trigger('click') } else { that.cancelEdit($tr) } }) } // Api - save edit tr Datagrid.prototype.doSaveEditRow = function(row) { var that = this, options = that.options, $tr if ($.type(row) == 'number') { $tr = this.$tbody.find('> tr').eq(row) } else if (row) { $tr = row } else { $tr = that.$tbody.find('> tr.'+ that.classnames.tr_edit) } if (!$tr.length) { that.$grid.alertmsg('info', BJUI.getRegional('datagrid.saveMsg')) } if ($tr.length == 1) { if ($tr.hasClass(that.classnames.tr_edit)) this.updateEdit($tr) } else { if (options.saveAll) { that.saveAll($tr) } else { $tr.each(function() { that.updateEdit($(this)) }) } } } // Api - del tr Datagrid.prototype.delRows = function(rows) { var that = this, options = that.options, beforeDelete = options.beforeDelete, confirmMsg = options.delConfirm, $trs if (beforeDelete) { if (typeof beforeDelete == 'string') beforeDelete = beforeDelete.toFunc() if (typeof beforeDelete == 'function') { if (!beforeDelete.call(this)) { return } } } if (typeof rows == 'object') { $trs = rows } else if (isNaN(rows)) { var $myTrs = that.$tbody.find('> tr'), $delTrs, rows = rows.split(',') rows = rows.unique() rows.sort(function(a, b) {return a.trim() - b.trim()}) $.each(rows, function(i, n) { var tr = $myTrs.eq(parseInt(n.trim())) if (tr && tr.length) { if (!$delTrs) $delTrs = tr else $delTrs = $delTrs.add(tr) } }) $trs = $delTrs } else if (!isNaN(rows)) { $trs = this.$tbody.find('> tr').eq(rows) } if (!$trs || !$trs.length) return var delEnd = function() { $trs.each(function() { $(this).trigger('bjui.datagrid.tr.delete') }) that.tools.afterDelete() } var doDel = function() { var $addTrs = $trs.filter('.'+ that.classnames.tr_add) if ($addTrs.length) { $addTrs.remove() if ($addTrs.length == $trs.length) return } // remote delete if (options.delUrl) { var postData = [], callback = options.delCallback $trs.each(function() { var $tr = $(this), index = $tr.index(), data, delData if (that.isDom) data = $tr.data('initData') || tools.setDomData($tr) else data = that.data[index] if (options.delPK) { postData.push(data[options.delPK]) } else { if (options.jsonPrefix) { delData = {} $.each(data, function(name, value) { if (name == 'gridCheckbox' || name == 'gridEdit') return true delData[options.jsonPrefix +'.'+ name] = value }) } else { delData = $.extend({}, data) delete delData.gridCheckbox delete delData.gridEdit } postData.push(delData) } }) if (typeof callback == 'string') callback = callback.toFunc() that.$grid.bjuiajax('doAjax', { url : options.delUrl, data : options.delPK ? [{ name:options.delPK, value:postData.join(',') }] : {json : JSON.stringify(postData)}, type : options.delType, callback : callback || function(json) { if (json[BJUI.keys.statusCode] == BJUI.statusCode.ok) { delEnd() } else { that.$grid.bjuiajax('ajaxDone', json) } } }) } else { // local delete delEnd() } } if (confirmMsg) { if (typeof confirmMsg != 'string') confirmMsg = $trs.length == 1 ? BJUI.getRegional('datagrid.delMsg') : BJUI.getRegional('datagrid.delMsgM') that.$grid.alertmsg('confirm', confirmMsg, { okCall:function() { doDel() } }) } else { doDel() } } // inline edit Datagrid.prototype.inlineEdit = function($tr, isAdd, data) { if (!this.tools.beforeEdit($tr, data)) { return false } var that = this, options = that.options, tools = that.tools, columnModel = that.columnModel, $tds = $tr.find('> td'), tds_length = $tds.length, tr_index = $tr.index() if (!data) { if (that.isDom) data = $tr.data('initData') || tools.setDomData($tr) else data = that.data[tr_index] } if ($tr.hasClass(that.classnames.tr_edit)) return false if (!that.inputs || !that.inputs.length) tools.initEditInputs() $tr.addClass(that.classnames.tr_edit).data(that.datanames.changeData, {}) if ($tr.data('validator')) $tr.validator('destroy') //remove old validate if (!options.inlineEditMult) { that.doCancelEditRow($tr.siblings('.'+ that.classnames.tr_edit)) } that.$lastEditTr = $tr $tds.each(function(i) { var $td = $(this), op = columnModel[i], val = op && op.name && data[op.name], html = $td.html(), input = that.inputs[i], $input var onChange = function($el, $td, val) { var changeData = $tr.data(that.datanames.changeData) switch (op.type) { case 'date': $el .on('afterchange.bjui.datepicker', function(e, data) { $td.addClass(that.classnames.td_changed) if ($el.val() == val) $td.removeClass(that.classnames.td_changed) changeData[op.name] = $el.val() }) .change(function() { $td.addClass(that.classnames.td_changed) if ($el.val() == val) $td.removeClass(that.classnames.td_changed) changeData[op.name] = $el.val() }) break case 'select': $el.change(function() { $td.addClass(that.classnames.td_changed) if ($el.val() == String(val)) $td.removeClass(that.classnames.td_changed) changeData[op.name] = $el.val() }) break case 'boolean': $el.on('ifChanged', function() { $td.toggleClass(that.classnames.td_changed) var checked = $(this).is(':checked') ? true : false if (checked == val) $td.removeClass(that.classnames.td_changed) changeData[op.name] = checked }) break case 'lookup': $td.on('customEvent.bjui.lookup', '[data-toggle="lookupbtn"]', function(e, args) { $td.toggleClass(that.classnames.td_changed) for (var key in args) { if (typeof data[key] != 'undefined') { changeData[key] = args[key] } if (op.name == key) { if ($el.val() == args[key]) $td.removeClass(that.classnames.td_changed) else $el.val(args[key]) } } }) $el.change(function() { $td.addClass(that.classnames.td_changed) if ($el.val() == val) $td.removeClass(that.classnames.td_changed) changeData[op.name] = $el.val() }) break case 'spinner': $el .on('afterchange.bjui.spinner', function(e, data) { $td.addClass(that.classnames.td_changed) if ($el.val() == val) $td.removeClass(that.classnames.td_changed) changeData[op.name] = $el.val() }) .change(function() { $td.addClass(that.classnames.td_changed) if ($el.val() == val) $td.removeClass(that.classnames.td_changed) changeData[op.name] = $el.val() }) break default: $el.change(function() { $td.addClass(that.classnames.td_changed) if ($el.val() == val) $td.removeClass(that.classnames.td_changed) changeData[op.name] = $el.val() }) break } } $td.data(that.datanames.td_html, html) if (isAdd) { if (!op.add) input = '' } else { if (!op.edit) input = '' } if (input) { $input = $(input) if (op.type == 'boolean') $input.prop('checked', val) else { if (!val || val == 'null') val = '' $input.val(String(val)) } if (isAdd) { if (op.addAttrs && typeof op.addAttrs == 'object') { $.each(op.addAttrs, function(i, n) { $input.attr(i, n) }) } } else { if (op.editAttrs && typeof op.editAttrs == 'object') { $.each(op.editAttrs, function(i, n) { $input.attr(i, n) }) } } $td .empty() .append($input) .addClass(that.classnames.td_edit) onChange($input, $td, val) if (op.locked) { var $lockTr = that.$lockTbody.find('tr:eq('+ tr_index +')') var $lockTd = $lockTr.find('> td:eq('+ op.lockIndex +')') $td.clone().html(html).insertAfter($td) $td.show().insertAfter($lockTd).initui() $lockTd.remove() } } if (!--tds_length) { $tr .initui() .validator({ msgClass : 'n-bottom', theme : 'red_bottom_effect_grid' }) } }) } Datagrid.prototype.saveAll = function($trs) { var that = this, options = that.options, callback = options.editCallback, $tr, data, changeData, tempData, postData = [], len = $trs && $trs.length if (!$trs || $trs.length) { $trs = that.$tbody.find('> tr.'+ that.classnames.tr_edit) len = $trs.length } $trs.each(function() { $tr = $(this), data = that.isDom ? $tr.data('initData') : that.data[$tr.index()] $tr.isValid(function(v) { if (v) { // Update data changeData = $tr.data(that.datanames.changeData) $.extend(data, changeData) // Specification post data if (options.jsonPrefix) { tempData = {} $.each(data, function(name, value) { if (name == 'gridCheckbox' || name == 'gridEdit') return true tempData[options.jsonPrefix +'.'+ name] = value }) } else { tempData = $.extend({}, data) delete tempData.gridCheckbox delete tempData.gridEdit } len -- postData.push(tempData) } else { postData = [] return false } }) }) // do save if (!len) { // Callback if (callback) { callback = callback.toFunc() } else { callback = function(json) { var complete = false, returnData = [] if ($.type(json) == 'array') { complete = true returnData = json } else if ($.type(json) == 'object') { if (json[BJUI.keys.statusCode]) { if (json[BJUI.keys.statusCode] == BJUI.statusCode.ok) { complete = true } else { that.$grid.bjuiajax('ajaxDone', json) } } else { complete = true returnData.push(json) } } if (complete) { $trs.each(function(i) { var $tr = $(this), data = that.isDom ? $tr.data('initData') : that.data[$tr.index()] $.extend(data, typeof returnData[i] == 'object' && returnData[i]) that.inlineEditComplete($tr, data) }) that.tools.afterSave($trs, postData) } } } // Do ajax that.$grid.bjuiajax('doAjax', {url:options.editUrl, data:{json:JSON.stringify(postData)}, type:'POST', callback:callback}) } } // update - inline edit Datagrid.prototype.updateEdit = function($tr, $btn) { var that = this, options = that.options, callback = options.editCallback, data, changeData, tempData, postData = [] if (that.isDom) data = $tr.data('initData') else data = that.data[$tr.index()] if ($tr.hasClass(that.classnames.tr_edit)) { // validate $tr.isValid(function(v) { if (v) { // Update data changeData = $tr.data(that.datanames.changeData) $.extend(data, changeData) // Specification post data if (options.jsonPrefix) { tempData = {} $.each(data, function(name, value) { if (name == 'gridCheckbox' || name == 'gridEdit') return true tempData[options.jsonPrefix +'.'+ name] = value }) } else { tempData = $.extend({}, data) delete tempData.gridCheckbox delete tempData.gridEdit } // Callback if (callback) { callback = callback.toFunc() } else { callback = function(json) { var complete = false, returnData if ($.type(json) == 'array') { complete = true returnData = json[0] } else if ($.type(json) == 'object') { if (json[BJUI.keys.statusCode]) { if (json[BJUI.keys.statusCode] == BJUI.statusCode.ok) { complete = true } else { that.$grid.bjuiajax('ajaxDone', json) } } else { complete = true returnData = json } } if (complete) { $.extend(data, typeof returnData == 'object' && returnData) that.inlineEditComplete($tr, data, $btn) that.tools.afterSave($tr, data) } } } // Do ajax $tr.bjuiajax('doAjax', {url:options.editUrl, data:{json:JSON.stringify(postData.push(tempData) && postData)}, type:'POST', callback:callback}) } }) } } /* cancel - inline edit */ Datagrid.prototype.cancelEdit = function($trs) { var that = this, columnModel = that.columnModel $trs.each(function() { var $tr = $(this), tr_index = $tr.index() if ($tr.hasClass(that.classnames.tr_edit)) { $tr .removeClass(that.classnames.tr_edit) .find('> td.'+ that.classnames.td_edit).each(function() { var $td = $(this), td_index = $td.index(), model = columnModel[td_index], html = $td.data(that.datanames.td_html) $td.removeClass(that.classnames.td_edit).removeClass(that.classnames.td_changed).html(html) if (model.locked) { var $lockTr = that.$lockTbody.find('tr:eq('+ tr_index +')') var $lockTd = $lockTr.find('> td:eq('+ model.lockIndex +')') html = $lockTd.data(that.datanames.td_html) $lockTr.removeClass(that.classnames.tr_edit) $lockTd.removeClass(that.classnames.td_edit).removeClass(that.classnames.td_changed).html(html) } }) } if ($tr.hasClass(that.classnames.tr_add)) { var isRemove = false, changeData = $tr.data(that.datanames.changeData) if ($.isEmptyObject(changeData)) { isRemove = true } else { for (var key in changeData) { if (!changeData[key]) delete changeData[key] } if ($.isEmptyObject(changeData)) isRemove = true } if (isRemove) { var index = $tr.index() that.data = that.data.remove(index) that.$lockTbody && that.$lockTbody.find('> tr:eq('+ index +')').remove() $tr.remove() } } }) } // inline editComplete Datagrid.prototype.inlineEditComplete = function($tr, trData, $btn) { var that = this, columnModel = that.columnModel, tr_index = $tr.index(), $tds = $tr.find('> td'), hasLinenumber = false, $trs = that.$tbody.find('> tr'), $addTrs = $trs.filter('.'+ that.classnames.tr_add) $.each(columnModel, function(i, n) { if (n.gridNumber) hasLinenumber = true if (!n.name) return if (n.gridNumber || n.gridCheckbox || n.gridEdit) return var label = trData[n.name], render_label, $td = $tds.eq(n.index) if (typeof label == 'undefined') label = '' $td.text(label).removeClass(that.classnames.td_edit).removeClass(that.classnames.td_changed) if (n.render && typeof n.render == 'function') { if (n.items) { render_label = n.render.call(that, label, n.items) $td.html(render_label) } else { render_label = n.render.call(that, label) $td.html(render_label) } } else if (n.items) { render_label = Datagrid.renderItem.call(that, label, n.items) $td.html(render_label) } if (n.locked) { var $lockTr = that.$lockTbody.find('> tr:eq('+ tr_index +')'), $lockTd = $lockTr.find('> td:eq('+ n.lockIndex +')') $lockTd.removeClass(that.classnames.td_changed).html($td.html()) } }) $tr.removeClass(that.classnames.tr_edit) if (!$btn) $btn = $tds.filter('.'+ that.classnames.s_edit).find('button.update') if ($btn && $btn.length) $btn.trigger('bjui.datagrid.update.tr') if (hasLinenumber && $addTrs.length) { $addTrs.removeClass(that.classnames.tr_add) $trs.each(function(index) { $(this).find('> td.'+ that.classnames.td_linenumber).text(index + 1) that.$lockTbody && that.$lockTbody.find('> tr:eq('+ index +')').find('> td.'+ that.classnames.td_linenumber).text(index + 1) }) } } // inline edit Datagrid.prototype.dialogEdit = function($tr, isAdd, data) { if (!this.tools.beforeEdit($tr, data)) { return false } var that = this, options = that.options, tools = that.tools, columnModel = that.columnModel, tr_index = $tr.index(), $dialog, $form, html = '', title if (!data) { if (that.isDom) data = $tr.data('initData') || tools.setDomData($tr) else data = that.data[tr_index] } if (!that.inputs || !that.inputs.length) tools.initEditInputs() title = options.gridTitle || 'datagrid' if (isAdd) { title += ' - '+ BJUI.getRegional('datagrid.add') } else { title += ' - '+ BJUI.getRegional('datagrid.edit') } $dialog = $('<div><div class="bjui-pageContent"></div><div class="bjui-pageFooter"></div></div>') $form = $('<form class="datagrid-dialog-edit-form"></form>') var onChange = function($tr, $form, $el, model) { var changeData = $tr.data(that.datanames.changeData) switch (model.type) { case 'date': $el .on('afterchange.bjui.datepicker', function(e, data) { changeData[model.name] = $el.val() }) .change(function() { changeData[model.name] = $el.val() }) break case 'select': $el.change(function() { changeData[model.name] = $el.val() }) break case 'boolean': $el.on('ifChanged', function() { var checked = $(this).is(':checked') ? true : false changeData[model.name] = checked }) break case 'lookup': $form.on('customEvent.bjui.lookup', '[data-toggle="lookupbtn"]', function(e, args) { for (var key in args) { if (typeof data[key] != 'undefined') { changeData[key] = args[key] } if (model.name == key) { $el.val(args[key]) } } }) $el.change(function() { changeData[model.name] = $el.val() }) break case 'spinner': $el .on('afterchange.bjui.spinner', function(e, data) { changeData[model.name] = $el.val() }) .change(function() { changeData[model.name] = $el.val() }) break default: $el.change(function() { changeData[model.name] = $el.val() }) break } } var onLoad = function($dialog) { var $form = $dialog.find('form.datagrid-dialog-edit-form'), $btns = $dialog.find('div.bjui-pageFooter button'), $prev = $btns.first(), $next = $btns.eq(1), $cancel = $btns.eq(2), $save = $btns.last() var createForm = function(data, $form, $tr) { $form.empty() if (!$tr.data(that.datanames.changeData)) $tr.data(that.datanames.changeData, {}) if ($form.data('validator')) $form.validator('destroy') $.each(columnModel, function(i, n) { if (n == that.linenumberColumn || n == that.checkboxColumn || n == that.editBtnsColumn) return true var $input = $(that.inputs[i]), $p = $('<p></p>'), id = 'datagrid-dialog-edit-column-'+ i if ($input.isTag('select')) $input.attr('data-width', 'auto') else if (!$input.isTag('checkbox')) $input.attr('size', 30) if (n.type == 'boolean') { $input.attr('checked', data[n.name]) } else if (n.type == 'textarea') { $input.html(data[n.name]) } else { $input.attr('value', data[n.name]) } $p .append('<label class="control-label x120" for="'+ id +'">'+ n.label +':</label>') .append($('<span class="datagrid-dialog-column-span"></span>').append($input.attr('id', id))) .appendTo($form) onChange($tr, $form, $input, n) }) $form .initui() .validator({ msgClass : 'n-bottom', theme : 'red_bottom_effect_grid' }) } if ($form.is(':empty')) createForm(data, $form, $tr) if ($tr.index() == 0) $prev.addClass('disabled') if ($tr.index() == that.data.length - 1) $next.addClass('disabled') $prev.click(function() { var $tr_prev = $tr.prev(), data if ($tr_prev.length) { if (that.isDom) { data = $tr_prev.data('initData') || tools.setDomData($tr_prev) } else { data = that.data[$tr_prev.index()] } $tr = $tr_prev createForm(data, $form, $tr) $next.removeClass('disabled') if (!$tr_prev.prev().length) $prev.addClass('disabled') } else { $prev.addClass('disabled') } }) $next.click(function() { var $tr_next = $tr.next(), data if ($tr_next.length) { if (that.isDom) { data = $tr_next.data('initData') || tools.setDomData($tr_next) } else { data = that.data[$tr_next.index()] } $tr = $tr_next createForm(data, $form, $tr) $form.initui() $prev.removeClass('disabled') if (!$tr_next.next().length) $next.addClass('disabled') } else { $next.addClass('disabled') } }) $save.click(function() { var changeData, data, postData, callback = options.editCallback if (that.isDom) data = $tr.data('initData') else data = that.data[$tr.index()] $form.isValid(function(v) { if (v) { changeData = $tr.data(that.datanames.changeData) $.extend(data, changeData) if (options.jsonPrefix) { postData = {} $.each(data, function(name, value) { if (name == 'gridCheckbox' || name == 'gridEdit') return true postData[options.jsonPrefix +'.'+ name] = value }) } else { postData = $.extend({}, data) delete postData.gridCheckbox delete postData.gridEdit } // Callback if (callback) { callback = callback.toFunc() } else { callback = function(json) { var complete = false, returnData if ($.type(json) == 'array') { complete = true returnData = json[0] } else if ($.type(json) == 'object') { if (json[BJUI.keys.statusCode]) { if (json[BJUI.keys.statusCode] == BJUI.statusCode.ok) { complete = true } else { that.$grid.bjuiajax('ajaxDone', json) } } else { complete = true returnData = json } } if (complete) { $.extend(data, typeof returnData == 'object' && returnData) that.dialogEditComplete($tr, data) that.$grid.dialog('close', 'datagrid-dialog-edit') that.tools.afterSave($tr, data) } } } // Do ajax $tr.bjuiajax('doAjax', {url:options.editUrl, data:{json:JSON.stringify(postData)}, type:'POST', callback:callback}) } }) }) $cancel.click(function() { that.$grid.dialog('close', 'datagrid-dialog-edit') }) } var onClose = function() { that.$tbody.find('> tr.'+ that.classnames.tr_add).each(function() { var isRemove = false, $tr = $(this), changeData = $tr.data(that.datanames.changeData) if ($.isEmptyObject(changeData)) { isRemove = true } else { for (var key in changeData) { if (!changeData[key]) delete changeData[key] } if ($.isEmptyObject(changeData)) isRemove = true } if (isRemove) { var index = $tr.index() that.data = that.data.remove(index) that.$lockTbody && that.$lockTbody.find('> tr:eq('+ index +')').remove() $tr.remove() } }) } $dialog.find('> div:first') .append($form) .next().append(BJUI.doRegional(FRAG.gridDialogEditBtns, that.regional)) var dialog_options = $.extend({}, {id:'datagrid-dialog-edit', fresh:true, target:$dialog[0], width:520, height:400, mask:true, title:title, onLoad:onLoad, onClose:onClose}, (typeof options.editDialogOp == 'object' && options.editDialogOp)) that.$grid.dialog(dialog_options) } // dialog editComplete Datagrid.prototype.dialogEditComplete = function($tr, trData) { var that = this, columnModel = that.columnModel, tr_index = $tr.index(), $tds = $tr.find('> td'), hasLinenumber = false, $trs = that.$tbody.find('> tr'), $addTrs = $trs.filter('.'+ that.classnames.tr_add) $.each(columnModel, function(i, n) { if (n.gridNumber) hasLinenumber = true if (!n.name) return if (n.gridNumber || n.gridCheckbox || n.gridEdit) return var label = trData[n.name], render_label, $td = $tds.eq(n.index) if (typeof label == 'undefined') label = '' $td.text(label).removeClass(that.classnames.td_edit).removeClass(that.classnames.td_changed) if (n.render && typeof n.render == 'function') { if (n.items) { render_label = n.render.call(that, label, n.items) $td.html(render_label) } else { render_label = n.render.call(that, label) $td.html(render_label) } } else if (n.items) { render_label = Datagrid.renderItem.call(that, label, n.items) $td.html(render_label) } if (n.locked) { var $lockTr = that.$lockTbody.find('> tr:eq('+ tr_index +')'), $lockTd = $lockTr.find('> td:eq('+ n.lockIndex +')') $lockTd.removeClass(that.classnames.td_edit).removeClass(that.classnames.td_changed).html($td.html()) $lockTr.removeClass(that.classnames.tr_edit) } }) if (hasLinenumber && $addTrs.length) { $addTrs.removeClass(that.classnames.tr_add) $trs.each(function(index) { $(this).find('> td.'+ that.classnames.td_linenumber).text(index + 1) that.$lockTbody && that.$lockTbody.find('> tr:eq('+ index +')').find('> td.'+ that.classnames.td_linenumber).text(index + 1) }) } } /* resize */ Datagrid.prototype.resizeGrid = function() { var that = this, $target = that.$grid.getPageTarget(), parentW, parentH var _resizeGrid = function() { if (that.initFixedW && String(that.options.width).endsWith('%')) { parentW = that.$grid.parent().width() if ($target.is(':hidden') && $target.hasClass('navtabPage')) { that.$grid.data('need.fixedW', true) } else { that.fixedWidth() } } if (String(that.options.height).endsWith('%')) { parentH = that.$grid.parent().height() if ($target.is(':hidden') && $target.hasClass('navtabPage')) { if ($target.hasClass('navtabPage')) { that.$grid.data('need.fixedH', true) } } else if (parentH) { if (parentH != that.parentH) that.tools.fixedH(parentH) } } } $target.on('bjui.navtab.switch', $.proxy(function() { if (that.$grid.data('need.fixedH')) { parentH = that.$grid.parent().height() if (parentH) that.tools.fixedH(parentH) that.$grid.removeData('need.fixedH') } if (that.$grid.data('need.fixedW')) { that.fixedWidth() that.$grid.removeData('need.fixedW') } }, that)) $(window).on(BJUI.eventType.resizeGrid, $.proxy(_resizeGrid, that)) } // DATAGRID PLUGIN DEFINITION // ======================= function Plugin(option) { var args = arguments var property = option return this.each(function () { var $this = $(this) var options = $.extend({}, Datagrid.DEFAULTS, $this.data(), typeof option == 'object' && option) var data = $this.data('bjui.datagrid') if (!data) $this.data('bjui.datagrid', (data = new Datagrid(this, options))) if (typeof property == 'string' && $.isFunction(data[property])) { [].shift.apply(args) if (!args) data[property]() else data[property].apply(data, args) } else { data.init() } }) } var old = $.fn.datagrid $.fn.datagrid = Plugin //$.fn.datagrid.Constructor = Datagrid $.datagrid = Datagrid // DATAGRID NO CONFLICT // ================= $.fn.datagrid.noConflict = function () { $.fn.datagrid = old return this } // DATAGRID DATA-API // ============== $(document).on(BJUI.eventType.initUI, function(e) { var $this = $(e.target).find('table[data-toggle="datagrid"]') if (!$this.length) return Plugin.call($this) }) }(jQuery);
{ "content_hash": "babb27a90a439debf240ad124ecbb7f3", "timestamp": "", "source": "github", "line_count": 4431, "max_line_length": 304, "avg_line_length": 45.51658767772512, "alnum_prop": 0.41339917891354794, "repo_name": "ianding/vote", "id": "ae1c402e23dbe99ab6014bab3d47240a553380dc", "size": "201891", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "backend/web/bjui/BJUI/js/bjui-datagrid.js", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "ApacheConf", "bytes": "450" }, { "name": "Batchfile", "bytes": "1541" }, { "name": "CSS", "bytes": "271496" }, { "name": "HTML", "bytes": "12111" }, { "name": "JavaScript", "bytes": "1784253" }, { "name": "PHP", "bytes": "247197" }, { "name": "Smarty", "bytes": "4168" } ], "symlink_target": "" }
<head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width initial-scale=1" /> <meta http-equiv="X-UA-Compatible" content="IE=edge"> {% if page.robots %} <meta name="robots" content="{{ page.robots }}"> {% endif %} <title>{% if page.title %}{{ site.title }} | {{ page.title }}{% else %}{{ site.title }}{% endif %}</title> <meta name="description" content="{% if page.excerpt %}{{ page.excerpt | strip_html }}{% else %}{{ site.description }}{% endif %}"> <meta name="author" content="{{ site.author.name }}"> <meta name="HandheldFriendly" content="True"> <meta name="MobileOptimized" content="320"> <meta name="apple-mobile-web-app-capable" content="yes"> <meta name="apple-mobile-web-app-status-bar-style" content="black-translucent"> <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"> <meta name="twitter:card" content="summary"> <meta name="twitter:title" content="{% if page.title %}{{ page.title }}{% else %}{{ site.title }}{% endif %}"> <meta name="twitter:description" content="{% if page.excerpt %}{{ page.excerpt | strip_html }}{% else %}{{ site.description | strip_html}}{% endif %}"> {% if site.author.twitter_username %} <meta name="twitter:creator" content="{{ site.author.twitter_username }}"> {% endif %} <meta name="twitter:image" content="{{ site.baseurl }}/images/favicons/android-icon-192x192.png" /> <meta property="og:type" content="article"> <meta property="og:title" content="{% if page.title %}{{ page.title }}{% else %}{{ site.title }}{% endif %}"> <meta property="og:description" content="{% if page.excerpt %}{{ page.excerpt | strip_html }}{% else %}{{ site.description }}{% endif %}"> <meta property="og:image" content="{{ site.baseurl }}/images/favicons/android-icon-192x192.png" /> <link rel="apple-touch-icon" sizes="57x57" href="{{ site.baseurl }}/images/favicons/apple-icon-57x57.png"> <link rel="apple-touch-icon" sizes="60x60" href="{{ site.baseurl }}/images/favicons/apple-icon-60x60.png"> <link rel="apple-touch-icon" sizes="72x72" href="{{ site.baseurl }}/images/favicons/apple-icon-72x72.png"> <link rel="apple-touch-icon" sizes="76x76" href="{{ site.baseurl }}/images/favicons/apple-icon-76x76.png"> <link rel="apple-touch-icon" sizes="114x114" href="{{ site.baseurl }}/images/favicons/apple-icon-114x114.png"> <link rel="apple-touch-icon" sizes="120x120" href="{{ site.baseurl }}/images/favicons/apple-icon-120x120.png"> <link rel="apple-touch-icon" sizes="144x144" href="{{ site.baseurl }}/images/favicons/apple-icon-144x144.png"> <link rel="apple-touch-icon" sizes="152x152" href="{{ site.baseurl }}/images/favicons/apple-icon-152x152.png"> <link rel="apple-touch-icon" sizes="180x180" href="{{ site.baseurl }}/images/favicons/apple-icon-180x180.png"> <link rel="icon" type="image/png" sizes="192x192" href="{{ site.baseurl }}/images/favicons/android-icon-192x192.png"> <link rel="icon" type="image/png" sizes="32x32" href="{{ site.baseurl }}/images/favicons/favicon-32x32.png"> <link rel="icon" type="image/png" sizes="96x96" href="{{ site.baseurl }}/images/favicons/favicon-96x96.png"> <link rel="icon" type="image/png" sizes="16x16" href="{{ site.baseurl }}/images/favicons/favicon-16x16.png"> <link rel="manifest" href="{{ site.baseurl }}/images/favicons/manifest.json"> <meta name="msapplication-TileColor" content="#ffffff"> <meta name="msapplication-TileImage" content="{{ site.baseurl }}/images/ms-icon-144x144.png"> <meta name="theme-color" content="#ffffff"> <link rel="stylesheet" href="{{ site.baseurl }}/css/main.css?{{site.time | date: '%s%N'}}"> <link rel="canonical" href="{% if page.canonical %}{{ page.canonical }}{% else %}{{ page.url | replace:'index.html','' | prepend: site.baseurl | prepend: site.url }}{% endif %}"> <link rel="alternate" type="application/rss+xml" title="{{ site.title }}" href="{{ site.baseurl }}/feed.xml"> <!-- Google verification --> {% if site.google_verify %}<meta name="google-site-verification" content="{{ site.google_verify }}">{% endif %} <!-- Bing Verification --> {% if site.bing_verify %}<meta name="msvalidate.01" content="{{ site.bing_verify }}">{% endif %} <!-- Alexa Verification --> {% if site.alexa_verify %}<meta name="alexaVerifyID" content="{{ site.alexa_verify }}">{% endif %} <script type='text/javascript' src='//platform-api.sharethis.com/js/sharethis.js#property=5aba0c5fce89f00013641a4d&product=inline-share-buttons' async='async'></script> </head>
{ "content_hash": "e701ce0128e5a93dd12e263cfac91520", "timestamp": "", "source": "github", "line_count": 59, "max_line_length": 180, "avg_line_length": 76.72881355932203, "alnum_prop": 0.6730726750607466, "repo_name": "valix/valix.github.io", "id": "fcb915c9efbfd80d7c7802acce9d0ba76b7d50ee", "size": "4527", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "_includes/head.html", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "9489" }, { "name": "HTML", "bytes": "39795" }, { "name": "JavaScript", "bytes": "43925" }, { "name": "PHP", "bytes": "1224" } ], "symlink_target": "" }
package java.sql; import java.io.InputStream; import java.io.Reader; import java.math.BigDecimal; import java.net.URL; import java.util.Calendar; import java.util.Map; /** * This interface provides access to the data set returned by a SQL * statement. An instance of this interface is returned by the various * execution methods in the <code>Statement</code>. * * <p> This class models a cursor, which can be stepped through one row at a * time. Methods are provided for accessing columns by column name or by * index.</p> * * <p> Note that a result set is invalidated if the statement that returned * it is closed.</p> * * @author Aaron M. Renn ([email protected]) */ public interface ResultSet { /** * The rows will be processed in order from first to last. */ int FETCH_FORWARD = 1000; /** * The rows will be processed in order from last to first. */ int FETCH_REVERSE = 1001; /** * The rows will be processed in an unknown order */ int FETCH_UNKNOWN = 1002; /** * This type of result set may only step forward through the rows returned. */ int TYPE_FORWARD_ONLY = 1003; /** * This type of result set is scrollable and is not sensitive to changes * made by other statements. */ int TYPE_SCROLL_INSENSITIVE = 1004; /** * This type of result set is scrollable and is also sensitive to changes * made by other statements. */ int TYPE_SCROLL_SENSITIVE = 1005; /** * The concurrency mode of for the result set may not be modified. */ int CONCUR_READ_ONLY = 1007; /** * The concurrency mode of for the result set may be modified. */ int CONCUR_UPDATABLE = 1008; int HOLD_CURSORS_OVER_COMMIT = 1; int CLOSE_CURSORS_AT_COMMIT = 2; /** * This method advances to the next row in the result set. Any streams * open on the current row are closed automatically. * * @return <code>true</code> if the next row exists, <code>false</code> * otherwise. * @exception SQLException If an error occurs. */ boolean next() throws SQLException; /** * This method closes the result set and frees any associated resources. * * @exception SQLException If an error occurs. */ void close() throws SQLException; /** * This method tests whether the value of the last column that was fetched * was actually a SQL NULL value. * * @return <code>true</code> if the last column fetched was a NULL, * <code>false</code> otherwise. * @exception SQLException If an error occurs. */ boolean wasNull() throws SQLException; /** * This method returns the value of the specified column as a Java * <code>String</code>. * * @param columnIndex The index of the column to return. * @return The column value as a <code>String</code>. * @exception SQLException If an error occurs. */ String getString(int columnIndex) throws SQLException; /** * This method returns the value of the specified column as a Java * <code>boolean</code>. * * @param columnIndex The index of the column to return. * @return The column value as a <code>boolean</code>. * @exception SQLException If an error occurs. */ boolean getBoolean(int columnIndex) throws SQLException; /** * This method returns the value of the specified column as a Java * <code>byte</code>. * * @param columnIndex The index of the column to return. * @return The column value as a <code>byte</code>. * @exception SQLException If an error occurs. */ byte getByte(int columnIndex) throws SQLException; /** * This method returns the value of the specified column as a Java * <code>short</code>. * * @param columnIndex The index of the column to return. * @return The column value as a <code>short</code>. * @exception SQLException If an error occurs. */ short getShort(int columnIndex) throws SQLException; /** * This method returns the value of the specified column as a Java * <code>int</code>. * * @param columnIndex The index of the column to return. * @return The column value as a <code>int</code>. * @exception SQLException If an error occurs. */ int getInt(int columnIndex) throws SQLException; /** * This method returns the value of the specified column as a Java * <code>long</code>. * * @param columnIndex The index of the column to return. * @return The column value as a <code>long</code>. * @exception SQLException If an error occurs. */ long getLong(int columnIndex) throws SQLException; /** * This method returns the value of the specified column as a Java * <code>float</code>. * * @param columnIndex The index of the column to return. * @return The column value as a <code>float</code>. * @exception SQLException If an error occurs. */ float getFloat(int columnIndex) throws SQLException; /** * This method returns the value of the specified column as a Java * <code>double</code>. * * @param columnIndex The index of the column to return. * @return The column value as a <code>double</code>. * @exception SQLException If an error occurs. */ double getDouble(int columnIndex) throws SQLException; /** * This method returns the value of the specified column as a Java * <code>BigDecimal</code>. * * @param columnIndex The index of the column to return. * @param scale The number of digits to the right of the decimal to return. * @return The column value as a <code>BigDecimal</code>. * @exception SQLException If an error occurs. * @deprecated */ BigDecimal getBigDecimal(int columnIndex, int scale) throws SQLException; /** * This method returns the value of the specified column as a Java * byte array. * * @param columnIndex The index of the column to return. * @return The column value as a byte array * @exception SQLException If an error occurs. */ byte[] getBytes(int columnIndex) throws SQLException; /** * This method returns the value of the specified column as a Java * <code>java.sql.Date</code>. * * @param columnIndex The index of the column to return. * @return The column value as a <code>java.sql.Date</code>. * @exception SQLException If an error occurs. */ Date getDate(int columnIndex) throws SQLException; /** * This method returns the value of the specified column as a Java * <code>java.sql.Time</code>. * * @param columnIndex The index of the column to return. * @return The column value as a <code>java.sql.Time</code>. * @exception SQLException If an error occurs. */ Time getTime(int columnIndex) throws SQLException; /** * This method returns the value of the specified column as a Java * <code>java.sql.Timestamp</code>. * * @param columnIndex The index of the column to return. * @return The column value as a <code>java.sql.Timestamp</code>. * @exception SQLException If an error occurs. */ Timestamp getTimestamp(int columnIndex) throws SQLException; /** * This method returns the value of the specified column as an ASCII * stream. Note that all the data from this stream must be read before * fetching the value of any other column. Please also be aware that * calling <code>next()</code> or <code>close()</code> on this result set * will close this stream as well. * * @param columnIndex The index of the column to return. * @return The column value as an ASCII <code>InputStream</code>. * @exception SQLException If an error occurs. */ InputStream getAsciiStream(int columnIndex) throws SQLException; /** * This method returns the value of the specified column as a Unicode UTF-8 * stream. Note that all the data from this stream must be read before * fetching the value of any other column. Please also be aware that * calling <code>next()</code> or <code>close()</code> on this result set * will close this stream as well. * * @param columnIndex The index of the column to return. * @return The column value as a Unicode UTF-8 <code>InputStream</code>. * @exception SQLException If an error occurs. * @deprecated Use getCharacterStream instead. */ InputStream getUnicodeStream(int columnIndex) throws SQLException; /** * This method returns the value of the specified column as a raw byte * stream. Note that all the data from this stream must be read before * fetching the value of any other column. Please also be aware that * calling <code>next()</code> or <code>close()</code> on this result set * will close this stream as well. * * @param columnIndex The index of the column to return. * @return The column value as a raw byte <code>InputStream</code>. * @exception SQLException If an error occurs. */ InputStream getBinaryStream(int columnIndex) throws SQLException; /** * This method returns the value of the specified column as a Java * <code>String</code>. * * @param columnName The name of the column to return. * @return The column value as a <code>String</code>. * @exception SQLException If an error occurs. */ String getString(String columnName) throws SQLException; /** * This method returns the value of the specified column as a Java * <code>boolean</code>. * * @param columnName The name of the column to return. * @return The column value as a <code>boolean</code>. * @exception SQLException If an error occurs. */ boolean getBoolean(String columnName) throws SQLException; /** * This method returns the value of the specified column as a Java * <code>byte</code>. * * @param columnName The name of the column to return. * @return The column value as a <code>byte</code>. * @exception SQLException If an error occurs. */ byte getByte(String columnName) throws SQLException; /** * This method returns the value of the specified column as a Java * <code>short</code>. * * @param columnName The name of the column to return. * @return The column value as a <code>short</code>. * @exception SQLException If an error occurs. */ short getShort(String columnName) throws SQLException; /** * This method returns the value of the specified column as a Java * <code>int</code>. * * @param columnName The name of the column to return. * @return The column value as a <code>int</code>. * @exception SQLException If an error occurs. */ int getInt(String columnName) throws SQLException; /** * This method returns the value of the specified column as a Java * <code>long</code>. * * @param columnName The name of the column to return. * @return The column value as a <code>long</code>. * @exception SQLException If an error occurs. */ long getLong(String columnName) throws SQLException; /** * This method returns the value of the specified column as a Java * <code>float</code>. * * @param columnName The name of the column to return. * @return The column value as a <code>float</code>. * @exception SQLException If an error occurs. */ float getFloat(String columnName) throws SQLException; /** * This method returns the value of the specified column as a Java * <code>double</code>. * * @param columnName The name of the column to return. * @return The column value as a <code>double</code>. * @exception SQLException If an error occurs. */ double getDouble(String columnName) throws SQLException; /** * This method returns the value of the specified column as a Java * <code>BigDecimal</code>. * * @param columnName The name of the column to return. * @return The column value as a <code>BigDecimal</code>. * @exception SQLException If an error occurs. * @deprecated */ BigDecimal getBigDecimal(String columnName, int scale) throws SQLException; /** * This method returns the value of the specified column as a Java * byte array. * * @param columnName The name of the column to return. * @return The column value as a byte array * @exception SQLException If an error occurs. */ byte[] getBytes(String columnName) throws SQLException; /** * This method returns the value of the specified column as a Java * <code>java.sql.Date</code>. * * @param columnName The name of the column to return. * @return The column value as a <code>java.sql.Date</code>. * @exception SQLException If an error occurs. */ Date getDate(String columnName) throws SQLException; /** * This method returns the value of the specified column as a Java * <code>java.sql.Time</code>. * * @param columnName The name of the column to return. * @return The column value as a <code>java.sql.Time</code>. * @exception SQLException If an error occurs. */ Time getTime(String columnName) throws SQLException; /** * This method returns the value of the specified column as a Java * <code>java.sql.Timestamp</code>. * * @param columnName The name of the column to return. * @return The column value as a <code>java.sql.Timestamp</code>. * @exception SQLException If an error occurs. */ Timestamp getTimestamp(String columnName) throws SQLException; /** * This method returns the value of the specified column as an ASCII * stream. Note that all the data from this stream must be read before * fetching the value of any other column. Please also be aware that * calling <code>next()</code> or <code>close()</code> on this result set * will close this stream as well. * * @param columnName The name of the column to return. * @return The column value as an ASCII <code>InputStream</code>. * @exception SQLException If an error occurs. */ InputStream getAsciiStream(String columnName) throws SQLException; /** * This method returns the value of the specified column as a Unicode UTF-8 * stream. Note that all the data from this stream must be read before * fetching the value of any other column. Please also be aware that * calling <code>next()</code> or <code>close()</code> on this result set * will close this stream as well. * * @param columnName The name of the column to return. * @return The column value as a Unicode UTF-8 <code>InputStream</code>. * @exception SQLException If an error occurs. * @deprecated Use getCharacterStream instead. */ InputStream getUnicodeStream(String columnName) throws SQLException; /** * This method returns the value of the specified column as a raw byte * stream. Note that all the data from this stream must be read before * fetching the value of any other column. Please also be aware that * calling <code>next()</code> or <code>close()</code> on this result set * will close this stream as well. * * @param columnName The name of the column to return. * @return The column value as a raw byte <code>InputStream</code>. * @exception SQLException If an error occurs. */ InputStream getBinaryStream(String columnName) throws SQLException; /** * This method returns the first SQL warning associated with this result * set. Any additional warnings will be chained to this one. * * @return The first SQLWarning for this result set, or <code>null</code> if * there are no warnings. * @exception SQLException If an error occurs. */ SQLWarning getWarnings() throws SQLException; /** * This method clears all warnings associated with this result set. * * @exception SQLException If an error occurs. */ void clearWarnings() throws SQLException; /** * This method returns the name of the database cursor used by this * result set. * * @return The name of the database cursor used by this result set. * @exception SQLException If an error occurs. */ String getCursorName() throws SQLException; /** * This method returns data about the columns returned as part of the * result set as a <code>ResultSetMetaData</code> instance. * * @return The <code>ResultSetMetaData</code> instance for this result set. * @exception SQLException If an error occurs. */ ResultSetMetaData getMetaData() throws SQLException; /** * This method returns the value of the specified column as a Java * <code>Object</code>. * * @param columnIndex The index of the column to return. * @return The column value as an <code>Object</code>. * @exception SQLException If an error occurs. */ Object getObject(int columnIndex) throws SQLException; /** * This method returns the value of the specified column as a Java * <code>Object</code>. * * @param columnName The name of the column to return. * @return The column value as an <code>Object</code>. * @exception SQLException If an error occurs. */ Object getObject(String columnName) throws SQLException; /** * This method returns the column index of the specified named column. * * @param columnName The name of the column. * @return The index of the column. * @exception SQLException If an error occurs. */ int findColumn(String columnName) throws SQLException; /** * This method returns the value of the specified column as a character * stream. Note that all the data from this stream must be read before * fetching the value of any other column. Please also be aware that * calling <code>next()</code> or <code>close()</code> on this result set * will close this stream as well. * * @param columnIndex The index of the column to return. * @return The column value as an character <code>Reader</code>. * @exception SQLException If an error occurs. */ Reader getCharacterStream(int columnIndex) throws SQLException; /** * This method returns the value of the specified column as a character * stream. Note that all the data from this stream must be read before * fetching the value of any other column. Please also be aware that * calling <code>next()</code> or <code>close()</code> on this result set * will close this stream as well. * * @param columnName The name of the column to return. * @return The column value as an character <code>Reader</code>. * @exception SQLException If an error occurs. */ Reader getCharacterStream(String columnName) throws SQLException; /** * This method returns the value of the specified column as a Java * <code>BigDecimal</code>. * * @param columnIndex The index of the column to return. * @return The column value as a <code>BigDecimal</code>. * @exception SQLException If an error occurs. */ BigDecimal getBigDecimal(int columnIndex) throws SQLException; /** * This method returns the value of the specified column as a Java * <code>BigDecimal</code>. * * @param columnName The name of the column to return. * @return The column value as a <code>BigDecimal</code>. * @exception SQLException If an error occurs. */ BigDecimal getBigDecimal(String columnName) throws SQLException; /** * This method tests whether or not the cursor is before the first row * in the result set. * * @return <code>true</code> if the cursor is positioned before the first * row, <code>false</code> otherwise. * @exception SQLException If an error occurs. */ boolean isBeforeFirst() throws SQLException; /** * This method tests whether or not the cursor is after the last row * in the result set. * * @return <code>true</code> if the cursor is positioned after the last * row, <code>false</code> otherwise. * @exception SQLException If an error occurs. */ boolean isAfterLast() throws SQLException; /** * This method tests whether or not the cursor is positioned on the first * row in the result set. * * @return <code>true</code> if the cursor is positioned on the first * row, <code>false</code> otherwise. * @exception SQLException If an error occurs. */ boolean isFirst() throws SQLException; /** * This method tests whether or not the cursor is on the last row * in the result set. * * @return <code>true</code> if the cursor is positioned on the last * row, <code>false</code> otherwise. * @exception SQLException If an error occurs. */ boolean isLast() throws SQLException; /** * This method repositions the cursor to before the first row in the * result set. * * @exception SQLException If an error occurs. */ void beforeFirst() throws SQLException; /** * This method repositions the cursor to after the last row in the result * set. * * @exception SQLException If an error occurs. */ void afterLast() throws SQLException; /** * This method repositions the cursor on the first row in the * result set. * * @return <code>true</code> if the cursor is on a valid row; * <code>false</code> if there are no rows in the result set. * @exception SQLException If an error occurs. */ boolean first() throws SQLException; /** * This method repositions the cursor on the last row in the result * set. * * @return <code>true</code> if the cursor is on a valid row; * <code>false</code> if there are no rows in the result set. * @exception SQLException If an error occurs. */ boolean last() throws SQLException; /** * This method returns the current row number in the cursor. Numbering * begins at index 1. * * @return The current row number, or 0 if there is not current row. * @exception SQLException If an error occurs. */ int getRow() throws SQLException; /** * This method positions the result set to the specified absolute row. * Positive numbers are row offsets from the beginning of the result * set (numbering starts from row 1) and negative numbers are row offsets * from the end of the result set (numbering starts from -1). * * @param row The row to position the result set to. * * @return <code>true</code> if the current position was changed, * <code>false</code> otherwise. * @exception SQLException If an error occurs. */ boolean absolute(int row) throws SQLException; /** * This method moves the result set position relative to the current row. * The offset can be positive or negative. * * @param rows The number of row positions to move. * @return <code>true</code> if the current position was changed, * <code>false</code> otherwise. * @exception SQLException If an error occurs. */ boolean relative(int rows) throws SQLException; /** * This method moves the current position to the previous row in the * result set. * * @return <code>true</code> if the previous row exists, <code>false</code> * otherwise. * @exception SQLException If an error occurs. */ boolean previous() throws SQLException; /** * This method provides a hint to the driver about which direction the * result set will be processed in. * * @param direction The direction in which rows will be processed. The * allowed values are the <code>FETCH_*</code> constants * defined in this interface. * @exception SQLException If an error occurs. */ void setFetchDirection(int direction) throws SQLException; /** * This method returns the current fetch direction for this result set. * * @return The fetch direction for this result set. * @exception SQLException If an error occurs. */ int getFetchDirection() throws SQLException; /** * This method provides a hint to the driver about how many rows at a * time it should fetch from the database. * * @param rows The number of rows the driver should fetch per call. * @exception SQLException If an error occurs. */ void setFetchSize(int rows) throws SQLException; /** * This method returns the current number of rows that will be fetched * from the database at a time. * * @return The current fetch size for this result set. * @exception SQLException If an error occurs. */ int getFetchSize() throws SQLException; /** * This method returns the result set type of this result set. This will * be one of the <code>TYPE_*</code> constants defined in this interface. * * @return The result set type. * @exception SQLException If an error occurs. */ int getType() throws SQLException; /** * This method returns the concurrency type of this result set. This will * be one of the <code>CONCUR_*</code> constants defined in this interface. * * @return The result set concurrency type. * @exception SQLException If an error occurs. */ int getConcurrency() throws SQLException; /** * This method tests whether or not the current row in the result set * has been updated. Updates must be visible in order of this method to * detect the update. * * @return <code>true</code> if the row has been updated, <code>false</code> * otherwise. * @exception SQLException If an error occurs. */ boolean rowUpdated() throws SQLException; /** * This method tests whether or not the current row in the result set * has been inserted. Inserts must be visible in order of this method to * detect the insert. * * @return <code>true</code> if the row has been inserted, <code>false</code> * otherwise. * @exception SQLException If an error occurs. */ boolean rowInserted() throws SQLException; /** * This method tests whether or not the current row in the result set * has been deleted. Deletes must be visible in order of this method to * detect the deletion. * * @return <code>true</code> if the row has been deleted, <code>false</code> * otherwise. * @exception SQLException If an error occurs. */ boolean rowDeleted() throws SQLException; /** * This method updates the specified column to have a NULL value. This * does not update the actual database. <code>updateRow</code> must be * called in order to do that. * * @param columnIndex The index of the column to update. * @exception SQLException If an error occurs. */ void updateNull(int columnIndex) throws SQLException; /** * This method updates the specified column to have a boolean value. This * does not update the actual database. <code>updateRow</code> must be * called in order to do that. * * @param columnIndex The index of the column to update. * @param value The new value of the column. * @exception SQLException If an error occurs. */ void updateBoolean(int columnIndex, boolean value) throws SQLException; /** * This method updates the specified column to have a byte value. This * does not update the actual database. <code>updateRow</code> must be * called in order to do that. * * @param columnIndex The index of the column to update. * @param value The new value of the column. * @exception SQLException If an error occurs. */ void updateByte(int columnIndex, byte value) throws SQLException; /** * This method updates the specified column to have a short value. This * does not update the actual database. <code>updateRow</code> must be * called in order to do that. * * @param columnIndex The index of the column to update. * @param value The new value of the column. * @exception SQLException If an error occurs. */ void updateShort(int columnIndex, short value) throws SQLException; /** * This method updates the specified column to have an int value. This * does not update the actual database. <code>updateRow</code> must be * called in order to do that. * * @param columnIndex The index of the column to update. * @param value The new value of the column. * @exception SQLException If an error occurs. */ void updateInt(int columnIndex, int value) throws SQLException; /** * This method updates the specified column to have a long value. This * does not update the actual database. <code>updateRow</code> must be * called in order to do that. * * @param columnIndex The index of the column to update. * @param value The new value of the column. * @exception SQLException If an error occurs. */ void updateLong(int columnIndex, long value) throws SQLException; /** * This method updates the specified column to have a float value. This * does not update the actual database. <code>updateRow</code> must be * called in order to do that. * * @param columnIndex The index of the column to update. * @param value The new value of the column. * @exception SQLException If an error occurs. */ void updateFloat(int columnIndex, float value) throws SQLException; /** * This method updates the specified column to have a double value. This * does not update the actual database. <code>updateRow</code> must be * called in order to do that. * * @param columnIndex The index of the column to update. * @param value The new value of the column. * @exception SQLException If an error occurs. */ void updateDouble(int columnIndex, double value) throws SQLException; /** * This method updates the specified column to have a BigDecimal value. This * does not update the actual database. <code>updateRow</code> must be * called in order to do that. * * @param columnIndex The index of the column to update. * @param value The new value of the column. * @exception SQLException If an error occurs. */ void updateBigDecimal(int columnIndex, BigDecimal value) throws SQLException; /** * This method updates the specified column to have a String value. This * does not update the actual database. <code>updateRow</code> must be * called in order to do that. * * @param columnIndex The index of the column to update. * @param value The new value of the column. * @exception SQLException If an error occurs. */ void updateString(int columnIndex, String value) throws SQLException; /** * This method updates the specified column to have a byte array value. This * does not update the actual database. <code>updateRow</code> must be * called in order to do that. * * @param columnIndex The index of the column to update. * @param value The new value of the column. * @exception SQLException If an error occurs. */ void updateBytes(int columnIndex, byte[] value) throws SQLException; /** * This method updates the specified column to have a java.sql.Date value. This * does not update the actual database. <code>updateRow</code> must be * called in order to do that. * * @param columnIndex The index of the column to update. * @param value The new value of the column. * @exception SQLException If an error occurs. */ void updateDate(int columnIndex, Date value) throws SQLException; /** * This method updates the specified column to have a java.sql.Time value. This * does not update the actual database. <code>updateRow</code> must be * called in order to do that. * * @param columnIndex The index of the column to update. * @param value The new value of the column. * @exception SQLException If an error occurs. */ void updateTime(int columnIndex, Time value) throws SQLException; /** * This method updates the specified column to have a java.sql.Timestamp value. * This does not update the actual database. <code>updateRow</code> must be * called in order to do that. * * @param columnIndex The index of the column to update. * @param value The new value of the column. * @exception SQLException If an error occurs. */ void updateTimestamp(int columnIndex, Timestamp value) throws SQLException; /** * This method updates the specified column from an ASCII text stream. * This does not update the actual database. <code>updateRow</code> must be * called in order to do that. * * @param columnIndex The index of the column to update. * @param stream The stream from which the column value is updated. * @param count The length of the stream. * @exception SQLException If an error occurs. */ void updateAsciiStream(int columnIndex, InputStream stream, int count) throws SQLException; /** * This method updates the specified column from a binary stream. * This does not update the actual database. <code>updateRow</code> must be * called in order to do that. * * @param columnIndex The index of the column to update. * @param stream The stream from which the column value is updated. * @param count The length of the stream. * @exception SQLException If an error occurs. */ void updateBinaryStream(int columnIndex, InputStream stream, int count) throws SQLException; /** * This method updates the specified column from a character stream. * This does not update the actual database. <code>updateRow</code> must be * called in order to do that. * * @param columnIndex The index of the column to update. * @param reader The reader from which the column value is updated. * @param count The length of the stream. * @exception SQLException If an error occurs. */ void updateCharacterStream(int columnIndex, Reader reader, int count) throws SQLException; /** * This method updates the specified column to have an Object value. * This does not update the actual database. <code>updateRow</code> must be * called in order to do that. * * @param columnIndex The index of the column to update. * @param value The new value of the column. * @param scale The scale of the object in question, which is used only * for numeric type objects. * @exception SQLException If an error occurs. */ void updateObject(int columnIndex, Object value, int scale) throws SQLException; /** * This method updates the specified column to have an Object value. * This does not update the actual database. <code>updateRow</code> must be * called in order to do that. * * @param columnIndex The index of the column to update. * @param value The new value of the column. * @exception SQLException If an error occurs. */ void updateObject(int columnIndex, Object value) throws SQLException; /** * This method updates the specified column to have a NULL value. This * does not update the actual database. <code>updateRow</code> must be * called in order to do that. * * @param columnName The name of the column to update. * @exception SQLException If an error occurs. */ void updateNull(String columnName) throws SQLException; /** * This method updates the specified column to have a boolean value. This * does not update the actual database. <code>updateRow</code> must be * called in order to do that. * * @param columnName The name of the column to update. * @param value The new value of the column. * @exception SQLException If an error occurs. */ void updateBoolean(String columnName, boolean value) throws SQLException; /** * This method updates the specified column to have a byte value. This * does not update the actual database. <code>updateRow</code> must be * called in order to do that. * * @param columnName The name of the column to update. * @param value The new value of the column. * @exception SQLException If an error occurs. */ void updateByte(String columnName, byte value) throws SQLException; /** * This method updates the specified column to have a short value. This * does not update the actual database. <code>updateRow</code> must be * called in order to do that. * * @param columnName The name of the column to update. * @param value The new value of the column. * @exception SQLException If an error occurs. */ void updateShort(String columnName, short value) throws SQLException; /** * This method updates the specified column to have an int value. This * does not update the actual database. <code>updateRow</code> must be * called in order to do that. * * @param columnName The name of the column to update. * @param value The new value of the column. * @exception SQLException If an error occurs. */ void updateInt(String columnName, int value) throws SQLException; /** * This method updates the specified column to have a long value. This * does not update the actual database. <code>updateRow</code> must be * called in order to do that. * * @param columnName The name of the column to update. * @param value The new value of the column. * @exception SQLException If an error occurs. */ void updateLong(String columnName, long value) throws SQLException; /** * This method updates the specified column to have a float value. This * does not update the actual database. <code>updateRow</code> must be * called in order to do that. * * @param columnName The name of the column to update. * @param value The new value of the column. * @exception SQLException If an error occurs. */ void updateFloat(String columnName, float value) throws SQLException; /** * This method updates the specified column to have a double value. This * does not update the actual database. <code>updateRow</code> must be * called in order to do that. * * @param columnName The name of the column to update. * @param value The new value of the column. * @exception SQLException If an error occurs. */ void updateDouble(String columnName, double value) throws SQLException; /** * This method updates the specified column to have a BigDecimal value. This * does not update the actual database. <code>updateRow</code> must be * called in order to do that. * * @param columnName The name of the column to update. * @param value The new value of the column. * @exception SQLException If an error occurs. */ void updateBigDecimal(String columnName, BigDecimal value) throws SQLException; /** * This method updates the specified column to have a String value. This * does not update the actual database. <code>updateRow</code> must be * called in order to do that. * * @param columnName The name of the column to update. * @param value The new value of the column. * @exception SQLException If an error occurs. */ void updateString(String columnName, String value) throws SQLException; /** * This method updates the specified column to have a byte array value. This * does not update the actual database. <code>updateRow</code> must be * called in order to do that. * * @param columnName The name of the column to update. * @param value The new value of the column. * @exception SQLException If an error occurs. */ void updateBytes(String columnName, byte[] value) throws SQLException; /** * This method updates the specified column to have a java.sql.Date value. This * does not update the actual database. <code>updateRow</code> must be * called in order to do that. * * @param columnName The name of the column to update. * @param value The new value of the column. * @exception SQLException If an error occurs. */ void updateDate(String columnName, Date value) throws SQLException; /** * This method updates the specified column to have a java.sql.Time value. This * does not update the actual database. <code>updateRow</code> must be * called in order to do that. * * @param columnName The name of the column to update. * @param value The new value of the column. * @exception SQLException If an error occurs. */ void updateTime(String columnName, Time value) throws SQLException; /** * This method updates the specified column to have a java.sql.Timestamp value. * This does not update the actual database. <code>updateRow</code> must be * called in order to do that. * * @param columnName The name of the column to update. * @param value The new value of the column. * @exception SQLException If an error occurs. */ void updateTimestamp(String columnName, Timestamp value) throws SQLException; /** * This method updates the specified column from an ASCII text stream. * This does not update the actual database. <code>updateRow</code> must be * called in order to do that. * * @param columnName The name of the column to update. * @param stream The stream from which the column value is updated. * @param count The length of the stream. * @exception SQLException If an error occurs. */ void updateAsciiStream(String columnName, InputStream stream, int count) throws SQLException; /** * This method updates the specified column from a binary stream. * This does not update the actual database. <code>updateRow</code> must be * called in order to do that. * * @param columnName The name of the column to update. * @param stream The stream from which the column value is updated. * @param count The length of the stream. * @exception SQLException If an error occurs. */ void updateBinaryStream(String columnName, InputStream stream, int count) throws SQLException; /** * This method updates the specified column from a character stream. * This does not update the actual database. <code>updateRow</code> must be * called in order to do that. * * @param columnName The name of the column to update. * @param reader The reader from which the column value is updated. * @param count The length of the stream. * @exception SQLException If an error occurs. */ void updateCharacterStream(String columnName, Reader reader, int count) throws SQLException; /** * This method updates the specified column to have an Object value. * This does not update the actual database. <code>updateRow</code> must be * called in order to do that. * * @param columnName The name of the column to update. * @param value The new value of the column. * @param scale The scale of the object in question, which is used only * for numeric type objects. * @exception SQLException If an error occurs. */ void updateObject(String columnName, Object value, int scale) throws SQLException; /** * This method updates the specified column to have an Object value. * This does not update the actual database. <code>updateRow</code> must be * called in order to do that. * * @param columnName The name of the column to update. * @param value The new value of the column. * @exception SQLException If an error occurs. */ void updateObject(String columnName, Object value) throws SQLException; /** * This method inserts the current row into the database. The result set * must be positioned on the insert row in order to call this method * successfully. * * @exception SQLException If an error occurs. */ void insertRow() throws SQLException; /** * This method updates the current row in the database. * * @exception SQLException If an error occurs. */ void updateRow() throws SQLException; /** * This method deletes the current row in the database. * * @exception SQLException If an error occurs. */ void deleteRow() throws SQLException; /** * This method refreshes the contents of the current row from the database. * * @exception SQLException If an error occurs. */ void refreshRow() throws SQLException; /** * This method cancels any changes that have been made to a row. If * the <code>rowUpdate</code> method has been called, then the changes * cannot be undone. * * @exception SQLException If an error occurs. */ void cancelRowUpdates() throws SQLException; /** * This method positions the result set to the "insert row", which allows * a new row to be inserted into the database from the result set. * * @exception SQLException If an error occurs. */ void moveToInsertRow() throws SQLException; /** * This method moves the result set position from the insert row back to * the current row that was selected prior to moving to the insert row. * * @exception SQLException If an error occurs. */ void moveToCurrentRow() throws SQLException; /** * This method returns a the <code>Statement</code> that was used to * produce this result set. * * @return The <code>Statement</code> used to produce this result set. * * @exception SQLException If an error occurs. */ Statement getStatement() throws SQLException; /** * This method returns the value of the specified column as a Java * <code>Object</code> using the specified SQL type to Java type map. * * @param columnIndex The index of the column to return. * @param map The SQL type to Java type map to use. * @return The value of the column as an <code>Object</code>. * @exception SQLException If an error occurs. */ Object getObject(int columnIndex, Map<String, Class<?>> map) throws SQLException; /** * This method returns a <code>Ref</code> for the specified column which * represents the structured type for the column. * * @param columnIndex The index of the column to return. * @return A <code>Ref</code> object for the column * @exception SQLException If an error occurs. */ Ref getRef(int columnIndex) throws SQLException; /** * This method returns the specified column value as a BLOB. * * @param columnIndex The index of the column value to return. * @return The value of the column as a BLOB. * @exception SQLException If an error occurs. */ Blob getBlob(int columnIndex) throws SQLException; /** * This method returns the specified column value as a CLOB. * * @param columnIndex The index of the column value to return. * @return The value of the column as a CLOB. * @exception SQLException If an error occurs. */ Clob getClob(int columnIndex) throws SQLException; /** * This method returns the specified column value as an <code>Array</code>. * * @param columnIndex The index of the column value to return. * @return The value of the column as an <code>Array</code>. * @exception SQLException If an error occurs. */ Array getArray(int columnIndex) throws SQLException; /** * This method returns the value of the specified column as a Java * <code>Object</code> using the specified SQL type to Java type map. * * @param columnName The name of the column to return. * @param map The SQL type to Java type map to use. * @return The value of the column as an <code>Object</code>. * @exception SQLException If an error occurs. */ Object getObject(String columnName, Map<String, Class<?>> map) throws SQLException; /** * This method returns a <code>Ref</code> for the specified column which * represents the structured type for the column. * * @param columnName The name of the column to return. * @return A <code>Ref</code> object for the column * @exception SQLException If an error occurs. */ Ref getRef(String columnName) throws SQLException; /** * This method returns the specified column value as a BLOB. * * @param columnName The name of the column value to return. * @return The value of the column as a BLOB. * @exception SQLException If an error occurs. */ Blob getBlob(String columnName) throws SQLException; /** * This method returns the specified column value as a CLOB. * * @param columnName The name of the column value to return. * @return The value of the column as a CLOB. * @exception SQLException If an error occurs. */ Clob getClob(String columnName) throws SQLException; /** * This method returns the specified column value as an <code>Array</code>. * * @param columnName The name of the column value to return. * @return The value of the column as an <code>Array</code>. * @exception SQLException If an error occurs. */ Array getArray(String columnName) throws SQLException; /** * This method returns the specified column value as a * <code>java.sql.Date</code>. The specified <code>Calendar</code> is used * to generate a value for the date if the database does not support * timezones. * * @param columnIndex The index of the column value to return. * @param cal The <code>Calendar</code> to use for calculating timezones. * @return The value of the column as a <code>java.sql.Date</code>. * @exception SQLException If an error occurs. */ Date getDate(int columnIndex, Calendar cal) throws SQLException; /** * This method returns the specified column value as a * <code>java.sql.Date</code>. The specified <code>Calendar</code> is used * to generate a value for the date if the database does not support * timezones. * * @param columnName The name of the column value to return. * @param cal The <code>Calendar</code> to use for calculating timezones. * @return The value of the column as a <code>java.sql.Date</code>. * @exception SQLException If an error occurs. */ Date getDate(String columnName, Calendar cal) throws SQLException; /** * This method returns the specified column value as a * <code>java.sql.Time</code>. The specified <code>Calendar</code> is used * to generate a value for the time if the database does not support * timezones. * * @param columnIndex The index of the column value to return. * @param cal The <code>Calendar</code> to use for calculating timezones. * @return The value of the column as a <code>java.sql.Time</code>. * @exception SQLException If an error occurs. */ Time getTime(int columnIndex, Calendar cal) throws SQLException; /** * This method returns the specified column value as a * <code>java.sql.Time</code>. The specified <code>Calendar</code> is used * to generate a value for the time if the database does not support * timezones. * * @param columnName The name of the column value to return. * @param cal The <code>Calendar</code> to use for calculating timezones. * @return The value of the column as a <code>java.sql.Time</code>. * @exception SQLException If an error occurs. */ Time getTime(String columnName, Calendar cal) throws SQLException; /** * This method returns the specified column value as a * <code>java.sql.Timestamp</code>. The specified <code>Calendar</code> is used * to generate a value for the timestamp if the database does not support * timezones. * * @param columnIndex The index of the column value to return. * @param cal The <code>Calendar</code> to use for calculating timezones. * @return The value of the column as a <code>java.sql.Timestamp</code>. * @exception SQLException If an error occurs. */ Timestamp getTimestamp(int columnIndex, Calendar cal) throws SQLException; /** * This method returns the specified column value as a * <code>java.sql.Timestamp</code>. The specified <code>Calendar</code> is used * to generate a value for the timestamp if the database does not support * timezones. * * @param columnName The name of the column value to return. * @param cal The <code>Calendar</code> to use for calculating timezones. * * @return The value of the column as a <code>java.sql.Timestamp</code>. * * @exception SQLException If an error occurs. */ Timestamp getTimestamp(String columnName, Calendar cal) throws SQLException; /** * This method returns the specified column value as a * <code>java.net.URL</code>. * * @param columnIndex The index of the column value to return. * @exception SQLException If an error occurs. * @since 1.4 */ URL getURL(int columnIndex) throws SQLException; /** * This method returns the specified column value as a * <code>java.net.URL</code>. * * @param columnName The name of the column value to return. * @exception SQLException If an error occurs. * @since 1.4 */ URL getURL(String columnName) throws SQLException; /** * This method updates the specified column to have a * <code>java.sql.Ref</code> value. * This does not update the actual database. <code>updateRow</code> must be * called in order to do that. * * @parm columnIndex The index of the column value to update. * @parm value The <code>java.sql.Ref</code> used to set the new value * of the column. * @exception SQLException If an error occurs. * @since 1.4 */ void updateRef(int columnIndex, Ref value) throws SQLException; /** * This method updates the specified column to have a * <code>java.sql.Ref</code> value. * This does not update the actual database. <code>updateRow</code> must be * called in order to do that. * * @parm columnName The name of the column value to update. * @parm value The <code>java.sql.Ref</code> used to set the new value * of the column. * @exception SQLException If an error occurs. * @since 1.4 */ void updateRef(String columnName, Ref value) throws SQLException; /** * This method updates the specified column to have a * <code>java.sql.Blob</code> value. * This does not update the actual database. <code>updateRow</code> must be * called in order to do that. * * @parm columnIndex The index of the column value to update. * @parm value The <code>java.sql.Blob</code> used to set the new value * of the column. * @exception SQLException If an error occurs. * @since 1.4 */ void updateBlob(int columnIndex, Blob value) throws SQLException; /** * This method updates the specified column to have a * <code>java.sql.Blob</code> value. * This does not update the actual database. <code>updateRow</code> must be * called in order to do that. * * @parm columnName The name of the column value to update. * @parm value The <code>java.sql.Blob</code> used to set the new value * of the column. * @exception SQLException If an error occurs. * @since 1.4 */ void updateBlob(String columnName, Blob value) throws SQLException; /** * This method updates the specified column to have a * <code>java.sql.Clob</code> value. * This does not update the actual database. <code>updateRow</code> must be * called in order to do that. * * @parm columnIndex The index of the column value to update. * @parm value The <code>java.sql.Clob</code> used to set the new value * of the column. * @exception SQLException If an error occurs. * @since 1.4 */ void updateClob(int columnIndex, Clob value) throws SQLException; /** * This method updates the specified column to have a * <code>java.sql.Clob</code> value. * This does not update the actual database. <code>updateRow</code> must be * called in order to do that. * * @parm columnName The name of the column value to update. * @parm value The <code>java.sql.Clob</code> used to set the new value * of the column. * @exception SQLException If an error occurs. * @since 1.4 */ void updateClob(String columnName, Clob value) throws SQLException; /** * This method updates the specified column to have a * <code>java.sqlArray</code> value. * This does not update the actual database. <code>updateRow</code> must be * called in order to do that. * * @parm columnIndex The index of the column value to update. * @parm value The new value of the column. * @exception SQLException If an error occurs. * @since 1.4 */ void updateArray(int columnIndex, Array value) throws SQLException; /** * This method updates the specified column to have a * <code>java.sqlArray</code> value. * This does not update the actual database. <code>updateRow</code> must be * called in order to do that. * * @parm columnName The name of the column value to update. * @parm value The new value of the column. * @exception SQLException If an error occurs. * @since 1.4 */ void updateArray(String columnName, Array value) throws SQLException; }
{ "content_hash": "0ced3e3a7f049986678b63da19ed864d", "timestamp": "", "source": "github", "line_count": 1577, "max_line_length": 83, "avg_line_length": 35.913126188966395, "alnum_prop": 0.6904211176834113, "repo_name": "nmldiegues/jvm-stm", "id": "573deb3e105316ae4192944327cf29c5b2fa6f5f", "size": "58411", "binary": false, "copies": "20", "ref": "refs/heads/master", "path": "classpath-0.98/java/sql/ResultSet.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Assembly", "bytes": "66583" }, { "name": "C", "bytes": "3107750" }, { "name": "C++", "bytes": "500403" }, { "name": "CSS", "bytes": "42335" }, { "name": "GAP", "bytes": "13089" }, { "name": "Groff", "bytes": "71735" }, { "name": "HTML", "bytes": "761911" }, { "name": "Java", "bytes": "42685062" }, { "name": "JavaScript", "bytes": "6158" }, { "name": "Perl", "bytes": "12256" }, { "name": "Shell", "bytes": "1008589" }, { "name": "TeX", "bytes": "290889" }, { "name": "XSLT", "bytes": "156419" }, { "name": "Yacc", "bytes": "18175" } ], "symlink_target": "" }
package org.apache.hadoop.hbase.master; import java.io.IOException; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.hadoop.fs.Path; import org.apache.hadoop.hbase.HRegionInfo; import org.apache.hadoop.hbase.RemoteExceptionHandler; import org.apache.hadoop.hbase.TableNotDisabledException; import org.apache.hadoop.hbase.ipc.HRegionInterface; import org.apache.hadoop.hbase.regionserver.HRegion; import org.apache.hadoop.hbase.util.Bytes; /** * Instantiated to delete a table. Table must be offline. */ class TableDelete extends TableOperation { private final Log LOG = LogFactory.getLog(this.getClass()); TableDelete(final HMaster master, final byte [] tableName) throws IOException { super(master, tableName); } @Override protected void processScanItem(String serverName, final HRegionInfo info) throws IOException { if (isEnabled(info)) { LOG.debug("Region still enabled: " + info.toString()); throw new TableNotDisabledException(tableName); } } @Override protected void postProcessMeta(MetaRegion m, HRegionInterface server) throws IOException { for (HRegionInfo i: unservedRegions) { if (!Bytes.equals(this.tableName, i.getTableDesc().getName())) { // Don't delete regions that are not from our table. continue; } // Delete the region try { HRegion.removeRegionFromMETA(server, m.getRegionName(), i.getRegionName()); HRegion.deleteRegion(this.master.fs, this.master.rootdir, i); } catch (IOException e) { LOG.error("failed to delete region " + Bytes.toString(i.getRegionName()), RemoteExceptionHandler.checkIOException(e)); } } // delete the table's folder from fs. master.fs.delete(new Path(master.rootdir, Bytes.toString(tableName)), true); } }
{ "content_hash": "020b9ebbee085b8d613eff85420424df", "timestamp": "", "source": "github", "line_count": 57, "max_line_length": 83, "avg_line_length": 32.98245614035088, "alnum_prop": 0.7154255319148937, "repo_name": "adragomir/hbaseindex", "id": "0bde1b18ca4f81d2d016ff9fa40be0995111471f", "size": "2738", "binary": false, "copies": "1", "ref": "refs/heads/trunk", "path": "src/java/org/apache/hadoop/hbase/master/TableDelete.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C++", "bytes": "9334" }, { "name": "Java", "bytes": "4746474" }, { "name": "JavaScript", "bytes": "17630" }, { "name": "PHP", "bytes": "7341" }, { "name": "Python", "bytes": "207735" }, { "name": "Ruby", "bytes": "58002" }, { "name": "Shell", "bytes": "21036" } ], "symlink_target": "" }
cask 'a-better-finder-rename' do version '10.44' sha256 :no_check # required as upstream package is updated in-place url "https://www.publicspace.net/download/ABFRX#{version.major}.dmg" appcast "https://www.publicspace.net/app/signed_abfr#{version.major}.xml" name 'A Better Finder Rename' homepage 'https://www.publicspace.net/ABetterFinderRename/' auto_updates true app "A Better Finder Rename #{version.major}.app" zap trash: [ "~/Library/Application Support/A Better Finder Rename #{version.major}", "~/Library/Caches/com.apple.helpd/Generated/net.publicspace.abfr#{version.major}.help*", "~/Library/Caches/net.publicspace.abfr#{version.major}", "~/Library/Cookies/net.publicspace.abfr#{version.major}.binarycookies", "~/Library/Preferences/net.publicspace.abfr#{version.major}.plist", "~/Library/Saved Application State/net.publicspace.abfr#{version.major}.savedState", ] end
{ "content_hash": "f888d6c30fd4e9294b08998c656a3bc7", "timestamp": "", "source": "github", "line_count": 22, "max_line_length": 103, "avg_line_length": 45.72727272727273, "alnum_prop": 0.6769383697813122, "repo_name": "Ephemera/homebrew-cask", "id": "ea073bbdbf0fcda2c411390d64f21e153a37b89e", "size": "1006", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "Casks/a-better-finder-rename.rb", "mode": "33188", "license": "bsd-2-clause", "language": [ { "name": "Dockerfile", "bytes": "546" }, { "name": "Python", "bytes": "3532" }, { "name": "Ruby", "bytes": "2090830" }, { "name": "Shell", "bytes": "34662" } ], "symlink_target": "" }
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("ConsoleApplication")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Microsoft")] [assembly: AssemblyProduct("ConsoleApplication")] [assembly: AssemblyCopyright("Copyright © Microsoft 2015")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("621f69a8-0d02-407e-9537-a87c63d45abe")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
{ "content_hash": "287ebde1d4035680509273995729fb71", "timestamp": "", "source": "github", "line_count": 36, "max_line_length": 84, "avg_line_length": 39.638888888888886, "alnum_prop": 0.7505255781359496, "repo_name": "andreireinus/vs2015-eneta", "id": "9c47fd2f725eb3316cba5dbc55098f1f863b51f4", "size": "1430", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "ConsoleApplication/Properties/AssemblyInfo.cs", "mode": "33188", "license": "mit", "language": [ { "name": "C#", "bytes": "15444" } ], "symlink_target": "" }
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://www.springframework.org/schema/beans" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"> <!--==================================Spring JDBC 模板演示==================================--> <!-- 指定spring读取db.properties配置 --> <context:property-placeholder location="classpath:db.properties"/> <!-- 1.将连接池放入spring容器 --> <bean name="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"> <property name="jdbcUrl" value="${jdbc.jdbcUrl}"/> <property name="driverClass" value="${jdbc.driverClass}"/> <property name="user" value="${jdbc.user}"/> <property name="password" value="${jdbc.password}"/> </bean> <!-- 2.将JDBCTemplate放入spring容器 --> <bean name="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate"> <property name="dataSource" ref="dataSource"/> </bean> <!-- 3.将UserDao放入spring容器 --> <bean name="userDao" class="com.ztiany.springf.test.jdbc.UserDaoImpl"> <property name="dataSource" ref="dataSource"/> </bean> </beans>
{ "content_hash": "94b28f947cb39793870045d14dabed98", "timestamp": "", "source": "github", "line_count": 36, "max_line_length": 95, "avg_line_length": 39.75, "alnum_prop": 0.6401118099231307, "repo_name": "Ztiany/Repository", "id": "1f2e19ed4a5a9821a6588d79c5a27d516ed273f6", "size": "1487", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "JavaEE/SpringFramework-Base/src/test/resources/jdbc.xml", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C", "bytes": "38608" }, { "name": "C++", "bytes": "52662" }, { "name": "CMake", "bytes": "316" }, { "name": "CSS", "bytes": "28" }, { "name": "Groovy", "bytes": "151193" }, { "name": "HTML", "bytes": "126611" }, { "name": "Java", "bytes": "632743" }, { "name": "Kotlin", "bytes": "81491" }, { "name": "Python", "bytes": "16189" } ], "symlink_target": "" }
#ifndef ISL_SPACE_H #define ISL_SPACE_H #include <isl/ctx.h> #include <isl/space_type.h> #include <isl/id_type.h> #include <isl/printer.h> #if defined(__cplusplus) extern "C" { #endif isl_ctx *isl_space_get_ctx(__isl_keep isl_space *dim); __isl_give isl_space *isl_space_alloc(isl_ctx *ctx, unsigned nparam, unsigned n_in, unsigned n_out); __isl_give isl_space *isl_space_set_alloc(isl_ctx *ctx, unsigned nparam, unsigned dim); __isl_give isl_space *isl_space_params_alloc(isl_ctx *ctx, unsigned nparam); __isl_give isl_space *isl_space_copy(__isl_keep isl_space *dim); __isl_null isl_space *isl_space_free(__isl_take isl_space *space); isl_bool isl_space_is_params(__isl_keep isl_space *space); isl_bool isl_space_is_set(__isl_keep isl_space *space); isl_bool isl_space_is_map(__isl_keep isl_space *space); __isl_give isl_space *isl_space_add_param_id(__isl_take isl_space *space, __isl_take isl_id *id); __isl_give isl_space *isl_space_set_tuple_name(__isl_take isl_space *dim, enum isl_dim_type type, const char *s); isl_bool isl_space_has_tuple_name(__isl_keep isl_space *space, enum isl_dim_type type); __isl_keep const char *isl_space_get_tuple_name(__isl_keep isl_space *dim, enum isl_dim_type type); __isl_give isl_space *isl_space_set_tuple_id(__isl_take isl_space *dim, enum isl_dim_type type, __isl_take isl_id *id); __isl_give isl_space *isl_space_reset_tuple_id(__isl_take isl_space *dim, enum isl_dim_type type); isl_bool isl_space_has_tuple_id(__isl_keep isl_space *dim, enum isl_dim_type type); __isl_give isl_id *isl_space_get_tuple_id(__isl_keep isl_space *dim, enum isl_dim_type type); __isl_give isl_space *isl_space_reset_user(__isl_take isl_space *space); __isl_give isl_space *isl_space_set_dim_id(__isl_take isl_space *dim, enum isl_dim_type type, unsigned pos, __isl_take isl_id *id); isl_bool isl_space_has_dim_id(__isl_keep isl_space *dim, enum isl_dim_type type, unsigned pos); __isl_give isl_id *isl_space_get_dim_id(__isl_keep isl_space *dim, enum isl_dim_type type, unsigned pos); int isl_space_find_dim_by_id(__isl_keep isl_space *dim, enum isl_dim_type type, __isl_keep isl_id *id); int isl_space_find_dim_by_name(__isl_keep isl_space *space, enum isl_dim_type type, const char *name); isl_bool isl_space_has_dim_name(__isl_keep isl_space *space, enum isl_dim_type type, unsigned pos); __isl_give isl_space *isl_space_set_dim_name(__isl_take isl_space *dim, enum isl_dim_type type, unsigned pos, __isl_keep const char *name); __isl_keep const char *isl_space_get_dim_name(__isl_keep isl_space *dim, enum isl_dim_type type, unsigned pos); ISL_DEPRECATED __isl_give isl_space *isl_space_extend(__isl_take isl_space *dim, unsigned nparam, unsigned n_in, unsigned n_out); __isl_give isl_space *isl_space_add_dims(__isl_take isl_space *space, enum isl_dim_type type, unsigned n); __isl_give isl_space *isl_space_move_dims(__isl_take isl_space *space, enum isl_dim_type dst_type, unsigned dst_pos, enum isl_dim_type src_type, unsigned src_pos, unsigned n); __isl_give isl_space *isl_space_insert_dims(__isl_take isl_space *dim, enum isl_dim_type type, unsigned pos, unsigned n); __isl_give isl_space *isl_space_join(__isl_take isl_space *left, __isl_take isl_space *right); __isl_give isl_space *isl_space_product(__isl_take isl_space *left, __isl_take isl_space *right); __isl_give isl_space *isl_space_domain_product(__isl_take isl_space *left, __isl_take isl_space *right); __isl_give isl_space *isl_space_range_product(__isl_take isl_space *left, __isl_take isl_space *right); __isl_give isl_space *isl_space_factor_domain(__isl_take isl_space *space); __isl_give isl_space *isl_space_factor_range(__isl_take isl_space *space); __isl_give isl_space *isl_space_domain_factor_domain( __isl_take isl_space *space); __isl_give isl_space *isl_space_domain_factor_range( __isl_take isl_space *space); __isl_give isl_space *isl_space_range_factor_domain( __isl_take isl_space *space); __isl_give isl_space *isl_space_range_factor_range( __isl_take isl_space *space); __isl_give isl_space *isl_space_map_from_set(__isl_take isl_space *space); __isl_give isl_space *isl_space_map_from_domain_and_range( __isl_take isl_space *domain, __isl_take isl_space *range); __isl_give isl_space *isl_space_reverse(__isl_take isl_space *dim); __isl_give isl_space *isl_space_drop_dims(__isl_take isl_space *dim, enum isl_dim_type type, unsigned first, unsigned num); ISL_DEPRECATED __isl_give isl_space *isl_space_drop_inputs(__isl_take isl_space *dim, unsigned first, unsigned n); ISL_DEPRECATED __isl_give isl_space *isl_space_drop_outputs(__isl_take isl_space *dim, unsigned first, unsigned n); __isl_give isl_space *isl_space_domain(__isl_take isl_space *space); __isl_give isl_space *isl_space_from_domain(__isl_take isl_space *dim); __isl_give isl_space *isl_space_range(__isl_take isl_space *space); __isl_give isl_space *isl_space_from_range(__isl_take isl_space *dim); __isl_give isl_space *isl_space_domain_map(__isl_take isl_space *space); __isl_give isl_space *isl_space_range_map(__isl_take isl_space *space); __isl_give isl_space *isl_space_params(__isl_take isl_space *space); __isl_give isl_space *isl_space_set_from_params(__isl_take isl_space *space); __isl_give isl_space *isl_space_align_params(__isl_take isl_space *dim1, __isl_take isl_space *dim2); isl_bool isl_space_is_wrapping(__isl_keep isl_space *dim); isl_bool isl_space_domain_is_wrapping(__isl_keep isl_space *space); isl_bool isl_space_range_is_wrapping(__isl_keep isl_space *space); isl_bool isl_space_is_product(__isl_keep isl_space *space); __isl_give isl_space *isl_space_wrap(__isl_take isl_space *dim); __isl_give isl_space *isl_space_unwrap(__isl_take isl_space *dim); isl_bool isl_space_can_zip(__isl_keep isl_space *space); __isl_give isl_space *isl_space_zip(__isl_take isl_space *dim); isl_bool isl_space_can_curry(__isl_keep isl_space *space); __isl_give isl_space *isl_space_curry(__isl_take isl_space *space); isl_bool isl_space_can_range_curry(__isl_keep isl_space *space); __isl_give isl_space *isl_space_range_curry(__isl_take isl_space *space); isl_bool isl_space_can_uncurry(__isl_keep isl_space *space); __isl_give isl_space *isl_space_uncurry(__isl_take isl_space *space); isl_bool isl_space_is_domain(__isl_keep isl_space *space1, __isl_keep isl_space *space2); isl_bool isl_space_is_range(__isl_keep isl_space *space1, __isl_keep isl_space *space2); isl_bool isl_space_is_equal(__isl_keep isl_space *space1, __isl_keep isl_space *space2); isl_bool isl_space_has_equal_params(__isl_keep isl_space *space1, __isl_keep isl_space *space2); isl_bool isl_space_has_equal_tuples(__isl_keep isl_space *space1, __isl_keep isl_space *space2); isl_bool isl_space_tuple_is_equal(__isl_keep isl_space *space1, enum isl_dim_type type1, __isl_keep isl_space *space2, enum isl_dim_type type2); ISL_DEPRECATED isl_bool isl_space_match(__isl_keep isl_space *space1, enum isl_dim_type type1, __isl_keep isl_space *space2, enum isl_dim_type type2); unsigned isl_space_dim(__isl_keep isl_space *dim, enum isl_dim_type type); __isl_give isl_space *isl_space_flatten_domain(__isl_take isl_space *space); __isl_give isl_space *isl_space_flatten_range(__isl_take isl_space *space); __isl_give char *isl_space_to_str(__isl_keep isl_space *space); __isl_give isl_printer *isl_printer_print_space(__isl_take isl_printer *p, __isl_keep isl_space *dim); void isl_space_dump(__isl_keep isl_space *dim); #if defined(__cplusplus) } #endif #endif
{ "content_hash": "eeaabccc5c0b21d99eb530a7fc96fc64", "timestamp": "", "source": "github", "line_count": 168, "max_line_length": 79, "avg_line_length": 44.767857142857146, "alnum_prop": 0.7101449275362319, "repo_name": "youtube/cobalt_sandbox", "id": "deb592b897be2562b350e32c23700e8cf6bac589", "size": "7769", "binary": false, "copies": "3", "ref": "refs/heads/main", "path": "third_party/llvm-project/polly/lib/External/isl/include/isl/space.h", "mode": "33188", "license": "bsd-3-clause", "language": [], "symlink_target": "" }
========== Connectors ========== Connectors are the source of all data for queries in Presto. Even if your data source doesn't have underlying tables backing it, as long as you adapt your data source to the API expected by Presto, you can write queries against this data. ConnectorSplit ---------------- Instances of your connector splits. The ``getNodeSelectionStrategy`` method indicates the node affinity of a Split,it has three options: ``HARD_AFFINITY``: Split is NOT remotely accessible and has to be on specific nodes ``SOFT_AFFINITY``: Connector split provides a list of preferred nodes for engine to pick from but not mandatory. ``NO_PREFERENCE``: Split is remotely accessible and can be on any nodes The ``getPreferredNodes`` method provides a list of preferred nodes for scheduler to pick. The scheduler will respect the preference if the strategy is HARD_AFFINITY. Otherwise, the scheduler will prioritize the provided nodes if the strategy is SOFT_AFFINITY. But there is no guarantee that the scheduler will pick them if the provided nodes are busy. Empty list indicates no preference. ConnectorFactory ---------------- Instances of your connector are created by a ``ConnectorFactory`` instance which is created when Presto calls ``getConnectorFactory()`` on the plugin. The connector factory is a simple interface responsible for creating an instance of a ``Connector`` object that returns instances of the following services: * ``ConnectorMetadata`` * ``ConnectorSplitManager`` * ``ConnectorHandleResolver`` * ``ConnectorRecordSetProvider`` ConnectorMetadata ^^^^^^^^^^^^^^^^^ The connector metadata interface has a large number of important methods that are responsible for allowing Presto to look at lists of schemas, lists of tables, lists of columns, and other metadata about a particular data source. This interface is too big to list in this documentation, but if you are interested in seeing strategies for implementing these methods, look at the :doc:`example-http` and the Cassandra connector. If your underlying data source supports schemas, tables and columns, this interface should be straightforward to implement. If you are attempting to adapt something that is not a relational database (as the Example HTTP connector does), you may need to get creative about how you map your data source to Presto's schema, table, and column concepts. ConnectorSplitManger ^^^^^^^^^^^^^^^^^^^^ The split manager partitions the data for a table into the individual chunks that Presto will distribute to workers for processing. For example, the Hive connector lists the files for each Hive partition and creates one or more split per file. For data sources that don't have partitioned data, a good strategy here is to simply return a single split for the entire table. This is the strategy employed by the Example HTTP connector. ConnectorRecordSetProvider ^^^^^^^^^^^^^^^^^^^^^^^^^^ Given a split and a list of columns, the record set provider is responsible for delivering data to the Presto execution engine. It creates a ``RecordSet``, which in turn creates a ``RecordCursor`` that is used by Presto to read the column values for each row.
{ "content_hash": "fe7ca1073e287f77ce46e7d6d44489d7", "timestamp": "", "source": "github", "line_count": 83, "max_line_length": 79, "avg_line_length": 38.265060240963855, "alnum_prop": 0.7729848866498741, "repo_name": "mvp/presto", "id": "c77877890e3d3dd5916780be5022360dec39fd36", "size": "3176", "binary": false, "copies": "5", "ref": "refs/heads/master", "path": "presto-docs/src/main/sphinx/develop/connectors.rst", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "ANTLR", "bytes": "28355" }, { "name": "CSS", "bytes": "13127" }, { "name": "HTML", "bytes": "28633" }, { "name": "Java", "bytes": "34991851" }, { "name": "JavaScript", "bytes": "215251" }, { "name": "Makefile", "bytes": "6830" }, { "name": "PLSQL", "bytes": "2797" }, { "name": "Python", "bytes": "8714" }, { "name": "SQLPL", "bytes": "926" }, { "name": "Shell", "bytes": "29909" }, { "name": "TSQL", "bytes": "161695" }, { "name": "Thrift", "bytes": "12631" } ], "symlink_target": "" }
if(DEFINED HUNTER_CMAKE_PROJECTS_QT_QTSERIALPORT_HUNTER_CMAKE_) return() else() set(HUNTER_CMAKE_PROJECTS_QT_QTSERIALPORT_HUNTER_CMAKE_ 1) endif() include(hunter_add_package) include(hunter_download) include(hunter_generate_qt_info) include(hunter_pick_scheme) include(hunter_status_debug) ## 5.5 only -- string(COMPARE EQUAL "qtserialport" "qtquick1" _is_qtquick1) string(COMPARE EQUAL "qtserialport" "qtwebkit" _is_qtwebkit) string(COMPARE EQUAL "qtserialport" "qtwebkit-examples" _is_qtwebkit_examples) if(_is_qtquick1 OR _is_qtwebkit OR _is_qtwebkit_examples) if(NOT HUNTER_Qt_VERSION MATCHES "^5\\.5\\.") return() endif() endif() ## -- end ## 5.6 only -- string(COMPARE EQUAL "qtserialport" "qtquickcontrol2" _is_qtquickcontrols2) string(COMPARE EQUAL "qtserialport" "qtwebview" _is_qtwebview) if(_is_qtquickcontrols2 OR _is_qtwebview) if(NOT HUNTER_Qt_VERSION MATCHES "^5\\.6\\.") return() endif() endif() ## -- end hunter_generate_qt_info( "qtserialport" _unused_toskip _depends_on _unused_nobuild "${HUNTER_Qt_VERSION}" "${ANDROID}" "${WIN32}" ) foreach(_x ${_depends_on}) hunter_add_package(Qt COMPONENTS ${_x}) endforeach() # We should call this function again since hunter_add_package is include-like # instruction, i.e. will overwrite variable values (foreach's _x will survive) hunter_generate_qt_info( "qtserialport" _unused_toskip _unused_depends_on _nobuild "${HUNTER_Qt_VERSION}" "${ANDROID}" "${WIN32}" ) list(FIND _nobuild "qtserialport" _dont_build_it) if(NOT _dont_build_it EQUAL -1) hunter_status_debug( "Qt component doesn't install anything and will be skipped: qtserialport" ) return() endif() string(COMPARE EQUAL "qtserialport" "qtdeclarative" _is_qtdeclarative) if(WIN32 AND _is_qtdeclarative) find_program(_python_path NAME "python" PATHS ENV PATH) if(NOT _python_path) hunter_user_error( "Python not found in PATH:\n $ENV{PATH}\n" "Python required for building Qt component (qtdeclarative):\n" " http://doc.qt.io/qt-5/windows-requirements.html" ) endif() endif() hunter_pick_scheme(DEFAULT url_sha1_qt) hunter_download( PACKAGE_NAME Qt PACKAGE_COMPONENT "qtserialport" PACKAGE_INTERNAL_DEPS_ID "1" )
{ "content_hash": "5ce1dd76d14bc1239bf9cad41b7bb8cd", "timestamp": "", "source": "github", "line_count": 87, "max_line_length": 79, "avg_line_length": 26.24137931034483, "alnum_prop": 0.6990801576872536, "repo_name": "sumedhghaisas/hunter", "id": "41c9c7e056653b905a2e70e0522b7f06576e0e19", "size": "2344", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "cmake/projects/Qt/qtserialport/hunter.cmake", "mode": "33188", "license": "bsd-2-clause", "language": [ { "name": "C++", "bytes": "51275" }, { "name": "CMake", "bytes": "531743" }, { "name": "Python", "bytes": "10091" }, { "name": "Shell", "bytes": "11378" } ], "symlink_target": "" }
'use strict'; // Declare app level module which depends on filters, and services angular.module('myApp', [ 'ngRoute', 'myApp.filters', 'myApp.services', 'myApp.directives', 'myApp.controllers' ]). filter('toHumanReadableFormat',function () { return function (input) { var millisec, seconds, minutes = 0; function pad(n, width, z) { z = z || '0'; n = n + ''; return n.length >= width ? n : new Array(width - n.length + 1).join(z) + n; } if (input === 3600000) return 'n/a' millisec = pad(Math.floor(input % 1000), 3, 0); input /= 1000; seconds = pad(Math.floor(input % 60), 2, 0); input /= 60; minutes = pad(Math.floor(input % 60), 2, 0); return [[minutes, seconds].join(':'), millisec].join('.') } }). config(['$routeProvider', function ($routeProvider) { $routeProvider.when('/generalka', {templateUrl: 'partials/partial0.html'}); $routeProvider.when('/proba1', {templateUrl: 'partials/partial1.html'}); $routeProvider.when('/proba2', {templateUrl: 'partials/partial2.html'}); $routeProvider.otherwise({redirectTo: '/generalka'}); }]);
{ "content_hash": "a55bc646d29509356a9d7416f24b7863", "timestamp": "", "source": "github", "line_count": 39, "max_line_length": 91, "avg_line_length": 34.23076923076923, "alnum_prop": 0.5235955056179775, "repo_name": "piotrlochowski/simplegui", "id": "723eb5ba155d1a301f2973cad83aa006fecbc3d2", "size": "1335", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "app/js/app.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "4812" }, { "name": "JavaScript", "bytes": "2707589" }, { "name": "Ruby", "bytes": "503" }, { "name": "Shell", "bytes": "1026" } ], "symlink_target": "" }
window.onload = function(){ (function() { // requestAnimationFrame polyfill by Erik Möller // fixes from Paul Irish and Tino Zijdel var lastTime = 0; var vendors = ['ms', 'moz', 'webkit', 'o']; for(var x = 0; x < vendors.length && !window.requestAnimationFrame; ++x) { window.requestAnimationFrame = window[vendors[x]+'RequestAnimationFrame']; window.cancelAnimationFrame = window[vendors[x]+'CancelAnimationFrame'] || window[vendors[x]+'CancelRequestAnimationFrame']; } if (!window.requestAnimationFrame) window.requestAnimationFrame = function(callback, element) { var currTime = new Date().getTime(); var timeToCall = Math.max(0, 16 - (currTime - lastTime)); var id = window.setTimeout(function() { callback(currTime + timeToCall); }, timeToCall); lastTime = currTime + timeToCall; return id; }; if (!window.cancelAnimationFrame) window.cancelAnimationFrame = function(id) { clearTimeout(id); }; }()); //define removeByIndex method as part of the array Array.prototype.removeByIndex = function(index) { this.splice(index, 1); } //GEt angle from two points findAngle = function(x1, y1, x2, y2){ deltaX = x2 - x1; deltaY = y2 - y1; angle = Math.atan2(deltaY, deltaX); return angle; } function makeid() { var text = ""; var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"; for( var i=0; i < 10; i++ ) text += possible.charAt(Math.floor(Math.random() * possible.length)); return text; } } helpers = function(){ } helpers.prototype = { findAngle : function(x1, y1, x2, y2){ deltaX = x2 - x1; deltaY = y2 - y1; angle = Math.atan2(deltaY, deltaX); return angle; } } help = new helpers();
{ "content_hash": "af2e124d73650e84a94779b4b516edf4", "timestamp": "", "source": "github", "line_count": 70, "max_line_length": 85, "avg_line_length": 25.285714285714285, "alnum_prop": 0.6559322033898305, "repo_name": "spoeken/waves", "id": "fd04c36782de53699403d6ac323d9f67f486064f", "size": "1771", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "js/helpers.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "1092" }, { "name": "JavaScript", "bytes": "15626" } ], "symlink_target": "" }
// Copyright (c) 2010-2013 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using System; using NUnit.Framework; namespace ICSharpCode.NRefactory.CSharp.Parser.Expression { [TestFixture] public class ObjectCreateExpressionTests { [Test] public void Simple() { ParseUtilCSharp.AssertExpression( "new MyObject(1, 2, 3)", new ObjectCreateExpression { Type = new SimpleType("MyObject"), Arguments = { new PrimitiveExpression(1), new PrimitiveExpression(2), new PrimitiveExpression(3) }}); } [Test] public void Nullable() { ParseUtilCSharp.AssertExpression( "new IntPtr?(1)", new ObjectCreateExpression { Type = new SimpleType("IntPtr").MakeNullableType(), Arguments = { new PrimitiveExpression(1) } }); } [Test] public void ObjectInitializer() { ParseUtilCSharp.AssertExpression( "new Point() { X = 0, Y = 1 }", new ObjectCreateExpression { Type = new SimpleType("Point"), Initializer = new ArrayInitializerExpression { Elements = { new NamedExpression("X", new PrimitiveExpression(0)), new NamedExpression("Y", new PrimitiveExpression(1)) } }}); } [Test] public void ObjectInitializerWithoutParenthesis() { ParseUtilCSharp.AssertExpression( "new Point { X = 0, Y = 1 }", new ObjectCreateExpression { Type = new SimpleType("Point"), Initializer = new ArrayInitializerExpression { Elements = { new NamedExpression("X", new PrimitiveExpression(0)), new NamedExpression("Y", new PrimitiveExpression(1)) } }}); } [Test] public void ObjectInitializerWithTrailingComma() { ParseUtilCSharp.AssertExpression( "new Point() { X = 0, Y = 1, }", new ObjectCreateExpression { Type = new SimpleType("Point"), Initializer = new ArrayInitializerExpression { Elements = { new NamedExpression("X", new PrimitiveExpression(0)), new NamedExpression("Y", new PrimitiveExpression(1)) } }}); } [Test] public void NestedObjectInitializer() { ParseUtilCSharp.AssertExpression( "new Rectangle { P1 = new Point { X = 0, Y = 1 }, P2 = new Point { X = 2, Y = 3 } }", new ObjectCreateExpression { Type = new SimpleType("Rectangle"), Initializer = new ArrayInitializerExpression { Elements = { new NamedExpression( "P1", new ObjectCreateExpression { Type = new SimpleType("Point"), Initializer = new ArrayInitializerExpression { Elements = { new NamedExpression("X", new PrimitiveExpression(0)), new NamedExpression("Y", new PrimitiveExpression(1)) } }}), new NamedExpression( "P2", new ObjectCreateExpression { Type = new SimpleType("Point"), Initializer = new ArrayInitializerExpression { Elements = { new NamedExpression("X", new PrimitiveExpression(2)), new NamedExpression("Y", new PrimitiveExpression(3)) } }}) }}}); } [Test] public void NestedObjectInitializerForPreinitializedProperty() { ParseUtilCSharp.AssertExpression( "new Rectangle { P1 = { X = 0, Y = 1 }, P2 = { X = 2, Y = 3 } }", new ObjectCreateExpression { Type = new SimpleType("Rectangle"), Initializer = new ArrayInitializerExpression { Elements = { new NamedExpression( "P1", new ArrayInitializerExpression { Elements = { new NamedExpression("X", new PrimitiveExpression(0)), new NamedExpression("Y", new PrimitiveExpression(1)) } }), new NamedExpression( "P2", new ArrayInitializerExpression { Elements = { new NamedExpression("X", new PrimitiveExpression(2)), new NamedExpression("Y", new PrimitiveExpression(3)) } }) }}}); } [Test] public void CollectionInitializer() { ParseUtilCSharp.AssertExpression( "new List<int> { 0, 1, 2 }", new ObjectCreateExpression { Type = new SimpleType("List", new PrimitiveType("int")), Initializer = new ArrayInitializerExpression { Elements = { new ArrayInitializerExpression(new PrimitiveExpression(0)), new ArrayInitializerExpression(new PrimitiveExpression(1)), new ArrayInitializerExpression(new PrimitiveExpression(2)) }}}); } [Test] public void DictionaryInitializer() { ParseUtilCSharp.AssertExpression( "new Dictionary<string, int> { { \"a\", 0 }, { \"b\", 1 } }", new ObjectCreateExpression { Type = new SimpleType("Dictionary", new PrimitiveType("string"), new PrimitiveType("int")), Initializer = new ArrayInitializerExpression { Elements = { new ArrayInitializerExpression { Elements = { new PrimitiveExpression("a"), new PrimitiveExpression(0) } }, new ArrayInitializerExpression { Elements = { new PrimitiveExpression("b"), new PrimitiveExpression(1) } } }}}); } [Test] public void ComplexCollectionInitializer() { ParseUtilCSharp.AssertExpression( @"new List<Contact> { new Contact { Name = ""Chris"", PhoneNumbers = { ""206-555-0101"" } }, new Contact(additionalParameter) { Name = ""Bob"", PhoneNumbers = { ""650-555-0199"", ""425-882-8080"" } } }", new ObjectCreateExpression { Type = new SimpleType("List", new SimpleType("Contact")), Initializer = new ArrayInitializerExpression( new ArrayInitializerExpression( new ObjectCreateExpression { Type = new SimpleType("Contact"), Initializer = new ArrayInitializerExpression { Elements = { new NamedExpression("Name", new PrimitiveExpression("Chris")), new NamedExpression("PhoneNumbers", new ArrayInitializerExpression () { Elements = { new ArrayInitializerExpression(new PrimitiveExpression("206-555-0101")) } }) }}}), new ArrayInitializerExpression( new ObjectCreateExpression { Type = new SimpleType("Contact"), Arguments = { new IdentifierExpression("additionalParameter") }, Initializer = new ArrayInitializerExpression { Elements = { new NamedExpression("Name", new PrimitiveExpression("Bob")), new NamedExpression("PhoneNumbers", new ArrayInitializerExpression () { Elements = { new ArrayInitializerExpression(new PrimitiveExpression("650-555-0199")), new ArrayInitializerExpression(new PrimitiveExpression("425-882-8080")) } }) }}}) )}); } [Test] public void AssignmentInCollectionInitializer() { ParseUtilCSharp.AssertExpression( @"new List<int> { { a = 1 } }", new ObjectCreateExpression { Type = new SimpleType("List", new PrimitiveType("int")), Initializer = new ArrayInitializerExpression { Elements = { new ArrayInitializerExpression { Elements = { new AssignmentExpression(new IdentifierExpression("a"), new PrimitiveExpression(1)) } } }}}); } } }
{ "content_hash": "c7cf1eaeaa9492888ebb82ae3858b251", "timestamp": "", "source": "github", "line_count": 252, "max_line_length": 97, "avg_line_length": 32.964285714285715, "alnum_prop": 0.642349825448417, "repo_name": "korbenzhang/vim-ycm-win", "id": "4a69001508eada71ed802aab1247633e8872774e", "size": "8309", "binary": false, "copies": "20", "ref": "refs/heads/master", "path": "third_party/ycmd/third_party/OmniSharpServer/NRefactory/ICSharpCode.NRefactory.Tests/CSharp/Parser/Expression/ObjectCreateExpressionTests.cs", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Python", "bytes": "93345" }, { "name": "VimL", "bytes": "30287" } ], "symlink_target": "" }
using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; using System; namespace MonoEngine.Graphics { public interface IRenderService : IDisposable { SpriteBatch SpriteBatch { get; } GraphicsDevice GraphicsDevice { get; } Rectangle ViewPortRectangle { get; } } }
{ "content_hash": "1c9af6c807e3af866c7a6f501bfc3820", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 49, "avg_line_length": 24.307692307692307, "alnum_prop": 0.7056962025316456, "repo_name": "XinliZ/MonoEngine", "id": "2d4dbb9919f654468360feaeaad3f663427693f4", "size": "318", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "MonoEngine/Graphics/IRenderService.cs", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C#", "bytes": "46562" } ], "symlink_target": "" }
<!-- @license Apache-2.0 Copyright (c) 2018 The Stdlib 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 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. --> # Logarithm of Cumulative Distribution Function > [Laplace][laplace-distribution] distribution logarithm of [cumulative distribution function][cdf]. <section class="intro"> The [cumulative distribution function][cdf] for a [Laplace][laplace-distribution] random variable is <!-- <equation class="equation" label="eq:laplace_cdf" align="center" raw="F(x;\mu,b) =\tfrac{1}{2} + \tfrac{1}{2} \operatorname{sgn}(x-\mu) \left(1-\exp \left(-\frac{|x-\mu|}{b} \right ) \right )" alt="Cumulative distribution function for a Laplace distribution."> --> <div class="equation" align="center" data-raw-text="F(x;\mu,b) =\tfrac{1}{2} + \tfrac{1}{2} \operatorname{sgn}(x-\mu) \left(1-\exp \left(-\frac{|x-\mu|}{b} \right ) \right )" data-equation="eq:laplace_cdf"> <img src="https://cdn.jsdelivr.net/gh/stdlib-js/stdlib@591cf9d5c3a0cd3c1ceec961e5c49d73a68374cb/lib/node_modules/@stdlib/stats/base/dists/laplace/logcdf/docs/img/equation_laplace_cdf.svg" alt="Cumulative distribution function for a Laplace distribution."> <br> </div> <!-- </equation> --> where `mu` is the location parameter and `b > 0` is the scale parameter. </section> <!-- /.intro --> <section class="usage"> ## Usage ```javascript var logcdf = require( '@stdlib/stats/base/dists/laplace/logcdf' ); ``` #### logcdf( x, mu, b ) Evaluates the logarithm of the [cumulative distribution function][cdf] (CDF) for a [Laplace][laplace-distribution] distribution with parameters `mu` (location parameter) and `b > 0` (scale parameter). ```javascript var y = logcdf( 2.0, 0.0, 1.0 ); // returns ~-0.07 y = logcdf( 5.0, 10.0, 3.0 ); // returns ~-2.36 ``` If provided `NaN` as any argument, the function returns `NaN`. ```javascript var y = logcdf( NaN, 0.0, 1.0 ); // returns NaN y = logcdf( 0.0, NaN, 1.0 ); // returns NaN y = logcdf( 0.0, 0.0, NaN ); // returns NaN ``` If provided `b <= 0`, the function returns `NaN`. ```javascript var y = logcdf( 2.0, 0.0, -1.0 ); // returns NaN y = logcdf( 2.0, 0.0, 0.0 ); // returns NaN ``` #### logcdf.factory( mu, b ) Returns a function for evaluating the logarithm of the [cumulative distribution function][cdf] of a [Laplace][laplace-distribution] distribution with parameters `mu` (location parameter) and `b > 0` (scale parameter). ```javascript var mylogcdf = logcdf.factory( 3.0, 1.5 ); var y = mylogcdf( 1.0 ); // returns ~-2.026 y = mylogcdf( 4.0 ); // returns ~-0.297 ``` </section> <!-- /.usage --> <section class="notes"> ## Notes - In virtually all cases, using the `logpdf` or `logcdf` functions is preferable to manually computing the logarithm of the `pdf` or `cdf`, respectively, since the latter is prone to overflow and underflow. </section> <!-- /.notes --> <section class="examples"> ## Examples <!-- eslint no-undef: "error" --> ```javascript var randu = require( '@stdlib/random/base/randu' ); var logcdf = require( '@stdlib/stats/base/dists/laplace/logcdf' ); var mu; var b; var x; var y; var i; for ( i = 0; i < 100; i++ ) { x = randu() * 10.0; mu = randu() * 10.0; b = randu() * 10.0; y = logcdf( x, mu, b ); console.log( 'x: %d, µ: %d, b: %d, ln(F(x;µ,b)): %d', x.toFixed( 4 ), mu.toFixed( 4 ), b.toFixed( 4 ), y.toFixed( 4 ) ); } ``` </section> <!-- /.examples --> <!-- Section for related `stdlib` packages. Do not manually edit this section, as it is automatically populated. --> <section class="related"> </section> <!-- /.related --> <!-- Section for all links. Make sure to keep an empty line after the `section` element and another before the `/section` close. --> <section class="links"> [cdf]: https://en.wikipedia.org/wiki/Cumulative_distribution_function [laplace-distribution]: https://en.wikipedia.org/wiki/Laplace_distribution </section> <!-- /.links -->
{ "content_hash": "5372ddb3cbd35faca780b40ff671cd92", "timestamp": "", "source": "github", "line_count": 162, "max_line_length": 269, "avg_line_length": 26.938271604938272, "alnum_prop": 0.6727772685609532, "repo_name": "stdlib-js/stdlib", "id": "84b6092df8b0851f1db0f92605dba6bc8f8fbb5d", "size": "4366", "binary": false, "copies": "1", "ref": "refs/heads/develop", "path": "lib/node_modules/@stdlib/stats/base/dists/laplace/logcdf/README.md", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Awk", "bytes": "21739" }, { "name": "C", "bytes": "15336495" }, { "name": "C++", "bytes": "1349482" }, { "name": "CSS", "bytes": "58039" }, { "name": "Fortran", "bytes": "198059" }, { "name": "HTML", "bytes": "56181" }, { "name": "Handlebars", "bytes": "16114" }, { "name": "JavaScript", "bytes": "85975525" }, { "name": "Julia", "bytes": "1508654" }, { "name": "Makefile", "bytes": "4806816" }, { "name": "Python", "bytes": "3343697" }, { "name": "R", "bytes": "576612" }, { "name": "Shell", "bytes": "559315" }, { "name": "TypeScript", "bytes": "19309407" }, { "name": "WebAssembly", "bytes": "5980" } ], "symlink_target": "" }
Public methods do not require the use of an api key and can be accessed via the GET method. General Market Data (All Markets): (OLD METHOD) http://pubapi.cryptsy.com/api.php?method=marketdata General Market Data (All Markets): (NEW METHOD) http://pubapi.cryptsy.com/api.php?method=marketdatav2 General Market Data (Single Market): http://pubapi.cryptsy.com/api.php?method=singlemarketdata&marketid={MARKET ID} General Orderbook Data (All Markets): http://pubapi.cryptsy.com/api.php?method=orderdata General Orderbook Data (Single Market): http://pubapi.cryptsy.com/api.php?method=singleorderdata&marketid={MARKET ID} ### Authenticated Methods Authenticated methods require the use of an api key and can only be accessed via the POST method. URL - The URL you will be posting to is: https://api.cryptsy.com/api (notice it does NOT have the '.php' at the end) Authorization is performed by sending the following variables into the request header: Key — Public API key. An example API key: 5a8808b25e3f59d8818d3fbc0ce993fbb82dcf90 Sign — ALL POST data (param=val&param1=val1) signed by a secret key according to HMAC-SHA512 method. Your secret key and public keys can be generated from your account settings page. An additional security element must be passed into the post: nonce - All requests must also include a special nonce POST parameter with incrementing integer. The integer must always be greater than the previous requests nonce value. Other Variables method - The method from the list below which you are accessing. General Return Values success - Either a 1 or a 0. 1 Represents sucessful call, 0 Represents unsuccessful error - If unsuccessful, this will be the error message return - If successful, this will be the data returned ### Method List ##### Method: getinfo Inputs: n/a Outputs: balances_available Array of currencies and the balances availalbe for each balances_hold Array of currencies and the amounts currently on hold for open orders servertimestamp Current server timestamp servertimezone Current timezone for the server serverdatetime Current date/time on the server openordercount Count of open orders on your account ##### Method: getmarkets Inputs: n/a Outputs: Array of Active Markets marketid Integer value representing a market label Name for this market, for example: AMC/BTC primary_currency_code Primary currency code, for example: AMC primary_currency_name Primary currency name, for example: AmericanCoin secondary_currency_code Secondary currency code, for example: BTC secondary_currency_name Secondary currency name, for example: BitCoin current_volume 24 hour trading volume in this market last_trade Last trade price for this market high_trade 24 hour highest trade price in this market low_trade 24 hour lowest trade price in this market created Datetime (EST) the market was created ##### Method: getwalletstatus Inputs: n/a Outputs: Array of Wallet Statuses currencyid Integer value representing a currency name Name for this currency, for example: Bitcoin code Currency code, for example: BTC blockcount Blockcount of currency hot wallet as of lastupdate time difficulty Difficulty of currency hot wallet as of lastupdate time version Version of currency hotwallet as of lastupdate time peercount Connected peers of currency hot wallet as of lastupdate time hashrate Network hashrate of currency hot wallet as of lastupdate time gitrepo Git Repo URL for this currency withdrawalfee Fee charged for withdrawals of this currency lastupdate Datetime (EST) the hot wallet information was last updated ##### Method: mytransactions Inputs: n/a Outputs: Array of Deposits and Withdrawals on your account currency Name of currency account timestamp The timestamp the activity posted datetime The datetime the activity posted timezone Server timezone type Type of activity. (Deposit / Withdrawal) address Address to which the deposit posted or Withdrawal was sent amount Amount of transaction (Not including any fees) fee Fee (If any) Charged for this Transaction (Generally only on Withdrawals) trxid Network Transaction ID (If available) ##### Method: markettrades Inputs: marketid Market ID for which you are querying Outputs: Array of last 1000 Trades for this Market, in Date Decending Order tradeid A unique ID for the trade datetime Server datetime trade occurred tradeprice The price the trade occurred at quantity Quantity traded total Total value of trade (tradeprice * quantity) initiate_ordertype The type of order which initiated this trade ##### Method: marketorders Inputs: marketid Market ID for which you are querying Outputs: 2 Arrays. First array is sellorders listing current open sell orders ordered price ascending. Second array is buyorders listing current open buy orders ordered price descending. sellprice If a sell order, price which order is selling at buyprice If a buy order, price the order is buying at quantity Quantity on order total Total value of order (price * quantity) ##### Method: mytrades Inputs: marketid Market ID for which you are querying limit (optional) Limit the number of results. Default: 200 Outputs: Array your Trades for this Market, in Date Decending Order tradeid An integer identifier for this trade tradetype Type of trade (Buy/Sell) datetime Server datetime trade occurred tradeprice The price the trade occurred at quantity Quantity traded total Total value of trade (tradeprice * quantity) - Does not include fees fee Fee Charged for this Trade initiate_ordertype The type of order which initiated this trade order_id Original order id this trade was executed against ##### Method: allmytrades Inputs: startdate (optional) Starting date for query (format: yyyy-mm-dd) enddate (optional) Ending date for query (format: yyyy-mm-dd) Outputs: Array your Trades for all Markets, in Date Decending Order tradeid An integer identifier for this trade tradetype Type of trade (Buy/Sell) datetime Server datetime trade occurred marketid The market in which the trade occurred tradeprice The price the trade occurred at quantity Quantity traded total Total value of trade (tradeprice * quantity) - Does not include fees fee Fee Charged for this Trade initiate_ordertype The type of order which initiated this trade order_id Original order id this trade was executed against ##### Method: myorders Inputs: marketid Market ID for which you are querying Outputs: Array of your orders for this market listing your current open sell and buy orders. orderid Order ID for this order created Datetime the order was created ordertype Type of order (Buy/Sell) price The price per unit for this order quantity Quantity remaining for this order total Total value of order (price * quantity) orig_quantity Original Total Order Quantity ##### Method: depth Inputs: marketid Market ID for which you are querying Outputs: Array of buy and sell orders on the market representing market depth. Output Format is: array( 'sell'=>array( array(price,quantity), array(price,quantity), .... ), 'buy'=>array( array(price,quantity), array(price,quantity), .... ) ) ##### Method: allmyorders Inputs: n/a Outputs: Array of all open orders for your account. orderid Order ID for this order marketid The Market ID this order was created for created Datetime the order was created ordertype Type of order (Buy/Sell) price The price per unit for this order quantity Quantity remaining for this order total Total value of order (price * quantity) orig_quantity Original Total Order Quantity ##### Method: createorder Inputs: marketid Market ID for which you are creating an order for ordertype Order type you are creating (Buy/Sell) quantity Amount of units you are buying/selling in this order price Price per unit you are buying/selling at Outputs: orderid If successful, the Order ID for the order which was created ##### Method: cancelorder Inputs: orderid Order ID for which you would like to cancel Outputs: n/a. If successful, it will return a success code. ##### Method: cancelmarketorders Inputs: marketid Market ID for which you would like to cancel all open orders Outputs: return Array for return information on each order cancelled ##### Method: cancelallorders Inputs: N/A Outputs: return Array for return information on each order cancelled ##### Method: calculatefees Inputs: ordertype Order type you are calculating for (Buy/Sell) quantity Amount of units you are buying/selling price Price per unit you are buying/selling at Outputs: fee The that would be charged for provided inputs net The net total with fees ##### Method: generatenewaddress Inputs: (either currencyid OR currencycode required - you do not have to supply both) currencyid Currency ID for the coin you want to generate a new address for (ie. 3 = BitCoin) currencycode Currency Code for the coin you want to generate a new address for (ie. BTC = BitCoin) Outputs: address The new generated address ##### Method: mytransfers Inputs: n/a Outputs: Array of all transfers into/out of your account sorted by requested datetime descending. currency Currency being transfered request_timestamp Datetime the transfer was requested/initiated processed Indicator if transfer has been processed (1) or not (0) processed_timestamp Datetime of processed transfer from Username sending transfer to Username receiving transfer quantity Quantity being transfered direction Indicates if transfer is incoming or outgoing (in/out) ##### Method: makewithdrawal Inputs: address Pre-approved Address for which you are withdrawing to (Set up these addresses on Settings page) amount Amount you are withdrawing. Supports up to 8 decimal places. Outputs: Either successful or error. If error, gives reason for error.
{ "content_hash": "119cf137434f3fe31ec5d145d45b316b", "timestamp": "", "source": "github", "line_count": 354, "max_line_length": 187, "avg_line_length": 27.918079096045197, "alnum_prop": 0.7834665587372256, "repo_name": "korlabs/bitsell-beta", "id": "d17808a015ee68cb3776810ba771bf094431b318", "size": "9926", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "api/cryptsy/README.md", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "113894" }, { "name": "HTML", "bytes": "7722" }, { "name": "JavaScript", "bytes": "265117" }, { "name": "PHP", "bytes": "57602" } ], "symlink_target": "" }