text:
from six import text_type as unicode

from robot.errors import ExecutionFailed, DataError, PassExecution
from robot.model import SuiteVisitor
from robot.result import TestSuite, Result
from robot.variables import GLOBAL_VARIABLES
from robot.utils import get_timestamp, NormalizedDict

from .context import EXECUTION_CONTEXTS
from .keywords import Keywords, Keyword
from .namespace import Namespace
from .status import SuiteStatus, TestStatus
from .timeouts import TestTimeout

# TODO: Some 'extract method' love needed here. Perhaps even 'extract class'.

class Runner(SuiteVisitor):

    def __init__(self, output, settings):
        self.result = None
        self._output = output
        self._settings = settings
        self._suite = None
        self._suite_status = None
        self._executed_tests = None

    @property
    def _context(self):
        return EXECUTION_CONTEXTS.current

    @property
    def _variables(self):
        ctx = self._context
        return ctx.variables if ctx else None

    def start_suite(self, suite):
        variables = GLOBAL_VARIABLES.copy()
        variables.set_from_variable_table(suite.variables)
        result = TestSuite(source=suite.source,
                           name=suite.name,
                           doc=suite.doc,
                           metadata=suite.metadata,
                           starttime=get_timestamp())
        if not self.result:
            result.set_criticality(self._settings.critical_tags,
                                   self._settings.non_critical_tags)
            self.result = Result(root_suite=result)
            self.result.configure(status_rc=self._settings.status_rc,
                                  stat_config=self._settings.statistics_config)
        else:
            self._suite.suites.append(result)
        ns = Namespace(result, variables, self._variables,
                       suite.user_keywords, suite.imports)
        EXECUTION_CONTEXTS.start_suite(ns, self._output, self._settings.dry_run)
        self._context.set_suite_variables(result)
        if not (self._suite_status and self._suite_status.failures):
            ns.handle_imports()
        variables.resolve_delayed()
        result.doc = self._resolve_setting(result.doc)
        result.metadata = [(self._resolve_setting(n), self._resolve_setting(v))
                           for n, v in result.metadata.items()]
        self._context.set_suite_variables(result)
        self._suite = result
        self._suite_status = SuiteStatus(self._suite_status,
                                         self._settings.exit_on_failure,
                                         self._settings.skip_teardown_on_exit)
        self._output.start_suite(ModelCombiner(suite, self._suite))
        self._run_setup(suite.keywords.setup, self._suite_status)
        self._executed_tests = NormalizedDict(ignore='_')

    def _resolve_setting(self, value):
        return self._variables.replace_string(value, ignore_errors=True)

    def end_suite(self, suite):
        self._suite.message = self._suite_status.message
        self._context.report_suite_status(self._suite.status,
                                          self._suite.full_message)
        with self._context.suite_teardown():
            failure = self._run_teardown(suite.keywords.teardown, self._suite_status)
            if failure:
                self._suite.suite_teardown_failed(unicode(failure))
        self._suite.endtime = get_timestamp()
        self._suite.message = self._suite_status.message
        self._context.end_suite(self._suite)
        self._suite = self._suite.parent
        self._suite_status = self._suite_status.parent

    def visit_test(self, test):
        if test.name in self._executed_tests:
            self._output.warn("Multiple test cases with name '%s' executed in "
                              "test suite '%s'." % (test.name, self._suite.longname))
        self._executed_tests[test.name] = True
        result = self._suite.tests.create(name=test.name,
                                          doc=self._resolve_setting(test.doc),
                                          tags=test.tags,
                                          starttime=get_timestamp(),
                                          timeout=self._get_timeout(test))
        keywords = Keywords(test.keywords.normal, bool(test.template))
        status = TestStatus(self._suite_status)
        if not status.failures and not test.name:
            status.test_failed('Test case name cannot be empty.', result.critical)
        if not status.failures and not keywords:
            status.test_failed('Test case contains no keywords.', result.critical)
        try:
            result.tags = self._context.variables.replace_list(result.tags)
        except DataError as err:
            status.test_failed('Replacing variables from test tags failed: %s'
                               % unicode(err), result.critical)
        self._context.start_test(result)
        self._output.start_test(ModelCombiner(result, test))
        self._run_setup(test.keywords.setup, status, result)
        try:
            if not status.failures:
                keywords.run(self._context)
        except PassExecution as exception:
            err = exception.earlier_failures
            if err:
                status.test_failed(err, result.critical)
            else:
                result.message = exception.message
        except ExecutionFailed as err:
            status.test_failed(err, result.critical)
            if err.timeout:
                self._context.timeout_occurred = True
        result.status = status.status
        result.message = status.message or result.message
        if status.teardown_allowed:
            with self._context.test_teardown(result):
                self._run_teardown(test.keywords.teardown, status, result)
        if not status.failures and result.timeout and result.timeout.timed_out():
            status.test_failed(result.timeout.get_message(), result.critical)
            result.message = status.message
        result.status = status.status
        result.endtime = get_timestamp()
        self._output.end_test(ModelCombiner(result, test))
        self._context.end_test(result)

    def _get_timeout(self, test):
        if not test.timeout:
            return None
        timeout = TestTimeout(test.timeout.value, test.timeout.message,
                              self._variables)
        timeout.start()
        return timeout

    def _run_setup(self, setup, status, result=None):
        if not status.failures:
            exception = self._run_setup_or_teardown(setup, 'setup')
            status.setup_executed(exception)
            if result and isinstance(exception, PassExecution):
                result.message = exception.message

    def _run_teardown(self, teardown, status, result=None):
        if status.teardown_allowed:
            exception = self._run_setup_or_teardown(teardown, 'teardown')
            status.teardown_executed(exception)
            failed = not isinstance(exception, PassExecution)
            if result and exception:
                result.message = status.message if failed else exception.message
            return exception if failed else None

    def _run_setup_or_teardown(self, data, kw_type):
        if not data:
            return None
        try:
            name = self._variables.replace_string(data.name)
        except DataError as err:
            return err
        if name.upper() in ('', 'NONE'):
            return None
        kw = Keyword(name, data.args, type=kw_type)
        try:
            kw.run(self._context)
        except ExecutionFailed as err:
            if err.timeout:
                self._context.timeout_occurred = True
            return err

class ModelCombiner(object):

    def __init__(self, *models):
        self.models = models

    def __getattr__(self, name):
        for model in self.models:
            if hasattr(model, name):
                return getattr(model, name)
        raise AttributeError(name)


text:
'use strict';

angular.module('coq').config(function($provide) {

  $provide.decorator('$q', function($delegate) {

    $delegate.pipeline = function(tasks, defaultValue) {
      var tasksLength = tasks.length;

      if (tasksLength) {
        return (function() {
          var defer = $delegate.defer();
          function callTask (i, lastResult) {
            $delegate.when(tasks[i](lastResult)).then(function(result) {
              if (i + 1 < tasksLength) {
                callTask(i + 1, result);
              } else {
                defer.resolve(result);
              }
            }, function(error) {
              defer.reject(error);
            });
          }
          callTask(0, defaultValue);

          return defer.promise;
        })();
      } else {
        return $delegate.when(defaultValue);
      }
    };

    return $delegate;

  });
});

redpajama_set_name: RedPajamaGithub


text:
//
//  VELNSViewLayer.h
//  Velvet
//
//  Created by Justin Spahr-Summers on 23.01.12.
//  Copyright (c) 2012 Bitswift. All rights reserved.
//

#import "VELViewLayer.h"
#import "VELNSView.h"

@class VELNSView;

/**
 * Private layer class for backing a <VELNSView>.
 */
@interface VELNSViewLayer : VELViewLayer

/**
 * @name View
 */

/**
 * The view that this layer is backing.
 */
@property (nonatomic, weak, readonly) VELNSView *view;

@end


text:
package OptimizationTests.NonTemporalMove.SimpleForLoopFloat_001;

// No non temporal move expected: optimization is only applied to int and long type arrays

public class Main {
    final int iterations = 0x40000;

    public float checkSum(float[] tab, int n) {
        float s = 0;
        for (int i = 0; i < n ; i++) {
            s = s + tab[i];
        }
        return s;
    }

    public float testLoop(float[] tab) {

        float f = 0.5f;
        for (int i = 0; i < iterations; i++) {
            tab[i] = i + f;
        }
        return checkSum(tab, iterations);
    }

    public void test()
    {
        float[] tab = new float [iterations];
        System.out.println(testLoop(tab));
    }

    public static void main(String[] args)
    {
        new Main().test();
    }

}


text:
""" synrcat

radial selection function

"""
import sys
import os
import numpy as np
from collections import OrderedDict

from astropy.table import Table

from pypeline import pype, add_param

import syncat.misc as misc
from syncat.errors import NoPoints

from sample_dist import sample_dist

import time

@add_param('zdist_file', metavar='filename', default='in/zdist.txt', type=str,
    help='path to file specifying redshift distribution')
@add_param('zdist_interp', metavar='name', default='pchip', choices=('linear','pchip'), type=str,
    help='method to interpolate cumulative distribution function')
class Radial(pype):
    """ SynCat mode to generate a random catalogue by drawing redshift from a distribution.

    Parameters
    ----------
    mask : minimask.Mask instance
        mask describing survey geometry to sample from.  If None, sample from full-sky.
    zdist_file : str
        path to file with catalogue model to load
    zdist_interp : str
        method to interpolate cumulative distribution function (default pchip)
    zdist : tuple
        redshift distribution histogram in tuple form (bin_edges, n_z)
    """

    def __init__(self, config={}, mask=None, zdist=None, **kwargs):
        """ """
        self._parse_config(config, **kwargs)
        self._setup_logging()

        self.zdist = zdist
        if zdist is None:
            self.load_zdist()

        self.mask = mask

    def load_zdist(self, filename=None):
        """ Load a redshift distribution from a file.

        The file format can be ascii with columns redshift and n(z)
        or a tuple (z, nz) stored in a numpy .npy or pickle file.

        Parameters
        ----------
        filename : str
            Path to redshift distribution file.
        """
        if filename is None:
            filename = self.config['zdist_file']

        if not os.path.exists(filename):
            self.logger.warning("redshift distribution file %s does not exist", filename)
            return

        try:
            zz, nz = np.load(filename)
            done = True
        except:
            pass

        try:
            zz, nz = np.loadtxt(filename, unpack=True)
            done = True
        except:
            pass

        if not done:
            self.logger.warning("Could not load file %s.  Unknown format.", filename)
            return

        # normalize redshift distribution
        nz = nz * 1. / np.sum(nz)

        step = zz[1] - zz[0]
        bin_edges = np.arange(len(zz) + 1) * step + zz[0] - step / 2.

        self.zdist = (bin_edges, nz)
        self.logger.info("Loaded redshift distribution file %s.", filename)

    def sample_sky(self, zone=None, nside=None, order=None):
        """ Sample sky coordinates.

        Parameters
        ----------
        zone : int, list
            optional healpix zone index or list of indices from which to sample.  Otherwise sample from all zones.
        nside : int
            healpix nside for zone pixelization
        order : str
            healpix ordering for zone pixelization
        """
        return np.transpose(self.mask.draw_random_position(density=self.config['density'], n=self.config['count'],
                                                            cell=zone, nside=nside, order=order))

    def fit(self):
        """ """
        pass

    def sample(self, add_columns=(), zone=None, nside=None, order=None):
        """ Draw samples from the radial selection function.

        Returns
        -------
        numpy strucarray : random catalogue
        """
        if self.config['overwrite']:
            if os.path.exists(self.config['out_cat']):
                self.logger.info("overwriting existing catalogue: %s", self.config['out_cat'])
                os.unlink(self.config['out_cat'])

        bin_edges, bin_counts = self.zdist

        sampler = sample_dist(bin_edges, bin_counts)

        skycoord = self.sample_sky(zone=zone, nside=nside, order=order)
        if len(skycoord) == 0:
    		raise NoPoints

        redshift = sampler(len(skycoord))

        data_out = OrderedDict({'z': redshift})

        skycoord_name = self.config['skycoord_name']
        for i in range(len(skycoord_name)):
            data_out[skycoord_name[i]] = skycoord[:, i]

        for column, t in add_columns:
            data_out[column] = np.zeros(len(redshift), dtype=t)

        data_out = misc.dict_to_structured_array(data_out)

        self.logger.info("Wrote radial random catalogue nobj=%i: %s", len(data_out), self.config['out_cat'])

        return data_out


text:
package com.spotify.helios.testing;

import static org.hamcrest.Matchers.is;
import static org.junit.Assert.assertThat;
import static org.junit.experimental.results.PrintableResult.testResult;
import static org.junit.experimental.results.ResultMatchers.isSuccessful;

import com.google.common.base.Optional;
import com.spotify.helios.common.descriptors.PortMapping;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;

public class ProberTest extends TemporaryJobsTestBase {

  @Test
  public void testOverrideDefaultProber() throws Exception {
    assertThat(testResult(OverrideDefaultProberTest.class), isSuccessful());
  }

  private static class MockProber implements Prober {
    private boolean probed;

    @Override
    public boolean probe(String host, PortMapping port) {
      return probed = true;
    }

    public boolean probed() {
      return probed;
    }
  }

  public static class OverrideDefaultProberTest {

    private MockProber defaultProber = new MockProber();
    private MockProber overrideProber = new MockProber();

    @Rule
    public final TemporaryJobs temporaryJobs = temporaryJobsBuilder()
        .client(client)
        .prober(defaultProber)
        .jobPrefix(Optional.of(testTag).get())
        .build();

    @Before
    public void setup() {
      temporaryJobs.job()
          .command(IDLE_COMMAND)
          .port("default", 4711)
          .deploy(testHost1);

      temporaryJobs.job()
          .command(IDLE_COMMAND)
          .port("override", 4712)
          .prober(overrideProber)
          .deploy(testHost1);
    }

    @Test
    public void test() {
      // Verify that the first job used the prober passed to the TemporaryJobs rule.
      assertThat(defaultProber.probed(), is(true));
      // Verify that the second job used the prober that was passed to its builder.
      assertThat(overrideProber.probed(), is(true));
    }
  }

}


text:
import React from "react"
import sinon from "sinon"
import { assert } from "chai"
import { shallow } from "enzyme"
import { Formik } from "formik"

import ChangeEmailForm from "./ChangeEmailForm"

import { findFormikFieldByName } from "../../lib/test_utils"

import { makeUser } from "../../factories/user"

describe("ChangeEmailForm", () => {
  let sandbox, onSubmitStub

  const user = makeUser()

  const renderForm = () =>
    shallow(<ChangeEmailForm onSubmit={onSubmitStub} user={user} />)

  beforeEach(() => {
    sandbox = sinon.createSandbox()
    onSubmitStub = sandbox.stub()
  })

  it("passes onSubmit to Formik", () => {
    const wrapper = renderForm()

    assert.equal(wrapper.find("Formik").props().onSubmit, onSubmitStub)
  })

  it("renders the form", () => {
    const wrapper = renderForm()

    const form = wrapper.find("Formik").dive()
    assert.ok(findFormikFieldByName(form, "email").exists())
    assert.ok(findFormikFieldByName(form, "confirmPassword").exists())
    assert.ok(form.find("ButtonWithLoader[type='submit']").exists())
  })

  it("confirm password is required to change the email address", async () => {
    const wrapper = renderForm()
    try {
      await wrapper.find(Formik).prop("validate")(
        {
          email:           "abc@example.com",
          confirmPassword: ""
        },
        {
          context: { currentEmail: "abc@example.com" }
        }
      )
    } catch (errors) {
      assert.equal(
        errors.confirmPassword,
        "Confirm Password is a required field"
      )
    }
  })
})


text:
RailsAdmin support for the gem [countries](https://github.com/hexorx/countries/). It defines new ```country_field```.

## Installation

Add this line to your application's Gemfile:

```ruby
gem 'rails_admin_countries'
```

And then execute:

    $ bundle

Or install it yourself as:

    $ gem install rails_admin_countries

## Usage

Example usage with [Mongoid](https://github.com/mongoid/mongoid):

    class Address
      include Mongoid::Document

      field :country, type: Country

      rails_admin do
        field :country
      end
    end

## Development

After checking out the repo, run `bin/setup` to install dependencies. Then, run `bin/console` for an interactive prompt that will allow you to experiment.

To install this gem onto your local machine, run `bundle exec rake install`. To release a new version, update the version number in `version.rb`, and then run `bundle exec rake release` to create a git tag for the version, push git commits and tags, and push the `.gem` file to [rubygems.org](https://rubygems.org).

## Contributing

1. Fork it ( https://github.com/[my-github-username]/rails_admin_countries/fork )
2. Create your feature branch (`git checkout -b my-new-feature`)
3. Commit your changes (`git commit -am 'Add some feature'`)
4. Push to the branch (`git push origin my-new-feature`)
5. Create a new Pull Request


text:
When called with just the `key` argument, return a random element from the set value stored at `key`.

If the provided `count` argument is positive, return an array of **distinct elements**.
The array's length is either `count` or the set's cardinality (`SCARD`), whichever is lower.

If called with a negative `count`, the behavior changes and the command is allowed to return the **same element multiple times**.
In this case, the number of returned elements is the absolute value of the specified `count`.

@return

@bulk-string-reply: without the additional `count` argument, the command returns a Bulk Reply with the randomly selected element, or `nil` when `key` does not exist.

@array-reply: when the additional `count` argument is passed, the command returns an array of elements, or an empty array when `key` does not exist.

@examples

```cli
SADD myset one two three
SRANDMEMBER myset
SRANDMEMBER myset 2
SRANDMEMBER myset -5
```

@history

* `>= 2.6.0`: Added the optional `count` argument.

## Specification of the behavior when count is passed

When the `count` argument is a positive value this command behaves as follows:

* No repeated elements are returned.
* If `count` is bigger than the set's cardinality, the command will only return the whole set without additional elements.
* The order of elements in the reply is not truly random, so it is up to the client to shuffle them if needed.

When the `count` is a negative value, the behavior changes as follows:

* Repeating elements are possible.
* Exactly `count` elements, or an empty array if the set is empty (non-existing key), are always returned.
* The order of elements in the reply is truly random.

## Distribution of returned elements

Note: this section is relevant only for Redis 5 or below, as Redis 6 implements a fairer algorithm.

The distribution of the returned elements is far from perfect when the number of elements in the set is small, this is due to the fact that we used an approximated random element function that does not really guarantees good distribution.

The algorithm used, that is implemented inside dict.c, samples the hash table buckets to find a non-empty one. Once a non empty bucket is found, since we use chaining in our hash table implementation, the number of elements inside the bucket is checked and a random element is selected.

This means that if you have two non-empty buckets in the entire hash table, and one has three elements while one has just one, the element that is alone in its bucket will be returned with much higher probability.


text:
"""## Functions for working with arbitrarily nested sequences of elements.

This module is used to perform any operations on nested structures, which can be
specified as sequences that contain non-sequence elements or other sequences.
The utilities here assume (and do not check) that the nested structures form a
'tree', i.e. no references in the structure of the input of these functions
should be recursive.

@@assert_same_structure
@@is_sequence
@@flatten
@@flatten_dict_items
@@pack_sequence_as
"""

from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

import collections

import six

def _sequence_like(instance, args):
  """Converts the sequence `args` to the same type as `instance`.

  Args:
    instance: an instance of `tuple`, `list`, or a `namedtuple` class.
    args: elements to be converted to a sequence.

  Returns:
    `args` with the type of `instance`.
  """
  if (isinstance(instance, tuple) and
      hasattr(instance, "_fields") and
      isinstance(instance._fields, collections.Sequence) and
      all(isinstance(f, six.string_types) for f in instance._fields)):
    # This is a namedtuple
    return type(instance)(*args)
  else:
    # Not a namedtuple
    return type(instance)(args)

def _yield_flat_nest(nest):
  for n in nest:
    if is_sequence(n):
      for ni in _yield_flat_nest(n):
        yield ni
    else:
      yield n

def is_sequence(seq):
  """Returns a true if its input is a collections.Sequence (except strings).

  Args:
    seq: an input sequence.

  Returns:
    True if the sequence is a not a string and is a collections.Sequence.
  """
  return (isinstance(seq, collections.Sequence)
          and not isinstance(seq, six.string_types))

def flatten(nest):
  """Returns a flat sequence from a given nested structure.

  If `nest` is not a sequence, this returns a single-element list: `[nest]`.

  Args:
    nest: an arbitrarily nested structure or a scalar object.
      Note, numpy arrays are considered scalars.

  Returns:
    A Python list, the flattened version of the input.
  """
  return list(_yield_flat_nest(nest)) if is_sequence(nest) else [nest]

def _recursive_assert_same_structure(nest1, nest2):
  is_sequence_nest1 = is_sequence(nest1)
  if is_sequence_nest1 != is_sequence(nest2):
    raise ValueError(
        "The two structures don't have the same nested structure. "
        "First structure: %s, second structure: %s." % (nest1, nest2))

  if is_sequence_nest1:
    type_nest1 = type(nest1)
    type_nest2 = type(nest2)
    if type_nest1 != type_nest2:
      raise TypeError(
          "The two structures don't have the same sequence type. First "
          "structure has type %s, while second structure has type %s."
          % (type_nest1, type_nest2))

    for n1, n2 in zip(nest1, nest2):
      _recursive_assert_same_structure(n1, n2)

def assert_same_structure(nest1, nest2):
  """Asserts that two structures are nested in the same way.

  Args:
    nest1: an arbitrarily nested structure.
    nest2: an arbitrarily nested structure.

  Raises:
    ValueError: If the two structures do not have the same number of elements or
      if the two structures are not nested in the same way.
    TypeError: If the two structures differ in the type of sequence in any of
      their substructures.
  """
  len_nest1 = len(flatten(nest1)) if is_sequence(nest1) else 1
  len_nest2 = len(flatten(nest2)) if is_sequence(nest2) else 1
  if len_nest1 != len_nest2:
    raise ValueError("The two structures don't have the same number of "
                     "elements. First structure: %s, second structure: %s."
                     % (nest1, nest2))
  _recursive_assert_same_structure(nest1, nest2)

def flatten_dict_items(dictionary):
  """Returns a dictionary with flattened keys and values.

  This function flattens the keys and values of a dictionary, which can be
  arbitrarily nested structures, and returns the flattened version of such
  structures:

  ```python
  example_dictionary = {(4, 5, (6, 8)): ("a", "b", ("c", "d"))}
  result = {4: "a", 5: "b", 6: "c", 8: "d"}
  flatten_dict_items(example_dictionary) == result
  ```

  The input dictionary must satisfy two properties:

  1. Its keys and values should have the same exact nested structure.
  2. The set of all flattened keys of the dictionary must not contain repeated
     keys.

  Args:
    dictionary: the dictionary to zip

  Returns:
    The zipped dictionary.

  Raises:
    TypeError: If the input is not a dictionary.
    ValueError: If any key and value have not the same structure, or if keys are
      not unique.
  """
  if not isinstance(dictionary, dict):
    raise TypeError("input must be a dictionary")
  flat_dictionary = {}
  for i, v in six.iteritems(dictionary):
    if not is_sequence(i):
      if i in flat_dictionary:
        raise ValueError(
            "Could not flatten dictionary: key %s is not unique." % i)
      flat_dictionary[i] = v
    else:
      flat_i = flatten(i)
      flat_v = flatten(v)
      if len(flat_i) != len(flat_v):
        raise ValueError(
            "Could not flatten dictionary. Key had %d elements, but value had "
            "%d elements. Key: %s, value: %s."
            % (len(flat_i), len(flat_v), flat_i, flat_v))
      for new_i, new_v in zip(flat_i, flat_v):
        if new_i in flat_dictionary:
          raise ValueError(
              "Could not flatten dictionary: key %s is not unique."
              % (new_i))
        flat_dictionary[new_i] = new_v
  return flat_dictionary

def _packed_nest_with_indices(structure, flat, index):
  """Helper function for pack_nest_as.

  Args:
    structure: Substructure (tuple of elements and/or tuples) to mimic
    flat: Flattened values to output substructure for.
    index: Index at which to start reading from flat.

  Returns:
    The tuple (new_index, child), where:
      * new_index - the updated index into `flat` having processed `structure`.
      * packed - the subset of `flat` corresponding to `structure`,
                 having started at `index`, and packed into the same nested
                 format.

  Raises:
    ValueError: if `structure` contains more elements than `flat`
      (assuming indexing starts from `index`).
  """
  packed = []
  for s in structure:
    if is_sequence(s):
      new_index, child = _packed_nest_with_indices(s, flat, index)
      packed.append(_sequence_like(s, child))
      index = new_index
    else:
      packed.append(flat[index])
      index += 1
  return index, packed

def pack_sequence_as(structure, flat_sequence):
  """Returns a given flattened sequence packed into a nest.

  If `structure` is a scalar, `flat_sequence` must be a single-element list;
  in this case the return value is `flat_sequence[0]`.

  Args:
    structure: tuple or list constructed of scalars and/or other tuples/lists,
      or a scalar.  Note: numpy arrays are considered scalars.
    flat_sequence: flat sequence to pack.

  Returns:
    packed: `flat_sequence` converted to have the same recursive structure as
      `structure`.

  Raises:
    ValueError: If nest and structure have different element counts.
  """
  if not is_sequence(flat_sequence):
    raise TypeError("flat_sequence must be a sequence")

  if not is_sequence(structure):
    if len(flat_sequence) != 1:
      raise ValueError("Structure is a scalar but len(flat_sequence) == %d > 1"
                       % len(flat_sequence))
    return flat_sequence[0]

  flat_structure = flatten(structure)
  if len(flat_structure) != len(flat_sequence):
    raise ValueError(
        "Could not pack sequence. Structure had %d elements, but flat_sequence "
        "had %d elements.  Structure: %s, flat_sequence: %s."
        % (len(flat_structure), len(flat_sequence), structure, flat_sequence))

  _, packed = _packed_nest_with_indices(structure, flat_sequence, 0)
  return _sequence_like(structure, packed)


text:
describe('Circle', function () {
	describe('#getBounds', function () {

		var circle;

		beforeEach(function () {
			circle = L.circle([50, 30], 200);
		});

		it('returns bounds', function () {
			var bounds = circle.getBounds();

			expect(bounds.getSouthWest().equals([49.998203369, 29.997204939])).toBeTruthy();
			expect(bounds.getNorthEast().equals([50.001796631, 30.002795061])).toBeTruthy();
		});
	});
});


text:
package com.oasisfeng.android.ui;

import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.PaintFlagsDrawFilter;
import android.graphics.PixelFormat;
import android.graphics.Rect;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.PaintDrawable;
import androidx.annotation.UiThread;

/**
 * Utility class to resize icons to match default icon size.
 *
 * Derived from {@link android.app.LauncherActivity.IconResizer}
 */
public class IconResizer {
	// Code is borrowed from com.android.launcher.Utilities.
	private final int mIconWidth, mIconHeight;
	private final Rect mOldBounds = new Rect();
	private final Canvas mCanvas = new Canvas();

	public IconResizer() {
		this((int) Resources.getSystem().getDimension(android.R.dimen.app_icon_size));
	}

	public IconResizer(final int size) {
		mCanvas.setDrawFilter(new PaintFlagsDrawFilter(Paint.DITHER_FLAG,
				Paint.FILTER_BITMAP_FLAG));

		mIconWidth = mIconHeight = size;
	}

	/**
	 * Returns a Drawable representing the thumbnail of the specified Drawable.
	 * The size of the thumbnail is defined by the dimension
	 * android.R.dimen.launcher_application_icon_size.
	 *
	 * This method is not thread-safe and should be invoked on the UI thread only.
	 *
	 * @param icon The icon to get a thumbnail of.
	 *
	 * @return A thumbnail for the specified icon or the icon itself if the
	 *         thumbnail could not be created.
	 */
	@UiThread public Drawable createIconThumbnail(Drawable icon) {
		int width = mIconWidth;
		int height = mIconHeight;

		final int iconWidth = icon.getIntrinsicWidth();
		final int iconHeight = icon.getIntrinsicHeight();

		if (icon instanceof PaintDrawable) {
			final PaintDrawable painter = (PaintDrawable) icon;
			painter.setIntrinsicWidth(width);
			painter.setIntrinsicHeight(height);
		}

		if (width > 0 && height > 0) {
			if (width < iconWidth || height < iconHeight) {
				final float ratio = (float) iconWidth / iconHeight;

				if (iconWidth > iconHeight) {
					height = (int) (width / ratio);
				} else if (iconHeight > iconWidth) {
					width = (int) (height * ratio);
				}

				final Bitmap.Config c = icon.getOpacity() != PixelFormat.OPAQUE ?
						Bitmap.Config.ARGB_8888 : Bitmap.Config.RGB_565;
				final Bitmap thumb = Bitmap.createBitmap(mIconWidth, mIconHeight, c);
				final Canvas canvas = mCanvas;
				canvas.setBitmap(thumb);
				// Copy the old bounds to restore them later
				// If we were to do oldBounds = icon.getBounds(),
				// the call to setBounds() that follows would
				// change the same instance and we would lose the
				// old bounds
				mOldBounds.set(icon.getBounds());
				final int x = (mIconWidth - width) / 2;
				final int y = (mIconHeight - height) / 2;
				icon.setBounds(x, y, x + width, y + height);
				icon.draw(canvas);
				icon.setBounds(mOldBounds);
				icon = new BitmapDrawable(Resources.getSystem(), thumb);
				canvas.setBitmap(null);
			} else if (iconWidth < width && iconHeight < height) {
				final Bitmap.Config c = Bitmap.Config.ARGB_8888;
				final Bitmap thumb = Bitmap.createBitmap(mIconWidth, mIconHeight, c);
				final Canvas canvas = mCanvas;
				canvas.setBitmap(thumb);
				mOldBounds.set(icon.getBounds());
				final int x = (width - iconWidth) / 2;
				final int y = (height - iconHeight) / 2;
				icon.setBounds(x, y, x + iconWidth, y + iconHeight);
				icon.draw(canvas);
				icon.setBounds(mOldBounds);
				icon = new BitmapDrawable(Resources.getSystem(), thumb);
				canvas.setBitmap(null);
			}
		}

		return icon;
	}
}


text:
package esapi

import (
	"context"
	"net/http"
	"strings"
)

func newMLDeleteCalendarEventFunc(t Transport) MLDeleteCalendarEvent {
	return func(calendar_id string, event_id string, o ...func(*MLDeleteCalendarEventRequest)) (*Response, error) {
		var r = MLDeleteCalendarEventRequest{CalendarID: calendar_id, EventID: event_id}
		for _, f := range o {
			f(&r)
		}
		return r.Do(r.ctx, t)
	}
}

// ----- API Definition -------------------------------------------------------

// MLDeleteCalendarEvent - Deletes scheduled events from a calendar.
//
// See full documentation at https://www.elastic.co/guide/en/elasticsearch/reference/current/ml-delete-calendar-event.html.
//
type MLDeleteCalendarEvent func(calendar_id string, event_id string, o ...func(*MLDeleteCalendarEventRequest)) (*Response, error)

// MLDeleteCalendarEventRequest configures the ML Delete Calendar Event API request.
//
type MLDeleteCalendarEventRequest struct {
	CalendarID string
	EventID    string

	Pretty     bool
	Human      bool
	ErrorTrace bool
	FilterPath []string

	Header http.Header

	ctx context.Context
}

// Do executes the request and returns response or error.
//
func (r MLDeleteCalendarEventRequest) Do(ctx context.Context, transport Transport) (*Response, error) {
	var (
		method string
		path   strings.Builder
		params map[string]string
	)

	method = "DELETE"

	path.Grow(1 + len("_ml") + 1 + len("calendars") + 1 + len(r.CalendarID) + 1 + len("events") + 1 + len(r.EventID))
	path.WriteString("/")
	path.WriteString("_ml")
	path.WriteString("/")
	path.WriteString("calendars")
	path.WriteString("/")
	path.WriteString(r.CalendarID)
	path.WriteString("/")
	path.WriteString("events")
	path.WriteString("/")
	path.WriteString(r.EventID)

	params = make(map[string]string)

	if r.Pretty {
		params["pretty"] = "true"
	}

	if r.Human {
		params["human"] = "true"
	}

	if r.ErrorTrace {
		params["error_trace"] = "true"
	}

	if len(r.FilterPath) > 0 {
		params["filter_path"] = strings.Join(r.FilterPath, ",")
	}

	req, err := newRequest(method, path.String(), nil)
	if err != nil {
		return nil, err
	}

	if len(params) > 0 {
		q := req.URL.Query()
		for k, v := range params {
			q.Set(k, v)
		}
		req.URL.RawQuery = q.Encode()
	}

	if len(r.Header) > 0 {
		if len(req.Header) == 0 {
			req.Header = r.Header
		} else {
			for k, vv := range r.Header {
				for _, v := range vv {
					req.Header.Add(k, v)
				}
			}
		}
	}

	if ctx != nil {
		req = req.WithContext(ctx)
	}

	res, err := transport.Perform(req)
	if err != nil {
		return nil, err
	}

	response := Response{
		StatusCode: res.StatusCode,
		Body:       res.Body,
		Header:     res.Header,
	}

	return &response, nil
}

// WithContext sets the request context.
//
func (f MLDeleteCalendarEvent) WithContext(v context.Context) func(*MLDeleteCalendarEventRequest) {
	return func(r *MLDeleteCalendarEventRequest) {
		r.ctx = v
	}
}

// WithPretty makes the response body pretty-printed.
//
func (f MLDeleteCalendarEvent) WithPretty() func(*MLDeleteCalendarEventRequest) {
	return func(r *MLDeleteCalendarEventRequest) {
		r.Pretty = true
	}
}

// WithHuman makes statistical values human-readable.
//
func (f MLDeleteCalendarEvent) WithHuman() func(*MLDeleteCalendarEventRequest) {
	return func(r *MLDeleteCalendarEventRequest) {
		r.Human = true
	}
}

// WithErrorTrace includes the stack trace for errors in the response body.
//
func (f MLDeleteCalendarEvent) WithErrorTrace() func(*MLDeleteCalendarEventRequest) {
	return func(r *MLDeleteCalendarEventRequest) {
		r.ErrorTrace = true
	}
}

// WithFilterPath filters the properties of the response body.
//
func (f MLDeleteCalendarEvent) WithFilterPath(v ...string) func(*MLDeleteCalendarEventRequest) {
	return func(r *MLDeleteCalendarEventRequest) {
		r.FilterPath = v
	}
}

// WithHeader adds the headers to the HTTP request.
//
func (f MLDeleteCalendarEvent) WithHeader(h map[string]string) func(*MLDeleteCalendarEventRequest) {
	return func(r *MLDeleteCalendarEventRequest) {
		if r.Header == nil {
			r.Header = make(http.Header)
		}
		for k, v := range h {
			r.Header.Add(k, v)
		}
	}
}

// WithOpaqueID adds the X-Opaque-Id header to the HTTP request.
//
func (f MLDeleteCalendarEvent) WithOpaqueID(s string) func(*MLDeleteCalendarEventRequest) {
	return func(r *MLDeleteCalendarEventRequest) {
		if r.Header == nil {
			r.Header = make(http.Header)
		}
		r.Header.Set("X-Opaque-Id", s)
	}
}


text:
const config = {
  language: 'zh-cn',
  uiColor: '#9AB8F3',
  bodyClass: 'main-content'
}
config.toolbarGroups = [
  {name: 'clipboard', groups: ['clipboard', 'undo']},
  {name: 'editing', groups: ['find', 'selection', 'spellchecker']},
  {name: 'links'},
  {name: 'insert'},
  {name: 'forms'},
  {name: 'tools'},
  {name: 'document', groups: ['mode', 'document', 'doctools']},
  {name: 'others'},
  '/',
  {name: 'basicstyles', groups: ['basicstyles', 'cleanup']},
  {name: 'paragraph', groups: ['list', 'indent', 'blocks', 'align', 'bidi']},
  {name: 'styles'},
  {name: 'colors'},
  {name: 'about'}
]

// Remove some buttons provided by the standard plugins, which are
// not needed in the Standard(s) toolbar.
config.removeButtons = 'Underline,Subscript,Superscript'

// Set the most common block elements.
config.format_tags = 'p;h1;h2;h3;pre'

// Simplify the dialog windows.
config.removeDialogTabs = 'image:advanced;link:advanced'

export {config as default}


text:
package org.gradle.internal.resource.transport.http;

import org.gradle.internal.exceptions.Contextual;

/**
 * Signals that HTTP response has been received successfully but an error code is encountered (neither 2xx/3xx nor 404).
 */
@Contextual
public class HttpErrorStatusCodeException extends RuntimeException {

    private final int statusCode;

    public HttpErrorStatusCodeException(String method, String source, int statusCode, String reason) {
        super(String.format("Could not %s '%s'. Received status code %s from server: %s",
            method, source, statusCode, reason));
        this.statusCode = statusCode;
    }

    public boolean isServerError() {
        return statusCode >= 500 && statusCode < 600;
    }
}


text:
package com.honeycomb.client.lib.bugreporter;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Handler;
import android.os.Message;
import android.widget.Toast;

public class UiHandler extends Handler {
    public UiHandler() {
        super(UiThread.get().getLooper());
    }

    @Override
    public void handleMessage(Message msg) {
//        AlertDialog dialog  = createDialog("test", "hi");
//        dialog.show();
        Toast.makeText(Bee.getContext(), "Test", Toast.LENGTH_LONG).show();
    }

    private static AlertDialog createDialog(String title, String message) {
        AlertDialog.Builder ab = new AlertDialog.Builder(Bee.getContext().getApplicationContext());
        ab.setTitle(title);
        ab.setMessage(message);
        ab.setPositiveButton("OK", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {

            }
        });
        return ab.create();
    }
}


text:
//---------------------------------------------------------------------------
#ifndef uSup3002H
#define uSup3002H
//---------------------------------------------------------------------------
#include <Classes.hpp>
#include <Controls.hpp>
#include <StdCtrls.hpp>
#include <Forms.hpp>
#include "SfgResButtons.hpp"
#include "uFormBase01.h"
#include <ExtCtrls.hpp>
#include <Mask.hpp>
#include <DBCtrls.hpp>
#include "CustomButtons.h"
#include <Buttons.hpp>
//---------------------------------------------------------------------------
class TSup3002 : public TfrmBase01
{
__published:	// IDE-managed Components
	TPanel *SfgToolbar;
	TResBitBtn *btRelatorio;
	TResBitBtn *btExit;
	TBevel *Bevel2;
	TGroupBox *gbFiltros;
	TLabel *Label1;
	TLabel *Label2;
	TEdit *cod_fornecedor;
	TResBitBtn *btPesqFornecedor;
	TEdit *den_fornecedor;
	TMaskEdit *data_ini;
	TCustomImgButton *btCalendar01;
	TMaskEdit *data_fim;
	TCustomImgButton *btCalendar02;
	TLabel *Label12;
	TLabel *Label4;
	TEdit *cod_plano_conta_ini;
	TResBitBtn *btPesqPlanoContaIni;
	TLabel *Label5;
	TEdit *cod_centro_custo_ini;
	TResBitBtn *btPesqCentroCustoIni;
	TRadioGroup *rbAgrupamento;
	TGroupBox *gbSituacao;
	TCheckBox *ckAberto;
	TCheckBox *ckEnviado;
	TCheckBox *ckRecebido;
	TCheckBox *ckFechado;
	TCheckBox *ckCancelado;
	TResBitBtn *btPesqPlanoContaFim;
	TEdit *cod_plano_conta_fim;
	TLabel *Label3;
	TLabel *Label6;
	TEdit *cod_centro_custo_fim;
	TResBitBtn *btPesqCentroCustoFim;
	void __fastcall cod_fornecedorExit(TObject *Sender);
	void __fastcall btPesqFornecedorClick(TObject *Sender);
	void __fastcall btPesqPlanoContaIniClick(TObject *Sender);
	void __fastcall btPesqPlanoContaFimClick(TObject *Sender);
	void __fastcall btPesqCentroCustoIniClick(TObject *Sender);
	void __fastcall btPesqCentroCustoFimClick(TObject *Sender);
	void __fastcall btRelatorioClick(TObject *Sender);
	void __fastcall data_iniExit(TObject *Sender);
	void __fastcall data_fimExit(TObject *Sender);
	void __fastcall btExitClick(TObject *Sender);
	void __fastcall btCalendar01Click(TObject *Sender);
	void __fastcall btCalendar02Click(TObject *Sender);
private:	// User declarations
	TEdit *pEditRet;
	void __fastcall SearchReturn(Variant Value);
	void __fastcall ConsultaPorFornecedor(String SQL, System::TDateTime dt_data_ini, System::TDateTime dt_data_fim);
	void __fastcall ConsultaPorSitacao(String SQL, System::TDateTime dt_data_ini, System::TDateTime dt_data_fim);
	void __fastcall ConsultaPorCentroCusto(String SQL, System::TDateTime dt_data_ini, System::TDateTime dt_data_fim);
	void __fastcall ConsultaPorContaContabil(String SQL, System::TDateTime dt_data_ini, System::TDateTime dt_data_fim);
public:		// User declarations
	__fastcall TSup3002(TComponent* Owner);
};
//---------------------------------------------------------------------------
#endif


text:
import React from 'react';
import Row from './row';
import {keys, map, compose, pick} from 'ramda';

export default function renderRows(objectsArray, restaurantId='', whiteListKeys=[], removeFn, editFn, idAttribute='id'){
  return map(item => {
    var id = item[idAttribute];
    var oldItem = {...item};
    var whiteListed = pick(whiteListKeys, item);
    return (
      <Row
        key={id}
        id={id}
        data={whiteListed}
        onClickRemoveHandler={commandsFactory(removeFn, oldItem, restaurantId)}
        onClickEditHandler={commandsFactory(editFn, oldItem, restaurantId)} />
    );
  }, objectsArray);
}

function commandsFactory(fn, item, restaurantId){
  if (fn) {
    return function commandsFactoryThunk(){
      return fn(item, restaurantId);
    };
  } else {
    return null;
  }
}


text:
require 'spec_helper'

describe OmniauthCallbacksController do
  before { request.env['devise.mapping'] = Devise.mappings[:user] }

  describe 'GET :slack' do
    def do_request
      get :slack
    end

    let!(:omniauth_hash) {
      {
        "provider" => "slack",
        "uid" => "U0304SBK4",
        "info" => {
          "name" => "Arun Thampi",
          "email" => "arun@mixcel.io",
          "nickname" => "arun",
          "first_name" => "Arun",
          "last_name" => "Thampi",
          "description" => nil,
          "image" => "https://s3-us-west-2.amazonaws.com/slack-files2/avatars/2015-05-11/4836202382_65573aedd51b9b423a87_192.jpg",
          "team"=>"Mixcel",
          "user" => "arun",
          "team_id" => "T0304SBJU",
          "user_id" => "U0304SBK4"
        },
        "credentials" => {
          "token" => "deadbeef",
          "expires" => false
        },
        "extra" => {
          "bot_info" => {
            "bot_access_token" => "xoxb-cafedead",
            "bot_user_id" => "UDEADBEEF1"
          },
          "raw_info" => {
            "ok" => true,
            "url" => "https://mixcel.slack.com/",
            "team" => "Mixcel",
            "user" => "arun",
            "team_id" => "T0304SBJU",
            "user_id" => "U0304SBK4"
          },
          "user_info" => {
            "ok" =>true,
            "user" =>{
              "id" => "U0304SBK4",
              "name" => "arun",
              "deleted" => false,
              "status" => nil,
              "color" => "9f69e7",
              "real_name" => "Arun Thampi",
              "tz" => "America/Los_Angeles",
              "tz_label" => "Pacific Daylight Time",
              "tz_offset" => -25200,
              "profile" => {
                "first_name" => "Arun",
                "last_name" => "Thampi",
                "image_24" => "https://s3-us-west-2.amazonaws.com/slack-files2/avatars/2015-05-11/4836202382_65573aedd51b9b423a87_24.jpg",
                "image_32" => "https://s3-us-west-2.amazonaws.com/slack-files2/avatars/2015-05-11/4836202382_65573aedd51b9b423a87_32.jpg",
                "image_48"=>"https://s3-us-west-2.amazonaws.com/slack-files2/avatars/2015-05-11/4836202382_65573aedd51b9b423a87_48.jpg",
                "image_72"=>"https://s3-us-west-2.amazonaws.com/slack-files2/avatars/2015-05-11/4836202382_65573aedd51b9b423a87_72.jpg",
                "image_192"=>"https://s3-us-west-2.amazonaws.com/slack-files2/avatars/2015-05-11/4836202382_65573aedd51b9b423a87_192.jpg",
                "image_original"=>"https://s3-us-west-2.amazonaws.com/slack-files2/avatars/2015-05-11/4836202382_65573aedd51b9b423a87_original.jpg",
                "skype"=>"arun_thampi",
                "real_name"=>"Arun Thampi",
                "real_name_normalized"=>"Arun Thampi",
                "email"=>"arun@mixcel.io"
              },
              "is_admin"=>true,
              "is_owner"=>true,
              "is_primary_owner"=>true,
              "is_restricted"=>false,
              "is_ultra_restricted"=>false,
              "is_bot"=>false,
              "has_files"=>true,
              "has_2fa"=>false
            }
          }
        }
      }
    }

    before do
      allow(ImportUsersForTeamJob).to receive(:perform_async)
    end

    context 'when user is signed in' do
      let!(:user) { create :user }

      before do
        request.env.merge!('omniauth.auth' => omniauth_hash)
        sign_in user
      end

      def do_request
        get :slack
      end

      context 'when a matching identity is not found (user is signed in to a different team with the same uid)' do
        let!(:identity) {
          create(:identity, provider: 'slack',
                 uid: omniauth_hash['uid'],
                 team_uid: 'TDEADBEEF',
                 token: 'deadbeef',
                 user: user)
        }

        it 'creates a new identity record' do
          expect {
            do_request
          }.to change { user.reload.identities.count }.by(1)

          expect(user.identities.last.provider).to eq('slack')
          expect(user.identities.last.uid).to eq(omniauth_hash['uid'])
          expect(user.identities.last.team_uid).to eq(omniauth_hash['info']['team_id'])
          expect(user.identities.last.token).to eq 'deadbeef'
        end
      end

      context 'when a matching identity is found' do
        let!(:identity) {
          create(:identity, provider: 'slack',
                 uid: omniauth_hash['uid'],
                 team_uid: omniauth_hash['info']['team_id'],
                 token: 'deadbeef',
                 user: user)
        }

        it 'does not create new identity' do
          expect {
            do_request
          }.to_not change { user.reload.identities.count }
        end

        it "should redirect to the team path" do
          do_request
          expect(response).to redirect_to team_url('T0304SBJU')
        end

        it 'updates identity object with new token' do
          do_request
          expect(identity.reload.token).to eql omniauth_hash['credentials']['token']
        end

        it 'should not update the email of the user' do
          expect {
            do_request
            user.reload
          }.to_not change(user, :email)
        end

        it 'should update the user with the Omniauth data received' do
          do_request
          user.reload

          expect(user.nickname).to eql 'arun'
          expect(user.first_name).to eql 'Arun'
          expect(user.last_name).to eql 'Thampi'
          expect(user.full_name).to eql 'Arun Thampi'

          expect(user.signed_in_via_oauth).to be_truthy

          team = user.teams.first

          expect(team.name).to eql 'Mixcel'
          expect(team.uid).to eql 'T0304SBJU'
          expect(team.url).to eql 'https://mixcel.slack.com/'

          tm = user.team_memberships.first
          expect(tm.membership_type).to eql 'owner'

          expect(user.image_url).to eql 'https://s3-us-west-2.amazonaws.com/slack-files2/avatars/2015-05-11/4836202382_65573aedd51b9b423a87_192.jpg'
          expect(user.timezone).to eql 'America/Los_Angeles'
          expect(user.timezone_description).to eql 'Pacific Daylight Time'
          expect(user.timezone_offset).to eql -25200
        end

        it "creates a new bot" do
          do_request

          u = controller.current_user
          team = u.teams.first
          bot = team.bot

          expect(bot).to_not be_nil
          expect(bot.creator).to eql u
          expect(bot.token).to eql 'xoxb-cafedead'
        end
      end
    end

    context 'when user is not signed in' do
      before do
        request.env.merge!('omniauth.auth' => omniauth_hash)
      end

      context 'when there is an existing user identity with the same uid and provider' do
        let!(:identity)       { create :identity, uid: omniauth_hash['uid'], provider: 'slack', team_uid: omniauth_hash['info']['team_id'] }
        let!(:user)           { identity.user }

        it "logs the user in" do
          do_request
          expect(controller).to be_signed_in
          expect(controller.current_user).to eq(user)
        end

        it "redirects to the team path" do
          do_request
          expect(response).to redirect_to team_url('T0304SBJU')
        end

        # This user already exists in the database and is most likely
        # creating a new team from the same Nestor user account
        # (but probably a different email address on Slack)
        # So we don't update email addresses
        it "should not change the user's email address" do
          expect {
            do_request
            user.reload
          }.to_not change(user, :email)
        end

        it "updates the identity data" do
          do_request
          identity.reload
          expect(identity.token).to eq(omniauth_hash['credentials']['token'])
        end

        it "updates the information for that user based on the Omniauth callback data" do
          do_request
          user.reload

          expect(user.nickname).to eql 'arun'
          expect(user.first_name).to eql 'Arun'
          expect(user.last_name).to eql 'Thampi'
          expect(user.full_name).to eql 'Arun Thampi'

          expect(user.signed_in_via_oauth).to be_truthy

          team = user.teams.first

          expect(team.name).to eql 'Mixcel'
          expect(team.uid).to eql 'T0304SBJU'
          expect(team.url).to eql 'https://mixcel.slack.com/'

          tm = user.team_memberships.first
          expect(tm.membership_type).to eql 'owner'

          expect(user.image_url).to eql 'https://s3-us-west-2.amazonaws.com/slack-files2/avatars/2015-05-11/4836202382_65573aedd51b9b423a87_192.jpg'
          expect(user.timezone).to eql 'America/Los_Angeles'
          expect(user.timezone_description).to eql 'Pacific Daylight Time'
          expect(user.timezone_offset).to eql -25200
        end

        it "creates a new bot" do
          do_request

          u = controller.current_user
          team = u.teams.first
          bot = team.bot

          expect(bot).to_not be_nil
          expect(bot.creator).to eql u
          expect(bot.token).to eql 'xoxb-cafedead'
        end
      end

      # This is the case when a user has been imported into the system
      # (from a team)
      context "when there is a user with the given provider_uid and no identity" do
        let!(:team) { create :team, name: 'Mixcel', uid: 'T0304SBJU', url: 'https://mixcel.slack.com/' }
        let!(:user) { create :user }
        let!(:tm)   { create :team_membership, team: team, user: user, user_uid: 'U0304SBK4' }

        it "logs the user in" do
          do_request
          expect(controller).to be_signed_in
          expect(controller.current_user).to eq(user)
        end

        it "redirects to the team path" do
          do_request
          expect(response).to redirect_to team_url('T0304SBJU')
        end

        it "updates the identity data" do
          do_request
          identity = user.identities.where(provider: omniauth_hash['provider'], uid: omniauth_hash['uid']).first

          expect(identity).to_not be_nil
          expect(identity.token).to eq(omniauth_hash['credentials']['token'])
        end

        it 'should not update the email of the user' do
          expect {
            do_request
            user.reload
          }.to_not change(user, :email)
        end

        it "updates the information for that user based on the Omniauth callback data" do
          do_request
          user.reload

          expect(user.nickname).to eql 'arun'
          expect(user.first_name).to eql 'Arun'
          expect(user.last_name).to eql 'Thampi'
          expect(user.full_name).to eql 'Arun Thampi'
          expect(user.signed_in_via_oauth).to be_truthy

          team = user.teams.first

          expect(team.name).to eql 'Mixcel'
          expect(team.uid).to eql 'T0304SBJU'
          expect(team.url).to eql 'https://mixcel.slack.com/'

          tm = user.team_memberships.first
          expect(tm.membership_type).to eql 'owner'

          expect(user.image_url).to eql 'https://s3-us-west-2.amazonaws.com/slack-files2/avatars/2015-05-11/4836202382_65573aedd51b9b423a87_192.jpg'
          expect(user.timezone).to eql 'America/Los_Angeles'
          expect(user.timezone_description).to eql 'Pacific Daylight Time'
          expect(user.timezone_offset).to eql -25200
        end

        it "creates a new bot" do
          do_request

          u = controller.current_user
          team = u.teams.first
          bot = team.bot

          expect(bot).to_not be_nil
          expect(bot.creator).to eql u
          expect(bot.token).to eql 'xoxb-cafedead'
        end
      end
    end
  end
end


text:
from __future__ import unicode_literals

from django.db import migrations, models

class Migration(migrations.Migration):

    dependencies = [
        ('model_less', '0002_userloc_username'),
    ]

    operations = [
        migrations.CreateModel(
            name='group',
            fields=[
                ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
                ('groupid', models.CharField(max_length=200)),
                ('users', models.CharField(max_length=200)),
            ],
        ),
    ]


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

import com.intellij.openapi.project.Project;
import com.intellij.util.messages.Topic;
import org.jetbrains.annotations.CalledInAwt;
import org.jetbrains.annotations.NotNull;

public interface ProjectEx extends Project {
  /**
   * Consider using only and only if {@link com.intellij.configurationStore.SettingsSavingComponent} is not possible to use.
   */
  interface ProjectSaved {
    Topic<ProjectSaved> TOPIC = Topic.create("SaveProjectTopic", ProjectSaved.class);

    @SuppressWarnings("unused")
    @CalledInAwt
    @Deprecated
    default void saved(@NotNull Project project) {
    }

    /**
     * Not called in EDT.
     */
    default void duringSave(@NotNull Project project) {
    }
  }

  void init();

  void setProjectName(@NotNull String name);
}


text:
/**
 * A collection of grpc resolovers.
 */
package org.apache.bookkeeper.grpc.resolver;


text:
{% comment %}
This template must be overriden to implement listing comments and displaying a comment box.

You will recieve a context object called comment_object which is the object being commented on.
{% endcomment %}


text:
package alec_wam.CrystalMod.tiles.machine.power.redstonereactor;

import java.util.Random;

import alec_wam.CrystalMod.CrystalMod;
import alec_wam.CrystalMod.blocks.ICustomModel;
import alec_wam.CrystalMod.blocks.ModBlocks;
import alec_wam.CrystalMod.util.ItemUtil;
import net.minecraft.block.BlockContainer;
import net.minecraft.block.material.Material;
import net.minecraft.block.state.IBlockState;
import net.minecraft.client.renderer.block.model.ModelResourceLocation;
import net.minecraft.client.renderer.block.statemap.StateMapperBase;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.inventory.IInventory;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.EnumBlockRenderType;
import net.minecraft.util.EnumFacing;
import net.minecraft.util.EnumHand;
import net.minecraft.util.EnumParticleTypes;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.World;
import net.minecraftforge.client.model.ModelLoader;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;

public class BlockRedstoneReactor extends BlockContainer implements ICustomModel {

	public BlockRedstoneReactor() {
		super(Material.IRON);
		setHardness(5.0F);
		setResistance(10.0F);
		setCreativeTab(CrystalMod.tabBlocks);
	}

	@Override
    public void breakBlock(World world, BlockPos pos, IBlockState blockState)
    {
		TileEntity tileentitychest = world.getTileEntity(pos);
        if (tileentitychest != null && tileentitychest instanceof IInventory)
        {
        	ItemUtil.dropContent(0, (IInventory)tileentitychest, world, tileentitychest.getPos());
        }
        super.breakBlock(world, pos, blockState);
    }

	@Override
    public EnumBlockRenderType getRenderType(IBlockState state){
    	return EnumBlockRenderType.MODEL;
    }

	@SideOnly(Side.CLIENT)
    @Override
    public void randomDisplayTick(IBlockState state, World world, BlockPos pos, Random rand)
    {
		TileEntity tile = world.getTileEntity(pos);
        if (tile != null && tile instanceof TileRedstoneReactor)
        {
           TileRedstoneReactor reactor = (TileRedstoneReactor)tile;
           if(reactor.remainingFuel.getValue() > 0 && !world.isBlockPowered(pos)){
	           Random random = world.rand;
	           double d1 = pos.getX() + random.nextFloat();
	           double d2 = pos.getY() + random.nextFloat();
	           double d3 = pos.getZ() + random.nextFloat();

	           if (!world.getBlockState(pos.up()).isOpaqueCube())
	           {
	        	   d2 = pos.getY() + 0.0625D + 1.0D;
	           }

	           if (d1 < pos.getX() || d1 > pos.getX() + 1 || d2 < 0.0D || d2 > pos.getY() + 1 || d3 < pos.getZ() || d3 > pos.getZ() + 1)
	           {
	        	   random.nextFloat();
	        	   world.spawnParticle(EnumParticleTypes.REDSTONE, d1, d2, d3, 0.0D, 0.0D, 0.0D, new int[0]);
	           }
           }
        }
    }

	@Override
	public boolean onBlockActivated(World world, BlockPos pos, IBlockState state, EntityPlayer player, EnumHand hand, EnumFacing facing, float hitX, float hitY, float hitZ)
    {
		if(!player.isSneaking()){
			if(!world.isRemote){
				player.openGui(CrystalMod.instance, 0, world, pos.getX(), pos.getY(), pos.getZ());
			}
			return true;
		}
        return false;
    }

	@Override
	public TileEntity createNewTileEntity(World worldIn, int meta) {
		return new TileRedstoneReactor();
	}

	public static class CustomBlockStateMapper extends StateMapperBase
	{
		@Override
		protected ModelResourceLocation getModelResourceLocation(IBlockState state)
		{
			return new ModelResourceLocation(state.getBlock().getRegistryName(), "normal");
		}
	}

	@Override
	@SideOnly(Side.CLIENT)
	public void initModel() {
    	ModelLoader.setCustomStateMapper(this, new CustomBlockStateMapper());
		ModBlocks.initBasicModel(this);
	}

}


text:
'use strict';

/**
 * @ngdoc service
 * @name labelsApp.waybackService
 * @description
 * # waybackService
 * Service in the labelsApp.
 */
angular.module('labelsApp')
  .service('WaybackService', function ($http, ConfigService) {

    this.get = function(url, success, failure) {
        $http.get(ConfigService.api + '/resourcewayback?url=' + url).then(function(res) {
            // return wayback link
            success(res.data.uri);
        }, function(err) {
            failure(err);
        });
    };

  });