text:
"""Tests for inference_gym.internal.test_util."""

import atexit
import functools

from absl import logging
import jax
import numpy as np
import tensorflow.compat.v2 as tf
# Don't rewrite this one.
import tensorflow.compat.v2 as otf  # pylint: disable=reimported
import tensorflow_probability as tfp

from tensorflow_probability.python.internal import test_util as tfp_test_util
from inference_gym import targets
from inference_gym.internal import test_util

tfd = tfp.distributions
tfb = tfp.bijectors

BACKEND = None  # Rewritten by backends/rewrite.py.

class TestModel(targets.Model):

  def __init__(self, bijector=None, ground_truth_mean=np.exp(1.5)):
    """Creates a test model.

    The defaults are 'correct', in that they correspond to the joint
    distribution defined herein. You can adjust them to make the model
    'incorrect' for testing purposes, e.g. an 'incorrect' `bijector` might not
    correctly constrain the values to the domain of the joint distribution. An
    'incorrect' `ground_truth_mean` is different from the true mean of the joint
    distribution.

    Args:
      bijector: Default event space bijector to use. Default: `tfb.Exp`.
      ground_truth_mean: What ground truth mean to use for the `'identity'`
        sample transformation.
    """
    self._distribution = tfd.LogNormal(1., 1.)

    if bijector is None:
      bijector = tfb.Exp()

    super(TestModel, self).__init__(
        default_event_space_bijector=bijector,
        event_shape=self._distribution.event_shape,
        dtype=self._distribution.dtype,
        name='test_model',
        pretty_name='TestModel',
        sample_transformations=dict(
            identity=targets.Model.SampleTransformation(
                fn=lambda x: x,
                pretty_name='Identity',
                ground_truth_mean=ground_truth_mean,
            ),),
    )

  def _unnormalized_log_prob(self, x):
    return self._distribution.log_prob(x)

  def sample(self, n, seed=None):
    return self._distribution.sample(n, seed=seed)

class TestModelWithDataset(targets.Model):

  def __init__(self, dataset, materialize_dataset=False):
    """Creates a model that uses a dataset.

    Args:
      dataset: A 1D Tensor.
      materialize_dataset: Python `bool`. If True, the dataset is erroneously
        materialized in the initializer.
    """
    self._distribution = tfd.Sample(tfd.Normal(0., 1.), dataset.shape[-1])
    if materialize_dataset:
      tf.convert_to_tensor(dataset)

    super(TestModelWithDataset, self).__init__(
        default_event_space_bijector=tfb.Identity(),
        event_shape=self._distribution.event_shape,
        dtype=self._distribution.dtype,
        name='test_model_width_dataset',
        pretty_name='TestModelWithDataset',
        sample_transformations=dict(
            identity=targets.Model.SampleTransformation(
                fn=lambda x: x,
                pretty_name='Identity',
                ground_truth_mean=0.,
            ),),
    )

  def _unnormalized_log_prob(self, x):
    return self._distribution.log_prob(x)

@test_util.multi_backend_test(globals(), 'internal.test_util_test')
class InferenceGymTestCaseTest(test_util.InferenceGymTestCase):

  # See _check_backends below.
  _BACKEND_TESTED = BACKEND

  def testActuallyRewritten(self):
    """Tests that this file is rewritten to actually use different backends."""
    a = tf.constant([0.]) + 1.
    expected_type = {
        'backend_tensorflow': otf.Tensor,
        'backend_numpy': np.ndarray,
        'backend_jax': jax.Array,
    }[BACKEND]
    self.assertIsInstance(a, expected_type)

  def testWellFormedModel(self):
    """A well formed model won't raise an error."""
    model = TestModel()
    self.validate_log_prob_and_transforms(
        model,
        sample_transformation_shapes=dict(identity=[]),
        check_ground_truth_mean=True)

  def testBadBijector(self):
    """Tests that an error is raised if bijector is incorrect."""
    model = TestModel(tfb.Identity())
    with self.assertRaisesRegex(AssertionError, 'Arrays are not equal'):
      self.validate_log_prob_and_transforms(
          model, sample_transformation_shapes=dict(identity=[]))

  def testBadShape(self):
    """Tests that an error is raised if expectations shapes are wrong."""
    model = TestModel()
    with self.assertRaisesRegex(AssertionError,
                                r'Checking outputs(.|\n)*Tuples differ'):
      self.validate_log_prob_and_transforms(
          model, sample_transformation_shapes=dict(identity=[13]))

  def testBadGroundTruth(self):
    """Tests that an error is raised if ground truth shapes are wrong."""
    model = TestModel(ground_truth_mean=np.array([1, 2]))
    with self.assertRaisesRegex(
        AssertionError, r'Checking ground truth mean(.|\n)*Tuples differ'):
      self.validate_log_prob_and_transforms(
          model,
          sample_transformation_shapes=dict(identity=[]),
          check_ground_truth_mean=True)

  @test_util.numpy_disable_gradient_test
  def testCorrectGroundTruthWithHMC(self):
    """Tests the ground truth with HMC for a well formed model."""
    model = TestModel()
    self.validate_ground_truth_using_hmc(
        model,
        num_chains=4,
        num_steps=2000,
        num_leapfrog_steps=10,
        step_size=1.,
    )

  @test_util.numpy_disable_gradient_test
  def testBadGroundTruthWithHMC(self):
    """Tests that an error is raised if the ground truth is wrong."""
    model = TestModel(ground_truth_mean=-1000.)
    with self.assertRaisesRegexp(AssertionError, 'Not equal to tolerance'):
      self.validate_ground_truth_using_hmc(
          model,
          num_chains=4,
          num_steps=2000,
          num_leapfrog_steps=10,
          step_size=1.,
      )

  def testCorrectGroundTruthWithMC(self):
    """Tests the ground truth with MC for a well formed model."""
    model = TestModel()
    self.validate_ground_truth_using_monte_carlo(
        model,
        num_samples=4000,
    )

  def testBadGroundTruthWithMC(self):
    """Tests that an error is raised if the ground truth is wrong."""
    model = TestModel(ground_truth_mean=-10.)
    with self.assertRaisesRegexp(AssertionError, 'Not equal to tolerance'):
      self.validate_ground_truth_using_monte_carlo(
          model,
          num_samples=4000,
      )

  def testCorrectMaterialization(self):
    """Tests the dataset materialization a well formed model."""
    dataset = np.zeros(5)
    self.validate_deferred_materialization(
        TestModelWithDataset, dataset=dataset)

  def testBadMaterialization(self):
    """Tests that an error is raised if dataset materialization is wrong."""
    dataset = np.zeros(5)
    with self.assertRaisesRegexp(AssertionError,
                                 'Erroneously materialized dataset'):
      self.validate_deferred_materialization(
          functools.partial(TestModelWithDataset, materialize_dataset=True),
          dataset=dataset)

def _check_backends():
  """Check that all the backends were tested.

  This works by collecting all the test cases in globals() and verifying that
  they were rewritten correctly. We assume that after that point, the test
  system works.
  """
  tested_backends = set()
  for test_case in globals().values():
    if hasattr(test_case, '_BACKEND_TESTED'):
      tested_backends.add(test_case._BACKEND_TESTED)

  expected_backends = set(
      ['backend_numpy', 'backend_jax', 'backend_tensorflow'])
  assert tested_backends == expected_backends, 'Missing backends: {}'.format(
      expected_backends - tested_backends)
  logging.info('Tested Inference Gym backends: %s.',
               ', '.join(expected_backends))

if BACKEND is None:
  # Only test this in the original module.
  atexit.register(_check_backends)

if __name__ == '__main__':
  tfp_test_util.main()


text:
package eu.binjr.core.data.adapters;

import eu.binjr.core.data.indexes.SearchHit;
import eu.binjr.core.data.indexes.parser.profile.ParsingProfile;
import eu.binjr.core.data.workspace.LogWorksheet;
import eu.binjr.core.data.workspace.Worksheet;
import eu.binjr.core.preferences.UserPreferences;
import jakarta.xml.bind.annotation.XmlAccessType;
import jakarta.xml.bind.annotation.XmlAccessorType;
import jakarta.xml.bind.annotation.XmlTransient;
import javafx.scene.paint.Color;

import java.util.Objects;

@XmlAccessorType(XmlAccessType.FIELD)
public class LogFilesBinding extends SourceBinding<SearchHit> {

    public static final String MIME_TYPE = "x-binjr/LogFilesBinding";
    private transient boolean indexed = false;

    @XmlTransient
    private final ParsingProfile parsingProfile;

    private LogFilesBinding() {
        super();
        this.parsingProfile = null;
    }

    public LogFilesBinding(String label,
                           String legend,
                           String path,
                           String treeHierarchy,
                           ParsingProfile parsingProfile,
                           DataAdapter<SearchHit> adapter) {
        super(label, legend, null, path, treeHierarchy, adapter);
        this.parsingProfile = parsingProfile;
    }

    @Override
    public String getMimeType() {
        return MIME_TYPE;
    }

    public ParsingProfile getParsingProfile() {
        return parsingProfile;
    }

    @Override
    public int hashCode() {
        return super.hashCode() +
                Objects.hashCode(parsingProfile);
    }

    @Override
    public boolean equals(Object obj) {
        return super.equals(obj) &&
                Objects.equals(parsingProfile, ((LogFilesBinding) obj).parsingProfile);
    }

    @Override
    public Class<? extends Worksheet<SearchHit>> getWorksheetClass() {
        return LogWorksheet.class;
    }

    @Override
    protected Color[] getDefaultColorPalette() {
        return UserPreferences.getInstance().logFilesColorPalette.get().getPalette();
    }

    public boolean isIndexed() {
        return indexed;
    }

    public void setIndexed(boolean indexed) {
        this.indexed = indexed;
    }

    public static class Builder extends SourceBinding.Builder<SearchHit, LogFilesBinding, Builder> {
        private ParsingProfile parsingProfile;

        @Override
        protected Builder self() {
            return this;
        }

        public LogFilesBinding.Builder withParsingProfile(ParsingProfile parsingProfile) {
            this.parsingProfile = parsingProfile;
            return self();
        }

        @Override
        protected LogFilesBinding construct(String label, String legend, Color color, String path, String treeHierarchy, DataAdapter<SearchHit> adapter) {
            return new LogFilesBinding(label, legend, path, treeHierarchy, parsingProfile, adapter);
        }
    }

}

redpajama_set_name: RedPajamaGithub


text:
using namespace Amiga;

// MARK: - Mouse.

int Mouse::get_number_of_buttons() {
	return 2;
}

void Mouse::set_button_pressed(int button, bool is_set) {
	switch(button) {
		case 0:
			cia_state_ = (cia_state_ &~ 0x40) | (is_set ? 0 : 0x40);
		break;
		default:
		break;
	}
}

uint8_t Mouse::get_cia_button() const {
	return cia_state_;
}

void Mouse::reset_all_buttons() {
	cia_state_ = 0xff;
}

void Mouse::move(int x, int y) {
	position_[0] += x;
	position_[1] += y;
}

uint16_t Mouse::get_position() {
	// The Amiga hardware retains only eight bits of position
	// for the mouse; its software polls frequently and maps
	// changes into a larger space.
	//
	// On modern computers with 5k+ displays and trackpads, it
	// proved empirically possible to overflow the hardware
	// counters more quickly than software would poll.
	//
	// Therefore the approach taken for mapping mouse motion
	// into the Amiga is to do it in steps of no greater than
	// [-128, +127], as per the below.
	const int pending[] = {
		position_[0], position_[1]
	};

	const int8_t change[] = {
		int8_t(std::clamp(pending[0], -128, 127)),
		int8_t(std::clamp(pending[1], -128, 127))
	};

	position_[0] -= change[0];
	position_[1] -= change[1];
	declared_position_[0] += change[0];
	declared_position_[1] += change[1];

	return uint16_t(
		(declared_position_[1] << 8) |
		declared_position_[0]
	);
}

// MARK: - Joystick.

// TODO: add second fire button.

Joystick::Joystick() :
	ConcreteJoystick({
						Input(Input::Up),
						Input(Input::Down),
						Input(Input::Left),
						Input(Input::Right),
						Input(Input::Fire, 0),
					}) {}

void Joystick::did_set_input(const Input &input, bool is_active) {
	// Accumulate state.
	inputs_[input.type] = is_active;

	// Determine what that does to the two position bits.
	const auto low =
		(inputs_[Input::Type::Down] ^ inputs_[Input::Type::Right]) |
		(inputs_[Input::Type::Right] << 1);
	const auto high =
		(inputs_[Input::Type::Up] ^ inputs_[Input::Type::Left]) |
		(inputs_[Input::Type::Left] << 1);

	// Ripple upwards if that affects the mouse position counters.
	const uint8_t previous_low = position_ & 3;
	uint8_t low_upper = (position_ >> 2) & 0x3f;
	const uint8_t previous_high = (position_ >> 8) & 3;
	uint8_t high_upper = (position_ >> 10) & 0x3f;

	if(!low && previous_low == 3) ++low_upper;
	if(!previous_low && low == 3) --low_upper;
	if(!high && previous_high == 3) ++high_upper;
	if(!previous_high && high == 3) --high_upper;

	position_ = uint16_t(
		low | ((low_upper & 0x3f) << 2) |
		(high << 8) | ((high_upper & 0x3f) << 10)
	);
}

uint16_t Joystick::get_position() {
	return position_;
}

uint8_t Joystick::get_cia_button() const {
	return inputs_[Input::Type::Fire] ? 0xbf : 0xff;
}


text:
<?php

namespace ZendTest\Crypt\Symmetric\Padding;

use Zend\Crypt\Symmetric\Padding\Pkcs7;

class Pkcs7Test extends \PHPUnit_Framework_TestCase
{
    /** @var Pkcs7 */
    public $padding;
    /** @var integer */
    public $start;
    /** @var integer */
    public $end;

    public function setUp()
    {
        $this->padding = new Pkcs7();
        $this->start   = 1;
        $this->end     = 32;
    }

    public function testPad()
    {
        for ($blockSize = $this->start; $blockSize <= $this->end; $blockSize++) {
            for ($i = 1; $i <= $blockSize; $i++) {
                $input  = str_repeat(chr(rand(0, 255)), $i);
                $output = $this->padding->pad($input, $blockSize);
                $num    = $blockSize - ($i % $blockSize);
                $this->assertEquals($output, $input . str_repeat(chr($num), $num));
            }
        }
    }

    public function testStrip()
    {
        for ($blockSize = $this->start; $blockSize <= $this->end; $blockSize++) {
            for ($i = 1; $i < $blockSize; $i++) {
                $input  = str_repeat('a', $i);
                $num    = $blockSize - ($i % $blockSize);
                $output = $this->padding->strip($input . str_repeat(chr($num), $num));
                $this->assertEquals($output, $input);
            }
        }
    }
}


text:
[![Build Status](https://travis-ci.org/kimmobrunfeldt/concurrently.svg)](https://travis-ci.org/kimmobrunfeldt/concurrently)

**Version: 2.0.0** ([*previous stable*](https://github.com/kimmobrunfeldt/concurrently/tree/1.0.0))

Run multiple commands concurrently.
Like `npm run watch-js & npm run watch-less` but better.

![](docs/demo.gif)

**Features:**

* Cross platform, works also in Windows
* Output is easy to follow with prefixes
* With `--kill-others` switch, all commands are killed if one dies

## Install

The tool is written in Node.js, but you can use it to run **any** commands.

```bash
npm install -g concurrently
```

## Usage

Remember to surround separate commands with quotes, like this:
```bash
concurrently "command1 arg" "command2 arg"
```

Otherwise **concurrently** would try to run 4 separate commands:
`command1`, `arg`, `command2`, `arg`.

Help:

```
Usage: concurrently [options] <command ...>

Options:

  -h, --help                        output usage information
  -V, --version                     output the version number
  -k, --kill-others                 kill other processes if one exits or dies
  --no-color                        disable colors from logging
  -p, --prefix <prefix>             prefix used in logging for each process.
  Possible values: index, pid, time, command, none or a template. Default: index. Example template "{time}-{pid}"

  -tf, --timestamp-format <format>  specify the timestamp in moment format. Default: YYYY-MM-DD HH:mm:ss.SSS

  -r, --raw                         output only raw output of processes, disables prettifying and concurrently coloring
  -s, --success <first|last|all>    Return exit code of zero or one based on the success or failure of the "first" child to terminate, the "last" child, or succeed  only if "all" child processes succeed. Default: all

  -l, --prefix-length <length>      limit how many characters of the command is displayed in prefix.
  The option can be used to shorten long commands.
  Works only if prefix is set to "command". Default: 10

Examples:

 - Kill other processes if one exits or dies

     $ concurrently --kill-others "grunt watch" "http-server"

 - Output nothing more than stdout+stderr of child processes

     $ concurrently --raw "npm run watch-less" "npm run watch-js"

 - Normal output but without colors e.g. when logging to file

     $ concurrently --no-color "grunt watch" "http-server" > log

 - Custom prefix

     $ concurrently --prefix "{time}-{pid}" "grunt watch" "http-server"

For more details, visit https://github.com/kimmobrunfeldt/concurrently
```

## FAQ

* Process exited with code *null*?

    From [Node child_process documentation](http://nodejs.org/api/child_process.html#child_process_event_exit), `exit` event:

    > This event is emitted after the child process ends. If the process
    > terminated normally, code is the final exit code of the process,
    > otherwise null. If the process terminated due to receipt of a signal,
    > signal is the string name of the signal, otherwise null.

    So *null* means the process didn't terminate normally. This will make **concurrent**
    to return non-zero exit code too.

## Why

I like [task automation with npm](http://substack.net/task_automation_with_npm_run)
but the usual way to run multiple commands concurrently is
`npm run watch-js & npm run watch-css`. That's fine but it's hard to keep
on track of different outputs. Also if one process fails, others still keep running
and you won't even notice the difference.

Another option would be to just run all commands in separate terminals. I got
tired of opening terminals and made **concurrently**.

### NPM Issue

Previously I thought this could fix some problems I had with watching scripts and this readme said:

> When running watch or serve tasks, I'd recommend to use `--kill-others` option:
>
> ```bash
> concurrent --kill-others "npm run watch-js" "npm run watch-less"
> ```
>
> That way, if for some reason e.g. your `watch-less` died, you would notice it easier.

However NPM didn't work as I hoped it would. See [this issue](https://github.com/kimmobrunfeldt/concurrently/issues/4).


text:
#include "plot/pairPlot.h"

PLOTLIB_INLINE PairPlot::PairPlot(const std::vector< PMat > &mats, const std::vector< std::string > &names,
                                  const std::vector< std::string > &hue)
{
    assert(hue.size() == mats.size());
    mStream << "data = pd.DataFrame()\nhue = []\n";

    for (size_t k = 0, kEnd = names.size(); k < kEnd; ++k)
    {
        mStream << "x" << k << " = []\n";
    }

    size_t j = 0;

    for (const auto &mat : mats)
    {
        assert(names.size() == mat.GetData().size());

        size_t i = 0;

        for (const auto &column : mat.GetData())
        {
            mStream << "x" << i << " = x" << i << " + " << this->ToArray(column) << "\n";
            ++i;
        }

        mStream << "hue = hue + "
                << this->ToArray(std::vector< std::string >(mat.GetData()[0].size(), hue[j++])) << "\n";
    }

    size_t l = 0;

    for (const auto &name : names)
    {
        mStream << "data['" << name << "']" << " = x" << l << "\n";
        ++l;
    }

    mStream << "data['hue'] = hue\n";
    mStream << "sns.pairplot( data, hue = 'hue'";
}

PLOTLIB_INLINE PairPlot::PairPlot(const PMat &mat, const std::vector< std::string > &names)
{
    assert(names.size() == mat.GetData().size());
    mStream << "data = pd.DataFrame()\n";
    size_t i = 0;

    for (const auto &column : mat.GetData())
    {
        mStream << "data['" << names[i++] << "'] = " << this->ToArray(column) << "\n";
    }

    mStream << "sns.pairplot( data";
}

PLOTLIB_INLINE std::string PairPlot::ToString()
{
    return mStream.str() + " )";
}

PLOTLIB_INLINE PairPlot &PairPlot::SetXVars(const std::vector< std::string > &xvars)
{
    this->AddArgument("x_vars", this->ToArray(xvars));
    return *this;
}

PLOTLIB_INLINE PairPlot &PairPlot::SetYVars(const std::vector< std::string > &yvars)
{
    this->AddArgument("y_vars", this->ToArray(yvars));
    return *this;
}

PLOTLIB_INLINE PairPlot &PairPlot::SetType(Type type)
{
    this->AddArgument("kind", this->GetString(type == Type::Scatter ? "scatter" : "reg"));
    return *this;
}

PLOTLIB_INLINE PairPlot &PairPlot::SetDiagonalType(DiagonalType type)
{
    this->AddArgument("diag_kind", this->GetString(type == DiagonalType::Histogram ? "hist" : "kde"));
    return *this;
}

PLOTLIB_INLINE PairPlot &PairPlot::SetMarker(const std::string &marker)
{
    this->AddArgument("markers", this->GetString(marker));
    return *this;
}

PLOTLIB_INLINE PairPlot &PairPlot::SetMarkers(const std::vector<std::string> &marker)
{
    this->AddArgument("markers", this->ToArray(marker));
    return *this;
}

PLOTLIB_INLINE PairPlot &PairPlot::SetSize(double size)
{
    this->AddArgument("size", size);
    return *this;
}

PLOTLIB_INLINE PairPlot &PairPlot::SetAspect(double aspect)
{
    this->AddArgument("aspect", aspect);
    return *this;
}


text:
@implementation UIWindow (SIUtils)

- (UIViewController *)currentViewController
{
	return [self dgs_topViewControllerWithRootViewController:self.rootViewController];
}

- (UIViewController *)dgs_topViewControllerWithRootViewController:(UIViewController*)rootViewController
{

	// http://stackoverflow.com/a/17578272
	if ([rootViewController isKindOfClass:[UITabBarController class]])
	{
		UITabBarController *tabBarController = (UITabBarController *)rootViewController;
		return [self dgs_topViewControllerWithRootViewController:tabBarController.selectedViewController];
	}
	else if ([rootViewController isKindOfClass:[UINavigationController class]])
	{
		UINavigationController *navigationController = (UINavigationController *)rootViewController;
		return [self dgs_topViewControllerWithRootViewController:navigationController.visibleViewController];
	}
	else if (rootViewController.presentedViewController)
	{
		UIViewController *presentedViewController = rootViewController.presentedViewController;
		return [self dgs_topViewControllerWithRootViewController:presentedViewController];
	}
	else
	{
		return rootViewController;
	}
}

#ifdef __IPHONE_7_0

- (UIViewController *)viewControllerForStatusBarStyle
{
    UIViewController *currentViewController = [self currentViewController];

    while ([currentViewController childViewControllerForStatusBarStyle]) {
        currentViewController = [currentViewController childViewControllerForStatusBarStyle];
    }
    return currentViewController;
}

- (UIViewController *)viewControllerForStatusBarHidden
{
    UIViewController *currentViewController = [self currentViewController];

    while ([currentViewController childViewControllerForStatusBarHidden]) {
        currentViewController = [currentViewController childViewControllerForStatusBarHidden];
    }
    return currentViewController;
}

#endif

@end


text:
package org.apache.qpid.protonj2.buffer;

import java.nio.ByteBuffer;

/**
 * ProtonBuffer wrapper around a NIO ByteBuffer instance.
 */
public class ProtonNioByteBuffer extends ProtonAbstractBuffer {

    // TODO - Operations in this class assume the originating buffer is zero indexed, one alternative is to
    //        slice but that might have unintended consequences.

    private final ByteBuffer buffer;

    public ProtonNioByteBuffer(ByteBuffer buffer) {
        this(buffer, buffer.remaining());
    }

    public ProtonNioByteBuffer(ByteBuffer buffer, int writeIndex) {
        super(buffer.remaining());

        this.buffer = buffer.slice();

        setIndex(0, writeIndex);
    }

    @Override
    public ByteBuffer unwrap() {
        return buffer;
    }

    @Override
    public boolean hasArray() {
        return buffer.hasArray();
    }

    @Override
    public byte[] getArray() {
        return buffer.array();
    }

    @Override
    public int getArrayOffset() {
        return buffer.arrayOffset();
    }

    @Override
    public int capacity() {
        return buffer.remaining();
    }

    @Override
    public ProtonBuffer capacity(int newCapacity) {
        if (newCapacity < 0) {
            throw new IllegalArgumentException("Cannot alter a buffer's capacity to a negative value: " + newCapacity);
        } else {
            throw new UnsupportedOperationException("NIO Buffer wrapper cannot adjust capacity");
        }
    }

    @Override
    public byte getByte(int index) {
        return buffer.get(index);
    }

    @Override
    public short getShort(int index) {
        return buffer.getShort(index);
    }

    @Override
    public int getInt(int index) {
        return buffer.getInt(index);
    }

    @Override
    public long getLong(int index) {
        return buffer.getLong(index);
    }

    @Override
    public ProtonBuffer getBytes(int index, ProtonBuffer destination, int destinationIndex, int length) {
        checkDestinationIndex(index, length, destinationIndex, destination.capacity());
        if (hasArray()) {
            destination.setBytes(destinationIndex, getArray(), getArrayOffset() + index, length);
        } else if (destination.hasArray()) {
            int position = buffer.position();

            buffer.position(index);
            buffer.get(destination.getArray(), destination.getArrayOffset() + destinationIndex, length);
            buffer.position(position);
        } else {
            while (length-- > 0) {
                destination.setByte(destinationIndex++, buffer.get(index++));
            }
        }

        return this;
    }

    @Override
    public ProtonBuffer getBytes(int index, byte[] destination, int offset, int length) {
        checkDestinationIndex(index, length, offset, destination.length);
        if (hasArray()) {
            System.arraycopy(getArray(), getArrayOffset() + index, destination, offset, length);
        } else {
            final int position = buffer.position();

            buffer.position(index);
            buffer.get(destination, offset, length);
            buffer.position(position);
        }
        return this;
    }

    @Override
    public ProtonBuffer getBytes(int index, ByteBuffer destination) {
        checkIndex(index, destination.remaining());
        if (destination.hasArray()) {
            final int position = buffer.position();

            buffer.position(index);
            buffer.get(destination.array(), destination.arrayOffset() + destination.position(), destination.remaining());
            buffer.position(position);

            destination.position(destination.limit());
        } else if (hasArray()) {
            destination.put(getArray(), getArrayOffset() + index, destination.remaining());
        } else {
            while (destination.hasRemaining()) {
                destination.put(getByte(index++));
            }
        }

        return this;
    }

    @Override
    public ProtonBuffer setByte(int index, int value) {
        buffer.put(index, (byte) value);
        return this;
    }

    @Override
    public ProtonBuffer setShort(int index, int value) {
        buffer.putShort(index, (short) value);
        return this;
    }

    @Override
    public ProtonBuffer setInt(int index, int value) {
        buffer.putInt(index, value);
        return this;
    }

    @Override
    public ProtonBuffer setLong(int index, long value) {
        buffer.putLong(index, value);
        return this;
    }

    @Override
    public ProtonBuffer setBytes(int index, ProtonBuffer source, int sourceIndex, int length) {
        checkSourceIndex(index, length, sourceIndex, source.capacity());
        if (source.hasArray()) {
            final int position = buffer.position();

            buffer.position(index);
            buffer.put(source.getArray(), source.getArrayOffset() + sourceIndex, length);
            buffer.position(position);
        } else if (hasArray()) {
            source.getBytes(sourceIndex, getArray(), getArrayOffset() + index, length);
        } else {
            while (length-- > 0) {
                buffer.put(index++, source.getByte(sourceIndex++));
            }
        }

        return this;
    }

    @Override
    public ProtonBuffer setBytes(int index, byte[] source, int sourceIndex, int length) {
        checkSourceIndex(index, length, sourceIndex, source.length);

        final int position = buffer.position();

        buffer.position(index);
        buffer.put(source, sourceIndex, length);
        buffer.position(position);

        return this;
    }

    @Override
    public ProtonBuffer setBytes(int index, ByteBuffer source) {
        checkSourceIndex(index, source.remaining(), source.position(), source.capacity());

        final int position = buffer.position();

        buffer.position(index);
        buffer.put(source);
        buffer.position(position);

        return this;
    }

    @Override
    public ProtonBuffer copy(int index, int length) {
        ProtonByteBuffer buffer = new ProtonByteBuffer(length);
        getBytes(index, buffer, length);
        return buffer;
    }

    @Override
    public ByteBuffer toByteBuffer(int index, int length) {
        checkIndex(index, length);

        int position = buffer.position();
        int limit = buffer.limit();

        buffer.position(index);
        buffer.limit(index + length);

        final ByteBuffer result = buffer.slice();

        buffer.limit(limit);
        buffer.position(position);

        return result;
    }
}


text:
<html py:strip="True">
<py:def function="header_metadescription(description, keyworks, title)">
	<meta HTTP-EQUIV="CONTENT-TYPE" CONTENT="TEXT/HTML; CHARSET=${response.charset}" />
	<meta http-equiv='content-language' content='th' />
	<meta http-equiv='content-type' content='text/html; charset=UTF-8?' />
	<!-- <meta http-equiv="refresh" content="30"/> refresh page-->
	<meta http-equiv="X-UA-Compatible" content="IE=EDGE; IE=9; IE=8; IE=7"/>

 	<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no"/>
	<meta charset="${response.charset}"/>

	<meta name="description" content="${description}"/>
	<meta name="keyworks" content="${keyworks}"/>

	<meta name="author" content="Greatherthanmatch Co., ltd."/>
	<meta name="copyright" content="© Copyright 2016-2017 Greatherthanmatch Co., Ltd." />
	<meta name="ABSTRACT" content="create poll or survey or exam on website"/>
	<meta name="revisit-after" content="3 days"/>

	<meta name="robots" content="all" />

	<meta NAME="CONTACT_ADDR" CONTENT="support@pollsurfvey.com"/>
	<meta NAME="RATING" CONTENT="General"/>

	<meta content="width=device-width, initial-scale=1.0" name="viewport"/>
	<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1"/>
	<meta property="og:site_name" content="pollsurfvey.com"/>

	<meta property="og:type" content="article"/>
	<meta property="og:title" content="${title}"/>
	<meta property="og:url" content="//www.pollsurfvey.com"/>
	<meta property="og:description" content="${description}"/>

	<!-- <meta property="og:image" content="http://www.pollsurfvey.com/img/function_about.png"/> -->
	<meta property="og:image" content="//www.pollsurfvey.com/img/poll120x120.gif"/>
	<meta property="og:locale" content="en_US" />

	<meta property="fb:app_id" content="966242223397117"/>
</py:def>
</html>


text:
#ifndef __I_SOUND__
#define __I_SOUND__

#include "doomtype.h"
#include "i_soundinternal.h"

enum ECodecType
{
	CODEC_Unknown,
	CODEC_Vorbis,
};

enum EStartSoundFlags
{
	SNDF_LOOP=1,
	SNDF_NOPAUSE=2,
	SNDF_AREA=4,
	SNDF_ABSTIME=8,
	SNDF_NOREVERB=16,
};

class SoundStream
{
public:
	virtual ~SoundStream ();

	enum
	{	// For CreateStream
		Mono = 1,
		Bits8 = 2,
		Bits32 = 4,
		Float = 8,

		// For OpenStream
		Loop = 16
	};

	virtual bool Play(bool looping, float volume) = 0;
	virtual void Stop() = 0;
	virtual void SetVolume(float volume) = 0;
	virtual bool SetPaused(bool paused) = 0;
	virtual unsigned int GetPosition() = 0;
	virtual bool IsEnded() = 0;
	virtual bool SetPosition(unsigned int pos);
	virtual bool SetOrder(int order);
	virtual FString GetStats();
};

typedef bool (*SoundStreamCallback)(SoundStream *stream, void *buff, int len, void *userdata);

class SoundRenderer
{
public:
	SoundRenderer ();
	virtual ~SoundRenderer ();

	virtual bool IsNull() { return false; }
	virtual void SetSfxVolume (float volume) = 0;
	virtual void SetMusicVolume (float volume) = 0;
	virtual SoundHandle LoadSound(BYTE *sfxdata, int length) = 0;
	SoundHandle LoadSoundVoc(BYTE *sfxdata, int length);
	virtual SoundHandle LoadSoundRaw(BYTE *sfxdata, int length, int frequency, int channels, int bits, int loopstart, int loopend = -1) = 0;
	virtual void UnloadSound (SoundHandle sfx) = 0;	// unloads a sound from memory
	virtual unsigned int GetMSLength(SoundHandle sfx) = 0;	// Gets the length of a sound at its default frequency
	virtual unsigned int GetSampleLength(SoundHandle sfx) = 0;	// Gets the length of a sound at its default frequency
	virtual float GetOutputRate() = 0;

	// Streaming sounds.
	virtual SoundStream *CreateStream (SoundStreamCallback callback, int buffbytes, int flags, int samplerate, void *userdata) = 0;
	virtual SoundStream *OpenStream (const char *filename, int flags, int offset, int length) = 0;

	// Starts a sound.
	virtual FISoundChannel *StartSound (SoundHandle sfx, float vol, int pitch, int chanflags, FISoundChannel *reuse_chan) = 0;
	virtual FISoundChannel *StartSound3D (SoundHandle sfx, SoundListener *listener, float vol, FRolloffInfo *rolloff, float distscale, int pitch, int priority, const FVector3 &pos, const FVector3 &vel, int channum, int chanflags, FISoundChannel *reuse_chan) = 0;

	// Stops a sound channel.
	virtual void StopChannel (FISoundChannel *chan) = 0;

	// Changes a channel's volume.
	virtual void ChannelVolume (FISoundChannel *chan, float volume) = 0;

	// Marks a channel's start time without actually playing it.
	virtual void MarkStartTime (FISoundChannel *chan) = 0;

	// Returns position of sound on this channel, in samples.
	virtual unsigned int GetPosition(FISoundChannel *chan) = 0;

	// Gets a channel's audibility (real volume).
	virtual float GetAudibility(FISoundChannel *chan) = 0;

	// Synchronizes following sound startups.
	virtual void Sync (bool sync) = 0;

	// Pauses or resumes all sound effect channels.
	virtual void SetSfxPaused (bool paused, int slot) = 0;

	// Pauses or resumes *every* channel, including environmental reverb.
	enum EInactiveState
	{
		INACTIVE_Active,		// sound is active
		INACTIVE_Complete,		// sound is completely paused
		INACTIVE_Mute			// sound is only muted
	};
	virtual void SetInactive(EInactiveState inactive) = 0;

	// Updates the volume, separation, and pitch of a sound channel.
	virtual void UpdateSoundParams3D (SoundListener *listener, FISoundChannel *chan, bool areasound, const FVector3 &pos, const FVector3 &vel) = 0;

	virtual void UpdateListener (SoundListener *) = 0;
	virtual void UpdateSounds () = 0;

	virtual bool IsValid () = 0;
	virtual void PrintStatus () = 0;
	virtual void PrintDriversList () = 0;
	virtual FString GatherStats ();
	virtual short *DecodeSample(int outlen, const void *coded, int sizebytes, ECodecType type);

	virtual void DrawWaveDebug(int mode);
};

extern SoundRenderer *GSnd;
extern bool nosfx;
extern bool nosound;

void I_InitSound ();
void I_ShutdownSound ();

void S_ChannelEnded(FISoundChannel *schan);
void S_ChannelVirtualChanged(FISoundChannel *schan, bool is_virtual);
float S_GetRolloff(FRolloffInfo *rolloff, float distance, bool logarithmic);
FISoundChannel *S_GetChannel(void *syschan);

extern ReverbContainer *DefaultEnvironments[26];

#endif


text:
import unittest

# test functionality
class TestMethods(unittest.TestCase):
    def test_assignments(self):
        a, b = 5, 10

        self.assertEqual(a, 5)
        self.assertEqual(b, 10)

    def test_unpacking(self):
        people = {'name': 'Joe'}

        for k, v in people.items():
            self.assertEqual(k, 'name')
            self.assertEqual(v, 'Joe')

    def test_failed_assignment_count(self):
        with self.assertRaises(ValueError):
            (x, y) = 'a'

    def test_remaining_assignments(self):
        first, *rest = [1, 2, 3, 4]

        self.assertEqual(first, 1)
        self.assertEqual(rest, [2, 3, 4])

# main execution
if __name__ == '__main__':
    unittest.main()


text:
import google.api_core.grpc_helpers

from google.cloud.recommender_v1beta1.proto import recommender_service_pb2_grpc

class RecommenderGrpcTransport(object):
    """gRPC transport class providing stubs for
    google.cloud.recommender.v1beta1 Recommender API.

    The transport provides access to the raw gRPC stubs,
    which can be used to take advantage of advanced
    features of gRPC.
    """

    # The scopes needed to make gRPC calls to all of the methods defined
    # in this service.
    _OAUTH_SCOPES = ("https://www.googleapis.com/auth/cloud-platform",)

    def __init__(
        self, channel=None, credentials=None, address="recommender.googleapis.com:443"
    ):
        """Instantiate the transport class.

        Args:
            channel (grpc.Channel): A ``Channel`` instance through
                which to make calls. This argument is mutually exclusive
                with ``credentials``; providing both will raise an exception.
            credentials (google.auth.credentials.Credentials): The
                authorization credentials to attach to requests. These
                credentials identify this application to the service. If none
                are specified, the client will attempt to ascertain the
                credentials from the environment.
            address (str): The address where the service is hosted.
        """
        # If both `channel` and `credentials` are specified, raise an
        # exception (channels come with credentials baked in already).
        if channel is not None and credentials is not None:
            raise ValueError(
                "The `channel` and `credentials` arguments are mutually " "exclusive."
            )

        # Create the channel.
        if channel is None:
            channel = self.create_channel(
                address=address,
                credentials=credentials,
                options={
                    "grpc.max_send_message_length": -1,
                    "grpc.max_receive_message_length": -1,
                }.items(),
            )

        self._channel = channel

        # gRPC uses objects called "stubs" that are bound to the
        # channel and provide a basic method for each RPC.
        self._stubs = {
            "recommender_stub": recommender_service_pb2_grpc.RecommenderStub(channel)
        }

    @classmethod
    def create_channel(
        cls, address="recommender.googleapis.com:443", credentials=None, **kwargs
    ):
        """Create and return a gRPC channel object.

        Args:
            address (str): The host for the channel to use.
            credentials (~.Credentials): The
                authorization credentials to attach to requests. These
                credentials identify this application to the service. If
                none are specified, the client will attempt to ascertain
                the credentials from the environment.
            kwargs (dict): Keyword arguments, which are passed to the
                channel creation.

        Returns:
            grpc.Channel: A gRPC channel object.
        """
        return google.api_core.grpc_helpers.create_channel(
            address, credentials=credentials, scopes=cls._OAUTH_SCOPES, **kwargs
        )

    @property
    def channel(self):
        """The gRPC channel used by the transport.

        Returns:
            grpc.Channel: A gRPC channel object.
        """
        return self._channel

    @property
    def list_recommendations(self):
        """Return the gRPC stub for :meth:`RecommenderClient.list_recommendations`.

        Lists recommendations for a Cloud project. Requires the
        recommender.\*.list IAM permission for the specified recommender.

        Returns:
            Callable: A callable which accepts the appropriate
                deserialized request object and returns a
                deserialized response object.
        """
        return self._stubs["recommender_stub"].ListRecommendations

    @property
    def get_recommendation(self):
        """Return the gRPC stub for :meth:`RecommenderClient.get_recommendation`.

        Gets the requested recommendation. Requires the recommender.\*.get IAM
        permission for the specified recommender.

        Returns:
            Callable: A callable which accepts the appropriate
                deserialized request object and returns a
                deserialized response object.
        """
        return self._stubs["recommender_stub"].GetRecommendation

    @property
    def mark_recommendation_claimed(self):
        """Return the gRPC stub for :meth:`RecommenderClient.mark_recommendation_claimed`.

        Mark the Recommendation State as Claimed. Users can use this method to
        indicate to the Recommender API that they are starting to apply the
        recommendation themselves. This stops the recommendation content from
        being updated.

        MarkRecommendationClaimed can be applied to recommendations in CLAIMED,
        SUCCEEDED, FAILED, or ACTIVE state.

        Requires the recommender.\*.update IAM permission for the specified
        recommender.

        Returns:
            Callable: A callable which accepts the appropriate
                deserialized request object and returns a
                deserialized response object.
        """
        return self._stubs["recommender_stub"].MarkRecommendationClaimed

    @property
    def mark_recommendation_succeeded(self):
        """Return the gRPC stub for :meth:`RecommenderClient.mark_recommendation_succeeded`.

        Mark the Recommendation State as Succeeded. Users can use this method to
        indicate to the Recommender API that they have applied the
        recommendation themselves, and the operation was successful. This stops
        the recommendation content from being updated.

        MarkRecommendationSucceeded can be applied to recommendations in ACTIVE,
        CLAIMED, SUCCEEDED, or FAILED state.

        Requires the recommender.\*.update IAM permission for the specified
        recommender.

        Returns:
            Callable: A callable which accepts the appropriate
                deserialized request object and returns a
                deserialized response object.
        """
        return self._stubs["recommender_stub"].MarkRecommendationSucceeded

    @property
    def mark_recommendation_failed(self):
        """Return the gRPC stub for :meth:`RecommenderClient.mark_recommendation_failed`.

        Mark the Recommendation State as Failed. Users can use this method to
        indicate to the Recommender API that they have applied the
        recommendation themselves, and the operation failed. This stops the
        recommendation content from being updated.

        MarkRecommendationFailed can be applied to recommendations in ACTIVE,
        CLAIMED, SUCCEEDED, or FAILED state.

        Requires the recommender.\*.update IAM permission for the specified
        recommender.

        Returns:
            Callable: A callable which accepts the appropriate
                deserialized request object and returns a
                deserialized response object.
        """
        return self._stubs["recommender_stub"].MarkRecommendationFailed


text:
package org.overlord.commons.dev.server.discovery;

import java.io.File;
import java.io.IOException;

import org.overlord.commons.dev.server.DevServerModule;

/**
 * Discovers the module when presumably running from maven. Basically this strategy tries to find the module
 * by looking for a class on the classpath and assuming that it's in a JAR.
 *
 * @author eric.wittmann@redhat.com
 */
public class WebAppModuleFromMavenDiscoveryStrategy extends AbstractModuleDiscoveryStrategy {

    private final Class<?> someClass;

    /**
     * Constructor.
     *
     * @param someClass
     */
    public WebAppModuleFromMavenDiscoveryStrategy(Class<?> someClass) {
        this.someClass = someClass;
    }

    /**
     * @see org.overlord.commons.dev.server.discovery.IModuleDiscoveryStrategy#getName()
     */
    @Override
    public String getName() {
        return "Maven Artifact"; //$NON-NLS-1$
    }

    /**
     * @see org.overlord.commons.dev.server.discovery.IModuleDiscoveryStrategy#discover(org.overlord.commons.dev.server.discovery.ModuleDiscoveryContext)
     */
    @Override
    public DevServerModule discover(ModuleDiscoveryContext context) {
        String path = someClass.getClassLoader()
                .getResource(someClass.getName().replace('.', '/') + ".class").getPath(); //$NON-NLS-1$
        if (path == null) {
            return null;
        }

        debug("Path: " + path); //$NON-NLS-1$

        File file = new File(path);
        // The class file is available on the file system, so not what we're looking for.
        if (file.exists()) {
            return null;
        }

        if (path.contains("-classes.jar") && path.startsWith("file:")) { //$NON-NLS-1$ //$NON-NLS-2$
            String pathToWar = path.substring(5, path.indexOf("-classes.jar")) + ".war"; //$NON-NLS-1$ //$NON-NLS-2$
            debug("Path to WAR: " + pathToWar); //$NON-NLS-1$
            File war = new File(pathToWar);
            if (war.isFile()) {
                File workDir = new File(context.getTargetDir(), war.getName());
                debug("Work Dir: " + workDir); //$NON-NLS-1$
                DevServerModule module = new DevServerModule();
                module.setInIDE(false);
                module.setWorkDir(workDir);
                module.setModuleDir(workDir);
                module.clean();
                workDir.mkdirs();
                try {
                    org.overlord.commons.dev.server.util.ArchiveUtils.unpackToWorkDir(war, workDir);
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
                return module;
            }
        }

        return null;
    }

}


text:
package org.get.oxicam.clinicalguide.xml.stats;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;

import org.get.oxicam.clinicalguide.xml.DateHelper;
import org.get.oxicam.clinicalguide.xml.query.QueryResultCell;
import org.get.oxicam.clinicalguide.xml.query.QueryResultTable;

public class StatsAnswerHolder {

    public final QueryResultTable table;
    public final Long start;
    public final Long end;

    /**
     * Constructs a StatsAnswerHolder.
     * @param table The QueryResult table
     * @param start long representing start date(this is mostly used if there are groupings in the timespan) use null if not used
     * @param end long representing end date(this is mostly used if there are groupings in the timespan) use null if not used.
     */
    public StatsAnswerHolder(QueryResultTable table, Long start,Long end){
	this.table = table;
	this.start = start;
	this.end = end;
	fixBirthdates();
    }

    /**
     * Sets the age if the columnname is patient_age. Gives the age depending on the birthdate and the current time
     */
    private void fixBirthdates(){
	int len = table.rows.size();
	for (int i = 0; i < len; i++) {
	    ArrayList<QueryResultCell> cells = table.rows.get(i).cells;
	    int mapLen = cells.size();
	    for(int j = 0; j < mapLen; j++){
		QueryResultCell cell = cells.get(j);
		String colName = cell.getColumnname();
		if(colName.equalsIgnoreCase("patient_age")){
		    long bday = DateHelper.changeTextDateToLong(cell.getData());
		    int age = DateHelper.calculateAge(bday);
		    cell.setData(age + "");
		}
	    }
	}
    }

    /**
     * Very basic toString, Just prints all the details.
     */
    public String toString(){

	SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd");

	String dateStr = "";
	if(end != null && start != null){
	    Calendar c1 = Calendar.getInstance();
	    Calendar c2 = Calendar.getInstance();
	    c1.setTimeInMillis(start);
	    c2.setTimeInMillis(end);
	    dateStr += fmt.format(new Date(start));
	    if(c1.get(Calendar.DAY_OF_YEAR) != c2.get(Calendar.DAY_OF_YEAR)){
		dateStr += " " + fmt.format(new Date(end));
	    }
	}
	String retVal = dateStr + "\n";
	int len = table.rows.size();
	if(len == 0) { retVal += "NONE\n"; }
	for (int j = 0; j < len; j++) {
	    ArrayList<QueryResultCell> map = table.rows.get(j).cells;
	    int mapLen = map.size();
	    for(int k = 0; k < mapLen; k++){
		QueryResultCell cell = map.get(k);
		retVal += " " + cell.getColumnname() + ": " + cell.getData() + "\n";
	    }
	    retVal += "\n";
	}
	return retVal;
    }
}


text:
import type {
  InferAttributes,
  InferCreationAttributes,
  CreationOptional,
  HasMany,
  HasManyAddAssociationMixin,
  HasManyAddAssociationsMixin,
  HasManyCountAssociationsMixin,
  HasManyCreateAssociationMixin,
  HasManyGetAssociationsMixin,
  HasManyHasAssociationMixin,
  HasManyRemoveAssociationMixin,
  HasManyRemoveAssociationsMixin,
  HasManySetAssociationsMixin,
  NonAttribute,
} from '@sequelize/core';
import {
  DataTypes,
  Model,
} from '@sequelize/core';
import { sequelize } from '../connection';
// associate
// it is important to import _after_ the model above is already exported so the circular reference works.
import { User } from './user';

// This class doesn't extend the generic Model<TAttributes>, but should still
// function just fine, with a bit less safe type-checking
export class UserGroup extends Model<
  InferAttributes<UserGroup>,
  InferCreationAttributes<UserGroup>
> {
  static associations: {
    users: HasMany<UserGroup, User>,
  };

  declare id: CreationOptional<number>;
  declare name: string;

  // mixins for association (optional)
  declare users?: NonAttribute<User[]>;
  declare getUsers: HasManyGetAssociationsMixin<User>;
  declare setUsers: HasManySetAssociationsMixin<User, number>;
  declare addUser: HasManyAddAssociationMixin<User, number>;
  declare addUsers: HasManyAddAssociationsMixin<User, number>;
  declare createUser: HasManyCreateAssociationMixin<User, 'groupId'>;
  declare countUsers: HasManyCountAssociationsMixin<User>;
  declare hasUser: HasManyHasAssociationMixin<User, number>;
  declare removeUser: HasManyRemoveAssociationMixin<User, number>;
  declare removeUsers: HasManyRemoveAssociationsMixin<User, number>;
}

// attach all the metadata to the model
// instead of this, you could also use decorators
UserGroup.init({
  name: DataTypes.STRING,
  id: {
    type: DataTypes.INTEGER,
    allowNull: false,
    primaryKey: true,
    autoIncrement: true,
  },
}, { sequelize });

export const Users = UserGroup.hasMany(User, { as: 'users', foreignKey: 'groupId' });


text:
<?php

namespace eecli\Command;

use Illuminate\Console\Command as BaseCommand;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;

abstract class Command extends BaseCommand
{
    /**
     * Execute the console command.
     *
     * Override laravel container dependency in Illuminate\Console\Command
     *
     * @param  \Symfony\Component\Console\Input\InputInterface  $input
     * @param  \Symfony\Component\Console\Output\OutputInterface  $output
     * @return mixed
     */
    protected function execute(InputInterface $input, OutputInterface $output)
    {
        $method = method_exists($this, 'handle') ? 'handle' : 'fire';

        return $this->$method();
    }
}


text:
.class Lcom/android/server/accounts/AccountManagerService$9;
.super Lcom/android/server/accounts/AccountManagerService$Session;
.source "AccountManagerService.java"

# annotations
.annotation system Ldalvik/annotation/EnclosingMethod;
    value = Lcom/android/server/accounts/AccountManagerService;->updateCredentials(Landroid/accounts/IAccountManagerResponse;Landroid/accounts/Account;Ljava/lang/String;ZLandroid/os/Bundle;)V
.end annotation

.annotation system Ldalvik/annotation/InnerClass;
    accessFlags = 0x0
    name = null
.end annotation

# instance fields
.field final synthetic this$0:Lcom/android/server/accounts/AccountManagerService;

.field final synthetic val$account:Landroid/accounts/Account;

.field final synthetic val$authTokenType:Ljava/lang/String;

.field final synthetic val$loginOptions:Landroid/os/Bundle;

# direct methods
.method constructor <init>(Lcom/android/server/accounts/AccountManagerService;Lcom/android/server/accounts/AccountManagerService$UserAccounts;Landroid/accounts/IAccountManagerResponse;Ljava/lang/String;ZZLandroid/accounts/Account;Ljava/lang/String;Landroid/os/Bundle;)V
    .registers 10
    .param p2    # Lcom/android/server/accounts/AccountManagerService$UserAccounts;
    .param p3    # Landroid/accounts/IAccountManagerResponse;
    .param p4    # Ljava/lang/String;
    .param p5    # Z
    .param p6    # Z

    iput-object p1, p0, Lcom/android/server/accounts/AccountManagerService$9;->this$0:Lcom/android/server/accounts/AccountManagerService;

    iput-object p7, p0, Lcom/android/server/accounts/AccountManagerService$9;->val$account:Landroid/accounts/Account;

    iput-object p8, p0, Lcom/android/server/accounts/AccountManagerService$9;->val$authTokenType:Ljava/lang/String;

    iput-object p9, p0, Lcom/android/server/accounts/AccountManagerService$9;->val$loginOptions:Landroid/os/Bundle;

    invoke-direct/range {p0 .. p6}, Lcom/android/server/accounts/AccountManagerService$Session;-><init>(Lcom/android/server/accounts/AccountManagerService;Lcom/android/server/accounts/AccountManagerService$UserAccounts;Landroid/accounts/IAccountManagerResponse;Ljava/lang/String;ZZ)V

    return-void
.end method

# virtual methods
.method public run()V
    .registers 5
    .annotation system Ldalvik/annotation/Throws;
        value = {
            Landroid/os/RemoteException;
        }
    .end annotation

    iget-object v0, p0, Lcom/android/server/accounts/AccountManagerService$9;->mAuthenticator:Landroid/accounts/IAccountAuthenticator;

    iget-object v1, p0, Lcom/android/server/accounts/AccountManagerService$9;->val$account:Landroid/accounts/Account;

    iget-object v2, p0, Lcom/android/server/accounts/AccountManagerService$9;->val$authTokenType:Ljava/lang/String;

    iget-object v3, p0, Lcom/android/server/accounts/AccountManagerService$9;->val$loginOptions:Landroid/os/Bundle;

    invoke-interface {v0, p0, v1, v2, v3}, Landroid/accounts/IAccountAuthenticator;->updateCredentials(Landroid/accounts/IAccountAuthenticatorResponse;Landroid/accounts/Account;Ljava/lang/String;Landroid/os/Bundle;)V

    return-void
.end method

.method protected toDebugString(J)Ljava/lang/String;
    .registers 5
    .param p1    # J

    iget-object v0, p0, Lcom/android/server/accounts/AccountManagerService$9;->val$loginOptions:Landroid/os/Bundle;

    if-eqz v0, :cond_9

    iget-object v0, p0, Lcom/android/server/accounts/AccountManagerService$9;->val$loginOptions:Landroid/os/Bundle;

    invoke-virtual {v0}, Landroid/os/Bundle;->keySet()Ljava/util/Set;

    :cond_9
    new-instance v0, Ljava/lang/StringBuilder;

    invoke-direct {v0}, Ljava/lang/StringBuilder;-><init>()V

    invoke-super {p0, p1, p2}, Lcom/android/server/accounts/AccountManagerService$Session;->toDebugString(J)Ljava/lang/String;

    move-result-object v1

    invoke-virtual {v0, v1}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;

    move-result-object v0

    const-string v1, ", updateCredentials"

    invoke-virtual {v0, v1}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;

    move-result-object v0

    const-string v1, ", "

    invoke-virtual {v0, v1}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;

    move-result-object v0

    iget-object v1, p0, Lcom/android/server/accounts/AccountManagerService$9;->val$account:Landroid/accounts/Account;

    invoke-virtual {v0, v1}, Ljava/lang/StringBuilder;->append(Ljava/lang/Object;)Ljava/lang/StringBuilder;

    move-result-object v0

    const-string v1, ", authTokenType "

    invoke-virtual {v0, v1}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;

    move-result-object v0

    iget-object v1, p0, Lcom/android/server/accounts/AccountManagerService$9;->val$authTokenType:Ljava/lang/String;

    invoke-virtual {v0, v1}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;

    move-result-object v0

    const-string v1, ", loginOptions "

    invoke-virtual {v0, v1}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;

    move-result-object v0

    iget-object v1, p0, Lcom/android/server/accounts/AccountManagerService$9;->val$loginOptions:Landroid/os/Bundle;

    invoke-virtual {v0, v1}, Ljava/lang/StringBuilder;->append(Ljava/lang/Object;)Ljava/lang/StringBuilder;

    move-result-object v0

    invoke-virtual {v0}, Ljava/lang/StringBuilder;->toString()Ljava/lang/String;

    move-result-object v0

    return-object v0
.end method


text:
<?php

/**
 * Created by PhpStorm.
 * User: Jacky
 * Date: 3/9/2017
 * Time: 9:31 AM
 */
class Company_model extends CI_Model {

    public function __construct()
    {
        parent::__construct();
    }

    public function select_all(){
        $query = $this->db->get('companies');
        $data = $query->result();
        return $data;
    }

    public function insert($data){
        if($this->db->insert('companies', $data)){
            return true;
        }
    }

    public function delete($id){
        if($this->db->delete('companies', 'id = '. $id)){
            return true;
        }
    }

    public function update($data, $old_id){
        $this->db->set($data);
        $this->db->where('id', $old_id);
        return $this->db->update('companies', $data);
    }

}


text:
using System.Collections.Generic;
using System.Text.Json;
using Azure.Core;

namespace Azure.ResourceManager.DataBoxEdge.Models
{
    public partial class DataBoxEdgeJobErrorItem
    {
        internal static DataBoxEdgeJobErrorItem DeserializeDataBoxEdgeJobErrorItem(JsonElement element)
        {
            Optional<IReadOnlyList<string>> recommendations = default;
            Optional<string> code = default;
            Optional<string> message = default;
            foreach (var property in element.EnumerateObject())
            {
                if (property.NameEquals("recommendations"))
                {
                    if (property.Value.ValueKind == JsonValueKind.Null)
                    {
                        property.ThrowNonNullablePropertyIsNull();
                        continue;
                    }
                    List<string> array = new List<string>();
                    foreach (var item in property.Value.EnumerateArray())
                    {
                        array.Add(item.GetString());
                    }
                    recommendations = array;
                    continue;
                }
                if (property.NameEquals("code"))
                {
                    code = property.Value.GetString();
                    continue;
                }
                if (property.NameEquals("message"))
                {
                    message = property.Value.GetString();
                    continue;
                }
            }
            return new DataBoxEdgeJobErrorItem(Optional.ToList(recommendations), code.Value, message.Value);
        }
    }
}


text:
using System;
using System.Windows.Forms;

namespace xDockPanel
{
    internal class DummyControl : Control
    {
        public DummyControl()
        {
            SetStyle(ControlStyles.Selectable, false);
        }
    }
}


text:
// Generated by typings
// Source: https://raw.githubusercontent.com/DefinitelyTyped/DefinitelyTyped/5421783adfaf9b99e9274f4488cfc0ee73f17a56/copy-paste/copy-paste.d.ts
// Type definitions for copy-paste v1.1.3
// Project: https://github.com/xavi-/node-copy-paste
// Definitions by: Tobias Kahlert <https://github.com/SrTobi>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped

declare module 'copy-paste' {

    export type CopyCallback = (err: Error) => void;
    export type PasteCallback = (err: Error, content: string) => void;

    /**
     * Asynchronously replaces the current contents of the clip board with text.
     *
     * @param {T} content Takes either a string, array, object, or readable stream.
     * @return {T} Returns the same value passed in.
     */
    export function copy<T>(content: T): T;

    /**
     * Asynchronously replaces the current contents of the clip board with text.
     *
     * @param {T} content Takes either a string, array, object, or readable stream.
     * @param {CopyCallback} callback will fire when the copy operation is complete.
     * @return {T} Returns the same value passed in.
     */
    export function copy<T>(content: T, callback: CopyCallback): T;

    /**
     * Synchronously returns the current contents of the system clip board.
     *
     * Note: The synchronous version of paste is not always availabled.
     * An error message is shown if the synchronous version of paste is used on an unsupported platform.
     * The asynchronous version of paste is always available.
     *
     * @return {string} Returns the current contents of the system clip board.
     */
    export function paste(): string;

    /**
     * Asynchronously returns the current contents of the system clip board.
     *
     * @param {PasteCallback} callback The contents of the system clip board are passed to the callback as the second parameter.
     */
    export function paste(callback: PasteCallback): void;
}


text:
//Problem 11. Bank Account Data

//A bank account has a holder name (first name, middle name and last name), available amount of money
//(balance), bank name, IBAN, 3 credit card numbers associated with the account.
//Declare the variables needed to keep the information for a single bank account using the appropriate
//data types and descriptive names.

using System;

class AccData
{
    static void Main()
    {
        string firstName = "Ivan";
        string middleName = "Ivanov";
        string lastName = "Penev";
        string bankName = "UBB";

        decimal accountAmmount = 1024m;

        long firstCreditCardNumber = 2332453422323l;
        long secondCreditCardNumber = 23123123132323l;
        long thirCreditCardNumber = 123131231312312L;

    }
}


text:
using Docker.DotNet.Models;
using System;
using System.Collections.Generic;
using System.Text;

namespace AKDK
{
    /// <summary>
    ///     Extension methods for well-known Docker API models.
    /// </summary>
    public static class DockerModelExtensions
    {
        /// <summary>
        ///     Configure the container to use the "json-file" logging driver.
        /// </summary>
        /// <param name="parameters">
        ///     The container-creation parameters.
        /// </param>
        /// <returns>
        ///     The container-creation parameters (enables method-chaining).
        /// </returns>
        public static CreateContainerParameters UseJsonFileLogger(this CreateContainerParameters parameters)
        {
            if (parameters == null)
                throw new ArgumentNullException(nameof(parameters));

            HostConfig hostConfig = parameters.HostConfig ?? (parameters.HostConfig = new HostConfig());
            LogConfig logConfig = hostConfig.EnsureLogConfig();
            logConfig.Type = "json-file";
            logConfig.Config.Clear();

            return parameters;
        }

        /// <summary>
        ///     Configure the container to use the "journald" logging driver.
        /// </summary>
        /// <param name="parameters">
        ///     The container-creation parameters.
        /// </param>
        /// <returns>
        ///     The container-creation parameters (enables method-chaining).
        /// </returns>
        public static CreateContainerParameters UseJournaldLogger(this CreateContainerParameters parameters)
        {
            if (parameters == null)
                throw new ArgumentNullException(nameof(parameters));

            HostConfig hostConfig = parameters.HostConfig ?? (parameters.HostConfig = new HostConfig());
            LogConfig logConfig = hostConfig.EnsureLogConfig();
            logConfig.Type = "journald";
            logConfig.Config.Clear();

            return parameters;
        }

        static LogConfig EnsureLogConfig(this HostConfig hostConfig)
        {
            if (hostConfig == null)
                throw new ArgumentNullException(nameof(hostConfig));

            LogConfig logConfig = hostConfig.LogConfig ?? (hostConfig.LogConfig = new LogConfig());
            if (logConfig.Config == null)
                logConfig.Config = new Dictionary<string, string>();

            return logConfig;
        }
    }
}


text:
import React, { Component, PropTypes } from 'react';
import { Card, CardActions, CardHeader, CardMedia, CardTitle, CardText } from 'material-ui/Card';
import FlatButton from 'material-ui/FlatButton';
import coverImage from '../../common/coverVideo/cover.jpg';

// import baseStyle from '../../common/Style/baseStyle.css';
import styles from './styles.css';

class FlipCard extends Component {
  constructor(props) {
    super(props);
    this.state = {
      frontClass: styles.front,
      backClass: styles.back,
      umbraClass: styles.umbra,
      penumbraClass: styles.penumbra,
    };
    this.handleClick = this.handleClick.bind(this);
  }
  handleClick(side) {
    switch (side) {
      case 'front':
        this.setState({
          frontClass: [styles.front, styles.sideOneAnimation].join(' '),
          backClass: [styles.back, styles.sideTwoAnimation].join(' '),
        });
        break;
      case 'back':
        this.setState({
          frontClass: [styles.front, styles.sideTwoAnimation].join(' '),
          backClass: [styles.back, styles.sideOneAnimation].join(' '),
        });
        break;

      default:
        throw new Error('Unknown side');
    }
    this.setState({
      umbraClass: [styles.umbra, styles.umbraAnimation].join(' '),
      penumbraClass: [styles.penumbra, styles.penumbraAnimation].join(' '),
    });
  }
  render() {
    return (

          <Card>
            <CardHeader
              title="URL Avatar"
              />
            <CardMedia>

            </CardMedia>
            <CardTitle title="Card title" subtitle="Card subtitle" />

            <CardActions>
              <FlatButton label="Action1" onTouchTap={() => this.handleClick('front') } />
              <FlatButton label="Action2" onTouchTap={() => this.handleClick('front') } />
            </CardActions>
          </Card>

          <Card>
            <CardTitle title="Card title" subtitle="Card subtitle" />
            <CardText>
              Lorem ipsum dolor sit amet, consectetur adipiscing elit.
              Donec mattis pretium massa.Aliquam erat volutpat.Nulla facilisi.
              Donec vulputate interdum sollicitudin.Nunc lacinia auctor quam sed pellentesque.
              Aliquam dui mauris, mattis quis lacus id, pellentesque lobortis odio.
            </CardText>
            <CardActions>
              <FlatButton label="Action1" onTouchTap={() => this.handleClick('back') } />
              <FlatButton label="Action2" onTouchTap={() => this.handleClick('back') } />
            </CardActions>
          </Card>

    );
  }
}

FlipCard.propTypes = {
  axis: PropTypes.string.isRequired,
  duration: PropTypes.number.isRequired,
};

export default FlipCard;


text:
var hoverZoomPlugins = hoverZoomPlugins || [];
hoverZoomPlugins.push({
    name:'Vox Media',
    prepareImgLinks:function (callback) {
        var res = [];
        hoverZoom.urlReplace(res,
            'img[src*=".vox-cdn.com"], [style*=".vox-cdn.com"]',
            /_(medium|epic|small)/,
            options.showHighRes ? '' : '_epic'
        );
        callback($(res));
    }
});


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

package org.chromium.policy;

import android.annotation.TargetApi;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.os.Parcel;
import android.os.UserManager;
import android.preference.PreferenceManager;
import android.util.Base64;

import org.chromium.base.metrics.RecordHistogram;

import java.util.concurrent.TimeUnit;

/**
 * Retrieves app restrictions and provides them to a {@link Delegate} object as Bundles. Retrieving
 * the restrictions is done asynchronously.
 */
public class AppRestrictionsProvider {
    /** Delegate to notify when restrictions have been received. */
    public interface Delegate {
        /** Called when new restrictions are available. */
        public void notifyNewAppRestrictionsAvailable(Bundle newAppRestrictions);
    }

    private static final String PREFERENCE_KEY = "App Restrictions";

    private final UserManager mUserManager;
    private final Context mContext;
    private final Delegate mDelegate;
    private final SharedPreferences mSharedPreferences;
    private final BroadcastReceiver mAppRestrictionsChangedReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            refreshRestrictions();
        }
    };

    /**
     * @param context The application context.
     * @param appRestrictionsProviderDelegate Object to be notified when new restrictions are
     *            available.
     */
    public AppRestrictionsProvider(Context context, Delegate appRestrictionsProviderDelegate) {
        mContext = context;
        mDelegate = appRestrictionsProviderDelegate;
        mUserManager = getUserManager();
        mSharedPreferences = PreferenceManager.getDefaultSharedPreferences(mContext);
    }

    /**
     * Start listening for restrictions changes. Does nothing if this is not supported by the
     * platform.
     */
    @TargetApi(Build.VERSION_CODES.LOLLIPOP)
    public void startListening() {
        if (!isChangeIntentSupported()) return;
        mContext.registerReceiver(mAppRestrictionsChangedReceiver,
                new IntentFilter(Intent.ACTION_APPLICATION_RESTRICTIONS_CHANGED));
    }

    /**
     * Asynchronously retrieve the restrictions.
     * {@link Delegate#notifyNewAppRestrictionsAvailable(Bundle)} will be called as a result.
     */
    public void refreshRestrictions() {
        if (!isRestrictionsSupported()) {
            mDelegate.notifyNewAppRestrictionsAvailable(new Bundle());
            return;
        }
        final Bundle cachedResult = getCachedPolicies();
        if (cachedResult != null) {
            mDelegate.notifyNewAppRestrictionsAvailable(cachedResult);
        }

        new AsyncTask<Void, Void, Bundle>() {
            @Override
            protected Bundle doInBackground(Void... params) {
                long startTime = System.currentTimeMillis();
                Bundle bundle = getApplicationRestrictions();
                RecordHistogram.recordTimesHistogram("Enterprise.AppRestrictionLoadTime",
                        System.currentTimeMillis() - startTime, TimeUnit.MILLISECONDS);
                return bundle;
            }

            @Override
            protected void onPostExecute(Bundle result) {
                cachePolicies(result);
                mDelegate.notifyNewAppRestrictionsAvailable(result);
            }
        }.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
    }

    /**
     * Stop listening for restrictions changes. Does nothing if this is not supported by the
     * platform.
     */
    public void stopListening() {
        if (isChangeIntentSupported()) {
            mContext.unregisterReceiver(mAppRestrictionsChangedReceiver);
        }
    }

    /**
     * getApplicationRestrictions method of UserManger was introduced in JELLY_BEAN_MR2.
     */
    private boolean isRestrictionsSupported() {
        return Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2;
    }

    /**
     * Intent.ACTION_APPLICATION_RESTRICTIONS_CHANGED was introduced in LOLLIPOP.
     */
    private boolean isChangeIntentSupported() {
        return Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP;
    }

    /**
     * Wrap access to the Android UserManager to allow being swapped out in environments where it is
     * not available yet.
     */
    @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR2)
    private Bundle getApplicationRestrictions() {
        return mUserManager.getApplicationRestrictions(mContext.getPackageName());
    }

    /**
     * Wrap access to the Android UserManager to allow being swapped out in environments where it is
     * not available yet.
     */
    @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR2)
    private UserManager getUserManager() {
        if (!isRestrictionsSupported()) return null;
        return (UserManager) mContext.getSystemService(Context.USER_SERVICE);
    }

    private void cachePolicies(Bundle policies) {
        Parcel p = Parcel.obtain();
        p.writeBundle(policies);
        byte bytes[] = p.marshall();
        String s = Base64.encodeToString(bytes, 0);
        SharedPreferences.Editor ed = mSharedPreferences.edit();
        ed.putString(PREFERENCE_KEY, s);
        ed.apply();
    }

    private Bundle getCachedPolicies() {
        String s = mSharedPreferences.getString(PREFERENCE_KEY, null);
        if (s == null) {
            return null;
        }
        byte bytes[] = Base64.decode(s, 0);
        Parcel p = Parcel.obtain();
        // Unmarshalling the parcel is, in theory, unsafe if the Android version or API version has
        // changed, but the worst that is likely to happen is that the bundle comes back empty, and
        // this will be corrected once the Android returns the real App Restrictions.
        p.unmarshall(bytes, 0, bytes.length);
        p.setDataPosition(0);
        Bundle result = p.readBundle();
        try {
            result = p.readBundle();
        } catch (IllegalStateException e) {
            result = null;
        }
        RecordHistogram.recordBooleanHistogram(
                "Enterprise.AppRestrictionsCacheLoad", result != null);
        return result;
    }
}


text:
<xml xmlns:o="urn:schemas-microsoft-com:office:office">
 <o:MainFile HRef="../2022ClubChampionshipLeague2.htm"/>
 <o:File HRef="2022ClubChampionshipLeague2_image001.png"
  PublicationID="2022ClubChampionshipLeague2"/>
 <o:File HRef="2022ClubChampionshipLeague2_image002.png"
  PublicationID="2022ClubChampionshipLeague2"/>
 <o:File HRef="filelist.xml"/>
</xml>


text:
0.1
===

First released version


text:
$domainName = $args[0]

$password = $args[1]

net user tuser "$password" /ADD

Set-DnsClient `
  -InterfaceAlias "Ethernet*" `
  -ConnectionSpecificSuffix $domainName

Install-WindowsFeature `
  -Name AD-Domain-Services `
  -IncludeManagementTools

$securePassword = ConvertTo-SecureString $password `
  -AsPlainText `
  -Force

Install-ADDSForest `
  -DomainName $domainName `
  -SafeModeAdministratorPassword $securePassword `
  -Force


text:
//
// Diese Datei wurde mit der JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.8-b130911.1802 generiert
// Siehe http://java.sun.com/xml/jaxb
// Änderungen an dieser Datei gehen bei einer Neukompilierung des Quellschemas verloren.
// Generiert: 2014.10.07 um 04:55:05 PM CEST
//

package com.v2gclarity.risev2g.shared.v2gMessages.msgDef;

import javax.xml.bind.annotation.XmlEnum;
import javax.xml.bind.annotation.XmlEnumValue;
import javax.xml.bind.annotation.XmlType;

/**
 *
Java-Klasse für EVSEProcessingType.
 *
 *
Das folgende Schemafragment gibt den erwarteten Content an, der in dieser Klasse enthalten ist.
 *

 *

 * <simpleType name="EVSEProcessingType">
 *   <restriction base="{http://www.w3.org/2001/XMLSchema}string">
 *     <enumeration value="Finished"/>
 *     <enumeration value="Ongoing"/>
 *     <enumeration value="Ongoing_WaitingForCustomerInteraction"/>
 *   </restriction>
 * </simpleType>
 *

 *
 */
@XmlType(name = "EVSEProcessingType")
@XmlEnum
public enum EVSEProcessingType {

    @XmlEnumValue("Finished")
    FINISHED("Finished"),
    @XmlEnumValue("Ongoing")
    ONGOING("Ongoing"),
    @XmlEnumValue("Ongoing_WaitingForCustomerInteraction")
    ONGOING_WAITING_FOR_CUSTOMER_INTERACTION("Ongoing_WaitingForCustomerInteraction");
    private final String value;

    EVSEProcessingType(String v) {
        value = v;
    }

    public String value() {
        return value;
    }

    public static EVSEProcessingType fromValue(String v) {
        for (EVSEProcessingType c: EVSEProcessingType.values()) {
            if (c.value.equals(v)) {
                return c;
            }
        }
        throw new IllegalArgumentException(v);
    }

}


text:
A Feathers application can be [dockerized like any other Node.js application](https://nodejs.org/en/docs/guides/nodejs-docker-webapp/).

## Create an app

```sh
mkdir feathers-app
cd feathers-app/
feathers generate app
```

### Dockerfile

Add the following `Dockerfile` to the project directory:

```
FROM node:lts-alpine

WORKDIR /usr/src/app

COPY package*.json ./

RUN npm install

COPY . .

EXPOSE 3030

CMD ["npm", "run", "start"]
```

## Build the image

```sh
docker build -t my-feathers-image .
```

## Start the container

```sh
docker run -d -p 3030:3030 --name my-feathers-container my-feathers-image
```


text:
package org.keviny.gallery.common.mail;

import java.io.IOException;
import java.util.Date;
import java.util.concurrent.ConcurrentHashMap;

import javax.mail.*;
import javax.mail.internet.MimeBodyPart;

public class DefaultMailStore implements MailStore {

	private ConcurrentHashMap<String, MailMessageHandler> handlers = new ConcurrentHashMap<String, MailMessageHandler>();

	@Override
	public boolean isUnread(String uid) {
		return true;
	}

	@Override
	public void store(Message message) {
        System.out.println("-------------------------------------------");
        try {
            Date sentDate = message.getSentDate();
            String contentType = message.getContentType();

            if(contentType.contains("multipart")) {
                Multipart multipart = (Multipart)message.getContent();
                int numOfParts = multipart.getCount();
                for(int i = 0; i < numOfParts; i++) {
                    MimeBodyPart part = (MimeBodyPart)multipart.getBodyPart(i);
                    String disposition = part.getDisposition();
                    if(Part.ATTACHMENT.equalsIgnoreCase(disposition)) {
                        String filename = part.getFileName();
                        System.out.println("Attachment: " + filename);
                    } else if(Part.INLINE.equalsIgnoreCase(disposition)) {
                        String filename = part.getFileName();
                        System.out.println("Inline: " +  filename);
                    } else {
                        System.out.println("Content: " + part.getContent());
                    }
                }
            } else {
                System.out.println(message.getContent());
            }

        System.out.println();
        } catch (MessagingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

	@Override
	public void addHandler(String mimeType, MailMessageHandler handler) {
		handlers.putIfAbsent(mimeType, handler);
	}

}


text:
#pragma once

#include <system_error>

#include "boost/asio/io_service.hpp"
#include "boost/filesystem/path.hpp"
#include "boost/date_time/posix_time/ptime.hpp"

#include "mediafire_sdk/utils/fileio.hpp"
#include "mediafire_sdk/utils/sha256_hasher.hpp"
#include "mediafire_sdk/uploader/hasher.hpp"

namespace mf {
namespace uploader {
namespace detail {
namespace hash_event {

struct HasherStateData_
{
    boost::asio::io_service * io_service;

    boost::filesystem::path filepath;
    uint64_t filesize;
    std::time_t mtime;

    ::mf::utils::Sha256Hasher primary_hasher;
    ::mf::utils::Sha256Hasher chunk_hasher;

    std::vector<std::pair<uint64_t,uint64_t>> chunk_ranges;
    std::vector<std::string> chunk_hashes;
};
using HasherStateData = std::shared_ptr<HasherStateData_>;

struct StartHash
{
    HasherStateData state;
};

struct ReadNext
{
    HasherStateData state;
    mf::utils::FileIO::Pointer file_io;
    uint64_t read_byte_pos;
};

struct HashSuccess
{
    HasherStateData state;
    std::string sha256_hash;
};

struct Error
{
    HasherStateData state;

    std::error_code error_code;
    std::string description;
};

}  // namespace hash_event
}  // namespace detail
}  // namespace uploader
}  // namespace mf


text:
module Azure::Logic::Mgmt::V2015_02_01_preview
  module Models
    #
    # Defines values for WorkflowStatus
    #
    module WorkflowStatus
      NotSpecified = "NotSpecified"
      Paused = "Paused"
      Running = "Running"
      Waiting = "Waiting"
      Succeeded = "Succeeded"
      Skipped = "Skipped"
      Suspended = "Suspended"
      Cancelled = "Cancelled"
      Failed = "Failed"
      Faulted = "Faulted"
      TimedOut = "TimedOut"
      Aborted = "Aborted"
    end
  end
end


text:
/**
 * Get dependencies.
 */
const express = require('express'),
      path = require('path'),
      favicon = require('serve-favicon'),
      logger = require('morgan'),
      moment = require('moment');

/**
 * Do configurations.
 */
moment.locale('tr');

/**
 * Get configs.
 */
global.config = require('./configs/config.json');

/**
 * Get lib.
 */
const errorHandler = require('./lib/errorHandler');

/**
 * Create routes.
 */
const routes = require('./routes/index');

/**
 * Create app.
 */
const app = express();

/**
 * Setup view engine.
 */
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');

/**
 * Middlewares.
 */
app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(express.static(path.join(__dirname, 'public')));

/**
 * Use routes.
 */
app.use('/', routes);
app.use(errorHandler);

/**
 * Export app.
 */
module.exports = app;


text:
namespace medida {

class Histogram : public MetricInterface, SamplingInterface, SummarizableInterface {
 public:
  Histogram(SampleType sample_type = kUniform);
  ~Histogram();
  virtual stats::Snapshot GetSnapshot() const;
  virtual double sum() const;
  virtual double max() const;
  virtual double min() const;
  virtual double mean() const;
  virtual double std_dev() const;
  void Update(std::int64_t value);
  std::uint64_t count() const;
  double variance() const;
  void Process(MetricProcessor& processor);
  void Clear();
 private:
  class Impl;
  std::unique_ptr<Impl> impl_;
};

} // namespace medida

#endif // MEDIDA_HISTOGRAM_H_


text:
function moveWindowDirection(side, amount)
  local win = hs.window.focusedWindow()
  local frame = win:frame()

  if side == 's' then
    frame.y = frame.y + amount
  elseif side == 'e' then
    frame.x = frame.x + amount
  elseif side == 'n' then
    frame.y = frame.y - amount
  elseif side == 'w' then
    frame.x = frame.x - amount
  end

  win:setFrame(frame)
end

local moveMode = hs.hotkey.modal.new('cmd-alt-ctrl-shift', 'w')

function moveMode:entered()
  hs.alert('Move Mode')
end

function moveMode:exited()
  hs.alert('Exited Move Mode')
end

moveMode:bind('', 'escape', function()
  moveMode:exit()
end)

local moveWest = function()
  moveWindowDirection('w', 50)
end
moveMode:bind('', 'h', moveWest, nil, moveWest)

local moveWestFine = function()
  moveWindowDirection('w', 1)
end
moveMode:bind('cmd', 'h', moveWestFine, nil, moveWestFine)

local moveNorth = function()
  moveWindowDirection('n', 50)
end
moveMode:bind('', 'k', moveNorth, nil, moveNorth)

local moveNorthFine = function()
  moveWindowDirection('n', 1)
end
moveMode:bind('cmd', 'k', moveNorthFine, nil, moveNorthFine)

local moveSouth = function()
  moveWindowDirection('s', 50)
end
moveMode:bind('', 'j', moveSouth, nil, moveSouth)

local moveSouthFine = function()
  moveWindowDirection('s', 1)
end
moveMode:bind('cmd', 'j', moveSouthFine, nil, moveSouthFine)

local moveEast = function()
  moveWindowDirection('e', 50)
end
moveMode:bind('', 'l', moveEast, nil, moveEast)

local moveEastFine = function()
  moveWindowDirection('e', 1)
end
moveMode:bind('cmd', 'l', moveEastFine, nil, moveEastFine)


text:
package android.palharini.myhealth.activities.edit;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.palharini.myhealth.R;
import android.palharini.myhealth.db.ws.dao.IndicatorDAO;
import android.palharini.myhealth.db.entities.Indicator;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.*;
import android.widget.AdapterView.OnItemSelectedListener;

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

public class IndicatorEdit extends Activity {

	private Indicator indicator;
	private IndicatorDAO indicatorDAO;

	private Spinner spType;
	private EditText etMeasure1, etMeasure2;
	private TextView tvMeasUnit1, tvMeasUnit2, tvMeasure2;
	private Button btSave;
	private Button btDelete;

	private Integer intSelectedIndicator, intSelectedIndicatorID;
	private ArrayAdapter<String> adTypes;
	private String[] arrMeasUnits;
	private List<String> lsMeasUnits;

	private Boolean blUpdate, blDelete;
	private String stMeasUnit;
	private Double dbMeasure1, dbMeasure2;

	private Intent itData;

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

        // Gets data from call on monitoring tabs
		itData = getIntent();
		intSelectedIndicator = itData.getIntExtra("idIndicador", 0);

        // Instantiating screen elements
		spType = (Spinner) findViewById(R.id.spTipo);
		etMeasure1 = (EditText) findViewById(R.id.etMedida1);
		tvMeasUnit1 = (TextView) findViewById(R.id.tvUnidade1);
		tvMeasure2 = (TextView) findViewById(R.id.tvMedida2);
		etMeasure2 = (EditText) findViewById(R.id.etMedida2);
		tvMeasUnit2 = (TextView) findViewById(R.id.tvUnidade2);
		btSave = (Button) findViewById(R.id.btSave);
		btDelete = (Button) findViewById(R.id.btExcluir);

        // Setting up spinner for type selection
		adTypes = new ArrayAdapter<>(
				this, android.R.layout.simple_spinner_item, getResources().getStringArray(R.array.lsTypes));
		adTypes.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		spType.setAdapter(adTypes);

		spType.setOnItemSelectedListener(new OnItemSelectedListener() {
			public void onItemSelected(AdapterView<?> parent, View view, int posSpinner, long id) {
				// TODO Auto-generated method stub
				arrMeasUnits = getResources().getStringArray(R.array.lsUnidades);
				lsMeasUnits = Arrays.asList(arrMeasUnits);
				switch (posSpinner) {
				case 0:
					tvMeasUnit1.setText(lsMeasUnits.get(posSpinner));
					tvMeasure2.setVisibility(View.GONE);
					etMeasure2.setVisibility(View.GONE);
					tvMeasUnit2.setVisibility(View.GONE);
					break;
				case 1:
					tvMeasUnit1.setText(lsMeasUnits.get(posSpinner));
					tvMeasure2.setVisibility(View.GONE);
					etMeasure2.setVisibility(View.GONE);
					tvMeasUnit2.setVisibility(View.GONE);
					break;
				case 2:
					tvMeasUnit1.setText(lsMeasUnits.get(posSpinner));
					tvMeasure2.setVisibility(View.GONE);
					etMeasure2.setVisibility(View.GONE);
					tvMeasUnit2.setVisibility(View.GONE);
					break;
				case 3:
					tvMeasUnit1.setText(lsMeasUnits.get(posSpinner));
					tvMeasUnit2.setText("");
					tvMeasure2.setVisibility(View.VISIBLE);
					etMeasure2.setVisibility(View.VISIBLE);
					tvMeasUnit2.setVisibility(View.VISIBLE);
					break;
				case 4:
					tvMeasUnit1.setText(lsMeasUnits.get(posSpinner));
					tvMeasure2.setVisibility(View.GONE);
					etMeasure2.setVisibility(View.GONE);
					tvMeasUnit2.setVisibility(View.GONE);
					break;
				case 5:
					tvMeasUnit1.setText(lsMeasUnits.get(posSpinner));
					tvMeasure2.setVisibility(View.GONE);
					etMeasure2.setVisibility(View.GONE);
					tvMeasUnit2.setVisibility(View.GONE);
					break;
				case 6:
					tvMeasUnit1.setText(lsMeasUnits.get(posSpinner));
					tvMeasure2.setVisibility(View.GONE);
					etMeasure2.setVisibility(View.GONE);
					tvMeasUnit2.setVisibility(View.GONE);
					break;
				case 7:
					tvMeasUnit1.setText(lsMeasUnits.get(posSpinner));
					tvMeasure2.setVisibility(View.GONE);
					etMeasure2.setVisibility(View.GONE);
					tvMeasUnit2.setVisibility(View.GONE);
					break;
				case 8:
					tvMeasUnit1.setText(lsMeasUnits.get(posSpinner));
					tvMeasure2.setVisibility(View.GONE);
					etMeasure2.setVisibility(View.GONE);
					tvMeasUnit2.setVisibility(View.GONE);
					break;
				case 9:
					tvMeasUnit1.setText(lsMeasUnits.get(posSpinner));
					tvMeasure2.setVisibility(View.GONE);
					etMeasure2.setVisibility(View.GONE);
					tvMeasUnit2.setVisibility(View.GONE);
					break;
				}
			}

			@Override
			public void onNothingSelected(AdapterView<?> arg0) {
				// TODO Auto-generated method stub

			}
		});

		arrMeasUnits = getResources().getStringArray(R.array.lsUnidades);
		lsMeasUnits = Arrays.asList(arrMeasUnits);

		indicatorDAO = new IndicatorDAO();
		indicator = indicatorDAO.searchById(intSelectedIndicator);

		spType.setSelection(indicator.getTypeID());
		etMeasure1.setText(indicator.getMeasure1().toString());

		btSave.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick (View v){
				dbMeasure1 = Double.parseDouble(etMeasure1.getText().toString());
				stMeasUnit = tvMeasUnit1.getText().toString();
				intSelectedIndicatorID = spType.getSelectedItemPosition();

				if (intSelectedIndicatorID !=3) {
					blUpdate = indicatorDAO.update(new Indicator(
							indicator.getId(),
                            intSelectedIndicatorID,
                            dbMeasure1,
							0.0,
                            stMeasUnit
					));
				}
				else {
					dbMeasure2 = Double.parseDouble(etMeasure2.getText().toString());
					blUpdate = indicatorDAO.update(new Indicator(
							indicator.getId(),
                            intSelectedIndicatorID,
                            dbMeasure1,
                            dbMeasure2,
                            stMeasUnit
					));
				}

				if (blUpdate) {
					Toast.makeText(getApplicationContext(), getString(R.string.toastIndAtOK), Toast.LENGTH_LONG).show();
					finish();
				}
				else {
					Toast.makeText(getApplicationContext(), getString(R.string.toastIndAtFalha), Toast.LENGTH_LONG).show();
				}
			}
		});

		btDelete.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick (View v){
				blDelete = indicatorDAO.delete(indicator.getId());

				if (blDelete) {
					Toast.makeText(getApplicationContext(), getString(R.string.toastIndExcOK), Toast.LENGTH_LONG).show();
					finish();
				}
				else {
					Toast.makeText(getApplicationContext(), getString(R.string.toastIndExcFalha), Toast.LENGTH_LONG).show();
				}
			}
		});

	}
}


text:
class AddPublicationAttachments < ActiveRecord::Migration[4.2]
  def change
    add_column :publications, :chat_data_main_forms_attachment, :string
    add_column :publications, :chat_data_main_database_attachment, :string
    add_column :publications, :attachment_chat_form_attachment, :string
  end
end


text:
<!doctype html>
<title>loading</title>
<button>test ipfs app</button>
<script>
const { ipcRenderer } = require('electron')

ipcRenderer.on('message', (event, msg) => appendPre(msg))
ipcRenderer.on('error', (event, err) => appendPre(err))

document.querySelector('button')
  .addEventListener('click', () => {
    ipcRenderer.once('id', (event, id) => appendPre(id))
    ipcRenderer.send('start')
  })

function appendPre(data) {
  const pre = document.createElement('pre')
  pre.textContent = data
  document.body.appendChild(pre)
}
</script>


text:
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package gov.hhs.fha.nhinc.account.service;

import gov.hhs.fha.nhinc.account.dao.PatientProviderItemDao;
import gov.hhs.fha.nhinc.account.dao.UserSessionDao;
import gov.hhs.fha.nhinc.account.model.PatientProviderItem;
import gov.hhs.fha.nhinc.account.model.PatientProviderQueryParams;
import gov.hhs.fha.nhinc.account.model.UserSession;
import java.util.List;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
 *
 * @author Sushma
 */
public class AccountService {

    private static Log log = LogFactory.getLog(AccountService.class);

    /**
     * Save address record.
     *
     * @param addr Address object to save.
     */
    public void savePatientProvider(PatientProviderItem ppi) {
        log.debug("Saving a PatientProvider");

        if (ppi != null) {
            if (ppi.getPatientProviderId() != null) {
                log.debug("Performing an update for patient provider: " + ppi.getPatientProviderId());
            } else {
                log.debug("Performing an insert");
            }

        }

        PatientProviderItemDao dao = new PatientProviderItemDao();
        dao.save(ppi);
    }

    /**
     * Saves the user session in the User Session table in the database.
     *
     * @param userSession
     */
    public void saveUserSession(UserSession userSession) {
        log.debug("Saving a UserSession");

        if (userSession != null) {
            log.debug("Performing an update for user session, token is: " + userSession.getToken());
        }
        else {
            log.debug("Inserting user session");
        }

        UserSessionDao dao = new UserSessionDao();
        dao.save(userSession);
    }

    /**
     * Deletes a user session. To be called from the KMRHttpBindingListener
     * when a session times out.
     *
     * @param userSession
     * @throws AccountServiceException
     */
    public void deleteUserSession(UserSession userSession) throws AccountServiceException {
        if (userSession == null) {
            throw new AccountServiceException("UserSession to delete was null");
        }
        log.debug("Deleting a UserSession for " + userSession.getUserId());

        UserSessionDao dao = new UserSessionDao();
        dao.delete(userSession);
    }

    /**
     * Delete a patientProvider
     *
     * @param ppi patient provider to delete
     * @throws AccountServiceException
     */
    public void deleteAdress(PatientProviderItem ppi) throws AccountServiceException {
        log.debug("Deleting a PatientProvider");
        PatientProviderItemDao dao = new PatientProviderItemDao();

        if (ppi == null) {
            throw new AccountServiceException("PatientProvider to delete was null");
        }

        dao.delete(ppi);
    }

    public UserSession getUserSession(String token) {
        UserSessionDao dao = new UserSessionDao();
        return dao.findById(token);
    }

    /**
     * Retrieve a PatientProvider by identifier
     *
     * @param PatientProviderId PatientProvider identifier
     * @return Retrieved PatientProviderItem
     */
    public PatientProviderItem getPatient(Long providerId) {
        PatientProviderItemDao dao = new PatientProviderItemDao();
        return dao.findById(providerId);
    }

    /**
     * Retrieve a PatientProvider by identifier
     *
     * @param PatientProviderId PatientProvider identifier
     * @return Retrieved PatientProviderItem
     */
    public PatientProviderItem getProvider(Long patientId) {
        PatientProviderItemDao dao = new PatientProviderItemDao();
        return dao.findById(patientId);
    }

    /**
     * Retrieve a list of PatientProviders by PatientProviderQueryParams
     *
     * @param queryParams PatientProviderQueryParams
     * @return Retrieved List<PatientProviderItem>
     */
    public List<PatientProviderItem> getProvidersByParams(PatientProviderQueryParams queryParams) {
        PatientProviderItemDao dao = new PatientProviderItemDao();
        return dao.findPatient(queryParams);
    }

    /**
     * Retrieves all PatientProvider
     *
     * @return All PatientProvider records
     */
    public List<PatientProviderItem> getAllPatientProvider() {
        PatientProviderItemDao dao = new PatientProviderItemDao();
        return dao.findAll();
    }
}