text:
"""
Takes a list tokens and converts them to a parse tree
Uses recursive-descent parsing algorithm

Grammar
=======
statement     : identifier '=' expr
              | identifier
expr          : array_expr
              | atom
array_expr    : '[' array_list ']'

array_list    : expr_list  ';' expr_list
              | expr_list

expr_list     : expr ',' expr_list
              | expr expr_list
              | expr

atom          : NUMERIC_LITERAL
              | '-' NUMERIC_LITERAL

identifier    : IDENTIFIER

"""

from __future__ import unicode_literals
from lexer import Token
from errors import MatlabetteSyntaxError

class Parser(object):
    """
    Takes a list tokens and converts them to a parse tree
    """

    def __init__(self, tokens):
        self.tokens = tokens
        self.position = 0

    @property
    def token(self):
        return self.tokens[self.position]

    @property
    def token_type(self):
        return self.token[0]

    @property
    def token_value(self):
        return self.token[1]

    def match(self, token):
        return token == self.token_type

    def consume(self):
        self.position += 1

    def expect(self, token):
        if self.match(token):
            self.consume()
            return True
        raise MatlabetteSyntaxError(self.token_value, token)

    def parse(self):
        if self.match(Token.END_OF_LINE):
            return ParseTreeNode()
        parse_tree = self.statement()
        if parse_tree is None:
            parse_tree = ParseTreeNode(
                operator=u'=',
                left_child=ParseTreeNode(value='ans', locked=True),
                right_child=self.expression(True)
            )
        self.expect(Token.END_OF_LINE)
        return parse_tree

    def statement(self):
        """
        Implements the rule:
            statement     : identifier '=' expr
                          | identifier
        """
        identifier = self.identifier()
        if identifier is not None:
            if self.match(Token.END_OF_LINE):
                node = ParseTreeNode(
                    operator=u'show',
                    value=identifier,
                    locked=True
                )
                return node
            elif self.match(Token.ASSIGN_OPERATOR):
                self.consume()
                node = ParseTreeNode(
                    left_child=ParseTreeNode(value=identifier, locked=True),
                    operator=u'=',
                    right_child=self.expression(True)
                )
                return node
            elif self.match(Token.TRANSPOSE_OPERATOR):
                self.consume()
                node = ParseTreeNode(
                    left_child=ParseTreeNode(value=u'ans', locked=True),
                    operator=u'=',
                    right_child=ParseTreeNode(value=identifier, operator=u'\'')
                )
                return node
            elif self.match(Token.LEFT_PARENTHESIS):
                self.consume()
                function = ParseTreeNode(
                    value=identifier,
                    locked=True
                )
                node = ParseTreeNode(
                    operator=u'call',
                    left_child=function,
                    right_child=ParseTreeNode(value=self.expression_list())
                )
                self.expect(Token.RIGHT_PARENTHESIS)
                return ParseTreeNode(
                    left_child=ParseTreeNode(value=u'ans', locked=True),
                    operator=u'=',
                    right_child=node
                )

            else:
                op, sub_expr = self.sub_expression()
                if sub_expr is not None:
                    return ParseTreeNode(
                        left_child=ParseTreeNode(value=u'ans', locked=True),
                        operator=u'=',
                        right_child=ParseTreeNode(
                            operator=op,
                            left_child=ParseTreeNode(value=identifier),
                            right_child=sub_expr)
                    )
                op, sub_expr = self.sub_term()
                if sub_expr is not None:
                    return ParseTreeNode(
                        left_child=ParseTreeNode(value=u'ans', locked=True),
                        operator=u'=',
                        right_child=ParseTreeNode(
                            operator=op,
                            left_child=ParseTreeNode(value=identifier),
                            right_child=sub_expr)
                    )
                raise MatlabetteSyntaxError(
                    self.token_value,
                    "'=', (, ' or an operator"
                )
        return None

    def expression(self, fail):
        """
        Implements: expression : array_expr | atom
        :param fail: if set to True, raise an exception instead of returning None
        """
        term = self.term()
        if term is not None:
            op, sub_expr = self.sub_expression()
            if sub_expr is not None:
                return ParseTreeNode(
                    operator=op,
                    left_child=term,
                    right_child=sub_expr
                )
            op, sub_expr = self.sub_term()
            if sub_expr is not None:
                return ParseTreeNode(
                    operator=op,
                    left_child=term,
                    right_child=sub_expr
                )
            return term
        if fail:
            raise MatlabetteSyntaxError(
                self.token_value,
                "[ or a number"
            )

    def sub_expression(self):
        node = ParseTreeNode()
        if self.match(Token.SUBTRACT_OPERATOR) \
                or self.match(Token.ADD_OPERATOR) \
                or self.match(Token.ELEM_SUBTRACT_OPERATOR) \
                or self.match(Token.ELEM_ADD_OPERATOR):
            operator = self.token_value
            self.consume()
            node.left_child = self.term()
            if not node.left_child:
                raise MatlabetteSyntaxError(
                    self.token_type,
                    "number"
                )
            node.operator, node.right_child = self.sub_expression()
            return operator, node
        return None, None

    def term(self):
        terminal = self.terminal()
        if terminal:
            op, sub_term = self.sub_term()
            if sub_term is not None:
                return ParseTreeNode(
                    operator=op,
                    left_child=terminal,
                    right_child=sub_term
                )
            return terminal
        return None

    def sub_term(self):
        node = ParseTreeNode()
        if self.match(Token.DIVIDE_OPERATOR) \
                or self.match(Token.MULTIPLY_OPERATOR) \
                or self.match(Token.ELEM_DIVIDE_OPERATOR) \
                or self.match(Token.ELEM_MULTIPLY_OPERATOR):
            operator = self.token_value
            self.consume()
            node.left_child = self.terminal()
            if not node.left_child:
                raise MatlabetteSyntaxError(
                    self.token_type,
                    "number"
                )
            node.operator, node.right_child = self.sub_term()
            return operator, node
        return None, None

    def array_expression(self):
        """
        Implements the rule:
            array_expression : '[' array_list ']'
        """
        if self.match(Token.LEFT_SQUARE_BRACKET):
            self.consume()
            node = self.array_list()
            self.expect(Token.RIGHT_SQUARE_BRACKET)
        else:
            return None
        return node

    def array_list(self):
        """
        Implements the rule:
            array_list : expr_list  ';' expr_list
                       | expr_list
        """
        node = ParseTreeNode(value=[])
        while True:
            if self.match(Token.SEMI_COLON):
                self.consume()
            atoms = self.expression_list()
            if atoms:
                node.value.append(atoms)
            else:
                break
        return node

    def expression_list(self):
        """
        Implements the rule:
            expr_list     : expr ',' expr_list
                          | expr expr_list
                          | expr
        """
        expressions = []
        while True:
            if self.match(Token.COMMA):
                self.consume()
            expression = self.expression(False)
            if expression is not None:
                expressions.append(expression)
            else:
                break
        return expressions

    def terminal(self):
        terminal = self.atom()
        if terminal is None:
            terminal = self.identifier()
            if terminal is not None and self.match(Token.LEFT_PARENTHESIS):
                self.consume()
                function = ParseTreeNode(
                    value=terminal,
                    locked=True
                )
                node = ParseTreeNode(
                    operator=u'call',
                    left_child=function,
                    right_child=ParseTreeNode(value=self.expression_list())
                )
                self.expect(Token.RIGHT_PARENTHESIS)
                return node

        if terminal is not None:
            node = ParseTreeNode(value=terminal)
        else:
            node = self.array_expression()
        if node and self.match(Token.TRANSPOSE_OPERATOR):
            node.operator = self.token_value
            self.consume()
        return node

    def identifier(self):
        """
        Implements the rule:
            identifier : IDENTIFIER
        """
        identifier = None
        if self.match(Token.VARIABLE_NAME) \
                or self.match(Token.BUILTIN_NAME):
            identifier = self.token_value
            self.consume()
        return identifier

    def atom(self):
        """
        Implements the rule:
            atom : NUMERIC_LITERAL
                 | '-' NUMERIC_LITERAL
        """
        value = None
        if self.match(Token.INTEGER_LITERAL) \
                or self.match(Token.FLOAT_LITERAL):
            value = float(self.token_value)
            self.consume()
        elif self.match(Token.SUBTRACT_OPERATOR):
            self.consume()
            value = -self.atom()
        return value

class ParseTreeNode(object):
    """
    One node of the parse tree
    This defines the parse tree recursively
    """

    def __init__(self, **kwargs):
        self.operator = kwargs.get("operator")
        self.left_child = kwargs.get("left_child")
        self.right_child = kwargs.get("right_child")
        self.value = kwargs.get("value")
        self.locked = kwargs.get("locked", False)


text:
<?xml version="1.0"?>
<!DOCTYPE Configure PUBLIC "-//Jetty//Configure//EN" "http://www.eclipse.org/jetty/configure_9_3.dtd">

<!-- =============================================================== -->
<!-- Configure extended support for webapps                          -->
<!-- =============================================================== -->
<Configure id="Server" class="org.eclipse.jetty.server.Server">

  <!-- =========================================================== -->
  <!-- Add plus Configuring classes to all webapps for this Server -->
  <!-- =========================================================== -->
  <Call class="org.eclipse.jetty.webapp.Configuration$ClassList" name="setServerDefault">
    <Arg><Ref refid="Server" /></Arg>
    <Call name="addAfter">
      <Arg name="afterClass">org.eclipse.jetty.webapp.FragmentConfiguration</Arg>
      <Arg>
        <Array type="String">
          <Item>org.eclipse.jetty.plus.webapp.EnvConfiguration</Item>
          <Item>org.eclipse.jetty.plus.webapp.PlusConfiguration</Item>
        </Array>
      </Arg>
    </Call>
  </Call>

</Configure>

redpajama_set_name: RedPajamaGithub


text:
using namespace cgv::base;
using namespace cgv::signal;
using namespace cgv::gui;
using namespace cgv::math;
using namespace cgv::render;
using namespace cgv::utils;

class exercise1 : public node,
                  public drawable,
                  public provider,
                  public event_handler
{
private:
    // The example meshs
    obj_reader *meshs[11];
    // The animation counter
    int counter;
    // True if the mesh shall be rendered as a point cloud
    bool is_pointcloud;
    // True if a bounding box shall be rendered
    bool show_bbox;
    // True if coordinate systems shall be rendered
    bool show_coordinate_system;
    // True iff in free mode
    bool free_mode;
    // Counter to ensure smooth frames
    double timer_offset;

    bool meshs_loaded;

    // True if the ascending animation is shown
    bool ascending;
    // Time when the ascension is/was started
    int ascension_counter_start;
    // Step animation position when the ascension started
    float ascension_step_ani;
    // Current ascension speed
    dake::vec3 ascension_speed;
    // Current center in ascension
    dake::vec3 ascension_position;
    // Current ascension acceleration
    dake::vec3 ascension_acceleration;
    // Current direction
    float dir_x, dir_y;

    // Render the mesh "model". This method calls render_mesh_pointcloud
    // if the variable "is_pointcloud" is true and "render_mesh_solid"
    // otherwise.
    void render_mesh(obj_reader *model);

    // Render the mesh "model" as a point cloud
    void render_mesh_pointcloud(obj_reader *model);

    // Render the mesh "model" as solid geometry
    void render_mesh_solid(obj_reader *model);

    // Render the bounding box of a mesh. This method is called from
    // render_mesh if show_bbox is set to true
    void render_bounding_box(obj_reader* model);

    // Render a simple coordinate system
    void render_coordinate_system();

    // The timer event. This method is called every 1/60 sec.
    void timer_event(double, double dt);

    // Goddess Madoka gives you hope
    void ascension(void);

    // But I want Madoka D:
    void rematerialize(void);

    // Toggle free mode™
    void toggle_free_mode(void);

    // Method that is called whenever a gui element is clicked
    void on_set(void* member_ptr);

public:
    // The constructor of this class
    exercise1();

    // Create the gui elements
    void create_gui();
    // Draw the scene
    void draw(context& c);

    virtual bool handle(event &e);
    virtual void stream_help(std::ostream &os);
};


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<title>Uses of Class org.drip.spline.params.SegmentInelasticDesignControl</title>
<meta name="date" content="2017-01-04">
<link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes

Uses of Class
org.drip.spline.params.SegmentInelasticDesignControl

Packages that use SegmentInelasticDesignControl

Package
Description

org.drip.sample.stretch

org.drip.spline.params

org.drip.spline.segment

org.drip.state.creator

Uses of SegmentInelasticDesignControl in org.drip.sample.stretch

Methods in org.drip.sample.stretch with parameters of type SegmentInelasticDesignControl

Modifier and Type
Method and Description

static SegmentCustomBuilderControl
KnotInsertionPolynomialEstimator.ExponentialTensionSegmentControlParams(double dblTension,
                                      SegmentInelasticDesignControl sdic,
                                      ResponseScalingShapeControl rssc)

static SegmentCustomBuilderControl
CurvatureRoughnessPenaltyFit.PolynomialSegmentControlParams(int iNumBasis,
                              SegmentInelasticDesignControl sdic,
                              ResponseScalingShapeControl rssc)

static SegmentCustomBuilderControl
CurvatureLengthRoughnessPenalty.PolynomialSegmentControlParams(int iNumBasis,
                              SegmentInelasticDesignControl sdic,
                              ResponseScalingShapeControl rssc)

Uses of SegmentInelasticDesignControl in org.drip.spline.params

Methods in org.drip.spline.params that return SegmentInelasticDesignControl

Modifier and Type
Method and Description

static SegmentInelasticDesignControl
SegmentInelasticDesignControl.Create(int iCk,
      int iCurvaturePenaltyDerivativeOrder)

Create the Inelastic Design Parameters for the desired Ck Criterion and the Roughness Penalty Order

SegmentInelasticDesignControl
SegmentCustomBuilderControl.inelasticParams()

Retrieve the Segment Inelastic Parameters

static SegmentInelasticDesignControl
SegmentInelasticDesignControl.MakeC2DesignInelasticControl()

Create the C2 Inelastic Design Params

Constructors in org.drip.spline.params with parameters of type SegmentInelasticDesignControl

Constructor and Description

SegmentCustomBuilderControl(java.lang.String strBasisSpline,
                           FunctionSetBuilderParams fsbp,
                           SegmentInelasticDesignControl sdic,
                           ResponseScalingShapeControl rssc,
                           PreceedingManifestSensitivityControl pmsc)

SegmentCustomBuilderControl constructor

Uses of SegmentInelasticDesignControl in org.drip.spline.segment

Methods in org.drip.spline.segment that return SegmentInelasticDesignControl

Modifier and Type
Method and Description

SegmentInelasticDesignControl
LatentStateResponseModel.designControl()

Retrieve the Segment Inelastic Design Control

Methods in org.drip.spline.segment with parameters of type SegmentInelasticDesignControl

Modifier and Type
Method and Description

static LatentStateResponseModel
LatentStateResponseModel.Create(double dblLeftPredictorOrdinate,
      double dblRightPredictorOrdinate,
      BasisEvaluator be,
      SegmentInelasticDesignControl sidc)

Build the LatentStateResponseModel instance from the Basis Evaluator Set

static LatentStateResponseModel
LatentStateResponseModel.Create(double dblLeftPredictorOrdinate,
      double dblRightPredictorOrdinate,
      FunctionSet fs,
      ResponseScalingShapeControl rssc,
      SegmentInelasticDesignControl sidc)

Build the LatentStateResponseModel instance from the Basis Function/Shape Controller Set

Uses of SegmentInelasticDesignControl in org.drip.state.creator

Methods in org.drip.state.creator with parameters of type SegmentInelasticDesignControl

Modifier and Type
Method and Description

static GovvieCurve
ScenarioGovvieCurveBuilder.<a href="../../../../../org/drip/state/creator/ScenarioGovvieCurveBuilder.html#ShapePreservingGovvieCurve-java.lang.String-java.lang.String-java.lang.String-org.drip.param.valuation.ValuationParams-org.drip.param.pricer.CreditPricerParams-org.drip.param.market.CurveSurfaceQuoteContainer-org.drip.param.valuation.ValuationCustomizationParams-java.lang.String-org.drip.spline.basis.FunctionSetBuilderParams-org.drip.spline.params.SegmentInelasticDesignControl-org.drip.product.definition.CalibratableComponent:A-java.lang.String-double:A-">ShapePreservingGovvieCurve(java.lang.String strName,
                          java.lang.String strTreasuryCode,
                          java.lang.String strCurrency,
                          ValuationParams valParams,
                          CreditPricerParams pricerParams,
                          CurveSurfaceQuoteContainer csqc,
                          ValuationCustomizationParams vcp,
                          java.lang.String strBasisType,
                          FunctionSetBuilderParams fsbp,
                          SegmentInelasticDesignControl sdic,
                          CalibratableComponent[] aCalibComp,
                          java.lang.String strManifestMeasure,
                          double[] adblQuote)

Construct an Instance of the Shape Preserver of the desired Basis Spline Type, using the specified
  Basis Spline Set Builder Parameters.

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes


text:
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.

#ifndef PX_PHYSICS_COMMON_SCALING
#define PX_PHYSICS_COMMON_SCALING

#include "foundation/PxBounds3.h"
#include "geometry/PxMeshScale.h"
#include "CmMatrix34.h"
#include "PsMathUtils.h"
#include "foundation/PxMat33.h"

namespace physx
{
namespace Cm
{
	PX_CUDA_CALLABLE PX_INLINE PxBounds3 transformBounds34(const Cm::Matrix34& matrix, const PxBounds3& bounds)
	{
		if( bounds.isEmpty() )
			return bounds;
		else
		{
			PxMat33 M(matrix.base0, matrix.base1, matrix.base2);
			return PxBounds3::basisExtent(matrix.transform( bounds.getCenter()), M, bounds.getExtents());
		}
	}

	// class that can perform scaling fast.  Relatively large size, generated from PxMeshScale on demand.
	// CS: I've removed most usages of this class, because most of the time only one-way transform is needed.
	// If you only need a temporary FastVertex2ShapeScaling, setup your transform as PxMat34Legacy and use
	// normal matrix multiplication or a transform() overload to convert points and bounds between spaces.
	class FastVertex2ShapeScaling
	{
	public:
		PX_INLINE FastVertex2ShapeScaling()
		{
			//no scaling by default:
			vertex2ShapeSkew = PxMat33(PxIdentity);
			shape2VertexSkew = PxMat33(PxIdentity);
			mFlipNormal = false;
		}

		PX_INLINE explicit FastVertex2ShapeScaling(const PxMeshScale& scale)
		{
			init(scale);
		}

		PX_INLINE FastVertex2ShapeScaling(const PxVec3& scale, const PxQuat& rotation)
		{
			init(scale, rotation);
		}

		PX_INLINE void init(const PxMeshScale& scale)
		{
			init(scale.scale, scale.rotation);
		}

		PX_INLINE void setIdentity()
		{
			vertex2ShapeSkew = PxMat33(PxIdentity);
			shape2VertexSkew = PxMat33(PxIdentity);
			mFlipNormal = false;
		}

		PX_INLINE void init(const PxVec3& scale, const PxQuat& rotation)
		{
			// TODO: may want to optimize this for cases where we have uniform or axis aligned scaling!
			// That would introduce branches and it's unclear to me whether that's faster than just doing the math.
			// Lazy computation would be another option, at the cost of introducing even more branches.

			PxMat33 R(rotation);
			vertex2ShapeSkew = R.getTranspose();
			PxMat33 diagonal = PxMat33::createDiagonal(scale);
			vertex2ShapeSkew = vertex2ShapeSkew * diagonal;
			vertex2ShapeSkew = vertex2ShapeSkew * R;

			/*
			The inverse, is, explicitly:
			shape2VertexSkew.setTransposed(R);
			shape2VertexSkew.multiplyDiagonal(PxVec3(1.0f/scale.x, 1.0f/scale.y, 1.0f/scale.z));
			shape2VertexSkew *= R;

			It may be competitive to compute the inverse -- though this has a branch in it:
			*/

			shape2VertexSkew = vertex2ShapeSkew.getInverse();

			mFlipNormal = ((scale.x * scale.y * scale.z) < 0.0f);
		}

		PX_FORCE_INLINE void flipNormal(PxVec3& v1, PxVec3& v2) const
		{
			if (mFlipNormal)
			{
				PxVec3 tmp = v1; v1 = v2; v2 = tmp;
			}
		}

		PX_FORCE_INLINE PxVec3 operator*  (const PxVec3& src) const
		{
			return vertex2ShapeSkew * src;
		}
		PX_FORCE_INLINE PxVec3 operator%  (const PxVec3& src) const
		{
			return shape2VertexSkew * src;
		}

		PX_FORCE_INLINE const PxMat33& getVertex2ShapeSkew() const
		{
			return vertex2ShapeSkew;
		}

		PX_FORCE_INLINE const PxMat33& getShape2VertexSkew() const
		{
			return shape2VertexSkew;
		}

		PX_INLINE Cm::Matrix34 getVertex2WorldSkew(const Cm::Matrix34& shape2world) const
		{
			Cm::Matrix34 vertex2worldSkew = shape2world * getVertex2ShapeSkew();
			//vertex2worldSkew = shape2world * [vertex2shapeSkew, 0]
			//[aR at] * [bR bt] = [aR * bR		aR * bt + at]  NOTE: order of operations important so it works when this ?= left ?= right.
			return vertex2worldSkew;
		}

		PX_INLINE Cm::Matrix34 getWorld2VertexSkew(const Cm::Matrix34& shape2world) const
		{
			//world2vertexSkew = shape2vertex * invPQ(shape2world)
			//[aR 0] * [bR' -bR'*bt] = [aR * bR'		-aR * bR' * bt + 0]

			PxMat33 rotate( shape2world[0], shape2world[1], shape2world[2] );
			PxMat33 M = getShape2VertexSkew() * rotate.getTranspose();
			return Cm::Matrix34(M[0], M[1], M[2], -M * shape2world[3]);
		}

		//! Transforms bounds first by this scale transform and then by absPose.  Useful for computing the bounds of a scaled object in world space.
		PX_INLINE PxBounds3 transformBounds(const PxBounds3& bounds, const PxTransform& shape2World) const
		{
			return transformBounds34(getVertex2WorldSkew(Cm::Matrix34(shape2World)), bounds);
		}

		//! same as transformBounds with absPose == id.
		PX_INLINE PxBounds3 transformBounds(const PxBounds3& bounds) const
		{
			PX_ASSERT(!bounds.isEmpty());
			return PxBounds3::transformFast(vertex2ShapeSkew, bounds);
		}

		//! Transforms a shape space OBB to a vertex space OBB.  All 3 params are in and out.
		void transformQueryBounds(PxVec3& center, PxVec3& extents, PxMat33& basis)	const
		{
			basis.column0 = shape2VertexSkew * (basis.column0 * extents.x);
			basis.column1 = shape2VertexSkew * (basis.column1 * extents.y);
			basis.column2 = shape2VertexSkew * (basis.column2 * extents.z);

			center = shape2VertexSkew * center;
			extents = Ps::optimizeBoundingBox(basis);
		}

		//! Transforms a shape space AABB to a vertex space AABB (conservative). Both parameters are in and out
		void transformQueryBounds(PxVec3& center, PxVec3& extents)	const
		{
			PxBounds3 bounds = PxBounds3::basisExtent(shape2VertexSkew * center, shape2VertexSkew, extents);
			center = bounds.getCenter();
			extents = bounds.getExtents();
		}

		void transformPlaneToShapeSpace(const PxVec3& nIn, const PxReal dIn, PxVec3& nOut, PxReal& dOut)	const
		{
			const PxVec3 tmp = shape2VertexSkew.transformTranspose(nIn);
			const PxReal Denom = 1.0f / tmp.magnitude();
			nOut = tmp * Denom;
			dOut = dIn * Denom;
		}

		PX_FORCE_INLINE bool flipsNormal() const { return mFlipNormal; }

	private:
		PxMat33 vertex2ShapeSkew;
		PxMat33 shape2VertexSkew;
		bool mFlipNormal;
	};

	PX_FORCE_INLINE void getScaledVertices(PxVec3* v, const PxVec3& v0, const PxVec3& v1, const PxVec3& v2, bool idtMeshScale, const Cm::FastVertex2ShapeScaling& scaling)
	{
		if(idtMeshScale)
		{
			v[0] = v0;
			v[1] = v1;
			v[2] = v2;
		}
		else
		{
			const PxI32 winding = scaling.flipsNormal() ? 1 : 0;
			v[0] = scaling * v0;
			v[1+winding] = scaling * v1;
			v[2-winding] = scaling * v2;
		}
	}

} // namespace Cm

PX_INLINE Cm::Matrix34 operator*(const PxTransform& transform, const PxMeshScale& scale)
{
	return Cm::Matrix34(PxMat33(transform.q) * scale.toMat33(), transform.p);
}

PX_INLINE Cm::Matrix34 operator*(const PxMeshScale& scale, const PxTransform& transform)
{
	PxMat33 scaleMat = scale.toMat33();
	PxMat33 t = PxMat33(transform.q);
	PxMat33 r = scaleMat * t;
	PxVec3 p = scaleMat * transform.p;
	return Cm::Matrix34(r, p);
}

PX_INLINE Cm::Matrix34 operator*(const Cm::Matrix34& transform, const PxMeshScale& scale)
{
	PxMat33 scaleMat = scale.toMat33();
	PxMat33 rotate( transform.base0, transform.base1, transform.base2 );
	return Cm::Matrix34(rotate* scaleMat, transform.base3);
}

PX_INLINE Cm::Matrix34 operator*(const PxMeshScale& scale, const Cm::Matrix34& transform)
{
	PxMat33 scaleMat = scale.toMat33();
	PxMat33 rotate( transform.base0, transform.base1, transform.base2 );
	return Cm::Matrix34(scaleMat * rotate, scaleMat * transform.base3);
}

}

#endif


text:
use v6.c;

class X::Bailador::NoRouteFound is Exception {
    method message() {
        "Did not find a route that matches the request";
    }
}

class X::Bailador::ControllerReturnedNoResult is Exception {
    has Str $.method;
    has Str $.uri;
    method message() {
        "Controller did not return a defined value for HTTP method: $.method on URI: $.uri";
    }
}


text:
.class Lcom/android/server/hdmi/HdmiControlService$BinderService$13;
.super Ljava/lang/Object;
.source "HdmiControlService.java"

# interfaces
.implements Ljava/lang/Runnable;

# annotations
.annotation system Ldalvik/annotation/EnclosingMethod;
    value = Lcom/android/server/hdmi/HdmiControlService$BinderService;->stopOneTouchRecord(I)V
.end annotation

.annotation system Ldalvik/annotation/InnerClass;
    accessFlags = 0x0
    name = null
.end annotation

# instance fields
.field final synthetic this$1:Lcom/android/server/hdmi/HdmiControlService$BinderService;

.field final synthetic val$recorderAddress:I

# direct methods
.method constructor <init>(Lcom/android/server/hdmi/HdmiControlService$BinderService;I)V
    .locals 0

    iput-object p1, p0, Lcom/android/server/hdmi/HdmiControlService$BinderService$13;->this$1:Lcom/android/server/hdmi/HdmiControlService$BinderService;

    iput p2, p0, Lcom/android/server/hdmi/HdmiControlService$BinderService$13;->val$recorderAddress:I

    invoke-direct {p0}, Ljava/lang/Object;-><init>()V

    return-void
.end method

# virtual methods
.method public run()V
    .locals 2

    iget-object v0, p0, Lcom/android/server/hdmi/HdmiControlService$BinderService$13;->this$1:Lcom/android/server/hdmi/HdmiControlService$BinderService;

    iget-object v0, v0, Lcom/android/server/hdmi/HdmiControlService$BinderService;->this$0:Lcom/android/server/hdmi/HdmiControlService;

    invoke-virtual {v0}, Lcom/android/server/hdmi/HdmiControlService;->isTvDeviceEnabled()Z

    move-result v0

    if-nez v0, :cond_0

    const-string/jumbo v0, "HdmiControlService"

    const-string/jumbo v1, "TV device is not enabled."

    invoke-static {v0, v1}, Landroid/util/Slog;->w(Ljava/lang/String;Ljava/lang/String;)I

    return-void

    :cond_0
    iget-object v0, p0, Lcom/android/server/hdmi/HdmiControlService$BinderService$13;->this$1:Lcom/android/server/hdmi/HdmiControlService$BinderService;

    iget-object v0, v0, Lcom/android/server/hdmi/HdmiControlService$BinderService;->this$0:Lcom/android/server/hdmi/HdmiControlService;

    invoke-virtual {v0}, Lcom/android/server/hdmi/HdmiControlService;->tv()Lcom/android/server/hdmi/HdmiCecLocalDeviceTv;

    move-result-object v0

    iget v1, p0, Lcom/android/server/hdmi/HdmiControlService$BinderService$13;->val$recorderAddress:I

    invoke-virtual {v0, v1}, Lcom/android/server/hdmi/HdmiCecLocalDeviceTv;->stopOneTouchRecord(I)V

    return-void
.end method


text:
import time
from types import IntType, LongType, StringTypes
import textwrap

#from openflow.optin_manager.sfa.util.sfalogging import logger
from openflow.optin_manager.sfa.util.faults import SfaFault, SfaInvalidAPIMethod, SfaInvalidArgumentCount, SfaInvalidArgument

from openflow.optin_manager.sfa.util.parameter import Parameter, Mixed, python_type, xmlrpc_type

class Method:
    """
    Base class for all SfaAPI functions. At a minimum, all SfaAPI
    functions must define:

    interfaces = [allowed interfaces]
    accepts = [Parameter(arg1_type, arg1_doc), Parameter(arg2_type, arg2_doc), ...]
    returns = Parameter(return_type, return_doc)
    call(arg1, arg2, ...): method body

    Argument types may be Python types (e.g., int, bool, etc.), typed
    values (e.g., 1, True, etc.), a Parameter, or lists or
    dictionaries of possibly mixed types, values, and/or Parameters
    (e.g., [int, bool, ...]  or {'arg1': int, 'arg2': bool}).

    Once function decorators in Python 2.4 are fully supported,
    consider wrapping calls with accepts() and returns() functions
    instead of performing type checking manually.
    """

    interfaces = []
    accepts = []
    returns = bool
    status = "current"

    def call(self, *args):
        """
        Method body for all SfaAPI functions. Must override.
        """
        return None

    def __init__(self, api):
        self.name = self.__class__.__name__
        self.api = api

        # Auth may set this to a Person instance (if an anonymous
        # method, will remain None).
        self.caller = None

        # API may set this to a (addr, port) tuple if known
        self.source = None

    def __call__(self, *args, **kwds):
        """
        Main entry point for all SFA API functions. Type checks
        arguments, authenticates, and executes call().
        """

        try:
            start = time.time()
            methodname = self.name
            if not self.api.interface or self.api.interface not in self.interfaces:
                raise SfaInvalidAPIMethod(methodname, self.api.interface)

            (min_args, max_args, defaults) = self.args()

            # Check that the right number of arguments were passed in
            if len(args) < len(min_args) or len(args) > len(max_args):
                raise SfaInvalidArgumentCount(len(args), len(min_args), len(max_args))

            for name, value, expected in zip(max_args, args, self.accepts):
                self.type_check(name, value, expected, args)

            #logger.debug("method.__call__ [%s] : BEG %s"%(self.api.interface,methodname))
            result = self.call(*args, **kwds)

            runtime = time.time() - start
            #logger.debug("method.__call__ [%s] : END %s in %02f s (%s)"%\
            #                 (self.api.interface,methodname,runtime,getattr(self,'message',"[no-msg]")))

            return result

        except SfaFault, fault:

            caller = ""

            # Prepend caller and method name to expected faults
            fault.faultString = caller + ": " +  self.name + ": " + fault.faultString
            runtime = time.time() - start
            #logger.log_exc("Method %s raised an exception"%self.name)
            raise fault

    def help(self, indent = "  "):
        """
        Text documentation for the method.
        """

        (min_args, max_args, defaults) = self.args()

        text = "%s(%s) -> %s\n\n" % (self.name, ", ".join(max_args), xmlrpc_type(self.returns))

        text += "Description:\n\n"
        lines = [indent + line.strip() for line in self.__doc__.strip().split("\n")]
        text += "\n".join(lines) + "\n\n"

        def param_text(name, param, indent, step):
            """
            Format a method parameter.
            """

            text = indent

            # Print parameter name
            if name:
                param_offset = 32
                text += name.ljust(param_offset - len(indent))
            else:
                param_offset = len(indent)

            # Print parameter type
            param_type = python_type(param)
            text += xmlrpc_type(param_type) + "\n"

            # Print parameter documentation right below type
            if isinstance(param, Parameter):
                wrapper = textwrap.TextWrapper(width = 70,
                                               initial_indent = " " * param_offset,
                                               subsequent_indent = " " * param_offset)
                text += "\n".join(wrapper.wrap(param.doc)) + "\n"
                param = param.type

            text += "\n"

            # Indent struct fields and mixed types
            if isinstance(param, dict):
                for name, subparam in param.iteritems():
                    text += param_text(name, subparam, indent + step, step)
            elif isinstance(param, Mixed):
                for subparam in param:
                    text += param_text(name, subparam, indent + step, step)
            elif isinstance(param, (list, tuple, set)):
                for subparam in param:
                    text += param_text("", subparam, indent + step, step)

            return text

        text += "Parameters:\n\n"
        for name, param in zip(max_args, self.accepts):
            text += param_text(name, param, indent, indent)

        text += "Returns:\n\n"
        text += param_text("", self.returns, indent, indent)

        return text

    def args(self):
        """
        Returns a tuple:

        ((arg1_name, arg2_name, ...),
         (arg1_name, arg2_name, ..., optional1_name, optional2_name, ...),
         (None, None, ..., optional1_default, optional2_default, ...))

        That represents the minimum and maximum sets of arguments that
        this function accepts and the defaults for the optional arguments.
        """

        # Inspect call. Remove self from the argument list.
        max_args = self.call.func_code.co_varnames[1:self.call.func_code.co_argcount]
        defaults = self.call.func_defaults
        if defaults is None:
            defaults = ()

        min_args = max_args[0:len(max_args) - len(defaults)]
        defaults = tuple([None for arg in min_args]) + defaults

        return (min_args, max_args, defaults)

    def type_check(self, name, value, expected, args):
        """
        Checks the type of the named value against the expected type,
        which may be a Python type, a typed value, a Parameter, a
        Mixed type, or a list or dictionary of possibly mixed types,
        values, Parameters, or Mixed types.

        Extraneous members of lists must be of the same type as the
        last specified type. For example, if the expected argument
        type is [int, bool], then [1, False] and [14, True, False,
        True] are valid, but [1], [False, 1] and [14, True, 1] are
        not.

        Extraneous members of dictionaries are ignored.
        """

        # If any of a number of types is acceptable
        if isinstance(expected, Mixed):
            for item in expected:
                try:
                    self.type_check(name, value, item, args)
                    return
                except SfaInvalidArgument, fault:
                    pass
            raise fault

        # If an authentication structure is expected, save it and
        # authenticate after basic type checking is done.
        #if isinstance(expected, Auth):
        #    auth = expected
        #else:
        #    auth = None

        # Get actual expected type from within the Parameter structure
        if isinstance(expected, Parameter):
            min = expected.min
            max = expected.max
            nullok = expected.nullok
            expected = expected.type
        else:
            min = None
            max = None
            nullok = False

        expected_type = python_type(expected)

        # If value can be NULL
        if value is None and nullok:
            return

        # Strings are a special case. Accept either unicode or str
        # types if a string is expected.
        if expected_type in StringTypes and isinstance(value, StringTypes):
            pass

        # Integers and long integers are also special types. Accept
        # either int or long types if an int or long is expected.
        elif expected_type in (IntType, LongType) and isinstance(value, (IntType, LongType)):
            pass

        elif not isinstance(value, expected_type):
            raise SfaInvalidArgument("expected %s, got %s" % \
                                     (xmlrpc_type(expected_type), xmlrpc_type(type(value))),
                                     name)

        # If a minimum or maximum (length, value) has been specified
        if expected_type in StringTypes:
            if min is not None and \
               len(value.encode(self.api.encoding)) < min:
                raise SfaInvalidArgument, "%s must be at least %d bytes long" % (name, min)
            if max is not None and \
               len(value.encode(self.api.encoding)) > max:
                raise SfaInvalidArgument, "%s must be at most %d bytes long" % (name, max)
        elif expected_type in (list, tuple, set):
            if min is not None and len(value) < min:
                raise SfaInvalidArgument, "%s must contain at least %d items" % (name, min)
            if max is not None and len(value) > max:
                raise SfaInvalidArgument, "%s must contain at most %d items" % (name, max)
        else:
            if min is not None and value < min:
                raise SfaInvalidArgument, "%s must be > %s" % (name, str(min))
            if max is not None and value > max:
                raise SfaInvalidArgument, "%s must be < %s" % (name, str(max))

        # If a list with particular types of items is expected
        if isinstance(expected, (list, tuple, set)):
            for i in range(len(value)):
                if i >= len(expected):
                    j = len(expected) - 1
                else:
                    j = i
                self.type_check(name + "[]", value[i], expected[j], args)

        # If a struct with particular (or required) types of items is
        # expected.
        elif isinstance(expected, dict):
            for key in value.keys():
                if key in expected:
                    self.type_check(name + "['%s']" % key, value[key], expected[key], args)
            for key, subparam in expected.iteritems():
                if isinstance(subparam, Parameter) and \
                   subparam.optional is not None and \
                   not subparam.optional and key not in value.keys():
                    raise SfaInvalidArgument("'%s' not specified" % key, name)

        #if auth is not None:
        #    auth.check(self, *args)


text:
<?php
/**
 * iaeweb.php
 * 框架入口文件
 */

header('Content-Type: text/html; charset=utf-8');
define('IN_IAEWEB', true);
error_reporting(E_ERROR | E_WARNING | E_PARSE);
$config         = iaeweb::load_config('config');
/**
 * 配置
 */
define('SYS_START_TIME',     microtime(true));
define('HTTP_REFERER', isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : '');
define('CORE_PATH',           dirname(__FILE__) . DIRECTORY_SEPARATOR);
define('DATA_DIR',         IAEWEB_PATH . 'data' . DIRECTORY_SEPARATOR);
define('TEMPLATE_DIR',           IAEWEB_PATH . 'template' . DIRECTORY_SEPARATOR);
if (!defined('CONTROLLER_DIR')) define('CONTROLLER_DIR',     CORE_PATH . 'controller' . DIRECTORY_SEPARATOR);
define('COOKIE_PRE',			'iaeweb_');//Cookie 前缀,同一域名下安装多套系统时,请修改Cookie前缀
date_default_timezone_set('Asia/Shanghai');
iaeweb::load_file(CORE_PATH . 'library' . DIRECTORY_SEPARATOR . 'global.function.php');
iaeweb::load_file(CORE_PATH . 'version.php');
iaeweb::load_file(CORE_PATH . 'controller/Base.class.php');

/**
 * 系统核心全局控制类
 */
abstract class iaeweb {
	public static $controller;
	public static $action;
	/**
	 * 分析URL信息
	 */
	private static function parse_request() {
		$path_url_string = isset($_SERVER['QUERY_STRING']) && $_SERVER['QUERY_STRING'] ? $_SERVER['QUERY_STRING'] : $_SERVER['REQUEST_URI'];
		parse_str($path_url_string, $url_info_array);
		$controller_name  = trim((isset($url_info_array['c']) && $url_info_array['c']) ? $url_info_array['c'] : 'index');
		$action_name      = trim((isset($url_info_array['a']) && $url_info_array['a']) ? $url_info_array['a'] : 'index');
		self::$controller = self::_safe(strtolower($controller_name));
		self::$action 	  = self::_safe(strtolower($action_name));
		$_GET             = array_merge($_GET, $url_info_array);
		return true;
	}

	/**
	 * 项目运行函数
	 */
	public static function run() {
		global $config ;
		if (!empty($config['site_mobile']) && is_mobile()) { //如果你要指定手机版绑定域名就修改这里吧
			$config['site_theme'] =  (is_dir(TEMPLATE_DIR . 'mobile') ? 'mobile' : $config['site_theme']);
		}
		static $_app	= array();
		$app_id 		= self::$controller . '_' . self::$action;
		define('SYS_THEME_DIR',	$config['site_theme'] . DIRECTORY_SEPARATOR);	//模板风格
		self::parse_request();
		if (!isset($_app[$app_id])) {
			$controller = self::$controller;
			$action     = self::$action . 'Action';
			if (is_file(CONTROLLER_DIR . $controller . '.php')) {
				self::load_file(CONTROLLER_DIR . $controller . '.php');
			} else {
			   exit('iAEweb:Controller does not exist.');
			}
			$app_object = new $controller();
			if (method_exists($controller, $action)) {
				$_app[$app_id] = $app_object->$action();
			} else {
				exit('iAEweb:Action does not exist.');
			}
		}
		return $_app[$app_id];
	}

	/**
	 * 静态加载文件(相当于PHP函数require_once)
	 */
	public static function load_file($file_name) {
		static $_inc_files = array();
		//参数分析
		if (!$file_name) return false;
		 if (!isset($_inc_files[$file_name])) {
			if (!is_file($file_name)) {
				exit('The file:' . $file_name . ' not found!');
			}
			include $file_name;
			$_inc_files[$file_name] = true;
		}
		return $_inc_files[$file_name];
	}

	/**
	 * 加载配置文件
	 */
	public static function load_config($file) {
		static $configs = array();
		$path = IAEWEB_PATH . 'data' . DIRECTORY_SEPARATOR . 'config' . DIRECTORY_SEPARATOR . $file . '.ini.php';
		if (is_file($path)) {
			$configs[$file] = include $path;
			return $configs[$file];
		}
	}

	/**
	 * 加载类
	 */
	public static function load_class($classname, $initialize = 1) {
		static $classes = array();

		$key = md5($classname);
		if (isset($classes[$key])) {
			if (!empty($classes[$key])) {
				return $classes[$key];
			} else {
				return true;
			}
		}
		if (is_file(CORE_PATH.'library'.DIRECTORY_SEPARATOR.$classname.'.class.php')) {
			include CORE_PATH.'library'.DIRECTORY_SEPARATOR.$classname.'.class.php';
			$name = $classname;
			if ($initialize) {
				$classes[$key] = new $name;
			} else {
				$classes[$key] = true;
			}
			return $classes[$key];
		} else {
			return false;
		}
	}

    /**
	 * 安全处理函数controller
	 */
	private static function _safe($str) {
		return str_replace(array('/', '.'), '', $str);
	}

	/**
	 * 获取当前运行的controller名称
	 */
	public static function get_controller_id() {
		return self::$controller;
	}

	/**
	 * 获取当前运行的action名称
	 */
	public static function get_action_id() {
		return self::$action;
	}

}


text:
. ${PROGDIR}/backend/functions.sh
. ${PROGDIR}/backend/functions-ftp.sh

MIRROR="${1}"

if [ -z "${MIRROR}" ]
then
  echo "Error: No mirror specified!"
  exit 1
fi

set_ftp_mirror "${MIRROR}"
exit 0


text:
/* eslint-disable */

'use strict';

/*::
import type { ReaderFragment } from 'relay-runtime';
import type { FragmentReference } from "relay-runtime";
declare export opaque type RelayMockEnvironmentWithComponentsTestNoticeableResultFragment$ref: FragmentReference;
declare export opaque type RelayMockEnvironmentWithComponentsTestNoticeableResultFragment$fragmentType: RelayMockEnvironmentWithComponentsTestNoticeableResultFragment$ref;
export type RelayMockEnvironmentWithComponentsTestNoticeableResultFragment = {|
  +id: string,
  +message: ?{|
    +text: ?string,
  |},
  +doesViewerLike: ?boolean,
  +$refType: RelayMockEnvironmentWithComponentsTestNoticeableResultFragment$ref,
|};
export type RelayMockEnvironmentWithComponentsTestNoticeableResultFragment$data = RelayMockEnvironmentWithComponentsTestNoticeableResultFragment;
export type RelayMockEnvironmentWithComponentsTestNoticeableResultFragment$key = {
  +$data?: RelayMockEnvironmentWithComponentsTestNoticeableResultFragment$data,
  +$fragmentRefs: RelayMockEnvironmentWithComponentsTestNoticeableResultFragment$ref,
  ...
};
*/

var node/*: ReaderFragment*/ = {
  "argumentDefinitions": [],
  "kind": "Fragment",
  "metadata": null,
  "name": "RelayMockEnvironmentWithComponentsTestNoticeableResultFragment",
  "selections": [
    {
      "alias": null,
      "args": null,
      "kind": "ScalarField",
      "name": "id",
      "storageKey": null
    },
    {
      "alias": null,
      "args": null,
      "concreteType": "Text",
      "kind": "LinkedField",
      "name": "message",
      "plural": false,
      "selections": [
        {
          "alias": null,
          "args": null,
          "kind": "ScalarField",
          "name": "text",
          "storageKey": null
        }
      ],
      "storageKey": null
    },
    {
      "alias": null,
      "args": null,
      "kind": "ScalarField",
      "name": "doesViewerLike",
      "storageKey": null
    }
  ],
  "type": "Feedback",
  "abstractKey": null
};

if (__DEV__) {
  (node/*: any*/).hash = "7ca93b0d31402b484bcbb0af777a088e";
}

module.exports = node;


text:
@interface DemoFloatingWindow : UIWindow

@end


text:
import { IUser } from '../models/user.model';
import { UserService } from '../services/user.service';
import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-users-page',
  templateUrl: './users-page.component.html',
  styleUrls: ['./users-page.component.css']
})
export class UsersPageComponent implements OnInit {
  users: IUser[] = [];

  constructor(private userService: UserService) { }

  ngOnInit() {
    this.userService.getUsers()
      .subscribe(
        (users) => this.users = users
      );
  }

}


text:
<?php
namespace App\EventListener;

use Symfony\Component\DependencyInjection\ContainerInterface;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Bundle\FrameworkBundle\Routing\Router;
use Symfony\Component\HttpFoundation\RequestStack;
use Symfony\Component\HttpKernel\Event\GetResponseEvent;
use Symfony\Component\HttpKernel\HttpKernelInterface;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\Translation\TranslatorInterface;

use App\Classes\System\Helper;

class RequestListener {
    // Vars
    private $container;
    private $entityManager;
    private $router;
    private $requestStack;

    private $helper;
    private $query;

    private $session;

    private $settingRow;

    // Properties

    // Functions public
    public function __construct(ContainerInterface $container, EntityManagerInterface $entityManager, Router $router, RequestStack $requestStack, TranslatorInterface $translator) {
        $this->container = $container;
        $this->entityManager = $entityManager;
        $this->router = $router;
        $this->requestStack = $requestStack;

        $this->helper = new Helper($this->container, $this->entityManager, $translator);
        $this->query = $this->helper->getQuery();

        $this->session = $this->helper->getSession();

        $this->settingRow = $this->helper->getSettingRow();
    }

    public function onKernelRequest(GetResponseEvent $event) {
        if (HttpKernelInterface::MASTER_REQUEST != $event->getRequestType())
            return;

        $this->helper->xssProtection();

        $request = $this->helper->checkLanguage($event->getRequest());

        $checkSessionOver = $this->helper->checkSessionOver($request, $this->router);

        $urlCurrentPageId = 2;

        if ($request->get("urlCurrentPageId") != null && $request->get("urlCurrentPageId") > 0)
             $urlCurrentPageId = $request->get("urlCurrentPageId");

        $phpSession = Array(
            'name' => $this->session->getName(),
            'userInform' => $this->session->get("userInform"),
            'languageTextCode' => $this->session->get("languageTextCode"),
            'currentPageId' => $urlCurrentPageId,
            'xssProtectionValue' => $this->session->get("xssProtectionValue"),
            'sessionMaxIdleTime' => $this->helper->getSessionMaxIdleTime()
        );

        $this->container->get("twig")->addGlobal("php_session", $phpSession);
        $this->container->get("twig")->addGlobal("websiteName", $this->helper->getWebsiteName());
        $this->container->get("twig")->addGlobal("settingRow", $this->settingRow);
        $this->container->get("twig")->addGlobal("pageRow", $this->query->selectPageDatabase($request->getLocale(), $urlCurrentPageId));

        if ($this->settingRow['javascript_minify'] == 1)
            $this->container->get("twig")->addGlobal("javascriptMinify", ".min.js");
        else
            $this->container->get("twig")->addGlobal("javascriptMinify", ".js");

        if ($checkSessionOver != false)
            $event->setResponse(new RedirectResponse($checkSessionOver));

        if ($this->settingRow['https'] == true) {
            if ($request->isSecure() == false) {
                $request->server->set("HTTPS", true);
                $request->server->set("SERVER_PORT", 443);

                $event->setResponse(new RedirectResponse($request->getUri()));
            }
        }
        else {
            if ($request->isSecure() == true) {
                $request->server->set("HTTPS", false);
                $request->server->set("SERVER_PORT", 80);

                $event->setResponse(new RedirectResponse($request->getUri()));
            }
        }
    }

    // Functions private
}


text:
package flaxbeard.sprockets.items;

import flaxbeard.sprockets.Sprockets;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.ItemStack;
import net.minecraft.util.ActionResult;
import net.minecraft.util.EnumActionResult;
import net.minecraft.util.EnumHand;
import net.minecraft.world.World;

public class ItemSprocketBook extends ItemSprocketBase
{

	public ItemSprocketBook()
	{
		super("book");
	}

	@Override
	public ActionResult<ItemStack> onItemRightClick(ItemStack itemStackIn, World world, EntityPlayer playerIn, EnumHand hand)
	{
		playerIn.openGui(Sprockets.INSTANCE, 0, world, 0, 0, 0);
		return new ActionResult(EnumActionResult.SUCCESS, itemStackIn);
	}
}


text:
<?php

namespace App\Controller;

use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\JsonResponse;
use Tree\TreeService;
use Tree\Exception\NotFoundException;
use Ramsey\Uuid\Uuid;

class ParentController {

    /**
     * @var TreeService
     */
    protected $service;

    public function __construct(TreeService $service)
    {
        $this->service = $service;
    }

    public function __invoke(Request $request, $id)
    {
        try {
            $node = $this->service->findById(Uuid::fromString($id));

            try {
                $parent = $this->service->parent($node);

                return new JsonResponse(['parent' => $parent]);
            } catch (NotFoundException $e) {
                return new JsonResponse([
                    'errors' => [
                        sprintf('Parent of node with id "%s" not found', $id)
                    ]
                ]);
            }

        } catch (NotFoundException $e) {
            return new JsonResponse([
                'errors' => [
                    sprintf('Target node with id "%s" not found', $id)
                ]
            ]);
        }
    }
}


text:
package quickfix;

import edu.umd.cs.findbugs.BugInstance;
import edu.umd.cs.findbugs.plugin.eclipse.quickfix.BugResolution;
import edu.umd.cs.findbugs.plugin.eclipse.quickfix.exception.BugResolutionException;

import org.eclipse.jdt.core.dom.CompilationUnit;
import org.eclipse.jdt.core.dom.MethodDeclaration;
import org.eclipse.jdt.core.dom.rewrite.ASTRewrite;

import util.TraversalUtil;

public class CopyOverridenMethodResolution extends BugResolution {

    @Override
    protected boolean resolveBindings() {
        return false;
    }

    @Override
    protected void repairBug(ASTRewrite rewrite, CompilationUnit workingUnit, BugInstance bug) throws BugResolutionException {
        MethodDeclaration redundantMethod = TraversalUtil.findEnclosingMethod(workingUnit, bug.getPrimarySourceLineAnnotation());

        if (redundantMethod != null) {
            rewrite.remove(redundantMethod, null);
        }
    }

}


text:
package com.rafasalas.rugs;

import android.content.Context;
import android.graphics.Canvas;
import android.media.audiofx.Visualizer;
import android.os.Handler;
import android.service.wallpaper.WallpaperService;
import android.util.Log;
import android.view.SurfaceHolder;

import java.util.Random;

/**
 * Created by salas on 15/06/2017.
 */

public class wallpaper extends WallpaperService {

    private Context context;
    private Visualizer mVisualizer;

    @Override
    public Engine onCreateEngine() {

        return new wallpaperEngine();

    }
    private class wallpaperEngine extends Engine  {
        private boolean visible;
        private final int frameDuration = 16;
        private SurfaceHolder holder;

        private Handler handler;

        private lienzo lienzotrabajo;
        //Variables musica
        final global dataglobal = (global) getApplicationContext();

        private wallpaperEngine() {
            context= getApplicationContext();

            int width = getApplicationContext().getResources().getDisplayMetrics().widthPixels;
            int height = getApplicationContext().getResources().getDisplayMetrics().heightPixels;
            lienzotrabajo=new lienzo(context,width,height);

            handler = new Handler();
            init_music();
        }
        @Override
        public void onCreate(SurfaceHolder surfaceHolder) {

            super.onCreate(surfaceHolder);

            this.holder = surfaceHolder;

        }
        private Runnable drawNucleus = new Runnable() {
            @Override
            public void run() {
                draw();

            }
        }
                ;

        private void draw() {

            if (visible) {
                Canvas canvas = holder.lockCanvas();
                canvas.save();
                //int width=canvas.getWidth();
               // int height=canvas.getHeight();

                //aqui su publicidad
                int width = getApplicationContext().getResources().getDisplayMetrics().widthPixels;
                int height = getApplicationContext().getResources().getDisplayMetrics().heightPixels;
                // trying fixing error of black screen

                lienzotrabajo.draw(canvas, width, height);

                canvas.restore();
                holder.unlockCanvasAndPost(canvas);

                handler.removeCallbacks(drawNucleus);
                handler.postDelayed(drawNucleus, frameDuration);
            }
        }

        public void onVisibilityChanged(boolean visible) {
            this.visible = visible;

            if (visible) {
                handler.post(drawNucleus);
            } else {
                handler.removeCallbacks(drawNucleus);
            }

        }
        @Override
        public void onSurfaceChanged(SurfaceHolder holder, int format, int width, int height) {
            // trying fixing error of black screen

            super.onSurfaceChanged(holder, format, width, height);
            lienzotrabajo.construction(width, height);

        }

        @Override
        public void onDestroy() {

            super.onDestroy();
            handler.removeCallbacks(drawNucleus);
        }
}
//music!!
private void init_music(){
    final global dataglobal = (global) getApplicationContext();
    mVisualizer = new Visualizer(0);
    mVisualizer.setEnabled(false);

    mVisualizer.setCaptureSize(128);

    Visualizer.OnDataCaptureListener captureListener = new Visualizer.OnDataCaptureListener()
    {
        @Override
        public void onWaveFormDataCapture(Visualizer visualizer, byte[] bytes,
                                          int samplingRate)
        { float sum=0;

            for (int i = 0; i < bytes.length; i++) {
                sum=sum+(float)bytes[i];
            }
            //if (sum<-16383){sum=1;}else{sum=sum/1000;}
            if (sum<-12000 || sum>12000){sum=1;}else{sum=sum/1000;}

            dataglobal.setIntensity(sum);
            Log.v("sumatorio"," "+sum);
        }

        @Override
        public void onFftDataCapture(Visualizer visualizer, byte[] bytes,
                                     int samplingRate)
        {
            Log.v("fft", " " + bytes.length+bytes[0] + " "+bytes[60] + " " + bytes[125]);
        }
    };

    mVisualizer.setDataCaptureListener(captureListener,
            Visualizer.getMaxCaptureRate() / 2, true, true);

    // Enabled Visualizer and disable when we're done with the stream

    mVisualizer.setEnabled(true);

}

    public void release()
    {
        mVisualizer.release();
    }

}

//////////////

    //music


text:
package com.microsoft.azure.management.batchai.v2017_09_01_preview;

import com.microsoft.azure.arm.model.HasInner;
import com.microsoft.azure.arm.resources.models.Resource;
import com.microsoft.azure.arm.resources.models.HasResourceGroup;
import com.microsoft.azure.arm.model.Refreshable;
import com.microsoft.azure.arm.model.Updatable;
import com.microsoft.azure.arm.model.Appliable;
import com.microsoft.azure.arm.model.Creatable;
import com.microsoft.azure.arm.resources.models.GroupableResourceCore;
import com.microsoft.azure.arm.resources.models.HasManager;
import com.microsoft.azure.management.batchai.v2017_09_01_preview.implementation.BatchAIManager;
import org.joda.time.DateTime;
import com.microsoft.azure.management.batchai.v2017_09_01_preview.implementation.FileServerInner;

/**
 * Type representing FileServer.
 */
public interface FileServer extends HasInner<FileServerInner>, Resource, GroupableResourceCore<BatchAIManager, FileServerInner>, HasResourceGroup, Refreshable<FileServer>, Updatable<FileServer.Update>, HasManager<BatchAIManager> {
    /**
     * @return the creationTime value.
     */
    DateTime creationTime();

    /**
     * @return the dataDisks value.
     */
    DataDisks dataDisks();

    /**
     * @return the mountSettings value.
     */
    MountSettings mountSettings();

    /**
     * @return the provisioningState value.
     */
    FileServerProvisioningState provisioningState();

    /**
     * @return the provisioningStateTransitionTime value.
     */
    DateTime provisioningStateTransitionTime();

    /**
     * @return the sshConfiguration value.
     */
    SshConfiguration sshConfiguration();

    /**
     * @return the subnet value.
     */
    ResourceId subnet();

    /**
     * @return the vmSize value.
     */
    String vmSize();

    /**
     * The entirety of the FileServer definition.
     */
    interface Definition extends DefinitionStages.Blank, DefinitionStages.WithGroup, DefinitionStages.WithDataDisks, DefinitionStages.WithSshConfiguration, DefinitionStages.WithVmSize, DefinitionStages.WithCreate {
    }

    /**
     * Grouping of FileServer definition stages.
     */
    interface DefinitionStages {
        /**
         * The first stage of a FileServer definition.
         */
        interface Blank extends GroupableResourceCore.DefinitionWithRegion<WithGroup> {
        }

        /**
         * The stage of the FileServer definition allowing to specify the resource group.
         */
        interface WithGroup extends GroupableResourceCore.DefinitionStages.WithGroup<WithDataDisks> {
        }

        /**
         * The stage of the fileserver definition allowing to specify DataDisks.
         */
        interface WithDataDisks {
           /**
            * Specifies dataDisks.
            */
            WithSshConfiguration withDataDisks(DataDisks dataDisks);
        }

        /**
         * The stage of the fileserver definition allowing to specify SshConfiguration.
         */
        interface WithSshConfiguration {
           /**
            * Specifies sshConfiguration.
            */
            WithVmSize withSshConfiguration(SshConfiguration sshConfiguration);
        }

        /**
         * The stage of the fileserver definition allowing to specify VmSize.
         */
        interface WithVmSize {
           /**
            * Specifies vmSize.
            */
            WithCreate withVmSize(String vmSize);
        }

        /**
         * The stage of the fileserver update allowing to specify Subnet.
         */
        interface WithSubnet {
            /**
             * Specifies subnet.
             */
            WithCreate withSubnet(ResourceId subnet);
        }

        /**
         * The stage of the definition which contains all the minimum required inputs for
         * the resource to be created (via {@link WithCreate#create()}), but also allows
         * for any other optional settings to be specified.
         */
        interface WithCreate extends Creatable<FileServer>, Resource.DefinitionWithTags<WithCreate>, DefinitionStages.WithSubnet {
        }
    }
    /**
     * The template for a FileServer update operation, containing all the settings that can be modified.
     */
    interface Update extends Appliable<FileServer>, Resource.UpdateWithTags<Update>, UpdateStages.WithSubnet {
    }

    /**
     * Grouping of FileServer update stages.
     */
    interface UpdateStages {
        /**
         * The stage of the fileserver {0} allowing to specify Subnet.
         */
        interface WithSubnet {
            /**
             * Specifies subnet.
             */
            Update withSubnet(ResourceId subnet);
        }

    }
}


text:
package org.openqa.selenium.remote.server.handler.html5;

import org.openqa.selenium.html5.WebStorage;
import org.openqa.selenium.remote.server.JsonParametersAware;
import org.openqa.selenium.remote.server.Session;
import org.openqa.selenium.remote.server.handler.ResponseAwareWebDriverHandler;
import org.openqa.selenium.remote.server.rest.ResultType;

import java.util.Map;

public class GetLocalStorageItem extends ResponseAwareWebDriverHandler implements JsonParametersAware {
  private volatile String key;

  public GetLocalStorageItem(Session session) {
    super(session);
  }

  public ResultType call() throws Exception {
    Object value = ((WebStorage) getUnwrappedDriver()).getLocalStorage().getItem(key);
    response.setValue(value);
    return ResultType.SUCCESS;
  }

  public void setJsonParameters(Map<String, Object> allParameters) throws Exception {
    key = (String) allParameters.get("key");
  }

  @Override
  public String toString() {
    return String.format("[get local storage item for key: %s]", key);
  }
}


text:
import re

from twilio import TwilioException
from twilio.rest.resources.util import change_dict_key, transform_params
from twilio.rest.resources.util import UNSET_TIMEOUT
from twilio.rest.resources import InstanceResource, ListResource

TYPES = {"local": "Local", "tollfree": "TollFree", "mobile": "Mobile"}

class AvailablePhoneNumber(InstanceResource):
    """ An available phone number resource

   .. attribute:: friendly_name

      A nicely-formatted version of the phone number.

   .. attribute:: phone_number

      The phone number, in E.164 (i.e. "+1") format.

   .. attribute:: lata

      The LATA of this phone number.

   .. attribute:: rate_center

      The rate center of this phone number.

   .. attribute:: latitude

      The latitude coordinate of this phone number.

   .. attribute:: longitude

      The longitude coordinate of this phone number.

   .. attribute:: region

      The two-letter state or province abbreviation of this phone number.

   .. attribute:: postal_code

      The postal (zip) code of this phone number.

   .. attribute:: iso_country

        The country for this number

    """

    def __init__(self, parent):
        # Available Phone Numbers have no sid.
        super(AvailablePhoneNumber, self).__init__(parent, "")
        self.name = ""

    def purchase(self, **kwargs):
        return self.parent.purchase(phone_number=self.phone_number,
                                    **kwargs)

class AvailablePhoneNumbers(ListResource):

    name = "AvailablePhoneNumbers"
    key = "available_phone_numbers"
    instance = AvailablePhoneNumber

    def __init__(self, base_uri, auth, timeout, phone_numbers):
        super(AvailablePhoneNumbers, self).__init__(base_uri, auth, timeout)
        self.phone_numbers = phone_numbers

    def get(self, sid):
        raise TwilioException("Individual AvailablePhoneNumbers have no sid")

    def list(self, type="local", country="US", region=None, postal_code=None,
             lata=None, rate_center=None, **kwargs):
        """
        Search for phone numbers
        """
        kwargs["in_region"] = kwargs.get("in_region", region)
        kwargs["in_postal_code"] = kwargs.get("in_postal_code", postal_code)
        kwargs["in_lata"] = kwargs.get("in_lata", lata)
        kwargs["in_rate_center"] = kwargs.get("in_rate_center", rate_center)
        params = transform_params(kwargs)

        uri = "%s/%s/%s" % (self.uri, country, TYPES[type])
        resp, page = self.request("GET", uri, params=params)

        return [self.load_instance(i) for i in page[self.key]]

    def load_instance(self, data):
        instance = self.instance(self.phone_numbers)
        instance.load(data)
        instance.load_subresources()
        return instance

class PhoneNumber(InstanceResource):
    """ An IncomingPhoneNumber object

   .. attribute:: sid

      A 34 character string that uniquely identifies this resource.

   .. attribute:: date_created

      The date that this resource was created, given as GMT RFC 2822 format.

   .. attribute:: date_updated

      The date that this resource was last updated, in GMT RFC 2822 format.

   .. attribute:: friendly_name

      A human readable descriptive text for this resource, up to 64 characters
      long. By default, the FriendlyName is a nicely formatted version of
      the phone number.

   .. attribute:: account_sid

      The unique id of the Account responsible for this phone number.

   .. attribute:: phone_number

      The incoming phone number. e.g., +16175551212 (E.164 format)

   .. attribute:: api_version

      Calls to this phone number will start a new TwiML session with this
      API version.

   .. attribute:: voice_caller_id_lookup

      Look up the caller's caller-ID name from the CNAM database (additional
      charges apply). Either true or false.

   .. attribute:: voice_url

      The URL Twilio will request when this phone number receives a call.

   .. attribute:: voice_method

      The HTTP method Twilio will use when requesting the above Url.
      Either GET or POST.

   .. attribute:: voice_fallback_url

      The URL that Twilio will request if an error occurs retrieving or
      executing the TwiML requested by Url.

   .. attribute:: voice_fallback_method

      The HTTP method Twilio will use when requesting the VoiceFallbackUrl.
      Either GET or POST.

   .. attribute:: status_callback

      The URL that Twilio will request to pass status parameters (such as
      call ended) to your application.

   .. attribute:: status_callback_method

      The HTTP method Twilio will use to make requests to the
      StatusCallback URL. Either GET or POST.

   .. attribute:: sms_url

      The URL Twilio will request when receiving an incoming SMS message
      to this number.

   .. attribute:: sms_method

      The HTTP method Twilio will use when making requests to the SmsUrl.
      Either GET or POST.

   .. attribute:: sms_fallback_url

      The URL that Twilio will request if an error occurs retrieving or
      executing the TwiML from SmsUrl.

   .. attribute:: sms_fallback_method

      The HTTP method Twilio will use when requesting the above URL.
      Either GET or POST.

   .. attribute:: uri

      The URI for this resource, relative to https://api.twilio.com.
    """

    def load(self, entries):
        """ Set the proper Account owner of this phone number """

        # Only check if entries has a uri
        if "account_sid" in entries:
            # Parse the parent's uri to get the scheme and base
            uri = re.sub(r'AC(.*)', entries["account_sid"],
                         self.parent.base_uri)

            self.parent = PhoneNumbers(
                uri,
                self.parent.auth,
                self.parent.timeout
            )
            self.base_uri = self.parent.uri

        super(PhoneNumber, self).load(entries)

    def transfer(self, account_sid):
        """
        Transfer the phone number with sid from the current account to another
        identified by account_sid
        """
        a = self.parent.transfer(self.name, account_sid)
        self.load(a.__dict__)

    def update(self, **kwargs):
        """
        Update this phone number instance.
        """
        kwargs_copy = dict(kwargs)
        change_dict_key(kwargs_copy, from_key="status_callback_url",
                        to_key="status_callback")

        a = self.parent.update(self.name, **kwargs_copy)
        self.load(a.__dict__)

    def delete(self):
        """
        Release this phone number from your account. Twilio will no longer
        answer calls to this number, and you will stop being billed the monthly
        phone number fees. The phone number will eventually be recycled and
        potentially given to another customer, so use with care. If you make a
        mistake, contact us... we may be able to give you the number back.
        """
        return self.parent.delete(self.name)

class PhoneNumbers(ListResource):

    name = "IncomingPhoneNumbers"
    key = "incoming_phone_numbers"
    instance = PhoneNumber

    def __init__(self, base_uri, auth, timeout=UNSET_TIMEOUT):
        super(PhoneNumbers, self).__init__(base_uri, auth, timeout)
        self.available_phone_numbers = \
            AvailablePhoneNumbers(base_uri, auth, timeout, self)

    def delete(self, sid):
        """
        Release this phone number from your account. Twilio will no longer
        answer calls to this number, and you will stop being billed the
        monthly phone number fees. The phone number will eventually be
        recycled and potentially given to another customer, so use with care.
        If you make a mistake, contact us... we may be able to give you the
        number back.
        """
        return self.delete_instance(sid)

    def list(self, type=None, **kwargs):
        """
        :param phone_number: Show phone numbers that match this pattern.
        :param friendly_name: Show phone numbers with this friendly name
        :param type: Filter numbers by type. Available types are
            'local', 'mobile', or 'tollfree'

        You can specify partial numbers and use '*' as a wildcard.
        """

        uri = self.uri
        if type:
            uri = "%s/%s" % (self.uri, TYPES[type])

        params = transform_params(kwargs)
        resp, page = self.request("GET", uri, params=params)

        return [self.load_instance(i) for i in page[self.key]]

    def purchase(self, status_callback_url=None, **kwargs):
        """
        Attempt to purchase the specified number. The only required parameters
        are **either** phone_number or area_code

        :returns: Returns a :class:`PhoneNumber` instance on success,
                  :data:`False` on failure
        :raises: A :exc:`TypeError` if neither phone_number or area_code
        is specified.
        """
        kwargs["StatusCallback"] = kwargs.get("status_callback",
                                              status_callback_url)

        if 'phone_number' not in kwargs and 'area_code' not in kwargs:
            raise TypeError("phone_number or area_code is required")

        number_type = kwargs.pop('type', False)
        uri = self.uri
        if number_type:
            uri = "%s/%s" % (self.uri, TYPES[number_type])

        params = transform_params(kwargs)
        resp, instance = self.request('POST', uri, data=params)

        return self.load_instance(instance)

    def search(self, **kwargs):
        """
        :param type: The type of phone number to search for.
        :param str country: Only show numbers for this country (iso2)
        :param str region: When searching the US, show numbers in this state
        :param str postal_code: Only show numbers in this area code
        :param str rate_center: US only.
        :param tuple near_lat_long: Find close numbers within Distance miles.
        :param integer distance: Search radius for a Near- query in miles.
        """
        return self.available_phone_numbers.list(**kwargs)

    def transfer(self, sid, account_sid):
        """
        Transfer the phone number with sid from the current account to another
        identified by account_sid
        """
        return self.update(sid, account_sid=account_sid)

    def update(self, sid, **kwargs):
        """
        Update this phone number instance
        """
        kwargs_copy = dict(kwargs)
        change_dict_key(kwargs_copy, from_key="status_callback_url",
                        to_key="status_callback")

        if "application_sid" in kwargs_copy:
            for sid_type in ["voice_application_sid", "sms_application_sid"]:
                if sid_type not in kwargs_copy:
                    kwargs_copy[sid_type] = kwargs_copy["application_sid"]
            del kwargs_copy["application_sid"]
        return self.update_instance(sid, kwargs_copy)


text:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.IO;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Data;
using System.Windows.Markup;
using System.Xml;

namespace Koopakiller.Apps.Brainstorming.Shared.UI
{
    ///
    /// Stellt Hilfsmethoden zum Sortieren der in einer <see cref="System.Windows.Controls.ListView"/> angezeigten Datensätze bereit.
    ///
    public class ListViewSort
    {
        #region DataTemplates

        /// Ruft das Template für einen GridViewColumnHeader mit einem hoch-pfeil ab.
        private static readonly DataTemplate HeaderTemplateArrowUp = XamlReader.Load(XmlReader.Create(new StringReader(@"
<DataTemplate xmlns=""http://schemas.microsoft.com/winfx/2006/xaml/presentation"" xmlns:x=""http://schemas.microsoft.com/winfx/2006/xaml"">
    <DockPanel LastChildFill=""True"" Width=""{Binding ActualWidth, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type GridViewColumnHeader}}}"">
        <Path StrokeThickness=""1"" Fill=""Gray"" Data=""M 5,10 L 15,10 L 10,5 L 5,10"" DockPanel.Dock=""Right"" Width=""20"" HorizontalAlignment=""Right"" Margin=""5,0,5,0"" SnapsToDevicePixels=""True""/>
        <TextBlock Text=""{Binding }"" />
    </DockPanel>
</DataTemplate>"))) as DataTemplate;
        /// Ruft das Template für einen GridViewColumnHeader mit einem runter-pfeil ab.
        private static readonly DataTemplate HeaderTemplateArrowDown = XamlReader.Load(XmlReader.Create(new StringReader(@"
<DataTemplate xmlns=""http://schemas.microsoft.com/winfx/2006/xaml/presentation"" xmlns:x=""http://schemas.microsoft.com/winfx/2006/xaml"">
    <DockPanel LastChildFill=""True"" Width=""{Binding ActualWidth, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type GridViewColumnHeader}}}"">
        <Path StrokeThickness=""1"" Fill=""Gray""  Data=""M 5,5 L 10,10 L 15,5 L 5,5"" DockPanel.Dock=""Right"" Width=""20"" HorizontalAlignment=""Right"" Margin=""5,0,5,0"" SnapsToDevicePixels=""True""/>
        <TextBlock Text=""{Binding }"" />
    </DockPanel>
</DataTemplate>"))) as DataTemplate;

        #endregion

        #region Get/Set for DPs

        ///
        /// Ruft den Wert der angefügten IsSortAtClickEnabled Abhängigkeitseigenschaft für eine bestimmte <see cref="System.Windows.Controls.GridViewColumn"/> ab.
        ///
        /// <param name="gvc">Die <see cref="System.Windows.Controls.GridViewColumn"/> deren IsSortAtClickEnabled Wert abgerufen werden soll.</param>
        public static bool GetIsSortAtClickEnabled(GridViewColumn gvc)
        {
            return (bool)gvc.GetValue(IsSortAtClickEnabledProperty);
        }

        ///
        /// Setzt den Wert der angefügten IsSortAtClickEnabled Abhängigkeitseigenschaft für eine bestimmte <see cref="System.Windows.Controls.GridViewColumn"/>.
        ///
        /// <param name="gvc">Die <see cref="System.Windows.Controls.GridViewColumn"/> deren Wert gesetzt werdne soll.</param>
        /// <param name="value">Der zu setzende Wert. <c>true</c> wenn das Sortierren der Spalte erlaubt ist; andernfalls <c>false</c></param>
        public static void SetIsSortAtClickEnabled(GridViewColumn gvc, bool value)
        {
            gvc.SetValue(IsSortAtClickEnabledProperty, value);
        }

        ///
        /// Ruft den Wert der angefügten SortAtHeaderClick Abhängigkeitseigenschaft für eine bestimmte <see cref="System.Windows.Controls.ListView"/> ab.
        ///
        /// <param name="lv">Die <see cref="System.Windows.Controls.ListView"/> deren SortAtHeaderClick Wert abgerufen werden soll.</param>
        public static bool GetSortAtHeaderClick(ListView lv)
        {
            return (bool)lv.GetValue(SortAtHeaderClickProperty);
        }

        ///
        /// Setzt den Wert der angefügten SortAtHeaderClick Abhängigkeitseigenschaft für eine bestimmte <see cref="System.Windows.Controls.ListView"/>.
        ///
        /// <param name="lv">Die <see cref="System.Windows.Controls.ListView"/> deren Wert gesetzt werdne soll.</param>
        /// <param name="value">Der zu setzende Wert. <c>true</c> wenn das Sortierren des ListViews erlaubt ist; andernfalls <c>false</c></param>
        public static void SetSortAtHeaderClick(ListView lv, bool value)
        {
            lv.SetValue(SortAtHeaderClickProperty, value);
        }

        #endregion

        #region DependencyProperties

        ///
        /// Bezeichnet die angefügte IsSortAtClickEnabled Abhängigkeitseigenschaft.
        ///
        public static readonly DependencyProperty IsSortAtClickEnabledProperty = DependencyProperty.RegisterAttached("IsSortAtClickEnabled", typeof(bool), typeof(ListViewSort), new PropertyMetadata(true, OnIsSortAtClickEnabledChanged));
        ///
        /// Bezeichnet die angefügte SortAtHeaderClick Abhängigkeitseigenschaft.
        ///
        public static readonly DependencyProperty SortAtHeaderClickProperty = DependencyProperty.RegisterAttached("SortAtHeaderClick", typeof(bool), typeof(ListViewSort), new PropertyMetadata(false, OnSortAtHeaderClickChanged));

        #endregion

        #region DP Changed handler

        /// Wird aufgerufen, wenn sich die IsSortAtClickEnabled-Eigenshcat ändert.
        private static void OnIsSortAtClickEnabledChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            if ((bool)e.NewValue) return;
            var col = (GridViewColumn)d;

            foreach (var item in LastClickedHeaders.Where(item => item.Value != null && Equals(item.Value.Column, col)))
            {
                col.HeaderTemplate = null;
                ClearSortRules(item.Key.Target as ListView);
            }
        }

        /// Wird aufgerufen, wenn sich die SortAtHeaderClick Eigenschaft ändert
        private static void OnSortAtHeaderClickChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            var lv = (ListView)d;
            if ((bool)e.NewValue)
            {
                LastClickedHeaders.Add(new WeakReference(lv), null);
                LastDirections.Add(new WeakReference(lv), ListSortDirectionEx.Ascending);
                lv.AddHandler(ButtonBase.ClickEvent, new RoutedEventHandler(ColumnClicked));
            }
            else
            {
                lv.RemoveHandler(ButtonBase.ClickEvent, new RoutedEventHandler(ColumnClicked));
                var gv = lv.View as GridView;
                if (gv != null)
                    foreach (var col in gv.Columns)
                        col.HeaderTemplate = null;
                ClearSortRules(lv);
                LastClickedHeaders.Remove(LastClickedHeaders.FirstOrDefault(x => Equals(x.Key.Target, lv)).Key);
                LastDirections.Remove(LastDirections.FirstOrDefault(x => Equals(x.Key.Target, lv)).Key);
            }
        }

        #endregion

        /// Enthält eine Liste der zuletzt angeklickten Spaltenüberschriften.
        private static readonly Dictionary<WeakReference, GridViewColumnHeader> LastClickedHeaders = new Dictionary<WeakReference, GridViewColumnHeader>();
        /// Enthält eine Liste der gesetzten Ordnungsreihenfolgen.
        private static readonly Dictionary<WeakReference, ListSortDirectionEx> LastDirections = new Dictionary<WeakReference, ListSortDirectionEx>();

        /// Wird aufgerufen, wenn der Benutzer auf eine Spaltenüberschrift in einem ListView klickt, für das Sortierung möglich ist.
        private static void ColumnClicked(object sender, RoutedEventArgs e)
        {
            var headerClicked = e.OriginalSource as GridViewColumnHeader;
            var lv = sender as ListView;

            var lastClickedHeader = LastClickedHeaders.FirstOrDefault(x => x.Key.Target == sender).Value;
            var lastDirection = LastDirections.FirstOrDefault(x => x.Key.Target == sender).Value;

            if (headerClicked == null || !GetIsSortAtClickEnabled(headerClicked.Column)) return;
            {
                if (headerClicked.Role == GridViewColumnHeaderRole.Padding) return;
                ListSortDirectionEx direction;
                if (!Equals(headerClicked, lastClickedHeader))
                {
                    direction = ListSortDirectionEx.Ascending;
                }
                else
                {
                    switch (lastDirection)
                    {
                        case ListSortDirectionEx.Ascending:
                            direction = ListSortDirectionEx.Descending;
                            break;
                        case ListSortDirectionEx.Descending:
                            direction = ListSortDirectionEx.None;
                            break;
                        case ListSortDirectionEx.None:
                            direction = ListSortDirectionEx.Ascending;
                            break;
                        default:
                            throw new ArgumentOutOfRangeException();
                    }
                }

                if (direction == ListSortDirectionEx.None)
                {
                    ClearSortRules(lv);
                }
                else
                {
                    Sort(((Binding)headerClicked.Column.DisplayMemberBinding).Path.Path, (ListSortDirection)direction, lv);
                }

                switch (direction)
                {
                    case ListSortDirectionEx.Ascending:
                        headerClicked.Column.HeaderTemplate = HeaderTemplateArrowUp;
                        break;
                    case ListSortDirectionEx.Descending:
                        headerClicked.Column.HeaderTemplate = HeaderTemplateArrowDown;
                        break;
                    case ListSortDirectionEx.None:
                        headerClicked.Column.HeaderTemplate = null;
                        break;
                }

                // Remove arrow from previously sorted header
                if (lastClickedHeader != null && !Equals(lastClickedHeader, headerClicked))
                {
                    lastClickedHeader.Column.HeaderTemplate = null;
                }
                LastClickedHeaders[LastClickedHeaders.FirstOrDefault(x => x.Key.Target == sender).Key] = headerClicked;
                LastDirections[LastDirections.FirstOrDefault(x => x.Key.Target == sender).Key] = direction;
            }
        }

        /// Sortiert das angegebene ListView nach der angegebenen Eigenschaft und in der angegebenen Reihenfolge.
        private static void Sort(string sortBy, ListSortDirection direction, ListView lv)
        {
            var dataView = CollectionViewSource.GetDefaultView(lv.ItemsSource);
            if (dataView == null)
            {
                return;
            }
            dataView.SortDescriptions.Clear();
            var sd = new SortDescription(sortBy, direction);
            dataView.SortDescriptions.Add(sd);
            dataView.Refresh();
        }

        /// Setzt die Sortierung für das angegebene ListView zurück.
        private static void ClearSortRules(ListView lv)
        {
            var dataView = CollectionViewSource.GetDefaultView(lv.ItemsSource);
            if (dataView == null)
            {
                return;
            }
            dataView.SortDescriptions.Clear();
            dataView.Refresh();
        }

        #region Types

        /// Die Möglichen Sortierreihenfolgen.
        private enum ListSortDirectionEx
        {
            Ascending = ListSortDirection.Ascending,
            Descending = ListSortDirection.Descending,
            None,
        }

        #endregion
    }
}


text:
'use strict';

const get = require('get-value');
const has = require('has-values');

module.exports = function(obj, path, options) {
  if (isObject(obj) && (typeof path === 'string' || Array.isArray(path))) {
    return has(get(obj, path, options));
  }
  return false;
};

function isObject(val) {
  return val != null && (typeof val === 'object' || typeof val === 'function' || Array.isArray(val));
}