text:
<?php

namespace Zend\Validator;

use Zend\Stdlib\StringUtils;
use Zend\Stdlib\StringWrapper\StringWrapperInterface as StringWrapper;

class StringLength extends AbstractValidator
{
    const INVALID   = 'stringLengthInvalid';
    const TOO_SHORT = 'stringLengthTooShort';
    const TOO_LONG  = 'stringLengthTooLong';

    /**
     * @var array
     */
    protected $messageTemplates = array(
        self::INVALID   => "Invalid type given. String expected",
        self::TOO_SHORT => "The input is less than %min% characters long",
        self::TOO_LONG  => "The input is more than %max% characters long",
    );

    /**
     * @var array
     */
    protected $messageVariables = array(
        'min' => array('options' => 'min'),
        'max' => array('options' => 'max'),
    );

    protected $options = array(
        'min'      => 0,       // Minimum length
        'max'      => null,    // Maximum length, null if there is no length limitation
        'encoding' => 'UTF-8', // Encoding to use
    );

    protected $stringWrapper;

    /**
     * Sets validator options
     *
     * @param  int|array|\Traversable $options
     */
    public function __construct($options = array())
    {
        if (!is_array($options)) {
            $options     = func_get_args();
            $temp['min'] = array_shift($options);
            if (!empty($options)) {
                $temp['max'] = array_shift($options);
            }

            if (!empty($options)) {
                $temp['encoding'] = array_shift($options);
            }

            $options = $temp;
        }

        parent::__construct($options);
    }

    /**
     * Returns the min option
     *
     * @return int
     */
    public function getMin()
    {
        return $this->options['min'];
    }

    /**
     * Sets the min option
     *
     * @param  int $min
     * @throws Exception\InvalidArgumentException
     * @return StringLength Provides a fluent interface
     */
    public function setMin($min)
    {
        if (null !== $this->getMax() && $min > $this->getMax()) {
            throw new Exception\InvalidArgumentException(
                "The minimum must be less than or equal to the maximum length, but $min >" . " " . $this->getMax()
            );
        }

        $this->options['min'] = max(0, (int) $min);
        return $this;
    }

    /**
     * Returns the max option
     *
     * @return int|null
     */
    public function getMax()
    {
        return $this->options['max'];
    }

    /**
     * Sets the max option
     *
     * @param  int|null $max
     * @throws Exception\InvalidArgumentException
     * @return StringLength Provides a fluent interface
     */
    public function setMax($max)
    {
        if (null === $max) {
            $this->options['max'] = null;
        } elseif ($max < $this->getMin()) {
            throw new Exception\InvalidArgumentException(
                "The maximum must be greater than or equal to the minimum length, but $max < " . $this->getMin()
            );
        } else {
            $this->options['max'] = (int) $max;
        }

        return $this;
    }

    /**
     * Get the string wrapper to detect the string length
     *
     * @return StringWrapper
     */
    public function getStringWrapper()
    {
        if (!$this->stringWrapper) {
            $this->stringWrapper = StringUtils::getWrapper($this->getEncoding());
        }
        return $this->stringWrapper;
    }

    /**
     * Set the string wrapper to detect the string length
     *
     * @param StringWrapper $stringWrapper
     * @return StringLength
     */
    public function setStringWrapper(StringWrapper $stringWrapper)
    {
        $stringWrapper->setEncoding($this->getEncoding());
        $this->stringWrapper = $stringWrapper;
    }

    /**
     * Returns the actual encoding
     *
     * @return string
     */
    public function getEncoding()
    {
        return $this->options['encoding'];
    }

    /**
     * Sets a new encoding to use
     *
     * @param string $encoding
     * @return StringLength
     * @throws Exception\InvalidArgumentException
     */
    public function setEncoding($encoding)
    {
        $this->stringWrapper = StringUtils::getWrapper($encoding);
        $this->options['encoding'] = $encoding;
        return $this;
    }

    /**
     * Returns true if and only if the string length of $value is at least the min option and
     * no greater than the max option (when the max option is not null).
     *
     * @param  string $value
     * @return bool
     */
    public function isValid($value)
    {
        if (!is_string($value)) {
            $this->error(self::INVALID);
            return false;
        }

        $this->setValue($value);

        $length = $this->getStringWrapper()->strlen($value);
        if ($length < $this->getMin()) {
            $this->error(self::TOO_SHORT);
        }

        if (null !== $this->getMax() && $this->getMax() < $length) {
            $this->error(self::TOO_LONG);
        }

        if (count($this->getMessages())) {
            return false;
        }

        return true;
    }
}


text:
export interface MsgChat {
    channel: number,
    userName: string,
    content: string,
    time: number
}

redpajama_set_name: RedPajamaGithub


text:
log_user 0

# A script to upload the specified Sequel Pro build to the nightlies server, as another minor security hurdle.
# This will be called by the build script with the first parameter being the VCS revision, second passphrase

# Ensure a revision number was passed in
set REVISION_NUMBER [lindex $argv 0]
set PASSPHRASE [lindex $argv 1]

# Perform the upload
spawn scp -q -P 32100 /Users/spbuildbot/buildbot/sequel-pro/build/build/Release/Sequel_Pro_r${REVISION_NUMBER}.dmg sequelpro@sequelpro.com:public_html/nightly
expect "Enter passphrase for key '/Users/spbuildbot/.ssh/id_rsa': "
send "${PASSPHRASE}\r"
expect eof
catch wait result
exit [lindex $result 3]


text:
'use strict';

// Declare app level module which depends on filters, and services
angular.module('myApp', [
  'ngRoute',
  'myApp.filters',
  'myApp.services',
  'myApp.directives',
  'myApp.controllers'
]).
config(['$routeProvider', function($routeProvider) {
  $routeProvider.when('/menu', {templateUrl: 'partials/menu.html', controller: 'MenuCtrl'});
  $routeProvider.when('/settings', {templateUrl: 'partials/settings.html', controller: 'SettingsCtrl'});
  $routeProvider.when('/timer', {templateUrl: 'partials/timer.html', controller: 'TimerCtrl'});
  $routeProvider.otherwise({redirectTo: '/timer'});
}]);


text:
package org.apache.logging.log4j.core.async;

import java.util.Map;

import org.apache.logging.log4j.Level;
import org.apache.logging.log4j.Marker;
import org.apache.logging.log4j.ThreadContext.ContextStack;
import org.apache.logging.log4j.message.Message;

import com.lmax.disruptor.EventTranslator;

/**
 * This class is responsible for writing elements that make up a log event into
 * the ringbuffer {@code RingBufferLogEvent}. After this translator populated
 * the ringbuffer event, the disruptor will update the sequence number so that
 * the event can be consumed by another thread.
 */
public class RingBufferLogEventTranslator implements
        EventTranslator<RingBufferLogEvent> {

    private AsyncLogger asyncLogger;
    private String loggerName;
    protected Marker marker;
    protected String fqcn;
    protected Level level;
    protected Message message;
    protected Throwable thrown;
    private Map<String, String> contextMap;
    private ContextStack contextStack;
    private long threadId = Thread.currentThread().getId();
    private String threadName = Thread.currentThread().getName();
    private int threadPriority = Thread.currentThread().getPriority();
    private StackTraceElement location;
    private long currentTimeMillis;
    private long nanoTime;

    // @Override
    @Override
    public void translateTo(final RingBufferLogEvent event, final long sequence) {
        event.setValues(asyncLogger, loggerName, marker, fqcn, level, message, thrown, contextMap, contextStack,
                threadId, threadName, threadPriority, location, currentTimeMillis, nanoTime);
        clear();
    }

    /**
     * Release references held by this object to allow objects to be garbage-collected.
     */
    private void clear() {
        setBasicValues(null, // asyncLogger
                null, // loggerName
                null, // marker
                null, // fqcn
                null, // level
                null, // data
                null, // t
                null, // map
                null, // contextStack
                null, // location
                0, // currentTimeMillis
                0 // nanoTime
        );
    }

    public void setBasicValues(final AsyncLogger anAsyncLogger, final String aLoggerName, final Marker aMarker,
            final String theFqcn, final Level aLevel, final Message msg, final Throwable aThrowable,
            final Map<String, String> aMap, final ContextStack aContextStack, final StackTraceElement aLocation,
            final long aCurrentTimeMillis, final long aNanoTime) {
        this.asyncLogger = anAsyncLogger;
        this.loggerName = aLoggerName;
        this.marker = aMarker;
        this.fqcn = theFqcn;
        this.level = aLevel;
        this.message = msg;
        this.thrown = aThrowable;
        this.contextMap = aMap;
        this.contextStack = aContextStack;
        this.location = aLocation;
        this.currentTimeMillis = aCurrentTimeMillis;
        this.nanoTime = aNanoTime;
    }

    public void updateThreadValues() {
        final Thread currentThread = Thread.currentThread();
        this.threadId = currentThread.getId();
        this.threadName = currentThread.getName();
        this.threadPriority = currentThread.getPriority();
    }
}


text:
package filters

import (
	"net/http"

	"github.com/astaxie/beego/context"
	"github.com/gernest/lora/controllers"
	"github.com/gernest/lora/models"
)

func StaticProxy(ctx *context.Context) {
	db, err := models.Conn()
	if err != nil {
		return
	}
	defer db.Close()
	projects := []models.Project{}
	db.Debug().Find(&projects)

	if ctx.Input.SubDomains() != "" {
		for _, project := range projects {
			if ctx.Input.SubDomains() == project.Name {
				ctx.Input.SetData("projectPath", project.ProjectPath)
				controllers.ServeSite(ctx)
				break
			}
		}
		if ctx.Input.GetData("projectPath") == nil {
			http.NotFound(ctx.ResponseWriter, ctx.Request)
			return
		}
	}

}


text:
const gulp = require('gulp');
const del = require('del');
const cache = require('gulp-cached');
const help = require('gulp-task-listing');
const babel = require('gulp-babel');
const ext = require('gulp-ext');
const eslint = require('gulp-eslint');

function clean() {
  return del(['build'])
}

function transpileBin() {
  return gulp.src('bin/**/*')
  .pipe(cache('bin'))
  .pipe(babel())
  .pipe(ext.crop())
  .pipe(gulp.dest('build'))
}

function transpileLib() {
  return gulp.src('lib/**/*')
  .pipe(cache('lib'))
  .pipe(babel())
  .pipe(gulp.dest('build/lib'))
}

function copy() {
  return gulp.src(['default.json'])
  .pipe(gulp.dest('build'));
}

function watchFiles() {
  gulp.watch('lib/**/*', build);
}

function lint() {
  return gulp.src(['**/*.js', '!node_modules/**', '!build/**', '!docs/**'])
  .pipe(eslint())
  .pipe(eslint.format())
  .pipe(eslint.failAfterError())
}

export { clean, help, transpileBin, transpileLib, copy, lint, watchFiles as watch };

const build = gulp.series(copy, transpileBin, transpileLib);

export default build;


text:
package dcode.games.uEngine2.SFX.tslib;

/**
 * The Sound interface  is an abstraction for sound effects.  Sound objects
 * should only be loaded via the TinySound loadSound() functions.
 * Sounds can be played repeatedly in an overlapping fashion.
 *
 * @author Finn Kuusisto
 */
public interface Sound {

	/**
	 * Plays this Sound.
	 */
	void play();

	/**
	 * Plays this Sound with a specified volume.
	 * @param volume the volume at which to play this Sound
	 */
	void play(double volume);

	/**
	 * Plays this Sound with a specified volume and pan.
	 * @param volume the volume at which to play this Sound
	 * @param pan the pan value to play this Sound [-1.0,1.0], values outside
	 * the valid range will assume no panning (0.0)
	 */
	void play(double volume, double pan);

	/**
	 * Stops this Sound from playing.  Note that if this Sound was played
	 * repeatedly in an overlapping fashion, all instances of this Sound still
	 * playing will be stopped.
	 */
	void stop();

	/**
	 * Unloads this Sound from the system.  Attempts to use this Sound after
	 * unloading will result in error.
	 */
	void unload();

}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using Wikiled.Common.Extensions;
using Wikiled.MachineLearning.Mathematics;
using Wikiled.Sentiment.Text.MachineLearning;
using Wikiled.Sentiment.Text.Sentiment;
using Wikiled.Sentiment.Text.Words;
using Wikiled.Text.Analysis.NLP.NRC;
using Wikiled.Text.Analysis.Structure;

namespace Wikiled.Sentiment.Text.Data
{
    public class ParsedReview : IParsedReview
    {
        private readonly List<ISentence> allSentences = new List<ISentence>();

        private readonly string text;

        internal ParsedReview(INRCDictionary dictionary, Document document, ISessionContext context)
        {
            if (document is null)
            {
                throw new ArgumentNullException(nameof(document));
            }

            if (context == null) throw new ArgumentNullException(nameof(context));

            if (document.DocumentTime.HasValue &&
                document.DocumentTime.Value.Ticks > 0)
            {
                Date = document.DocumentTime.Value;
            }

            Document = document;
            Context = context;
            text = document.Text;
            Vector = new ExtractReviewTextVector(dictionary, this);
        }

        public Document Document { get; }

        public ISentence CurrentSentence { get; private set; }

        public ISessionContext Context { get; }

        public DateTime? Date { get; }

        public IEnumerable<IWordItem> AllWords => Sentences.SelectMany(item => item.Occurrences);

        public IEnumerable<IWordItem> ImportantWords => Sentences.SelectMany(item => item.Occurrences.GetImportant());

        public IList<ISentence> Sentences
        {
            get
            {
                return allSentences.Where(item => item.Parts.Any()).ToList();
            }
        }

        public string Text
        {
            get
            {
                if (!string.IsNullOrEmpty(text))
                {
                    return text;
                }

                if (!Sentences.Any())
                {
                    return string.Empty;
                }

                return Sentences
                    .Select(item => item.Text)
                    .AccumulateItems(". ");
            }
        }

        public ExtractTextVectorBase Vector { get; }

        public void AddNewSentence(SentenceItem sentence)
        {
            CurrentSentence = new Sentence(this, sentence);
            if (allSentences.Count > 0)
            {
                allSentences[allSentences.Count - 1].Next = CurrentSentence;
                CurrentSentence.Previous = allSentences[allSentences.Count - 1];
            }

            allSentences.Add(CurrentSentence);
        }

        public RatingData CalculateRawRating()
        {
            return RatingData.Accumulate(allSentences.Select(item => item.CalculateRating()));
        }

        public SentimentValue[] GetAllSentiments()
        {
            return (from item in ImportantWords
                    where item.Relationship.Sentiment != null
                    select item.Relationship.Sentiment)
                .ToArray();
        }

        public void Reset()
        {
            foreach (var sentence in Sentences)
            {
                foreach (var wordOccurrence in sentence.Occurrences)
                {
                    wordOccurrence.Reset();
                    var parent = wordOccurrence.Parent as Phrase;
                    parent?.Reset();
                }
            }
        }
    }
}


text:
function [] = count_chromosomes_directory()
run('Aro_parameters.m');

dye = dyesUsed{1};
if ~exist([ImageDir filesep dye], 'dir')
    disp('[ERROR] The images have not been trimmed/placed in the proper folders! Please trim first.');
    return;
end
current_files = dir([RawImageDir filesep '*.tif']);
tif_files = {current_files.name};
disp(tif_files);

mask_files = dir([SegmentationMaskDir filesep 'Mask*.tif']);
mask_files = {mask_files.name};
disp(mask_files);

masks_exist = (numel(mask_files) == numel(tif_files));

if isempty(tif_files)
    disp('[ERROR] There appear to be no images in the directory for this dye! Please check your image files.');
    return;
else

    for i = 1:numel(tif_files)
        name = tif_files{i};
        if masks_exist
            mask_name = [SegmentationMaskDir filesep mask_files{i}];
        else
            mask_name = '0';
        end
        count = count_chromosomes([RawImageDir filesep name], mask_name);
        fileID = fopen(ChromosomeFile, 'a');
        fprintf(fileID, [name ', ' num2str(count) '\n']);
        fclose(fileID);
    end
end
clear;
return;


text:
class CreateTaggings < ActiveRecord::Migration
  def change
    create_table :taggings do |t|
      t.integer :micropost_id
      t.integer :tag_id

      t.timestamps
    end
  end
end


text:
<?php

use yii\helpers\Html;
use yii\widgets\ActiveForm;

/* @var $this yii\web\View */
/* @var $model app\models\Tipo */
/* @var $form yii\widgets\ActiveForm */
?>

    <?php $form = ActiveForm::begin(); ?>

    <?= $form->field($model, 'idtipo')->textInput() ?>

    <?= $form->field($model, 'nombretipo')->textInput(['maxlength' => true]) ?>

    <?= $form->field($model, 'descripcion')->textInput(['maxlength' => true]) ?>

        <?= Html::submitButton($model->isNewRecord ? 'Crear' : 'Actualizar', ['class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-primary']) ?>

    <?php ActiveForm::end(); ?>


text:
"""
Module to test fitting routines
"""

import os.path

import pytest
import numpy as np
from numpy import linalg
from numpy.testing.utils import assert_allclose, assert_almost_equal
from unittest import mock

from . import irafutil
from .. import models
from ..core import Fittable2DModel, Parameter
from ..fitting import *
from ...utils import NumpyRNGContext
from ...utils.data import get_pkg_data_filename
from .utils import ignore_non_integer_warning
from ...stats import sigma_clip

from ...utils.exceptions import AstropyUserWarning
from ..fitting import populate_entry_points
import warnings

try:
    from scipy import optimize
    HAS_SCIPY = True
except ImportError:
    HAS_SCIPY = False

try:
    from pkg_resources import EntryPoint
    HAS_PKG = True
except ImportError:
    HAS_PKG = False

fitters = [SimplexLSQFitter, SLSQPLSQFitter]

_RANDOM_SEED = 0x1337

class TestPolynomial2D:
    """Tests for 2D polynomail fitting."""

    def setup_class(self):
        self.model = models.Polynomial2D(2)
        self.y, self.x = np.mgrid[:5, :5]

        def poly2(x, y):
            return 1 + 2 * x + 3 * x ** 2 + 4 * y + 5 * y ** 2 + 6 * x * y
        self.z = poly2(self.x, self.y)
        self.fitter = LinearLSQFitter()

    def test_poly2D_fitting(self):
        v = self.model.fit_deriv(x=self.x, y=self.y)
        p = linalg.lstsq(v, self.z.flatten())[0]
        new_model = self.fitter(self.model, self.x, self.y, self.z)
        assert_allclose(new_model.parameters, p)

    def test_eval(self):
        new_model = self.fitter(self.model, self.x, self.y, self.z)
        assert_allclose(new_model(self.x, self.y), self.z)

    @pytest.mark.skipif('not HAS_SCIPY')
    def test_polynomial2D_nonlinear_fitting(self):
        self.model.parameters = [.6, 1.8, 2.9, 3.7, 4.9, 6.7]
        nlfitter = LevMarLSQFitter()
        new_model = nlfitter(self.model, self.x, self.y, self.z)
        assert_allclose(new_model.parameters, [1, 2, 3, 4, 5, 6])

class TestICheb2D:
    """
    Tests 2D Chebyshev polynomial fitting

    Create a 2D polynomial (z) using Polynomial2DModel and default coefficients
    Fit z using a ICheb2D model
    Evaluate the ICheb2D polynomial and compare with the initial z
    """

    def setup_class(self):
        self.pmodel = models.Polynomial2D(2)
        self.y, self.x = np.mgrid[:5, :5]
        self.z = self.pmodel(self.x, self.y)
        self.cheb2 = models.Chebyshev2D(2, 2)
        self.fitter = LinearLSQFitter()

    def test_default_params(self):
        self.cheb2.parameters = np.arange(9)
        p = np.array([1344., 1772., 400., 1860., 2448., 552., 432., 568.,
                      128.])
        z = self.cheb2(self.x, self.y)
        model = self.fitter(self.cheb2, self.x, self.y, z)
        assert_almost_equal(model.parameters, p)

    def test_poly2D_cheb2D(self):
        model = self.fitter(self.cheb2, self.x, self.y, self.z)
        z1 = model(self.x, self.y)
        assert_almost_equal(self.z, z1)

    @pytest.mark.skipif('not HAS_SCIPY')
    def test_chebyshev2D_nonlinear_fitting(self):
        cheb2d = models.Chebyshev2D(2, 2)
        cheb2d.parameters = np.arange(9)
        z = cheb2d(self.x, self.y)
        cheb2d.parameters = [0.1, .6, 1.8, 2.9, 3.7, 4.9, 6.7, 7.5, 8.9]
        nlfitter = LevMarLSQFitter()
        model = nlfitter(cheb2d, self.x, self.y, z)
        assert_allclose(model.parameters, [0, 1, 2, 3, 4, 5, 6, 7, 8],
                        atol=10**-9)

    @pytest.mark.skipif('not HAS_SCIPY')
    def test_chebyshev2D_nonlinear_fitting_with_weights(self):
        cheb2d = models.Chebyshev2D(2, 2)
        cheb2d.parameters = np.arange(9)
        z = cheb2d(self.x, self.y)
        cheb2d.parameters = [0.1, .6, 1.8, 2.9, 3.7, 4.9, 6.7, 7.5, 8.9]
        nlfitter = LevMarLSQFitter()
        weights = np.ones_like(self.y)
        model = nlfitter(cheb2d, self.x, self.y, z, weights=weights)
        assert_allclose(model.parameters, [0, 1, 2, 3, 4, 5, 6, 7, 8],
                        atol=10**-9)

@pytest.mark.skipif('not HAS_SCIPY')
class TestJointFitter:

    """
    Tests the joint fitting routine using 2 gaussian models
    """

    def setup_class(self):
        """
        Create 2 gaussian models and some data with noise.
        Create a fitter for the two models keeping the amplitude parameter
        common for the two models.
        """
        self.g1 = models.Gaussian1D(10, mean=14.9, stddev=.3)
        self.g2 = models.Gaussian1D(10, mean=13, stddev=.4)
        self.jf = JointFitter([self.g1, self.g2],
                                      {self.g1: ['amplitude'],
                                       self.g2: ['amplitude']}, [9.8])
        self.x = np.arange(10, 20, .1)
        y1 = self.g1(self.x)
        y2 = self.g2(self.x)

        with NumpyRNGContext(_RANDOM_SEED):
            n = np.random.randn(100)

        self.ny1 = y1 + 2 * n
        self.ny2 = y2 + 2 * n
        self.jf(self.x, self.ny1, self.x, self.ny2)

    def test_joint_parameter(self):
        """
        Tests that the amplitude of the two models is the same
        """
        assert_allclose(self.jf.fitparams[0], self.g1.parameters[0])
        assert_allclose(self.jf.fitparams[0], self.g2.parameters[0])

    def test_joint_fitter(self):
        """
        Tests the fitting routine with similar procedure.
        Compares the fitted parameters.
        """
        p1 = [14.9, .3]
        p2 = [13, .4]
        A = 9.8
        p = np.r_[A, p1, p2]

        def model(A, p, x):
            return A * np.exp(-0.5 / p[1] ** 2 * (x - p[0]) ** 2)

        def errfunc(p, x1, y1, x2, y2):
            return np.ravel(np.r_[model(p[0], p[1:3], x1) - y1,
                            model(p[0], p[3:], x2) - y2])

        coeff, _ = optimize.leastsq(errfunc, p,
                                    args=(self.x, self.ny1, self.x, self.ny2))
        assert_allclose(coeff, self.jf.fitparams, rtol=10 ** (-2))

class TestLinearLSQFitter:
    def test_chebyshev1D(self):
        """Tests fitting a 1D Chebyshev polynomial to some real world data."""

        test_file = get_pkg_data_filename(os.path.join('data',
                                                       'idcompspec.fits'))
        with open(test_file) as f:
            lines = f.read()
            reclist = lines.split('begin')

        record = irafutil.IdentifyRecord(reclist[1])
        coeffs = record.coeff
        order = int(record.fields['order'])

        initial_model = models.Chebyshev1D(order - 1,
                                           domain=record.get_range())
        fitter = LinearLSQFitter()

        fitted_model = fitter(initial_model, record.x, record.z)
        assert_allclose(fitted_model.parameters, np.array(coeffs),
                        rtol=10e-2)

    def test_linear_fit_model_set(self):
        """Tests fitting multiple models simultaneously."""

        init_model = models.Polynomial1D(degree=2, c0=[1, 1], n_models=2)
        x = np.arange(10)
        y_expected = init_model(x, model_set_axis=False)
        assert y_expected.shape == (2, 10)

        # Add a bit of random noise
        with NumpyRNGContext(_RANDOM_SEED):
            y = y_expected + np.random.normal(0, 0.01, size=y_expected.shape)

        fitter = LinearLSQFitter()
        fitted_model = fitter(init_model, x, y)
        assert_allclose(fitted_model(x, model_set_axis=False), y_expected,
                        rtol=1e-1)

    def test_linear_fit_2d_model_set(self):
        """Tests fitted multiple 2-D models simultaneously."""

        init_model = models.Polynomial2D(degree=2, c0_0=[1, 1], n_models=2)
        x = np.arange(10)
        y = np.arange(10)
        z_expected = init_model(x, y, model_set_axis=False)
        assert z_expected.shape == (2, 10)

        # Add a bit of random noise
        with NumpyRNGContext(_RANDOM_SEED):
            z = z_expected + np.random.normal(0, 0.01, size=z_expected.shape)

        fitter = LinearLSQFitter()
        fitted_model = fitter(init_model, x, y, z)
        assert_allclose(fitted_model(x, y, model_set_axis=False), z_expected,
                        rtol=1e-1)

    def test_linear_fit_fixed_parameter(self):
        """
        Tests fitting a polynomial model with a fixed parameter (issue #6135).
        """
        init_model = models.Polynomial1D(degree=2, c1=1)
        init_model.c1.fixed = True

        x = np.arange(10)
        y = 2 + x + 0.5*x*x

        fitter = LinearLSQFitter()
        fitted_model = fitter(init_model, x, y)
        assert_allclose(fitted_model.parameters, [2., 1., 0.5], atol=1e-14)

    def test_linear_fit_model_set_fixed_parameter(self):
        """
        Tests fitting a polynomial model set with a fixed parameter (#6135).
        """
        init_model = models.Polynomial1D(degree=2, c1=[1, -2], n_models=2)
        init_model.c1.fixed = True

        x = np.arange(10)
        yy = np.array([2 + x + 0.5*x*x, -2*x])

        fitter = LinearLSQFitter()
        fitted_model = fitter(init_model, x, yy)

        assert_allclose(fitted_model.c0, [2., 0.], atol=1e-14)
        assert_allclose(fitted_model.c1, [1., -2.], atol=1e-14)
        assert_allclose(fitted_model.c2, [0.5, 0.], atol=1e-14)

    def test_linear_fit_2d_model_set_fixed_parameters(self):
        """
        Tests fitting a 2d polynomial model set with fixed parameters (#6135).
        """
        init_model = models.Polynomial2D(degree=2, c1_0=[1, 2], c0_1=[-0.5, 1],
                                         n_models=2,
                                         fixed={'c1_0': True, 'c0_1': True})

        x, y = np.mgrid[0:5, 0:5]
        zz = np.array([1+x-0.5*y+0.1*x*x, 2*x+y-0.2*y*y])

        fitter = LinearLSQFitter()
        fitted_model = fitter(init_model, x, y, zz)

        assert_allclose(fitted_model(x, y, model_set_axis=False), zz,
                        atol=1e-14)

    def test_linear_fit_model_set_masked_values(self):
        """
        Tests model set fitting with masked value(s) (#4824, #6819).
        """
        # NB. For single models, there is an equivalent doctest.

        init_model = models.Polynomial1D(degree=1, n_models=2)
        x = np.arange(10)
        y = np.ma.masked_array([2*x+1, x-2], mask=np.zeros_like([x, x]))

        y[0, 7] = 100.  # throw off fit coefficients if unmasked
        y.mask[0, 7] = True
        y[1, 1:3] = -100.
        y.mask[1, 1:3] = True

        fitter = LinearLSQFitter()
        fitted_model = fitter(init_model, x, y)

        assert_allclose(fitted_model.c0, [1., -2.], atol=1e-14)
        assert_allclose(fitted_model.c1, [2., 1.], atol=1e-14)

    def test_linear_fit_2d_model_set_masked_values(self):
        """
        Tests 2D model set fitting with masked value(s) (#4824, #6819).
        """
        init_model = models.Polynomial2D(1, n_models=2)
        x, y = np.mgrid[0:5, 0:5]
        z = np.ma.masked_array([2*x+3*y+1, x-0.5*y-2],
                               mask=np.zeros_like([x, x]))

        z[0, 3, 1] = -1000.  # throw off fit coefficients if unmasked
        z.mask[0, 3, 1] = True

        fitter = LinearLSQFitter()
        fitted_model = fitter(init_model, x, y, z)

        assert_allclose(fitted_model.c0_0, [1., -2.], atol=1e-14)
        assert_allclose(fitted_model.c1_0, [2., 1.], atol=1e-14)
        assert_allclose(fitted_model.c0_1, [3., -0.5], atol=1e-14)

@pytest.mark.skipif('not HAS_SCIPY')
class TestNonLinearFitters:
    """Tests non-linear least squares fitting and the SLSQP algorithm."""

    def setup_class(self):
        self.initial_values = [100, 5, 1]

        self.xdata = np.arange(0, 10, 0.1)
        sigma = 4. * np.ones_like(self.xdata)

        with NumpyRNGContext(_RANDOM_SEED):
            yerror = np.random.normal(0, sigma)

        def func(p, x):
            return p[0] * np.exp(-0.5 / p[2] ** 2 * (x - p[1]) ** 2)

        self.ydata = func(self.initial_values, self.xdata) + yerror
        self.gauss = models.Gaussian1D(100, 5, stddev=1)

    def test_estimated_vs_analytic_deriv(self):
        """
        Runs `LevMarLSQFitter` with estimated and analytic derivatives of a
        `Gaussian1D`.
        """

        fitter = LevMarLSQFitter()
        model = fitter(self.gauss, self.xdata, self.ydata)
        g1e = models.Gaussian1D(100, 5.0, stddev=1)
        efitter = LevMarLSQFitter()
        emodel = efitter(g1e, self.xdata, self.ydata, estimate_jacobian=True)
        assert_allclose(model.parameters, emodel.parameters, rtol=10 ** (-3))

    def test_estimated_vs_analytic_deriv_with_weights(self):
        """
        Runs `LevMarLSQFitter` with estimated and analytic derivatives of a
        `Gaussian1D`.
        """

        weights = 1.0 / (self.ydata / 10.)

        fitter = LevMarLSQFitter()
        model = fitter(self.gauss, self.xdata, self.ydata, weights=weights)
        g1e = models.Gaussian1D(100, 5.0, stddev=1)
        efitter = LevMarLSQFitter()
        emodel = efitter(g1e, self.xdata, self.ydata, weights=weights, estimate_jacobian=True)
        assert_allclose(model.parameters, emodel.parameters, rtol=10 ** (-3))

    def test_with_optimize(self):
        """
        Tests results from `LevMarLSQFitter` against `scipy.optimize.leastsq`.
        """

        fitter = LevMarLSQFitter()
        model = fitter(self.gauss, self.xdata, self.ydata,
                       estimate_jacobian=True)

        def func(p, x):
            return p[0] * np.exp(-0.5 / p[2] ** 2 * (x - p[1]) ** 2)

        def errfunc(p, x, y):
            return func(p, x) - y

        result = optimize.leastsq(errfunc, self.initial_values,
                                  args=(self.xdata, self.ydata))
        assert_allclose(model.parameters, result[0], rtol=10 ** (-3))

    def test_with_weights(self):
        """
        Tests results from `LevMarLSQFitter` with weights.
        """
        # part 1: weights are equal to 1
        fitter = LevMarLSQFitter()
        model = fitter(self.gauss, self.xdata, self.ydata,
                       estimate_jacobian=True)
        withw = fitter(self.gauss, self.xdata, self.ydata,
                       estimate_jacobian=True, weights=np.ones_like(self.xdata))

        assert_allclose(model.parameters, withw.parameters, rtol=10 ** (-4))

        # part 2: weights are 0 or 1 (effectively, they are a mask)
        weights = np.zeros_like(self.xdata)
        weights[::2] = 1.
        mask = weights >= 1.

        model = fitter(self.gauss, self.xdata[mask], self.ydata[mask],
                       estimate_jacobian=True)
        withw = fitter(self.gauss, self.xdata, self.ydata,
                       estimate_jacobian=True, weights=weights)

        assert_allclose(model.parameters, withw.parameters, rtol=10 ** (-4))

    @pytest.mark.parametrize('fitter_class', fitters)
    def test_fitter_against_LevMar(self, fitter_class):
        """Tests results from non-linear fitters against `LevMarLSQFitter`."""

        levmar = LevMarLSQFitter()
        fitter = fitter_class()
        with ignore_non_integer_warning():
            new_model = fitter(self.gauss, self.xdata, self.ydata)
        model = levmar(self.gauss, self.xdata, self.ydata)
        assert_allclose(model.parameters, new_model.parameters,
                        rtol=10 ** (-4))

    def test_LSQ_SLSQP_with_constraints(self):
        """
        Runs `LevMarLSQFitter` and `SLSQPLSQFitter` on a model with
        constraints.
        """

        g1 = models.Gaussian1D(100, 5, stddev=1)
        g1.mean.fixed = True
        fitter = LevMarLSQFitter()
        fslsqp = SLSQPLSQFitter()
        with ignore_non_integer_warning():
            slsqp_model = fslsqp(g1, self.xdata, self.ydata)
        model = fitter(g1, self.xdata, self.ydata)
        assert_allclose(model.parameters, slsqp_model.parameters,
                        rtol=10 ** (-4))

    def test_simplex_lsq_fitter(self):
        """A basic test for the `SimplexLSQ` fitter."""

        class Rosenbrock(Fittable2DModel):
            a = Parameter()
            b = Parameter()

            @staticmethod
            def evaluate(x, y, a, b):
                return (a - x) ** 2 + b * (y - x ** 2) ** 2

        x = y = np.linspace(-3.0, 3.0, 100)
        with NumpyRNGContext(_RANDOM_SEED):
            z = Rosenbrock.evaluate(x, y, 1.0, 100.0)
            z += np.random.normal(0., 0.1, size=z.shape)

        fitter = SimplexLSQFitter()
        r_i = Rosenbrock(1, 100)
        r_f = fitter(r_i, x, y, z)

        assert_allclose(r_f.parameters, [1.0, 100.0], rtol=1e-2)

    def test_param_cov(self):
        """
        Tests that the 'param_cov' fit_info entry gets the right answer for
        *linear* least squares, where the answer is exact
        """

        a = 2
        b = 100

        with NumpyRNGContext(_RANDOM_SEED):
            x = np.linspace(0, 1, 100)
            # y scatter is amplitude ~1 to make sure covarience is
            # non-negligible
            y = x*a + b + np.random.randn(len(x))

        # first compute the ordinary least squares covariance matrix
        X = np.matrix(np.vstack([x, np.ones(len(x))]).T)
        beta = np.linalg.inv(X.T * X) * X.T * np.matrix(y).T
        s2 = np.sum((y - (X * beta).A.ravel())**2) / (len(y) - len(beta))
        olscov = np.linalg.inv(X.T * X) * s2

        # now do the non-linear least squares fit
        mod = models.Linear1D(a, b)
        fitter = LevMarLSQFitter()

        fmod = fitter(mod, x, y)

        assert_allclose(fmod.parameters, beta.A.ravel())
        assert_allclose(olscov, fitter.fit_info['param_cov'])

@pytest.mark.skipif('not HAS_PKG')
class TestEntryPoint:
    """Tests population of fitting with entry point fitters"""

    def setup_class(self):
        self.exception_not_thrown = Exception("The test should not have gotten here. There was no exception thrown")

    def successfulimport(self):
            # This should work
            class goodclass(Fitter):
                __name__ = "GoodClass"
            return goodclass

    def raiseimporterror(self):
        #  This should fail as it raises an Import Error
        raise ImportError

    def returnbadfunc(self):
        def badfunc():
            # This should import but it should fail type check
            pass
        return badfunc

    def returnbadclass(self):
        # This should import But it should fail subclass type check
        class badclass:
            pass
        return badclass

    def test_working(self):
        """This should work fine"""
        mock_entry_working = mock.create_autospec(EntryPoint)
        mock_entry_working.name = "Working"
        mock_entry_working.load = self.successfulimport
        populate_entry_points([mock_entry_working])

    def test_import_error(self):
        """This raises an import error on load to test that it is handled correctly"""
        with warnings.catch_warnings():
            warnings.filterwarnings('error')
            try:
                mock_entry_importerror = mock.create_autospec(EntryPoint)
                mock_entry_importerror.name = "IErr"
                mock_entry_importerror.load = self.raiseimporterror
                populate_entry_points([mock_entry_importerror])
            except AstropyUserWarning as w:
                if "ImportError" in w.args[0]:  # any error for this case should have this in it.
                    pass
                else:
                    raise w
            else:
                raise self.exception_not_thrown

    def test_bad_func(self):
        """This returns a function which fails the type check"""
        with warnings.catch_warnings():
            warnings.filterwarnings('error')
            try:
                mock_entry_badfunc = mock.create_autospec(EntryPoint)
                mock_entry_badfunc.name = "BadFunc"
                mock_entry_badfunc.load = self.returnbadfunc
                populate_entry_points([mock_entry_badfunc])
            except AstropyUserWarning as w:
                if "Class" in w.args[0]:  # any error for this case should have this in it.
                    pass
                else:
                    raise w
            else:
                raise self.exception_not_thrown

    def test_bad_class(self):
        """This returns a class which doesn't inherient from fitter """
        with warnings.catch_warnings():
            warnings.filterwarnings('error')
            try:
                mock_entry_badclass = mock.create_autospec(EntryPoint)
                mock_entry_badclass.name = "BadClass"
                mock_entry_badclass.load = self.returnbadclass
                populate_entry_points([mock_entry_badclass])
            except AstropyUserWarning as w:
                if 'modeling.Fitter' in w.args[0]:  # any error for this case should have this in it.
                    pass
                else:
                    raise w
            else:
                raise self.exception_not_thrown

@pytest.mark.skipif('not HAS_SCIPY')
class Test1DFittingWithOutlierRemoval:
    def setup_class(self):
        self.x = np.linspace(-5., 5., 200)
        self.model_params = (3.0, 1.3, 0.8)

        def func(p, x):
            return p[0]*np.exp(-0.5*(x - p[1])**2/p[2]**2)

        self.y = func(self.model_params, self.x)

    def test_with_fitters_and_sigma_clip(self):
        import scipy.stats as stats

        np.random.seed(0)
        c = stats.bernoulli.rvs(0.25, size=self.x.shape)
        self.y += (np.random.normal(0., 0.2, self.x.shape) +
                   c*np.random.normal(3.0, 5.0, self.x.shape))

        g_init = models.Gaussian1D(amplitude=1., mean=0, stddev=1.)
        # test with Levenberg-Marquardt Least Squares fitter
        fit = FittingWithOutlierRemoval(LevMarLSQFitter(), sigma_clip,
                                        niter=3, sigma=3.0)
        _, fitted_model = fit(g_init, self.x, self.y)
        assert_allclose(fitted_model.parameters, self.model_params, rtol=1e-1)
        # test with Sequential Least Squares Programming fitter
        fit = FittingWithOutlierRemoval(SLSQPLSQFitter(), sigma_clip,
                                        niter=3, sigma=3.0)
        _, fitted_model = fit(g_init, self.x, self.y)
        assert_allclose(fitted_model.parameters, self.model_params, rtol=1e-1)
        # test with Simplex LSQ fitter
        fit = FittingWithOutlierRemoval(SimplexLSQFitter(), sigma_clip,
                                        niter=3, sigma=3.0)
        _, fitted_model = fit(g_init, self.x, self.y)
        assert_allclose(fitted_model.parameters, self.model_params, atol=1e-1)

@pytest.mark.skipif('not HAS_SCIPY')
class Test2DFittingWithOutlierRemoval:
    def setup_class(self):
        self.y, self.x = np.mgrid[-3:3:128j, -3:3:128j]
        self.model_params = (3.0, 1.0, 0.0, 0.8, 0.8)

        def Gaussian_2D(p, pos):
            return p[0]*np.exp(-0.5*(pos[0] - p[2])**2 / p[4]**2 -
                               0.5*(pos[1] - p[1])**2 / p[3]**2)

        self.z = Gaussian_2D(self.model_params, np.array([self.y, self.x]))

    def initial_guess(self, data, pos):
        y = pos[0]
        x = pos[1]

        """computes the centroid of the data as the initial guess for the
        center position"""

        wx = x * data
        wy = y * data
        total_intensity = np.sum(data)
        x_mean = np.sum(wx) / total_intensity
        y_mean = np.sum(wy) / total_intensity

        x_to_pixel = x[0].size / (x[x[0].size - 1][x[0].size - 1] - x[0][0])
        y_to_pixel = y[0].size / (y[y[0].size - 1][y[0].size - 1] - y[0][0])
        x_pos = np.around(x_mean * x_to_pixel + x[0].size / 2.).astype(int)
        y_pos = np.around(y_mean * y_to_pixel + y[0].size / 2.).astype(int)

        amplitude = data[y_pos][x_pos]

        return amplitude, x_mean, y_mean

    def test_with_fitters_and_sigma_clip(self):
        import scipy.stats as stats

        np.random.seed(0)
        c = stats.bernoulli.rvs(0.25, size=self.z.shape)
        self.z += (np.random.normal(0., 0.2, self.z.shape) +
                   c*np.random.normal(self.z, 2.0, self.z.shape))

        guess = self.initial_guess(self.z, np.array([self.y, self.x]))
        g2_init = models.Gaussian2D(amplitude=guess[0], x_mean=guess[1],
                                    y_mean=guess[2], x_stddev=0.75,
                                    y_stddev=1.25)

        # test with Levenberg-Marquardt Least Squares fitter
        fit = FittingWithOutlierRemoval(LevMarLSQFitter(), sigma_clip,
                                        niter=3, sigma=3.)
        _, fitted_model = fit(g2_init, self.x, self.y, self.z)
        assert_allclose(fitted_model.parameters[0:5], self.model_params,
                        atol=1e-1)
        # test with Sequential Least Squares Programming fitter
        fit = FittingWithOutlierRemoval(SLSQPLSQFitter(), sigma_clip, niter=3,
                                        sigma=3.)
        _, fitted_model = fit(g2_init, self.x, self.y, self.z)
        assert_allclose(fitted_model.parameters[0:5], self.model_params,
                        atol=1e-1)
        # test with Simplex LSQ fitter
        fit = FittingWithOutlierRemoval(SimplexLSQFitter(), sigma_clip,
                                        niter=3, sigma=3.)
        _, fitted_model = fit(g2_init, self.x, self.y, self.z)
        assert_allclose(fitted_model.parameters[0:5], self.model_params,
                        atol=1e-1)

@pytest.mark.skipif('not HAS_SCIPY')
def test_fitters_with_weights():
    """Issue #5737 """
    Xin, Yin = np.mgrid[0:21, 0:21]
    fitter = LevMarLSQFitter()

    with NumpyRNGContext(_RANDOM_SEED):
        zsig = np.random.normal(0, 0.01, size=Xin.shape)

    # Non-linear model
    g2 = models.Gaussian2D(10, 10, 9, 2, 3)
    z = g2(Xin, Yin)
    gmod = fitter(models.Gaussian2D(15, 7, 8, 1.3, 1.2), Xin, Yin, z + zsig)
    assert_allclose(gmod.parameters, g2.parameters, atol=10 ** (-2))

    # Linear model
    p2 = models.Polynomial2D(3)
    p2.parameters = np.arange(10)/1.2
    z = p2(Xin, Yin)
    pmod = fitter(models.Polynomial2D(3), Xin, Yin, z + zsig)
    assert_allclose(pmod.parameters, p2.parameters, atol=10 ** (-2))

@pytest.mark.skipif('not HAS_SCIPY')
def test_fitters_interface():
    """
    Test that **kwargs work with all optimizers.
    This is a basic smoke test.
    """
    levmar = LevMarLSQFitter()
    slsqp = SLSQPLSQFitter()
    simplex = SimplexLSQFitter()

    kwargs = {'maxiter': 77, 'verblevel': 1, 'epsilon': 1e-2, 'acc': 1e-6}
    simplex_kwargs = {'maxiter': 77, 'verblevel': 1, 'acc': 1e-6}
    model = models.Gaussian1D(10, 4, .3)
    x = np.arange(21)
    y = model(x)

    slsqp_model = slsqp(model, x, y, **kwargs)
    simplex_model = simplex(model, x, y, **simplex_kwargs)
    kwargs.pop('verblevel')
    lm_model = levmar(model, x, y, **kwargs)


text:
<!DOCTYPE html>

<title>Shadow DOM Test: Distribution: Ordered list</title>
<link rel="match" href="distribution-002-ref.html">
<link rel="author" title="Sergey G. Grekhov" href="mailto:sgrekhov@unipro.ru">
<link rel="author" title="Yuta Kitamura" href="mailto:yutak@google.com">
<link rel="help" href="http://www.w3.org/TR/2013/WD-shadow-dom-20130514/#shadow-trees">
<meta name="assert" content="Lower-boundary Encapsulation: Each insertion point participates in distribution by providing a matching criteria for the child nodes. The matching criteria determines whether a given node could be distributed to a given insertion point.">

You should see an ordered list below, consisting of ten elements numbered
from 1 through 10, and each line should contain a capital letter ranging from
"A" to "J", in alphabetical order.

H

B

E

I

C


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

import javax.annotation.Generated;

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

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

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

    private static final MarshallingInfo<String> MINVALUE_BINDING = MarshallingInfo.builder(MarshallingType.STRING).marshallLocation(MarshallLocation.PAYLOAD)
            .marshallLocationName("MinValue").build();
    private static final MarshallingInfo<String> MAXVALUE_BINDING = MarshallingInfo.builder(MarshallingType.STRING).marshallLocation(MarshallLocation.PAYLOAD)
            .marshallLocationName("MaxValue").build();

    private static final ContinuousParameterRangeSpecificationMarshaller instance = new ContinuousParameterRangeSpecificationMarshaller();

    public static ContinuousParameterRangeSpecificationMarshaller getInstance() {
        return instance;
    }

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

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

        try {
            protocolMarshaller.marshall(continuousParameterRangeSpecification.getMinValue(), MINVALUE_BINDING);
            protocolMarshaller.marshall(continuousParameterRangeSpecification.getMaxValue(), MAXVALUE_BINDING);
        } catch (Exception e) {
            throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
        }
    }

}


text:
set -uxe

# note: this can be easily done in a 1-liner, however circle CI does NOT allow volume mounts from the host in docker executors (since they are on remote hosts, where the host files are inaccessible)

PKGSDIR=$1
CTRID=$(docker create -u "$(id -u):$(id -g)" -v /example-java-app -w /example-java-app gradle:6.8.3-jdk gradle build)

function cleanup() {
  docker rm "${CTRID}"
}

trap cleanup EXIT
set +e

docker cp "$(pwd)/example-java-app" "${CTRID}:/"
docker start -a "${CTRID}"
mkdir -p "$PKGSDIR"
docker cp "${CTRID}:/example-java-app/build/libs/example-java-app-gradle-0.1.0.jar" "$PKGSDIR"


text:
package com.tngtech.configbuilder.annotation.typetransformer;

import java.nio.file.Path;
import java.nio.file.Paths;

public class StringToPathTransformer extends TypeTransformer<String, Path> {
    @Override
    public Path transform(String argument) {
        return Paths.get(argument);
    }
}


text:
require 'marta/options_and_paths'
require 'marta/element_information'
module Marta

  # Marta has very simple read\write actions
  module ReadWrite

    include ElementInformation

    private

    #
    # Sometimes marta reads files. Sometimes writes
    #
    # @note It is believed that no user will use it
    class ReaderWriter
      include OptionsAndPaths, ElementInformation
      # Marta is writing to jsons from time to time
      def self.file_write(name, data)
        file_name = File.join(SettingMaster.pageobjects_folder, name + '.json')
        File.open(file_name,"w") do |f|
          f.write(JSON.pretty_generate(data))
        end
        file_name
      end

      # Marta reads file to hash if it is a valid json
      # If it is not a json file Marta will treat it like nothing
      def self.file_2_hash(json)
        begin
          file = File.read(json)
          data = JSON.parse(file)
          # If there are methods
          if data['meths'] != {}
            # If there are old methods
            if !data['meths'].first[1]['options']['self'].nil? or !data['meths'].first[1]['options']['not_self'].nil?
              data = treat_old_version(data)
              File.open(json,"w") do |f|
                f.write(JSON.pretty_generate(data))
              end
            end
          end
          return data
        rescue
          nil
        end
      end

      def self.treat_old_version(data)
        result, result['meths'] = Hash.new, Hash.new
        result['vars'] = data['vars']
        # Taking all methods one by one
        data['meths'].each_pair do |method, method_content|
          result['meths'][method] = ElementHelper.method_structure
          result['meths'][method]['options']['collection'] = method_content['options'].to_h['collection']
          ['self','pappy','granny'].each do |level|
            if !method_content['options'].to_h[level].nil?
              result['meths'][method]['positive'][level]['tag'] = [method_content['options'][level]] - ['*']
            end
            if !method_content[level].to_h['retrieved_by_marta_text'].nil?
              result['meths'][method]['positive'][level]['text'] = [method_content[level]['retrieved_by_marta_text']]
            end
            method_content[level].to_h.each_pair do |name, value|
              if name != "retrieved_by_marta_text"
                result['meths'][method]['positive'][level]['attributes'][name] = value.class == String ? value.split(' ').uniq : value
              end
            end
            if !method_content['options'].to_h["not_#{level}"].nil?
              result['meths'][method]['negative'][level]['tag'] = [method_content['options']["not_#{level}"]] - ['*']
            end
            if !method_content["not_#{level}"].to_h['retrieved_by_marta_text'].nil?
              result['meths'][method]['negative'][level]['text'] = [method_content["not_#{level}"]['retrieved_by_marta_text']]
            end
            method_content["not_#{level}"].to_h.each_pair do |name, value|
              if name != "retrieved_by_marta_text"
                result['meths'][method]['negative'][level]['attributes'][name] = value.class == String ? value.split(' ').uniq : value
              end
            end
          end
        end
        result
      end
    end

    def file_write(name, data)
      ReaderWriter.file_write(name, data)
    end

    def file_2_hash(json)
      ReaderWriter.file_2_hash(json)
    end
  end
end


text:
import Fixture from "./helpers/Fixture"
import {web3, ethers} from "hardhat"

import chai, {expect, assert} from "chai"
import {solidity} from "ethereum-waffle"
chai.use(solidity)

describe("ServiceRegistry", () => {
    let fixture
    let registry
    let signers
    let controller
    before(async () => {
        signers = await ethers.getSigners()
        fixture = new Fixture(web3)
        // Use dummy Controller in these unit tests
        // We are testing the logic of ServiceRegistry directly so we do not
        // interact with the contract via a proxy
        // Thus, we do not need an actual Controller for the tests
        controller = signers[0].address

        registry = await (
            await ethers.getContractFactory("ServiceRegistry")
        ).deploy(controller)
    })

    beforeEach(async () => {
        await fixture.setUp()
    })

    afterEach(async () => {
        await fixture.tearDown()
    })

    describe("constructor", () => {
        it("invokes base Manager contract constructor", async () => {
            assert.equal(
                await registry.controller(),
                controller,
                "wrong Controller address"
            )
        })
    })

    describe("setServiceURI", () => {
        it("stores service URI endpoint for caller", async () => {
            await registry.setServiceURI("foo")
            await registry.connect(signers[1]).setServiceURI("bar")

            assert.equal(
                await registry.getServiceURI(signers[0].address),
                "foo",
                "wrong service URI stored for caller 1"
            )
            assert.equal(
                await registry.getServiceURI(signers[1].address),
                "bar",
                "wrong service URI stored for caller 2"
            )
        })

        it("fires ServiceURIUpdate event", async () => {
            const tx = registry.setServiceURI("foo")
            await expect(tx)
                .to.emit(registry, "ServiceURIUpdate")
                .withArgs(signers[0].address, "foo")
        })
    })

    describe("getServiceURI", () => {
        it("returns service URI endpoint for provided address", async () => {
            await registry.setServiceURI("foo")
            await registry.connect(signers[1]).setServiceURI("bar")

            assert.equal(
                await registry.getServiceURI(signers[0].address),
                "foo",
                "wrong service URI stored for caller 1"
            )
            assert.equal(
                await registry.getServiceURI(signers[1].address),
                "bar",
                "wrong service URI stored for caller 2"
            )
        })

        it("returns empty string for address without stored service URI endpoint", async () => {
            assert.equal(
                await registry.getServiceURI(signers[5].address),
                "",
                "should return empty string for address without service URI"
            )
        })
    })
})


text:
#include <boost/container/detail/auto_link.hpp>
#include <boost/container/detail/alloc_lib.h>

#endif   //#ifndef BOOST_CONTAINER_DETAIL_BOOST_CONT_EXT_AUTO_LINK_HPP


text:
<?php

namespace App\Providers;

use Illuminate\Support\ServiceProvider;
use Illuminate\Database\Eloquent\Relations\Relation;
use Illuminate\Support\Facades\Validator;
use App\SkeletalElement;
use App\SkeletalBone;

class AppServiceProvider extends ServiceProvider
{
    /**
     * Bootstrap any application services.
     *
     * @return void
     */
    public function boot()
    {
//        Relation::morphMap([
//            //
//        ]);
//
//        Validator::extend('phone', function($attribute, $value, $parameters, $validator) {
//            return preg_match('%^(?:(?:\(?(?:00|\+)([1-4]\d\d|[1-9]\d?)\)?)?[\-\.\ \\\/]?)?((?:\(?\d{1,}\)?[\-\.\ \\\/]?){0,})(?:[\-\.\ \\\/]?(?:#|ext\.?|extension|x)[\-\.\ \\\/]?(\d+))?$%i', $value) && strlen($value) >= 10;
//        });
//        Validator::replacer('phone', function($message, $attribute, $rule, $parameters) {
//            return str_replace(':attribute',$attribute, ':attribute is invalid phone number. Enter without + symbol. Just the 11 digits');
//        });
    }

    /**
     * Register any application services.
     *
     * @return void
     */
    public function register()
    {
        //
    }
}


text:
class EvtTensor4C;
class EvtVector4C;
class EvtDiracSpinor ;

class EvtDiracSpinor {

  friend EvtDiracSpinor rotateEuler(const EvtDiracSpinor& sp,
				 double alpha,double beta,double gamma);
  friend EvtDiracSpinor boostTo(const EvtDiracSpinor& sp,
			     const EvtVector4R p4);
  friend EvtDiracSpinor boostTo(const EvtDiracSpinor& sp,
			     const EvtVector3R boost);
  friend EvtVector4C EvtLeptonVACurrent
	(const EvtDiracSpinor& d,const EvtDiracSpinor& dp);
  friend EvtVector4C EvtLeptonVCurrent
	(const EvtDiracSpinor& d,const EvtDiracSpinor& dp);
  friend EvtVector4C EvtLeptonACurrent
	(const EvtDiracSpinor& d,const EvtDiracSpinor& dp);
  friend EvtComplex  EvtLeptonSCurrent
	(const EvtDiracSpinor& d,const EvtDiracSpinor& dp);
  friend EvtComplex  EvtLeptonPCurrent
	(const EvtDiracSpinor& d,const EvtDiracSpinor& dp);
  friend EvtTensor4C  EvtLeptonTCurrent
	(const EvtDiracSpinor& d,const EvtDiracSpinor& dp);
  friend EvtDiracSpinor operator+(const EvtDiracSpinor& u1,
				  const EvtDiracSpinor& u2);
  friend EvtDiracSpinor operator-(const EvtDiracSpinor& u1,
				  const EvtDiracSpinor& u2);
  friend EvtDiracSpinor operator*(const EvtComplex& c,
				  const EvtDiracSpinor& d);

  friend EvtComplex operator*(const EvtDiracSpinor& d ,
                              const EvtDiracSpinor& dp ) ;

  friend std::ostream& operator<<(std::ostream& s, const EvtDiracSpinor& c);

public:

  inline EvtDiracSpinor();
  EvtDiracSpinor(const EvtComplex& sp0,const EvtComplex& sp1,
		 const EvtComplex& sp2,const EvtComplex& sp3);
  virtual ~EvtDiracSpinor();
  inline EvtDiracSpinor(const EvtDiracSpinor& dspinor);
  inline EvtDiracSpinor& operator=(const EvtDiracSpinor& dspinor);

  inline EvtDiracSpinor& operator+=(const EvtDiracSpinor& u2);
  inline EvtDiracSpinor& operator-=(const EvtDiracSpinor& u2);

  void set(const EvtComplex& sp0,const EvtComplex& sp1,
	   const EvtComplex& sp2,const EvtComplex& sp3);
  void set_spinor(int i,const EvtComplex& sp);
  const EvtComplex& get_spinor(int i) const;
  EvtDiracSpinor conj() const;
  void applyRotateEuler(double alpha,double beta,double gamma);
  void applyBoostTo(const EvtVector4R& p4);
  void applyBoostTo(const EvtVector3R& boost);
  EvtDiracSpinor adjoint() const;

private:

  EvtComplex spinor[4];

};

EvtDiracSpinor::EvtDiracSpinor(){

  spinor[0]=EvtComplex(); spinor[1]=EvtComplex();
  spinor[2]=EvtComplex(); spinor[3]=EvtComplex();

}

EvtDiracSpinor::EvtDiracSpinor(const EvtDiracSpinor& dspinor){

  spinor[0]=dspinor.spinor[0];
  spinor[1]=dspinor.spinor[1];
  spinor[2]=dspinor.spinor[2];
  spinor[3]=dspinor.spinor[3];

}

EvtDiracSpinor& EvtDiracSpinor::operator=(const EvtDiracSpinor& dspinor){

  spinor[0]=dspinor.spinor[0];
  spinor[1]=dspinor.spinor[1];
  spinor[2]=dspinor.spinor[2];
  spinor[3]=dspinor.spinor[3];

  return *this;

}

inline EvtDiracSpinor& EvtDiracSpinor::operator+=(const EvtDiracSpinor& u2){

  spinor[0]+=u2.spinor[0];
  spinor[1]+=u2.spinor[1];
  spinor[2]+=u2.spinor[2];
  spinor[3]+=u2.spinor[3];

  return *this;
}

inline EvtDiracSpinor operator+(const EvtDiracSpinor& u1,
				const EvtDiracSpinor& u2){

  return EvtDiracSpinor(u1)+=u2;

}

inline EvtDiracSpinor& EvtDiracSpinor::operator-=(const EvtDiracSpinor& u2){

  spinor[0]-=u2.spinor[0];
  spinor[1]-=u2.spinor[1];
  spinor[2]-=u2.spinor[2];
  spinor[3]-=u2.spinor[3];

  return *this;
}

inline EvtDiracSpinor operator-(const EvtDiracSpinor& u1,
				const EvtDiracSpinor& u2){

  return EvtDiracSpinor(u1)-=u2;

}

#endif


text:
<?php

return array(
    'router' => array(
        'routes' => array(
            'member' => array(
                'type' => 'segment',
                'options' => array(
                    'route'    => '/user[/:action][/:id]',
                	'constrains'=> array (
                				'action' => '[a-zA-Z][a-zA-Z0-9_-]*',
                				'id'=> '[0-9]+',
                				) ,
                    'defaults' => array(
                        'controller' => 'Member\Controller\Member',
                        'action'     => 'index',
                    ),
                ),
            ),
            // The following is a route to simplify getting started creating
            // new controllers and actions without needing to create a new
            // module. Simply drop new controllers in, and you can access them
            // using the path /application/:controller/:action
        ),
    ),

    'controllers' => array(
        'invokables' => array(
            'Member\Controller\Member' => 'Member\Controller\MemberController'
        ),
    ),
    'view_manager' => array(
        'display_not_found_reason' => true,
        'display_exceptions'       => true,
        'doctype'                  => 'HTML5',

        'template_path_stack' => array(
            __DIR__ . '/../view',
        ),
    ),
    'view_helpers' => array(
    		'invokables'=> array(
    				'test_helper' => 'Member\View\Helper\Testhelper',
    		)
    ),
    // Placeholder for console routes
    'console' => array(
        'router' => array(
            'routes' => array(
            ),
        ),
    ),
);


text:
<?php

namespace MwbExporter\Storage;

class FileStorage extends Storage
{
    public function initialize()
    {
        $this->result = $this->outDir;

        return $this;
    }

    public function save($filename, $content)
    {
        $filename = $this->getFile($filename);
        file_put_contents($filename, $content);

        return $this;
    }
}


text:
Cloud Speech-to-Text API . projects . locations . customClasses

Instance Methods

  close()

Close httplib2 connections.

  create(parent, body=None, x__xgafv=None)

Create a custom class.

  delete(name, x__xgafv=None)

Delete a custom class.

  get(name, x__xgafv=None)

Get a custom class.

  list(parent, pageSize=None, pageToken=None, x__xgafv=None)

List custom classes.

  list_next()

Retrieves the next page of results.

  patch(name, body=None, updateMask=None, x__xgafv=None)

Update a custom class.

Method Details

    close()

Close httplib2 connections.

    create(parent, body=None, x__xgafv=None)

Create a custom class.

Args:
  parent: string, Required. The parent resource where this custom class will be created. Format: `projects/{project}/locations/{location}/customClasses` Speech-to-Text supports three locations: `global`, `us` (US North America), and `eu` (Europe). If you are calling the `speech.googleapis.com` endpoint, use the `global` location. To specify a region, use a [regional endpoint](https://cloud.google.com/speech-to-text/docs/endpoints) with matching `us` or `eu` location value. (required)
  body: object, The request body.
    The object takes the form of:

{ # Message sent by the client for the `CreateCustomClass` method.
  "customClass": { # A set of words or phrases that represents a common concept likely to appear in your audio, for example a list of passenger ship names. CustomClass items can be substituted into placeholders that you set in PhraseSet phrases. # Required. The custom class to create.
    "customClassId": "A String", # If this custom class is a resource, the custom_class_id is the resource id of the CustomClass. Case sensitive.
    "items": [ # A collection of class items.
      { # An item of the class.
        "value": "A String", # The class item's value.
      },
    ],
    "name": "A String", # The resource name of the custom class.
  },
  "customClassId": "A String", # Required. The ID to use for the custom class, which will become the final component of the custom class' resource name. This value should restrict to letters, numbers, and hyphens, with the first character a letter, the last a letter or a number, and be 4-63 characters.
}

  x__xgafv: string, V1 error format.
    Allowed values
      1 - v1 error format
      2 - v2 error format

Returns:
  An object of the form:

    { # A set of words or phrases that represents a common concept likely to appear in your audio, for example a list of passenger ship names. CustomClass items can be substituted into placeholders that you set in PhraseSet phrases.
  "customClassId": "A String", # If this custom class is a resource, the custom_class_id is the resource id of the CustomClass. Case sensitive.
  "items": [ # A collection of class items.
    { # An item of the class.
      "value": "A String", # The class item's value.
    },
  ],
  "name": "A String", # The resource name of the custom class.
}

    delete(name, x__xgafv=None)

Delete a custom class.

Args:
  name: string, Required. The name of the custom class to delete. Format: `projects/{project}/locations/{location}/customClasses/{custom_class}` Speech-to-Text supports three locations: `global`, `us` (US North America), and `eu` (Europe). If you are calling the `speech.googleapis.com` endpoint, use the `global` location. To specify a region, use a [regional endpoint](https://cloud.google.com/speech-to-text/docs/endpoints) with matching `us` or `eu` location value. (required)
  x__xgafv: string, V1 error format.
    Allowed values
      1 - v1 error format
      2 - v2 error format

Returns:
  An object of the form:

    { # A generic empty message that you can re-use to avoid defining duplicated empty messages in your APIs. A typical example is to use it as the request or the response type of an API method. For instance: service Foo { rpc Bar(google.protobuf.Empty) returns (google.protobuf.Empty); }
}

    get(name, x__xgafv=None)

Get a custom class.

Args:
  name: string, Required. The name of the custom class to retrieve. Format: `projects/{project}/locations/{location}/customClasses/{custom_class}` (required)
  x__xgafv: string, V1 error format.
    Allowed values
      1 - v1 error format
      2 - v2 error format

Returns:
  An object of the form:

    { # A set of words or phrases that represents a common concept likely to appear in your audio, for example a list of passenger ship names. CustomClass items can be substituted into placeholders that you set in PhraseSet phrases.
  "customClassId": "A String", # If this custom class is a resource, the custom_class_id is the resource id of the CustomClass. Case sensitive.
  "items": [ # A collection of class items.
    { # An item of the class.
      "value": "A String", # The class item's value.
    },
  ],
  "name": "A String", # The resource name of the custom class.
}

    list(parent, pageSize=None, pageToken=None, x__xgafv=None)

List custom classes.

Args:
  parent: string, Required. The parent, which owns this collection of custom classes. Format: `projects/{project}/locations/{location}/customClasses` Speech-to-Text supports three locations: `global`, `us` (US North America), and `eu` (Europe). If you are calling the `speech.googleapis.com` endpoint, use the `global` location. To specify a region, use a [regional endpoint](https://cloud.google.com/speech-to-text/docs/endpoints) with matching `us` or `eu` location value. (required)
  pageSize: integer, The maximum number of custom classes to return. The service may return fewer than this value. If unspecified, at most 50 custom classes will be returned. The maximum value is 1000; values above 1000 will be coerced to 1000.
  pageToken: string, A page token, received from a previous `ListCustomClass` call. Provide this to retrieve the subsequent page. When paginating, all other parameters provided to `ListCustomClass` must match the call that provided the page token.
  x__xgafv: string, V1 error format.
    Allowed values
      1 - v1 error format
      2 - v2 error format

Returns:
  An object of the form:

    { # Message returned to the client by the `ListCustomClasses` method.
  "customClasses": [ # The custom classes.
    { # A set of words or phrases that represents a common concept likely to appear in your audio, for example a list of passenger ship names. CustomClass items can be substituted into placeholders that you set in PhraseSet phrases.
      "customClassId": "A String", # If this custom class is a resource, the custom_class_id is the resource id of the CustomClass. Case sensitive.
      "items": [ # A collection of class items.
        { # An item of the class.
          "value": "A String", # The class item's value.
        },
      ],
      "name": "A String", # The resource name of the custom class.
    },
  ],
  "nextPageToken": "A String", # A token, which can be sent as `page_token` to retrieve the next page. If this field is omitted, there are no subsequent pages.
}

    list_next()

Retrieves the next page of results.

        Args:
          previous_request: The request for the previous page. (required)
          previous_response: The response from the request for the previous page. (required)

        Returns:
          A request object that you can call 'execute()' on to request the next
          page. Returns None if there are no more items in the collection.

    patch(name, body=None, updateMask=None, x__xgafv=None)

Update a custom class.

Args:
  name: string, The resource name of the custom class. (required)
  body: object, The request body.
    The object takes the form of:

{ # A set of words or phrases that represents a common concept likely to appear in your audio, for example a list of passenger ship names. CustomClass items can be substituted into placeholders that you set in PhraseSet phrases.
  "customClassId": "A String", # If this custom class is a resource, the custom_class_id is the resource id of the CustomClass. Case sensitive.
  "items": [ # A collection of class items.
    { # An item of the class.
      "value": "A String", # The class item's value.
    },
  ],
  "name": "A String", # The resource name of the custom class.
}

  updateMask: string, The list of fields to be updated.
  x__xgafv: string, V1 error format.
    Allowed values
      1 - v1 error format
      2 - v2 error format

Returns:
  An object of the form:

    { # A set of words or phrases that represents a common concept likely to appear in your audio, for example a list of passenger ship names. CustomClass items can be substituted into placeholders that you set in PhraseSet phrases.
  "customClassId": "A String", # If this custom class is a resource, the custom_class_id is the resource id of the CustomClass. Case sensitive.
  "items": [ # A collection of class items.
    { # An item of the class.
      "value": "A String", # The class item's value.
    },
  ],
  "name": "A String", # The resource name of the custom class.
}


text:
package org.diirt.graphene;

import org.diirt.util.stats.Range;
import org.diirt.util.stats.Ranges;
import org.junit.Test;
import static org.junit.Assert.*;
import static org.hamcrest.Matchers.*;

/**
 *
 * @author carcassi
 */
public class AxisRangesTest {

    public AxisRangesTest() {
    }

    @Test
    public void fixed1() {
        AxisRange axisRange = AxisRanges.fixed(0.0, 10.0);
        assertThat(axisRange.toString(), equalTo("fixed(0.0, 10.0)"));
        AxisRangeInstance axisRangeInstance = axisRange.createInstance();
        Range range = axisRangeInstance.axisRange(Ranges.range(3.0, 15.0), Ranges.range(-3.0, 4.0));
        assertThat(range.getMinimum(), equalTo((Number) 0.0));
        assertThat(range.getMaximum(), equalTo((Number) 10.0));
    }

    @Test(expected=IllegalArgumentException.class)
    public void fixed2() {
        AxisRange axisRange = AxisRanges.fixed(10.0, 0.0);
    }

    @Test
    public void relative1() {
        AxisRange axisRange = AxisRanges.data();
        assertThat(axisRange.toString(), equalTo("data"));
        AxisRangeInstance axisRangeInstance = axisRange.createInstance();
        Range range = axisRangeInstance.axisRange(Ranges.range(3.0, 15.0), Ranges.range(-3.0, 4.0));
        assertThat(range.getMinimum(), equalTo((Number) 3.0));
        assertThat(range.getMaximum(), equalTo((Number) 15.0));

        range = axisRangeInstance.axisRange(Ranges.range(1.0, 5.0), Ranges.range(-3.0, 4.0));
        assertThat(range.getMinimum(), equalTo((Number) 1.0));
        assertThat(range.getMaximum(), equalTo((Number) 5.0));
    }

    @Test
    public void auto1() {
        AxisRange axisRange = AxisRanges.auto();
        assertThat(axisRange.toString(), equalTo("auto(80%)"));
        AxisRangeInstance axisRangeInstance = axisRange.createInstance();
        Range range = axisRangeInstance.axisRange(Ranges.range(3.0, 5.0), Ranges.range(-3.0, 4.0));
        assertThat(range.getMinimum(), equalTo((Number) 3.0));
        assertThat(range.getMaximum(), equalTo((Number) 5.0));

        range = axisRangeInstance.axisRange(Ranges.range(4.0, 15.0), Ranges.range(-3.0, 4.0));
        assertThat(range.getMinimum(), equalTo((Number) 3.0));
        assertThat(range.getMaximum(), equalTo((Number) 15.0));
    }

    @Test
    public void auto2() {
        AxisRange axisRange = AxisRanges.auto();
        assertThat(axisRange.toString(), equalTo("auto(80%)"));
        AxisRangeInstance axisRangeInstance = axisRange.createInstance();
        Range range = axisRangeInstance.axisRange(Ranges.range(3.0, 5.0), Ranges.range(-3.0, 4.0));
        assertThat(range.getMinimum(), equalTo((Number) 3.0));
        assertThat(range.getMaximum(), equalTo((Number) 5.0));

        range = axisRangeInstance.axisRange(Ranges.range(1000000.0, 1000015.0), Ranges.range(-3.0, 4.0));
        assertThat(range.getMinimum(), equalTo((Number) 1000000.0));
        assertThat(range.getMaximum(), equalTo((Number) 1000015.0));
    }

    @Test
    public void display1() {
        AxisRange axisRange = AxisRanges.display();
        assertThat(axisRange.toString(), equalTo("display"));
        AxisRangeInstance axisRangeInstance = axisRange.createInstance();
        Range range = axisRangeInstance.axisRange(Ranges.range(3.0, 15.0), Ranges.range(-3.0, 4.0));
        assertThat(range.getMinimum(), equalTo((Number) (-3.0)));
        assertThat(range.getMaximum(), equalTo((Number) 4.0));
    }

    @Test
    public void display2() {
        AxisRangeInstance axisRangeInstance = AxisRanges.display().createInstance();
        Range range = axisRangeInstance.axisRange(Ranges.range(3.0, 15.0), Ranges.range(0.0, 0.0));
        assertThat(range.getMinimum(), equalTo((Number) 3.0));
        assertThat(range.getMaximum(), equalTo((Number) 15.0));
    }

    @Test
    public void fixedEquals() {
        assertThat(AxisRanges.fixed(0, 1), equalTo(AxisRanges.fixed(0, 1)));
        assertThat(AxisRanges.fixed(0, 1), not(equalTo(AxisRanges.fixed(0, 5))));
    }

    @Test
    public void displayEquals() {
        assertThat(AxisRanges.display(), equalTo(AxisRanges.display()));
    }

    @Test
    public void dataEquals() {
        assertThat(AxisRanges.data(), equalTo(AxisRanges.data()));
    }

    @Test
    public void autoEquals() {
        assertThat(AxisRanges.auto(), equalTo(AxisRanges.auto()));
        assertThat(AxisRanges.auto(0.5), equalTo(AxisRanges.auto(0.5)));
        assertThat(AxisRanges.auto(0.5), not(equalTo(AxisRanges.auto(0.8))));
    }
}


text:
#include "mocap_optitrack/mocap_config.h"

#include <XmlRpcValue.h>

namespace mocap_optitrack
{

namespace impl
{
  template<typename T>
  bool check_and_get_param(
    XmlRpc::XmlRpcValue& config_node,
    std::string const& key,
    T& value)
  {
    return false;
  }

  template<>
  bool check_and_get_param<std::string>(
    XmlRpc::XmlRpcValue& config_node,
    std::string const& key,
    std::string& value)
  {
    if (config_node[key].getType() == XmlRpc::XmlRpcValue::TypeString)
    {
      value = (std::string&)config_node[key];
      return true;
    }

    return false;
  }
} // namespace impl

// Server description defaults
const int ServerDescription::Default::CommandPort = 1510;
const int ServerDescription::Default::DataPort   = 9000;
const std::string ServerDescription::Default::MulticastIpAddress = "224.0.0.1";

// Param keys
namespace rosparam
{
  namespace keys
  {
    const std::string MulticastIpAddress = "optitrack_config/multicast_address";
    const std::string CommandPort = "optitrack_config/command_port";
    const std::string DataPort = "optitrack_config/data_port";
    const std::string RigidBodies = "rigid_bodies";
    const std::string PoseTopicName = "pose";
    const std::string Pose2dTopicName = "pose2d";
    const std::string ChildFrameId = "child_frame_id";
    const std::string ParentFrameId = "parent_frame_id";
  }
}

ServerDescription::ServerDescription() :
  commandPort(ServerDescription::Default::CommandPort),
  dataPort(ServerDescription::Default::DataPort),
  multicastIpAddress(ServerDescription::Default::MulticastIpAddress)
{}

void NodeConfiguration::fromRosParam(
  ros::NodeHandle& nh,
  ServerDescription& serverDescription,
  PublisherConfigurations& pubConfigs)
{
  // Get server cconfiguration from ROS parameter server
  if (nh.hasParam(rosparam::keys::MulticastIpAddress) )
  {
    nh.getParam(rosparam::keys::MulticastIpAddress, serverDescription.multicastIpAddress);
  }
  else
  {
    ROS_WARN_STREAM("Could not get multicast address, using default: " <<
      serverDescription.multicastIpAddress);
  }

  if (nh.hasParam(rosparam::keys::CommandPort) )
  {
    nh.getParam(rosparam::keys::CommandPort, serverDescription.commandPort);
  }
  else
  {
    ROS_WARN_STREAM("Could not get command port, using default: " <<
      serverDescription.commandPort);
  }

  if (nh.hasParam(rosparam::keys::DataPort) )
  {
    nh.getParam(rosparam::keys::DataPort, serverDescription.dataPort);
  }
  else
  {
    ROS_WARN_STREAM("Could not get data port, using default: " <<
      serverDescription.dataPort);
  }

  // Parse rigid bodies section
  if (nh.hasParam(rosparam::keys::RigidBodies))
  {
    XmlRpc::XmlRpcValue bodyList;
    nh.getParam(rosparam::keys::RigidBodies, bodyList);

    if (bodyList.getType() == XmlRpc::XmlRpcValue::TypeStruct && bodyList.size() > 0)
    {
      XmlRpc::XmlRpcValue::iterator iter;
      //for (iter = bodyList.begin(); iter != bodyList.end(); ++iter) {
      for (auto const& iter : bodyList)
      {
        std::string strBodyId = iter.first;
        XmlRpc::XmlRpcValue bodyParameters = iter.second;

        if (bodyParameters.getType() == XmlRpc::XmlRpcValue::TypeStruct)
        {
          // Load configuration for this rigid body from ROS
          PublisherConfiguration publisherConfig;
          std::sscanf(strBodyId.c_str(), "%d", &publisherConfig.rigidBodyId);

          bool readPoseTopicName = impl::check_and_get_param(bodyParameters,
            rosparam::keys::PoseTopicName, publisherConfig.poseTopicName);

          if (!readPoseTopicName)
          {
            ROS_WARN_STREAM("Failed to parse " << rosparam::keys::PoseTopicName <<
              " for body `" << publisherConfig.rigidBodyId << "`. Pose publishing disabled.");
            publisherConfig.publishPose = false;
          }
          else
          {
            publisherConfig.publishPose = true;
          }

          bool readPose2dTopicName = impl::check_and_get_param(bodyParameters,
            rosparam::keys::Pose2dTopicName, publisherConfig.pose2dTopicName);

          if (!readPose2dTopicName)
          {
            ROS_WARN_STREAM("Failed to parse " << rosparam::keys::Pose2dTopicName <<
              " for body `" << publisherConfig.rigidBodyId << "`. Pose publishing disabled.");
            publisherConfig.publishPose2d = false;
          }
          else
          {
            publisherConfig.publishPose2d = true;
          }

          bool readChildFrameId = impl::check_and_get_param(bodyParameters,
            rosparam::keys::ChildFrameId, publisherConfig.childFrameId);

          bool readParentFrameId = impl::check_and_get_param(bodyParameters,
            rosparam::keys::ParentFrameId, publisherConfig.parentFrameId);

          if (!readChildFrameId || !readParentFrameId)
          {
            if (!readChildFrameId)
              ROS_WARN_STREAM("Failed to parse " << rosparam::keys::ChildFrameId <<
                " for body `" << publisherConfig.rigidBodyId << "`. TF publishing disabled.");

            if (!readParentFrameId)
              ROS_WARN_STREAM("Failed to parse " << rosparam::keys::ParentFrameId <<
                " for body `" << publisherConfig.rigidBodyId << "`. TF publishing disabled.");

            publisherConfig.publishTf = false;
          }
          else
          {
            publisherConfig.publishTf = true;
          }

          pubConfigs.push_back(publisherConfig);
        }
      }
    }
  }
}

}


text:
//
//  BFStaticCategoriesTableViewCellExtension.h
//  OpenShop
//
//  Created by Jirka Apps
//  Copyright (c) 2015 Business Factory. All rights reserved.
//

#import "BFBaseTableViewCellExtension.h"

NS_ASSUME_NONNULL_BEGIN

/**
 * `BFStaticCategoriesTableViewCellExtension` manages products static categories displaying in a table view.
 */
@interface BFStaticCategoriesTableViewCellExtension : BFBaseTableViewCellExtension

@end

NS_ASSUME_NONNULL_END


text:
package jokrey.utilities.network.mcnp.io;

import jokrey.utilities.network.mcnp.io.ConnectionHandler.ConnectionState;
import jokrey.utilities.network.mcnp.MCNP_Server;

import java.io.EOFException;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.atomic.AtomicInteger;

/**
 *
 * @author jokrey
 */
public class MCNP_ServerIO<CT extends ConnectionState> extends MCNP_Server<CT> implements AutoCloseable {
    private ServerSocket serverSocket;

    public MCNP_ServerIO(int port) {
        super(port);
    }
    public MCNP_ServerIO(int port, ConnectionHandler<CT> connectionHandler) {
        super(port, connectionHandler);
    }
    /**Should not be used, too few max_threads may cause max_number_of_concurrent_connections with blocking io*/
    public MCNP_ServerIO(int port, int min_threads, int max_threads) {
        super(port, min_threads, max_threads);
    }
    /**Should not be used, too few max_threads may cause max_number_of_concurrent_connections with blocking io*/
    public MCNP_ServerIO(int port, int min_threads, int max_threads, ConnectionHandler<CT> connectionHandler) {
        super(port, min_threads, max_threads, connectionHandler);
    }

    @Override public void close() throws IOException {
        stop();
        serverSocket.close();
    }
    @Override public boolean isProperlyClosed() {
        return !isRunning() && serverSocket.isClosed();
    }

    public void setConnectionHandler(ConnectionHandler<CT> connectionHandler) {
        this.connectionHandler = connectionHandler;
    }

    public void runListenerLoop() throws IOException {
        if(connectionHandler == null) throw new IllegalStateException("No c handler set.");

        serverSocket = new ServerSocket(port);

        System.out.println("SERVER READY");
        System.out.println("port: "+port);
        System.out.println("serverSocket.getLocalPort: "+serverSocket.getLocalPort());

        try {
            AtomicInteger number = new AtomicInteger(0);
            while (isRunning() && !serverSocket.isClosed()) {
                Socket newConnection = serverSocket.accept();

                Runnable r = () -> {
                    int numberOfSimultaneousConnections = number.getAndIncrement();
                    System.out.println("bef: "+numberOfSimultaneousConnections);
                    MCNP_ConnectionIO conn = null;
                    try {
                        conn = new MCNP_ConnectionIO(newConnection);
                        int initial_cause = conn.receive_cause();
                        CT state = connectionHandler.newConnection(initial_cause, conn);
                        while (!conn.isClosed()) {
                            int cause = conn.receive_cause();
                            state = connectionHandler.handleInteraction(new ConnectionHandler.TypedCause(initial_cause, cause), conn, state);
                        }
                    } catch (EOFException e) {
                        System.err.println("EOF from c(" + conn + "): " + e.getMessage());
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    number.getAndDecrement();
                    System.out.println("aft: "+numberOfSimultaneousConnections);
                };
                new Thread(r).start();
//                pool.execute(r);  //this - weirdly - does not work(even with
            }
            System.out.println("server socket closing");

        } catch (IOException e) {
            if(isRunning()) throw e;
        } finally {
            if(!isProperlyClosed())
                close();
        }
    }
}


text: La bruja les ofreció su ayuda para derrotar al ejército invasor a cambio del primer hijo del rey.


text:
<?php
/* Sales Test cases generated on: 2012-03-12 19:32:12 : 1331580732*/
App::uses('SalesController', 'Controller');

/**
 * TestSalesController *
 */
class TestSalesController extends SalesController {
/**
 * Auto render
 *
 * @var boolean
 */
	public $autoRender = false;

/**
 * Redirect action
 *
 * @param mixed $url
 * @param mixed $status
 * @param boolean $exit
 * @return void
 */
	public function redirect($url, $status = null, $exit = true) {
		$this->redirectUrl = $url;
	}
}

/**
 * SalesController Test Case
 *
 */
class SalesControllerTestCase extends CakeTestCase {
/**
 * Fixtures
 *
 * @var array
 */
	public $fixtures = array('app.sale');

/**
 * setUp method
 *
 * @return void
 */
	public function setUp() {
		parent::setUp();

		$this->Sales = new TestSalesController();
		$this->Sales->constructClasses();
	}

/**
 * tearDown method
 *
 * @return void
 */
	public function tearDown() {
		unset($this->Sales);

		parent::tearDown();
	}

/**
 * testIndex method
 *
 * @return void
 */
	public function testIndex() {

	}

/**
 * testView method
 *
 * @return void
 */
	public function testView() {

	}

/**
 * testAdd method
 *
 * @return void
 */
	public function testAdd() {

	}

/**
 * testEdit method
 *
 * @return void
 */
	public function testEdit() {

	}

/**
 * testDelete method
 *
 * @return void
 */
	public function testDelete() {

	}

}


text:
from django.db import models
from django import template
from django.utils.timezone import now
from datetime import timedelta

class Message(models.Model):
    phone_number = models.CharField(max_length=16)
    message = models.TextField()
    created_at = models.DateTimeField(auto_now_add=True)

    def __str__(self):
        return "{}: {}".format(self.phone_number, self.message)

def log_message(phone_number, message):
    Message(phone_number=phone_number, message=message).save()
    return message

class SavedMessage(models.Model):
    phone_number = models.CharField(max_length=16)
    message = models.TextField()
    tag = models.CharField(max_length=16)

    def __str__(self):
        return "{}: {}".format(self.tag, self.message)

def save_tagged_message(tag, phone_number, message):
    SavedMessage(tag=tag, phone_number=phone_number, message=message).save()

def pop_message_tag(tag):
    message = SavedMessage.objects.filter(tag=tag).first()
    if message:
        message.delete()
    return message

class Config(models.Model):
    """ Persistant server state beyond cache resets. """
    key = models.CharField(max_length=16, unique=True)
    val = models.CharField(max_length=16)

    def __str__(self):
        return "{}: {}".format(self.key, self.val)

def config(key, val):
    """ Sets and unsets server variables

    Takes in key, val. If val is Falsey, delete key if it exists."""
    if not val:
        [c.delete() for c in Config.objects.filter(key=key) ]
        return
    try:
        config = Config.objects.get(key=key)
        config.val = val
        config.save()
    except Config.DoesNotExist:
        Config(key=key, val=val).save()

class Template(models.Model):
    name = models.CharField(max_length=16, unique=True)
    text = models.TextField()

    def __str__(self):
        return "{}: {}".format(self.name, self.text)

    def as_template(self):
        return template.Template(self.text)

class DelayedCommandManager(models.Manager):
    def create_from_delay(self, delay, command):
        """Delay is in minutes."""
        send_at = now().replace(microsecond=0) + timedelta(minutes=int(delay))
        return DelayedCommand.objects.create(send_at=send_at, command=command)

    def due_commands(self):
        return DelayedCommand.objects.filter(send_at__lte=now())

class DelayedCommand(models.Model):
    created_at = models.DateTimeField(auto_now_add=True)
    command = models.TextField()
    send_at = models.DateTimeField()
    objects = DelayedCommandManager()

    def __str__(self):
        return "{}: {}".format(self.send_at, self.command)

    def get_command(self):
        return self.command


text:
require 'net/http'
require 'json'

class Oohlalog::Counter
  def initialzie
  end

  def increment(code,counter=1)
    Thread.new do
      begin
        request = Net::HTTP::Post.new("/api/counter/increment?apiKey=#{Oohlalog.api_key}&incr=#{counter}",{'Content-Type' =>'application/json'})

        http_net = Net::HTTP.new(Oohlalog.host, Oohlalog.port)
        http_net.read_timeout = 5
        http_net.start {|http| http.request(request) }
      rescue
        # puts "Oohlalog Exception**:"
      end
    end
  end
end


text:
<?php

/**
 * @file
 * Contains \BartFeenstra\Doobie\Tests\Constraint\ConstraintTest.
 */

namespace BartFeenstra\Doobie\Tests\Constraint;
use BartFeenstra\Doobie\Constraint\Constraint;

/**
 * @coversDefaultClass \BartFeenstra\Doobie\Constraint\Constraint
 */
class ConstraintTest extends \PHPUnit_Framework_TestCase {

  /**
   * The constraint under test.
   *
   * @var \BartFeenstra\Doobie\Constraint\Constraint
   */
  protected $constraint;

  /**
   * The expected constraint value.
   *
   * @var string
   */
  protected $expectedValue;

  /**
   * The name of the file the constraint is defined in.
   *
   * @var string
   */
  protected $fileName;

  /**
   * The number of the line the constraint is defined on.
   *
   * @var string
   */
  protected $lineNumber;

  /**
   * The constraint type.
   *
   * @var string
   */
  protected $type;

  /**
   * {@inheritdoc}
   *
   * @covers ::__construct
   */
  public function setUp() {
    $this->expectedValue = 'foobarbaz';
    $this->filename = __FILE__;
    $this->lineNumber = mt_rand();
    $this->type = 'qux';
    $this->constraint = new Constraint($this->type, $this->expectedValue, $this->fileName, $this->lineNumber);
  }

  /**
   * @covers ::getExpectedValue
   */
  public function testGetExpectedValue() {
    $this->assertSame($this->expectedValue, $this->constraint->getExpectedValue());
  }

  /**
   * @covers ::getFileName
   */
  public function testGetFileName() {
    $this->assertSame($this->fileName, $this->constraint->getFileName());
  }

  /**
   * @covers ::getLineNumber
   */
  public function testGetLineNumber() {
    $this->assertSame($this->lineNumber, $this->constraint->getLineNumber());
  }

  /**
   * @covers ::getType
   */
  public function testGetType() {
    $this->assertSame($this->type, $this->constraint->getType());
  }

  /**
   * @covers ::setStatus
   * @covers ::getStatus
   */
  public function testGetStatus() {
    $this->assertSame($this->constraint, $this->constraint->setStatus(TRUE));
    $this->assertTrue($this->constraint->getStatus());
    $this->constraint->setStatus(FALSE);
    $this->assertFalse($this->constraint->getStatus());
  }

  /**
   * @covers ::setActualValue
   * @covers ::getActualValue
   */
  public function testGetActualValue() {
    $actual_value = 'barfoo';
    $this->assertSame($this->constraint, $this->constraint->setActualValue($actual_value));
    $this->assertSame($actual_value, $this->constraint->getActualValue());
  }

}


text:
<?php

namespace Zitec\RuleEngineBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;

/**
 * Class DefaultController
 */
class DefaultController extends Controller
{
    /**
     * Action for the autocomplete call used in the Autocomplete widget type in the RuleBuilder javascript component.
     *
     * @param Request $request
     * @return JsonResponse
     * @throws \Exception
     */
    public function autocompleteAction(Request $request)
    {
        $dataSourceKey = $request->get('key');
        $queryMode = $request->get('mode');
        $queryString = $request->get('q');

        switch ($queryMode) {
            case 'like':
                $page = $request->get('page');
                $results = $this->get('rule_engine.autocomplete')
                    ->getSuggestions($dataSourceKey, $queryString, $page);
                break;
            case 'label':
                $results = $this->get('rule_engine.autocomplete')
                    ->getLabels($dataSourceKey, $queryString);
                break;
            default:
                throw new \Exception('Invalid query mode.');
        }

        return new JsonResponse($results);
    }
}