text:
import os

from toscaparser.common import exception
from toscaparser.substitution_mappings import SubstitutionMappings
from toscaparser.tests.base import TestCase
from toscaparser.topology_template import TopologyTemplate
from toscaparser.tosca_template import ToscaTemplate
from toscaparser.utils.gettextutils import _
import toscaparser.utils.yamlparser

YAML_LOADER = toscaparser.utils.yamlparser.load_yaml

class TopologyTemplateTest(TestCase):

    def setUp(self):
        TestCase.setUp(self)
        '''TOSCA template.'''
        self.tosca_tpl_path = os.path.join(
            os.path.dirname(os.path.abspath(__file__)),
            "data/topology_template/transactionsubsystem.yaml")
        self.tpl = YAML_LOADER(self.tosca_tpl_path)
        self.topo_tpl = self.tpl.get('topology_template')
        self.imports = self.tpl.get('imports')
        self.topo = TopologyTemplate(self.topo_tpl,
                                     self._get_all_custom_def())

    def _get_custom_def(self, type_definition):
        custom_defs = {}
        for definition in self.imports:
            if os.path.isabs(definition):
                def_file = definition
            else:
                tpl_dir = os.path.dirname(os.path.abspath(self.tosca_tpl_path))
                def_file = os.path.join(tpl_dir, definition)
            custom_type = YAML_LOADER(def_file)
            custom_defs.update(custom_type.get(type_definition))
        return custom_defs

    def _get_all_custom_def(self):
        custom_defs = {}
        custom_defs.update(self._get_custom_def('node_types'))
        custom_defs.update(self._get_custom_def('capability_types'))
        return custom_defs

    def _get_custom_types(self):
        custom_types = {}
        def_file = os.path.join(
            os.path.dirname(os.path.abspath(__file__)),
            "data/topology_template/definitions.yaml")
        custom_type = YAML_LOADER(def_file)
        node_types = custom_type['node_types']
        for name in node_types:
            defintion = node_types[name]
            custom_types[name] = defintion
        return custom_types

    def test_description(self):
        expected_desc = 'Template of a database including its hosting stack.'
        self.assertEqual(expected_desc, self.topo.description)

    def test_inputs(self):
        self.assertEqual(
            ['mq_server_ip', 'my_cpus', 'receiver_port'],
            sorted([input.name for input in self.topo.inputs]))

        input_name = "receiver_port"
        expected_description = "Port to be used for receiving messages."
        for input in self.topo.inputs:
            if input.name == input_name:
                self.assertEqual(expected_description, input.description)

    def test_node_tpls(self):
        '''Test nodetemplate names.'''
        self.assertEqual(
            ['app', 'server', 'websrv'],
            sorted([tpl.name for tpl in self.topo.nodetemplates]))

        tpl_name = "app"
        expected_type = "example.SomeApp"
        expected_properties = ['admin_user', 'pool_size']
        expected_capabilities = ['app_endpoint', 'feature', 'message_receiver']
        expected_requirements = [{'host': {'node': 'websrv'}}]
        expected_relationshp = ['tosca.relationships.HostedOn']
        expected_host = ['websrv']
        for tpl in self.topo.nodetemplates:
            if tpl_name == tpl.name:
                '''Test node type.'''
                self.assertEqual(tpl.type, expected_type)

                '''Test properties.'''
                self.assertEqual(
                    expected_properties,
                    sorted(tpl.get_properties().keys()))

                '''Test capabilities.'''
                self.assertEqual(
                    expected_capabilities,
                    sorted(tpl.get_capabilities().keys()))

                '''Test requirements.'''
                self.assertEqual(
                    expected_requirements, tpl.requirements)

                '''Test relationship.'''
                ''' TODO : skip tempororily. need to fix it
                '''
                self.assertEqual(
                    expected_relationshp,
                    [x.type for x in tpl.relationships.keys()])
                self.assertEqual(
                    expected_host,
                    [y.name for y in tpl.relationships.values()])
                '''Test interfaces.'''
                # TODO(hurf) add interface test when new template is available

            if tpl.name == 'server':
                '''Test property value'''
                props = tpl.get_properties()
                if props and 'mem_size' in props.keys():
                    self.assertEqual(props['mem_size'].value, '4096 MB')
                '''Test capability'''
                caps = tpl.get_capabilities()
                self.assertIn('os', caps.keys())
                os_props_objs = None
                os_props = None
                os_type_prop = None
                if caps and 'os' in caps.keys():
                    capability = caps['os']
                    os_props_objs = capability.get_properties_objects()
                    os_props = capability.get_properties()
                    os_type_prop = capability.get_property_value('type')
                    break
                self.assertEqual(
                    ['Linux'],
                    [p.value for p in os_props_objs if p.name == 'type'])
                self.assertEqual(
                    'Linux',
                    os_props['type'].value if 'type' in os_props else '')
                self.assertEqual('Linux', os_props['type'].value)
                self.assertEqual('Linux', os_type_prop)

    def test_outputs(self):
        self.assertEqual(
            sorted(['receiver_ip', 'receiver_port']),
            sorted([output.name for output in self.topo.outputs]))

    def test_groups(self):
        group = self.topo.groups[0]
        self.assertEqual('webserver_group', group.name)
        self.assertEqual(['websrv', 'server'], group.members)
        for node in group.get_member_nodes():
            if node.name == 'server':
                '''Test property value'''
                props = node.get_properties()
                if props and 'mem_size' in props.keys():
                    self.assertEqual(props['mem_size'].value, '4096 MB')

    def test_system_template(self):
        tpl_path = os.path.join(
            os.path.dirname(os.path.abspath(__file__)),
            "data/topology_template/system.yaml")
        system_tosca_template = ToscaTemplate(tpl_path)
        self.assertIsNotNone(system_tosca_template)
        self.assertEqual(
            len(system_tosca_template.
                nested_tosca_templates_with_topology), 4)
        self.assertTrue(system_tosca_template.has_nested_templates())

    def test_invalid_keyname(self):
        tpl_snippet = '''
        substitution_mappings:
          node_type: example.DatabaseSubsystem
          capabilities:
            database_endpoint: [ db_app, database_endpoint ]
          requirements:
            receiver1: [ tran_app, receiver1 ]
          invalid_key: 123
        '''
        sub_mappings = (toscaparser.utils.yamlparser.
                        simple_parse(tpl_snippet))['substitution_mappings']
        expected_message = _(
            'SubstitutionMappings contains unknown field '
            '"invalid_key". Refer to the definition '
            'to verify valid values.')
        err = self.assertRaises(
            exception.UnknownFieldError,
            lambda: SubstitutionMappings(sub_mappings, None, None,
                                         None, None, None))
        self.assertEqual(expected_message, err.__str__())

    def test_missing_required_keyname(self):
        tpl_snippet = '''
        substitution_mappings:
          capabilities:
            database_endpoint: [ db_app, database_endpoint ]
          requirements:
            receiver1: [ tran_app, receiver1 ]
        '''
        sub_mappings = (toscaparser.utils.yamlparser.
                        simple_parse(tpl_snippet))['substitution_mappings']
        expected_message = _('SubstitutionMappings used in topology_template '
                             'is missing required field "node_type".')
        err = self.assertRaises(
            exception.MissingRequiredFieldError,
            lambda: SubstitutionMappings(sub_mappings, None, None,
                                         None, None, None))
        self.assertEqual(expected_message, err.__str__())

    def test_invalid_nodetype(self):
        tpl_snippet = '''
        substitution_mappings:
          node_type: example.DatabaseSubsystem1
          capabilities:
            database_endpoint: [ db_app, database_endpoint ]
          requirements:
            receiver1: [ tran_app, receiver1 ]
        '''
        sub_mappings = (toscaparser.utils.yamlparser.
                        simple_parse(tpl_snippet))['substitution_mappings']
        custom_defs = self._get_custom_types()
        expected_message = _('Node type "example.DatabaseSubsystem1" '
                             'is not a valid type.')
        err = self.assertRaises(
            exception.InvalidNodeTypeError,
            lambda: SubstitutionMappings(sub_mappings, None, None,
                                         None, None, custom_defs))
        self.assertEqual(expected_message, err.__str__())

    def test_system_with_input_validation(self):
        tpl_path0 = os.path.join(
            os.path.dirname(os.path.abspath(__file__)),
            "data/topology_template/validate/system_invalid_input.yaml")
        tpl_path1 = os.path.join(
            os.path.dirname(os.path.abspath(__file__)),
            "data/topology_template/validate/"
            "queuingsubsystem_invalid_input.yaml")
        errormsg = _('SubstitutionMappings with node_type '
                     'example.QueuingSubsystem is missing '
                     'required input definition of input "server_port".')

        # It's invalid in nested template.
        self.assertRaises(exception.ValidationError,
                          lambda: ToscaTemplate(tpl_path0))
        exception.ExceptionCollector.assertExceptionMessage(
            exception.MissingRequiredInputError, errormsg)

        # Subtemplate deploy standaolone is also invalid.
        self.assertRaises(exception.ValidationError,
                          lambda: ToscaTemplate(tpl_path1))
        exception.ExceptionCollector.assertExceptionMessage(
            exception.MissingRequiredInputError, errormsg)

    def test_substitution_mappings_valid_output(self):
        tpl_path = os.path.join(
            os.path.dirname(os.path.abspath(__file__)),
            "data/topology_template/validate/"
            "test_substitution_mappings_valid_output.yaml")
        self.assertIsNotNone(ToscaTemplate(tpl_path))

    def test_system_with_unknown_output_validation(self):
        tpl_path = os.path.join(
            os.path.dirname(os.path.abspath(__file__)),
            "data/topology_template/validate/"
            "test_substitution_mappings_invalid_output.yaml")
        errormsg = _('\'Attribute "my_cpu_output" was not found in node '
                     'template "substitute_app".\'')
        self.assertRaises(exception.ValidationError,
                          lambda: ToscaTemplate(tpl_path))
        exception.ExceptionCollector.assertExceptionMessage(
            KeyError, errormsg)

    def test_invalid_type_policies(self):
        tpl_snippet = '''
        policies:
           some_policy:
              type: tosca.policies.Placement
        '''
        policies = (toscaparser.utils.yamlparser.simple_parse(tpl_snippet))
        custom_defs = self._get_custom_types()
        err = self.assertRaises(exception.TypeMismatchError,
                                lambda: TopologyTemplate(policies,
                                                         custom_defs))
        errormsg = _('policies must be of type "list".')
        self.assertEqual(errormsg, err.__str__())

    def test_invalid_type_groups(self):
        tpl_snippet = '''
        groups:
           - some_group:
              type: tosca.groups.Root
        '''
        policies = (toscaparser.utils.yamlparser.simple_parse(tpl_snippet))
        custom_defs = self._get_custom_types()
        err = self.assertRaises(exception.TypeMismatchError,
                                lambda: TopologyTemplate(policies,
                                                         custom_defs))
        errormsg = _('groups must be of type "dict".')
        self.assertEqual(errormsg, err.__str__())

    def test_invalid_type_substitution_mappings(self):
        tpl_snippet = '''
        substitution_mappings:
           - node_type: MyService
             properties:
               num_cpus: cpus
        '''
        policies = (toscaparser.utils.yamlparser.simple_parse(tpl_snippet))
        custom_defs = self._get_custom_types()
        err = self.assertRaises(exception.TypeMismatchError,
                                lambda: TopologyTemplate(policies,
                                                         custom_defs))
        errormsg = _('substitution_mappings must be of type "dict".')
        self.assertEqual(errormsg, err.__str__())

    def test_invalid_type_outputs(self):
        tpl_snippet = '''
        outputs:
           - some_output:
               value: some_value
        '''
        policies = (toscaparser.utils.yamlparser.simple_parse(tpl_snippet))
        custom_defs = self._get_custom_types()
        err = self.assertRaises(exception.TypeMismatchError,
                                lambda: TopologyTemplate(policies,
                                                         custom_defs))
        errormsg = _('outputs must be of type "dict".')
        self.assertEqual(errormsg, err.__str__())

    def test_invalid_type_relationship_templates(self):
        tpl_snippet = '''
        relationship_templates:
           - my_connection:
                type: ConnectsTo
        '''
        policies = (toscaparser.utils.yamlparser.simple_parse(tpl_snippet))
        custom_defs = self._get_custom_types()
        err = self.assertRaises(exception.TypeMismatchError,
                                lambda: TopologyTemplate(policies,
                                                         custom_defs))
        errormsg = _('relationship_templates must be of type "dict".')
        self.assertEqual(errormsg, err.__str__())

    def test_invalid_type_nodetemplates(self):
        tpl_snippet = '''
        node_templates:
           - some_node:
               type: tosca.nodes.Compute
        '''
        policies = (toscaparser.utils.yamlparser.simple_parse(tpl_snippet))
        custom_defs = self._get_custom_types()
        err = self.assertRaises(exception.TypeMismatchError,
                                lambda: TopologyTemplate(policies,
                                                         custom_defs))
        errormsg = _('node_templates must be of type "dict".')
        self.assertEqual(errormsg, err.__str__())

    def test_invalid_type_inputs(self):
        tpl_snippet = '''
        inputs:
           - some_input:
               type: integer
               value: 1
        '''
        policies = (toscaparser.utils.yamlparser.simple_parse(tpl_snippet))
        custom_defs = self._get_custom_types()
        err = self.assertRaises(exception.TypeMismatchError,
                                lambda: TopologyTemplate(policies,
                                                         custom_defs))
        errormsg = _('inputs must be of type "dict".')
        self.assertEqual(errormsg, err.__str__())


text:
'use strict';

angular.module('mean.meis')
.directive('thumbnailsrow', function() {
    return {
	restrict: 'E',
	templateUrl: 'meis/directives/thumbnails.html',
	link: function () {
	    console.log('link');
	}
    };
});

redpajama_set_name: RedPajamaGithub


text:
var path = require('path');
var webpack = require('webpack');

var isProduction = !!(process.argv.filter(function(a) { return a === '-p';})).length;

var plugins = [];

if (isProduction) {
  plugins.push(new webpack.DefinePlugin({
    'process.env': {
      'NODE_ENV': JSON.stringify('production')
    }
  }));
  plugins.push(new webpack.optimize.UglifyJsPlugin({
    compress: {
      warnings: false
    }
  }));
}

var APP_DIR = path.resolve(__dirname, 'app');
var OUT_DIR = path.resolve(__dirname, 'public');

module.exports = {
  entry: APP_DIR + '/main',
  output: {
    path: OUT_DIR,
    filename: 'bundle.js'
  },
  resolve: {
    extensions: ['', '.js', '.jsx']
  },
  module: {
    loaders: [
      {
        test: /\.jsx?$/,
        include: APP_DIR,
        loader: 'babel-loader'
      }
    ]
  },
  devtool: 'source-map',
  plugins: plugins
};


text:
package io.ruoyan.pxnavigator.ui.activity;

import android.os.Bundle;
import android.support.design.widget.TabLayout;
import android.support.v4.app.FragmentManager;
import android.support.v4.view.ViewPager;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;

import com.afollestad.materialdialogs.MaterialDialog;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.SupportMapFragment;

import butterknife.InjectView;
import io.ruoyan.pxnavigator.R;
import io.ruoyan.pxnavigator.ui.adapter.FeedPagerAdapter;
import io.ruoyan.pxnavigator.utils.BasicUtils;
import io.ruoyan.pxnavigator.helper.DayHelper;
import io.ruoyan.pxnavigator.helper.MapHelper;

/**
 * Created by ruoyan on 12/20/15.
 */
public class MainActivity extends BaseDrawerActivity {

    @InjectView(R.id.photoCategoryTab)
    TabLayout mPhotoCategoryTab;

    @InjectView(R.id.photoViewPager)
    ViewPager mPhotoViewPager;

    private int mFeedDay = 0;
    private FeedPagerAdapter mFeedPagerAdapter;
    private boolean mPendingAnimation;

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

        if (savedInstanceState == null)
            mPendingAnimation = true;

        setupTabs();
        initializeMap();

        FragmentManager fragmentManager = getSupportFragmentManager();
        mFeedPagerAdapter = new FeedPagerAdapter(fragmentManager);
        mPhotoViewPager.setAdapter(mFeedPagerAdapter);
        mPhotoViewPager.setOffscreenPageLimit(3);
        TabLayout.OnTabSelectedListener tabSelectedListener = new TabLayout
                .OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                int position = tab.getPosition();
                mPhotoViewPager.setCurrentItem(position);
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {

            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {

            }
        };
        mPhotoCategoryTab.setOnTabSelectedListener(tabSelectedListener);
        mPhotoViewPager.addOnPageChangeListener
                (new TabLayout.TabLayoutOnPageChangeListener(mPhotoCategoryTab));
        tabSelectedListener.onTabSelected(mPhotoCategoryTab.getTabAt(0));

    }

    private void setupTabs() {
        mPhotoCategoryTab.addTab(mPhotoCategoryTab.newTab().setIcon(R.drawable.ic_place_white));
        mPhotoCategoryTab.addTab(mPhotoCategoryTab.newTab().setIcon(R.drawable.ic_tab_city));
        mPhotoCategoryTab.addTab(mPhotoCategoryTab.newTab().setIcon(R.drawable.ic_tab_landscape));
        mPhotoCategoryTab.addTab(mPhotoCategoryTab.newTab().setIcon(R.drawable.ic_tab_people));
    }

    private void initializeMap() {
        GoogleMap map = ((SupportMapFragment) getSupportFragmentManager().
                findFragmentById(R.id.mapFragment)).getMap();
        MapHelper.setupGoogleMap(map);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        super.onCreateOptionsMenu(menu);
        if (mPendingAnimation) {
            mPendingAnimation = false;
            startIntroAnimation();
        }
        return true;
    }

    private void startIntroAnimation() {
        int actionbarSize = BasicUtils.dpToPx(56);
        getToolbar().setTranslationY(-actionbarSize);
        getIvLogo().setTranslationY(-actionbarSize);

        getToolbar().animate().translationY(0).setDuration(300);
        getIvLogo().animate().translationY(0).setDuration(300).setStartDelay(500).start();

    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == R.id.action_day_selection)
            showDaySelectionDialog();

        return super.onOptionsItemSelected(item);
    }

    private void showDaySelectionDialog() {
        new MaterialDialog.Builder(this)
                .title(R.string.day_selection_dialog_title)
                .items(R.array.day_selection_options)
                .itemsCallbackSingleChoice(mFeedDay, new MaterialDialog.ListCallbackSingleChoice() {
                    @Override
                    public boolean onSelection(MaterialDialog dialog, View view, int which, CharSequence text) {
                        int oldDay = mFeedDay;
                        mFeedDay = which;
                        if (oldDay != mFeedDay)
                            replaceFeed();
                        switch (mFeedDay) {
                            case 0:
                                getDayMenuItem().setIcon(R.drawable.ic_toolbar_today);
                                break;
                            case 1:
                                getDayMenuItem().setIcon(R.drawable.ic_toolbar_day3);
                                break;
                            case 2:
                                getDayMenuItem().setIcon(R.drawable.ic_toolbar_week);
                        }
                        return true;
                    }
                })
                .positiveText(R.string.choose_label)
                .show();
    }

    private void replaceFeed() {
        DayHelper.instance().setDay(mFeedDay);
        int currentPosition = mPhotoViewPager.getCurrentItem();
        mPhotoViewPager.setAdapter(mFeedPagerAdapter); //refresh current page
        if (currentPosition != 0)
            mPhotoViewPager.setCurrentItem(currentPosition);
        else {
            mPhotoViewPager.setCurrentItem(1); //this is a workaround for the bug that
            // setCurrentItem(0) does not work
        }
    }

    @Override
    protected void refreshFeed() {
        super.refreshFeed();
        replaceFeed();
    }
}


text:
import _ from "lodash";

import { ConfidenceLevel, DetectedDetails, TypeProperty } from "../types";
import { PlaceDetector } from "./detect_place";

test("placeTypesAndProperties", () => {
  const det = new PlaceDetector();
  const expected = new Set<TypeProperty>([
    {
      dcType: { dcid: "GeoCoordinates", displayName: "Geo Coordinates" },
      dcProperty: { dcid: "longitude", displayName: "Longitude" },
    },
    {
      dcType: { dcid: "GeoCoordinates", displayName: "Geo Coordinates" },
      dcProperty: { dcid: "latitude", displayName: "Latitude" },
    },
    {
      dcType: { dcid: "GeoCoordinates", displayName: "Geo Coordinates" },
      dcProperty: { dcid: "name", displayName: "Name" },
    },
    {
      dcType: { dcid: "Country", displayName: "Country" },
      dcProperty: { dcid: "name", displayName: "Name" },
    },
    {
      dcType: { dcid: "Country", displayName: "Country" },
      dcProperty: { dcid: "isoCode", displayName: "ISO Code" },
    },
    {
      dcType: { dcid: "Country", displayName: "Country" },
      dcProperty: { dcid: "countryAlpha3Code", displayName: "Alpha 3 Code" },
    },
    {
      dcType: { dcid: "Country", displayName: "Country" },
      dcProperty: { dcid: "countryNumericCode", displayName: "Numeric Code" },
    },
    {
      dcType: { dcid: "State", displayName: "State" },
      dcProperty: { dcid: "name", displayName: "Name" },
    },
    {
      dcType: { dcid: "State", displayName: "State" },
      dcProperty: { dcid: "isoCode", displayName: "ISO Code" },
    },
    {
      dcType: { dcid: "State", displayName: "State" },
      dcProperty: {
        dcid: "fips52AlphaCode",
        displayName: "US State Alpha Code",
      },
    },
    {
      dcType: { dcid: "State", displayName: "State" },
      dcProperty: {
        dcid: "geoId",
        displayName: "FIPS Code",
      },
    },
    {
      dcType: { dcid: "Province", displayName: "Province" },
      dcProperty: { dcid: "name", displayName: "Name" },
    },
    {
      dcType: { dcid: "Municipality", displayName: "Municipality" },
      dcProperty: { dcid: "name", displayName: "Name" },
    },
    {
      dcType: { dcid: "County", displayName: "County" },
      dcProperty: { dcid: "name", displayName: "Name" },
    },
    {
      dcType: { dcid: "City", displayName: "City" },
      dcProperty: { dcid: "name", displayName: "Name" },
    },
  ]);
  expect(det.placeTypesAndProperties).toEqual(expected);
});

test("supportedPlaceTypeProperties", () => {
  const det = new PlaceDetector();
  const expected = new Set<TypeProperty>([
    {
      dcType: { dcid: "Country", displayName: "Country" },
      dcProperty: { dcid: "name", displayName: "Name" },
    },
    {
      dcType: { dcid: "Country", displayName: "Country" },
      dcProperty: { dcid: "isoCode", displayName: "ISO Code" },
    },
    {
      dcType: { dcid: "Country", displayName: "Country" },
      dcProperty: { dcid: "countryAlpha3Code", displayName: "Alpha 3 Code" },
    },
    {
      dcType: { dcid: "Country", displayName: "Country" },
      dcProperty: { dcid: "countryNumericCode", displayName: "Numeric Code" },
    },
    {
      dcType: { dcid: "State", displayName: "State" },
      dcProperty: { dcid: "name", displayName: "Name" },
    },
    {
      dcType: { dcid: "State", displayName: "State" },
      dcProperty: { dcid: "isoCode", displayName: "ISO Code" },
    },
    {
      dcType: { dcid: "State", displayName: "State" },
      dcProperty: {
        dcid: "fips52AlphaCode",
        displayName: "US State Alpha Code",
      },
    },
    {
      dcType: { dcid: "State", displayName: "State" },
      dcProperty: { dcid: "geoId", displayName: "FIPS Code" },
    },
  ]);
  expect(det.getSupportedPlaceTypesAndProperties()).toEqual(expected);
});

test("placeDetectionKeys", () => {
  const expected = new Set<string>([
    "longitude",
    "latitude",
    "latlon",
    "geocoordinates",
    "country",
    "state",
    "province",
    "municipality",
    "county",
    "city",
  ]);
  const got = new Set(PlaceDetector.columnToTypePropertyMapping.keys());
  expect(got).toEqual(expected);
});

test("countries", () => {
  const det = new PlaceDetector();
  const numCountriesExpected = 271;
  const numIsoCodes = 247; // 24 countries without ISO codes.
  const numAbbrv3Codes = 246; // 25 countries without 3-letter abbreviations.
  const numNumeric = 246; // 25 countries without numeric codes.
  expect(det.countryNames.size).toEqual(numCountriesExpected);
  expect(det.countryISO.size).toEqual(numIsoCodes);
  expect(det.countryAbbrv3.size).toEqual(numAbbrv3Codes);
  expect(det.countryNumeric.size).toEqual(numNumeric);

  // Some other random spot checks.
  // Norway.
  expect(det.countryNames).toContain("norway");
  expect(det.countryISO).toContain("no");
  expect(det.countryAbbrv3).toContain("nor");
  expect(det.countryNumeric).toContain("578"); // Senegal.

  expect(det.countryNames).toContain("senegal");
  expect(det.countryISO).toContain("sn");
  expect(det.countryAbbrv3).toContain("sen");
  expect(det.countryNumeric).toContain("686"); // Other checks.

  expect(det.countryNames).not.toContain("");
  expect(det.countryNames).not.toContain(null);

  expect(det.countryISO).not.toContain("");
  expect(det.countryISO).not.toContain(null);

  expect(det.countryAbbrv3).not.toContain("");
  expect(det.countryAbbrv3).not.toContain(null);

  expect(det.countryNumeric).not.toContain("");
  expect(det.countryNumeric).not.toContain(null);
  expect(det.countryNumeric).not.toContain(0);
});

test("States", () => {
  const det = new PlaceDetector();
  const numStatesExpected = 89; // US and India.
  const numIsoCodes = 89; // US and India.
  const numFips52AlphaCodes = 52; // US only.
  const numFipsCodes = 52; // US only.

  expect(det.stateNames.size).toEqual(numStatesExpected);
  expect(det.stateISO.size).toEqual(numIsoCodes);
  expect(det.stateFipsAlpha.size).toEqual(numFips52AlphaCodes);
  expect(det.stateFipsCode.size).toEqual(numFipsCodes);

  // Some random checks.
  // California.
  expect(det.stateNames).toContain("california");
  expect(det.stateISO).toContain("us-ca");
  expect(det.stateFipsAlpha).toContain("ca");
  expect(det.stateFipsCode).toContain("06");

  // New York.
  expect(det.stateNames).toContain("newyork");
  expect(det.stateNames).toContain("newyork");
  expect(det.stateISO).toContain("us-ny");
  expect(det.stateFipsAlpha).toContain("ny");
  expect(det.stateFipsCode).toContain("36");

  // Texas.
  expect(det.stateNames).toContain("texas");
  expect(det.stateISO).toContain("us-tx");
  expect(det.stateFipsAlpha).toContain("tx");
  expect(det.stateFipsCode).toContain("48");

  // Haryana (India).
  expect(det.stateNames).toContain("haryana");
  expect(det.stateISO).toContain("in-hr");
});

test("placeLowConfidenceDetection", () => {
  const det = new PlaceDetector();

  expect(det.detectLowConfidence("")).toBe(null);
  expect(det.detectLowConfidence(" ")).toBe(null);
  expect(det.detectLowConfidence("continent")).toBe(null);

  const countryType = { dcType: { dcid: "Country", displayName: "Country" } };
  const stateType = { dcType: { dcid: "State", displayName: "State" } };
  const countyType = { dcType: { dcid: "County", displayName: "County" } };
  const cityType = { dcType: { dcid: "City", displayName: "City" } };

  expect(_.isEqual(det.detectLowConfidence("Country.."), countryType)).toBe(
    true
  );
  expect(_.isEqual(det.detectLowConfidence("Country"), countryType)).toBe(true);
  expect(_.isEqual(det.detectLowConfidence("cOuntry"), countryType)).toBe(true);
  expect(_.isEqual(det.detectLowConfidence("COUNTRY"), countryType)).toBe(true);
  expect(_.isEqual(det.detectLowConfidence("State  "), stateType)).toBe(true);
  expect(_.isEqual(det.detectLowConfidence("County---"), countyType)).toBe(
    true
  );
  expect(_.isEqual(det.detectLowConfidence("city"), cityType)).toBe(true);

  const geoType = {
    dcType: { dcid: "GeoCoordinates", displayName: "Geo Coordinates" },
  };
  expect(_.isEqual(det.detectLowConfidence("Lat-Lon"), geoType)).toBe(true);
  expect(_.isEqual(det.detectLowConfidence("Lat,Lon"), geoType)).toBe(true);
  expect(_.isEqual(det.detectLowConfidence("LatLon"), geoType)).toBe(true);
  expect(_.isEqual(det.detectLowConfidence("Geo-coordinates"), geoType)).toBe(
    true
  );
  expect(_.isEqual(det.detectLowConfidence("Geo Coordinates"), geoType)).toBe(
    true
  );
  expect(_.isEqual(det.detectLowConfidence("GeoCoordinates"), geoType)).toBe(
    true
  );
  expect(_.isEqual(det.detectLowConfidence("longitude()()"), geoType)).toBe(
    true
  );
  expect(_.isEqual(det.detectLowConfidence("Latitude=#$#$%"), geoType)).toBe(
    true
  );
});

test("detectionLowConf", () => {
  const det = new PlaceDetector();

  expect(det.detect("randomColName", ["1", "2", "3"])).toBe(null);
  expect(det.detect("", [])).toBe(null);

  const expected: DetectedDetails = {
    detectedTypeProperty: { dcType: { dcid: "City", displayName: "City" } },
    confidence: ConfidenceLevel.Low,
  };
  const notExpected: DetectedDetails = {
    detectedTypeProperty: { dcType: { dcid: "City", displayName: "City" } },
    confidence: ConfidenceLevel.High, // should be Low.
  };

  // Should return low confidence detection of a city.
  const got = det.detect("city", ["a", "b", "c"]);

  expect(_.isEqual(expected, got)).toBe(true);
  expect(_.isEqual(notExpected, got)).toBe(false);
});

test("countryHighConf", () => {
  const det = new PlaceDetector();
  const cases: {
    name: string;
    colArray: Array<string>;
    expected: TypeProperty;
  }[] = [
    {
      name: "name-detection",
      colArray: [
        "United states",
        "Norway",
        "sri lanka",
        "new zealand",
        "south africa",
        "australia",
        "Pakistan",
        "India",
        "bangladesh",
        "french Afars and Issas",
      ],
      expected: {
        dcType: { dcid: "Country", displayName: "Country" },
        dcProperty: { dcid: "name", displayName: "Name" },
      },
    },
    {
      name: "iso-detection",
      colArray: ["us", "no", "lk", "nz", "sa", "au", "pk", "in", "bd", "it"],
      expected: {
        dcType: { dcid: "Country", displayName: "Country" },
        dcProperty: { dcid: "isoCode", displayName: "ISO Code" },
      },
    },
    {
      name: "alpha3-detection",
      colArray: [
        "usa",
        "NOR",
        "lka",
        "nzl",
        "zaf",
        "aus",
        "pak",
        "ind",
        "bgd",
        "ita",
      ],
      expected: {
        dcType: { dcid: "Country", displayName: "Country" },
        dcProperty: {
          dcid: "countryAlpha3Code",
          displayName: "Alpha 3 Code",
        },
      },
    },
    {
      name: "numeric-detection",
      colArray: [
        "840",
        "578",
        "144",
        "554",
        "710",
        "36",
        "586",
        "356",
        "50",
        "380",
      ],
      expected: {
        dcType: { dcid: "Country", displayName: "Country" },
        dcProperty: {
          dcid: "countryNumericCode",
          displayName: "Numeric Code",
        },
      },
    },
    {
      name: "numeric-detection-with-null",
      colArray: [
        "840",
        "578",
        "144",
        "554",
        "710",
        "36",
        "586",
        null,
        null,
        null,
      ],
      expected: {
        dcType: { dcid: "Country", displayName: "Country" },
        dcProperty: {
          dcid: "countryNumericCode",
          displayName: "Numeric Code",
        },
      },
    },
    {
      name: "name-no-detection", // No detection. Too many non names.
      colArray: [
        "United statesssss",
        "Norwayyyy",
        "sri lankawwww",
        "new zealandiiiiii",
        "north africaaaaaaaaa",
        "australiayyyyy",
        "Pakistanyyyyyy",
        "Indiannnnnn",
        "bangladesh",
        "french Afars and Issas",
      ],
      expected: null,
    },
    {
      name: "iso-no-detection", // No detection. Too many non-ISO codes.
      colArray: ["aa", "dd", "ff", "ww", "xx", "yy", "uu", "bd", "it"],
      expected: null,
    },
    {
      name: "alpha3-no-detection", // No detection. Too many non-Alpha3 codes.
      colArray: [
        "aaa",
        "bbb",
        "ccc",
        "ddd",
        "zzz",
        "yyy",
        "xxx",
        "ind",
        "bgd",
        "ita",
      ],
      expected: null,
    },
    {
      name: "numeric-no-detection", // No detection. Too many non-numeric codes.
      colArray: ["0", "1", "2", "-1", "-2", "-3", "-4", "-5", "50", "380"],
      expected: null,
    },
  ];
  for (const c of cases) {
    if (c.expected == null) {
      expect(det.detect("", c.colArray)).toBe(null);
      continue;
    }
    expect(det.detect("country", c.colArray)).toStrictEqual({
      detectedTypeProperty: c.expected,
      confidence: ConfidenceLevel.High,
    });
  }
});

test("stateHighConf", () => {
  const det = new PlaceDetector();
  const cases: {
    name: string;
    colArray: Array<string>;
    expected: TypeProperty;
  }[] = [
    {
      name: "name-detection",
      colArray: [
        "california",
        "new york",
        "massahusetts",
        "new hampshire",
        "south dakota",
        "north dakota",
        "washington",
        "puerto rico",
        "michigan",
        "idaho",
      ],
      expected: {
        dcType: { dcid: "State", displayName: "State" },
        dcProperty: { dcid: "name", displayName: "Name" },
      },
    },
    {
      name: "iso-detection",
      colArray: [
        "US-CA",
        "US-NY",
        "US-MA",
        "US-NH",
        "US-SD",
        "US-ND",
        "US-WA",
        "US-PR",
        "US-MI",
        "US-ID",
      ],
      expected: {
        dcType: { dcid: "State", displayName: "State" },
        dcProperty: { dcid: "isoCode", displayName: "ISO Code" },
      },
    },
    {
      name: "fips52AlphaCode",
      colArray: ["nm", "ny", "wy", "nj", "ct", "nd", "nh", "wa", "fl"],
      expected: {
        dcType: { dcid: "State", displayName: "State" },
        dcProperty: {
          dcid: "fips52AlphaCode",
          displayName: "US State Alpha Code",
        },
      },
    },
    {
      name: "fipsCode",
      colArray: ["01", "02", "04", "48", "49", "50", "36", "28", "30"],
      expected: {
        dcType: { dcid: "State", displayName: "State" },
        dcProperty: {
          dcid: "geoId",
          displayName: "FIPS Code",
        },
      },
    },
    {
      name: "fips52AlphaCode-detection-with-null",
      colArray: ["nm", "ny", "wy", "nj", "ct", "nd", "nh", "wa", "fl", null],
      expected: {
        dcType: { dcid: "State", displayName: "State" },
        dcProperty: {
          dcid: "fips52AlphaCode",
          displayName: "US State Alpha Code",
        },
      },
    },
    {
      name: "iso-no-detection", // No detection due to too many non-ISO codes.
      colArray: [
        "US-AA",
        "US-BB",
        "US-CC",
        "US-DD",
        "US-EE",
        "US-FF",
        "US-RR",
        "US-KK",
        "US-MI",
        "US-ID",
      ],
      expected: null,
    },
  ];
  for (const c of cases) {
    if (c.expected == null) {
      expect(det.detect("", c.colArray)).toBe(null);
      continue;
    }
    expect(det.detect("state in col header", c.colArray)).toStrictEqual({
      detectedTypeProperty: c.expected,
      confidence: ConfidenceLevel.High,
    });
  }
});

test("placeDetection", () => {
  const det = new PlaceDetector();
  const colName = "country";

  // High Conf. State Detection.
  let colArray = ["US-CA", "US-WA", "US-PA"];
  let expectedHighConf = {
    detectedTypeProperty: {
      dcType: { dcid: "State", displayName: "State" },
      dcProperty: {
        dcid: "isoCode",
        displayName: "ISO Code",
      },
    },
    confidence: ConfidenceLevel.High,
  };
  expect(det.detect(colName, colArray)).toStrictEqual(expectedHighConf);

  // High Conf. Country Detection.
  colArray = ["USA", "NOR", "ITA"];
  expectedHighConf = {
    detectedTypeProperty: {
      dcType: { dcid: "Country", displayName: "Country" },
      dcProperty: { dcid: "countryAlpha3Code", displayName: "Alpha 3 Code" },
    },
    confidence: ConfidenceLevel.High,
  };

  expect(det.detect(colName, colArray)).toStrictEqual(expectedHighConf);

  // Modifying colArray to ensure country cannot be detected with high conf.
  // But it should be a low confidence detection due to the colName.
  colArray[0] = "randomString";
  colArray[1] = "randomString";
  const expectedLowConf = {
    detectedTypeProperty: {
      dcType: { dcid: "Country", displayName: "Country" },
    },
    confidence: ConfidenceLevel.Low,
  };
  expect(det.detect(colName, colArray)).toStrictEqual(expectedLowConf);

  // Now, use a column name which is not found to result in no detection.
  expect(det.detect("", colArray)).toStrictEqual(null);
});

test("countryNumericVsStateFIPS", () => {
  const det = new PlaceDetector();

  // Column has values which can be Numeric Codes for countries or
  // FIPS codes for US States.
  const colArray = ["36", "40", "50", "60"];

  // If the column header is no helpful information, detection should give
  // preference to Country.
  let header = "nothing helpful";
  let expectedHighConf = {
    detectedTypeProperty: {
      dcType: { dcid: "Country", displayName: "Country" },
      dcProperty: {
        dcid: "countryNumericCode",
        displayName: "Numeric Code",
      },
    },
    confidence: ConfidenceLevel.High,
  };
  expect(det.detect(header, colArray)).toStrictEqual(expectedHighConf);

  // If the column header contains "country", detection should still give
  // preference to Country.
  header = "something that has country in it";
  expect(det.detect(header, colArray)).toStrictEqual(expectedHighConf);

  // If the column header contains "state", detection should give preference to
  // US State.
  header = "Something with State in it";
  expectedHighConf = {
    detectedTypeProperty: {
      dcType: { dcid: "State", displayName: "State" },
      dcProperty: {
        dcid: "geoId",
        displayName: "FIPS Code",
      },
    },
    confidence: ConfidenceLevel.High,
  };
  expect(det.detect(header, colArray)).toStrictEqual(expectedHighConf);
});


text: -uxwrite-paragraph-style = p.Something


text:
package mpicbg.imglib.container.dynamic;

import mpicbg.imglib.container.basictypecontainer.BitAccess;

public class BitDynamicContainerAccessor extends DynamicContainerAccessor implements BitAccess
{
	final BitDynamicContainer<?> container;

	public BitDynamicContainerAccessor( BitDynamicContainer<?> container, final int entitiesPerPixel )
	{
		super( entitiesPerPixel );

		this.container = container;
	}

	@Override
	public void close() {}

	@Override
	public boolean getValue( final int index )
	{
		final int realIndex = currentIndex + index;

		final int arrayIndex = realIndex / BitDynamicContainer.bitsPerEntity;
		final int arrayOffset = realIndex % BitDynamicContainer.bitsPerEntity;

		final int entry = container.data.get( arrayIndex );
		final int value = (entry & ( 1 << arrayOffset ) );

		return value != 0;
	}

	@Override
	public void setValue( final int index, final boolean value )
	{
		final int realIndex = currentIndex + index;

		final int arrayIndex = realIndex / BitDynamicContainer.bitsPerEntity;
		final int arrayOffset = realIndex % BitDynamicContainer.bitsPerEntity;

		if ( value )
			container.data.set( arrayIndex, container.data.get( arrayIndex ) | ( 1 << arrayOffset ) );
		else
			container.data.set( arrayIndex, container.data.get( arrayIndex ) & ~( 1 << arrayOffset ) );
	}
}


text:
'use strict';

var SpikeArrest = require('../memory');
var expressServer = require('./expressserver');
var verifySpikeArrest = require('./verifySpikeArrest');

describe('SpikeArrest Middleware', function() {

  describe('Express', function() {
    var options = {
      timeUnit: 'minute',
      allow: 1
    };
    var spikeArrest = SpikeArrest.create(options);
    var server = expressServer(spikeArrest);
    verifySpikeArrest.verify(server);
  });

});


text:
package org.apache.calcite.rel.core;

import org.apache.calcite.linq4j.Ord;
import org.apache.calcite.plan.RelOptCluster;
import org.apache.calcite.plan.RelOptCost;
import org.apache.calcite.plan.RelOptPlanner;
import org.apache.calcite.plan.RelTraitSet;
import org.apache.calcite.rel.RelCollation;
import org.apache.calcite.rel.RelCollations;
import org.apache.calcite.rel.RelFieldCollation;
import org.apache.calcite.rel.RelNode;
import org.apache.calcite.rel.RelWriter;
import org.apache.calcite.rel.SingleRel;
import org.apache.calcite.rel.metadata.RelMetadataQuery;
import org.apache.calcite.rel.type.RelDataType;
import org.apache.calcite.rex.RexCall;
import org.apache.calcite.rex.RexChecker;
import org.apache.calcite.rex.RexFieldCollation;
import org.apache.calcite.rex.RexLiteral;
import org.apache.calcite.rex.RexLocalRef;
import org.apache.calcite.rex.RexNode;
import org.apache.calcite.rex.RexSlot;
import org.apache.calcite.rex.RexWindowBound;
import org.apache.calcite.sql.SqlAggFunction;
import org.apache.calcite.util.ImmutableBitSet;
import org.apache.calcite.util.ImmutableIntList;
import org.apache.calcite.util.Litmus;
import org.apache.calcite.util.Util;

import com.google.common.collect.ImmutableList;

import java.util.AbstractList;
import java.util.List;

/**
 * A relational expression representing a set of window aggregates.
 *
 *
A Window can handle several window aggregate functions, over several
 * partitions, with pre- and post-expressions, and an optional post-filter.
 * Each of the partitions is defined by a partition key (zero or more columns)
 * and a range (logical or physical). The partitions expect the data to be
 * sorted correctly on input to the relational expression.
 *
 *
Each {@link Window.Group} has a set of
 * {@link org.apache.calcite.rex.RexOver} objects.
 *
 *
Created by {@link org.apache.calcite.rel.rules.ProjectToWindowRule}.
 */
public abstract class Window extends SingleRel {
  public final ImmutableList<Group> groups;
  public final ImmutableList<RexLiteral> constants;

  /**
   * Creates a window relational expression.
   *
   * @param cluster Cluster
   * @param traitSet Trait set
   * @param input   Input relational expression
   * @param constants List of constants that are additional inputs
   * @param rowType Output row type
   * @param groups Windows
   */
  public Window(RelOptCluster cluster, RelTraitSet traitSet, RelNode input,
      List<RexLiteral> constants, RelDataType rowType, List<Group> groups) {
    super(cluster, traitSet, input);
    this.constants = ImmutableList.copyOf(constants);
    assert rowType != null;
    this.rowType = rowType;
    this.groups = ImmutableList.copyOf(groups);
  }

  @Override public boolean isValid(Litmus litmus, Context context) {
    // In the window specifications, an aggregate call such as
    // 'SUM(RexInputRef #10)' refers to expression #10 of inputProgram.
    // (Not its projections.)
    final RelDataType childRowType = getInput().getRowType();

    final int childFieldCount = childRowType.getFieldCount();
    final int inputSize = childFieldCount + constants.size();
    final List<RelDataType> inputTypes =
        new AbstractList<RelDataType>() {
          @Override public RelDataType get(int index) {
            return index < childFieldCount
                ? childRowType.getFieldList().get(index).getType()
                : constants.get(index - childFieldCount).getType();
          }

          @Override public int size() {
            return inputSize;
          }
        };

    final RexChecker checker = new RexChecker(inputTypes, context, litmus);
    int count = 0;
    for (Group group : groups) {
      for (RexWinAggCall over : group.aggCalls) {
        ++count;
        if (!checker.isValid(over)) {
          return litmus.fail(null);
        }
      }
    }
    if (count == 0) {
      return litmus.fail("empty");
    }
    return litmus.succeed();
  }

  public RelWriter explainTerms(RelWriter pw) {
    super.explainTerms(pw);
    for (Ord<Group> window : Ord.zip(groups)) {
      pw.item("window#" + window.i, window.e.toString());
    }
    return pw;
  }

  public static ImmutableIntList getProjectOrdinals(final List<RexNode> exprs) {
    return ImmutableIntList.copyOf(
        new AbstractList<Integer>() {
          public Integer get(int index) {
            return ((RexSlot) exprs.get(index)).getIndex();
          }

          public int size() {
            return exprs.size();
          }
        });
  }

  public static RelCollation getCollation(
      final List<RexFieldCollation> collations) {
    return RelCollations.of(
        new AbstractList<RelFieldCollation>() {
          public RelFieldCollation get(int index) {
            final RexFieldCollation collation = collations.get(index);
            return new RelFieldCollation(
                ((RexLocalRef) collation.left).getIndex(),
                collation.getDirection(),
                collation.getNullDirection());
          }

          public int size() {
            return collations.size();
          }
        });
  }

  /**
   * Returns constants that are additional inputs of current relation.
   * @return constants that are additional inputs of current relation
   */
  public List<RexLiteral> getConstants() {
    return constants;
  }

  @Override public RelOptCost computeSelfCost(RelOptPlanner planner,
      RelMetadataQuery mq) {
    // Cost is proportional to the number of rows and the number of
    // components (groups and aggregate functions). There is
    // no I/O cost.
    //
    // TODO #1. Add memory cost.
    // TODO #2. MIN and MAX have higher CPU cost than SUM and COUNT.
    final double rowsIn = mq.getRowCount(getInput());
    int count = groups.size();
    for (Group group : groups) {
      count += group.aggCalls.size();
    }
    return planner.getCostFactory().makeCost(rowsIn, rowsIn * count, 0);
  }

  /**
   * Group of windowed aggregate calls that have the same window specification.
   *
   *
The specification is defined by an upper and lower bound, and
   * also has zero or more partitioning columns.
   *
   *
A window is either logical or physical. A physical window is measured
   * in terms of row count. A logical window is measured in terms of rows
   * within a certain distance from the current sort key.
   *
   *
For example:
   *
   *

   *
ROWS BETWEEN 10 PRECEDING and 5 FOLLOWING is a physical
   * window with an upper and lower bound;
   *
RANGE BETWEEN INTERVAL '1' HOUR PRECEDING AND UNBOUNDED
   * FOLLOWING is a logical window with only a lower bound;
   *
RANGE INTERVAL '10' MINUTES PRECEDING (which is
   * equivalent to RANGE BETWEEN INTERVAL '10' MINUTES PRECEDING AND
   * CURRENT ROW) is a logical window with an upper and lower bound.
   *

   */
  public static class Group {
    public final ImmutableBitSet keys;
    public final boolean isRows;
    public final RexWindowBound lowerBound;
    public final RexWindowBound upperBound;
    public final RelCollation orderKeys;
    private final String digest;

    /**
     * List of {@link Window.RexWinAggCall}
     * objects, each of which is a call to a
     * {@link org.apache.calcite.sql.SqlAggFunction}.
     */
    public final ImmutableList<RexWinAggCall> aggCalls;

    public Group(
        ImmutableBitSet keys,
        boolean isRows,
        RexWindowBound lowerBound,
        RexWindowBound upperBound,
        RelCollation orderKeys,
        List<RexWinAggCall> aggCalls) {
      assert orderKeys != null : "precondition: ordinals != null";
      assert keys != null;
      this.keys = keys;
      this.isRows = isRows;
      this.lowerBound = lowerBound;
      this.upperBound = upperBound;
      this.orderKeys = orderKeys;
      this.aggCalls = ImmutableList.copyOf(aggCalls);
      this.digest = computeString();
    }

    public String toString() {
      return digest;
    }

    private String computeString() {
      final StringBuilder buf = new StringBuilder();
      buf.append("window(partition ");
      buf.append(keys);
      buf.append(" order by ");
      buf.append(orderKeys);
      buf.append(isRows ? " rows " : " range ");
      if (lowerBound != null) {
        if (upperBound != null) {
          buf.append("between ");
          buf.append(lowerBound);
          buf.append(" and ");
          buf.append(upperBound);
        } else {
          buf.append(lowerBound);
        }
      } else if (upperBound != null) {
        buf.append(upperBound);
      }
      buf.append(" aggs ");
      buf.append(aggCalls);
      buf.append(")");
      return buf.toString();
    }

    @Override public boolean equals(Object obj) {
      return this == obj
          || obj instanceof Group
          && this.digest.equals(((Group) obj).digest);
    }

    @Override public int hashCode() {
      return digest.hashCode();
    }

    public RelCollation collation() {
      return orderKeys;
    }

    /**
     * Returns if the window is guaranteed to have rows.
     * This is useful to refine data type of window aggregates.
     * For instance sum(non-nullable) over (empty window) is NULL.
     * @return true when the window is non-empty
     * @see org.apache.calcite.sql.SqlWindow#isAlwaysNonEmpty()
     * @see org.apache.calcite.sql.SqlOperatorBinding#getGroupCount()
     * @see org.apache.calcite.sql.validate.SqlValidatorImpl#resolveWindow(org.apache.calcite.sql.SqlNode, org.apache.calcite.sql.validate.SqlValidatorScope, boolean)
     */
    public boolean isAlwaysNonEmpty() {
      int lowerKey = lowerBound.getOrderKey();
      int upperKey = upperBound.getOrderKey();
      return lowerKey > -1 && lowerKey <= upperKey;
    }

    /**
     * Presents a view of the {@link RexWinAggCall} list as a list of
     * {@link AggregateCall}.
     */
    public List<AggregateCall> getAggregateCalls(Window windowRel) {
      final List<String> fieldNames =
          Util.skip(windowRel.getRowType().getFieldNames(),
              windowRel.getInput().getRowType().getFieldCount());
      return new AbstractList<AggregateCall>() {
        public int size() {
          return aggCalls.size();
        }

        public AggregateCall get(int index) {
          final RexWinAggCall aggCall = aggCalls.get(index);
          return AggregateCall.create((SqlAggFunction) aggCall.getOperator(),
              false, getProjectOrdinals(aggCall.getOperands()), -1,
              aggCall.getType(), fieldNames.get(aggCall.ordinal));
        }
      };
    }
  }

  /**
   * A call to a windowed aggregate function.
   *
   *
Belongs to a {@link Window.Group}.
   *
   *
It's a bastard son of a {@link org.apache.calcite.rex.RexCall}; similar
   * enough that it gets visited by a {@link org.apache.calcite.rex.RexVisitor},
   * but it also has some extra data members.
   */
  public static class RexWinAggCall extends RexCall {
    /**
     * Ordinal of this aggregate within its partition.
     */
    public final int ordinal;

    /**
     * Creates a RexWinAggCall.
     *
     * @param aggFun   Aggregate function
     * @param type     Result type
     * @param operands Operands to call
     * @param ordinal  Ordinal within its partition
     */
    public RexWinAggCall(
        SqlAggFunction aggFun,
        RelDataType type,
        List<RexNode> operands,
        int ordinal) {
      super(type, aggFun, operands);
      this.ordinal = ordinal;
    }

    @Override public RexCall clone(RelDataType type, List<RexNode> operands) {
      throw new UnsupportedOperationException();
    }
  }
}

// End Window.java


text:
package com.jwetherell.algorithms.graph;

import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Queue;

import com.jwetherell.algorithms.data_structures.Graph;
import com.jwetherell.algorithms.data_structures.Graph.Edge;
import com.jwetherell.algorithms.data_structures.Graph.Vertex;

/* Breath First Travesal in given "Directed graph" (Adjacany matrix) */
public class BreadthFirstTraversal {

    @SuppressWarnings("unchecked")
    public static final <T extends Comparable<T>> Graph.Vertex<T>[] breadthFirstTraversal(Graph<T> graph, Graph.Vertex<T> source) {
        // use for look-up via index
        final ArrayList<Vertex<T>> vertices = new ArrayList<Vertex<T>>();
        vertices.addAll(graph.getVertices());

        // used for look-up via vertex
        final int n = vertices.size();
        final Map<Vertex<T>,Integer> vertexToIndex = new HashMap<Vertex<T>,Integer>();
        for (int i=0; i<n; i++) {
            final Vertex<T> v = vertices.get(i);
            vertexToIndex.put(v,i);
        }

        // adjacency matrix
        final byte[][] adj = new byte[n][n];
        for (int i=0; i<n; i++) {
            final Vertex<T> v = vertices.get(i);
            final int idx = vertexToIndex.get(v);
            final byte[] array = new byte[n];
            adj[idx] = array;
            final List<Edge<T>> edges = v.getEdges();
            for (Edge<T> e : edges)
                array[vertexToIndex.get(e.getToVertex())] = 1;
        }

        // visited array
        final byte[] visited = new byte[n];
        for (int i = 0; i < visited.length; i++)
            visited[i] = -1;

        // for holding results
        final Graph.Vertex<T>[] arr = new Graph.Vertex[n];

        // start at the source
        Vertex<T> element = source;
        int c = 0;
        int i = vertexToIndex.get(element);
        visited[i] = 1;
        int k = 0;
        arr[k] = element;
        k++;

        final Queue<Vertex<T>> queue = new ArrayDeque<Vertex<T>>();
        queue.add(source);
        while (!queue.isEmpty()) {
            element = queue.peek();
            c = vertexToIndex.get(element);
            i = 0;
            while (i < n) {
                if (adj[c][i] == 1 && visited[i] == -1) {
                    final Vertex<T> v = vertices.get(i);
                    queue.add(v);
                    visited[i] = 1;
                    arr[k] = v;
                    k++;
                }
                i++;
            }
            queue.poll();
        }
        return arr;
    }
}


text:
<?php

/* ConnectionWebBundle:Frontend/Parts:background.html.twig */
class __TwigTemplate_64024a70bb36dcdcb3870e35d8196b261bf4ebfbb208aaf3ee750a88dc873b88 extends Twig_Template
{
    public function __construct(Twig_Environment $env)
    {
        parent::__construct($env);

        $this->parent = false;

        $this->blocks = array(
        );
    }

    protected function doDisplay(array $context, array $blocks = array())
    {
        // line 1
        if ((array_key_exists("background", $context) && (!twig_test_empty((isset($context["background"]) ? $context["background"] : $this->getContext($context, "background")))))) {
            // line 2
            echo "
env, $this->getAttribute((isset($context["background"]) ? $context["background"] : $this->getContext($context, "background")), "path", array()), "html", null, true);
            echo "') no-repeat center; -moz-background-size: 100%; /* Firefox 3.6+ */
        -webkit-background-size: 100%; /* Safari 3.1+ и Chrome 4.0+ */
        -o-background-size: 100%; /* Opera 9.6+ */
        background-size: 100%; /* Современные браузеры */\">
";
        } else {
            // line 7
            echo "

";
        }
    }

    public function getTemplateName()
    {
        return "ConnectionWebBundle:Frontend/Parts:background.html.twig";
    }

    public function isTraitable()
    {
        return false;
    }

    public function getDebugInfo()
    {
        return array (  30 => 7,  21 => 2,  19 => 1,);
    }
}


text:
using Dongbo.Configuration;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Serialization;

namespace Dongbo.Search.AliCloudOpenSearch
{
    [Serializable]
    [XmlRoot("AliCloudSearchConfig")]
    public class AliCloudSearchConfig : BaseConfig<AliCloudSearchConfig>
    {
        public const string SectionName = "AliCloudSearchConfig";

        [XmlElement("accessKey")]
        public string AccessKey { get; set; }

        [XmlElement("accessSecret")]
        public string AccessSecret { get; set; }

        [XmlElement("host")]
        public string Host { get; set; }

        [XmlArray("applications"), XmlArrayItem("app")]
        public Application[] Applications { get; set; }

        [XmlIgnore]
        public Application this[string name]
        {

            get
            {
                if (this.Applications == null || this.Applications.Length == 0)
                {
                    return null;
                }
                return Applications.FirstOrDefault(p => string.Equals(name, p.Name, StringComparison.OrdinalIgnoreCase));
            }
        }

    }

    [Serializable]
    public class Application
    {
        [XmlAttribute("name")]
        public string Name { get; set; }

        [XmlAttribute("indexName")]
        public string IndexName { get; set; }
        [XmlAttribute("host")]
        public string Host { get; set; }
        [XmlAttribute("host_internal")]
        public string HostInternal { get; set; }
        [XmlAttribute("host_vpc")]
        public string HostVPC { get; set; }
        [XmlAttribute("description")]
        public string Description { get; set; }

    }

}


text:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
using DNS.Protocol;
using DNS.Protocol.ResourceRecords;
using Newtonsoft.Json;
using Stratis.Bitcoin.Utilities;

namespace Stratis.Bitcoin.Features.Dns
{
    /// <summary>
    /// This class defines a DNS masterfile used to cache the whitelisted peers discovered by the DNS Seed service that supports saving
    /// and loading from a stream.
    /// This is based on 3rd party library https://github.com/kapetan/dns.
    /// </summary>
    public class DnsSeedMasterFile : IMasterFile
    {
        /// <summary>
        /// Sets the default ttl.
        /// </summary>
        private static readonly TimeSpan DEFAULT_TTL = new TimeSpan(0);

        /// <summary>
        /// The default time to live.
        /// </summary>
        private TimeSpan ttl = DEFAULT_TTL;

        /// <summary>
        /// The resource record entries in the master file.
        /// </summary>
        protected IList<IResourceRecord> entries = new List<IResourceRecord>();

        /// <summary>
        /// Initializes a new instance of a <see cref="DnsSeedMasterFile"/> class.
        /// </summary>
        /// <param name="ttl">The time to live.</param>
        public DnsSeedMasterFile(TimeSpan ttl)
        {
            this.ttl = ttl;
        }

        /// <summary>
        /// Initializes a new instance of a <see cref="DnsSeedMasterFile"/> class.
        /// </summary>
        public DnsSeedMasterFile() { }

        public DnsSeedMasterFile(IList<IResourceRecord> resourceRecords)
        {
            this.entries = resourceRecords;
        }

        /// <summary>
        /// Identifies if the domain matches the entry.
        /// </summary>
        /// <param name="domain">The domain to match.</param>
        /// <param name="entry">The entry to match.</param>
        /// <returns><c>True</c> if there is a match, otherwise <c>false</c>.</returns>
        private static bool Matches(Domain domain, Domain entry)
        {
            string[] labels = entry.ToString().Split('.');
            var patterns = new string[labels.Length];

            for (int i = 0; i < labels.Length; i++)
            {
                string label = labels[i];
                patterns[i] = label == "*" ? "(\\w+)" : Regex.Escape(label);
            }

            var re = new Regex("^" + string.Join("\\.", patterns) + "$");
            return re.IsMatch(domain.ToString());
        }

        /// <summary>
        /// Creates the serializer for loading and saving the master file contents.
        /// </summary>
        /// <returns></returns>
        private JsonSerializer CreateSerializer()
        {
            var settings = new Newtonsoft.Json.JsonSerializerSettings();
            settings.Converters.Add(new ResourceRecordConverter());
            settings.Formatting = Formatting.Indented;

            return JsonSerializer.Create(settings);
        }

        /// <summary>
        /// Gets a list of matching <see cref="IResourceRecord"/> objects.
        /// </summary>
        /// <param name="domain">The domain to match on.</param>
        /// <param name="type">The type to match on.</param>
        /// <returns>The matching entries.</returns>
        public IList<IResourceRecord> Get(Domain domain, RecordType type)
        {
            // Fix logic from 3rd party library to support the ANY DNS query record type and
            // when dig uses +trace option, the recursion request to get the NS record doesn't specify a domain
            // which is catered for by testing to see if the domain is empty.
            return this.entries.Where(e => (string.IsNullOrWhiteSpace(domain.ToString()) || Matches(domain, e.Name)) && (e.Type == type || type == RecordType.ANY)).ToList();
        }

        /// <summary>
        /// Gets a list of matching <see cref="IResourceRecord"/> objects.
        /// </summary>
        /// <param name="question">The <see cref="Question"/>used to match on.</param>
        /// <returns>The matching entries.</returns>
        public IList<IResourceRecord> Get(Question question)
        {
            return this.Get(question.Name, question.Type);
        }

        /// <summary>
        /// Loads the saved masterfile from the specified stream.
        /// </summary>
        /// <param name="stream">The stream containing the masterfile.</param>
        public void Load(Stream stream)
        {
            Guard.NotNull(stream, nameof(stream));

            using (var textReader = new JsonTextReader(new StreamReader(stream)))
            {
                JsonSerializer serializer = this.CreateSerializer();
                this.entries = serializer.Deserialize<List<IResourceRecord>>(textReader);
            }
        }

        /// <summary>
        /// Saves the cached masterfile to the specified stream.
        /// </summary>
        /// <param name="stream">The stream to write the masterfile to.</param>
        public void Save(Stream stream)
        {
            Guard.NotNull(stream, nameof(stream));

            var textWriter = new JsonTextWriter(new StreamWriter(stream));
            JsonSerializer serializer = this.CreateSerializer();

            // Send a copy of the entries to the serializer because the collection can be modified during serialization.
            serializer.Serialize(textWriter, this.entries.ToList());
            textWriter.Flush();
        }

        /// <inheritdoc />
        public void Seed(DnsSettings dnsSettings)
        {
            // Check if SOA record exists for host.
            int count = this.Get(new Question(new Domain(dnsSettings.DnsHostName), RecordType.SOA)).Count;
            if (count == 0)
            {
                // Add SOA record for host.
                this.entries.Add(new StartOfAuthorityResourceRecord(new Domain(dnsSettings.DnsHostName), new Domain(dnsSettings.DnsNameServer), new Domain(dnsSettings.DnsMailBox.Replace('@', '.'))));
            }

            // Check if NS record exists for host.
            count = this.Get(new Question(new Domain(dnsSettings.DnsHostName), RecordType.NS)).Count;
            if (count == 0)
            {
                // Add NS record for host.
                this.entries.Add(new NameServerResourceRecord(new Domain(dnsSettings.DnsHostName), new Domain(dnsSettings.DnsNameServer)));
            }
        }
    }
}


text:
import { INCREMENT_COUNTER, DECREMENT_COUNTER } from '../actions/counter'
//reducer其实也是个方法而已,参数是state和action,返回值是新的state
export default function counter(state = { count: 0}, action) {
  switch (action.type) {
    case INCREMENT_COUNTER:
      return {
        count: state.count + 1
      }
    case DECREMENT_COUNTER:
      return {
        count: state.count - 1
      }
    default:
      return state
  }

}


text:
layout: blog
title: Open Salt Lake's Code Across
date: 2014-02-24 13:43:52.000000000 -07:00
type: blog
published: true
status: publish
categories: []
tags: []
meta:
  _edit_last: '23253177'
  _publicize_pending: '1'
  _oembed_35ac0849a1957c5491273e092ce97f09: "{{unknown}}"
author:
  login: nolewalkingshaw
  email: nolewalkingshaw@gmail.com
  display_name: nolewalkingshaw
  first_name: 'Nole'
  last_name: 'Walkingshaw'
---

The Code Across event for Open Salt Lake was productive. We worked on two projects, the US Cities Open Data Census and the Salt Lake City open Data Policy. These two projects complimented each other as we went through the census exercise searching for data sets we were able to identify the strengths and weaknesses.  We discussed and reviewed the draft open data policy and noted places where Salt Lake City may be able to strengthen their open data portal.

To view the census click here to review the draft open data policy click here.

We talked about building upon our ideas site and the need to recruit new ideas or to see if we can get someone working on the ones we have. Please take a look at our Ideas Page and offer up a comment or suggestion or hey take on one of the great ideas already there.

To get involved or just keep an eye on the chatter join our Google group https://groups.google.com/forum/#!forum/openslc.


text:
NullUnit::GuiReporter::GuiReporter(std::ostream& s)	: stream(s)
{
	return;
}

void NullUnit::GuiReporter::PrepareMessage(std::string& message)
{
	std::replace(message.begin(), message.end(), '\n', ' ');
}

void NullUnit::GuiReporter::ReportCaseFail(const std::string& suite_name, const std::string& case_name,
	const std::string& reason, const std::string& filename, int lineNumber)
{
	std::string preparedMessage(reason);
	PrepareMessage(preparedMessage);

	stream << "CASE_FAIL" << delim << suite_name << delim << case_name << delim << preparedMessage
		<< delim << filename << delim << lineNumber << std::endl;
}

void NullUnit::GuiReporter::ListBegin()
{
	stream << "NULLUNIT" << std::endl;
	stream << "LIST_BEGIN" << std::endl;
}

void NullUnit::GuiReporter::ListEnd()
{
	stream << "LIST_END" << std::endl;
}

void NullUnit::GuiReporter::ListEntrySuite(const std::string& suite_name,
	const std::string& filename, int lineNumber)
{
	stream << "LIST_SUITE" << delim << suite_name << delim << filename << delim << lineNumber << std::endl;
}

void NullUnit::GuiReporter::ListEntryCase(const std::string& suite_name, const std::string& case_name,
	const std::string& filename, int lineNumber)
{
	stream << "LIST_CASE" << delim << suite_name << delim << case_name << delim <<
		filename << delim << lineNumber << std::endl;
}

void NullUnit::GuiReporter::ReportBegin()
{
	stream << "NULLUNIT" << std::endl;
	stream << "REPORT_BEGIN" << std::endl;
}

void NullUnit::GuiReporter::ReportEnd()
{
	stream << "REPORT_END" << std::endl;
}

void NullUnit::GuiReporter::SuiteBegin(const std::string& suite_name)
{
	stream << "SUITE_BEGIN" << delim << suite_name << std::endl;
}

void NullUnit::GuiReporter::SuiteEnd(const std::string& suite_name)
{
	stream << "SUITE_END" << delim << suite_name << std::endl;
}

void NullUnit::GuiReporter::CaseBegin(const std::string& suite_name, const std::string& case_name)
{
	stream << "CASE_BEGIN" << delim << suite_name << delim << case_name << std::endl;
}

void NullUnit::GuiReporter::CaseEnd(const std::string& suite_name, const std::string& case_name)
{
	stream << "CASE_END" << delim << suite_name << delim << case_name << std::endl;
}

void NullUnit::GuiReporter::CasePass(const std::string& suite_name, const std::string& case_name)
{
	stream << "CASE_PASS" << delim << suite_name << delim << case_name << std::endl;
}

void NullUnit::GuiReporter::CaseFail(const std::string& suite_name, const std::string& case_name,
	const std::string& reason, const std::string& filename, int lineNumber)
{
	ReportCaseFail(suite_name, case_name, reason, filename, lineNumber);
}

void NullUnit::GuiReporter::CaseStdExceptionFail(const std::string& suite_name, const std::string& case_name,
	const std::string& what, const std::string& filename, int lineNumber)
{
	ReportCaseFail(suite_name, case_name, Strings::MakeUnhandledStdExceptionString(what), filename, lineNumber);
}

void NullUnit::GuiReporter::CaseUnhandledExceptionFail(const std::string& suite_name, const std::string& case_name,
	const std::string& filename, int lineNumber)
{
	ReportCaseFail(suite_name, case_name, Strings::UnhandledException, filename, lineNumber);
}

void NullUnit::GuiReporter::CaseAssertionFail(const std::string& suite_name, const std::string& case_name,
	const std::string& reason, const std::string& filename, int lineNumber)
{
	ReportCaseFail(suite_name, case_name, reason, filename, lineNumber);
}

void NullUnit::GuiReporter::CaseExpectationFail(const std::string& suite_name, const std::string& case_name,
	const std::string& reason, const std::string& filename, int lineNumber)
{
	ReportCaseFail(suite_name, case_name, reason, filename, lineNumber);
}

void NullUnit::GuiReporter::FixtureSetupFail(const std::string& suite_name, const std::string& case_name,
	const std::string& filename, int lineNumber)
{
	ReportCaseFail(suite_name, case_name, Strings::FixtureSetupFailure, filename, lineNumber);
}

void NullUnit::GuiReporter::FixtureTeardownFail(const std::string& suite_name, const std::string& case_name,
	const std::string& filename, int lineNumber)
{
	ReportCaseFail(suite_name, case_name, Strings::FixtureTeardownFailure, filename, lineNumber);
}


text:
package com.example.android.supportv4.app;

import android.app.Activity;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;

import androidx.core.app.ShareCompat;

import com.example.android.supportv4.R;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;

/**
 * This example shows a simple way to handle data shared with your app through the
 * use of the support library's ShareCompat features. It will display shared text
 * content as well as the application label and icon of the app that shared the content.
 */
public class SharingReceiverSupport extends Activity {
    private static final String TAG = "SharingReceiverSupport";
    private static final int ICON_SIZE = 32; // dip

    @Override
    protected void onCreate(Bundle b) {
        super.onCreate(b);
        setContentView(R.layout.sharing_receiver_support);

        final float density = getResources().getDisplayMetrics().density;
        final int iconSize = (int) (ICON_SIZE * density + 0.5f);

        ShareCompat.IntentReader intentReader = ShareCompat.IntentReader.from(this);

        // The following provides attribution for the app that shared the data with us.
        TextView info = findViewById(R.id.app_info);
        Drawable d = intentReader.getCallingActivityIcon();
        d.setBounds(0, 0, iconSize, iconSize);
        info.setCompoundDrawables(d, null, null, null);
        info.setText(intentReader.getCallingApplicationLabel());

        TextView tv = findViewById(R.id.text);
        StringBuilder txt = new StringBuilder("Received share!\nText was: ");

        txt.append(intentReader.getText());
        txt.append("\n");

        txt.append("Streams included:\n");
        final int N = intentReader.getStreamCount();
        for (int i = 0; i < N; i++) {
            Uri uri = intentReader.getStream(i);
            txt.append("Share included stream " + i + ": " + uri + "\n");
            try {
                BufferedReader reader = new BufferedReader(new InputStreamReader(
                        getContentResolver().openInputStream(uri), "UTF-8"));
                try {
                    txt.append(reader.readLine() + "\n");
                } catch (IOException e) {
                    Log.e(TAG, "Reading stream threw exception", e);
                } finally {
                    reader.close();
                }
            } catch (FileNotFoundException e) {
                Log.e(TAG, "File not found from share.", e);
            } catch (IOException e) {
                Log.d(TAG, "I/O Error", e);
            }
        }

        tv.setText(txt.toString());
    }
}


text:
package com.hazelcast.client.impl.protocol.codec.custom;

import com.hazelcast.client.impl.protocol.ClientMessage;
import com.hazelcast.client.impl.protocol.Generated;
import com.hazelcast.client.impl.protocol.codec.builtin.*;

import static com.hazelcast.client.impl.protocol.codec.builtin.CodecUtil.fastForwardToEndFrame;
import static com.hazelcast.client.impl.protocol.ClientMessage.*;
import static com.hazelcast.client.impl.protocol.codec.builtin.FixedSizeTypesCodec.*;

@Generated("81ada5402a317de1c4d63c185f96d54f")
public final class TimedExpiryPolicyFactoryConfigCodec {
    private static final int EXPIRY_POLICY_TYPE_FIELD_OFFSET = 0;
    private static final int INITIAL_FRAME_SIZE = EXPIRY_POLICY_TYPE_FIELD_OFFSET + INT_SIZE_IN_BYTES;

    private TimedExpiryPolicyFactoryConfigCodec() {
    }

    public static void encode(ClientMessage clientMessage, com.hazelcast.config.CacheSimpleConfig.ExpiryPolicyFactoryConfig.TimedExpiryPolicyFactoryConfig timedExpiryPolicyFactoryConfig) {
        clientMessage.add(BEGIN_FRAME.copy());

        ClientMessage.Frame initialFrame = new ClientMessage.Frame(new byte[INITIAL_FRAME_SIZE]);
        encodeInt(initialFrame.content, EXPIRY_POLICY_TYPE_FIELD_OFFSET, timedExpiryPolicyFactoryConfig.getExpiryPolicyType());
        clientMessage.add(initialFrame);

        DurationConfigCodec.encode(clientMessage, timedExpiryPolicyFactoryConfig.getDurationConfig());

        clientMessage.add(END_FRAME.copy());
    }

    public static com.hazelcast.config.CacheSimpleConfig.ExpiryPolicyFactoryConfig.TimedExpiryPolicyFactoryConfig decode(ClientMessage.ForwardFrameIterator iterator) {
        // begin frame
        iterator.next();

        ClientMessage.Frame initialFrame = iterator.next();
        int expiryPolicyType = decodeInt(initialFrame.content, EXPIRY_POLICY_TYPE_FIELD_OFFSET);

        com.hazelcast.config.CacheSimpleConfig.ExpiryPolicyFactoryConfig.DurationConfig durationConfig = DurationConfigCodec.decode(iterator);

        fastForwardToEndFrame(iterator);

        return CustomTypeFactory.createTimedExpiryPolicyFactoryConfig(expiryPolicyType, durationConfig);
    }
}


text:
package cmd

import (
	"bytes"
	"fmt"
	"io"
	"io/ioutil"
	"os"
	"testing"

	"github.com/GoogleCloudPlatform/kubernetes/pkg/api"
	"github.com/GoogleCloudPlatform/kubernetes/pkg/api/latest"
	"github.com/GoogleCloudPlatform/kubernetes/pkg/api/meta"
	"github.com/GoogleCloudPlatform/kubernetes/pkg/api/testapi"
	"github.com/GoogleCloudPlatform/kubernetes/pkg/api/validation"
	"github.com/GoogleCloudPlatform/kubernetes/pkg/client"
	"github.com/GoogleCloudPlatform/kubernetes/pkg/kubectl"
	cmdutil "github.com/GoogleCloudPlatform/kubernetes/pkg/kubectl/cmd/util"
	"github.com/GoogleCloudPlatform/kubernetes/pkg/kubectl/resource"
	"github.com/GoogleCloudPlatform/kubernetes/pkg/runtime"
)

type internalType struct {
	Kind       string
	APIVersion string

	Name string
}

type externalType struct {
	Kind       string `json:"kind"`
	APIVersion string `json:"apiVersion"`

	Name string `json:"name"`
}

type ExternalType2 struct {
	Kind       string `json:"kind"`
	APIVersion string `json:"apiVersion"`

	Name string `json:"name"`
}

func (*internalType) IsAnAPIObject()  {}
func (*externalType) IsAnAPIObject()  {}
func (*ExternalType2) IsAnAPIObject() {}

func newExternalScheme() (*runtime.Scheme, meta.RESTMapper, runtime.Codec) {
	scheme := runtime.NewScheme()
	scheme.AddKnownTypeWithName("", "Type", &internalType{})
	scheme.AddKnownTypeWithName("unlikelyversion", "Type", &externalType{})
	scheme.AddKnownTypeWithName("v1beta1", "Type", &ExternalType2{})

	codec := runtime.CodecFor(scheme, "unlikelyversion")
	validVersion := testapi.Version()
	mapper := meta.NewDefaultRESTMapper([]string{"unlikelyversion", validVersion}, func(version string) (*meta.VersionInterfaces, bool) {
		return &meta.VersionInterfaces{
			Codec:            runtime.CodecFor(scheme, version),
			ObjectConvertor:  scheme,
			MetadataAccessor: meta.NewAccessor(),
		}, (version == validVersion || version == "unlikelyversion")
	})
	for _, version := range []string{"unlikelyversion", validVersion} {
		for kind := range scheme.KnownTypes(version) {
			mixedCase := false
			scope := meta.RESTScopeNamespace
			mapper.Add(scope, kind, version, mixedCase)
		}
	}

	return scheme, mapper, codec
}

type testPrinter struct {
	Objects []runtime.Object
	Err     error
}

func (t *testPrinter) PrintObj(obj runtime.Object, out io.Writer) error {
	t.Objects = append(t.Objects, obj)
	fmt.Fprintf(out, "%#v", obj)
	return t.Err
}

type testDescriber struct {
	Name, Namespace string
	Output          string
	Err             error
}

func (t *testDescriber) Describe(namespace, name string) (output string, err error) {
	t.Namespace, t.Name = namespace, name
	return t.Output, t.Err
}

type testFactory struct {
	Mapper       meta.RESTMapper
	Typer        runtime.ObjectTyper
	Client       kubectl.RESTClient
	Describer    kubectl.Describer
	Printer      kubectl.ResourcePrinter
	Validator    validation.Schema
	Namespace    string
	ClientConfig *client.Config
	Err          error
}

func NewTestFactory() (*cmdutil.Factory, *testFactory, runtime.Codec) {
	scheme, mapper, codec := newExternalScheme()
	t := &testFactory{
		Validator: validation.NullSchema{},
		Mapper:    mapper,
		Typer:     scheme,
	}
	return &cmdutil.Factory{
		Object: func() (meta.RESTMapper, runtime.ObjectTyper) {
			return t.Mapper, t.Typer
		},
		RESTClient: func(*meta.RESTMapping) (resource.RESTClient, error) {
			return t.Client, t.Err
		},
		Describer: func(*meta.RESTMapping) (kubectl.Describer, error) {
			return t.Describer, t.Err
		},
		Printer: func(mapping *meta.RESTMapping, noHeaders, withNamespace bool) (kubectl.ResourcePrinter, error) {
			return t.Printer, t.Err
		},
		Validator: func() (validation.Schema, error) {
			return t.Validator, t.Err
		},
		DefaultNamespace: func() (string, error) {
			return t.Namespace, t.Err
		},
		ClientConfig: func() (*client.Config, error) {
			return t.ClientConfig, t.Err
		},
	}, t, codec
}

func NewMixedFactory(apiClient resource.RESTClient) (*cmdutil.Factory, *testFactory, runtime.Codec) {
	f, t, c := NewTestFactory()
	f.Object = func() (meta.RESTMapper, runtime.ObjectTyper) {
		return meta.MultiRESTMapper{t.Mapper, latest.RESTMapper}, runtime.MultiObjectTyper{t.Typer, api.Scheme}
	}
	f.RESTClient = func(m *meta.RESTMapping) (resource.RESTClient, error) {
		if m.ObjectConvertor == api.Scheme {
			return apiClient, t.Err
		}
		return t.Client, t.Err
	}
	return f, t, c
}

func NewAPIFactory() (*cmdutil.Factory, *testFactory, runtime.Codec) {
	t := &testFactory{
		Validator: validation.NullSchema{},
	}
	generators := map[string]kubectl.Generator{
		"run-container/v1": kubectl.BasicReplicationController{},
		"service/v1":       kubectl.ServiceGenerator{},
	}
	return &cmdutil.Factory{
		Object: func() (meta.RESTMapper, runtime.ObjectTyper) {
			return latest.RESTMapper, api.Scheme
		},
		Client: func() (*client.Client, error) {
			// Swap out the HTTP client out of the client with the fake's version.
			fakeClient := t.Client.(*client.FakeRESTClient)
			c := client.NewOrDie(t.ClientConfig)
			c.Client = fakeClient.Client
			return c, t.Err
		},
		RESTClient: func(*meta.RESTMapping) (resource.RESTClient, error) {
			return t.Client, t.Err
		},
		Describer: func(*meta.RESTMapping) (kubectl.Describer, error) {
			return t.Describer, t.Err
		},
		Printer: func(mapping *meta.RESTMapping, noHeaders, withNamespace bool) (kubectl.ResourcePrinter, error) {
			return t.Printer, t.Err
		},
		Validator: func() (validation.Schema, error) {
			return t.Validator, t.Err
		},
		DefaultNamespace: func() (string, error) {
			return t.Namespace, t.Err
		},
		ClientConfig: func() (*client.Config, error) {
			return t.ClientConfig, t.Err
		},
		Generator: func(name string) (kubectl.Generator, bool) {
			generator, ok := generators[name]
			return generator, ok
		},
	}, t, testapi.Codec()
}

func objBody(codec runtime.Codec, obj runtime.Object) io.ReadCloser {
	return ioutil.NopCloser(bytes.NewReader([]byte(runtime.EncodeOrDie(codec, obj))))
}

func stringBody(body string) io.ReadCloser {
	return ioutil.NopCloser(bytes.NewReader([]byte(body)))
}

// Verify that resource.RESTClients constructed from a factory respect mapping.APIVersion
func TestClientVersions(t *testing.T) {
	f := cmdutil.NewFactory(nil)

	version := testapi.Version()
	mapping := &meta.RESTMapping{
		APIVersion: version,
	}
	c, err := f.RESTClient(mapping)
	if err != nil {
		t.Errorf("unexpected error: %v", err)
	}
	client := c.(*client.RESTClient)
	if client.APIVersion() != version {
		t.Errorf("unexpected Client APIVersion: %s %v", client.APIVersion, client)
	}
}

func ExamplePrintReplicationController() {
	f, tf, codec := NewAPIFactory()
	tf.Printer = kubectl.NewHumanReadablePrinter(false, false)
	tf.Client = &client.FakeRESTClient{
		Codec:  codec,
		Client: nil,
	}
	cmd := NewCmdRunContainer(f, os.Stdout)
	ctrl := &api.ReplicationController{
		ObjectMeta: api.ObjectMeta{
			Name:   "foo",
			Labels: map[string]string{"foo": "bar"},
		},
		Spec: api.ReplicationControllerSpec{
			Replicas: 1,
			Selector: map[string]string{"foo": "bar"},
			Template: &api.PodTemplateSpec{
				ObjectMeta: api.ObjectMeta{
					Labels: map[string]string{"foo": "bar"},
				},
				Spec: api.PodSpec{
					Containers: []api.Container{
						{
							Name:  "foo",
							Image: "someimage",
						},
					},
				},
			},
		},
	}
	err := f.PrintObject(cmd, ctrl, os.Stdout)
	if err != nil {
		fmt.Printf("Unexpected error: %v", err)
	}
	// Output:
	// CONTROLLER   CONTAINER(S)   IMAGE(S)    SELECTOR   REPLICAS
	// foo          foo            someimage   foo=bar    1
}


text:
package com.teamwizardry.refraction.common.block;

import com.teamwizardry.refraction.api.beam.Effect;
import com.teamwizardry.refraction.common.effect.EffectBurn;
import com.teamwizardry.refraction.init.ModBlocks;
import net.minecraft.block.material.Material;
import net.minecraft.block.state.IBlockState;
import net.minecraft.entity.EntityLiving;
import net.minecraft.entity.EnumCreatureType;
import net.minecraft.util.EnumFacing;
import net.minecraft.util.EnumParticleTypes;
import net.minecraft.util.math.AxisAlignedBB;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.World;
import net.minecraft.world.WorldServer;
import net.minecraft.world.biome.Biome;

import javax.annotation.Nonnull;
import java.util.Random;

/**
 * Created by Saad on 8/16/2016.
 */
public class BlockDarkBridge extends BlockLightBridgeBase {

	public BlockDarkBridge() {
		super("dark_bridge", Material.GLASS);
		setTickRandomly(true);
		setLightOpacity(150);
	}

	@Override
	public void randomTick( @Nonnull World worldIn, @Nonnull BlockPos pos, @Nonnull IBlockState state, @Nonnull Random random) {
		WorldServer world = (WorldServer) worldIn;
		if (world.getLightFromNeighbors(pos.up()) >= 9) return;

		AxisAlignedBB bb = new AxisAlignedBB(pos).grow(-7, 4, 7);
		int monsterCount = world.getEntitiesWithinAABB(EntityLiving.class, bb,
				input -> input != null && input.isCreatureType(EnumCreatureType.MONSTER, false)).size();

		if (monsterCount < 8) {
			Biome.SpawnListEntry entry = world.getSpawnListEntryForTypeAt(EnumCreatureType.MONSTER, pos);
			if (entry == null || !world.canCreatureTypeSpawnHere(EnumCreatureType.MONSTER, entry, pos))
				return;

			try {
				EntityLiving mob = entry.entityClass.getConstructor(World.class).newInstance(world);

				EnumFacing.Axis axis = state.getValue(FACING);
				if ( axis == EnumFacing.Axis.X || axis == EnumFacing.Axis.Z ) {
					mob.setLocationAndAngles(pos.getX() + 0.5F, pos.getY() + 1, pos.getZ() + 0.5F,
							world.rand.nextFloat() * 360.0F, 0.0F);

					if (mob.isNotColliding() && mob.getCanSpawnHere())
						world.spawnEntity(mob);
				}

			} catch (Exception exception) {
				exception.printStackTrace();
			}
		}
	}

	@Override
	public void randomDisplayTick(IBlockState stateIn, World worldIn, BlockPos pos, Random rand) {
		worldIn.spawnParticle(
				EnumParticleTypes.SMOKE_NORMAL,
				pos.getX() + rand.nextDouble(),
				pos.getY() + 1.01,
				pos.getZ() + rand.nextDouble(),
				0.0D, 0.0D, 0.0D);
	}

	@Override
	protected boolean checkEffect(Effect effect){
		return effect instanceof EffectBurn;
	}
	@Override
	protected BlockLightBridgeBase getBridgeBlock() {
		return ModBlocks.DARK_BRIDGE;
	}

	@Override
	public boolean shouldEmit(@Nonnull World world, @Nonnull BlockPos pos) {
		return false;
	}
}


text:
from __future__ import division

from pycho.world_objects import WorldObject, Bomb
from pycho.world.world_exceptions import *

from pycho.hivemind import Action

from random import randint, choice

try:
    xrange(1)
except NameError:
    xrange = range

class OldGrumper(WorldObject):
    def __init__(self,
        x,
        y,
        color,
        facing,
        health=3,
        scale=1,
        speed=1,
        *args,
        **kwargs):
        WorldObject.__init__(self, x, y, color, facing, health=3, scale=scale, *args, **kwargs)

    def populated_at(self, x, y):
        """ returns a list of tuples containing the coordinates of populated
            squares, should the square be at this point
        """

        #   #
        #  ###
        #   #
        #-># #
        #  01234
        populated = []
        populate = lambda i, j, color: populated.append((x + i, y + j, color))

        scaled_x = 5 * self.scale
        scaled_y = 4 * self.scale

        middle_x = int(scaled_x / 2)
        middle_y = int(scaled_y / 2)

        ## TODO: fix y scaling

        # bottom and top lines
        for i in xrange(scaled_x):
            populate(i, 0, self.color)

            populate(i, scaled_y - 2, (0.5, 1, 0))

        # connector

        populate(middle_x, 1, (1, 0, 0))
        populate(middle_x, scaled_y - 1, (1, 0, 0))

        return populated

    def take_damage(self, damage, other):
        if other is self:
            return
        WorldObject.take_damage(self, damage, other)

    def deal_damage(self, other):
        other.take_damage(0.1, self)

    @Action('move away from player', type='defence')
    def move_away_from_player(self, world):
        try:
            direction = world.direction_to_object(self, world.player)
            # jitter
            if randint(0, 100) < 10:
                direction = DIRECTIONS[choice(DIRECTIONS.keys())]

            self.facing = opposite_direction(direction)
            self.move(world, self.facing, 1)
        except CollisionException as e:
            e.other.take_damage(other, self)
        except OutOfWorldException:
            pass

    @Action('stay still', type='defence')
    def stay_still(self, world):
        self.facing = DIRECTIONS['still']

    @Action('move towards player', type='attack')
    def move_towards_player(self, world):
        try:
            self.facing = world.direction_to_object(self, world.player)
            self.move(world, self.facing, 1)
        except CollisionException as e:
            e.other.take_damage(5, self)
        except OutOfWorldException:
            pass

    def tick(self, world):
        behavior = choice(['attack', 'attack', 'attack', 'attack' 'defence'])
        self.mind.next_move(behavior)(world)


text:
/* Commentary:
 *
 */

/* Change log:
 *
 */

#pragma once

#include "dtkComposerNodeLeaf.h"

class dtkComposerNodeProxyPrivate;

class  dtkComposerNodeProxy : public dtkComposerNodeLeaf
{
public:
     dtkComposerNodeProxy(void);
    ~dtkComposerNodeProxy(void);

public:
    inline QString type(void) {
        return "proxy";
    }

    inline QString titleHint(void) {
        return "Proxy";
    }

private:
    dtkComposerNodeProxyPrivate *d;
};


text:
'use strict';

var User = function(socket) {
  return Object.defineProperties(this, {
    _socket: {
      value: socket,
      writable: true
    },
    id: {
      value: require('node-uuid').v4(),
      writable: false
    },
    room: {
      value: null,
      writable: true
    }
  });
};

User.prototype = Object.create(require('eventemitter2').EventEmitter2.prototype);

module.exports = User;


text:
package modprune

import (
	"context"
	"fmt"

	"github.com/bufbuild/buf/private/buf/bufcli"
	"github.com/bufbuild/buf/private/bufpkg/bufconfig"
	"github.com/bufbuild/buf/private/bufpkg/bufconnect"
	"github.com/bufbuild/buf/private/bufpkg/buflock"
	"github.com/bufbuild/buf/private/bufpkg/bufmodule"
	"github.com/bufbuild/buf/private/bufpkg/bufmodule/bufmoduleref"
	"github.com/bufbuild/buf/private/gen/proto/connect/buf/alpha/registry/v1alpha1/registryv1alpha1connect"
	registryv1alpha1 "github.com/bufbuild/buf/private/gen/proto/go/buf/alpha/registry/v1alpha1"
	"github.com/bufbuild/buf/private/pkg/app/appcmd"
	"github.com/bufbuild/buf/private/pkg/app/appflag"
	"github.com/bufbuild/buf/private/pkg/connectclient"
	"github.com/bufbuild/buf/private/pkg/storage/storageos"
	"github.com/bufbuild/connect-go"
	"github.com/spf13/cobra"
)

// NewCommand returns a new prune Command.
func NewCommand(
	name string,
	builder appflag.Builder,
) *appcmd.Command {
	return &appcmd.Command{
		Use:   name + " <directory>",
		Short: "Prunes unused dependencies from the " + buflock.ExternalConfigFilePath + " file.",
		Long:  `The first argument is the directory of the local module to prune. Defaults to "." if no argument is specified.`,
		Args:  cobra.MaximumNArgs(1),
		Run: builder.NewRunFunc(
			func(ctx context.Context, container appflag.Container) error {
				return run(ctx, container)
			},
			bufcli.NewErrorInterceptor(),
		),
	}
}

// run tidy to trim the buf.lock file for a specific module.
func run(
	ctx context.Context,
	container appflag.Container,
) error {
	directoryInput, err := bufcli.GetInputValue(container, "", ".")
	if err != nil {
		return err
	}
	storageosProvider := storageos.NewProvider(storageos.ProviderWithSymlinks())
	readWriteBucket, err := storageosProvider.NewReadWriteBucket(
		directoryInput,
		storageos.ReadWriteBucketWithSymlinksIfSupported(),
	)
	if err != nil {
		return err
	}
	existingConfigFilePath, err := bufconfig.ExistingConfigFilePath(ctx, readWriteBucket)
	if err != nil {
		return err
	}
	if existingConfigFilePath == "" {
		return bufcli.ErrNoConfigFile
	}
	config, err := bufconfig.GetConfigForBucket(ctx, readWriteBucket)
	if err != nil {
		return err
	}
	remote := bufconnect.DefaultRemote
	if config.ModuleIdentity != nil && config.ModuleIdentity.Remote() != "" {
		remote = config.ModuleIdentity.Remote()
	}
	clientConfig, err := bufcli.NewConnectClientConfig(container)
	if err != nil {
		return err
	}
	service := connectclient.Make(clientConfig, remote, registryv1alpha1connect.NewResolveServiceClient)

	module, err := bufmodule.NewModuleForBucket(ctx, readWriteBucket)
	if err != nil {
		return fmt.Errorf("couldn't read current dependencies: %w", err)
	}

	requestReferences, err := referencesPinnedByLock(config.Build.DependencyModuleReferences, module.DependencyModulePins())
	if err != nil {
		return err
	}
	var dependencyModulePins []bufmoduleref.ModulePin
	if len(requestReferences) > 0 {
		resp, err := service.GetModulePins(
			ctx,
			connect.NewRequest(&registryv1alpha1.GetModulePinsRequest{
				ModuleReferences: bufmoduleref.NewProtoModuleReferencesForModuleReferences(requestReferences...),
			}),
		)
		if err != nil {
			if connect.CodeOf(err) == connect.CodeUnimplemented && remote != bufconnect.DefaultRemote {
				return bufcli.NewUnimplementedRemoteError(err, remote, config.ModuleIdentity.IdentityString())
			}
			return err
		}
		dependencyModulePins, err = bufmoduleref.NewModulePinsForProtos(resp.Msg.ModulePins...)
		if err != nil {
			return bufcli.NewInternalError(err)
		}
	}
	if err := bufmoduleref.PutDependencyModulePinsToBucket(ctx, readWriteBucket, dependencyModulePins); err != nil {
		return err
	}
	return nil
}

// referencesPinnedByLock takes moduleReferences and a list of pins, then
// returns a new list of moduleReferences with the same identity, but their
// reference set to the commit of the pin with the corresponding identity.
func referencesPinnedByLock(moduleReferences []bufmoduleref.ModuleReference, modulePins []bufmoduleref.ModulePin) ([]bufmoduleref.ModuleReference, error) {
	pinsByIdentity := make(map[string]bufmoduleref.ModulePin, len(modulePins))
	for _, modulePin := range modulePins {
		pinsByIdentity[modulePin.IdentityString()] = modulePin
	}

	var pinnedModuleReferences []bufmoduleref.ModuleReference
	for _, moduleReference := range moduleReferences {
		pin, ok := pinsByIdentity[moduleReference.IdentityString()]
		if !ok {
			return nil, fmt.Errorf(`can't tidy with dependency %q: no corresponding entry found in buf.lock. Use "mod update" first if this is a new dependency`, moduleReference.IdentityString())
		}
		newModuleReference, err := bufmoduleref.NewModuleReference(
			moduleReference.Remote(),
			moduleReference.Owner(),
			moduleReference.Repository(),
			pin.Commit(),
		)
		if err != nil {
			return nil, err
		}
		pinnedModuleReferences = append(pinnedModuleReferences, newModuleReference)
	}
	return pinnedModuleReferences, nil
}