text:
/* ----------------------------------------------------------------------------
 * This file was automatically generated by SWIG (http://www.swig.org).
 * Version 4.0.2
 *
 * Do not make changes to this file unless you know what you are doing--modify
 * the SWIG interface file instead.
 * ----------------------------------------------------------------------------- */

package org.opensim.modeling;

/**
 * The abstract Component class defines the interface used to add computational

 * elements to the underlying SimTK::System (MultibodySystem). It specifies

 * the interface that components must satisfy in order to be part of the system

 * and provides a series of helper methods for adding variables

 * (state, discrete, cache, ...) to the underlying system. As such, Component

 * handles all of the bookkeeping of system indices and provides convenience

 * access to variable values (incl. derivatives) via their names as strings.

 *

 * # Component's Interfaces

 * ## System and State

 *

 * The MultibodySystem and its State are defined by Simbody (ref ...). Briefly,

 * a System represents the mathematical equations that specify the behavior

 * of a computational model. The State is a collection of all the variables

 * that uniquely define the unknowns in the system equations. Consider a single

 * differential equation as a system, while a single set of variable values that

 * satisfy the equation is a state of that system. These could be values for

 * joint coordinates, their speeds, as well other variables that govern

 * the system dynamics (e.g. muscle activation and fiber-length variables

 * that dictate muscle force). These variables are called continuous state

 * variables in Simbody, but are more simply referred to as StateVariables

 * in OpenSim. Component provides services to define and access its

 * StateVariables and specify their dynamics (derivatives with respect to time)

 * that are automatically and simultaneously integrated with the MultibodySystem

 * dynamics. Common operations to integrate, take the max or min, or to delay a

 * signal, etc. require internal variables to perform their calculations and

 * these are also held in the State. Simbody provides the infrastructure to

 * ensure that calculations are kept up-to-date with the state variable values.

 *

 * There are other types of "State" variables such as a flag (or options) that

 * enables a component to be disabled or for a muscle force to be overridden and

 * and these are identified as ModelingOptions since they may change

 * the modeled dynamics of the component. Component provides services

 * that enable developers of components to define additional ModelingOptions.

 *

 * ## Discrete variables

 *

 * Often a component requires input from an outside source (precomputed data

 * from a file, another program, or interaction from a user) in which case these

 * variables do not have dynamics (differential eqns.) known to the component,

 * but are necessary to describe the dynamical "state" of the system. An example,

 * is a throttle component (a "controller" that provides an actuator, e.g. a

 * motor, with a control signal like a voltage or current) which it gets as direct

 * input from the user (via a joystick, key press, etc..). The throttle controls

 * the motor torque output and therefore the behavior of the model. The input by

 * the user to the throttle the motor (the controls) is necessary to specify the

 * model dynamics at any instant and therefore are considered part of the State.

 * In OpenSim they are simply referred to as DiscreteVariables. The Component

 * provides services to enable developers of components to define and access its

 * DiscreteVariables.

 *

 * ## Cache variables

 *

 * Fast and efficient simulations also require computationally expensive

 * calculations to be performed only when necessary. Often the result of an

 * expensive calculation can be reused many times over, while the variables it

 * is dependent on remain fixed. The concept of holding onto these values is

 * called caching and the variables that hold these values are call

 * CacheVariables. It is important to note, that cache variables are

 * not state variables. Cache variables can always be recomputed exactly

 * from the State. OpenSim uses the Simbody infrastructure to manage cache

 * variables and their validity. Component provides a simplified interface to

 * define and access CacheVariables.

 *

 * ## Stages

 *

 * Many modeling and simulation codes put the onus on users and component

 * creators to manage the validity of cache variables, which is likely to lead

 * to undetectable errors where cache values are stale (calculated based on past

 * state variable values). Simbody, on the other hand, provides a more strict

 * infrastructure to make it easy to exploit the efficiencies of caching while

 * reducing the risks of validity errors. To do this, Simbody employs the concept

 * of computational stages to "realize" (or compute) a model's system to a

 * particular stage requires cached quantities up to and including the stage to

 * to computed/specified. Simbody utilizes nine realization stages

 * (<tt>SimTK::Stage::</tt>)

 *

 * -# Topology       finalize System with "slots" for most variables (above)

 * -# %Model         specify modeling choices

 * -# Instance       specify modifiable model parameters

 * -# Time           compute time dependent quantities

 * -# Position       compute position dependent quantities

 * -# Velocity       compute velocity dependent quantities

 * -# Dynamics       compute system applied forces and dependent quantities

 * -# Acceleration   compute system accelerations and all other derivatives

 * -# Report         compute quantities for reporting/output

 *

 * The Component interface is automatically invoked by the System and its

 * realizations. Component users and most developers need not concern themselves

 * with Topology, %Model or Instance stages. That interaction is managed

 * by Component when component creators implement extendAddToSystem() and use the

 * services provided by Component. Component creators do need to determine and

 * specify stage dependencies for Discrete and CacheVariables that they add to

 * their components. For example, the throttle controller reads its value from

 * user input and it is valid for all calculations as long as time does not

 * change. If the simulation (via numerical integration) steps forward (or

 * backward for a trial step) and updates the state, the control from a previous

 * state (time) should be invalid and an error generated for trying to access

 * the DiscreteVariable for the control value. To do this one specifies the

 * "invalidates" stage (e.g. <tt>SimTK::Stage::Time</tt>) for a DiscreteVariable

 * when the variable is added to the Component. A subsequent change to that

 * variable will invalidate all state cache entries at that stage or higher. For

 * example, if a DiscreteVariable is declared to invalidate <tt>Stage::Position</tt>

 * then changing it will invalidate cache entries that depend on positions,

 * velocities, forces, and accelerations.

 *

 * Similar principles apply to CacheVariables, which requires a "dependsOn" stage to

 * be specified when a CacheVariable is added to the component. In this case,

 * the cache variable "shadows" the State (unlike a DiscreteVariable, which is a

 * part of the State) holding already-computed state-dependent values so that

 * they do not need to be recomputed until the state changes.

 * Accessing the CacheVariable in a State whose current stage is lower than

 * that CacheVariable's specified dependsOn stage will trigger an exception.

 * It is up to the component to update the value of the cache variable.

 * Component provides methods to check if the cache is valid, update its value

 * and then to mark it as valid.

 *

 * ## The interface of this class

 *

 * The primary responsibility of a Component is to add its computational

 * representation(s) to the underlying SimTK::System by implementing

 * extendAddToSystem().

 *

 * Additional methods provide support for adding modeling options, state and

 * cache variables.

 *

 * Public methods enable access to component variables via their names.

 *

 * ## Subcomponents

 *

 * A %Component can have any number of %Components within it; we call these

 * subcomponents. Subcomponents can also contain their own subcomponents as

 * well. There are three categories of subcomponents, which vary in whether

 * they are *configurable* and *fixed in number*:

 *

 * - **property subcomponents** Any Property in a Component that is of type

 *   Component is a subcomponent. This includes list properties and Set%s. This

 *   is the most common category of subcomponent, and its distinguishing

 *   feature is that these subcomponents are *configurable* by the user of this

 *   component. These subcomponents appear in the XML for this component, and

 *   can be modified in XML or through the API. They are also not fixed in

 *   number; users can add more property subcomponents to an existing

 *   component (though it is possible to enforce a fixed number by using

 *   one-value properties or limiting the size of a list property). The bodies,

 *   joints, forces, etc. in a Model's BodySet, JointSet, ForceSet, etc. are

 *   all examples of property subcomponents. This category of subcomponent is

 *   the most similar to what was available pre-v4.0.

 * - **member subcomponents** These are *not* configurable by the user of this

 *   Component, and can only be modified by this Component. You can

 *   still access member subcomponents through the API, but only the component

 *   containing the subcomponents can modify them. Any Component class can have

 *   any number of member subcomponents, but this number is *fixed* for every

 *   instance of the component.

 * - **adopted subcomponents** These are *not* configurable (does not appear in

 *   XML) and *not* fixed in number. For example, a component can decide,

 *   based on other aspects of the model, that it needs to create a new

 *   subcomponent. This can be done using adopted subcomponents.

 *

 * Also, any specific Component can end up in any of these three categories.

 * That is, if you have a MySpecialForce Component, any other Component can

 * have it as a property subcomponent, a member subcomponent, or as an adopted

 * subcomponent.

 *

 * @author Ajay Seth, Michael Sherman, Chris Dembia
 */
public class Component extends OpenSimObject {
  private transient long swigCPtr;

  public Component(long cPtr, boolean cMemoryOwn) {
    super(opensimCommonJNI.Component_SWIGUpcast(cPtr), cMemoryOwn);
    swigCPtr = cPtr;
  }

  public static long getCPtr(Component obj) {
    return (obj == null) ? 0 : obj.swigCPtr;
  }

  @SuppressWarnings("deprecation")
  protected void finalize() {
    delete();
  }

  public synchronized void delete() {
    if (swigCPtr != 0) {
      if (swigCMemOwn) {
        swigCMemOwn = false;
        opensimCommonJNI.delete_Component(swigCPtr);
      }
      swigCPtr = 0;
    }
    super.delete();
  }

  public void addComponent(Component comp) {
      comp.markAdopted();
      private_addComponent(comp);
  }

  public static Component safeDownCast(OpenSimObject obj) {
    long cPtr = opensimCommonJNI.Component_safeDownCast(OpenSimObject.getCPtr(obj), obj);
    return (cPtr == 0) ? null : new Component(cPtr, false);
  }

  public void assign(OpenSimObject aObject) {
    opensimCommonJNI.Component_assign(swigCPtr, this, OpenSimObject.getCPtr(aObject), aObject);
  }

  public static String getClassName() {
    return opensimCommonJNI.Component_getClassName();
  }

  public OpenSimObject clone() {
    long cPtr = opensimCommonJNI.Component_clone(swigCPtr, this);
    return (cPtr == 0) ? null : new Component(cPtr, true);
  }

  public String getConcreteClassName() {
    return opensimCommonJNI.Component_getConcreteClassName(swigCPtr, this);
  }

  /**
   * Define a Component's internal data members and structure according to

   *         its properties. This includes its subcomponents as part of the component

   *         ownership tree and identifies its owner (if present) in the tree.

   *         finalizeFromProperties propagates to all of the component's subcomponents

   *         prior to invoking the virtual extendFinalizeFromProperties() on itself.

   *         Note that if the Component has already been added to a System (result of

   *         addToSystem(); e.g., Model::initSystem()) when finalizeFromProperties()

   *         is called, then finalizeFromProperties() disassociates the component from

   *         that System.
   */
  public void finalizeFromProperties() {
    opensimCommonJNI.Component_finalizeFromProperties(swigCPtr, this);
  }

  /**
   *  Satisfy the Component's connections specified by its Sockets and Inputs.

   *         Locate Components and their Outputs to satisfy the connections in an

   *         aggregate Component (e.g. Model), which is the root of a tree of

   *         Components.
   */
  public void finalizeConnections(Component root) {
    opensimCommonJNI.Component_finalizeConnections(swigCPtr, this, Component.getCPtr(root), root);
  }

  /**
   *  Disconnect/clear this Component from its aggregate component. Empties

   *         all component's sockets and sets them as disconnected.
   */
  public void clearConnections() {
    opensimCommonJNI.Component_clearConnections(swigCPtr, this);
  }

  /**
   *  Have the Component add itself to the underlying computational System
   */
  public void addToSystem(SWIGTYPE_p_SimTK__MultibodySystem system) {
    opensimCommonJNI.Component_addToSystem(swigCPtr, this, SWIGTYPE_p_SimTK__MultibodySystem.getCPtr(system));
  }

  /**
   *  Initialize Component's state variable values from its properties
   */
  public void initStateFromProperties(State state) {
    opensimCommonJNI.Component_initStateFromProperties(swigCPtr, this, State.getCPtr(state), state);
  }

  /**
   *  %Set Component's properties given a state.
   */
  public void setPropertiesFromState(State state) {
    opensimCommonJNI.Component_setPropertiesFromState(swigCPtr, this, State.getCPtr(state), state);
  }

  /**
   * Optional method for generating arbitrary display geometry that reflects

   *     this %Component at the specified state. This will be called once to

   *     obtain ground- and body-fixed geometry (with fixed=true), and then

   *     once per frame (with fixed=false) to generate on-the-fly geometry such

   *     as rubber band lines, force arrows, labels, or debugging aids.

   *

   *     Please note that there is a precondition that the state passed in to

   *     generateDecorations be realized to Stage::Position. If your component can

   *     visualize quantities realized at Velocity, Dynamics or Acceleration stages,

   *     then you must check that the stage has been realized before using/requesting

   *     stage dependent values. It is forbidden to realize the model to a higher

   *     stage within generateDecorations, because this can trigger costly side-

   *     effects such as evaluating all model forces even when performing a purely

   *     kinematic study.

   *

   *     If you override this method, be sure to invoke the base class method first,

   *     using code like this:

   *     {@code
      void MyComponent::generateDecorations
         (bool                                        fixed,
          const ModelDisplayHints&                    hints,
          const SimTK::State&                         state,
          SimTK::Array_<SimTK::DecorativeGeometry>&   appendToThis) const
      {
  invoke parent class method
          Super::generateDecorations(fixed,hints,state,appendToThis);
  ... your code goes here
  can render velocity dependent quanities if stage is Velocity or higher
          if(state.getSystemStage() >= Stage::Velocity) {
  draw velocity vector for model COM
          }
  can render computed forces if stage is Dynamics or higher
          if(state.getSystemStage() >= Stage::Dynamics) {
  change the length of a force arrow based on the force in N
          }
      }
      }

   *

   *     @param fixed

   *         If true, generate only geometry that is fixed to a PhysicalFrame,

   *         configuration, and velocity. Otherwise generate only such dependent

   *         geometry.

   *     @param hints

   *         See documentation for ModelDisplayHints; you may want to alter the

   *         geometry you generate depending on what you find there. For example,

   *         you can determine whether the user wants to see debug geometry.

   *     @param state

   *         The State for which geometry should be produced. See below for more

   *         information.

   *     @param appendToThis

   *         %Array to which generated geometry should be appended via the

   *         push_back() method.

   *

   *     When called with fixed=true only modeling options and parameters

   *     (Instance variables) should affect geometry; time, position, and velocity

   *     should not. In that case OpenSim will already have realized the state

   *     through Instance stage. When called with fixed=false, you may

   *     consult any relevant value in state. However, to avoid unnecessary

   *     computation, OpenSim guarantees only that state will have been realized

   *     through Position stage; if you need anything higher than that (reaction

   *     forces, for example) you should make sure the state is realized through

   *     Acceleration stage. *
   */
  public void generateDecorations(boolean fixed, ModelDisplayHints hints, State state, ArrayDecorativeGeometry appendToThis) {
    opensimCommonJNI.Component_generateDecorations(swigCPtr, this, fixed, ModelDisplayHints.getCPtr(hints), hints, State.getCPtr(state), state, ArrayDecorativeGeometry.getCPtr(appendToThis), appendToThis);
  }

  /**
   * Get the underlying MultibodySystem that this component is connected to.

   * Make sure you have called Model::initSystem() prior to accessing the System.

   * Throws an Exception if the System has not been created or the Component

   * has not added itself to the System.

   * @see hasSystem().
   */
  public SWIGTYPE_p_SimTK__MultibodySystem getSystem() {
    return new SWIGTYPE_p_SimTK__MultibodySystem(opensimCommonJNI.Component_getSystem(swigCPtr, this), false);
  }

  /**
   * Check if this component has an underlying MultibodySystem.

   * Returns false if the System has not been created OR if this

   * Component has not added itself to the System.
   */
  public boolean hasSystem() {
    return opensimCommonJNI.Component_hasSystem(swigCPtr, this);
  }

  /**
   *  Does the provided component already exist anywhere in the ownership

   * tree (not just subcomponents of this component)?
   */
  public boolean isComponentInOwnershipTree(Component component) {
    return opensimCommonJNI.Component_isComponentInOwnershipTree(swigCPtr, this, Component.getCPtr(component), component);
  }

  /**
   * Add a Component (as a subcomponent) of this component.

   * This component takes ownership of the subcomponent and it will be

   * serialized (appear in XML) as part of this component. Specifically,

   * it will appear in the `<components>` list for this Component.

   * If the subcomponent is already owned by this component or exists

   * in the same hierarchy (tree) as this component, an Exception

   * is thrown.

   * Note: addComponent is intended to replace existing addBody(), addJoint,

   *       ... on Model or the requirement for specific add###() methods to

   *       subcomponents to a Component.

   *

   * Typical usage is:

   *     {@code
  Start with an empty Model (which is a Component)
          Model myModel;
  Create any Component type on the heap
          Body* newBody = new Body();
  Customize the Component by setting its properties
          newBody->setName("newBody");
          newBody->setMass(10.0);
          newBody->setMassCenter(SimTK::Vec3(0));
  ...
  Now add it to your model, which will take ownership of it
          myModel.addComponent(newBody);

  Keep creating and adding new components, like Joints, Forces, etc..
      }

   *

   * @throws ComponentAlreadyPartOfOwnershipTree

   * @param subcomponent is the Component to be added.
   */
  private void private_addComponent(Component subcomponent) {
    opensimCommonJNI.Component_private_addComponent(swigCPtr, this, Component.getCPtr(subcomponent), subcomponent);
  }

  /**
   *  Get the complete (absolute) pathname for this Component to its ancestral

   * Component, which is the root of the tree to which this Component belongs.

   * For example: a Coordinate Component would have an absolute path name

   * like: `/arm26/elbow_r/flexion`. Accessing a Component by its

   * absolutePathName from root is guaranteed to be unique. The

   * absolutePathName is generated on-the-fly by traversing the ownership tree

   * and, therefore, calling this method is not "free".
   */
  public String getAbsolutePathString() {
    return opensimCommonJNI.Component_getAbsolutePathString(swigCPtr, this);
  }

  /**
   *  Return a ComponentPath of the absolute path of this Component.

   * Note that this has more overhead than calling `getName()` because

   * it traverses up the tree to generate the absolute pathname (and its

   * computational cost is thus a function of depth). Consider other

   * options if this is repeatedly called and efficiency is important.

   * For instance, `getAbsolutePathString()` is faster if you only

   * need the path as a string.
   */
  public ComponentPath getAbsolutePath() {
    return new ComponentPath(opensimCommonJNI.Component_getAbsolutePath(swigCPtr, this), true);
  }

  /**
   *  Get the relative path of this Component with respect to another

   * Component, as a string.
   */
  public String getRelativePathString(Component wrt) {
    return opensimCommonJNI.Component_getRelativePathString(swigCPtr, this, Component.getCPtr(wrt), wrt);
  }

  /**
   *  Get the relative path of this Component with respect to another

   * Component.
   */
  public ComponentPath getRelativePath(Component wrt) {
    return new ComponentPath(opensimCommonJNI.Component_getRelativePath(swigCPtr, this, Component.getCPtr(wrt), wrt), true);
  }

  /**
   *  Query if there is a component (of any type) at the specified

   * path name. For example,

   * {@code
  bool exists = model.hasComponent("right_elbow/elbow_flexion");
  }

   * checks if `model` has a subcomponent "right_elbow," which has a

   * subcomponent "elbow_flexion."
   */
  public boolean hasComponent(String pathname) {
    return opensimCommonJNI.Component_hasComponent(swigCPtr, this, pathname);
  }

  /**
   *  Similar to the templatized getComponent(), except this returns the

   * component as the generic Component type. This can be used in

   * Python/Java/MATLAB. Here is an example of using this in MATLAB:

   * {@code
  coord = model.getComponent('right_elbow/elbow_flexion')
  coord.getNumConnectees() % okay; this is a Component method.
  coord.getDefaultClamped() % inaccessible; method on Coordinate.
  Coordinate.safeDownCast(coord).getDefaultClamped() % now accessible.
  }

   *

   * %Exception: in Python, you will get the concrete type (in most cases):

   * {@code
  coord = model.getComponent('right_elbow/elbow_flexion')
  coord.getDefaultClamped() # works; no downcasting necessary.
  }
   */
  public Component getComponent(String pathname) {
    return new Component(opensimCommonJNI.Component_getComponent(swigCPtr, this, pathname), false);
  }

  /**
   *  Similar to the templatized updComponent(), except this returns the

   * component as the generic Component type. As with the non-templatized

   * getComponent(), though, this will give the concrete type in Python in

   * most cases.

   * @see getComponent()
   */
  public Component updComponent(String pathname) {
    return new Component(opensimCommonJNI.Component_updComponent(swigCPtr, this, pathname), false);
  }

  /**
   *  Print a list to the console of all components whose absolute path name

   * contains the given string. You might use this if (a) you know the name

   * of a component in your model but don't know its absolute path, (b) if

   * you want to find all components with a given name, or (c) to get a list

   * of all components on the right leg of a model (if all components on the

   * right side have "_r" in their name).

   *

   * A function call like:

   * {@code
  unsigned num = comp.printComponentsMatching("rotation");
  }

   * may produce output like:

   * {@literal
  /leg_model/right_hip/rotation
  /leg_model/left_hip/rotation
  }

   *

   * @return The number of matches.
   */
  public long printComponentsMatching(String substring) {
    return opensimCommonJNI.Component_printComponentsMatching(swigCPtr, this, substring);
  }

  /**
   * Get the number of "continuous" state variables maintained by the

   * Component and its subcomponents.

   * @throws ComponentHasNoSystem if this Component has not been added to a

   *         System (i.e., if initSystem has not been called)
   */
  public int getNumStateVariables() {
    return opensimCommonJNI.Component_getNumStateVariables(swigCPtr, this);
  }

  /**
   * Get the names of "continuous" state variables maintained by the Component

   * and its subcomponents.

   * @throws ComponentHasNoSystem if this Component has not been added to a

   *         System (i.e., if initSystem has not been called)
   */
  public ArrayStr getStateVariableNames() {
    return new ArrayStr(opensimCommonJNI.Component_getStateVariableNames(swigCPtr, this), true);
  }

  /**
   *  Get the number of Sockets in this Component.
   */
  public int getNumSockets() {
    return opensimCommonJNI.Component_getNumSockets(swigCPtr, this);
  }

  /**
   *  Collect and return the names of the sockets in this component. You

   * can use this to iterate through the sockets:

   * {@code
  for (std::string name : comp.getSocketNames()) {
      const AbstractSocket& socket = getSocket(name);
  }
  }
   */
  public StdVectorString getSocketNames() {
    return new StdVectorString(opensimCommonJNI.Component_getSocketNames(swigCPtr, this), true);
  }

  /**
   *  Get the connectee as an Object. This means you will not have

   * access to the methods on the concrete connectee. This is the method you

   * must use in MATLAB to access the connectee.

   *

   * Example:

   * {@code
  const Object& obj = joint.getConnectee("parent_frame");
  obj.getName(); // method on Object works.
  obj.getMobilizedBody(); // error: not available.
  }

   *

   * In MATLAB, if you want the concrete type, you need to downcast the

   * Object. Here is an example where you know the "parent_frame" is a Body:

   * {@code
  f = joint.getConnectee('parent_frame');
  m = Body.safeDownCast(f).getMass();
  }

   *

   * Exception: in Python, you will get the concrete type (in most cases):

   * {@code
  f = joint.getConnectee("parent_frame");
  m = f.getMass() # works (if the parent frame is a body)
  }
   */
  public OpenSimObject getConnectee(String name) {
    return new OpenSimObject(opensimCommonJNI.Component_getConnectee(swigCPtr, this, name), false);
  }

  public AbstractSocket getSocket(String name) {
    return new AbstractSocket(opensimCommonJNI.Component_getSocket(swigCPtr, this, name), false);
  }

  /**
   *  Get a writable reference to the AbstractSocket for the given

   * socket name. Use this method to connect the Socket to something.

   *

   * C++ example

   * {@code
  joint.updSocket("parent_frame").connect(model.getGround());
  }

   *

   * If you have not yet called finalizeFromProperties() on this

   * component, this function will update the Socket (to tell it which

   * component it's in) before providing it to you.
   */
  public AbstractSocket updSocket(String name) {
    return new AbstractSocket(opensimCommonJNI.Component_updSocket(swigCPtr, this, name), false);
  }

  /**
   *  Access the number of Inputs that this component has.
   */
  public int getNumInputs() {
    return opensimCommonJNI.Component_getNumInputs(swigCPtr, this);
  }

  /**
   *  Access the number of Outputs that this component has.
   */
  public int getNumOutputs() {
    return opensimCommonJNI.Component_getNumOutputs(swigCPtr, this);
  }

  /**
   *  Collect and return the names of Inputs in this component as an

   * std::vector.
   */
  public StdVectorString getInputNames() {
    return new StdVectorString(opensimCommonJNI.Component_getInputNames(swigCPtr, this), true);
  }

  /**
   *  Collect and return the names of Outputs in this component as an

   * std::vector.
   */
  public StdVectorString getOutputNames() {
    return new StdVectorString(opensimCommonJNI.Component_getOutputNames(swigCPtr, this), true);
  }

  /**
   * Get an Input provided by this Component by name.

   *

   * C++ example: get an Input from a Component in the model

   * {@code
  model.getComponent("/path/to/component").getInput("inputName");
  }

   *

   * If you have not yet called finalizeFromProperties() on this

   * component, this function will update the Input (to tell it which

   * component it's in) before providing it to you.

   *

   * @param name   the name of the Input

   * @return const reference to the AbstractInput
   */
  public AbstractInput getInput(String name) {
    return new AbstractInput(opensimCommonJNI.Component_getInput(swigCPtr, this, name), false);
  }

  /**
   * Get a writable reference to an Input provided by this Component by name.

   *

   * C++ example: get a writable reference to an Input of a

   * Component in a model

   * {@code
  model.updComponent("/path/to/component").updInput("inputName");
  }

   *

   * If you have not yet called finalizeFromProperties() on this

   * component, this function will update the Input (to tell it which

   * component it's in) before providing it to you.

   *

   * @param name   the name of the Input

   * @return reference to the AbstractInput
   */
  public AbstractInput updInput(String name) {
    return new AbstractInput(opensimCommonJNI.Component_updInput(swigCPtr, this, name), false);
  }

  /**
   * Get the Output provided by this Component by name.

   *

   * C++ example: get an Output from a Component in a model

   * {@code
  model.getComponent("/path/to/component").getOutput("outputName");
  }

   *

   * @param name   the name of the Output

   * @return const reference to the AbstractOutput
   */
  public AbstractOutput getOutput(String name) {
    return new AbstractOutput(opensimCommonJNI.Component_getOutput(swigCPtr, this, name), false);
  }

  /**
   * Get a writable reference to an Output provided by this Component by name.

   *

   * C++ example: get a writable reference to an Output of a

   * Component in a model

   * {@code
  model.updComponent("/path/to/component").updOutput("outputName");
  }

   *

   * @param name   the name of the Output

   * @return reference to the AbstractOutput
   */
  public AbstractOutput updOutput(String name) {
    return new AbstractOutput(opensimCommonJNI.Component_updOutput(swigCPtr, this, name), false);
  }

  /**
   * Get a ModelingOption flag for this Component by name.

   * The flag is an integer corresponding to the index of modelingOptionNames used

   * add the modeling option to the component. @see addModelingOption

   *

   * @param state  the State in which to set the modeling option

   * @param name   the name (string) of the modeling option of interest

   * @return flag  integer value for modeling option
   */
  public int getModelingOption(State state, String name) {
    return opensimCommonJNI.Component_getModelingOption(swigCPtr, this, State.getCPtr(state), state, name);
  }

  /**
   * %Set the value of a ModelingOption flag for this Component.

   * if the integer value exceeds the number of option names used to

   * define the options, an exception is thrown. The SimTK::State

   * Stage will be reverted back to Stage::Instance.

   *

   * @param state  the State in which to set the flag

   * @param name   the name (string) of the modeling option of interest

   * @param flag   the desired flag (int) value specifying the modeling option
   */
  public void setModelingOption(State state, String name, int flag) {
    opensimCommonJNI.Component_setModelingOption(swigCPtr, this, State.getCPtr(state), state, name, flag);
  }

  /**
   * Get the value of a state variable allocated by this Component.

   *

   * To connect this StateVariable as an input to another component (such as

   * a Reporter), use getOutput(name); each state variable has a

   * corresponding Output:

   *  {@code
   foo.getInput("input1").connect(bar.getOutput(name));
   }

   *

   * @param state   the State for which to get the value

   * @param name    the name (string) of the state variable of interest

   * @throws ComponentHasNoSystem if this Component has not been added to a

   *         System (i.e., if initSystem has not been called)
   */
  public double getStateVariableValue(State state, String name) {
    return opensimCommonJNI.Component_getStateVariableValue__SWIG_0(swigCPtr, this, State.getCPtr(state), state, name);
  }

  /**
   * Get the value of a state variable allocated by this Component.

   *

   * To connect this StateVariable as an input to another component (such as

   * a Reporter), use getOutput(name); each state variable has a

   * corresponding Output:

   *

   *  {@code
   foo.getInput("input1").connect(bar.getOutput(name));
   }

   *

   * @param state   the State for which to get the value

   *

   * @throws ComponentHasNoSystem if this Component has not been added to a

   *         System (i.e., if initSystem has not been called)
   */
  public double getStateVariableValue(State state, ComponentPath path) {
    return opensimCommonJNI.Component_getStateVariableValue__SWIG_1(swigCPtr, this, State.getCPtr(state), state, ComponentPath.getCPtr(path), path);
  }

  /**
   * %Set the value of a state variable allocated by this Component by name.

   *

   * @param state  the State for which to set the value

   * @param name   the name of the state variable

   * @param value  the value to set

   * @throws ComponentHasNoSystem if this Component has not been added to a

   *         System (i.e., if initSystem has not been called)
   */
  public void setStateVariableValue(State state, String name, double value) {
    opensimCommonJNI.Component_setStateVariableValue(swigCPtr, this, State.getCPtr(state), state, name, value);
  }

  /**
   * Get all values of the state variables allocated by this Component.

   * Includes state variables allocated by its subcomponents.

   *

   * @param state   the State for which to get the value

   * @return Vector of state variable values of length getNumStateVariables()

   *                in the order returned by getStateVariableNames()

   * @throws ComponentHasNoSystem if this Component has not been added to a

   *         System (i.e., if initSystem has not been called)
   */
  public Vector getStateVariableValues(State state) {
    return new Vector(opensimCommonJNI.Component_getStateVariableValues(swigCPtr, this, State.getCPtr(state), state), true);
  }

  /**
   * %Set all values of the state variables allocated by this Component.

   * Includes state variables allocated by its subcomponents. Note, this

   * method simply sets the values on the input State. If other conditions

   * must be met (such as satisfying kinematic constraints for Coordinates,

   * or fiber and tendon equilibrium for muscles) you must invoke the

   * appropriate methods on Model (e.g. assemble() to satisfy constraints or

   * equilibrateMuscles()) to satisfy these conditions starting from the

   * State values provided by setStateVariableValues.

   *

   * @param state   the State whose values are set

   * @param values  Vector of state variable values of length

   *                getNumStateVariables() in the order returned by

   *                getStateVariableNames()

   * @throws ComponentHasNoSystem if this Component has not been added to a

   *         System (i.e., if initSystem has not been called)
   */
  public void setStateVariableValues(State state, Vector values) {
    opensimCommonJNI.Component_setStateVariableValues(swigCPtr, this, State.getCPtr(state), state, Vector.getCPtr(values), values);
  }

  /**
   * Get the value of a state variable derivative computed by this Component.

   *

   * @param state   the State for which to get the derivative value

   * @param name    the name (string) of the state variable of interest

   * @throws ComponentHasNoSystem if this Component has not been added to a

   *         System (i.e., if initSystem has not been called)
   */
  public double getStateVariableDerivativeValue(State state, String name) {
    return opensimCommonJNI.Component_getStateVariableDerivativeValue(swigCPtr, this, State.getCPtr(state), state, name);
  }

  /**
   * Get the value of a discrete variable allocated by this Component by name.

   *

   * @param state   the State from which to get the value

   * @param name    the name of the state variable

   * @return value  the discrete variable value

   * @throws ComponentHasNoSystem if this Component has not been added to a

   *         System (i.e., if initSystem has not been called)
   */
  public double getDiscreteVariableValue(State state, String name) {
    return opensimCommonJNI.Component_getDiscreteVariableValue(swigCPtr, this, State.getCPtr(state), state, name);
  }

  /**
   * %Set the value of a discrete variable allocated by this Component by name.

   *

   * @param state  the State for which to set the value

   * @param name   the name of the discrete variable

   * @param value  the value to set

   * @throws ComponentHasNoSystem if this Component has not been added to a

   *         System (i.e., if initSystem has not been called)
   */
  public void setDiscreteVariableValue(State state, String name, double value) {
    opensimCommonJNI.Component_setDiscreteVariableValue(swigCPtr, this, State.getCPtr(state), state, name, value);
  }

  /**
   * Get the index of a Component's cache variable in the Subsystem for allocations.

   *

   *

   * @param name

   *   Name of the cache variable, as provided to Component::addCacheVariable

   * @return

   *   A valid SimTK::CacheEntryIndex, which callers can use with simbody methods

   *   (e.g. markCacheValueRealized)
   */
  public SWIGTYPE_p_SimTK__CacheEntryIndex getCacheVariableIndex(String name) {
    return new SWIGTYPE_p_SimTK__CacheEntryIndex(opensimCommonJNI.Component_getCacheVariableIndex(swigCPtr, this, name), true);
  }

  /**
   * Returns true if the cache variable, identified by `name`, is valid.

   *

   * This method enables callers to monitor the validity of the cache variable,

   * which enables the caller to decide whether to update the cache variable's

   * value (or not). When computing an update is costly, use this method to check

   * whether computing the value is necessary.

   *

   * @param state

   *     the State in which the cache variable's value resides

   * @param name

   *     the name of the cache variable

   * @return bool

   *     whether the cache variable's value is valid or not

   * @throws ComponentHasNoSystem

   *     if this Component has not been added to a System (i.e., if initSystem has not been called)
   */
  public boolean isCacheVariableValid(State state, String name) {
    return opensimCommonJNI.Component_isCacheVariableValid(swigCPtr, this, State.getCPtr(state), state, name);
  }

  /**
   * Marks the value of a cache variable, identified by `name`, as valid.

   *

   * Upon marking a cache variable's value as valid, the cache variable will remain

   * valid until either:

   *

   * - the realization stage falls below the minimum realization stage set

   *   when the cache variable was initialized with `Component::addCacheVariable`

   *

   * - the cache variable is explicitly invalidated by calling

   *   `Component::markCacheVariableInvalid`

   *

   * This method causes `Component::isCacheVariableValid` to return true.

   * `Component::isCacheVariableValid` is commonly used by value-getting

   * methods to decide on whether to return the value as-is or recompute the

   * value. Therefore, if a cache variable is not marked as valid then the

   * cache variable's value may be recomputed more than necessary, which may

   * be costly.

   *

   * @param state

   *     the State in which the cache variable's value resides

   * @param name

   *     the name of the cache variable

   * @throws ComponentHasNoSystem

   *     if this Component has not been added to a System (i.e., if initSystem has not been called)
   */
  public void markCacheVariableValid(State state, String name) {
    opensimCommonJNI.Component_markCacheVariableValid(swigCPtr, this, State.getCPtr(state), state, name);
  }

  /**
   * Marks the value of a cache variable, identified by `name`, as invalid.

   *

   * Upon marking a cache variable's value as invalid, it will remain invalid

   * until `Component::markCacheVariableValid` is called (or a method which

   * uses that, such as `Component::setCacheVariableValue`, is called).

   *

   * - Cache variables are automatically marked as invalid when the realization stage

   *   falls below the minimum realization stage set when the cache variable was

   *   initialized with `Component::addCacheVariable`.

   *

   * - Cache variables *may* be indirectly marked as invalid by other methods. For

   *   example, a component-added state variable may invalidate a cache variable at

   *   a lower stage. Concretely:

   *

   *   - A (hypothetical) component has a `length` state variable

   *   - There are cache variables that are computed from `length` (e.g.

   *   `strain`)

   *   - So changing the `length` may invalidate the `strain` indirectly

   *     (depending on how the state variable is handled)

   *

   * @param state

   *     the State in which the cache variable's value resides

   * @param name

   *     the name of the cache variable

   * @throws ComponentHasNoSystem

   *     if this Component has not been added to a System (i.e., if initSystem has not been called)
   */
  public void markCacheVariableInvalid(State state, String name) {
    opensimCommonJNI.Component_markCacheVariableInvalid(swigCPtr, this, State.getCPtr(state), state, name);
  }

  /**
   *  List all subcomponents by name and recurse into these components to

   *     list their subcomponents, and so on.
   */
  public void printSubcomponentInfo() {
    opensimCommonJNI.Component_printSubcomponentInfo(swigCPtr, this);
  }

  /**
   *  List all the Sockets of this component and whether or not they are

   *     connected. Also list the connectee paths for sockets that are connected.
   */
  public void printSocketInfo() {
    opensimCommonJNI.Component_printSocketInfo(swigCPtr, this);
  }

  /**
   *  List all the inputs of this component and whether or not they are

   *     connected. Also list the (desired) connectee paths for the inputs.
   */
  public void printInputInfo() {
    opensimCommonJNI.Component_printInputInfo(swigCPtr, this);
  }

  /**
   *  Print outputs of this component and optionally, those of all

   *     subcomponents.
   */
  public void printOutputInfo(boolean includeDescendants) {
    opensimCommonJNI.Component_printOutputInfo__SWIG_0(swigCPtr, this, includeDescendants);
  }

  /**
   *  Print outputs of this component and optionally, those of all

   *     subcomponents.
   */
  public void printOutputInfo() {
    opensimCommonJNI.Component_printOutputInfo__SWIG_1(swigCPtr, this);
  }

  /**
   *  Access the owner of this Component.

   * An exception is thrown if the %Component has no owner; in this case, the

   * component is the root component, or is orphaned.

   * @see hasOwner()
   */
  public Component getOwner() {
    return new Component(opensimCommonJNI.Component_getOwner(swigCPtr, this), false);
  }

  /**
   *  (For advanced users) Check if this %Component has an owner.

   * A component may not have an owner if it:

   * (1) is the root component, or

   * (2) has not been added to another component
   */
  public boolean hasOwner() {
    return opensimCommonJNI.Component_hasOwner(swigCPtr, this);
  }

  /**
   *  Obtain the root %Component, which is this component if it is orphaned.
   */
  public Component getRoot() {
    return new Component(opensimCommonJNI.Component_getRoot(swigCPtr, this), false);
  }

  /**
   *  Find a Component to which this Component is an ancestor---in other

   *     words, a Component that is directly owned by this Component or is owned

   *     by one of its sub-components, sub-sub-components, etc. The Component can

   *     be found by type (by specifying a template argument) and either path or

   *     name.

   *

   *     Here is an example of searching for a component of any type with the name

   *     'elbow_flexion':

   *     {@code
      if (const Component* found =
              model.findComponent(ComponentPath("elbow_flexion"))) {
          std::cout << found.getName() << std::endl;
      }
      }

   *

   *     Here, we require that 'elbow_flexion' is of type Coordinate.

   *     {@code
      if (const Coordinate* found =
              model.findComponent<Coordinate>(ComponentPath("elbow_flexion"))) {
          std::cout << "Coordinate " << found.getName() << std::endl;
      }
      }

   *

   *     The search can be sped up considerably if the path or even partial path

   *     name is known. For example, "forearm/elbow/elbow_flexion" will find

   *     the Coordinate component of the elbow joint that connects the forearm body

   *     in linear time (linear search for name at each component level). Whereas

   *     supplying "elbow_flexion" requires a tree search. Returns nullptr (None in

   *     Python, empty array in Matlab) if Component of that specified name cannot

   *     be found.

   *

   *     NOTE: If the component name is ambiguous, an exception is thrown. To

   *     disambiguate, more information must be provided, such as the template

   *     argument to specify the type and/or a path rather than just the name.
   */
  public Component findComponent(ComponentPath pathToFind) {
    long cPtr = opensimCommonJNI.Component_findComponent__SWIG_2(swigCPtr, this, ComponentPath.getCPtr(pathToFind), pathToFind);
    return (cPtr == 0) ? null : new Component(cPtr, false);
  }

  /**
   *  Same as findComponent(const ComponentPath&), but accepting a string (a

   *     path or just a name) as input.
   */
  public Component findComponent(String pathToFind) {
    long cPtr = opensimCommonJNI.Component_findComponent__SWIG_3(swigCPtr, this, pathToFind);
    return (cPtr == 0) ? null : new Component(cPtr, false);
  }

  /**
   * Get an iterator through the underlying subcomponents that this component is

   * composed of. The hierarchy of Components/subComponents forms a tree.

   * The order of the Components is that of tree preorder traversal so that a

   * component is traversed before its subcomponents.

   *

   * {@code
  for (const auto& muscle : model.getComponentList<Muscle>()) {
      muscle.get_max_isometric_force();
  }
  }

   *

   * The returned ComponentList does not permit modifying any components; if

   * you want to modify the components, see updComponentList().

   *

   *
   */
  public ComponentsList getComponentsList() {
    return new ComponentsList(opensimCommonJNI.Component_getComponentsList(swigCPtr, this), true);
  }

}


text:
#import "FIRPhoneAuthProvider.h"

#import <FirebaseCore/FIRLogger.h>
#import "FIRPhoneAuthCredential_Internal.h"
#import <FirebaseCore/FIRApp.h>
#import "FIRAuthAPNSToken.h"
#import "FIRAuthAPNSTokenManager.h"
#import "FIRAuthAppCredential.h"
#import "FIRAuthAppCredentialManager.h"
#import "FIRAuthGlobalWorkQueue.h"
#import "FIRAuth_Internal.h"
#import "FIRAuthURLPresenter.h"
#import "FIRAuthNotificationManager.h"
#import "FIRAuthErrorUtils.h"
#import "FIRAuthBackend.h"
#import "FIRAuthSettings.h"
#import "FIRAuthWebUtils.h"
#import "FirebaseAuthVersion.h"
#import <FirebaseCore/FIROptions.h>
#import "FIRGetProjectConfigRequest.h"
#import "FIRGetProjectConfigResponse.h"
#import "FIRSendVerificationCodeRequest.h"
#import "FIRSendVerificationCodeResponse.h"
#import "FIRVerifyClientRequest.h"
#import "FIRVerifyClientResponse.h"

NS_ASSUME_NONNULL_BEGIN

/** @typedef FIRReCAPTCHAURLCallBack
    @brief The callback invoked at the end of the flow to fetch a reCAPTCHA URL.
    @param reCAPTCHAURL The reCAPTCHA URL.
    @param error The error that occurred while fetching the reCAPTCHAURL, if any.
 */
typedef void (^FIRReCAPTCHAURLCallBack)(NSURL *_Nullable reCAPTCHAURL, NSError *_Nullable error);

/** @typedef FIRVerifyClientCallback
    @brief The callback invoked at the end of a client verification flow.
    @param appCredential credential that proves the identity of the app during a phone
        authentication flow.
    @param error The error that occurred while verifying the app, if any.
 */
typedef void (^FIRVerifyClientCallback)(FIRAuthAppCredential *_Nullable appCredential,
                                        NSString *_Nullable reCAPTCHAToken,
                                        NSError *_Nullable error);

/** @typedef FIRFetchAuthDomainCallback
    @brief The callback invoked at the end of the flow to fetch the Auth domain.
    @param authDomain The Auth domain.
    @param error The error that occurred while fetching the auth domain, if any.
 */
typedef void (^FIRFetchAuthDomainCallback)(NSString *_Nullable authDomain,
                                           NSError *_Nullable error);

/** @var kauthTypeVerifyApp
    @brief The auth type to be specified in the app verification request.
 */
static NSString *const kAuthTypeVerifyApp = @"verifyApp";

/** @var kReCAPTCHAURLStringFormat
    @brief The format of the URL used to open the reCAPTCHA page during app verification.
 */
NSString *const kReCAPTCHAURLStringFormat = @"https://%@/__/auth/handler?";

@implementation FIRPhoneAuthProvider {

  /** @var _auth
      @brief The auth instance used for verifying the phone number.
   */
  FIRAuth *_auth;

  /** @var _callbackScheme
      @brief The callback URL scheme used for reCAPTCHA fallback.
   */
  NSString *_callbackScheme;
}

/** @fn initWithAuth:
    @brief returns an instance of @c FIRPhoneAuthProvider associated with the provided auth
          instance.
    @return An Instance of @c FIRPhoneAuthProvider.
   */
- (nullable instancetype)initWithAuth:(FIRAuth *)auth {
  self = [super init];
  if (self) {
    _auth = auth;
    _callbackScheme = [[[_auth.app.options.clientID componentsSeparatedByString:@"."]
        reverseObjectEnumerator].allObjects componentsJoinedByString:@"."];
  }
  return self;
}

- (void)verifyPhoneNumber:(NSString *)phoneNumber
               UIDelegate:(nullable id<FIRAuthUIDelegate>)UIDelegate
               completion:(nullable FIRVerificationResultCallback)completion {
  if (![FIRAuthWebUtils isCallbackSchemeRegisteredForCustomURLScheme:_callbackScheme]) {
    [NSException raise:NSInternalInconsistencyException
                format:@"Please register custom URL scheme '%@' in the app's Info.plist file.",
                       _callbackScheme];
  }
  dispatch_async(FIRAuthGlobalWorkQueue(), ^{
    FIRVerificationResultCallback callBackOnMainThread = ^(NSString *_Nullable verificationID,
                                                           NSError *_Nullable error) {
      if (completion) {
        dispatch_async(dispatch_get_main_queue(), ^{
          completion(verificationID, error);
        });
      }
    };
    [self internalVerifyPhoneNumber:phoneNumber
                         UIDelegate:UIDelegate
                         completion:^(NSString *_Nullable verificationID,
                                      NSError *_Nullable error) {
      if (!error) {
        callBackOnMainThread(verificationID, nil);
        return;
      } else {
        callBackOnMainThread(nil, error);
        return;
      }
    }];
  });
}

- (FIRPhoneAuthCredential *)credentialWithVerificationID:(NSString *)verificationID
                                        verificationCode:(NSString *)verificationCode {
  return [[FIRPhoneAuthCredential alloc] initWithProviderID:FIRPhoneAuthProviderID
                                             verificationID:verificationID
                                           verificationCode:verificationCode];
}

+ (instancetype)provider {
  return [[self alloc]initWithAuth:[FIRAuth auth]];
}

+ (instancetype)providerWithAuth:(FIRAuth *)auth {
  return [[self alloc]initWithAuth:auth];
}

#pragma mark - Internal Methods

/** @fn reCAPTCHATokenForURL:error:
    @brief Parses the reCAPTCHA URL and returns the reCAPTCHA token.
    @param URL The url to be parsed for a reCAPTCHA token.
    @param error The error that occurred if any.
    @return The reCAPTCHA token if successful.
 */
- (NSString *)reCAPTCHATokenForURL:(NSURL *)URL error:(NSError **)error {
  NSURLComponents *actualURLComponents = [NSURLComponents componentsWithURL:URL resolvingAgainstBaseURL:NO];
  NSArray<NSURLQueryItem *> *queryItems = [actualURLComponents queryItems];
  NSString *deepLinkURL = [FIRAuthWebUtils queryItemValue:@"deep_link_id" from:queryItems];
  NSData *errorData;
  if (deepLinkURL) {
    actualURLComponents = [NSURLComponents componentsWithString:deepLinkURL];
    queryItems = [actualURLComponents queryItems];
    NSString *recaptchaToken = [FIRAuthWebUtils queryItemValue:@"recaptchaToken" from:queryItems];
    if (recaptchaToken) {
      return recaptchaToken;
    }
    NSString *firebaseError = [FIRAuthWebUtils queryItemValue:@"firebaseError" from:queryItems];
    errorData = [firebaseError dataUsingEncoding:NSUTF8StringEncoding];
  } else {
    errorData = nil;
  }
  NSError *jsonError;
  NSDictionary *errorDict = [NSJSONSerialization JSONObjectWithData:errorData
                                                            options:0
                                                              error:&jsonError];
  if (jsonError) {
    *error = [FIRAuthErrorUtils JSONSerializationErrorWithUnderlyingError:jsonError];
    return nil;
  }
  *error = [FIRAuthErrorUtils URLResponseErrorWithCode:errorDict[@"code"]
                                               message:errorDict[@"message"]];
  if (!*error) {
    NSString *reason;
    if(errorDict[@"code"] && errorDict[@"message"]) {
      reason = [NSString stringWithFormat:@"[%@] - %@",errorDict[@"code"], errorDict[@"message"]];
    } else {
      reason = [NSString stringWithFormat:@"An unknown error occurred with the following "
          "response: %@", deepLinkURL];
    }
    *error = [FIRAuthErrorUtils appVerificationUserInteractionFailureWithReason:reason];
  }
  return nil;
}

/** @fn internalVerifyPhoneNumber:completion:
    @brief Starts the phone number authentication flow by sending a verifcation code to the
        specified phone number.
    @param phoneNumber The phone number to be verified.
    @param completion The callback to be invoked when the verification flow is finished.
 */

- (void)internalVerifyPhoneNumber:(NSString *)phoneNumber
                       UIDelegate:(nullable id<FIRAuthUIDelegate>)UIDelegate
                       completion:(nullable FIRVerificationResultCallback)completion {
  if (!phoneNumber.length) {
    completion(nil, [FIRAuthErrorUtils missingPhoneNumberErrorWithMessage:nil]);
    return;
  }
  [_auth.notificationManager checkNotificationForwardingWithCallback:
      ^(BOOL isNotificationBeingForwarded) {
    if (!isNotificationBeingForwarded) {
      completion(nil, [FIRAuthErrorUtils notificationNotForwardedError]);
      return;
    }
    FIRVerificationResultCallback callback = ^(NSString *_Nullable verificationID,
                                               NSError *_Nullable error) {
      if (completion) {
        completion(verificationID, error);
      }
    };
    [self verifyClientAndSendVerificationCodeToPhoneNumber:phoneNumber
                               retryOnInvalidAppCredential:YES
                                                UIDelegate:UIDelegate
                                                  callback:callback];
  }];
}

/** @fn verifyClientAndSendVerificationCodeToPhoneNumber:retryOnInvalidAppCredential:callback:
    @brief Starts the flow to verify the client via silent push notification.
    @param retryOnInvalidAppCredential Whether of not the flow should be retried if an
        FIRAuthErrorCodeInvalidAppCredential error is returned from the backend.
    @param phoneNumber The phone number to be verified.
    @param callback The callback to be invoked on the global work queue when the flow is
        finished.
 */
- (void)verifyClientAndSendVerificationCodeToPhoneNumber:(NSString *)phoneNumber
                             retryOnInvalidAppCredential:(BOOL)retryOnInvalidAppCredential
                                              UIDelegate:(nullable id<FIRAuthUIDelegate>)UIDelegate
                                                callback:(FIRVerificationResultCallback)callback {
  if (_auth.settings.isAppVerificationDisabledForTesting) {
    FIRSendVerificationCodeRequest *request =
        [[FIRSendVerificationCodeRequest alloc] initWithPhoneNumber:phoneNumber
                                                     appCredential:nil
                                                    reCAPTCHAToken:nil
                                              requestConfiguration:
                                                  _auth.requestConfiguration];
    [FIRAuthBackend sendVerificationCode:request
                                callback:^(FIRSendVerificationCodeResponse *_Nullable response,
                                           NSError *_Nullable error) {
      callback(response.verificationID, error);
    }];
    return;
  }
  [self verifyClientWithUIDelegate:UIDelegate
                        completion:^(FIRAuthAppCredential *_Nullable appCredential,
                                     NSString *_Nullable reCAPTCHAToken,
                                     NSError *_Nullable error) {
    if (error) {
      callback(nil, error);
      return;
    }
    FIRSendVerificationCodeRequest * _Nullable request;
    if (appCredential) {
      request =
          [[FIRSendVerificationCodeRequest alloc]
              initWithPhoneNumber:phoneNumber
                    appCredential:appCredential
                   reCAPTCHAToken:nil
             requestConfiguration:self->_auth.requestConfiguration];
    } else if (reCAPTCHAToken) {
      request =
          [[FIRSendVerificationCodeRequest alloc]
              initWithPhoneNumber:phoneNumber
                    appCredential:nil
                   reCAPTCHAToken:reCAPTCHAToken
             requestConfiguration:self->_auth.requestConfiguration];
    }
    if (request) {
      [FIRAuthBackend sendVerificationCode:request
                                  callback:^(FIRSendVerificationCodeResponse *_Nullable response,
                                             NSError *_Nullable error) {
        if (error) {
          if (error.code == FIRAuthErrorCodeInvalidAppCredential) {
            if (retryOnInvalidAppCredential) {
              [self->_auth.appCredentialManager clearCredential];
              [self verifyClientAndSendVerificationCodeToPhoneNumber:phoneNumber
                                         retryOnInvalidAppCredential:NO
                                                          UIDelegate:UIDelegate
                                                            callback:callback];
              return;
            }
            callback(nil, [FIRAuthErrorUtils unexpectedResponseWithDeserializedResponse:nil
                                                                        underlyingError:error]);
            return;
          }
          callback(nil, error);
          return;
        }
        callback(response.verificationID, nil);
      }];
    }
  }];
}

/** @fn verifyClientWithCompletion:completion:
    @brief Continues the flow to verify the client via silent push notification.
    @param completion The callback to be invoked when the client verification flow is finished.
 */
- (void)verifyClientWithUIDelegate:(nullable id<FIRAuthUIDelegate>)UIDelegate
                        completion:(FIRVerifyClientCallback)completion {
  if (_auth.appCredentialManager.credential) {
    completion(_auth.appCredentialManager.credential, nil, nil);
    return;
  }
  [_auth.tokenManager getTokenWithCallback:^(FIRAuthAPNSToken *_Nullable token,
                                             NSError *_Nullable error) {
    if (!token) {
      [self reCAPTCHAFlowWithUIDelegate:UIDelegate completion:completion];
      return;
    }
    FIRVerifyClientRequest *request =
        [[FIRVerifyClientRequest alloc] initWithAppToken:token.string
                                               isSandbox:token.type == FIRAuthAPNSTokenTypeSandbox
                                    requestConfiguration:self->_auth.requestConfiguration];
    [FIRAuthBackend verifyClient:request callback:^(FIRVerifyClientResponse *_Nullable response,
                                                    NSError *_Nullable error) {
      if (error) {
        NSError *underlyingError = error.userInfo[NSUnderlyingErrorKey];
        BOOL isInvalidAppCredential = error.code == FIRAuthErrorCodeInternalError &&
            underlyingError.code == FIRAuthErrorCodeInvalidAppCredential;
        if (error.code != FIRAuthErrorCodeMissingAppToken && !isInvalidAppCredential) {
          completion(nil, nil, error);
          return;
        } else {
          [self reCAPTCHAFlowWithUIDelegate:UIDelegate completion:completion];
          return;
        }
      }
      NSTimeInterval timeout = [response.suggestedTimeOutDate timeIntervalSinceNow];
      [self->_auth.appCredentialManager
          didStartVerificationWithReceipt:response.receipt
                                  timeout:timeout
                                 callback:^(FIRAuthAppCredential *credential) {
        if (!credential.secret) {
          FIRLogWarning(kFIRLoggerAuth, @"I-AUT000014",
                        @"Failed to receive remote notification to verify app identity within "
                        @"%.0f second(s)", timeout);
        }
        completion(credential, nil, nil);
      }];
    }];
  }];
}

- (void)reCAPTCHAFlowWithUIDelegate:(nullable id<FIRAuthUIDelegate>)UIDelegate
                         completion:(FIRVerifyClientCallback)completion {
  NSString *eventID = [FIRAuthWebUtils randomStringWithLength:10];
  [self reCAPTCHAURLWithEventID:eventID completion:^(NSURL *_Nullable reCAPTCHAURL,
                                                     NSError *_Nullable error) {
    if (error) {
      completion(nil, nil, error);
      return;
    }
    FIRAuthURLCallbackMatcher callbackMatcher = ^BOOL(NSURL *_Nullable callbackURL) {
      return [FIRAuthWebUtils isExpectedCallbackURL:callbackURL
                                            eventID:eventID
                                           authType:kAuthTypeVerifyApp
                                     callbackScheme:self->_callbackScheme];
    };
    [self->_auth.authURLPresenter presentURL:reCAPTCHAURL
                                  UIDelegate:UIDelegate
                             callbackMatcher:callbackMatcher
                                  completion:^(NSURL *_Nullable callbackURL,
                                               NSError *_Nullable error) {
      if (error) {
        completion(nil, nil, error);
        return;
      }
      NSError *reCAPTCHAError;
      NSString *reCAPTCHAToken = [self reCAPTCHATokenForURL:callbackURL error:&reCAPTCHAError];
      if (!reCAPTCHAToken) {
        completion(nil, nil, reCAPTCHAError);
        return;
      } else {
        completion(nil, reCAPTCHAToken, nil);
        return;
      }
    }];
  }];
}

/** @fn reCAPTCHAURLWithEventID:completion:
    @brief Constructs a URL used for opening a reCAPTCHA app verification flow using a given event
        ID.
    @param eventID The event ID used for this purpose.
    @param completion The callback invoked after the URL has been constructed or an error
        has been encountered.
 */
- (void)reCAPTCHAURLWithEventID:(NSString *)eventID completion:(FIRReCAPTCHAURLCallBack)completion {
  [FIRAuthWebUtils fetchAuthDomainWithRequestConfiguration:_auth.requestConfiguration
                                                completion:^(NSString *_Nullable authDomain,
                                                             NSError *_Nullable error) {
    if (error) {
      if (completion) {
        completion(nil, error);
        return;
      }
    }
    NSString *bundleID = [NSBundle mainBundle].bundleIdentifier;
    NSString *clientID = self->_auth.app.options.clientID;
    NSString *apiKey = self->_auth.requestConfiguration.APIKey;
    NSMutableArray<NSURLQueryItem *> *queryItems = [@[
      [NSURLQueryItem queryItemWithName:@"apiKey" value:apiKey],
      [NSURLQueryItem queryItemWithName:@"authType" value:kAuthTypeVerifyApp],
      [NSURLQueryItem queryItemWithName:@"ibi" value:bundleID ?: @""],
      [NSURLQueryItem queryItemWithName:@"clientId" value:clientID],
      [NSURLQueryItem queryItemWithName:@"v" value:[FIRAuthBackend authUserAgent]],
      [NSURLQueryItem queryItemWithName:@"eventId" value:eventID]
      ] mutableCopy
    ];

    if (self->_auth.requestConfiguration.languageCode) {
      [queryItems addObject:[NSURLQueryItem queryItemWithName:@"hl"value:
                             self->_auth.requestConfiguration.languageCode]];
    }
    NSURLComponents *components = [[NSURLComponents alloc] initWithString:
      [NSString stringWithFormat:kReCAPTCHAURLStringFormat, authDomain]];
    [components setQueryItems:queryItems];
    if (completion) {
      completion([components URL], nil);
    }
  }];
}

@end

NS_ASSUME_NONNULL_END

redpajama_set_name: RedPajamaGithub


text:
#ifndef MINIKIN_FONT_TEST_UTILS_H
#define MINIKIN_FONT_TEST_UTILS_H

#include <minikin/FontCollection.h>

#include <memory>

namespace minikin {

/**
 * Returns list of FontFamily from installed fonts.
 *
 * This function reads an XML file and makes font families.
 *
 * Caller must unref the returned pointer.
 */
std::vector<std::shared_ptr<FontFamily>> getFontFamilies(const char* fontDir,
                                                         const char* fontXml);

/**
 * Returns FontCollection from installed fonts.
 *
 * This function reads an XML file and makes font families and collections of
 * them. MinikinFontForTest is used for FontFamily creation.
 *
 * Caller must unref the returned pointer.
 */
std::shared_ptr<FontCollection> getFontCollection(const char* fontDir,
                                                  const char* fontXml);

}  // namespace minikin
#endif  // MINIKIN_FONT_TEST_UTILS_H


text:
package utils

object Time {
  def getUnixTimestampSeconds = System.currentTimeMillis() / 1000L
  def getUnixTimestampMilliseconds = System.currentTimeMillis()
}


text:
FOUNDATION_EXPORT double sliderMenuVersionNumber;

//! Project version string for sliderMenu.
FOUNDATION_EXPORT const unsigned char sliderMenuVersionString[];

// In this header, you should import all the public headers of your framework using statements like #import <sliderMenu/PublicHeader.h>


text:
package com.github.tomakehurst.wiremock.extension.responsetemplating.helpers;

import com.fasterxml.jackson.core.type.TypeReference;
import com.github.jknack.handlebars.Options;
import com.github.jknack.handlebars.TagType;
import com.github.tomakehurst.wiremock.common.Json;

import java.io.IOException;
import java.util.Map;
import java.util.List;
import java.util.HashMap;

public class ParseJsonHelper extends HandlebarsHelper<Object> {

    @Override
    public Object apply(Object context, Options options) throws IOException {
        CharSequence json;
        String variableName;
        Object result = new HashMap<String, Object>();

        // Edge case if null JSON object passed in
        if(context == null) { return result; }

        boolean hasContext = context != options.context.model();

        if (options.tagType == TagType.SECTION) {
            json =  options.apply(options.fn);
            variableName = hasContext ? context.toString() : null;
        } else {
            if (!hasContext) {
                return handleError("Missing required JSON string parameter");
            }

            json = context.toString();
            variableName = options.params.length > 0 ? options.param(0) : null;
        }

        if(json != null) {
            String jsonAsString = json.toString().trim();

            // Edge case if JSON object is empty {}
            String jsonAsStringWithoutSpace = jsonAsString.replaceAll("\\s", "");
            if(jsonAsStringWithoutSpace.equals("{}") || jsonAsStringWithoutSpace.equals("")) { return result; }

            if(jsonAsString.startsWith("[") && jsonAsString.endsWith("]")) {
                result = Json.read(jsonAsString, new TypeReference<List<Object>>() {});
            } else {
                result = Json.read(jsonAsString, new TypeReference<Map<String, Object>>() {});
            }
        }

        if (variableName != null) {
            options.context.data(variableName, result);
            return null;
        }

        return result;
    }
}


text:
"use strict";

var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.default = void 0;

var _createSvgIcon = _interopRequireDefault(require("./utils/createSvgIcon"));

var _jsxRuntime = require("react/jsx-runtime");

var _default = (0, _createSvgIcon.default)( /*#__PURE__*/(0, _jsxRuntime.jsx)("path", {
  d: "M4 18.99h11c.67 0 1.27-.32 1.63-.83L21 12l-4.37-6.16C16.27 5.33 15.67 5 15 5H4l5 7-5 6.99z"
}), 'LabelImportantOutlined');

exports.default = _default;


text:
module ActiveRecord
  class Relation
    class FromClause # :nodoc:
      attr_reader :value, :name

      def initialize(value, name)
        @value = value
        @name = name
      end

      def binds
        if value.is_a?(Relation)
          value.bound_attributes
        else
          []
        end
      end

      def merge(other)
        self
      end

      def empty?
        value.nil?
      end

      def self.empty
        new(nil, nil)
      end
    end
  end
end


text:
cask 'haroopad' do
  version '0.13.1'
  sha256 '97ea132dfb1efa5492d98ee3b7de4beda79796ac75ce293c57e8300e11b1f694'

  # bitbucket.org/rhiokim/haroopad-download was verified as official when first introduced to the cask
  url "https://bitbucket.org/rhiokim/haroopad-download/downloads/Haroopad-v#{version}-x64.dmg"
  name 'Haroopad'
  homepage 'http://pad.haroopress.com/'

  app 'Haroopad.app'
end


text:
<?php

namespace Mautic\CampaignBundle\EventListener;

use Mautic\CalendarBundle\CalendarEvents;
use Mautic\CalendarBundle\Event\CalendarGeneratorEvent;
use Mautic\CoreBundle\EventListener\CommonSubscriber;
use Mautic\CoreBundle\Helper\DateTimeHelper;

/**
 * Class CalendarSubscriber
 *
 * @package Mautic\CampaignBundle\EventListener
 */
class CalendarSubscriber extends CommonSubscriber
{

    /**
     * @return array
     */
    static public function getSubscribedEvents()
    {
        return array(
            CalendarEvents::CALENDAR_ON_GENERATE => array('onCalendarGenerate', 0)
        );
    }

    /**
     * Adds events to the calendar
     *
     * @param CalendarGeneratorEvent $event
     *
     * @return void
     */
    public function onCalendarGenerate(CalendarGeneratorEvent $event)
    {
        $dates  = $event->getDates();
        $router = $this->factory->getRouter();
        $now    = new DateTimeHelper;

        $commonSelect = 'cl.campaign_id, c.name AS campaign_name, l.firstname, l.lastname, ce.type AS event_type, ce.name as event_name, cat.color';
        $eventTypes = array();
        $eventTypes['triggered'] = array('dateName' => 'cl.date_triggered');
        $eventTypes['upcoming']  = array('dateName' => 'cl.trigger_date');

        $query = $this->factory->getEntityManager()->getConnection()->createQueryBuilder();
        $query->from(MAUTIC_TABLE_PREFIX . 'campaign_lead_event_log', 'cl')
            ->leftJoin('cl', MAUTIC_TABLE_PREFIX . 'campaigns', 'c', 'cl.campaign_id = c.id')
            ->leftJoin('cl', MAUTIC_TABLE_PREFIX . 'leads', 'l', 'cl.lead_id = l.id')
            ->leftJoin('cl', MAUTIC_TABLE_PREFIX . 'campaign_events', 'ce', 'cl.event_id = ce.id')
            ->leftJoin('cl', MAUTIC_TABLE_PREFIX . 'categories', 'cat', 'cat.id = c.category_id AND cat.bundle=:bundle')
            ->setParameter('bundle', 'campaign')
            ->setParameter('start', $dates['start_date'])
            ->setParameter('end', $dates['end_date'])
            ->setFirstResult(0)
            ->setMaxResults(50);

        foreach ($eventTypes as $eventKey => $eventType) {
            $query->select($commonSelect . ', ' . $eventType['dateName'] . ' AS start')
                ->where($query->expr()->andX(
                    $query->expr()->gte($eventType['dateName'], ':start'),
                    $query->expr()->lte($eventType['dateName'], ':end')
                ));
            if ($eventKey == 'upcoming') {
                $query->andWhere($query->expr()->gte($eventType['dateName'], ':now'))
                    ->setParameter('now', $now->toUtcString());
            }
            $results = $query->execute()->fetchAll();
            // echo "<pre>";var_dump($results);die("</pre>");

            // We need to convert the date to a ISO8601 compliant string
            foreach ($results as &$object) {
                if ($object['firstname'] || $object['lastname']) {
                    $leadName = $object['firstname'] . ' ' . $object['lastname'];
                } else {
                    $leadName = $this->translator->trans('mautic.lead.lead.anonymous');
                }
                $date = new DateTimeHelper($object['start']);
                $object['start'] = $date->toLocalString(\DateTime::ISO8601);
                $object['url']   = $router->generate('mautic_campaign_action', array('objectAction' => 'view', 'objectId' => $object['campaign_id']), true);
                $object['attr']  = 'data-toggle="ajax"';
                $object['description'] = $this->translator->trans('mautic.campaign.event.' . $eventKey . '.description', array('%campaign%' => $object['campaign_name'], '%lead%' => $leadName));
                $object['title'] = $this->translator->trans('mautic.campaign.event.' . $eventKey, array('%event%' => $object['event_name']));
            }

            $event->addEvents($results);
        }
    }
}


text:
/** @namespace ext.share.filesystem */
js.extend('ext.share.filesystem', function (js) {

  var CSelection = js.ext.share.Selection;

  /**
   * @class Tree
   */

  var CTree = this.Tree = function (dnode, nodeClass) {
    CSelection.apply(this);
    this.hub = dnode.getDataBridge();
    if (!nodeClass) nodeClass = js.ext.share.filesystem.Node;
    this.rootNode = new nodeClass(dnode, this);
  };

  var _proto = this.Tree.prototype = js.lang.createMethods(
    CSelection
  );

  /**
   * @function expandNodeByAddress
   * @param addr
   * @param cb
   */

  _proto.expandNodeByAddress = function (addr, cb) {
    this.hub.fetch(addr, [function (data) {
      if (!data) {
        // Node does not exist
        if (cb) js.lang.callback(cb, this);
        return;
      }
      var targetNode = this.rootNode.getNodeByAddress(data.getAddress());
      if (targetNode) {
        // Expand this node (and parent nodes)
        var node = targetNode;
        while(node) {
          node.expand();
          node = node.parentNode;
        }
      }
      if (cb) js.lang.callback(cb, this, [targetNode]);
    }, this]);
  };

  _proto.selectCwdByAddress = function (addr, cb) {
    this.expandNodeByAddress(addr, [function (node) {
      if (node) node.setAsCwd();
      if (cb) js.lang.callback(cb, this, [node]);
    }, this]);
  };

  /**
   * @function selectNodeByAddress
   * @param addr
   * @param cb
   */

  _proto.selectNodeByAddress = function (addr, cb) {
    var selected = this.getSelected();
    if (selected) {
      var selectedAddr = selected.data.getAddress();
      if (selectedAddr == addr) return;
    }
    this.clearSelection();
    var paddr = js.data.addr_parent(addr);
    this.expandNodeByAddress(paddr, [function (pnode) {
      if (!pnode) {
        // Node does not exist
        if (cb) js.lang.callback(cb, this);
        return;
      }
      pnode.setAsCwd();
      var node = pnode.getNodeByAddress(addr);
      if (node) node.select();
      if (cb) js.lang.callback(cb, this, [node]);
    }, this]);
  };

  _proto.validateCwd = function () {
    var node = this.getCwd();
    if (!node || node.parentNode) return;
    var addr = node.data.getAddress();
    while (!this.hub.getNodeByAddress(addr)) {
      addr = js.data.addr_parent(addr);
    }
    var node = this.rootNode.getNodeByAddress(addr);
    if (node) node.setAsCwd();
  };

  _proto.unload = function () {
    this.rootNode.removeAllChildren();
  };

});


text:
/**
 * @file dht/id.h
 * @brief DHT Id representing a DHT key and positions in the hash space
 */
#ifndef EPYX_DHT_ID_H
#define EPYX_DHT_ID_H

#include <iostream>
#include <string>
#include <stdint.h>
#include "../crypto/sha2.h"

namespace Epyx
{
namespace DHT
{

    class Distance;

    /**
     * @class Id
     * @brief represents positions in the DHT hash space
     */
    class Id
    {
    public:
        static const int LENGTH = 256;
        static const int STORAGE_SIZE = 256/8;
        uint8_t data[STORAGE_SIZE];

        // Initialisation method
        enum Initialisation {
            INIT_ZERO,
            INIT_RANDOM
        };

        /**
         * @brief build a zeroed ID
         */
        Id();

        Id(Initialisation init);

        // Copy
        Id(const Id& id);
        Id& operator=(const Id& id);

        /**
         * @brief Randomize ID data
         */
        void randomize();

        /**
         * @brief Reset an ID to zero
         */
        void reset();
    };

    std::ostream& operator<<(std::ostream& os, const Id& id);
    std::istream& operator>>(std::istream& in, Id& id);

    void idForString(Id& id, const std::string& toCipher);

    /**
     * @class Distance
     * @brief a distance is just an Id but we want different types to add methods
     */
    class Distance: public Id
    {
    public:
        /**
         * @brief the constructor of a Distance from 2 Ids
         * @param a one of the Ids
         * @param b the other
         */
        Distance(const Id* a, const Id* b);
        /**
         * @brief the constructor of a Distance from 2 Ids
         * @param a one of the Ids
         * @param b the other
         */
        Distance(const Id& a, const Id& b);

        /**
         * @brief returns the index first non null bit
         * @return log2(distance) kind of
         */
        int firstActiveBit() const;

    private:
        int firstActive;

        void initSelf(const Id* a, const Id* b);
    };

    std::ostream& operator<<(std::ostream& os, const Distance& d);
    bool operator<(const Id &a, const Id &b);
    bool operator==(const Id &a, const Id &b);
}
}

#endif /* EPYX_DHT_ID_H */


text:
Localizer

## What is Localizer?

Localizer is a laravel package to change easily locale on laravel projects.

It's so simple to use, once it's installed, your App locale will change only by passing routes into localizer middleare.

**Top features:**

- Change automatically app locale depending on user browser configuration
- Get language like 'Spanish' or 'English' from codes such as 'es' or 'en'.
- Store on users database table the user locale preference
- Restrict users to set languages you don't have translations

## Getting Started

### 1. Install it with composer

Running the command below:

```
composer require aitor24/localizer
```

### 2. Register service provider

Register the localizer service provider on ``config/app.php``.

```php
Aitor24\Localizer\LocalizerServiceProvider::class,
```

Remind to add alias to use Localizer functions comfortably.

```php
'Localizer'   => Aitor24\Localizer\Facades\LocalizerFacade::class,
```

### 3. Publish config

It will publish config file.

Running the command below:

```
php artisan vendor:publish --tag=localizer_config
```

#### 3.1 Publish languages

Also you can publish your languages to modify or add.

```
php artisan vendor:publish --tag=localizer_languages
```

### 4. Migrate

Publish migrations:
```
php artisan vendor:publish --tag=localizer_migrations
```

Running the command below:

```
php artisan migrate
```

### 5. Configure defalt values

Default values can be modified also on `config/localizer.php`.

#### Keys

- routes: Makes routes available.
- carbon: Sets carbon translator language.
- homeRoute: Make home route available.
- set_auto_lang: Sets language automatically depending on user's browser config
- default_lang: Default language if set_auto_lang is false or user is attempting to set an unallowed language
- prefix: Prefix of routes URI to set locale,
- allowed_langs: All allowed languages,
- middleware: default middleware to set locale,

## Using Localizer

### Middleware

All routes in which you want to set language should be under the localizer's
middleware to set at each request de App locale.

```php
Route::group(['middleware' => 'localizer'], function () {

    // Here your routes

});
```

### Changing languages

- Via URL with return home: /lang/set/{locale}/home
- Via URL with return back: /lang/set/{locale}

**Tip:** */lang prefix will be changed on config*

## Example languages view

Following there are a little code snippet of a view to select and
set languages:

```php
@foreach (Localizer::allowedLanguages() as $code => $value)
    <a href="{{ Localizer::setRouteHome($code) }}">{{ $value }}</a>
@endforeach
```

## API

### Localizer::allowedLanguages()

Returns an array with [$code => $language] for all allowed
languages of config.

### Localizer::addNames($codes)

Get an array like [$code => $language] from an array of only $codes.

### Localizer::addCodes($lang)

Get an array like [$language => $code] from an array of only $langs.

### Localizer::setRoute($code)

*Used for modals or dropdowns*

Returns the url to set up language and return back.

Also if you prefer to use directly route() function you can use it
as following code:

```php
{{ route('localizer::setLocale', ['locale' => $code]) }}
```

### Localizer::setRouteHome($code)

*Used for language selection views*

Returns the url to set language and return '/' *url('/')*

Also if you prefer to use directly route() function you can use it
as following code:

```php
{{ route('localizer::setLocaleHome', ['locale' => $code]) }}
```

### Localizer::getLanguage($code = App::getLocale())

Returns the language name of $code if specified or the current
language setted if not.

**Tip:** *Use App::getLocale() to get the current locale*