text:
.. _mechanisms:

Cable cell mechanisms
=====================

Mechanisms describe biophysical processes such as ion channels, synapses and gap-junctions.
Mechanisms are assigned to regions and locations on a cell morphology
through the process of :ref:`decoration <cablecell-decoration>`.
Mechanisms are described using a dialect of the :ref:`NMODL <nmodl>` domain
specific language that is similarly used in `NEURON <https://neuron.yale.edu/neuron/>`_.

Arbor supports mechanism descriptions using the NMODL language through our ``modcc``
compiler. ``modcc`` supports many of NMODL's features but there are a few
additional :ref:`guidelines <formatnmodl>`.
for users who wish to compile their own mechanisms for Arbor. Out-of-tree mechanism
building is available in Arbor (See: :ref:`mechanisms_dynamic`). We also have built-in
mechanisms, which are organized in *mechanism catalogues*.

Mechanism catalogues
--------------------

A *mechanism catalogue* is a collection of mechanisms that maintains:

1. A collection of mechanism metadata indexed by name.
2. A further hierarchy of *derived* mechanisms, that allow specialization of
   global parameters, ion bindings, and implementations.
3. A map for looking up a concrete mechanism implementation on a target hardware back end.

Derived mechanisms will always have a different name to the mechanism from which they are derived.
This name is given explicitly when the derivation is constructed, or implicitly when a mechanism
is :ref:`requested <mechanisms-name-note>` with a name of the form ``"mech/param=value,..."``.
In this instance, if a mechanism of that name does not already exist in the catalogue, it will be
implicitly derived from an existing mechanism ``"mech"`` with global parameters and ion bindings
set according to the assignments following the slash. If the mechanism ``"mech"`` depends upon
only a single ion, the name of that ion can be omitted in the assignments:
``"mech/oldion=newion"`` and ``"mech/newion"`` are equivalent derivations.

Catalogues provide an interface for querying mechanism metadata, which includes the following information:

* Global parameter names, units, and default values.
* Range parameter names, units, and default values.
* State variable names, units and default values.
* Ion dependencies: for each ion used by the mechanism, information on whether the mechanism writes
  to its internal or external concentration or to its reversal potential value, and whether it reads
  or asserts the ionic charge.

Arbor provides a default catalogue of mechanisms as well as two other catalogues containing the sets of common mechanisms
used by the `Allen Institute <https://alleninstitute.org/>`_ and the `Blue Brain Project <https://portal.bluebrain.epfl.ch/>`_.
(Find the NMODL descriptions of the `default mechanisms <https://github.com/arbor-sim/arbor/tree/master/mechanisms/default>`_,
the `Allen institute mechanisms <https://github.com/arbor-sim/arbor/tree/master/mechanisms/allen>`_ and
the `BBP mechanisms <https://github.com/arbor-sim/arbor/tree/master/mechanisms/bbp>`_ at the provided links.)

.. _mechanisms_builtins:

Built-in Catalogues
'''''''''''''''''''

Arbor provides the ``default_catalogue`` with the following mechanisms:

* *pas*: Leaky current (:ref:`density mechanism <mechanisms-density>`).
* *hh*: Classic Hodgkin-Huxley dynamics (:ref:`density mechanism
  <mechanisms-density>`).
* *nernst*: Calculate reversal potential for an ionic species using the Nernst
  equation (:ref:`reversal potential mechanism <mechanisms-revpot>`). **NB**
  This is not meant to be used directly
* *expsyn*: Synapse with discontinuous change in conductance at an event
  followed by an exponential decay (:ref:`point mechanism <mechanisms-point>`).
* *exp2syn*: Bi-exponential conductance synapse described by two time constants:
  rise and decay (:ref:`point mechanism <mechanisms-point>`).
* *gj*: Linear gap-junction mechanism with constant conductance (:ref:`junction mechanism <mechanisms-junction>`).

With the exception of *nernst*, these mechanisms are the same as those available in NEURON.

Two catalogues are provided that collect mechanisms associated with specific projects and model databases:

* ``bbp_catalogue`` For models published by the Blue Brain Project (BBP).
* ``allen_catalogue`` For models published on the Allen Brain Atlas Database.

.. _mechanisms_dynamic:

Adding Catalogues to Arbor
''''''''''''''''''''''''''

.. Note::

   If you are coming from NEURON this is the equivalent of ``nrnivmodl``.

This will produce a catalogue loadable at runtime by calling ``load_catalogue``
with a filename in both C++ and Python. The steps are

1. Prepare a directory containing your NMODL files (.mod suffixes required)
2. Call ``arbor-build-catalogue`` installed by arbor

   .. code-block :: bash

     arbor-build-catalogue <name> <path/to/nmodl>

All files with the suffix ``.mod`` located in ``<path/to/nmodl>`` will be baked
into a catalogue named ``lib<name>-catalogue.so`` and placed into your current
working directory. Note that these files are platform-specific and should only
be used on the combination of OS, compiler, arbor, and machine they were built
with. See our internal documentation for more advanced usage of the builder.
Errors might be diagnosable by passing the ``-v`` flag.

This catalogue can then be used similarly to the built-in ones

   .. code-block :: python

     import arbor as A

     c = A.load_catalogue('bbp2-catalogue.so')

     [n for n in c]
     >> ['Ca_LVAst',
         'Nap_Et2',
         'NaTa_t',
         'SKv3_1',
         'K_Tst',
         'Ih',
         'SK_E2',
         'Ca_HVA',
         'CaDynamics_E2',
         'Im',
         'NaTs2_t',
         'K_Pst']

See also the demonstration in ``python/example/dynamic-catalogue.py`` for an example.

Parameters
''''''''''

Mechanism behaviour can be tuned using parameters and ion channel dependencies,
as defined in the NMODL description.
Parameters and ion species are set initially before a simulation starts, and remain
unchanged thereafter, for the duration of the simulation.
There are two types of parameters that can be set by users:

* *Global* parameters are a single scalar value that is the same everywhere a mechanism is defined.
* *Range* parameters can vary spatially.

Every mechanism is applied to a cell via a *mechanism description*, a
``(name, range_parameters)`` tuple, where ``name`` is a string,
and ``range_parameters`` is an optional dictionary of key-value pairs
that specifies values for range parameters.
For example, consider a mechanism that models passive leaky dynamics with
the following parameters:

* *Name*: ``"pas"``.
* *Global parameter*: reversal potential ``e``, default -70 mV.
* *Range parameter*: conductance ``g``, default 0.001 S⋅cm⁻².

The following example mechanism descriptions for our passive mechanism show that parameters and
ion species dependencies only need to be specified when they differ from their defaults:

* ``("pas")``: the passive mechanism with default parameters.
* ``("pas/e=-80")``: derive a new passive mechanism with a non-default value for global parameter.
* ``("pas", {"g": 0.005})``: passive mechanism with a new a non-default range parameter value.
* ``("pas/e=-80", {"g": 0.005})``: derive a new passive mechanism that overrides both

Similarly to global parameters, ion species can be renamed in the mechanism name.
This allows the use of generic mechanisms that can be adapted to a specific species
during model instantiation.
For example, the ``nernst`` mechanism in Arbor's default mechanism catalogue calculates
the reversal potential of a generic ionic species ``x`` according to its internal
and external concentrations and valence. To specialize ``nernst`` for calcium name it
``("nernst/x=ca")``, or as there is only one ion species in the mechanism the
shorthand ``("nernst/ca")`` can be used unambiguously.

.. _mechanisms-name-note:

.. note::
    Global parameter values and ionic dependencies are the same for each instance of
    a mechanism; changing these requires the derivation of a new mechanism, implicitly or explicitly.
    For this reason, new global parameter values and ion renaming are part of the name of
    the new mechanism, or a mechanism with a new unique name must be defined.

Mechanism types
---------------

There are three broad categories of mechanism: density mechanisms, point mechanisms,
gap-junction mechanisms and a fourth special density mechanism for computing ionic
reversal potential.

.. _mechanisms-density:

Density mechanisms
''''''''''''''''''''''

Density mechanisms describe biophysical processes that are distributed in space,
but whose behaviour is defined purely by the state of the cell and the process
at any given point.

Density mechanisms are commonly used to describe ion channel dynamics,
for example the ``hh`` and ``pas`` mechanisms provided by NEURON and Arbor,
which model classic Hodgkin-Huxley and passive leaky currents respectively.

In NMODL, density mechanisms are identified using the ``SUFFIX`` keyword in the
``NEURON`` block.

.. _mechanisms-revpot:

Ion reversal potential mechanisms
'''''''''''''''''''''''''''''''''

These mechanisms, which describe ionic reversal potential
behaviour, can be specified for cells or the whole model.

The reversal potential of an ion species is calculated by an
optional *reversal potential mechanism*.
If no such mechanism is specified for an ion species, the initial
reversal potential values are maintained for the course of a simulation.
Otherwise, the mechanism does the work.

Reversal potential mechanisms are density mechanisms subject to some strict restrictions.
Specifically, a reversal potential mechanism described in NMODL:

* May not maintain any state variables.
* Can only write to the reversal potential (``eX``) value of the ion species.
* Can not be a :ref:`point mechanism <mechanisms-point>`.

Essentially, reversal potential mechanisms must be pure functions of cellular
and ionic state.

.. note::
    Arbor imposes greater restrictions on mechanisms that update ionic reversal potentials
    than NEURON. Doing so simplifies reasoning about interactions between
    mechanisms that share ionic species, by virtue of having one mechanism, and one
    mechanism only, that calculates reversal potentials according to concentrations
    that the other mechanisms use and modify.

.. _mechanisms-point:

Point mechanisms
''''''''''''''''

*Point mechanisms*, which are associated with connection end points on a
cable cell, are placed at discrete locations on the cell.
Unlike density mechanisms, whose behaviour is defined purely by the state of the cell
and the process, their behaviour is additionally governed by the timing and weight of
events delivered via incoming connections.

In NMODL, point mechanisms are identified using the ``POINT_PROCESS`` keyword in the
``NEURON`` block.

.. _mechanisms-junction:

Junction mechanisms
'''''''''''''''''''

*Junction mechanisms*, which are associated with gap-junction connection end points on a
cable cell, are placed at discrete locations on the cell.
A junction mechanism contributes a current at the discrete location of the cell on which it is placed.
This current contribution depends on the state of the mechanism and the process, as well as the membrane
potential at the discrete location which forms the other end of the gap-junction connection and the weight
of that connection.

In NMODL, junction mechanisms are identified using the ``JUNCTION_PROCESS`` keyword in the
``NEURON`` block.

.. note::
    ``JUNCTION_PROCESS`` is an Arbor-specific extension to NMODL. The NMODL description of gap-junction
    mechanisms in arbor is not identical to NEURON's though it is similar.

API
---

* :ref:`Python <py_mechanisms>`
* *TODO* C++ documentation.


text:
module Sequel
  module EmptyArrayIgnoreNulls
    # Use a simple expression that is always true or false, never NULL.
    def empty_array_value(op, cols)
      {1 => ((op == :IN) ? 0 : 1)}
    end

  end

  Dataset.register_extension(:empty_array_ignore_nulls, EmptyArrayIgnoreNulls)
end

redpajama_set_name: RedPajamaGithub


text:
module Guard
  class Alfred
    class Runner

      ##
      # Runs all the scenario's.
      #
      def run_all
        Bundler.with_clean_env { Kernel.system('bundle exec alfred') }
      end

      ##
      # Runs scenario's for controller paths.
      #
      def run(paths)
        return true if paths.empty?
        Bundler.with_clean_env { Kernel.system("bundle exec alfred #{paths.join(' ')}") }
      end

    end # Runner
  end # Alfred
end # Guard


text:
<?php

declare(strict_types=1);

namespace GrahamCampbell\TestBench;

use GrahamCampbell\TestBenchCore\HelperTrait;
use GrahamCampbell\TestBenchCore\LaravelTrait;
use GrahamCampbell\TestBenchCore\MockeryTrait;
use Illuminate\Foundation\Application;
use Orchestra\Database\MigrationServiceProvider;
use Orchestra\Testbench\TestCase;
use ReflectionClass;
use RuntimeException;

/**
 * This is the abstract app test case class.
 *
 * @author Graham Campbell <hello@gjcampbell.co.uk>
 */
abstract class AbstractAppTestCase extends TestCase
{
    use HelperTrait;
    use LaravelTrait;
    use MockeryTrait;

    /**
     * Get the base path.
     *
     * @return string
     */
    protected function getBasePath()
    {
        $class = new ReflectionClass($this);

        $parents = [];

        // get an array of all the parent classes
        while ($parent = $class->getParentClass()) {
            $parents[] = $parent->getName();
            $class = $parent;
        }

        // we want to select the penultimate class from the list of parents
        // this is because the class directly extending this must be the
        // abstract test case the user has used in their app
        $pos = count($parents) - 5;

        if ($pos < 0) {
            throw new RuntimeException('The base path could not be automatically determined.');
        }

        // get the reflection class for the selected class
        $selected = new ReflectionClass($parents[$pos]);

        // get the filepath of the selected class
        $path = $selected->getFileName();

        // return the filepath one up from the folder the selected class is saved in
        return realpath(dirname($path).'/../');
    }

    /**
     * Get application aliases.
     *
     * @param \Illuminate\Contracts\Foundation\Application $app
     *
     * @return array
     */
    protected function getApplicationAliases($app)
    {
        return $app->config['app.aliases'];
    }

    /**
     * Get application providers.
     *
     * @param \Illuminate\Contracts\Foundation\Application $app
     *
     * @return array
     */
    protected function getApplicationProviders($app)
    {
        if (class_exists(MigrationServiceProvider::class)) {
            return array_merge($app->config['app.providers'], [MigrationServiceProvider::class]);
        }

        return $app->config['app.providers'];
    }

    /**
     * Resolve application implementation.
     *
     * @return \Illuminate\Contracts\Foundation\Application
     */
    protected function resolveApplication()
    {
        return new Application($this->getBasePath());
    }

    /**
     * Get the service provider class.
     *
     * @return string
     */
    protected function getServiceProviderClass()
    {
        // this may be overwritten, and must be overwritten
        // if used with the service provider test case trait
    }
}


text:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<license-lookup xmlns="https://source.jasig.org/schemas/maven-notice-plugin/license-lookup" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="https://source.jasig.org/schemas/maven-notice-plugin/license-lookup https://source.jasig.org/schemas/maven-notice-plugin/license-lookup/license-lookup-v1.0.xsd">
    <artifact>
        <groupId>aredis.sourceforge.net</groupId>
        <artifactId>aredis-api</artifactId>
        <version>1.4</version>
        <license>Apache 2.0</license>
    </artifact>
    <artifact>
        <groupId>com.creditease.moniter</groupId>
        <artifactId>com.creditease.uav.monitorframework.buildComponent</artifactId>
        <version>1.0</version>
        <license>Apache 2.0</license>
    </artifact>
    <artifact>
        <groupId>com.creditease.moniter</groupId>
        <artifactId>com.creditease.uav.elasticsearch.client</artifactId>
        <version>1.0</version>
        <license>Apache 2.0</license>
    </artifact>
    <artifact>
        <groupId>avalon-framework</groupId>
        <artifactId>avalon-framework-api</artifactId>
        <version>4.3</version>
        <license>Apache 2.0</license>
    </artifact>
    <artifact>
        <groupId>avalon-logkit</groupId>
        <artifactId>avalon-logkit</artifactId>
        <version>2.1</version>
        <license>Apache 2.0</license>
    </artifact>
    <artifact>
        <groupId>celocaljar</groupId>
        <artifactId>catalina</artifactId>
        <version>1.0</version>
        <license>Apache 2.0</license>
    </artifact>
    <artifact>
        <groupId>celocaljar</groupId>
        <artifactId>tomcat-coyote</artifactId>
        <version>1.0</version>
        <license>Apache 2.0</license>
    </artifact>
    <artifact>
        <groupId>celocaljar</groupId>
        <artifactId>tomcat-juli</artifactId>
        <version>1.0</version>
        <license>Apache 2.0</license>
    </artifact>
    <artifact>
        <groupId>com.alibaba</groupId>
        <artifactId>druid</artifactId>
        <version>1.0.0</version>
        <license>Apache 2.0</license>
    </artifact>
    <artifact>
        <groupId>com.creditease.moniter</groupId>
        <artifactId>com.creditease.uav.base</artifactId>
        <version>1.0</version>
        <license>Apache 2.0</license>
    </artifact>
    <artifact>
        <groupId>com.creditease.moniter</groupId>
        <artifactId>com.creditease.uav.cache.redis</artifactId>
        <version>1.0</version>
        <license>Apache 2.0</license>
    </artifact>
    <artifact>
        <groupId>com.creditease.moniter</groupId>
        <artifactId>com.creditease.uav.monitorframework.buildComponent</artifactId>
        <version>1.0</version>
        <license>Apache 2.0</license>
    </artifact>
    <artifact>
        <groupId>geronimo-spec</groupId>
        <artifactId>geronimo-spec-javamail</artifactId>
        <version>1.3.1-rc3</version>
        <license>Apache 2.0</license>
    </artifact>
    <artifact>
        <groupId>geronimo-spec</groupId>
        <artifactId>geronimo-spec-jms</artifactId>
        <version>1.1-rc4</version>
        <license>Apache 2.0</license>
    </artifact>
    <artifact>
        <groupId>jetty</groupId>
        <artifactId>jetty-deploy</artifactId>
        <version>1.0</version>
        <license>Apache 2.0</license>
    </artifact>
    <artifact>
        <groupId>jetty</groupId>
        <artifactId>jetty-server</artifactId>
        <version>1.0</version>
        <license>Apache 2.0</license>
    </artifact>
    <artifact>
        <groupId>jetty</groupId>
        <artifactId>jetty-servlet</artifactId>
        <version>1.0</version>
        <license>Apache 2.0</license>
    </artifact>
    <artifact>
        <groupId>jetty</groupId>
        <artifactId>jetty-util</artifactId>
        <version>1.0</version>
        <license>Apache 2.0</license>
    </artifact>
    <artifact>
        <groupId>jetty</groupId>
        <artifactId>jetty-webapp</artifactId>
        <version>1.0</version>
        <license>Apache 2.0</license>
    </artifact>
    <artifact>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>3.8.1</version>
        <license>Apache 2.0</license>
    </artifact>
    <artifact>
        <groupId>log4j</groupId>
        <artifactId>log4j</artifactId>
        <version>1.2.11</version>
        <license>Apache 2.0</license>
    </artifact>
</license-lookup>


text:
using System;
using System.ComponentModel.Composition;
using System.Threading.Tasks;

using Microsoft.AnalysisServices.Tabular;

using Microsoft.Deployment.Common.ActionModel;
using Microsoft.Deployment.Common.Actions;

namespace Microsoft.Deployment.Actions.AzureCustom.AzureAS
{
    [Export(typeof(IAction))]
    public class AssignPermissionsForUser : BaseAction
    {
        public override async Task<ActionResponse> ExecuteActionAsync(ActionRequest request)
        {
            var azureToken = request.DataStore.GetJson("AzureTokenAS");
            string serverUrl = request.DataStore.GetValue("ASServerUrl");
            string asDatabase = request.DataStore.GetValue("ASDatabase");
            string user = request.DataStore.GetValue("UserToAdd");
            string connectionString = ValidateConnectionToAS.GetASConnectionString(request, azureToken, serverUrl);

            Server server = null;
            try
            {
                server = new Server();
                server.Connect(connectionString);

                Database db = server.Databases.FindByName(asDatabase);
                if (db == null)
                {
                    return new ActionResponse(ActionStatus.Failure, string.Empty, null, null, "Unable to find model");
                }

                var role = new ModelRole()
                {
                    Name = "ProcessOnlyRole"
                };

                role.ModelPermission = ModelPermission.Administrator;
                ExternalModelRoleMember member = new ExternalModelRoleMember();
                member.IdentityProvider = "AzureAD";
                member.MemberName = user;
                //AzureAD
                role.Members.Add(member);

                db.Model.Roles.Add(role);
                db.Model.SaveChanges();
                server.Disconnect(true);

                return new ActionResponse(ActionStatus.Success);
            }
            catch (Exception e)
            {
                return new ActionResponse(ActionStatus.Failure, string.Empty, e, null, "Unable to assign permissions");
            }
            finally
            {
                server?.Dispose();
            }

        }
    }
}


text:
package org.elasticsearch.index.query;

import org.apache.lucene.index.Term;
import org.apache.lucene.search.MultiTermQuery;
import org.apache.lucene.search.PrefixQuery;
import org.apache.lucene.search.Query;
import org.elasticsearch.common.inject.Inject;
import org.elasticsearch.common.xcontent.XContentParser;
import org.elasticsearch.index.mapper.MapperService;
import org.elasticsearch.index.query.support.QueryParsers;

import java.io.IOException;

import static org.elasticsearch.index.query.support.QueryParsers.wrapSmartNameQuery;

/**
 *
 */
public class PrefixQueryParser implements QueryParser {

    public static final String NAME = "prefix";

    @Inject
    public PrefixQueryParser() {
    }

    @Override
    public String[] names() {
        return new String[]{NAME};
    }

    @Override
    public Query parse(QueryParseContext parseContext) throws IOException, QueryParsingException {
        XContentParser parser = parseContext.parser();

        XContentParser.Token token = parser.nextToken();
        if (token != XContentParser.Token.FIELD_NAME) {
            throw new QueryParsingException(parseContext.index(), "[prefix] query malformed, no field");
        }
        String fieldName = parser.currentName();
        String rewriteMethod = null;

        String value = null;
        float boost = 1.0f;
        token = parser.nextToken();
        if (token == XContentParser.Token.START_OBJECT) {
            String currentFieldName = null;
            while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) {
                if (token == XContentParser.Token.FIELD_NAME) {
                    currentFieldName = parser.currentName();
                } else if (token.isValue()) {
                    if ("prefix".equals(currentFieldName)) {
                        value = parser.text();
                    } else if ("value".equals(currentFieldName)) {
                        value = parser.text();
                    } else if ("boost".equals(currentFieldName)) {
                        boost = parser.floatValue();
                    } else if ("rewrite".equals(currentFieldName)) {
                        rewriteMethod = parser.textOrNull();
                    }
                } else {
                    throw new QueryParsingException(parseContext.index(), "[prefix] query does not support [" + currentFieldName + "]");
                }
            }
            parser.nextToken();
        } else {
            value = parser.text();
            parser.nextToken();
        }

        if (value == null) {
            throw new QueryParsingException(parseContext.index(), "No value specified for prefix query");
        }

        MultiTermQuery.RewriteMethod method = QueryParsers.parseRewriteMethod(rewriteMethod, null);

        Query query = null;
        MapperService.SmartNameFieldMappers smartNameFieldMappers = parseContext.smartFieldMappers(fieldName);
        if (smartNameFieldMappers != null && smartNameFieldMappers.hasMapper()) {
            if (smartNameFieldMappers.explicitTypeInNameWithDocMapper()) {
                String[] previousTypes = QueryParseContext.setTypesWithPrevious(new String[]{smartNameFieldMappers.docMapper().type()});
                try {
                    query = smartNameFieldMappers.mapper().prefixQuery(value, method, parseContext);
                } finally {
                    QueryParseContext.setTypes(previousTypes);
                }
            } else {
                query = smartNameFieldMappers.mapper().prefixQuery(value, method, parseContext);
            }
        }
        if (query == null) {
            PrefixQuery prefixQuery = new PrefixQuery(new Term(fieldName, value));
            prefixQuery.setRewriteMethod(method);
            query = prefixQuery;
        }
        query.setBoost(boost);
        return wrapSmartNameQuery(query, smartNameFieldMappers, parseContext);
    }
}


text:
import pickle
from io import BytesIO
from unittest import TestCase

import numpy as np
from numpy.testing import assert_array_almost_equal
from scipy import linalg
from nose.tools import assert_true

from pykalman import KalmanFilter
from pykalman.datasets import load_robot

class KalmanFilterTests(object):
    """All of the actual tests to check against an implementation of the usual
    Kalman Filter. Abstract so that sister implementations can re-use these
    tests.
    """

    def test_kalman_sampling(self):
        kf = self.KF(
            self.data.transition_matrix,
            self.data.observation_matrix,
            self.data.transition_covariance,
            self.data.observation_covariance,
            self.data.transition_offsets,
            self.data.observation_offset,
            self.data.initial_state_mean,
            self.data.initial_state_covariance)

        (x, z) = kf.sample(100)
        assert_true(x.shape == (100, self.data.transition_matrix.shape[0]))
        assert_true(z.shape == (100, self.data.observation_matrix.shape[0]))

    def test_kalman_filter_update(self):
        kf = self.KF(
            self.data.transition_matrix,
            self.data.observation_matrix,
            self.data.transition_covariance,
            self.data.observation_covariance,
            self.data.transition_offsets,
            self.data.observation_offset,
            self.data.initial_state_mean,
            self.data.initial_state_covariance)

        # use Kalman Filter
        (x_filt, V_filt) = kf.filter(X=self.data.observations)

        # use online Kalman Filter
        n_timesteps = self.data.observations.shape[0]
        n_dim_obs, n_dim_state = self.data.observation_matrix.shape
        kf2 = self.KF(n_dim_state=n_dim_state, n_dim_obs=n_dim_obs)
        x_filt2 = np.zeros((n_timesteps, n_dim_state))
        V_filt2 = np.zeros((n_timesteps, n_dim_state, n_dim_state))
        for t in range(n_timesteps - 1):
            if t == 0:
                x_filt2[0] = self.data.initial_state_mean
                V_filt2[0] = self.data.initial_state_covariance
            (x_filt2[t + 1], V_filt2[t + 1]) = kf2.filter_update(
                x_filt2[t], V_filt2[t],
                observation=self.data.observations[t + 1],
                transition_matrix=self.data.transition_matrix,
                transition_offset=self.data.transition_offsets[t],
                transition_covariance=self.data.transition_covariance,
                observation_matrix=self.data.observation_matrix,
                observation_offset=self.data.observation_offset,
                observation_covariance=self.data.observation_covariance
            )
        assert_array_almost_equal(x_filt, x_filt2)
        assert_array_almost_equal(V_filt, V_filt2)

    def test_kalman_filter(self):
        kf = self.KF(
            self.data.transition_matrix,
            self.data.observation_matrix,
            self.data.transition_covariance,
            self.data.observation_covariance,
            self.data.transition_offsets,
            self.data.observation_offset,
            self.data.initial_state_mean,
            self.data.initial_state_covariance)

        (x_filt, V_filt) = kf.filter(X=self.data.observations)
        assert_array_almost_equal(
            x_filt[:500],
            self.data.filtered_state_means[:500],
            decimal=7
        )
        assert_array_almost_equal(
            V_filt[:500],
            self.data.filtered_state_covariances[:500],
            decimal=7
        )

    def test_kalman_predict(self):
        kf = self.KF(
            self.data.transition_matrix,
            self.data.observation_matrix,
            self.data.transition_covariance,
            self.data.observation_covariance,
            self.data.transition_offsets,
            self.data.observation_offset,
            self.data.initial_state_mean,
            self.data.initial_state_covariance)

        x_smooth = kf.smooth(X=self.data.observations)[0]
        assert_array_almost_equal(
            x_smooth[:501],
            self.data.smoothed_state_means[:501],
            decimal=7
        )

    def test_kalman_fit(self):
        # check against MATLAB dataset
        kf = self.KF(
            self.data.transition_matrix,
            self.data.observation_matrix,
            self.data.initial_transition_covariance,
            self.data.initial_observation_covariance,
            self.data.transition_offsets,
            self.data.observation_offset,
            self.data.initial_state_mean,
            self.data.initial_state_covariance,
            em_vars=['transition_covariance', 'observation_covariance'])

        loglikelihoods = np.zeros(5)
        for i in range(len(loglikelihoods)):
            loglikelihoods[i] = kf.loglikelihood(self.data.observations)
            kf.em(X=self.data.observations, n_iter=1)

        assert_true(np.allclose(loglikelihoods, self.data.loglikelihoods[:5]))

        # check that EM for all parameters is working
        kf.em_vars = 'all'
        n_timesteps = 30
        for i in range(len(loglikelihoods)):
            kf.em(X=self.data.observations[0:n_timesteps], n_iter=1)
            loglikelihoods[i] = kf.loglikelihood(self.data.observations[0:n_timesteps])
        for i in range(len(loglikelihoods) - 1):
            assert_true(loglikelihoods[i] < loglikelihoods[i + 1])

    def test_kalman_initialize_parameters(self):
        self.check_dims(5, 1, {'transition_matrices': np.eye(5)})
        self.check_dims(1, 3, {'observation_offsets': np.zeros(3)})
        self.check_dims(2, 3, {'transition_covariance': np.eye(2),
                          'observation_offsets': np.zeros(3)})
        self.check_dims(3, 2, {'n_dim_state': 3, 'n_dim_obs': 2})
        self.check_dims(4, 1, {'initial_state_mean': np.zeros(4)})

    def check_dims(self, n_dim_state, n_dim_obs, kwargs):
        kf = self.KF(**kwargs)
        (transition_matrices, transition_offsets, transition_covariance,
         observation_matrices, observation_offsets, observation_covariance,
         initial_state_mean, initial_state_covariance) = (
            kf._initialize_parameters()
        )
        assert_true(transition_matrices.shape == (n_dim_state, n_dim_state))
        assert_true(transition_offsets.shape == (n_dim_state,))
        assert_true(transition_covariance.shape == (n_dim_state, n_dim_state))
        assert_true(observation_matrices.shape == (n_dim_obs, n_dim_state))
        assert_true(observation_offsets.shape == (n_dim_obs,))
        assert_true(observation_covariance.shape == (n_dim_obs, n_dim_obs))
        assert_true(initial_state_mean.shape == (n_dim_state,))
        assert_true(
            initial_state_covariance.shape == (n_dim_state, n_dim_state)
        )

    def test_kalman_pickle(self):
        kf = self.KF(
            self.data.transition_matrix,
            self.data.observation_matrix,
            self.data.transition_covariance,
            self.data.observation_covariance,
            self.data.transition_offsets,
            self.data.observation_offset,
            self.data.initial_state_mean,
            self.data.initial_state_covariance,
            em_vars='all')

        # train and get log likelihood
        X = self.data.observations[0:10]
        kf = kf.em(X, n_iter=5)
        loglikelihood = kf.loglikelihood(X)

        # pickle Kalman Filter
        store = BytesIO()
        pickle.dump(kf, store)
        clf = pickle.load(BytesIO(store.getvalue()))

        # check that parameters came out already
        np.testing.assert_almost_equal(loglikelihood, kf.loglikelihood(X))

class KalmanFilterTestSuite(TestCase, KalmanFilterTests):
    """Class that nose can pick up on to actually run Kalman Filter tests
    against default implementation.
    """

    def setUp(self):
        self.KF = KalmanFilter
        self.data = load_robot()


text:
class BrowserContextDependencyManager;
class Profile;

namespace web_app {

class WebAppProviderBase;

// Singleton that associates WebAppProviderBase with Profile.
class WebAppProviderBaseFactory : public BrowserContextKeyedServiceFactory {
 public:
  static WebAppProviderBase* GetForProfile(Profile* profile);

  static WebAppProviderBaseFactory* GetInstance();
  static void SetInstance(WebAppProviderBaseFactory* factory);

 protected:
  WebAppProviderBaseFactory(
      const char* service_name,
      BrowserContextDependencyManager* dependency_manager);
  ~WebAppProviderBaseFactory() override;

  DISALLOW_COPY_AND_ASSIGN(WebAppProviderBaseFactory);
};

}  // namespace web_app

#endif  // CHROME_BROWSER_WEB_APPLICATIONS_COMPONENTS_WEB_APP_PROVIDER_BASE_FACTORY_H_


text:
namespace AbpKendoDemo.Migrations
{
    using System;
    using System.Data.Entity.Migrations;

    public partial class Changed_Code_MaxLength_Of_OrganizationUnit : DbMigration
    {
        public override void Up()
        {
            DropIndex("dbo.AbpOrganizationUnits", new[] { "TenantId", "Code" });
            AlterColumn("dbo.AbpOrganizationUnits", "Code", c => c.String(nullable: false, maxLength: 95));
            CreateIndex("dbo.AbpOrganizationUnits", new[] { "TenantId", "Code" });
        }

        public override void Down()
        {
            DropIndex("dbo.AbpOrganizationUnits", new[] { "TenantId", "Code" });
            AlterColumn("dbo.AbpOrganizationUnits", "Code", c => c.String(nullable: false, maxLength: 128));
            CreateIndex("dbo.AbpOrganizationUnits", new[] { "TenantId", "Code" });
        }
    }
}


text: export * from './example-doc.component';


text:
package org.wintersleep.util.spring.plugin;

import org.springframework.beans.factory.xml.NamespaceHandlerSupport;

public class PluginNamespaceHandler extends NamespaceHandlerSupport {

    public void init() {
        registerBeanDefinitionParser("extension-point", new ExtensionPointBeanDefinitionParser());
        registerBeanDefinitionParser("register", new RegisterExtensionBeanDefinitionParser());
    }

}


text:
<faction>
    <character>
        <name>Akimoto</name>
        <mini>akimotoMini.jpg</mini>
        <card>akimotoCard.jpg</card>
    </character>

    <character>
        <name>Ayako</name>
        <mini>ayakoMini.jpg</mini>
        <card>ayakoCard.jpg</card>
    </character>

    <character>
        <name>Chiyo</name>
        <mini>chiyoMini.jpg</mini>
        <card>chiyoCard.jpg</card>
    </character>

    <character>
        <name>Hitoshi</name>
        <mini>hitoshiMini.jpg</mini>
        <card>hitoshiCard.jpg</card>
    </character>

    <character>
        <name>Itsunagi</name>
        <mini>itsunagiMini.jpg</mini>
        <card>itsunagiCard.jpg</card>
    </character>

    <character>
        <name>Jade Mamba Guard</name>
        <mini>jadeMambaGuardMini.jpg</mini>
        <card>jadeMambaGuardCard.jpg</card>
    </character>

    <character>
        <name>Kaihime</name>
        <mini>kaihimeMini.jpg</mini>
        <card>kaihimeCard.jpg</card>
    </character>

    <character>
        <name>Kazuhiko</name>
        <mini>kazuhikoMini.jpg</mini>
        <card>kazuhikoCard.jpg</card>
    </character>

    <character>
        <name>Kenzo</name>
        <mini>kenzoMini.jpg</mini>
        <card>kenzoCard.jpg</card>
    </character>

    <character>
        <name>Masunagi Ito</name>
        <mini>masunagiMini.jpg</mini>
        <card>masunagiCard.jpg</card>
    </character>

    <character>
        <name>Naoko</name>
        <mini>naokoMini.jpg</mini>
        <card>naokoCard.jpg</card>
    </character>

    <character>
        <name>Sakura</name>
        <mini>sakuraMini.jpg</mini>
        <card>sakuraCard.jpg</card>
    </character>

    <character>
        <name>Satoshi</name>
        <mini>satoshiMini.jpg</mini>
        <card>satoshiCard.jpg</card>
    </character>

    <character>
        <name>Takeji</name>
        <mini>takejiMini.jpg</mini>
        <card>takejiCard.jpg</card>
    </character>

    <character>
        <name>Temple Bushi</name>
        <mini>templeBushiMini.jpg</mini>
        <card>templeBushiCard.jpg</card>
    </character>

    <character>
        <name>Yukio</name>
        <mini>yukioMini.jpg</mini>
        <card>yukioCard.jpg</card>
    </character>

  <character>
    <name>Yatsumata</name>
    <mini>yatsumataMini.jpg</mini>
    <card>yatsumataCard.jpg</card>
  </character>

  <character>
    <name>Golden
sentinel</name>
    <mini>goldenSentinelMini.jpg</mini>
    <card>goldenSentinelCard.jpg</card>
  </character>

  <character>
    <name>Saburo</name>
    <mini>saburoMini.jpg</mini>
    <card>saburoCard.jpg</card>
  </character>

  <character>
    <name>Satsuki</name>
    <mini>satsukiMini.jpg</mini>
    <card>satsukiCard.jpg</card>
  </character>

  <character>
    <name>Mizuki Ito</name>
    <card>mizukiCard.jpg</card>
  </character>

</faction>


text:
public class jiangjinhui_Hello
{

	/**
	 * @param args
	 */
	public static void main(String[] args)
	{
		// TODO Auto-generated method stub

		System.out.println("hello world");
	}

}


text:
#ifndef PORT_PROTOS_H
#define PORT_PROTOS_H

#include <dlfcn.h>
#include "utils/dynamic_loader.h"

/*
 * In some older systems, the RTLD_NOW flag isn't defined and the mode
 * argument to dlopen must always be 1.  The RTLD_GLOBAL flag is wanted
 * if available, but it doesn't exist everywhere.
 * If it doesn't exist, set it to 0 so it has no effect.
 */
#ifndef RTLD_NOW
#define RTLD_NOW 1
#endif
#ifndef RTLD_GLOBAL
#define RTLD_GLOBAL 0
#endif

#define pg_dlopen(f)	dlopen((f), RTLD_NOW | RTLD_GLOBAL)
#define pg_dlsym		dlsym
#define pg_dlclose		dlclose
#define pg_dlerror		dlerror

#endif   /* PORT_PROTOS_H */


text:
/* Office JavaScript API library */
/* Version: 16.0.3825.1000 */
/*
	Copyright (c) Microsoft Corporation.  All rights reserved.
*/

/*
	Your use of this file is governed by the Microsoft Services Agreement http://go.microsoft.com/fwlink/?LinkId=266419.
*/

var OSF = OSF || {};

OSF.HostSpecificFileVersion = "16.00";

OSF.SupportedLocales = {
    "ar-sa": true,
    "bg-bg": true,
    "ca-es": true,
    "cs-cz": true,
    "da-dk": true,
    "de-de": true,
    "el-gr": true,
    "en-us": true,
    "es-es": true,
    "et-ee": true,
    "eu-es": true,
    "fi-fi": true,
    "fr-fr": true,
    "gl-es": true,
    "he-il": true,
    "hi-in": true,
    "hr-hr": true,
    "hu-hu": true,
    "id-id": true,
    "it-it": true,
    "ja-jp": true,
    "kk-kz": true,
    "ko-kr": true,
    "lt-lt": true,
    "lv-lv": true,
    "ms-my": true,
    "nb-no": true,
    "nl-nl": true,
    "pl-pl": true,
    "pt-br": true,
    "pt-pt": true,
    "ro-ro": true,
    "ru-ru": true,
    "sk-sk": true,
    "sl-si": true,
    "sr-cyrl-cs": true,
    "sr-cyrl-rs": true,
    "sr-latn-cs": true,
    "sr-latn-rs": true,
    "sv-se": true,
    "th-th": true,
    "tr-tr": true,
    "uk-ua": true,
    "vi-vn": true,
    "zh-cn": true,
    "zh-tw": true
};

OSF.AssociatedLocales = {
    ar: "ar-sa",
    bg: "bg-bg",
    ca: "ca-es",
    cs: "cs-cz",
    da: "da-dk",
    de: "de-de",
    el: "el-gr",
    en: "en-us",
    es: "es-es",
    et: "et-ee",
    eu: "eu-es",
    fi: "fi-fi",
    fr: "fr-fr",
    gl: "gl-es",
    he: "he-il",
    hi: "hi-in",
    hr: "hr-hr",
    hu: "hu-hu",
    id: "id-id",
    it: "it-it",
    ja: "ja-jp",
    kk: "kk-kz",
    ko: "ko-kr",
    lt: "lt-lt",
    lv: "lv-lv",
    ms: "ms-my",
    nb: "nb-no",
    nl: "nl-nl",
    pl: "pl-pl",
    pt: "pt-br",
    ro: "ro-ro",
    ru: "ru-ru",
    sk: "sk-sk",
    sl: "sl-si",
    sr: "sr-cyrl-cs",
    sv: "sv-se",
    th: "th-th",
    tr: "tr-tr",
    uk: "uk-ua",
    vi: "vi-vn",
    zh: "zh-cn"
};
OSF.ConstantNames = {
    HostSpecificFallbackVersion: OSF.HostSpecificFileVersion,
    OfficeJS: "office.js",
    OfficeDebugJS: "office.debug.js",
    DefaultLocale: "en-us",
    LocaleStringLoadingTimeout: 2000,
    OfficeStringJS: "office_strings.debug.js",
    O15InitHelper: "o15apptofilemappingtable.debug.js",
    SupportedLocales: OSF.SupportedLocales,
    AssociatedLocales: OSF.AssociatedLocales
};

OSF.InitializationHelper = function OSF_InitializationHelper(hostInfo, webAppState, context, settings, hostFacade) {
    this._hostInfo = hostInfo;
    this._webAppState = webAppState;
    this._context = context;
    this._settings = settings;
    this._hostFacade = hostFacade;
};
OSF.InitializationHelper.prototype.getAppContext = function OSF_InitializationHelper$getAppContext(wnd, gotAppContext) {
};
OSF.InitializationHelper.prototype.setAgaveHostCommunication = function OSF_InitializationHelper$setAgaveHostCommunication() {
};
OSF.InitializationHelper.prototype.prepareRightBeforeWebExtensionInitialize = function OSF_InitializationHelper$prepareRightBeforeWebExtensionInitialize(appContext) {
};
OSF.InitializationHelper.prototype.loadAppSpecificScriptAndCreateOM = function OSF_InitializationHelper$loadAppSpecificScriptAndCreateOM(appContext, appReady, basePath) {
};

OSF._OfficeAppFactory = (function OSF__OfficeAppFactory() {
    var _setNamespace = function OSF_OUtil$_setNamespace(name, parent) {
        if (parent && name && !parent[name]) {
            parent[name] = {};
        }
    };
    _setNamespace("Office", window);
    _setNamespace("Microsoft", window);
    _setNamespace("Office", Microsoft);
    _setNamespace("WebExtension", Microsoft.Office);
    window.Office = Microsoft.Office.WebExtension;
    var _context = {};
    var _settings = {};
    var _hostFacade = {};
    var _WebAppState = { id: null, webAppUrl: null, conversationID: null, clientEndPoint: null, wnd: window.parent, focused: false };
    var _hostInfo = { isO15: true, isRichClient: true, hostType: "", hostPlatform: "", hostSpecificFileVersion: "" };
    var _initializationHelper = {};
    var _appInstanceId = null;

    var _windowLocationHash = window.location.hash;
    var _parseHostInfo = function OSF__OfficeAppFactory$_parseHostInfo() {
        var hostInfoValue;
        var hostInfo = "_host_Info=";
        var searchString = window.location.search;
        if (searchString) {
            var hostInfoParts = searchString.split(hostInfo);
            if (hostInfoParts.length > 1) {
                var hostInfoValueRestString = hostInfoParts[1];
                var separatorRegex = new RegExp("/[&#]/g");
                var hostInfoValueParts = hostInfoValueRestString.split(separatorRegex);
                if (hostInfoValueParts.length > 0) {
                    hostInfoValue = hostInfoValueParts[0];
                }
            }
        }
        return hostInfoValue;
    };
    var _loadScript = function OSF_OUtil$_loadScript(url, callback, timeoutInMs) {
        var loadedScripts = {};
        var defaultScriptLoadingTimeout = 30000;
        if (url && callback) {
            var doc = window.document;
            var loadedScriptEntry = loadedScripts[url];
            if (!loadedScriptEntry) {
                var script = doc.createElement("script");
                script.type = "text/javascript";
                loadedScriptEntry = { loaded: false, pendingCallbacks: [callback], timer: null };
                loadedScripts[url] = loadedScriptEntry;
                var onLoadCallback = function OSF_OUtil_loadScript$onLoadCallback() {
                    if (loadedScriptEntry.timer != null) {
                        clearTimeout(loadedScriptEntry.timer);
                        delete loadedScriptEntry.timer;
                    }
                    loadedScriptEntry.loaded = true;
                    var pendingCallbackCount = loadedScriptEntry.pendingCallbacks.length;
                    for (var i = 0; i < pendingCallbackCount; i++) {
                        var currentCallback = loadedScriptEntry.pendingCallbacks.shift();
                        currentCallback();
                    }
                };
                var onLoadError = function OSF_OUtil_loadScript$onLoadError() {
                    delete loadedScripts[url];
                    if (loadedScriptEntry.timer != null) {
                        clearTimeout(loadedScriptEntry.timer);
                        delete loadedScriptEntry.timer;
                    }
                    var pendingCallbackCount = loadedScriptEntry.pendingCallbacks.length;
                    for (var i = 0; i < pendingCallbackCount; i++) {
                        var currentCallback = loadedScriptEntry.pendingCallbacks.shift();
                        currentCallback();
                    }
                };
                if (script.readyState) {
                    script.onreadystatechange = function () {
                        if (script.readyState == "loaded" || script.readyState == "complete") {
                            script.onreadystatechange = null;
                            onLoadCallback();
                        }
                    };
                } else {
                    script.onload = onLoadCallback;
                }
                script.onerror = onLoadError;

                timeoutInMs = timeoutInMs || defaultScriptLoadingTimeout;
                loadedScriptEntry.timer = setTimeout(onLoadError, timeoutInMs);
                script.src = url;
                doc.getElementsByTagName("head")[0].appendChild(script);
            } else if (loadedScriptEntry.loaded) {
                callback();
            } else {
                loadedScriptEntry.pendingCallbacks.push(callback);
            }
        }
    };
    var _retrieveHostInfo = function OSF__OfficeAppFactory$_retrieveHostInfo() {
        var hostInfoValue = _parseHostInfo();
        var getSessionStorage = function OSF__OfficeAppFactory$_retrieveHostInfo$getSessionStorage() {
            var osfSessionStorage = null;
            try  {
                if (window.sessionStorage) {
                    osfSessionStorage = window.sessionStorage;
                }
            } catch (ex) {
            }
            return osfSessionStorage;
        };
        var osfSessionStorage = getSessionStorage();
        if (!hostInfoValue && osfSessionStorage && osfSessionStorage.getItem("hostInfoValue")) {
            hostInfoValue = osfSessionStorage.getItem("hostInfoValue");
        }
        if (hostInfoValue) {
            _hostInfo.isO15 = false;
            var items = hostInfoValue.split("$");
            if (typeof items[2] == "undefined") {
                items = hostInfoValue.split("|");
            }
            _hostInfo.hostType = items[0];
            _hostInfo.hostPlatform = items[1];
            _hostInfo.hostSpecificFileVersion = items[2];
            var hostSpecificFileVersionValue = parseFloat(_hostInfo.hostSpecificFileVersion);

            if (hostSpecificFileVersionValue > OSF.ConstantNames.HostSpecificFallbackVersion) {
                _hostInfo.hostSpecificFileVersion = OSF.ConstantNames.HostSpecificFallbackVersion.toString();
            }
            if (osfSessionStorage) {
                try  {
                    osfSessionStorage.setItem("hostInfoValue", hostInfoValue);
                } catch (e) {
                }
            }
        } else {
            _hostInfo.isO15 = true;
        }
    };
    var getAppContextAsync = function OSF__OfficeAppFactory$getAppContextAsync(wnd, gotAppContext) {
        _initializationHelper.getAppContext(wnd, gotAppContext);
    };
    var initialize = function OSF__OfficeAppFactory$initialize() {
        _retrieveHostInfo();
        var getScriptBase = function OSF__OfficeAppFactory_initialize$getScriptBase(scriptSrc, scriptNameToCheck) {
            var scriptBase, indexOfJS, scriptSrcLowerCase;
            scriptSrcLowerCase = scriptSrc.toLowerCase();
            indexOfJS = scriptSrcLowerCase.indexOf(scriptNameToCheck);
            if (indexOfJS >= 0 && indexOfJS === (scriptSrc.length - scriptNameToCheck.length) && (indexOfJS === 0 || scriptSrc.charAt(indexOfJS - 1) === '/' || scriptSrc.charAt(indexOfJS - 1) === '\\')) {
                scriptBase = scriptSrc.substring(0, indexOfJS);
            }
            return scriptBase;
        };
        var scripts = document.getElementsByTagName("script");
        var scriptsCount = scripts.length;
        var officeScripts = [OSF.ConstantNames.OfficeJS, OSF.ConstantNames.OfficeDebugJS];
        var officeScriptsCount = officeScripts.length;
        var i, j, basePath;
        for (i = 0; !basePath && i < scriptsCount; i++) {
            if (scripts[i].src) {
                for (j = 0; !basePath && j < officeScriptsCount; j++) {
                    basePath = getScriptBase(scripts[i].src, officeScripts[j]);
                }
            }
        }
        if (!basePath)
            throw "Office Web Extension script library file name should be " + OSF.ConstantNames.OfficeJS + " or " + OSF.ConstantNames.OfficeDebugJS + ".";
        var numberOfTimeForMsAjaxTries = 500;
        var timerId;
        var loadLocaleStringsAndAppSpecificCode = function OSF__OfficeAppFactory_initialize$loadLocaleStringsAndAppSpecificCode() {
            if (typeof (Sys) !== 'undefined' && typeof (Type) !== 'undefined' && Sys.StringBuilder && typeof (Sys.StringBuilder) === "function" && Type.registerNamespace && typeof (Type.registerNamespace) === "function" && Type.registerClass && typeof (Type.registerClass) === "function") {
                _initializationHelper = new OSF.InitializationHelper(_hostInfo, _WebAppState, _context, _settings, _hostFacade);
                _initializationHelper.setAgaveHostCommunication();
                getAppContextAsync(_WebAppState.wnd, function (appContext) {
                    _appInstanceId = appContext._appInstanceId;
                    var postLoadLocaleStringInitialization = function OSF__OfficeAppFactory_initialize$postLoadLocaleStringInitialization() {
                        var retryNumber = 100;
                        var t;
                        function appReady() {
                            if (Microsoft.Office.WebExtension.initialize != undefined) {
                                _initializationHelper.prepareRightBeforeWebExtensionInitialize(appContext);
                                if (t != undefined)
                                    window.clearTimeout(t);
                            } else if (retryNumber == 0) {
                                clearTimeout(t);
                                throw "Office.js has not been fully loaded yet. Please try again later or make sure to add your initialization code on the Office.initialize function.";
                            } else {
                                retryNumber--;
                                t = window.setTimeout(appReady, 100);
                            }
                        }
                        ;
                        _initializationHelper.loadAppSpecificScriptAndCreateOM(appContext, appReady, basePath);
                    };
                    var getSupportedLocale = function OSF__OfficeAppFactory_initialize$getSupportedLocale(locale) {
                        if (!locale) {
                            return OSF.ConstantNames.DefaultLocale;
                        }
                        var supportedLocale;
                        locale = locale.toLowerCase();
                        if (locale in OSF.ConstantNames.SupportedLocales) {
                            supportedLocale = locale;
                        } else {
                            var localeParts = locale.split('-', 1);
                            if (localeParts && localeParts.length > 0) {
                                supportedLocale = OSF.ConstantNames.AssociatedLocales[localeParts[0]];
                            }
                        }
                        if (!supportedLocale) {
                            supportedLocale = OSF.ConstantNames.DefaultLocale;
                        }
                        return supportedLocale;
                    };
                    var fallbackLocaleTried = false;
                    var loadLocaleStringCallback = function OSF__OfficeAppFactory_initialize$loadLocaleStringCallback() {
                        if (typeof Strings == 'undefined' || typeof Strings.OfficeOM == 'undefined') {
                            if (!fallbackLocaleTried) {
                                fallbackLocaleTried = true;
                                var fallbackLocaleStringFile = basePath + OSF.ConstantNames.DefaultLocale + "/" + OSF.ConstantNames.OfficeStringJS;
                                _loadScript(fallbackLocaleStringFile, loadLocaleStringCallback);
                            } else {
                                throw "Neither the locale, " + appContext.get_appUILocale().toLowerCase() + ", provided by the host app nor the fallback locale " + OSF.ConstantNames.DefaultLocale + " are supported.";
                            }
                        } else {
                            fallbackLocaleTried = false;
                            postLoadLocaleStringInitialization();
                        }
                    };
                    var localeStringFile = OSF.OUtil.formatString("{0}{1}/{2}", basePath, getSupportedLocale(appContext.get_appUILocale()), OSF.ConstantNames.OfficeStringJS);
                    _loadScript(localeStringFile, loadLocaleStringCallback, OSF.ConstantNames.LocaleStringLoadingTimeout);
                });
            } else if (numberOfTimeForMsAjaxTries === 0) {
                clearTimeout(timerId);
                throw "MicrosoftAjax.js is not loaded successfully.";
            } else {
                numberOfTimeForMsAjaxTries--;
                timerId = window.setTimeout(loadLocaleStringsAndAppSpecificCode, 100);
            }
        };
        if (_hostInfo.isO15) {
            _loadScript(basePath + OSF.ConstantNames.O15InitHelper, loadLocaleStringsAndAppSpecificCode);
        } else {
            var hostSpecificFileName;
            hostSpecificFileName = _hostInfo.hostType + "-" + _hostInfo.hostPlatform + "-" + _hostInfo.hostSpecificFileVersion + ".debug.js";
            _loadScript(basePath + hostSpecificFileName.toLowerCase(), loadLocaleStringsAndAppSpecificCode);
        }
        window.confirm = function OSF__OfficeAppFactory_initialize$confirm(message) {
            throw 'Function window.confirm is not supported.';
            return false;
        };
        window.alert = function OSF__OfficeAppFactory_initialize$alert(message) {
            throw 'Function window.alert is not supported.';
        };
        window.prompt = function OSF__OfficeAppFactory_initialize$prompt(message, defaultvalue) {
            throw 'Function window.prompt is not supported.';
            return null;
        };

        window.history.replaceState = null;
        window.history.pushState = null;
    };
    initialize();
    return {
        getId: function OSF__OfficeAppFactory$getId() {
            return _WebAppState.id;
        },
        getClientEndPoint: function OSF__OfficeAppFactory$getClientEndPoint() {
            return _WebAppState.clientEndPoint;
        },
        getContext: function OSF__OfficeAppFactory$getContext() {
            return _context;
        },
        setContext: function OSF__OfficeAppFactory$setContext(context) {
            _context = context;
        },
        getHostFacade: function OSF__OfficeAppFactory$getHostFacade() {
            return _hostFacade;
        },
        setHostFacade: function setHostFacade(hostFacade) {
            _hostFacade = hostFacade;
        },
        getInitializationHelper: function OSF__OfficeAppFactory$getInitializationHelper() {
            return _initializationHelper;
        },
        getCachedSessionSettingsKey: function OSF__OfficeAppFactory$getCachedSessionSettingsKey() {
            return (_WebAppState.conversationID != null ? _WebAppState.conversationID : _appInstanceId) + "CachedSessionSettings";
        },
        getWebAppState: function OSF__OfficeAppFactory$getWebAppState() {
            return _WebAppState;
        },
        getWindowLocationHash: function OSF__OfficeAppFactory$getHash() {
            return _windowLocationHash;
        }
    };
})();


text:
import * as _ from 'lodash';
import * as jsdom from 'jsdom';
import * as moment from 'moment';

const BBISTRO_URL = 'http://budapest-bistro.hu/napi-ebed-menu.html';
const BBISTRO_SELECTOR = '#page_content';

function getMenuForToday(text: string, dayIndex: number): string {
  return _.join(getDailyOffer(text, dayIndex), '\n');
}

function getDailyOffer(text: string, dayIndex: number): string[] {
  const daySeparators = ['', 'Hétfő', 'Kedd', 'Szerda', 'Csütörtök', 'Péntek', 'A napi'];
  return text.slice(text.indexOf(daySeparators[dayIndex]), text.indexOf(daySeparators[dayIndex+1]))
    .split('\n')
    .filter((element, index) => index !== 0 && element.length > 3);
}

function parseText(text: string) {
  const dayOfWeek = moment().day();
  const menu = getMenuForToday(text, dayOfWeek);
  const price = '1550.-Ft';

  return `${menu} \n ${price}`;
}

export async function getBudapestBisztro() {
  let window: any;
  try {
    window = await new Promise(
      (resolve, reject) => jsdom.env(BBISTRO_URL, ['http://code.jquery.com/jquery.js'], (err, res) => err ? reject(err) : resolve(res))
    );

    const nodes = window.$(BBISTRO_SELECTOR);

    const text = nodes.length && nodes.first().text();

    const parsedText = parseText(text);

    return {
      title: 'Budapest Bisztró :meat_on_bone:',
      title_link: BBISTRO_URL,
      text: parsedText,
    };
  } catch (err) {
    return {
      title: 'Budapest Bisztró :ripepperonis:',
      title_link: BBISTRO_URL,
      text: `${ err }`,
    };
  } finally {
    if (window) {
      window.close();
    }
  }
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using SysUt14Gr03.Classes;

namespace SysUt14Gr03
{
    public partial class AdministratorForside : System.Web.UI.Page
    {
        protected void Page_PreInit(Object sener, EventArgs e)
        {
            string master = SessionSjekk.findMaster();
            this.MasterPageFile = master;
        }

        protected void Page_Load(object sender, EventArgs e)
        {

        }

        protected void bt_nav_opprettTeam_Click(object sender, EventArgs e)
        {
            Response.Redirect("http://localhost:60154/OpprettTeam.aspx");
 //           Server.Transfer("/OpprettTeam.aspx");
        }

    }
}


text:
package com.intellij.xdebugger.breakpoints;

import javax.annotation.Nonnull;

/**
 * @author nik
 */
public abstract class XBreakpointHandler<B extends XBreakpoint<?>> {
  public static final XBreakpointHandler<?>[] EMPTY_ARRAY = new XBreakpointHandler<?>[0];
  private final Class<? extends XBreakpointType> myBreakpointTypeClass;

  protected XBreakpointHandler(@Nonnull Class<? extends XBreakpointType> breakpointTypeClass) {
    myBreakpointTypeClass = breakpointTypeClass;
  }

  public final Class<? extends XBreakpointType> getBreakpointTypeClass() {
    return myBreakpointTypeClass;
  }

  /**
   * Called when a breakpoint need to be registered in the debugging engine
   * @param breakpoint breakpoint to register
   */
  public abstract void registerBreakpoint(@Nonnull B breakpoint);

  /**
   * Called when a breakpoint need to be unregistered from the debugging engine
   * @param breakpoint breakpoint to unregister
   * @param temporary determines whether breakpoint is unregistered forever or it may be registered again. This parameter may
   * be used for performance purposes. For example the breakpoint may be disabled rather than removed in the debugging engine if
   * temporary is true
   */
  public abstract void unregisterBreakpoint(@Nonnull B breakpoint, final boolean temporary);

}


text:
package udpsource

import (
	"net"
	_log "log"
	"os"
	"streamplay/pipe"
)

const (
	name = "UDP"
	udp  = "udp"
)

// Define some logging constants
var log = _log.New(os.Stderr, "[" + name + "] ", _log.Ldate|_log.Ltime|_log.Lshortfile)

type UDPSource struct {
	pipe   *pipe.Pipe		// The pipe
	config map[string]string	// The config for this module
	data   chan<- *pipe.Chunk	// This is how the info is passed around
	isOpen bool			// is the source open
}

func NewUDPSource(pipe *pipe.Pipe, config map[string]string) *UDPSource {
	source := &UDPSource{pipe: pipe, config: config}
	return source
}

func (us *UDPSource) GetName() string {
	return name
}

func (us *UDPSource) SetStream(data chan<- *pipe.Chunk) {
	us.data = data
}

func (us *UDPSource) Open() {
	if us.isOpen {
		return
	}

	p, err := net.ResolveUDPAddr(us.config["address"])
	if err != nil {
		log.Fatalf("failed to resolve udp address %s", us.config["address"])
	}

	l, err := net.ListenUDP(udp, p)
	if err != nil {
		log.Fatal(err)
	}
	// Assign this to the internal data
	us.isOpen = true
	go us.Run(l)
	log.Println("Accepting packets")
}

func (us *UDPSource) Run(l *net.UDPConn) {
	// Why doesn't this get called on ctrl + c
	var buf [1024]byte

	for {
		n, err := l.Read(buf[0:])
		if err != nil || n == 0 {
			break
		}
		us.data <- pipe.NewSimpleChunk(buf[0:n])
	}
}


text:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Closingfee_model extends MY_Model

{

	protected $_table="closingfee";
	protected $primary_key="closing_id";
	protected $soft_delete = FALSE;
    public $before_create = array( 'created_at', 'updated_at' );
    public $before_update = array( 'updated_at' );
	public function __construct()

	{

	parent::__construct();

	}

public function search(){

    $match = $this->input->post('search');
	$this->db->like('product_price',$match);
	$query = $this->db->get('closing');
	return $query->result();

}
}


text:
<?php defined('SYSPATH') OR die('No direct script access.');

class Deta_Form extends Deta_Core_Form {}


text:
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.openapi.vcs.history.actions;

import com.intellij.history.LocalHistory;
import com.intellij.history.LocalHistoryAction;
import com.intellij.openapi.actionSystem.AnActionExtensionProvider;
import com.intellij.openapi.actionSystem.ExtendableAction;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.command.CommandProcessor;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.diff.impl.patch.formove.TriggerAdditionOrDeletion;
import com.intellij.openapi.extensions.ExtensionPointName;
import com.intellij.openapi.fileEditor.FileDocumentManager;
import com.intellij.openapi.progress.ProgressIndicator;
import com.intellij.openapi.progress.Task;
import com.intellij.openapi.project.DumbAware;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.Messages;
import com.intellij.openapi.util.NlsContexts;
import com.intellij.openapi.util.Ref;
import com.intellij.openapi.vcs.FilePath;
import com.intellij.openapi.vcs.VcsBundle;
import com.intellij.openapi.vcs.VcsException;
import com.intellij.openapi.vcs.history.VcsFileRevision;
import com.intellij.openapi.vcs.history.VcsHistoryUtil;
import com.intellij.openapi.vcs.ui.ReplaceFileConfirmationDialog;
import com.intellij.openapi.vfs.ReadonlyStatusHandler;
import com.intellij.openapi.vfs.VfsUtil;
import com.intellij.openapi.vfs.VfsUtilCore;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.util.ObjectUtils;
import com.intellij.util.containers.ContainerUtil;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import java.io.IOException;
import java.util.Collections;
import java.util.List;
import java.util.Objects;

public class GetVersionAction extends ExtendableAction implements DumbAware {
  private static final Logger LOG = Logger.getInstance(GetVersionAction.class);

  private static final ExtensionPointName<AnActionExtensionProvider> EP_NAME =
    ExtensionPointName.create("com.intellij.openapi.vcs.history.actions.GetVersionAction.ExtensionProvider");

  public GetVersionAction() {
    super(EP_NAME);
  }

  public static void doGet(@NotNull Project project, @NotNull VcsFileRevision revision, @NotNull FilePath filePath) {
    String actionTitle = VcsBundle.message("action.name.for.file.get.version", filePath.getPath(), revision.getRevisionNumber());
    doGet(project, actionTitle, Collections.singletonList(new VcsFileRevisionProvider(filePath, revision)), null);
  }

  public static void doGet(@NotNull Project project,
                           @NotNull @NlsContexts.Label String actionTitle,
                           @NotNull List<FileRevisionProvider> providers,
                           @Nullable Runnable onFinished) {
    List<VirtualFile> files = ContainerUtil.mapNotNull(providers, it -> it.getFilePath().getVirtualFile());
    if (!files.isEmpty()) {
      ReplaceFileConfirmationDialog confirmationDialog =
        new ReplaceFileConfirmationDialog(project, VcsBundle.message("acton.name.get.revision"));
      if (!confirmationDialog.confirmFor(VfsUtilCore.toVirtualFileArray(files))) {
        return;
      }

      if (ReadonlyStatusHandler.getInstance(project).ensureFilesWritable(files).hasReadonlyFiles()) {
        return;
      }
    }

    new MyWriteVersionTask(project, actionTitle, providers, onFinished).queue();
  }

  private static class MyWriteVersionTask extends Task.Backgroundable {
    @NotNull private final @NlsContexts.Label String myActionTitle;
    @NotNull private final List<FileRevisionProvider> myProviders;
    @Nullable private final Runnable myOnFinished;

    MyWriteVersionTask(@NotNull Project project,
                       @NotNull @NlsContexts.Label String actionTitle,
                       @NotNull List<FileRevisionProvider> providers,
                       @Nullable Runnable onFinished) {
      super(project, VcsBundle.message("show.diff.progress.title"));
      myActionTitle = actionTitle;
      myProviders = providers;
      myOnFinished = onFinished;
    }

    @Override
    public void run(@NotNull ProgressIndicator indicator) {
      LocalHistoryAction action = LocalHistory.getInstance().startAction(myActionTitle);
      try {
        TriggerAdditionOrDeletion trigger = new TriggerAdditionOrDeletion(myProject);
        Object commandGroup = new Object();

        for (FileRevisionProvider provider : myProviders) {
          FilePath localFilePath = provider.getFilePath();
          FileRevisionContent revisionContent = provider.getContent();

          Ref<IOException> exRef = new Ref<>();
          ApplicationManager.getApplication().invokeAndWait(() -> {
            try {
              CommandProcessor.getInstance().executeCommand(myProject, () -> {
                VirtualFile virtualFile = localFilePath.getVirtualFile();
                if (revisionContent == null && virtualFile == null) return;

                if (revisionContent == null) {
                  trigger.prepare(Collections.emptyList(), Collections.singletonList(localFilePath));
                }
                else if (virtualFile == null) {
                  trigger.prepare(Collections.singletonList(localFilePath), Collections.emptyList());
                }

                ApplicationManager.getApplication().runWriteAction(() -> {
                  try {
                    if (revisionContent == null) {
                      writeDeletion(virtualFile);
                    }
                    else if (virtualFile == null) {
                      FilePath path = ObjectUtils.chooseNotNull(revisionContent.oldFilePath, localFilePath);
                      writeCreation(path, revisionContent.bytes);
                    }
                    else {
                      if (revisionContent.oldFilePath != null && !localFilePath.equals(revisionContent.oldFilePath)) {
                        writeRename(virtualFile, revisionContent.oldFilePath);
                      }
                      writeModification(virtualFile, revisionContent.bytes);
                    }
                  }
                  catch (IOException e) {
                    exRef.set(e);
                  }
                });
              }, VcsBundle.message("message.title.get.version"), commandGroup);
            }
            finally {
              trigger.cleanup();
            }
          });
          if (!exRef.isNull()) throw exRef.get();
        }

        trigger.processIt();
      }
      catch (IOException e) {
        ApplicationManager.getApplication().invokeLater(
          () -> Messages.showMessageDialog(VcsBundle.message("message.text.cannot.save.content", e.getLocalizedMessage()),
                                           VcsBundle.message("message.title.get.revision.content"), Messages.getErrorIcon()));
      }
      catch (VcsException e) {
        LOG.info(e);
        ApplicationManager.getApplication().invokeLater(
          () -> Messages.showMessageDialog(VcsBundle.message("message.text.cannot.load.revision", e.getLocalizedMessage()),
                                           VcsBundle.message("message.title.get.revision.content"), Messages.getInformationIcon()));
      }
      finally {
        action.finish();
      }
    }

    private static void writeDeletion(@NotNull VirtualFile virtualFile) throws IOException {
      virtualFile.delete(MyWriteVersionTask.class);
    }

    private static void writeCreation(@NotNull FilePath filePath, byte @NotNull [] revisionContent) throws IOException {
      FilePath parentPath = Objects.requireNonNull(filePath.getParentPath());
      VirtualFile parent = VfsUtil.createDirectories(parentPath.getPath());
      if (parent == null) throw new IOException("Can't create directory: " + parentPath);

      VirtualFile virtualFile = parent.createChildData(MyWriteVersionTask.class, filePath.getName());
      virtualFile.setBinaryContent(revisionContent);
    }

    private static void writeModification(@NotNull VirtualFile virtualFile, byte @NotNull [] revisionContent) throws IOException {
      virtualFile.setBinaryContent(revisionContent);
      // Avoid MemoryDiskConflictResolver. We've got user consent to override file in ReplaceFileConfirmationDialog.
      FileDocumentManager.getInstance().reloadFiles(virtualFile);
    }

    private static void writeRename(@NotNull VirtualFile virtualFile, @NotNull FilePath filePath) throws IOException {
      FilePath parentPath = filePath.getParentPath();
      if (parentPath != null) {
        VirtualFile parentFile = VfsUtil.createDirectories(parentPath.getPath());
        if (parentFile != null && !parentFile.equals(virtualFile.getParent())) {
          virtualFile.move(MyWriteVersionTask.class, parentFile);
        }
      }

      if (!virtualFile.getName().equals(filePath.getName())) {
        virtualFile.rename(MyWriteVersionTask.class, filePath.getName());
      }
    }

    @Override
    public void onFinished() {
      if (myOnFinished != null) myOnFinished.run();
    }
  }

  public interface FileRevisionProvider {
    @NotNull
    FilePath getFilePath();

    /**
     * @return file content at some revision. Return null if file does not exist in this revision.
     */
    @Nullable FileRevisionContent getContent() throws VcsException;
  }

  private static class VcsFileRevisionProvider implements FileRevisionProvider {
    @NotNull private final FilePath myFilePath;
    @NotNull private final VcsFileRevision myRevision;

    private VcsFileRevisionProvider(@NotNull FilePath filePath, @NotNull VcsFileRevision revision) {
      myFilePath = filePath;
      myRevision = revision;
    }

    @NotNull
    @Override
    public FilePath getFilePath() {
      return myFilePath;
    }

    @Override
    public @Nullable FileRevisionContent getContent() throws VcsException {
      try {
        byte[] bytes = VcsHistoryUtil.loadRevisionContent(myRevision);
        return new FileRevisionContent(bytes, null);
      }
      catch (IOException e) {
        throw new VcsException(e);
      }
    }
  }

  public static class FileRevisionContent {
    public final byte @NotNull [] bytes;
    public final @Nullable FilePath oldFilePath;

    public FileRevisionContent(byte @NotNull [] bytes, @Nullable FilePath oldFilePath) {
      this.bytes = bytes;
      this.oldFilePath = oldFilePath;
    }
  }
}


text:
<meta charset="utf-8">
    <title>WebCLKernel setArg() basic type testing.</title>
    <link rel="stylesheet" href="../../../resources/js-test-style.css"/>


text:
{-|
Module      : Idris.Elab.Type
Description : Code to elaborate types.
Copyright   :
License     : BSD3
Maintainer  : The Idris Community.
-}
{-# LANGUAGE PatternGuards #-}
module Idris.Elab.Type (
    buildType, elabType, elabType'
  , elabPostulate, elabExtern
  ) where

import Idris.AbsSyntax
import Idris.ASTUtils
import Idris.Core.CaseTree
import Idris.Core.Elaborate hiding (Tactic(..))
import Idris.Core.Evaluate
import Idris.Core.Execute
import Idris.Core.TT
import Idris.Core.Typecheck
import Idris.Coverage
import Idris.DataOpts
import Idris.DeepSeq
import Idris.Delaborate
import Idris.Docstrings (Docstring)
import Idris.DSL
import Idris.Elab.Term
import Idris.Elab.Utils
import Idris.Elab.Value
import Idris.Error
import Idris.Imports
import Idris.Inliner
import Idris.Output (iWarn, iputStrLn, pshow, sendHighlighting)
import Idris.PartialEval
import Idris.Primitives
import Idris.Providers
import IRTS.Lang

import Util.Pretty (pretty, text)

import Prelude hiding (id, (.))

import Control.Applicative hiding (Const)
import Control.Category
import Control.DeepSeq
import Control.Monad
import Control.Monad.State.Strict as State
import Data.Char (isLetter, toLower)
import Data.List
import Data.List.Split (splitOn)
import qualified Data.Map as Map
import Data.Maybe
import qualified Data.Set as S
import qualified Data.Text as T
import qualified Data.Traversable as Traversable
import Debug.Trace

buildType :: ElabInfo
          -> SyntaxInfo
          -> FC
          -> FnOpts
          -> Name
          -> PTerm
          -> Idris (Type, Type, PTerm, [(Int, Name)])
buildType info syn fc opts n ty' = do
         ctxt <- getContext
         i <- getIState

         logElab 2 $ show n ++ " pre-type " ++ showTmImpls ty' ++ show (no_imp syn)
         ty' <- addUsingConstraints syn fc ty'
         ty' <- addUsingImpls syn n fc ty'
         let ty = addImpl (imp_methods syn) i ty'

         logElab 5 $ show n ++ " type pre-addimpl " ++ showTmImpls ty'
         logElab 5 $ "with methods " ++ show (imp_methods syn)
         logElab 2 $ show n ++ " type " ++ show (using syn) ++ "\n" ++ showTmImpls ty

         ((ElabResult tyT' defer is ctxt' newDecls highlights newGName, est), log) <-
            tclift $ elaborate (constraintNS info) ctxt (idris_datatypes i) (idris_name i) n (TType (UVal 0)) initEState
                     (errAt "type of " n Nothing
                        (erunAux fc (build i info ETyDecl [] n ty)))

         displayWarnings est
         setContext ctxt'
         processTacticDecls info newDecls
         sendHighlighting highlights
         updateIState $ \i -> i { idris_name = newGName }

         let tyT = patToImp tyT'

         logElab 3 $ show ty ++ "\nElaborated: " ++ show tyT'

         ds <- checkAddDef True False info fc iderr True defer
         -- if the type is not complete, note that we'll need to infer
         -- things later (for solving metavariables)
         when (length ds > length is) -- more deferred than case blocks
              $ addTyInferred n

         mapM_ (elabCaseBlock info opts) is
         ctxt <- getContext
         logElab 5 "Rechecking"
         logElab 6 (show tyT)
         logElab 10 $ "Elaborated to " ++ showEnvDbg [] tyT
         (cty, ckind)   <- recheckC (constraintNS info) fc id [] tyT

         -- record the implicit and inaccessible arguments
         i <- getIState
         let (inaccData, impls) = unzip $ getUnboundImplicits i cty ty
         let inacc = inaccessibleImps 0 cty inaccData
         logElab 3 $ show n ++ ": inaccessible arguments: " ++ show inacc ++
                     " from " ++ show cty ++ "\n" ++ showTmImpls ty

         putIState $ i { idris_implicits = addDef n impls (idris_implicits i) }
         logElab 3 ("Implicit " ++ show n ++ " " ++ show impls)
         addIBC (IBCImp n)

         -- Add the names referenced to the call graph, and check we're not
         -- referring to anything less visible
         -- In particular, a public/export type can not refer to anything
         -- private, but can refer to any public/export
         let refs = freeNames cty
         nvis <- getFromHideList n
         case nvis of
              Nothing -> return ()
              Just acc -> mapM_ (checkVisibility fc n (max Frozen acc) acc) refs
         addCalls n refs
         addIBC (IBCCG n)

         when (Constructor `notElem` opts) $ do
             let pnames = getParamsInType i [] impls cty
             let fninfo = FnInfo (param_pos 0 pnames cty)
             setFnInfo n fninfo
             addIBC (IBCFnInfo n fninfo)

         return (cty, ckind, ty, inacc)
  where
    patToImp (Bind n (PVar t) sc) = Bind n (Pi Nothing t (TType (UVar [] 0))) (patToImp sc)
    patToImp (Bind n b sc) = Bind n b (patToImp sc)
    patToImp t = t

    param_pos i ns (Bind n (Pi _ t _) sc)
        | n `elem` ns = i : param_pos (i + 1) ns sc
        | otherwise = param_pos (i + 1) ns sc
    param_pos i ns t = []

-- | Elaborate a top-level type declaration - for example, "foo : Int -> Int".
elabType :: ElabInfo
         -> SyntaxInfo
         -> Docstring (Either Err PTerm)
         -> [(Name, Docstring (Either Err PTerm))]
         -> FC
         -> FnOpts
         -> Name
         -> FC -- ^ The precise location of the name
         -> PTerm
         -> Idris Type
elabType = elabType' False

elabType' :: Bool  -- normalise it
          -> ElabInfo
          -> SyntaxInfo
          -> Docstring (Either Err PTerm)
          -> [(Name, Docstring (Either Err PTerm))]
          -> FC
          -> FnOpts
          -> Name
          -> FC
          -> PTerm
          -> Idris Type
elabType' norm info syn doc argDocs fc opts n nfc ty' = {- let ty' = piBind (params info) ty_in
                                                       n  = liftname info n_in in    -}
      do checkUndefined fc n
         (cty, _, ty, inacc) <- buildType info syn fc opts n ty'

         addStatics n cty ty
         let nty = cty -- normalise ctxt [] cty
         -- if the return type is something coinductive, freeze the definition
         ctxt <- getContext
         logElab 2 $ "Rechecked to " ++ show nty
         let nty' = normalise ctxt [] nty
         logElab 2 $ "Rechecked to " ++ show nty'

         -- Add function name to internals (used for making :addclause know
         -- the name unambiguously)
         i <- getIState
         rep <- useREPL
         when rep $ do
           addInternalApp (fc_fname fc) (fst . fc_start $ fc) (PTyped (PRef fc [] n) ty') -- (mergeTy ty' (delab i nty')) -- TODO: Should use span instead of line and filename?
         addIBC (IBCLineApp (fc_fname fc) (fst . fc_start $ fc) (PTyped (PRef fc [] n) ty')) -- (mergeTy ty' (delab i nty')))

         let (fam, _) = unApply (getRetTy nty')
         let corec = case fam of
                        P _ rcty _ -> case lookupCtxt rcty (idris_datatypes i) of
                                        [TI _ True _ _ _] -> True
                                        _ -> False
                        _ -> False
         -- Productivity checking now via checking for guarded 'Delay'
         let opts' = opts -- if corec then (Coinductive : opts) else opts
         let usety = if norm then nty' else nty
         ds <- checkDef info fc iderr True [(n, (-1, Nothing, usety, []))]
         addIBC (IBCDef n)
         addDefinedName n
         let ds' = map (\(n, (i, top, fam, ns)) -> (n, (i, top, fam, ns, True, True))) ds
         addDeferred ds'
         setFlags n opts'
         checkDocs fc argDocs ty
         doc' <- elabDocTerms info doc
         argDocs' <- mapM (\(n, d) -> do d' <- elabDocTerms info d
                                         return (n, d')) argDocs
         addDocStr n doc' argDocs'
         addIBC (IBCDoc n)
         addIBC (IBCFlags n)
         fputState (opt_inaccessible . ist_optimisation n) inacc
         addIBC (IBCOpt n)
         when (Implicit `elem` opts') $ do addCoercion n
                                           addIBC (IBCCoercion n)
         when (AutoHint `elem` opts') $
             case fam of
                P _ tyn _ -> do addAutoHint tyn n
                                addIBC (IBCAutoHint tyn n)
                t -> ifail "Hints must return a data or record type"

         -- If the function is declared as an error handler and the language
         -- extension is enabled, then add it to the list of error handlers.
         errorReflection <- fmap (elem ErrorReflection . idris_language_extensions) getIState
         when (ErrorHandler `elem` opts) $ do
           if errorReflection
             then
               -- Check that the declared type is the correct type for an error handler:
               -- handler : List (TTName, TT) -> Err -> ErrorReport - for now no ctxt
               if tyIsHandler nty'
                 then do i <- getIState
                         putIState $ i { idris_errorhandlers = idris_errorhandlers i ++ [n] }
                         addIBC (IBCErrorHandler n)
                 else ifail $ "The type " ++ show nty' ++ " is invalid for an error handler"
             else ifail "Error handlers can only be defined when the ErrorReflection language extension is enabled."
         -- Send highlighting information about the name being declared
         sendHighlighting [(nfc, AnnName n Nothing Nothing Nothing)]
         -- if it's an export list type, make a note of it
         case (unApply usety) of
              (P _ ut _, _)
                 | ut == ffiexport -> do addIBC (IBCExport n)
                                         addExport n
              _ -> return ()
         return usety
  where
    -- for making an internalapp, we only want the explicit ones, and don't
    -- want the parameters, so just take the arguments which correspond to the
    -- user declared explicit ones
    mergeTy (PPi e n fc ty sc) (PPi e' n' _ _ sc')
         | e == e' = PPi e n fc ty (mergeTy sc sc')
         | otherwise = mergeTy sc sc'
    mergeTy _ sc = sc

    ffiexport = sNS (sUN "FFI_Export") ["FFI_Export"]

    err = txt "Err"
    maybe = txt "Maybe"
    lst = txt "List"
    errrep = txt "ErrorReportPart"

    tyIsHandler (Bind _ (Pi _ (P _ (NS (UN e) ns1) _) _)
                        (App _ (P _ (NS (UN m) ns2) _)
                             (App _ (P _ (NS (UN l) ns3) _)
                                  (P _ (NS (UN r) ns4) _))))
        | e == err && m == maybe && l == lst && r == errrep
        , ns1 == map txt ["Errors","Reflection","Language"]
        , ns2 == map txt ["Maybe", "Prelude"]
        , ns3 == map txt ["List", "Prelude"]
        , ns4 == map txt ["Reflection","Language"] = True
    tyIsHandler _                                           = False

elabPostulate :: ElabInfo -> SyntaxInfo -> Docstring (Either Err PTerm) ->
                 FC -> FC -> FnOpts -> Name -> PTerm -> Idris ()
elabPostulate info syn doc fc nfc opts n ty = do
    elabType info syn doc [] fc opts n NoFC ty
    putIState . (\ist -> ist{ idris_postulates = S.insert n (idris_postulates ist) }) =<< getIState
    addIBC (IBCPostulate n)
    sendHighlighting [(nfc, AnnName n (Just PostulateOutput) Nothing Nothing)]

    -- remove it from the deferred definitions list
    solveDeferred fc n

elabExtern :: ElabInfo -> SyntaxInfo -> Docstring (Either Err PTerm) ->
                 FC -> FC -> FnOpts -> Name -> PTerm -> Idris ()
elabExtern info syn doc fc nfc opts n ty = do
    cty <- elabType info syn doc [] fc opts n NoFC ty
    ist <- getIState
    let arity = length (getArgTys (normalise (tt_ctxt ist) [] cty))

    putIState . (\ist -> ist{ idris_externs = S.insert (n, arity) (idris_externs ist) }) =<< getIState
    addIBC (IBCExtern (n, arity))

    -- remove it from the deferred definitions list
    solveDeferred fc n


text:
var Assembler = function (features, filter) {
  var currentFeature, currentScenarioOrBackground, currentStep, suggestedFeature;
  var stashedTags = [];

  var self = {
    setCurrentFeature: function setCurrentFeature(feature) {
      currentFeature = feature;
      self.setCurrentScenarioOrBackground(undefined);
    },

    getCurrentFeature: function getCurrentFeature() {
      return currentFeature;
    },

    setCurrentScenarioOrBackground: function setCurrentScenarioOrBackground(scenarioOrBackground) {
      currentScenarioOrBackground = scenarioOrBackground;
      self.setCurrentStep(undefined);
    },

    getCurrentScenarioOrBackground: function getCurrentScenarioOrBackground() {
      return currentScenarioOrBackground;
    },

    setCurrentStep: function setCurrentStep(step) {
      currentStep = step;
    },

    getCurrentStep: function getCurrentStep() {
      return currentStep;
    },

    stashTag: function stashTag(tag) {
      stashedTags.push(tag);
    },

    revealTags: function revealTags() {
      var revealedTags = stashedTags;
      stashedTags      = [];
      return revealedTags;
    },

    applyCurrentFeatureTagsToElement: function applyCurrentFeatureTagsToElement(element) {
      var currentFeature = self.getCurrentFeature();
      var featureTags    = currentFeature.getTags();
      element.addInheritedtags(featureTags);
    },

    applyStashedTagsToElement: function applyStashedTagsToElement(element) {
      var revealedTags = self.revealTags();
      element.addTags(revealedTags);
    },

    insertBackground: function insertBackground(background) {
      self.setCurrentScenarioOrBackground(background);
      var currentFeature = self.getCurrentFeature();
      currentFeature.addBackground(background);
    },

    insertDataTableRow: function insertDataTableRow(dataTableRow) {
      var currentStep = self.getCurrentStep();
      currentStep.attachDataTableRow(dataTableRow);
    },

    insertDocString: function insertDocString(docString) {
      var currentStep = self.getCurrentStep();
      currentStep.attachDocString(docString);
    },

    insertFeature: function insertFeature(feature) {
      self.tryEnrollingSuggestedFeature();
      self.applyStashedTagsToElement(feature);
      self.setCurrentFeature(feature);
      self.suggestFeature(feature);
    },

    insertScenario: function insertScenario(scenario) {
      self.applyCurrentFeatureTagsToElement(scenario);
      self.applyStashedTagsToElement(scenario);
      self.setCurrentScenarioOrBackground(scenario);
      if (filter.isElementEnrolled(scenario)) {
        var currentFeature = self.getCurrentFeature();
        currentFeature.addFeatureElement(scenario);
      }
    },

    insertExamples: function insertExamples(examples) {
      var currentScenarioOrBackground = self.getCurrentScenarioOrBackground();
      if (currentScenarioOrBackground.payloadType == 'scenarioOutline')
        currentScenarioOrBackground.setExamples(examples);
      else
        throw new Error("Examples are allowed inside scenario outlines only");
      self.setCurrentStep(examples);
    },

    insertStep: function insertStep(step) {
      self.setCurrentStep(step);
      var currentScenarioOrBackground = self.getCurrentScenarioOrBackground();
      currentScenarioOrBackground.addStep(step);
    },

    insertTag: function insertTag(tag) {
      self.stashTag(tag);
    },

    convertScenarioOutlineToScenarios: function convertScenarioOutlineToScenarios(scenario){
        var subScenarios = scenario.buildScenarios();
        subScenarios.syncForEach(self.insertScenario);
    },

    convertScenarioOutlinesToScenarios: function convertScenarioOutlinesToScenarios(){
      var currentFeature = self.getCurrentFeature();
      var scenarios = currentFeature.getFeatureElements();

      scenarios.syncForEach(function(scenario){
          self.convertScenarioOutlineToScenarios(scenario);
      });
    },

    finish: function finish() {
      self.convertScenarioOutlinesToScenarios();
      self.tryEnrollingSuggestedFeature();
    },

    suggestFeature: function suggestFeature(feature) {
      suggestedFeature = feature;
    },

    isSuggestedFeatureEnrollable: function isSuggestedFeatureEnrollable() {
      var enrollable = suggestedFeature && (suggestedFeature.hasFeatureElements() || filter.isElementEnrolled(suggestedFeature));
      return enrollable;
    },

    tryEnrollingSuggestedFeature: function tryEnrollingSuggestedFeature() {
      if (self.isSuggestedFeatureEnrollable())
        self.enrollSuggestedFeature();
    },

    enrollSuggestedFeature: function enrollSuggestedFeature() {
      features.addFeature(suggestedFeature);
      suggestedFeature = null;
    }
  };
  return self;
};

module.exports = Assembler;


text:
@interface ChatVoiceRecorderVC : VoiceRecorderBaseVC
{
}
@property(nonatomic)BOOL isFinish;

//录音界面
@property(nonatomic,assign)ChatRecorderView*recorderView;
//开始录音
- (void)beginRecordByFileName:(NSString*)_fileName;
//停止录音
-(void)touchEnded;

@end


text:
This project shows how to implement a side menu that collapses on small screens.

This project was generated with [Angular CLI](https://github.com/angular/angular-cli) version 1.2.1 and by copying and adapting the code snippet by [TerryTel93](https://bootsnipp.com/snippets/featured/responsive-sidebar-menu).

## Development server

Run `ng serve` for a dev server. Navigate to `http://localhost:4200/`. The app will automatically reload if you change any of the source files.

## Code scaffolding

Run `ng generate component component-name` to generate a new component. You can also use `ng generate directive|pipe|service|class|module`.

## Build

Run `ng build` to build the project. The build artifacts will be stored in the `dist/` directory. Use the `-prod` flag for a production build.

## Running unit tests

Run `ng test` to execute the unit tests via [Karma](https://karma-runner.github.io).

## Running end-to-end tests

Run `ng e2e` to execute the end-to-end tests via [Protractor](http://www.protractortest.org/).
Before running the tests make sure you are serving the app via `ng serve`.

## Further help

To get more help on the Angular CLI use `ng help` or go check out the [Angular CLI README](https://github.com/angular/angular-cli/blob/master/README.md).


text:
module Riot
  # A runnable block is pretty much an anonymous block decorator. It's goal is to accept a block, a
  # description for what the block is intended to be for, and provide a +run+ method expects a
  # {Riot::Situation} instance. Any time a {Riot::Situation} is provided to +run+, a {Riot::RunnableBlock}
  # promises to evaluate itself against the situation in some way.
  #
  # Intent is to sub-class {Riot::RunnableBlock} with specific mechanisms for contorting the
  # {Riot::Situation}.
  class RunnableBlock

    # The decorated block.
    attr_reader :definition

    # Creates a new RunnableBlock.
    #
    # @param [String] description a description of what this block is for
    # @param [lambda] &definition the block to decorate
    def initialize(description, &definition)
      @description, @definition = description, definition || proc { false }
    end

    # Given a {Riot::Situation}, eval the provided block against it and then return a status tuple.
    #
    # @param [Riot::Situation] situation An instance of a {Riot::Situation}
    # @return [Array<Symbol[, String]>] array containing at least an evaluation state
    def run(situation)
      raise "Define your own run"
    end

    # String representation of this block, which is basically the description.
    #
    # @return [String]
    def to_s; @description; end
  end # RunnableBlock

  # Used to decorate a setup, hookup, a teardown or anything else that is about context administration.
  class Setup < RunnableBlock
    def initialize(&definition)
      super("setup", &definition)
    end

    # Calls {Riot::Situation#setup} with the predefined block at {Riot::Context} run-time. Though this is
    # like every other kind of {Riot::RunnableBlock}, +run+ will not return a meaningful state, which means
    # the reporter will likely not report anything.
    #
    # @param [Riot::Situation] situation the situation for the current {Riot::Context} run
    # @return [Array<Symbol>] array containing the evaluation state
    def run(situation)
      situation.setup(&definition)
      [:setup]
    rescue StandardError => e
      [:setup_error, e]
    end
  end # Setup

  # Used to decorate a helper. A helper generally ends up being a glorified method that can be referenced
  # from within a setup, teardown, hookup, other helpers, assertion blocks, and assertion macro blocks;
  # basically anywhere the {Riot::Situation} instance is available.
  #
  #   context "Making dinner" do
  #     helper(:easy_bake) do |thing|
  #       EasyBake.new(thing, :ingredients => [:ketchup, :chocolate, :syrup])
  #     end
  #
  #     setup do
  #       easy_bake(:meatloaf)
  #     end
  #
  #     asserts(:food_poisoning_probabilty).equals(0.947)
  #   end # Making dinner
  class Helper < RunnableBlock
    def initialize(name, &definition)
      super("helper #{name}", &definition)
      @name = name
    end

    # Calls {Riot::Situation#helper} with the predefined helper name and block at {Riot::Context} run-time.
    # Though this is like every other kind of {Riot::RunnableBlock}, +run+ will not return a meaningful
    # state, which means the reporter will likely not report anything.
    #
    # @param [Riot::Situation] situation the situation for the current {Riot::Context} run
    # @return [Array<Symbol>] array containing the evaluation state
    def run(situation)
      situation.helper(@name, &definition)
      [:helper]
    end
  end
end # Riot