text:
import copy
import textwrap
import unittest
from contextlib import contextmanager

import mock
from twitter.common import log
from twitter.common.contextutil import temporary_file
from twitter.common.quantity import Amount, Time

from apache.aurora.admin.host_maintenance import HostMaintenance
from apache.aurora.client.api import AuroraClientAPI
from apache.aurora.client.base import add_grouping, remove_grouping
from apache.aurora.common.cluster import Cluster

from gen.apache.aurora.api.ttypes import (
    Hosts,
    HostStatus,
    MaintenanceMode,
    MaintenanceStatusResult,
    Response,
    ResponseCode,
    Result,
    StartMaintenanceResult
)

DEFAULT_CLUSTER = Cluster(
    name='us-west',
    scheduler_uri='us-west-234.example.com:8888',
)
TEST_HOSTNAMES = [
    'us-west-001.example.com',
    'us-west-002.example.com',
    'us-west-003.example.com']

class TestHostMaintenance(unittest.TestCase):
  @mock.patch("apache.aurora.client.api.AuroraClientAPI.maintenance_status",
      spec=AuroraClientAPI.maintenance_status)
  @mock.patch("apache.aurora.client.api.AuroraClientAPI.drain_hosts",
      spec=AuroraClientAPI.drain_hosts)
  @mock.patch("threading._Event.wait")
  def test_drain_hosts(self, mock_event_wait, mock_drain_hosts, mock_maintenance_status):
    fake_maintenance_status_response = [
        Response(
            responseCode=ResponseCode.OK,
            result=Result(maintenanceStatusResult=MaintenanceStatusResult(set([
                HostStatus(host=TEST_HOSTNAMES[0], mode=MaintenanceMode.SCHEDULED),
                HostStatus(host=TEST_HOSTNAMES[1], mode=MaintenanceMode.SCHEDULED),
                HostStatus(host=TEST_HOSTNAMES[2], mode=MaintenanceMode.SCHEDULED)
            ])))),
        Response(
            responseCode=ResponseCode.OK,
            result=Result(maintenanceStatusResult=MaintenanceStatusResult(set([
                HostStatus(host=TEST_HOSTNAMES[0], mode=MaintenanceMode.DRAINING),
                HostStatus(host=TEST_HOSTNAMES[1], mode=MaintenanceMode.DRAINING),
                HostStatus(host=TEST_HOSTNAMES[2], mode=MaintenanceMode.DRAINING)
            ])))),
        Response(
            responseCode=ResponseCode.OK,
            result=Result(maintenanceStatusResult=MaintenanceStatusResult(set([
                HostStatus(host=TEST_HOSTNAMES[0], mode=MaintenanceMode.DRAINING),
                HostStatus(host=TEST_HOSTNAMES[1], mode=MaintenanceMode.DRAINED),
                HostStatus(host=TEST_HOSTNAMES[2], mode=MaintenanceMode.DRAINED)
            ])))),
        Response(
            responseCode=ResponseCode.OK,
            result=Result(maintenanceStatusResult=MaintenanceStatusResult(set([
                HostStatus(host=TEST_HOSTNAMES[0], mode=MaintenanceMode.DRAINED)
            ]))))]

    fake_maintenance_status_call_args = []
    def fake_maintenance_status_side_effect(hosts):
      fake_maintenance_status_call_args.append(copy.deepcopy(hosts))
      return fake_maintenance_status_response.pop(0)

    mock_drain_hosts.return_value = Response(responseCode=ResponseCode.OK)
    mock_maintenance_status.side_effect = fake_maintenance_status_side_effect
    test_hosts = Hosts(set(TEST_HOSTNAMES))
    maintenance = HostMaintenance(DEFAULT_CLUSTER, 'quiet')

    not_drained_hostnames = maintenance._drain_hosts(test_hosts)
    assert len(not_drained_hostnames) == 0
    mock_drain_hosts.assert_called_once_with(test_hosts)
    assert mock_maintenance_status.call_count == 4
    assert mock_event_wait.call_count == 4
    assert fake_maintenance_status_call_args == [
        (Hosts(set(TEST_HOSTNAMES))),
        (Hosts(set(TEST_HOSTNAMES))),
        (Hosts(set(TEST_HOSTNAMES))),
        (Hosts(set([TEST_HOSTNAMES[0]])))]

  @mock.patch("twitter.common.log.warning", spec=log.warning)
  @mock.patch("apache.aurora.client.api.AuroraClientAPI.maintenance_status",
              spec=AuroraClientAPI.maintenance_status)
  @mock.patch("apache.aurora.client.api.AuroraClientAPI.drain_hosts",
              spec=AuroraClientAPI.drain_hosts)
  @mock.patch("threading._Event.wait")
  def test_drain_hosts_timed_out_wait(self, _, mock_drain_hosts, mock_maintenance_status, mock_log):
    fake_maintenance_status_response = Response(
        responseCode=ResponseCode.OK,
        result=Result(maintenanceStatusResult=MaintenanceStatusResult(set([
          HostStatus(host=TEST_HOSTNAMES[0], mode=MaintenanceMode.SCHEDULED),
          HostStatus(host=TEST_HOSTNAMES[1], mode=MaintenanceMode.SCHEDULED),
          HostStatus(host=TEST_HOSTNAMES[2], mode=MaintenanceMode.SCHEDULED)
        ]))))

    mock_drain_hosts.return_value = Response(responseCode=ResponseCode.OK)
    mock_maintenance_status.return_value = fake_maintenance_status_response
    test_hosts = Hosts(set(TEST_HOSTNAMES))
    maintenance = HostMaintenance(DEFAULT_CLUSTER, 'quiet')
    maintenance.MAX_STATUS_WAIT = Amount(1, Time.MILLISECONDS)

    not_drained_hostnames = maintenance._drain_hosts(test_hosts)
    assert TEST_HOSTNAMES == sorted(not_drained_hostnames)
    assert mock_maintenance_status.call_count == 1
    mock_drain_hosts.assert_called_once_with(test_hosts)
    mock_maintenance_status.assert_called_once_with((Hosts(set(TEST_HOSTNAMES))))
    assert mock_log.mock_calls == [mock.call(textwrap.dedent("""\
        Failed to move all hosts into DRAINED within 1 ms:
        \tHost:us-west-001.example.com\tStatus:SCHEDULED
        \tHost:us-west-002.example.com\tStatus:SCHEDULED
        \tHost:us-west-003.example.com\tStatus:SCHEDULED"""))]

  @mock.patch("twitter.common.log.warning", spec=log.warning)
  @mock.patch("apache.aurora.client.api.AuroraClientAPI.maintenance_status",
      spec=AuroraClientAPI.maintenance_status)
  @mock.patch("apache.aurora.client.api.AuroraClientAPI.end_maintenance",
      spec=AuroraClientAPI.end_maintenance)
  def test_complete_maintenance(self, mock_end_maintenance, mock_maintenance_status, mock_warning):
    mock_maintenance_status.return_value = Response(result=Result(
        maintenanceStatusResult=MaintenanceStatusResult(set([
            HostStatus(host=TEST_HOSTNAMES[0], mode=MaintenanceMode.NONE),
            HostStatus(host=TEST_HOSTNAMES[1], mode=MaintenanceMode.NONE),
            HostStatus(host=TEST_HOSTNAMES[2], mode=MaintenanceMode.DRAINED)
        ]))
    ))
    mock_end_maintenance.return_value = Response(responseCode=ResponseCode.OK)
    test_hosts = Hosts(set(TEST_HOSTNAMES))
    maintenance = HostMaintenance(DEFAULT_CLUSTER, 'quiet')
    maintenance._complete_maintenance(test_hosts)
    mock_end_maintenance.assert_called_once_with(test_hosts)
    mock_maintenance_status.assert_called_once_with(test_hosts)
    mock_warning.assert_called_once_with('%s is DRAINING or in DRAINED' % TEST_HOSTNAMES[2])

  @mock.patch("apache.aurora.admin.host_maintenance.HostMaintenance._complete_maintenance",
    spec=HostMaintenance._complete_maintenance)
  def test_end_maintenance(self, mock_complete_maintenance):
    maintenance = HostMaintenance(DEFAULT_CLUSTER, 'quiet')
    maintenance.end_maintenance(TEST_HOSTNAMES)
    mock_complete_maintenance.assert_called_once_with(Hosts(set(TEST_HOSTNAMES)))

  @mock.patch("apache.aurora.client.api.AuroraClientAPI.start_maintenance",
      spec=AuroraClientAPI.start_maintenance)
  def test_start_maintenance(self, mock_api):
    mock_api.return_value = Response(responseCode=ResponseCode.OK,
        result=Result(startMaintenanceResult=StartMaintenanceResult(statuses=set([HostStatus()]))))
    maintenance = HostMaintenance(DEFAULT_CLUSTER, 'quiet')
    maintenance.start_maintenance(TEST_HOSTNAMES)
    mock_api.assert_called_once_with(Hosts(set(TEST_HOSTNAMES)))

  def test_operate_on_hosts(self):
    mock_callback = mock.Mock()
    maintenance = HostMaintenance(DEFAULT_CLUSTER, 'quiet')
    maintenance._operate_on_hosts(TEST_HOSTNAMES, mock_callback)
    assert mock_callback.call_count == 3

  @mock.patch("apache.aurora.admin.host_maintenance.HostMaintenance._drain_hosts",
    spec=HostMaintenance._drain_hosts)
  @mock.patch("apache.aurora.admin.host_maintenance.HostMaintenance.start_maintenance",
    spec=HostMaintenance.start_maintenance)
  @mock.patch("apache.aurora.admin.host_maintenance.HostMaintenance._check_sla",
    spec=HostMaintenance._check_sla)
  @mock.patch("apache.aurora.admin.host_maintenance.HostMaintenance._operate_on_hosts",
    spec=HostMaintenance._operate_on_hosts)
  def test_perform_maintenance(self, mock_operate_on_hosts, mock_check_sla, mock_start_maintenance,
                               mock_drain_hosts):
    mock_callback = mock.Mock()
    mock_check_sla.return_value = set()
    mock_start_maintenance.return_value = TEST_HOSTNAMES
    drain_hosts_results = [set() for _ in TEST_HOSTNAMES]
    drain_hosts_results[0] = set([TEST_HOSTNAMES[0]])
    def drain_hosts_result(*args):
      return drain_hosts_results.pop(0)
    mock_drain_hosts.side_effect = drain_hosts_result
    maintenance = HostMaintenance(DEFAULT_CLUSTER, 'quiet')
    maintenance.perform_maintenance(TEST_HOSTNAMES, callback=mock_callback)
    mock_start_maintenance.assert_called_once_with(TEST_HOSTNAMES)
    assert mock_check_sla.call_count == 3
    assert mock_drain_hosts.call_count == 3
    assert mock_drain_hosts.call_args_list == [
        mock.call(Hosts(set([hostname]))) for hostname in TEST_HOSTNAMES]
    assert mock_operate_on_hosts.call_count == 3
    assert mock_operate_on_hosts.call_args_list == [mock.call(set(), mock_callback)] + [
        mock.call(set([hostname]), mock_callback) for hostname in TEST_HOSTNAMES[1:]]

  @mock.patch("apache.aurora.admin.host_maintenance.HostMaintenance._drain_hosts",
              spec=HostMaintenance._drain_hosts)
  @mock.patch("apache.aurora.admin.host_maintenance.HostMaintenance.start_maintenance",
              spec=HostMaintenance.start_maintenance)
  @mock.patch("apache.aurora.admin.host_maintenance.HostMaintenance._check_sla",
              spec=HostMaintenance._check_sla)
  def test_perform_maintenance_partial_sla_failure(self, mock_check_sla, mock_start_maintenance,
                               mock_drain_hosts):
    failed_host = 'us-west-001.example.com'
    mock_check_sla.return_value = set([failed_host])
    mock_start_maintenance.return_value = TEST_HOSTNAMES
    drained_hosts = set(TEST_HOSTNAMES) - set([failed_host])
    mock_drain_hosts.return_value = set()
    maintenance = HostMaintenance(DEFAULT_CLUSTER, 'quiet')

    with temporary_file() as fp:
      with group_by_rack():
        drained = maintenance.perform_maintenance(
            TEST_HOSTNAMES,
            grouping_function='by_rack',
            output_file=fp.name)

        with open(fp.name, 'r') as fpr:
          content = fpr.read()
          assert failed_host in content

        mock_start_maintenance.assert_called_once_with(TEST_HOSTNAMES)
        assert len(drained) == 2
        assert failed_host not in drained
        assert mock_check_sla.call_count == 1
        assert mock_drain_hosts.call_count == 1
        assert mock_drain_hosts.call_args_list == [mock.call(Hosts(drained_hosts))]

  @mock.patch("apache.aurora.client.api.AuroraClientAPI.maintenance_status",
      spec=AuroraClientAPI.maintenance_status)
  def test_check_status(self, mock_maintenance_status):
    mock_maintenance_status.return_value = Response(responseCode=ResponseCode.OK, result=Result(
        maintenanceStatusResult=MaintenanceStatusResult(set([
            HostStatus(host=TEST_HOSTNAMES[0], mode=MaintenanceMode.DRAINING),
            HostStatus(host=TEST_HOSTNAMES[1], mode=MaintenanceMode.DRAINED),
            HostStatus(host=TEST_HOSTNAMES[2], mode=MaintenanceMode.NONE)
        ]))
    ))
    maintenance = HostMaintenance(DEFAULT_CLUSTER, 'quiet')
    result = maintenance.check_status(TEST_HOSTNAMES)
    mock_maintenance_status.assert_called_once_with(Hosts(set(TEST_HOSTNAMES)))

    assert len(result) == 3
    assert (TEST_HOSTNAMES[0], MaintenanceMode._VALUES_TO_NAMES[MaintenanceMode.DRAINING]) in result
    assert (TEST_HOSTNAMES[1], MaintenanceMode._VALUES_TO_NAMES[MaintenanceMode.DRAINED]) in result
    assert (TEST_HOSTNAMES[2], MaintenanceMode._VALUES_TO_NAMES[MaintenanceMode.NONE]) in result

def test_default_grouping():
  example_host_list = [
    'xyz321.example.com',
    'bar337.example.com',
    'foo001.example.com',
  ]

  batches = list(HostMaintenance.iter_batches(example_host_list))
  assert batches[0] == Hosts(set(['bar337.example.com']))
  assert batches[1] == Hosts(set(['foo001.example.com']))
  assert batches[2] == Hosts(set(['xyz321.example.com']))

def test_none_grouping():
  example_host_list = [
    'xyz321.example.com',
    'bar337.example.com',
    'foo001.example.com',
  ]

  batches = list(HostMaintenance.iter_batches(example_host_list, 'none'))
  assert batches[0] == Hosts(set(example_host_list))
  assert len(batches) == 1

@contextmanager
def group_by_rack():
  add_grouping('by_rack', rack_grouping)
  yield
  remove_grouping('by_rack')

def rack_grouping(hostname):
  return hostname.split('-')[1]

def test_rack_grouping():
  example_host_list = [
    'west-aaa-001.example.com',
    'west-aaa-002.example.com',
    'west-xyz-002.example.com',
    'east-xyz-003.example.com',
    'east-xyz-004.example.com',
  ]

  with group_by_rack():
    batches = list(HostMaintenance.iter_batches(example_host_list, 'by_rack'))
    assert batches[0] == Hosts(set([
        'west-aaa-001.example.com',
        'west-aaa-002.example.com'
    ]))
    assert batches[1] == Hosts(set([
        'west-xyz-002.example.com',
        'east-xyz-003.example.com',
        'east-xyz-004.example.com',
    ]))


text:
Cloud-PyDashie
########

PyDashie is a port of `Dashing <https://github.com/Shopify/dashing>`_ by `Shopify <http://www.shopify.com/>`_ to Python 2.7

This is simply an implementation of pydashie tailored to showing information about an openstack cluster with nagios/icinga for monitoring. It is primarily for internal use by maintainers of openstack deloyments, as the current flask file servicing may be somewhat unsafe for public access.

It uses the standard python clients for collecting formation from openstack across multiple regions.

The nagios/icinga data is currently collected via ssh but in future might be moved to MKlivestatus as the current method is roundabout.

.. image:: https://raw.githubusercontent.com/catalyst/openstack-pydashie/master/mainscreen.png

**NOTE**: The current layout is hardcoded for 1080p. This might be changed to be configurable by the conf.yaml later. If you need to change the sizing, you can do so by changing the widget dimensions and number of columns within this function:

    https://github.com/catalyst/openstack-pydashie/blob/master/pydashie/assets/javascripts/app.js#L336

Configuration
############

Configuration is handled via a yaml file as follows:

.. code-block:: yaml

    main:
        log_file: pydashie.log
    openstack:
        allocation:
            RegionOne:
                vcpus_allocation_ratio: 2.0
                ram_allocation_ratio: 1.0
                # remove this amount per node available metric:
                reserved_ram_per_node: 0
                reserved_vcpus_per_node: 0
                # remove this amount from total
                # to take into account possible nova evacuate:
                reserved_vcpus: 0
                # ram in bytes
                reserved_ram: 0
                # total IPs are here as getting this from Neutron is
                # far from straightforward
                total_floating_ips: 256
        auth:
            auth_url: 'http://localhost:5000/v2.0'
            username: 'admin'
            password: 'openstack'
            project_name: 'demo'
            insecure: False
    nagios:
        services:
            RegionOne:
                statfile: './RegionOne-status.dat'
                host: 'RegionOne-mon0'
                username: 'admin'

Because of differences between allocation per region, and the need for a region list, each region is given it's own allocation data. We use this to know which regions to build clients for and aggregate data over, but in future might try and query a for a full region list and for allocation data from openstack itself.

The nagios collection relies on a local ssh key for the given username, and access for that key on the given host.

Widgets
############

Info on adding/removing/updating widgets will go here later.

Installation
############

**NOTE**: Development/deployment has been done in a Ubuntu environment, so the following might be different for you. Also, the following is a step by step guide for installing into a clean server.

Some of the python libraries have certain requirements, and the app itself needs a javascript service to deal with javascript files. As such you will need the following packages:

    sudo apt-get install python-dev nodejs

You will ideally want to run the app inside a virtualenv. If you don't have virtualenv installed you can get it via:

    sudo apt-get install python-virtualenv

And then create the environment by (this will create a directory for the environment, so be careful where you do this):

    virtualenv <name_of_environment>

To then activate it:

    source <name_of_environment>/bin/activate

Now that you are in your environment, you will need to install all the required python libraries:

    pip install -r requirements.txt

At this point you can install the app itself.

For development purposes use:

    python setup.py develop

Which will build a python egg pointing to the local git files so that you can edit them and just restart the service when you change them.

If you aren't planning to develop or edit the files:

    python setup.py install

But if the files are changed, or you pull an update, you will need to rerun the install.

Running
############

Provided you have a conf with working credentials and correctly named regions, you can run the application by:

    pydashie -c conf.yaml

Goto localhost:5050 to view the application in action.

**NOTE**: Getting the app up and running quickly with just openstack credentials is relatively easy, and you can simply comment out the nagios samplers from:

     https://github.com/catalyst/openstack-pydashie/blob/master/pydashie/openstack_app.py

The port and interface can also be set via the commandline:

    pydashie -c conf.yaml -ip 0.0.0.0 -p 5050

Although they default to 0.0.0.0 and 5050 if not manually given.

redpajama_set_name: RedPajamaGithub


text:
class stats_c
{
	public:
		double	Minimum;
		double	Maximum;
		double	Total;
		double	Average();

		int		Attempts;
		int		Connects;
		int		Failures;

		void	UpdateMaxMin(double value);
		int		GetStatisticsString(pcc_t stats);
};


text:
import React from "react";
import { storiesOf } from "@storybook/react";
import { number } from "@storybook/addon-knobs";

import ProgressBar from "./ProgressBar";

storiesOf("ProgressBar", module).add("Basic", () => {
  const value = number("Value", 42);
  return (
    <div>
      <ProgressBar value={value} />
      <ProgressBar appearance="secondary" value={value} />
      <ProgressBar appearance="danger" value={value} />
      <ProgressBar appearance="success" value={value} />
      <ProgressBar appearance="dark" value={value} />
    </div>
  );
});


text:
package io.reactivex.internal.operators.flowable;

import java.util.concurrent.Callable;

import org.junit.Test;
import org.reactivestreams.Subscriber;

import io.reactivex.*;
import io.reactivex.functions.Function;
import io.reactivex.internal.functions.Functions;
import io.reactivex.internal.operators.flowable.FlowableMapNotification.MapNotificationSubscriber;
import io.reactivex.internal.subscriptions.BooleanSubscription;
import io.reactivex.processors.PublishProcessor;
import io.reactivex.subscribers.TestSubscriber;

public class FlowableMapNotificationTest {
    @Test
    public void testJust() {
        TestSubscriber<Object> ts = new TestSubscriber<Object>();
        Flowable.just(1)
        .flatMap(
                new Function<Integer, Flowable<Object>>() {
                    @Override
                    public Flowable<Object> apply(Integer item) {
                        return Flowable.just((Object)(item + 1));
                    }
                },
                new Function<Throwable, Flowable<Object>>() {
                    @Override
                    public Flowable<Object> apply(Throwable e) {
                        return Flowable.error(e);
                    }
                },
                new Callable<Flowable<Object>>() {
                    @Override
                    public Flowable<Object> call() {
                        return Flowable.never();
                    }
                }
        ).subscribe(ts);

        ts.assertNoErrors();
        ts.assertNotComplete();
        ts.assertValue(2);
    }

    @Test
    public void backpressure() {
        TestSubscriber<Object> ts = TestSubscriber.create(0L);

        new FlowableMapNotification<Integer, Integer>(Flowable.range(1, 3),
                new Function<Integer, Integer>() {
                    @Override
                    public Integer apply(Integer item) {
                        return item + 1;
                    }
                },
                new Function<Throwable, Integer>() {
                    @Override
                    public Integer apply(Throwable e) {
                        return 0;
                    }
                },
                new Callable<Integer>() {
                    @Override
                    public Integer call() {
                        return 5;
                    }
                }
        ).subscribe(ts);

        ts.assertNoValues();
        ts.assertNoErrors();
        ts.assertNotComplete();

        ts.request(3);

        ts.assertValues(2, 3, 4);
        ts.assertNoErrors();
        ts.assertNotComplete();

        ts.request(1);

        ts.assertValues(2, 3, 4, 5);
        ts.assertNoErrors();
        ts.assertComplete();
    }

    @Test
    public void noBackpressure() {
        TestSubscriber<Object> ts = TestSubscriber.create(0L);

        PublishProcessor<Integer> ps = PublishProcessor.create();

        new FlowableMapNotification<Integer, Integer>(ps,
                new Function<Integer, Integer>() {
                    @Override
                    public Integer apply(Integer item) {
                        return item + 1;
                    }
                },
                new Function<Throwable, Integer>() {
                    @Override
                    public Integer apply(Throwable e) {
                        return 0;
                    }
                },
                new Callable<Integer>() {
                    @Override
                    public Integer call() {
                        return 5;
                    }
                }
        ).subscribe(ts);

        ts.assertNoValues();
        ts.assertNoErrors();
        ts.assertNotComplete();

        ps.onNext(1);
        ps.onNext(2);
        ps.onNext(3);
        ps.onComplete();

        ts.assertNoValues();
        ts.assertNoErrors();
        ts.assertNotComplete();

        ts.request(1);

        ts.assertValue(0);
        ts.assertNoErrors();
        ts.assertComplete();

    }

    @Test
    public void dispose() {
        TestHelper.checkDisposed(new Flowable<Integer>() {
            @SuppressWarnings({ "rawtypes", "unchecked" })
            @Override
            protected void subscribeActual(Subscriber<? super Integer> observer) {
                MapNotificationSubscriber mn = new MapNotificationSubscriber(
                        observer,
                        Functions.justFunction(Flowable.just(1)),
                        Functions.justFunction(Flowable.just(2)),
                        Functions.justCallable(Flowable.just(3))
                );
                mn.onSubscribe(new BooleanSubscription());
            }
        });
    }

    @Test
    public void doubleOnSubscribe() {
        TestHelper.checkDoubleOnSubscribeFlowable(new Function<Flowable<Object>, Flowable<Integer>>() {
            @Override
            public Flowable<Integer> apply(Flowable<Object> o) throws Exception {
                return o.flatMap(
                        Functions.justFunction(Flowable.just(1)),
                        Functions.justFunction(Flowable.just(2)),
                        Functions.justCallable(Flowable.just(3))
                );
            }
        });
    }
}


text:
FROM ubuntu:14.04
MAINTAINER Mitja Kleider <mitja@kleider.name>

# Do not ask questions during installation.
ENV DEBIAN_FRONTEND noninteractive

# upgrade packages
RUN apt-get -qq update
RUN apt-get -qqy upgrade

# install base packages
RUN apt-get -qqy install git build-essential zlib1g-dev automake libtool xutils-dev make cmake pkg-config nodejs-legacy curl python

# install C++11 capable GCC
RUN apt-get -qqy install gcc-4.8 g++-4.8

# glfw3 dependencies
RUN apt-get -qqy install libxi-dev libglu1-mesa-dev x11proto-randr-dev x11proto-xext-dev libxrandr-dev x11proto-xf86vidmode-dev libxxf86vm-dev libxcursor-dev

# workaround for build error in curl 7.36.0
# http://sourceforge.net/p/curl/bugs/1350/
# which will not occur if man-db is installed
RUN apt-get -qqy install man-db

# create user account
ENV USER mapuser
ENV HOME /home/mapuser
RUN adduser --disabled-password --gecos "" mapuser

# add repo
ADD ./mapbox-gl-native /home/mapuser/mapbox-gl-native
RUN chown -R mapuser:mapuser /home/mapuser/mapbox-gl-native

USER mapuser
WORKDIR /home/mapuser/mapbox-gl-native

RUN make setup
RUN make linux
WORKDIR /home/mapuser/mapbox-gl-native/build/Release

CMD ./mapbox-gl


text:
object Example extends App {

  final case class Foo[A](run: A ?=> Int)

}


text:
package com.djdch.log4j;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.core.LoggerContext;
import org.apache.logging.log4j.core.config.Configuration;
import org.apache.logging.log4j.core.config.LoggerConfig;
import org.apache.logging.log4j.core.layout.PatternLayout;
import org.junit.Before;
import org.junit.Test;

import java.io.IOException;
import java.util.UUID;
import java.util.concurrent.BlockingQueue;

import static org.junit.Assert.assertEquals;

public class AppenderTest {
    private static final Logger logger = LogManager.getLogger();

    private static final String LINE_SEPARATOR = System.getProperty("line.separator");

    @Before
    public void setUpAppender() throws IOException {
        final LoggerContext ctx = (LoggerContext) LogManager.getContext(false);
        final Configuration config = ctx.getConfiguration();
        final LoggerConfig root = config.getRootLogger();

        PatternLayout layout = PatternLayout.newBuilder().withPattern("[%p] %m%n").withConfiguration(config).build();
        QueuedConsoleAppender appender = QueuedConsoleAppender.createAppender(layout, null, "TestLogFile", "SYSTEM_OUT", "false", "true");

        appender.start();
        config.addAppender(appender);

        root.addAppender(appender, null, null);
        ctx.updateLoggers();
    }

    @Test
    public void testLogger() throws IOException {
        // Used to randomize message
        UUID uuid = UUID.randomUUID();

        // This message should always be logged
        logger.debug("Before shutdown " + uuid);

        // Shutdown Log4j
        QueuedConsoleAppender.setRunning(false);

        // This message should never be logged
        logger.debug("After shutdown " + uuid);

        // Get console appender queue
        BlockingQueue<String> queue = QueuedConsoleAppender.getOutputQueue();

        // Assert size
        assertEquals("Output queue should only contain one message", 1, queue.size());

        // Assert message
        assertEquals("Queued message should be equals to the first message", "[DEBUG] Before shutdown " + uuid + LINE_SEPARATOR, queue.peek());
    }
}


text:
import {Component} from 'angular2/core';

import {AfterContentParentComponent} from './after-content.component';
import {AfterViewParentComponent} from './after-view.component';
import {CounterParentComponent} from './counter.component';
import {DoCheckParentComponent} from './do-check.component';
import {OnChangesParentComponent} from './on-changes.component';
import {PeekABooParentComponent} from './peek-a-boo-parent.component';
import {SpyParentComponent} from './spy.component';

@Component({
  selector: 'my-app',
  templateUrl: 'app/app.component.html',
  directives: [
    AfterContentParentComponent,
    AfterViewParentComponent,
    CounterParentComponent,
    DoCheckParentComponent,
    OnChangesParentComponent,
    PeekABooParentComponent,
    SpyParentComponent,
  ]
})
export class AppComponent {
}


text:
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

/*============================================================================
**
** Source:  test2.c
**
** Purpose: Test #2 for the vfprintf function. Tests the string specifier
**          (%s).
**
**
**==========================================================================*/

#include <palsuite.h>
#include "../vfprintf.h"

int __cdecl main(int argc, char *argv[])
{

    if (PAL_Initialize(argc, argv))
    {
        return FAIL;
    }

    DoStrTest("foo %s", "bar", "foo bar");
    DoStrTest("foo %hs", "bar", "foo bar");
    DoWStrTest("foo %ls", convert("bar"), "foo bar");
    DoWStrTest("foo %ws", convert("bar"), "foo bar");
    DoStrTest("foo %Ls", "bar", "foo bar");
    DoStrTest("foo %I64s", "bar", "foo bar");
    DoStrTest("foo %5s", "bar", "foo   bar");
    DoStrTest("foo %.2s", "bar", "foo ba");
    DoStrTest("foo %5.2s", "bar", "foo    ba");
    DoStrTest("foo %-5s", "bar", "foo bar  ");
    DoStrTest("foo %05s", "bar", "foo 00bar");
    DoStrTest("foo %s", NULL, "foo (null)");
    DoStrTest("foo %hs", NULL, "foo (null)");
    DoStrTest("foo %ls", NULL, "foo (null)");
    DoStrTest("foo %ws", NULL, "foo (null)");
    DoStrTest("foo %Ls", NULL, "foo (null)");
    DoStrTest("foo %I64s", NULL, "foo (null)");

    PAL_Terminate();
    return PASS;
}


text:
package com.blackjack.api.filters;

import com.blackjack.api.services.TokenAuthenticationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.GenericFilterBean;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

@Component
public class JWTAuthenticationFilter extends GenericFilterBean {

    private TokenAuthenticationService tokenAuthenticationService;

    @Autowired
    JWTAuthenticationFilter(TokenAuthenticationService tokenAuthenticationService) {
        this.tokenAuthenticationService = tokenAuthenticationService;
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) throws
            IOException, ServletException {
        Authentication authentication = tokenAuthenticationService.getAuthentication((HttpServletRequest) request);
        SecurityContextHolder.getContext().setAuthentication(authentication);
        filterChain.doFilter(request, response);
    }

}


text:
<?php

namespace zpt\cdt;

use \DirectoryIterator;
use \Exception;

/**
 * This class is responsible for loading any PHP libraries installed along side
 * Conductor.
 *
 * TODO Update dependency directory structures to comply with PSR-0
 *      https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-0.md
 *
 * @author Philip Graham <philip@zeptech.ca>
 */
class Loader {

  /* Whether or not dependencies have been loaded or not */
  private static $_loaded = false;

  /**
   * Verify that conductor dependencies are installed and register their
   * autoloaders.
   *
   * @param string $root Root path for the website
   * @param object $loader Composer loader
   */
  public static function registerDependencies($root, $loader) {
    if (self::$_loaded) {
      return;
    }
    self::$_loaded = true;

    $lib = "$root/lib";
    $cdt = "$lib/conductor";
    $cdtLib = "$cdt/lib";
    $target = "$root/target";

    $optLibs = array(
      'pdf' => 'php-pdf'
    );

    foreach ($optLibs as $optLib => $optLibPath) {
      if (file_exists("$lib/$optLibPath")) {
        $loader->add("zpt\\$optLib", "$lib/$optLibPath");
      }
    }

    // Register loaders for the site's modules
    if (file_exists("$root/modules")) {
      $dir = new DirectoryIterator("$root/modules");
      foreach ($dir as $mod) {
        $modName = $mod->getBasename();

        $loader->add("zpt\\mod\\$modName", $mod->getPathName());
      }
    }
  }
}


text:
package spoukfw

import (
	"crypto/md5"
	"fmt"
	"github.com/nu7hatch/gouuid"
	"time"
	"errors"
)

type (
	SpoukCSRF struct {
		TimeActive time.Duration
		TimeStart  time.Time
		Salt       string
		Key        *uuid.UUID
		ReadyKey   string
		Csrf_form  func() (*string, error)
		Csrf_head  func() (*string, error)
	}
)
func NewSpoukCSRF(minutesActive int, salt string) (*SpoukCSRF) {
	n := &SpoukCSRF{
		TimeActive: time.Duration(minutesActive) * time.Minute,
		TimeStart: time.Now(),
		Salt:salt,
	}
	u, err := uuid.NewV4()
	if err != nil {
		return nil
	}
	n.Key = u
	n.Csrf_form = n.wrapper(true, false)
	n.Csrf_head = n.wrapper(false, true)
	return n
}
func (c *SpoukCSRF) wrapper(form, head bool) (func() (*string, error)) {
	return func() (*string, error) {
		_tmptime := c.TimeStart.Add(c.TimeActive)
		if _tmptime.Before(time.Now()) {
			c.TimeStart = time.Now()
			u, err := uuid.NewV4()
			if err != nil {
				return nil, errors.New("[CSRF] [csrf_form] error generate uuid")
			}
			c.Key = u
		}
		r := fmt.Sprintf("%x", md5.Sum([]byte(fmt.Sprintf("%v%v", c.Key, c.Salt))))
		c.ReadyKey = r
		var result string
		if form {
			result = fmt.Sprintf(`<input type="hidden" name="csrf_token" value="%s"> `, r)
		} else if head {
			result = fmt.Sprintf(`<meta id="csrf_token_ajax" content="%s" name="csrf_token_ajax" />`, r)
		}
		return &result, nil
	}
}
func (c SpoukCSRF) VerifyToken(s *SpoukCarry) bool {
	token := s.GetFormValue("csrf_token")
	if (token == c.ReadyKey) {
		return true
	}
	return false
}
func (c SpoukCSRF) VerifyTokenString(token string) bool {
	if (token == c.ReadyKey) {
		return true
	}
	return false
}


text:
module SpecHelper
    ( module Test.Hspec
    , module Envirius.Util
    ) where

import Test.Hspec
import Envirius.Util


text:
ACCEPTED

#### According to
International Plant Names Index

#### Published in
null

#### Original name
Tetrapodenia glandifera Gleason

### Remarks
null


text:
package de.uni.freiburg.iig.telematik.swat.misc;

public class OperatingSystem {

	public static OperatingSystems getOperatingSystem() {
		String OS = System.getProperty("os.name").toLowerCase();
		if (OS.contains("win"))
			return OperatingSystems.win;
		if (OS.contains("mac"))
			return OperatingSystems.mac;
		if (OS.contains("nux") || OS.contains("sunos"))
			return OperatingSystems.linux;
		return null;
	}

	public enum OperatingSystems {
		win, linux, mac;
	}

}


text:
package net.kyori.adventure.nbt;

import java.io.DataInput;
import java.io.DataOutput;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.file.Path;
import java.util.Map;
import java.util.zip.DeflaterOutputStream;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;
import java.util.zip.InflaterInputStream;
import org.jetbrains.annotations.NotNull;

/**
 * Serialization operations for binary tags.
 *
 * @since 4.0.0
 */
public final class BinaryTagIO {
  private BinaryTagIO() {
  }

  static {
    BinaryTagTypes.COMPOUND.id(); // initialize tag types
  }

  /**
   * Returns {@link Reader}, used to read binary tags.
   *
   *
There is a maximum depth of {@code 512} nested tags allowed, but no limit for the amount of containe data.

   *
   * @return binary tag reader
   * @since 4.4.0
   */
  public static @NotNull Reader unlimitedReader() {
    return BinaryTagReaderImpl.UNLIMITED;
  }

  /**
   * Returns {@link Reader}, used to read binary tags.
   *
   *
This reader has a size limit for the estimated number of data bytes for a tag.

   *
   * @return binary tag reader
   * @since 4.4.0
   */
  public static @NotNull Reader reader() {
    return BinaryTagReaderImpl.DEFAULT_LIMIT;
  }

  /**
   * Returns {@link Reader}, used to read binary tags.
   *
   *
This reader will limit the number of bytes read to the approximate size limit indicated.

   *
   * @return binary tag reader
   * @since 4.4.0
   */
  public static @NotNull Reader reader(final long sizeLimitBytes) {
    if (sizeLimitBytes <= 0) {
      throw new IllegalArgumentException("The size limit must be greater than zero");
    }
    return new BinaryTagReaderImpl(sizeLimitBytes);
  }

  /**
   * Returns {@link Writer}, used to write binary tags.
   *
   * @return binary tag writer
   * @since 4.4.0
   */
  public static @NotNull Writer writer() {
    return BinaryTagWriterImpl.INSTANCE;
  }

  /**
   * Reads a compound tag from {@code path}.
   *
   * @param path the path
   * @return the compound tag
   * @throws IOException if an exception was encountered while reading a compound tag
   * @deprecated since 4.4.0, use {@link #reader()}
   * @since 4.0.0
   */
  @Deprecated
  public static @NotNull CompoundBinaryTag readPath(final @NotNull Path path) throws IOException {
    return reader().read(path);
  }

  /**
   * Reads a compound tag from an input stream. The stream is not closed afterwards.
   *
   * @param input the input stream
   * @return the compound tag
   * @throws IOException if an exception was encountered while reading a compound tag
   * @deprecated since 4.4.0, use {@link #reader()}
   * @since 4.0.0
   */
  @Deprecated
  public static @NotNull CompoundBinaryTag readInputStream(final @NotNull InputStream input) throws IOException {
    return reader().read(input);
  }

  /**
   * Reads a compound tag from {@code path} using GZIP decompression.
   *
   * @param path the path
   * @return the compound tag
   * @throws IOException if an exception was encountered while reading a compound tag
   * @deprecated since 4.4.0, use {@link #reader()}
   * @since 4.0.0
   */
  @Deprecated
  public static @NotNull CompoundBinaryTag readCompressedPath(final @NotNull Path path) throws IOException {
    return reader().read(path, Compression.GZIP);
  }

  /**
   * Reads a compound tag from an input stream using GZIP decompression. The stream is not closed afterwards.
   *
   * @param input the input stream
   * @return the compound tag
   * @throws IOException if an exception was encountered while reading a compound tag
   * @deprecated since 4.4.0, use {@link #reader()}
   * @since 4.0.0
   */
  @Deprecated
  public static @NotNull CompoundBinaryTag readCompressedInputStream(final @NotNull InputStream input) throws IOException {
    return reader().read(input, Compression.GZIP);
  }

  /**
   * Reads a compound tag from {@code input}.
   *
   * @param input the input
   * @return the compound tag
   * @throws IOException if an exception was encountered while reading a compound tag
   * @deprecated since 4.4.0, use {@link #reader()}
   * @since 4.0.0
   */
  @Deprecated
  public static @NotNull CompoundBinaryTag readDataInput(final @NotNull DataInput input) throws IOException {
    return reader().read(input);
  }

  /**
   * Writes a compound tag to {@code path}.
   *
   * @param tag the compound tag
   * @param path the path
   * @throws IOException if an exception was encountered while writing the compound tag
   * @deprecated since 4.4.0, use {@link #writer()}
   * @since 4.0.0
   */
  @Deprecated
  public static void writePath(final @NotNull CompoundBinaryTag tag, final @NotNull Path path) throws IOException {
    writer().write(tag, path);
  }

  /**
   * Writes a compound tag to an output stream. The output stream will not be closed.
   *
   * @param tag the compound tag
   * @param output the output stream
   * @throws IOException if an exception was encountered while writing the compound tag
   * @deprecated since 4.4.0, use {@link #writer()}
   * @since 4.0.0
   */
  @Deprecated
  public static void writeOutputStream(final @NotNull CompoundBinaryTag tag, final @NotNull OutputStream output) throws IOException {
    writer().write(tag, output);
  }

  /**
   * Writes a compound tag to {@code path} using GZIP compression.
   *
   * @param tag the compound tag
   * @param path the path
   * @throws IOException if an exception was encountered while writing the compound tag
   * @deprecated since 4.4.0, use {@link #writer()}
   * @since 4.0.0
   */
  @Deprecated
  public static void writeCompressedPath(final @NotNull CompoundBinaryTag tag, final @NotNull Path path) throws IOException {
    writer().write(tag, path, Compression.GZIP);
  }

  /**
   * Writes a compound tag to an output stream using GZIP compression. The output stream is not closed afterwards.
   *
   * @param tag the compound tag
   * @param output the output stream
   * @throws IOException if an exception was encountered while writing the compound tag
   * @deprecated since 4.4.0, use {@link #writer()}
   * @since 4.0.0
   */
  @Deprecated
  public static void writeCompressedOutputStream(final @NotNull CompoundBinaryTag tag, final @NotNull OutputStream output) throws IOException {
    writer().write(tag, output, Compression.GZIP);
  }

  /**
   * Writes a compound tag to {@code output}.
   *
   * @param tag the compound tag
   * @param output the output
   * @throws IOException if an exception was encountered while writing the compound tag
   * @deprecated since 4.4.0, use {@link #writer()}
   * @since 4.0.0
   */
  @Deprecated
  public static void writeDataOutput(final @NotNull CompoundBinaryTag tag, final @NotNull DataOutput output) throws IOException {
    writer().write(tag, output);
  }

  /**
   * {@link CompoundBinaryTag} reader.
   *
   * @since 4.4.0
   */
  public interface Reader {
    /**
     * Reads a binary tag from {@code path}.
     *
     *
This is the equivalent of passing {@code Compression#NONE} as the second parameter to {@link #read(Path, Compression)}.

     *
     * @param path the path
     * @return a binary tag
     * @throws IOException if an exception was encountered while reading the tag
     * @since 4.4.0
     */
    default @NotNull CompoundBinaryTag read(final @NotNull Path path) throws IOException {
      return this.read(path, Compression.NONE);
    }

    /**
     * Reads a binary tag from {@code path} with a {@code compression} type.
     *
     * @param path the path
     * @param compression the compression type
     * @return a binary tag
     * @throws IOException if an exception was encountered while reading the tag
     * @since 4.4.0
     */
    @NotNull CompoundBinaryTag read(final @NotNull Path path, final @NotNull Compression compression) throws IOException;

    /**
     * Reads a binary tag from {@code input}.
     *
     *
This is the equivalent of passing {@code Compression#NONE} as the second parameter to {@link #read(InputStream, Compression)}.

     *
     * @param input the input stream
     * @return a binary tag
     * @throws IOException if an exception was encountered while reading the tag
     * @since 4.4.0
     */
    default @NotNull CompoundBinaryTag read(final @NotNull InputStream input) throws IOException {
      return this.read(input, Compression.NONE);
    }

    /**
     * Reads a binary tag from {@code input} with a {@code compression} type.
     *
     * @param input the input stream
     * @param compression the compression type
     * @return a binary tag
     * @throws IOException if an exception was encountered while reading the tag
     * @since 4.4.0
     */
    @NotNull CompoundBinaryTag read(final @NotNull InputStream input, final @NotNull Compression compression) throws IOException;

    /**
     * Reads a binary tag from {@code input}.
     *
     * @param input the input stream
     * @return a binary tag
     * @throws IOException if an exception was encountered while reading the tag
     * @since 4.4.0
     */
    @NotNull CompoundBinaryTag read(final @NotNull DataInput input) throws IOException;

    /**
     * Reads a binary tag, with a name, from {@code path}.
     *
     *
This is the equivalent of passing {@code Compression#NONE} as the second parameter to {@link #readNamed(Path, Compression)}.

     *
     * @param path the path
     * @return a binary tag
     * @throws IOException if an exception was encountered while reading the tag
     * @since 4.4.0
     */
    default Map.@NotNull Entry<String, CompoundBinaryTag> readNamed(final @NotNull Path path) throws IOException {
      return this.readNamed(path, Compression.NONE);
    }

    /**
     * Reads a binary tag, with a name, from {@code path}.
     *
     * @param path the path
     * @param compression the compression type
     * @return a binary tag
     * @throws IOException if an exception was encountered while reading the tag
     * @since 4.4.0
     */
    Map.@NotNull Entry<String, CompoundBinaryTag> readNamed(final @NotNull Path path, final @NotNull Compression compression) throws IOException;

    /**
     * Reads a binary tag, with a name, from {@code input}.
     *
     *
This is the equivalent of passing {@code Compression#NONE} as the second parameter to {@link #readNamed(InputStream, Compression)}.

     *
     * @param input the input stream
     * @return a binary tag
     * @throws IOException if an exception was encountered while reading the tag
     * @since 4.4.0
     */
    default Map.@NotNull Entry<String, CompoundBinaryTag> readNamed(final @NotNull InputStream input) throws IOException {
      return this.readNamed(input, Compression.NONE);
    }

    /**
     * Reads a binary tag, with a name, from {@code input}.
     *
     * @param input the input stream
     * @param compression the compression type
     * @return a binary tag
     * @throws IOException if an exception was encountered while reading the tag
     * @since 4.4.0
     */
    Map.@NotNull Entry<String, CompoundBinaryTag> readNamed(final @NotNull InputStream input, final @NotNull Compression compression) throws IOException;

    /**
     * Reads a binary tag, with a name, from {@code input}.
     *
     * @param input the input
     * @return a binary tag
     * @throws IOException if an exception was encountered while reading the tag
     * @since 4.4.0
     */
    Map.@NotNull Entry<String, CompoundBinaryTag> readNamed(final @NotNull DataInput input) throws IOException;
  }

  /**
   * {@link CompoundBinaryTag} writer.
   *
   * @since 4.4.0
   */
  public interface Writer {
    /**
     * Writes a binary tag to {@code path} with a {@code compression} type.
     *
     *
This is the equivalent of passing {@code Compression#NONE} as the second parameter to {@link #write(CompoundBinaryTag, Path, Compression)}.

     *
     * @param path the path
     * @throws IOException if an exception was encountered while reading the tag
     * @since 4.4.0
     */
    default void write(final @NotNull CompoundBinaryTag tag, final @NotNull Path path) throws IOException {
      this.write(tag, path, Compression.NONE);
    }

    /**
     * Writes a binary tag to {@code path} with a {@code compression} type.
     *
     * @param path the path
     * @param compression the compression type
     * @throws IOException if an exception was encountered while reading the tag
     * @since 4.4.0
     */
    void write(final @NotNull CompoundBinaryTag tag, final @NotNull Path path, final @NotNull Compression compression) throws IOException;

    /**
     * Writes a binary tag to {@code output}.
     *
     *
This is the equivalent of passing {@link Compression#NONE} as the second parameter to {@link #write(CompoundBinaryTag, OutputStream, Compression)}.

     *
     * @param output the output stream
     * @throws IOException if an exception was encountered while reading the tag
     * @since 4.4.0
     */
    default void write(final @NotNull CompoundBinaryTag tag, final @NotNull OutputStream output) throws IOException {
      this.write(tag, output, Compression.NONE);
    }

    /**
     * Writes a binary tag to {@code output} with a {@code compression} type.
     *
     * @param output the output stream
     * @param compression the compression type
     * @throws IOException if an exception was encountered while reading the tag
     * @since 4.4.0
     */
    void write(final @NotNull CompoundBinaryTag tag, final @NotNull OutputStream output, final @NotNull Compression compression) throws IOException;

    /**
     * Writes a binary tag to {@code output}.
     *
     * @param output the output
     * @throws IOException if an exception was encountered while reading the tag
     * @since 4.4.0
     */
    void write(final @NotNull CompoundBinaryTag tag, final @NotNull DataOutput output) throws IOException;

    /**
     * Writes a binary tag, with a name, to {@code path}.
     *
     *
This is the equivalent of passing {@code Compression#NONE} as the second parameter to {@link #write(CompoundBinaryTag, Path, Compression)}.

     *
     * @param path the path
     * @throws IOException if an exception was encountered while reading the tag
     * @since 4.4.0
     */
    default void writeNamed(final Map.@NotNull Entry<String, CompoundBinaryTag> tag, final @NotNull Path path) throws IOException {
      this.writeNamed(tag, path, Compression.NONE);
    }

    /**
     * Writes a binary tag, with a name, to {@code path} with a {@code compression} type.
     *
     * @param path the path
     * @param compression the compression type
     * @throws IOException if an exception was encountered while reading the tag
     * @since 4.4.0
     */
    void writeNamed(final Map.@NotNull Entry<String, CompoundBinaryTag> tag, final @NotNull Path path, final @NotNull Compression compression) throws IOException;

    /**
     * Writes a binary tag, with a name, to {@code output}.
     *
     *
This is the equivalent of passing {@code Compression#NONE} as the second parameter to {@link #write(CompoundBinaryTag, OutputStream, Compression)}.

     *
     * @param output the output stream
     * @throws IOException if an exception was encountered while reading the tag
     * @since 4.4.0
     */
    default void writeNamed(final Map.@NotNull Entry<String, CompoundBinaryTag> tag, final @NotNull OutputStream output) throws IOException {
      this.writeNamed(tag, output, Compression.NONE);
    }

    /**
     * Writes a binary tag, with a name, to {@code output} with a {@code compression} type.
     *
     * @param output the output stream
     * @param compression the compression type
     * @throws IOException if an exception was encountered while reading the tag
     * @since 4.4.0
     */
    void writeNamed(final Map.@NotNull Entry<String, CompoundBinaryTag> tag, final @NotNull OutputStream output, final @NotNull Compression compression) throws IOException;

    /**
     * Writes a binary tag, with a name, to {@code output}.
     *
     * @param output the output
     * @throws IOException if an exception was encountered while reading the tag
     * @since 4.4.0
     */
    void writeNamed(final Map.@NotNull Entry<String, CompoundBinaryTag> tag, final @NotNull DataOutput output) throws IOException;
  }

  /**
   * Compression types.
   *
   * @since 4.4.0
   */
  public static abstract class Compression {
    /**
     * No compression.
     *
     * @since 4.4.0
     */
    public static final Compression NONE = new Compression() {
      @Override
      @NotNull InputStream decompress(final @NotNull InputStream is) {
        return is;
      }

      @Override
      @NotNull OutputStream compress(final @NotNull OutputStream os) {
        return os;
      }

      @Override
      public String toString() {
        return "Compression.NONE";
      }
    };
    /**
     * GZIP compression.
     *
     * @since 4.4.0
     */
    public static final Compression GZIP = new Compression() {
      @Override
      @NotNull InputStream decompress(final @NotNull InputStream is) throws IOException {
        return new GZIPInputStream(is);
      }

      @Override
      @NotNull OutputStream compress(final @NotNull OutputStream os) throws IOException {
        return new GZIPOutputStream(os);
      }

      @Override
      public String toString() {
        return "Compression.GZIP";
      }
    };
    /**
     * ZLIB compression.
     *
     * @since 4.6.0
     */
    public static final Compression ZLIB = new Compression() {
      @Override
      @NotNull InputStream decompress(final @NotNull InputStream is) {
        return new InflaterInputStream(is);
      }

      @Override
      @NotNull OutputStream compress(final @NotNull OutputStream os) {
        return new DeflaterOutputStream(os);
      }

      @Override
      public String toString() {
        return "Compression.ZLIB";
      }
    };

    abstract @NotNull InputStream decompress(final @NotNull InputStream is) throws IOException;

    abstract @NotNull OutputStream compress(final @NotNull OutputStream os) throws IOException;
  }
}


text:
<action>
    <field name="string">Sales by Customer</field>
    <field name="view_cls">report_view</field>
    <field name="model">sale.order</field>
    <field name="condition">[["state","in",["confirmed","done"]]]</field>
    <field name="group_select">year,quarter,month,week,contact_id,contact_id.categ_id,user_id,state</field>
    <field name="function_select">agg_amount_total,agg_est_profit,agg_act_profit</field>
    <field name="group_fields">contact_id</field>
    <field name="agg_fields">agg_amount_total</field>
    <field name="menu">sale_menu</field>
</action>


text:
// ---------------------------------------------------------------------------------------
// <copyright file="Product.cs" company="Corale">
//     Copyright © 2015 by Adam Hellberg and Brandon Scott.
//
//     Permission is hereby granted, free of charge, to any person obtaining a copy of
//     this software and associated documentation files (the "Software"), to deal in
//     the Software without restriction, including without limitation the rights to
//     use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
//     of the Software, and to permit persons to whom the Software is furnished to do
//     so, subject to the following conditions:
//
//     The above copyright notice and this permission notice shall be included in all
//     copies or substantial portions of the Software.
//
//     THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
//     IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
//     FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
//     AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
//     WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
//     CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
//     Disclaimer: Corale and/or Colore is in no way affiliated with Razer and/or any
//     of its employees and/or licensors. Corale, Adam Hellberg, and/or Brandon Scott
//     do not take responsibility for any harm caused, direct or indirect, to any
//     Razer peripherals via the use of Colore.
//
//     "Razer" is a trademark of Razer USA Ltd.
// </copyright>
// ---------------------------------------------------------------------------------------

namespace Corale.Colore.Razer
{
    using Corale.Colore.Annotations;

    /// <summary>
    /// Chroma-supported products.
    /// </summary>
    [PublicAPI]
    public enum Product
    {
        /// <summary>
        /// No product.
        /// </summary>
        [PublicAPI]
        None = 0,

        /// <summary>
        /// The Razer BlackWidow Chroma.
        /// </summary>
        /// <remarks>
        /// Device Id = <c>2EA1BB63-CA28-428D-9F06-196B88330BBB</c>.
        /// </remarks>
        [PublicAPI]
        BlackWidowChroma,

        /// <summary>
        /// Invalid product.
        /// </summary>
        [PublicAPI]
        Invalid
    }
}


text:
yearmonth=`date +%Y%m`
daynumber=31

for i in {0..7}
do
	mysql -h 127.0.0.1  -uroot -e"create database IF NOT EXISTS record0$i default charset utf8;"
	for date in $(seq 1 $daynumber)
	do
		for j in {0..31}
		do
			K=`expr $i \* 32 + $j`
			X=$K
			M=`echo $X $yearmonth $date |awk '{printf "%03d%6d%02d",$1,$2,$3}'`
			echo CREATE TABLE RECORD0$M
			mysql -h 127.0.0.1 -uroot -e"use record0$i;create table RECORD0$M(\`SEQ_ID\` bigint(20) unsigned NOT NULL auto_increment,\`APP_ID\` int(11) unsigned  NOT NULL  default '0',\`RECORD_TYPE\` int(11) unsigned  NOT NULL  default '0',\`RELATION_ACCOUNT\` CHAR(128) NOT NULL default '',\`CHAT_TIME\` int(11) unsigned  NOT NULL  default '0',\`CHAT_ID\` CHAR(32) NOT NULL default '',\`MSG_TYPE\` int(11) unsigned  NOT NULL  default '0',\`CHAT_TEXT\` blob,\`INSERT_TIME\` timestamp NOT NULL default CURRENT_TIMESTAMP on update CURRENT_TIMESTAMP,PRIMARY KEY  (\`SEQ_ID\`), KEY \`SELECT_ANY_RECORD\` (\`RELATION_ACCOUNT\`, \`RECORD_TYPE\`, \`APP_ID\`), KEY \`SELECT_ACCOUNT\` (\`RELATION_ACCOUNT\`,\`APP_ID\`), KEY \`SELECT_CHAT_ID\` (\`CHAT_ID\`) ) ENGINE=MYISAM DEFAULT CHARSET=utf8;"
		done
	done
done


text:
import json
import uuid

import httpretty
import pytest

from mock import patch

from lecli.log import api

ID_WITH_VALID_LENGTH = str(uuid.uuid4())
MOCK_API_URL = 'http://mydummylink.com'
LOG_RESPONSE = {
    "log" : {
        "id" : "XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX",
        "name" : "Test Log",
        "logsets_info" : [{
            "id" : "XXXXXXXX-ABCD-ABCD-ABCD-XXXXXXXXXXXX",
            "name" : "Test Logset 1",
            "links" : {
                "rel" : "Self",
                "href" : "http://mydummyurl.com/management/logsets/XXXXXXXX-ABCD-ABCD-ABCD-XXXXXXXXXXXX"
            }
        },
        {
            "id" : "XXXXXXXX-DCBA-DCBA-DCBA-XXXXXXXXXXXX",
            "name" : "Test Logset 2",
            "links" : {
                "rel" : "Self",
                "href" : "http://mydummyurl.com/management/logsets/XXXXXXXX-DCBA-DCBA-DCBA-XXXXXXXXXXXX"
            }
        }],
        "source_type" : "token",
        "token_seed" : "12345678-abcd-efgh-ijkl-12345678",
        "tokens": [{}],
        "structures" : [{}],
        "user_data": {
            "LocationDescription" : "All logs for DC1",
            "le_hostname" : "testhost"
        }
    }
}

@httpretty.activate
@patch('lecli.api_utils.get_ro_apikey')
@patch('lecli.log.api._url')
def test_get_logs(mocked_url, mocked_ro_apikey, capsys):
    mocked_url.return_value = '', MOCK_API_URL
    mocked_ro_apikey.return_value = ID_WITH_VALID_LENGTH

    httpretty.register_uri(httpretty.GET, MOCK_API_URL,
                           status=200,
                           content_type='application/json',
                           body=json.dumps({}))

    api.get_logs()
    out, err = capsys.readouterr()
    assert not err

@httpretty.activate
@patch('lecli.api_utils.get_ro_apikey')
@patch('lecli.log.api._url')
def test_get_log(mocked_url, mocked_ro_apikey, capsys):
    mocked_url.return_value = '', MOCK_API_URL
    mocked_ro_apikey.return_value = ID_WITH_VALID_LENGTH

    httpretty.register_uri(httpretty.GET, MOCK_API_URL,
                           status=200,
                           content_type='application/json',
                           body=json.dumps(LOG_RESPONSE))

    api.get_log(ID_WITH_VALID_LENGTH)
    out, err = capsys.readouterr()

    assert not err

@httpretty.activate
@patch('lecli.api_utils.get_rw_apikey')
@patch('lecli.log.api._url')
def test_create_log_with_default_source_type(mocked_url, mocked_rw_apikey, capsys):
    mocked_url.return_value = '', MOCK_API_URL
    mocked_rw_apikey.return_value = ID_WITH_VALID_LENGTH

    httpretty.register_uri(httpretty.POST, MOCK_API_URL,
                           status=201,
                           body=json.dumps(LOG_RESPONSE),
                           content_type='application/json')

    api.create_log("Test Log", None)
    out, err = capsys.readouterr()

    assert 'Test Log' in out
    assert 'token' in out

@httpretty.activate
@patch('lecli.api_utils.get_rw_apikey')
@patch('lecli.log.api._url')
def test_create_log_with_source_type(mocked_url, mocked_rw_apikey, capsys):
    mocked_url.return_value = '', MOCK_API_URL
    mocked_rw_apikey.return_value = ID_WITH_VALID_LENGTH

    httpretty.register_uri(httpretty.POST, MOCK_API_URL,
                           status=201,
                           body='{"log": {"name": "test log","id": "2caec19c-d8a2-40ef-9c1e-91e89157fe28",'
                                '"source_type": "syslog","logsets_info": [{"id": "20a9b70b-e70c-4cb5-a4f6-0e40b60b7118","name": "logset"}]}}',
                           content_type = 'application/json')

    api.create_log("test log", None)
    out, err = capsys.readouterr()

    assert 'test log' in out
    assert 'syslog' in out

@httpretty.activate
@patch('lecli.api_utils.get_rw_apikey')
@patch('lecli.log.api._url')
def test_delete_log(mocked_url, mocked_rw_apikey, capsys):
    mocked_url.return_value = '', MOCK_API_URL
    mocked_rw_apikey.return_value = ID_WITH_VALID_LENGTH

    httpretty.register_uri(httpretty.DELETE, MOCK_API_URL, status=204)
    log_id = str(uuid.uuid4())
    api.delete_log(log_id)

    out, err = capsys.readouterr()
    assert "Deleted log with id: %s" % log_id in out

@httpretty.activate
@patch('lecli.api_utils.get_rw_apikey')
@patch('lecli.api_utils.get_ro_apikey')
@patch('lecli.log.api._url')
def test_rename_log(mocked_url, mocked_rw_apikey, mocked_ro_apikey, capsys):
    test_log_id = str(uuid.uuid4())
    mocked_url.return_value = '', MOCK_API_URL
    mocked_rw_apikey.return_value = ID_WITH_VALID_LENGTH
    mocked_ro_apikey.return_value = ID_WITH_VALID_LENGTH

    request_body = '{"log": {"name": "test.log", "logsets_info": [], "source_type": "token"}}'
    expected_result = '{"log": {"name": "new_test_log_name", "logsets_info": [], "source_type": "token"}}'

    httpretty.register_uri(httpretty.GET, MOCK_API_URL,
                           status=200,
                           content_type='application/json',
                           body=request_body)

    httpretty.register_uri(httpretty.PUT, MOCK_API_URL, status=200,
                           body = expected_result, content_type='application/json')

    new_name_for_log = "new_test_log_name"
    api.rename_log(test_log_id, new_name_for_log)
    out, err = capsys.readouterr()

    assert new_name_for_log in out

@httpretty.activate
@patch('lecli.api_utils.get_rw_apikey')
@patch('lecli.log.api._url')
def test_replace_log(mocked_url, mocked_rw_apikey, capsys):
    log_id = str(uuid.uuid4())

    request_body = '{"log": {"name": "test.log", "logsets_info": [], "source_type": "token"}}'
    mocked_rw_apikey.return_value = ID_WITH_VALID_LENGTH
    mocked_url.return_value = '', MOCK_API_URL

    httpretty.register_uri(httpretty.PUT, MOCK_API_URL, status=200, body=request_body,
                           content_type='application/json')

    api.replace_log(log_id, params=request_body)

    out, err = capsys.readouterr()
    assert "test.log" in out

@httpretty.activate
@patch('lecli.api_utils.get_rw_apikey')
@patch('lecli.api_utils.get_ro_apikey')
@patch('lecli.log.api._url')
@patch('lecli.logset.api._url')
def test_update_log(logset_url, log_url, mocked_ro_apikey, mocked_rw_apikey, capsys):
    test_log_id = str(uuid.uuid4())
    log_url.return_value = '', MOCK_API_URL
    logset_url.return_value = '', MOCK_API_URL

    mocked_rw_apikey.return_value = ID_WITH_VALID_LENGTH
    mocked_ro_apikey.return_value = ID_WITH_VALID_LENGTH

    request_body = '{"log": {"name": "test.log", "logsets_info": [], "source_type": "token"}}'
    expected_result = '{"log": {"name": "test.log", ' \
                      '"logsets_info": [{"id": "e227f890-7742-47b4-86b2-5ff1d345397e",' \
                      '"name": "test_logset"}], "source_type": "token"}}'

    httpretty.register_uri(httpretty.GET, MOCK_API_URL, status=200,
                           content_type='application/json', body=request_body)
    httpretty.register_uri(httpretty.GET, MOCK_API_URL, status=200,
                           content_type='application/json', body=request_body)
    httpretty.register_uri(httpretty.PUT, MOCK_API_URL, status=200,
                           content_type='application/json', body=expected_result)

    logset_info = {
        "logsets_info": [
            {
                "id": "e227f890-7742-47b4-86b2-5ff1d345397e",
                "name": "test_logset"
            }
        ]
    }

    api.update_log(test_log_id, logset_info)
    out, err = capsys.readouterr()

    assert "test_logset" in out

@httpretty.activate
@patch('lecli.api_utils.get_rw_apikey')
@patch('lecli.log.api._url')
def test_duplicate_log_id(mocked_url, mocked_rw_apikey):
    with pytest.raises(Exception) as exception:
        mocked_url.return_value = '', MOCK_API_URL
        mocked_rw_apikey.return_value = ID_WITH_VALID_LENGTH
        httpretty.register_uri(httpretty.POST, MOCK_API_URL, status=409, content_type='application/json')

        api.create_log('existing log')

        assert exception.value.message=='409'


text:
package org.simpleframework.http.socket.service;

import static org.simpleframework.http.socket.service.ServiceEvent.DISPATCH_SOCKET;
import static org.simpleframework.http.socket.service.ServiceEvent.ERROR;
import static org.simpleframework.http.socket.service.ServiceEvent.TERMINATE_SOCKET;

import org.simpleframework.http.Request;
import org.simpleframework.http.Response;
import org.simpleframework.http.socket.Session;
import org.simpleframework.transport.Channel;
import org.simpleframework.transport.trace.Trace;

/**
 * The SessionDispatcher object is used to perform the
 * opening handshake for a WebSocket session. Once the session has been
 * established it is connected to a Service where frames
 * can be sent and received. If for any reason the handshake fails
 * this will terminated the connection with a HTTP 400 response.
 *
 * @author Niall Gallagher
 */
class SessionDispatcher {

   /**
    * This is used to create the session for the WebSocket.
    */
   private final SessionBuilder builder;

   /**
    * This is used to select the service to dispatch to.
    */
   private final Router router;

   /**
    * Constructor for the SessionDispatcher object. The
    * dispatcher created will dispatch WebSocket sessions to a service
    * using the provided Router instance.
    *
    * @param builder this is used to build the WebSocket session
    * @param router this is used to select the service
    */
   public SessionDispatcher(SessionBuilder builder, Router router) {
      this.builder = builder;
      this.router = router;
   }

   /**
    * This method is used to create a dispatch a Session to
    * a specific service selected by a router. If the session initiating
    * handshake fails for any reason this will close the underlying TCP
    * connection and send a HTTP 400 response back to the client.
    *
    * @param request this is the session initiating request
    * @param response this is the session initiating response
    */
   public void dispatch(Request request, Response response) {
      Channel channel = request.getChannel();
      Trace trace = channel.getTrace();

      try {
         Service service = router.route(request, response);
         Session session = builder.create(request, response);

         trace.trace(DISPATCH_SOCKET);
         service.connect(session);
      } catch(Exception cause) {
         trace.trace(ERROR, cause);
         terminate(request, response);
      }
   }

   /**
    * This method is used to terminate the connection and commit the
    * response. Terminating the session before it has been dispatched
    * is done when there is a protocol or an unexpected I/O error with
    * the underlying TCP channel.
    *
    * @param request this is the session initiating request
    * @param response this is the session initiating response
    */
   public void terminate(Request request, Response response) {
      Channel channel = request.getChannel();
      Trace trace = channel.getTrace();

      try {
         response.close();
         channel.close();
         trace.trace(TERMINATE_SOCKET);
      } catch(Exception cause) {
         trace.trace(ERROR, cause);
      }
   }
}


text:
<?xml version="1.0"?>
<project xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"
    xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>com.mycom.bds</groupId>
        <artifactId>bds-main</artifactId>
        <version>1.0.0</version>
    </parent>
    <groupId>com.mycom.bds</groupId>
    <artifactId>bds-hbase</artifactId>
    <version>1.0.0</version>
    <name>bds-hbase</name>
	<properties>
	<hadoop-version>2.7.3</hadoop-version>
	</properties>
    <dependencies>
        <dependency>
            <groupId>org.apache.hbase</groupId>
            <artifactId>hbase-client</artifactId>
            <version>1.2.4</version>
        </dependency>
		<dependency>
			<groupId>org.apache.hadoop</groupId>
			<artifactId>hadoop-common</artifactId>
			<version>${hadoop-version}</version>
		</dependency>
		<dependency>
			<groupId>org.apache.hadoop</groupId>
			<artifactId>hadoop-auth</artifactId>
			<version>${hadoop-version}</version>
		</dependency>
		<dependency>
			<groupId>org.apache.hadoop</groupId>
			<artifactId>hadoop-client</artifactId>
			<version>${hadoop-version}</version>
		</dependency>
		<dependency>
			<groupId>org.apache.hadoop</groupId>
			<artifactId>hadoop-mapreduce-client-core</artifactId>
			<version>${hadoop-version}</version>
		</dependency>
		<dependency>
			<groupId>org.apache.hadoop</groupId>
			<artifactId>hadoop-mapreduce-client-jobclient</artifactId>
			<version>${hadoop-version}</version>
			<type>test-jar</type>
			<scope>test</scope>
		</dependency>
		<dependency>
			<groupId>org.apache.hadoop</groupId>
			<artifactId>hadoop-hdfs</artifactId>
			<version>${hadoop-version}</version>
		</dependency>
		<dependency>
			<groupId>org.apache.hadoop</groupId>
			<artifactId>hadoop-hdfs</artifactId>
			<version>${hadoop-version}</version>
			<type>test-jar</type>
			<scope>test</scope>
		</dependency>
		<dependency>
			<groupId>org.apache.hadoop</groupId>
			<artifactId>hadoop-minicluster</artifactId>
			<version>${hadoop-version}</version>
			<scope>test</scope>
		</dependency>
        <dependency>
            <groupId>commons-io</groupId>
            <artifactId>commons-io</artifactId>
            <version>2.5</version>
        </dependency>
    </dependencies>
</project>


text:
function printNumber(number) {
  var placeholder = document.getElementById("placeholder");
  placeholder.innerHTML = number;
}

var button = document.getElementById("button");

button.onclick = function () {
  var result = dice.roll();
  printNumber(result);
};


text:
struct FRAME {
    unsigned char kind; // frame kind : ack/nak/data
    unsigned char ack;
    unsigned char seq; // sequence number from 0 to MAX_SEQ
    unsigned char data[PKT_LEN];
    unsigned int padding; // give room to crc32
};

static unsigned char out_buffer[MAX_BUF][PKT_LEN]; // buffer to send
static unsigned char in_buffer[MAX_BUF][PKT_LEN]; // buffer to receive
static unsigned char nbuffered; // the use of buffers
static unsigned char frame_expected = 0; // lower bound of receive window
static unsigned char ack_expected = 0; // lower bound of send window
static unsigned char next_frame_to_send = 0; // upper bound of send window
static unsigned char too_far = MAX_BUF; // upper bound of receive window
int no_nak = 1 ; // only need one nak call for expect frame
int arrv[MAX_BUF]; // if the in_buffer is in use , make sure put_packet in order
int in_timer[MAX_TIMER]; // array of timer , to decide the time of unconfirmed frames

static int phl_ready = 0;

void inc_timer(void) // increase the timer of each unconfirmed frames
{
    int i;
    for(i = 0 ; i <= MAX_SEQ ; i++)
    {
        if(in_timer[i] >= 0)
            in_timer[i] ++;
    }
}

unsigned char get_oldest_frame(void) // get the oldest unconfirmed frame
{
    int i;
    int max_timer = -2;
    int of;

    for(i = 0;i<=MAX_SEQ;i++)
    {
        if(in_timer[i] > max_timer)
        {
            of = i;
            max_timer = in_timer[i];
        }
    }
    return  of;
}
static void put_frame(unsigned char *frame, int len)
{
    *(unsigned int *)(frame + len) = crc32(frame, len);
    send_frame(frame, len + 4);
    phl_ready = 0;
}
char inc(char c)
{
    return (c + 1) % (MAX_SEQ + 1);
}

static void send_ack_frame(void) // single ack to send
{
    struct FRAME s;

    s.kind = FRAME_ACK;
    s.ack = ( frame_expected + MAX_SEQ ) % (MAX_SEQ + 1);
    dbg_frame("Send ACK  %d\n", s.ack);
    put_frame((unsigned char *)&s, 2);
    stop_ack_timer();
}
static void send_data_frame(void)
{
    struct FRAME s;

    s.kind = FRAME_DATA;
    s.seq = next_frame_to_send;
    s.ack = ( frame_expected + MAX_SEQ ) % (MAX_SEQ + 1);
    memcpy(s.data, out_buffer[s.seq % MAX_BUF], PKT_LEN);
    dbg_frame("Send DATA %d %d, ID %d\n", s.seq, s.ack, *(short *)s.data);
    put_frame((unsigned char *)&s, 3 + PKT_LEN);
    start_timer(s.seq, DATA_TIMER);int event, arg;
    struct FRAME f;
    int len = 0; // the length of frame
    in_timer[s.seq]++; // let timer of s.seq -1 -> 0 ,to start timer
    inc_timer(); // increase every started timer
    stop_ack_timer();
}
static void send_nakdata_frame(unsigned char send_ack) // resend data frame due to nak
{
    struct FRAME s;

    s.kind = FRAME_DATA;
    s.seq =( send_ack + 1 ) % ( MAX_SEQ + 1);
    s.ack = ( frame_expected + MAX_SEQ ) % (MAX_SEQ + 1);
    memcpy(s.data, out_buffer[s.seq % MAX_BUF], PKT_LEN);
    dbg_frame("Send RESEND-DATA-TIMEOUT resendseq:%d ack:%d, ID %d\n",
               s.seq, s.ack, *(short *)s.data);
    put_frame((unsigned char *)&s, 3 + PKT_LEN);
    start_timer(s.seq, DATA_TIMER);
    in_timer[s.seq]++;
    inc_timer();
    stop_ack_timer();
}
static void send_timerout_data_frame(void) // resend data frame due to timeout
{
    struct FRAME s;

    s.kind = FRAME_DATA;
    s.seq = get_oldest_frame(); // send the oldest unconfirmed frame
    s.ack = ( frame_expected + MAX_SEQ ) % (MAX_SEQ + 1);
    memcpy(s.data, out_buffer[s.seq % MAX_BUF], PKT_LEN);
    dbg_frame("Send RESEND-DATA-NAK resendseq:%d ack:%d, ID %d\n",
               s.seq, s.ack, *(short *)s.data);
    put_frame((unsigned char *)&s, 3 + PKT_LEN);
    start_timer(s.seq, DATA_TIMER);
    in_timer[s.seq] = 0; // such frame become another unconfirmed frame
    inc_timer();
    stop_ack_timer();
}

static void send_nak_frame(void) // send single nak frame
{
    struct FRAME s;
    no_nak = 0;
    s.kind = FRAME_NAK;
    s.seq = 0;
    s.ack = ( frame_expected + MAX_SEQ ) % (MAX_SEQ + 1);
    dbg_frame("Send NAK req: %d\n", (s.ack + 1) % (MAX_SEQ + 1));
    put_frame((unsigned char *)&s, 3);
}

static int between(unsigned char a, unsigned char b, unsigned char c)
{
     // if the frame is in the window
    if( (a<=b && b<c) || (c<a &&a <=b) || (b<c && c<a) ) return 1;
    return 0;
}

int main(int argc, char **argv)
{
    int event, arg;
    struct FRAME f;
    int len = 0; // the length of frame
    int i;

    for( i = 0 ; i <= MAX_BUF - 1;i++) // initialize the buffer in use
        arrv[i] = 0;

    for( i = 0 ; i <= MAX_TIMER - 1 ; i++) // initialize the timer array
        in_timer[i] = -1;

    protocol_init(argc, argv);
    disable_network_layer();

    for (;;) {
        event = wait_for_event(&arg);

        switch (event) {
        case NETWORK_LAYER_READY:
            get_packet(out_buffer[next_frame_to_send % MAX_BUF]);
            send_data_frame();
            nbuffered++; // increase the buffer in use
            next_frame_to_send = inc(next_frame_to_send); // update the send-window
            break;

        case PHYSICAL_LAYER_READY:
            phl_ready = 1; // tag for enable network layer
            break;

        case FRAME_RECEIVED:
            //dbg_event("FRAME_RECEIVED\n");
            //for(i = 0;i<=MAX_SEQ;i++)
            //   lprintf("*%d ",in_timer[i]);
            //lprintf("\n");
            len = recv_frame((unsigned char *)&f, sizeof f);
            if (crc32((unsigned char *)&f, len) != 0)
            {
                dbg_frame("BAD CRC : %d\n",f.seq);
                if(no_nak == 1)
                    send_nak_frame(); // send nak due to bad crc32
                break; // no need for piggy-backing
            }
            if (f.kind == FRAME_DATA)
            {
                dbg_frame("Recv DATA %d %d, ID %d , PHL QUEUE: %d\n",
                           f.seq, f.ack, *(short *)f.data, phl_sq_len());
                if (f.seq != frame_expected && no_nak == 1) // not the expected frame
                    send_nak_frame();
                if(between(frame_expected,f.seq,too_far) && arrv[f.seq % MAX_BUF] == 0)
                {
                     // put frames to in_buffer
                    arrv[f.seq % MAX_BUF] = 1; // buffer is in use
                    memcpy(in_buffer[f.seq%MAX_BUF], f.data , PKT_LEN);
                    //lprintf("fe:%d\n",frame_expected);
                    //for(i = 0;i<=MAX_BUF -1 ;i++)
                    //    lprintf("%d:",arrv[i]);
                    //lprintf("\n");
                    while(arrv[frame_expected % MAX_BUF]) // check if is enable to put packet in order
                    {
                        arrv[frame_expected%MAX_BUF] = 0; // buffer is not in use
                        put_packet(in_buffer[frame_expected % MAX_BUF],len - 7);
                        no_nak = 1; // update the nak
                        start_ack_timer(ACK_TIMER); // see if to send single ack
                        frame_expected = inc(frame_expected); // update receive-window
                        too_far = inc(too_far);
                    }
                }
                //for(i = 0;i<=MAX_BUF -1 ;i++)
                //        lprintf("%d:",arrv[i]);
                //    lprintf("\n");
                //lprintf("--------\n");
            }
            if(f.kind == FRAME_ACK) // single ack
            {
                dbg_frame("!!!!recv lonely ack %d\n",f.ack);
            }
            if(f.kind == FRAME_NAK) // nak frame ,cautious : nak is taking ack as well
            {
                dbg_frame("!!!!recv lonely NAKNAK call for  %d\n",(f.ack + 1) % (MAX_SEQ + 1));
                if(between(ack_expected , (f.ack + 1) % (MAX_SEQ + 1) , next_frame_to_send))
                    // if the resend frame is in send-window
                    send_nakdata_frame(f.ack);
            }
            while(between(ack_expected , f.ack , next_frame_to_send)) // the process of piggy-backing
            {
                stop_timer(ack_expected);
                in_timer[ack_expected] = -1; // stop timer in array
                ack_expected = inc(ack_expected);
                nbuffered -- ;
            }
            break;

        case DATA_TIMEOUT:
            dbg_event("---- DATA %d timeout\n", arg);
            send_timerout_data_frame();
            break;

        case ACK_TIMEOUT:
            dbg_event("---- ACK %d timeout\n", arg);
            send_ack_frame();
            break;
        }
        if (nbuffered < MAX_BUF && phl_ready)
            enable_network_layer();
        else
            disable_network_layer();
   }
}


text:
package com.mozu.api.events;

import java.util.Date;

public class EventNotification {
    /**
     * The unique identifier for an event
     */
    public String eventId;

    /**
     * The topic of the event (i.e. product.created)
     */
    public String topic;

    /**
     * The ID of the entity that changed (i.e. product code)
     */
    public String entityId;

    /**
     * The date the event occurred
     */
    public Date timestamp;

    /**
     * The Correlation Id of the original API request that caused the event to
     * occur
     */
    public String correlationId;

    /**
     * Indicates whether this is a test request
     */
    public boolean isTest;

    public String getEventId() {
        return eventId;
    }

    public void setEventId(String eventId) {
        this.eventId = eventId;
    }

    public String getTopic() {
        return topic;
    }

    public void setTopic(String topic) {
        this.topic = topic;
    }

    public String getEntityId() {
        return entityId;
    }

    public void setEntityId(String entityId) {
        this.entityId = entityId;
    }

    public Date getTimestamp() {
        return timestamp;
    }

    public void setTimestamp(Date timestamp) {
        this.timestamp = timestamp;
    }

    public String getCorrelationId() {
        return correlationId;
    }

    public void setCorrelationId(String correlationId) {
        this.correlationId = correlationId;
    }

    public boolean isTest() {
        return isTest;
    }

    public void setTest(boolean isTest) {
        this.isTest = isTest;
    }
}


text:
<?php if (!defined('IDIR')) { die; }

/**
* drupal_004 Import Forum module
*
* @package			ImpEx.drupal
*
*/
class drupal_004 extends drupal_000
{
	var $_dependent 	= '003';

	function drupal_004(&$displayobject)
	{
		$this->_modulestring = $displayobject->phrases['import_forum'];
	}

	function init(&$sessionobject, &$displayobject, &$Db_target, &$Db_source)
	{
		if ($this->check_order($sessionobject,$this->_dependent))
		{
			if ($this->_restart)
			{
				if ($this->restart($sessionobject, $displayobject, $Db_target, $Db_source,'clear_imported_forums'))
				{
					$displayobject->display_now("
{$displayobject->phrases['forums_cleared']}
");
					$this->_restart = true;
				}
				else
				{
					$sessionobject->add_error(substr(get_class($this) , -3), $displayobject->phrases['forum_restart_failed'], $displayobject->phrases['check_db_permissions']);
				}
			}

			// Start up the table
			$displayobject->update_basic('title', $displayobject->phrases['import_forum']);
			$displayobject->update_html($displayobject->do_form_header('index',substr(get_class($this) , -3)));
			$displayobject->update_html($displayobject->make_hidden_code(substr(get_class($this) , -3),'WORKING'));
			$displayobject->update_html($displayobject->make_table_header($this->_modulestring));

			// Ask some questions
			$displayobject->update_html($displayobject->make_input_code($displayobject->phrases['forums_per_page'],'forumperpage',500));

			// End the table
			$displayobject->update_html($displayobject->do_form_footer($displayobject->phrases['continue'],$displayobject->phrases['reset']));

			// Reset/Setup counters for this
			$sessionobject->add_session_var(substr(get_class($this) , -3) . '_objects_done', '0');
			$sessionobject->add_session_var(substr(get_class($this) , -3) . '_objects_failed', '0');
			$sessionobject->add_session_var('forumstartat','0');
			$sessionobject->add_session_var('categoriesfinished','FALSE');
		}
		else
		{
			// Dependant has not been run
			$displayobject->update_html($displayobject->do_form_header('index',''));
			$displayobject->update_html($displayobject->make_description("
{$displayobject->phrases['dependant_on']} " . $sessionobject->get_module_title($this->_dependent) . " {$displayobject->phrases['cant_run']} ."));
			$displayobject->update_html($displayobject->do_form_footer($displayobject->phrases['continue'],''));
			$sessionobject->set_session_var(substr(get_class($this) , -3),'FALSE');
			$sessionobject->set_session_var('module','000');
		}
	}

	function resume(&$sessionobject, &$displayobject, &$Db_target, &$Db_source)
	{
		// Set up working variables.
		$displayobject->update_basic('displaymodules','FALSE');
		$target_database_type	= $sessionobject->get_session_var('targetdatabasetype');
		$target_table_prefix	= $sessionobject->get_session_var('targettableprefix');
		$source_database_type	= $sessionobject->get_session_var('sourcedatabasetype');
		$source_table_prefix	= $sessionobject->get_session_var('sourcetableprefix');

		// Per page vars
		$forum_start_at			= $sessionobject->get_session_var('forumstartat');
		$forum_per_page			= $sessionobject->get_session_var('forumperpage');
		$class_num				= substr(get_class($this) , -3);

		// Start the timing
		if(!$sessionobject->get_session_var($class_num . '_start'))
		{
			$sessionobject->timing($class_num ,'start' ,$sessionobject->get_session_var('autosubmit'));
		}

		if($sessionobject->get_session_var('categoriesfinished') == 'FALSE')
		{
			// Sort out the categories
			$categories_array = $this->get_drupal_cat_details($Db_source, $source_database_type, $source_table_prefix);

			$displayobject->display_now("
{$displayobject->phrases['importing']} " . count($categories_array) . " {$displayobject->phrases['categories']}
");

			$category_object = new ImpExData($Db_target, $sessionobject, 'forum');

			foreach ($categories_array as $cat_id => $cat)
			{
				$try = (phpversion() < '5' ? $category_object : clone($category_object));

				$try->set_value('mandatory', 'title', 				$cat['name']);
				$try->set_value('mandatory', 'displayorder',		$cat_id);
				$try->set_value('mandatory', 'parentid',			'-1');
				$try->set_value('mandatory', 'options',				$this->_default_cat_permissions);
				$try->set_value('mandatory', 'importforumid',		'0');
				$try->set_value('mandatory', 'importcategoryid',	$cat_id);

				$try->set_value('nonmandatory', 'description',		$forum_details['description']);

				if($try->is_valid())
				{
					if($try->import_category($Db_target, $target_database_type, $target_table_prefix))
					{
						$displayobject->display_now('
' . $try->how_complete() . '% ' . $displayobject->phrases['forum'] . ' -> ' . $try->get_value('mandatory', 'title'));
						$sessionobject->add_session_var($class_num  . '_objects_done', intval($sessionobject->get_session_var($class_num . '_objects_done')) + 1);
					}
					else
					{
						$sessionobject->set_session_var($class_num . '_objects_failed',$sessionobject->get_session_var($class_num. '_objects_failed') + 1 );
						$sessionobject->add_error($try->get_value('mandatory', 'importcategoryid'), $displayobject->phrases['forum_not_imported'], $displayobject->phrases['forum_not_imported_rem']);
						$displayobject->display_now("
{$displayobject->phrases['failed']} :: {$displayobject->phrases['forum_not_imported']}");
					}
				}
				else
				{
					$displayobject->display_now("
{$displayobject->phrases['invalid_object']}" . $try->_failedon);
					$sessionobject->set_session_var($class_num . '_objects_failed',$sessionobject->get_session_var($class_num. '_objects_failed') + 1 );
				}
				unset($try);
			}

			// Default Category
			$try = new ImpExData($Db_target, $sessionobject, 'forum');
			$try->set_value('mandatory', 'title', 				'Default Cat');
			$try->set_value('mandatory', 'displayorder',		'1');
			$try->set_value('mandatory', 'parentid',			'-1');
			$try->set_value('mandatory', 'importforumid',		'0');
			$try->set_value('mandatory', 'importcategoryid',	'99999');
			$try->set_value('mandatory', 'options',				$this->_default_cat_permissions);
			$try->set_value('nonmandatory', 'description', 		'This is a default category for imported forums');

			$try->import_category($Db_target, $target_db_type, $target_table_prefix);

			$sessionobject->add_session_var('categoriesfinished','TRUE');
		}
		else
		{
			// Get an array of forum details
			$forum_array 	= $this->get_drupal_forum_details($Db_source, $source_database_type, $source_table_prefix, $forum_start_at, $forum_per_page);

			$cat_ids_array = $this->get_category_ids($Db_target, $target_database_type, $target_table_prefix);

			// Display count and pass time
			$displayobject->display_now("
{$displayobject->phrases['importing']} " . count($forum_array) . " {$displayobject->phrases['forums']}

{$displayobject->phrases['from']} : " . $forum_start_at . " ::  {$displayobject->phrases['to']} : " . ($forum_start_at + count($forum_array)) . "
");

			$forum_object = new ImpExData($Db_target, $sessionobject, 'forum');

			foreach ($forum_array as $forum_id => $forum_details)
			{
				$try = (phpversion() < '5' ? $forum_object : clone($forum_object));

				// Mandatory
				$try->set_value('mandatory', 'displayorder',		'1');
				$try->set_value('mandatory', 'options',				$forum_details['options']);
				$try->set_value('mandatory', 'importcategoryid',	'0');

				if ($cat_ids_array["$forum_details[parent]"])
				{
					$try->set_value('mandatory', 'parentid',			$cat_ids_array["$forum_details[parent]"]);
				}
				else
				{
					$try->set_value('mandatory', 'parentid',			$cat_ids_array[99999]);
				}

				$try->set_value('mandatory', 'title',				$forum_details['name']);
				$try->set_value('mandatory', 'importforumid',		$forum_id);
				$try->set_value('mandatory', 'options',				$this->_default_forum_permissions);

				// Non Mandatory
				$try->set_value('nonmandatory', 'description',		$forum_details['description']);

				// Check if forum object is valid
				if($try->is_valid())
				{
					if($try->import_forum($Db_target, $target_database_type, $target_table_prefix))
					{
						$displayobject->display_now('
' . $try->how_complete() . '%' . $displayobject->phrases['forum'] . ' -> ' . $try->get_value('mandatory','title'));
						$sessionobject->add_session_var($class_num . '_objects_done',intval($sessionobject->get_session_var($class_num . '_objects_done')) + 1 );
					}
					else
					{
						$sessionobject->set_session_var($class_num . '_objects_failed',$sessionobject->get_session_var($class_num. '_objects_failed') + 1 );
						$sessionobject->add_error($forum_id, $displayobject->phrases['forum_not_imported'], $displayobject->phrases['forum_not_imported_rem']);
						$displayobject->display_now("
{$impex_phrases['failed']} :: {$displayobject->phrases['forum_not_imported']}");
					}
				}
				else
				{
					$displayobject->display_now("
{$impex_phrases['invalid_object']}" . $try->_failedon);
				}
				unset($try);
			}// End foreach

			if (count($forum_array) == 0 OR count($forum_array) < $forum_per_page)
			{
				$this->build_forum_child_lists($Db_target, $target_database_type, $target_table_prefix);

				#$this->get_out_of_sync_parentids($Db_target, $target_database_type, $target_table_prefix);

				$sessionobject->timing($class_num, 'stop', $sessionobject->get_session_var('autosubmit'));
				$sessionobject->remove_session_var($class_num . '_start');

				$displayobject->update_html($displayobject->module_finished($this->_modulestring,
					$sessionobject->return_stats($class_num, '_time_taken'),
					$sessionobject->return_stats($class_num, '_objects_done'),
					$sessionobject->return_stats($class_num, '_objects_failed')
				));

				$sessionobject->set_session_var($class_num, 'FINISHED');
				$sessionobject->set_session_var('module', '000');
				$sessionobject->set_session_var('autosubmit', '0');
			}
			$sessionobject->set_session_var('forumstartat',$forum_start_at+$forum_per_page);
		}
		$displayobject->update_html($displayobject->print_redirect('index.php',$sessionobject->get_session_var('pagespeed')));
	}// End resume
}//End Class
# Autogenerated on : April 27, 2006, 9:34 am
# By ImpEx-generator 2.1.
/*======================================================================*/
?>


text:
'use strict';

function trimLinebreaks(str) {
  // Remove leading and trailing linebreaks
  if (!str) {
    return str;
  }
  return str.replace(/^[\r\n]+|[\r\n]+$/g, '');
}

function standardizeLinebreaks(str) {
  // Replace windows and mac line endings to unix line endings convention
  if (!str) {
    return str;
  }
  return str.replace(/\r?\n|\r/g, '\n');
}

// A list of params which need values parsing
var ComplexParams = [
  'sg-angular-directive'
];

module.exports = {

  /* Parses additional KSS params for the styleguide */
  get: function(source) {

    // Remove comment markup from comments
    var comment = source.split(/\/\/[ ]?/).join('').split('/*').join('').split('*/').join(''),
      additionalKssParams = {},
      _this = this;

    comment = standardizeLinebreaks(comment);
    comment = trimLinebreaks(comment);

    comment.split('\n\n').forEach(function(markUpBlock) {

      var varName = markUpBlock.match(/([^:^\n]*):[\s\S]*\n/);
      if (varName && varName[1] !== undefined) {
        varName = varName[1].trim();
      }
      if (varName && varName.substring(0, 3) === 'sg-') {
        additionalKssParams[varName] = _this.getValue(varName, markUpBlock);
      }

    });

    return additionalKssParams;
  },

  /* Parses values */
  getValue: function(varName, source) {

    var body = source.substring(source.indexOf('\n') + 1),
      result;

    // Do not parse every variable
    if (ComplexParams.indexOf(varName) === -1) {
      result = body;
    } else {

      result = {};

      body.split('\n').forEach(function(line) {

        var keyVal = line.split(':').map(function(str) {
          str = str.trim();
          if (str.indexOf(',') !== -1) {
            str = str.split(',').map(function(s) {
              return s.trim();
            });
          }
          return str;
        });

        if (!result[keyVal[0]]) {
          // Define new value
          result[keyVal[0]] = keyVal[1];
        } else {
          // Add another value
          if (!(result[keyVal[0]] instanceof Array)) {
            result[keyVal[0]] = [
              result[keyVal[0]]
            ];
          }
          result[keyVal[0]].push(keyVal[1]);
        }

      });
    }

    return result;
  }

};


text:
package com.jacky.permanent;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.widget.Toast;

public class BootBroadcastReceiver extends BroadcastReceiver{

	@Override
	public void onReceive(Context context, Intent intent)
	{
		if (Intent.ACTION_BOOT_COMPLETED.equals(intent.getAction()))
		{
			Intent startServiceIntent = new Intent(context, MyService.class);
			startServiceIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
			context.startService(startServiceIntent);
		}
	}
}