text:
require 'web_blocks/strategy/link/base'
require 'web_blocks/structure/js_file'
require 'web_blocks/product/concat_file/js'

module WebBlocks
  module Strategy
    module Link
      class Js < Base

        def initialize task
          super task
          @log = task.log.scope 'JS - Link'
        end

        def product_path
          task.base_path + '.blocks/workspace/js/blocks.js'
        end

        def make_linker_file
          ::WebBlocks::Product::ConcatFile::Js.new product_path
        end

        def compute_files_to_link
          task.root.get_file_load_order(::WebBlocks::Structure::JsFile)
        end

      end
    end
  end
end


text:
<link rel="stylesheet" href="../style.css">

### Mailgun

![](mailgun.png)

Mailgun is an email automation service provided by Rackspace. It offers a complete cloud-based email service for sending, receiving and tracking email sent through your websites and applications. Login to Mailgun and go to "Routes" to access the full list of routes or to create a new mail forwarding route using the format shown.

redpajama_set_name: RedPajamaGithub


text:
namespace thewizardplusplus {
namespace wizard_basic_2 {
namespace framework {
namespace base {
namespace exceptions {

class BaseException : public framework::exceptions::
	WizardBasicFrameworkException
{
public:
	BaseException(const std::string& message);
};

}
}
}
}
}
#endif


text:
<!-- $Id: Page.html 677 2006-05-30 19:53:52Z mayer $ -->

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>PLACEHOLDER_TITLE</title>
<link rel="StyleSheet" href="style.css" type="text/css" media="all" />
</head>
<body>
PLACE_HOLDER_CONTENT
</body>
</html>


text:
class MongoClient
  include Mongoid::Document

  has_many :mongo_accounts
  field :name,          type: String
  field :accountant_id, type: Integer

  before_create :set_accountant

  def set_accountant
    self.accountant_id = User.current.id
  end

  def accountant
    User.find_by_id(self.accountant_id)
  end
end


text:
#pragma once

#include <stdio.h>
#include <stdlib.h>

#include "io.h"

struct cosmology_data
{
  double  G;
  double  H0;
  double h100;
  double  Omega_0;
  double  Omega_b;
  double  Omega_dm;
  double  Omega_m;
  double  Omega_lambda;
  double  Omega_rad;
  double  Omega_k;
  float K_fit;/* Maccio et al. 2008 fitting parameters*/
  float F_fit;
};

/* functions in set_cosmology */
double agefunc(double z,void *params);
double epeebles(float z);
double get_age(float z);
void set_cosmology(struct cosmology_data *CP);
float get_scalefactor(float z);
float get_overdensity(float z,struct cosmology_data *CP);
double get_rhocrit_at_redshift(float z,struct cosmology_data *CP);
double get_hubble_at_redshift(float z,struct cosmology_data *CP);
double getrvir_anyl(const double mvir,const float z,struct cosmology_data *CP);
float getconc_anyl(const double mvir,const float z);
void getrvir_from_overdensity(struct group_data *group,int NBINS,const double RhoCrit,const float OverDensity);


text:
using Microsoft.VisualStudio.TestTools.UnitTesting;
using BilibiliJJ_BarrageSystem.COM;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace BilibiliJJ_BarrageSystem.COM.Tests {
    [TestClass()]
    public class SinaWeiPanTests {
        [TestMethod()]
        public void Get_Access_TokenTest() {

        }
    }
}


text:
BASH Commands to create Chef Deployment package
-----

berks install
berks package Chef_LinuxServers.tar.gz
aws s3 cp Chef_LinuxServers.tar.gz s3://digitized.sanctuary.code.deploy

<!--
  AWS OpsWorks
  http://docs.aws.amazon.com/opsworks/latest/userguide/cli-examples.html
  http://docs.aws.amazon.com/cli/latest/reference/opsworks/index.html
-->

sId="bcb14c5b-b2cb-46d0-90d1-6dc23431d633"
sId
dId=aws opsworks --region us-east-1 create-deployment --stack-id $sId  --command '{"Name": "update_custom_cookbooks"}' --query 'DeploymentId'

aws opsworks --region us-east-1 wait deployment-successful --deployment-id $dId

"DeploymentId": "baf30d8a-df8c-4e19-81ce-87f91c644d1d"

---s3


text:
package com.helpers.notification.handlers;

import com.helpers.notification.messages.NotificationMessage;

//Interface for defining capabilities of methods to handle notifications
public interface NotificationHandler {

  void handle(NotificationMessage message);
}


text:
import React, { FunctionComponent } from "react"
import path from "path"
import { Box, Text } from "ink"
import { IStructuredError } from "../../../../structured-errors/types"

interface IFileProps {
  filePath: string
  location: IStructuredError["location"]
}

const File: FunctionComponent<IFileProps> = ({ filePath, location }) => {
  const lineNumber = location?.start.line

  let locString = ``
  if (typeof lineNumber !== `undefined`) {
    locString += `:${lineNumber}`
    const columnNumber = location?.start.column
    if (typeof columnNumber !== `undefined`) {
      locString += `:${columnNumber}`
    }
  }

  return (
    <Text color="blue">
      {path.relative(process.cwd(), filePath)}
      {locString}
    </Text>
  )
}

interface IDocsLinkProps {
  docsUrl: string | undefined
}

const DocsLink: FunctionComponent<IDocsLinkProps> = ({ docsUrl }) => {
  // TODO: when there's no specific docsUrl, add helpful message describing how
  // to submit an issue
  if (docsUrl === `https://gatsby.dev/issue-how-to`) return null
  return (
    <Box marginTop={1}>
      <Text>See our docs page for more info on this error: {docsUrl}</Text>
    </Box>
  )
}

export interface IErrorProps {
  details: IStructuredError
}

export const Error: FunctionComponent<IErrorProps> = React.memo(
  ({ details }) => (
    // const stackLength = get(details, `stack.length`, 0

    <Box marginY={1} flexDirection="column">
      <Box flexDirection="column">
        <Box flexDirection="column">
          <Box>
            <Box marginRight={1}>
              <Text color="black" backgroundColor="red">
                {` ${details.level} `}
                {details.code ? `#${details.code} ` : ``}
              </Text>
              <Text color="red">{details.type ? ` ` + details.type : ``}</Text>
            </Box>
          </Box>
          <Box marginTop={1}>
            <Text>{details.text}</Text>
          </Box>
          {details.filePath && (
            <Box marginTop={1}>
              <Text>File:{` `}</Text>
              <File filePath={details.filePath} location={details.location} />
            </Box>
          )}
        </Box>
        <DocsLink docsUrl={details.docsUrl} />
      </Box>
      {/* TODO: use this to replace errorFormatter.render in reporter.error func
      {stackLength > 0 && (
        <Box>
          <Color>
            <Box flexDirection="column">
              <Box>Error stack:</Box>
              {details.stack.map((item, id) => (
                <Box key={id}>
                  {item.fileName && `${item.fileName} line ${item.lineNumber}`}
                </Box>
              ))}
            </Box>
          </Color>
        </Box>
      )} */}
    </Box>
  )
)


text:
#ifndef SimTK_SIMBODY_FORCE_GRAVITY_H_
#define SimTK_SIMBODY_FORCE_GRAVITY_H_

#include "SimTKcommon.h"
#include "simbody/internal/Force.h"

/** @file
This contains the user-visible API ("handle" class) for the SimTK::Force
subclass Force::Gravity and is logically part of Force.h. The file assumes that
Force.h will have included all necessary declarations. **/

namespace SimTK {

/** This force element represents a uniform gravitational field applied to a
set of bodies. This can be used instead of the more limited
Force::UniformGravity class if you want more control.

Force::Gravity is given a magnitude g in units of acceleration, and a "down"
direction (unit vector) d, expressed in the Ground frame. For example, in SI
units "standard gravity" g at the Earth's surface is defined to be exactly
g=9.80665 m/s^2. If gravity acts in Ground's -Y direction, then its direction
vector is d=[0,-1,0]; together this yields a gravity vector
v=g*d=[0,-9.80665,0]. By default gravity will be applied to each MobilizedBody
in the given SimbodyMatterSubsystem (except for Ground). You can specify that
some bodies are excluded; those will not have a gravity force applied. You can
include multiple Force::Gravity elements with different exclusion lists in the
same System if you want different bodies to feel different effects.

\par Force
Each body B that has not been explicitly excluded will experience a force
fb = mb*g*d, applied to its center of mass, where mb is the mass of body B.
Although this is a pure force, note that when it is measured in the body frame
B there will also be a moment unless the body frame origin Bo is located at the
body's mass center. You can obtain the applied forces if you need them, for
example for gravity compensation; see getBodyForces().

\par Potential Energy
Gravitational potential energy for a body B is mb*g*hb where hb is the height of
body B's mass center over an arbitrary "zero" height hz (default is hz=0),
measured along the "up" direction -d. If pb is the Ground frame vector giving
the position of body B's mass center, its height over or under hz is
hb=pb*(-d) - hz. Note that this is a signed quantity so the potential energy is
also signed.

@author Michael Sherman
**/
class SimTK_SIMBODY_EXPORT Force::Gravity : public Force {
public:

//------------------------------------------------------------------------------
/** @name                       Construction
Methods in this section refer both to constructors, and to methods that can
be used to set or change contruction (Topology-stage) parameters; these
specify the values assigned by default to the corresponding state variables.
Note:
  - Changing one of these default parameters invalidates the containing
    System's topology, meaning that realizeTopology() will have to be called
    and a new State obtained before subsequent use.
  - The set...() methods return a reference to "this" %Gravity element (in
    the manner of an assignment operator) so they can be chained in a single
    expression. **/
/*@{*/

/** This is the most general constructor for creating a %Gravity force element
within a particular force subsystem and affecting all the bodies of a particular
matter subsystem, given gravity magnitude and direction separately.

If you want to exclude by default some bodies from the effects of this force
element, call setDefaultBodyIsExcluded(). You can also make changes on the
fly with setBodyIsExcluded().

@param[in,out]      forces
    The subsystem to which this force should be added.
@param[in]          matter
    The subsystem containing the bodies that will be affected.
@param[in]          down
    The default gravity direction vector d (i.e., the "down" direction),
    expressed in the Ground frame. %Gravity will be directed along this direction
    unless explicitly changed within a particular State via the setDirection()
    or setGravityVector() methods. This is a unit vector; if you provide an
    ordinary Vec3 it will be normalized before use and its magnitude ignored.
    It is an error to provide a zero vector here; provide a zero magnitude
    instead or use the alternate constructor.
@param[in]          g
    The default magnitude g to be used for gravity, given as a nonnegative
    scalar with units of acceleration. The gravity vector is calculated as
    v=g*d where d is the current direction vector, typically the default
    direction as given by the \a down argument to this constructor.
    %Gravity will have the magnitude given here unless explicitly changed within
    a particular State via the setMagnitude() or setGravityVector() methods.
@param[in]          zeroHeight
    This is an optional specification of the default value for the height
    up the gravity vector that is considered to be "zero" for purposes of
    calculating the gravitational potential energy. The default is
    \a zeroHeight == 0, i.e., a body's potential energy is defined to be zero
    when the height of its mass center is the same as the height of the Ground
    origin. The zero height will have the value specified here unless
    explicitly changed within a particular State use the setZeroHeight()
    method. **/
Gravity(GeneralForceSubsystem&          forces,
        const SimbodyMatterSubsystem&   matter,
        const UnitVec3&                 down,
        Real                            g,
        Real                            zeroHeight = 0);

/** Convenience constructor to create a %Gravity force element by specifying
only a gravity vector, that is, the product of the gravity magnitude and the
"down" direction vector. We have to extract both a magnitude and direction from
this since they are maintained separately by this force element. If you provide
a zero vector here (exactly zero, that is), then the magnitude is zero but there
is no direction. In that case we default to the negative of the containing
System's default "up" direction.

If you want to exclude by default some bodies from the effects of this force
element, call setDefaultBodyIsExcluded(). You can also make changes on the
fly with setBodyIsExcluded().

@param[in,out]      forces
    The subsystem to which this force should be added.
@param[in]          matter
    The subsystem containing the bodies that will be affected.
@param[in]          gravity
    The default gravity vector v, interpreted as v=g*d where g=|\a gravity| is
    a positive scalar and d is the "down" direction unit vector d=\a gravity/g.
    If the magnitude is exactly zero we'll set the "down" direction to the
    opposite of the containing System's "up" direction, otherwise the direction
    is extracted from the given vector.

This constructor sets the default zero height hz to zero (for use in calculating
gravitational potential energy). If you want a different default value, use
the more general constructor or the setDefaultZeroHeight() method.
@see SimTK::System::setUpDirection() **/
Gravity(GeneralForceSubsystem&          forces,
        const SimbodyMatterSubsystem&   matter,
        const Vec3&                     gravity);

/** Convenience constructor to create a %Gravity force element by specifying
only gravity's magnitude, with the direction chosen to oppose the containing
System's "up" direction. Note that the direction is extracted from the System
and recorded when this %Gravity element is contructed; it will not be affected
by subsequent changes to the System's up direction.

If you want to exclude by default some bodies from the effects of this force
element, call setDefaultBodyIsExcluded(). You can also make changes on the
fly with setBodyIsExcluded().

@param[in,out]      forces
    The subsystem to which this force should be added.
@param[in]          matter
    The subsystem containing the bodies that will be affected.
@param[in]          g
    The default magnitude g to be used for gravity, given as a nonnegative
    scalar with units of acceleration. %Gravity will have the magnitude given
    here unless explicitly changed within a particular State via the
    setMagnitude() or setGravityVector() methods.

This constructor sets the default zero height hz to zero (for use in calculating
gravitational potential energy). If you want a different default value, use
the more general constructor or the setDefaultZeroHeight() method.
@see SimTK::System::setUpDirection() **/
Gravity(GeneralForceSubsystem&          forces,
        const SimbodyMatterSubsystem&   matter,
        Real                            g);

/** Default constructor creates an empty handle. **/
Gravity() {}

/** Set how the indicated body is to be treated by default. Normally all bodies
except Ground are affected by this force element so you only need to call this
if you want to exclude a body. This is a topological change since the flag will
be stored with the System; for on-the-fly changes you should call
setBodyIsExcluded() instead. Ground is always excluded; you can call this
method on Ground but the call will be ignored.

@param[in]      mobod
    This is a MobilizedBody or MobilizedBodyIndex for the body whose
    default exclusion status you want to change.
@param[in]      isExcluded
    Set to true if the default should be that this body is \e not to be affected
    by this %Gravity force element.
@return A writable reference to "this" %Gravity element which will now have
    the indicated body excluded.

@see setBodyIsExcluded() **/
Gravity& setDefaultBodyIsExcluded(MobilizedBodyIndex mobod, bool isExcluded);

/** Set the default value for the gravity vector, that is, the direction and
magnitude with which gravity will act. From the given vector we extract
separately the magnitude g and "down" direction d (a unit vector), unless the
magnitude is exactly zero in which case we'll leave the direction unchanged.
@param[in]      gravity
    A vector giving the magnitude and direction with which gravity will act
    on the bodies. If exactly zero only the magnitude will be changed.
@return A writable reference to "this" %Gravity element which will now have
    the new default magnitude and direction. **/
Gravity& setDefaultGravityVector(const Vec3& gravity);

/** Set the default "down" direction d, that is, the direction along which
gravity will act.
@param[in] down
    A unit vector giving the direction along which gravity will act ("down").
    If you pass an ordinary Vec3, it will be normalized before use and its
    length will be ignored. Do not pass a zero-length Vec3, however.
@return A writable reference to "this" %Gravity element which will now have
    the new default \a direction. **/
Gravity& setDefaultDownDirection(const UnitVec3& down);
/** Convenience overload that takes the down direction as a Vec3 and
normalizes it (throwing away the magnitude) to create the required unit
vector for the down direction. It is an error if the supplied Vec3 has zero
length. **/
Gravity& setDefaultDownDirection(const Vec3& down)
{   return setDefaultDownDirection(UnitVec3(down)); }

/** Set the default magnitude of gravity (a nonegative scalar). This will be
combined with the default \a direction unit vector d to calculate the gravity
vector v = g*d that is used to generate body forces mb*v where mb is the
mass of body b and the force is applied to b's mass center.
@param[in]      g
    The magnitude of the uniform gravitational field, given as a nonnegative
    scalar in units of acceleration. If this is zero no forces will be applied
    by this element.
@return A writable reference to "this" %Gravity element which will now have
    the new default \a strength. **/
Gravity& setDefaultMagnitude(Real g);

/** Set the default zero height (a signed scalar), for use in potential energy
calculation. See the Gravity class comments for how this is used.
@param[in]      zeroHeight
    The height that is considered to be "zero" for purposes of potential
    energy calculation. An affected body whose mass center is at this height
    will have zero gravitational potential energy.
@return A writable reference to "this" %Gravity element which will now have
    the new default \a zeroHeight. **/
Gravity& setDefaultZeroHeight(Real zeroHeight);

/** Return the current setting of the "is excluded by default" flag for the
given body. This is the status that the flag will have in the default State
returned by System::realizeTopology().
@param[in]      mobod
    This is a MobilizedBody or MobilizedBodyIndex for the body whose
    exclusion status you want to obtain.
@return The current value of the "is excluded by default" flag for this body;
    this will always be \c true for Ground.
@see getBodyIsExcluded() **/
bool getDefaultBodyIsExcluded(MobilizedBodyIndex mobod) const;
/** Return the default gravity vector being used for this %Gravity force
element, calculated from the default magnitude and direction. **/
Vec3 getDefaultGravityVector() const;
/** Return the default down direction (a unit vector) for this %Gravity force
element. **/
const UnitVec3& getDefaultDownDirection() const;
/** Return the default gravity magnitude g (a nonnegative scalar). **/
Real getDefaultMagnitude() const;
/** Return the default zero height used in the calculation of graviational
potential energy. **/
Real getDefaultZeroHeight() const;

/*@}............................ Construction ................................*/

//------------------------------------------------------------------------------
/** @name                      Runtime Changes

These refer to Dynamics-stage discrete state variables that determine the actual
values to be used to calculate gravitational forces and energy from a given
State object, and which bodies are to be excluded from that calculation. If
these are not set explicitly, the values are set to those provided in the
constructor or via the correponding setDefault...() methods. Note:
  - Changing one of these parameters invalidates the given State's
    Stage::Dynamics, meaning that the State's stage will be no higher than
    Stage::Velocity after the parameter change. That ensures that forces
    will be recalcuated before they are used (forces are calculated when
    Stage::Dynamics is realized).
  - The set...() methods here return a const reference to "this" %Gravity force
    element (in the manner of an assignment operator, except read-only) so they
    can be chained in a single expression. **/
/*@{*/

/** Within a given State, selectively exclude (or include) a body from the
effects of this %Gravity force. The default State will inherit the "is excluded
by default" values set during construction, but then you can change them. Ground
is always excluded; you can call this method on Ground but the call will
be ignored.
@param[in,out]      state
    The State object that is modified by this method; Stage::Dynamics will
    be invalidated leaving the current stage no higher than Stage::Velocity.
@param[in]          mobod
    This is a MobilizedBody or MobilizedBodyIndex for the body whose
    exclusion status you want to change.
@param[in]          isExcluded
    Set to true if this body should \e not be affected by this force element.
@return A const reference to "this" %Gravity force element for convenient
    chaining of  set...() methods in a single expression.
@pre \a state must already be realized to Stage::Topology.
@post Stage::Dynamics is invalidated in \a state if anything was changed.
@see setDefaultBodyIsExcluded(), getBodyIsExcluded() **/
const Gravity& setBodyIsExcluded(State& state, MobilizedBodyIndex mobod,
                                bool isExcluded) const;

/** Set the gravity vector v, that is, the magnitude and direction with which
gravitational forces will act, overriding the default magnitude and direction
that are stored in this %Gravity force element. If the given vector is exactly
zero, then only the magnitude will be changed here.
@param[in,out]      state
    The State object that is modified by this method; Stage::Dynamics will
    be invalidated leaving the current stage no higher than Stage::Velocity.
@param[in]          gravity
    The gravity vector including both the magnitude and direction. If this is
    exactly zero only the magnitude will be changed.
@return A const reference to "this" %Gravity element for convenient chaining of
    set...() methods in a single expression.
@pre \a state must already be realized to Stage::Topology.
@post Stage::Dynamics is invalidated in \a state if anything was changed.
@see setDownDirection(), setMagnitude() **/
const Gravity& setGravityVector(State& state, const Vec3& gravity) const;

/** Set the "down" direction d (a unit vector), that is, the direction along
which gravitational forces will act. Magnitude can be changed independently
with setMagnitude().
@param[in,out]      state
    The State object that is modified by this method; Stage::Dynamics will
    be invalidated leaving the current stage no higher than Stage::Velocity.
@param[in]          down
    A unit vector giving the "down" direction along which gravity will act.
@return A const reference to "this" %Gravity element for convenient chaining of
    set...() methods in a single expression.
@pre \a state must already be realized to Stage::Topology.
@post Stage::Dynamics is invalidated in \a state if anything was changed.
@see setMagnitude() **/
const Gravity& setDownDirection(State&           state,
                                const UnitVec3&  down) const;
/** Convenience overload that takes the down direction as a Vec3 and
normalizes it (throwing away the magnitude) to create the required unit
vector. It is an error if the supplied Vec3 has zero length. **/
const Gravity& setDownDirection(State&          state,
                                const Vec3&     down) const
{   return setDownDirection(state, UnitVec3(down)); }

/** Set the gravity magnitude g (a nonnegative scalar) in this \a state,
overriding the default gravity magnitude that is stored in this %Gravity force
element.
@param[in,out]      state
    The State object that is modified by this method; Stage::Dynamics will
    be invalidated leaving the current stage no higher than Stage::Velocity.
@param[in]          g
    The magnitude of the uniform gravitational field.
@return A const reference to "this" %Gravity element for convenient chaining of
    set...() methods in a single expression.
@pre \a state must already be realized to Stage::Topology.
@post Stage::Dynamics is invalidated in \a state if anything was changed.
@see setDownDirection() **/
const Gravity& setMagnitude(State& state, Real g) const;

/** Set the potential energy zero height hz (a scalar) in this \a state,
overriding the default zero height that is stored in this %Gravity force
element.
@param[in,out]      state
    The State object that is modified by this method; Stage::Dynamics will
    be invalidated leaving the current stage no higher than Stage::Velocity.
@param[in]          hz
    The height at which potential energy is considered to be zero.
@return A const reference to "this" %Gravity element for convenient chaining of
    set...() methods in a single expression.
@pre \a state must already be realized to Stage::Topology.
@post Stage::Dynamics is invalidated in \a state if anything was changed. **/
const Gravity& setZeroHeight(State& state, Real hz) const;

/** Return the current setting of the "is excluded" flag for a given body in a
given State. This is not necessarily the same as the default value for this
body's exclusion status.
@param[in]      state
    The state containing the "is excluded" flag to be obtained.
@param[in]      mobod
    A MobilizedBody or MobilizedBodyIndex for the body whose exclusion status
    you want to obtain.
@return The current value of the "is excluded" flag for this body in this
    \a state; this will always be \c true for Ground.
@pre \a state must already be realized to Stage::Topology.
@see getDefaultBodyIsExcluded(), setBodyIsExcluded() **/
bool getBodyIsExcluded(const State& state, MobilizedBodyIndex mobod) const;
/** Get the gravity vector v that will be used for computations done with this
\a state. This is calculated as v=g*d from the current values of the magnitude
g and direction d Instance variables in the \a state.
@param[in]      state
    The state containing the gravity runtime variables used to calculate the
    gravity vector.
@return The current value of the gravity vector.
@pre \a state must have been realized to Topology stage. **/
Vec3 getGravityVector(const State& state) const;
/** Get the gravity "down" direction d (a unit vector) that is currently set
in this \a state.
@param[in]      state
    The state containing the gravity direction runtime variable whose value is
    returned.
@return The current value of the gravity direction variable.
@pre \a state must have been realized to Topology stage. **/
const UnitVec3& getDownDirection(const State& state) const;
/** Get the gravity magnitude g (a nonnegative scalar) that is currently set
in this \a state.
@param[in]      state
    The state containing the gravity magnitude runtime variable whose value is
    returned.
@return The current value of the gravity magnitude variable.
@pre \a state must have been realized to Topology stage. **/
Real getMagnitude(const State& state) const;
/** Get the zero height hz that is currently set in this \a state for use in
calculating gravitational potential energy. See the class documentation for
information about hz is used.
@param[in]      state
    The state containing the zero height runtime variable whose value is
    returned.
@return The current value of the zero height variable.
@pre \a state must have been realized to Topology stage. **/
Real getZeroHeight(const State& state) const;

/*@}.......................... Runtime Changes ...............................*/

//------------------------------------------------------------------------------
/** @name                       Energy and Forces
These methods return the gravitational potential energy and the forces being
applied by this %Gravity element in the configuration contained in the supplied
State. These are evaluated during force calculation and available at no
computational cost afterwards, although the first call after a position or
runtime variable change will initiate computation if forces haven't already
been computed. **/
/*@{*/

/** Obtain the gravitational potential energy contained in this %Gravity force
element in the given configuration. Note that gravitational potential energy
is m*g*h for each body where the height h is measured from an arbitrary zero
height. By default the zero height is defined to be height of the Ground
origin but that can be changed arbitrarily.
@param[in]          state
    The State from whose cache the potential energy is retrieved.
@return The gravitational potential energy of this %Gravity force element in the
    configuration contained in \a state (a signed scalar).
@pre \a state must be realized to Stage::Position **/
Real getPotentialEnergy(const State& state) const;

/** Obtain a reference to the set of gravitational forces currently being
applied by this %Gravity force element, as a Vector of spatial forces indexed
by MobilizedBodyIndex. The force on Ground or on any explicitly excluded body
is zero, but there is an entry for every mobilized body (starting with Ground)
in the returned result. The return vector of spatial vectors is in a form
suitable for direct use with the SimbodyMatterSubsystem Jacobian operators,
which can be used to transform these into the equivalent generalized forces.
This can be useful for gravity compensation.

@param[in]  state
    The State from whose cache the force is retrieved.
@return A reference to the vector of spatial forces (meaning the gravitational
    moment about and force at the body origin, \e not necessarily the center
    of mass) currently being applied to each of the mobilized bodies, expressed
    in the Ground frame.
@pre \a state must be realized to Stage::Position

Forces are returned as though applied at the body origin, which is
\e not necessarily the same place as the body center of mass. That means that
in general there will be both a moment and a force returned for each body.

If gravity forces have not yet been calculated for the configuration given
in \a state, the computation will be initiated here and cached for use later.
**/
const Vector_<SpatialVec>& getBodyForces(const State& state) const;

/** Convenience method to extract the gravitational force on just one body;
see getBodyForces() to get the whole set at once, and for more information.

@param[in]  state
    The State from whose cache the force is retrieved.
@param[in]  mobod
    The MobilizedBody or MobilizedBodyIndex whose force is wanted.
@return The spatial force (meaning the gravitational force and moment about
    the body origin, \e not necessarily the center of mass) currently being
    applied to the given mobilized body, expressed in the Ground frame.
@pre \a state must be realized to Stage::Position **/
const SpatialVec&
getBodyForce(const State& state, MobilizedBodyIndex mobod) const
{   return getBodyForces(state)[mobod]; }

// Particles aren't supported yet so don't show this in Doxygen.
/** @cond **/
/** Obtain the gravitational forces currently being applied by this %Gravity
force element to the particles.
@param[in]  state       The State from whose cache the force is retrieved.
@return The current value of the forces, expressed in the Ground frame.
@pre \a state must be realized to Stage::Position **/
const Vector_<Vec3>& getParticleForces(const State& state) const;
/** @endcond **/

/*@}............................ Energy and Forces ...........................*/

//------------------------------------------------------------------------------
/** @name                     Debugging/Testing
This is information for use by developers of this class for debugging and
testing -- please ignore. **/
/*@{*/
/** Return a count of the number of times the set of gravitational forces
or potential energy was calculated since this force element was constructed.
Note that this is not a per-body count. This count is only incremented when an
actual computation is performed, not when forces are requested but are already
valid. Also, we don't consider it a computation if the gravity magnitude is
zero. This is intended for use in testing that caching and invalidation is being
done properly. **/
long long getNumEvaluations() const;

/** Return true if the gravitational forces for this configuration have already
been calculated and are up to date. That means they can be retrieved with no
further evaluation. **/
bool isForceCacheValid(const State& state) const;

/** Invalidate the stored gravitational forces if they have already been
calculated at this configuration. That will force a new evaluation the next
time they are requested (unless the gravity magnitude is currently zero). **/
void invalidateForceCache(const State& state) const;
/*@}*/

// Don't show this in Doxygen.
/** @cond **/
SimTK_INSERT_DERIVED_HANDLE_DECLARATIONS(Gravity, GravityImpl, Force);
/** @endcond **/
};

} // namespace SimTK

#endif // SimTK_SIMBODY_FORCE_GRAVITY_H_


text:
using System;
using Jal.Factory.Impl;
using Jal.Factory.Interface;
using Jal.Locator.Interface;
using Jal.Validator.Interface;
using Jal.Validator.Model;

namespace Jal.Validator.Impl
{
    public class ModelValidator : IModelValidator
    {
        public ModelValidator(IValidatorFactory validatorFactory)
        {
            Factory = validatorFactory;

            Interceptor = AbstractModelValidatorInterceptor.Instance;
        }

        public static IModelValidator Current;

        public static IModelValidator Create(IObjectFactoryConfigurationSource[] sources, IServiceLocator locator)
        {
            return new ModelValidator(new ValidatorFactory(new ObjectFactory(new ObjectFactoryConfigurationProvider(sources), new ObjectCreator(locator))));
        }

        public IModelValidatorInterceptor Interceptor { get; set; }

        ValidationResult Try<T>(T instance,  Func<IValidator<T>[]> creation, Func<IValidator<T>, ValidationResult> validation)
        {
            Interceptor.OnEnter(instance);
            try
            {
                var validators = creation();

                if (validators != null)
                {
                    foreach (var validator in validators)
                    {
                        var result = validation(validator);

                        if (!result.IsValid)
                        {
                            Interceptor.OnSuccess(instance, result);

                            return result;
                        }
                    }
                }

                return new ValidationResult();
            }
            catch (Exception ex)
            {
                Interceptor.OnError(instance, ex);

                throw;
            }
            finally
            {
                Interceptor.OnExit(instance);
            }
        }

        #region IModelValidator Members

        public ValidationResult Validate<T>(T instance)
        {
            return Try(instance, () => Factory.Create(instance, string.Empty), validator => validator.Validate(instance));
        }

        public ValidationResult Validate<T>(T instance, dynamic context)
        {
            return Try(instance, () => Factory.Create(instance, string.Empty), validator => validator.Validate(instance, context));
        }

        public ValidationResult Validate<T>(T instance, string validationgroup , dynamic context)
        {

            return Try(instance, () => Factory.Create(instance, validationgroup), validator => validator.Validate(instance, context));

        }

        public ValidationResult Validate<T>(T instance, string validationgroup, string validationsubgroup, dynamic context)
        {
            return Try(instance, () => Factory.Create(instance, validationgroup), validator => validator.Validate(instance, validationsubgroup, context));
        }

        public IValidatorFactory Factory { get; set; }

        public ValidationResult Validate<T>(T instance, string validationgroup)
        {
            return Try(instance, () => Factory.Create(instance, validationgroup), validator => validator.Validate(instance));

        }

        public ValidationResult Validate<T>(T instance, string validationgroup, string validationsubgroup)
        {
            return Try(instance, () => Factory.Create(instance, validationgroup), validator => validator.Validate(instance, validationsubgroup));
        }

        #endregion
    }
}


text:
package org.easycassandra.bean.model;

import javax.persistence.Column;
import javax.persistence.EmbeddedId;
import javax.persistence.MappedSuperclass;

/**
 * @author Nenita A. Casuga
 *         Date 10/28/13
 */
@MappedSuperclass
public class Lifestyle {

    @EmbeddedId
    private IdLifestyle id;

    @Column
    private Double value;

    public Double getValue() {
        return value;
    }

    public void setValue(Double value) {
        this.value = value;
    }

    public IdLifestyle getId() {
        return id;
    }

    public void setId(final IdLifestyle id) {
        this.id = id;
    }

}


text:
package com.intellij.execution.process;

import com.intellij.execution.ExecutionException;
import com.intellij.execution.configurations.GeneralCommandLine;
import com.intellij.openapi.util.Key;
import org.jetbrains.annotations.NotNull;

import java.nio.charset.Charset;

/**
 * @author Roman Chernyatchik
 */
public class ColoredProcessHandler extends OSProcessHandler implements AnsiEscapeDecoder.ColoredTextAcceptor {
  private final AnsiEscapeDecoder myAnsiEscapeDecoder = new AnsiEscapeDecoder();

  public ColoredProcessHandler(final GeneralCommandLine commandLine) throws ExecutionException {
    super(commandLine.createProcess(), commandLine.getCommandLineString(), commandLine.getCharset());
  }

  public ColoredProcessHandler(Process process, String commandLine) {
    super(process, commandLine);
  }

  public ColoredProcessHandler(final Process process,
                               final String commandLine,
                               @NotNull final Charset charset) {
    super(process, commandLine, charset);
  }

  @Override
  public final void notifyTextAvailable(final String text, final Key outputType) {
    myAnsiEscapeDecoder.escapeText(text, outputType, this);
  }

  @Override
  public void coloredTextAvailable(String text, Key attributes) {
    textAvailable(text, attributes);
  }

  /**
   * @deprecated Inheritors should override coloredTextAvailable method
   * or implement {@link com.intellij.execution.process.AnsiEscapeDecoder.ColoredChunksAcceptor}
   * and override method coloredChunksAvailable to process colored chunks.
   * To be removed in IDEA 14.
   */
  protected void textAvailable(final String text, final Key attributes) {
    super.notifyTextAvailable(text, attributes);
  }
}


text:
<!DOCTYPE HTML>

hello


text:
id: 587d7b7d367417b2b2512b1e
title: Generate an Array of All Object Keys with Object.keys()
challengeType: 1
forumTopicId: 301160
---

## Description

We can also generate an array which contains all the keys stored in an object using the Object.keys() method and passing in an object as the argument. This will return an array with strings representing each property in the object. Again, there will be no specific order to the entries in the array.

## Instructions

Finish writing the getArrayOfUsers function so that it returns an array containing all the properties in the object it receives as an argument.

## Tests

```yml
tests:
  - text: The <code>users</code> object should only contain the keys <code>Alan</code>, <code>Jeff</code>, <code>Sarah</code>, and <code>Ryan</code>
    testString: assert('Alan' in users && 'Jeff' in users && 'Sarah' in users && 'Ryan' in users && Object.keys(users).length === 4);
  - text: The <code>getArrayOfUsers</code> function should return an array which contains all the keys in the <code>users</code> object
    testString: assert((function() { users.Sam = {}; users.Lewis = {}; let R = getArrayOfUsers(users); return (R.indexOf('Alan') !== -1 && R.indexOf('Jeff') !== -1 && R.indexOf('Sarah') !== -1 && R.indexOf('Ryan') !== -1 && R.indexOf('Sam') !== -1 && R.indexOf('Lewis') !== -1); })() === true);

```

## Challenge Seed

```js
let users = {
  Alan: {
    age: 27,
    online: false
  },
  Jeff: {
    age: 32,
    online: true
  },
  Sarah: {
    age: 48,
    online: false
  },
  Ryan: {
    age: 19,
    online: true
  }
};

function getArrayOfUsers(obj) {
  // change code below this line

  // change code above this line
}

console.log(getArrayOfUsers(users));
```

## Solution

```js
let users = {
  Alan: {
    age: 27,
    online: false
  },
  Jeff: {
    age: 32,
    online: true
  },
  Sarah: {
    age: 48,
    online: false
  },
  Ryan: {
    age: 19,
    online: true
  }
};

function getArrayOfUsers(obj) {
  return Object.keys(obj);
}

console.log(getArrayOfUsers(users));
```


text:
from phovea_server.ns import Namespace, request, Response, abort
import tables
import numpy as np
import itertools
from phovea_server.util import to_json, jsonify
import logging
import phovea_server.config
import memcache

_log = logging.getLogger(__name__)

# create the api application
app = Namespace(__name__)

filename = phovea_server.config.get('file', 'pathfinder_ccle')
_log.debug('loading file: %s', filename)
h5 = tables.open_file(filename, 'r')

mc = memcache.Client([phovea_server.config.get('memcached', 'pathfinder_ccle')], debug=0)

mc_prefix = 'ccle_'

@app.route('/')
def all():
  key = mc_prefix + '_info'
  obj = mc.get(key)
  if not obj:
    obj = all_impl()
    mc.set(key, obj)
  return Response(obj, mimetype='application/json')

def all_impl():
  r = []
  for group in h5.walk_groups('/'):
    if 'type' not in group._v_attrs:
      continue
    _log.debug('loading group %s', group)
    tt = group._v_attrs.type
    base = dict(id=group._v_name, name=group._v_title.strip(), type=tt)
    if tt == 'matrix':
      base['coltype'] = group._v_attrs.coltype.strip()
      base['rowtype'] = group._v_attrs.rowtype.strip()
    elif tt == 'stratification':
      base['idtype'] = group._v_attrs.idtype.strip()
    r.append(base)

  return to_json(r)

@app.route('/<dataset>')
def get_info(dataset):
  key = mc_prefix + dataset + '_info'
  obj = mc.get(key)
  if not obj:
    obj = get_info_impl(dataset)
    mc.set(key, obj)
  return Response(obj, mimetype='application/json')

def get_info_impl(dataset):
  if '/' + dataset not in h5:
    abort(404)

  group = h5.get_node('/' + dataset)
  if group._v_attrs.type == 'matrix':
    return to_json(name=group._v_name, title=group._v_title.strip(), coltype=group._v_attrs.coltype.strip(),
                   rowtype=group._v_attrs.rowtype.strip(), dim=map(int, group.data.shape))
  if group._v_attrs.type == 'stratification':
    return to_json(name=group._v_name, title=group._v_title.strip(), idtype=group._v_attrs.idtype.strip(),
                   groups={name: dict(title=gf._v_title, size=len(gf)) for name, gf in group._v_children.iteritems()})

def resolve(dataset):
  rows = request.args.getlist('rows[]')
  cols = request.args.getlist('cols[]')
  rowdata = h5.get_node('/' + dataset + '/rows')
  if len(rows) > 0:
    rowids = np.nonzero(np.in1d(rowdata, rows))[0]
    rowdata = rowdata[rowids]
  else:
    rowids = Ellipsis
  coldata = h5.get_node('/' + dataset + '/cols')
  if len(cols) > 0:
    colids = np.nonzero(np.in1d(coldata, cols))[0]
    coldata = coldata[colids]
  else:
    colids = Ellipsis
  data = h5.get_node('/' + dataset + '/data')
  mini = data[rowids, colids]
  return mini, rowdata, coldata

@app.route('/<dataset>/data', methods=['GET', 'POST'])
def get_data(dataset):
  key = mc_prefix + dataset + '_data'
  obj = mc.get(key)
  if not obj:
    obj = get_data_impl(dataset)
    mc.set(key, obj)
  return Response(obj, mimetype='application/json')

def get_data_impl(dataset):
  if '/' + dataset not in h5:
    abort(404)
  mini, rows, cols = resolve(dataset)
  return to_json(dict(data=mini, cols=cols, rows=rows))

@app.route('/<dataset>/stats', methods=['GET', 'POST'])
def get_stats(dataset):
  axis = request.args.get('axis', None)
  key = mc_prefix + dataset + '_stats' + (axis if axis is not None else '')
  obj = mc.get(key)
  if not obj:
    obj = get_stats_impl(dataset, axis)
    mc.set(key, obj)
  return Response(obj, mimetype='application/json')

def get_stats_impl(dataset, axis):
  mini, rows, cols = resolve(dataset)
  if axis == 'rows':
    axis = 1
  elif axis == 'cols':
    axis = 0
  amin = np.nanmin(mini, axis=axis)
  amax = np.nanmax(mini, axis=axis)
  amedian = np.median(mini, axis=axis)
  amean = np.nanmean(mini, axis=axis)
  astd = np.nanstd(mini, axis=axis)
  if axis is None:
    return to_json(dict(min=float(amin), max=float(amax), median=float(amedian), mean=float(amean), std=float(astd)))
  elif axis == 1:
    r = dict()
    for i, row in enumerate(rows):
      r[row] = dict(dict(min=float(amin[i]), max=float(amax[i]), median=float(amedian[i]), mean=float(amean[i]),
                         std=float(astd[i])))
    return to_json(**r)
  elif axis == 0:
    r = dict()
    for i, row in enumerate(cols):
      r[row] = dict(dict(min=float(amin[i]), max=float(amax[i]), median=float(amedian[i]), mean=float(amean[i]),
                         std=float(astd[i])))
    return to_json(**r)

@app.route('/<dataset>/rows', methods=['GET', 'POST'])
def get_rows(dataset):
  rows = request.args.getlist('rows[]')
  key = mc_prefix + dataset + '_rows_' + ','.join(rows)
  obj = mc.get(key)
  if not obj:
    obj = get_rows_impl(dataset, rows)
    mc.set(key, obj)
  return Response(obj, mimetype='application/json')

def get_rows_impl(dataset, rows):
  if '/' + dataset not in h5:
    abort(404)
  if len(rows) > 0:
    rowids = np.nonzero(np.in1d(h5.get_node('/' + dataset + '/rows'), rows))[0]
  else:
    rowids = Ellipsis
  data = h5.get_node('/' + dataset + '/rows')
  return to_json(data[rowids])

@app.route('/<dataset>/cols', methods=['GET', 'POST'])
def get_cols(dataset):
  rows = request.args.getlist('cols[]')
  key = mc_prefix + dataset + '_cols_' + ','.join(rows)
  obj = mc.get(key)
  if not obj:
    obj = get_cols_impl(dataset, rows)
    mc.set(key, obj)
  return Response(obj, mimetype='application/json')

def get_cols_impl(dataset, rows):
  if '/' + dataset not in h5:
    abort(404)
  if len(rows) > 0:
    rowids = np.nonzero(np.in1d(h5.get_node('/' + dataset + '/cols'), rows))[0]
  else:
    rowids = Ellipsis
  data = h5.get_node('/' + dataset + '/cols')
  return to_json(data[rowids])

@app.route('/<dataset>/group')
def get_groups(dataset):
  key = mc_prefix + dataset + '_groups'
  obj = mc.get(key)
  if not obj:
    obj = get_groups_impl(dataset)
    mc.set(key, obj)
  return Response(obj, mimetype='application/json')

def get_groups_impl(dataset):
  if '/' + dataset not in h5:
    abort(404)
  g = h5.get_node('/' + dataset)
  r = {name: dict(title=gf._v_title, ids=gf) for name, gf in g._v_children.iteritems()}
  return to_json(r)

def boxplot_impl(d):
  d = np.array(d)

  h = np.percentile(d, [25, 75])
  lower_iqr = h[0] - (h[1] - h[0]) * 1.5
  upper_iqr = h[1] + (h[1] - h[0]) * 1.5

  r = dict(min=np.nanmin(d), max=np.nanmax(d), nans=np.isnan(d).sum(), median=np.median(d), mean=np.nanmean(d),
           std=np.nanstd(d), quartile25=h[0], quartile75=h[1], iqrMin=None, iqrMax=None, numElements=d.size)
  d = d.flat
  candidates = d[np.logical_and(lower_iqr <= d, d <= h[0])]
  if len(candidates) > 0:
    r['iqrMin'] = candidates[0]
  candidates = d[np.logical_and(h[1] <= d, d <= upper_iqr)]
  if len(candidates) > 0:
    r['iqrMax'] = candidates[-1]

  return r

cache = dict()

def to_datasetid(dataset, k, cols, genes):
  global cache
  key = dataset + '_' + k
  if key in cache:
    return cache[key]
  r = np.nonzero(np.in1d(cols, genes))[0]
  cache[key] = r
  return r

@app.route('/boxplot', methods=['GET', 'POST'])
def boxplot():
  """
  boxplot data for a specific case
  :return:
  """
  strat = request.args.get('stratification', 'compoundcelleffect_siteprimary')
  datasets = request.args.getlist('datasets[]')
  if len(datasets) == 0:
    datasets = ['copynumbervariation', 'mrnaexpression']
  summary = request.args.getlist('groups[]')
  if len(summary) == 0:
    summary = None
  genes = request.args['g'].split(',') if 'g' in request.args else None

  obj = boxplot_api(genes, summary, strat, datasets)
  return Response(obj, mimetype='application/json')

def boxplot_api(genes, summary=None, strat='compoundcelleffect_siteprimary',
                datasets=['copynumbervariation', 'mrnaexpression']):
  key = mc_prefix + 'boxplot@' + to_json(dict(strat=strat, datsets=datasets, summary=summary, genes=genes)).replace(' ',
                                                                                '_')

  obj = mc.get(key)
  if obj:
    return obj

  strat = h5.get_node('/' + strat)
  groups = {name: gf for name, gf in strat._v_children.iteritems()}

  if summary is not None:  # create a summary
    s = set()
    for k, v in groups.iteritems():
      if k in summary or '_all' in summary:
        s = s.union(v)
    groups = dict()
    groups['_'.join(summary)] = np.array(list(s))

  all_genes = genes is None
  import collections
  r = collections.defaultdict(dict)
  for dataset in datasets:
    d = h5.get_node('/' + dataset + '/data')
    if all_genes:
      rowdata = ['summary']
      rowids = [Ellipsis]
    else:
      rowdata = h5.get_node('/' + dataset + '/rows')
      rowids = np.nonzero(np.in1d(rowdata, genes))[0]
      rowdata = rowdata[rowids]

    coldata = h5.get_node('/' + dataset + '/cols')
    dgroups = {k: to_datasetid(dataset, k, coldata, v) for k, v in groups.iteritems()}

    for gene, row in itertools.izip(rowdata, rowids):
      data = d[row, ...]
      container = dict()
      r[gene][dataset] = container
      for group, groupids in dgroups.iteritems():
        # print data.shape, groupids, group
        dg = data[..., groupids]
        stats = boxplot_impl(dg)
        container[group] = dict(stats=stats, data=dg)

  obj = to_json(r)
  mc.set(key, obj)
  return obj

def boxplot_api2(gene, strat='compoundcelleffect_siteprimary', datasets=['copynumbervariation', 'mrnaexpression']):
  strat = h5.get_node('/' + strat)
  groups = {name: gf for name, gf in strat._v_children.iteritems()}

  s = set()
  for k, v in groups.iteritems():
    s = s.union(v)
  groups['_all'] = np.array(list(s))

  import collections
  r = collections.defaultdict(dict)
  for dataset in datasets:
    d = h5.get_node('/' + dataset + '/data')
    rowdata = h5.get_node('/' + dataset + '/rows')
    row = np.nonzero(np.in1d(rowdata, [gene]))[0]

    if len(row) == 0:
      return dict()
    row = row[0]

    coldata = h5.get_node('/' + dataset + '/cols')
    dgroups = {k: to_datasetid(dataset, k, coldata, v) for k, v in groups.iteritems()}

    data = d[row, ...]
    container = dict()
    r[dataset] = container
    for group, groupids in dgroups.iteritems():
      # print data.shape, groupids, group
      dg = data[..., groupids]
      stats = boxplot_impl(dg)
      container[group] = dict(stats=stats, data=dg)

  return r

@app.route('/<dataset>/group/<group>')
def get_group(dataset, group):
  if '/' + dataset + '/' + group not in h5:
    abort(404)
  g = h5.get_node('/' + dataset + '/' + group)
  return jsonify(g)

def create():
  return app

if __name__ == '__main__':
  app.debug = True
  app.run(host='0.0.0.0', port=9000)


text:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:jaxws="http://cxf.apache.org/jaxws"
	xmlns:jaxrs="http://cxf.apache.org/jaxrs"
	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-2.5.xsd
					http://cxf.apache.org/jaxws http://cxf.apache.org/schemas/jaxws.xsd
					http://cxf.apache.org/jaxrs http://cxf.apache.org/schemas/jaxrs.xsd">
					<!--
	<import resource="classpath:META-INF/cxf/cxf.xml" />
	<import resource="classpath:META-INF/cxf/cxf-extension-soap.xml" />
	<import resource="classpath:META-INF/cxf/cxf-servlet.xml" />
	<context:annotation-config />
	<bean id="inMessageInterceptor" class="org.apache.cxf.interceptor.LoggingInInterceptor" />
	<bean id="outMessageInterceptor" class="org.apache.cxf.interceptor.LoggingOutInterceptor" />

	<jaxrs:server id="rest_HelloWorld" address="/">
		<jaxrs:inInterceptors>
			<ref bean="inMessageInterceptor" />
		</jaxrs:inInterceptors>
		<jaxrs:outInterceptors>
			<ref bean="outMessageInterceptor" />
		</jaxrs:outInterceptors>
		<jaxrs:serviceBeans>
			<ref bean="rest_HelloWorldImpl" />
		</jaxrs:serviceBeans>
		<jaxrs:extensionMappings>
			<entry key="json" value="application/json" />
			<entry key="xml" value="application/xml" />
		</jaxrs:extensionMappings>
	</jaxrs:server>

 -->
</beans>


text:
'''
Things that are common to testing...
'''
import doctest
import imp
import multiprocessing
import os
import types
import warnings

import music21
from music21 import common
from music21 import environment
from music21.test import testRunner

_MOD = 'commonTest.py'
environLocal = environment.Environment(_MOD)

def defaultDoctestSuite(name=None):
    globs = __import__('music21').__dict__.copy()
    docTestOptions = (doctest.ELLIPSIS|doctest.NORMALIZE_WHITESPACE)
    kwArgs = {
              'globs': globs,
              'optionflags': docTestOptions,
              'checker': testRunner.Py3In2OutputChecker()
              }
    # in case there are any tests here, get a suite to load up later
    if name is not None:
        s1 = doctest.DocTestSuite(name, **kwArgs)
    else:
        s1 = doctest.DocTestSuite(**kwArgs)
    return s1

#-------------------------------------------------------------------------------
class ModuleGather(object):
    r'''
    Utility class for gathering and importing all modules in the music21
    package. Puts them in self.modulePaths.

    >>> from music21.test import commonTest
    >>> mg = commonTest.ModuleGather(useExtended=True)
    >>> #_DOCS_SHOW print mg.modulePaths[0]
    D:\Web\eclipse\music21base\music21\xmlnode.py
    '''
    def __init__(self, useExtended=False):
        self.dirParent = common.getSourceFilePath()
        self.useExtended = useExtended
        self.modulePaths = []

        self.moduleSkip = [
            'testSingleCoreAll.py',
            'testExternal.py',
            'testDefault.py',
            'testInstallation.py',
            'testLint.py',
            'testPerformance.py',
            'timeGraphs.py',
            'exceldiff.py',
            'multiprocessTest.py',
            'figuredBass/examples.py', # 40 seconds and runs fine
            ]

        self.moduleSkipExtended = self.moduleSkip + [
            'exceldiff.py',
            'mrjobaws.py', # takes too long.
            'configure.py', # runs oddly...

            'timeGraphImportStar.py',
            'testSerialization.py',
            'mptCurses.py',
            'memoryUsage.py',
            'dedent.py',

            'testPerformance.py',
            'multiprocessTest.py',
            'timeGraphs.py',

            'alpha/trecento/quodJactatur.py',
            'alpha/trecento/find_vatican1790.py',
            'alpha/trecento/findSevs.py',
            'alpha/trecento/correlations.py',
            'alpha/trecento/contenanceAngloise.py',
            'alpha/trecento/capuaProbabilities.py',
            'alpha/theoryAnalysis/wwnortonMGTA.py',
            'test/treeYield.py',
            'test/toggleDebug.py',

            'musicxml/testPrimitive.py',
            'musicxml/testFiles.py',
            'musedata/testPrimitive/test01/__init__.py',
            'musedata/testPrimitive/__init__.py',
            'mei/test_base.py',
            'humdrum/questions.py',

            'documentation/upload.py',
            'documentation/source/conf.py',
            'documentation/extensions.py',

            'corpus/testCorpus.py',
            'composition/seeger.py',
            'composition/aug30.py',
            'audioSearch/scores/__init__.py',
            'audioSearch/scoreFollower.py',
            'audioSearch/repetitionGame.py',
            'audioSearch/omrfollow.py',
            'audioSearch/humanVScomputer.py',
            'audioSearch/graphicalInterfaceTranscriber.py',
            'audioSearch/graphicalInterfaceSF.py',
            'audioSearch/graphicalInterfaceGame.py',
            'analysis/phrasing.py',
            'abcFormat/testFiles.py',
            ]
        # run these first...
        self.slowModules = ['graph',
                            'figuredBass/realizer',
                            'features/jSymbolic',
                            'features/native',
                            'figuredBass/examples',
                            'braille/test',
                            'test/testStream',
                            'analysis/windowed',
                            'converter/__init__',
                            'metadata/bundles',

                            'musicxml/m21ToXml',
                            'musicxml/xmlToM21',

                            'musicxml/fromMxObjects',
                            'musicxml/m21ToString',

                            'romanText/translate',
                            'alpha/theoryAnalysis/theoryAnalyzer',
                            ]

        # skip any path that contains this string
        self.pathSkip = ['obsolete',
                         'ext',
                         'alpha/webapps/server',
                         'alpha/webapps/archive',
                         ]
        self.pathSkipExtended = self.pathSkip + [
                         'demos',
                        ]

        self.moduleSkip = [x.replace('/', os.sep) for x in self.moduleSkip]
        self.moduleSkipExtended = [x.replace('/', os.sep) for x in self.moduleSkipExtended]
        self.pathSkip = [x.replace('/', os.sep) for x in self.pathSkip]
        self.pathSkipExtended = [x.replace('/', os.sep) for x in self.pathSkipExtended]
        self.slowModules = [x.replace('/', os.sep) for x in self.slowModules]

        # search on init
        self._walk()

    def _visitFunc(self, args, dirname, names):
        '''
        append all module paths from _walk() to self.modulePaths.
        Utility function called from os.walk()
        '''
        for fileName in names:
            if fileName.endswith('py'):
                fp = os.path.join(dirname, fileName)
                if not os.path.isdir(fp):
                    self.modulePaths.append(fp)

    def _walk(self):
        '''
        Get all the modules in reverse order, storing them in self.modulePaths
        '''
        def manyCoreSortFunc(name):
            '''
            for many core systems, like the MacPro, running slowest modules first
            helps there be fewer idle cores later
            '''
            name = name[len(self.dirParent) + 1:]
            name = name.replace('.py', '')
            return (name in self.slowModules, name)

        # the results of this are stored in self.curFiles, self.dirList
        for dirpath, unused_dirnames, filenames in os.walk(self.dirParent):
            self._visitFunc(None, dirpath, filenames)

        if multiprocessing.cpu_count() > 4:# @UndefinedVariable
            self.modulePaths.sort(key=manyCoreSortFunc)
        else:
            self.modulePaths.sort()

        #for p in self.modulePaths:
        #    print p# self.modulePaths
        self.modulePaths.reverse()

    def _getName(self, fp):
        r'''
        Given full file path, find a name for the module with _ as the separator.

        >>> from music21.test import commonTest
        >>> mg = commonTest.ModuleGather()
        >>> #_DOCS_SHOW mg._getName(r'D:\Web\eclipse\music21base\music21\chord.py')
        'chord'
        '''
        fn = fp.replace(self.dirParent, '') # remove parent
        if fn.startswith(os.sep):
            fn = fn[1:]
        fn = fn.replace(os.sep, '_') # replace w/ _
        fn = fn.replace('.py', '')
        return fn

    def _getNamePeriod(self, fp):
        r'''
        Given full file path, find a name for the module with . as the separator.

        >>> from music21.test import commonTest
        >>> mg = commonTest.ModuleGather()
        >>> #_DOCS_SHOW mg._getName(r'D:\Web\eclipse\music21base\music21\trecento\findSevs.py')
        'trecento.findSevs'
        '''
        fn = fp.replace(self.dirParent, '') # remove parent
        parts = [x for x in fn.split(os.sep) if x]
        if parts[-1] == '__init__.py':
            parts.pop()
        fn = '.'.join(parts) # replace w/ period
        fn = fn.replace('.py', '')

        return fn

    def load(self, restoreEnvironmentDefaults=False):
        '''
        Return a list of module objects that are not in the skip list.

        N.B. the list is a list of actual module objects not names,
        therefore cannot be pickled.
        '''
        modules = []
        for fp in self.modulePaths:
            moduleObject = self.getModule(fp, restoreEnvironmentDefaults)
            if moduleObject is not None:
                modules.append(moduleObject)
        return modules

    def getModule(self, fp, restoreEnvironmentDefaults = False):
        '''
        gets one module object from the file path
        '''
        skip = False
        ms = self.moduleSkip
        if self.useExtended:
            ms = self.moduleSkipExtended

        for fnSkip in ms:
            if fp.endswith(fnSkip):
                skip = True
                break
        if skip:
            return None

        ps = self.pathSkip
        if self.useExtended:
            ps = self.pathSkipExtended

        for dirSkip in ps:
            if dirSkip in fp:
                skip = True
                break
        if skip:
            return None
        name = self._getName(fp)
        #print(name, os.path.dirname(fp))
        #fmFile, fmPathname, fmDescription = imp.find_module(name, os.path.dirname(fp) + os.sep)
        try:
            #environLocal.printDebug(['import:', fp])
            #mod = imp.load_module(name, fmFile, fmPathname, fmDescription)
            with warnings.catch_warnings():
                warnings.simplefilter('ignore', RuntimeWarning)
                mod = imp.load_source(name, fp)
        except Exception as excp: # this takes all exceptions!
            environLocal.printDebug(['failed import:', fp, '\n',
                '\tEXCEPTION:', str(excp).strip()])
            return None
        if restoreEnvironmentDefaults:
            if hasattr(mod, 'environLocal'):
                mod.environLocal.restoreDefaults()
        return mod

    def getModuleWithoutImp(self, fp, restoreEnvironmentDefaults = False):
        '''
        gets one module object from the file path without using Imp
        '''
        skip = False
        for fnSkip in self.moduleSkip:
            if fp.endswith(fnSkip):
                skip = True
                break
        if skip:
            return "skip"
        for dirSkip in self.pathSkip:
            dirSkipSlash = os.sep + dirSkip + os.sep
            if dirSkipSlash in fp:
                skip = True
                break
        if skip:
            return "skip"
        moduleName = self._getNamePeriod(fp)
        moduleNames = moduleName.split('.')
        currentModule = music21
        for thisName in moduleNames:
            if hasattr(currentModule, thisName):
                currentModule = object.__getattribute__(currentModule, thisName)
                if not isinstance(currentModule, types.ModuleType):
                    return "notInTree"
            else:
                return "notInTree"
        mod = currentModule

        if restoreEnvironmentDefaults:
            if hasattr(mod, 'environLocal'):
                mod.environLocal.restoreDefaults()
        print('starting ' + moduleName)
        return mod

if __name__ == '__main__':
    music21.mainTest()


text:
module Chaindrive
  module Gear

    class Isolation < Hashie::Mash

    end

  end
end


text:
define({
  "visible": "Visa översiktskarta som standard",
  "minWidth": "Minsta bredd",
  "minHeight": "Minsta höjd",
  "maxWidth": "Maximal bredd",
  "maxHeight": "Maximal höjd",
  "minText": "Minimum",
  "maxText": "max",
  "attachText": "Ange i vilket hörn av kartan som widgeten ska fästas.",
  "expandText": "Börja med att expandera widgeten",
  "topLeft": "Överst till vänster",
  "topRight": "Överst till höger",
  "bottomLeft": "Nederst till vänster",
  "bottomRight": "Nederst till höger",
  "baseLayerType": "Visa",
  "BaseMap": "Kartans baskarta",
  "ArcGIS": "ArcGIS",
  "tiledMapService": "ArcGIS-tjänst för kartor i tileform",
  "dynamicMapService": "Dynamisk ArcGIS-karttjänst",
  "imageService": "ArcGIS-bildtjänst",
  "OSM": "Open Street Map",
  "bingRoad": "Bing Maps Vägar",
  "bingAerial": "Bing Maps Flygbilder",
  "bingHybrid": "Bing Maps Hybrid",
  "WebTiled": "Webbtilelager",
  "VETiled": "Tilelager för Virtual Earth",
  "tileLayerUrl": "URL för tilelager",
  "tile": "Titel",
  "credits": "Krediter",
  "subdomain": "Subdomän",
  "extent": "Utbredning",
  "initExtent": "Påbörja utbredning",
  "tileInfo": "TileInfo",
  "VEStyle": "Virtual Earth-stil",
  "Aerial": "Lagret Bing Maps Flygbilder",
  "AerialWithLabels": "Lagret Flygbilder med etiketter",
  "Roads": "Lagret Vägar",
  "errWkid": "wkid matchar inte",
  "errUrl": "Ogiltig URL",
  "errReqTimeout": "Tidsgräns har överskridits",
  "layerPlaceholder": "Ange URL"
});


text:
/**
 * @author Markus Kroetzsch, Aug 8, 2011
 */
package org.semanticweb.elk.owl.interfaces;

import java.util.List;

import org.semanticweb.elk.owl.visitors.ElkObjectUnionOfVisitor;

/**
 * Corresponds to a
 * <a href= "http://www.w3.org/TR/owl2-syntax/#Union_of_Class_Expressions" >
 * Union of Class Expressions<a> in the OWL 2 specification.
 *
 * @author Markus Kroetzsch
 */
public interface ElkObjectUnionOf extends ElkClassExpression {

	/**
	 * Get the list of class expressions that this expression refers to. The
	 * order of class expressions does not affect the semantics but it is
	 * relevant to the syntax of OWL.
	 *
	 * @return list of class expressions
	 */
	public List<? extends ElkClassExpression> getClassExpressions();

	/**
	 * Accept an {@link ElkObjectUnionOfVisitor}.
	 *
	 * @param visitor
	 *            the visitor that can work with this object type
	 * @return the output of the visitor
	 */
	public <O> O accept(ElkObjectUnionOfVisitor<O> visitor);

	/**
	 * A factory for creating instances
	 *
	 * @author Yevgeny Kazakov
	 *
	 */
	interface Factory {

		/**
		 * Create an {@link ElkObjectUnionOf}.
		 *
		 * @param first
		 *            the first {@link ElkClassExpression} of the union for
		 *            which the object should be created
		 * @param second
		 *            the second {@link ElkClassExpression} of the union for
		 *            which the object should be created
		 * @param other
		 *            other {@link ElkClassExpression}s of the union for which
		 *            the object should be created
		 * @return an {@link ElkObjectUnionOf} corresponding to the input
		 */
		public ElkObjectUnionOf getObjectUnionOf(
				ElkClassExpression first,
				ElkClassExpression second,
				ElkClassExpression... other);

		/**
		 * Create an {@link ElkObjectUnionOf}.
		 *
		 * @param members
		 *            the {@link ElkClassExpression}s for which the object
		 *            should be created
		 * @return an {@link ElkObjectUnionOf} corresponding to the input
		 */
		public ElkObjectUnionOf getObjectUnionOf(
				List<? extends ElkClassExpression> members);
	}

}


text:
<component name="ProjectDictionaryState">
  <dictionary name="Scott">
    <words>
      <w>amirite</w>
      <w>callmethod</w>
      <w>generatesession</w>
      <w>hmmss</w>
      <w>lodash</w>
      <w>serverdata</w>
    </words>
  </dictionary>
</component>


text:
    <title>React Higher Order Component From Validate Demo</title>
    <link ref="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/normalize/6.0.0/normalize.min.css">


text:
import $ from 'jquery';
import _ from 'underscore';
import moment from 'moment';

import View from '@girder/core/views/View';
import events from '@girder/core/events';
import { getCurrentUser } from '@girder/core/auth';
import FolderCollection from '@girder/core/collections/FolderCollection';
import ItemModel from '@girder/core/models/ItemModel';
import FileModel from '@girder/core/models/FileModel';
import FolderModel from '@girder/core/models/FolderModel';
import UserModel from '@girder/core/models/UserModel';
import CollectionModel from '@girder/core/models/CollectionModel';

import { restRequest } from '@girder/core/rest';

import ItemSelectorWidget from './ItemSelectorWidget';

import booleanWidget from '../templates/booleanWidget.pug';
import colorWidget from '../templates/colorWidget.pug';
import enumerationWidget from '../templates/enumerationWidget.pug';
import fileWidget from '../templates/fileWidget.pug';
import rangeWidget from '../templates/rangeWidget.pug';
import regionWidget from '../templates/regionWidget.pug';
import widget from '../templates/widget.pug';

import '../stylesheets/controlWidget.styl';
import 'bootstrap-colorpicker/dist/js/bootstrap-colorpicker';
import 'bootstrap-colorpicker/dist/css/bootstrap-colorpicker.css';
import 'bootstrap-slider/dist/bootstrap-slider';
import 'bootstrap-slider/dist/css/bootstrap-slider.css';

const ControlWidget = View.extend({
    events: {
        'change input,select': '_input',
        changeColor: '_input',
        'click .s-select-file-button': '_selectFile',
        'click .s-select-multifile-button': '_selectMultiFile',
        'click .s-select-region-button': '_selectRegion',
        'click .s-select-region-add-button': '_selectRegionAdd',
        'click .s-select-region-polygon-button': '_selectRegionPolygon',
        'click .s-select-region-polygon-add-button': '_selectRegionAddPolygon',
        'click .s-select-region-clear-button': '_clearRegion'
    },

    initialize(settings) {
        this._disableRegionSelect = settings.disableRegionSelect === true;
        this._rootPath = settings.rootPath;
        this.listenTo(this.model, 'change', this.change);
        this.listenTo(this.model, 'destroy', this.remove);
        this.listenTo(this.model, 'invalid', this.invalid);
        this.listenTo(events, 's:widgetSet:' + this.model.id, (value) => {
            this.model.set('value', value);
        });

        this._initModel(settings);
    },

    _initModel(settings) {
        const prefix = settings.setDefaultOutput;
        const model = this.model;
        const type = model.get('type');
        const channel = model.get('channel');
        const required = model.get('required');
        if (channel === 'input') {
            if (model.get('defaultNameMatch') || model.get('defaultPathMatch')) {
                this._getDefaultInputResource(model).then((resource) => {
                    if (!resource) {
                        return null;
                    }
                    this.model.set({
                        path: resource._path,
                        value: resource
                    });
                    return null;
                });
            }
        }
        if (!prefix || (!required && (!this._findReference() || !model.get('extensions'))) || channel !== 'output' || !['new-file', 'file', 'item', 'directory', 'multi'].includes(type)) {
            return;
        }
        this._getDefaultOutputFolder().then((folder) => {
            if (!folder) {
                return null;
            }
            const extension = (model.get('extensions') || '').split('|')[0];
            const modelName = model.get('id') === 'returnparameterfile' ? '' : `-${model.get('title')}`;
            const reference = this._findReference();
            if (reference) {
                this.listenTo(reference, 'change', () => {
                    const value = reference.get('value');
                    if (value && value.get('name')) {
                        let refName = value.get('name');
                        if (refName.includes('.')) {
                            refName = refName.slice(0, refName.lastIndexOf('.'));
                        }
                        const name = `${refName}-${prefix}${modelName}-${moment().local().format()}${extension}`;
                        this._setValue(folder, name);
                    }
                });
            } else {
                const name = `${prefix}${modelName}-${moment().local().format()}${extension}`;
                this._setValue(folder, name);
            }
            return null;
        });
    },

    _setValue(folder, name) {
        this.model.set({
            path: [folder.get('name'), name],
            parent: folder,
            value: new ItemModel({
                name,
                folderId: folder.id
            })
        });
    },

    _findReference() {
        const ref = this.model.get('reference');
        if (!ref) {
            return null;
        }
        // ref is an id of another model
        return this.model.collection.find((d) => d.get('id') === ref);
    },

    render(_, options) {
        this.$('[data-toggle="tooltip"]').tooltip('destroy');
        this.$('.form-group').removeClass('has-error');
        this.model.isValid();
        if (options && options.norender) {
            return this;
        }
        const params = Object.assign({
            disableRegionSelect: this._disableRegionSelect
        }, this.model.toJSON());
        this.$el.html(this.template()(params));
        this.$('.s-control-item[data-type="range"] input').slider();
        this.$('.s-control-item[data-type="color"] .input-group').colorpicker({});
        this.$('[data-toggle="tooltip"]').tooltip({container: 'body'});
        if (params.datalist) {
            this.$('.s-control-item input').addClass('has-datalist');
        }
        return this;
    },

    change() {
        events.trigger(`s:widgetChanged:${this.model.get('type')}`, this.model);
        events.trigger('s:widgetChanged', this.model);
        this.render.apply(this, arguments);
    },

    remove() {
        events.trigger(`s:widgetRemoved:${this.model.get('type')}`, this.model);
        events.trigger('s:widgetRemoved', this.model);
        this.$('.s-control-item[data-type="color"] .input-group').colorpicker('destroy');
        this.$('.s-control-item[data-type="range"] input').slider('destroy');
        this.$el.empty();
    },

    /**
     * Set classes on the input element to indicate to the user that the current value
     * is invalid.  This is automatically triggered by the model's "invalid" event.
     */
    invalid() {
        events.trigger(`s:widgetInvalid:${this.model.get('type')}`, this.model);
        events.trigger('s:widgetInvalid', this.model);
        this.$('.form-group').addClass('has-error');
    },

    /**
     * Type definitions mapping used internally.  Each widget type
     * specifies it's pug template and possibly more customizations
     * as needed.
     */
    _typedef: {
        range: {
            template: rangeWidget
        },
        color: {
            template: colorWidget
        },
        string: {
            template: widget
        },
        number: {
            template: widget
        },
        integer: {
            template: widget
        },
        boolean: {
            template: booleanWidget
        },
        'string-vector': {
            template: widget
        },
        'number-vector': {
            template: widget
        },
        'string-enumeration': {
            template: enumerationWidget
        },
        'number-enumeration': {
            template: enumerationWidget
        },
        file: {
            template: fileWidget
        },
        item: {
            template: fileWidget
        },
        image: {
            template: fileWidget
        },
        multi: {
            template: fileWidget
        },
        directory: {
            template: fileWidget
        },
        'new-file': {
            template: fileWidget
        },
        region: {
            template: regionWidget
        }
    },

    /**
     * Get the appropriate template for the model type.
     */
    template() {
        const type = this.model.get('type');
        let def = this._typedef[type];

        if (def === undefined) {
            console.warn('Invalid widget type "' + type + '"'); // eslint-disable-line no-console
            def = {};
        }
        return def.template || _.template('');
    },

    /**
     * Get the current value from an input (or select) element.
     */
    _input(evt) {
        const $el = $(evt.target);
        let val = $el.val();

        if ($el.attr('type') === 'checkbox') {
            val = $el.get(0).checked;
        }

        // we don't want to rerender, because this event is generated by the input element
        this.model.set('value', val, {norender: true});
    },

    /**
     * Get the value from a file selection modal and set the text in the widget's
     * input element.
     */
    _selectFile() {
        // If we converted to multi, convert it back to the older type
        // We reset the name if it was multi before
        if (this.model.get('type') === 'multi') {
            if (this.model.get('value')) {
                this.model.set({
                    value: new ItemModel({
                        folderId: this.model.get('value').get('folderId')
                    })
                });
            }
        }
        const t = this.model.get('defaultType');

        if (t) {
            this.model.set({
                type: t
            });
        }

        const itemSelectorSettings = {
            el: $('#g-dialog-container'),
            parentView: this,
            model: this.model,
            rootPath: this._rootPath,
            rootSelectorSettings: {
                pageLimit: 1000
            }
        };
        if (this.model.get('value')) {
            this.getRoot(this.model.get('value'), itemSelectorSettings);
        } else {
            this.completeInitialization(itemSelectorSettings);
        }
    },
    /**
     * Used to collect the root of the resource passed to the itemSelectorWidget to enable the defaultSelectedResource
     * The value isn't always a valid model so we need to fetch the model from the itemId, folderID, or if it is the item, the actual item
     * @param {*} resource value object for model containing either itemId, folderId, or a standard model
     * @param {*} settings ItemSelectorWidget settings extended from BrowserWidget
     */
    getRoot(resource, settings) {
        const modelTypes = {
            item: ItemModel,
            folder: FolderModel,
            collection: CollectionModel,
            user: UserModel
        };
        let modelType = 'folder'; // folder type by default, other types if necessary
        let modelId = null;
        // If it is an item it will have a folderId associated with it as a parent item
        if (resource.get('itemId')) {
            modelId = resource.get('itemId');
            modelType = 'item';
        } else if (resource.get('folderId')) {
            modelId = resource.get('folderId');
        } else if (resource.get('parentCollection')) {
            // Case for providing a folder as the defaultSelectedResource but want the user to select an item
            // folder parent is either 'user' | 'folder' | 'collection', most likely folder though
            modelType = resource.get('parentCollection');
            modelId = resource.get('parentId');
        }
        // We need to fetch the itemID to get the model stuff
        if (modelType === 'item') {
            const itemModel = new modelTypes[modelType]();
            itemModel.set({
                _id: modelId
            }).on('g:fetched', function () {
                settings.defaultSelectedResource = itemModel;
                settings.highlightItem = true;
                settings.selectItem = true;
                this.getRoot(itemModel, settings);
            }, this).on('g:error', function () {
                settings.root = null;
                this.completeInitialization(settings);
            }, this).fetch();
        } else if (modelTypes[modelType] && modelId) {
            const parentModel = new modelTypes[modelType]();
            parentModel.set({
                _id: modelId
            }).on('g:fetched', function () {
                settings.root = parentModel;
                settings.rootSelectorSettings.selectByResource = parentModel;
                this.completeInitialization(settings);
            }, this).on('g:error', function () {
                settings.root = null;
                this.completeInitialization(settings);
            }, this).fetch();
        } else {
            this.completeInitialization(settings);
        }
    },
    completeInitialization(settings) {
        const modal = new ItemSelectorWidget(settings);
        modal.once('g:saved', () => {
            modal.$el.modal('hide');
        }).render();
    },
    _selectMultiFile() {
        // Store the current type in case it is opened again
        const t = this.model.get('type');
        if (t !== 'multi') {
            this.model.set({
                type: 'multi',
                defaultType: t
            });
        }

        const itemSelectorSettings = {
            el: $('#g-dialog-container'),
            parentView: this,
            model: this.model,
            rootPath: this._rootPath,
            rootSelectorSettings: {
                pageLimit: 1000
            }
        };
        if (this.model.get('value')) {
            this.getRoot(this.model.get('value'), itemSelectorSettings);
        } else {
            this.completeInitialization(itemSelectorSettings);
        }
    },

    _getDefaultOutputFolder() {
        const user = getCurrentUser();
        if (!user) {
            return $.Deferred().resolve(null).promise();
        }
        const userFolders = new FolderCollection();
        // find first private one
        return userFolders.fetch({
            parentId: user.id,
            parentType: 'user',
            public: false,
            limit: 1
        }).then(() => {
            if (!userFolders.isEmpty()) {
                return userFolders;
            }
            // find first one including public
            return userFolders.fetch({
                parentId: user.id,
                parentType: 'user',
                limit: 1
            });
        }).then(() => {
            return userFolders.isEmpty() ? null : userFolders.at(0);
        });
    },

    _getDefaultInputResource(model) {
        var type = {image: 'item', item: 'item', file: 'file', directory: 'folder'}[model.get('type')];
        return restRequest({
            url: 'slicer_cli_web/path_match',
            data: {
                type: type,
                name: model.get('defaultNameMatch'),
                path: model.get('defaultPathMatch'),
                relative_path: model.get('defaultRelativePath'),
                base_id: model.get('defaultRelativePath_id'),
                base_type: model.get('defaultRelativePath_type')
            },
            error: null
        }).then((resource) => {
            var ModelType = {image: ItemModel, item: ItemModel, file: FileModel, directory: FolderModel}[model.get('type')];
            const result = new ModelType(resource);
            result._path = resource._path;
            return result;
        });
    },

    /**
     * Trigger a global event to initiate rectangle drawing mode to whoever
     * might be listening.
     */
    _selectRegion() {
        this.$('.tooltip[role="tooltip"]').remove();
        events.trigger('s:widgetDrawRegion', this.model);
    },

    _selectRegionAdd() {
        this.$('.tooltip[role="tooltip"]').remove();
        events.trigger('s:widgetDrawAddRegion', this.model);
    },

    _selectRegionAddPolygon() {
        this.$('.tooltip[role="tooltip"]').remove();
        events.trigger('s:widgetDrawAddPolygonRegion', this.model);
    },

    _selectRegionPolygon() {
        this.$('.tooltip[role="tooltip"]').remove();
        events.trigger('s:widgetDrawPolygonRegion', this.model);
    },

    _clearRegion() {
        this.$('.tooltip[role="tooltip"]').remove();
        events.trigger('s:widgetClearRegion', this.model);
    }

});

export default ControlWidget;


text:
1. Add the HOTFIX_ENABLE macro to enable this feature (to File->Build Setting->Scripting Define Symbols on Unity3D). This macro should be set separately on the editor and each mobile platform! For automatic packaging, it should be noted that the macro set in the code in the API are not valid and it needs to be set in the editor.

(It is recommended that you use HOTFIX_ENABLE only for mobile phone build versions or for developing a patch in the editor, but not for usual development codes)

2. Execute the XLua/Generate Code menu.

3. This step will be automatically carried out in injection and construction of mobile phone packages. You need to manually execute the "XLua/Hotfix Inject In Editor" menu when developing a hotfix in the editor. After successful injection, "hotfix inject finish!" or "had injected!" will be printed.

## Constraints

Static constructors are not supported.

At present, only the code hotfix for Assets is supported, but not the code hotfix for engine or for the C# system library.

## API

xlua.hotfix(class, [method_name], fix)

* Description: Inject Lua patch
* class: C# class, two representation methods, CS.Namespace.Typename or string method "Namespace.Typename"; The string format is consistent with the Type.GetType of C#; If the nested type is non-Public type, you can only use the string method to represent "Namespace.TypeName+NestedTypeName".
* method_name: method name, optional;
* fix: If you transfer method_name, fix will be a function; otherwise it will provide a set of functions through the table. The table organization is based on the principle that key is method_name and value is the function.

base(csobj)

* Description: The child type override function is implemented by calling the parent type via base.
* csobj: object
* Returned value: new object, which can be used to call the method via base

Example (in HotfixTest2.cs):

```lua
xlua.hotfix(CS.BaseTest, 'Foo', function(self, p)
    print('BaseTest', p)
    base(self):Foo(p)
end)
```

util.hotfix_ex(class, method_name, fix)

* Description: This is the enhanced version of xlua.hotfix, which can perform the original function in the fix function. Its disadvantage is that the implementation of fix will be slightly slower.
* method_name: method name;
* fix: This is the Lua function used to replace the C# method.

## Tag the type of hotfix

Like other configurations, there are two methods:

1. Add Hotfix flag directly in the type;

2. Configure a list in the static field or property of a static type. Properties can be used to implement more complex configurations, such as whitelisting based on Namespace.

~~~csharp
public static class HotfixCfg
{
    [Hotfix]
    public static List<Type> by_field = new List<Type>()
    {
        typeof(HotFixSubClass),
        typeof(GenericClass<>),
    };

    [Hotfix]
    public static List<Type> by_property
    {
        get
        {
            return (from type in Assembly.Load("Assembly-CSharp").GetTypes()
                    where type.Namespace == "XXXX"
                    select type).ToList();
        }
    }
}
~~~

## Hotfix Flag

The Hotfix flag can set some flags to customize the generated code and instrumentation.

* Stateless and Stateful

This is is a legacy setting. The Stateful method has been removed in the new version because similar effects can be achieved with the xlua.util.state interface. For how to use this interface, see the sample code in HotfixTest2.cs.

Without Stateful, the default is Stateless, so there is no need to set this flag.

* ValueTypeBoxing

Value type adaptation. The delegate will converge to the object. Its advantage lies in having less code. Its disadvantage is that boxing and gc are generated. It is suitable for text segment sensitive services.

* IgnoreProperty

No property injection and generation of adaptation code. In general, most properties have simple implementation and lower error probability. No injection is recommended.

* IgnoreNotPublic

No injection or generation of adaptation code for non-public methods. Only private methods (such as MonoBehaviour) which are called by reflection will be injected. Other non-public methods that are only called by this type may not be injected. but the workload for repair will be slightly heavier. All public methods that reference this function must be rewritten.

* Inline

No generation of the adaptation delegate. The process code is directly injected into the function body.

* IntKey

Instead of generating static fields, all injection points are managed centrally in an array.

Advantages: Little effect on the text segment.

Disadvantages: This is not as convenient as the default method, and needs to use the id to indicate which function the hotfix is used for. This id is assigned when the code is injected into the tool. The function-id mapping will be saved in Gen/Resources/hotfix_id_map.lua.txt. Automatic timestamping is backed up to the same level directory as hotfix_id_map.lua.txt. After releasing the mobile version, properly save the file.

The format of this file is like this (Note: This file is only used in IntKey mode. If you do not specify IntKey mode injection, only an empty table is returned in the file):

~~~lua
return {
    ["HotfixTest"] = {
        [".ctor"] = {
            5
        },
        ["Start"] = {
            6
        },
        ["Update"] = {
            7
        },
        ["FixedUpdate"] = {
            8
        },
        ["Add"] = {
            9,10
        },
        ["OnGUI"] = {
            11
        },
    },
}
~~~

To replace the Update function of HotfixTest, you have to

~~~lua
CS.XLua.HotfixDelegateBridge.Set(7, func)
~~~

If it is an overloaded function, a function name will correspond to multiple ids, such as the Add function above.

Can it be automated? Yes. xlua.util provides the auto_id_map function. When it is executed once, you can use the type and method name to indicate the repaired function.

~~~lua
(require 'xlua.util').auto_id_map()
xlua.hotfix(CS.HotfixTest, 'Update', function(self)
        self.tick = self.tick + 1
        if (self.tick % 50) == 0 then
            print('<<<<<<<<Update in lua, tick = ' .. self.tick)
        end
    end)
~~~

The premise is that hotfix_id_map.lua.txt is in a directory that can be referenced by require 'hotfix_id_map'.

## Usage suggestions

* Add the Hotfix flag to all types that are most likely to be modified.
* It is recommended that you use reflection to find all delegate types involved in the function parameters, fields, properties and events, and then add CSharpCallLua.
* Add LuaCallCSharp to business code, engine APIs, system APIs, and the types to which the Lua hotfix requires high-performance access.
* Engine APIs and system APIs may be stripped by code (those not referenced by C# will be stripped). If you think you may add API calls other than C# codes, these APIs are added to either LuaCallCSharp or ReflectionUse.

## Patching

Xlua uses Lua functions to replace C#'s constructors, functions, properties and events. Lua implementations are based on functions. For example, the property corresponds to a getter function and a setter function, and the event corresponds to an add function and a remove function.

* Functions

method_name transfers the function name and supports overload. Different overloads are forwarded to the same Lua function.

For example:

```csharp
// 要fix的C#类
[Hotfix]
public class HotfixCalc
{
    public int Add(int a, int b)
    {
        return a - b;
    }

    public Vector3 Add(Vector3 a, Vector3 b)
    {
        return a - b;
    }
}
```

```lua
xlua.hotfix(CS.HotfixCalc, 'Add', function(self, a, b)
    return a + b
end)
```

The difference between a static function and a member function is that a member function will have a self parameter added. This self is the C# object itself in Stateless mode (corresponding to C#'s this).

Ordinary parameters correspond to Lua parameters. The ref parameter corresponds to a Lua parameter and a returned value, and the out parameter corresponds to a returned value on Lua.

Generic functions have the same hotfix rules as ordinary functions.

* Constructors

The method_name corresponding to the constructor is ".ctor".

Unlike the ordinary function, the hotfix of the constructor is not a replacement, but calls Lua after executing the original logic.

* Properties

The property named "AProp" will correspond to a getter, its method_name equals to get_AProp, and the setter's method_name is equal to set_AProp.

* []Operators

The setter corresponds to set_Item, and the getter corresponds to get_Item. The first parameter is self, which is followed by key and value for the setter. The getter has only the key parameter, and the returned value is the value that it has gotten.

* Other operators

The operators of C# have a set of internal representations. For example, the + operator function name is op_Addition (for the internal representation of other operators, see the relevant document). Overriding this function will override the + operator of C#.

* Events

For example, for the event "AEvent", the += operator is add_AEvent, and the -= operator is remove_AEvent. The first parameter of the two functions is self, and the second parameter is the delegate immediately after the operator.

Then, directly access the private delegate corresponding to the event via xlua.private_accessible. (For versions newer than 2.1.11, calling xlua.private_accessible is not required.) The event can be triggered directly through the object's "&event name" field, such as self\['&MyEvent'\](), where MyEvent is the event name.

* Destructors

The method_name is "Finalize" and transfers a self parameter.

Unlike the ordinary function, the hotfix of the destructor is not a replacement, but continues the original logic after calling the Lua function.

* Generic types

Other rules are the same. It should be noted that each instantiated generic type is an independent type. You can only patch each instantiated type. For example:

```csharp
public class GenericClass<T>
{
}
```

You can only patch GenericClass\<double\> and GenericClass\<int\>, instead of GenericClass.

The following is an example of patching GenericClass<double>:

```csharp
luaenv.DoString(@"
    xlua.hotfix(CS.GenericClass(CS.System.Double), {
        ['.ctor'] = function(obj, a)
            print('GenericClass<double>', obj, a)
        end;
        Func1 = function(obj)
            print('GenericClass<double>.Func1', obj)
        end;
        Func2 = function(obj)
            print('GenericClass<double>.Func2', obj)
            return 1314
        end
    })
");
```

* Unity coroutine

Using util.cs_generator, you can simulate an IEnumerator with a function. The coroutine.yield here is similar to the yield return in C#. For example, the following C# code is equivalent to the corresponding hotfix code.

~~~csharp
[XLua.Hotfix]
public class HotFixSubClass : MonoBehaviour {
    IEnumerator Start()
    {
        while (true)
        {
            yield return new WaitForSeconds(3);
            Debug.Log("Wait for 3 seconds");
        }
    }
}
~~~

~~~csharp
luaenv.DoString(@"
    local util = require 'xlua.util'
    xlua.hotfix(CS.HotFixSubClass,{
        Start = function(self)
            return util.cs_generator(function()
                while true do
                    coroutine.yield(CS.UnityEngine.WaitForSeconds(3))
                    print('Wait for 3 seconds')
                end
            end)
        end;
    })
");
~~~

* Entire type

If you want to replace the entire type, you don't need to call xlua.hotfix again and again, you can do it all at once. Just give a table and press method_name = function.

```lua
xlua.hotfix(CS.StatefullTest, {
    ['.ctor'] = function(csobj)
        return util.state(csobj, {evt = {}, start = 0, prop = 0})
    end;
    set_AProp = function(self, v)
        print('set_AProp', v)
        self.prop = v
    end;
    get_AProp = function(self)
        return self.prop
    end;
    get_Item = function(self, k)
        print('get_Item', k)
        return 1024
    end;
    set_Item = function(self, k, v)
        print('set_Item', k, v)
    end;
    add_AEvent = function(self, cb)
        print('add_AEvent', cb)
        table.insert(self.evt, cb)
    end;
    remove_AEvent = function(self, cb)
       print('remove_AEvent', cb)
       for i, v in ipairs(self.evt) do
           if v == cb then
               table.remove(self.evt, i)
               break
           end
       end
    end;
    Start = function(self)
        print('Start')
        for _, cb in ipairs(self.evt) do
            cb(self.start, 2)
        end
        self.start = self.start + 1
    end;
    StaticFunc = function(a, b, c)
       print(a, b, c)
    end;
    GenericTest = function(self, a)
       print(self, a)
    end;
    Finalize = function(self)
       print('Finalize', self)
    end
})
```