text:
package github

import (
	"bytes"
	"io/ioutil"
	"net/http"
	"net/http/httptest"
	"strings"
	"testing"

	kapi "github.com/GoogleCloudPlatform/kubernetes/pkg/api"
	"github.com/GoogleCloudPlatform/kubernetes/pkg/labels"
	"github.com/GoogleCloudPlatform/kubernetes/pkg/watch"

	"github.com/openshift/origin/pkg/build/api"
	"github.com/openshift/origin/pkg/build/webhook"
	"github.com/openshift/origin/pkg/client"
)

type osClient struct {
	client.Fake
}

func (_ *osClient) GetBuildConfig(ctx kapi.Context, id string) (result *api.BuildConfig, err error) {
	return &api.BuildConfig{
		Secret: "secret101",
		Parameters: api.BuildParameters{
			Source: api.BuildSource{
				Type: api.BuildSourceGit,
				Git: &api.GitBuildSource{
					URI: "git://github.com/my/repo.git",
				},
			},
		},
	}, nil
}

func (_ *osClient) WatchBuilds(ctx kapi.Context, field, label labels.Selector, resourceVersion string) (watch.Interface, error) {
	return nil, nil
}

func TestWrongMethod(t *testing.T) {
	server := httptest.NewServer(webhook.NewController(&osClient{}, map[string]webhook.Plugin{"github": New()}))
	defer server.Close()

	resp, _ := http.Get(server.URL + "/build100/secret101/github")
	body, _ := ioutil.ReadAll(resp.Body)
	if resp.StatusCode != http.StatusBadRequest ||
		!strings.Contains(string(body), "method") {
		t.Errorf("Expected BadRequest , got %s: %s!", resp.Status, string(body))
	}
}

func TestWrongContentType(t *testing.T) {
	server := httptest.NewServer(webhook.NewController(&osClient{}, map[string]webhook.Plugin{"github": New()}))
	defer server.Close()

	client := &http.Client{}
	req, _ := http.NewRequest("POST", server.URL+"/build100/secret101/github", nil)
	req.Header.Add("Content-Type", "application/text")
	req.Header.Add("User-Agent", "GitHub-Hookshot/github")
	req.Header.Add("X-Github-Event", "ping")
	resp, _ := client.Do(req)
	body, _ := ioutil.ReadAll(resp.Body)
	if resp.StatusCode != http.StatusBadRequest ||
		!strings.Contains(string(body), "Content-Type") {
		t.Errorf("Excepcted BadRequest, got %s: %s!", resp.Status, string(body))
	}
}

func TestWrongUserAgent(t *testing.T) {
	server := httptest.NewServer(webhook.NewController(&osClient{}, map[string]webhook.Plugin{"github": New()}))
	defer server.Close()

	client := &http.Client{}
	req, _ := http.NewRequest("POST", server.URL+"/build100/secret101/github", nil)
	req.Header.Add("Content-Type", "application/json")
	req.Header.Add("User-Agent", "go-lang")
	req.Header.Add("X-Github-Event", "ping")
	resp, _ := client.Do(req)
	body, _ := ioutil.ReadAll(resp.Body)
	if resp.StatusCode != http.StatusBadRequest ||
		!strings.Contains(string(body), "User-Agent") {
		t.Errorf("Excepcted BadRequest, got %s: %s!", resp.Status, string(body))
	}
}

func TestMissingGithubEvent(t *testing.T) {
	server := httptest.NewServer(webhook.NewController(&osClient{}, map[string]webhook.Plugin{"github": New()}))
	defer server.Close()

	client := &http.Client{}
	req, _ := http.NewRequest("POST", server.URL+"/build100/secret101/github", nil)
	req.Header.Add("Content-Type", "application/json")
	req.Header.Add("User-Agent", "GitHub-Hookshot/github")
	resp, _ := client.Do(req)
	body, _ := ioutil.ReadAll(resp.Body)
	if resp.StatusCode != http.StatusBadRequest ||
		!strings.Contains(string(body), "X-GitHub-Event") {
		t.Errorf("Excepcted BadRequest, got %s: %s!", resp.Status, string(body))
	}
}

func TestWrongGithubEvent(t *testing.T) {
	server := httptest.NewServer(webhook.NewController(&osClient{}, map[string]webhook.Plugin{"github": New()}))
	defer server.Close()

	client := &http.Client{}
	req, _ := http.NewRequest("POST", server.URL+"/build100/secret101/github", nil)
	req.Header.Add("Content-Type", "application/json")
	req.Header.Add("User-Agent", "GitHub-Hookshot/github")
	req.Header.Add("X-GitHub-Event", "wrong")
	resp, _ := client.Do(req)
	body, _ := ioutil.ReadAll(resp.Body)
	if resp.StatusCode != http.StatusBadRequest ||
		!strings.Contains(string(body), "Unknown") {
		t.Errorf("Excepcted BadRequest, got %s: %s!", resp.Status, string(body))
	}
}

func TestJsonPingEvent(t *testing.T) {
	server := httptest.NewServer(webhook.NewController(&osClient{}, map[string]webhook.Plugin{"github": New()}))
	defer server.Close()

	postFile("ping", "pingevent.json", server.URL+"/build100/secret101/github",
		http.StatusOK, t)
}

func TestJsonPushEventError(t *testing.T) {
	server := httptest.NewServer(webhook.NewController(&osClient{}, map[string]webhook.Plugin{"github": New()}))
	defer server.Close()

	post("push", []byte{}, server.URL+"/build100/secret101/github", http.StatusBadRequest, t)
}

func TestJsonPushEvent(t *testing.T) {
	server := httptest.NewServer(webhook.NewController(&osClient{}, map[string]webhook.Plugin{"github": New()}))
	defer server.Close()

	postFile("push", "pushevent.json", server.URL+"/build100/secret101/github",
		http.StatusOK, t)
}

func postFile(event, filename, url string, expStatusCode int, t *testing.T) {
	data, err := ioutil.ReadFile("fixtures/" + filename)
	if err != nil {
		t.Errorf("Failed to open %s: %v", filename, err)
	}

	post(event, data, url, expStatusCode, t)
}

func post(event string, data []byte, url string, expStatusCode int, t *testing.T) {
	client := &http.Client{}
	req, err := http.NewRequest("POST", url, bytes.NewReader(data))
	if err != nil {
		t.Errorf("Error creating POST request: %v!", err)
	}

	req.Header.Add("Content-Type", "application/json")
	req.Header.Add("User-Agent", "GitHub-Hookshot/github")
	req.Header.Add("X-Github-Event", event)
	resp, err := client.Do(req)

	if err != nil {
		t.Errorf("Failed posting webhook to: %s!", url)
	}
	body, _ := ioutil.ReadAll(resp.Body)
	if resp.StatusCode != expStatusCode {
		t.Errorf("Wrong response code, expecting %d, got %s: %s!",
			expStatusCode, resp.Status, string(body))
	}
}

type testContext struct {
	plugin   GitHubWebHook
	buildCfg *api.BuildConfig
	req      *http.Request
	path     string
}

func setup(t *testing.T, filename, eventType string) *testContext {
	context := testContext{
		plugin: GitHubWebHook{},
		buildCfg: &api.BuildConfig{
			Secret: "secret101",
			Parameters: api.BuildParameters{
				Source: api.BuildSource{
					Type: api.BuildSourceGit,
					Git: &api.GitBuildSource{
						URI: "git://github.com/my/repo.git",
					},
				},
			},
		},
		path: "/foobar",
	}
	event, err := ioutil.ReadFile("fixtures/" + filename)
	if err != nil {
		t.Errorf("Failed to open %s: %v", filename, err)
	}
	req, err := http.NewRequest("POST", "http://origin.com", bytes.NewReader(event))
	req.Header.Add("Content-Type", "application/json")
	req.Header.Add("User-Agent", "GitHub-Hookshot/github")
	req.Header.Add("X-Github-Event", eventType)

	context.req = req
	return &context
}

func TestExtractForAPingEvent(t *testing.T) {
	//setup
	context := setup(t, "pingevent.json", "ping")

	//execute
	_, proceed, err := context.plugin.Extract(context.buildCfg, context.path, context.req)

	//validation
	if err != nil {
		t.Errorf("Error while extracting build info: %s", err)
	}
	if proceed {
		t.Errorf("The 'proceed' return value should equal 'false' %s", proceed)
	}
}

func TestExtractProvidesValidBuildForAPushEvent(t *testing.T) {
	//setup
	context := setup(t, "pushevent.json", "push")

	//execute
	build, proceed, err := context.plugin.Extract(context.buildCfg, context.path, context.req)

	//validation
	if err != nil {
		t.Errorf("Error while extracting build info: %s", err)
	}
	if !proceed {
		t.Errorf("The 'proceed' return value should equal 'true' %s", proceed)
	}
	if build == nil {
		t.Error("Expecting the build to not be nil")
	} else {
		if build.Parameters.Revision.Git.Commit != "9bdc3a26ff933b32f3e558636b58aea86a69f051" {
			t.Error("Expecting the build's desired input to contain the commit id from the push event")
		}
	}
}

func TestExtractProvidesValidBuildForAPushEventOtherThanMaster(t *testing.T) {
	//setup
	context := setup(t, "pushevent-not-master-branch.json", "push")
	context.buildCfg.Parameters.Source.Git.Ref = "my_other_branch"

	//execute
	build, proceed, err := context.plugin.Extract(context.buildCfg, context.path, context.req)

	//validation
	if err != nil {
		t.Errorf("Error while extracting build info: %s", err)
	}
	if !proceed {
		t.Errorf("The 'proceed' return value should equal 'true' %s", proceed)
	}
	if build == nil {
		t.Error("Expecting the build to not be nil")
	} else {
		if build.Parameters.Revision.Git.Commit != "9bdc3a26ff933b32f3e558636b58aea86a69f051" {
			t.Error("Expecting the build's desired input to contain the commit id from the push event")
		}
	}
}

func TestExtractSkipsBuildForUnmatchedBranches(t *testing.T) {
	//setup
	context := setup(t, "pushevent.json", "push")
	context.buildCfg.Parameters.Source.Git.Ref = "adfj32qrafdavckeaewra"

	//execute
	build, proceed, _ := context.plugin.Extract(context.buildCfg, context.path, context.req)
	if proceed {
		t.Errorf("Expecting to not continue from this event because the branch '%s' is not for this buildConfig '%s'", build.Parameters.Source.Git.Ref, context.buildCfg.Parameters.Source.Git.Ref)
	}
}


text:
@interface TrainingLevelToSingSegue : UIStoryboardSegue

@end

redpajama_set_name: RedPajamaGithub


text:
module Rebase.Prelude
(
  module Exports,
)
where

-- base
-------------------------
import Prelude as Exports hiding (fail, concat, foldr, mapM_, sequence_, foldl1, maximum, minimum, product, sum, all, and, any, concatMap, elem, foldl, foldr1, notElem, or, mapM, sequence, id, (.))
import Rebase.Control.Applicative as Exports
import Rebase.Control.Arrow as Exports hiding (first, second)
import Rebase.Control.Category as Exports
import Rebase.Control.Concurrent as Exports
import Rebase.Control.Exception as Exports
import Rebase.Control.Monad as Exports hiding (fail, mapM_, sequence_, forM_, msum, mapM, sequence, forM)
import Rebase.Control.Monad.Fail as Exports
import Rebase.Control.Monad.Fix as Exports hiding (fix)
import Rebase.Control.Monad.IO.Class as Exports
import Rebase.Control.Monad.ST as Exports
import Rebase.Data.Bifunctor as Exports
import Rebase.Data.Bits as Exports
import Rebase.Data.Bool as Exports
import Rebase.Data.Char as Exports
import Rebase.Data.Coerce as Exports
import Rebase.Data.Complex as Exports
import Rebase.Data.Data as Exports
import Rebase.Data.Dynamic as Exports
import Rebase.Data.Either as Exports
import Rebase.Data.Fixed as Exports
import Rebase.Data.Foldable as Exports hiding (toList)
import Rebase.Data.Function as Exports hiding (id, (.))
import Rebase.Data.Functor as Exports
import Rebase.Data.Functor.Classes as Exports
import Rebase.Data.Functor.Compose as Exports
import Rebase.Data.Functor.Contravariant as Exports
import Rebase.Data.Functor.Identity as Exports
import Rebase.Data.Int as Exports
import Rebase.Data.IORef as Exports
import Rebase.Data.Ix as Exports
import Rebase.Data.List as Exports hiding (concat, foldr, foldl1, maximum, minimum, product, sum, all, and, any, concatMap, elem, foldl, foldr1, notElem, or, find, maximumBy, minimumBy, mapAccumL, mapAccumR, foldl')
import Rebase.Data.List.NonEmpty as Exports (NonEmpty(..))
import Rebase.Data.Maybe as Exports
import Rebase.Data.Monoid as Exports hiding (Alt, First(..), Last(..), (<>))
import Rebase.Data.Ord as Exports
import Rebase.Data.Proxy as Exports
import Rebase.Data.Ratio as Exports
import Rebase.Data.Semigroup as Exports
import Rebase.Data.STRef as Exports
import Rebase.Data.String as Exports
import Rebase.Data.Traversable as Exports
import Rebase.Data.Tuple as Exports
import Rebase.Data.Unique as Exports
import Rebase.Data.Version as Exports
import Rebase.Data.Void as Exports
import Rebase.Data.Word as Exports
import Rebase.Debug.Trace as Exports
import Rebase.Foreign.ForeignPtr as Exports
import Rebase.Foreign.Ptr as Exports
import Rebase.Foreign.StablePtr as Exports
import Rebase.Foreign.Storable as Exports
import Rebase.GHC.Conc as Exports hiding (orElse, withMVar, threadWaitWriteSTM, threadWaitWrite, threadWaitReadSTM, threadWaitRead)
import Rebase.GHC.Exts as Exports (lazy, inline, sortWith, groupWith, IsList(..))
import Rebase.GHC.Generics as Exports (Generic)
import Rebase.GHC.IO.Exception as Exports
import Rebase.GHC.OverloadedLabels as Exports
import Rebase.GHC.Records as Exports
import Rebase.Numeric as Exports
import Rebase.Numeric.Natural as Exports
import Rebase.System.Environment as Exports
import Rebase.System.Exit as Exports
import Rebase.System.IO as Exports (Handle, hClose)
import Rebase.System.IO.Error as Exports
import Rebase.System.IO.Unsafe as Exports
import Rebase.System.Mem as Exports
import Rebase.System.Mem.StableName as Exports
import Rebase.System.Timeout as Exports
import Rebase.Text.ParserCombinators.ReadP as Exports (ReadP, ReadS, readP_to_S, readS_to_P)
import Rebase.Text.ParserCombinators.ReadPrec as Exports (ReadPrec, readPrec_to_P, readP_to_Prec, readPrec_to_S, readS_to_Prec)
import Rebase.Text.Printf as Exports (printf, hPrintf)
import Rebase.Text.Read as Exports (Read(..), readMaybe, readEither)
import Rebase.Unsafe.Coerce as Exports

-- profunctors
-------------------------
import Rebase.Data.Profunctor as Exports hiding (WrappedArrow(..))
import Rebase.Data.Profunctor.Adjunction as Exports
import Rebase.Data.Profunctor.Cayley as Exports
import Rebase.Data.Profunctor.Choice as Exports
import Rebase.Data.Profunctor.Closed as Exports
import Rebase.Data.Profunctor.Composition as Exports
import Rebase.Data.Profunctor.Mapping as Exports
import Rebase.Data.Profunctor.Monad as Exports
import Rebase.Data.Profunctor.Ran as Exports
import Rebase.Data.Profunctor.Rep as Exports
import Rebase.Data.Profunctor.Sieve as Exports
import Rebase.Data.Profunctor.Strong as Exports
import Rebase.Data.Profunctor.Traversing as Exports
import Rebase.Data.Profunctor.Types as Exports hiding (WrappedArrow(..))
import Rebase.Data.Profunctor.Unsafe as Exports
import Rebase.Data.Profunctor.Yoneda as Exports

-- contravariant
-------------------------
import Rebase.Data.Functor.Contravariant as Exports
import Rebase.Data.Functor.Contravariant.Divisible as Exports

-- semigroups
-------------------------
import Rebase.Data.List.NonEmpty as Exports (NonEmpty)

-- semigroupoids
-------------------------
import Rebase.Data.Bifunctor.Apply as Exports
import Rebase.Data.Groupoid as Exports
import Rebase.Data.Functor.Alt as Exports hiding (($>), many, some, optional)
import Rebase.Data.Functor.Apply as Exports hiding (($>))
import Rebase.Data.Functor.Bind as Exports hiding (join, ($>))
import Rebase.Data.Functor.Extend as Exports
import Rebase.Data.Functor.Plus as Exports hiding (($>), some, many, optional)
import Rebase.Data.Semigroup.Bifoldable as Exports
import Rebase.Data.Semigroup.Bitraversable as Exports
import Rebase.Data.Semigroup.Foldable as Exports
import Rebase.Data.Semigroup.Traversable as Exports
import Rebase.Data.Semigroupoid as Exports

-- comonad
-------------------------
import Rebase.Control.Comonad as Exports

-- deepseq
-------------------------
import Rebase.Control.DeepSeq as Exports

-- selective
-------------------------
import Rebase.Control.Selective as Exports hiding (swapEither)

-- transformers
-------------------------
import Rebase.Control.Monad.IO.Class as Exports
import Rebase.Control.Monad.Trans.Class as Exports
import Rebase.Control.Monad.Trans.Cont as Exports hiding (shift, callCC)
import Rebase.Control.Monad.Trans.Except as Exports (ExceptT(ExceptT), Except, except, runExcept, runExceptT, mapExcept, mapExceptT, withExcept, withExceptT)
import Rebase.Control.Monad.Trans.Maybe as Exports
import Rebase.Control.Monad.Trans.Reader as Exports (Reader, runReader, mapReader, withReader, ReaderT(ReaderT), runReaderT, mapReaderT, withReaderT)
import Rebase.Control.Monad.Trans.State.Strict as Exports (State, runState, evalState, execState, mapState, withState, StateT(StateT), runStateT, evalStateT, execStateT, mapStateT, withStateT)
import Rebase.Control.Monad.Trans.Writer.Strict as Exports (Writer, runWriter, execWriter, mapWriter, WriterT(..), execWriterT, mapWriterT)

-- mtl
-------------------------
import Rebase.Control.Monad.Cont.Class as Exports
import Rebase.Control.Monad.Error.Class as Exports hiding (Error(..))
import Rebase.Control.Monad.Reader.Class as Exports
import Rebase.Control.Monad.State.Class as Exports
import Rebase.Control.Monad.Writer.Class as Exports

-- either
-------------------------
import Rebase.Data.Either.Combinators as Exports hiding (isLeft, isRight, mapLeft, mapRight, fromLeft, fromRight)

-- fail
-------------------------
import Rebase.Control.Monad.Fail as Exports

-- hashable
-------------------------
import Rebase.Data.Hashable as Exports

-- containers
-------------------------
import Rebase.Data.IntMap.Strict as Exports (IntMap)
import Rebase.Data.IntSet as Exports (IntSet)
import Rebase.Data.Map.Strict as Exports (Map)
import Rebase.Data.Sequence as Exports (Seq)
import Rebase.Data.Set as Exports (Set)

-- unordered-containers
-------------------------
import Rebase.Data.HashSet as Exports (HashSet)
import Rebase.Data.HashMap.Strict as Exports (HashMap)

-- vector
-------------------------
import Rebase.Data.Vector as Exports (Vector)

-- vector-instances
-------------------------
import Rebase.Data.Vector.Instances as Exports ()

-- bytestring
-------------------------
import Rebase.Data.ByteString as Exports (ByteString)
import Rebase.Data.ByteString.Short as Exports (ShortByteString)

-- text
-------------------------
import Rebase.Data.Text as Exports (Text)

-- scientific
-------------------------
import Rebase.Data.Scientific as Exports (Scientific)

-- uuid
-------------------------
import Rebase.Data.UUID as Exports (UUID)

-- dlist
-------------------------
import Rebase.Data.DList as Exports (DList)

-- void
-------------------------
import Rebase.Data.Void as Exports
import Rebase.Data.Void.Unsafe as Exports

-- time
-------------------------
import Rebase.Data.Time as Exports
import Rebase.Data.Time.Clock.POSIX as Exports
import Rebase.Data.Time.Clock.System as Exports
import Rebase.Data.Time.Format.ISO8601 as Exports (ISO8601 (..), iso8601ParseM, iso8601Show)

-- time-compat
-------------------------
import Rebase.Data.Time.Compat as Exports ()

-- stm
-------------------------
import Rebase.Control.Concurrent.STM as Exports hiding (orElse)

-- invariant
-------------------------
import Rebase.Data.Functor.Invariant as Exports

-- groups
-------------------------
import Rebase.Data.Group as Exports

-- custom
-------------------------
import Rebase.Data.List1 as Exports (List1)


text:
OpenStack-Ansible LXC container create
######################################

Ansible role for creating LXC containers. This role will create several
directories on the LXC host for use in bind mounted storage within the
container.

Default Variables
=================

.. literalinclude:: ../../defaults/main.yml
   :language: yaml
   :start-after: under the License.

Required Variables
==================

None

Example Playbook
================

.. code-block:: yaml

    - name: Create container(s)
      hosts: all_containers
      gather_facts: false
      user: root
      roles:
        - { role: "lxc_container_create" }


text:
"""The server password extension."""

from nova.api.metadata import password
from nova.api.openstack import common
from nova.api.openstack import extensions
from nova.api.openstack import wsgi
from nova import compute

authorize = extensions.extension_authorizer('compute', 'server_password')

class ServerPasswordController(object):
    """The Server Password API controller for the OpenStack API."""
    def __init__(self):
        self.compute_api = compute.API()

    def index(self, req, server_id):
        context = req.environ['nova.context']
        authorize(context)
        instance = common.get_instance(self.compute_api, context, server_id,
                                       want_objects=True)

        passw = password.extract_password(instance)
        return {'password': passw or ''}

    @wsgi.response(204)
    def delete(self, req, server_id):
        context = req.environ['nova.context']
        authorize(context)
        instance = common.get_instance(self.compute_api, context, server_id,
                                       want_objects=True)
        meta = password.convert_password(context, None)
        instance.system_metadata.update(meta)
        instance.save()

class Server_password(extensions.ExtensionDescriptor):
    """Server password support."""

    name = "ServerPassword"
    alias = "os-server-password"
    namespace = ("http://docs.openstack.org/compute/ext/"
                 "server-password/api/v2")
    updated = "2012-11-29T00:00:00Z"

    def get_resources(self):
        resources = []

        res = extensions.ResourceExtension(
            'os-server-password',
            controller=ServerPasswordController(),
            collection_actions={'delete': 'DELETE'},
            parent=dict(member_name='server', collection_name='servers'))
        resources.append(res)

        return resources


text:
package com.greensnow25.chess.exeptions;
/**
 * public exeption, throws if wrong color of figure.
 * or figure do not move that.
 * @author greensnow25.
 * @since 08.02.17.
 * @version 1.
 */
public class ImposibleMoveExeption extends Exception {
    /**
     * if wrong color of figure or figure do not move that.
     * @param msg massage about exeption.
     */
    public ImposibleMoveExeption(String msg) {
        super(msg);
    }
}


text:
<?php

namespace lib;

use php_user_filter;

class FilterReplace extends php_user_filter
{
    const FILTER_NAME = 'convert.replace.';

    private $search;

    private $replace;

    public function onCreate()
    {
        if( strpos( $this->filtername, self::FILTER_NAME ) !== 0 ){
            return false;
        }

        $params = substr( $this->filtername, strlen( self::FILTER_NAME ) );

        if( !preg_match( '/([^:]+):([^$]+)$/', $params, $matches ) ){
            return false;
        }

        $this->search  = $matches[1];
        $this->replace = $matches[2];

        return true;
    }

    public function filter( $in, $out, &$consumed, $closing )
    {
        while( $res = stream_bucket_make_writeable( $in ) ){

            $res->data = str_replace( $this->search, $this->replace, $res->data );

            $consumed += $res->datalen;

            /** @noinspection PhpParamsInspection */
            stream_bucket_append( $out, $res );
        }

        return PSFS_PASS_ON;
    }
}


text:
package com.novoda.downloadmanager;

import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

class FixedRateTimerActionScheduler implements ActionScheduler {

    private static final long DELAY_IN_MILLIS = 0;

    private final Timer timer;
    private final long frequencyInMillis;
    private final Map<Action, TimerTask> actionTimerTasks;

    FixedRateTimerActionScheduler(Timer timer, long frequencyInMillis, Map<Action, TimerTask> actionTimerTasks) {
        this.timer = timer;
        this.frequencyInMillis = frequencyInMillis;
        this.actionTimerTasks = actionTimerTasks;
    }

    @Override
    public void schedule(final Action action) {
        if (actionTimerTasks.containsKey(action)) {
            Logger.v("Already contains action, aborting schedule");
            return;
        }

        TimerTask taskToExecute = new TimerTask() {
            @Override
            public void run() {
                action.perform();
            }
        };
        timer.scheduleAtFixedRate(taskToExecute, DELAY_IN_MILLIS, frequencyInMillis);
        actionTimerTasks.put(action, taskToExecute);
    }

    @Override
    public void cancel(Action action) {
        if (actionTimerTasks.containsKey(action)) {
            TimerTask timerTask = actionTimerTasks.get(action);
            timerTask.cancel();
            actionTimerTasks.remove(action);
        }
    }

    @Override
    public void cancelAll() {
        for (Map.Entry<Action, TimerTask> timerTaskEntry : actionTimerTasks.entrySet()) {
            TimerTask timerTask = timerTaskEntry.getValue();
            timerTask.cancel();
        }
        actionTimerTasks.clear();
    }

    @Override
    public boolean isScheduled(Action action) {
        return actionTimerTasks.containsKey(action);
    }

}


text:
package com.iknowers.learning.concurrent;

/**
 * ThreadLocal 案列,每个线程都有一个副本
 *
 * @author Shun Xu
 */
public class ThreadLocalDemo {

    public static class MyRunnable implements Runnable {

        private ThreadLocal<Integer> threadLocal = new ThreadLocal<>();

        @Override
        public void run() {
            int value = (int) (Math.random() * 100D);
            threadLocal.set(value);
            System.out.printf("Thread %s set value %d\n", Thread.currentThread().getName(), value);

            try {
                Thread.sleep(2000);
            } catch (InterruptedException e) {
            }
            System.out.printf("Thread %s get value %d\n", Thread.currentThread().getName(), threadLocal.get());
        }
    }

    public static void main(String[] args) throws InterruptedException {
        MyRunnable sharedRunnableInstance = new MyRunnable();

        Thread thread1 = new Thread(sharedRunnableInstance);
        Thread thread2 = new Thread(sharedRunnableInstance);

        thread1.start();
        thread2.start();

        thread1.join(); //wait for thread 1 to terminate
        thread2.join(); //wait for thread 2 to terminate
    }

}


text:
package tv.ustream.yolo.module.processor;

/**
 * @author bandesz
 */
public interface ICompositeProcessor extends IProcessor
{

    void addProcessor(IProcessor processor);

}


text:
"""
no annotations for the subject, so the blast(z) is just query features against
subject genomic sequence.
we use the subject hits as the new features by:
    + overlapping subject hits are merged into single hsps
    + nearby subject hits to the same query are merge into single HSPs
    + no introns are recorded.

bed and feature fasta files are created.
"""
import sys
import collections
from pyfasta import Fasta
import numpy as np
import os.path as op
from itertools import tee, izip

blast_file = sys.argv[1]
subject_fasta_file = sys.argv[2]

out_fasta = "%s.features%s" % op.splitext(subject_fasta_file)

by_subject = collections.defaultdict(list)
fa = Fasta(subject_fasta_file)

def pairwise(iterable):
    "s -> (s0,s1), (s1,s2), (s2, s3), ..."
    a, b = tee(iterable)
    next(b, None)
    return izip(a, b)

by_subject = {}
seqids = []
for seqid in fa.iterkeys():
    by_subject[seqid] = np.zeros((len(fa[seqid]) + 1,), dtype=np.uint8)
    seqids.append((len(fa[seqid]),seqid))

by_query_subject = collections.defaultdict(dict)
for line in open(blast_file):
    args = line.split("\t")
    query, subject = args[0], args[1]
    sstart, sstop = sorted(map(int, args[8:10]))
    by_subject[subject][sstart: sstop + 1] |= 1
    if not subject in by_query_subject[query]:
        by_query_subject[query][subject] = [(sstart, sstop)]
    else:
        by_query_subject[query][subject].append((sstart, sstop))

# if 2 HSPs are nearby on the subject and from the same query, merge them into a single HSP
NEAR_SAME = 1000
for query in by_query_subject:
    for subject in by_query_subject[query]:
        li = sorted(by_query_subject[query][subject])
        if len(li) < 2: continue
        for alocs, blocs in pairwise(li):

            if blocs[0] - alocs[1] < NEAR_SAME:
                by_subject[subject][alocs[1]: blocs[0] + 1] |= 1

print >>sys.stderr, "writing features.fasta to: %s" % out_fasta
out = open(out_fasta, "w")

for seqlen, seqid in sorted(seqids, reverse=True):
    masks = by_subject[seqid]
    starts, = np.where((masks[:-1] == 0) & (masks[1:] == 1))
    ends,   = np.where((masks[:-1] == 1) & (masks[1:] == 0))

    for s, e in zip(starts, ends):
        assert s < e, (s, e, seqid)
        # add 1 for 0-based and 1 for the [1:]
        start = s + 2
        end = e + 1
        name = "%s-%i-%i" % (seqid, start, end)
        print "%s\t%i\t%i\t%s" % (seqid, s + 1, e, name)
        print >>out, ">" + name
        print >>out, fa[seqid][start - 1: end]


text:
// ----------------------------------------------------------------------------------
//
// Copyright Microsoft Corporation
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// ----------------------------------------------------------------------------------

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Management.Automation;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Microsoft.WindowsAzure.Commands.Test.Utilities.HDInsight.PowerShellTestAbstraction.Interfaces;
using Microsoft.WindowsAzure.Commands.Test.Utilities.HDInsight.Utilities;
using Microsoft.WindowsAzure.Management.HDInsight;
using Microsoft.WindowsAzure.Management.HDInsight.Cmdlet.DataObjects;

namespace Microsoft.WindowsAzure.Commands.Test.HDInsight.CmdLetTests
{
    [TestClass]
    public class GetJobOutputCmdletTests : HDInsightTestCaseBase
    {
        [TestInitialize]
        public override void Initialize()
        {
            base.Initialize();
        }

        [TestCleanup]
        public override void TestCleanup()
        {
            base.TestCleanup();
        }

        [TestMethod]
        [TestCategory("CheckIn")]
        [TestCategory("Integration")]

        [TestCategory("Jobs")]
        [TestCategory("Get-AzureHDInsightJobOutput")]
        public void ICanCallThe_Get_HDInsightJobOutputCmdlet()
        {
            using (IRunspace runspace = this.GetPowerShellRunspace())
            {
                ClusterDetails testCluster = CmdletScenariosTestCaseBase.GetHttpAccessEnabledCluster();
                IPipelineResult results =
                    runspace.NewPipeline()
                            .AddCommand(CmdletConstants.GetAzureHDInsightJob)
                            .WithParameter(CmdletConstants.Cluster, testCluster.Name)
                            .WithParameter(CmdletConstants.Credential, GetPSCredential(testCluster.HttpUserName, testCluster.HttpPassword))
                            .Invoke();
                IEnumerable<AzureHDInsightJob> jobHistory = results.Results.ToEnumerable<AzureHDInsightJob>();

                IPipelineResult outputContent =
                    runspace.NewPipeline()
                            .AddCommand(CmdletConstants.GetAzureHDInsightJobOutput)
                            .WithParameter(CmdletConstants.Cluster, testCluster.Name)
                            .WithParameter(CmdletConstants.Id, jobHistory.First().JobId)
                            .Invoke();
                string result = outputContent.Results.ToEnumerable<string>().First();
                Assert.IsTrue(result.Length > 0);
            }
        }

        [TestMethod]
        [TestCategory("CheckIn")]
        [TestCategory("Integration")]

        [TestCategory("Jobs")]
        [TestCategory("Get-AzureHDInsightJobOutput")]
        public void ICanCallThe_Get_HDInsightJobOutputCmdlet_WithStdErrSwitch()
        {
            using (IRunspace runspace = this.GetPowerShellRunspace())
            {
                ClusterDetails testCluster = CmdletScenariosTestCaseBase.GetHttpAccessEnabledCluster();
                IPipelineResult results =
                    runspace.NewPipeline()
                            .AddCommand(CmdletConstants.GetAzureHDInsightJob)
                            .WithParameter(CmdletConstants.Cluster, testCluster.Name)
                            .WithParameter(CmdletConstants.Credential, GetPSCredential(testCluster.HttpUserName, testCluster.HttpPassword))
                            .Invoke();
                IEnumerable<AzureHDInsightJob> jobHistory = results.Results.ToEnumerable<AzureHDInsightJob>();

                IPipelineResult outputContent =
                    runspace.NewPipeline()
                            .AddCommand(CmdletConstants.GetAzureHDInsightJobOutput)
                            .WithParameter(CmdletConstants.Cluster, testCluster.Name)
                            .WithParameter(CmdletConstants.Id, jobHistory.First().JobId)
                            .WithParameter(CmdletConstants.StdErr, null)
                            .Invoke();
                string result = outputContent.Results.ToEnumerable<string>().First();
                Assert.IsTrue(result.Length > 0);
            }
        }

        [TestMethod]
        [TestCategory("CheckIn")]
        [TestCategory("Integration")]

        [TestCategory("Jobs")]
        [TestCategory("Get-AzureHDInsightJobOutput")]
        public void ICanCallThe_Get_HDInsightJobOutputCmdlet_WithTaskLogsSwitch()
        {
            using (IRunspace runspace = this.GetPowerShellRunspace())
            {
                ClusterDetails testCluster = CmdletScenariosTestCaseBase.GetHttpAccessEnabledCluster();
                IPipelineResult results =
                    runspace.NewPipeline()
                            .AddCommand(CmdletConstants.GetAzureHDInsightJob)
                            .WithParameter(CmdletConstants.Cluster, testCluster.Name)
                            .WithParameter(CmdletConstants.Credential, GetPSCredential(testCluster.HttpUserName, testCluster.HttpPassword))
                            .Invoke();
                IEnumerable<AzureHDInsightJob> jobHistory = results.Results.ToEnumerable<AzureHDInsightJob>();
                DirectoryInfo taskLogsDirectory = Directory.CreateDirectory(Guid.NewGuid().ToString());
                IPipelineResult outputContent =
                    runspace.NewPipeline()
                            .AddCommand(CmdletConstants.GetAzureHDInsightJobOutput)
                            .WithParameter(CmdletConstants.Cluster, testCluster.Name)
                            .WithParameter(CmdletConstants.JobId, jobHistory.First().JobId)
                            .WithParameter(CmdletConstants.DownloadTaskLogs, null)
                            .WithParameter(CmdletConstants.TaskLogsDirectory, taskLogsDirectory.Name)
                            .Invoke();
                IEnumerable<FileInfo> result = taskLogsDirectory.EnumerateFiles();
                Assert.IsTrue(result.Any());
            }
        }

        [TestMethod]
        [TestCategory("CheckIn")]
        [TestCategory("Integration")]

        [TestCategory("Jobs")]
        [TestCategory("Get-AzureHDInsightJobOutput")]
        public void ICanCallThe_Get_HDInsightJobOutputCmdlet_WithTaskSummarySwitch()
        {
            using (IRunspace runspace = this.GetPowerShellRunspace())
            {
                ClusterDetails testCluster = CmdletScenariosTestCaseBase.GetHttpAccessEnabledCluster();
                IPipelineResult results =
                    runspace.NewPipeline()
                            .AddCommand(CmdletConstants.GetAzureHDInsightJob)
                            .WithParameter(CmdletConstants.Cluster, testCluster.Name)
                            .WithParameter(CmdletConstants.Credential, GetPSCredential(testCluster.HttpUserName, testCluster.HttpPassword))
                            .Invoke();
                IEnumerable<AzureHDInsightJob> jobHistory = results.Results.ToEnumerable<AzureHDInsightJob>();

                IPipelineResult outputContent =
                    runspace.NewPipeline()
                            .AddCommand(CmdletConstants.GetAzureHDInsightJobOutput)
                            .WithParameter(CmdletConstants.Cluster, testCluster.Name)
                            .WithParameter(CmdletConstants.Id, jobHistory.First().JobId)
                            .WithParameter(CmdletConstants.TaskSummary, null)
                            .Invoke();
                string result = outputContent.Results.ToEnumerable<string>().First();
                Assert.IsTrue(result.Length > 0);
            }
        }

        [TestMethod]
        [TestCategory("CheckIn")]
        [TestCategory("Integration")]

        [TestCategory("Jobs")]
        [TestCategory("Get-AzureHDInsightJobOutput")]
        public void ICanCallThe_Get_HDInsightJobsCmdlet_WithNonExistantJobId()
        {
            using (IRunspace runspace = this.GetPowerShellRunspace())
            {
                ClusterDetails testCluster = CmdletScenariosTestCaseBase.GetHttpAccessEnabledCluster();
                string jobId = Guid.NewGuid().ToString();
                IPipelineResult results =
                    runspace.NewPipeline()
                            .AddCommand(CmdletConstants.GetAzureHDInsightJobOutput)
                            .WithParameter(CmdletConstants.Cluster, testCluster.Name)
                            .WithParameter(CmdletConstants.Id, jobId)
                            .WithParameter(CmdletConstants.StdErr, null)
                            .Invoke();

                Assert.IsTrue(results.Results.ToEnumerable<string>().All(string.IsNullOrEmpty));
            }
        }

        [TestMethod]
        [TestCategory("CheckIn")]
        [TestCategory("Integration")]

        [TestCategory("Jobs")]
        [TestCategory("Get-AzureHDInsightJobOutput")]
        public void ICannotCallThe_Get_HDInsightJobOutputCmdlet_WithTaskLogsSwitch_NoDirectory()
        {
            using (IRunspace runspace = this.GetPowerShellRunspace())
            {
                ClusterDetails testCluster = CmdletScenariosTestCaseBase.GetHttpAccessEnabledCluster();
                IPipelineResult results =
                    runspace.NewPipeline()
                            .AddCommand(CmdletConstants.GetAzureHDInsightJob)
                            .WithParameter(CmdletConstants.Cluster, testCluster.Name)
                            .WithParameter(CmdletConstants.Credential, GetPSCredential(testCluster.HttpUserName, testCluster.HttpPassword))
                            .Invoke();
                IEnumerable<AzureHDInsightJob> jobHistory = results.Results.ToEnumerable<AzureHDInsightJob>();
                try
                {
                    runspace.NewPipeline()
                            .AddCommand(CmdletConstants.GetAzureHDInsightJobOutput)
                            .WithParameter(CmdletConstants.Cluster, testCluster.Name)
                            .WithParameter(CmdletConstants.Id, jobHistory.First().JobId)
                            .WithParameter(CmdletConstants.DownloadTaskLogs, null)
                            .Invoke();
                    Assert.Fail("test failed");
                }
                catch (CmdletInvocationException invokeException)
                {
                    var argException = invokeException.GetBaseException() as PSArgumentException;
                    Assert.IsNotNull(argException);
                    Assert.AreEqual(argException.ParamName, "taskLogsDirectory");
                    Assert.AreEqual(argException.Message, "Please specify the directory to download logs to.");
                }
            }
        }
    }
}


text:
package com.pedrorijo91.yo.model

case class Location(private val latitude: String, private val longitude: String) {
  def value: String = s"$latitude,$longitude"
}


text:
name 'my_java'
maintainer 'The Authors'
maintainer_email 'you@example.com'
license 'All Rights Reserved'
description 'Installs/Configures my_java'
long_description 'Installs/Configures my_java'
version '0.1.0'
chef_version '>= 12.1' if respond_to?(:chef_version)

depends 'java'

# The `issues_url` points to the location where issues for this cookbook are
# tracked.  A `View Issues` link will be displayed on this cookbook's page when
# uploaded to a Supermarket.
#
# issues_url 'https://github.com/<insert_org_here>/my_java/issues'

# The `source_url` points to the development repository for this cookbook.  A
# `View Source` link will be displayed on this cookbook's page when uploaded to
# a Supermarket.
#
# source_url 'https://github.com/<insert_org_here>/my_java'


text:
class User < ActiveRecord::Base
  include PgSearchCommon

  has_attached_file :avatar,
    styles: { medium: '300x300>', thumb: '100x100>', head: '32x32#'},
    default_url: 'standard_:style.png'

  before_validation :clear_avatar

  validates_attachment_size :avatar, less_than: 1.megabyte
  validates_attachment_content_type :avatar,
    content_type: %r(\Aimage/.*\Z)

  # call on authlogic
  acts_as_authentic do |c|
    # replace SHA512 by bcrypt
    c.transition_from_crypto_providers = Authlogic::CryptoProviders::Sha512
    c.crypto_provider = Authlogic::CryptoProviders::BCrypt
  end
  #after_create :make_standard_phenotypes

  # dependent so stuff gets destroyed on delete
  has_many :user_phenotypes, dependent: :destroy
  has_many :phenotypes, through: :user_phenotypes
  has_many :user_picture_phenotypes, dependent: :destroy
  has_many :picture_phenotypes, through: :user_picture_phenotypes
  has_many :genotypes, dependent: :destroy
  has_many :user_snps, through: :genotypes
  has_many :snps, through: :user_snps
  has_many :homepages, dependent: :destroy
  has_many :messages, dependent: :destroy
  has_many :user_achievements, dependent: :destroy
  has_many :achievements, through: :user_achievements
  has_many :snp_comments # these shouldn't be deleted, but orphaned
  has_many :phenotype_comments, dependent: :destroy
  has_many :picture_phenotype_comments, dependent: :destroy
  has_one :fitbit_profile, dependent: :destroy

  # needed to edit several user_phenotypes at once, add and delete, and not empty
  accepts_nested_attributes_for :homepages, allow_destroy: true
  accepts_nested_attributes_for :user_phenotypes, allow_destroy: true

  pg_search_common_scope against: [:description, :name]

  def deliver_password_reset_instructions!
    reset_perishable_token!
    UserMailer.password_reset_instructions(self).deliver_later
  end

  def phenotype_length
    # tiny workaround for user-index
    phenotypes.length
  end

  def user_has_sequence_string
    # used in the user-index-page instead of ugly true/false
    if has_sequence
      'Yes'
    else
      'No'
    end
  end

  def check_if_phenotype_exists(charact)
    # checks so we don't create duplicate phenotypes
    if Phenotype.find_by_characteristic(charact) != nil
      true
    else
      false
    end
  end

  def check_and_make_standard_phenotypes(charact)
    # checks whether phenotype exists, creates one if doesn't,
    # creates fitting user_phenotype in both cases
    if check_if_phenotype_exists(charact) == true
      @phen_id = Phenotype.find_by_characteristic(charact).id
      UserPhenotype.create(phenotype_id: @phen_id, variation: '', user_id: id)
    else
      @phen_id = Phenotype.create(characteristic: charact).id
      UserPhenotype.create(phenotype_id: @phen_id, variation: '', user_id: id)
    end
  end

  def make_standard_phenotypes
    check_and_make_standard_phenotypes('Hair color')
    check_and_make_standard_phenotypes('Eye color')
    check_and_make_standard_phenotypes('Skin color')
    check_and_make_standard_phenotypes('Blood type')
  end

  def delete_avatar=(value)
    @delete_avatar = !value.to_i.zero?
  end

  def delete_avatar
    !!@delete_avatar
  end
  alias_method :delete_avatar?, :delete_avatar

  def clear_avatar
    self.avatar = nil if delete_avatar?
  end

end


text:
require 'spec_helper'

describe Money::Currency::Heuristics do
  describe "#analyze_string" do
    let(:it) { Money::Currency }

    it "is not affected by blank characters and numbers" do
      it.analyze('123').should == []
      it.analyze('\n123 \t').should == []
    end

    it "returns nothing when given nothing" do
      it.analyze('').should == []
      it.analyze(nil).should == []
    end

    it "finds a currency by use of its symbol" do
      it.analyze('zł').should == ['PLN']
    end

    it "is not affected by trailing dot" do
      it.analyze('zł.').should == ['PLN']
    end

    it "finds match even if has numbers after" do
      it.analyze('zł 123').should == ['PLN']
    end

    it "finds match even if has numbers before" do
      it.analyze('123 zł').should == ['PLN']
    end

    it "find match even if symbol is next to number" do
      it.analyze('300zł').should == ['PLN']
    end

    it "finds match even if has numbers with delimiters" do
      it.analyze('zł 123,000.50').should == ['PLN']
      it.analyze('zł123,000.50').should == ['PLN']
    end

    it "finds currencies with dots in symbols" do
      it.analyze('L.E.').should == ['EGP']
    end

    it "finds by name" do
      it.analyze('1900 bulgarian lev').should == ['BGN']
      it.analyze('Swedish Krona').should == ['SEK']
    end

    it "Finds several currencies when several match" do
      r = it.analyze('$400')
      r.should include("ARS")
      r.should include("USD")
      r.should include("NZD")

      r = it.analyze('9000 £')
      r.should include("GBP")
      r.should include("SHP")
      r.should include("SYP")
    end

    it "should use alternate symbols" do
      it.analyze('US$').should == ['USD']
    end

    it "finds a currency by use of its iso code" do
      it.analyze('USD 200').should == ['USD']
    end

    it "finds currencies in the middle of a sentence!" do
      it.analyze('It would be nice to have 10000 Albanian lek by tomorrow!').should == ['ALL']
    end

    it "finds several currencies in the same text!" do
      it.analyze("10EUR is less than 100:- but really, I want US$1").should == ['EUR', 'SEK', 'USD']
    end

    it "should function with unicode characters" do
      it.analyze("10 դր.").should == ["AMD"]
    end
  end
end


text:
truncate holdblanket;
alter table holdblanket alter column expiration_date type character varying(10);
copy holdblanket from 'c:\dbdata\symphony\holdblanket.txt' delimiter '|';
update holdblanket set expiration_date = null where expiration_date = 'NEVER';
alter table holdblanket alter column expiration_date type date using to_date(expiration_date, 'DD/MM/YYYY');


text:
package main

import (
	cwe "github.com/aws/aws-sdk-go/service/cloudwatchevents"
)

// Rules is for store unmarshalized configuration yaml
type Rules struct {
	Rules []Rule
}

// Rule is for expression CloudWatch Events Rule
type Rule struct {
	Description        string   `yaml:"description"`
	EventPattern       string   `yaml:"event_pattern"`
	Name               string   `yaml:"name"`
	RoleArn            string   `yaml:"role_arn"`
	ScheduleExpression string   `yaml:"schedule_expression"`
	State              string   `yaml:"state"`
	Targets            []Target `yaml:"targets"`
	ActualRule         cwe.Rule
	NeedUpdate         bool
	NeedDelete         bool
}

// Target is for expression CloudWatch Events Target
type Target struct {
	Arn               string            `yaml:"arn"`
	ID                string            `yaml:"id"`
	Input             string            `yaml:"input"`
	InputPath         string            `yaml:"input_path"`
	EcsParameters     EcsParameters     `yaml:"ecs_parameters"`
	KinesisParameters KinesisParameters `yaml:"kinesis_parameters"`
	RoleArn           string            `yaml:"role_arn"`
	ActualTarget      cwe.Target
	NeedUpdate        bool
	NeedDelete        bool
}

// EcsParameters is a part of the Target
type EcsParameters struct {
	TaskCount         int64  `yaml:"task_count"`
	TaskDefinitionArn string `yaml:"task_definition_arn"`
}

// KinesisParameters is a part of the Target
type KinesisParameters struct {
	PartitionKeyPath string `yaml:"partition_key_path"`
}

// LambdaPolicy is for JSON that return from Lambda.GetPolicy
type LambdaPolicy struct {
	Version   string             `json:"Version"`
	ID        string             `json:"Id"`
	Statement *[]PolicyStatement `json:"Statement"`
}

// PolicyStatement is a part of the LambdaPolicy
type PolicyStatement struct {
	Resource    string           `json:"Resource"`
	Condition   *PolicyCondition `json:"Condition"`
	StatementID string           `json:"Sid"`
	Effect      string           `json:"Effect"`
	Principal   *PolicyPrincipal `json:"Principal"`
	Action      string           `json:"Action"`
}

// PolicyCondition is a part of the LambdaPolicy
type PolicyCondition struct {
	ArnLike *PolicyArnLike `json:"ArnLike"`
}

// PolicyArnLike is a part of the LambdaPolicy
type PolicyArnLike struct {
	AwsSourceArn string `json:"AWS:SourceArn"`
}

// PolicyPrincipal is a part of the LambdaPolicy
type PolicyPrincipal struct {
	Service string `json:"Service"`
}


text:
package leetCode;

/*
 * Link : https://leetcode.com/problems/excel-sheet-column-title/
 */

public class _168ExcelSheetColumnTitle {
	public static String convertToTitle(int n) {
		StringBuffer sb=new StringBuffer();
		while(n>0)
		{
			n--;
			sb.append((char)(n%26+'A'));
			n=n/26;
		}
		return sb.reverse().toString();
	}
	public static void main(String[] args) {
		System.out.println(convertToTitle(26));
	}
}


text:
package utils

import (
	"unicode"
)

// ToSnake convert the given string to snake case following the Golang format:
// acronyms are converted to lower-case and preceded by an underscore.
func ToSnake(in string) string {
	runes := []rune(in)
	length := len(runes)

	var out []rune
	for i := 0; i < length; i++ {
		if i > 0 && unicode.IsUpper(runes[i]) && ((i+1 < length && unicode.IsLower(runes[i+1])) || unicode.IsLower(runes[i-1])) {
			out = append(out, '_')
		}
		out = append(out, unicode.ToLower(runes[i]))
	}

	return string(out)
}

// UcFirst convert first letter into upper.
func UcFirst(str string) string {
	for i, v := range str {
		return string(unicode.ToUpper(v)) + str[i+1:]
	}

	return ""
}


text:
<litepal>

    <dbname value="by_weather"/>

    <version value="1"/>

    <list>
        <mapping class="activitytest.example.dell.byweather.db.Province"/>
        <mapping class="activitytest.example.dell.byweather.db.City"/>
        <mapping class="activitytest.example.dell.byweather.db.County"/>
    </list>
</litepal>


text:
package io.jenkins.blueocean.rest.model;

import net.sf.json.JSONObject;
import org.kohsuke.stapler.DataBoundConstructor;

import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * SCM configuration
 *
 * @author Vivek Pandey
 */
public class BlueScmConfig {
    private String uri;
    private String credentialId;

    private Map<String, Object> config = new LinkedHashMap<>();

    @DataBoundConstructor
    public BlueScmConfig(String uri, String credentialId, JSONObject config) {
        this.uri = uri;
        this.credentialId = credentialId;
        this.config = config;
    }

    /**
     * Gives URI of SCM
     */
    public @Nullable String getUri() {
        return uri;
    }

    /**
     * Gives credential id
     */
    public String getCredentialId() {
        return credentialId;
    }

    /**
     * Gives map of configuration item specific to this pipeline creation
     */
    public @Nonnull Map<String, Object> getConfig() {
        return config;
    }

}


text:
package org.tuxdevelop.spring.batch.lightmin.client.discovery.configuration;

import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.cloud.client.serviceregistry.AutoServiceRegistrationProperties;
import org.springframework.cloud.consul.ConditionalOnConsulEnabled;
import org.springframework.cloud.consul.discovery.ConsulDiscoveryClient;
import org.springframework.cloud.consul.discovery.ConsulDiscoveryProperties;
import org.springframework.cloud.consul.discovery.HeartbeatProperties;
import org.springframework.cloud.consul.serviceregistry.ConsulAutoRegistration;
import org.springframework.cloud.consul.serviceregistry.ConsulManagementRegistrationCustomizer;
import org.springframework.cloud.consul.serviceregistry.ConsulRegistrationCustomizer;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.tuxdevelop.spring.batch.lightmin.client.discovery.annotation.EnableLightminClientDiscoveryCore;
import org.tuxdevelop.spring.batch.lightmin.client.discovery.metadata.ConsulMetaDataExtender;
import org.tuxdevelop.spring.batch.lightmin.client.discovery.metadata.MetaDataExtender;

import java.util.List;

@Configuration
@ConditionalOnConsulEnabled
@EnableLightminClientDiscoveryCore
@ConditionalOnClass(ConsulDiscoveryClient.class)
public class ConsulLightminClientDiscoveryConfiguration {

    @Bean
    public MetaDataExtender metaDataExtender(final ConsulDiscoveryProperties consulDiscoveryProperties) {
        return new ConsulMetaDataExtender(consulDiscoveryProperties);
    }

    @Bean
    @ConditionalOnMissingBean(ConsulAutoRegistration.class)
    public ConsulAutoRegistration consulAutoRegistration(
            final MetaDataExtender metaDataExtender,
            final AutoServiceRegistrationProperties autoServiceRegistrationProperties,
            final ConsulDiscoveryProperties consulDiscoveryProperties,
            final ApplicationContext applicationContext,
            final List<ConsulRegistrationCustomizer> consulRegistrationCustomizers,
            final List<ConsulManagementRegistrationCustomizer> managementRegistrationCustomizers,
            final HeartbeatProperties heartbeatProperties) {

        metaDataExtender.extendMetaData();
        return ConsulAutoRegistration.registration(
                autoServiceRegistrationProperties,
                consulDiscoveryProperties,
                applicationContext,
                consulRegistrationCustomizers,
                managementRegistrationCustomizers,
                heartbeatProperties);
    }
}


text:
<?php
// src/AppBundle/UserManager/UserManager.php
namespace AppBundle\UserManager;

use Doctrine\ORM\EntityManager;
use Zend\Ldap\Ldap;
use AppBundle\Entity\FOSUser;

/**
 * Class UserManager
 * @package AppBundle\UserManager
 */
class UserManager
{
    /**
     * @var EntityManager
     */
    private $em;
    /**
     * @var Ldap
     */
    private $ldap;
    /**
     * @var string
     */
    private $ldap_domain_name_long;
    /**
     * @var string
     */
    private $ldap_baseDn_users;

    /**
     * @var array
     */
    private $ldap_groups = array(
        "Team_BioInformatics" => "Bioinformatics",
        "Team_Fermentation" => "Fermentation",
        "Team_Synthetic Biology" => "Synthetic Biology",
        "Team_Eng Process Engineering" => "Process Engineering",
        "Team_Eng Global Operations" => "Engineering",
        "Team_Eng Design Development" => "Engineering",
        "Team_Process Validation" => "Process Validation"
    );

    /**
     * UserManager constructor.
     * @param EntityManager $em
     * @param string $ldap_host
     * @param string $ldap_port
     * @param string $ldap_username
     * @param string $ldap_password
     * @param string $ldap_baseDn_users
     * @param string $ldap_domain_long
     */
    public function __construct(EntityManager $em, $ldap_host, $ldap_port, $ldap_username, $ldap_password, $ldap_baseDn_users, $ldap_domain_long)
    {
        $this->em = $em;

        $options = array(
            'host' => $ldap_host,
            'port' => $ldap_port,
            'useStartTls' => true,
            'username' => $ldap_username,
            'password' => $ldap_password,
            'baseDn' => $ldap_baseDn_users
        );

        $this->ldap = new Ldap($options);
        $this->ldap->bind();

        $this->ldap_baseDn_users = $ldap_baseDn_users;
        $this->ldap_domain_name_long = $ldap_domain_long;

    }

    /**
     * Returns a user or creates one.
     * @param string $name
     * @return FOSUser $user
     */
    public function findOrCreateUser($name)
    {
        $name = $this->convertToSamaccountname($name);
        $user = $this->em
            ->getRepository('AppBundle:FOSUser')
            ->findOneBy(array('username' => $name));

        if ($user) {
            return $user;
        } else {
            $user = $this->createUser($name);
            return $user;
        }
    }

    /**
     * Creates all users from LDAP server which have valid memberof groups defined by
     * $this->ldap_groups.
     */
    public function createAllUsers()
    {
        $filter = '(&(&(ObjectClass=user))(samaccountname=*))';
        $attributes = ['samaccountname', 'dn', 'memberof', 'cn'];
        $result = $this->ldap->searchEntries($filter, $this->ldap_baseDn_users, Ldap::SEARCH_SCOPE_SUB, $attributes);

        foreach ($result as $item) {
            if (array_key_exists("memberof", $item)) {
                if ($this->hasValidDepartment($item["memberof"])) {
                    // $item is wrapped in an array because $this->createUser unwraps single queries
                    // (Which is how LDAP queries are returned by default).
                    $this->createUser($item['cn'][0], array($item));
                }
            }
        }
    }

    /**
     * Updates FOSUser DNs for a set of FOSUsers.
     * @param array $users
     * @return string
     */
    public function updateUsersDn($users)
    {
        $string_result = "";
        foreach ($users as $user) {
            /*  @var FOSUser $user */
            $record = $this->findViaLDAP($user->getUsername());
            if ($record) {
                // Unpack single user query.
                $record = $record[0];
                if ($record["dn"] != $user->getDn()) {
                    $user->setDn($record["dn"]);
                    $string_result .= $user->getUsername() . " DN set to: " . $record["dn"] . PHP_EOL;
                } else {
                    $string_result .= $user->getUsername() . " DN not set (already consistent)." . PHP_EOL;
                }
            }
        }
        return $string_result;
    }

    /**
     * Converts normal names like John Smith to usernames like John.Smith.
     * @param string $name
     * @return string
     */
    private function convertToSamaccountname($name)
    {
        return str_replace(" ", ".", $name);
    }

    /**
     * @param $name
     * @param null|array $ldap_result
     * @return FOSUser
     */
    private function createUser($name, $ldap_result = null)
    {
        $name = $this->convertToSamaccountname($name);
        $user = new FOSUser();
        if ($ldap_result == null) {
            $ldap_result = $this->findViaLDAP($name);
        }
        if ($ldap_result) {
            $ldap_result = $ldap_result[0];
            $user->setDn($ldap_result["dn"]);
            $user->setEnabled(1);
            $user->setUsername($ldap_result["samaccountname"][0]);
            $user->setUsernameCanonical(strtolower($ldap_result["samaccountname"][0]));
            $email = $ldap_result["samaccountname"][0] . "@" . $this->ldap_domain_name_long;
            $user->setEmail($email);
            $user->setEmailCanonical(strtolower($email));
            $this->setDepartmentForUser($user, $ldap_result["memberof"]);
            $user->setCn($ldap_result['cn'][0]);
            $user->setFromBioControl(false);
        } else {
            $user->setUsername($name);
            $user->setUsernameCanonical(strtolower($name));
            $user->setCn(str_replace(".", " ", $name));
            $email = $name . "@" . $this->ldap_domain_name_long;
            $user->setEmail($email);
            $user->setEmailCanonical(strtolower($email));
            $user->setFromBioControl(true);
            $user->setEnabled(0);
        }
        $this->em->persist($user);
        $this->em->flush();

        return $user;
    }

    /**
     * Queries LDAP for accountname and returns result.
     * @param string $samaccountname
     * @return array $result
     */
    private function findViaLDAP($samaccountname)
    {
        $baseDn = $this->ldap_baseDn_users;
        $filter = '(&(&(ObjectClass=user))(samaccountname=' . $samaccountname . '))';
        $attributes = ['samaccountname', 'dn', 'memberof', 'cn', 'mail'];
        $result = $this->ldap->searchEntries($filter, $baseDn, Ldap::SEARCH_SCOPE_SUB, $attributes);

        return $result;
    }

    /**
     * Attempts to set department and departmentDn from LDAP memberof array.
     * @param FOSUser $user
     * @param array $memberof
     * @return bool
     */
    private function setDepartmentForUser(FOSUser $user, $memberof)
    {
        foreach ($memberof as $group) {
            $matches = [];
            preg_match("/CN=([\w\s]+),/", $group, $matches);
            if (array_key_exists(1, $matches) && array_key_exists($matches[1], $this->ldap_groups)) {
                $user->setDepartment($this->ldap_groups[$matches[1]]);
                $user->setDepartmentDn($group);
                return true;
            }
        }
        return false;
    }

    /**
     * Checks whether memberof ldap array contains a valid group.
     * @param array $memberof
     * @return bool
     */
    private function hasValidDepartment($memberof)
    {
        foreach ($memberof as $group) {
            $matches = [];
            preg_match("/CN=([\w\s]+),/", $group, $matches);
            if (array_key_exists(1, $matches) && array_key_exists($matches[1], $this->ldap_groups)) {
                return true;
            }
        }
        return false;
    }
}


text:
var Strategy = require("../strategy");

class AlwaysCooperateStrategy extends Strategy {

	constructor(name) {
		super((name)? name : "AlwaysCooperateStrategy");
	}

	/**
	 * Always cooperates (returns true), as per its definition.
	 */
	willCooperate(params) {
		return true;
	}
}

module.exports = AlwaysCooperateStrategy;


text:
<?php
$url = '../index.php';
header('Request-URI: '.$url);
header('Content-Location: '.$url);
header('Location: '.$url);
exit();
?>


text:
const {DockerComposeEnvironment, Wait} = require("testcontainers");

let test_container = null;

module.exports = {
    startDb: async () => {

        console.log("starting docker db")
        const dbPort =  50000;

        // solve ioredis connection problem https://github.com/luin/ioredis/issues/763
        const environment = await new DockerComposeEnvironment(__dirname, "test-redis-db.yml")
            .withWaitStrategy("redis_1", Wait.forLogMessage("Ready to accept connections"))
            .up();
        test_container = await environment.getContainer("redis_1");
        const exposedDbPort = test_container.getMappedPort(dbPort);
        process.env.REDIS_PORT = exposedDbPort;

        console.log("connecting redis-server with " + exposedDbPort + " " + test_container.getHost());

        return test_container;
    },

    checkdb: async () => {
    },

    cleanDb: async () => {
        //read-only DB
    },

    stopDb: () => {
        if (test_container) {
            test_container.stop();
            test_container = null;
        }
    }

}


text:
<?php

declare(strict_types=1);

namespace OpenTelemetry\SDK\Common\Attribute;

/**
 * @internal
 */
final class AttributesFactory implements AttributesFactoryInterface
{
    private ?int $attributeCountLimit;
    private ?int $attributeValueLengthLimit;

    public function __construct(?int $attributeCountLimit = null, ?int $attributeValueLengthLimit = null)
    {
        $this->attributeCountLimit = $attributeCountLimit;
        $this->attributeValueLengthLimit = $attributeValueLengthLimit;
    }

    public function builder(iterable $attributes = []): AttributesBuilderInterface
    {
        $builder = new AttributesBuilder(
            [],
            $this->attributeCountLimit,
            $this->attributeValueLengthLimit,
            0,
        );
        foreach ($attributes as $key => $value) {
            $builder[$key] = $value;
        }

        return $builder;
    }
}


text:
"""
Simple CLI script to load the top N players from
a nationals competition based on +/- stats.

Example:

    ./nationals_player_stats.py -y 2017 --level d1college --markdown
"""
from __future__ import print_function

import argparse

import pandas as pd

import usau.reports
import usau.fantasy
import usau.markdown

def compute_plus_minus(df, g_weight=1, a_weight=1, d_weight=1, turn_weight=-0.5):
  return (g_weight * df["Goals"].fillna(0) +
          a_weight * df["Assists"].fillna(0) +
          d_weight * df["Ds"].fillna(0) +
          turn_weight * df["Turns"].fillna(0))

if __name__ == "__main__":
  parser = argparse.ArgumentParser()
  parser.add_argument("-y", "--year", type=int, required=True,
                      help="Year, e.g. 20xx")
  parser.add_argument("-e", "--event", default="nationals",
                      help="USAU event label, such as \"nationals\" or \"us open\"")
  parser.add_argument("-l", "--level",
                      required=True, choices=usau.reports.USAUResults._NATIONALS_LEVELS,
                      help="Competition level")
  parser.add_argument("-n", "--num_players", default=25, type=int,
                      help="Minimum number of players to enumerate")
  parser.add_argument("-g", "--gender", nargs="+", choices=["Men", "Mixed", "Women"],
                      help="Enumerate genders (by default all)")
  parser.add_argument("--markdown", action="store_true",
                      help="Format output tables using markdown table syntax")
  parser.add_argument("--sort_per_game", "--pg", action="store_true",
                      help="Sort by per-game +/- instead of total")
  parser.add_argument("-G", "--goal_weight", type=float, default=1,
                      help="Multiplier for goals")
  parser.add_argument("-A", "--assist_weight", type=float, default=1,
                      help="Multiplier for assists")
  parser.add_argument("-D", "--d_weight", type=float, default=1,
                      help="Multiplier for defensive blocks")
  parser.add_argument("-T", "--turn_weight", type=float, default=-0.5,
                      help="Multiplier for turns; usually negative")
  parser.add_argument("--bold_teams", nargs="+",
                      help="Teams to bold, e.g. as **team**")
  parser.add_argument("--keep_teams", nargs="+",
                      help="Teams to keep")
  parser.add_argument("--skip_teams", nargs="+",
                      help="Teams to skip")
  args = parser.parse_args()

  # rosters = {}
  genders = args.gender
  if genders is None:
    genders = ["Men", "Mixed", "Women"] if args.level == "club" else ["Men", "Women"]

  for gender in genders:
    report = usau.reports.USAUResults.from_event(year=args.year,
                                                 level=args.level,
                                                 gender=gender,
                                                 event=args.event)
    report.load_from_csvs(mandatory=False, write=True)
    roster = report.rosters
    if "Points" in roster.columns:
        roster.rename(columns={"Points": "Goals"}, inplace=True)
    elif "Goals" not in roster.columns:
        raise ValueError("No goals column found: {}".format(roster.column))

    for col in ("Goals", "Assists", "Ds", "Turns"):
      roster[col] = roster[col].fillna(0).astype(int)
    roster["+/-"] = compute_plus_minus(roster,
                                       g_weight=args.goal_weight,
                                       a_weight=args.assist_weight,
                                       d_weight=args.d_weight,
                                       turn_weight=args.turn_weight)

    # Compute the total number of games played per team, for normalization purposes
    matches = report.match_results.drop_duplicates(subset=["Team", "url"])
    matches["Team Games Played"] = 1
    matches["Team Points Played"] = matches["Score"] + matches["Opp Score"]
    matches = matches[matches["Gs"] > 0] \
        .rename(columns={"Score": "Team Score",
                         "Opp Score": "Team Opp Score",
                        })
    matches = matches.groupby("Team")[["Team Games Played", "Team Points Played",
                                       "Team Score", "Team Opp Score"]].sum()
    roster = roster.join(matches, on="Team")
    roster["+/- per Game"] = roster["+/-"] / roster["Team Games Played"]
    roster["#Games"] = roster["Team Games Played"]

    if args.keep_teams:
      roster = roster.loc[roster["Team"].isin(args.keep_teams)].copy()
    if args.skip_teams:
      roster = roster.loc[~roster["Team"].isin(args.skip_teams)].copy()

    # Sort by +/-
    sort_column = "+/- per Game" if args.sort_per_game else "+/-"
    sort_fn = roster.sort_values if hasattr(roster, "sort_values") else roster.sort
    res = (sort_fn(sort_column, ascending=False)
                 .reset_index(drop=True)
                 .head(args.num_players)
                 [["Name", "Team",
                   "Goals", "Assists", "Ds", "Turns",
                   "+/-", "+/- per Game", "#Games"]]
                 .rename(columns={"Goals": "Gs", "Assists": "As", "Turns": "Ts",
                                  "+/- per Game": "+/-pg"})
          )
    #     .style \
    #     .bar(subset=['Fantasy Score', 'Goals', 'Ds', '+/-'],
    #          color='rgba(80, 200, 100, 0.5)') \
    #     .bar(subset=['Assists', 'Turns'],
    #          color='rgba(200, 80, 80, 0.5)')

    if args.bold_teams:
      res.loc[res["Team"].isin(args.bold_teams), "Team"] = \
          res["Team"].apply(lambda x: "**" + x + "**")

    print("{event} {gender} ({year})"
          .format(year=args.year, event=report, gender=report.gender))
    if args.markdown:
      with pd.option_context('display.float_format', lambda x: "%.2f" % x):
        print(usau.markdown.pandas_to_markdown(res))
    else:
      with pd.option_context('display.width', 200, 'display.max_columns', 50,
                             'display.max_rows', 200, 'display.precision', 2):
        print(res)


text:
var package = require('../package.json');
require('@babel/register')(package.browserify.transform[0][1]);
var test = require('tape');
var testData = require('./data.json');
var getHash = require('../lib/get-layer-hash');
test('stringify', function (t) {
  t.plan(1);
  var res = getHash.stringify(testData);
  try {
    JSON.parse(res);
    t.ok(true, 'works');
  } catch (e) {
    t.error(e, 'no!');
  }
});


text:
<?php

namespace App\Discussion\Controllers;

use App\Base\Utilities\GroupTrait;
use App\Discussion\Models\Discussion;
use App\Base\Http\Controllers\Controller;
use App\Discussion\Requests\UpdateDiscussionRequest;
use App\Discussion\Repositories\DiscussionRepository;
use App\Discussion\Requests\ValidateDiscussionCreation;

class DiscussionController extends Controller
{
    use GroupTrait;

    public function index(DiscussionRepository $repository)
    {
        $group = $this->getGroupModel();
        if ($group->notOpenForPublic()) {
            abort(401);
        } elseif (auth()->user()) {
            $this->authorize('view', $group);
        }
        $discussions = $repository->getAllDiscussionWithCreator(request('group_type'), request('group_id'), request('cycle_id'));

        return response()->json([
            'status'      => 'success',
            'total'       => count($discussions),
            'discussions' => $discussions,
        ]);
    }

    public function store(ValidateDiscussionCreation $request, DiscussionRepository $repository)
    {
        $discussion = $repository->create($request->all());
        $discussion->load(['creator:id,avatar,name,username', 'category:id,name']);
        $message = request('draft') ? localize('misc.Your post has been saved') : localize('misc.New discussion post has been created');

        return response()->json([
            'status'     => 'success',
            'message'    => $message,
            'discussion' => $discussion,
        ], 201);
    }

    /**
     * @param  Discussion $discussion
     * @return Discussion
     */
    public function show(Discussion $discussion)
    {
        $this->authorize('view', $discussion);

        return response()->json($discussion);
    }

    public function delete(Discussion $discussion)
    {
        $this->authorize('delete', $discussion);
        $discussion->delete();

        return response()->json([
            'status'  => 'success',
            'message' => localize('misc.The discussion has been deleted'),
        ]);
    }

    public function update(UpdateDiscussionRequest $request, Discussion $discussion, DiscussionRepository $repository)
    {
        $this->authorize('update', $discussion);
        $discussion = $repository->update($discussion, $request->all());
        $discussion->load(['creator:id,avatar,name,username', 'category:id,name']);

        return response()->json([
            'status'     => 'success',
            'message'    => localize('misc.The discussion has been updated'),
            'discussion' => $discussion,
        ], 201);
    }
}


text:
<?php

namespace Zenify\DoctrineFixtures\Alice;

use Doctrine\ORM\EntityManagerInterface;
use Nelmio\Alice\Fixtures\Loader;
use Nette\Utils\Finder;
use Zenify\DoctrineFixtures\Contract\Alice\AliceLoaderInterface;
use Zenify\DoctrineFixtures\Exception\MissingSourceException;

class AliceLoader implements AliceLoaderInterface
{

	/**
	 * @var Loader
	 */
	private $aliceLoader;

	/**
	 * @var EntityManagerInterface
	 */
	private $entityManager;

	public function __construct(Loader $aliceLoader, EntityManagerInterface $entityManager)
	{
		$this->aliceLoader = $aliceLoader;
		$this->entityManager = $entityManager;
	}

	/**
	 * {@inheritdoc}
	 */
	public function load($sources)
	{
		if ( ! is_array($sources)) {
			$sources = [$sources];
		}

		$entities = [];
		foreach ($sources as $source) {
			$newEntities = $this->loadEntitiesFromSource($source);
			$entities = array_merge($entities, $newEntities);
		}

		$this->entityManager->flush();

		return $entities;
	}

	/**
	 * @param $source
	 * @return object[]
	 * @throws MissingSourceException
	 */
	private function loadEntitiesFromSource($source)
	{
		if (is_dir($source)) {
			return $this->loadFromDirectory($source);

		} elseif (is_file($source)) {
			return $this->loadFromFile($source);

		} else {
			throw new MissingSourceException(
				sprintf('Source "%s" was not found.', $source)
			);
		}
	}

	/**
	 * @param string $path
	 * @return object[]
	 */
	private function loadFromFile($path)
	{
		$entities = $this->aliceLoader->load($path);
		foreach ($entities as $entity) {
			$this->entityManager->persist($entity);
		}
		return $entities;
	}

	/**
	 * {@inheritdoc}
	 */
	private function loadFromDirectory($path)
	{
		$files = [];
		foreach (Finder::find(['*.neon', '*.yaml', '*.yml'])->from($path) as $file) {
			$files[] = $file;
		}
		return $this->load($files);
	}

}


text:
package io.github.multilateralis.android_furk_app.adapter;

import android.content.Context;
import android.widget.BaseAdapter;

import io.github.multilateralis.android_furk_app.APIClient;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.Iterator;

public abstract class FilesAdapter extends BaseAdapter implements APIClient.APICallback {

    protected final Context context;
    protected JSONArrayChain jArrayChain;

    public FilesAdapter(Context context) {
        super();
        this.context = context;
        jArrayChain = new JSONArrayChain();
    }

    public abstract void Execute(Object... args);

    public JSONObject getJSONObject(int index) throws JSONException {
        return jArrayChain.getJSONObject(index);
    }

    @Override
    public int getCount() {
        return jArrayChain.length();
    }

public class JSONArrayChain {
    private ArrayList<JSONArray> innerList;

    public JSONArrayChain() {
        this.innerList = new ArrayList<JSONArray>();
    }
    public JSONArrayChain(JSONArray jArray) {
        this.innerList = new ArrayList<JSONArray>();
        innerList.add(jArray);
    }

    public void addJSONArray(JSONArray jarray)
    {
        innerList.add(jarray);
    }

    public JSONArray getJSONArray(int index)
    {
        return innerList.get(index);
    }

    public JSONObject getJSONObject(int index) throws JSONException {
        int offset = index;
        JSONArray itemContainer = null;
        Iterator<JSONArray> arrayIterator = innerList.iterator();
        while (arrayIterator.hasNext())
        {
            itemContainer = arrayIterator.next();
            if(offset >= itemContainer.length())
                offset -= itemContainer.length();
            else
                break;
        }

        if(itemContainer != null)
        {
            return itemContainer.getJSONObject(offset);
        }
        else
            throw new JSONException("index out of bounds");
    }

    public int length()
    {
        int l = 0;
        for(JSONArray item : innerList)
        {
            l += item.length();
        }
        return l;
    }

    public void clear()
    {
        innerList.clear();
    }
}
}


text:
import { StandardEditorProps } from '@savantly/sprout-api';
import { Form, FormField, Icon } from '@sprout-platform/ui';
import { css, cx } from 'emotion';
import { Field, FieldArray } from 'formik';
import React, { Fragment, useState } from 'react';
import { Button, Col, Row } from 'reactstrap';
import { QueryPanelOptions } from '../types';

export type QueryParameterControlType = 'CHOICE' | 'TEXT' | 'DATE';

interface NameValue {
  name: string;
  value: string;
}
export interface QueryParameterControlOptions {
  choices: NameValue[];
}

export interface QueryParameterControl {
  type: QueryParameterControlType;
  label: string;
  id: string;
  defaultValue?: string;
  options: QueryParameterControlOptions;
}

export interface QueryParametersConfiguration {
  controls: QueryParameterControl[];
}

const initialParameterControl: QueryParameterControl = {
  type: 'TEXT',
  label: 'My Param',
  id: 'param1',
  options: {
    choices: []
  }
};

export const QueryParametersEditor: React.FC<
  StandardEditorProps<QueryParametersConfiguration, any, QueryPanelOptions>
> = ({ value, onChange, context, item }) => {
  const [state] = useState(value);

  if (!state) {
    console.log(`no value passed to editor`);
  }

  if (!state) {
    return
Loading...
;
  }

  return (

        <Form
          initialValues={state}
          onSubmit={(values, helpers) => {
            onChange(values);
            helpers.setSubmitting(false);
          }}
          showCancelButton={false}
          showSubmitButton={true}
          submitText="Update"
        >
          {({ values }) => (
            <Row>
              <Col>

                <FieldArray name="controls">
                  {({ insert, remove, push }) => (
                    <Fragment>
                      <Button
                        color="info"
                        onClick={() => {
                          push(initialParameterControl);
                        }}
                      >
                        Add Parameter Control
                      </Button>

                        {values.controls &&
                          values.controls.length > 0 &&
                          values.controls.map((control, index) => (
                            <Fragment key={`control-${index}`}>
                              <div className="mb-1" key={`control-${index}`}>

                                    <Button
                                      color="danger"
                                      onClick={() => {
                                        remove(index);
                                      }}
                                    >
                                      <Icon name="trash-alt" />
                                    </Button>

                                    <Field name={`controls.${index}.type`} as="select" className="form-control">
                                      <option value="CHOICE">Choice</option>
                                      <option value="TEXT">Text</option>
                                      <option value="DATE">Date</option>
                                    </Field>

                                <Row>
                                  <FormField name={`controls.${index}.id`} label="ID" />
                                  <FormField name={`controls.${index}.label`} label="Label" />
                                  <FormField name={`controls.${index}.defaultValue`} label="Default" />
                                </Row>
                                {values.controls[index].type === 'CHOICE' && (
                                  <FieldArray name={`controls.${index}.options.choices`}>
                                    {({ insert, remove, push }) => (

                                        <Button
                                          color="info"
                                          onClick={() => {
                                            push({ name: 'friendly name', value: 'value' });
                                          }}
                                        >
                                          Add Choice
                                        </Button>
                                        <Fragment>
                                          {values.controls[index].options.choices &&
                                            values.controls[index].options.choices.length > 0 &&
                                            values.controls[index].options.choices.map((control, subIndex) => (
                                              <div className="form-inline" key={`choice-${subIndex}`}>
                                                <Button
                                                  color="danger"
                                                  className="mr-2"
                                                  onClick={() => {
                                                    remove(subIndex);
                                                  }}
                                                >
                                                  <Icon name="trash-alt" />
                                                </Button>

Name

                                                  <Field
                                                    name={`controls.${index}.options.choices.${subIndex}.name`}
                                                    className="form-control"
                                                  />

Value

                                                  <Field
                                                    name={`controls.${index}.options.choices.${subIndex}.value`}
                                                    className="form-control"
                                                  />

                                            ))}
                                        </Fragment>

                                    )}
                                  </FieldArray>
                                )}

                            </Fragment>
                          ))}

                    </Fragment>
                  )}
                </FieldArray>
              </Col>
            </Row>
          )}
        </Form>

  );
};


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>R-Index</title>
<meta name="date" content="2018-01-16">
<link rel="stylesheet" type="text/css" href="../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev Letter

Next Letter

Frames

No Frames

All Classes

A B C D E F G H I L M N O P R S T V Y

R

resetCriteria() - Method in class com.airic.fortel.core.util.DestinyCellCriteria

Reset criteria.

ROMANCE_STARS - Static variable in class com.airic.fortel.core.model.Data

The Constant GOOD_STARS.

RUNTIME_MINOR_STARS - Static variable in class com.airic.fortel.core.model.Data

The Constant RUNTIME_MINOR_STARS.

RuntimeInfo - Class in com.airic.fortel.core.model

The Class RuntimeInfo.

RuntimeInfo() - Constructor for class com.airic.fortel.core.model.RuntimeInfo

Instantiates a new runtime info.

RuntimeInfo.RuntimeCategory - Enum in com.airic.fortel.core.model

The Enum RuntimeCategory.

A B C D E F G H I L M N O P R S T V Y

Skip navigation links

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev Letter

Next Letter

Frames

No Frames

All Classes


text:
.. _core-patterns:

Design Patterns & Anti-patterns
===============================

This section is a collection of common design patterns and anti-patterns for writing Ray applications.

.. toctree::
    :maxdepth: 1

    nested-tasks
    generators
    limit-pending-tasks
    limit-running-tasks
    actor-sync
    tree-of-actors
    pipelining
    ray-get-loop
    unnecessary-ray-get
    ray-get-submission-order
    ray-get-too-many-objects
    too-fine-grained-tasks
    redefine-task-actor-loop
    pass-large-arg-by-value
    closure-capture-large-objects
    global-variables


text:
module.exports = function () {
    return function javascript(assetConfig, fromUrl, cb) {
        assetConfig.text = assetConfig.url.replace(/^javascript:/i, '');
        assetConfig.type = 'JavaScript';
        assetConfig.isResolved = true;
        delete assetConfig.url;
        setImmediate(function () {
            cb(null, assetConfig);
        });
    };
};


text:
<?xml version="1.0" encoding="UTF-8"?>
<sem:triples uri="http://www.lds.org/vrl/objects/food-and-beverages/food/veal" xmlns:sem="http://marklogic.com/semantics">
  <sem:triple>
    <sem:subject>http://www.lds.org/vrl/objects/food-and-beverages/food/veal</sem:subject>
    <sem:predicate>http://www.w3.org/2004/02/skos/core#prefLabel</sem:predicate>
    <sem:object datatype="xsd:string" xml:lang="eng">Veal</sem:object>
  </sem:triple>
  <sem:triple>
    <sem:subject>http://www.lds.org/vrl/objects/food-and-beverages/food/veal</sem:subject>
    <sem:predicate>http://www.w3.org/2004/02/skos/core#inScheme</sem:predicate>
    <sem:object datatype="sem:iri">http://www.lds.org/concept-scheme/vrl</sem:object>
  </sem:triple>
  <sem:triple>
    <sem:subject>http://www.lds.org/vrl/objects/food-and-beverages/food/veal</sem:subject>
    <sem:predicate>http://www.lds.org/core#entityType</sem:predicate>
    <sem:object datatype="sem:iri">http://www.lds.org/Topic</sem:object>
  </sem:triple>
</sem:triples>


text:
$(document).ready(function() {
  // Handles FunctionBar
  $(window).on("load resize", function() {
    if ( $("#dynamic-storage").width() > 768 ) {
      $("link[href=\"assets/polyui-small.css\"]").attr("href","assets/polyui-mod.css");
    } else if ( $("#dynamic-storage").width() < 768 ) {
      $("link[href=\"assets/polyui-mod.css\"]").attr("href","assets/polyui-small.css");
    }

    if ( $(this).width() > 900 ) {
      $("#functionbar").removeAttr("class style");
      $("#functionbar").draggable({
        disabled: true
      });
    } else  {
      $("#functionbar").draggable({
        axis: "y",
        handle: "#handlesbar",
        disabled: false
      });
    }
  }).bind("beforeunload", function(){
    return "Are you sure you want to leave? None of your work will be saved.";
  });

  // Select all text that has `.selectallthistxt`
  $(".selectallthistxt").on("click", function() {
    $(this).select();
  });

  // Change Selected Elements HTML Manually
  $(".code").on("keyup", function() {
    $(".selected").html( $(this).val() );
  });

});


text:
.. _toolbox_auto:

   The ``toolbox`` API

``toolbox`` API Reference
=========================

.. automodule:: tidegates.toolbox
   :members:
   :undoc-members:
   :show-inheritance:


text:
import { moduleForModel, test } from 'ember-qunit';

moduleForModel('structure-definition-differential', 'Unit | Model | StructureDefinition_Differential', {
  needs: [
    'model:meta',
    'model:narrative',
    'model:resource',
    'model:extension',
    'model:element-definition'
  ]
});

test('it exists', function(assert) {
  const model = this.subject();
  assert.ok(!!model);
});


text:
import typescript from 'rollup-plugin-typescript';
import commonjs from 'rollup-plugin-commonjs';
import { uglify } from "rollup-plugin-uglify";

export default {
    input: './src/index.ts',
    plugins: [
        typescript({module: 'CommonJS'}),
        commonjs({extensions: ['.js', '.ts']}),
        uglify({
            mangle: {
                properties: { regex: new RegExp(/^_/) }
            }
        })
    ],
    output: {
        file: 'nano-sql-rollup.min.js',
        format: "umd",
        name: "nSQL",
        exports: "named"
    }
}


text:
/
public class DefaultDataCollectorTest
{
    /** Data collector. */
    private DataCollector _dataCollector;

    /** Data collector specification. */
    private DCSpec _dcSpec;

    /**
     * Test the fetchData() method.
     */
    @Test
    public void fetchDataJava()
    {
        final String username = null;
        final String password = null;
        final RivalryData rivalryData = new DefaultRivalryData();
        final Candidate candidate = createCandidate("Java", _dcSpec.getUrl());
        rivalryData.getCandidates().add(candidate);

        _dataCollector.fetchData(_dcSpec, username, password, rivalryData);

        assertThat(rivalryData.getCandidates().size(), is(1));
        assertThat(rivalryData.getCategories().size(), is(0));
        assertThat(rivalryData.getCriteria().size(), is(1));

        final Candidate candidate0 = rivalryData.getCandidates().get(0);
        final Criterion criterion0 = rivalryData.getCriteria().get(0);

        assertThat(candidate0.getName(), is("Java"));
        assertThat(criterion0.getName(), is("Count"));

        final Integer value = (Integer)candidate0.getValue(criterion0);
        assertNotNull(value);
        System.out.println("value = [" + value + "] " + value.getClass().getName());
        // assertThat(value, is(17548));
        assertTrue(value > 0);

        final Double rating = candidate0.getRating(criterion0);
        assertNotNull(rating);
        // assertThat(rating, is(17548.0));
        assertTrue(rating > 0);
    }

    /**
     * Set up the tests.
     */
    @Before
    public void setUp()
    {
        final DataCollectorInjector injector = new SkillDemandInjector();
        _dataCollector = injector.injectDataCollector();

        _dcSpec = readDcSpec();
    }

    /**
     *
     * @param candidateName Candidate name.
     * @param url URL.
     *
     * @return a new candidate.
     */
    private Candidate createCandidate(final String candidateName, final String url)
    {
        String page = url;

        if (page.contains("$1"))
        {
            page = page.replaceAll("\\$1", candidateName);
        }

        final Candidate answer = new DefaultCandidate();

        answer.setName(candidateName);
        answer.setPage(page);

        return answer;
    }

    /**
     * @return a new data collector specification read from a file of the given name.
     */
    private DCSpec readDcSpec()
    {
        final InputStream inputStream = getClass().getResourceAsStream("DataCollectorDice.xml");
        assertNotNull(inputStream);
        final Reader reader = new InputStreamReader(inputStream);
        final DCSpecReader dcReader = new DCSpecReader();
        final DCSpec dcSpec = dcReader.read(reader);
        assertNotNull(dcSpec);

        return dcSpec;
    }
}


text:
package org.codehaus.mojo.webstart.generator;

import org.apache.maven.artifact.Artifact;
import org.codehaus.mojo.webstart.dependency.filenaming.DependencyFilenameStrategy;

/**
 * Created on 1/5/14.
 *
 * @author Tony Chemit - dev@tchemit.fr
 * @since 1.0-beta-5
 */
public abstract class AbstractGeneratorExtraConfigWithDeps
        implements GeneratorExtraConfigWithDeps
{

    private final String libPath;

    private final boolean pack200;

    private final boolean outputJarVersions;

    private final boolean useUniqueVersions;

    private final Artifact artifactWithMainClass;

    private final DependencyFilenameStrategy dependencyFilenameStrategy;

    public AbstractGeneratorExtraConfigWithDeps( String libPath, boolean pack200, boolean outputJarVersions,
                                                 boolean useUniqueVersions, Artifact artifactWithMainClass,
                                                 DependencyFilenameStrategy dependencyFilenameStrategy )
    {

        this.libPath = libPath;
        this.pack200 = pack200;
        this.outputJarVersions = outputJarVersions;
        this.useUniqueVersions = useUniqueVersions;
        this.artifactWithMainClass = artifactWithMainClass;
        this.dependencyFilenameStrategy = dependencyFilenameStrategy;
    }

    /**
     * {@inheritDoc}
     */
    public boolean isPack200()
    {
        return pack200;
    }

    /**
     * {@inheritDoc}
     */
    public boolean isOutputJarVersions()
    {
        return outputJarVersions;
    }

    /**
     * {@inheritDoc}
     */
    public boolean isUseUniqueVersions()
    {
        return useUniqueVersions;
    }

    /**
     * {@inheritDoc}
     */
    public String getLibPath()
    {
        return libPath;
    }

    /**
     * {@inheritDoc}
     */
    public boolean isArtifactWithMainClass( Artifact artifact )
    {
        return artifactWithMainClass != null && artifactWithMainClass.equals( artifact );
    }

    /**
     * {@inheritDoc}
     */
    public String getDependencyFilename( Artifact artifact, Boolean outputJarVersion )
    {
        return dependencyFilenameStrategy.getDependencyFilename( artifact, outputJarVersion, useUniqueVersions );
    }

    /**
     * {@inheritDoc}
     */
    public String getDependencyFileVersion( Artifact artifact )
    {
        return dependencyFilenameStrategy.getDependencyFileVersion( artifact, useUniqueVersions );
    }
}


text:
__author__ = "TwIStOy FanChing"
"""Load configuration from root path"""

import json
import codecs
import os

class ConfigError(Exception):
    pass

def load_config_json(file_name):
    if os.path.isfile(file_name):
        with codecs.open(file_name, "r", encoding='utf-8') as fp:
            global_config = json.load(fp)
    else:
        raise OSError('No "{}" file! Please check and retry.'.format(file_name))
    return global_config

class ConfigBase(object):
    """
        config class base
    """
    def __init__(self, file_name):
        self.file_name = file_name

    def load(self):
        return self

    def get(self, attr):
        if hasattr(self, attr):
            return getattr(self, attr)
        else:
            raise AttributeError('No attribute <{attr}> in class <{name}>'.format(
                attr=attr, name=self.__class__.__name__
            ))

class ConfigFromJson(ConfigBase):
    def load(self):
        config = load_config_json(self.file_name)
        for item in config:
            if hasattr(self, item):
                raise ConfigError("Illegal attribute <{attr}> in class <{name}>".format(
                    attr=item, name=self.__class__.__name__
                ))
            setattr(self, item, config.get(item))
        return self

Config = ConfigFromJson


text:
#ifndef __ZMQ_CURVE_SERVER_HPP_INCLUDED__
#define __ZMQ_CURVE_SERVER_HPP_INCLUDED__

#ifdef ZMQ_HAVE_CURVE

#include "curve_mechanism_base.hpp"
#include "options.hpp"
#include "zap_client.hpp"

namespace zmq
{
#ifdef _MSC_VER
#pragma warning(push)
#pragma warning(disable : 4250)
#endif
class curve_server_t : public zap_client_common_handshake_t,
                       public curve_mechanism_base_t
{
  public:
    curve_server_t (session_base_t *session_,
                    const std::string &peer_address_,
                    const options_t &options_);
    virtual ~curve_server_t ();

    // mechanism implementation
    virtual int next_handshake_command (msg_t *msg_);
    virtual int process_handshake_command (msg_t *msg_);
    virtual int encode (msg_t *msg_);
    virtual int decode (msg_t *msg_);

  private:
    //  Our secret key (s)
    uint8_t _secret_key[crypto_box_SECRETKEYBYTES];

    //  Our short-term public key (S')
    uint8_t _cn_public[crypto_box_PUBLICKEYBYTES];

    //  Our short-term secret key (s')
    uint8_t _cn_secret[crypto_box_SECRETKEYBYTES];

    //  Client's short-term public key (C')
    uint8_t _cn_client[crypto_box_PUBLICKEYBYTES];

    //  Key used to produce cookie
    uint8_t _cookie_key[crypto_secretbox_KEYBYTES];

    int process_hello (msg_t *msg_);
    int produce_welcome (msg_t *msg_);
    int process_initiate (msg_t *msg_);
    int produce_ready (msg_t *msg_);
    int produce_error (msg_t *msg_) const;

    void send_zap_request (const uint8_t *key_);
};
#ifdef _MSC_VER
#pragma warning(pop)
#endif
}

#endif

#endif