text:
module Rubyvis
  class Layout
    # Alias for Rubyvis::Layout::Treemap
    def self.Treemap
      Rubyvis::Layout::Treemap
    end

    # Implements a space-filling rectangular layout, with the hierarchy
    # represented via containment. Treemaps represent nodes as boxes, with child
    # nodes placed within parent boxes. The size of each box is proportional
    # to the size of the node in the tree. This particular algorithm is taken from Bruls,
    # D.M., C. Huizing, and J.J. van Wijk, "Squarified Treemaps" in
    # Data Visualization 2000, Proceedings of the Joint Eurographics and IEEE
    # TCVG Sumposium on Visualization, 2000, pp. 33-42.
    #
    #
The meaning of the exported mark prototypes changes slightly in the
    # space-filling implementation:

    #
    #
<tt>node</tt> - for rendering nodes; typically a {@link pv.Bar}. The node
    # data is populated with <tt>dx</tt> and <tt>dy</tt> attributes, in addition to
    # the standard <tt>x</tt> and <tt>y</tt> position attributes.
    #
    #

<tt>leaf</tt> - for rendering leaf nodes only, with no fill or stroke
    # style by default; typically a Rubyvis::Panel or another layout!
    #
    #

<tt>link</tt> - unsupported; undefined. Links are encoded implicitly
    # in the arrangement of the space-filling nodes.
    #
    #

<tt>label</tt> - for rendering node labels; typically a
    # Rubyvis::Label.
    #
    #
For more details on how to use this layout, see
    # Rubyvis::Layout::Hierarchy.
    #
    class Treemap < Hierarchy
      @properties=Hierarchy.properties.dup
      def initialize
        super
        @size=lambda {|d| d.node_value.to_f}

        @node.stroke_style("#fff").
          fill_style("rgba(31, 119, 180, .25)").
          width(lambda {|n| n.dx}).
          height(lambda {|n| n.dy })

        @node_label.
          visible(lambda {|n| !n.first_child }).
          left(lambda {|n| n.x + (n.dx / 2.0) }).
          top(lambda {|n| n.y + (n.dy / 2.0) }).
          text_align("center").
          text_angle(lambda {|n| n.dx > n.dy ? 0 : -Math::PI / 2.0 })
      end

      def leaf
        m=Rubyvis::Mark.new.
        mark_extend(self.node).
        fill_style(nil).
        stroke_style(nil).
        visible(lambda {|n| !n.first_child })
        m.parent = self
        m
      end
      def link
        nil
      end

      ##
      # :attr: round
      # Whether node sizes should be rounded to integer values. This has a similar
      # effect to setting <tt>antialias(false)</tt> for node values, but allows the
      # treemap algorithm to accumulate error related to pixel rounding.
      #
      # @type boolean

      ##
      # :attr: padding_left
      # The left inset between parent add child in pixels. Defaults to 0.
      #
      # @type number
      # @see #padding

      ##
      # :attr: padding_rigth
      # The right inset between parent add child in pixels. Defaults to 0.
      #
      # @type number
      # @name pv.Layout.Treemap.prototype.paddingRight
      # @see #padding

      ##
      # :attr: padding_top
      # The top inset between parent and child in pixels. Defaults to 0.
      #
      # @type number
      # @name pv.Layout.Treemap.prototype.paddingTop
      # @see #padding

      ##
      # :attr: padding_bottom
      # The bottom inset between parent and child in pixels. Defaults to 0.
      #
      # @type number
      # @name pv.Layout.Treemap.prototype.paddingBottom
      # @see #padding

      ##
      # :attr: mode
      # The treemap algorithm. The default value is "squarify". The "slice-and-dice"
      # algorithm may also be used, which alternates between horizontal and vertical
      # slices for different depths. In addition, the "slice" and "dice" algorithms
      # may be specified explicitly to control whether horizontal or vertical slices
      # are used, which may be useful for nested treemap layouts.
      #
      # @type string
      # @name pv.Layout.Treemap.prototype.mode
      # @see "Ordered Treemap Layouts" by B. Shneiderman & M. Wattenberg, IEEE
      # InfoVis 2001.

      ##
      # :attr: order
      # The sibling node order. A <tt>null</tt> value means to use the sibling order
      # specified by the nodes property as-is; "reverse" will reverse the given
      # order. The default value "ascending" will sort siblings in ascending order of
      # size, while "descending" will do the reverse. For sorting based on data
      # attributes other than size, use the default <tt>null</tt> for the order
      # property, and sort the nodes beforehand using the {@link pv.Dom} operator.
      #
      # @type string
      # @name pv.Layout.Treemap.prototype.order

      attr_accessor_dsl :round, :padding_left, :padding_right, :padding_top, :padding_bottom, :mode, :order

      # Default propertiess for treemap layouts. The default mode is "squarify" and the default order is "ascending".
      def self.defaults
        Rubyvis::Layout::Treemap.new.mark_extend(Rubyvis::Layout::Hierarchy.defaults).
        mode("squarify"). # squarify, slice-and-dice, slice, dice
        order('ascending') # ascending, descending, reverse, nil
      end

      # Alias for setting the left, right, top and bottom padding properties
      # simultaneously.
      def padding(n)
        padding_left(n).padding_right(n).padding_top(n).padding_bottom(n)
      end
      def _size(d)
        @size.call(d)
      end

      ##
      # Specifies the sizing function. By default, the size function uses the
      # +node_value+ attribute of nodes as a numeric value:
      #
The sizing function is invoked for each leaf node in the tree, per the
      # <tt>nodes</tt> property. For example, if the tree data structure represents a
      # file system, with files as leaf nodes, and each file has a <tt>bytes</tt>
      # attribute, you can specify a size function as:
      #
      #
    .size(function(d) d.bytes)

      #
      # @param {function} f the new sizing function.
      # @returns {pv.Layout.Treemap} this.

      def size(f)
        @size=Rubyvis.functor(f)
        self
      end

      def build_implied(s)
        return nil if hierarchy_build_implied(s)

        that=self
        nodes = s.nodes
        root = nodes[0]
        stack = Mark.stack

        left = s.padding_left
        right = s.padding_right
        top = s.padding_top
        bottom = s.padding_bottom
        left||=0
        right||=0
        top||=0
        bottom||=0
        size=lambda {|n| n.size}
        round = s.round ?
          lambda {|a| a.round } :
          lambda {|a| a.to_f}
        mode = s.mode

        slice=lambda { |row, sum, horizontal, x, y, w, h|
          # puts "slice:#{sum},#{horizontal},#{x},#{y},#{w},#{h}"
          d=0
          row.size.times {|i|
            n=row[i]
            # puts "i:#{i},d:#{d}"
            if horizontal
              n.x = x + d
              n.y = y
              d += n.dx = round.call(w * n.size / sum.to_f)
              n.dy = h
            else
              n.x = x
              n.y = y + d
              n.dx = w
              d += n.dy = round.call(h * n.size / sum.to_f)
            end
            # puts "n.x:#{n.x}, n.y:#{n.y}, n.dx:#{n.dx}, n.dy:#{n.dy}"
          }

          if (row.last)  # correct on-axis rounding error
            n=row.last
            if (horizontal)
              n.dx += w - d
            else
              n.dy += h - d
            end
          end
        }

        ratio=lambda {|row, l|
          rmax = -Infinity
          rmin = Infinity
          s = 0
          row.each_with_index {|v,i|
            r = v.size
            rmin = r if (r < rmin)
            rmax = r if (r > rmax)
            s += r
          }
          s = s * s
          l = l * l
          [l * rmax / s.to_f, s.to_f / (l * rmin)].max
        }

        layout=lambda {|n,i|
          x = n.x + left
          y = n.y + top
          w = n.dx - left - right
          h = n.dy - top - bottom

          # puts "Layout: '#{n.node_name}', #{n.x}, #{n.y}, #{n.dx}, #{n.dy}"
          #/* Assume squarify by default. */
          if (mode != "squarify")
            slice.call(n.child_nodes, n.size, ( mode == "slice" ? true : mode == "dice" ? false : (i & 1)!=0), x, y, w, h)
          else
            row = []
            mink = Infinity
            l = [w,h].min
            k = w * h / n.size.to_f
            #/* Abort if the size is nonpositive. */

            if (n.size > 0)
              #/* Scale the sizes to fill the current subregion. */
              n.visit_before {|n1,i1| n1.size *= k }

              #/** @private Position the specified nodes along one dimension. */
              position=lambda {|row1|
                horizontal = w == l
                sum = Rubyvis.sum(row1, size)
                r = l>0 ? round.call(sum / l.to_f) : 0
                slice.call(row1, sum, horizontal, x, y, horizontal ? w : r, horizontal ? r : h)
                if horizontal
                  y += r
                  h -= r
                else
                  x += r
                  w -= r
                end
                l = [w, h].min
                horizontal
              }

              children = n.child_nodes.dup # copy
              while (children.size>0) do
                child = children[children.size - 1]
                if (child.size==0)
                  children.pop
                  next
                end
                row.push(child)

                k = ratio.call(row, l)

                if (k <= mink)
                  children.pop
                  mink = k
                else
                  row.pop
                  position.call(row)
                  row.clear
                  mink = Infinity
                end
              end

              #/* correct off-axis rounding error */

              if (position.call(row))
                row.each {|v|
                  v.dy+=h
                }
              else
                row.each {|v|
                  v.dx+=w
                }
              end
            end
          end
        }

        stack.unshift(nil)
        root.visit_after {|nn,i|
          nn.depth = i
          nn.x = nn.y = nn.dx = nn.dy = 0
          if nn.first_child
            nn.size=Rubyvis.sum(nn.child_nodes, lambda {|v| v.size})
          else
            stack[0]=nn
            nn.size=that._size(stack[0])
          end
        }
        stack.shift()

        #/* Sort. */

        case s.order
          when 'ascending'
            root.sort(lambda {|a,b| a.size<=>b.size})
          when 'descending'
            root.sort(lambda {|a,b| b.size<=>a.size})
          when 'reverse'
            root.reverse
        end
        # /* Recursively compute the layout. */
        root.x = 0;
        root.y = 0;
        root.dx = s.width
        root.dy = s.height
        root.visit_before {|n,i| layout.call(n,i)}
      end

    end
  end
end


text:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <parent>
        <groupId>io.astefanutti.cdeye</groupId>
        <artifactId>cdeye-parent</artifactId>
        <version>1.0-SNAPSHOT</version>
    </parent>

    <artifactId>cdeye-core</artifactId>
    <name>CDEye Core</name>

    <build>
        <plugins>
            <plugin>
                <groupId>org.jvnet.jaxb2.maven2</groupId>
                <artifactId>maven-jaxb2-plugin</artifactId>
                <version>0.9.0</version>
                <executions>
                    <execution>
                        <goals>
                            <goal>generate</goal>
                        </goals>
                    </execution>
                </executions>
                <configuration>
                    <extension>true</extension>
                    <schemaDirectory>${basedir}/src/main/xsd</schemaDirectory>
                    <bindingDirectory>${basedir}/src/main/xsd</bindingDirectory>
                    <args>
                        <arg>-Xnamespace-prefix</arg>
                        <arg>-Xfluent-api</arg>
                        <arg>-Xfluent-api-ext</arg>
                        <arg>-Xinheritance</arg>
                    </args>
                    <plugins>
                        <plugin>
                            <groupId>org.jvnet.jaxb2_commons</groupId>
                            <artifactId>jaxb2-basics</artifactId>
                            <version>0.9.0</version>
                        </plugin>
                        <plugin>
                            <groupId>org.jvnet.jaxb2_commons</groupId>
                            <artifactId>jaxb2-namespace-prefix</artifactId>
                            <version>1.1</version>
                        </plugin>
                        <plugin>
                            <groupId>org.jvnet.jaxb2_commons</groupId>
                            <artifactId>jaxb2-fluent-api</artifactId>
                            <version>3.0</version>
                        </plugin>
                        <plugin>
                            <groupId>redmosquito</groupId>
                            <artifactId>jaxb-fluent-api-ext</artifactId>
                            <version>0.0.3</version>
                        </plugin>
                    </plugins>
                </configuration>
            </plugin>
        </plugins>
    </build>

    <dependencies>

        <!-- compile dependencies -->

        <!-- provided dependencies -->

        <dependency>
            <groupId>javax.enterprise</groupId>
            <artifactId>cdi-api</artifactId>
        </dependency>

        <dependency>
            <groupId>javax.annotation</groupId>
            <artifactId>javax.annotation-api</artifactId>
        </dependency>

        <!-- test dependencies -->

        <dependency>
            <groupId>org.eclipse.persistence</groupId>
            <artifactId>eclipselink</artifactId>
            <version>2.5.2</version>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>ch.qos.logback</groupId>
            <artifactId>logback-classic</artifactId>
        </dependency>

        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
        </dependency>

        <dependency>
            <groupId>org.hamcrest</groupId>
            <artifactId>hamcrest-library</artifactId>
        </dependency>

        <dependency>
            <groupId>org.mockito</groupId>
            <artifactId>mockito-core</artifactId>
        </dependency>

    </dependencies>

</project>

redpajama_set_name: RedPajamaGithub


text:
<?php

final class Twig_Extension_Sandbox extends Twig_Extension
{
    private $sandboxedGlobally;
    private $sandboxed;
    private $policy;

    public function __construct(Twig_Sandbox_SecurityPolicyInterface $policy, $sandboxed = false)
    {
        $this->policy = $policy;
        $this->sandboxedGlobally = $sandboxed;
    }

    public function getTokenParsers()
    {
        return array(new Twig_TokenParser_Sandbox());
    }

    public function getNodeVisitors()
    {
        return array(new Twig_NodeVisitor_Sandbox());
    }

    public function enableSandbox()
    {
        $this->sandboxed = true;
    }

    public function disableSandbox()
    {
        $this->sandboxed = false;
    }

    public function isSandboxed()
    {
        return $this->sandboxedGlobally || $this->sandboxed;
    }

    public function isSandboxedGlobally()
    {
        return $this->sandboxedGlobally;
    }

    public function setSecurityPolicy(Twig_Sandbox_SecurityPolicyInterface $policy)
    {
        $this->policy = $policy;
    }

    public function getSecurityPolicy()
    {
        return $this->policy;
    }

    public function checkSecurity($tags, $filters, $functions)
    {
        if ($this->isSandboxed()) {
            $this->policy->checkSecurity($tags, $filters, $functions);
        }
    }

    public function checkMethodAllowed($obj, $method)
    {
        if ($this->isSandboxed()) {
            $this->policy->checkMethodAllowed($obj, $method);
        }
    }

    public function checkPropertyAllowed($obj, $method)
    {
        if ($this->isSandboxed()) {
            $this->policy->checkPropertyAllowed($obj, $method);
        }
    }

    public function ensureToStringAllowed($obj)
    {
        if ($this->isSandboxed() && is_object($obj)) {
            $this->policy->checkMethodAllowed($obj, '__toString');
        }

        return $obj;
    }
}

class_alias('Twig_Extension_Sandbox', 'Twig\Extension\SandboxExtension', false);


text:
"""Utilities for the Django web framework

Provides Django views and helpers the make using the OAuth2 web server
flow easier. It includes an ``oauth_required`` decorator to automatically ensure
that user credentials are available, and an ``oauth_enabled`` decorator to check
if the user has authorized, and helper shortcuts to create the authorization
URL otherwise.

Configuration
=============

To configure, you'll need a set of OAuth2 web application credentials from
`Google Developer's Console <https://console.developers.google.com/project/_/apiui/credential>`.

Add the helper to your INSTALLED_APPS:

.. code-block:: python
   :caption: settings.py
   :name: installed_apps

    INSTALLED_APPS = (
        # other apps
        "oauth2client.contrib.django_util"
    )

Add the client secrets created earlier to the settings. You can either
specify the path to the credentials file in JSON format

.. code-block:: python
   :caption:  settings.py
   :name: secrets_file

   GOOGLE_OAUTH2_CLIENT_SECRETS_JSON=/path/to/client-secret.json

Or, directly configure the client Id and client secret.

.. code-block:: python
   :caption: settings.py
   :name: secrets_config

   GOOGLE_OAUTH2_CLIENT_ID=client-id-field
   GOOGLE_OAUTH2_CLIENT_SECRET=client-secret-field

By default, the default scopes for the required decorator only contains the
``email`` scopes. You can change that default in the settings.

.. code-block:: python
   :caption: settings.py
   :name: scopes

   GOOGLE_OAUTH2_SCOPES = ('email', 'https://www.googleapis.com/auth/calendar',)

By default, the decorators will add an `oauth` object to the Django request
object, and include all of its state and helpers inside that object. If the
`oauth` name conflicts with another usage, it can be changed

.. code-block:: python
   :caption: settings.py
   :name: request_prefix

   # changes request.oauth to request.google_oauth
   GOOGLE_OAUTH2_REQUEST_ATTRIBUTE = 'google_oauth'

Add the oauth2 routes to your application's urls.py urlpatterns.

.. code-block:: python
   :caption: urls.py
   :name: urls

   from oauth2client.contrib.django_util.site import urls as oauth2_urls

   urlpatterns += [url(r'^oauth2/', include(oauth2_urls))]

To require OAuth2 credentials for a view, use the `oauth2_required` decorator.
This creates a credentials object with an id_token, and allows you to create an
`http` object to build service clients with. These are all attached to the
request.oauth

.. code-block:: python
   :caption: views.py
   :name: views_required

   from oauth2client.contrib.django_util.decorators import oauth_required

   @oauth_required
   def requires_default_scopes(request):
      email = request.oauth.credentials.id_token['email']
      service = build(serviceName='calendar', version='v3',
                    http=request.oauth.http,
                   developerKey=API_KEY)
      events = service.events().list(calendarId='primary').execute()['items']
      return HttpResponse("email: %s , calendar: %s" % (email, str(events)))

To make OAuth2 optional and provide an authorization link in your own views.

.. code-block:: python
   :caption: views.py
   :name: views_enabled2

   from oauth2client.contrib.django_util.decorators import oauth_enabled

   @oauth_enabled
   def optional_oauth2(request):
       if request.oauth.has_credentials():
           # this could be passed into a view
           # request.oauth.http is also initialized
           return HttpResponse("User email: %s"
            % request.oauth.credentials.id_token['email'])
       else:
           return HttpResponse('Here is an OAuth Authorize link:
           Authorize' % request.oauth.get_authorize_redirect())

If a view needs a scope not included in the default scopes specified in
the settings, you can use [incremental auth](https://developers.google.com/identity/sign-in/web/incremental-auth)
and specify additional scopes in the decorator arguments.

.. code-block:: python
   :caption: views.py
   :name: views_required_additional_scopes

   @oauth_enabled(scopes=['https://www.googleapis.com/auth/drive'])
   def drive_required(request):
       if request.oauth.has_credentials():
           service = build(serviceName='drive', version='v2',
                http=request.oauth.http,
                developerKey=API_KEY)
           events = service.files().list().execute()['items']
           return HttpResponse(str(events))
       else:
           return HttpResponse('Here is an OAuth Authorize link:
           Authorize' % request.oauth.get_authorize_redirect())

To provide a callback on authorization being completed, use the
oauth2_authorized signal:

.. code-block:: python
   :caption: views.py
   :name: signals

   from oauth2client.contrib.django_util.signals import oauth2_authorized

   def test_callback(sender, request, credentials, **kwargs):
       print "Authorization Signal Received %s" % credentials.id_token['email']

   oauth2_authorized.connect(test_callback)

"""

import django.conf
from django.core import exceptions
from django.core import urlresolvers
import httplib2
from oauth2client import clientsecrets
from oauth2client.contrib.django_util import storage
from six.moves.urllib import parse

GOOGLE_OAUTH2_DEFAULT_SCOPES = ('email',)
GOOGLE_OAUTH2_REQUEST_ATTRIBUTE = 'oauth'

def _load_client_secrets(filename):
    """Loads client secrets from the given filename."""
    client_type, client_info = clientsecrets.loadfile(filename)

    if client_type != clientsecrets.TYPE_WEB:
        raise ValueError(
            'The flow specified in {} is not supported, only the WEB flow '
            'type  is supported.'.format(client_type))
    return client_info['client_id'], client_info['client_secret']

def _get_oauth2_client_id_and_secret(settings_instance):
    """Initializes client id and client secret based on the settings"""
    secret_json = getattr(django.conf.settings,
                          'GOOGLE_OAUTH2_CLIENT_SECRETS_JSON', None)
    if secret_json is not None:
        return _load_client_secrets(secret_json)
    else:
        client_id = getattr(settings_instance, "GOOGLE_OAUTH2_CLIENT_ID",
                            None)
        client_secret = getattr(settings_instance,
                                "GOOGLE_OAUTH2_CLIENT_SECRET", None)
        if client_id is not None and client_secret is not None:
            return client_id, client_secret
        else:
            raise exceptions.ImproperlyConfigured(
                "Must specify either GOOGLE_OAUTH2_CLIENT_SECRETS_JSON, or  "
                " both GOOGLE_OAUTH2_CLIENT_ID and GOOGLE_OAUTH2_CLIENT_SECRET "
                "in settings.py")

class OAuth2Settings(object):
    """Initializes Django OAuth2 Helper Settings

    This class loads the OAuth2 Settings from the Django settings, and then
    provides those settings as attributes to the rest of the views and
    decorators in the module.

    Attributes:
      scopes: A list of OAuth2 scopes that the decorators and views will use
              as defaults
      request_prefix: The name of the attribute that the decorators use to
                    attach the UserOAuth2 object to the Django request object.
      client_id: The OAuth2 Client ID
      client_secret: The OAuth2 Client Secret
    """

    def __init__(self, settings_instance):
        self.scopes = getattr(settings_instance, 'GOOGLE_OAUTH2_SCOPES',
                              GOOGLE_OAUTH2_DEFAULT_SCOPES)
        self.request_prefix = getattr(settings_instance,
                                      'GOOGLE_OAUTH2_REQUEST_ATTRIBUTE',
                                      GOOGLE_OAUTH2_REQUEST_ATTRIBUTE)
        self.client_id, self.client_secret = \
            _get_oauth2_client_id_and_secret(settings_instance)

        if ('django.contrib.sessions.middleware.SessionMiddleware'
                not in settings_instance.MIDDLEWARE_CLASSES):
            raise exceptions.ImproperlyConfigured(
                "The Google OAuth2 Helper requires session middleware to "
                "be installed. Edit your MIDDLEWARE_CLASSES setting"
                " to include 'django.contrib.sessions.middleware."
                "SessionMiddleware'.")

oauth2_settings = OAuth2Settings(django.conf.settings)

def _redirect_with_params(url_name, *args, **kwargs):
    """Helper method to create a redirect response that uses GET URL
    parameters."""

    url = urlresolvers.reverse(url_name, args=args)
    params = parse.urlencode(kwargs, True)
    return "{0}?{1}".format(url, params)

class UserOAuth2(object):
    """Class to create oauth2 objects on Django request objects containing
    credentials and helper methods.
    """

    def __init__(self, request, scopes=None, return_url=None):
        """Initialize the Oauth2 Object
        :param request: Django request object
        :param scopes: Scopes desired for this OAuth2 flow
        :param return_url: URL to return to after authorization is complete
        :return:
        """
        self.request = request
        self.return_url = return_url or request.get_full_path()
        self.scopes = set(oauth2_settings.scopes)
        if scopes:
            self.scopes |= set(scopes)

        # make sure previously requested custom scopes are maintained
        # in future authorizations
        credentials = storage.get_storage(self.request).get()
        if credentials:
            self.scopes |= credentials.scopes

    def get_authorize_redirect(self):
        """Creates a URl to start the OAuth2 authorization flow"""
        get_params = {
            'return_url': self.return_url,
            'scopes': self.scopes
        }

        return _redirect_with_params('google_oauth:authorize',
                                     **get_params)

    def has_credentials(self):
        """Returns True if there are valid credentials for the current user
        and required scopes."""
        return (self.credentials and not self.credentials.invalid
                and self.credentials.has_scopes(self.scopes))

    @property
    def credentials(self):
        """Gets the authorized credentials for this flow, if they exist"""
        return storage.get_storage(self.request).get()

    @property
    def http(self):
        """Helper method to create an HTTP client authorized with OAuth2
        credentials"""
        if self.has_credentials():
            return self.credentials.authorize(httplib2.Http())
        return None


text:
var async = require('async');

module.exports = function(app, done) {
  if(process.env.NODE_ENV !== 'production') {
    var batches, provisions;

    async.series([
      callback => app.models.ProvisionRequirement.find(callback),
      callback => app.models.Batch.find(callback)
    ], (err, results) => {
      provisions = results[0];
      batches = results[1];

      async.series(provisions.map((provision, i) => function(cb) {
        var promised = [100, 100, 100, 10, 0, 20];
        var shipped = [80, 30, 50, 5, 0, 5];
        app.models.ProvisionActivity.create({
          promised: promised[i],
          batchId: batches[0].id,
          provisionRequirementId: provision.id,
          stationId: 1
        }, function() {
          app.models.ProvisionActivity.create({
            shipped: shipped[i],
            batchId: batches[0].id,
            provisionRequirementId: provision.id,
            stationId: 1
          }, cb);
        });
      }), done);
    });
  }
  else {
    done();
  }
};


text:
<?php

namespace Surfnet\StepupMiddleware\CommandHandlingBundle\Tests\Value;

use PHPUnit\Framework\TestCase as UnitTest;
use Surfnet\StepupMiddleware\CommandHandlingBundle\Value\Institution;

class InstitutionTest extends UnitTest
{
    /**
     * @test
     * @dataProvider nonStringOrNonEmptyStringProvider
     *
     * @param mixed $invalidValue
     */
    public function an_institution_cannot_be_created_with_anything_but_a_nonempty_string($invalidValue)
    {
        $this->expectException(\Surfnet\StepupMiddleware\CommandHandlingBundle\Exception\InvalidArgumentException::class);

        new Institution($invalidValue);
    }

    /**
     * @test
     */
    public function two_institutions_with_the_same_value_are_equal()
    {
        $institution       = new Institution('a');
        $theSame           = new Institution('a');
        $theSameWithSpaces = new Institution('  a ');
        $different         = new Institution('A');

        $this->assertTrue($institution->equals($theSame));
        $this->assertTrue($institution->equals($theSameWithSpaces));
        $this->assertFalse($institution->equals($different));
    }

    public function nonStringOrNonEmptyStringProvider()
    {
        return [
            'empty string' => [''],
            'blank string' => ['   '],
            'array'        => [[]],
            'integer'      => [1],
            'float'        => [1.2],
            'object'       => [new \StdClass()],
        ];
    }
}


text:
export WANT_AUTOMAKE=1.8

aclocal --version | grep aclocal | sed s/'aclocal (GNU automake) '// | grep -q 1\.9.*
if [ $0 ]
then
    aclocal  | grep -v "underquoted definition"
    autoheader
    automake -a --warnings=none
else
    echo "Automake 1.8 is being used"
    aclocal --version | grep aclocal | sed s/'aclocal (GNU automake) '// | grep -q 1\.8.*
    if [ $0 ]
    then
	aclocal-1.8  | grep -v "underquoted definition"
	autoheader
	automake-1.8 -a --warnings=none
    else
	aclocal --version | grep aclocal | sed s/'aclocal (GNU automake) '// | grep -q 1\.5.*
	if [ $0 ]
	then
	    aclocal-1.5  | grep -v "underquoted definition"
	    autoheader
	    automake-1.5 -a --warnings=none
	else
	    echo "Error: automake 1.5 or newer is required"
	fi
    fi
fi

autoconf


text:
/* eslint-env node */
/* global describe before it */
'use strict';

const chai         = require('chai');
const expect       = chai.expect;
const fs           = require('fs-extra');
const AddonTestApp = require('ember-cli-addon-tests').AddonTestApp;

describe('with default .env path', function() {
  this.timeout(600000);

  let app;

  before(function() {
    app = new AddonTestApp();

    return app.create('dummy', { skipNpm: true })
      .then(addMissingDependencies)
      .then(installModules)
      .then(function() {
        return app.runEmberCommand('build');
      });
  });

  it('add clientAllowedKeys to <app name>/config/environment JS module', function () {
    let config = readConfig(app);

    expect(config.DOTENV_VAR).to.equal('dotenv');
  });

  it('allows to use process.env in config/environment.js', function () {
    let config = readConfig(app);

    expect(config.IN_PROCESS_ENV).to.equal('IN_PROCESS_ENV');
  });

});

describe('with custom .env path', function() {
  this.timeout(600000);

  let app;

  before(function() {
    app = new AddonTestApp();

    return app.create('custom-path', { skipNpm: true })
      .then(addMissingDependencies)
      .then(installModules)
      .then(function() {
        return app.runEmberCommand('build');
      });
  });

  it('add clientAllowedKeys to <app name>/config/environment JS module', function () {
    let config = readConfig(app);

    expect(config.DOTENV_VAR).to.equal('custom.dotenv');
  });

  it('allows to use process.env in config/environment.js', function () {
    let config = readConfig(app);

    expect(config.IN_PROCESS_ENV).to.equal('CUSTOM_IN_PROCESS_ENV');
  });

});

describe('with env specific .env path', function() {
  this.timeout(600000);

  describe('for development environment', function() {

    let app;

    before(function() {
      app = new AddonTestApp();

      return app.create('env-specific-paths', { skipNpm: true })
        .then(addMissingDependencies)
        .then(installModules)
        .then(function() {
          return app.runEmberCommand('build');
        });
    });

    it('add clientAllowedKeys to <app name>/config/environment JS module', function () {
      let config = readConfig(app);

      expect(config.DOTENV_VAR).to.equal('development.dotenv');
    });

    it('allows to use process.env in config/environment.js', function () {
      let config = readConfig(app);

      expect(config.IN_PROCESS_ENV).to.equal('DEVELOPMENT_IN_PROCESS_ENV');
    });

  });

  describe('for production environment', function() {

    let app;

    before(function() {
      app = new AddonTestApp();

      return app.create('env-specific-paths', { skipNpm: true })
        .then(addMissingDependencies)
        .then(installModules)
        .then(function() {
          return app.runEmberCommand('build', '--environment=production');
        });
    });

    it('add clientAllowedKeys to <app name>/config/environment JS module', function () {
      let config = readConfig(app);

      expect(config.DOTENV_VAR).to.equal('production.dotenv');
    });

    it('allows to use process.env in config/environment.js', function () {
      let config = readConfig(app);

      expect(config.IN_PROCESS_ENV).to.equal('PRODUCTION_IN_PROCESS_ENV');
    });

  });

  describe('for production environment alias command', function() {

    let app;

    before(function() {
      app = new AddonTestApp();

      return app.create('env-specific-paths', { skipNpm: true })
        .then(addMissingDependencies)
        .then(installModules)
        .then(function() {
          return app.runEmberCommand('build', '-prod');
        });
    });

    it('properly resolves environment name', function () {
      let config = readConfig(app);

      expect(config.DOTENV_VAR).to.equal('production.dotenv');
      expect(config.IN_PROCESS_ENV).to.equal('PRODUCTION_IN_PROCESS_ENV');
    });

  });

});

describe('generating app build with FastBoot', function() {
  this.timeout(600000);

  let app;

  before(function() {
    app = new AddonTestApp();

    return app.create('dummy', { skipNpm: true })
      .then(function(app) {
        app.editPackageJSON(pkg => {
          pkg.devDependencies['ember-cli-fastboot'] = '*';
        });

        return app;
      })
      .then(addMissingDependencies)
      .then(installModules)
      .then(function() {
        return app.runEmberCommand('build');
      });
  });

  it('provides additional config added to package.json', function () {
    let pkg = fs.readJsonSync(app.filePath('dist/package.json'));

    expect(pkg.fastboot.config.dummy.DOTENV_VAR).to.equal('dotenv');
    expect(pkg.fastboot.config.dummy.FASTBOOT_DOTENV_VAR).to.equal('fastboot dotenv');
  });

  it('fastbootAllowedKeys do not appear in <app name>/config/environment JS module', function () {
    let config = readConfig(app);

    expect(config.FASTBOOT_DOTENV_VAR).to.be.undefined;
  });

});

/**
 * Reads config from meta tag in index.html of the final build.
 *
 * @param {AddonTestApp} app
 * @return {Object}
 */
function readConfig (app) {
  let configRegExp = new RegExp(
    `<meta name="${app.appName}\\/config\\/environment" content="([a-z\\d._\\-%/\\\\]*)" \\/>`,
    'gi'
  );
  let contents = require('fs').readFileSync(app.filePath('dist/index.html'), 'utf8');

  let matches = configRegExp.exec(contents);
  return matches && matches[1] && JSON.parse(unescape(matches[1]));
}

/**
 * Adds missing dependencies.
 *
 * @param {AddonTestApp} app
 */
function addMissingDependencies (app) {
  app.editPackageJSON(function (pkg) {
    pkg.devDependencies['ember-data'] = '*';
    pkg.devDependencies['@babel/plugin-transform-block-scoping'] = '*';
    pkg.devDependencies['@babel/core'] = '*';
  });

  return app;
}

/**
 * Runs script for installing npm modules.
 *
 * @param {AddonTestApp} app
 */
function installModules (app) {
  return app.run('npm', 'install');
}


text:
export class AppError extends Error {
    /**
     * 构造函数
     */
    constructor(message) {
        super(message);
    }
}

export class DbError extends AppError {
    /**
     * 构造函数
     */
    constructor(message) {
        super(message);
    }
}

export class ArgumentError extends AppError {
    /**
     * 构造函数
     */
    constructor(message) {
        super(message);
    }
}


text:
"""
Public API for all plotting renderers supported by HoloViews,
regardless of plotting package or backend.
"""
from __future__ import unicode_literals

from io import BytesIO
import os, base64
from contextlib import contextmanager

import param
from ..core.io import Exporter
from ..core.options import Store, StoreOptions, SkipRendering
from ..core.util import find_file, unicode
from .. import Layout, HoloMap, AdjointLayout
from .widgets import NdWidget, ScrubberWidget, SelectionWidget

from .. import DynamicMap
from . import Plot
from .util import displayable, collate

from param.parameterized import bothmethod

# Tags used when visual output is to be embedded in HTML
IMAGE_TAG = ""
VIDEO_TAG = """
<video controls style='max-width:100%; margin: auto; display: block; {css}'>
<source src='{src}' type='{mime_type}'>
Your browser does not support the video tag.
</video>"""
PDF_TAG = ""
HTML_TAG = "{src}"

HTML_TAGS = {
    'base64': 'data:{mime_type};base64,{b64}', # Use to embed data
    'svg':  IMAGE_TAG,
    'png':  IMAGE_TAG,
    'gif':  IMAGE_TAG,
    'webm': VIDEO_TAG,
    'mp4':  VIDEO_TAG,
    'pdf':  PDF_TAG,
    'html': HTML_TAG
}

MIME_TYPES = {
    'svg':  'image/svg+xml',
    'png':  'image/png',
    'gif':  'image/gif',
    'webm': 'video/webm',
    'mp4':  'video/mp4',
    'pdf':  'application/pdf',
    'html':  None,
    'json':  None
}

static_template = """

    {css}
    {js}

    {html}

"""

class Renderer(Exporter):
    """
    The job of a Renderer is to turn the plotting state held within
    Plot classes into concrete, visual output in the form of the PNG,
    SVG, MP4 or WebM formats (among others). Note that a Renderer is a
    type of Exporter and must therefore follow the Exporter interface.

    The Renderer needs to be able to use the .state property of the
    appropriate Plot classes associated with that renderer in order to
    generate output. The process of 'drawing' is execute by the Plots
    and the Renderer turns the final plotting state into output.
    """

    backend = param.String(doc="""
        The full, lowercase name of the rendering backend or third
        part plotting package used e.g 'matplotlib' or 'cairo'.""")

    dpi=param.Integer(None, allow_None=True, doc="""
        The render resolution in dpi (dots per inch)""")

    fig = param.ObjectSelector(default='auto', objects=['auto'], doc="""
        Output render format for static figures. If None, no figure
        rendering will occur. """)

    fps=param.Number(20, doc="""
        Rendered fps (frames per second) for animated formats.""")

    holomap = param.ObjectSelector(default='auto',
                                   objects=['scrubber','widgets', None, 'auto'], doc="""
        Output render multi-frame (typically animated) format. If
        None, no multi-frame rendering will occur.""")

    mode = param.ObjectSelector(default='default', objects=['default'], doc="""
         The available rendering modes. As a minimum, the 'default'
         mode must be supported.""")

    size=param.Integer(100, doc="""
        The rendered size as a percentage size""")

    widget_mode = param.ObjectSelector(default='embed', objects=['embed', 'live'], doc="""
        The widget mode determining whether frames are embedded or generated
        'live' when interacting with the widget.""")

    css = param.Dict(default={},
                     doc="Dictionary of CSS attributes and values to apply to HTML output")

    info_fn = param.Callable(None, allow_None=True, constant=True,  doc="""
        Renderers do not support the saving of object info metadata""")

    key_fn = param.Callable(None, allow_None=True, constant=True,  doc="""
        Renderers do not support the saving of object key metadata""")

    post_render_hooks = param.Dict(default={'svg':[], 'png':[]}, doc="""
       Optional dictionary of hooks that are applied to the rendered
       data (according to the output format) before it is returned.

       Each hook is passed the rendered data and the object that is
       being rendered. These hooks allow post-processing of renderered
       data before output is saved to file or displayed.""")

    # Defines the valid output formats for each mode.
    mode_formats = {'fig': {'default': [None, 'auto']},
                    'holomap': {'default': [None, 'auto']}}

    # Define appropriate widget classes
    widgets = {'scrubber': ScrubberWidget, 'widgets': SelectionWidget}

    core_dependencies = {'jQueryUI': {'js': ['https://code.jquery.com/ui/1.10.4/jquery-ui.min.js'],
                                      'css': ['https://code.jquery.com/ui/1.10.4/themes/smoothness/jquery-ui.css']}}

    extra_dependencies = {'jQuery': {'js': ['https://code.jquery.com/jquery-2.1.4.min.js']},
                          'underscore': {'js': ['https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js']},
                          'require': {'js': ['https://cdnjs.cloudflare.com/ajax/libs/require.js/2.1.20/require.min.js']},
                          'bootstrap': {'css': ['https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css']}}

    # Any additional JS and CSS dependencies required by a specific backend
    backend_dependencies = {}

    def __init__(self, **params):
        self.last_plot = None
        super(Renderer, self).__init__(**params)

    @bothmethod
    def get_plot(self_or_cls, obj):
        """
        Given a HoloViews Viewable return a corresponding plot instance.
        """
        if not isinstance(obj, Plot) and not displayable(obj):
            obj = collate(obj)

        # Initialize DynamicMaps with first data item
        dmaps = obj.traverse(lambda x: x, specs=[DynamicMap])
        for dmap in dmaps:
            if dmap.sampled:
                # Skip initialization until plotting code
                continue
            if dmap.call_mode == 'key':
                dmap[dmap._initial_key()]
            else:
                try:
                    next(dmap)
                except StopIteration: # Exhausted DynamicMap
                    raise SkipRendering("DynamicMap generator exhausted.")

        if not isinstance(obj, Plot):
            obj = Layout.from_values(obj) if isinstance(obj, AdjointLayout) else obj
            plot_opts = self_or_cls.plot_options(obj, self_or_cls.size)
            plot = self_or_cls.plotting_class(obj)(obj, **plot_opts)
            plot.update(0)
        else:
            plot = obj
        return plot

    def _validate(self, obj, fmt):
        """
        Helper method to be used in the __call__ method to get a
        suitable plot or widget object and the appropriate format.
        """
        if isinstance(obj, tuple(self.widgets.values())):
            return obj, 'html'
        plot = self.get_plot(obj)

        fig_formats = self.mode_formats['fig'][self.mode]
        holomap_formats = self.mode_formats['holomap'][self.mode]

        if fmt in ['auto', None]:
            if ((len(plot) == 1 and not plot.dynamic)
                or (len(plot) > 1 and self.holomap is None)):
                fmt = fig_formats[0] if self.fig=='auto' else self.fig
            else:
                fmt = holomap_formats[0] if self.holomap=='auto' else self.holomap

        if fmt in self.widgets:
            plot = self.get_widget(plot, fmt, display_options={'fps': self.fps})
            fmt = 'html'

        all_formats = set(fig_formats + holomap_formats)
        if fmt not in all_formats:
            raise Exception("Format %r not supported by mode %r. Allowed formats: %r"
                            % (fmt, self.mode, fig_formats + holomap_formats))
        self.last_plot = plot
        return plot, fmt

    def __call__(self, obj, fmt=None):
        """
        Render the supplied HoloViews component or plot instance using
        the appropriate backend. The output is not a file format but a
        suitable, in-memory byte stream together with any suitable
        metadata.
        """
        plot, fmt =  self._validate(obj, fmt)
        if plot is None: return
        # [Backend specific code goes here to generate data]
        data = None

        # Example of how post_render_hooks are applied
        data = self._apply_post_render_hooks(data, obj, fmt)
        # Example of the return format where the first value is the rendered data.
        return data, {'file-ext':fmt, 'mime_type':MIME_TYPES[fmt]}

    def _apply_post_render_hooks(self, data, obj, fmt):
        """
        Apply the post-render hooks to the data.
        """
        hooks = self.post_render_hooks.get(fmt,[])
        for hook in hooks:
            try:
                data = hook(data, obj)
            except Exception as e:
                self.warning("The post_render_hook %r could not be applied:\n\n %s"
                             % (hook, e))
        return data

    def html(self, obj, fmt=None, css=None):
        """
        Renders plot or data structure and wraps the output in HTML.
        """
        plot, fmt =  self._validate(obj, fmt)
        figdata, _ = self(plot, fmt)
        if css is None: css = self.css

        if fmt in ['html', 'json']:
            return figdata
        else:
            if fmt == 'svg':
                figdata = figdata.encode("utf-8")
            elif fmt == 'pdf' and 'height' not in css:
                _, h = self.get_size(plot)
                css['height'] = '%dpx' % (h*self.dpi*1.15)

        if isinstance(css, dict):
            css = '; '.join("%s: %s" % (k, v) for k, v in css.items())
        else:
            raise ValueError("CSS must be supplied as Python dictionary")

        b64 = base64.b64encode(figdata).decode("utf-8")
        (mime_type, tag) = MIME_TYPES[fmt], HTML_TAGS[fmt]
        src = HTML_TAGS['base64'].format(mime_type=mime_type, b64=b64)
        return tag.format(src=src, mime_type=mime_type, css=css)

    def static_html(self, obj, fmt=None, template=None):
        """
        Generates a static HTML with the rendered object in the
        supplied format. Allows supplying a template formatting string
        with fields to interpolate 'js', 'css' and the main 'html'.
        """
        js_html, css_html = self.html_assets()
        if template is None: template = static_template
        html = self.html(obj, fmt)
        return template.format(js=js_html, css=css_html, html=html)

    @bothmethod
    def get_widget(self_or_cls, plot, widget_type, **kwargs):
        if not isinstance(plot, Plot):
            plot = self_or_cls.get_plot(plot)
        dynamic = plot.dynamic
        if widget_type == 'auto':
            isuniform = plot.uniform
            if not isuniform:
                widget_type = 'scrubber'
            else:
                widget_type = 'widgets'
        elif dynamic == 'open': widget_type = 'scrubber'
        elif dynamic == 'bounded': widget_type = 'widgets'
        elif widget_type == 'widgets' and dynamic == 'open':
            raise ValueError('Selection widgets not supported in dynamic open mode')
        elif widget_type == 'scrubber' and dynamic == 'bounded':
            raise ValueError('Scrubber widget not supported in dynamic bounded mode')

        if widget_type in [None, 'auto']:
            holomap_formats = self_or_cls.mode_formats['holomap'][self_or_cls.mode]
            widget_type = holomap_formats[0] if self_or_cls.holomap=='auto' else self_or_cls.holomap

        widget_cls = self_or_cls.widgets[widget_type]
        return widget_cls(plot, renderer=self_or_cls.instance(),
                          embed=self_or_cls.widget_mode == 'embed', **kwargs)

    @bothmethod
    def export_widgets(self_or_cls, obj, filename, fmt=None, template=None,
                       json=False, json_path='', **kwargs):
        """
        Render and export object as a widget to a static HTML
        file. Allows supplying a custom template formatting string
        with fields to interpolate 'js', 'css' and the main 'html'
        containing the widget. Also provides options to export widget
        data to a json file in the supplied json_path (defaults to
        current path).
        """
        if fmt not in list(self_or_cls.widgets.keys())+['auto', None]:
            raise ValueError("Renderer.export_widget may only export "
                             "registered widget types.")

        if not isinstance(obj, NdWidget):
            if not isinstance(filename, BytesIO):
                filedir = os.path.dirname(filename)
                current_path = os.getcwd()
                html_path = os.path.abspath(filedir)
                rel_path = os.path.relpath(html_path, current_path)
                save_path = os.path.join(rel_path, json_path)
            else:
                save_path = json_path
            kwargs['json_save_path'] = save_path
            kwargs['json_load_path'] = json_path
            widget = self_or_cls.get_widget(obj, fmt, **kwargs)
        else:
            widget = obj

        html = self_or_cls.static_html(widget, fmt, template)
        if isinstance(filename, BytesIO):
            filename.write(html)
            filename.seek(0)
        else:
            with open(filename, 'w') as f:
                f.write(html)

    @classmethod
    def plotting_class(cls, obj):
        """
        Given an object or Element class, return the suitable plotting
        class needed to render it with the current renderer.
        """
        if isinstance(obj, AdjointLayout) or obj is AdjointLayout:
            obj  = Layout
        if isinstance(obj, type):
            element_type = obj
        else:
            element_type = obj.type if isinstance(obj, HoloMap) else type(obj)
        try:
            plotclass = Store.registry[cls.backend][element_type]
        except KeyError:
            raise SkipRendering("No plotting class for {0} "
                                "found".format(element_type.__name__))
        return plotclass

    @classmethod
    def html_assets(cls, core=True, extras=True, backends=None):
        """
        Returns JS and CSS and for embedding of widgets.
        """
        if backends is None:
            backends = [cls.backend] if cls.backend else []

        # Get all the widgets and find the set of required js widget files
        widgets = [wdgt for r in Renderer.__subclasses__()
                   for wdgt in r.widgets.values()]
        css = list({wdgt.css for wdgt in widgets})
        basejs = list({wdgt.basejs for wdgt in widgets})
        extensionjs = list({wdgt.extensionjs for wdgt in widgets})

        # Join all the js widget code into one string
        path = os.path.dirname(os.path.abspath(__file__))
        widgetjs = '\n'.join(open(find_file(path, f), 'r').read()
                             for f in basejs + extensionjs
                             if f is not None )
        widgetcss = '\n'.join(open(find_file(path, f), 'r').read()
                              for f in css if f is not None)

        dependencies = {}
        if core:
            dependencies.update(cls.core_dependencies)
        if extras:
            dependencies.update(cls.extra_dependencies)
        for backend in backends:
            dependencies['backend'] = Store.renderers[backend].backend_dependencies

        js_html, css_html = '', ''
        for _, dep in sorted(dependencies.items(), key=lambda x: x[0]):
            js_data = dep.get('js', [])
            if isinstance(js_data, tuple):
                for js in js_data:
                    js_html += '\n' % js
            else:
                for js in js_data:
                    js_html += '\n' % js
            css_data = dep.get('css', [])
            if isinstance(js_data, tuple):
                for css in css_data:
                    css_html += '\n' % css
            else:
                for css in css_data:
                    css_html += '\n<link rel="stylesheet" href="%s">' % css

        js_html += '\n' % widgetjs
        css_html += '\n' % widgetcss

        return unicode(js_html), unicode(css_html)

    @classmethod
    def plot_options(cls, obj, percent_size):
        """
        Given an object and a percentage size (as supplied by the
        %output magic) return all the appropriate plot options that
        would be used to instantiate a plot class for that element.

        Default plot sizes at the plotting class level should be taken
        into account.
        """
        raise NotImplementedError

    @bothmethod
    def save(self_or_cls, obj, basename, fmt='auto', key={}, info={}, options=None, **kwargs):
        """
        Save a HoloViews object to file, either using an explicitly
        supplied format or to the appropriate default.
        """
        if info or key:
            raise Exception('MPLRenderer does not support saving metadata to file.')

        with StoreOptions.options(obj, options, **kwargs):
            plot = self_or_cls.get_plot(obj)

        if (fmt in list(self_or_cls.widgets.keys())+['auto']) and len(plot) > 1:
            with StoreOptions.options(obj, options, **kwargs):
                self_or_cls.export_widgets(plot, basename+'.html', fmt)
            return

        with StoreOptions.options(obj, options, **kwargs):
            rendered = self_or_cls(plot, fmt)
        if rendered is None: return
        (data, info) = rendered
        if isinstance(basename, BytesIO):
            basename.write(data)
            basename.seek(0)
        else:
            encoded = self_or_cls.encode(rendered)
            filename ='%s.%s' % (basename, info['file-ext'])
            with open(filename, 'wb') as f:
                f.write(encoded)

    @bothmethod
    def get_size(self_or_cls, plot):
        """
        Return the display size associated with a plot before
        rendering to any particular format. Used to generate
        appropriate HTML display.

        Returns a tuple of (width, height) in pixels.
        """
        raise NotImplementedError

    @classmethod
    @contextmanager
    def state(cls):
        """
        Context manager to handle global state for a backend,
        allowing Plot classes to temporarily override that state.
        """
        yield

    @classmethod
    def validate(cls, options):
        """
        Validate an options dictionary for the renderer.
        """
        return options

    @classmethod
    def load_nb(cls, inline=True):
        """
        Loads any resources required for display of plots
        in the Jupyter notebook
        """


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<meta name="generator" content="Doxygen 1.8.11"/>
<title>Csound API: Data Fields - Variables</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>

<link href="navtree.css" rel="stylesheet" type="text/css"/>

<link href="search/search.css" rel="stylesheet" type="text/css"/>

<link href="doxygen.css" rel="stylesheet" type="text/css" />

Csound API
    6.07

Main Page

Modules

Data Structures

Files

          <input type="text" id="MSearchField" value="Search" accesskey="S"
               onfocus="searchBox.OnSearchFieldFocus(true)"
               onblur="searchBox.OnSearchFieldFocus(false)"
               onkeyup="searchBox.OnSearchFieldChange(event)"/>

Data Structures

Data Structure Index

Data Fields

All

Variables

_

a

b

c

d

e

f

g

h

i

j

k

l

m

n

o

p

q

r

s

t

u

v

w

x

y

z

- b -

barrier1
: CSOUND_

barrier2
: CSOUND_

baseFreq
: SNDMEMFILE_

bData
: MIDIMESSAGE

Beatmode
: OPARMS

beatOffs
: CSOUND_

begin1
: FUNC

begin2
: FUNC

beginp
: MEMFIL

begp
: OCTDAT

behav
: controlChannelHints_s

bkpt_anchor
: csdebug_data_s

bkpt_buffer
: csdebug_data_s

bkpt_cb
: csdebug_data_s

body
: CORFIL
, S_MACRO

bp
: CSOUND_::sreadStatics__

breakpointInstr
: debug_bkpt_info_t

buffer_frames
: CSOUND_PARAMS

bufp
: midiglobals

bufSamp_HW
: csRtAudioParams

bufSamp_SW
: csRtAudioParams

Generated by

     1.8.11


text:
require "rails_helper"

RSpec.describe ApplicationMailer do
  let(:application_pdf) { Tempfile.new }

  describe ".snap_application_notification" do
    it "sets the correct headers" do
      with_modified_env EMAIL_DOMAIN: "example.com" do
        email = ApplicationMailer.snap_application_notification(
          application_pdf: application_pdf,
          recipient_email: "user@example.com",
        )
        from_header = email.header.select do |header|
          header.name == "From"
        end.first.value

        expect(from_header).to eq %("Michigan Benefits" <hello@example.com>)
        expect(email.from).to eq(["hello@example.com"])
        expect(email.to).to eq(["user@example.com"])
        expect(email.subject).to eq("Your SNAP application")
      end
    end

    it "attaches the application PDF with correct name" do
      email = ApplicationMailer.snap_application_notification(
        application_pdf: application_pdf,
        recipient_email: "user@example.com",
      )
      attachment_filename = email.attachments.first.filename

      expect(email.attachments.count).to eq(1)
      expect(attachment_filename).to eq("snap_application.pdf")
    end
  end

  describe ".client_integrated_application_notification" do
    it "sets the correct headers" do
      with_modified_env EMAIL_DOMAIN: "example.com" do
        email = ApplicationMailer.client_integrated_application_notification(
          application_pdf: application_pdf,
          recipient_email: "user@example.com",
        )
        from_header = email.header.select do |header|
          header.name == "From"
        end.first.value

        expect(from_header).to eq %("Michigan Benefits" <hello@example.com>)
        expect(email.from).to eq(["hello@example.com"])
        expect(email.to).to eq(["user@example.com"])
        expect(email.subject).to eq("Your FAP + Medicaid application")
      end
    end

    it "attaches the application PDF with correct name" do
      email = ApplicationMailer.client_integrated_application_notification(
        application_pdf: application_pdf,
        recipient_email: "user@example.com",
      )
      attachment_filename = email.attachments.first.filename

      expect(email.attachments.count).to eq(1)
      expect(attachment_filename).to eq("integrated_application.pdf")
    end
  end

  describe ".office_snap_application_notification" do
    context "office_location not present" do
      it "sets the correct headers" do
        time = Time.utc(2017, 12, 30, 10, 5, 0)
        Timecop.freeze(time) do
          with_modified_env EMAIL_DOMAIN: "example.com" do
            email = ApplicationMailer.office_snap_application_notification(
              application_pdf: application_pdf,
              recipient_email: "user@example.com",
              applicant_name: "Alice Algae",
            )
            from_header = email.header.select do |header|
              header.name == "From"
            end.first.value

            expect(from_header).to eq %("Michigan Benefits" <hello@example.com>)
            expect(email.from).to eq(["hello@example.com"])
            expect(email.to).to eq(["user@example.com"])
            expect(email.subject).to eq(
              "A new 1171 from Alice Algae (online) was submitted!",
            )
            expect(email.body.encoded).not_to include(
              "client in your office lobby",
            )
            expect(email.attachments[0].filename).to eq(
              "2017-12-30 Alice Algae 1171.pdf",
            )
          end
        end
      end
    end

    context "office_location present" do
      it "sets the correct values" do
        time = Time.utc(2008, 9, 1, 10, 5, 0)
        Timecop.freeze(time) do
          with_modified_env EMAIL_DOMAIN: "example.com" do
            email = ApplicationMailer.office_snap_application_notification(
              application_pdf: application_pdf,
              recipient_email: "user@example.com",
              office_location: "union",
              applicant_name: "Freddy Fungus",
            )

            from_header = email.header.select do |header|
              header.name == "From"
            end.first.value

            expect(from_header).to eq %("Michigan Benefits" <hello@example.com>)
            expect(email.from).to eq(["hello@example.com"])
            expect(email.to).to eq(["user@example.com"])
            expect(email.subject).to eq(
              "A new 1171 from Freddy Fungus (in the lobby) was submitted!",
            )
            expect(email.body.encoded).to include(
              "Union",
            )
            expect(email.body.encoded).to include(
              "client in your office lobby",
            )
            expect(email.attachments[0].filename).to eq(
              "2008-09-01 Freddy Fungus 1171.pdf",
            )
          end
        end
      end
    end
  end

  describe ".office_medicaid_application_notification" do
    it "sets the correct headers" do
      time = Time.utc(1999, 1, 1, 10, 5, 0)
      Timecop.freeze(time) do
        with_modified_env EMAIL_DOMAIN: "example.com" do
          email = ApplicationMailer.office_medicaid_application_notification(
            application_pdf: application_pdf,
            recipient_email: "user@example.com",
            applicant_name: "Larry Lichen",
          )

          from_header = email.header.select do |header|
            header.name == "From"
          end.first.value

          expect(from_header).to eq %("Michigan Benefits" <hello@example.com>)
          expect(email.from).to eq(["hello@example.com"])
          expect(email.to).to eq(["user@example.com"])
          expect(email.subject).to eq(
            "A new 1426 from Larry Lichen was submitted!",
          )
          expect(email.attachments[0].filename).to eq(
            "1999-01-01 Larry Lichen 1426.pdf",
          )
        end
      end
    end
  end

  describe ".office_integrated_application_notification" do
    it "sets the correct headers" do
      time = Time.utc(1999, 1, 1, 10, 5, 0)
      Timecop.freeze(time) do
        with_modified_env EMAIL_DOMAIN: "example.com" do
          email = ApplicationMailer.office_integrated_application_notification(
            application_pdf: application_pdf,
            recipient_email: "user@example.com",
            applicant_name: "Larry Lichen",
          )

          from_header = email.header.select do |header|
            header.name == "From"
          end.first.value

          expect(from_header).to eq %("Michigan Benefits" <hello@example.com>)
          expect(email.from).to eq(["hello@example.com"])
          expect(email.to).to eq(["user@example.com"])
          expect(email.subject).to eq(
            "A new 1171 from Larry Lichen was submitted!",
          )
          expect(email.attachments[0].filename).to eq(
            "1999-01-01 Larry Lichen 1171.pdf",
          )
        end
      end
    end
  end
end


text:
require 'name_search'
require 'rails'

module NameSearch
  class Railtie < Rails::Railtie
    rake_tasks do
      load 'name_search/railties/tasks.rake'
    end
  end
end


text:
package mil.nga.giat.geowave.adapter.vector.plugin;

import java.io.IOException;
import java.net.URI;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import org.apache.log4j.Logger;
import org.geotools.data.FeatureListenerManager;
import org.geotools.data.Query;
import org.geotools.data.Transaction;
import org.geotools.data.store.ContentDataStore;
import org.geotools.data.store.ContentEntry;
import org.geotools.data.store.ContentFeatureSource;
import org.geotools.feature.NameImpl;
import org.geotools.referencing.CRS;
import org.opengis.feature.simple.SimpleFeature;
import org.opengis.feature.simple.SimpleFeatureType;
import org.opengis.feature.type.Name;
import org.opengis.referencing.FactoryException;
import org.opengis.referencing.crs.CoordinateReferenceSystem;

import mil.nga.giat.geowave.adapter.vector.FeatureDataAdapter;
import mil.nga.giat.geowave.adapter.vector.GeotoolsFeatureDataAdapter;
import mil.nga.giat.geowave.adapter.vector.auth.AuthorizationSPI;
import mil.nga.giat.geowave.adapter.vector.index.IndexQueryStrategySPI;
import mil.nga.giat.geowave.adapter.vector.index.SimpleFeaturePrimaryIndexConfiguration;
import mil.nga.giat.geowave.adapter.vector.plugin.lock.LockingManagement;
import mil.nga.giat.geowave.adapter.vector.plugin.transaction.GeoWaveAutoCommitTransactionState;
import mil.nga.giat.geowave.adapter.vector.plugin.transaction.GeoWaveTransactionManagementState;
import mil.nga.giat.geowave.adapter.vector.plugin.transaction.GeoWaveTransactionState;
import mil.nga.giat.geowave.adapter.vector.plugin.transaction.MemoryTransactionsAllocator;
import mil.nga.giat.geowave.adapter.vector.plugin.transaction.TransactionsAllocator;
import mil.nga.giat.geowave.adapter.vector.plugin.visibility.VisibilityManagementHelper;
import mil.nga.giat.geowave.core.geotime.ingest.SpatialDimensionalityTypeProvider;
import mil.nga.giat.geowave.core.geotime.store.dimension.LatitudeField;
import mil.nga.giat.geowave.core.geotime.store.dimension.LongitudeField;
import mil.nga.giat.geowave.core.geotime.store.dimension.TimeField;
import mil.nga.giat.geowave.core.index.ByteArrayId;
import mil.nga.giat.geowave.core.index.StringUtils;
import mil.nga.giat.geowave.core.store.AdapterToIndexMapping;
import mil.nga.giat.geowave.core.store.CloseableIterator;
import mil.nga.giat.geowave.core.store.DataStore;
import mil.nga.giat.geowave.core.store.adapter.AdapterIndexMappingStore;
import mil.nga.giat.geowave.core.store.adapter.AdapterStore;
import mil.nga.giat.geowave.core.store.adapter.DataAdapter;
import mil.nga.giat.geowave.core.store.adapter.statistics.DataStatisticsStore;
import mil.nga.giat.geowave.core.store.data.visibility.VisibilityManagement;
import mil.nga.giat.geowave.core.store.dimension.NumericDimensionField;
import mil.nga.giat.geowave.core.store.index.Index;
import mil.nga.giat.geowave.core.store.index.IndexStore;
import mil.nga.giat.geowave.core.store.index.PrimaryIndex;
import mil.nga.giat.geowave.core.store.query.EverythingQuery;
import mil.nga.giat.geowave.core.store.query.QueryOptions;

public class GeoWaveGTDataStore extends
		ContentDataStore
{
	/** Package logger */
	private final static Logger LOGGER = Logger.getLogger(GeoWaveGTDataStore.class);
	public static final CoordinateReferenceSystem DEFAULT_CRS;

	static {
		try {
			DEFAULT_CRS = CRS.decode(
					"EPSG:4326",
					true);
		}
		catch (final FactoryException e) {
			LOGGER.error(
					"Unable to decode EPSG:4326 CRS",
					e);
			throw new RuntimeException(
					"Unable to initialize EPSG:4326 object",
					e);
		}
	}

	private FeatureListenerManager listenerManager = null;
	protected AdapterStore adapterStore;
	protected IndexStore indexStore;
	protected DataStatisticsStore dataStatisticsStore;
	protected DataStore dataStore;
	protected AdapterIndexMappingStore adapterIndexMappingStore;
	private final Map<String, PrimaryIndex[]> preferredIndexes = new ConcurrentHashMap<String, PrimaryIndex[]>();

	private final VisibilityManagement<SimpleFeature> visibilityManagement = VisibilityManagementHelper
			.loadVisibilityManagement();
	private final AuthorizationSPI authorizationSPI;
	private final IndexQueryStrategySPI indexQueryStrategy;
	private final URI featureNameSpaceURI;
	private int transactionBufferSize = 10000;
	private final TransactionsAllocator transactionsAllocator;

	public GeoWaveGTDataStore(
			final GeoWavePluginConfig config )
			throws IOException {
		listenerManager = new FeatureListenerManager();
		lockingManager = config.getLockingManagementFactory().createLockingManager(
				config);
		authorizationSPI = config.getAuthorizationFactory().create(
				config.getAuthorizationURL());
		init(config);
		featureNameSpaceURI = config.getFeatureNamespace();
		indexQueryStrategy = config.getIndexQueryStrategy();
		transactionBufferSize = config.getTransactionBufferSize();
		transactionsAllocator = new MemoryTransactionsAllocator();
	}

	private void init(
			final GeoWavePluginConfig config ) {
		dataStore = config.getDataStore();
		dataStatisticsStore = config.getDataStatisticsStore();
		indexStore = config.getIndexStore();
		adapterStore = config.getAdapterStore();
		adapterIndexMappingStore = config.getAdapterIndexMappingStore();
	}

	public AuthorizationSPI getAuthorizationSPI() {
		return authorizationSPI;
	}

	public FeatureListenerManager getListenerManager() {
		return listenerManager;
	}

	public IndexQueryStrategySPI getIndexQueryStrategy() {
		return indexQueryStrategy;
	}

	public DataStore getDataStore() {
		return dataStore;
	}

	public AdapterStore getAdapterStore() {
		return adapterStore;
	}

	public IndexStore getIndexStore() {
		return indexStore;
	}

	public DataStatisticsStore getDataStatisticsStore() {
		return dataStatisticsStore;
	}

	protected PrimaryIndex[] getIndicesForAdapter(
			final GeotoolsFeatureDataAdapter adapter ) {
		PrimaryIndex[] currentSelections = preferredIndexes.get(adapter.getType().getName().toString());
		if (currentSelections != null) {
			return currentSelections;
		}
		final AdapterToIndexMapping adapterIndexMapping = adapterIndexMappingStore.getIndicesForAdapter(adapter
				.getAdapterId());
		if (adapterIndexMapping != null && adapterIndexMapping.isNotEmpty()) {
			currentSelections = adapterIndexMapping.getIndices(this.indexStore);
		}
		else {
			currentSelections = getPreferredIndices(adapter);
		}
		preferredIndexes.put(
				adapter.getType().getName().toString(),
				currentSelections);
		return currentSelections;
	}

	@Override
	public void createSchema(
			final SimpleFeatureType featureType ) {
		if (featureType.getGeometryDescriptor() == null) {
			throw new UnsupportedOperationException(
					"Schema missing geometry");
		}
		final FeatureDataAdapter adapter = new FeatureDataAdapter(
				featureType,
				visibilityManagement);
		if (featureNameSpaceURI != null) {
			adapter.setNamespace(featureNameSpaceURI.toString());
		}

		adapterStore.addAdapter(adapter);
	}

	private GeotoolsFeatureDataAdapter getAdapter(
			final String typeName ) {
		final GeotoolsFeatureDataAdapter featureAdapter;
		final DataAdapter<?> adapter = adapterStore.getAdapter(new ByteArrayId(
				StringUtils.stringToBinary(typeName)));
		if ((adapter == null) || !(adapter instanceof GeotoolsFeatureDataAdapter)) {
			return null;
		}
		featureAdapter = (GeotoolsFeatureDataAdapter) adapter;
		if (featureNameSpaceURI != null) {
			if (adapter instanceof FeatureDataAdapter) {
				((FeatureDataAdapter) featureAdapter).setNamespace(featureNameSpaceURI.toString());
			}
		}
		return featureAdapter;
	}

	@Override
	protected List<Name> createTypeNames()
			throws IOException {
		final List<Name> names = new ArrayList<>();
		final CloseableIterator<DataAdapter<?>> adapters = adapterStore.getAdapters();
		while (adapters.hasNext()) {
			final DataAdapter<?> adapter = adapters.next();
			if (adapter instanceof GeotoolsFeatureDataAdapter) {
				names.add(((GeotoolsFeatureDataAdapter) adapter).getType().getName());
			}
		}
		adapters.close();
		return names;
	}

	@Override
	public ContentFeatureSource getFeatureSource(
			final String typeName )
			throws IOException {
		return getFeatureSource(
				typeName,
				Transaction.AUTO_COMMIT);
	}

	@Override
	public ContentFeatureSource getFeatureSource(
			final String typeName,
			final Transaction tx )
			throws IOException {
		return super.getFeatureSource(
				new NameImpl(
						null,
						typeName),
				tx);
	}

	@Override
	public ContentFeatureSource getFeatureSource(
			final Name typeName,
			final Transaction tx )
			throws IOException {
		return getFeatureSource(
				typeName.getLocalPart(),
				tx);

	}

	@Override
	public ContentFeatureSource getFeatureSource(
			final Name typeName )
			throws IOException {
		return getFeatureSource(
				typeName.getLocalPart(),
				Transaction.AUTO_COMMIT);
	}

	@Override
	protected ContentFeatureSource createFeatureSource(
			final ContentEntry entry )
			throws IOException {
		return new GeoWaveFeatureSource(
				entry,
				Query.ALL,
				getAdapter(entry.getTypeName()),
				transactionsAllocator);
	}

	@Override
	public void removeSchema(
			final Name typeName )
			throws IOException {
		this.removeSchema(typeName.getLocalPart());
	}

	@Override
	public void removeSchema(
			final String typeName )
			throws IOException {
		final DataAdapter<?> adapter = adapterStore.getAdapter(new ByteArrayId(
				StringUtils.stringToBinary(typeName)));
		if (adapter != null) {
			final String[] authorizations = getAuthorizationSPI().getAuthorizations();
			dataStore.delete(
					new QueryOptions(
							adapter,
							authorizations),
					new EverythingQuery());
			// TODO do we want to delete the adapter from the adapter store?
		}
	}

	/**
	 * Used to retrieve the TransactionStateDiff for this transaction.
	 * <p>
	 *
	 * @param transaction
	 * @return GeoWaveTransactionState or null if subclass is handling
	 *         differences
	 * @throws IOException
	 */
	protected GeoWaveTransactionState getMyTransactionState(
			final Transaction transaction,
			final GeoWaveFeatureSource source )
			throws IOException {
		synchronized (transaction) {
			GeoWaveTransactionState state = null;
			if (transaction == Transaction.AUTO_COMMIT) {
				state = new GeoWaveAutoCommitTransactionState(
						source);
			}
			else {
				state = (GeoWaveTransactionState) transaction.getState(this);
				if (state == null) {
					state = new GeoWaveTransactionManagementState(
							transactionBufferSize,
							source.getComponents(),
							transaction,
							(LockingManagement) lockingManager);
					transaction.putState(
							this,
							state);
				}
			}
			return state;
		}
	}

	public PrimaryIndex[] getPreferredIndices(
			final GeotoolsFeatureDataAdapter adapter ) {

		List<PrimaryIndex> currentSelectionsList = new ArrayList<PrimaryIndex>(
				2);
		final List<String> indexNames = SimpleFeaturePrimaryIndexConfiguration.getIndexNames(adapter.getType());
		final boolean canUseTime = adapter.hasTemporalConstraints();

		/**
		 * Requires the indices to EXIST prior to set up of the adapter.
		 * Otherwise, only Geospatial is chosen and the index Names are ignored.
		 */
		try (CloseableIterator<Index<?, ?>> indices = indexStore.getIndices()) {
			while (indices.hasNext()) {
				Index<?, ?> nextIndex = indices.next();
				if (!(nextIndex instanceof PrimaryIndex)) continue;
				final PrimaryIndex index = (PrimaryIndex) nextIndex;

				if (!indexNames.isEmpty()) {
					// Only used selected preferred indices
					if (indexNames.contains(index.getId().getString())) {
						currentSelectionsList.add(index);
					}
				}
				@SuppressWarnings("rawtypes")
				final NumericDimensionField[] dims = index.getIndexModel().getDimensions();
				boolean hasLat = false;
				boolean hasLong = false;
				boolean hasTime = false;
				for (final NumericDimensionField<?> dim : dims) {
					hasLat |= dim instanceof LatitudeField;
					hasLong |= dim instanceof LongitudeField;
					hasTime |= dim instanceof TimeField;
				}

				if (hasLat && hasLong) {
					// If not requiring time OR (requires time AND has time
					// constraints)
					if (!hasTime || canUseTime) {
						currentSelectionsList.add(index);
					}
				}
			}
		}
		catch (final IOException ex) {
			LOGGER.error(
					"Cannot close index iterator.",
					ex);
		}

		if (currentSelectionsList.isEmpty())
			currentSelectionsList.add(new SpatialDimensionalityTypeProvider().createPrimaryIndex());

		return currentSelectionsList.toArray(new PrimaryIndex[currentSelectionsList.size()]);
	}
}


text:
package ratelimiter

import (
	"fmt"
	"net"
	"net/http"
	"sync"
	"time"

	"github.com/getlantern/golog"
	"github.com/getlantern/http-proxy/filters"
	"github.com/hashicorp/golang-lru"
)

var log = golog.LoggerFor("ratelimiter")

type ratelimiter struct {
	hostPeriods          map[string]time.Duration
	hostAccessesByClient *lru.Cache
	mx                   sync.Mutex
}

// New creates a new rate limiting filter that only allows access to the hosts
// listed in the given hostPeriods, and limits the periodicity of requests to
// each host to the given duration. It limits the number of clients tracked to
// the the numClients with the most recent activity.
func New(numClients int, hostPeriods map[string]time.Duration) filters.Filter {
	if numClients <= 0 {
		numClients = 5000
	}
	// We can safely ignore the error, since the only thing that would cause an
	// error is numClients <= 0
	cache, _ := lru.New(numClients)
	return &ratelimiter{
		hostPeriods:          hostPeriods,
		hostAccessesByClient: cache,
	}
}

func (f *ratelimiter) Apply(resp http.ResponseWriter, req *http.Request, next filters.Next) error {
	err := f.verifyAllowed(resp, req, next)
	if err != nil {
		return fail(resp, err)
	}
	return next()
}

func (f *ratelimiter) verifyAllowed(resp http.ResponseWriter, req *http.Request, next filters.Next) error {
	host, _, err := net.SplitHostPort(req.Host)
	if err != nil {
		host = req.Host
	}
	client, _, _ := net.SplitHostPort(req.RemoteAddr)
	now := time.Now()

	f.mx.Lock()
	defer f.mx.Unlock()
	period := f.hostPeriods[host]
	if period == 0 {
		return fmt.Errorf("Access to %v not allowed", host)
	}
	var hostAccesses map[string]time.Time
	_hostAccesses, found := f.hostAccessesByClient.Get(client)
	if found {
		hostAccesses = _hostAccesses.(map[string]time.Time)
	} else {
		hostAccesses = make(map[string]time.Time)
	}
	allowed := now.Sub(hostAccesses[host]) > period
	if allowed {
		hostAccesses[host] = now
		f.hostAccessesByClient.Add(client, hostAccesses)
	}
	if !allowed {
		return fmt.Errorf("Rate limit for %v exceeded", host)
	}

	return nil
}

func fail(resp http.ResponseWriter, err error) error {
	resp.WriteHeader(http.StatusForbidden)
	fmt.Fprint(resp, err)
	return filters.Stop()
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
  <component name="DaemonCodeAnalyzer">
    <disable_hints />
  </component>
  <component name="DependencyValidationManager">
    <option name="SKIP_IMPORT_STATEMENTS" value="false" />
  </component>
  <component name="Encoding" useUTFGuessing="true" native2AsciiForPropertiesFiles="false" />
  <component name="ProjectDictionaryState">
    <dictionary name="bk" />
  </component>
  <component name="ProjectInspectionProfilesVisibleTreeState">
    <entry key="Project Default">
      <profile-state>
        <expanded-state>
          <State>
            <id />
          </State>
        </expanded-state>
        <selected-state>
          <State>
            <id>Buildout</id>
          </State>
        </selected-state>
      </profile-state>
    </entry>
  </component>
  <component name="ProjectLevelVcsManager" settingsEditedManually="false">
    <OptionsSetting value="true" id="Add" />
    <OptionsSetting value="true" id="Remove" />
    <OptionsSetting value="true" id="Checkout" />
    <OptionsSetting value="true" id="Update" />
    <OptionsSetting value="true" id="Status" />
    <OptionsSetting value="true" id="Edit" />
    <ConfirmationsSetting value="0" id="Add" />
    <ConfirmationsSetting value="0" id="Remove" />
  </component>
  <component name="ProjectModuleManager">
    <modules />
  </component>
  <component name="ProjectRootManager" version="2" project-jdk-name="Python 2.7.6 (/usr/bin/python)" project-jdk-type="Python SDK" />
  <component name="PropertiesComponent">
    <property name="options.lastSelected" value="configurable.group.tools" />
    <property name="options.splitter.main.proportions" value="0.3" />
    <property name="options.splitter.details.proportions" value="0.2" />
  </component>
  <component name="PyConsoleOptionsProvider">
    <option name="myPythonConsoleState">
      <console-settings />
    </option>
  </component>
  <component name="RunManager">
    <list size="0" />
  </component>
  <component name="VcsContentAnnotationSettings">
    <option name="myLimit" value="2678400000" />
  </component>
  <component name="VcsManagerConfiguration">
    <option name="myTodoPanelSettings">
      <TodoPanelSettings />
    </option>
  </component>
  <component name="masterDetails">
    <states>
      <state key="ScopeChooserConfigurable.UI">
        <settings>
          <splitter-proportions>
            <option name="proportions">
              <list>
                <option value="0.2" />
              </list>
            </option>
          </splitter-proportions>
        </settings>
      </state>
    </states>
  </component>
</project>


text:
import './styles';
import { exportEntity } from 'odgn-entity/src/util/export/json';
import { Entity } from 'odgn-entity/src/entity';
import { EntitySet } from 'odgn-entity/src/entity_set';
import { stringify, truncate } from '@odgn/utils';
import { Fragment } from 'react';

// export const dst = 'entity.html';

export default ({ InlineCSS, e, es, site, ...args }) => {

    return <>
        <InlineCSS />
        {entityTo(es, e)}
    </>;
}

function entityTo(es: EntitySet, e: Entity) {
    const json = exportEntity(es, e, { comName: true });

    // let result = [];
    let coms = [];
    for (const com of json.components) {
        const { '@d': did, '@dn': name, ...attrs } = com;
        coms.push({ name, did, attrs });
    }

    return
        e{json.id}
        {coms.map(({ did, name, attrs }, idx) =>

{name}

                {Object.entries(attrs).map(([attr, val]) => (
                    <Fragment key={`${did}`}>

{attr}

{stringify(val)}

                    </Fragment>
                ))}

        )}
    ;
}


text:
from django.apps import AppConfig

class VulnConfig(AppConfig):
    name = 'vuln'


text:
require File.expand_path('../spec_helper', __FILE__)

module CLAideCompletion
  describe Generator do
    before do
      @subject = Generator
    end

    describe '::generate' do
      it 'returns the completion helper for the given shell' do
        result = @subject.generate(Fixture::Command, 'zsh')
        result.should.start_with?('#compdef bin')
      end

      it 'infers the given shell is one is not provided' do
        ENV.stubs(:[]).with('SHELL').returns('zsh')
        @subject::Zsh.any_instance.expects(:generate).once
        @subject.generate(Fixture::Command)
      end

      it 'raises if unable to support the shell' do
        should.raise Generator::ShellCompletionNotFound do
          @subject.generate(Fixture::Command, 'heheshell!')
        end.message.should.include?('shell is not implemented')
      end
    end

    describe '::indent' do
      it 'indents the given string by the given amount' do
        @subject.indent("line 1\nline 2", 1).should == "line 1\n  line 2"
      end

      it 'it does not indent the first line' do
        @subject.indent("line 1\nline 2", 1).should.start_with?('line 1')
      end
    end
  end
end


text:
package com.hxxc.user.app.utils;

import android.content.Context;
import android.content.SharedPreferences;

import com.hxxc.user.app.HXXCApplication;
import com.hxxc.user.app.UserInfoConfig;

/**
 * Created by Administrator on 2016/9/21.
 * 功能:配置参数保存
 */
public class SharedPreUtils {

    private static String Preferences_TAG = SharedPreUtils.class
            .getSimpleName();
    private static SharedPreUtils preferencesUtils = null;

    public static SharedPreUtils getInstanse() {
        if (preferencesUtils == null) {
            preferencesUtils = new SharedPreUtils();
        }
        return preferencesUtils;
    }
    /**
     *
     * @param context
     *
     */
    public void putKeyValue(Context context, String key, String value) {
        if (context == null) {
            return;
        }
        SharedPreferences sharedPreferences = context.getSharedPreferences(
                Preferences_TAG, Context.MODE_WORLD_READABLE);
        SharedPreferences.Editor editor = sharedPreferences.edit();
        editor.putString(key,value);
        editor.commit();
    }
    public void putKeyValue(Context context, String key,int value) {
        if (context == null) {
            return;
        }
        SharedPreferences sharedPreferences = context.getSharedPreferences(
                Preferences_TAG, Context.MODE_WORLD_READABLE);
        SharedPreferences.Editor editor = sharedPreferences.edit();
        editor.putInt(key,value);
        editor.commit();
    }
    public void putKeyValue(Context context, String key,boolean value) {
        if (context == null) {
            return;
        }
        SharedPreferences sharedPreferences = context.getSharedPreferences(
                Preferences_TAG, Context.MODE_WORLD_READABLE);
        SharedPreferences.Editor editor = sharedPreferences.edit();
        editor.putBoolean(key,value);
        editor.commit();
    }

    public String getKeyValue(Context context,String key) {
        if (context == null) {
            return null;
        }
        SharedPreferences sharedPreferences = context.getSharedPreferences(
                Preferences_TAG, Context.MODE_WORLD_READABLE);
        return sharedPreferences.getString(key,null);
    }

    public String getUid(){
        return getKeyValue(HXXCApplication.getInstance(), UserInfoConfig.spUid);
    }
    public String getToken(){
        return getKeyValue(HXXCApplication.getInstance(),UserInfoConfig.spToken);
    }

//    public UserInfoBean getUserInfo(Context context){
//        String value = getKeyValue(context.getApplicationContext(), UserInfoConfig.UserInfo);
//        LogUtil.i(value);
//        if(TextUtils.isEmpty(value)) return null;
//        BaseBean<UserInfoBean> baseBean = HXXCApplication.getInstance().getGson().fromJson(value,new TypeToken<BaseBean<UserInfoBean>>() {}.getType());
//        return baseBean.getModel();
//    }

    public String getKeyValue(Context context,String key,String def) {
        if (context == null) {
            return null;
        }
        SharedPreferences sharedPreferences = context.getSharedPreferences(
                Preferences_TAG, Context.MODE_WORLD_READABLE);
        return sharedPreferences.getString(key,def);
    }
    public boolean getKeyValue_b(Context context,String key) {
        if (context == null) {
            return false;
        }
        SharedPreferences sharedPreferences = context.getSharedPreferences(
                Preferences_TAG, Context.MODE_WORLD_READABLE);
        return sharedPreferences.getBoolean(key,false);
    }
    public int getKeyValue_i(Context context,String key) {
        if (context == null) {
            return -1;
        }
        SharedPreferences sharedPreferences = context.getSharedPreferences(
                Preferences_TAG, Context.MODE_WORLD_READABLE);
        return sharedPreferences.getInt(key,-1);
    }

    /**
     * 移除key
     * @param context
     * @param key
     */
    public void removeKeyValue(Context context,String key) {
        if (context == null) {
            return ;
        }
        SharedPreferences sharedPreferences = context.getSharedPreferences(
                Preferences_TAG, Context.MODE_WORLD_READABLE);
        SharedPreferences.Editor editor = sharedPreferences.edit();
        editor.remove(key);
        editor.commit();
    }
}


text:
"""Test zha binary sensor."""
from homeassistant.components.binary_sensor import DOMAIN
from homeassistant.const import STATE_ON, STATE_OFF, STATE_UNAVAILABLE
from .common import (
    async_init_zigpy_device, make_attribute, make_entity_id,
    async_test_device_join, async_enable_traffic
)

async def test_binary_sensor(hass, config_entry, zha_gateway):
    """Test zha binary_sensor platform."""
    from zigpy.zcl.clusters.security import IasZone
    from zigpy.zcl.clusters.measurement import OccupancySensing
    from zigpy.zcl.clusters.general import OnOff, LevelControl, Basic
    from zigpy.profiles.zha import DeviceType

    # create zigpy devices
    zigpy_device_zone = await async_init_zigpy_device(
        hass,
        [IasZone.cluster_id, Basic.cluster_id],
        [],
        None,
        zha_gateway
    )

    zigpy_device_remote = await async_init_zigpy_device(
        hass,
        [Basic.cluster_id],
        [OnOff.cluster_id, LevelControl.cluster_id],
        DeviceType.LEVEL_CONTROL_SWITCH,
        zha_gateway,
        ieee="00:0d:6f:11:0a:90:69:e7",
        manufacturer="FakeManufacturer",
        model="FakeRemoteModel"
    )

    zigpy_device_occupancy = await async_init_zigpy_device(
        hass,
        [OccupancySensing.cluster_id, Basic.cluster_id],
        [],
        None,
        zha_gateway,
        ieee="00:0d:6f:11:9a:90:69:e7",
        manufacturer="FakeOccupancy",
        model="FakeOccupancyModel"
    )

    # load up binary_sensor domain
    await hass.config_entries.async_forward_entry_setup(
        config_entry, DOMAIN)
    await hass.async_block_till_done()

    # on off binary_sensor
    zone_cluster = zigpy_device_zone.endpoints.get(
        1).ias_zone
    zone_entity_id = make_entity_id(DOMAIN, zigpy_device_zone, zone_cluster)
    zone_zha_device = zha_gateway.get_device(str(zigpy_device_zone.ieee))

    # occupancy binary_sensor
    occupancy_cluster = zigpy_device_occupancy.endpoints.get(
        1).occupancy
    occupancy_entity_id = make_entity_id(
        DOMAIN, zigpy_device_occupancy, occupancy_cluster)
    occupancy_zha_device = zha_gateway.get_device(
        str(zigpy_device_occupancy.ieee))

    # dimmable binary_sensor
    remote_on_off_cluster = zigpy_device_remote.endpoints.get(
        1).out_clusters[OnOff.cluster_id]
    remote_level_cluster = zigpy_device_remote.endpoints.get(
        1).out_clusters[LevelControl.cluster_id]
    remote_entity_id = make_entity_id(DOMAIN, zigpy_device_remote,
                                      remote_on_off_cluster,
                                      use_suffix=False)
    remote_zha_device = zha_gateway.get_device(str(zigpy_device_remote.ieee))

    # test that the sensors exist and are in the unavailable state
    assert hass.states.get(zone_entity_id).state == STATE_UNAVAILABLE
    assert hass.states.get(remote_entity_id).state == STATE_UNAVAILABLE
    assert hass.states.get(occupancy_entity_id).state == STATE_UNAVAILABLE

    await async_enable_traffic(hass, zha_gateway,
                               [zone_zha_device, remote_zha_device,
                                occupancy_zha_device])

    # test that the sensors exist and are in the off state
    assert hass.states.get(zone_entity_id).state == STATE_OFF
    assert hass.states.get(remote_entity_id).state == STATE_OFF
    assert hass.states.get(occupancy_entity_id).state == STATE_OFF

    # test getting messages that trigger and reset the sensors
    await async_test_binary_sensor_on_off(hass, occupancy_cluster,
                                          occupancy_entity_id)
    await async_test_binary_sensor_on_off(hass, remote_on_off_cluster,
                                          remote_entity_id)

    # test changing the level attribute for dimming remotes
    await async_test_remote_level(
        hass, remote_level_cluster, remote_entity_id, 150, STATE_ON)
    await async_test_remote_level(
        hass, remote_level_cluster, remote_entity_id, 0, STATE_OFF)
    await async_test_remote_level(
        hass, remote_level_cluster, remote_entity_id, 255, STATE_ON)

    await async_test_remote_move_level(
        hass, remote_level_cluster, remote_entity_id, 20, STATE_ON)

    # test IASZone binary sensors
    await async_test_iaszone_on_off(hass, zone_cluster, zone_entity_id)

    # test new sensor join
    await async_test_device_join(
        hass, zha_gateway, OccupancySensing.cluster_id, DOMAIN)

async def async_test_binary_sensor_on_off(hass, cluster, entity_id):
    """Test getting on and off messages for binary sensors."""
    # binary sensor on
    attr = make_attribute(0, 1)
    cluster.handle_message(False, 1, 0x0a, [[attr]])
    await hass.async_block_till_done()
    assert hass.states.get(entity_id).state == STATE_ON

    # binary sensor off
    attr.value.value = 0
    cluster.handle_message(False, 0, 0x0a, [[attr]])
    await hass.async_block_till_done()
    assert hass.states.get(entity_id).state == STATE_OFF

async def async_test_remote_level(hass, cluster, entity_id, level,
                                  expected_state):
    """Test dimmer functionality from the remote."""
    attr = make_attribute(0, level)
    cluster.handle_message(False, 1, 0x0a, [[attr]])
    await hass.async_block_till_done()
    assert hass.states.get(entity_id).state == expected_state
    assert hass.states.get(entity_id).attributes.get('level') == level

async def async_test_remote_move_level(hass, cluster, entity_id, change,
                                       expected_state):
    """Test move to level command."""
    level = hass.states.get(entity_id).attributes.get('level')
    cluster.listener_event('cluster_command', 1, 1, [1, change])
    await hass.async_block_till_done()
    assert hass.states.get(entity_id).state == expected_state
    assert hass.states.get(entity_id).attributes.get('level') == level - change

async def async_test_iaszone_on_off(hass, cluster, entity_id):
    """Test getting on and off messages for iaszone binary sensors."""
    # binary sensor on
    cluster.listener_event('cluster_command', 1, 0, [1])
    await hass.async_block_till_done()
    assert hass.states.get(entity_id).state == STATE_ON

    # binary sensor off
    cluster.listener_event('cluster_command', 1, 0, [0])
    await hass.async_block_till_done()
    assert hass.states.get(entity_id).state == STATE_OFF


text:
#ifndef _VQSPL_H_
#define _VQSPL_H_

#include "codebook.h"

extern void vqsp_book(vqgen *v,codebook *b,long *quantlist);
extern int vqenc_entry(codebook *b,float *val);
extern int lp_split(float *pointlist,long totalpoints,
		    codebook *b,
		    long *entryindex,long entries,
		    long *pointindex,long points,
		    long *membership,long *reventry,
		    long depth, long *pointsofar);

#endif


text:
from torch.autograd import Function
from torch.nn import functional as F

class SigmoidGeometricMean(Function):
    """Forward and backward function of geometric mean of two sigmoid
    functions.

    This implementation with analytical gradient function substitutes
    the autograd function of (x.sigmoid() * y.sigmoid()).sqrt(). The
    original implementation incurs none during gradient backprapagation
    if both x and y are very small values.
    """

    @staticmethod
    def forward(ctx, x, y):
        x_sigmoid = x.sigmoid()
        y_sigmoid = y.sigmoid()
        z = (x_sigmoid * y_sigmoid).sqrt()
        ctx.save_for_backward(x_sigmoid, y_sigmoid, z)
        return z

    @staticmethod
    def backward(ctx, grad_output):
        x_sigmoid, y_sigmoid, z = ctx.saved_tensors
        grad_x = grad_output * z * (1 - x_sigmoid) / 2
        grad_y = grad_output * z * (1 - y_sigmoid) / 2
        return grad_x, grad_y

sigmoid_geometric_mean = SigmoidGeometricMean.apply

def interpolate_as(source, target, mode='bilinear', align_corners=False):
    """Interpolate the `source` to the shape of the `target`.

    The `source` must be a Tensor, but the `target` can be a Tensor or a
    np.ndarray with the shape (..., target_h, target_w).

    Args:
        source (Tensor): A 3D/4D Tensor with the shape (N, H, W) or
            (N, C, H, W).
        target (Tensor | np.ndarray): The interpolation target with the shape
            (..., target_h, target_w).
        mode (str): Algorithm used for interpolation. The options are the
            same as those in F.interpolate(). Default: ``'bilinear'``.
        align_corners (bool): The same as the argument in F.interpolate().

    Returns:
        Tensor: The interpolated source Tensor.
    """
    assert len(target.shape) >= 2

    def _interpolate_as(source, target, mode='bilinear', align_corners=False):
        """Interpolate the `source` (4D) to the shape of the `target`."""
        target_h, target_w = target.shape[-2:]
        source_h, source_w = source.shape[-2:]
        if target_h != source_h or target_w != source_w:
            source = F.interpolate(
                source,
                size=(target_h, target_w),
                mode=mode,
                align_corners=align_corners)
        return source

    if len(source.shape) == 3:
        source = source[:, None, :, :]
        source = _interpolate_as(source, target, mode, align_corners)
        return source[:, 0, :, :]
    else:
        return _interpolate_as(source, target, mode, align_corners)


text:
<?php

namespace App\Validation\Exceptions;

class PhpLabelException extends ValidationException
{
    public static $defaultTemplates = [
        self::MODE_DEFAULT => [
            self::STANDARD => '{{name}} must be a valid PHP label',
        ],
        self::MODE_NEGATIVE => [
            self::STANDARD => '{{name}} must not be a valid PHP label',
        ],
    ];
}


text:
from msrest.serialization import Model

class UpdateTrustedIdProviderParameters(Model):
    """Data Lake Store Trusted Identity Provider update parameters.

    :param id_provider: The URL of this trusted identity provider
    :type id_provider: str
    """

    _attribute_map = {
        'id_provider': {'key': 'properties.idProvider', 'type': 'str'},
    }

    def __init__(self, id_provider=None):
        self.id_provider = id_provider