text:
package codeu.chat.common;

import static org.junit.Assert.*;

import java.io.IOException;
import org.junit.Test;

public final class SecretTest {

  @Test
  public void testParseEvenLength() throws IOException {

    final String input = "2345";
    final Secret expected = new Secret((byte)0x23, (byte)0x45);
    final Secret actual = Secret.parse(input);

    assertNotNull(actual);
    assertEquals(actual, expected);
  }

  @Test
  public void testParseEvenLengthWithUppercaseLetters() throws IOException {

    final String input = "ABCDEF";
    final Secret expected = new Secret((byte) 0xAB, (byte) 0xCD, (byte) 0xEF);
    final Secret actual = Secret.parse(input);

    assertNotNull(actual);
    assertEquals(actual, expected);
  }

  @Test
  public void testParseEvenLengthWithLowercaseLetters() throws IOException {

    final String input = "abcdef";
    final Secret expected = new Secret((byte) 0xAB, (byte) 0xCD, (byte) 0xEF);
    final Secret actual = Secret.parse(input);

    assertNotNull(actual);
    assertEquals(actual, expected);
  }

  @Test
  public void testParseEvenLengthWithLeadingZero() throws IOException {

    final String input = "012345";
    final Secret expected = new Secret((byte)0x01, (byte)0x23, (byte)0x45);
    final Secret actual = Secret.parse(input);

    assertNotNull(actual);
    assertEquals(actual, expected);
  }

  @Test
  public void testParseEvenLengthWithLeadingDoubleZero() throws IOException {

    final String input = "00123456";
    final Secret expected = new Secret((byte)0x00, (byte)0x12, (byte)0x34, (byte)0x56);
    final Secret actual = Secret.parse(input);

    assertNotNull(actual);
    assertEquals(actual, expected);
  }

  @Test
  public void testParseOddLength() throws IOException {

    final String input = "12345";
    final Secret expected = new Secret((byte)0x01, (byte)0x23, (byte)0x45);
    final Secret actual = Secret.parse(input);

    assertNotNull(actual);
    assertEquals(actual, expected);
  }

  @Test
  public void testParseOddLengthWithLeadingZero() throws IOException {

    final String input = "0123456";
    final Secret expected = new Secret((byte)0x00, (byte)0x12, (byte)0x34, (byte)0x56);
    final Secret actual = Secret.parse(input);

    assertNotNull(actual);
    assertEquals(actual, expected);
  }

  @Test
  public void testParseOddLengthWithLeadingDoubleZero() throws IOException {

    final String input = "001234567";
    final Secret expected = new Secret((byte)0x00, (byte)0x01, (byte)0x23, (byte)0x45, (byte)0x67);
    final Secret actual = Secret.parse(input);

    assertNotNull(actual);
    assertEquals(actual, expected);
  }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<spring:beans xmlns="http://www.citrusframework.org/schema/testcase"
              xmlns:spring="http://www.springframework.org/schema/beans"
              xmlns:http="http://www.citrusframework.org/schema/http/testcase"
              xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
              xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
                                  http://www.citrusframework.org/schema/testcase http://www.citrusframework.org/schema/testcase/citrus-testcase.xsd
                                  http://www.citrusframework.org/schema/http/testcase http://www.citrusframework.org/schema/http/testcase/citrus-http-testcase.xsd">
  <testcase name="JsonPathValidationIT">
    <meta-info>
      <author>Christoph Deppisch</author>
      <creationdate>2015-07-21</creationdate>
      <status>FINAL</status>
      <last-updated-by>Christoph Deppisch</last-updated-by>
      <last-updated-on>2015-07-21T00:00:00</last-updated-on>
    </meta-info>

    <description>Send plain text as message payload. Here we use custom data format to send it over HTTP to a server and receive simple plain text as response.</description>

    <actions>
      <parallel>
        <http:send-request client="httpClient">
          <http:POST>
            <http:body>
              <http:data>
                {
                  "type" : "read",
                  "mbean" : "java.lang:type=Memory",
                  "attribute" : "HeapMemoryUsage",
                  "path" : "used",
                  "lastModified": null
                }
              </http:data>
            </http:body>
          </http:POST>
        </http:send-request>

        <sequential>
          <http:receive-request server="httpServerRequestEndpoint">
            <http:POST>
              <http:body type="json">
                <http:validate>
                    <http:json-path expression="$.type" value="read"/>
                    <http:json-path expression="$.mbean" value="java.lang:type=Memory"/>
                    <http:json-path expression="$..attribute" value="HeapMemoryUsage"/>
                    <http:json-path expression="$.path" value="@equalsIgnoreCase('USED')@"/>
                    <http:json-path expression="$.lastModified" value="@assertThat(nullValue())@"/>
                </http:validate>
              </http:body>
            </http:POST>
            <http:extract>
              <http:header name="citrus_jms_messageId" variable="correlation_id"/>
            </http:extract>
          </http:receive-request>

          <http:send-response server="httpServerResponseEndpoint">
            <http:headers status="200" reason-phrase="OK" version="HTTP/1.1">
              <http:header name="citrus_jms_correlationId" value="${correlation_id}"/>
            </http:headers>
            <http:body>
              <http:data>
                {
                  "timestamp" : "2011-01-01",
                  "status" : 200,
                  "request" :
                      {
                        "mbean" : "java.lang:type=Memory",
                        "path" : "used",
                        "attribute" : "HeapMemoryUsage",
                        "type" : "read"
                      },
                  "value" : "512",
                  "lastModified": null
                }
              </http:data>
            </http:body>
          </http:send-response>
        </sequential>
      </parallel>

      <http:receive-response client="httpClient">
        <http:headers status="200" reason-phrase="OK" version="HTTP/1.1"/>
        <http:body type="json">
          <http:data>
            {
              "timestamp" : "@matchesDatePattern('yyyy-MM-dd')@",
              "status" : 200,
              "request" :
                  {
                    "mbean" : "java.lang:type=Memory",
                    "path" : "@matches('u*s*e*d*')@",
                    "attribute" : "HeapMemoryUsage",
                    "type" : "read"
                  },
              "value" : "@isNumber()@",
              "lastModified": "@assertThat(nullValue())@"
            }
          </http:data>
          <http:validate>
              <http:json-path expression="$.timestamp" value="@matchesDatePattern('yyyy-MM-dd')@"/>
              <http:json-path expression="$.request.path" value="@matches('u*s*e*d*')@"/>
              <http:json-path expression="$..attribute" value="HeapMemoryUsage"/>
              <http:json-path expression="$.value" value="@isNumber()@"/>
              <http:json-path expression="$.lastModified" value=""/>
          </http:validate>
        </http:body>
      </http:receive-response>

    </actions>
  </testcase>
</spring:beans>

redpajama_set_name: RedPajamaGithub


text:
function data = fm_get_TEs(data)

echoes_to_use = data.echoes_to_use;
n_echoes_to_use = data.n_echoes_to_use;
root_dir = data.root_dir;
readfile_dirs = data.readfile_dirs;
file_code = data.file_code;

TEs = zeros(n_echoes_to_use,1);

switch file_code
    case {'SE','SCSE'}
        for j=1:n_echoes_to_use
            i=echoes_to_use(j);
            header_file = fullfile(root_dir, char(readfile_dirs(i)), 'text_header.txt');
            if exist(header_file)==2
                TEs(j) = str2double(search_text_header_func(header_file, sprintf('alTE[0]')));
            else
                error(['Could not find ' header_file]);
            end
        end
    case {'SESPM','SCSESPM'}
        for j=1:n_echoes_to_use
            i=echoes_to_use(j);
            header_file = fullfile(root_dir, char(readfile_dirs(2*i-1)), 'text_header.txt');
            if exist(header_file)==2
                TEs(j) = str2double(search_text_header_func(header_file, sprintf('alTE[0]')));
            else
                error(['Could not find ' header_file]);
            end
        end
    otherwise
        if iscell(readfile_dirs) == 1
            header_file = fullfile(root_dir, char(readfile_dirs(1)), 'text_header.txt');
        else
            header_file = fullfile(root_dir, readfile_dirs, 'text_header.txt');
        end
        if exist(header_file)==2
            for j=1:n_echoes_to_use
                i=echoes_to_use(j);
                TEs(j) = str2num(search_text_header_func(header_file, sprintf('alTE[%s]', num2str(i-1))));
            end
        else
            error(['Could not find ' header_file]);
        end
end

data.TEs = TEs;


text:
var objToString = Object.prototype.toString,
    objectNumber = "[object Number]";

module.exports = isNumber;

function isNumber(value) {

    return typeof(value) === "number" || objToString.call(value) === objectNumber;

}


text:
#include "PingTestsTest.h"

/*
Description:
Tests out:
virtual int 	GetAveragePing (const SystemAddress systemAddress)=0
virtual int 	GetLastPing (const SystemAddress systemAddress) const =0
virtual int 	GetLowestPing (const SystemAddress systemAddress) const =0
virtual void 	SetOccasionalPing (bool doPing)=0

Ping is tested in CrossConnectionConvertTest,SetOfflinePingResponse and GetOfflinePingResponse tested in OfflineMessagesConvertTest

Success conditions:
Currently is that GetAveragePing and SetOccasionalPing works

Failure conditions:

RakPeerInterface Functions used, tested indirectly by its use, not all encompassing list:
Startup
SetMaximumIncomingConnections
Receive
DeallocatePacket

RakPeerInterface Functions Explicitly Tested:
GetAveragePing
GetLastPing
GetLowestPing
SetOccasionalPing
*/

int PingTestsTest::RunTest(DataStructures::List<RakString> params,bool isVerbose,bool noPauses)
{

	RakPeerInterface *sender,*sender2, *receiver;
	destroyList.Clear(false,_FILE_AND_LINE_);

	TestHelpers::StandardClientPrep(sender,destroyList);

	TestHelpers::StandardClientPrep(sender2,destroyList);

	receiver=RakPeerInterface::GetInstance();
	destroyList.Push(receiver,_FILE_AND_LINE_);
	receiver->Startup(2, &SocketDescriptor(60000,0), 1);
	receiver->SetMaximumIncomingConnections(2);
	Packet * packet;

	SystemAddress currentSystem;

	currentSystem.SetBinaryAddress("127.0.0.1");
	currentSystem.port=60000;

	printf("Connecting sender2\n");
	if (!TestHelpers::WaitAndConnectTwoPeersLocally(sender2,receiver,5000))
	{

		if (isVerbose)
			DebugTools::ShowError("Could not connect after 5 seconds\n",!noPauses && isVerbose,__LINE__,__FILE__);

		return 2;

	}

	printf("Getting ping data for lastping and lowestping\n");
	sender2->SetOccasionalPing(false);//Test the lowest ping and such without  occassionalping,occasional ping comes later
	RakTimer timer(1500);

	int lastPing=0;
	int lowestPing=0;
	TimeMS nextPing=0;

	while(!timer.IsExpired())
	{
		for (packet=receiver->Receive();packet;receiver->DeallocatePacket(packet),packet=receiver->Receive())
		{
			if (isVerbose)
				printf("Receive packet id %i\n",packet->data[0]);
		}

		for (packet=sender2->Receive();packet;sender2->DeallocatePacket(packet),packet=sender2->Receive())
		{
			if (isVerbose)
				printf("Send packet id %i\n",packet->data[0]);

		}

		if (GetTimeMS()>nextPing)
		{
			sender2->Ping(currentSystem);
			nextPing=GetTimeMS()+30;
		}

		RakSleep(3);
	}

	int averagePing=sender2->GetAveragePing(currentSystem);
	if (isVerbose)
		printf("Average Ping time %i\n",averagePing);

	lastPing=sender2->GetLastPing(currentSystem);
	lowestPing=sender2->GetLowestPing(currentSystem);

	if (isVerbose)
		printf("Last Ping time %i\n",lastPing);

	if (isVerbose)
		printf("Lowest Ping time %i\n",lowestPing);

	int returnVal=TestAverageValue(averagePing,__LINE__, noPauses, isVerbose);

	if (returnVal!=0)
	{

		return returnVal;
	}

	if (lastPing>100)//100 MS for localhost?
	{
		if (isVerbose)
			DebugTools::ShowError("Problem with the last ping time,greater then 100MS for localhost\n",!noPauses && isVerbose,__LINE__,__FILE__);

		return 3;
	}

	if (lowestPing>10)//The lowest ping for localhost should drop below 10MS at least once
	{

		if (isVerbose)
			DebugTools::ShowError("The lowest ping for localhost should drop below 10MS at least once\n",!noPauses && isVerbose,__LINE__,__FILE__);

		return 4;
	}

	if (lastPing<lowestPing)
	{

		if (isVerbose)
			DebugTools::ShowError("There is a problem if the lastping is lower than the lowestping stat\n",!noPauses && isVerbose,__LINE__,__FILE__);

		return 5;
	}

	CommonFunctions::DisconnectAndWait(sender2,"127.0.0.1",60000);//Eliminate variables.

	printf("Connecting sender\n");
	if (!TestHelpers::WaitAndConnectTwoPeersLocally(sender,receiver,5000))
	{

		if (isVerbose)
			DebugTools::ShowError("Could not connect after 5 seconds\n",!noPauses && isVerbose,__LINE__,__FILE__);

		return 2;

	}

	lastPing=0;
	lowestPing=0;
	sender->SetOccasionalPing(true);

	printf("Testing SetOccasionalPing\n");

	timer.Start();
	while(!timer.IsExpired())
	{
		for (packet=receiver->Receive();packet;receiver->DeallocatePacket(packet),packet=receiver->Receive())
		{
			if (isVerbose)
				printf("Receive packet id %i\n",packet->data[0]);
		}

		for (packet=sender->Receive();packet;sender->DeallocatePacket(packet),packet=sender->Receive())
		{
			if (isVerbose)
				printf("Send packet id %i\n",packet->data[0]);

		}

		RakSleep(3);
	}

	averagePing=sender->GetAveragePing(currentSystem);
	if (isVerbose)
		printf("Average Ping time %i\n",averagePing);

	returnVal=TestAverageValue(averagePing,__LINE__, noPauses, isVerbose);

	if (returnVal!=0)
	{

		return returnVal;
	}

	return 0;

}

int PingTestsTest::TestAverageValue(int averagePing,int line,bool noPauses,bool isVerbose)
{

	if (averagePing<0)
	{

		if (isVerbose)
			DebugTools::ShowError("Problem with the average ping time,should never be less than zero in this test\n",!noPauses && isVerbose,line,__FILE__);

		return 1;

	}

	if (averagePing>10)//Average Ping should not be greater than 10MS for localhost. Command line pings typically give < 1ms
	{

		if (isVerbose)
			DebugTools::ShowError("Average Ping should not be greater than 10MS for localhost. Command line pings typically give < 1ms\n",!noPauses && isVerbose,line,__FILE__);

		return 5;

	}

	return 0;

}

RakString PingTestsTest::GetTestName()
{

	return "PingTestsTest";

}

RakString PingTestsTest::ErrorCodeToString(int errorCode)
{

	switch (errorCode)
	{

	case 0:
		return "No error";
		break;

	case 1:
		return "Problem with the average ping time,should never be less than 0 in this test";
		break;

	case 2:
		return "Could not connect after 5 seconds";
		break;

	case 3:
		return "Problem with the last ping time,greater then 100MS for localhost";
		break;

	case 4:
		return "The lowest ping for localhost should drop below 10MS at least once";
		break;

	case 5:
		return "There is a problem if the lastping is lower than the lowestping stat";
		break;

	case 6:
		return "Average Ping should not be greater than 10MS for localhost. Command line pings typically give < 1ms";
		break;

	default:
		return "Undefined Error";
	}

}

PingTestsTest::PingTestsTest(void)
{
}

PingTestsTest::~PingTestsTest(void)
{
}

void PingTestsTest::DestroyPeers()
{

	int theSize=destroyList.Size();

	for (int i=0; i < theSize; i++)
		RakPeerInterface::DestroyInstance(destroyList[i]);

}


text:
package google

import (
	"fmt"
	"testing"

	"github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource"
)

func TestAccRedisInstanceDatasource_basic(t *testing.T) {
	t.Parallel()

	vcrTest(t, resource.TestCase{
		PreCheck:  func() { testAccPreCheck(t) },
		Providers: testAccProviders,
		Steps: []resource.TestStep{
			{
				Config: testAccRedisInstanceDatasourceConfig(randString(t, 10)),
				Check: resource.ComposeTestCheckFunc(
					checkDataSourceStateMatchesResourceState("data.google_redis_instance.redis", "google_redis_instance.redis"),
				),
			},
		},
	})
}

func testAccRedisInstanceDatasourceConfig(suffix string) string {
	return fmt.Sprintf(`
resource "google_redis_instance" "redis" {
  name               = "redis-test-%s"
  memory_size_gb     = 1
}

data "google_redis_instance" "redis" {
  name = google_redis_instance.redis.name
}
`, suffix)
}


text:
from setuptools import setup

setup(
    name="simple_namespace",
    version="1.0",
    namespace_packages=["simple_namespace"],
    packages=["simple_namespace.module"],
)


text:
<?php
require_once('init.php');

// start tests
$t = new lime_test(28, new lime_output_color());

$t->diag('check getMaxRating()');

// default
$t->is(sfRatingToolkit::getMaxRating(new $test_class), 5, 'retrieve correct default value');

sfConfig::set('app_rating_default_max', 8);
$t->is(sfRatingToolkit::getMaxRating(new $test_class), 8, 'retrieve correct default value, even when set');

sfConfig::set('app_rating_default_max', "8");
$t->isa_ok(sfRatingToolkit::getMaxRating(new $test_class), 'integer', 'MAX_RATING is an integer');

// get
sfConfig::set(sprintf('app_rating_%s_max', $test_class), 5);
$t->is(sfRatingToolkit::getMaxRating(new $test_class), 5, 'retrieve correct value');

sfConfig::set(sprintf('app_rating_%s_max', $test_class), 10);
$t->is(sfRatingToolkit::getMaxRating(new $test_class), 10, 'retrieve correct value, even when changed');

// interval
try
{
  sfConfig::set(sprintf('app_rating_%s_max', $test_class), 11);
  sfRatingToolkit::getMaxRating(new $test_class);

  $t->fail('no code should be executed after throwing an sfRatingException');
}
catch (sfRatingException $e)
{
  $t->pass('throw exception when greather than 10');
}

try
{
  sfConfig::set(sprintf('app_rating_%s_max', $test_class), 0);
  sfRatingToolkit::getMaxRating(new $test_class);

  $t->fail('no code should be executed after throwing an sfRatingException');
}
catch (sfRatingException $e)
{
  $t->pass('throw exception when less than 1');
}

$t->todo('check getUserId()');

$t->is(sfRatingToolkit::getUserId(), null, 'no auth');

$t->todo('check addTokenToSession()');

$t->diag('check generateToken()');

$t->is(sfRatingToolkit::generateToken($test_class, 23), md5($test_class.'-23-r4t4bl3'), 'without config salt');

$salt = '3kbt2';
sfConfig::set('app_rating_salt', $salt);
$t->is(sfRatingToolkit::generateToken($test_class, 54), md5($test_class.'-54-'.$salt), 'with config salt');

$t->todo('check retrieveFromToken()');

$t->diag('check getObjectRatingField()');
sfConfig::clear();

$t->ok(is_null(sfRatingToolkit::getObjectRatingField(new $test_class)), 'get null if no field is set');

$field = 'rating';
sfConfig::set('app_rating_' . $test_class, array('rating_field' => $field));
$t->is(sfRatingToolkit::getObjectRatingField(new $test_class), $field, 'retrieve correct value');

sfConfig::clear();
$t->ok(is_null(sfRatingToolkit::getObjectRatingField(new $test_class)), 'get null if no field is set for this class');

$t->diag('check getObjectReferenceField()');
sfConfig::clear();

$t->ok(is_null(sfRatingToolkit::getObjectReferenceField($test_class)), 'get null if no field is set for class name');
$t->ok(is_null(sfRatingToolkit::getObjectReferenceField(new $test_class)), 'get null if no field is set for object');

$field = 'rating';
sfConfig::set('app_rating_' . $test_class, array('reference_field' => $field));
$t->is(sfRatingToolkit::getObjectReferenceField($test_class), $field, 'retrieve correct value for class name');
$t->is(sfRatingToolkit::getObjectReferenceField(new $test_class), $field, 'retrieve correct value for object');

sfConfig::clear();
$t->ok(is_null(sfRatingToolkit::getObjectReferenceField($test_class)), 'get null if no field is set for this class name');
$t->ok(is_null(sfRatingToolkit::getObjectReferenceField(new $test_class)), 'get null if no field is set for this object');

$t->todo('check getReferenceKey()');

$t->diag('check getPrecision()');

$t->is(sfRatingToolkit::getPrecision(), 2, 'without any default');

sfConfig::set('app_rating_default_precision', 3);
$t->is(sfRatingToolkit::getPrecision(), 3, 'with config default');

$t->is(sfRatingToolkit::getPrecision(4), 4, 'with argument');

sfConfig::set('app_rating_precision', 6);
$t->is(sfRatingToolkit::getPrecision(), 6, 'with global');

sfConfig::set('app_rating_precision', 2);
$t->is(sfRatingToolkit::getPrecision(4), 2, 'with global and argument');


text: Pmacctstats::Application.config.secret_token = ENV['SECRET_TOKEN']


text:
from functools import wraps
from typing import Callable, Dict, Set, Tuple, Union

from django.http import HttpRequest, HttpResponse
from django.urls import path
from django.urls.resolvers import URLPattern
from django.utils.cache import add_never_cache_headers
from django.views.decorators.csrf import csrf_exempt, csrf_protect
from typing_extensions import Concatenate, ParamSpec

from zerver.decorator import (
    authenticated_json_view,
    authenticated_rest_api_view,
    authenticated_uploads_api_view,
    process_as_post,
    public_json_view,
)
from zerver.lib.exceptions import MissingAuthenticationError
from zerver.lib.request import RequestNotes
from zerver.lib.response import json_method_not_allowed

ParamT = ParamSpec("ParamT")
METHODS = ("GET", "HEAD", "POST", "PUT", "DELETE", "PATCH")

def default_never_cache_responses(
    view_func: Callable[Concatenate[HttpRequest, ParamT], HttpResponse]
) -> Callable[Concatenate[HttpRequest, ParamT], HttpResponse]:
    """Patched version of the standard Django never_cache_responses
    decorator that adds headers to a response so that it will never be
    cached, unless the view code has already set a Cache-Control
    header.
    """

    @wraps(view_func)
    def _wrapped_view_func(
        request: HttpRequest, /, *args: ParamT.args, **kwargs: ParamT.kwargs
    ) -> HttpResponse:
        response = view_func(request, *args, **kwargs)
        if response.has_header("Cache-Control"):
            return response

        add_never_cache_headers(response)
        return response

    return _wrapped_view_func

def get_target_view_function_or_response(
    request: HttpRequest, rest_dispatch_kwargs: Dict[str, object]
) -> Union[Tuple[Callable[..., HttpResponse], Set[str]], HttpResponse]:
    """Helper for REST API request dispatch. The rest_dispatch_kwargs
    parameter is expected to be a dictionary mapping HTTP methods to
    a mix of view functions and (view_function, {view_flags}) tuples.

    * Returns an error HttpResponse for unsupported HTTP methods.

    * Otherwise, returns a tuple containing the view function
      corresponding to the request's HTTP method, as well as the
      appropriate set of view flags.

    HACK: Mutates the passed rest_dispatch_kwargs, removing the HTTP
    method details but leaving any other parameters for the caller to
    pass directly to the view function. We should see if we can remove
    this feature; it's not clear it's actually used.

    """
    supported_methods: Dict[str, object] = {}
    request_notes = RequestNotes.get_notes(request)
    if request_notes.saved_response is not None:
        # For completing long-polled Tornado requests, we skip the
        # view function logic and just return the response.
        return request_notes.saved_response

    # The list() duplicates rest_dispatch_kwargs, since this loop
    # mutates the original.
    for arg in list(rest_dispatch_kwargs):
        if arg in METHODS:
            supported_methods[arg] = rest_dispatch_kwargs[arg]
            del rest_dispatch_kwargs[arg]

    if "GET" in supported_methods:
        supported_methods.setdefault("HEAD", supported_methods["GET"])

    if request.method == "OPTIONS":
        response = HttpResponse(status=204)  # No content
        response["Allow"] = ", ".join(sorted(supported_methods.keys()))
        return response

    # Override requested method if magic method=??? parameter exists
    method_to_use = request.method
    if request.POST and "method" in request.POST:
        method_to_use = request.POST["method"]

    if method_to_use in supported_methods:
        entry = supported_methods[method_to_use]
        if isinstance(entry, tuple):
            handler, view_flags = entry
            assert callable(handler)
            assert isinstance(view_flags, set)
            return handler, view_flags
        assert callable(entry)
        return entry, set()

    return json_method_not_allowed(list(supported_methods.keys()))

@default_never_cache_responses
@csrf_exempt
def rest_dispatch(request: HttpRequest, /, **kwargs: object) -> HttpResponse:
    """Dispatch to a REST API endpoint.

    Authentication is verified in the following ways:
        * for paths beginning with /api, HTTP basic auth
        * for paths beginning with /json (used by the web client), the session token

    Unauthenticated requests may use this endpoint only with the
    allow_anonymous_user_web view flag.

    This calls the function named in kwargs[request.method], if that request
    method is supported, and after wrapping that function to:

        * protect against CSRF (if the user is already authenticated through
          a Django session)
        * authenticate via an API key (otherwise)
        * coerce PUT/PATCH/DELETE into having POST-like semantics for
          retrieving variables

    Any keyword args that are *not* HTTP methods are passed through to the
    target function.

    Never make a urls.py pattern put user input into a variable called GET, POST,
    etc, as that is where we route HTTP verbs to target functions.

    """
    result = get_target_view_function_or_response(request, kwargs)
    if isinstance(result, HttpResponse):
        return result
    target_function, view_flags = result
    request_notes = RequestNotes.get_notes(request)

    # Set request_notes.query for update_activity_user(), which is called
    # by some of the later wrappers.
    request_notes.query = target_function.__name__

    # We want to support authentication by both cookies (web client)
    # and API keys (API clients). In the former case, we want to
    # do a check to ensure that CSRF etc is honored, but in the latter
    # we can skip all of that.
    #
    # Security implications of this portion of the code are minimal,
    # as we should worst-case fail closed if we miscategorize a request.

    # for some special views (e.g. serving a file that has been
    # uploaded), we support using the same URL for web and API clients.
    if "override_api_url_scheme" in view_flags and "Authorization" in request.headers:
        # This request uses standard API based authentication.
        # For override_api_url_scheme views, we skip our normal
        # rate limiting, because there are good reasons clients
        # might need to (e.g.) request a large number of uploaded
        # files or avatars in quick succession.
        target_function = authenticated_rest_api_view(skip_rate_limiting=True)(target_function)
    elif "override_api_url_scheme" in view_flags and request.GET.get("api_key") is not None:
        # This request uses legacy API authentication.  We
        # unfortunately need that in the React Native mobile apps,
        # because there's no way to set the Authorization header in
        # React Native.  See last block for rate limiting notes.
        target_function = authenticated_uploads_api_view(skip_rate_limiting=True)(target_function)
    # /json views (web client) validate with a session token (cookie)
    elif not request.path.startswith("/api") and request.user.is_authenticated:
        # Authenticated via sessions framework, only CSRF check needed
        auth_kwargs = {}
        if "override_api_url_scheme" in view_flags:
            auth_kwargs["skip_rate_limiting"] = True
        target_function = csrf_protect(authenticated_json_view(target_function, **auth_kwargs))

    # most clients (mobile, bots, etc) use HTTP basic auth and REST calls, where instead of
    # username:password, we use email:apiKey
    elif "Authorization" in request.headers:
        # Wrap function with decorator to authenticate the user before
        # proceeding
        target_function = authenticated_rest_api_view(
            allow_webhook_access="allow_incoming_webhooks" in view_flags,
        )(target_function)
    elif (
        request.path.startswith(("/json", "/avatar", "/user_uploads", "/thumbnail"))
        and "allow_anonymous_user_web" in view_flags
    ):
        # For endpoints that support anonymous web access, we do that.
        # TODO: Allow /api calls when this is stable enough.
        target_function = csrf_protect(public_json_view(target_function))
    else:
        # Otherwise, throw an authentication error; our middleware
        # will generate the appropriate HTTP response.
        raise MissingAuthenticationError()

    if request.method in ["DELETE", "PATCH", "PUT"]:
        # process_as_post needs to be the outer decorator, because
        # otherwise we might access and thus cache a value for
        # request.POST.
        target_function = process_as_post(target_function)

    return target_function(request, **kwargs)

def rest_path(
    route: str,
    **handlers: Union[Callable[..., HttpResponse], Tuple[Callable[..., HttpResponse], Set[str]]],
) -> URLPattern:
    return path(route, rest_dispatch, handlers)


text:
#include "config.h"

#if ENABLE(VIDEO)
#include "RenderMedia.h"

#include "HTMLMediaElement.h"
#include "RenderView.h"

namespace WebCore {

RenderMedia::RenderMedia(HTMLMediaElement* video)
    : RenderImage(video)
{
    setImageResource(RenderImageResource::create());
}

RenderMedia::RenderMedia(HTMLMediaElement* video, const IntSize& intrinsicSize)
    : RenderImage(video)
{
    setImageResource(RenderImageResource::create());
    setIntrinsicSize(intrinsicSize);
}

RenderMedia::~RenderMedia()
{
}

HTMLMediaElement* RenderMedia::mediaElement() const
{
    return static_cast<HTMLMediaElement*>(node());
}

void RenderMedia::layout()
{
    StackStats::LayoutCheckPoint layoutCheckPoint;
    LayoutSize oldSize = contentBoxRect().size();

    RenderImage::layout();

    RenderBox* controlsRenderer = toRenderBox(m_children.firstChild());
    if (!controlsRenderer)
        return;

    LayoutSize newSize = contentBoxRect().size();
    if (newSize == oldSize && !controlsRenderer->needsLayout())
        return;

    // When calling layout() on a child node, a parent must either push a LayoutStateMaintainter, or
    // instantiate LayoutStateDisabler. Since using a LayoutStateMaintainer is slightly more efficient,
    // and this method will be called many times per second during playback, use a LayoutStateMaintainer:
    LayoutStateMaintainer statePusher(view(), this, locationOffset(), hasTransform() || hasReflection() || style()->isFlippedBlocksWritingMode());

    controlsRenderer->setLocation(LayoutPoint(borderLeft(), borderTop()) + LayoutSize(paddingLeft(), paddingTop()));
    controlsRenderer->style()->setHeight(Length(newSize.height(), Fixed));
    controlsRenderer->style()->setWidth(Length(newSize.width(), Fixed));
    controlsRenderer->setNeedsLayout(true, MarkOnlyThis);
    controlsRenderer->layout();
    setChildNeedsLayout(false);

    statePusher.pop();
}

void RenderMedia::paintReplaced(PaintInfo&, const LayoutPoint&)
{
}

} // namespace WebCore

#endif


text:
<?php //-->

namespace Controllers;

use Modules\Helper;
use Modules\Rest;
use Services\User as U;
use Services\Permission;

class User
{
    /* Constants
    --------------------------------------------*/
    /* Public Properties
    --------------------------------------------*/
    /* Protected Properties
    --------------------------------------------*/
    /* Public Methods
    --------------------------------------------*/
    public static $permissions = array(
        'GET' => Permission::USER_VIEW,
        'POST' => Permission::USER_CREATE,
        'PUT' => Permission::USER_UPDATE,
        'DELETE' => Permission::USER_REMOVE,
    );

    public function main()
    {
        // restrict the username not to be change
        if(Helper::getRequestMethod() == 'PUT') {
            if(Helper::getJson('username')) {
                return Helper::error('USERNAME_MUST_NOT_CHANGE',
                    'Username cannot be change');
            }
        }

        // call to api
        return Rest::resource(new U(), true);
    }

    /* Protected Methods
    --------------------------------------------*/
    /* Private Methods
    --------------------------------------------*/
}


text:
import os
from ansible.module_utils.basic import *

def create_test_file(name, content):
    with open(name, 'w') as f:
        f.write(content)

def delete_test_file(name):
    if os.path.exists(name):
        os.remove(name)

if __name__ == '__main__':
    module = AnsibleModule(
        argument_spec = dict(
            state = dict(default='present', choices=['present', 'absent']),
            name = dict(required=True),
            content = dict(type='str')))

    result = module.params.copy()
    result['changed'] = False

    if module.params['state'] == 'present':
        create_test_file(module.params['name'], module.params['content'])
        result['changed'] = True

    elif module.params['state'] == 'absent':
        delete_test_file(module.params['name'])
        result['changed'] = True

    module.exit_json(**result)


text:
import { moduleForComponent, test } from 'ember-qunit';
import hbs from 'htmlbars-inline-precompile';

moduleForComponent('hallo-editor', 'Integration | Component | hallo editor', {
  integration: true
});

test('it renders', function(assert) {

  // Set any properties with this.set('myProperty', 'value');
  // Handle any actions with this.on('myAction', function(val) { ... });

  this.render(hbs`{{hallo-editor}}`);

  assert.equal(this.$().text().trim(), '');

  // Template block usage:
  this.render(hbs`
    {{#hallo-editor}}
      template block text
    {{/hallo-editor}}
  `);

  assert.equal(this.$().text().trim(), 'template block text');
});


text:
/**
* @author Alexey V. Varlamov
*/

package org.apache.harmony.security.tests.support;

import java.security.Permission;

/**
 * Custom security manager
 */

public class SecurityChecker extends SecurityManager {

    public boolean enableAccess;

    public Permission checkTarget;

    public boolean checkAsserted;

    public SecurityChecker(Permission target, boolean enable) {
        checkAsserted = false;
        checkTarget = target;
        enableAccess = enable;
    }

    public void checkPermission(Permission p) {
        if (checkTarget.equals(p)) {
            checkAsserted = true;
            if (!enableAccess) {
                throw new SecurityException();
            }
        }
    }

    public SecurityChecker reset() {
        checkAsserted = false;
        return this;
    }
}


text:
package io.disassemble.asm.util;

/**
 * Uses Combinatorics to calculate alphabetical strings to and from integers.
 *
 * @author Tyler Sedlar
 * @since 10/31/14
 */
public class AlphaLabel {

    /**
     * Gets the alpha label for the given number [1 = A, 26 = Z, 27 = AA]
     *
     * @param n The number to get the alpha label for
     * @return the alpha label for the given number
     */
    public static String get(int n) {
        char[] buf = new char[(int) Math.floor(StrictMath.log(25 * (n + 1)) / StrictMath.log(26))];
        for (int i = buf.length - 1; i >= 0; i--) {
            buf[i] = (char) ('A' + (--n) % 26);
            n /= 26;
        }
        return new String(buf);
    }

    /**
     * Gets the numeric value of the given label
     *
     * @param label the label to get the numeric value for
     * @return the numeric value of the given label
     */
    public static int numeric(String label) {
        int result = 0;
        for (int i = label.length() - 1; i >= 0; i--) {
            result = result + (label.charAt(i) - 64) * (int) StrictMath.pow(26, label.length() - (i + 1));
        }
        return result;
    }
}


text:
"""
Margin implementations for a :class:`~prompt_toolkit.layout.containers.Window`.
"""
from __future__ import unicode_literals

from abc import ABCMeta, abstractmethod
from six import with_metaclass
from six.moves import range

from prompt_toolkit.filters import to_filter
from prompt_toolkit.formatted_text import fragment_list_to_text, to_formatted_text
from prompt_toolkit.utils import get_cwidth

__all__ = [
    'Margin',
    'NumberedMargin',
    'ScrollbarMargin',
    'ConditionalMargin',
    'PromptMargin',
]

class Margin(with_metaclass(ABCMeta, object)):
    """
    Base interface for a margin.
    """
    @abstractmethod
    def get_width(self, get_ui_content):
        """
        Return the width that this margin is going to consume.

        :param get_ui_content: Callable that asks the user control to create
            a :class:`.UIContent` instance. This can be used for instance to
            obtain the number of lines.
        """
        return 0

    @abstractmethod
    def create_margin(self, window_render_info, width, height):
        """
        Creates a margin.
        This should return a list of (style_str, text) tuples.

        :param window_render_info:
            :class:`~prompt_toolkit.layout.containers.WindowRenderInfo`
            instance, generated after rendering and copying the visible part of
            the :class:`~prompt_toolkit.layout.controls.UIControl` into the
            :class:`~prompt_toolkit.layout.containers.Window`.
        :param width: The width that's available for this margin. (As reported
            by :meth:`.get_width`.)
        :param height: The height that's available for this margin. (The height
            of the :class:`~prompt_toolkit.layout.containers.Window`.)
        """
        return []

class NumberedMargin(Margin):
    """
    Margin that displays the line numbers.

    :param relative: Number relative to the cursor position. Similar to the Vi
                     'relativenumber' option.
    :param display_tildes: Display tildes after the end of the document, just
        like Vi does.
    """
    def __init__(self, relative=False, display_tildes=False):
        self.relative = to_filter(relative)
        self.display_tildes = to_filter(display_tildes)

    def get_width(self, get_ui_content):
        line_count = get_ui_content().line_count
        return max(3, len('%s' % line_count) + 1)

    def create_margin(self, window_render_info, width, height):
        relative = self.relative()

        style = 'class:line-number'
        style_current = 'class:line-number,current-line-number'

        # Get current line number.
        current_lineno = window_render_info.ui_content.cursor_position.y

        # Construct margin.
        result = []
        last_lineno = None

        for y, lineno in enumerate(window_render_info.displayed_lines):
            # Only display line number if this line is not a continuation of the previous line.
            if lineno != last_lineno:
                if lineno is None:
                    pass
                elif lineno == current_lineno:
                    # Current line.
                    if relative:
                        # Left align current number in relative mode.
                        result.append((style_current, '%i' % (lineno + 1)))
                    else:
                        result.append((style_current, ('%i ' % (lineno + 1)).rjust(width)))
                else:
                    # Other lines.
                    if relative:
                        lineno = abs(lineno - current_lineno) - 1

                    result.append((style, ('%i ' % (lineno + 1)).rjust(width)))

            last_lineno = lineno
            result.append(('', '\n'))

        # Fill with tildes.
        if self.display_tildes():
            while y < window_render_info.window_height:
                result.append(('class:tilde', '~\n'))
                y += 1

        return result

class ConditionalMargin(Margin):
    """
    Wrapper around other :class:`.Margin` classes to show/hide them.
    """
    def __init__(self, margin, filter):
        assert isinstance(margin, Margin)

        self.margin = margin
        self.filter = to_filter(filter)

    def get_width(self, ui_content):
        if self.filter():
            return self.margin.get_width(ui_content)
        else:
            return 0

    def create_margin(self, window_render_info, width, height):
        if width and self.filter():
            return self.margin.create_margin(window_render_info, width, height)
        else:
            return []

class ScrollbarMargin(Margin):
    """
    Margin displaying a scrollbar.

    :param display_arrows: Display scroll up/down arrows.
    """
    def __init__(self, display_arrows=False, up_arrow_symbol='^', down_arrow_symbol='v'):
        self.display_arrows = to_filter(display_arrows)
        self.up_arrow_symbol = up_arrow_symbol
        self.down_arrow_symbol = down_arrow_symbol

    def get_width(self, ui_content):
        return 1

    def create_margin(self, window_render_info, width, height):
        content_height = window_render_info.content_height
        window_height = window_render_info.window_height
        display_arrows = self.display_arrows()

        if display_arrows:
            window_height -= 2

        try:
            fraction_visible = len(window_render_info.displayed_lines) / float(content_height)
            fraction_above = window_render_info.vertical_scroll / float(content_height)

            scrollbar_height = int(min(window_height, max(1, window_height * fraction_visible)))
            scrollbar_top = int(window_height * fraction_above)
        except ZeroDivisionError:
            return []
        else:
            def is_scroll_button(row):
                " True if we should display a button on this row. "
                return scrollbar_top <= row <= scrollbar_top + scrollbar_height

            # Up arrow.
            result = []
            if display_arrows:
                result.extend([
                    ('class:scrollbar.arrow', self.up_arrow_symbol),
                    ('class:scrollbar', '\n')
                ])

            # Scrollbar body.
            scrollbar_background = 'class:scrollbar.background'
            scrollbar_background_start = 'class:scrollbar.background,scrollbar.start'
            scrollbar_button = 'class:scrollbar.button'
            scrollbar_button_end = 'class:scrollbar.button,scrollbar.end'

            for i in range(window_height):
                if is_scroll_button(i):
                    if not is_scroll_button(i + 1):
                        # Give the last cell a different style, because we
                        # want to underline this.
                        result.append((scrollbar_button_end, ' '))
                    else:
                        result.append((scrollbar_button, ' '))
                else:
                    if is_scroll_button(i + 1):
                        result.append((scrollbar_background_start, ' '))
                    else:
                        result.append((scrollbar_background, ' '))
                result.append(('', '\n'))

            # Down arrow
            if display_arrows:
                result.append(('class:scrollbar.arrow', self.down_arrow_symbol))

            return result

class PromptMargin(Margin):
    """
    [Deprecated]

    Create margin that displays a prompt.
    This can display one prompt at the first line, and a continuation prompt
    (e.g, just dots) on all the following lines.

    This `PromptMargin` implementation has been largely superseded in favor of
    the `get_line_prefix` attribute of `Window`. The reason is that a margin is
    always a fixed width, while `get_line_prefix` can return a variable width
    prefix in front of every line, making it more powerful, especially for line
    continuations.

    :param get_prompt: Callable returns formatted text or a list of
        `(style_str, type)` tuples to be shown as the prompt at the first line.
    :param get_continuation: Callable that takes three inputs. The width (int),
        line_number (int), and is_soft_wrap (bool). It should return formatted
        text or a list of `(style_str, type)` tuples for the next lines of the
        input.
    """
    def __init__(self, get_prompt, get_continuation=None):
        assert callable(get_prompt)
        assert get_continuation is None or callable(get_continuation)

        self.get_prompt = get_prompt
        self.get_continuation = get_continuation

    def get_width(self, ui_content):
        " Width to report to the `Window`. "
        # Take the width from the first line.
        text = fragment_list_to_text(self.get_prompt())
        return get_cwidth(text)

    def create_margin(self, window_render_info, width, height):
        get_continuation = self.get_continuation
        result = []

        # First line.
        result.extend(to_formatted_text(self.get_prompt()))

        # Next lines.
        if get_continuation:
            last_y = None

            for y in window_render_info.displayed_lines[1:]:
                result.append(('', '\n'))
                result.extend(to_formatted_text(get_continuation(width, y, y == last_y)))
                last_y = y

        return result


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<title>vgatext library: Data Structures</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>

<link href="doxygen.css" rel="stylesheet" type="text/css" />

vgatext library
    v0.90

Provides functions to simplify Propeller text display on a VGA monitor

Main Page

Data Structures

Files

Data Structures

Data Structure Index

Data Structures

Here are the data structures with brief descriptions:

_vga_text_struct

<address class="footer">
Generated on Sun Apr 27 2014 14:20:56 for vgatext library by

 1.8.1.2
</address>


text:
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 *
This class initializes the fields of ReportWriter.java

 * @author Ashwin Gupta
 * @version 1.1
 */
public class ReportWriter
{

	private BufferedWriter writer = null;

	/**
	 * Specify the reportWriter field
	 */
	private static ReportWriter reportWriter = null;

	/**
	 * Specify the fileNamePrefix field
	 */
	private String fileNamePrefix = "\\build_report_";

	/**
	 * Specify the dateFormatSuffix field
	 */
	private String dateFormatSuffix = "dd_MM_yyyy_HH_mm_ss";

	/**
	 * @return report writer object
	 */
	public static ReportWriter getInstance()
	{
		if (reportWriter == null)
		{
			reportWriter = new ReportWriter();
		}
		return reportWriter;
	}

	/**
	 * @return dir path
	 */
	public String getDirPath()
	{
		String currDir = System.getProperty("user.dir");
		StringBuffer dirPath = new StringBuffer(currDir);
		dirPath.append("\\report");
		System.out.println("Build report directory: "+dirPath);
		return dirPath.toString();
	}

	public String getFileName(String currDirString)
	{
		StringBuffer fileName = new StringBuffer(fileNamePrefix);
		StringBuffer filePath = new StringBuffer(currDirString);
		Date currDate = new Date();
	    SimpleDateFormat dateFormat = new SimpleDateFormat(dateFormatSuffix);
		String dateStr = dateFormat.format(currDate);
		filePath.append(fileName + dateStr +".txt");
		System.out.println("Build report File Name: "+fileName + dateStr +".txt");
		return filePath.toString();
	}

	public void createDir(String dirPath)
	{
		File dir = new File(dirPath);

		if (!dir.exists())
		{
			System.out.println("Not exists");
			boolean success = dir.mkdir();
			if (!success)
			{
				System.out.println(" File is not created");
				return;
			}
		}
	}

	public void createFile(String filePath)
	{
		try
		{
			//System.out.println(filePath);
			writer = new BufferedWriter(new FileWriter(filePath));
		}
		catch (IOException e)
		{
			e.printStackTrace();
		}
	}

	public void closeFile()
	{
		if (writer != null)
		{
			try
			{
				writer.close();
			}
			catch (IOException e)
			{
				e.printStackTrace();
			}
		}
	}

	public void writeToFile(String str)
	{
		try
		{
			//System.out.println(str);
			writer.write(str);
		}
		catch (IOException e)
		{
			e.printStackTrace();
		}
	}
}


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

<title>M-Index</title>
<meta name="date" content="2015-12-31">
<link rel="stylesheet" type="text/css" href="../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Use

Tree

Index

Help

Prev Letter

Next Letter

Frames

No Frames

All Classes

A B C D E F G H I J K L M N O P Q R S T U V W X Y

M

m_bDebug - Variable in class midiInDump.DumpReceiver

m_bPrintTimeStampAsTicks - Variable in class midiInDump.DumpReceiver

m_printStream - Variable in class midiInDump.DumpReceiver

Main - Class in gui

Main program class.

Main() - Constructor for class gui.Main

Create the application.

main(String[]) - Static method in class gui.Main

Launches the application.

mainCard - Static variable in class gui.Main

mainWindowH - Static variable in class gui.AnimationGUI

mainWindowH - Static variable in class gui.CheckersGUI

mainWindowH - Static variable in class gui.Error

mainWindowH - Static variable in class gui.GameOfLifeGUI

mainWindowH - Static variable in class gui.LightsOutGUI

mainWindowH - Static variable in class gui.PianoGUI

mainWindowH - Static variable in class gui.ReactionGameGUI

mainWindowH - Static variable in class gui.ReactiveDemoGUI

mainWindowH - Static variable in class gui.SimonGUI

mainWindowH - Static variable in class gui.SnakeGUI

mainWindowH - Static variable in class gui.StatisticsGUI

mainWindowH - Static variable in class gui.TextScrollGUI

mainWindowW - Static variable in class gui.AnimationGUI

mainWindowW - Static variable in class gui.CheckersGUI

mainWindowW - Static variable in class gui.Error

mainWindowW - Static variable in class gui.GameOfLifeGUI

mainWindowW - Static variable in class gui.LightsOutGUI

mainWindowW - Static variable in class gui.PianoGUI

mainWindowW - Static variable in class gui.ReactionGameGUI

mainWindowW - Static variable in class gui.ReactiveDemoGUI

mainWindowW - Static variable in class gui.SimonGUI

mainWindowW - Static variable in class gui.SnakeGUI

mainWindowW - Static variable in class gui.StatisticsGUI

mainWindowW - Static variable in class gui.TextScrollGUI

mainWindowX - Static variable in class gui.AnimationGUI

mainWindowX - Static variable in class gui.CheckersGUI

mainWindowX - Static variable in class gui.Error

mainWindowX - Static variable in class gui.GameOfLifeGUI

mainWindowX - Static variable in class gui.LightsOutGUI

mainWindowX - Static variable in class gui.PianoGUI

mainWindowX - Static variable in class gui.ReactionGameGUI

mainWindowX - Static variable in class gui.ReactiveDemoGUI

mainWindowX - Static variable in class gui.SimonGUI

mainWindowX - Static variable in class gui.SnakeGUI

mainWindowX - Static variable in class gui.StatisticsGUI

mainWindowX - Static variable in class gui.TextScrollGUI

mainWindowY - Static variable in class gui.AnimationGUI

mainWindowY - Static variable in class gui.CheckersGUI

mainWindowY - Static variable in class gui.Error

mainWindowY - Static variable in class gui.GameOfLifeGUI

mainWindowY - Static variable in class gui.LightsOutGUI

mainWindowY - Static variable in class gui.PianoGUI

mainWindowY - Static variable in class gui.ReactionGameGUI

mainWindowY - Static variable in class gui.ReactiveDemoGUI

mainWindowY - Static variable in class gui.SimonGUI

mainWindowY - Static variable in class gui.SnakeGUI

mainWindowY - Static variable in class gui.StatisticsGUI

mainWindowY - Static variable in class gui.TextScrollGUI

map - Static variable in class launchpad_s_plus.Launchpad

maxDelay - Static variable in class games.ReactionGame

maxMissedDelay - Static variable in class games.ReactionGame

maxOctaveShift - Static variable in class piano.Piano

maxOnTime - Static variable in class games.ReactionGame

maxSecondaryWindowW - Variable in class gui.Main

maxSimultaneous - Static variable in class tech_demo.Animation

maxTempo - Static variable in class piano.Piano

maxTickLength - Variable in class games.GameOfLife

maxVelocity - Static variable in class piano.Piano

menuBar - Static variable in class gui.Main

message - Static variable in class tech_demo.ScrollingText

Metronome - Class in tech_demo

Implements methods to play a metronome, for use with the Piano Demo.

Metronome() - Constructor for class tech_demo.Metronome

Unused Constructor

Metronome(int, int, String, String, int, int, int) - Constructor for class tech_demo.Metronome

Constructor for Metronome.

metronomeTick - Variable in class tech_demo.Metronome

mid - Static variable in class launchpad_s_plus.Colors

MidiCommon - Class in midiInDump

Utility methods for MIDI examples.

MidiCommon() - Constructor for class midiInDump.MidiCommon

midiFromLP - Static variable in class launchpad_s_plus.Launchpad

midiFromvrt - Static variable in class launchpad_s_plus.VirtualMIDI

midiInDump - package midiInDump

Adapted external API originally used to display on console all MIDI input
 messages.

 Used in this project to detect when there is a MIDI input received

MidiInDump - Class in midiInDump

Dumps input into console and notifies listeners

MidiInDump() - Constructor for class midiInDump.MidiInDump

midilist - Static variable in class launchpad_s_plus.DisplayDevices

midilist - Static variable in class launchpad_s_plus.SetupProcess

midiMessage - Static variable in class launchpad_s_plus.SetMidiMessage

midiToLP - Static variable in class launchpad_s_plus.Launchpad

midiTovrt - Static variable in class launchpad_s_plus.VirtualMIDI

minDelay - Static variable in class games.ReactionGame

minMissedDelay - Static variable in class games.ReactionGame

minOctaveShift - Static variable in class piano.Piano

minSimultaneous - Static variable in class tech_demo.Animation

minTempo - Static variable in class piano.Piano

minTickLength - Variable in class games.GameOfLife

minVelocity - Static variable in class piano.Piano

mnFile - Static variable in class gui.Main

mnStats - Static variable in class gui.Main

mntmExit - Static variable in class gui.Main

mntmReconnect - Static variable in class gui.Main

mntmStatistics - Static variable in class gui.Main

moreButton - Static variable in class gui.AnimationGUI

mouseIsInBounds(JLabel, MouseEvent) - Method in class gui.Main

Checks whether the mouse in within the bounds of the given card

moveDelay() - Method in class games.Snake

Delays for a duration determined by the difficulty and snake length

movePlayerTo(int, int, int, int, int, int, int, boolean, boolean) - Method in class games.Checkers

Move selected player's piece to designated location based on input
 parameters

moves - Variable in class games.Checkers2.CheckerCell

moveSnake(int) - Method in class games.Snake

Moves the snake into the given direction

movingSnake() - Method in class games.Snake

Moves the snake, updates the board, increments the amount of times moved
 and updates the GUI with the new score

mtr - Variable in class piano.Piano

A B C D E F G H I J K L M N O P Q R S T U V W X Y

Skip navigation links

Overview

Package

Class

Use

Tree

Index

Help

Prev Letter

Next Letter

Frames

No Frames

All Classes


text:
package org.usfirst.frc.team847.robot;
import edu.wpi.first.wpilibj.*;

public class ObstacleArmElbow implements RobotMap{

	GamePad gamePad;

	CANTalon Elbow = new CANTalon(CANTALON_ELBOW);
	CANTalon Shoulder = new CANTalon(CANTALON_SHOULDER);

	AnalogInput sPot;
	AnalogInput ePot;

	double ePosition;
	double sPosition;

	boolean elbowQuadrantOne = true;
	boolean is15broke = false;
	boolean isHeightBroke = false;

	public ObstacleArmElbow(GamePad xbox){

		sPot = new AnalogInput(ANALOG_IN_SHOULDER);
		ePot = new AnalogInput(ANALOG_IN_ELBOW);

		gamePad = xbox;

		Shoulder.set(0);
		Elbow.set(0);
	}

	public void armOverride(){
		double reach_S = -gamePad.rightStickY() * SHOULDER_SPEED_ADJ;
		double reach_E = -gamePad.leftStickY() * ELBOW_SPEED_ADJ;
		ePosition = ePot.getAverageVoltage();
		sPosition = sPot.getAverageVoltage();

		System.out.println("ShdlrPot: " + sPosition);
		System.out.println("ElbowPot: " + ePosition);

		if(sPosition >= MAX_S && reach_S > 0)
			reach_S = 0;
		else if(sPosition <= MIN_S && reach_S < 0)
			reach_S = 0;

		if( ePosition <= MIN_E  && reach_E < 0)
			reach_E = 0;

		Shoulder.set(reach_S);
		Elbow.set(reach_E);
	}

	public void moveArm (){
		ePosition = ePot.getAverageVoltage();
		sPosition = sPot.getAverageVoltage();

		MaxReachCheck();
		shoulderJoint();
		elbowJoint();
	}

	public void shoulderJoint(){

		double reach_S = -gamePad.rightStickY() * SHOULDER_SPEED_ADJ;

		if(is15broke && reach_S > 0)
			reach_S = 0;

		if(isHeightBroke && reach_S < 0)
			reach_S = 0;

		if(Math.abs(reach_S) > 0){
			if(sPosition >= MAX_S && reach_S > 0)
				reach_S = 0;
			else if(sPosition <= MIN_S && reach_S < 0)
				reach_S = 0;
		}

		//System.out.println("Shdlr:" + reach_S);
		//System.out.println("ShdlrPot: " + sPosition);

		Shoulder.set(reach_S);
	}

	public void elbowJoint(){

		double reach_E = -gamePad.leftStickY() * ELBOW_SPEED_ADJ;

		if(is15broke){
			System.out.println("reach");
			if(elbowQuadrantOne && reach_E < 0)
				reach_E = 0;
			else if(!elbowQuadrantOne && reach_E > 0)
				reach_E = 0;
		}

		//if(isHeightBroke) System.out.println("height");
		//if(elbowQuadrantOne) System.out.println("Q1");
		//else System.out.println("Q4");
		//System.out.println("Elbow:" + reach_E);

		if(isHeightBroke && elbowQuadrantOne && reach_E > 0)
			reach_E = 0;

		if(Math.abs(reach_E) > 0){
			if(ePosition <= MIN_E && reach_E < 0)
				reach_E = 0;
			else if(ePosition >= MAX_E && reach_E > 0)
				reach_E = 0;
		}

		//System.out.println("ElbowPot: " + ePosition);

		Elbow.set(reach_E);
	}

 	public void MaxReachCheck(){

		double ninetyDegrees = Math.PI/2; //Radians in 90 degrees
		//double VoltToAngle = 1.02;//ninetyDegrees / EVERTICAL - EHORIZONTAL; //Multiplier to convert volts to an angle, radians/volt
		double VoltToAngle = ninetyDegrees / (EVERTICAL - EHORIZONTAL); //1.92
		double angleOne = (sPosition - SVERTICAL) * VoltToAngle;
		double lengthOne = ARM_BICEP * Math.sin(angleOne);
		double heightOne = ARM_BICEP * Math.cos(angleOne);

		double angleTwo = (EVERTICAL - ePosition) * VoltToAngle;
		double heightTwo;

		if(angleTwo >= ninetyDegrees){
			heightTwo = 0;
			elbowQuadrantOne = false;
			angleTwo = Math.PI - angleTwo;
		} else {
			heightTwo = ARM_TRICEP * Math.cos(angleTwo);
			elbowQuadrantOne = true;
		}

		double lengthTwo = ARM_TRICEP * Math.sin(angleTwo);

		//angleOne = (180 *angleOne)/3.14;
		//System.out.println("sa: " + angleOne);
		//System.out.println("sl: " + lengthOne);
		//System.out.println("sh: " + heightOne);

		//System.out.println("el: " + lengthTwo);

		if(lengthOne + lengthTwo >= MAX_REACH)
			is15broke = true;
		else
			is15broke = false;

		if(heightOne + heightTwo >= MAX_HEIGHT)
			isHeightBroke = true;
		else
			isHeightBroke = false;
 	}
}


text:
class SeedLocalCouncilAreas < ActiveRecord::Migration
  def change

    create_table :administrative_boundries do |t|
      t.string :name
      t.text   :description
      t.multi_polygon :area, srid: 4326
      t.timestamps
    end

  end
end


text:
<?xml version="1.0" encoding="UTF-8"?>

<!--************************************************************************
**
** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/legal
**
** This file is part of the Qt Designer of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Digia.  For licensing terms and
** conditions see http://qt.digia.com/licensing.  For further information
** use the contact form at http://qt.digia.com/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Digia gives you certain additional
** rights.  These rights are described in the Digia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3.0 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU General Public License version 3.0 requirements will be
** met: http://www.gnu.org/copyleft/gpl.html.
**
**
** $QT_END_LICENSE$
**
**************************************************************************-->

<!DOCTYPE fontmapping
[
<!ENTITY ce "Windows CE" >
<!ENTITY qe "Qt Embedded" >
]>

<fontmappings>
<mapping><family>DejaVu Sans</family><display>DejaVu Sans [&qe;]</display></mapping>
<mapping><family>DejaVu Sans</family><display>DejaVu Sans [&qe;]</display></mapping>
<mapping><family>DejaVu Sans</family><display>DejaVu Sans [&qe;]</display></mapping>
<mapping><family>DejaVu Sans</family><display>DejaVu Sans [&qe;]</display></mapping>
<mapping><family>DejaVu Sans Mono</family><display>DejaVu Sans Mono [&qe;]</display></mapping>
<mapping><family>DejaVu Sans Mono</family><display>DejaVu Sans Mono [&qe;]</display></mapping>
<mapping><family>DejaVu Sans Mono</family><display>DejaVu Sans Mono [&qe;]</display></mapping>
<mapping><family>DejaVu Sans Mono</family><display>DejaVu Sans Mono [&qe;]</display></mapping>
<mapping><family>DejaVu Serif</family><display>DejaVu Serif [&qe;]</display></mapping>
<mapping><family>DejaVu Serif</family><display>DejaVu Serif [&qe;]</display></mapping>
<mapping><family>DejaVu Serif</family><display>DejaVu Serif [&qe;]</display></mapping>
<mapping><family>DejaVu Serif</family><display>DejaVu Serif [&qe;]</display></mapping>
<mapping><family>Bitstream Vera Sans</family><display>Bitstream Vera Sans [&qe;]</display></mapping>
<mapping><family>Bitstream Vera Sans</family><display>Bitstream Vera Sans [&qe;]</display></mapping>
<mapping><family>Bitstream Vera Sans</family><display>Bitstream Vera Sans [&qe;]</display></mapping>
<mapping><family>Bitstream Vera Sans</family><display>Bitstream Vera Sans [&qe;]</display></mapping>
<mapping><family>Bitstream Vera Sans Mono</family><display>Bitstream Vera Sans Mono [&qe;]</display></mapping>
<mapping><family>Bitstream Vera Sans Mono</family><display>Bitstream Vera Sans Mono [&qe;]</display></mapping>
<mapping><family>Bitstream Vera Sans Mono</family><display>Bitstream Vera Sans Mono [&qe;]</display></mapping>
<mapping><family>Bitstream Vera Sans Mono</family><display>Bitstream Vera Sans Mono [&qe;]</display></mapping>
<mapping><family>Bitstream Vera Serif</family><display>Bitstream Vera Serif [&qe;]</display></mapping>
<mapping><family>Bitstream Vera Serif</family><display>Bitstream Vera Serif [&qe;]</display></mapping>
</fontmappings>


text:
import * as ad from "./ad";
import { Value } from "./value";

export type Shape = GenericShape<number>;
export type ShapeAD = GenericShape<ad.Num>;

export type Properties<T> = { [k: string]: Value<T> };

/**
 * A shape (Graphical Primitive Instance, aka GPI) in penrose has a type (_e.g._ `Circle`) and a set of properties (_e.g._ `center`). This type is specifically used for rendering. See {@link GPI} for the version used for the runtime.
 */
interface GenericShape<T> {
  shapeType: string;
  properties: Properties<T>;
}


text:
package me.chanjar.weixin.cp.bean.school.user;

import com.google.gson.annotations.SerializedName;
import lombok.Data;
import lombok.Getter;
import lombok.Setter;
import me.chanjar.weixin.cp.bean.WxCpBaseResp;
import me.chanjar.weixin.cp.util.json.WxCpGsonBuilder;

import java.io.Serializable;
import java.util.List;

/**
 * 批量返回结果.
 *
 * @author Wang_Wong  created on  2022-07-01
 */
@Data
public class WxCpBatchResultList extends WxCpBaseResp implements Serializable {
  private static final long serialVersionUID = -5028321625140879571L;

  @SerializedName("result_list")
  private List<ResultList> resultList;

  /**
   * The type Result list.
   */
  @Setter
  @Getter
  public static class ResultList extends WxCpBaseResp {

    @SerializedName("parent_userid")
    private String parentUserId;

    @SerializedName("student_userid")
    private String studentUserId;

    /**
     * From json result list.
     *
     * @param json the json
     * @return the result list
     */
    public static ResultList fromJson(String json) {
      return WxCpGsonBuilder.create().fromJson(json, ResultList.class);
    }

    public String toJson() {
      return WxCpGsonBuilder.create().toJson(this);
    }

  }

  /**
   * From json wx cp batch result list.
   *
   * @param json the json
   * @return the wx cp batch result list
   */
  public static WxCpBatchResultList fromJson(String json) {
    return WxCpGsonBuilder.create().fromJson(json, WxCpBatchResultList.class);
  }

  public String toJson() {
    return WxCpGsonBuilder.create().toJson(this);
  }

}


text:
package com.signalcollect

import com.signalcollect.interfaces.EdgeId

/**
 * This trait represents the framework's view of an edge.
 *
 *  @author Philip Stutz
 */
trait Edge[+TargetId] extends Serializable {

  type Source <: Vertex[_, _]

  /** An edge id uniquely identifies an edge in the graph. */
  def id: EdgeId[_]

  def sourceId: Any = source.id
  def targetId: TargetId
  def source: Source

  /** Called when the edge is attached to a source vertex */
  def onAttach(source: Vertex[_, _], graphEditor: GraphEditor[Any, Any])

  /** The weight of this edge. */
  def weight: Double

  /** EdgeClassName(id=`edge id`) */
  override def toString = getClass.getSimpleName + "(id=" + id + ")"

  /** The edge hashCode is the hashCode of the id */
  override def hashCode = id.hashCode

  /** Two edges are equal if their ids are equal */
  override def equals(other: Any): Boolean =
    other match {
      case e: Edge[_] => e.id == id
      case _          => false
    }

  /**
   *  Function that gets called by the source vertex whenever this edge is supposed to send a signal.
   *
   *  @param sourceVertex The source vertex of this edge.
   *
   *  @param messageBus an instance of MessageBus which can be used by this edge to interact with the graph.
   */
  def executeSignalOperation(sourceVertex: Vertex[_, _], graphEditor: GraphEditor[Any, Any])

}


text:
/**************************************************
 * Source Code for the Original Compiler for the
 * Programming Language Wake
 *
 * TableFileWriter.h
 *
 * Licensed under the MIT license
 * See LICENSE.TXT for details
 *
 * Author: Michael Fairhurst
 * Revised By:
 *
 **************************************************/

#ifndef HEADER_TABLE_FILE_WRITER
#define HEADER_TABLE_FILE_WRITER

#include <iostream>
#include "PropertySymbolTable.h"

class TableFileWriter {

	public:
		void write(ostream& out, PropertySymbolTable* table);
	private:
		void writeType(ostream& out, PureType<wake::QUALIFIED>* type);
		void writeProperty(ostream& out, ObjectProperty* property);
		void writeVarDecl(ostream& out, VarDecl<wake::QUALIFIED>& decl);
		void writeAnnotations(ostream& out, const boost::ptr_vector<Annotation>& annotations);
};

#endif


text:
- this Meteoris.FormValidation extension depends on collection2 and simpleschema:

```
AccountType = new Mongo.Collection("accountType");

var schemas = new SimpleSchema({
    accountClassId: {
        type: String,
        label: "Kelas Akun",
    },
});

AccountType.attachSchema(schemas);

```

- how to use in your js helper:

```
    /* show error message on view */
    error: function(field) {
        return Meteoris.FormValidation.error(YourCollectionName, field);
    },
```

- how to use in your html view:

```
        <div class="form-group {{#if error 'name'}}has-error{{/if}}">
            <label for="name" class="control-label">Kelas Akun *</label>
            <input type="text" id="name" value="{{name}}" placeholder="Kelas Akun" class="form-control" autofocus="true">
            <span class="help-block">{{error "name"}}</span>
        </div>

```


text:
import StackSection from 'ui/components/stack-section/component';

export default StackSection.extend();


text:
'use strict';

const HeightCoordinates = require('./heightcoodinates');

const CONVERGE_EVERY = 5;
const CONVERGE_FACTOR = 50;
const ERROR_MIN = 0.1;

const cc = 0.25;
const ce = 0.5;
const initial_error = 10;

module.exports = class VivaldiPosition {
	constructor(coords) {
		if (!(coords instanceof HeightCoordinates)) {
			throw new TypeError('Argument 1 must be a HeightCoordinates');
		}

		this._coordinates = coords;
		this._error = initial_error;
		this._nbUpdates = 0;
	}

	static create(error) {
		var np = new VivaldiPosition(new HeightCoordinates(0, 0, 0))

		if (error !== void 0) {
			np.setErrorEstimate( error );
		}

		return np;
	}

	getCoordinates() {
		return this._coordinates;
	}

	getLocation() {
		this._coordinates.getCoordinates();
	}

	getErrorEstimate() {
		return this._error;
	}

	setErrorEstimate(e) {
		this._error = Number(e);
	}

	/**
	 * @param {number} rtt
	 * @param {HeightCoordinates|Float32Array|VivaldiPosition} cj
	 * @param {number} ej
	 */
	update(rtt, cj, ej) {
		if (cj instanceof Float32Array) {
			return this.update(rtt, new HeightCoordinates(cj[0], cj[1], cj[2]), cj[3]);
		}

		if (cj instanceof VivaldiPosition) {
			return this.update(rtt, cj.getCoordinates(), cj.getErrorEstimate());
		}

		if (!valid(rtt) || !cj.isValid() || !valid(ej)) {
			return false;	// throw error may be
		}

		var error = this._error;

		// Ensure we have valid data in input
		// (clock changes lead to crazy rtt values)
		if (rtt <= 0 || rtt > 5 * 60 * 1000) return false;
		if (error + ej == 0) return false;

		// Sample weight balances local and remote error. (1)
		var w = error / (ej + error);

		// Real error
		var re = rtt - this._coordinates.distance(cj);

		// Compute relative error of this sample. (2)
		var es = Math.abs(re) / rtt;

		// Update weighted moving average of local error. (3)
		var new_error = es * ce * w + error * (1 - ce * w);

		// Update local coordinates. (4)
		var delta = cc * w;
		var scale = delta * re;

		var random_error = new HeightCoordinates(Math.random() / 10, Math.random() / 10, 0);
		var new_coordinates = this._coordinates.add(this._coordinates.sub(cj.add(random_error))
			.unity().scale(scale));

		if (valid(new_error) && new_coordinates.isValid()) {
			this._coordinates = new_coordinates;
			this._error = new_error > ERROR_MIN ? new_error : ERROR_MIN;
		} else {
			this._coordinates = new HeightCoordinates(0, 0, 0);
			this._error = initial_error;
		}

		if(!cj.atOrigin()) {
			this._nbUpdates++;
		}
		if(this._nbUpdates > CONVERGE_EVERY) {
			this._nbUpdates = 0;
			this.update(10,new HeightCoordinates(0,0,0),CONVERGE_FACTOR);
		}

		return true;
	}

	isValid() {
		return !Number.isNaN(this._error) && this.getCoordinates().isValid();
	}

	/**
	 * @param {HeightCoordinates|VivaldiPosition} data
	 * @returns {number}
	 */
	estimateRTT(data) {
		if (data instanceof HeightCoordinates) {
			return this._coordinates.distance(data);
		} else if (data instanceof VivaldiPosition) {
			let coords = data.getCoordinates();

			if (coords.atOrigin() || this._coordinates.atOrigin()) {
				return NaN;
			}

			return this._coordinates.distance(coords);
		}
	}

	toFloatArray() {
		return new Float32Array([this._coordinates.x, this._coordinates.y, this._coordinates.h, this._error]);
	}

	static fromFloatArray(data) {
		var coords = new HeightCoordinates(data[0], data[1], data[2]);

		var pos = new VivaldiPosition(coords);
		pos.setErrorEstimate(data[3]);

		return pos;
	}

	equals(other) {
		if (other instanceof VivaldiPosition) {
			if (other._error !== this._error) {
				return false;
			}

			if (!other._coordinates.equals(this._coordinates)) {
				return false;
			}

			return true;
		}

		return false;
	}
}

function valid(f) {
	return Number.isFinite(f);
}


text:
<?php /* Smarty version 2.6.28, created on 2014-12-25 09:25:16
         compiled from top.tpl */ ?>
<link rel="stylesheet" href="css/top.css" />

    <a href="<?php echo $this->_tpl_vars['index']; ?>
" class="top">首页

    最新商品

	推荐商品

    热门商品

    订单查询


text:
Get-Neo4jServer [[-Neo4jHome] <string>] [<CommonParameters>]

## Syntax

```powershell
Get-Neo4jServer [-Neo4jHome <string>] [<CommonParameters>]
```

## Parameters

###  -Neo4jHome [\<string\>]

Property               | Value
---------------------- | --------------
Aliases                |
Required?              | false
Position?              | 0
Default Value          |
Accept Pipeline Input? | true (ByValue)

### \<CommonParameters\>

This cmdlet supports the common parameters: -Verbose, -Debug, -ErrorAction, -ErrorVariable, -OutBuffer, and -OutVariable. For more information, see `about_CommonParameters` http://go.microsoft.com/fwlink/p/?LinkID=113216 .

## Aliases

None

## Notes

## Examples

## Links


text:
<?php

namespace FKakSila\Bundle\MainBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use FKakSila\Bundle\MainBundle\Form\PhraseType;
use FKakSila\Bundle\MainBundle\Entity\Phrase;
use Symfony\Component\HttpFoundation\Request;

class DefaultController extends Controller
{
    public function translateAction(Request $request)
    {
        $phrase = new Phrase();
        $action = array('action' => $this->generateUrl('translate'));
        $form = $this->createForm(new PhraseType(), $phrase, $action);

        $form->handleRequest($request);

        if ($form->isValid()) {

            $text = $form['text']->getData();
            return $this->redirect($this->generateUrl('translate', array('text' => $text)));

        }

        $text = $request->query->get('text');
        if (!empty($text)) {

            $length = strlen($text);
            $letters = str_split($text);

            $phrase = new Phrase();
            $phrase->setText($text);
            $em = $this->get('doctrine.orm.entity_manager');
            $repo = $em->getRepository('FKakSilaMainBundle:Letter');
            $result = [];
            for ($i = 0; $i < $length; $i++) {
                $letter = $repo->findOneBy(['name' => $phrase->getText()[$i]]);
                if ($i != $length - 1) {
                    if (empty($letter->getTranscription())) {
                        $data = sprintf('%s', $letter->getdescription() . ',');
                    } else {
                        $data = sprintf('[%s] %s %s', $letter->getTranscription(), ' - как', $letter->getdescription() . ',');
                    }
                } else {
                    if (empty($letter->getTranscription())) {
                        $data = sprintf('%s', $letter->getdescription());
                    } else {
                        $data = sprintf('[%s] %s %s', $letter->getTranscription(), ' - как', $letter->getdescription());
                    }
                }

                array_push($result, $data);
            }

            return $this->render('FKakSilaMainBundle:Default:index.html.twig', array('form' => $form->createView(), 'letters' => $letters, 'result' => $result));
        } else {
            return $this->render('FKakSilaMainBundle:Default:index.html.twig', array('form' => $form->createView()));

        }
    }
}


text:
<?php

class Sailthru_Social Extends Sailthru_Client{

  var $debug = false;
  var $fields = array('keys' => 1);

  function __construct($api_key, $api_secret) {
    parent::__construct($api_key, $api_secret);
  }

  /*
  * Passes login data from social login services to the user API
  *
  */
  function social_login($social_data) {

    if ($this->debug) {
      // print '<pre>';
      var_dump($social_data);
      // print '</pre>';
    }

    $use_email_as_key = false;
    $vars = array();
    // find out what provider we're dealing with;
    $provider = $social_data->provider;

    // by default use an email address as the key
    if (isset($social_data->user->email)) {
      $data['key']  = 'email';
      $data['id'] = $social_data->user->email;
    } else {
      // need to do check to see if sharding is enabled on the account at setup
      switch ($provider) {
          case 'twitter':
            $data['key'] = 'twitter';
          break;

          case 'facebook':
            $data['key'] = 'facebook';
          break;

          default;
          // post details on another provider
          $data['key'] = 'extid';
      }
      $data['id'] =  $social_data->loginProviderUID;
    }

    $data['options'] = array(
                  'login' => array(
                  'user_agent' => $_SERVER['HTTP_USER_AGENT'],
                  'key' => $data['key'],
                  'ip' => $_SERVER['REMOTE_ADDR'],
                  'site' => $_SERVER['HTTP_HOST'],
                  ),
                  'fields' => array('activity' => 1),
                  );

    $data['vars'] = array();
    $not_wanted = array('UID', 'UIDSig', 'UIDSignature');

    foreach ($social_data->user as $key => $val) {
        // remove Gigya identifiers and put them in a different var
        if (!in_array($key, $not_wanted)) {
          $data['vars'][$provider.'_'.$key] = $val;
        }

    }
    $sync = $this->sync_data($data);

  }

  /*
  * POST the data to the Sailthru API using the user call
  */
  private function sync_data($data) {

    try {
      return $post = $this->apiPost('user', $data);
    } catch (Sailthru_Client_Exception $e) {
      // log the error somewhere
      return false;
    }

  }

}


text:
import Ember from 'ember-metal/core';
import isEmpty from 'ember-metal/is_empty';
import ArrayProxy from 'ember-runtime/system/array_proxy';

QUnit.module('Ember.isEmpty');

QUnit.test('Ember.isEmpty', function() {
  var arrayProxy = ArrayProxy.create({ content: Ember.A() });

  equal(true, isEmpty(arrayProxy), 'for an ArrayProxy that has empty content');
});


text:
package sbt.testing;

/**
 * A task to execute.
 *
 *

 * The client may decide when or how to execute the task based on its tags.
 * A task can be any job, but is primarily intended for running tests and/or supplying more tasks
 * to the client. A framework can supply more tasks
 * to the client in the returned an array of Tasks (which can be empty if there's
 * no more work to do.)
 *

 */
public interface Task {

  /**
   * A possibly zero-length array of string tags associated with this task.
   *
   *

   * A task may be tagged, for example, with a string that indicates it consumes a lot
   * of CPU time. Users can configure the client to only run, say, three such CPU-intensive
   * tasks concurrently.
   *

   *
   * @return a possibly zero-length string array of this task's tags
   */
  String[] tags();

  /**
   * Executes this task, possibly returning to the client new tasks to execute.
   *
   * @param eventHandler an event handler to which to fire events during the run
   * @param loggers an array of loggers to which to emit log messages during the run
   * @return a possibly empty array of new tasks for the client to execute
   */
  Task[] execute(EventHandler eventHandler, Logger[] loggers);

  /**
   * Returns the TaskDef that was used to request this Task.
   *
   * @return the TaskDef that was used to request this Task.
   */
  TaskDef taskDef();
}


text:
import copy
import json

import uritemplate

__all__ = ['Document',
           'Resource',

           'MEDIA_TYPE',

           'JsonHomeException',
           'MissingValues',
           'UnknownResource',
           'ResourceAlreadyExists'
           ]

MEDIA_TYPE = 'application/json-home'

class JsonHomeException(Exception):
    """Base Exception class that all JSONHome exceptions inherit from."""

class MissingValues(JsonHomeException):
    """There is not enough information in the JSONHome document to finish."""

class UnknownResource(JsonHomeException):
    """There is no resource available with the specified relation."""

class ResourceAlreadyExists(JsonHomeException):
    """A resource with the specified relation already exists."""

def _allow_prop(method):

    def _allow_getter(self):
        return self.is_allowed(method)

    def _allow_setter(self, value):
        in_list = self.is_allowed(method)

        if value and not in_list:
            self.allow.append(method)
        if in_list and not value:
            self.hints['allow'] = [x for x in self.allow
                                   if x.upper() != method]

    return property(_allow_getter,
                    _allow_setter,
                    doc='Allow the %s method on this resource' % method)

def _item_prop(name, default=None, setdefault=None, hint=False):
    """Create a property that fetches a value from the dictionary.

    We implement getter, setter and deleter here. Whilst we may not want users
    to do all of those things it is not our job to prevent users from doing
    something stupid. Our goal is to provide helper functions and if people go
    and delete hints or force set multiple href methods that's not our fault.

    Note that set
    :param default: A value that is returned if nothing present in the object.
        This value will be ignored if setdefault is set.
    :param callable setdefault: A value set and returned if nothing present in
        the object. This value will take priority to default. Note that this is
        a callable so the set value will be the result of executing this
        function. This allows us to create new objects for default values.
    :param bool hint: True if this attribute exists in the hints dictionary.

    :rtype: property
    """

    def o(self):
        return self.hints if hint else self

    def _getter(self):
        if setdefault:
            return o(self).setdefault(name, setdefault())
        else:
            return o(self).get(name, default)

    def _setter(self, value):
        o(self)[name] = value

    def _deleter(self):
        o(self).pop(name, None)

    return property(_getter, _setter, _deleter)

class Resource(dict):
    """One resource that exists within a JSON home document."""

    href_vars = _item_prop('href-vars', setdefault=dict)
    """A indication for variables in the template to construct a URI."""

    href_template = _item_prop('href-template')
    """A templated URI link to a resource."""

    href = _item_prop('href')
    """A Direct URI Link to a resource."""

    hints = _item_prop('hints', setdefault=dict)
    """Additional hint information defined by the resource.

    Resource hints allow clients to find relevant information about
    interacting with a resource beforehand, as a means of optimising
    communications, as well as advertising available behaviours (e.g., to
    aid in laying out a user interface for consuming the API).

    Hints are just that - they are not a "contract", and are to only be
    taken as advisory.  The runtime behaviour of the resource always
    overrides hinted information.

    For example, a resource might hint that the PUT method is allowed on
    all "widget" resources.  This means that generally, the user has the
    ability to PUT to a particular resource, but a specific resource
    might reject a PUT based upon access control or other considerations.
    More fine-grained information might be gathered by interacting with
    the resource (e.g., via a GET), or by another resource "containing"
    it (such as a "widgets" collection) or describing it (e.g., one
    linked to it with a "describedby" link relation).
    """

    allow = _item_prop('allow', setdefault=list, hint=True)
    """HTTP Allow Methods for this resource.

    Hints the HTTP methods that the current client will be able to use to
    interact with the resource; equivalent to the Allow HTTP response
    header.
    """

    accept_patch = _item_prop('accept-patch', setdefault=list, hint=True)
    """Hints the PATCH request formats accepted by the resource.

    This is equivalent to the Accept-Patch HTTP response header.
    """

    accept_post = _item_prop('accept-post', setdefault=list, hint=True)
    """Hints the POST request formats accepted by the resource."""

    accept_prefer = _item_prop('accept-prefer', setdefault=list, hint=True)
    """Hints the preferences supported by the resource.

    Note that, as per that specifications, a preference can be ignored by the
    server.
    """

    accept_ranges = _item_prop('accept-ranges', setdefault=list, hint=True)
    """Hints the range-specifiers available to the client.

    This is equivalent to the Accept-Ranges HTTP response header.
    """

    docs = _item_prop('docs', hint=True)
    """The location for human-readable documentation for the resource."""

    def is_allowed(self, method):
        """Test if a HTTP method can be used with this resource.

        :param str method: a HTTP method string to find.

        :returns: bool or None if no hints are defined by the resource.
        """
        try:
            allowed = self.hints['allow']
        except KeyError:
            return None
        else:
            return method.upper() in (a.upper() for a in allowed)

    allow_delete = _allow_prop('DELETE')
    allow_get = _allow_prop('GET')
    allow_head = _allow_prop('HEAD')
    allow_options = _allow_prop('OPTIONS')
    allow_patch = _allow_prop('PATCH')
    allow_post = _allow_prop('POST')
    allow_put = _allow_prop('PUT')

    def get_uri(self, **kwargs):
        """Get an absolute URI for this resource.

        Fetch the absolute URI. If there is an absolute URI set on this
        resource that will be returned.

        If there is a templated URI then the variables in the template will be
        evaluated against the values passed in through keyword arguments.
        """
        if self.href:
            return self.href

        if self.href_template:
            return uritemplate.expand(self.href_template, **kwargs)

        raise MissingValues("Couldn't determine href from values in Resource")

    def set_uri(self, uri, **kwargs):
        """Set the URI on this resource based on its format.

        Selective set the href or href-template and href-vars depending on if
        the URI contains a templated form or not. If there are variables set in
        the URI then a relation name be passed as a kwarg as well.

        Passing an absolute URI::

            res.set_uri('/path/to/resource')

        Passing a templated URI::

            res.set_uri('/path/to/resource{/param}',
                        param='http://description/rel/param')

        :param str uri: The URI you want to set. This may contain variables.

        :raises jsonhome.MissingValues: If a templated URI is passed and there
            is not a relation passed as a keyword argument that matches the
            variable.
        """
        variables = uritemplate.URITemplate(uri).variables

        if variables:
            try:
                href_vars = dict((n, kwargs.pop(n))
                                 for v in variables
                                 for n in v.variable_names)
            except KeyError as e:
                msg = "Missing parameter %s from template" % str(e)
                raise MissingValues(msg)

            del self.href
            self.href_template = uri
            self.href_vars = href_vars

        else:
            self.href = uri
            del self.href_template
            del self.href_vars

    @classmethod
    def create(cls, **kwargs):
        """Create a new resource with specified values.

        A factory function that allows you to create a new Resource object with
        a number of attributes in one method.

        :param str href: A direct URI link to a resource.
        :param str href_template: A template from which a URI is determined.
        :param dict href_vars: The raw href variables that should be set.

        :param str uri: A templatable URI, of the form expected by
            :py:meth:`~jsonhome.Resource.set_uri`.
        :param dict uri_vars: The URI variables that are interpolated in the
            form expected by :py:meth:`~jsonhome.Resource.set_uri`.

        :param str docs: location for human-readable documentation.

        :param bool allow_delete: allow the DELETE method on resource.
        :param bool allow_get: allow the GET method on resource.
        :param bool allow_head: allow the HEAD method on resource.
        :param bool allow_options: allow the OPTIONS method on resource.
        :param bool allow_patch: allow the PATCH method on resource.
        :param bool allow_post: allow the POST method on resource.
        :param bool allow_put: allow the PUT method on resource.

        :param accept_patch: Hints the PATCH [RFC5789] request formats accepted
            by the resource for this client; equivalent to the Accept-Patch
            HTTP response header.
        :type accept_patch: list(str)

        :param accept_post: Hints the POST request formats accepted by the
            resource for this client.
        :type accept_post: list(str)

        :param accept_prefer: Hints the preferences supported by the resource.
            Note that, as per that specifications, a preference can be ignored
            by the server.
        :type accept_prefer: list(str)

        :param accept_ranges: Hints the range-specifiers available to the
            client for this resource; equivalent to the Accept-Ranges HTTP
            response header
        :type accept_ranges: list(str)

        :rtype: :py:class:`~jsonhome.Resource`.
        """
        # NOTE(jamielennox): keep the above parameter list in sync with the
        # Document.add_resource function below for better documentation.

        # before we start handle some SHOULD aspects of the specification to
        # try and make the resources as consistent with the spec as possible.
        if kwargs.get('accept_patch'):
            kwargs.setdefault('allow_patch', True)
        if kwargs.get('accept_post'):
            kwargs.setdefault('allow_post', True)

        # ensure that the URI is only handled in one way.
        uri = kwargs.pop('uri', None)
        uri_vars = kwargs.pop('uri_vars', {})

        # NOTE(jamielennox): we purposefully only check uri here, not uri_vars
        # so that you can keep a repository of uri_vars that are passed every
        # time and ignored if no uri parameter is passed.
        if sum([bool(uri),
                bool(kwargs.get('href')),
                bool(kwargs.get('href_template') or
                     kwargs.get('href_vars'))]) > 1:
            m = 'You should choose only one way to set the URI on a resource.'
            raise ValueError(m)

        r = cls()

        if uri:
            r.set_uri(uri, **uri_vars)

        for method in ('href',
                       'href_template',
                       'href_vars',

                       'docs',

                       'allow_delete',
                       'allow_get',
                       'allow_head',
                       'allow_options',
                       'allow_patch',
                       'allow_post',
                       'allow_put',

                       'accept_patch',
                       'accept_post',
                       'accept_prefer',
                       'accept_ranges'):
            value = kwargs.pop(method, None)
            if value is not None:
                setattr(r, method, value)

        if kwargs:
            msg = 'create got an unexpected argument: %s' % ', '.join(kwargs)
            raise TypeError(msg)

        return r

class Document(dict):
    """A model of a JSON Home document that can be manipulated."""

    resource_class = Resource
    """The class of resource that should be created."""

    def __setitem__(self, relation, value):
        if not isinstance(value, self.resource_class):
            raise TypeError('Can only set valid resources on Document')

        if relation in self:
            raise ResourceAlreadyExists(relation)

        super(Document, self).__setitem__(relation, value)

    def get_uri(self, relation, **kwargs):
        """Get an absolute URI for this resource.

        Fetch the absolute URI. If there is an absolute URI set on this
        resource that will be returned.

        If there is a templated URI then the variables in the template will be
        evaluated against the values passed in through keyword arguments.

        :param str relation: The relation to the resource you wish to get the
            URI for.
        """
        try:
            res = self[relation]
        except KeyError:
            raise UnknownResource(relation)

        return res.get_uri(**kwargs)

    def add_resource(self, relation, **kwargs):
        """Create a new resource on this document.

        Create a new resource with prefilled attributes and add it to the
        current document.

        :param str relation: The string relationship to this resource that will
            be used to identity resources.

        :param str href: A direct URI link to a resource.
        :param str href_template: A template from which a URI is determined.
        :param dict href_vars: The raw href variables that should be set.

        :param str uri: A templatable URI, of the form expected by
            :py:meth:`~jsonhome.Resource.set_uri`.
        :param dict uri_vars: The URI variables that are interpolated in the
            form expected by :py:meth:`~jsonhome.Resource.set_uri`.

        :param str docs: location for human-readable documentation.

        :param bool allow_delete: allow the DELETE method on resource.
        :param bool allow_get: allow the GET method on resource.
        :param bool allow_head: allow the HEAD method on resource.
        :param bool allow_options: allow the OPTIONS method on resource.
        :param bool allow_patch: allow the PATCH method on resource.
        :param bool allow_post: allow the POST method on resource.
        :param bool allow_put: allow the PUT method on resource.

        :param accept_patch: Hints the PATCH [RFC5789] request formats accepted
            by the resource for this client; equivalent to the Accept-Patch
            HTTP response header.
        :type accept_patch: list(str)

        :param accept_post: Hints the POST request formats accepted by the
            resource for this client.
        :type accept_post: list(str)

        :param accept_prefer: Hints the preferences supported by the resource.
            Note that, as per that specifications, a preference can be ignored
            by the server.
        :type accept_prefer: list(str)

        :param accept_ranges: Hints the range-specifiers available to the
            client for this resource; equivalent to the Accept-Ranges HTTP
            response header
        :type accept_ranges: list(str)

        :raises jsonhome.ResourceAlreadyExists: If there is already a relation
            with the requested name available on the document.

        :returns: The new resource. This is the same resource that was added to
            the document so a user may perform additional manipulation.
        :rtype: :py:class:`~jsonhome.Resource`.
        """
        r = self.resource_class.create(**kwargs)
        self[relation] = r
        return r

    def to_dict(self):
        """Convert the document into a serializable format.

        Convert the current document into a valid json-home format so that it
        can be serialized into JSON.

        :rtype: dict
        """
        return {'resources': copy.deepcopy(self)}

    @classmethod
    def from_dict(cls, data):
        """Create a json-home document from de-serialized data.

        Convert a dict that may have been received from an external site into
        a json-home document that can be manipulated and queried.

        :param dict data: The data to be converted.

        :rtype: :py:class:`~jsonhome.Document`
        """
        return cls(dict((relation, cls.resource_class(d))
                        for relation, d in data['resources'].items()))

    def to_json(self, **kwargs):
        """Convert the Document into JSON format.

        Serialize the json-home document into valid JSON so that it can be sent
        to users.

        :rtype: str
        """
        return json.dumps(self.to_dict(), **kwargs)

    @classmethod
    def from_json(cls, data):
        """Create a JSON home document from a JSON string.

        Take a string that was received from a remote service and load the JSON
        home document that describes its resources.

        :rtype: :py:class:`~jsonhome.Document`
        """
        return cls.from_dict(json.loads(data))


text:
using System.Web.Mvc;

namespace Task03_MobileShop.Areas.Laptops
{
    public class LaptopsAreaRegistration : AreaRegistration
    {
        public override string AreaName
        {
            get
            {
                return "Laptops";
            }
        }

        public override void RegisterArea(AreaRegistrationContext context)
        {
            context.MapRoute(
                "Laptops_default",
                "Laptops/{controller}/{action}/{id}",
                new { action = "Index", id = UrlParameter.Optional }
            );
        }
    }
}