text:
[![npm](https://img.shields.io/npm/v/testingbot-tunnel-launcher.svg?maxAge=2592000)](https://www.npmjs.com/package/testingbot-tunnel-launcher)
[![dependencies Status](https://david-dm.org/testingbot/testingbot-tunnel-launcher/status.svg)](https://david-dm.org/testingbot/testingbot-tunnel-launcher)
[![devDependencies Status](https://david-dm.org/testingbot/testingbot-tunnel-launcher/dev-status.svg)](https://david-dm.org/testingbot/testingbot-tunnel-launcher?type=dev)
[![Build Status](https://travis-ci.org/testingbot/testingbot-tunnel-launcher.svg?branch=master)](https://travis-ci.org/testingbot/testingbot-tunnel-launcher)

A library to download and launch TestingBot Tunnel.

## Installation

```sh
npm install testingbot-tunnel-launcher
```

## Usage

### Simple Usage

```javascript
var testingbotTunnel = require('testingbot-tunnel-launcher');

testingbotTunnel({
  apiKey: 'key',
  apiSecret: 'secret',
  verbose: true
}, function (err, tunnel) {
  if (err) {
    console.error(err.message);
    return;
  }
  console.log("Tunnel ready");

  tunnel.close(function () {
    console.log("Tunnel closed completely");
  })
});
```

### Advanced Usage

```javascript

var testingbotTunnel = require('testingbot-tunnel-launcher'),
  options = {

    // The TestingBot API key which you can get for free, listed in our member area
    apiKey: 'key',

    // The TestingBot API secret which you can get for free, listed in our member area
    apiSecret: 'secret',

    // More verbose output from the tunnel
    verbose: true,

    // Port on which the tunnel Selenium relay will listen for
    // requests. Default 4445. (optional)
    se-port: null,

    // Proxy host and port the tunnel can use to connect to an upstream proxy
    // e.g. "localhost:1234" (optional)
    proxy: null,

    // a comma-separated list of domains that
    // will not go through the tunnel. (optional)
    fast-fail-regexps: null,

    // Write logging output to this logfile (optional)
    logfile: null,

    // Change the tunnel version - see versions on https://testingbot.com/support/other/tunnel
    tunnelVersion: "1.19", // or 2.1 (Java 8)

    // Gives this tunnel a unique identifier
    tunnelIdentifier: "myIdentifier"
  };

testingbotTunnel(options, function(err, tunnel) {
  console.log("Started Tunnel");
  tunnel.close(function () {
    console.log("Closed tunnel");
  });
});

```

### Credentials

You can pass the TestingBot credentials as `apiKey` and `apiSecret` in the options.

You can also create a `~/.testingbot` file with `apiKey:apiSecret` as content

## Testing

```
npm test
```

## Changelog

### v1.1.11
- Add support for `tunnelIdentifier`
- Improve parsing of arguments passed to the tunnel

### v1.1.11
- Throw error when user does not have any minutes left

### v1.1.9
- Add corrupt download check for tunnel binary

### v1.1.8
- Update dependencies

### v1.1.0
- Get rid of exit handlers, they're causing issues
- Add tests
- Update dependencies

### v1.0.7
- Properly handle SIGINT, exit and uncaughtException

### v1.0.6
- Small fixes
- Display new version/invalid credentials

### v1.0.5
- Add `tunnelVersion` support to specify which version of the tunnel you want to use

### v1.0.1 - v1.0.4
- Minor fixes

### v1.0.0
- First release of testingbot-tunnel-launcher

## MIT license

Copyright (c) TestingBot <info@testingbot.com>


text:
#import "EDPattern.h"

@interface EDWildcardPattern : EDPattern

@end

redpajama_set_name: RedPajamaGithub


text:
package org.apache.geode.management.internal.cli.converters;

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

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import org.springframework.shell.core.Completion;

import org.apache.geode.management.cli.ConverterHint;

public class JarFilesPathConverterTest {
  @Rule
  public TemporaryFolder tmpDir = new TemporaryFolder();

  @Test
  public void itSupportsStringArray() {
    JarFilesPathConverter jarFilesPathConverter = new JarFilesPathConverter();
    assertThat(jarFilesPathConverter.supports(String[].class, ConverterHint.JARFILES)).isTrue();
    assertThat(jarFilesPathConverter.supports(String[].class, ConverterHint.JARDIR)).isFalse();
    assertThat(jarFilesPathConverter.supports(Integer.class, ConverterHint.JARDIR)).isFalse();
  }

  @Test
  public void itFindsJarDirs() throws Exception {
    File testDir = createFileOrDir(tmpDir.getRoot(), "testOne", true);
    File libDir = createFileOrDir(testDir, "lib", true);
    createFileOrDir(testDir, "empty", true);
    createFileOrDir(libDir, "jar_one.jar", false);
    createFileOrDir(libDir, "jar_two.jar", false);

    JarFilesPathConverter jarFilesPathConverter = new JarFilesPathConverter();
    List<Completion> completions = new ArrayList<>();
    jarFilesPathConverter.getAllPossibleValues(completions, null, testDir.getPath(), null, null);

    assertThat(completions.size()).isEqualTo(1);
    assertThat(completions.get(0).getValue()).endsWith("lib");
  }

  @Test
  public void itFindsJarFiles() throws Exception {
    File testDir = createFileOrDir(tmpDir.getRoot(), "testOne", true);
    File libDir = createFileOrDir(testDir, "lib", true);
    createFileOrDir(testDir, "empty", true);
    createFileOrDir(libDir, "jar_one.jar", false);
    createFileOrDir(libDir, "jar_two.jar", false);

    JarFilesPathConverter jarFilesPathConverter = new JarFilesPathConverter();
    List<Completion> completions = new ArrayList<>();
    jarFilesPathConverter.getAllPossibleValues(completions, null, libDir.getPath(), null, null);

    assertThat(completions.size()).isEqualTo(2);
    assertThat(completions.get(0).getValue()).endsWith(".jar");
  }

  @Test
  public void itFindsDirsWithSubdirs() throws Exception {
    File testDir = createFileOrDir(tmpDir.getRoot(), "testTwo", true);
    File libDir = createFileOrDir(testDir, "lib", true);
    createFileOrDir(libDir, "file.txt", false);
    File nonEmptyDir = createFileOrDir(testDir, "nonEmpty", true);
    createFileOrDir(nonEmptyDir, "subDirOne", true);
    createFileOrDir(nonEmptyDir, "subDirTwo", true);

    JarFilesPathConverter jarFilesPathConverter = new JarFilesPathConverter();
    List<Completion> completions = new ArrayList<>();
    jarFilesPathConverter.getAllPossibleValues(completions, null, "garbage," + testDir.getPath(),
        null, null);

    assertThat(completions.size()).isEqualTo(1);
    assertThat(completions.get(0).getValue()).endsWith("nonEmpty");
    assertThat(completions.get(0).getValue()).startsWith("garbage,");
  }

  @Test
  public void itFindsDirsWithSubdirsAndJars() throws Exception {
    File testDir = createFileOrDir(tmpDir.getRoot(), "testTwo", true);
    File libDir = createFileOrDir(testDir, "lib", true);
    createFileOrDir(libDir, "file.jar", false);
    File nonEmptyDir = createFileOrDir(testDir, "nonEmpty", true);
    createFileOrDir(nonEmptyDir, "subDirOne", true);
    createFileOrDir(nonEmptyDir, "subDirTwo", true);

    JarFilesPathConverter jarFilesPathConverter = new JarFilesPathConverter();
    List<Completion> completions = new ArrayList<>();
    jarFilesPathConverter.getAllPossibleValues(completions, null, testDir.getPath(), null, null);

    assertThat(completions).hasSize(2);
    assertThat(completions).containsExactlyInAnyOrder(new Completion(nonEmptyDir.getPath()),
        new Completion(libDir.getPath()));
  }

  @Test
  public void itFindsNothingWithBadSearch() throws Exception {
    File testDir = createFileOrDir(tmpDir.getRoot(), "testTwo", true);
    File libDir = createFileOrDir(testDir, "lib", true);
    createFileOrDir(libDir, "file.txt", false);
    File nonEmptyDir = createFileOrDir(testDir, "nonEmpty", true);
    createFileOrDir(nonEmptyDir, "subDirOne", true);
    createFileOrDir(nonEmptyDir, "subDirTwo", true);

    JarFilesPathConverter jarFilesPathConverter = new JarFilesPathConverter();
    List<Completion> completions = new ArrayList<>();
    jarFilesPathConverter.getAllPossibleValues(completions, null, "garbage", null, null);

    assertThat(completions).isEmpty();
  }

  @Test
  public void itFindsNothing() throws Exception {
    File testDir = createFileOrDir(tmpDir.getRoot(), "testTwo", true);
    File libDir = createFileOrDir(testDir, "lib", true);
    createFileOrDir(libDir, "file.txt", false);
    createFileOrDir(testDir, "empty", true);

    JarFilesPathConverter jarFilesPathConverter = new JarFilesPathConverter();
    List<Completion> completions = new ArrayList<>();
    jarFilesPathConverter.getAllPossibleValues(completions, null, testDir.getPath(), null, null);

    assertThat(completions.size()).isEqualTo(0);
  }

  private File createFileOrDir(File parent, String fileOrDirName, boolean isDir) throws Exception {
    File fileOrDir = new File(parent, fileOrDirName);
    boolean success = fileOrDir.exists() || (isDir ? fileOrDir.mkdir() : fileOrDir.createNewFile());
    assertThat(success).isTrue();

    return fileOrDir;
  }
}


text:
import * as Loadable from 'react-loadable';
export default Loadable({
  loader: () => import('./BulkEditPage'),
  loading: () => null,
});


text:
require_relative '../modules/configreader'
class Komponent
  include ConfigReader

  class << self
    attr_reader :komponent_classes
  end

  attr_reader :commands

  @komponent_classes = []

  def initialize
    @commands = []
    post_construct
  end

  def post_construct()
    #to be overwritten by subclasses
  end

  def can_handle?(msgBag)
    false
  end

  def handle(msgBag)
  end

  def self.inherited(subclass)
    self.komponent_classes << subclass
  end

end


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel;
using Grabacr07.KanColleWrapper.Models;
using Livet;
using Livet.Commands;
using Livet.Messaging;
using Livet.Messaging.IO;
using Livet.EventListeners;
using Livet.Messaging.Windows;

namespace LvChartPlugin.ViewModels
{
    public class ShipViewModel : ViewModel
    {

        #region Level変更通知プロパティ
        private int _Level;

        public int Level
        {
            get
            { return this._Level; }
            set
            {
                if (this._Level == value)
                    return;
                this._Level = value;
                this.RaisePropertyChanged();
            }
        }
        #endregion

        #region Name変更通知プロパティ
        private string _Name;

        public string Name
        {
            get
            { return this._Name; }
            set
            {
                if (this._Name == value)
                    return;
                this._Name = value;
                this.RaisePropertyChanged();
            }
        }
        #endregion

        public ShipViewModel() { }

        public ShipViewModel(Ship ship)
        {
            this.Level = ship.Level;
            this.Name = ship.Info.Name;
        }
    }
}


text:
import { expect } from 'chai';
import 'mocha';
import { is } from 'ramda';
import Message from './message';

describe('Message', () => {

  describe('is', () => {

    it('does not throw on invalid values', () => {
      expect(() => Message.is(false)).not.to.throw;
      expect(() => Message.is(null)).not.to.throw;
      expect(() => Message.is(undefined)).not.to.throw;
    });

    it('accepts a Message', () => {
      class CoolMessage extends Message {}
      expect(Message.is(CoolMessage)).to.be.true;
    });

    it('does not accept a function', () => {
      expect(Message.is(() => {})).to.be.false;
    });

    it('accepts a subclass of a subclass of a subclass of Message', () => {
      class SubClass extends Message {}
      class SubSubClass extends SubClass {}
      class SubSubSubClass extends SubSubClass {}
      expect(Message.is(SubSubSubClass)).to.be.true;
    });
  });

  describe('#constructor', () => {
    it('populates data on init', () => {
      expect((new Message({ foo: true })).data).to.deep.equal({ foo: true });
    });

    it('freezes data', () => {
      const msg = new Message({ foo: true });

      expect(() => { (msg as any).rando = false; }).to.throw(TypeError);
      expect(() => { msg.data.foo = false; }).to.throw(TypeError);
      expect(() => { msg.data.bar = true; }).to.throw(TypeError);

      expect(msg.data).to.deep.equal({ foo: true });
    });

    it('validates its inputs', () => {
      class Msg extends Message { public static expects = { foo: is(Function) }; }

      expect(() => new Msg({ foo: null })).to.throw(TypeError);
      expect(() => new Msg({})).to.throw(TypeError);
    });
  });

  describe('#map', () => {
    it('uses the correct constructor', () => {
      class Foo extends Message {}
      const msg = (new Foo({ bar: true })).map({ bar: false, baz: true });

      expect(msg.data).to.deep.equal({ bar: false, baz: true });
      expect(msg).to.be.an.instanceof(Foo);
    });
  });

  describe('#validate', () => {
    it('passes on empty messages', () => {
      expect(() => new Message()).to.not.throw();
    });

    it('throws on unmatched expectations', () => {
      class Foo extends Message {
        public static expects = { foo: is(String), bar: is(Number) };
      }
      expect(() => new Foo({ foo: 'hello', bar: 1138 })).to.not.throw();
      expect(() => new Foo({ foo: 1138, bar: 1138 })).to.throw(TypeError);
    });
  });

});


text:
[Apache Groovy](http://groovy-lang.org/) is a powerful, optionally typed and dynamic language, with static-typing and static compilation capabilities, for the Java platform aimed at improving developer productivity thanks to a concise, familiar and easy to learn syntax. It integrates smoothly with any Java program, and immediately delivers to your application powerful features, including scripting capabilities, Domain-Specific Language authoring, runtime and compile-time meta-programming and functional programming.

%%LOGO%%

# How to use this image

Note that if you are mounting a volume and the uid running Docker is not `1000`, you should run as user `root` (`-u root`).

## Starting Groovysh

`docker run -it --rm groovy`

## Running a Groovy script

`docker run --rm -v "$PWD":/home/groovy/scripts -w /home/groovy/scripts %%IMAGE%% groovy <script> <script-args>`

## Reusing the Grapes cache

The local Grapes cache can be reused across containers by creating a volume and mounting it in `/home/groovy/.groovy/grapes`.

```console
docker volume create --name grapes-cache
docker run --rm -it -v grapes-cache:/home/groovy/.groovy/grapes %%IMAGE%%
```

**Note: Java 9 support is experimental**


text:
int main(int argc, char ** argv)
{
    StiGame::Viewport *viewport = new StiGame::Viewport();

    //LabelBenchmark *benchmark = new LabelBenchmark();
    DecoratedButtonBenchmark *benchmark = new DecoratedButtonBenchmark();
    viewport->setTitle("StiGame Benchmark");
    viewport->addProfiler(benchmark);

    viewport->setFps(50);
    viewport->push(benchmark);

    viewport->startLoop();

    return 0;
}


text:
{% load static %}

<!DOCTYPE html>

    <meta charset="utf-8">
    <title>Profile |{% block title %}{% endblock %}</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta name="description" content="">
    <meta name="author" content="">

    <link href="{% static 'bootstrap/css/bootstrap.css' %}" rel="stylesheet">

            <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
              Toggle navigation

            </button>
            User Profile

Home

Account Settings

                {% if not user.username %}

Sign In

                {% else %}

Profile

Logout ({{user.username|truncatechars:17}})

                {% endif %}

          {% block content %}

          {% endblock %}

A simple user login, registration, and account management django application.
          About


text:
from typing import TYPE_CHECKING

from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available

_import_structure = {
    "configuration_xlm_roberta_xl": [
        "XLM_ROBERTA_XL_PRETRAINED_CONFIG_ARCHIVE_MAP",
        "XLMRobertaXLConfig",
        "XLMRobertaXLOnnxConfig",
    ],
}

try:
    if not is_torch_available():
        raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
    pass
else:
    _import_structure["modeling_xlm_roberta_xl"] = [
        "XLM_ROBERTA_XL_PRETRAINED_MODEL_ARCHIVE_LIST",
        "XLMRobertaXLForCausalLM",
        "XLMRobertaXLForMaskedLM",
        "XLMRobertaXLForMultipleChoice",
        "XLMRobertaXLForQuestionAnswering",
        "XLMRobertaXLForSequenceClassification",
        "XLMRobertaXLForTokenClassification",
        "XLMRobertaXLModel",
        "XLMRobertaXLPreTrainedModel",
    ]

if TYPE_CHECKING:
    from .configuration_xlm_roberta_xl import (
        XLM_ROBERTA_XL_PRETRAINED_CONFIG_ARCHIVE_MAP,
        XLMRobertaXLConfig,
        XLMRobertaXLOnnxConfig,
    )

    try:
        if not is_torch_available():
            raise OptionalDependencyNotAvailable()
    except OptionalDependencyNotAvailable:
        pass
    else:
        from .modeling_xlm_roberta_xl import (
            XLM_ROBERTA_XL_PRETRAINED_MODEL_ARCHIVE_LIST,
            XLMRobertaXLForCausalLM,
            XLMRobertaXLForMaskedLM,
            XLMRobertaXLForMultipleChoice,
            XLMRobertaXLForQuestionAnswering,
            XLMRobertaXLForSequenceClassification,
            XLMRobertaXLForTokenClassification,
            XLMRobertaXLModel,
            XLMRobertaXLPreTrainedModel,
        )

else:
    import sys

    sys.modules[__name__] = _LazyModule(__name__, globals()["__file__"], _import_structure)


text:
package org.newdawn.slick.tests.xml;

import java.util.ArrayList;

/**
 * A test example of some object data that can be configured via XML
 *
 * @author kevin
 */
public class Inventory {
	/** The items held in the inventory */
	private ArrayList items = new ArrayList();

	/**
	 * Called by XML parser to add a configured item to the entity
	 *
	 * @param item The item to be added
	 */
	private void add(Item item) {
		items.add(item);
	}

	/**
	 * Dump this object to sysout
	 *
	 * @param prefix The prefix to apply to all lines
	 */
	public void dump(String prefix) {
		System.out.println(prefix+"Inventory");
		for (int i=0;i<items.size();i++) {
			((Item) items.get(i)).dump(prefix+"\t");
		}
	}
}


text:
from heat.common import exception
from heat.common.i18n import _
from heat.engine import attributes
from heat.engine import constraints
from heat.engine import properties
from heat.engine import resource
from heat.engine import support

class Node(resource.Resource):
    """A resource that creates a Senlin Node.

    Node is an object that belongs to at most one Cluster, it can be created
    based on a profile.
    """

    support_status = support.SupportStatus(version='6.0.0')

    default_client_name = 'senlin'

    PROPERTIES = (
        NAME, METADATA, PROFILE,
    ) = (
        'name', 'metadata', 'profile',
    )

    _NODE_STATUS = (
        INIT, ACTIVE, CREATING,
    ) = (
        'INIT', 'ACTIVE', 'CREATING',
    )

    _ACTION_STATUS = (
        ACTION_SUCCEEDED, ACTION_FAILED,
    ) = (
        'SUCCEEDED', 'FAILED',
    )

    ATTRIBUTES = (
        ATTR_DETAILS, ATTR_CLUSTER,
    ) = (
        'details', 'cluster_id'
    )

    properties_schema = {
        NAME: properties.Schema(
            properties.Schema.STRING,
            _('Name of the senlin node. By default, physical resource name '
              'is used.'),
            update_allowed=True,
        ),
        METADATA: properties.Schema(
            properties.Schema.MAP,
            _('Metadata key-values defined for node.'),
            update_allowed=True,
        ),
        PROFILE: properties.Schema(
            properties.Schema.STRING,
            _('Name or ID of senlin profile to create this node.'),
            required=True,
            update_allowed=True,
            constraints=[
                constraints.CustomConstraint('senlin.profile')
            ]
        ),
    }

    attributes_schema = {
        ATTR_DETAILS: attributes.Schema(
            _("The details of physical object."),
            type=attributes.Schema.MAP
        ),
        ATTR_CLUSTER: attributes.Schema(
            _("The cluster ID this node belongs to."),
            type=attributes.Schema.STRING
        ),
    }

    def handle_create(self):
        params = {
            'name': (self.properties[self.NAME] or
                     self.physical_resource_name()),
            'metadata': self.properties[self.METADATA],
            'profile_id': self.properties[self.PROFILE],
        }

        node = self.client().create_node(**params)
        self.resource_id_set(node.id)
        return node.id

    def check_create_complete(self, resource_id):
        node = self.client().get_node(resource_id)
        if node.status == self.ACTIVE:
            return True
        elif node.status in [self.INIT, self.CREATING]:
            return False
        else:
            raise exception.ResourceInError(
                status_reason=node.status_reason,
                resource_status=node.status,
            )

    def handle_delete(self):
        if self.resource_id is not None:
            with self.client_plugin().ignore_not_found:
                self.client().delete_node(self.resource_id)
        return self.resource_id

    def check_delete_complete(self, res_id):
        if not res_id:
            return True

        try:
            self.client().get_node(self.resource_id)
        except Exception as ex:
            self.client_plugin().ignore_not_found(ex)
            return True
        return False

    def _show_resource(self):
        node = self.client().get_node(self.resource_id)
        return node.to_dict()

    def handle_update(self, json_snippet, tmpl_diff, prop_diff):
        updaters = dict()
        UPDATE_PROPS = [self.NAME, self.METADATA, self.PROFILE]
        if any(p in prop_diff for p in UPDATE_PROPS):
            params = dict((k, v) for k, v in prop_diff.items()
                          if k in UPDATE_PROPS)
            if self.PROFILE in params:
                params['profile_id'] = params.pop(self.PROFILE)
            updaters['profile_update'] = {
                'params': params,
                'finished': False,
            }

        return updaters

    def check_update_complete(self, updaters):
        def check_action(updater, set_key):
            action = self.client().get_action(updater['action'])
            if action.status == self.ACTION_SUCCEEDED:
                updater[set_key] = True
            elif action.status == self.ACTION_FAILED:
                raise exception.ResourceInError(
                    status_reason=action.status_reason,
                    resource_status=action.status,
                )

        if not updaters:
            return True
        profile_update = updaters.get('profile_update')
        if profile_update and not profile_update['finished']:
            if 'action' not in profile_update:
                resp = self.client().update_node(
                    self.resource_id, **profile_update['params'])
                profile_update['action'] = resp.location.split('/')[-1]
                return False
            else:
                check_action(profile_update, 'finished')
                if not profile_update['finished']:
                    return False

        return True

    def _resolve_attribute(self, name):
        node = self.client().get_node(self.resource_id,
                                      args={'show_details': True})
        return getattr(node, name, None)

def resource_mapping():
    return {
        'OS::Senlin::Node': Node
    }


text:
class CreateStudentTexts < ActiveRecord::Migration
  def change
    create_table :student_texts do |t|
      t.integer :student_id
      t.integer :text_id
      t.integer :rating, default: nil
      t.boolean :favorite, default: false
      t.boolean :checked_out, default: false
      t.boolean :completed, default: false
      t.boolean :abandoned, default: false
      t.string :reason_for_abandoning, default: ''
      t.string :review_title, default: ''
      t.string :review_content, default: ''

      t.timestamps
    end
  end
end


text:
from django.contrib.comments.models import Comment
from django.db import models
from django.utils.translation import ugettext_lazy as _

class ProtectComment(Comment):
    security_hash = models.CharField(_('security hash'), max_length=50, blank=True)
    timestamp = models.CharField(_('timestamp'), max_length=50, blank=True)
    headers_data = models.TextField(_('headers'), blank=True)

    class Meta:
        db_table = "django_comments_protect"
        verbose_name = _('comment')
        verbose_name_plural = _('comments')

    def save(self, *args, **kwargs):
        super(Comment, self).save(*args, **kwargs)

#    def save(self, *args, **kwargs):
#        super(Comment, self).save(*args, **kwargs)
#
#    class Meta:
#        db_table = "django_comments"
#    class Meta:
#        super()


text:
namespace blink {

TEST(NetworkUtilsTest, IsReservedIPAddress) {
  // Unreserved IPv4 addresses (in various forms).
  EXPECT_FALSE(network_utils::IsReservedIPAddress("8.8.8.8"));
  EXPECT_FALSE(network_utils::IsReservedIPAddress("99.64.0.0"));
  EXPECT_FALSE(network_utils::IsReservedIPAddress("212.15.0.0"));
  EXPECT_FALSE(network_utils::IsReservedIPAddress("212.15"));
  EXPECT_FALSE(network_utils::IsReservedIPAddress("212.15.0"));
  EXPECT_FALSE(network_utils::IsReservedIPAddress("3557752832"));

  // Reserved IPv4 addresses (in various forms).
  EXPECT_TRUE(network_utils::IsReservedIPAddress("192.168.0.0"));
  EXPECT_TRUE(network_utils::IsReservedIPAddress("192.168.0.6"));
  EXPECT_TRUE(network_utils::IsReservedIPAddress("10.0.0.5"));
  EXPECT_TRUE(network_utils::IsReservedIPAddress("10.0.0"));
  EXPECT_TRUE(network_utils::IsReservedIPAddress("10.0"));
  EXPECT_TRUE(network_utils::IsReservedIPAddress("3232235526"));

  // Unreserved IPv6 addresses.
  EXPECT_FALSE(network_utils::IsReservedIPAddress(
      "[FFC0:ba98:7654:3210:FEDC:BA98:7654:3210]"));
  EXPECT_FALSE(network_utils::IsReservedIPAddress(
      "[2000:ba98:7654:2301:EFCD:BA98:7654:3210]"));
  // IPv4-mapped to IPv6
  EXPECT_FALSE(network_utils::IsReservedIPAddress("[::ffff:8.8.8.8]"));

  // Reserved IPv6 addresses.
  EXPECT_TRUE(network_utils::IsReservedIPAddress("[::1]"));
  EXPECT_TRUE(network_utils::IsReservedIPAddress("[::192.9.5.5]"));
  EXPECT_TRUE(network_utils::IsReservedIPAddress("[::ffff:192.168.1.1]"));
  EXPECT_TRUE(network_utils::IsReservedIPAddress("[FEED::BEEF]"));
  EXPECT_TRUE(network_utils::IsReservedIPAddress(
      "[FEC0:ba98:7654:3210:FEDC:BA98:7654:3210]"));

  // Not IP addresses at all.
  EXPECT_FALSE(network_utils::IsReservedIPAddress("example.com"));
  EXPECT_FALSE(network_utils::IsReservedIPAddress("127.0.0.1.example.com"));

  // Moar IPv4
  for (int i = 0; i < 256; i++) {
    net::IPAddress address(i, 0, 0, 1);
    std::string address_string = address.ToString();
    if (i == 0 || i == 10 || i == 127 || i == 192 || i > 223) {
      EXPECT_TRUE(network_utils::IsReservedIPAddress(
          String::FromUTF8(address_string.data(), address_string.length())));
    } else {
      EXPECT_FALSE(network_utils::IsReservedIPAddress(
          String::FromUTF8(address_string.data(), address_string.length())));
    }
  }
}

TEST(NetworkUtilsTest, GetDomainAndRegistry) {
  EXPECT_EQ("", network_utils::GetDomainAndRegistry(
                    "", network_utils::kIncludePrivateRegistries));
  EXPECT_EQ("", network_utils::GetDomainAndRegistry(
                    ".", network_utils::kIncludePrivateRegistries));
  EXPECT_EQ("", network_utils::GetDomainAndRegistry(
                    "..", network_utils::kIncludePrivateRegistries));
  EXPECT_EQ("", network_utils::GetDomainAndRegistry(
                    "com", network_utils::kIncludePrivateRegistries));
  EXPECT_EQ("", network_utils::GetDomainAndRegistry(
                    ".com", network_utils::kIncludePrivateRegistries));
  EXPECT_EQ("", network_utils::GetDomainAndRegistry(
                    "www.example.com:8000",
                    network_utils::kIncludePrivateRegistries));

  EXPECT_EQ("", network_utils::GetDomainAndRegistry(
                    "localhost", network_utils::kIncludePrivateRegistries));
  EXPECT_EQ("", network_utils::GetDomainAndRegistry(
                    "127.0.0.1", network_utils::kIncludePrivateRegistries));

  EXPECT_EQ("example.com",
            network_utils::GetDomainAndRegistry(
                "example.com", network_utils::kIncludePrivateRegistries));
  EXPECT_EQ("example.com",
            network_utils::GetDomainAndRegistry(
                "www.example.com", network_utils::kIncludePrivateRegistries));
  EXPECT_EQ("example.com", network_utils::GetDomainAndRegistry(
                               "static.example.com",
                               network_utils::kIncludePrivateRegistries));
  EXPECT_EQ("example.com", network_utils::GetDomainAndRegistry(
                               "multilevel.www.example.com",
                               network_utils::kIncludePrivateRegistries));
  EXPECT_EQ("example.co.uk",
            network_utils::GetDomainAndRegistry(
                "www.example.co.uk", network_utils::kIncludePrivateRegistries));

  // Verify proper handling of 'private registries'.
  EXPECT_EQ("foo.appspot.com", network_utils::GetDomainAndRegistry(
                                   "www.foo.appspot.com",
                                   network_utils::kIncludePrivateRegistries));
  EXPECT_EQ("appspot.com", network_utils::GetDomainAndRegistry(
                               "www.foo.appspot.com",
                               network_utils::kExcludePrivateRegistries));

  // Verify that unknown registries are included.
  EXPECT_EQ("example.notarealregistry",
            network_utils::GetDomainAndRegistry(
                "www.example.notarealregistry",
                network_utils::kIncludePrivateRegistries));
}

}  // namespace blink


text:
#ifndef TENSORFLOW_SERVING_CORE_LOAD_SERVABLES_FAST_H_
#define TENSORFLOW_SERVING_CORE_LOAD_SERVABLES_FAST_H_

#include <functional>
#include <memory>

#include "tensorflow/core/lib/core/status.h"
#include "tensorflow_serving/core/aspired_versions_manager.h"
#include "tensorflow_serving/core/loader.h"
#include "tensorflow_serving/core/manager.h"
#include "tensorflow_serving/core/servable_state_monitor.h"

namespace tensorflow {
namespace serving {

// Connects 'source' to 'manager', and speeds up loading of the servables
// matching 'initial_servables'. The speeding up is accomplished by boosting the
// number of threads used for loading until the initial servables have been
// loaded, and then resetting it to the manager's originally configured value.
Status ConnectSourceWithFastInitialLoad(
    AspiredVersionsManager* manager, Source<std::unique_ptr<Loader>>* source,
    ServableStateMonitor* servable_state_monitor,
    const std::vector<ServableRequest>& initial_servables,
    uint32 num_threads = 4 * port::NumSchedulableCPUs());

// Like ConnectSourceWithFastInitialLoad(), but with multiple sources.
Status ConnectSourcesWithFastInitialLoad(
    AspiredVersionsManager* manager,
    std::vector<Source<std::unique_ptr<Loader>>*> sources,
    ServableStateMonitor* servable_state_monitor,
    const std::vector<ServableRequest>& initial_servables,
    uint32 num_threads = 4 * port::NumSchedulableCPUs());

////
// Implementation detail. API readers may skip.
///

namespace internal {

Status ConnectSourcesWithFastInitialLoad(
    AspiredVersionsManager* manager,
    std::vector<Source<std::unique_ptr<Loader>>*> sources,
    const std::function<Status()>& wait_until_loaded_fn, uint32 num_threads);

}  // namespace internal

}  // namespace serving
}  // namespace tensorflow

#endif  // TENSORFLOW_SERVING_CORE_LOAD_SERVABLES_FAST_H_


text:
from pathlib import Path

import pytest

from c7n.testing import PyTestUtils, reset_session_cache
from zpill import PillTest

class CloudControlTesting(PyTestUtils, PillTest):
    """Pytest AWS Testing Fixture"""

    placebo_dir = Path(__file__).absolute().parent / "data" / "placebo"

@pytest.fixture(scope="function")
def test_awscc(request):
    test_utils = CloudControlTesting(request)
    test_utils.addCleanup(reset_session_cache)
    return test_utils


text:
[![Build Status](https://travis-ci.org/doug-martin/leafy.png?branch=master)](https://travis-ci.org/doug-martin/leafy)

[![browser support](http://ci.testling.com/doug-martin/leafy.png)](http://ci.testling.com/doug-martin/leafy)

# Leafy

`leafy` is a library of different tree implementations. `leafy` can be used in both the browser and node.

Why would I need a tree in javascript? I have arrays and objects.

Good question!

The driving reason behind the creation of `leafy` was the library [`nools`](https://github.com/C2FO/nools) which needed a datastructure that was

 * fast
 * maintained order
 * could have items inserted into it without having to re-sort the entire structure.

This was needed in order to maintain a real time list of rule activations without having to search or sort the actions on insertion.

Often a tree is overkill but when you need one its good to know its out there.

## Installation

```
npm install leafy
```

Or [download the source](https://raw.github.com/doug-martin/leafy/master/index.js) ([minified](https://raw.github.com/doug-martin/leafy/master/leafy.min.js))

**Note** `leafy` depends on [`declare.js`](https://github.com/doug-martin/declare.js), [`extended`](https://github.com/doug-martin/extended), [`is-extended`](https://github.com/doug-martin/is-extended), [`string-extended`](https://github.com/doug-martin/extended), and [`array-extended`](https://github.com/doug-martin/array-extended)

## Usage

`leafy` contains the following tree implementations.

 * [`AVLTree`](http://en.wikipedia.org/wiki/AVL_tree)
 * [`RedBlackTree`](http://en.wikipedia.org/wiki/Red%E2%80%93black_tree)
 * [`BinaryTree`](http://en.wikipedia.org/wiki/Binary_tree)
 * [`AnderssonTree`](http://en.wikipedia.org/wiki/AA_tree)

**`options`**

When creating a tree you can specify a compare function used to sort items as they are inserted or removed.

```javscript
var tree = new leafy.AVLTree({
   compare : function(a, b){
       var ret = 0;
       if (a.type > b.type) {
           ret = 1;
       } else if (a.type < b.type) {
           ret = -1;
       }
       return ret;
   }
});
```

By default the tree uses a natural ordering function.

```javascript
function compare(a, b) {
   var ret = 0;
   if (a > b) {
       return 1;
   } else if (a < b) {
       return -1;
   } else if (!b) {
       return 1;
   }
   return ret;
}
```

Each tree contains the following functions.

**`insert`**

Insert an item into an the tree.

```javascript
tree.insert("a");
tree.insert("b");
tree.insert("c");
tree.insert("aa");
```

**`remove`**

Remove an item from a tree.

```
tree.remove("a");
tree.remove("c");
```

**`clear`**

Remove all items from a tree.

```javascript

tree.insert("a");
tree.insert("b");
tree.insert("c");
tree.insert("aa");

tree.clear();

```

**`isEmpty`**

Returns a boolean indicating if the tree is currently empty.

```
tree.insert("a");
tree.insert("b");
tree.insert("c");
tree.insert("aa");

tree.isEmpty(); //false

tree.clear();

tree.isEmpty(); //true
```

**`contains`**

Test if a tree contains a particular value.

```javascript
tree.insert("a");
tree.insert("b");
tree.insert("c");

tree.contains("a"); //true
tree.contains("d"); //false
```

**`toArray([order=leafy.IN_ORDER]);

Coverts a tree to an array with the values in the order specified, or in order if not specified

```javascript
tree.insert("a");
tree.insert("b");
tree.insert("c");

tree.toArray(); //["a", "b", "c", "d"]
tree.toArray(leafy.REVERSE_ORDER); //["d", "c", "b", "a"]
```

**`forEach(iterator(iterator[, scope[, order=leafy.IN_ORDER]])`**

Loop through the items in tree.

By default the tree will loop through items in order.

```javascript
tree.insert("a");
tree.insert("b");
tree.insert("c");
tree.insert("aa");

tree.forEach(function(item, tree){
    console.log(item); //"a", "b", "c", "d" respectively
});
```

You can loop through a tree in any order you wish by specifying any of the following orders.

* `leafy.REVERSE_ORDER`
* `leafy.IN_ORDER`
* `leafy.POST_ORDER`
* `leafy.PRE_ORDER`

```javascript

tree.forEach(function(item, tree){
    console.log(item); //"d", "c", "b", "a" respectively
}, null, leafy.REVERSE_ORDER);

```

**`map(iterator[, scope[, order=leafy.IN_ORDER]])`**

Map is very similar to the array counter part except that it returns new tree with the mapped values.

```javascript
//creates a new tree with the returned values "aa", "bb", "cc", "dd"
var mapped = tree.map(function(item, tree){
    return item + item;
});

```

**`filter(iterator[, scope[, order=leafy.IN_ORDER]])`**

Filter is very similar to the array counter part except that it returns new tree with the mapped values.

```javascript
//creates a new tree with the returned values "a", "b"
var mapped = tree.map(function(item, tree){
    return item === "a" || item === "b";
});

```

### Other iterator methods.

Trees also contains the following array methods that act just like their array counter part.

**Note** all of these methods accept an order parameter.

* `reduce`
* `reduceRight`
* `every`
* `some`

**`findLessThan(value[, exclusive=true])`**

Find all values in a tree less than a particular value. If exclusive is set to false then the original value will be included in the resulting array.

```javascript
tree.insert("a");
tree.insert("b");
tree.insert("c");
tree.insert("d");

tree.findLessThan("d"); //["a", "b", "c"];
tree.findLessThan("d", false); //["a", "b", "c", "d"];

```

**`findGreaterThan(value[, exclusive=true])`**

Find all values in a tree greater than a particular value. If exclusive is set to false then the original value will be included in the resulting array.

```javascript
tree.insert("a");
tree.insert("b");
tree.insert("c");
tree.insert("d");

tree.findGreaterThan("a"); //["d", "c", "b"];
tree.findGreaterThan("a", false); //["d", "c", "b", "a"];

```

**`print()`**

Prints the current structure of a tree to the console.


text:
package events;

/**
 * @author Cloudraid Dev Team (cloudraid.stnetix.com)
 */
public interface FileBrowserEventListener {
    void onChange(FileBrowserEvent event);
}


text:
from webunit.webunittest import WebTestCase
import unittest

class TestPythonOrg(WebTestCase):
    '''Load the front page of www.python.org
    '''
    def test_home(self):
        page = self.page('http://www.python.org')

def suite():
    l = [
         unittest.makeSuite(TestPythonOrg, 'test'),
    ]
    return unittest.TestSuite(l)


text:
package org.dashbuilder.dataset.client.uuid;

import javax.enterprise.context.ApplicationScoped;

import com.google.gwt.dom.client.Document;
import org.dashbuilder.dataset.uuid.UUIDGenerator;
import org.jboss.errai.ioc.client.container.IOC;
import org.jboss.errai.ioc.client.container.IOCBeanDef;

import java.util.Collection;

@ApplicationScoped
public class ClientUUIDGenerator implements UUIDGenerator {

    public static ClientUUIDGenerator get() {
        Collection<IOCBeanDef<ClientUUIDGenerator>> beans = IOC.getBeanManager().lookupBeans(ClientUUIDGenerator.class);
        IOCBeanDef<ClientUUIDGenerator> beanDef = beans.iterator().next();
        return beanDef.getInstance();
    }

    public String newUuid() {
        return Document.get().createUniqueId();
    }

    public String newUuidBase64() {
        return Document.get().createUniqueId();
    }

    public String uuidToBase64(String str) {
        return str;
    }

    public String uuidFromBase64(String str) {
        return str;
    }
}


text:
import Ember from "ember-metal/core";
import { A as emberA } from "ember-runtime/system/native_array";
import { typeOf } from "ember-runtime/utils";
import {
  dasherize,
  classify
} from "ember-runtime/system/string";
import Namespace from "ember-runtime/system/namespace";
import EmberObject from "ember-runtime/system/object";

/**
@module ember
@submodule ember-extension-support
*/

/**
  The `ContainerDebugAdapter` helps the container and resolver interface
  with tools that debug Ember such as the
  [Ember Extension](https://github.com/tildeio/ember-extension)
  for Chrome and Firefox.

  This class can be extended by a custom resolver implementer
  to override some of the methods with library-specific code.

  The methods likely to be overridden are:

  * `canCatalogEntriesByType`
  * `catalogEntriesByType`

  The adapter will need to be registered
  in the application's container as `container-debug-adapter:main`

  Example:

  ```javascript
  Application.initializer({
    name: "containerDebugAdapter",

    initialize: function(container, application) {
      application.register('container-debug-adapter:main', require('app/container-debug-adapter'));
    }
  });
  ```

  @class ContainerDebugAdapter
  @namespace Ember
  @extends Ember.Object
  @since 1.5.0
*/
export default EmberObject.extend({
  /**
    The container of the application being debugged.
    This property will be injected
    on creation.

    @property container
    @default null
  */
  container: null,

  /**
    The resolver instance of the application
    being debugged. This property will be injected
    on creation.

    @property resolver
    @default null
  */
  resolver: null,

  /**
    Returns true if it is possible to catalog a list of available
    classes in the resolver for a given type.

    @method canCatalogEntriesByType
    @param {String} type The type. e.g. "model", "controller", "route"
    @return {boolean} whether a list is available for this type.
  */
  canCatalogEntriesByType(type) {
    if (type === 'model' || type === 'template') {
      return false;
    }

    return true;
  },

  /**
    Returns the available classes a given type.

    @method catalogEntriesByType
    @param {String} type The type. e.g. "model", "controller", "route"
    @return {Array} An array of strings.
  */
  catalogEntriesByType(type) {
    var namespaces = emberA(Namespace.NAMESPACES);
    var types = emberA();
    var typeSuffixRegex = new RegExp(`${classify(type)}$`);

    namespaces.forEach(function(namespace) {
      if (namespace !== Ember) {
        for (var key in namespace) {
          if (!namespace.hasOwnProperty(key)) { continue; }
          if (typeSuffixRegex.test(key)) {
            var klass = namespace[key];
            if (typeOf(klass) === 'class') {
              types.push(dasherize(key.replace(typeSuffixRegex, '')));
            }
          }
        }
      }
    });
    return types;
  }
});


text:
//
//  ========================================================================
//  Copyright (c) 1995-2015 Mort Bay Consulting Pty. Ltd.
//  ------------------------------------------------------------------------
//  All rights reserved. This program and the accompanying materials
//  are made available under the terms of the Eclipse Public License v1.0
//  and Apache License v2.0 which accompanies this distribution.
//
//      The Eclipse Public License is available at
//      http://www.eclipse.org/legal/epl-v10.html
//
//      The Apache License v2.0 is available at
//      http://www.opensource.org/licenses/apache2.0.php
//
//  You may elect to redistribute this code under either of these licenses.
//  ========================================================================
//

package org.eclipse.jetty.spdy;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;

import org.eclipse.jetty.spdy.api.DataInfo;
import org.eclipse.jetty.spdy.api.Handler;
import org.eclipse.jetty.spdy.api.RstInfo;
import org.eclipse.jetty.spdy.api.Session;
import org.eclipse.jetty.spdy.api.SessionFrameListener;
import org.eclipse.jetty.spdy.api.Stream;
import org.eclipse.jetty.spdy.api.StreamFrameListener;
import org.eclipse.jetty.spdy.api.StreamStatus;
import org.eclipse.jetty.spdy.api.StringDataInfo;
import org.eclipse.jetty.spdy.api.SynInfo;
import org.eclipse.jetty.spdy.api.server.ServerSessionFrameListener;
import org.junit.Test;

import static org.hamcrest.Matchers.is;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;

public class ResetStreamTest extends AbstractTest
{
    @Test
    public void testResetStreamIsRemoved() throws Exception
    {
        Session session = startClient(startServer(new ServerSessionFrameListener.Adapter()/*TODO, true*/),null);

        Stream stream = session.syn(new SynInfo(false),null).get(5,TimeUnit.SECONDS);
        session.rst(new RstInfo(stream.getId(),StreamStatus.CANCEL_STREAM)).get(5,TimeUnit.SECONDS);

        assertEquals("session expected to contain 0 streams",0,session.getStreams().size());
    }

    @Test
    public void testRefusedStreamIsRemoved() throws Exception
    {
        final AtomicReference<Session> serverSessionRef = new AtomicReference<>();
        final CountDownLatch synLatch = new CountDownLatch(1);
        final CountDownLatch rstLatch = new CountDownLatch(1);
        Session clientSession = startClient(startServer(new ServerSessionFrameListener.Adapter()
        {
            @Override
            public StreamFrameListener onSyn(Stream stream, SynInfo synInfo)
            {
                Session serverSession = stream.getSession();
                serverSessionRef.set(serverSession);
                serverSession.rst(new RstInfo(stream.getId(),StreamStatus.REFUSED_STREAM));
                synLatch.countDown();
                return null;
            }
        }),new SessionFrameListener.Adapter()
        {
            @Override
            public void onRst(Session session, RstInfo rstInfo)
            {
                rstLatch.countDown();
            }
        });

        Stream stream = clientSession.syn(new SynInfo(false),null).get(5,TimeUnit.SECONDS);

        assertTrue("syncLatch didn't count down",synLatch.await(5,TimeUnit.SECONDS));
        Session serverSession = serverSessionRef.get();
        assertEquals("serverSession expected to contain 0 streams",0,serverSession.getStreams().size());

        assertTrue("rstLatch didn't count down",rstLatch.await(5,TimeUnit.SECONDS));
        // Need to sleep a while to give the chance to the implementation to remove the stream
        TimeUnit.SECONDS.sleep(1);
        assertTrue("stream is expected to be reset",stream.isReset());
        assertEquals("clientSession expected to contain 0 streams",0,clientSession.getStreams().size());
    }

    @Test
    public void testRefusedStreamIgnoresData() throws Exception
    {
        final CountDownLatch synLatch = new CountDownLatch(1);
        final CountDownLatch dataLatch = new CountDownLatch(1);
        final CountDownLatch rstLatch = new CountDownLatch(1);
        Session session = startClient(startServer(new ServerSessionFrameListener.Adapter()
        {
            @Override
            public StreamFrameListener onSyn(Stream stream, SynInfo synInfo)
            {
                try
                {
                    // Refuse the stream, we must ignore data frames
                    assertTrue(synLatch.await(5,TimeUnit.SECONDS));
                    stream.getSession().rst(new RstInfo(stream.getId(),StreamStatus.REFUSED_STREAM));
                    return new StreamFrameListener.Adapter()
                    {
                        @Override
                        public void onData(Stream stream, DataInfo dataInfo)
                        {
                            dataLatch.countDown();
                        }
                    };
                }
                catch (InterruptedException x)
                {
                    x.printStackTrace();
                    return null;
                }
            }
        }),new SessionFrameListener.Adapter()
        {
            @Override
            public void onRst(Session session, RstInfo rstInfo)
            {
                rstLatch.countDown();
            }
        });

        Stream stream = session.syn(new SynInfo(false),null).get(5,TimeUnit.SECONDS);
        stream.data(new StringDataInfo("data",true),5,TimeUnit.SECONDS,new Handler.Adapter<Void>()
        {
            @Override
            public void completed(Void context)
            {
                synLatch.countDown();
            }
        });

        assertTrue("rstLatch didn't count down",rstLatch.await(5,TimeUnit.SECONDS));
        assertTrue("stream is expected to be reset",stream.isReset());
        assertFalse("dataLatch shouln't be count down",dataLatch.await(1,TimeUnit.SECONDS));
    }

    @Test
    public void testResetAfterServerReceivedFirstDataFrameAndSecondDataFrameFails() throws Exception
    {
        final CountDownLatch synLatch = new CountDownLatch(1);
        final CountDownLatch dataLatch = new CountDownLatch(1);
        final CountDownLatch rstLatch = new CountDownLatch(1);
        final CountDownLatch failLatch = new CountDownLatch(1);
        Session session = startClient(startServer(new ServerSessionFrameListener.Adapter()
        {
            @Override
            public StreamFrameListener onSyn(Stream stream, SynInfo synInfo)
            {
                synLatch.countDown();
                return new StreamFrameListener.Adapter()
                {
                    @Override
                    public void onData(Stream stream, DataInfo dataInfo)
                    {
                        dataLatch.countDown();
                        stream.getSession().rst(new RstInfo(stream.getId(),StreamStatus.REFUSED_STREAM));
                    }
                };
            }
        }),new SessionFrameListener.Adapter()
        {
            @Override
            public void onRst(Session session, RstInfo rstInfo)
            {
                rstLatch.countDown();
            }
        });

        Stream stream = session.syn(new SynInfo(false),null).get(5,TimeUnit.SECONDS);
        assertThat("syn is received by server", synLatch.await(5,TimeUnit.SECONDS),is(true));
        stream.data(new StringDataInfo("data",false),5,TimeUnit.SECONDS,null);
        assertThat("stream is reset",rstLatch.await(5,TimeUnit.SECONDS),is(true));
        stream.data(new StringDataInfo("2nd dataframe",false),5L,TimeUnit.SECONDS,new Handler.Adapter<Void>()
        {
            @Override
            public void failed(Void context, Throwable x)
            {
                failLatch.countDown();
            }
        });

        assertThat("2nd data call failed",failLatch.await(5,TimeUnit.SECONDS),is(true));
        assertThat("stream is reset",stream.isReset(),is(true));
    }

    // TODO: If server already received 2nd dataframe after it rst, it should ignore it. Not easy to do.

}


text:
import os

################################################################################
#   Constants.
kBaseDirName            = os.path.dirname(os.path.abspath(__file__))
kBaseFilePath_Header    = os.path.normpath(os.path.join(kBaseDirName, './base.hpp'))
kBaseFilePath_CPP       = os.path.normpath(os.path.join(kBaseDirName, './base.cpp'))
kExtensionForHeader     = '.hpp'
kExtensionForCPP        = '.cpp'
kTextureDirectoryPath   = ''

kGravityModeCodeBase = '''
    //-------------------------------------------
    // Emitter Mode
    this->_emitterMode              = {EmitterType};
    this->modeA.gravity.x           = {GravityX};
    this->modeA.gravity.y           = {GravityY};
    this->modeA.speed               = {Speed};
    this->modeA.speedVar            = {SpeedVariance};
    this->modeA.radialAccel         = {RadialAcceleration};
    this->modeA.radialAccelVar      = {RadialAccelVariance};
    this->modeA.tangentialAccel     = {TangentialAcceleration};
    this->modeA.tangentialAccelVar  = {TangentialAccelVariance};
    this->modeA.rotationIsDir       = {RotationIsDir};
'''

kRadiusModeCodeBase = '''
    //-------------------------------------------
    // Emitter Mode
    this->_emitterMode              = {EmitterType};
    this->modeB.startRadius         = {MaxRadius};
    this->modeB.startRadiusVar      = {MaxRadiusVariance};
    this->modeB.endRadius           = {MinRadius};
    this->modeB.endRadiusVar        = {MinRadiusVariance};
    this->modeB.rotatePerSecond     = {RotatePerSecond};
    this->modeB.rotatePerSecondVar  = {RotatePerSecondVariance};
'''

def _safeget(dic, key, default) :
    return dic[key] if key in dic else default

################################################################################
#   Generate Header.
def _gen_hpp_include_guard(namespace, file_name) :
    ns = [] if namespace is None else namespace.split('::')
    ig = '__'
    for n in ns:
        if n is not '':
            ig += n.upper() + '_'
    ig += file_name.upper() + '_H__'
    return ig

def _gen_hpp_namespace_codes(namespace) :
    ns = [] if namespace is None else namespace.split('::')
    begin, end = '', ''
    if len(ns) == 0 :
        return begin, end
    for n in ns :
        if n is not '':
            begin += 'namespace {0} {{{1}'.format(n, os.linesep)
            end = '}}  // namespace {0}{1}'.format(n, os.linesep) + end
    return begin, end

def _generate_header(plist, options) :
    # gen code parts.
    base = open(kBaseFilePath_Header, 'r').read()
    fname = options['output_file_name'] + kExtensionForHeader
    inc_guard = _gen_hpp_include_guard(
            options['namespace'], options['output_file_name'])
    ns_begin, ns_end = _gen_hpp_namespace_codes(options['namespace'])

    # generate header.
    return base.format(
        FileName        = fname,
        GenerateTime    = options['date'],
        ScriptName      = options['script_name'],
        IncludeGuard    = inc_guard,
        ClassName       = options['output_file_name'],
        NamespaceBegin  = ns_begin,
        NamespaceEnd    = ns_end,
        TotalParticles  = _safeget(plist, 'maxParticles', 100),
    )

################################################################################
#   Generate C++ implements.
def _gen_cpp_namespace(namespace) :
    if namespace is None or namespace == '':
        return ''
    return namespace if namespace[-2:] == '::' else namespace + '::'

def _gen_cpp_emitter_code(plist) :
    # Gravity Mode.
    if int(plist['emitterType']) == 0 :
        rotation_is_dir = _safeget(plist, 'rotationIsDir', False)
        code = kGravityModeCodeBase.format(
            EmitterType             = 'cocos2d::ParticleSystem::Mode::GRAVITY',
            GravityX                = _safeget(plist, 'gravityx', 0.0),
            GravityY                = _safeget(plist, 'gravityy', 0.0),
            Speed                   = _safeget(plist, 'speed', 0.0),
            SpeedVariance           = _safeget(plist, 'speedVariance', 0.0),
            RadialAcceleration      = _safeget(plist, 'radialAcceleration', 0.0),
            RadialAccelVariance     = _safeget(plist, 'radialAccelVariance', 0.0),
            TangentialAcceleration  = _safeget(plist, 'tangentialAcceleration', 0.0),
            TangentialAccelVariance = _safeget(plist, 'tangentialAccelVariance', 0.0),
            RotationIsDir           = ('true' if rotation_is_dir else 'false'),
        )

    # Radius Mode.
    else:
        code = kRadiusModeCodeBase.format(
            EmitterType             = 'cocos2d::ParticleSystem::Mode::RADIUS',
            MaxRadius               = _safeget(plist, 'maxRadius', 0.0),
            MaxRadiusVariance       = _safeget(plist, 'maxRadiusVariance', 0.0),
            MinRadius               = _safeget(plist, 'minRadius', 0.0),
            MinRadiusVariance       = _safeget(plist, 'minRadiusVariance', 0.0),
            RotatePerSecond         = _safeget(plist, 'rotatePerSecond', 0.0),
            RotatePerSecondVariance = _safeget(plist, 'rotatePerSecondVariance', 0.0),
        )
    return code

def _generate_cpp(plist, options) :
    # gen code parts.
    base = open(kBaseFilePath_CPP, 'r').read()
    fname = options['output_file_name'] + kExtensionForCPP
    header_fname = options['output_file_name'] + kExtensionForHeader

    # generate cpp.
    return base.format(
        # File properties.
        FileName        = fname,
        GenerateTime    = options['date'],
        ScriptName      = options['script_name'],
        ClassName       = options['output_file_name'],
        IncludeHeader   = './' + header_fname,
        Namespace       = _gen_cpp_namespace(options['namespace']),

        # Particle properties.
        TotalParticles              = _safeget(plist, 'maxParticles', 100),
        ConfigName                  = _safeget(plist, 'configName', ''),
        Angle                       = _safeget(plist, 'angle', 0.0),
        AngleVariance               = _safeget(plist, 'angleVariance', 0.0),
        Duration                    = _safeget(plist, 'duration', -1.0),
        BlendFuncSource             = _safeget(plist, 'blendFuncSource', 0.0),
        BlendFuncDestination        = _safeget(plist, 'blendFuncDestination', 0.0),
        StartColorRed               = _safeget(plist, 'startColorRed', 0.0),
        StartColorGreen             = _safeget(plist, 'startColorGreen', 0.0),
        StartColorBlue              = _safeget(plist, 'startColorBlue', 0.0),
        StartColorAlpha             = _safeget(plist, 'startColorAlpha', 0.0),
        StartColorVarianceRed       = _safeget(plist, 'startColorVarianceRed', 0.0),
        StartColorVarianceGreen     = _safeget(plist, 'startColorVarianceGreen', 0.0),
        StartColorVarianceBlue      = _safeget(plist, 'startColorVarianceBlue', 0.0),
        StartColorVarianceAlpha     = _safeget(plist, 'startColorVarianceAlpha', 0.0),
        FinishColorRed              = _safeget(plist, 'finishColorRed', 0.0),
        FinishColorGreen            = _safeget(plist, 'finishColorGreen', 0.0),
        FinishColorBlue             = _safeget(plist, 'finishColorBlue', 0.0),
        FinishColorAlpha            = _safeget(plist, 'finishColorAlpha', 0.0),
        FinishColorVarianceRed      = _safeget(plist, 'finishColorVarianceRed', 0.0),
        FinishColorVarianceGreen    = _safeget(plist, 'finishColorVarianceGreen', 0.0),
        FinishColorVarianceBlue     = _safeget(plist, 'finishColorVarianceBlue', 0.0),
        FinishColorVarianceAlpha    = _safeget(plist, 'finishColorVarianceAlpha', 0.0),
        StartParticleSize           = _safeget(plist, 'startParticleSize', 0.0),
        StartParticleSizeVariance   = _safeget(plist, 'startParticleSizeVariance', 0.0),
        FinishParticleSize          = _safeget(plist, 'finishParticleSize', 0.0),
        FinishParticleSizeVariance  = _safeget(plist, 'finishParticleSizeVariance', 0.0),
        SourcePositionX             = _safeget(plist, 'sourcePositionx', 0.0),
        SourcePositionY             = _safeget(plist, 'sourcePositiony', 0.0),
        SourcePositionVarianceX     = _safeget(plist, 'sourcePositionVariancex', 0.0),
        SourcePositionVarianceY     = _safeget(plist, 'sourcePositionVariancey', 0.0),
        RotationStart               = _safeget(plist, 'rotationStart', 0.0),
        RotationStartVariance       = _safeget(plist, 'rotationStartVariance', 0.0),
        RotationEnd                 = _safeget(plist, 'rotationEnd', 0.0),
        RotationEndVariance         = _safeget(plist, 'rotationEndVariance', 0.0),
        EmitterConfigCodes          = _gen_cpp_emitter_code(plist),
        ParticleLifespan            = _safeget(plist, 'particleLifespan', 0.0),
        ParticleLifespanVariance    = _safeget(plist, 'particleLifespanVariance', 0.0),

        # Texture
        TextureDirectoryPath        = kTextureDirectoryPath,
        TextureFileName             = _safeget(plist, 'textureFileName', ''),
        TextureData                 = _safeget(plist, 'textureImageData', ''),
        YCoordFlipped               = _safeget(plist, 'yCoordFlipped', 1),
    )

################################################################################
#   main.
def generate(plist, options) :
    print 'C++: generate start...'
    output_path = options['output_path']
    path_header = output_path + options['output_file_name'] + kExtensionForHeader
    path_cpp    = output_path + options['output_file_name'] + kExtensionForCPP

    # Generate header.
    header = _generate_header(plist, options)
    print 'C++: succeeded to converted for header.'

    header_file = open(path_header, 'w')
    header_file.write(header)
    header_file.close()
    print 'C++: succeeded to generated header: {0}'.format(path_header)

    # Generate cpp.
    cpp = _generate_cpp(plist, options)
    print 'C++: succeeded to converted for C++ implements.'

    cpp_file = open(path_cpp, 'w')
    cpp_file.write(cpp)
    cpp_file.close()
    print 'C++: succeeded to generated C++ implements: {0}'.format(path_header)

    return True


text:
package lt.keizik.ieva.security;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer;

@Configuration
@EnableAuthorizationServer
public class OAuth2Config extends AuthorizationServerConfigurerAdapter {

	@Autowired
	@Qualifier("userDetailsService")
	private UserDetailsService userDetailsService;

	@Autowired
	private AuthenticationManager authenticationManager;

	@Value("${oauth.tokenTimeout:3600}")
	private int expiration;

	@Bean
	public PasswordEncoder passwordEncoder() {
		return new BCryptPasswordEncoder();
	}

	@Override
	public void configure(AuthorizationServerEndpointsConfigurer configurer) throws Exception {
		configurer.authenticationManager(authenticationManager);
		configurer.userDetailsService(userDetailsService);
	}

	@Override
	public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
		clients.inMemory().withClient("ievablog").secret("ievasecret").accessTokenValiditySeconds(expiration)
				.scopes("read", "write").authorizedGrantTypes("password", "refresh_token").resourceIds("resource");
	}

	@Override
	public void configure(AuthorizationServerSecurityConfigurer oauthServer) throws Exception {
		oauthServer.tokenKeyAccess("permitAll()").checkTokenAccess("isAuthenticated()");
	}
}


text:
package com.amazonaws.services.forecast.model.transform;

import java.util.List;
import javax.annotation.Generated;

import com.amazonaws.SdkClientException;
import com.amazonaws.services.forecast.model.*;

import com.amazonaws.protocol.*;
import com.amazonaws.annotation.SdkInternalApi;

/**
 * EvaluationResultMarshaller
 */
@Generated("com.amazonaws:aws-java-sdk-code-generator")
@SdkInternalApi
public class EvaluationResultMarshaller {

    private static final MarshallingInfo<String> ALGORITHMARN_BINDING = MarshallingInfo.builder(MarshallingType.STRING)
            .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("AlgorithmArn").build();
    private static final MarshallingInfo<List> TESTWINDOWS_BINDING = MarshallingInfo.builder(MarshallingType.LIST).marshallLocation(MarshallLocation.PAYLOAD)
            .marshallLocationName("TestWindows").build();

    private static final EvaluationResultMarshaller instance = new EvaluationResultMarshaller();

    public static EvaluationResultMarshaller getInstance() {
        return instance;
    }

    /**
     * Marshall the given parameter object.
     */
    public void marshall(EvaluationResult evaluationResult, ProtocolMarshaller protocolMarshaller) {

        if (evaluationResult == null) {
            throw new SdkClientException("Invalid argument passed to marshall(...)");
        }

        try {
            protocolMarshaller.marshall(evaluationResult.getAlgorithmArn(), ALGORITHMARN_BINDING);
            protocolMarshaller.marshall(evaluationResult.getTestWindows(), TESTWINDOWS_BINDING);
        } catch (Exception e) {
            throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
        }
    }

}


text:
package gobblin.azkaban;

import java.util.List;
import java.util.Map;
import java.util.Properties;

import org.apache.commons.lang.StringUtils;
import org.apache.hadoop.conf.Configuration;
import org.apache.log4j.Logger;

import azkaban.jobExecutor.AbstractJob;

import com.google.common.base.Strings;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Lists;
import com.google.common.io.Closer;

import gobblin.configuration.ConfigurationKeys;
import gobblin.metrics.Tag;
import gobblin.runtime.EmailNotificationJobListener;
import gobblin.runtime.JobLauncher;
import gobblin.runtime.JobLauncherFactory;
import gobblin.runtime.JobListener;
import gobblin.runtime.util.JobMetrics;

/**
 * A utility class for launching a Gobblin Hadoop MR job through Azkaban.
 *
 * @author ynli
 */
public class AzkabanJobLauncher extends AbstractJob {

  private static final Logger LOG = Logger.getLogger(AzkabanJobLauncher.class);

  private static final String HADOOP_FS_DEFAULT_NAME = "fs.default.name";
  private static final String AZKABAN_LINK_JOBEXEC_URL = "azkaban.link.jobexec.url";
  private static final String HADOOP_TOKEN_FILE_LOCATION = "HADOOP_TOKEN_FILE_LOCATION";
  private static final String MAPREDUCE_JOB_CREDENTIALS_BINARY = "mapreduce.job.credentials.binary";

  private static final ImmutableMap<String, String> PROPERTIES_TO_TAGS_MAP = new ImmutableMap.Builder<String, String>()
      .put("azkaban.flow.projectname", "azkabanProjectName").put("azkaban.flow.flowid", "azkabanFlowId")
      .put("azkaban.job.id", "azkabanJobId").put("azkaban.flow.execid", "azkabanExecId").build();

  private final Closer closer = Closer.create();
  private final JobLauncher jobLauncher;
  private final JobListener jobListener = new EmailNotificationJobListener();

  public AzkabanJobLauncher(String jobId, Properties props)
      throws Exception {
    super(jobId, LOG);

    Properties properties = new Properties();
    properties.putAll(props);
    Configuration conf = new Configuration();

    String fsUri = conf.get(HADOOP_FS_DEFAULT_NAME);
    if (!Strings.isNullOrEmpty(fsUri)) {
      if (!properties.containsKey(ConfigurationKeys.FS_URI_KEY)) {
        properties.setProperty(ConfigurationKeys.FS_URI_KEY, fsUri);
      }
      if (!properties.containsKey(ConfigurationKeys.STATE_STORE_FS_URI_KEY)) {
        properties.setProperty(ConfigurationKeys.STATE_STORE_FS_URI_KEY, fsUri);
      }
    }

    // Set the job tracking URL to point to the Azkaban job execution link URL
    properties.setProperty(
        ConfigurationKeys.JOB_TRACKING_URL_KEY, Strings.nullToEmpty(conf.get(AZKABAN_LINK_JOBEXEC_URL)));

    // Necessary for compatibility with Azkaban's hadoopJava job type
    // http://azkaban.github.io/azkaban/docs/2.5/#hadoopjava-type
    if (System.getenv(HADOOP_TOKEN_FILE_LOCATION) != null) {
      properties.setProperty(MAPREDUCE_JOB_CREDENTIALS_BINARY, System.getenv(HADOOP_TOKEN_FILE_LOCATION));
    }

    JobMetrics.addCustomTagsToProperties(properties, getAzkabanTags());

    // Create a JobLauncher instance depending on the configuration. The same properties object is
    // used for both system and job configuration properties because Azkaban puts configuration
    // properties in the .job file and in the .properties file into the same Properties object.
    this.jobLauncher = this.closer.register(JobLauncherFactory.newJobLauncher(properties, properties));
  }

  private List<Tag<?>> getAzkabanTags() {
    Configuration conf = new Configuration();
    List<Tag<?>> tags = Lists.newArrayList();

    for (Map.Entry<String, String> entry : PROPERTIES_TO_TAGS_MAP.entrySet()) {
      if (StringUtils.isNotBlank(conf.get(entry.getKey()))) {
        tags.add(new Tag<String>(entry.getValue(), conf.get(entry.getKey())));
      } else {
        LOG.warn(String.format("No config value found for azkaban config %s. Metics will not have tag %s", entry.getKey(),
            entry.getValue()));
      }
    }
    return tags;
  }

  @Override
  public void run()
      throws Exception {
    try {
      this.jobLauncher.launchJob(this.jobListener);
    } finally {
      this.closer.close();
    }
  }

  @Override
  public void cancel()
      throws Exception {
    try {
      this.jobLauncher.cancelJob(this.jobListener);
    } finally {
      this.closer.close();
    }
  }
}


text: Off the beaten path Las Vegas Circle Tour


text:
<?php

namespace Booking\Service;

use Zend\ServiceManager\FactoryInterface;
use Zend\ServiceManager\ServiceLocatorInterface;

class BookingServiceFactory implements FactoryInterface
{

    public function createService(ServiceLocatorInterface $sm)
    {
        $notificationListener = $sm->get('Booking\Service\Listener\NotificationListener');

        $bookingService = new BookingService(
            $sm->get('Base\Manager\OptionManager'),
            $sm->get('Booking\Manager\BookingManager'),
            $sm->get('Booking\Manager\Booking\BillManager'),
            $sm->get('Booking\Manager\ReservationManager'),
            $sm->get('Square\Manager\SquarePricingManager'),
            $sm->get('ViewHelperManager'),
            $sm->get('Zend\Db\Adapter\Adapter')->getDriver()->getConnection());

        $eventManager = $bookingService->getEventManager();
        $eventManager->attach($notificationListener);

        return $bookingService;
    }

}


text:
.PHONY: build clean test lint cross

# build the CLI
build: clean
	@go build -o ./build/docker github.com/docker/cli/cmd/docker

# remove build artifacts
clean:
	@rm -rf ./build

# run go test
# the "-tags daemon" part is temporary
test:
	@go test -tags daemon -v $(shell go list ./... | grep -v /vendor/)

# run linters
lint:
	@gometalinter --config gometalinter.json ./...

# build the CLI for multiple architectures
cross: clean
	@gox -output build/docker-{{.OS}}-{{.Arch}} \
		 -osarch="linux/arm linux/amd64 darwin/amd64 windows/amd64" \
		 github.com/docker/cli/cmd/docker

vendor: vendor.conf
	@vndr 2> /dev/null
	@if [ "`git status --porcelain -- vendor 2>/dev/nul`" ]; then \
		echo; echo "vendoring is wrong. These files were changed:"; \
		echo; git status --porcelain -- vendor 2>/dev/nul; \
		echo; exit 1; \
	fi;

ci: cross test


text:
#include <opencv2/opencv.hpp>

#include "v4r/attention_segmentation/AttentionModule.h"
#include "v4r/attention_segmentation/EPUtils.h"

// This program shows the use of WTA to extract attention points
void printUsage(const char *argv0);

void printUsage(const char *argv0)
{
  printf(
    "Extracts attention points using WTA\n"
    "usage: %s image.png saliency.png output.txt output.png useRandom useCentering useMorphologyOpenning\n"
    "  image.png             ... color image\n"
    "  saliency.png          ... saliency image\n"
    "  points.txt            ... output text file with points\n"
    "  points.png            ... output image with points\n"
    "  useRandom             ... 0 -- false; 1 -- true;\n"
    "  useCentering          ... 0 -- false; 1 -- true;\n"
    "  useMorphologyOpenning ... 0 -- false; 1 -- true;\n", argv0);
  printf(" Example: %s 1 image.png saliency.png points.txt points.png 0 0 0\n",argv0);
}

int main(int argc, char** argv)
{
  srand ( time(NULL) );

  if(argc != 8)
  {
    printUsage(argv[0]);
    return(0);
  }

  std::string image_name(argv[1]);
  std::string map_name(argv[2]);
  std::string output_file_name(argv[3]);
  std::string output_png_name(argv[4]);

  int useRandom = atoi(argv[5]);
  int useCentering = atoi(argv[6]);
  int useMorphologyOpenning = atoi(argv[7]);

  // read image
  cv::Mat image = cv::imread(image_name,-1);

  // read saliency map
  cv::Mat saliencyMap = cv::imread(map_name,0);
  saliencyMap.convertTo(saliencyMap,CV_32F,1.0/255);

  v4r::Params wtaParams;
  v4r::defaultParams(wtaParams);
  //modify wta
  wtaParams.useRandom = (useRandom == 0 ? false : true);
  wtaParams.useCentering = (useCentering == 0 ? false : true);
  wtaParams.useMorphologyOpenning = (useMorphologyOpenning == 0 ? false : true);

  std::vector<cv::Point> attentionPoints;
  attentionPoints.clear();
  cv::Mat temp;
  image.copyTo(temp);
  temp.convertTo(temp,CV_32F,1.0/255);
  v4r::CalculateWTA(temp,saliencyMap,attentionPoints,0,wtaParams);

  v4r::writeAttentionPoints(attentionPoints,output_file_name);

  //save image with attantion points
  v4r::drawAttentionPoints(image,attentionPoints,10);

  cv::imwrite(output_png_name,image);
  //cv::waitKey();

  return(0);
}


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

(async function() {
  TestRunner.addResult(`Tests "Show more" button in CallStackSidebarPane.`);
  await TestRunner.loadLegacyModule('sources'); await TestRunner.loadTestModule('sources_test_runner');
  await TestRunner.showPanel('sources');
  await TestRunner.evaluateInPagePromise(`
      function callWithAsyncStack(f, depth) {
        if (depth === 0) {
          f();
          return;
        }
        wrapper = eval('(function call' + depth + '() { callWithAsyncStack(f, depth - 1) }) //# sourceURL=wrapper.js');
        Promise.resolve().then(wrapper);
      }
      function testFunction() {
        callWithAsyncStack(() => {debugger}, 36);
      }
      //# sourceURL=test.js
    `);

  await SourcesTestRunner.startDebuggerTestPromise(/* quiet */ true);
  await SourcesTestRunner.runTestFunctionAndWaitUntilPausedPromise();
  await TestRunner.addSnifferPromise(
      Sources.CallStackSidebarPane.prototype, 'updatedForTest');
  dumpCallStackSidebarPane();

  TestRunner.addResult('\n---------------\nClicks show more..');
  const pane = Sources.CallStackSidebarPane.instance();
  pane.contentElement.querySelector('.show-more-message > .link').click();
  await TestRunner.addSnifferPromise(
      Sources.CallStackSidebarPane.prototype, 'updatedForTest');
  dumpCallStackSidebarPane();
  SourcesTestRunner.completeDebuggerTest();

  function dumpCallStackSidebarPane() {
    const pane = Sources.CallStackSidebarPane.instance();
    for (const element of pane.contentElement.querySelectorAll(
             '.call-frame-item'))
      TestRunner.addResult(element.deepTextContent().replace(/VM\d+/g, 'VM'));
  }
})();


text:
package org.itas.core.dbpool;

import com.jolbox.bonecp.TestCustomThreadFactory;

/**
 * @author Wallace
 *
 */
public class MockThread implements Runnable {

	/** {@inheritDoc}
	 * @see java.lang.Runnable#run()
	 */
//	@Override
	public void run() {
		while(!TestCustomThreadFactory.signalled){
			try {
				Thread.sleep(50);
			} catch (InterruptedException e) {
				// never reached.
			}
		}
		throw new RuntimeException("fake exception");
	}

}


text:
public class NFEAndroidDoS extends Activity {
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_view);

		// BAD: Uncaught NumberFormatException due to remote user inputs
		{
			String minPriceStr = getIntent().getStringExtra("priceMin");
			double minPrice = Double.parseDouble(minPriceStr);
		}

		// GOOD: Use the proper Android method to get number extra
		{
			int width = getIntent().getIntExtra("width", 0);
			int height = getIntent().getIntExtra("height", 0);
		}
	}
}


text:
package tests

import (
	"math"
	"testing"
)

var safeFloat32s = []float32{
	float32(0.0),
	float32(1.0),
	float32(-1.0),
	float32(math.Inf(1)),
	float32(math.Inf(-1)),
}

var allFloat32s = append(safeFloat32s, float32(math.NaN()))

var safeFloat64s = []float64{
	float64(0.0),
	float64(1.0),
	float64(-1.0),
	math.Inf(1),
	math.Inf(-1),
}

var allFloat64s = append(safeFloat64s, math.NaN())

func TestFloat(t *testing.T) {
	runTestCases(t, false, "plain", flatten(
		allFloat32s,
		allFloat64s,
	))
	// See checkEqual for why NaNs are missing.
	runTestCases(t, false, "pointers", pointersTo(flatten(
		safeFloat32s,
		safeFloat64s,
	)))
	runTestCases(t, false, "interfaces", interfacesTo(flatten(
		safeFloat32s,
		safeFloat64s,
	)))
	runTestCases(t, false, "interfacesToPointers", interfacesTo(pointersTo(flatten(
		safeFloat32s,
		safeFloat64s,
	))))
}

const onlyDouble float64 = 1.0000000000000002

func TestFloatTruncation(t *testing.T) {
	runTestCases(t, true, "pass", []any{
		truncatingFloat32{save: onlyDouble},
	})
	runTestCases(t, false, "fail", []any{
		truncatingFloat32{save: 1.0},
	})
}

var safeComplex64s = combine(safeFloat32s, safeFloat32s, func(i, j any) any {
	return complex(i.(float32), j.(float32))
})

var allComplex64s = combine(allFloat32s, allFloat32s, func(i, j any) any {
	return complex(i.(float32), j.(float32))
})

var safeComplex128s = combine(safeFloat64s, safeFloat64s, func(i, j any) any {
	return complex(i.(float64), j.(float64))
})

var allComplex128s = combine(allFloat64s, allFloat64s, func(i, j any) any {
	return complex(i.(float64), j.(float64))
})

func TestComplex(t *testing.T) {
	runTestCases(t, false, "plain", flatten(
		allComplex64s,
		allComplex128s,
	))
	// See TestFloat; same issue.
	runTestCases(t, false, "pointers", pointersTo(flatten(
		safeComplex64s,
		safeComplex128s,
	)))
	runTestCases(t, false, "interfacse", interfacesTo(flatten(
		safeComplex64s,
		safeComplex128s,
	)))
	runTestCases(t, false, "interfacesTo", interfacesTo(pointersTo(flatten(
		safeComplex64s,
		safeComplex128s,
	))))
}

func TestComplexTruncation(t *testing.T) {
	runTestCases(t, true, "pass", []any{
		truncatingComplex64{save: complex(onlyDouble, onlyDouble)},
		truncatingComplex64{save: complex(1.0, onlyDouble)},
		truncatingComplex64{save: complex(onlyDouble, 1.0)},
	})
	runTestCases(t, false, "fail", []any{
		truncatingComplex64{save: complex(1.0, 1.0)},
	})
}


text:
import time
import re
import smtplib
import socket
from email.parser import Parser

import database

EMAIL_SERVER_ADDRESS = '127.0.0.1'
EMAIL_SERVER_PORT = 25

def deliver(mailfrom, rcpttos, data):
	print 'Sending email from: ', mailfrom, ' to: ', rcpttos
	#return

	refused = {}
	try:
		s = smtplib.SMTP(EMAIL_SERVER_ADDRESS, EMAIL_SERVER_PORT, timeout=5)
		#s.set_debuglevel(1)
		try:
			refused = s.sendmail(mailfrom, rcpttos, data)
		finally:
			s.quit()
	except smtplib.SMTPRecipientsRefused, e:
		print 'got SMTPRecipientsRefused'
		refused = e.recipients
	except (socket.error, smtplib.SMTPException), e:
		print 'got', e.__class__
		# All recipients were refused.  If the exception had an associated
		# error code, use it.  Otherwise,fake it with a non-triggering
		# exception code.
		errcode = getattr(e, 'smtp_code', -1)
		errmsg = getattr(e, 'smtp_error', 'ignore')
		for r in rcpttos:
			refused[r] = (errcode, errmsg)
	return refused

def process_mail(dbcon, mail_id, mail):
	#print mail
	cur = con.cursor()
	cur.execute('select * from forwarding_rules')
	rows = cur.fetchall()
	for row in rows:
		pattern = row[1]
		recipient = row[2]
		flags = re.S

		prog = re.compile(pattern, flags)
		result = prog.match(mail)

		if result is not None:
			mailfrom = Parser().parsestr(mail)['from']

			refused = deliver(mailfrom, recipient, mail)
			if not refused:
				cur.execute('update mails set forwarded = 1 where id = ?', (mail_id,))
				dbcon.commit()
	return

def poll(dbcon):
	while True:
		print 'Poll'
		# get unprocessed mails
		cur = dbcon.cursor()
		cur.execute('select * from mails where not forwarded')
		rows = cur.fetchall()
		for row in rows:
			process_mail(dbcon, row[0], row[2])

		time.sleep(5)

if __name__ == "__main__":
	con = None
	try:
		con = database.connect_db()

		poll(con)

	finally:
		if con:
			con.close()


text:
package org.saiku.service.olap.totals.aggregators;

import mondrian.util.Format;
import org.olap4j.Cell;
import org.olap4j.metadata.Measure;
import org.saiku.olap.util.SaikuProperties;

import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

public abstract class TotalAggregator {
  private static final Map<String, TotalAggregator> all;

  static {
    Map<String, TotalAggregator> tmp = new HashMap<String, TotalAggregator>();
    tmp.put( "sum", new SumAggregator( null ) );
    tmp.put( "max", new MaxAggregator( null ) );
    tmp.put( "min", new MinAggregator( null ) );
    tmp.put( "avg", new AvgAggregator( null ) );
    all = Collections.unmodifiableMap( tmp );
  }

  private String formattedValue;
  protected Format format;

  protected TotalAggregator( Format format ) {
    this.format = format;
  }

  public void addData( Cell cell ) {
    try {
      // FIXME - maybe we should try to do fetch the format here, but seems to cause some issues? infinite loop? make
      // sure we try this only once to override existing format?
      //		if (format == null) {
      //			String formatString = (String) cell.getPropertyValue(Property.StandardCellProperty.FORMAT_STRING);
      //			this.format = Format.get(formatString, SaikuProperties.locale);
      //
      //		}
      Object value = cell.getValue();
      if ( value instanceof Number ) {
        double doubleVal;

        doubleVal = cell.getDoubleValue();
        addData( doubleVal );
      }
    } catch ( Exception e ) {
      throw new RuntimeException( e );
    }

  }

  protected abstract void addData( double data );

  public abstract Double getValue();

  public abstract TotalAggregator newInstance( Format format, Measure measure );

  public String getFormattedValue() {
    if ( formattedValue != null ) {
      return formattedValue;
    } else {
      Double value = getValue();
      if ( value != null ) {
        return format.format( value );
      }
      return "";
    }
  }

  public void setFormattedValue( String formattedValue ) {
    this.formattedValue = formattedValue;
  }

  public TotalAggregator newInstance() {
    return newInstance( "" );
  }

  public TotalAggregator newInstance( String formatString ) {
    return newInstance( new Format( formatString, SaikuProperties.locale ), null );
  }

  public static TotalAggregator newInstanceByFunctionName( final String functionName ) {
    return all.get( functionName );
  }
}


text:
import * as Hub from "../../hub";
import { SegmentAction } from "./segment";
export declare class SegmentTrackAction extends SegmentAction {
    name: string;
    label: string;
    iconName: string;
    description: string;
    minimumSupportedLookerVersion: string;
    execute(request: Hub.ActionRequest): Promise<Hub.ActionResponse>;
    form(): Promise<Hub.ActionForm>;
}


text:
<Record>
<Term>Pexantel</Term>
<SemanticType>Pharmacologic Substance</SemanticType>
<ParentTerm>Antihelminthic Agent</ParentTerm>
<ClassificationPath>Chemicals_and_Drugs_Kind/Drug, Food, Chemical or Biomedical Material/Pharmacologic Substance/Anti-Infective Agent/Antiparasitic Agent/Antihelminthic Agent/Pexantel</ClassificationPath>
<BroaderTerm>Antiparasitic Agent</BroaderTerm>
<BroaderTerm>Chemicals_and_Drugs_Kind</BroaderTerm>
<BroaderTerm>Antihelminthic Agent</BroaderTerm>
<BroaderTerm>Pharmacologic Substance</BroaderTerm>
<BroaderTerm>Pexantel</BroaderTerm>
<BroaderTerm>Anti-Infective Agent</BroaderTerm>
<BroaderTerm>Drug, Food, Chemical or Biomedical Material</BroaderTerm>
<Synonym>PEXANTEL</Synonym>
<Synonym>Pexantel</Synonym>
<Source>NCI Thesaurus</Source>
</Record>


text:
from setuptools import setup, find_packages

setup(
    name='django-feedback',
    version=__import__('feedback').__version__,
    description='Basic Django Feedback',
    author='Luke Hutscal',
    author_email='luke@creaturecreative.com',
    url='http://github.com/girasquid/django-feedback/',
    packages=find_packages(),
    classifiers=[
        'Development Status :: 3 - Alpha',
        'Environment :: Web Environment',
        'Intended Audience :: Developers',
        'License :: OSI Approved :: MIT License',
        'Operating System :: OS Independent',
        'Programming Language :: Python',
        'Framework :: Django',
    ],
    include_package_data=True,
    zip_safe=False,
)


text:
package org.apache.hadoop.hive.ql.exec.vector.expressions;

import org.apache.hadoop.hive.ql.exec.vector.BytesColumnVector;
import org.apache.hadoop.hive.ql.exec.vector.ColumnVector;
import org.apache.hadoop.hive.ql.exec.vector.LongColumnVector;
import org.apache.hadoop.hive.ql.exec.vector.TimestampColumnVector;
import org.apache.hadoop.hive.ql.exec.vector.VectorExpressionDescriptor;
import org.apache.hadoop.hive.ql.exec.vector.VectorizedRowBatch;
import org.apache.hadoop.hive.serde2.io.DateWritable;
import org.apache.hadoop.io.Text;

import java.sql.Date;
import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;

public class VectorUDFDateDiffScalarCol extends VectorExpression {
  private static final long serialVersionUID = 1L;

  private int colNum;
  private int outputColumn;
  private long longValue;
  private Timestamp timestampValue = null;
  private byte[] stringValue;
  private transient SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
  private transient final Text text = new Text();
  private int baseDate;
  private transient Date date = new Date(0);

  public VectorUDFDateDiffScalarCol(Object object, int colNum, int outputColumn) {
    super();
    this.colNum = colNum;
    this.outputColumn = outputColumn;

    if (object instanceof Long) {
      this.longValue = (Long) object;
    } else if (object instanceof Timestamp) {
      this.timestampValue = (Timestamp) object;
    } else if (object instanceof byte []) {
      this.stringValue = (byte[]) object;
    } else {
      throw new RuntimeException("Unexpected scalar object " + object.getClass().getName() + " " + object.toString());
    }
  }

  public VectorUDFDateDiffScalarCol() {
    super();
  }

  @Override
  public void evaluate(VectorizedRowBatch batch) {

    if (childExpressions != null) {
      super.evaluateChildren(batch);
    }

    LongColumnVector outV = (LongColumnVector) batch.cols[outputColumn];
    ColumnVector inputCol = batch.cols[this.colNum];
    /* every line below this is identical for evaluateLong & evaluateString */
    final int n = inputCol.isRepeating ? 1 : batch.size;
    int[] sel = batch.selected;
    final boolean selectedInUse = (inputCol.isRepeating == false) && batch.selectedInUse;

    if(batch.size == 0) {
      /* n != batch.size when isRepeating */
      return;
    }

    /* true for all algebraic UDFs with no state */
    outV.isRepeating = inputCol.isRepeating;

    switch (inputTypes[0]) {
      case DATE:
        baseDate = (int) longValue;
        break;

      case TIMESTAMP:
        date.setTime(timestampValue.getTime());
        baseDate = DateWritable.dateToDays(date);
        break;

      case STRING:
      case CHAR:
      case VARCHAR:
        try {
          date.setTime(formatter.parse(new String(stringValue, "UTF-8")).getTime());
          baseDate = DateWritable.dateToDays(date);
          break;
        } catch (Exception e) {
          outV.noNulls = false;
          if (selectedInUse) {
            for(int j=0; j < n; j++) {
              int i = sel[j];
              outV.isNull[i] = true;
            }
          } else {
            for(int i = 0; i < n; i++) {
              outV.isNull[i] = true;
            }
          }
          return;
        }
      default:
        throw new Error("Unsupported input type " + inputTypes[0].name());
    }

    switch (inputTypes[1]) {
      case DATE:
        if (inputCol.noNulls) {
          outV.noNulls = true;
          if (selectedInUse) {
            for(int j=0; j < n; j++) {
              int i = sel[j];
              outV.vector[i] = evaluateDate(inputCol, i);
            }
          } else {
            for(int i = 0; i < n; i++) {
              outV.vector[i] = evaluateDate(inputCol, i);
            }
          }
        } else {
          // Handle case with nulls. Don't do function if the value is null, to save time,
          // because calling the function can be expensive.
          outV.noNulls = false;
          if (selectedInUse) {
            for(int j = 0; j < n; j++) {
              int i = sel[j];
              outV.isNull[i] = inputCol.isNull[i];
              if (!inputCol.isNull[i]) {
                outV.vector[i] = evaluateDate(inputCol, i);
              }
            }
          } else {
            for(int i = 0; i < n; i++) {
              outV.isNull[i] = inputCol.isNull[i];
              if (!inputCol.isNull[i]) {
                outV.vector[i] = evaluateDate(inputCol, i);
              }
            }
          }
        }
        break;

      case TIMESTAMP:
        if (inputCol.noNulls) {
          outV.noNulls = true;
          if (selectedInUse) {
            for(int j=0; j < n; j++) {
              int i = sel[j];
              outV.vector[i] = evaluateTimestamp(inputCol, i);
            }
          } else {
            for(int i = 0; i < n; i++) {
              outV.vector[i] = evaluateTimestamp(inputCol, i);
            }
          }
        } else {
          // Handle case with nulls. Don't do function if the value is null, to save time,
          // because calling the function can be expensive.
          outV.noNulls = false;
          if (selectedInUse) {
            for(int j = 0; j < n; j++) {
              int i = sel[j];
              outV.isNull[i] = inputCol.isNull[i];
              if (!inputCol.isNull[i]) {
                outV.vector[i] = evaluateTimestamp(inputCol, i);
              }
            }
          } else {
            for(int i = 0; i < n; i++) {
              outV.isNull[i] = inputCol.isNull[i];
              if (!inputCol.isNull[i]) {
                outV.vector[i] = evaluateTimestamp(inputCol, i);
              }
            }
          }
        }
        break;

      case STRING:
      case CHAR:
      case VARCHAR:
        if (inputCol.noNulls) {
          outV.noNulls = true;
          if (selectedInUse) {
            for(int j=0; j < n; j++) {
              int i = sel[j];
              evaluateString(inputCol, outV, i);
            }
          } else {
            for(int i = 0; i < n; i++) {
              evaluateString(inputCol, outV, i);
            }
          }
        } else {
          // Handle case with nulls. Don't do function if the value is null, to save time,
          // because calling the function can be expensive.
          outV.noNulls = false;
          if (selectedInUse) {
            for(int j = 0; j < n; j++) {
              int i = sel[j];
              outV.isNull[i] = inputCol.isNull[i];
              if (!inputCol.isNull[i]) {
                evaluateString(inputCol, outV, i);
              }
            }
          } else {
            for(int i = 0; i < n; i++) {
              outV.isNull[i] = inputCol.isNull[i];
              if (!inputCol.isNull[i]) {
                evaluateString(inputCol, outV, i);
              }
            }
          }
        }
        break;
      default:
        throw new Error("Unsupported input type " + inputTypes[1].name());
    }
  }

  protected int evaluateTimestamp(ColumnVector columnVector, int index) {
    TimestampColumnVector tcv = (TimestampColumnVector) columnVector;
    date.setTime(tcv.getTime(index));
    return baseDate - DateWritable.dateToDays(date);
  }

  protected int evaluateDate(ColumnVector columnVector, int index) {
    LongColumnVector lcv = (LongColumnVector) columnVector;
    return baseDate - ((int) lcv.vector[index]);
  }

  protected void evaluateString(ColumnVector columnVector, LongColumnVector output, int i) {
    BytesColumnVector bcv = (BytesColumnVector) columnVector;
    text.set(bcv.vector[i], bcv.start[i], bcv.length[i]);
    try {
      date.setTime(formatter.parse(text.toString()).getTime());
      output.vector[i] = baseDate - DateWritable.dateToDays(date);
    } catch (ParseException e) {
      output.vector[i] = 1;
      output.isNull[i] = true;
    }
  }
  @Override
  public int getOutputColumn() {
    return this.outputColumn;
  }

  @Override
  public String getOutputType() {
    return "long";
  }

  public int getColNum() {
    return colNum;
  }

  public void setColNum(int colNum) {
    this.colNum = colNum;
  }

  public void setOutputColumn(int outputColumn) {
    this.outputColumn = outputColumn;
  }

  public long getLongValue() {
    return longValue;
  }

  public void setLongValue(int longValue) {
    this.longValue = longValue;
  }

  public byte[] getStringValue() {
    return stringValue;
  }

  public void setStringValue(byte[] stringValue) {
    this.stringValue = stringValue;
  }

  @Override
  public String vectorExpressionParameters() {
    return "val " + stringValue + ", col " + colNum;
  }

  @Override
  public VectorExpressionDescriptor.Descriptor getDescriptor() {
    VectorExpressionDescriptor.Builder b = new VectorExpressionDescriptor.Builder();
    b.setMode(VectorExpressionDescriptor.Mode.PROJECTION)
        .setNumArguments(2)
        .setArgumentTypes(
            VectorExpressionDescriptor.ArgumentType.STRING_DATETIME_FAMILY,
            VectorExpressionDescriptor.ArgumentType.STRING_DATETIME_FAMILY)
        .setInputExpressionTypes(
            VectorExpressionDescriptor.InputExpressionType.SCALAR,
            VectorExpressionDescriptor.InputExpressionType.COLUMN);
    return b.build();
  }
}