text:
"""Tests of fiona.env"""

import os
import sys
try:
    from unittest import mock
except ImportError:
    import mock

import fiona
from fiona import _env
from fiona.env import getenv, hasenv, ensure_env, ensure_env_with_credentials
from fiona.session import AWSSession, GSSession

def test_nested_credentials(monkeypatch):
    """Check that rasterio.open() doesn't wipe out surrounding credentials"""

    @ensure_env_with_credentials
    def fake_opener(path):
        return fiona.env.getenv()

    with fiona.env.Env(session=AWSSession(aws_access_key_id='foo', aws_secret_access_key='bar')):
        assert fiona.env.getenv()['AWS_ACCESS_KEY_ID'] == 'foo'
        assert fiona.env.getenv()['AWS_SECRET_ACCESS_KEY'] == 'bar'

        monkeypatch.setenv('AWS_ACCESS_KEY_ID', 'lol')
        monkeypatch.setenv('AWS_SECRET_ACCESS_KEY', 'wut')
        gdalenv = fake_opener('s3://foo/bar')
        assert gdalenv['AWS_ACCESS_KEY_ID'] == 'foo'
        assert gdalenv['AWS_SECRET_ACCESS_KEY'] == 'bar'

def test_ensure_env_decorator(gdalenv):
    @ensure_env
    def f():
        return getenv()['FIONA_ENV']
    assert f() is True

def test_ensure_env_decorator_sets_gdal_data(gdalenv, monkeypatch):
    """fiona.env.ensure_env finds GDAL from environment"""
    @ensure_env
    def f():
        return getenv()['GDAL_DATA']

    monkeypatch.setenv('GDAL_DATA', '/lol/wut')
    assert f() == '/lol/wut'

@mock.patch("fiona._env.GDALDataFinder.find_file")
def test_ensure_env_decorator_sets_gdal_data_prefix(find_file, gdalenv, monkeypatch, tmpdir):
    """fiona.env.ensure_env finds GDAL data under a prefix"""
    @ensure_env
    def f():
        return getenv()['GDAL_DATA']

    find_file.return_value = None
    tmpdir.ensure("share/gdal/header.dxf")
    monkeypatch.delenv('GDAL_DATA', raising=False)
    monkeypatch.setattr(_env, '__file__', str(tmpdir.join("fake.py")))
    monkeypatch.setattr(sys, 'prefix', str(tmpdir))

    assert f() == str(tmpdir.join("share").join("gdal"))

@mock.patch("fiona._env.GDALDataFinder.find_file")
def test_ensure_env_decorator_sets_gdal_data_wheel(find_file, gdalenv, monkeypatch, tmpdir):
    """fiona.env.ensure_env finds GDAL data in a wheel"""
    @ensure_env
    def f():
        return getenv()['GDAL_DATA']

    find_file.return_value = None
    tmpdir.ensure("gdal_data/header.dxf")
    monkeypatch.delenv('GDAL_DATA', raising=False)
    monkeypatch.setattr(_env, '__file__', str(tmpdir.join(os.path.basename(_env.__file__))))

    assert f() == str(tmpdir.join("gdal_data"))

@mock.patch("fiona._env.GDALDataFinder.find_file")
def test_ensure_env_with_decorator_sets_gdal_data_wheel(find_file, gdalenv, monkeypatch, tmpdir):
    """fiona.env.ensure_env finds GDAL data in a wheel"""
    @ensure_env_with_credentials
    def f(*args):
        return getenv()['GDAL_DATA']

    find_file.return_value = None
    tmpdir.ensure("gdal_data/header.dxf")
    monkeypatch.delenv('GDAL_DATA', raising=False)
    monkeypatch.setattr(_env, '__file__', str(tmpdir.join(os.path.basename(_env.__file__))))

    assert f("foo") == str(tmpdir.join("gdal_data"))

def test_ensure_env_crs(path_coutwildrnp_shp):
    """Decoration of .crs works"""
    assert fiona.open(path_coutwildrnp_shp).crs

def test_env_default_env(path_coutwildrnp_shp):
    with fiona.open(path_coutwildrnp_shp):
        assert hasenv()

def test_nested_gs_credentials(monkeypatch):
    """Check that rasterio.open() doesn't wipe out surrounding credentials"""

    @ensure_env_with_credentials
    def fake_opener(path):
        return fiona.env.getenv()

    with fiona.env.Env(session=GSSession(google_application_credentials='foo')):
        assert fiona.env.getenv()['GOOGLE_APPLICATION_CREDENTIALS'] == 'foo'

        gdalenv = fake_opener('gs://foo/bar')
        assert gdalenv['GOOGLE_APPLICATION_CREDENTIALS'] == 'foo'


text:
from __future__ import division
from sympy import symbols, integrate, pi, lambdify, Number, cos, sin
from numpy.polynomial.legendre import leggauss
import scipy.sparse.linalg as sparse_la
import scipy.linalg as la
import lega.fourier_basis as fourier
import lega.shen_basis as shen
from lega.common import tensor_product, function
from lega.legendre_basis import forward_transformation_matrix as FLT
from lega.legendre_basis import backward_transformation_matrix as BLT
from itertools import product
from sympy.mpmath import quad
import numpy as np
import time

def get_u0(u0=None):

    x, y = symbols('x, y')

    if u0 is None:
        u0 = sin(pi*y)*cos(x)

    assert u0.subs(y, -1) == 0
    assert u0.subs(y, 1) == 0
    assert (u0.subs(x, 0) - u0.subs(x, 2*pi)) == 0

    return u0

def solve_heat(u0, n_fourier, n_shen, dt=1E-4, T=0.01):
    '''
    Solve the Poisson problem with highest frequency n_fourier and n_shen
    polynomials (that is n_shen+1 is the highest degree in that basis).
    '''
    # We plan to solve the problem in the basis of eigenvector of Au=aMu where
    # A, M are shen matrices. The time discretization is bit it's
    # innitialization requires a bit of work
    A = shen.stiffness_matrix(n_shen)
    M = shen.mass_matrix(n_shen)
    lmbda_shen, V = la.eigh(A.toarray(), M.toarray())

    # Prepare U0
    # First points are evaluated at the grid
    x, y = symbols('x, y')
    n, m = 2*n_fourier, n_shen+2
    fourier_points = np.linspace(0, 2*np.pi, n, endpoint=False)
    legendre_points = leggauss(m)[0]
    points = np.array([list(p)
                       for p in product(fourier_points, legendre_points)])
    if isinstance(u0, (int, float, Number)):
        U0_vec = float(f)*np.ones((n, m))
    else:
        u0 = lambdify([x, y], u0, 'numpy')
        U0_vec = u0(points[:, 0], points[:, 1]).reshape((n, m))

    # Now the columns which is u0 evaluated at Fourier points for fixed y at some
    # quadrature points is Fourier transformed
    U0 = np.array([fourier.fft(col) for col in U0_vec.T]).T
    # Now Forward Legendre transform each row
    flt = FLT(m)
    U0 = np.array([flt.dot(row) for row in U0])
    # At this points each row is a representation in the legendre basis and
    # needs to be transformed to Shen basis by projection.
    U0 = np.array([sparse_la.spsolve(M, shen.load_vector(row)) for row in U0])
    assert U0.shape == (n+1, n_shen)

    # As far as U0 is concerned, the ONLY extra step for Shen's eigenvectors is
    # to transform each row from normal Shen representation to the eigenvector
    # representation
    U0_eig = U0.dot(M.dot(V))  # SAME as U0_eig = V.T.dot(M.dot(U0.T)).T

    # Now we build the Crank-Nicolson. This multiples the U0 and that's it for
    # time stepping
    lmbda_fourier = fourier.stiffness_matrix(n_fourier)

    CN = 1 - 0.5*dt*np.tile(lmbda_fourier, (n_shen, 1)).T\
           - 0.5*dt*np.tile(lmbda_shen, (n+1, 1))
    CN /= 1 + 0.5*dt*np.tile(lmbda_fourier, (n_shen, 1)).T\
            + 0.5*dt*np.tile(lmbda_shen, (n+1, 1))
    assert U0.shape == CN.shape

    # FIXME: Here we build a new (2*n_fourier+1, n_shen) matrix. For saving
    # memory we can build a CN_k factor for each lmbda_fourier wavenumber. Then
    # there are two loops time  and within there over fourier wave numbers

    # Time loop
    t = 0
    n_steps = 0
    start = time.time()
    print 'Time integrating...',
    while t < T:
        t += dt
        n_steps +=1
        U0_eig *= CN
    print 'done in %gs [%d steps]' % (time.time() - start, n_steps)

    # Take the solution from eigenspace to Shen
    U0 = U0_eig.dot(V.T)
    assert U0.shape == (n+1, n_shen)

    # Take the solution from fourier x shen to fourier x leg and then points
    toLeg = shen.legendre_to_shen_matrix(n_shen+2).toarray()
    U0 = U0.dot(toLeg)

    blt = BLT(m).T
    U0 = np.array([blt.dot(row) for row in U0])
    U0 = np.array([fourier.ifft(col) for col in U0.T]).T

    return points, U0

# -----------------------------------------------------------------------------

if __name__ == '__main__':
    import matplotlib.pyplot as plt

    n_fourier = 1024
    n_shen = 48

    u0 = get_u0()
    points, Uh = solve_heat(u0, n_fourier, n_shen, T=1)

    # Get ready for plotting
    n, m = Uh.shape
    X = points[:, 0].reshape((n, m))
    Y = points[:, 1].reshape((n, m))

    plt.figure()
    plt.pcolor(X, Y, Uh)
    plt.colorbar()
    plt.xlim((0, 2*np.pi))
    plt.ylim((-1, 1))
    plt.show()

redpajama_set_name: RedPajamaGithub


text:
<?php
namespace Mopa\Bundle\BootstrapBundle\Navbar;

use Symfony\Component\Form\FormView;
use Symfony\Component\Form\AbstractType;

class GenericNavbar implements NavbarInterface
{

    protected $options = array();
    protected $formClasses = array();
    protected $formTypes = array();
    protected $formViews = array();
    protected $menus = array();

    public function __construct(array $menus, array $formClasses, array $options)
    {
        $this->menus = $menus;
        $this->formClasses = $formClasses;
        $this->options = $options;
    }
    public function hasMenu($key)
    {
        return array_key_exists($key, $this->menus);
    }
    public function getMenu($key)
    {
        if (array_key_exists($key, $this->menus)) {
            return $this->menus[$key];
        }
        throw new \Exception("Menu " . $key . " not found!");
    }
    public function getFormClass($key)
    {
        if (array_key_exists($key, $this->formClasses)) {
            return $this->formClasses[$key];
        }
        throw new \Exception("FormClass " . $key . " not found!");
    }
    public function getFormType($key)
    {
        if (array_key_exists($key, $this->formTypes)) {
            return $this->formTypes[$key];
        }
        throw new \Exception("FormType " . $key . " not found!");
    }
    public function setFormType($key, AbstractType $formView)
    {
        $this->formTypes[$key] = $formView;
    }
    public function hasOption($key)
    {
        return array_key_exists($key, $this->options);
    }
    public function getOption($key)
    {
        if (array_key_exists($key, $this->options)) {
            return $this->options[$key];
        }
        throw new OptionNotFoundException("Option " . $key . " not found!");
    }
    public function getFormClasses()
    {
        return $this->formClasses;
    }

    public function hasFormView($key)
    {
        return in_array($key, array_keys($this->formViews));
    }
    public function getFormView($key)
    {
        if ($this->hasFormView($key)) {
            return $this->formViews[$key];
        }
        throw new \Exception("FormView " . $key . " not found!");
    }
    public function setFormView($key, FormView $formView)
    {
        $this->formViews[$key] = $formView;
    }
    public function getFormRoute($key)
    {
        if (array_key_exists($key, $this->formTypes)) {
            if (($this->formTypes[$key]) instanceof NavbarFormInterface) {
                return $this->formTypes[$key]->getRoute();
            } else {
                throw new \Exception("FormType " . get_class($this->formType[$key]) . " must implement NavbarFormInterface");
            }
        }
    }
    public function makeDropdown($menuItem)
    {
        $menuItem
            ->setDisplay(false)
            ->setAttribute('class', 'nav secondary-nav');
    }
}


text:
import QuestionPage from '../question.page'

class Turnover2016Page extends QuestionPage {

  constructor() {
    super('turnover-2016')
  }

  setTurnover2016Answer(value) {
    browser.setValue('[name="turnover-2016-answer"]', value)
    return this
  }

  getTurnover2016Answer(value) {
    return browser.element('[name="turnover-2016-answer"]').getValue()
  }

}

export default new Turnover2016Page()


text:
<?xml version="1.0" encoding="utf-8"?>
<!-- Copyright (C) 2011 The Pluroium Development Team.

     Licensed under the Apache License, Version 2.0 (the "License");
     you may not use this file except in compliance with the License.
     You may obtain a copy of the License at

          http://www.apache.org/licenses/LICENSE-2.0

     Unless required by applicable law or agreed to in writing, software
     distributed under the License is distributed on an "AS IS" BASIS,
     WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
     See the License for the specific language governing permissions and
     limitations under the License.
-->

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              android:orientation="vertical"
              android:layout_width="fill_parent"
              android:layout_height="fill_parent"
              android:padding="3dp">

    <LinearLayout android:orientation="horizontal"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content">

        <ImageView android:id="@+id/upload_icon"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:src="@android:drawable/stat_sys_upload"/>

        <TextView android:id="@+id/upload_title"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:text="Uploading photo..." />

    </LinearLayout>

    <ProgressBar android:id="@+id/upload_progress"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:indeterminate="false"
        android:max="100"
        style="?android:attr/progressBarStyleHorizontal" />

</LinearLayout>


text:
package org.kordamp.jipsy.processor;

import org.junit.Test;
import org.kordamp.jipsy.processor.testutils.NoOutputTestBase;

import static junit.framework.Assert.assertFalse;
import static junit.framework.Assert.assertTrue;

public class LogLocationTest extends NoOutputTestBase {

    @Test
    public void testMessager() {
        assertTrue(LogLocation.MESSAGER.toMessager());
        assertFalse(LogLocation.MESSAGER.toLogFile());
    }

    @Test
    public void testLogFile() {
        assertFalse(LogLocation.LOG_FILE.toMessager());
        assertTrue(LogLocation.LOG_FILE.toLogFile());
    }

    @Test
    public void testBoth() {
        assertTrue(LogLocation.BOTH.toMessager());
        assertTrue(LogLocation.BOTH.toLogFile());
    }
}


text:
package tests

import (
	. "github.com/onsi/ginkgo/v2"
	"github.com/onsi/gomega"
	_ "github.com/vito/booklit/tests/fixtures/erroring-plugin"
)

var _ = DescribeTable("Booklit", (Example).Run,
	Entry("unknown function", Example{
		Input: `\title{Hello, world!}

\banana{attack}
`,

		LoadErr: gomega.ContainSubstring("undefined function \\banana"),
	}),

	Entry("erroring single-return function", Example{
		Input: `\title{Hello, world!}

\use-plugin{errer}

\single-fail{some arg}

\multi-return-fail{some arg}
`,

		LoadErr: gomega.ContainSubstring("function \\single-fail returned an error: oh no"),
	}),

	Entry("erroring multi-return function", Example{
		Input: `\title{Hello, world!}

\use-plugin{errer}

\multi-fail{some arg}
`,

		LoadErr: gomega.ContainSubstring("function \\multi-fail returned an error: oh no"),
	}),

	Entry("ambiguous references", Example{
		Input: `\title{Hello, world!}

See also \reference{dupe-tag}{this tag}.

\section{
	\title{First Tag}

	\target{dupe-tag}{I'm the first tag.}
}

\section{
	\title{Second Tag}

	\target{dupe-tag}{I'm the second tag.}
}
`,

		RenderErr: gomega.MatchRegexp(`ambiguous target for tag 'dupe-tag'`),
	}),

	Entry("missing references", Example{
		Input: `\title{Hello, world!}

See also \reference{missing-tag}{this tag}.
`,

		RenderErr: gomega.MatchRegexp(`unknown tag 'missing-tag'`),
	}),

	Entry("setting title twice", Example{
		Input: `\title{Hello, world!}

\title{BAM}
`,

		LoadErr: gomega.ContainSubstring("cannot set title twice"),
	}),
)


text:
<?php

namespace Sonata\FormatterBundle\Tests\Form\EventListener;

use Sonata\FormatterBundle\Form\EventListener\FormatterListener;
use Sonata\FormatterBundle\Formatter\Pool;
use Sonata\FormatterBundle\Formatter\FormatterInterface;
use Symfony\Component\Form\Test\FormInterface;

use Symfony\Component\Form\FormEvent;

class FormatterListenerTest extends \PHPUnit_Framework_TestCase
{
    public function testWithInvalidFormatter()
    {
        $this->setExpectedException('RuntimeException');

        $pool = new Pool();

        $listener = new FormatterListener($pool, '[format]', '[source]', '[target]');

        $event = new FormEvent($this->getMock('Symfony\Component\Form\Test\FormInterface'), array(
            'format' => 'error',
            'source' => 'data',
            'target' => null,
        ));

        $listener->postSubmit($event);
    }

    public function testWithValidFormatter()
    {
        $formater = $this->getMock('Sonata\FormatterBundle\Formatter\FormatterInterface');
        $formater->expects($this->once())->method('transform')->will($this->returnCallback(function($text) {
            return strtoupper($text);
        }));

        $pool = new Pool();
        $pool->add('myformat', $formater);

        $listener = new FormatterListener($pool, '[format]', '[source]', '[target]');

        $event = new FormEvent($this->getMock('Symfony\Component\Form\Test\FormInterface'), array(
            'format' => 'myformat',
            'source' => 'data',
            'target' => null,
        ));

        $listener->postSubmit($event);

        $expected =  array(
            'format' => 'myformat',
            'source' => 'data',
            'target' => 'DATA'
        );

        $this->assertEquals($expected, $event->getData());
    }

}


text:
@implementation UIApplication (HZExtend)

#pragma mark - Properties
- (NSString *)rootPath
{
    return NSHomeDirectory();
}

- (NSURL *)rootURL
{
    return [NSURL fileURLWithPath:[self rootPath]];
}

- (NSURL *)documentsURL
{
    return [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject];
}

- (NSString *)documentsPath
{
    return [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject];
}

- (NSURL *)cachesURL {
    return [[[NSFileManager defaultManager] URLsForDirectory:NSCachesDirectory inDomains:NSUserDomainMask] lastObject];
}

- (NSString *)cachesPath
{
    return [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) firstObject];
}

- (NSURL *)libraryURL
{
    return [[[NSFileManager defaultManager] URLsForDirectory:NSLibraryDirectory inDomains:NSUserDomainMask] lastObject];
}

- (NSString *)libraryPath
{
    return [NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES) firstObject];
}

- (NSURL *)tmpURL
{
    return [NSURL fileURLWithPath:[self tmpPath]];
}

- (NSString *)tmpPath
{
    return NSTemporaryDirectory();
}

- (NSString *)appBundleName
{
    return [[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleName"];
}

- (NSString *)appBundleID
{
    return [[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleIdentifier"];
}

- (NSString *)appBundleIdentifier
{
    return [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleIdentifier"];
}

- (NSString *)appVersion
{
    return [[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleShortVersionString"];
}

- (NSString *)appBuildVersion
{
    return [[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleVersion"];
}

@end


text:
package org.kaazing.mina.netty;

import java.util.Arrays;
import java.util.List;

import org.apache.mina.core.session.IoSession;
import org.jmock.integration.junit4.JUnitRuleMockery;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.RuleChain;
import org.junit.rules.TestRule;
import org.junit.runners.model.Statement;
import org.kaazing.mina.util.DefaultExceptionMonitor;
import org.kaazing.test.util.MemoryAppender;
import org.kaazing.test.util.MethodExecutionTrace;

public class DefaultExceptionMonitorTest
{
    @Rule
    public JUnitRuleMockery context = new JUnitRuleMockery();

    private static final String ERROR_MESSAGE = "ERROR";
    private static final String EXCEPTION_MESSAGE = "EXCEPTION";
    private List<String> expectedPatterns;

    public TestRule trace = new MethodExecutionTrace();

    private TestRule checkLogMessageRule = (base, description) -> new Statement() {
        @Override
        public void evaluate() throws Throwable {
            base.evaluate();
            MemoryAppender.assertMessagesLogged(expectedPatterns, null, null, true);
        }
    };

    @Rule
    public TestRule chain = RuleChain.outerRule(trace).around(checkLogMessageRule);

    @Test(expected=Error.class)
    public void exceptionCaughtShouldRethrowError() throws Exception {
        IoSession session = context.mock(IoSession.class);
        new DefaultExceptionMonitor().exceptionCaught(new Error(ERROR_MESSAGE), session);
    }

    @Test
    public void shouldLogMessageIncludingSession() throws Exception {
        IoSession session = context.mock(IoSession.class, "session");

        new DefaultExceptionMonitor().exceptionCaught(new NullPointerException(EXCEPTION_MESSAGE), session);
        expectedPatterns = Arrays.asList("Unexpected exception in session session");
    }
}


text:
<?php
/**
 * AffectedResourcesTest
 *
 * PHP version 5
 *
 * @category Class
 * @package  Swagger\Client
 * @author   Swagger Codegen team
 * @link     https://github.com/swagger-api/swagger-codegen
 */

/**
 * PhraseApp
 *
 * PhraseApp API for the interaction with the PhraseApp localization platform
 *
 * OpenAPI spec version: 2.0
 * Contact: support@phraseapp.com
 * Generated by: https://github.com/swagger-api/swagger-codegen.git
 *
 */

/**
 * NOTE: This class is auto generated by the swagger code generator program.
 * https://github.com/swagger-api/swagger-codegen
 * Please update the test case below to test the model.
 */

namespace Swagger\Client;

/**
 * AffectedResourcesTest Class Doc Comment
 *
 * @category    Class */
// * @description AffectedResources
/**
 * @package     Swagger\Client
 * @author      Swagger Codegen team
 * @link        https://github.com/swagger-api/swagger-codegen
 */
class AffectedResourcesTest extends \PHPUnit_Framework_TestCase
{

    /**
     * Setup before running any test case
     */
    public static function setUpBeforeClass()
    {
    }

    /**
     * Setup before running each test case
     */
    public function setUp()
    {
    }

    /**
     * Clean up after running each test case
     */
    public function tearDown()
    {
    }

    /**
     * Clean up after running all test cases
     */
    public static function tearDownAfterClass()
    {
    }

    /**
     * Test "AffectedResources"
     */
    public function testAffectedResources()
    {
    }

    /**
     * Test attribute "records_affected"
     */
    public function testPropertyRecordsAffected()
    {
    }
}


text:
'use strict';

Object.defineProperty(exports, "__esModule", {
  value: true
});

var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };

exports.default = dragOffset;
exports.getSourceClientOffset = getSourceClientOffset;
exports.getDifferenceFromInitialOffset = getDifferenceFromInitialOffset;

var _dragDrop = require('../actions/dragDrop');

var initialState = {
  initialSourceClientOffset: null,
  initialClientOffset: null,
  clientOffset: null
};

function areOffsetsEqual(offsetA, offsetB) {
  if (offsetA === offsetB) {
    return true;
  }
  return offsetA && offsetB && offsetA.x === offsetB.x && offsetA.y === offsetB.y;
}

function dragOffset() {
  var state = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : initialState;
  var action = arguments[1];

  switch (action.type) {
    case _dragDrop.BEGIN_DRAG:
      return {
        initialSourceClientOffset: action.sourceClientOffset,
        initialClientOffset: action.clientOffset,
        clientOffset: action.clientOffset
      };
    case _dragDrop.HOVER:
      if (areOffsetsEqual(state.clientOffset, action.clientOffset)) {
        return state;
      }
      return _extends({}, state, {
        clientOffset: action.clientOffset
      });
    case _dragDrop.END_DRAG:
    case _dragDrop.DROP:
      return initialState;
    default:
      return state;
  }
}

function getSourceClientOffset(state) {
  var clientOffset = state.clientOffset,
      initialClientOffset = state.initialClientOffset,
      initialSourceClientOffset = state.initialSourceClientOffset;

  if (!clientOffset || !initialClientOffset || !initialSourceClientOffset) {
    return null;
  }
  return {
    x: clientOffset.x + initialSourceClientOffset.x - initialClientOffset.x,
    y: clientOffset.y + initialSourceClientOffset.y - initialClientOffset.y
  };
}

function getDifferenceFromInitialOffset(state) {
  var clientOffset = state.clientOffset,
      initialClientOffset = state.initialClientOffset;

  if (!clientOffset || !initialClientOffset) {
    return null;
  }
  return {
    x: clientOffset.x - initialClientOffset.x,
    y: clientOffset.y - initialClientOffset.y
  };
}


text:
require 'active_support'
unless Module.respond_to?(:mattr_accessor)
  require 'active_support/core_ext/module/attribute_accessors'# rescue nil  # this may be needed for ActiveSupport versions >= 3.x
end
require 'net/http'
require 'net/https'
require 'uri'
require 'digest/md5'
require File.join(File.dirname(__FILE__), 'maxmind/request')
require File.join(File.dirname(__FILE__), 'maxmind/response')


text:
<resources>
    <string name="app_name">swimdroid</string>
</resources>


text:
now, I belong with "fpinscala" reading club in my company.

here is my repository for my exercise.


text:
require 'minfraud/model/abstract'

module Minfraud
  module Model
    # Subscores for components that are used in calculating the riskScore.
    class Subscores < Abstract
      # The risk associated with the AVS result. If present, this is a value in
      # the range 0.01 to 99.
      #
      # @return [Float, nil]
      attr_reader :avs_result

      # The risk associated with the billing address. If present, this is a
      # value in the range 0.01 to 99.
      #
      # @return [Float, nil]
      attr_reader :billing_address

      # The risk associated with the distance between the billing address and
      # the location for the given IP address. If present, this is a value in
      # the range 0.01 to 99.
      #
      # @return [Float, nil]
      attr_reader :billing_address_distance_to_ip_location

      # The risk associated with the browser attributes such as the User-Agent
      # and Accept-Language. If present, this is a value in the range 0.01 to
      # 99.
      #
      # @return [Float, nil]
      attr_reader :browser

      # Individualized risk of chargeback for the given IP address given for
      # your account and any shop ID passed. This is only available to users
      # sending chargeback data to MaxMind. If present, this is a value in the
      # range 0.01 to 99.
      #
      # @return [Float, nil]
      attr_reader :chargeback

      # The risk associated with the country the transaction originated from.
      # If present, this is a value in the range 0.01 to 99.
      #
      # @return [Float, nil]
      attr_reader :country

      # The risk associated with the combination of IP country, card issuer
      # country, billing country, and shipping country. If present, this is a
      # value in the range 0.01 to 99.
      #
      # @return [Float, nil]
      attr_reader :country_mismatch

      # The risk associated with the CVV result. If present, this is a value in
      # the range 0.01 to 99.
      #
      # @return [Float, nil]
      attr_reader :cvv_result

      # The risk associated with the device. If present, this is a value in the
      # range of 0.01 to 99.
      #
      # @return [Float, nil]
      attr_reader :device

      # The risk associated with the particular email address. If present, this
      # is a value in the range 0.01 to 99.
      #
      # @return [Float, nil]
      attr_reader :email_address

      # The general risk associated with the email domain. If present, this is
      # a value in the range 0.01 to 99.
      #
      # @return [Float, nil]
      attr_reader :email_domain

      # The risk associated with the email address local part (the part of
      # the email address before the @ symbol). If present, this is a value
      # in the range 0.01 to 99.
      #
      # @return [Float, nil]
      attr_reader :email_local_part

      # The risk associated with the issuer ID number on the email domain. If
      # present, this is a value in the range 0.01 to 99.
      #
      # Deprecated effective August 29, 2019. This subscore will default to 1
      # and will be removed in a future release. The user tenure on email is
      # reflected in the /subscores/email_address output.
      #
      # @return [Float, nil]
      attr_reader :email_tenure

      # The risk associated with the issuer ID number on the IP address. If
      # present, this is a value in the range 0.01 to 99.
      #
      # Deprecated effective August 29, 2019. This subscore will default to 1
      # and will be removed in a future release. The IP tenure is reflected in
      # the overall risk score.
      #
      # @return [Float, nil]
      attr_reader :ip_tenure

      # The risk associated with the particular issuer ID number (IIN) given
      # the billing location and the history of usage of the IIN on your
      # account and shop ID. If present, this is a value in the range 0.01 to
      # 99.
      #
      # @return [Float, nil]
      attr_reader :issuer_id_number

      # The risk associated with the particular order amount for your account
      # and shop ID. If present, this is a value in the range 0.01 to 99.
      #
      # @return [Float, nil]
      attr_reader :order_amount

      # The risk associated with the particular phone number. If present, this
      # is a value in the range 0.01 to 99.
      #
      # @return [Float, nil]
      attr_reader :phone_number

      # The risk associated with the shipping address. If present, this is a
      # value in the range 0.01 to 99.
      #
      # @return [Float, nil]
      attr_reader :shipping_address

      # The risk associated with the distance between the shipping address and
      # the IP location for the given IP address. If present, this is a value
      # in the range 0.01 to 99.
      #
      # @return [Float, nil]
      attr_reader :shipping_address_distance_to_ip_location

      # The risk associated with the local time of day of the transaction in
      # the IP address location. If present, this is a value in the range 0.01
      # to 99.
      #
      # @return [Float, nil]
      attr_reader :time_of_day

      # @!visibility private
      def initialize(record)
        super(record)

        @avs_result                               = get('avs_result')
        @billing_address                          = get('billing_address')
        @billing_address_distance_to_ip_location  = get(
          'billing_address_distance_to_ip_location'
        )
        @browser                                  = get('browser')
        @chargeback                               = get('chargeback')
        @country                                  = get('country')
        @country_mismatch                         = get('country_mismatch')
        @cvv_result                               = get('cvv_result')
        @device                                   = get('device')
        @email_address                            = get('email_address')
        @email_domain                             = get('email_domain')
        @email_local_part                         = get('email_local_part')
        @email_tenure                             = get('email_tenure')
        @ip_tenure                                = get('ip_tenure')
        @issuer_id_number                         = get('issuer_id_number')
        @order_amount                             = get('order_amount')
        @phone_number                             = get('phone_number')
        @shipping_address                         = get('shipping_address')
        @shipping_address_distance_to_ip_location = get(
          'shipping_address_distance_to_ip_location'
        )
        @time_of_day                              = get('time_of_day')
      end
    end
  end
end


text:
namespace proximity_auth {

// Mock implementation of ProximityAuthClient.
class MockProximityAuthClient : public ProximityAuthClient {
 public:
  MockProximityAuthClient();

  MockProximityAuthClient(const MockProximityAuthClient&) = delete;
  MockProximityAuthClient& operator=(const MockProximityAuthClient&) = delete;

  ~MockProximityAuthClient() override;

  // ProximityAuthClient:
  MOCK_METHOD1(UpdateSmartLockState, void(ash::SmartLockState state));
  MOCK_METHOD1(FinalizeUnlock, void(bool success));
  MOCK_METHOD1(FinalizeSignin, void(const std::string& secret));
  MOCK_METHOD4(
      GetChallengeForUserAndDevice,
      void(const std::string& user_id,
           const std::string& remote_public_key,
           const std::string& channel_binding_data,
           base::OnceCallback<void(const std::string& challenge)> callback));
  MOCK_CONST_METHOD0(GetAuthenticatedUsername, std::string(void));
  MOCK_METHOD0(GetPrefManager, ProximityAuthPrefManager*(void));
};

}  // namespace proximity_auth

#endif  // ASH_COMPONENTS_PROXIMITY_AUTH_MOCK_PROXIMITY_AUTH_CLIENT_H_


text:
package com.fastaccess.cheaphlight.ui.modules.setup.presenter;

import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;

import com.fastaccess.cheaphlight.App;
import com.fastaccess.cheaphlight.R;
import com.fastaccess.cheaphlight.data.model.CountriesModel;
import com.fastaccess.cheaphlight.data.model.UserModel;
import com.fastaccess.cheaphlight.helper.FirebaseHelper;
import com.fastaccess.cheaphlight.helper.InputHelper;
import com.fastaccess.cheaphlight.helper.PrefConstance;
import com.fastaccess.cheaphlight.helper.PrefHelper;
import com.fastaccess.cheaphlight.provider.Analytics;
import com.fastaccess.cheaphlight.ui.base.mvp.presenter.BasePresenter;
import com.fastaccess.cheaphlight.ui.modules.setup.model.MyFavCountryMvp;
import com.fastaccess.cheaphlight.ui.widgets.FontAutoCompleteEditText;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import rx.functions.Action1;

import static com.fastaccess.cheaphlight.data.model.CountriesModel.getCountries;

/**
 * Created by Kosh on 29 May 2016, 1:56 AM
 */

public class MyFavCountryPresenter extends BasePresenter<MyFavCountryMvp.View> implements MyFavCountryMvp.Presenter {

    protected MyFavCountryPresenter(MyFavCountryMvp.View view) {
        super(view);
    }

    public static MyFavCountryPresenter with(MyFavCountryMvp.View view) {
        return new MyFavCountryPresenter(view);
    }

    @Override public void onSelectedCountry(ArrayList<CountriesModel> myFavList, List<CountriesModel> countries, @Nullable CountriesModel country) {
        boolean isEmpty = InputHelper.isEmpty(country);
        if (!isEmpty) {
            if (countries.contains(country) && !myFavList.contains(country)) {
                if (canAddCountry(myFavList)) {
                    getView().insertCountry(country);
                } else {
                    getView().onError(R.string.favorite_maximum_error);
                }
            } else {
                getView().onError(R.string.fav_country_selection_error);
            }
        } else {
            getView().onCountryTextError(R.string.fav_country_selection_error);
        }
    }

    @Override public void onSubmit(@NonNull List<CountriesModel> selectedCountries) {
        Analytics.logEvent();
        if (selectedCountries.isEmpty()) {
            getView().onError(R.string.fav_country_selection_error);
            return;
        }
        if (canAddCountry(selectedCountries)) {
            FirebaseUser user = getUser();
            if (user == null) {
                getView().onError(R.string.please_login);
                return;
            }
            getView().onShowProgress();
            Map<String, Object> objectMap = UserModel.getFavMyCountries(selectedCountries);
            UserModel.getReference(getFirebaseDatabase(), user)
                    .updateChildren(objectMap, this);
        } else {
            getView().onError(R.string.favorite_maximum_error);
        }
    }

    @Override public boolean canAddCountry(@NonNull List<CountriesModel> myFavs) {
        return myFavs.size() <= 5;
    }

    @Override public void onGetMyFavCountries() {
        FirebaseUser user = getUser();
        if (user != null) {
            getView().onShowProgress();
            UserModel.getReference(getFirebaseDatabase(), user).child("myFavCountries").addValueEventListener(this);
        }
    }

    @Override
    public void onFillCountries(@NonNull FontAutoCompleteEditText country, @NonNull final ArrayAdapter adapter, @NonNull final List<CountriesModel>
            countries) {
        App.getInstance().getSubscriber()
                .add(getCountries()
                        .doOnNext(new Action1<List<CountriesModel>>() {
                            @Override public void call(List<CountriesModel> models) {
                                countries.addAll(models);
                                adapter.notifyDataSetChanged();
                            }
                        }).subscribe());
    }

    @Override public void onComplete(DatabaseError databaseError, DatabaseReference databaseReference) {
        getView().onHideProgress();
        if (databaseError != null) {
            getView().onError(databaseError.getMessage());
        } else {
            getView().onSuccess();
        }
    }

    @Override public void onItemClick(int position, View v, CountriesModel item) {
        getView().onRemove(position);
    }

    @Override public void onItemLongClick(int position, View v, CountriesModel item) {
        getView().onRemove(position);
    }

    @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        CountriesModel object = (CountriesModel) parent.getAdapter().getItem(position);
        getView().onAddCountry(object);
    }

    @Override public void onDataChange(DataSnapshot dataSnapshot) {
        getView().onHideProgress();
        if (dataSnapshot == null || dataSnapshot.getValue() == null) return;
        List<CountriesModel> models = FirebaseHelper.getList(dataSnapshot.getValue().toString(), CountriesModel[].class);
        if (!models.isEmpty()) {
            PrefHelper.set(PrefConstance.MY_FAV_COUNTRIES, models);
            getView().onReceivedMyFavCountries(models);
        }
    }

    @Override public void onCancelled(DatabaseError databaseError) {
        getView().onHideProgress();
        getView().onError(databaseError.getMessage());
    }
}


text:
package com.bluesnap.androidapi.views.activities;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.*;
import com.bluesnap.androidapi.R;
import com.bluesnap.androidapi.models.CountryListObject;
import com.bluesnap.androidapi.views.adapters.CountryListAdapter;

import java.util.*;

public class CountryActivity extends Activity {

    ListView listView;
    String[] country_values_array;
    String[] country_key_array;
    EditText inputSearch;
    String localeCountry;
    CountryListAdapter adapter;
    Map<String, Integer> mapIndex;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.bluesnap_country_selector);

        final ImageButton backButton = findViewById(R.id.back_button);
        inputSearch = findViewById(R.id.searchView);
        listView = findViewById(R.id.country_list_view);
        //country_map = getHashMapResource(this.getApplicationContext(), R.xml.countries_hash_map);
        country_values_array = getResources().getStringArray(R.array.country_value_array);
        country_key_array = getResources().getStringArray(R.array.country_key_array);

        savedInstanceState = getIntent().getExtras();
        if (savedInstanceState != null) {
            String country = savedInstanceState.getString(getString(R.string.COUNTRY_STRING));
            country = country == null ? "" : country.toUpperCase();
            localeCountry = country_values_array[Arrays.asList(country_key_array).indexOf(country)];
        }

        int[] country_drawable_array = new int[country_key_array.length];
        for (int i = 0; i < country_key_array.length; i++) {
            int countryId = getResources().getIdentifier(country_key_array[i].toLowerCase(), "drawable", getPackageName());
            // int The associated resource identifier.  Returns 0 if no such resource was found.  (0 is not a valid resource ID.)
            if (countryId > 0)
                country_drawable_array[i] = countryId;
            else
                country_drawable_array[i] = R.drawable.unknown;
        }
        adapter = new CountryListAdapter(this, CountryListObject.getCountryListObject(country_values_array, country_key_array, country_drawable_array), localeCountry);
        listView.setAdapter(adapter);

        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                String countryPick = adapter.countryListObjects.get(position).getCountryInitial();
                Intent returnIntent = new Intent();
                returnIntent.putExtra("result", countryPick);
                setResult(Activity.RESULT_OK, returnIntent);
                finish();
            }
        });

        getIndexList(country_values_array);
        displayIndex();

        backButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });

        inputSearch.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence cs, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence cs, int start, int before, int count) {
                adapter.getFilter().filter(cs);
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
    }

    private void getIndexList(String[] lists) {
        mapIndex = new LinkedHashMap<>();
        for (int i = 0; i < lists.length; i++) {
            String list = lists[i];
            String index = list.substring(0, 1);

            if (mapIndex.get(index) == null)
                mapIndex.put(index, i);
        }
    }

    private void displayIndex() {
        LinearLayout indexLayout = findViewById(R.id.side_index);

        TextView textView;
        List<String> indexList = new ArrayList<>(mapIndex.keySet());
        for (String index : indexList) {
            textView = (TextView) getLayoutInflater().inflate(
                    R.layout.side_index_item, null);
            textView.setText(index);
            textView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    TextView selectedIndex = (TextView) view;
                    listView.setSelection(mapIndex.get(selectedIndex.getText().toString()));
                }
            });
            indexLayout.addView(textView);
        }
    }
}


text:
<?php

/**
 * UserLogins form base class.
 *
 * @method UserLogins getObject() Returns the current form's model object
 *
 * @package    smint
 * @subpackage form
 * @author     Wolfgang Jochum, Spectralmind GmbH
 */
abstract class BaseUserLoginsForm extends BaseFormPropel
{
  public function setup()
  {
    $this->setWidgets(array(
      'id'            => new sfWidgetFormInputHidden(),
      'smint_user_id' => new sfWidgetFormPropelChoice(array('model' => 'SmintUser', 'add_empty' => true)),
      'ip'            => new sfWidgetFormInputText(),
      'created_at'    => new sfWidgetFormDateTime(),
    ));

    $this->setValidators(array(
      'id'            => new sfValidatorChoice(array('choices' => array($this->getObject()->getId()), 'empty_value' => $this->getObject()->getId(), 'required' => false)),
      'smint_user_id' => new sfValidatorPropelChoice(array('model' => 'SmintUser', 'column' => 'id', 'required' => false)),
      'ip'            => new sfValidatorString(array('max_length' => 255, 'required' => false)),
      'created_at'    => new sfValidatorDateTime(array('required' => false)),
    ));

    $this->widgetSchema->setNameFormat('user_logins[%s]');

    $this->errorSchema = new sfValidatorErrorSchema($this->validatorSchema);

    parent::setup();
  }

  public function getModelName()
  {
    return 'UserLogins';
  }

}


text:
package io.github.benas.unixstream.components;

import io.github.benas.unixstream.UnixStream;
import org.junit.Before;
import org.junit.Test;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import static org.assertj.core.api.Assertions.assertThat;

public class UnExpandTest {

    private Stream<String> stream;

    private UnExpand unExpand;

    @Before
    public void setUp() {
        stream = Stream.of("a b", "c  d");
        unExpand = UnExpand.unexpand();
    }

    @Test
    public void apply() {
        List<String> strings = unExpand.apply(stream).collect(Collectors.toList());

        assertThat(strings).isNotEmpty().isEqualTo(Arrays.asList("a\tb", "c\t\td"));
    }

    @Test
    public void unexpand() {
        UnixStream<String> unixStream = UnixStream.unixify(stream).unexpand();

        assertThat(unixStream).isEqualTo(Arrays.asList("a\tb", "c\t\td"));
    }
}


text:
use acl::{Acl, Permission};
use byteorder::{ReadBytesExt, WriteBytesExt, BigEndian};
use consts::{KeeperState, WatchedEventType};
use data::Stat;
use std::convert::From;
use std::io::{Cursor, Read, Write, Result, Error, ErrorKind};
use watch::WatchedEvent;

/// Operation code for messages. See `RequestHeader`.
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum OpCode {
    Auth = 100,
    Create = 1,
    Delete = 2,
    Exists = 3,
    GetAcl = 6,
    SetAcl = 7,
    GetChildren = 8,
    GetData = 4,
    SetData = 5,
    Ping = 11,
    CloseSession = -11,
}

pub type ByteBuf = Cursor<Vec<u8>>;

pub trait ReadFrom: Sized {
    fn read_from<R: Read>(read: &mut R) -> Result<Self>;
}

pub trait WriteTo {
    fn write_to(&self, writer: &mut dyn Write) -> Result<()>;

    fn to_len_prefixed_buf(&self) -> Result<ByteBuf> {
        let mut buf = Cursor::new(Vec::new());
        buf.set_position(4);
        try!(self.write_to(&mut buf));
        let len = buf.position() - 4;
        buf.set_position(0);
        try!(buf.write_i32::<BigEndian>(len as i32));
        buf.set_position(0);
        Ok(buf)
    }
}

pub fn to_len_prefixed_buf<Request: WriteTo>(rh: RequestHeader, req: Request) -> Result<ByteBuf> {
    let mut buf = Cursor::new(Vec::new());
    buf.set_position(4);
    try!(rh.write_to(&mut buf));
    try!(req.write_to(&mut buf));
    let len = buf.position() - 4;
    buf.set_position(0);
    try!(buf.write_i32::<BigEndian>(len as i32));
    buf.set_position(0);
    Ok(buf)
}

fn error(msg: &str) -> Error {
    Error::new(ErrorKind::InvalidInput, msg)
}

trait StringReader: Read {
    fn read_string(&mut self) -> Result<String>;
}

pub trait BufferReader: Read {
    fn read_buffer(&mut self) -> Result<Vec<u8>>;
}

impl<R: Read> StringReader for R {
    fn read_string(&mut self) -> Result<String> {
        let raw = try!(self.read_buffer());
        Ok(String::from_utf8(raw).unwrap())
    }
}

// A buffer is an u8 string prefixed with it's length as i32
impl<R: Read> BufferReader for R {
    fn read_buffer(&mut self) -> Result<Vec<u8>> {
        let len = try!(self.read_i32::<BigEndian>());
        let len = if len < 0 {
            0
        } else {
            len as usize
        };
        let mut buf = vec![0; len];
        let read = try!(self.read(&mut buf));
        if read == len {
            Ok(buf)
        } else {
            Err(error("read_buffer failed"))
        }
    }
}

impl WriteTo for u8 {
    fn write_to(&self, writer: &mut dyn Write) -> Result<()> {
        try!(writer.write_u8(*self));
        Ok(())
    }
}

impl WriteTo for String {
    fn write_to(&self, writer: &mut dyn Write) -> Result<()> {
        try!(writer.write_i32::<BigEndian>(self.len() as i32));
        writer.write_all(self.as_ref())
    }
}

impl<T: WriteTo> WriteTo for Vec<T> {
    fn write_to(&self, writer: &mut dyn Write) -> Result<()> {
        try!(writer.write_i32::<BigEndian>(self.len() as i32));
        let mut res = Ok(());
        for elem in self.iter() {
            res = elem.write_to(writer);
            if res.is_err() {
                return res;
            }
        }
        res
    }
}

impl ReadFrom for Acl {
    fn read_from<R: Read>(read: &mut R) -> Result<Acl> {
        Ok(Acl {
            perms: Permission::from_raw(read.read_u32::<BigEndian>()?),
            scheme: read.read_string()?,
            id: read.read_string()?,
        })
    }
}

impl WriteTo for Acl {
    fn write_to(&self, writer: &mut dyn Write) -> Result<()> {
        writer.write_u32::<BigEndian>(self.perms.code())?;
        self.scheme.write_to(writer)?;
        self.id.write_to(writer)
    }
}

impl ReadFrom for Stat {
    fn read_from<R: Read>(read: &mut R) -> Result<Stat> {
        Ok(Stat {
            czxid: try!(read.read_i64::<BigEndian>()),
            mzxid: try!(read.read_i64::<BigEndian>()),
            ctime: try!(read.read_i64::<BigEndian>()),
            mtime: try!(read.read_i64::<BigEndian>()),
            version: try!(read.read_i32::<BigEndian>()),
            cversion: try!(read.read_i32::<BigEndian>()),
            aversion: try!(read.read_i32::<BigEndian>()),
            ephemeral_owner: try!(read.read_i64::<BigEndian>()),
            data_length: try!(read.read_i32::<BigEndian>()),
            num_children: try!(read.read_i32::<BigEndian>()),
            pzxid: try!(read.read_i64::<BigEndian>()),
        })
    }
}

pub struct ConnectRequest {
    protocol_version: i32,
    last_zxid_seen: i64,
    timeout: i32,
    session_id: i64,
    passwd: Vec<u8>,
    read_only: bool,
}

impl ConnectRequest {
    pub fn from(conn_resp: &ConnectResponse, last_zxid_seen: i64) -> ConnectRequest {
        ConnectRequest {
            protocol_version: conn_resp.protocol_version,
            last_zxid_seen: last_zxid_seen,
            timeout: conn_resp.timeout as i32,
            session_id: conn_resp.session_id,
            passwd: conn_resp.passwd.clone(),
            read_only: conn_resp.read_only,
        }
    }
}

impl WriteTo for ConnectRequest {
    fn write_to(&self, writer: &mut dyn Write) -> Result<()> {
        try!(writer.write_i32::<BigEndian>(self.protocol_version));
        try!(writer.write_i64::<BigEndian>(self.last_zxid_seen));
        try!(writer.write_i32::<BigEndian>(self.timeout));
        try!(writer.write_i64::<BigEndian>(self.session_id));
        try!(self.passwd.write_to(writer));
        try!(writer.write_u8(self.read_only as u8));
        Ok(())
    }
}

#[derive(Debug)]
pub struct ConnectResponse {
    protocol_version: i32,
    pub timeout: u64, // is handled as i32
    pub session_id: i64,
    passwd: Vec<u8>,
    pub read_only: bool,
}

impl ConnectResponse {
    pub fn initial(timeout: u64) -> ConnectResponse {
        ConnectResponse {
            protocol_version: 0,
            timeout: timeout,
            session_id: 0,
            passwd: vec![0;16],
            read_only: false,
        }
    }
}

impl ReadFrom for ConnectResponse {
    fn read_from<R: Read>(reader: &mut R) -> Result<ConnectResponse> {
        Ok(ConnectResponse {
            protocol_version: try!(reader.read_i32::<BigEndian>()),
            timeout: try!(reader.read_i32::<BigEndian>()) as u64,
            session_id: try!(reader.read_i64::<BigEndian>()),
            passwd: try!(reader.read_buffer()),
            // Old zookeeper server doesn't have the "readonly" field, see also
            //
            //  https://github.com/apache/zookeeper/blob/master/zookeeper-server/src/main/java/org/apache/zookeeper/ClientCnxnSocket.java#L143-L154
            read_only: reader.read_u8().map_or(false, |v| v != 0),
        })
    }
}

pub struct RequestHeader {
    pub xid: i32,
    pub opcode: OpCode,
}

impl WriteTo for RequestHeader {
    fn write_to(&self, writer: &mut dyn Write) -> Result<()> {
        try!(writer.write_i32::<BigEndian>(self.xid));
        try!(writer.write_i32::<BigEndian>(self.opcode as i32));
        Ok(())
    }
}

#[derive(Debug)]
pub struct ReplyHeader {
    pub xid: i32,
    pub zxid: i64,
    pub err: i32,
}

impl ReadFrom for ReplyHeader {
    fn read_from<R: Read>(read: &mut R) -> Result<ReplyHeader> {
        Ok(ReplyHeader {
            xid: try!(read.read_i32::<BigEndian>()),
            zxid: try!(read.read_i64::<BigEndian>()),
            err: try!(read.read_i32::<BigEndian>()),
        })
    }
}

pub struct CreateRequest {
    pub path: String,
    pub data: Vec<u8>,
    pub acl: Vec<Acl>,
    pub flags: i32,
}

impl WriteTo for CreateRequest {
    fn write_to(&self, writer: &mut dyn Write) -> Result<()> {
        try!(self.path.write_to(writer));
        try!(self.data.write_to(writer));
        try!(self.acl.write_to(writer));
        try!(writer.write_i32::<BigEndian>(self.flags));
        Ok(())
    }
}

pub struct CreateResponse {
    pub path: String,
}

impl ReadFrom for CreateResponse {
    fn read_from<R: Read>(reader: &mut R) -> Result<CreateResponse> {
        Ok(CreateResponse { path: try!(reader.read_string()) })
    }
}

pub struct DeleteRequest {
    pub path: String,
    pub version: i32,
}

impl WriteTo for DeleteRequest {
    fn write_to(&self, writer: &mut dyn Write) -> Result<()> {
        try!(self.path.write_to(writer));
        try!(writer.write_i32::<BigEndian>(self.version));
        Ok(())
    }
}

pub struct StringAndBoolRequest {
    pub path: String,
    pub watch: bool,
}

impl WriteTo for StringAndBoolRequest {
    fn write_to(&self, writer: &mut dyn Write) -> Result<()> {
        try!(self.path.write_to(writer));
        try!(writer.write_u8(self.watch as u8));
        Ok(())
    }
}

pub type ExistsRequest = StringAndBoolRequest;
pub type ExistsResponse = StatResponse;

pub struct StatResponse {
    pub stat: Stat,
}

impl ReadFrom for StatResponse {
    fn read_from<R: Read>(read: &mut R) -> Result<StatResponse> {
        Ok(StatResponse { stat: try!(Stat::read_from(read)) })
    }
}

pub struct GetAclRequest {
    pub path: String,
}

impl WriteTo for GetAclRequest {
    fn write_to(&self, writer: &mut dyn Write) -> Result<()> {
        self.path.write_to(writer)
    }
}

pub struct GetAclResponse {
    pub acl_stat: (Vec<Acl>, Stat),
}

impl ReadFrom for GetAclResponse {
    fn read_from<R: Read>(reader: &mut R) -> Result<GetAclResponse> {
        let len = try!(reader.read_i32::<BigEndian>());
        let mut acl = Vec::with_capacity(len as usize);
        for _ in 0..len {
            acl.push(try!(Acl::read_from(reader)));
        }
        let stat = try!(Stat::read_from(reader));
        Ok(GetAclResponse { acl_stat: (acl, stat) })
    }
}

pub struct SetAclRequest {
    pub path: String,
    pub acl: Vec<Acl>,
    pub version: i32,
}

impl WriteTo for SetAclRequest {
    fn write_to(&self, writer: &mut dyn Write) -> Result<()> {
        try!(self.path.write_to(writer));
        try!(self.acl.write_to(writer));
        try!(writer.write_i32::<BigEndian>(self.version));
        Ok(())
    }
}

pub type SetAclResponse = StatResponse;

pub struct SetDataRequest {
    pub path: String,
    pub data: Vec<u8>,
    pub version: i32,
}

impl WriteTo for SetDataRequest {
    fn write_to(&self, writer: &mut dyn Write) -> Result<()> {
        try!(self.path.write_to(writer));
        try!(self.data.write_to(writer));
        try!(writer.write_i32::<BigEndian>(self.version));
        Ok(())
    }
}

pub type SetDataResponse = StatResponse;

pub type GetChildrenRequest = StringAndBoolRequest;

pub struct GetChildrenResponse {
    pub children: Vec<String>,
}

impl ReadFrom for GetChildrenResponse {
    fn read_from<R: Read>(reader: &mut R) -> Result<GetChildrenResponse> {
        let len = try!(reader.read_i32::<BigEndian>());
        let mut children = Vec::with_capacity(len as usize);
        for _ in 0..len {
            children.push(try!(reader.read_string()));
        }
        Ok(GetChildrenResponse { children: children })
    }
}

pub type GetDataRequest = StringAndBoolRequest;

pub struct GetDataResponse {
    pub data_stat: (Vec<u8>, Stat),
}

impl ReadFrom for GetDataResponse {
    fn read_from<R: Read>(reader: &mut R) -> Result<GetDataResponse> {
        let data = try!(reader.read_buffer());
        let stat = try!(Stat::read_from(reader));
        Ok(GetDataResponse { data_stat: (data, stat) })
    }
}

pub struct AuthRequest {
    pub typ: i32,
    pub scheme: String,
    pub auth: Vec<u8>,
}

impl WriteTo for AuthRequest {
    fn write_to(&self, writer: &mut dyn Write) -> Result<()> {
        try!(writer.write_i32::<BigEndian>(self.typ));
        try!(self.scheme.write_to(writer));
        self.auth.write_to(writer)
    }
}

pub struct EmptyRequest;
pub struct EmptyResponse;

impl WriteTo for EmptyRequest {
    fn write_to(&self, _: &mut dyn Write) -> Result<()> {
        Ok(())
    }
}

impl ReadFrom for EmptyResponse {
    fn read_from<R: Read>(_: &mut R) -> Result<EmptyResponse> {
        Ok(EmptyResponse)
    }
}

impl ReadFrom for WatchedEvent {
    fn read_from<R: Read>(reader: &mut R) -> Result<WatchedEvent> {
        let type_raw = try!(reader.read_i32::<BigEndian>());
        let state_raw = try!(reader.read_i32::<BigEndian>());
        let path = try!(reader.read_string());
        let event_type = WatchedEventType::from(type_raw);
        let state = KeeperState::from(state_raw);
        Ok(WatchedEvent {
            event_type: event_type,
            keeper_state: state,
            path: Some(path),
        })
    }
}


text:
module DocumentHelpers
  def create_document(type, fields, save: true, publish: false)
    visit send(:"new_#{type}_path")
    fill_in_fields(fields)

    if save
      save_document
    end

    if save && publish
      publish_document
    end
  end

  def save_document
    click_on "Save as draft"
  end

  def publish_document
    click_on "Publish"
  end

  def generate_preview
    click_button("Preview")
  end

  def check_document_does_not_exist_with(attributes)
    refute SpecialistDocumentEdition.exists?(conditions: attributes)
  end

  def check_for_unchanged_slug(title, expected_slug)
    go_to_show_page_for_cma_case(title)

    expected_link = "#{Plek.current.website_root}/#{expected_slug}"
    expect(page).to have_link("View on website", href: expected_link)
  end

  def check_document_published_to_publishing_api(slug, fields, draft: false)
    attributes = {
      title: fields[:title],
      description: fields[:summary],
      format: "specialist_document",
      publishing_app: "specialist-publisher",
      rendering_app: "specialist-frontend",
    }
    if draft
      assert_publishing_api_put_draft_item("/#{slug}", attributes)
    else
      assert_publishing_api_put_item("/#{slug}", attributes)
    end
  end

  def check_added_to_rummager(slug, fields)
    document_type_slug_prefix_map = {
      "cma-cases" => "cma_case",
      "aaib-reports" => "aaib_report",
      "asylum-support-tribunal-decisions" => "asylum_support_decision",
      "international-development-funding" => "international_development_fund",
      "drug-safety-update" => "drug_safety_update",
      "drug-device-alerts" => "medical_safety_alert",
      "employment-appeal-tribunal-decisions" => "employment_appeal_tribunal_decision",
      "employment-tribunal-decisions" => "employment_tribunal_decision",
      "european-structural-investment-funds" => "european_structural_investment_fund",
      "maib-reports" => "maib_report",
      "raib-reports" => "raib_report",
      "countryside-stewardship-grants" => "countryside_stewardship_grant",
      "tax-and-chancery-tribunal-decisions" => "tax_tribunal_decision",
      "administrative-appeals-tribunal-decisions" => "utaac_decision",
      "vehicle-recalls-faults" => "vehicle_recalls_and_faults_alert",
    }

    slug_prefix = slug.split("/").first
    document_type = document_type_slug_prefix_map.fetch(slug_prefix)

    rummager_fields = fields
      .except(:summary)
      .merge(
        description: fields.fetch(:summary),
      )

    expect(fake_rummager).to have_received(:add_document)
      .with(document_type, "/#{slug}", hash_including(rummager_fields))
  end

  def check_for_correctly_archived_editions(document_attrs)
    latest_edition = SpecialistDocumentEdition.where(document_attrs).first
    editions = SpecialistDocumentEdition.where(document_id: latest_edition.document_id)
    previous_editions = editions.to_a - latest_edition.to_a

    expect(latest_edition).to be_published

    previous_editions.each do |edition|
      expect(edition).to be_archived
    end
  end

  def check_document_is_withdrawn(slug, document_title)
    assert_publishing_api_put_item("/#{slug}", format: "gone")

    expect(page).to have_content("withdrawn")
    expect(RenderedSpecialistDocument.where(title: document_title)).to be_empty
  end

  def check_for_documents(*titles)
    titles.each do |title|
      expect(page).to have_content(title)
    end
  end

  def check_for_missing_title_error
    expect(page).to have_content("Title can't be blank")
  end

  def check_for_missing_summary_error
    expect(page).to have_content("Summary can't be blank")
  end

  def check_for_invalid_date_error(date_field)
    expect(page).to have_content("#{date_field} should be formatted YYYY-MM-DD")
  end

  def check_content_preview_link(slug)
    preview_url = "#{Plek.current.find("draft-origin")}/#{slug}"
    expect(page).to have_link("Preview draft", href: preview_url)
  end

  def check_live_link(slug)
    live_url = "#{Plek.current.website_root}/#{slug}"
    expect(page).to have_link("View on website", href: live_url)
  end

  def check_document_is_published(slug, fields)
    check_document_published_to_publishing_api(slug, fields)
    check_added_to_rummager(
      slug,
      fields.except(:body),
    )
  end

  def check_email_alert_api_notified_of_publish
    expect(fake_email_alert_api).to have_received(:send_alert)
      .with(
        hash_including(
          "subject",
          "body",
          "tags",
        )
      )
    reset_email_alert_api_stubs_and_messages
  end

  def check_email_alert_api_is_not_notified_of_publish
    expect(fake_email_alert_api).to_not have_received(:send_alert)
  end

  def check_document_was_republished(slug, fields)
    check_added_to_rummager(
      slug,
      fields.except(:body),
    )
  end

  def check_document_exists_with(type, attributes)
    send(:"go_to_show_page_for_#{type}", attributes.fetch(:title))

    attributes.except(:body).each do |_, value|
      expect(page).to have_content(Array(value).join(" "))
    end
  end

  def edit_document(title, updated_fields, minor_update: false, publish: false)
    fill_in_fields(updated_fields)

    check "Minor update" if minor_update && page.has_field?("Minor update")

    save_document

    if publish
      publish_document
    end
  end

  def go_to_show_page_for_document(type, title)
    raise "Cannot find #{type.to_s.humanize} nil title" if title.nil?
    send(:"go_to_#{type}_index")
    click_link title
  end

  def visit_path_if_elsewhere(path)
    unless current_path == path
      visit(path)
    end
  end

  def check_for_new_document_title(type, title)
    visit send(:"#{type.to_s.pluralize}_path")
    expect(page).to have_content(title)
  end

  def go_to_edit_page_for_document(type, title)
    go_to_show_page_for_document(type, title)

    click_on "Edit"
  end

  def withdraw_document(type, title)
    send(:"go_to_show_page_for_#{type}", title)
    click_button "Withdraw"
  end

  def check_for_javascript_usage_error(field)
    expect(page).to have_content("#{field} cannot include invalid Govspeak, invalid HTML, any JavaScript or images hosted on sites except for")
  end

  def check_for_slug_clash_warning
    expect(page).to have_content("You can't publish it until you change the title.")
  end

  def check_count_of_logs(expected_count_of_logs)
    count_of_logs = PublicationLog.where(slug: @slug).count
    expect(count_of_logs).to eq(expected_count_of_logs.to_i)
  end

  def check_document_cant_be_published
    expect(page).to_not have_selector(:button, "Publish")
  end

  def document_body
    %{

      ## Header

      Praesent commodo cursus magna, vel scelerisque nisl consectetur et.

      ### Level 2

      Praesent commodo cursus magna, vel scelerisque nisl consectetur et.
    }
  end
end
RSpec.configuration.include DocumentHelpers, type: :feature


text:
package org.efaps.eql;

import org.efaps.eql.eQL.QueryPart;
import org.efaps.eql.eQL.SelectPart;
import org.efaps.eql.eQL.Statement;
import org.testng.Assert;
import org.testng.annotations.Test;

/**
 * TODO comment!
 *
 * @author The eFaps Team
 * @version $Id: $
 */
public class QuerySelectTest extends AbstractTest
{

    @Test()
    public void oneTypeOneAttribute()
    {
        final Statement stmt = getStatement("query type Sales_Invoice select attribute[Name]");
        final QueryPart query = stmt.getQueryPart();
        final SelectPart select = query.getSelectPart();
        Assert.assertEquals(query.getTypes().get(0), "Sales_Invoice");
        Assert.assertEquals(select.getSelects().get(0).getSelect(), "attribute[Name]");
    }

    @Test
    public void printOneTypeOneAttribute()
    {
        final Statement stmt = getStatement("print query type Sales_Invoice select attribute[Name]");
        final QueryPart query = stmt.getQueryPart();
        final SelectPart select = query.getSelectPart();
        Assert.assertEquals(query.getTypes().get(0), "Sales_Invoice");
        Assert.assertEquals(select.getSelects().get(0).getSelect(), "attribute[Name]");
    }

    @Test
    public void twoTypesWithTwoeSelect()
    {
        final Statement stmt = getStatement("query type Sales_Invoice, Contacts_Contact select attribute[Name], linkto[DocLink].instance");
        final QueryPart query = stmt.getQueryPart();
        final SelectPart select = query.getSelectPart();
        Assert.assertEquals(query.getTypes().get(0), "Sales_Invoice");
        Assert.assertEquals(query.getTypes().get(1), "Contacts_Contact");
        Assert.assertEquals(select.getSelects().get(0).getSelect(), "attribute[Name]");
        Assert.assertEquals(select.getSelects().get(1).getSelect(), "linkto[DocLink].instance");
    }

    @Test
    public void oneTypeOneAttributeWithAlias()
    {
        final Statement stmt = getStatement("query type Sales_Invoice select attribute[Name] as Name");
        final QueryPart query = stmt.getQueryPart();
        final SelectPart select = query.getSelectPart();
        Assert.assertEquals(query.getTypes().get(0), "Sales_Invoice");
        Assert.assertEquals(select.getSelects().get(0).getSelect(), "attribute[Name]");
        Assert.assertEquals(select.getSelects().get(0).getAlias(), "Name");
    }

    @Test
    public void oneTypeTwoAttributeWithAlias()
    {
        final Statement stmt = getStatement("query type Sales_Invoice select attribute[Name] as Name, linkto[DocumentLink].instance as instance");
        final QueryPart query = stmt.getQueryPart();
        final SelectPart select = query.getSelectPart();
        Assert.assertEquals(query.getTypes().get(0), "Sales_Invoice");
        Assert.assertEquals(select.getSelects().get(0).getSelect(), "attribute[Name]");
        Assert.assertEquals(select.getSelects().get(0).getAlias(), "Name");
        Assert.assertEquals(select.getSelects().get(1).getSelect(), "linkto[DocumentLink].instance");
        Assert.assertEquals(select.getSelects().get(1).getAlias(), "instance");
    }

    @Test(description = "query with a limit")
    public void limit()
    {
        final Statement stmt = getStatement("query type Sales_Invoice, Contacts_Contact, HumanResource_Employee limit 10 select attribute[Name] as Name, linkto[DocumentLink].instance as instance");
        final QueryPart query = stmt.getQueryPart();
        final SelectPart select = query.getSelectPart();
        Assert.assertEquals(query.getTypes().get(0), "Sales_Invoice");
        Assert.assertEquals(query.getTypes().get(1), "Contacts_Contact");
        Assert.assertEquals(query.getTypes().get(2), "HumanResource_Employee");
        Assert.assertEquals(query.getLimitPart().getValue(), "10");
        Assert.assertEquals(select.getSelects().get(0).getSelect(), "attribute[Name]");
        Assert.assertEquals(select.getSelects().get(0).getAlias(), "Name");
        Assert.assertEquals(select.getSelects().get(1).getSelect(), "linkto[DocumentLink].instance");
        Assert.assertEquals(select.getSelects().get(1).getAlias(), "instance");
    }

}


text:
// Copyright 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

package org.chromium.content.browser;

import android.content.Context;

import org.chromium.base.CalledByNative;
import org.chromium.base.JNINamespace;
import org.chromium.ui.base.WindowAndroid.FileAccessCallback;

/**
 * Java counterpart of android DownloadController.
 *
 * Its a singleton class instantiated by the C++ DownloadController.
 */
@JNINamespace("content")
public class DownloadController {
    private static final String LOGTAG = "DownloadController";
    private static final DownloadController sInstance = new DownloadController();

    /**
     * Class for notifying the application that download has completed.
     */
    public interface DownloadNotificationService {
        /**
         * Notify the host application that a download is finished.
         * @param downloadInfo Information about the completed download.
         */
        void onDownloadCompleted(final DownloadInfo downloadInfo);

        /**
         * Notify the host application that a download is in progress.
         * @param downloadInfo Information about the in-progress download.
         */
        void onDownloadUpdated(final DownloadInfo downloadInfo);
    }

    private static DownloadNotificationService sDownloadNotificationService;

    @CalledByNative
    public static DownloadController getInstance() {
        return sInstance;
    }

    private DownloadController() {
        nativeInit();
    }

    private static ContentViewDownloadDelegate downloadDelegateFromView(ContentViewCore view) {
        return view.getDownloadDelegate();
    }

    public static void setDownloadNotificationService(DownloadNotificationService service) {
        sDownloadNotificationService = service;
    }

    /**
     * Notifies the download delegate of a new GET download and passes all the information
     * needed to download the file.
     *
     * The download delegate is expected to handle the download.
     */
    @CalledByNative
    public void newHttpGetDownload(ContentViewCore view, String url,
            String userAgent, String contentDisposition, String mimeType,
            String cookie, String referer, boolean hasUserGesture,
            String filename, long contentLength) {
        ContentViewDownloadDelegate downloadDelegate = downloadDelegateFromView(view);

        if (downloadDelegate != null) {
            DownloadInfo downloadInfo = new DownloadInfo.Builder()
                    .setUrl(url)
                    .setUserAgent(userAgent)
                    .setContentDisposition(contentDisposition)
                    .setMimeType(mimeType)
                    .setCookie(cookie)
                    .setReferer(referer)
                    .setHasUserGesture(hasUserGesture)
                    .setFileName(filename)
                    .setContentLength(contentLength)
                    .setIsGETRequest(true)
                    .build();
            downloadDelegate.requestHttpGetDownload(downloadInfo);
        }
    }

    /**
     * Notifies the download delegate that a new download has started. This can
     * be either a POST download or a GET download with authentication.
     * @param view ContentViewCore associated with the download item.
     * @param filename File name of the downloaded file.
     * @param mimeType Mime of the downloaded item.
     */
    @CalledByNative
    public void onDownloadStarted(ContentViewCore view, String filename, String mimeType) {
        ContentViewDownloadDelegate downloadDelegate = downloadDelegateFromView(view);

        if (downloadDelegate != null) {
            downloadDelegate.onDownloadStarted(filename, mimeType);
        }
    }

    /**
     * Notifies the download delegate that a download completed and passes along info about the
     * download. This can be either a POST download or a GET download with authentication.
     */
    @CalledByNative
    public void onDownloadCompleted(Context context, String url, String mimeType,
            String filename, String path, long contentLength, boolean successful, int downloadId) {
        if (sDownloadNotificationService != null) {
            DownloadInfo downloadInfo = new DownloadInfo.Builder()
                    .setUrl(url)
                    .setMimeType(mimeType)
                    .setFileName(filename)
                    .setFilePath(path)
                    .setContentLength(contentLength)
                    .setIsSuccessful(successful)
                    .setDescription(filename)
                    .setDownloadId(downloadId)
                    .setHasDownloadId(true)
                    .build();
            sDownloadNotificationService.onDownloadCompleted(downloadInfo);
        }
    }

    /**
     * Notifies the download delegate about progress of a download. Downloads that use Chrome
     * network stack use custom notification to display the progress of downloads.
     */
    @CalledByNative
    public void onDownloadUpdated(Context context, String url, String mimeType,
            String filename, String path, long contentLength, boolean successful, int downloadId,
            int percentCompleted, long timeRemainingInMs) {
        if (sDownloadNotificationService != null) {
            DownloadInfo downloadInfo = new DownloadInfo.Builder()
                    .setUrl(url)
                    .setMimeType(mimeType)
                    .setFileName(filename)
                    .setFilePath(path)
                    .setContentLength(contentLength)
                    .setIsSuccessful(successful)
                    .setDescription(filename)
                    .setDownloadId(downloadId)
                    .setHasDownloadId(true)
                    .setPercentCompleted(percentCompleted)
                    .setTimeRemainingInMillis(timeRemainingInMs)
                    .build();
            sDownloadNotificationService.onDownloadUpdated(downloadInfo);
        }
    }

    /**
     * Notifies the download delegate that a dangerous download started.
     */
    @CalledByNative
    public void onDangerousDownload(ContentViewCore view, String filename,
            int downloadId) {
        ContentViewDownloadDelegate downloadDelegate = downloadDelegateFromView(view);
        if (downloadDelegate != null) {
            downloadDelegate.onDangerousDownload(filename, downloadId);
        }
    }

    /**
     * Returns whether file access is allowed.
     *
     * @param view The ContentViewCore to access file system.
     * @return true if allowed, or false otherwise.
     */
    @CalledByNative
    private boolean hasFileAccess(ContentViewCore view) {
        return view.getWindowAndroid().hasFileAccess();
    }

    /**
     * Called to prompt user with the file access permission.
     *
     * @param view The ContentViewCore to access file system.
     * @param callbackId The native callback function pointer.
     */
    @CalledByNative
    private void requestFileAccess(ContentViewCore view, final long callbackId) {
        FileAccessCallback callback = new FileAccessCallback() {
            @Override
            public void onFileAccessResult(boolean granted) {
                nativeOnRequestFileAccessResult(callbackId, granted);
            }
        };
        view.getWindowAndroid().requestFileAccess(callback);
    }

    // native methods
    private native void nativeInit();
    private native void nativeOnRequestFileAccessResult(long callbackId, boolean granted);
}


text:
function formTest() {
    let formOptions: qq.FormOptions = {
        element: "qq-form",
        autoUpload: true,
        interceptSubmit: true
    };

    let config: qq.BasicOptions = {
        form: formOptions
    };

    let uploader = new qq.FineUploaderBasic(config);
}


text:
/**
  * This header file contains definition for global types
  */
#ifndef _LBS_TYPES_H_
#define _LBS_TYPES_H_

#include "type.h"
#include "wireless.h"
#include "common.h"
#ifdef IAR_CC
#pragma pack(1)
#endif

struct ieee_ie_header {
	u8 id;
	u8 len;
} __attribute__ ((packed));

struct ieee_ie_cf_param_set {
	struct ieee_ie_header header;

	u8 cfpcnt;
	u8 cfpperiod;
	__le16 cfpmaxduration;
	__le16 cfpdurationremaining;
} __attribute__((packed));

struct ieee_ie_ibss_param_set {
	struct ieee_ie_header header;

	__le16 atimwindow;
} __attribute__((packed));

union ieee_ss_param_set {
	struct ieee_ie_cf_param_set cf;
	struct ieee_ie_ibss_param_set ibss;
} __attribute__((packed));

struct ieee_ie_fh_param_set {
	struct ieee_ie_header header;

	__le16 dwelltime;
	u8 hopset;
	u8 hoppattern;
	u8 hopindex;
} __attribute__((packed));

struct ieee_ie_ds_param_set {
	struct ieee_ie_header header;

	u8 channel;
} __attribute__((packed));

union ieee_phy_param_set {
	struct ieee_ie_fh_param_set fh;
	struct ieee_ie_ds_param_set ds;
} __attribute__((packed));

/** TLV  type ID definition */
#define PROPRIETARY_TLV_BASE_ID		0x0100

/* Terminating TLV type */
#define MRVL_TERMINATE_TLV_ID		0xffff

#define TLV_TYPE_SSID				0x0000
#define TLV_TYPE_RATES				0x0001
#define TLV_TYPE_PHY_FH				0x0002
#define TLV_TYPE_PHY_DS				0x0003
#define TLV_TYPE_CF				    0x0004
#define TLV_TYPE_IBSS				0x0006

#define TLV_TYPE_DOMAIN				0x0007

#define TLV_TYPE_POWER_CAPABILITY	0x0021

#define TLV_TYPE_KEY_MATERIAL       (PROPRIETARY_TLV_BASE_ID + 0)
#define TLV_TYPE_CHANLIST           (PROPRIETARY_TLV_BASE_ID + 1)
#define TLV_TYPE_NUMPROBES          (PROPRIETARY_TLV_BASE_ID + 2)
#define TLV_TYPE_RSSI_LOW           (PROPRIETARY_TLV_BASE_ID + 4)
#define TLV_TYPE_SNR_LOW            (PROPRIETARY_TLV_BASE_ID + 5)
#define TLV_TYPE_FAILCOUNT          (PROPRIETARY_TLV_BASE_ID + 6)
#define TLV_TYPE_BCNMISS            (PROPRIETARY_TLV_BASE_ID + 7)
#define TLV_TYPE_LED_GPIO           (PROPRIETARY_TLV_BASE_ID + 8)
#define TLV_TYPE_LEDBEHAVIOR        (PROPRIETARY_TLV_BASE_ID + 9)
#define TLV_TYPE_PASSTHROUGH        (PROPRIETARY_TLV_BASE_ID + 10)
#define TLV_TYPE_REASSOCAP          (PROPRIETARY_TLV_BASE_ID + 11)
#define TLV_TYPE_POWER_TBL_2_4GHZ   (PROPRIETARY_TLV_BASE_ID + 12)
#define TLV_TYPE_POWER_TBL_5GHZ     (PROPRIETARY_TLV_BASE_ID + 13)
#define TLV_TYPE_BCASTPROBE	    (PROPRIETARY_TLV_BASE_ID + 14)
#define TLV_TYPE_NUMSSID_PROBE	    (PROPRIETARY_TLV_BASE_ID + 15)
#define TLV_TYPE_WMMQSTATUS   	    (PROPRIETARY_TLV_BASE_ID + 16)
#define TLV_TYPE_CRYPTO_DATA	    (PROPRIETARY_TLV_BASE_ID + 17)
#define TLV_TYPE_WILDCARDSSID	    (PROPRIETARY_TLV_BASE_ID + 18)
#define TLV_TYPE_TSFTIMESTAMP	    (PROPRIETARY_TLV_BASE_ID + 19)
#define TLV_TYPE_RSSI_HIGH          (PROPRIETARY_TLV_BASE_ID + 22)
#define TLV_TYPE_SNR_HIGH           (PROPRIETARY_TLV_BASE_ID + 23)
#define TLV_TYPE_AUTH_TYPE          (PROPRIETARY_TLV_BASE_ID + 31)
#define TLV_TYPE_MESH_ID            (PROPRIETARY_TLV_BASE_ID + 37)
#define TLV_TYPE_OLD_MESH_ID        (PROPRIETARY_TLV_BASE_ID + 291)

/** TLV related data structures*/
struct mrvl_ie_header {
	__le16 type;
	__le16 len;
} __attribute__((packed));

struct mrvl_ie_data {
	struct mrvl_ie_header header;
	u8 Data[1];
} __attribute__((packed));

struct mrvl_ie_rates_param_set {
	struct mrvl_ie_header header;
	u8 rates[1];
} __attribute__((packed));

struct mrvl_ie_ssid_param_set {
	struct mrvl_ie_header header;
	u8 ssid[1];
} __attribute__((packed));

struct mrvl_ie_wildcard_ssid_param_set {
	struct mrvl_ie_header header;
	u8 MaxSsidlength;
	u8 ssid[1];
} __attribute__((packed));

struct chanscanmode {
#ifdef __BIG_ENDIAN_BITFIELD
	u8 reserved_2_7:6;
	u8 disablechanfilt:1;
	u8 passivescan:1;
#else
	u8 passivescan:1;
	u8 disablechanfilt:1;
	u8 reserved_2_7:6;
#endif
} __attribute__((packed));

struct chanscanparamset {
	u8 radiotype;
	u8 channumber;
	struct chanscanmode chanscanmode;
	__le16 minscantime;
	__le16 maxscantime;
} __attribute__((packed));

struct mrvl_ie_chanlist_param_set {
	struct mrvl_ie_header header;
	struct chanscanparamset chanscanparam[1];
} __attribute__((packed));

struct mrvl_ie_cf_param_set {
	struct mrvl_ie_header header;
	u8 cfpcnt;
	u8 cfpperiod;
	__le16 cfpmaxduration;
	__le16 cfpdurationremaining;
} __attribute__((packed));

struct mrvl_ie_ds_param_set {
	struct mrvl_ie_header header;
	u8 channel;
} __attribute__((packed));

struct mrvl_ie_rsn_param_set {
	struct mrvl_ie_header header;
	u8 rsnie[1];
} __attribute__((packed));

struct mrvl_ie_tsf_timestamp {
	struct mrvl_ie_header header;
	__le64 tsftable[1];
} __attribute__((packed));

/* v9 and later firmware only */
struct mrvl_ie_auth_type {
	struct mrvl_ie_header header;
	__le16 auth;
} __attribute__((packed));

/**  Local Power capability */
struct mrvl_ie_power_capability {
	struct mrvl_ie_header header;
	s8 minpower;
	s8 maxpower;
} __attribute__((packed));

/* used in CMD_802_11_SUBSCRIBE_EVENT for SNR, RSSI and Failure */
struct mrvl_ie_thresholds {
	struct mrvl_ie_header header;
	u8 value;
	u8 freq;
} __attribute__((packed));

struct mrvl_ie_beacons_missed {
	struct mrvl_ie_header header;
	u8 beaconmissed;
	u8 reserved;
} __attribute__((packed));

struct mrvl_ie_num_probes {
	struct mrvl_ie_header header;
	__le16 numprobes;
} __attribute__((packed));

struct mrvl_ie_bcast_probe {
	struct mrvl_ie_header header;
	__le16 bcastprobe;
} __attribute__((packed));

struct mrvl_ie_num_ssid_probe {
	struct mrvl_ie_header header;
	__le16 numssidprobe;
} __attribute__((packed));

struct led_pin {
	u8 led;
	u8 pin;
} __attribute__((packed));

struct mrvl_ie_ledgpio {
	struct mrvl_ie_header header;
	struct led_pin ledpin[1];
} __attribute__((packed));

struct led_bhv {
	uint8_t	firmwarestate;
	uint8_t	led;
	uint8_t	ledstate;
	uint8_t	ledarg;
} __attribute__((packed));

struct mrvl_ie_ledbhv {
	struct mrvl_ie_header header;
	struct led_bhv ledbhv[1];
} __attribute__((packed));

/* Meant to be packed as the value member of a struct ieee80211_info_element.
 * Note that the len member of the ieee80211_info_element varies depending on
 * the mesh_id_len */
struct mrvl_meshie_val {
	uint8_t oui[3];
	uint8_t type;
	uint8_t subtype;
	uint8_t version;
	uint8_t active_protocol_id;
	uint8_t active_metric_id;
	uint8_t mesh_capability;
	uint8_t mesh_id_len;
	uint8_t mesh_id[IW_ESSID_MAX_SIZE];
} __attribute__((packed));

struct mrvl_meshie {
	u8 id, len;
	struct mrvl_meshie_val val;
} __attribute__((packed));

struct mrvl_mesh_defaults {
	__le32 bootflag;
	uint8_t boottime;
	uint8_t reserved;
	__le16 channel;
	struct mrvl_meshie meshie;
} __attribute__((packed));

#ifdef IAR_CC
#pragma pack()
#endif
#endif


text:
if [ "$6" == "true" ]
then
  sudo mkfs.ext4 /dev/xvdg
  sudo mkdir /mnt/hdrive
  sudo mount -t ext4 /dev/xvdg /mnt/hdrive
  sudo chown ubuntu /mnt/hdrive
fi

#get instance ID
INSTANCE=$(cat /var/lib/cloud/data/instance-id)

sleep 30
/usr/bin/aws s3 cp s3://$4/script/program.sh .
sudo chmod +x program.sh
/usr/bin/aws s3 cp s3://$4/bin/ bin --recursive
sudo chmod +x bin/*

#allocate elastic IP
/usr/bin/aws ec2 allocate-address --domain vpc > allocation.json

#get static IP and allocationID
IP=$(cat 'allocation.json' | jq -r .PublicIp)
ALLOCATION=$(cat 'allocation.json' | jq -r .AllocationId)

#associate and store association between elastic IP and instance
ASSOCIATION=$(/usr/bin/aws ec2 associate-address --instance-id $INSTANCE --allocation-id $ALLOCATION)
sleep 18
LOCALIP=$(curl http://169.254.169.254/latest/meta-data/local-ipv4)

#create tags
/usr/bin/aws ec2 create-tags --resources $INSTANCE --tags "Key=Name,Value=cluster_replica"

#run replica, args are 1:ownip, 2:tasks, 3:procs/task, 4:mem frac/task, 5:output loc, 6:primaryIP
python 'aether/replica/main.py' $IP $1 $2 $3 $4 $5 $ALLOCATION $INSTANCE $LOCALIP 2> replica.log


text:
<?php
namespace SplashPayments\Exceptions;

class Base extends \Exception {
  public function __construct($error) {
    parent::__construct($error);
  }
}


text:
"""
    sockjs.tornado.transports.htmlfile
    ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

    HtmlFile transport implementation.
"""

import re

from sockjs.tornado import proto
from sockjs.tornado.transports import streamingbase
from sockjs.tornado.util import asynchronous

try:
    # Python 3.4+
    from html import escape
except:
    from cgi import escape

RE = re.compile('[\W_]+')

# HTMLFILE template
HTMLFILE_HEAD = r'''
<!doctype html>

  <meta http-equiv="X-UA-Compatible" content="IE=edge" />
  <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />

Don't panic!

'''.strip()
HTMLFILE_HEAD += ' ' * (1024 - len(HTMLFILE_HEAD) + 14)
HTMLFILE_HEAD += '\r\n\r\n'

class HtmlFileTransport(streamingbase.StreamingTransportBase):
    name = 'htmlfile'

    def initialize(self, server):
        super(HtmlFileTransport, self).initialize(server)

    @asynchronous
    def get(self, session_id):
        # Start response
        self.preflight()
        self.handle_session_cookie()
        self.disable_cache()
        self.set_header('Content-Type', 'text/html; charset=UTF-8')

        # Grab callback parameter
        callback = self.get_argument('c', None)
        if not callback:
            self.write('"callback" parameter required')
            self.set_status(500)
            self.finish()
            return

        # TODO: Fix me - use parameter
        self.write(HTMLFILE_HEAD % escape(RE.sub('', callback)))
        self.flush()

        # Now try to attach to session
        if not self._attach_session(session_id):
            self.finish()
            return

        # Flush any pending messages
        if self.session:
            self.session.flush()

    def send_pack(self, message, binary=False):
        if binary:
            raise Exception('binary not supported for HtmlFileTransport')

        # TODO: Just do escaping
        msg = '\r\n' % proto.json_encode(message)

        self.active = False

        try:
            self.notify_sent(len(message))

            self.write(msg)
            self.flush().add_done_callback(self.send_complete)
        except IOError:
            # If connection dropped, make sure we close offending session instead
            # of propagating error all way up.
            self.session.delayed_close()
            self._detach()


text: var x: number = "not a number"; // Error: string ~> number


text:
using namespace CPF;
using namespace Concurrency;
using namespace Threading;

LoadBalancer::LoadBalancer(Plugin::iRegistry*, iUnknown*)
	: mLastUpdate(Time::Now())
{
}

LoadBalancer::~LoadBalancer()
{}

GOM::Result CPF_STDCALL LoadBalancer::QueryInterface(uint64_t id, void** outIface)
{
	if (outIface)
	{
		switch(id)
		{
		case iUnknown::kIID.GetID():
			*outIface = static_cast<iUnknown*>(this);
			break;
		case kIID.GetID():
			*outIface = static_cast<iLoadBalancer*>(this);
			break;
		default:
			return GOM::kUnknownInterface;
		}
		AddRef();
		return GOM::kOK;
	}
	return GOM::kInvalidParameter;
}

GOM::Result CPF_STDCALL LoadBalancer::Initialize(Plugin::iRegistry* regy, int count, iScheduler** schedulers)
{
	if(regy)
	{
		mSchedulers.clear();
		for (int i = 0; i < count; ++i)
			mSchedulers.push_back(schedulers[i]);
		return regy->Create(nullptr, kThreadTimeCID.GetID(), iThreadTimes::kIID.GetID(), mpDistTimeQuery.AsVoidPP());
	}
	return GOM::kInvalidParameter;
}

void CPF_STDCALL LoadBalancer::Balance()
{
	if (mSchedulers.empty())
		return;

	if (mQueryOutstanding)
	{
		CPF_LOG(Concurrency, Info) << " Processor usage: " << mCPUUsage.GetValue();

		mQueryOutstanding = false;
		ThreadTimeInfo info;
		mpDistTimeQuery->GetTimes(&info);
		int threadCount;

		// TODO: Currently expects scheduler 0 to be a distributor and 1 to be a thread pool.
		if (info.mDuration.GetTicks() > 0)
		{
			float duration = float(Time::Seconds(info.mDuration));
			float utilization = 0.0f;
			for (int i = 0; i < info.mThreadCount; ++i)
				utilization += float(Time::Seconds(info.mUserTime[i]));

			utilization = utilization / (float(info.mThreadCount) * duration);
			if (utilization < 0.9f)
			{
				threadCount = info.mThreadCount;
				if (threadCount>1)
				{
					threadCount -= 1;
					mSchedulers[0]->SetActiveThreads(threadCount);
				}
			}
			else
			{
				threadCount = info.mThreadCount;
				if (threadCount < mSchedulers[0]->GetMaxThreads() - 1)
				{
					threadCount += 1;
					mSchedulers[0]->SetActiveThreads(threadCount);
				}
			}

			// Simply set the number of pool threads to the inverse of those used in distribution.
			int targetThreads = mSchedulers[1]->GetMaxThreads() - threadCount;
			targetThreads = targetThreads > 0 ? targetThreads : 1;
			mSchedulers[1]->SetActiveThreads(targetThreads);
		}
	}
	else
	{
		auto now = Time::Now();
		if (Time::Seconds(now - mLastUpdate) < float(kUpdateRate))
			return;
		mLastUpdate = now;

		// Submits queries to pick up on the next loop.
		// Picking the result up on the next loop prevents blocking.
		mSchedulers[0]->Submit(mpDistTimeQuery);
		mQueryOutstanding = true;
	}
}


text:
using System;
using System.Reflection;
using System.Runtime.CompilerServices;
using FluentRegistration.Infrastructure;
using Microsoft.Extensions.DependencyInjection;

namespace FluentRegistration.Internal;

public class Registration : IRegistration
{
    private IRegister? _register;

    public IComponentImplementationSelector<TService> For<TService>()
        where TService : class
    {
        var registration = new ComponentRegistration<TService>(new[] { typeof(TService) });
        _register = registration;
        return registration;
    }

    public IComponentImplementationSelector<object> For(Type type)
    {
        GuardAgainst.Null(type);

        return For(new[] { type });
    }

    public IComponentImplementationSelector<object> For(params Type[] types)
    {
        GuardAgainst.NullOrEmpty(types);

        var registration = new ComponentRegistration<object>(types);
        _register = registration;
        return registration;
    }

    public ITypeSelector FromAssembly(Assembly assembly)
    {
        if (assembly == null)
        {
            throw new ArgumentNullException(nameof(assembly));
        }

        var registration = new AssemblyTypeSelector(assembly);
        _register = registration;
        return registration;
    }

    public ITypeSelector FromAssemblyContaining(Type type)
    {
        GuardAgainst.Null(type);

        var assembly = type.GetTypeInfo().Assembly;
        return FromAssembly(assembly);
    }

    public ITypeSelector FromAssemblyContaining<T>()
    {
        return FromAssemblyContaining(typeof(T));
    }

    [MethodImpl(MethodImplOptions.NoInlining)]
    public ITypeSelector FromThisAssembly()
    {
        return FromAssembly(Assembly.GetCallingAssembly());
    }

    public IWithServicesInitial ImplementedBy<T>()
    {
        return FromAssemblyContaining<T>()
            .Where(c => c.ImplementationType == typeof(T));
    }

    public IWithServicesInitial Instance<T>(T instance)
        where T : class
    {
        var registration = new InstanceRegistration<T>(instance);
        _register = registration;
        return registration;
    }

    public void Register(IServiceCollection services)
    {
        if (_register == null)
        {
            throw new InvalidOperationException("Register called without defining what to register via the fluent Api.");
        }

        _register.Register(services);
    }
}


text:
<?php

/**
 * @file
 * Contains \Drupal\Core\Field\WidgetBaseInterface.
 */

namespace Drupal\Core\Field;

use Drupal\Core\Form\FormStateInterface;
use Symfony\Component\Validator\ConstraintViolationListInterface;

/**
 * Base interface definition for "Field widget" plugins.
 *
 * This interface details base wrapping methods that most widget implementations
 * will want to directly inherit from Drupal\Core\Field\WidgetBase. See
 * Drupal\Core\Field\WidgetInterface for methods that will more likely be
 * overridden in actual widget implementations.
 */
interface WidgetBaseInterface extends PluginSettingsInterface {

  /**
   * Creates a form element for a field.
   *
   * If the entity associated with the form is new (i.e., $entity->isNew() is
   * TRUE), the 'default value', if any, is pre-populated. Also allows other
   * modules to alter the form element by implementing their own hooks.
   *
   * @param \Drupal\Core\Field\FieldItemListInterface $items
   *   An array of the field values. When creating a new entity this may be NULL
   *   or an empty array to use default values.
   * @param array $form
   *   An array representing the form that the editing element will be attached
   *   to.
   * @param \Drupal\Core\Form\FormStateInterface $form_state
   *   The current state of the form.
   * @param int $get_delta
   *   Used to get only a specific delta value of a multiple value field.
   *
   * @return array
   *   The form element array created for this field.
   */
  public function form(FieldItemListInterface $items, array &$form, FormStateInterface $form_state, $get_delta = NULL);

  /**
   * Extracts field values from submitted form values.
   *
   * @param \Drupal\Core\Field\FieldItemListInterface $items
   *   The field values. This parameter is altered by reference to receive the
   *   incoming form values.
   * @param array $form
   *   The form structure where field elements are attached to. This might be a
   *   full form structure, or a sub-element of a larger form.
   * @param \Drupal\Core\Form\FormStateInterface $form_state
   *   The form state.
   */
  public function extractFormValues(FieldItemListInterface $items, array $form, FormStateInterface $form_state);

  /**
   * Reports field-level validation errors against actual form elements.
   *
   * @param \Drupal\Core\Field\FieldItemListInterface $items
   *   The field values.
   * @param \Symfony\Component\Validator\ConstraintViolationListInterface|\Symfony\Component\Validator\ConstraintViolationInterface[] $violations
   *   The constraint violations that were detected.
   * @param array $form
   *   The form structure where field elements are attached to. This might be a
   *   full form structure, or a sub-element of a larger form.
   * @param \Drupal\Core\Form\FormStateInterface $form_state
   *   The form state.
   */
  public function flagErrors(FieldItemListInterface $items, ConstraintViolationListInterface $violations, array $form, FormStateInterface $form_state);

  /**
   * Retrieves processing information about the widget from $form_state.
   *
   * This method is static so that is can be used in static Form API callbacks.
   *
   * @param array $parents
   *   The array of #parents where the field lives in the form.
   * @param string $field_name
   *   The field name.
   * @param \Drupal\Core\Form\FormStateInterface $form_state
   *   The form state.
   *
   * @return array
   *   An array with the following key/value pairs:
   *   - items_count: The number of widgets to display for the field.
   *   - array_parents: The location of the field's widgets within the $form
   *     structure. This entry is populated at '#after_build' time.
   */
  public static function getWidgetState(array $parents, $field_name, FormStateInterface $form_state);

  /**
   * Stores processing information about the widget in $form_state.
   *
   * This method is static so that is can be used in static Form API #callbacks.
   *
   * @param array $parents
   *   The array of #parents where the widget lives in the form.
   * @param string $field_name
   *   The field name.
   * @param \Drupal\Core\Form\FormStateInterface $form_state
   *   The form state.
   * @param array $field_state
   *   The array of data to store. See getWidgetState() for the structure and
   *   content of the array.
   */
  public static function setWidgetState(array $parents, $field_name, FormStateInterface $form_state, array $field_state);

}


text:
inputList = ["kylan charles", "raymond strickland", "julissa shepard", "andrea meza", "destiny alvarado"]
inputList2 = ["maria garcia", "smith hernandez", "hernandez smith", "mary martinez", "james johnson"]
inputList3 = ["Sheldon Cooper", "Howord Wolowitz", "Amy Farrah Fowler", "Leonard Hofstadter", "Bernadette R"]
name_store = {}
for name in inputList3:
    name_store[name] = len(set(name.lower().replace(" ", "")))   # Remove spaces using replace and remove duplicates using set
res = []
maxLen = -float("inf")
for name in name_store.keys():
    if name_store.get(name) > maxLen:
        res.clear()
        res.append(name)
        maxLen = name_store.get(name)
    elif name_store.get(name) == maxLen:
        res.append(name)
res.sort()
print(res[0])