text:
/// <reference path="../refs.d.ts" />
var fpxt;
(function (fpxt) {
    (function (forms) {
        var Wrike = (function () {
            function Wrike() {
                this.extId = 'WRIKE';
            }
            Wrike.prototype.setup = function (baseApiUrl, authKeys, objParams, onCompleted) {
                var _this = this;
                $("#assignees-loading").show();
                $("folders-loading").show();
                $("#cboActivityParamAssignee").hide();
                $("#treeActivityParamFolders").hide();

                // get data first
                var pd = new Array();
                pd.push(new shearnie.tools.PostData(fpxt.BaseApiUrl.corepath + 'api/oauth/getwrikeassignees', { extId: this.extId, authKeys: JSON.stringify(authKeys), objParams: JSON.stringify(objParams) }));
                pd.push(new shearnie.tools.PostData(fpxt.BaseApiUrl.corepath + 'api/oauth/getwrikefolders', { extId: this.extId, authKeys: JSON.stringify(authKeys), objParams: JSON.stringify(objParams) }));

                var cd = [];
                new shearnie.tools.Poster().SendAsync(pd, function (numErrs) {
                    // fill assignees
                    cd.push({
                        getItems: function () {
                            var ret = [];
                            pd[0].result.items.forEach(function (item) {
                                ret.push({ value: item.id, display: item.name });
                            });
                            return ret;
                        }
                    });

                    shearnie.tools.html.fillCombo($("#cboActivityParamAssignee"), cd, "Select assignee");
                    $("#assignees-loading").hide();
                    $("#cboActivityParamAssignee").show();

                    _this.folders = pd[1].result.tree.foldersTree.folders;

                    //fill folders
                    shearnie.tools.html.fillTree($("#treeActivityParamFolders"), _this.folders, null); // this.onTreeChange);
                    $("#folders-loading").hide();
                    $("#treeActivityParamFolders").show();

                    onCompleted();
                });
            };

            //onTreeChange(nodes: string[])
            //{
            //    this.selectedFolders = nodes;
            //}
            Wrike.prototype.load_folders = function (checkedNodes) {
                $("#folders-loading").show();
                $("#treeActivityParamFolders").hide();
                this.selectedFolders = [];
                shearnie.tools.html.fillTree($("#treeActivityParamFolders"), this.folders, checkedNodes); //, this.onTreeChange);

                $("#folders-loading").hide();
                $("#treeActivityParamFolders").show();
            };

            Wrike.prototype.setupAuthPre = function (baseApiUrl, authKeys, objParams, onCompleted) {
                onCompleted();
            };

            Wrike.prototype.setupAuthPost = function (baseApiUrl, authKeys, objParams, onCompleted) {
                if ($('#txtWrikeConsumerKey').val() != '' && $('#txtWrikeConsumerSecret').val() != '') {
                    var bswitch = $('#chkWrikeOauthOption');
                    bswitch.bootstrapSwitch('toggleState');
                }
                onCompleted();
            };

            Wrike.prototype.fill = function (baseApiUrl, authKeys, values) {
                var _this = this;
                $("#txtActivityParamTaskDesc").val('');
                $("#cboActivityParamAssignee").val(null);

                if (values == null)
                    return;
                values.forEach(function (p) {
                    switch (p.key) {
                        case 'taskdesc':
                            $("#txtActivityParamTaskDesc").val(p.value);
                            break;
                        case 'taskfolders':
                            _this.selectedFolders = JSON.parse(p.value);
                            break;
                        case 'taskassignee':
                            $("#cboActivityParamAssignee").val(p.value);
                            break;
                    }
                });

                this.load_folders(this.selectedFolders);
            };

            Wrike.prototype.get_checkednodes = function () {
                var checked_ids = [];
                var checked = $.jstree.reference("#treeActivityParamFolders").get_selected();
                checked.forEach(function (i) {
                    checked_ids.push(i);
                });
                return checked_ids;
            };

            Wrike.prototype.getProperties = function () {
                if ($("#txtActivityParamTaskDesc").val() == "")
                    throw "Description is required.";

                var ret = [];

                ret.push({ key: "taskdesc", value: $("#txtActivityParamTaskDesc").val() });

                if ($("#cboActivityParamAssignee").val()) {
                    ret.push({ key: "taskassignee", value: $("#cboActivityParamAssignee").val() });
                    ret.push({ key: "taskassigneename", value: $("#cboActivityParamAssignee option:selected").text() });
                }
                this.selectedFolders = this.get_checkednodes();
                ret.push({ key: "taskfolders", value: JSON.stringify(this.selectedFolders) });

                return ret;
            };
            return Wrike;
        })();
        forms.Wrike = Wrike;
    })(fpxt.forms || (fpxt.forms = {}));
    var forms = fpxt.forms;
})(fpxt || (fpxt = {}));
//# sourceMappingURL=wrike.js.map


text:
#ifndef progress_h
#define progress_h

#include <stdbool.h>

#include "wapiti.h"
#include "model.h"

extern bool uit_stop;

void uit_setup(mdl_t *mdl);
void uit_cleanup(mdl_t *mdl);
bool uit_progress(mdl_t *mdl, int it, double obj);

#endif

redpajama_set_name: RedPajamaGithub


text:
package main

import (
	"bytes"
	"fmt"
	"strings"
	"testing"

	"v.io/v23"
	"v.io/v23/context"
	"v.io/v23/rpc"
	"v.io/x/lib/cmdline"
	"v.io/x/lib/vlog"
	"v.io/x/ref/cmd/vrpc/internal"
	"v.io/x/ref/lib/v23cmd"
	_ "v.io/x/ref/runtime/factories/generic"
	"v.io/x/ref/test"
)

type server struct{}

// TypeTester interface implementation

func (*server) EchoBool(_ *context.T, _ rpc.ServerCall, i1 bool) (bool, error) {
	vlog.VI(2).Info("EchoBool(%v) was called.", i1)
	return i1, nil
}

func (*server) EchoFloat32(_ *context.T, _ rpc.ServerCall, i1 float32) (float32, error) {
	vlog.VI(2).Info("EchoFloat32(%v) was called.", i1)
	return i1, nil
}

func (*server) EchoFloat64(_ *context.T, _ rpc.ServerCall, i1 float64) (float64, error) {
	vlog.VI(2).Info("EchoFloat64(%v) was called.", i1)
	return i1, nil
}

func (*server) EchoInt32(_ *context.T, _ rpc.ServerCall, i1 int32) (int32, error) {
	vlog.VI(2).Info("EchoInt32(%v) was called.", i1)
	return i1, nil
}

func (*server) EchoInt64(_ *context.T, _ rpc.ServerCall, i1 int64) (int64, error) {
	vlog.VI(2).Info("EchoInt64(%v) was called.", i1)
	return i1, nil
}

func (*server) EchoString(_ *context.T, _ rpc.ServerCall, i1 string) (string, error) {
	vlog.VI(2).Info("EchoString(%v) was called.", i1)
	return i1, nil
}

func (*server) EchoByte(_ *context.T, _ rpc.ServerCall, i1 byte) (byte, error) {
	vlog.VI(2).Info("EchoByte(%v) was called.", i1)
	return i1, nil
}

func (*server) EchoUint32(_ *context.T, _ rpc.ServerCall, i1 uint32) (uint32, error) {
	vlog.VI(2).Info("EchoUint32(%v) was called.", i1)
	return i1, nil
}

func (*server) EchoUint64(_ *context.T, _ rpc.ServerCall, i1 uint64) (uint64, error) {
	vlog.VI(2).Info("EchoUint64(%v) was called.", i1)
	return i1, nil
}

func (*server) XEchoArray(_ *context.T, _ rpc.ServerCall, i1 internal.Array2Int) (internal.Array2Int, error) {
	vlog.VI(2).Info("XEchoArray(%v) was called.", i1)
	return i1, nil
}

func (*server) XEchoMap(_ *context.T, _ rpc.ServerCall, i1 map[int32]string) (map[int32]string, error) {
	vlog.VI(2).Info("XEchoMap(%v) was called.", i1)
	return i1, nil
}

func (*server) XEchoSet(_ *context.T, _ rpc.ServerCall, i1 map[int32]struct{}) (map[int32]struct{}, error) {
	vlog.VI(2).Info("XEchoSet(%v) was called.", i1)
	return i1, nil
}

func (*server) XEchoSlice(_ *context.T, _ rpc.ServerCall, i1 []int32) ([]int32, error) {
	vlog.VI(2).Info("XEchoSlice(%v) was called.", i1)
	return i1, nil
}

func (*server) XEchoStruct(_ *context.T, _ rpc.ServerCall, i1 internal.Struct) (internal.Struct, error) {
	vlog.VI(2).Info("XEchoStruct(%v) was called.", i1)
	return i1, nil
}

func (*server) YMultiArg(_ *context.T, _ rpc.ServerCall, i1, i2 int32) (int32, int32, error) {
	vlog.VI(2).Info("YMultiArg(%v,%v) was called.", i1, i2)
	return i1, i2, nil
}

func (*server) YNoArgs(_ *context.T, _ rpc.ServerCall) error {
	vlog.VI(2).Info("YNoArgs() was called.")
	return nil
}

func (*server) ZStream(_ *context.T, call internal.TypeTesterZStreamServerCall, nStream int32, item bool) error {
	vlog.VI(2).Info("ZStream(%v,%v) was called.", nStream, item)
	sender := call.SendStream()
	for i := int32(0); i < nStream; i++ {
		sender.Send(item)
	}
	return nil
}

func initTest(t *testing.T) (ctx *context.T, name string, shutdown v23.Shutdown) {
	ctx, shutdown = test.V23Init()
	obj := internal.TypeTesterServer(&server{})
	ctx, server, err := v23.WithNewServer(ctx, "", obj, nil)
	if err != nil {
		t.Fatalf("NewServer failed: %v", err)
		return
	}
	name = server.Status().Endpoints[0].Name()
	return
}

func testSignature(t *testing.T, showReserved bool, wantSig string) {
	ctx, name, shutdown := initTest(t)
	defer shutdown()
	var stdout, stderr bytes.Buffer
	env := &cmdline.Env{Stdout: &stdout, Stderr: &stderr}
	args := []string{"signature", "-s", fmt.Sprintf("-show-reserved=%v", showReserved), name}
	if err := v23cmd.ParseAndRunForTest(cmdVRPC, ctx, env, args); err != nil {
		t.Fatalf("%s: %v", args, err)
	}

	if got, want := stdout.String(), wantSig; got != want {
		t.Errorf("%s: got stdout %s, want %s", args, got, want)
	}
	if got, want := stderr.String(), ""; got != want {
		t.Errorf("%s: got stderr %s, want %s", args, got, want)
	}
}

func TestSignatureWithReserved(t *testing.T) {
	wantSig := `// TypeTester methods are listed in alphabetical order, to make it easier to
// test Signature output, which sorts methods alphabetically.
type "v.io/x/ref/cmd/vrpc/internal".TypeTester interface {
	// Methods to test support for primitive types.
	EchoBool(I1 bool) (O1 bool | error)
	EchoByte(I1 byte) (O1 byte | error)
	EchoFloat32(I1 float32) (O1 float32 | error)
	EchoFloat64(I1 float64) (O1 float64 | error)
	EchoInt32(I1 int32) (O1 int32 | error)
	EchoInt64(I1 int64) (O1 int64 | error)
	EchoString(I1 string) (O1 string | error)
	EchoUint32(I1 uint32) (O1 uint32 | error)
	EchoUint64(I1 uint64) (O1 uint64 | error)
	// Methods to test support for composite types.
	XEchoArray(I1 "v.io/x/ref/cmd/vrpc/internal".Array2Int) (O1 "v.io/x/ref/cmd/vrpc/internal".Array2Int | error)
	XEchoMap(I1 map[int32]string) (O1 map[int32]string | error)
	XEchoSet(I1 set[int32]) (O1 set[int32] | error)
	XEchoSlice(I1 []int32) (O1 []int32 | error)
	XEchoStruct(I1 "v.io/x/ref/cmd/vrpc/internal".Struct) (O1 "v.io/x/ref/cmd/vrpc/internal".Struct | error)
	// Methods to test support for different number of arguments.
	YMultiArg(I1 int32, I2 int32) (O1 int32, O2 int32 | error)
	YNoArgs() error
	// Methods to test support for streaming.
	ZStream(NumStreamItems int32, StreamItem bool) stream<_, bool> error
}

// Reserved methods implemented by the RPC framework.  Each method name is prefixed with a double underscore "__".
type __Reserved interface {
	// Glob returns all entries matching the pattern.
	__Glob(pattern string) stream<any, any> error
	// MethodSignature returns the signature for the given method.
	__MethodSignature(method string) ("signature".Method | error)
	// Signature returns all interface signatures implemented by the object.
	__Signature() ([]"signature".Interface | error)
}

type "signature".Arg struct {
	Name string
	Doc string
	Type typeobject
}

type "signature".Embed struct {
	Name string
	PkgPath string
	Doc string
}

type "signature".Interface struct {
	Name string
	PkgPath string
	Doc string
	Embeds []"signature".Embed
	Methods []"signature".Method
}

type "signature".Method struct {
	Name string
	Doc string
	InArgs []"signature".Arg
	OutArgs []"signature".Arg
	InStream ?"signature".Arg
	OutStream ?"signature".Arg
	Tags []any
}

type "v.io/x/ref/cmd/vrpc/internal".Array2Int [2]int32

type "v.io/x/ref/cmd/vrpc/internal".Struct struct {
	X int32
	Y int32
}
`
	testSignature(t, true, wantSig)
}

func TestSignatureNoReserved(t *testing.T) {
	wantSig := `// TypeTester methods are listed in alphabetical order, to make it easier to
// test Signature output, which sorts methods alphabetically.
type "v.io/x/ref/cmd/vrpc/internal".TypeTester interface {
	// Methods to test support for primitive types.
	EchoBool(I1 bool) (O1 bool | error)
	EchoByte(I1 byte) (O1 byte | error)
	EchoFloat32(I1 float32) (O1 float32 | error)
	EchoFloat64(I1 float64) (O1 float64 | error)
	EchoInt32(I1 int32) (O1 int32 | error)
	EchoInt64(I1 int64) (O1 int64 | error)
	EchoString(I1 string) (O1 string | error)
	EchoUint32(I1 uint32) (O1 uint32 | error)
	EchoUint64(I1 uint64) (O1 uint64 | error)
	// Methods to test support for composite types.
	XEchoArray(I1 "v.io/x/ref/cmd/vrpc/internal".Array2Int) (O1 "v.io/x/ref/cmd/vrpc/internal".Array2Int | error)
	XEchoMap(I1 map[int32]string) (O1 map[int32]string | error)
	XEchoSet(I1 set[int32]) (O1 set[int32] | error)
	XEchoSlice(I1 []int32) (O1 []int32 | error)
	XEchoStruct(I1 "v.io/x/ref/cmd/vrpc/internal".Struct) (O1 "v.io/x/ref/cmd/vrpc/internal".Struct | error)
	// Methods to test support for different number of arguments.
	YMultiArg(I1 int32, I2 int32) (O1 int32, O2 int32 | error)
	YNoArgs() error
	// Methods to test support for streaming.
	ZStream(NumStreamItems int32, StreamItem bool) stream<_, bool> error
}

type "v.io/x/ref/cmd/vrpc/internal".Array2Int [2]int32

type "v.io/x/ref/cmd/vrpc/internal".Struct struct {
	X int32
	Y int32
}
`
	testSignature(t, false, wantSig)
}

func TestMethodSignature(t *testing.T) {
	ctx, name, shutdown := initTest(t)
	defer shutdown()

	tests := []struct {
		Method, Want string
	}{
		// Spot-check some individual methods.
		{"EchoByte", `EchoByte(I1 byte) (O1 byte | error)`},
		{"EchoFloat32", `EchoFloat32(I1 float32) (O1 float32 | error)`},
		{"XEchoStruct", `
XEchoStruct(I1 "v.io/x/ref/cmd/vrpc/internal".Struct) (O1 "v.io/x/ref/cmd/vrpc/internal".Struct | error)

type "v.io/x/ref/cmd/vrpc/internal".Struct struct {
	X int32
	Y int32
}
`},
	}
	for _, test := range tests {
		var stdout, stderr bytes.Buffer
		env := &cmdline.Env{Stdout: &stdout, Stderr: &stderr}
		if err := v23cmd.ParseAndRunForTest(cmdVRPC, ctx, env, []string{"signature", name, test.Method}); err != nil {
			t.Errorf("%q failed: %v", test.Method, err)
			continue
		}
		if got, want := strings.TrimSpace(stdout.String()), strings.TrimSpace(test.Want); got != want {
			t.Errorf("got stdout %q, want %q", got, want)
		}
		if got, want := stderr.String(), ""; got != want {
			t.Errorf("got stderr %q, want %q", got, want)
		}
	}
}

func TestCall(t *testing.T) {
	ctx, name, shutdown := initTest(t)
	defer shutdown()

	tests := []struct {
		Method, InArgs, Want string
	}{
		{"EchoBool", `true`, `true`},
		{"EchoBool", `false`, `false`},
		{"EchoFloat32", `1.2`, `float32(1.2)`},
		{"EchoFloat64", `-3.4`, `float64(-3.4)`},
		{"EchoInt32", `11`, `int32(11)`},
		{"EchoInt64", `-22`, `int64(-22)`},
		{"EchoString", `"abc"`, `"abc"`},
		{"EchoByte", `33`, `byte(33)`},
		{"EchoUint32", `44`, `uint32(44)`},
		{"EchoUint64", `55`, `uint64(55)`},
		{"XEchoArray", `{1,2}`, `"v.io/x/ref/cmd/vrpc/internal".Array2Int{1, 2}`},
		{"XEchoMap", `{1:"a"}`, `map[int32]string{1: "a"}`},
		{"XEchoSet", `{1}`, `set[int32]{1}`},
		{"XEchoSlice", `{1,2}`, `[]int32{1, 2}`},
		{"XEchoStruct", `{1,2}`, `"v.io/x/ref/cmd/vrpc/internal".Struct{X: 1, Y: 2}`},
		{"YMultiArg", `1,2`, `int32(1) int32(2)`},
		{"YNoArgs", ``, ``},
		{"ZStream", `2,true`, `<< true
<< true`},
	}
	for _, test := range tests {
		var stdout, stderr bytes.Buffer
		env := &cmdline.Env{Stdout: &stdout, Stderr: &stderr}
		if err := v23cmd.ParseAndRunForTest(cmdVRPC, ctx, env, []string{"call", name, test.Method, test.InArgs}); err != nil {
			t.Errorf("%q(%s) failed: %v", test.Method, test.InArgs, err)
			continue
		}
		if got, want := strings.TrimSpace(stdout.String()), strings.TrimSpace(test.Want); got != want {
			t.Errorf("got stdout %q, want %q", got, want)
		}
		if got, want := stderr.String(), ""; got != want {
			t.Errorf("got stderr %q, want %q", got, want)
		}
	}
}


text:
import picamera
from picamera import PiCamera
import time
from datetime import datetime
import os.path
from subprocess32 import Popen

print "\nSecurity Camera Logger v4 | Ben Broce & William Hampton\n"
print "Streams video to rtsp://pi-ip:8554/ | Captures to pics/[timestamp].jpg"
print "Ctrl-C quits.\n"

stream = raw_input("Should I stream video or take pictures (v/p)? ")
preview = raw_input("Should I display video preview on Pi (y/n)? ")

print "Running..."

#http://www.raspberry-projects.com/pi/pi-hardware/raspberry-pi-camera/streaming-video-using-vlc-player
#http://www.diveintopython.net/scripts_and_streams/stdin_stdout_stderr.html
#Ouput video (record) => stream => stdout => | => cvlc livestream => browser

if (stream == "v" or stream == "V"):
	try:
		live = Popen(["./livestream.sh"])
	finally:
		print "\n\nExiting..."
		live.terminate()
elif (stream == "p" or stream == "P"):
	length = float(raw_input("How long should I run (in minutes): "))*60
	interval = float(raw_input("How often should I take a picture (in seconds): "))

	camera = PiCamera()
	camera.annotate_background = picamera.Color('black')
	camera.rotation = 180
	camera.resolution = (640, 480)

	counter = 0

	try:
		if (preview == "y" or preview == "Y"):
			camera.start_preview()
		while (counter <= length):
			timestamp = datetime.now().strftime("%m-%d-%Y_%H:%M:%S")
			camera.annotate_text = timestamp
			path = 'pics/' + timestamp + '.jpg'
			camera.capture(path, use_video_port=True)
			time.sleep(interval)
			counter += interval
	finally:
		print "Exiting..."
		if (preview == "y" or preview == "Y"):
			camera.stop_preview()
else:
	print "Invalid input!"


text:
(* ::Package:: *)

(* Mathematica Init File *)

Get[ "NounouM2`NounouM2`"]

Needs[ "JLink`"];
(*SetOptions[JLink`InstallJava, JVMArguments -> "-Xmx1024m"];
SetOptions[JLink`ReinstallJava, JVMArguments -> "-Xmx1024m"];
ReinstallJava[];*)

NounouM2`IncreaseJavaStack[stackSize_Integer]:=
	Module[{tempOptStringI,tempOptStringR,tempReI=False, tempReR=False,
		tempPrint, tempns},

		tempPrint=PrintTemporary["Checking Java stack size..."];

    	(*Extract the stack settings for InstallJava*)
		tempOptStringI=OptionValue[JLink`InstallJava, JLink`JVMArguments];
		If[tempOptStringI===None, tempReI=True,
		If[Head[tempOptStringI]===String,
			tempOptStringI=StringCases[tempOptStringI,"-"~~Shortest[__]~~tempns:NumberString..~~"m"->tempns];
			If[Length[tempOptStringI]>=1,
				tempOptStringI=ToExpression[tempOptStringI[[1]]];
				If[tempOptStringI<stackSize,tempReI=True]
			];
		]];

    	(*Extract the stack settings for ReinstallJava*)
		tempOptStringR=OptionValue[JLink`ReinstallJava, JLink`JVMArguments];
		If[tempOptStringR===None, tempReR=True,
		If[Head[tempOptStringR]===String,
			tempOptStringR=StringCases[tempOptStringR,"-"~~Shortest[__]~~tempns:NumberString..~~"m"->tempns];
			If[Length[tempOptStringR]>=1,
				tempOptStringR=ToExpression[tempOptStringR[[1]]];
				If[tempOptStringR<stackSize,tempReR=True]
			];
		]];

		(*Change and ReinstallJava as necessary*)
		If[tempReI,
			SetOptions[JLink`InstallJava, JLink`JVMArguments -> "-Xmx"<>ToString[stackSize]<>"m"]
		];
		If[tempReR,
			SetOptions[JLink`ReinstallJava, JLink`JVMArguments -> "-Xmx"<>ToString[stackSize]<>"m"]
		];
		If[tempReI || tempReR,
			JLink`ReinstallJava[];
			Print["<<Set JLink` java stack size to "<>ToString[stackSize]<>"Mb>>"];
		];

		NotebookDelete[tempPrint];
	]; (*Module for KKMInstallJava*)

NounouM2`IncreaseJavaStack[6144];

(*Convenience object for static methods*)
NN=LoadJavaClass["nounou.NN"(*, StaticsVisible\[Rule]True*)];
NounouM2`$NNReader::usage="Main default reader object for NounouM2.";
NounouM2`$NNReader = NN`newReader[];

SetComplexClass["breeze.math.Complex"];

Needs["NounouM2`Plotting`"];

Needs["NounouM2`DataPlotting`"];

(*LoadJavaClass["de.ifn_magdeburg.kazukazuj.K"];
LoadJavaClass["de.ifn_magdeburg.kazukazuj.Kc"];
LoadJavaClass["de.ifn_magdeburg.kazukazuj.Ks"];
SetComplexClass["de.ifn_magdeburg.kazukazuj.Complex"];*)

(*Needs[ "KazukazuM`KazukazuM`"];
Needs[ "KazukazuM`Signal`"];
Needs[ "KazukazuM`Filters`"];
Needs[ "KazukazuM`CircularStatistics`"];
Needs[ "KazukazuM`Utilities`"];
Needs[ "KazukazuM`Plots`"];
Needs["KazukazuM`CircularPlots`"];
(*Needs["KazukazuM`ImageAnalysis`"];*)
DeclarePackage["KazukazuM`Heartbeat`",
	{"LocalMaxPositions","LocalMinPositions",
	"HeartbeatTrigger", "TriggeredAverage",
	"TriggeredAverageTrace","HeartbeatSubtract"}];*)


text:
import twython, time, pprint, traceback, os, sys
import config
from twython import TwythonStreamer, TwythonError, TwythonRateLimitError
import urllib, json, glob, re
import thread
queuelock = thread.allocate_lock()
watchlock = thread.allocate_lock()
import logging
logging.basicConfig(filename='highearthorbit.log', format='%(asctime)s %(levelname)s %(message)s')
log = logging.getLogger(__name__)
log.setLevel(logging.INFO)

"""
Config: create a file named config.py with these lines:

app_key="<your app key>"
app_secret="<your app secret>"
oauth_token="<your oauth token>"
oauth_token_secret="<your oauth token secret"
owner="<twitter name of owner>"

All keys, secrets and tokens are creatable on http://apps.twitter.com

Run: until I implement a better solution, run it in a screen session

"""

lasttry=0
rts = []
_queue = []
_fail = {}
_done = {}
friends = []
listmembers = []
blocked = []
twitter = None
user_screenname = ''

def update_friends(friendlist):
    global friends
    friends = friendlist
    log.info("Updated friends", friends)

def update_approved_list():
    global listmembers
    try:
        listmembers = [ user["id"] for user in twitter.get_list_members(slug=config.approved_list['name'], owner_screen_name=config.approved_list['owner'])["users"] ]
        log.info("Updated members of list %s by @%s: %s", (config.approved_list['name'], config.approved_list['owner'], str(listmembers)))
    except:
        log.warning("Error updating list %s by @%s." % (config.approved_list['name'], config.approved_list['owner']))

def find_and_delete_blocked_retweets():
    global blocked
    log.info("Checking the last 100 tweets in my timeline for retweets of blocked users. Just to destroy them.")
    try:
        tl = twitter.get_user_timeline(screen_name=user_screenname, count=100)
    except:
        log.error('Exception caught while checking for tweets of blocked users.')
    else:
        for t in tl:
            if 'retweeted_status' in t and t['retweeted_status']['user']['id'] in blocked:
                queue(twitter.destroy_status, id=t['id'])
                log.info('Will destroy status %s, because @%s is blocked.' % (t['id'], t['retweeted_status']['user']['screen_name']))
                for archived_file in glob.glob(os.path.join(config.archive_dir, '*', t['retweeted_status']['id_str']) + '-*.*'):
                    try:
                        os.remove(archived_file)
                    except:
                        log.warning("Unable to delete archive file %s" % archived_file)
                    else:
                        log.info("Removed archive file %s" % archived_file)

def update_block_list():
    global blocked
    old_blocked = blocked
    try:
        blocked = twitter.list_block_ids()['ids']
        log.info("Updated block list.")
    except Exception as e:
        log.warning("Could not update block list: %s", str(e))
    new = list(set(blocked) - set(old_blocked))
    if len(new) > 0:
        find_and_delete_blocked_retweets()

def cleanrts():
    for r in rts:
        m,t = r
        if t < time.time() - 3600:
            rts.remove(r)

def _fmt(func, args, kwargs):
    return "%s(%s)" % (func.__name__, ', '.join([ a for a in args ] + [ "%s=%s" % (k, repr(v)) for k,v in kwargs.iteritems() ]))

def run_queue():
    global _done, _queue, _fail, twitter
    with queuelock:
        t = int(time.time())
        _done = dict([ (k,v) for k,v in _done.iteritems() if k > t - 86400 ])
        _fail = dict([ (k,v) for k,v in _fail.iteritems() if k > t - 3600 ])
    log.info('Running queue (%s actions). Actions during last 24h: %s/last 15m: %s, Fails in the last 60m: %s.' % (len(_queue), len(_done), len([ k for k,v in _done.iteritems() if k > t - 900 ]), len(_fail)))
    with queuelock:
        while len(_queue) > 0 and twitter is not None:
            t = int(time.time())
            if len([ k for k,v in _done.iteritems() if k > t - 900 ]) + len([ k for k,v in _fail.iteritems() if k > t - 900 ]) >= config.rate_limit_per_15min:
                log.warn("Rate Limit reached. Currently not working on the %s items in the queue." % len(_queue))
                break
            if len(_fail) > 15:
                log.error("Fail Limit reached. Killing everything.")
                thread.interrupt_main()
            (tries, (func, args, kwargs)) = _queue.pop(0)
            if not (func, args, kwargs) in _done.values():
                try:
                    log.debug("Trying %s from queue" % _fmt(func, args, kwargs))
                    if not config.twitter_is_read_only:
                        func(*args, **kwargs)
                except Exception as e:
                    if isinstance(e, TwythonError) and e.error_code == 403:
                        log.warn("Twitter says I did %s already." % _fmt(func, args, kwargs))
                        #_fail[t] = (func, args, kwargs)
                    elif isinstance(e, TwythonRateLimitError):
                        log.warn("Twitter says I hit the Rate Limit with %s. Re-queuing." % _fmt(func, args, kwargs))
                        _queue.insert(0, (tries, (func, args, kwargs)) )
                        if e.retry_after is not None:
                            log.warn("Keeping queue lock until I slept for %s seconds." % e.retry_after)
                            time.sleep(int(e.retry_after))
                    elif tries < 3:
                        log.error("Error while running queue item %s: %s" % (_fmt(func, args, kwargs), str(e)), exc_info=True)
                        _queue.append( (tries+1, (func, args, kwargs)) )
                        _fail[t] = (func, args, kwargs)
                        log.warn("Try #%s of %s from queue failed, re-queuing." % (tries+1, _fmt(func, args, kwargs)))
                        log.warn("Reinitializing twitter connection except streaming.")
                        twitter = twython.Twython(app_key=config.app_key, app_secret=config.app_secret, oauth_token=config.oauth_token, oauth_token_secret=config.oauth_token_secret)
                    else:
                        log.error("Tried 3 times, but always got an exception... giving up on %s" % _fmt(func, args, kwargs))
                else:
                    _done[t] = (func, args, kwargs)
                    log.info("%s is done." % _fmt(func, args, kwargs))
            else:
                log.warn("I already had that one in my queue: %s" % _fmt(func, args, kwargs))
            time.sleep(5)

def queuewatch(check_time=900):
    if watchlock.acquire(0):
        while True:
            time.sleep(check_time)
            log.debug("It's time to check the queue for any forgotten actions. (interval=%ss)" % check_time)
            try:
                update_block_list()
                run_queue()
            except Exception as e:
                log.warning("Exception in watchdog thread: ", e)
        watchlock.release()

def queue(func, *args, **kwargs):
    global _queue
    _queue.append( (0, (func, args, kwargs)) )
    log.debug("Queued %s." % _fmt(func, args, kwargs))

def rt(tweetid):
    cleanrts()
    if twitter is not None:
        if not tweetid in [ m for m,t in rts ]:
            log.info("Will retweet id %s" % tweetid)
            queue(twitter.retweet, id=tweetid)
            rts.append( (tweetid, time.time(), ) )
        else:
            log.info("Tweet id %s has been retweeted already." % tweetid)

def tweet(tweettext):
    if twitter is not None:
        queue(twitter.update_status, status=tweettext[0:140])

def download_media(data, filename):
    datadict = data['entities']
    if 'extended_entities' in data and 'media' in data['extended_entities']:
        datadict = data['extended_entities']
    if 'extended_tweet' in data:
        if 'entities' in data['extended_tweet'] and 'media' in data['extended_tweet']['entities']:
            datadict = data['extended_tweet']['entities']
        if 'extended_entities' in data['extended_tweet'] and 'media' in data['extended_tweet']['extended_entities']:
            datadict = data['extended_tweet']['extended_entities']

    for index,mediadata in enumerate(datadict['media']):
        mediafile = '.'.join((filename, str(index), mediadata['media_url_https'].split('.')[-1]))
        mediaurl = ':'.join((mediadata['media_url_https'], 'orig'))
        if 'type' in mediadata and mediadata['type'] == 'photo':
            try:
                urllib.URLopener().retrieve(mediaurl, mediafile)
                log.info("Archived media: %s -> %s from tweet %s." % (mediaurl, mediafile, data['id']))
            except Exception as e:
                log.error("Archive image cannot be downloaded from %s or created in %s: %s" % (mediaurl, mediafile, str(e)))

def save(data):
    user = data['retweeted_status']['user'] if 'retweeted_status' in data else data['user']
    basedirname = os.path.join(config.archive_dir, data['id_str'][:-15].zfill(6))
    basefilename = '-'.join((data['id_str'], user['screen_name']))
    filename = os.path.join(basedirname, basefilename)
    if os.path.isfile(filename + '.json'):
        log.warn("Archive file %s.json for tweet %s already exists." % (filename, data['id']))
        return
    try:
        if not os.path.isdir(basedirname):
            os.makedirs(basedirname)
    except Exception as e:
        log.error("Archive directory %s cannot be created or is not writable: %s" % (basedirname, str(e)))
        return
    try:
        with open(filename + '.json', 'w') as f:
            json.dump(data, f, indent=4)
        log.info("Archived tweet %s to %s.json" % (data['id'], filename))
    except Exception as e:
        log.error("Archive file %s cannot be created or is not writable: %s" % (filename + '.json', str(e)))
        return
    if config.archive_photos and 'media' in data['entities']:
        download_media(data, filename)

def is_spam(data):
    log.info("%s @%s: %s" % (data['id'], data['user']['screen_name'], data['text'].replace('\n', ' ')))
    text = data['text'].strip()
    if not any(hashtag in text.lower() for hashtag in config.track.lower().split(" or ")):
        log.info("Retweet did not contain our search, assuming spam.")
        return True
    if text.startswith('"') and text.endswith('"'):
        log.info("Looks like a quoted Tweet, assuming tweet stealing.")
        return True
    if re.search(r'rt\W+@\w+\W*[:"]', text, re.IGNORECASE) is not None:
        log.info("Looks like a manual retweet, assuming tweet stealing.")
        return True
    if len(data['entities']['hashtags']) > config.spamfilter_max_hashtags:   	# Too many hashtags?
        log.info("Munched some Spam: Too many Hashtags. Not retweeting %s." % data['id'])
        return True
    if any(word.lower() in text.lower() for word in config.spamfilter_word_blacklist):	# Blacklisted words?
        log.info("This list of words is black. It contains %s, which is why I won't retweet %s." % (str([word for word in config.spamfilter_word_blacklist if word in data['text']]), data['id']))
        return True
    return False

def decide(data):
    if 'extended_tweet' in data and 'full_text' in data['extended_tweet']:
        data['text'] = data['extended_tweet']['full_text']
    if 'full_text' in data:
        data['text'] = data['full_text']
    if config.archive_own_retweets_only and 'retweeted_status' in data and data['user']['screen_name'] == user_screenname:
        log.info("%s @%s: %s" % (data['id'], data['user']['screen_name'], data['text'].replace('\n', ' ')))
        # I only save my own retweets for the archive. This allows the webviewer to "dumb-detect" that
        # a Retweet by the Bot has been destroyed manually from the Botaccount.
        save(data)
    elif 'retweeted_status' in data:
        # Normal retweets are only logged in debug level, else dropped silently.
        log.debug("Retweet received: %s @%s: %s" % (data['id'], data['user']['screen_name'], data['text'].replace('\n', ' ')))
        return
    elif is_spam(data):
        # If it's spam, the function is_spam() has already logged a message. We're just walking away.
        return
    elif 'text' in data:
        # Hey, something came in! Maybe it's interesting?
        #log.info("%s @%s: %s" % (data['id'], data['user']['screen_name'], data['text'].replace('\n', ' ')))
        if data['user']['id'] in blocked:
            # If we blocked someone, we don't want to read him. Twitter, why do I keep getting that blockhead in my search results?
            log.info('Not retweeting id %s because user @%s is blocked.' % (data['id'], data['user']['screen_name']))
        #elif data['text'].lower().find(config.track.lower()) > -1 and not 'retweeted_status' in data:
        elif not 'retweeted_status' in data:
            # Whohoo! A tweet that actually contains our Hashtag and is not a retweet!
            rt(data['id'])
            if not config.archive_own_retweets_only:
                # I save everything I can get. Okay, archiving photos are configured elsewhere.
                save(data)
    elif 'direct_message' in data:
        # Currently dead code because this type of message is not available in a "site stream".
        # To enable this, this Bot also needs to follow the "user stream" in another thread.
        update_approved_list()
        log.info("DM from @%s: %s" % (data['direct_message']['sender']['screen_name'], data['direct_message']['text']))
        if data['direct_message']['sender']['id'] in listmembers:
            tweet(data['direct_message']['text'])
    elif 'friends' in data:
        # Currently dead code because this type of message is not available in a "site stream".
        # To enable this, this Bot also needs to follow the "user stream" in another thread.
        update_friends(data['friends'])
    else:
        # Currently dead code because this type of message is not available in a "site stream".
        # To enable this, this Bot also needs to follow another stream in another thread.
        log.warning("Unknown notification received:")
        log.warning(data)

class MyStreamer(TwythonStreamer):
    def on_success(self, data):
        decide(data)
        thread.start_new_thread(run_queue, ())

    def on_error(self, status_code, data):
        log.error("Error Code %s received in data package:" % status_code)
        log.error(data)

        if status_code == 503:
            log.error("Waiting 10 minutes, then this bot restarts internally... hopefully finding all missed tweets then.")
            time.sleep(600)
            self.disconnect()

if __name__ == "__main__":
    readback = config.read_back
    if '--quick' in sys.argv:
        readback = 10
        log.info("------ Quick start, reading only 10 tweets back")
    while True:
        try:
            log.info("====== Entering High Earth Orbit in the Twitterverse... ehm. Okay, okay, I'm initializing. ======")
            twitter = twython.Twython(app_key=config.app_key, app_secret=config.app_secret, oauth_token=config.oauth_token, oauth_token_secret=config.oauth_token_secret)
            creds = twitter.verify_credentials()
            #userstream = MyStreamer(config.app_key, config.app_secret, config.oauth_token, config.oauth_token_secret)
            #userstream.creds = creds
            filterstream = MyStreamer(config.app_key, config.app_secret, config.oauth_token, config.oauth_token_secret)
            filterstream.creds = creds
            userid = creds['id_str']
            user_screenname = creds['screen_name']

            update_approved_list()
            update_block_list()

            log.info('Reading last retweets.')
            rts += [ (t['retweeted_status']['id'], time.time(),) for t in twitter.get_user_timeline(screen_name=user_screenname, count=readback) if 'retweeted_status' in t ]
            for a in (1,2):
                time.sleep((a-1)*10)
                log.info("Catching up on missed tweets, take %s." % a)
                old_tweets = twitter.search(q=config.track + " -filter:retweets", count=readback-5, tweet_mode='extended')['statuses']
                for t in sorted(old_tweets, key=lambda t: t['id']):
                    decide(t)

            log.info('Caught up on missed tweets, running queue.')
            thread.start_new_thread(run_queue, ())
            thread.start_new_thread(queuewatch, (900,))

            log.info('Going into streaming mode')
            filterstream.statuses.filter(track=[t.strip() for t in config.track.lower().split(' or ')])

        except Exception, e:
            log.warning('==Exception caught, restarting in 15 minutes==')
            log.warning(str(e), exc_info=True)
            time.sleep(900)
        readback = config.read_back


text:
<?php

/**
 * Generic Blipoteka service class
 *
 * @author Jakub Argasiński <argasek@gmail.com>
 *
 */
abstract class Blipoteka_Service {
	/**
	 * Any service record class must inherit this class
	 * @var string
	 */
	const SERVICE_PARENT_CLASS = 'Void_Doctrine_Record';

	/**
	 * Class of the record this service applies to
	 * @var string
	 */
	protected $_recordClass = '';

	/**
	 * Users table
	 * @var Doctrine_Table
	 */
	protected $_table;

	/**
	 * Default query object
	 * @var Doctrine_Query
	 */
	protected $_query;

	/**
	 * Request object
	 * @var Zend_Controller_Request_Abstract
	 */
	protected $_request;

	/**
	 * The constructor
	 */
	public function __construct(Zend_Controller_Request_Abstract $request = null) {
		if (is_subclass_of($this->_recordClass, self::SERVICE_PARENT_CLASS)) {
			$this->_table = Doctrine_Core::getTable($this->_recordClass);
			$this->_query = Doctrine_Query::create()->from($this->_recordClass);
		} else {
			throw new LogicException('The $_recordClass class should be a class being child of ' .  self::SERVICE_PARENT_CLASS);
		}

		if ($request instanceof Zend_Controller_Request_Abstract) {
			$this->_request = $request;
		} else {
			$this->_request = Zend_Controller_Front::getInstance()->getRequest();
		}
	}

}


text:
// <copyright file="Root.cs" company="Heleonix - Hennadii Lutsyshyn">
// Copyright (c) 2017-present Heleonix - Hennadii Lutsyshyn. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the repository root for full license information.
// </copyright>

namespace Heleonix.Utilities.Tests.Common.Dummies
{
    /// <summary>
    /// The root type.
    /// </summary>
    public class Root
    {
#pragma warning disable CA1051 // Do not declare visible instance fields
#pragma warning disable SA1401 // Fields must be private
#pragma warning disable S1104 // Fields should not have public accessibility
        /// <summary>
        /// Gets or sets the sub item field.
        /// </summary>
        public SubItem SubItemField = new SubItem();
#pragma warning restore S1104 // Fields should not have public accessibility
#pragma warning restore SA1401 // Fields must be private
#pragma warning restore CA1051 // Do not declare visible instance fields

        /// <summary>
        /// Gets or sets the static sub item property.
        /// </summary>
        public static SubItem StaticSubItemProperty { get; set; } = new SubItem();

        /// <summary>
        /// Gets or sets the sub item property.
        /// </summary>
        public SubItem SubItemProperty { get; set; } = new SubItem();
    }
}


text:
from __future__ import absolute_import

import pytest
import time

from sentry.digests import Record
from sentry.digests.backends.base import InvalidState
from sentry.digests.backends.redis import RedisBackend
from sentry.testutils import TestCase

from six.moves import xrange

class RedisBackendTestCase(TestCase):
    def test_basic(self):
        backend = RedisBackend()

        # The first item should return "true", indicating that this timeline
        # can be immediately dispatched to be digested.
        record_1 = Record("record:1", "value", time.time())
        assert backend.add("timeline", record_1) is True

        # The second item should return "false", since it's ready to be
        # digested but dispatching again would cause it to be sent twice.
        record_2 = Record("record:2", "value", time.time())
        assert backend.add("timeline", record_2) is False

        # There's nothing to move between sets, so scheduling should return nothing.
        assert set(backend.schedule(time.time())) == set()

        with backend.digest("timeline", 0) as records:
            assert set(records) == set([record_1, record_2])

        # The schedule should now contain the timeline.
        assert set(entry.key for entry in backend.schedule(time.time())) == set(["timeline"])

        # We didn't add any new records so there's nothing to do here.
        with backend.digest("timeline", 0) as records:
            assert set(records) == set([])

        # There's nothing to move between sets since the timeline contents no
        # longer exist at this point.
        assert set(backend.schedule(time.time())) == set()

    def test_truncation(self):
        backend = RedisBackend(capacity=2, truncation_chance=1.0)

        records = [Record(u"record:{}".format(i), "value", time.time()) for i in xrange(4)]
        for record in records:
            backend.add("timeline", record)

        with backend.digest("timeline", 0) as records:
            assert set(records) == set(records[-2:])

    def test_maintenance_failure_recovery(self):
        backend = RedisBackend()

        record_1 = Record("record:1", "value", time.time())
        backend.add("timeline", record_1)

        try:
            with backend.digest("timeline", 0) as records:
                raise Exception("This causes the digest to not be closed.")
        except Exception:
            pass

        # Maintenance should move the timeline back to the waiting state, ...
        backend.maintenance(time.time())

        # ...and you can't send a digest in the waiting state.
        with pytest.raises(InvalidState):
            with backend.digest("timeline", 0) as records:
                pass

        record_2 = Record("record:2", "value", time.time())
        backend.add("timeline", record_2)

        # The schedule should now contain the timeline.
        assert set(entry.key for entry in backend.schedule(time.time())) == set(["timeline"])

        # The existing and new record should be there because the timeline
        # contents were merged back into the digest.
        with backend.digest("timeline", 0) as records:
            assert set(records) == set([record_1, record_2])

    def test_maintenance_failure_recovery_with_capacity(self):
        backend = RedisBackend(capacity=10, truncation_chance=0.0)

        t = time.time()

        # Add 10 items to the timeline.
        for i in xrange(10):
            backend.add("timeline", Record(u"record:{}".format(i), u"{}".format(i), t + i))

        try:
            with backend.digest("timeline", 0) as records:
                raise Exception("This causes the digest to not be closed.")
        except Exception:
            pass

        # The 10 existing items should now be in the digest set (the exception
        # prevented the close operation from occurring, so they were never
        # deleted from Redis or removed from the digest set.) If we add 10 more
        # items, they should be added to the timeline set (not the digest set.)
        for i in xrange(10, 20):
            backend.add("timeline", Record(u"record:{}".format(i), u"{}".format(i), t + i))

        # Maintenance should move the timeline back to the waiting state, ...
        backend.maintenance(time.time())

        # The schedule should now contain the timeline.
        assert set(entry.key for entry in backend.schedule(time.time())) == set(["timeline"])

        # Only the new records should exist -- the older one should have been
        # trimmed to avoid the digest growing beyond the timeline capacity.
        with backend.digest("timeline", 0) as records:
            expected_keys = set(u"record:{}".format(i) for i in xrange(10, 20))
            assert set(record.key for record in records) == expected_keys

    def test_delete(self):
        backend = RedisBackend()
        backend.add("timeline", Record("record:1", "value", time.time()))
        backend.delete("timeline")

        with pytest.raises(InvalidState):
            with backend.digest("timeline", 0) as records:
                assert set(records) == set([])

        assert set(backend.schedule(time.time())) == set()
        assert len(backend._get_connection("timeline").keys("d:*")) == 0

    def test_missing_record_contents(self):
        backend = RedisBackend()

        record_1 = Record("record:1", "value", time.time())
        backend.add("timeline", record_1)
        backend._get_connection("timeline").delete("d:t:timeline:r:record:1")

        record_2 = Record("record:2", "value", time.time())
        backend.add("timeline", record_2)

        # The existing and new record should be there because the timeline
        # contents were merged back into the digest.
        with backend.digest("timeline", 0) as records:
            assert set(records) == set([record_2])

    def test_large_digest(self):
        backend = RedisBackend()

        n = 8192
        t = time.time()
        for i in xrange(n):
            backend.add("timeline", Record(u"record:{}".format(i), u"{}".format(i), t))

        with backend.digest("timeline", 0) as records:
            assert len(set(records)) == n


text:
<?xml version="1.0" encoding="UTF-8"?>
<resources xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
    <string name="app_label" msgid="8016145283189546017">"Amadivayisi wokufaka"</string>
    <string name="keyboard_layouts_label" msgid="6688773268302087545">"Ikhibhodi ye-Android"</string>
    <string name="keyboard_layout_english_uk_label" msgid="6664258463319999632">"I-English (UK)"</string>
    <string name="keyboard_layout_english_us_label" msgid="8994890249649106291">"I-English (US)"</string>
    <string name="keyboard_layout_english_us_intl" msgid="3705168594034233583">"I-English (US), isitayela sakwamanye amazwe"</string>
    <string name="keyboard_layout_english_us_colemak_label" msgid="4194969610343455380">"I-English (US), isitayela se-Colemak"</string>
    <string name="keyboard_layout_english_us_dvorak_label" msgid="793528923171145202">"I-English (US), isitayela se-Dvorak"</string>
    <string name="keyboard_layout_german_label" msgid="8451565865467909999">"Isi-German"</string>
    <string name="keyboard_layout_french_label" msgid="813450119589383723">"Isi-French"</string>
    <string name="keyboard_layout_french_ca_label" msgid="365352601060604832">"Isi-French (Canada)"</string>
    <string name="keyboard_layout_russian_label" msgid="8724879775815042968">"Isi-Russian"</string>
    <string name="keyboard_layout_russian_mac_label" msgid="3795866869038264796">"Isi-Russian, isitayela se-Mac"</string>
    <string name="keyboard_layout_spanish_label" msgid="7091555148131908240">"Isi-Spanish"</string>
    <string name="keyboard_layout_swiss_french_label" msgid="4659191025396371684">"Isi-Swiss French"</string>
    <string name="keyboard_layout_swiss_german_label" msgid="2305520941993314258">"Isi-Swiss German"</string>
    <string name="keyboard_layout_belgian" msgid="2011984572838651558">"Isi-Belgian"</string>
    <string name="keyboard_layout_bulgarian" msgid="8951224309972028398">"Isi-Bulgarian"</string>
    <string name="keyboard_layout_italian" msgid="6497079660449781213">"Isi-Italian"</string>
    <string name="keyboard_layout_danish" msgid="8036432066627127851">"Isi-Danish"</string>
    <string name="keyboard_layout_norwegian" msgid="9090097917011040937">"Isi-Norwegian"</string>
    <string name="keyboard_layout_swedish" msgid="732959109088479351">"Isi-Swedish"</string>
    <string name="keyboard_layout_finnish" msgid="5585659438924315466">"Isi-Finnish"</string>
    <string name="keyboard_layout_croatian" msgid="4172229471079281138">"Isi-Croatian"</string>
    <string name="keyboard_layout_czech" msgid="1349256901452975343">"Isi-Czech"</string>
    <string name="keyboard_layout_estonian" msgid="8775830985185665274">"Isi-Estonian"</string>
    <string name="keyboard_layout_hungarian" msgid="4154963661406035109">"Isi-Hungarian"</string>
    <string name="keyboard_layout_icelandic" msgid="5836645650912489642">"Isi-Icelandic"</string>
    <string name="keyboard_layout_brazilian" msgid="5117896443147781939">"Isi-Brazilian"</string>
    <string name="keyboard_layout_portuguese" msgid="2888198587329660305">"Isi-Portuguese"</string>
    <string name="keyboard_layout_slovak" msgid="2469379934672837296">"Isi-Slovak"</string>
    <string name="keyboard_layout_slovenian" msgid="1735933028924982368">"Isi-Slovenian"</string>
    <string name="keyboard_layout_turkish" msgid="7736163250907964898">"Isi-Turkish"</string>
    <string name="keyboard_layout_ukrainian" msgid="8176637744389480417">"Isi-Ukrainian"</string>
    <string name="keyboard_layout_arabic" msgid="5671970465174968712">"Isi-Arabic"</string>
    <string name="keyboard_layout_greek" msgid="7289253560162386040">"Isi-Greek"</string>
    <string name="keyboard_layout_hebrew" msgid="7241473985890173812">"Isi-Hebrew"</string>
    <string name="keyboard_layout_lithuanian" msgid="6943110873053106534">"Isi-Lithuanian"</string>
    <string name="keyboard_layout_spanish_latin" msgid="5690539836069535697">"Isi-Spanish (Latin)"</string>
    <string name="keyboard_layout_latvian" msgid="4405417142306250595">"Isi-Latvian"</string>
</resources>


text:
FROM digitallyseamless/nodejs-bower-grunt

MAINTAINER Victor Wibisono <devacto@gmail.com>

# Install image libs
ONBUILD RUN apt-get update && \
            apt-get install -y graphicsmagick imagemagick && \
            apt-get clean && \
            rm -rf /var/lib/apt/lists/* /tmp/* /var/tmp/*

# Expose port
EXPOSE 9000

# Mount volume
VOLUME /app

# Set working directory
WORKDIR /app

# Set instructions on build
# The following two instructions have to be executed in the /app directory
ONBUILD RUN npm install
ONBUILD RUN bower install --allow-root --config.interactive=false


text:
package io.appium.java_client.touch.offset;

import io.appium.java_client.touch.ActionOptions;
import org.openqa.selenium.Point;

import java.util.Map;

import static java.util.Optional.ofNullable;

public class PointOption<T extends PointOption<T>> extends ActionOptions<T> {

    protected Point coordinates;

    /**
     * It creates a built instance of {@link PointOption} which takes x and y coordinates.
     * This is offset from the upper left corner of the screen.
     *
     * @param offset is an offset value.
     * @return a built option
     */
    public static PointOption point(Point offset) {
        return new PointOption().withCoordinates(offset);
    }

    /**
     * It creates a built instance of {@link PointOption} which takes x and y coordinates.
     * This is offset from the upper left corner of the screen.
     *
     * @param xOffset is x value.
     * @param yOffset is y value.
     * @return a built option
     */
    public static PointOption point(int xOffset, int yOffset) {
        return new PointOption().withCoordinates(xOffset, yOffset);
    }

    /**
     * It defines x and y coordinates.
     * This is offset from the upper left corner of the screen.
     *
     * @param offset is an offset value.
     * @return self-reference
     */
    public T withCoordinates(Point offset) {
        return withCoordinates(offset.x, offset.y);
    }

    /**
     * It defines x and y coordinates.
     * This is offset from the upper left corner of the screen.
     *
     * @param xOffset is x value.
     * @param yOffset is y value.
     * @return self-reference
     */
    public T withCoordinates(int xOffset, int yOffset) {
        coordinates = new Point(xOffset, yOffset);
        //noinspection unchecked
        return (T) this;
    }

    @Override
    protected void verify() {
        //noinspection ResultOfMethodCallIgnored
        ofNullable(coordinates).orElseThrow(() -> new IllegalArgumentException(
                "Coordinate values must be defined"));
    }

    @Override
    public Map<String, Object> build() {
        final Map<String, Object> result = super.build();
        result.put("x", coordinates.x);
        result.put("y", coordinates.y);
        return result;
    }
}


text: export { ChartMedian16 as default } from "../../";


text:
package org.apache.ode.jbi;

import javax.jbi.messaging.MessageExchange;
import javax.jbi.messaging.MessagingException;

public interface JbiMessageExchangeProcessor {

	public void onJbiMessageExchange(MessageExchange mex)
			throws MessagingException;
}


text:
package com.magicbox.redio.network.packets;

import io.netty.buffer.ByteBuf;

/* @formatter:off */
public interface IPacketProtocol
{
	public int getPacketId();
	public void readData(ByteBuf buffer);
	public void writeData(ByteBuf buffer);
}


text:
<?php

namespace Sylius\Component\Variation\Model;

use Doctrine\Common\Collections\Collection;
use Sylius\Component\Resource\Model\TimestampableInterface;

/**
 * Object option translation interface.
 *
 * @author Gonzalo Vilaseca <gvilaseca@reiss.co.uk>
 */
interface OptionTranslationInterface
{
    /**
     * The name displayed to user.
     *
     * @return string
     */
    public function getPresentation();

    /**
     * Set presentation.
     *
     * @param string $presentation
     */
    public function setPresentation($presentation);
}


text:
from config import GRID
from utils import (get_table, get_structure,
                   max_cell_length, gen_rows,
                   gen_header, get_rows)

class Table(object):
    """
    Generates table from given source
    """
    def __init__(self, source, type=GRID):
        self.source = source
        self.type = type

    def table(self):
        table = get_table(self.source)[0]
        return table

    def __repr__(self):
        return '<%s %s>' % (self.__class__.__name__,
                            self.table()
        )

    def __str__(self):
        return self.table()

    def structure(self):
        """
        Structure of table
        """
        return get_structure(self.source)

    def max_cell_len(self, column):
        return max_cell_length(self.structure(), column)

    @property
    def header(self):
        return Header(self)

    @property
    def rows(self):
        rows = get_rows(self.table())
        check = lambda: all(len(x.split()) == len(self.header.split())
                            for x in rows)
        if check:
            return rows
        raise ValueError("Please check your table. You have different number"
                         "of columns for each row of the table")

    def create(self):
        return self.header.to_rst() + gen_rows(self)

class Header(object):
    """
    Header class
    """
    def __init__(self, table):
        self.table = table
        self.header = table.rows[0]

    def __str__(self):
        return self.header

    def __repr__(self):
        return self.__str__()

    def split(self):
        return self.header.split()

    def to_rst(self):
        return gen_header(self.table)


text:
using System;
using System.Collections;
using System.Reflection;
using log4net;
using Nini.Config;
using Mono.Addins;
using OpenMetaverse;
using OpenMetaverse.StructuredData;
using OpenSim.Framework;
using OpenSim.Framework.Servers.HttpServer;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Region.Framework.Scenes;
using OpenSim.Services.Interfaces;
using Caps = OpenSim.Framework.Capabilities.Caps;

namespace OpenSim.Region.ClientStack.Linden
{
    /// <summary>
    /// MeshUploadFlag capability. This is required for uploading Mesh.
    /// </summary>
    [Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "MeshUploadFlagModule")]
    public class MeshUploadFlagModule : INonSharedRegionModule
    {
//        private static readonly ILog m_log =
//            LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);

        /// <summary>
        /// Is this module enabled?
        /// </summary>
        public bool Enabled { get; private set; }

        private Scene m_scene;

        #region ISharedRegionModule Members

        public MeshUploadFlagModule()
        {
            Enabled = true;
        }

        public void Initialise(IConfigSource source)
        {
            IConfig config = source.Configs["Mesh"];
            if (config == null)
            {
                return;
            }
            else
            {
                Enabled = config.GetBoolean("AllowMeshUpload", Enabled);
            }
        }

        public void AddRegion(Scene s)
        {
            if (!Enabled)
                return;

            m_scene = s;
            m_scene.EventManager.OnRegisterCaps += RegisterCaps;
        }

        public void RemoveRegion(Scene s)
        {
            if (!Enabled)
                return;

            m_scene.EventManager.OnRegisterCaps -= RegisterCaps;
        }

        public void RegionLoaded(Scene s)
        {
        }

        public void PostInitialise()
        {
        }

        public void Close() { }

        public string Name { get { return "MeshUploadFlagModule"; } }

        public Type ReplaceableInterface
        {
            get { return null; }
        }

        #endregion

        public void RegisterCaps(UUID agentID, Caps caps)
        {
            IRequestHandler reqHandler
                = new RestHTTPHandler(
                    "GET", "/CAPS/" + UUID.Random(), ht => MeshUploadFlag(ht, agentID), "MeshUploadFlag", agentID.ToString());

            caps.RegisterHandler("MeshUploadFlag", reqHandler);

        }

        private Hashtable MeshUploadFlag(Hashtable mDhttpMethod, UUID agentID)
        {
//            m_log.DebugFormat("[MESH UPLOAD FLAG MODULE]: MeshUploadFlag request");

            OSDMap data = new OSDMap();
//    	    ScenePresence sp = m_scene.GetScenePresence(m_agentID);
//    	    data["username"] = sp.Firstname + "." + sp.Lastname;
//    	    data["display_name_next_update"] = new OSDDate(DateTime.Now);
//    	    data["legacy_first_name"] = sp.Firstname;
            data["mesh_upload_status"] = "valid";
//    	    data["display_name"] = sp.Firstname + " " + sp.Lastname;
//    	    data["legacy_last_name"] = sp.Lastname;
//    	    data["id"] = m_agentID;
//    	    data["is_display_name_default"] = true;

            //Send back data
            Hashtable responsedata = new Hashtable();
            responsedata["int_response_code"] = 200;
            responsedata["content_type"] = "text/plain";
            responsedata["keepalive"] = false;
            responsedata["str_response_string"] = OSDParser.SerializeLLSDXmlString(data);
            return responsedata;
        }
    }
}


text:
from __future__ import absolute_import

from . import common
from .. import rw
from .call_continue import CallContinueMessage
from .types import Types

class CallResponseContinueMessage(CallContinueMessage):
    """Represent a continuation of a call response (across multiple frames)."""
    message_type = Types.CALL_RES_CONTINUE

    def __init__(
        self,
        flags=0,
        checksum=None,
        args=None,
        id=0,
    ):
        super(CallResponseContinueMessage, self).__init__(
            flags, checksum, args, id)

    def fragment(self, space_left):
        fragment_msg = CallResponseContinueMessage(
            flags=self.flags,
            checksum=self.checksum,
        )
        return super(CallResponseContinueMessage, self).fragment(
            space_left, fragment_msg)

call_res_c_rw = rw.instance(
    CallResponseContinueMessage,
    ("flags", rw.number(1)),    # flags:1
    ("checksum", common.checksum_rw),   # csumtype:1 (csum:4){0, 1}
    ("args", rw.args(rw.number(2))),    # [arg1~2, arg2~2, arg3~2]
)


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

package org.chromium.chrome.browser.infobar;

import android.content.Context;
import android.graphics.Bitmap;
import android.support.v4.view.ViewCompat;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;

import org.chromium.base.ApiCompatibilityUtils;
import org.chromium.base.ContextUtils;
import org.chromium.base.annotations.CalledByNative;
import org.chromium.chrome.R;
import org.chromium.chrome.browser.banners.AppData;
import org.chromium.chrome.browser.widget.DualControlLayout;

/**
 * Infobar informing the user about an app related to this page.
 */
public class AppBannerInfoBarAndroid extends ConfirmInfoBar implements View.OnClickListener {
    // Installation states.
    public static final int INSTALL_STATE_NOT_INSTALLED = 0;
    public static final int INSTALL_STATE_INSTALLING = 1;
    public static final int INSTALL_STATE_INSTALLED = 2;

    // Views composing the infobar.
    private Button mButton;
    private InfoBarControlLayout mMessageLayout;
    private View mTitleView;
    private View mIconView;

    private final String mAppTitle;

    // Data for native app installs.
    private final AppData mAppData;
    private int mInstallState;

    // Data for web app installs.
    private final String mAppUrl;

    // Banner for native apps.
    private AppBannerInfoBarAndroid(String appTitle, Bitmap iconBitmap, AppData data) {
        super(0, iconBitmap, appTitle, null, data.installButtonText(), null);
        mAppTitle = appTitle;
        mAppData = data;
        mAppUrl = null;
        mInstallState = INSTALL_STATE_NOT_INSTALLED;
    }

    // Banner for web apps.
    private AppBannerInfoBarAndroid(String appTitle, Bitmap iconBitmap, String url) {
        super(0, iconBitmap, appTitle, null, getAddToHomescreenText(), null);
        mAppTitle = appTitle;
        mAppData = null;
        mAppUrl = url;
        mInstallState = INSTALL_STATE_NOT_INSTALLED;
    }

    @Override
    public void createContent(InfoBarLayout layout) {
        super.createContent(layout);

        mButton = layout.getPrimaryButton();
        mIconView = layout.getIcon();
        layout.setIsUsingBigIcon();
        layout.setMessage(mAppTitle);

        mMessageLayout = layout.getMessageLayout();
        mTitleView = layout.getMessageTextView();

        Context context = getContext();
        if (mAppData != null) {
            // Native app.
            layout.getPrimaryButton().setButtonColor(ApiCompatibilityUtils.getColor(
                    getContext().getResources(),
                    R.color.app_banner_install_button_bg));
            mMessageLayout.addRatingBar(mAppData.rating());
            mMessageLayout.setContentDescription(context.getString(
                    R.string.app_banner_view_native_app_accessibility, mAppTitle,
                    mAppData.rating()));
            updateButton();
        } else {
            // Web app.
            mMessageLayout.addDescription(mAppUrl);
            mMessageLayout.setContentDescription(context.getString(
                    R.string.app_banner_view_web_app_accessibility, mAppTitle,
                    mAppUrl));
        }

        // Hide uninteresting views from accessibility.
        if (mIconView != null) {
            ViewCompat.setImportantForAccessibility(mIconView, View.IMPORTANT_FOR_ACCESSIBILITY_NO);
        }

        // Clicking on the controls brings up the app's details.  The OnClickListener has to be
        // added to both the TextView and its parent because the TextView has special handling for
        // links within the text.
        mMessageLayout.setOnClickListener(this);
        mTitleView.setOnClickListener(this);
        if (mIconView != null) mIconView.setOnClickListener(this);
    }

    @Override
    protected void setButtons(InfoBarLayout layout, String primaryText, String secondaryText) {
        if (mAppData == null) {
            // The banner for web apps uses standard buttons.
            super.setButtons(layout, primaryText, secondaryText);
        } else {
            // The banner for native apps shows a Play logo in place of a secondary button.
            assert secondaryText == null;
            ImageView playLogo = new ImageView(layout.getContext());
            playLogo.setImageResource(R.drawable.google_play);
            layout.setBottomViews(primaryText, playLogo, DualControlLayout.ALIGN_APART);
        }
    }

    @Override
    public void onButtonClicked(boolean isPrimaryButton) {
        if (isPrimaryButton && mInstallState == INSTALL_STATE_INSTALLING) {
            setControlsEnabled(true);
            updateButton();
            return;
        }
        super.onButtonClicked(isPrimaryButton);
    }

    @CalledByNative
    public void onInstallStateChanged(int newState) {
        setControlsEnabled(true);
        mInstallState = newState;
        updateButton();
    }

    private void updateButton() {
        if (mButton == null || mAppData == null) return;

        String text;
        String accessibilityText = null;
        boolean enabled = true;
        if (mInstallState == INSTALL_STATE_NOT_INSTALLED) {
            text = mAppData.installButtonText();
            accessibilityText = getContext().getString(
                    R.string.app_banner_view_native_app_install_accessibility, text);
        } else if (mInstallState == INSTALL_STATE_INSTALLING) {
            text = getContext().getString(R.string.app_banner_installing);
            enabled = false;
        } else {
            text = getContext().getString(R.string.app_banner_open);
        }

        mButton.setText(text);
        mButton.setContentDescription(accessibilityText);
        mButton.setEnabled(enabled);
    }

    @Override
    public void onClick(View v) {
        if (v == mMessageLayout || v == mTitleView || v == mIconView) onLinkClicked();
    }

    private static String getAddToHomescreenText() {
        return ContextUtils.getApplicationContext().getString(R.string.menu_add_to_homescreen);
    }

    @CalledByNative
    private static InfoBar createNativeAppInfoBar(
            String appTitle, Bitmap iconBitmap, AppData appData) {
        return new AppBannerInfoBarAndroid(appTitle, iconBitmap, appData);
    }

    @CalledByNative
    private static InfoBar createWebAppInfoBar(String appTitle, Bitmap iconBitmap, String url) {
        return new AppBannerInfoBarAndroid(appTitle, iconBitmap, url);
    }
}


text:
describe('Doughnut controller tests', function() {
	it('Should be constructed', function() {
		var chart = {
			data: {
				datasets: [{
					data: []
				}]
			}
		};

		var controller = new Chart.controllers.doughnut(chart, 0);
		expect(controller).not.toBe(undefined);
		expect(controller.index).toBe(0);
		expect(chart.data.datasets[0].metaData).toEqual([]);

		controller.updateIndex(1);
		expect(controller.index).toBe(1);
	});

	it('Should create arc elements for each data item during initialization', function() {
		var chart = {
			data: {
				datasets: [{
					data: [10, 15, 0, 4]
				}]
			},
			config: {
				type: 'doughnut'
			},
			options: {
			}
		};

		var controller = new Chart.controllers.doughnut(chart, 0);

		expect(chart.data.datasets[0].metaData.length).toBe(4); // 4 rectangles created
		expect(chart.data.datasets[0].metaData[0] instanceof Chart.elements.Arc).toBe(true);
		expect(chart.data.datasets[0].metaData[1] instanceof Chart.elements.Arc).toBe(true);
		expect(chart.data.datasets[0].metaData[2] instanceof Chart.elements.Arc).toBe(true);
		expect(chart.data.datasets[0].metaData[3] instanceof Chart.elements.Arc).toBe(true);
	});

	it ('Should reset and update elements', function() {
		var chart = {
			chartArea: {
				left: 0,
				top: 0,
				right: 100,
				bottom: 200,
			},
			data: {
				datasets: [{
					hidden: true
				}, {
					data: [10, 15, 0, 4]
				}, {
					data: [1]
				}],
				labels: ['label0', 'label1', 'label2', 'label3']
			},
			config: {
				type: 'doughnut'
			},
			options: {
				animation: {
					animateRotate: false,
					animateScale: false
				},
				cutoutPercentage: 50,
				rotation: Math.PI * -0.5,
				circumference: Math.PI * 2.0,
				elements: {
					arc: {
						backgroundColor: 'rgb(255, 0, 0)',
						borderColor: 'rgb(0, 0, 255)',
						borderWidth: 2,
						hoverBackgroundColor: 'rgb(255, 255, 255)'
					}
				}
			}
		};

		var controller = new Chart.controllers.doughnut(chart, 1);
		controller.reset(); // reset first

		expect(chart.data.datasets[1].metaData[0]._model).toEqual(jasmine.objectContaining({
			x: 50,
			y: 100,
			startAngle: Math.PI * -0.5,
			endAngle: Math.PI * -0.5,
			circumference: 2.1666156231653746,
			outerRadius: 49,
			innerRadius: 36.75
		}));

		expect(chart.data.datasets[1].metaData[1]._model).toEqual(jasmine.objectContaining({
			x: 50,
			y: 100,
			startAngle: Math.PI * -0.5,
			endAngle: Math.PI * -0.5,
			circumference: 3.249923434748062,
			outerRadius: 49,
			innerRadius: 36.75
		}));

		expect(chart.data.datasets[1].metaData[2]._model).toEqual(jasmine.objectContaining({
			x: 50,
			y: 100,
			startAngle: Math.PI * -0.5,
			endAngle: Math.PI * -0.5,
			circumference: 0,
			outerRadius: 49,
			innerRadius: 36.75
		}));

		expect(chart.data.datasets[1].metaData[3]._model).toEqual(jasmine.objectContaining({
			x: 50,
			y: 100,
			startAngle: Math.PI * -0.5,
			endAngle: Math.PI * -0.5,
			circumference: 0.8666462492661499,
			outerRadius: 49,
			innerRadius: 36.75
		}));

		controller.update();

		expect(chart.data.datasets[1].metaData[0]._model).toEqual(jasmine.objectContaining({
			x: 50,
			y: 100,
			startAngle: Math.PI * -0.5,
			endAngle: 0.595819296370478,
			circumference: 2.1666156231653746,
			outerRadius: 49,
			innerRadius: 36.75,

			backgroundColor: 'rgb(255, 0, 0)',
			borderColor: 'rgb(0, 0, 255)',
			borderWidth: 2,
			hoverBackgroundColor: 'rgb(255, 255, 255)',

			label: 'label0',
		}));

		expect(chart.data.datasets[1].metaData[1]._model).toEqual(jasmine.objectContaining({
			x: 50,
			y: 100,
			startAngle: 0.595819296370478,
			endAngle: 3.84574273111854,
			circumference: 3.249923434748062,
			outerRadius: 49,
			innerRadius: 36.75,

			backgroundColor: 'rgb(255, 0, 0)',
			borderColor: 'rgb(0, 0, 255)',
			borderWidth: 2,
			hoverBackgroundColor: 'rgb(255, 255, 255)',

			label: 'label1'
		}));

		expect(chart.data.datasets[1].metaData[2]._model).toEqual(jasmine.objectContaining({
			x: 50,
			y: 100,
			startAngle: 3.84574273111854,
			endAngle: 3.84574273111854,
			circumference: 0,
			outerRadius: 49,
			innerRadius: 36.75,

			backgroundColor: 'rgb(255, 0, 0)',
			borderColor: 'rgb(0, 0, 255)',
			borderWidth: 2,
			hoverBackgroundColor: 'rgb(255, 255, 255)',

			label: 'label2'
		}));

		expect(chart.data.datasets[1].metaData[3]._model).toEqual(jasmine.objectContaining({
			x: 50,
			y: 100,
			startAngle: 3.84574273111854,
			endAngle: 4.71238898038469,
			circumference: 0.8666462492661499,
			outerRadius: 49,
			innerRadius: 36.75,

			backgroundColor: 'rgb(255, 0, 0)',
			borderColor: 'rgb(0, 0, 255)',
			borderWidth: 2,
			hoverBackgroundColor: 'rgb(255, 255, 255)',

			label: 'label3'
		}));

		// Change the amount of data and ensure that arcs are updated accordingly
		chart.data.datasets[1].data = [1, 2]; // remove 2 elements from dataset 0
		controller.buildOrUpdateElements();
		controller.update();

		expect(chart.data.datasets[1].metaData.length).toBe(2);
		expect(chart.data.datasets[1].metaData[0] instanceof Chart.elements.Arc).toBe(true);
		expect(chart.data.datasets[1].metaData[1] instanceof Chart.elements.Arc).toBe(true);

		// Add data
		chart.data.datasets[1].data = [1, 2, 3, 4];
		controller.buildOrUpdateElements();
		controller.update();

		expect(chart.data.datasets[1].metaData.length).toBe(4);
		expect(chart.data.datasets[1].metaData[0] instanceof Chart.elements.Arc).toBe(true);
		expect(chart.data.datasets[1].metaData[1] instanceof Chart.elements.Arc).toBe(true);
		expect(chart.data.datasets[1].metaData[2] instanceof Chart.elements.Arc).toBe(true);
		expect(chart.data.datasets[1].metaData[3] instanceof Chart.elements.Arc).toBe(true);
	});

	it ('Should rotate and limit circumference', function() {
		var chart = {
			chartArea: {
				left: 0,
				top: 0,
				right: 200,
				bottom: 100,
			},
			data: {
				datasets: [{
					hidden: true
				}, {
					data: [1, 3]
				}, {
					data: [1]
				}],
				labels: ['label0', 'label1']
			},
			config: {
				type: 'doughnut'
			},
			options: {
				animation: {
					animateRotate: false,
					animateScale: false
				},
				cutoutPercentage: 50,
				rotation: Math.PI,
				circumference: Math.PI * 0.5,
				elements: {
					arc: {
						backgroundColor: 'rgb(255, 0, 0)',
						borderColor: 'rgb(0, 0, 255)',
						borderWidth: 2,
						hoverBackgroundColor: 'rgb(255, 255, 255)'
					}
				}
			}
		};

		var controller = new Chart.controllers.doughnut(chart, 1);
		controller.update();

		expect(chart.data.datasets[1].metaData[0]._model.x).toEqual(149);
		expect(chart.data.datasets[1].metaData[0]._model.y).toEqual(99);
		expect(chart.data.datasets[1].metaData[0]._model.startAngle).toBeCloseTo(Math.PI, 10);
		expect(chart.data.datasets[1].metaData[0]._model.endAngle).toBeCloseTo(Math.PI + Math.PI / 8, 10);
		expect(chart.data.datasets[1].metaData[0]._model.circumference).toBeCloseTo(Math.PI / 8, 10);
		expect(chart.data.datasets[1].metaData[0]._model.outerRadius).toBeCloseTo(98, 10);
		expect(chart.data.datasets[1].metaData[0]._model.innerRadius).toBeCloseTo(73.5, 10);

		expect(chart.data.datasets[1].metaData[1]._model.x).toEqual(149);
		expect(chart.data.datasets[1].metaData[1]._model.y).toEqual(99);
		expect(chart.data.datasets[1].metaData[1]._model.startAngle).toBeCloseTo(Math.PI + Math.PI / 8, 10);
		expect(chart.data.datasets[1].metaData[1]._model.endAngle).toBeCloseTo(Math.PI + Math.PI / 2, 10);
		expect(chart.data.datasets[1].metaData[1]._model.circumference).toBeCloseTo(3 * Math.PI / 8, 10);
		expect(chart.data.datasets[1].metaData[1]._model.outerRadius).toBeCloseTo(98, 10);
		expect(chart.data.datasets[1].metaData[1]._model.innerRadius).toBeCloseTo(73.5, 10);
	});

	it ('should draw all arcs', function() {
		var chart = {
			chartArea: {
				left: 0,
				top: 0,
				right: 100,
				bottom: 200,
			},
			data: {
				datasets: [{
					data: [10, 15, 0, 4]
				}],
				labels: ['label0', 'label1', 'label2', 'label3']
			},
			config: {
				type: 'doughnut'
			},
			options: {
				animation: {
					animateRotate: false,
					animateScale: false
				},
				cutoutPercentage: 50,
				elements: {
					arc: {
						backgroundColor: 'rgb(255, 0, 0)',
						borderColor: 'rgb(0, 0, 255)',
						borderWidth: 2,
						hoverBackgroundColor: 'rgb(255, 255, 255)'
					}
				}
			}
		};

		var controller = new Chart.controllers.doughnut(chart, 0);

		spyOn(chart.data.datasets[0].metaData[0], 'draw');
		spyOn(chart.data.datasets[0].metaData[1], 'draw');
		spyOn(chart.data.datasets[0].metaData[2], 'draw');
		spyOn(chart.data.datasets[0].metaData[3], 'draw');

		controller.draw();

		expect(chart.data.datasets[0].metaData[0].draw.calls.count()).toBe(1);
		expect(chart.data.datasets[0].metaData[1].draw.calls.count()).toBe(1);
		expect(chart.data.datasets[0].metaData[2].draw.calls.count()).toBe(1);
		expect(chart.data.datasets[0].metaData[3].draw.calls.count()).toBe(1);
	});

	it ('should set the hover style of an arc', function() {
		var chart = {
			chartArea: {
				left: 0,
				top: 0,
				right: 100,
				bottom: 200,
			},
			data: {
				datasets: [{
					data: [10, 15, 0, 4]
				}],
				labels: ['label0', 'label1', 'label2', 'label3']
			},
			config: {
				type: 'doughnut'
			},
			options: {
				animation: {
					animateRotate: false,
					animateScale: false
				},
				cutoutPercentage: 50,
				elements: {
					arc: {
						backgroundColor: 'rgb(255, 0, 0)',
						borderColor: 'rgb(0, 0, 255)',
						borderWidth: 2,
					}
				}
			}
		};

		var controller = new Chart.controllers.doughnut(chart, 0);
		controller.reset(); // reset first
		controller.update();

		var arc = chart.data.datasets[0].metaData[0];

		controller.setHoverStyle(arc);

		expect(arc._model.backgroundColor).toBe('rgb(230, 0, 0)');
		expect(arc._model.borderColor).toBe('rgb(0, 0, 230)');
		expect(arc._model.borderWidth).toBe(2);

		// Set a dataset style to take precedence
		chart.data.datasets[0].hoverBackgroundColor = 'rgb(9, 9, 9)';
		chart.data.datasets[0].hoverBorderColor = 'rgb(18, 18, 18)';
		chart.data.datasets[0].hoverBorderWidth = 1.56;

		controller.setHoverStyle(arc);

		expect(arc._model.backgroundColor).toBe('rgb(9, 9, 9)');
		expect(arc._model.borderColor).toBe('rgb(18, 18, 18)');
		expect(arc._model.borderWidth).toBe(1.56);

		// Dataset styles can be an array
		chart.data.datasets[0].hoverBackgroundColor = ['rgb(255, 255, 255)', 'rgb(9, 9, 9)'];
		chart.data.datasets[0].hoverBorderColor = ['rgb(18, 18, 18)'];
		chart.data.datasets[0].hoverBorderWidth = [0.1, 1.56];

		controller.setHoverStyle(arc);

		expect(arc._model.backgroundColor).toBe('rgb(255, 255, 255)');
		expect(arc._model.borderColor).toBe('rgb(18, 18, 18)');
		expect(arc._model.borderWidth).toBe(0.1);

		// Element custom styles also work
		arc.custom = {
			hoverBackgroundColor: 'rgb(7, 7, 7)',
			hoverBorderColor: 'rgb(17, 17, 17)',
			hoverBorderWidth: 3.14159,
		};

		controller.setHoverStyle(arc);

		expect(arc._model.backgroundColor).toBe('rgb(7, 7, 7)');
		expect(arc._model.borderColor).toBe('rgb(17, 17, 17)');
		expect(arc._model.borderWidth).toBe(3.14159);
	});

	it ('should unset the hover style of an arc', function() {
		var chart = {
			chartArea: {
				left: 0,
				top: 0,
				right: 100,
				bottom: 200,
			},
			data: {
				datasets: [{
					data: [10, 15, 0, 4]
				}],
				labels: ['label0', 'label1', 'label2', 'label3']
			},
			config: {
				type: 'doughnut'
			},
			options: {
				animation: {
					animateRotate: false,
					animateScale: false
				},
				cutoutPercentage: 50,
				elements: {
					arc: {
						backgroundColor: 'rgb(255, 0, 0)',
						borderColor: 'rgb(0, 0, 255)',
						borderWidth: 2,
					}
				}
			}
		};

		var controller = new Chart.controllers.doughnut(chart, 0);
		controller.reset(); // reset first
		controller.update();

		var arc = chart.data.datasets[0].metaData[0];

		controller.removeHoverStyle(arc);

		expect(arc._model.backgroundColor).toBe('rgb(255, 0, 0)');
		expect(arc._model.borderColor).toBe('rgb(0, 0, 255)');
		expect(arc._model.borderWidth).toBe(2);

		// Set a dataset style to take precedence
		chart.data.datasets[0].backgroundColor = 'rgb(9, 9, 9)';
		chart.data.datasets[0].borderColor = 'rgb(18, 18, 18)';
		chart.data.datasets[0].borderWidth = 1.56;

		controller.removeHoverStyle(arc);

		expect(arc._model.backgroundColor).toBe('rgb(9, 9, 9)');
		expect(arc._model.borderColor).toBe('rgb(18, 18, 18)');
		expect(arc._model.borderWidth).toBe(1.56);

		// Dataset styles can be an array
		chart.data.datasets[0].backgroundColor = ['rgb(255, 255, 255)', 'rgb(9, 9, 9)'];
		chart.data.datasets[0].borderColor = ['rgb(18, 18, 18)'];
		chart.data.datasets[0].borderWidth = [0.1, 1.56];

		controller.removeHoverStyle(arc);

		expect(arc._model.backgroundColor).toBe('rgb(255, 255, 255)');
		expect(arc._model.borderColor).toBe('rgb(18, 18, 18)');
		expect(arc._model.borderWidth).toBe(0.1);

		// Element custom styles also work
		arc.custom = {
			backgroundColor: 'rgb(7, 7, 7)',
			borderColor: 'rgb(17, 17, 17)',
			borderWidth: 3.14159,
		};

		controller.removeHoverStyle(arc);

		expect(arc._model.backgroundColor).toBe('rgb(7, 7, 7)');
		expect(arc._model.borderColor).toBe('rgb(17, 17, 17)');
		expect(arc._model.borderWidth).toBe(3.14159);
	});
});


text:
package org.apache.storm.utils;

import org.apache.storm.metrics2.StormMetricRegistry;
import org.apache.storm.policy.WaitStrategyPark;
import org.apache.storm.utils.JCQueue.Consumer;
import org.junit.Assert;
import org.junit.Test;

public class JCQueueBackpressureTest {

    private static JCQueue createQueue(String name, int queueSize) {
        return new JCQueue(name, queueSize, 0, 1, new WaitStrategyPark(0), "test", "test", 1000, 1000, new StormMetricRegistry());
    }

    @Test
    public void testNoReOrderingUnderBackPressure() throws Exception {
        final int MESSAGES = 100;
        final int CAPACITY = 64;

        final JCQueue queue = createQueue("testBackPressure", CAPACITY);

        for (int i = 0; i < MESSAGES; i++) {
            if (!queue.tryPublish(i)) {
                Assert.assertTrue(queue.tryPublishToOverflow(i));
            }
        }

        TestConsumer consumer = new TestConsumer();
        queue.consume(consumer);
        Assert.assertEquals(MESSAGES, consumer.lastMsg);

        queue.close();
    }

    // check that tryPublish() & tryOverflowPublish() work as expected
    @Test
    public void testBasicBackPressure() throws Exception {
        final int MESSAGES = 100;
        final int CAPACITY = 64;

        final JCQueue queue = createQueue("testBackPressure", CAPACITY);

        // pump more msgs than Q size & verify msg count is as expexted
        for (int i = 0; i < MESSAGES; i++) {
            if (i >= CAPACITY) {
                Assert.assertFalse(queue.tryPublish(i));
            } else {
                Assert.assertTrue(queue.tryPublish(i));
            }
        }
        Assert.assertEquals(CAPACITY, queue.size());

        Assert.assertEquals(0, queue.getOverflowCount());

        // drain 1 element and ensure BP is relieved (i.e tryPublish() succeeds)
        final MutableLong consumeCount = new MutableLong(0);
        queue.consume(new TestConsumer(), () -> consumeCount.increment() <= 1);
        Assert.assertEquals(CAPACITY - 1, queue.size());
        Assert.assertTrue(queue.tryPublish(0));

        queue.close();
    }

    private static class TestConsumer implements Consumer {
        int lastMsg = 0;

        @Override
        public void accept(Object o) {
            Integer i = (Integer) o;
            Assert.assertEquals(lastMsg++, i.intValue());
            System.err.println(i);
        }

        @Override
        public void flush() throws InterruptedException { }
    }

}


text:
(function() {
'use strict';

window.Darkroom = Darkroom;

// Core object of DarkroomJS.
// Basically it's a single object, instanciable via an element
// (it could be a CSS selector or a DOM element), some custom options,
// and a list of plugin objects (or none to use default ones).
function Darkroom(element, options, plugins) {
  return this.constructor(element, options, plugins);
}

// Create an empty list of plugin objects, which will be filled by
// other plugin scripts. This is the default plugin list if none is
// specified in Darkroom'ss constructor.
Darkroom.plugins = [];

Darkroom.prototype = {
  // Reference to the main container element
  containerElement: null,

  // Reference to the Fabric canvas object
  canvas: null,

  // Reference to the Fabric image object
  image: null,

  // Reference to the Fabric source canvas object
  sourceCanvas: null,

  // Reference to the Fabric source image object
  sourceImage: null,

  // Track of the original image element
  originalImageElement: null,

  // Stack of transformations to apply to the image source
  transformations: [],

  // Default options
  defaults: {
    // Canvas properties (dimension, ratio, color)
    minWidth: null,
    minHeight: null,
    maxWidth: null,
    maxHeight: null,
    ratio: null,
    backgroundColor: '#fff',

    // Plugins options
    plugins: {},

    // Post-initialisation callback
    initialize: function() { /* noop */ }
  },

  // List of the instancied plugins
  plugins: {},

  // This options are a merge between `defaults` and the options passed
  // through the constructor
  options: {},

  constructor: function(element, options, plugins) {
    this.options = Darkroom.Utils.extend(options, this.defaults);

    if (typeof element === 'string')
      element = document.querySelector(element);
    if (null === element)
      return;

    var image = new Image();
    image.onload = function() {
      // Initialize the DOM/Fabric elements
      this._initializeDOM(element);
      this._initializeImage();

      // Then initialize the plugins
      this._initializePlugins(Darkroom.plugins);

      // Public method to adjust image according to the canvas
      this.refresh(function() {
        // Execute a custom callback after initialization
        this.options.initialize.bind(this).call();
      }.bind(this));

    }.bind(this)

    //image.crossOrigin = 'anonymous';
    image.src = element.src;
  },

  selfDestroy: function() {
    var container = this.containerElement;
    var image = new Image();
    image.onload = function() {
      container.parentNode.replaceChild(image, container);
    }

    image.src = this.sourceImage.toDataURL();
  },

  // Add ability to attach event listener on the core object.
  // It uses the canvas element to process events.
  addEventListener: function(eventName, callback) {
    var el = this.canvas.getElement();
    if (el.addEventListener){
      el.addEventListener(eventName, callback);
    } else if (el.attachEvent) {
      el.attachEvent('on' + eventName, callback);
    }
  },

  dispatchEvent: function(eventName) {
    // Use the old way of creating event to be IE compatible
    // See https://developer.mozilla.org/en-US/docs/Web/Guide/Events/Creating_and_triggering_events
    var event = document.createEvent('Event');
    event.initEvent(eventName, true, true);

    this.canvas.getElement().dispatchEvent(event);
  },

  // Adjust image & canvas dimension according to min/max width/height
  // and ratio specified in the options.
  // This method should be called after each image transformation.
  refresh: function(next) {
    var clone = new Image();
    clone.onload = function() {
      this._replaceCurrentImage(new fabric.Image(clone));

      if (next) next();
    }.bind(this);
    clone.src = this.sourceImage.toDataURL();
  },

  _replaceCurrentImage: function(newImage) {
    if (this.image) {
      this.image.remove();
    }

    this.image = newImage;
    this.image.selectable = false;

    // Adjust width or height according to specified ratio
    var viewport = Darkroom.Utils.computeImageViewPort(this.image);
    var canvasWidth = viewport.width;
    var canvasHeight = viewport.height;

    if (null !== this.options.ratio) {
      var canvasRatio = +this.options.ratio;
      var currentRatio = canvasWidth / canvasHeight;

      if (currentRatio > canvasRatio) {
        canvasHeight = canvasWidth / canvasRatio;
      } else if (currentRatio < canvasRatio) {
        canvasWidth = canvasHeight * canvasRatio;
      }
    }

    // Then scale the image to fit into dimension limits
    var scaleMin = 1;
    var scaleMax = 1;
    var scaleX = 1;
    var scaleY = 1;

    if (null !== this.options.maxWidth && this.options.maxWidth < canvasWidth) {
      scaleX =  this.options.maxWidth / canvasWidth;
    }
    if (null !== this.options.maxHeight && this.options.maxHeight < canvasHeight) {
      scaleY =  this.options.maxHeight / canvasHeight;
    }
    scaleMin = Math.min(scaleX, scaleY);

    scaleX = 1;
    scaleY = 1;
    if (null !== this.options.minWidth && this.options.minWidth > canvasWidth) {
      scaleX =  this.options.minWidth / canvasWidth;
    }
    if (null !== this.options.minHeight && this.options.minHeight > canvasHeight) {
      scaleY =  this.options.minHeight / canvasHeight;
    }
    scaleMax = Math.max(scaleX, scaleY);

    var scale = scaleMax * scaleMin; // one should be equals to 1

    canvasWidth *= scale;
    canvasHeight *= scale;

    // Finally place the image in the center of the canvas
    this.image.setScaleX(1 * scale);
    this.image.setScaleY(1 * scale);
    this.canvas.add(this.image);
    this.canvas.setWidth(canvasWidth);
    this.canvas.setHeight(canvasHeight);
    this.canvas.centerObject(this.image);
    this.image.setCoords();
  },

  // Apply the transformation on the current image and save it in the
  // transformations stack (in order to reconstitute the previous states
  // of the image).
  applyTransformation: function(transformation) {
    this.transformations.push(transformation);

    transformation.applyTransformation(
      this.sourceCanvas,
      this.sourceImage,
      this._postTransformation.bind(this)
    );
  },

  _postTransformation: function(newImage) {
    if (newImage)
      this.sourceImage = newImage;

    this.refresh(function() {
      this.dispatchEvent('core:transformation');
    }.bind(this));
  },

  // Initialize image from original element plus re-apply every
  // transformations.
  reinitializeImage: function() {
    this.sourceImage.remove();
    this._initializeImage();
    this._popTransformation(this.transformations.slice())
  },

  _popTransformation: function(transformations) {
    if (0 === transformations.length) {
      this.dispatchEvent('core:reinitialized');
      this.refresh();
      return;
    }

    var transformation = transformations.shift();

    var next = function(newImage) {
      if (newImage) this.sourceImage = newImage;
      this._popTransformation(transformations)
    };

    transformation.applyTransformation(
      this.sourceCanvas,
      this.sourceImage,
      next.bind(this)
    );
  },

  // Create the DOM elements and instanciate the Fabric canvas.
  // The image element is replaced by a new `div` element.
  // However the original image is re-injected in order to keep a trace of it.
  _initializeDOM: function(imageElement) {
    // Container
    var mainContainerElement = document.createElement('div');
    mainContainerElement.className = 'darkroom-container';

    // Toolbar
    var toolbarElement = document.createElement('div');
    toolbarElement.className = 'darkroom-toolbar';
    mainContainerElement.appendChild(toolbarElement);

    // Viewport canvas
    var canvasContainerElement = document.createElement('div');
    canvasContainerElement.className = 'darkroom-image-container';
    var canvasElement = document.createElement('canvas');
    canvasContainerElement.appendChild(canvasElement);
    mainContainerElement.appendChild(canvasContainerElement);

    // Source canvas
    var sourceCanvasContainerElement = document.createElement('div');
    sourceCanvasContainerElement.className = 'darkroom-source-container';
    sourceCanvasContainerElement.style.display = 'none';
    var sourceCanvasElement = document.createElement('canvas');
    sourceCanvasContainerElement.appendChild(sourceCanvasElement);
    mainContainerElement.appendChild(sourceCanvasContainerElement);

    // Original image
    imageElement.parentNode.replaceChild(mainContainerElement, imageElement);
    imageElement.style.display = 'none';
    mainContainerElement.appendChild(imageElement);

    // Instanciate object from elements
    this.containerElement = mainContainerElement;
    this.originalImageElement = imageElement;

    this.toolbar = new Darkroom.UI.Toolbar(toolbarElement);

    this.canvas = new fabric.Canvas(canvasElement, {
      selection: false,
      backgroundColor: this.options.backgroundColor
    });

    this.sourceCanvas = new fabric.Canvas(sourceCanvasElement, {
      selection: false,
      backgroundColor: this.options.backgroundColor
    });
  },

  // Instanciate the Fabric image object.
  // The image is created as a static element with no control,
  // then it is add in the Fabric canvas object.
  _initializeImage: function() {
    this.sourceImage = new fabric.Image(this.originalImageElement, {
      // Some options to make the image static
      selectable: false,
      evented: false,
      lockMovementX: true,
      lockMovementY: true,
      lockRotation: true,
      lockScalingX: true,
      lockScalingY: true,
      lockUniScaling: true,
      hasControls: false,
      hasBorders: false,
    });

    this.sourceCanvas.add(this.sourceImage);

    // Adjust width or height according to specified ratio
    var viewport = Darkroom.Utils.computeImageViewPort(this.sourceImage);
    var canvasWidth = viewport.width;
    var canvasHeight = viewport.height;

    this.sourceCanvas.setWidth(canvasWidth);
    this.sourceCanvas.setHeight(canvasHeight);
    this.sourceCanvas.centerObject(this.sourceImage);
    this.sourceImage.setCoords();
  },

  // Initialize every plugins.
  // Note that plugins are instanciated in the same order than they
  // are declared in the parameter object.
  _initializePlugins: function(plugins) {
    for (var name in plugins) {
      var plugin = plugins[name];
      var options = this.options.plugins[name];

      // Setting false into the plugin options will disable the plugin
      if (options === false)
        continue;

      // Avoid any issues with _proto_
      if (!plugins.hasOwnProperty(name))
        continue;

      this.plugins[name] = new plugin(this, options);
    }
  },
}

})();


text:
import unicodecsv
from django.core.management.base import BaseCommand
from tasks.models import Task

class Command(BaseCommand):
    args = '<task_csv_filename>'
    help = 'Import a CSV of tasks.'

    def handle(self, *args, **options):
        task_file = unicodecsv.DictReader(open(args[0]), encoding='utf-8')
        return self._handle_task_file(task_file)

    def _handle_task_file(self, task_file):
        for task in task_file:
            Task.objects.create(
                project=task['Project'],
                url=task['url'],
                item_id=task['itemID'],
                skills=task['Required skills'],
                community_tools=task['Community tools'],
                project_area=task['Project Area'],
                summary=task['Summary'],
                description=task['Description'],
                suggested_for=task['For'],
                mentor=task['Mentor'],
                env_difficulty=task['Environment setup difficulty'],
                closed=bool(task['closed'].strip()),
                suggested_mode=task['suggestedmode'],
                recently_verified=bool(task['recentlyVerified'].strip()),
            )


text:
// The MIT License (MIT)
// Copyright (c) 2014 Yufei (Benny) Chen
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
#ifndef LIBRARY_SYS_LREQ_H_
#define LIBRARY_SYS_LREQ_H_

#include <evhtp.h>
#include <map>
#include <vector>
#include <string>
#include "../threadlocal.h"
#include "./utils.h"

namespace loopy {

/**
 * Request class for Loopy. Contains all the necessary information related
 * to the current request
 */
class LReq {
 private:
  typedef std::map<std::string, std::string> stringKV;

 public:
  explicit LReq(pReq request);

  // accessor for different properties
  const char* path() const;

  // filename for the path
  const char* filename() const;

  // ip address
  const char* IPAddr() const;

  // http scheme
  htp_scheme scheme() const;

  // lazily evaluated query parameters and body parameters
  stringKV& queryParams();
  stringKV& httpHeaders();
  stringKV& bodyParams();

  void addToCallStack(std::string nextPath);
  const std::vector<std::string>& callStack() const;

  pReq rawReq();

 private:
  pReq request_;

  // these 2 parameters will not be evalauted when the request is received
  // only when the accessor for the class is called, the parameter will
  // be evaluated
  stringKV          query_params_;
  stringKV          body_params_;
  stringKV          http_headers_;

  // for hierarchical calling
  std::string       next_;

  // helper function that turns string KV to map of key value pairs
  stringKV          evhtpKVsToMap(evhtp_kvs_t* kv);

  // function call trace
  std::vector<std::string> request_stack_;
};

} // namespace loopy

#endif  // LIBRARY_SYS_LREQ_H_