text:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:oxm="http://www.springframework.org/schema/oxm"
    xmlns:jdbc="http://www.springframework.org/schema/jdbc" xmlns:lang="http://www.springframework.org/schema/lang"
    xmlns:p="http://www.springframework.org/schema/p" xmlns:tx="http://www.springframework.org/schema/tx"
    xmlns:util="http://www.springframework.org/schema/util"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
       http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-3.1.xsd
        http://www.springframework.org/schema/lang http://www.springframework.org/schema/lang/spring-lang-3.1.xsd
        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.1.xsd
        http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.1.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd
        ">
    <!-- ============================== -->
    <import resource="commonservices-context.xml" />

    <bean id="servicesPropertyConfigurer"
        class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
        <property name="systemPropertiesModeName" value="SYSTEM_PROPERTIES_MODE_OVERRIDE" />
        <property name="ignoreUnresolvablePlaceholders" value="true" />
        <property name="ignoreResourceNotFound" value="true"/>
        <property name="locations">
                <list>
                        <value>classpath*:/*.properties</value>
                        <value>file:${catalina.base}/conf/transcend.properties</value>
                        <value>classpath*:/asinternal.ports</value>
                        <value>classpath*:/compute.ports</value>
                </list>
        </property>
    </bean>
    <util:map id="actions">
    </util:map>

    <bean id="asInternalServiceAsync"
        class="com.msi.tough.query.AsyncServiceImpl">
        <constructor-arg ref="actions"/>
    </bean>

    <bean id="autoscaleInternal" class="com.msi.tough.internal.autoscale.AutoScaleInternalImpl">
        <constructor-arg>
            <map>
                <entry key="GatherInstancesData">
                    <bean class="com.msi.tough.internal.autoscale.actions.GatherInstancesData">
                    </bean>
                </entry>
                <entry key="ProcessAutoScaling">
                    <bean class="com.msi.tough.internal.autoscale.actions.ProcessAutoScaling">
                    </bean>
                </entry>
                <entry key="ProcessTerminatedInstances">
                    <bean
                        class="com.msi.tough.internal.autoscale.actions.ProcessTerminatedInstances">
                    </bean>
                </entry>
                <entry key = "PostWait">
                	<bean
                		class="com.msi.tough.internal.autoscale.actions.PostWait">
                	</bean>
                </entry>

                <entry key="PublishASMetrics">
                    <bean class="com.msi.tough.internal.autoscale.actions.PublishASMetrics">
                    </bean>
                </entry>
                <entry key="BootstrapChefRoles">
                    <bean class="com.msi.tough.internal.autoscale.actions.BootstrapChefRoles">
                    </bean>
                </entry>
                <entry key="BootstrapDBInstance">
                    <bean class="com.msi.tough.internal.autoscale.actions.BootstrapDBInstance">
                </bean>
                </entry>
                <entry key="CreateAccount">
                    <bean class="com.msi.tough.internal.autoscale.actions.CreateAccount">
                    </bean>
                </entry>
                <entry key="DescribeAccounts">
                    <bean class="com.msi.tough.internal.autoscale.actions.DescribeAccounts">
                    </bean>
                </entry>
                <entry key="DeleteAccount">
                    <bean class="com.msi.tough.internal.autoscale.actions.DeleteAccount">
                    </bean>
                </entry>
                <entry key="UpdateAccount">
                    <bean class="com.msi.tough.internal.autoscale.actions.UpdateAccount">
                    </bean>
                </entry>
                <entry key="RegisterInstance">
                    <bean class="com.msi.tough.internal.autoscale.actions.RegisterInstance">
                    </bean>
                </entry>
            </map>
        </constructor-arg>
    </bean>

    <bean id="endpoint" class="java.lang.String">
        <constructor-arg value="ActionIn"/>
    </bean>
    <bean id="rawEndpoint" class="java.lang.String">
        <constructor-arg value="DirectToZMQEntry"/>
    </bean>

    <bean id="workflow" factory-method="getInstance"
    class="com.msi.tough.workflow.core.MuleWorkflow">
    </bean>

    <bean id="recvEndpoint" class="java.lang.String">
        <constructor-arg value="tcp://*:${asinternal.port}"/>
    </bean>

    <bean id="workflowReceiver" init-method="init" destroy-method="destroy"
    class="com.msi.tough.workflow.core.WorkflowReceiver">
    </bean>

    <!-- compute setup, for creating/describing instances -->

    <util:list id="computePossibleTypes">
        <value>com.msi.tough.message.CoreMessage$ErrorResult</value>
        <value>com.transcend.compute.message.RunInstancesMessage$RunInstancesResponseMessage</value>
        <value>com.transcend.compute.message.DescribeInstancesMessage$DescribeInstancesResponseMessage</value>
    </util:list>

    <bean id="remoteEndpoint" class="java.lang.String">
        <constructor-arg value="tcp://${compute.host}:${compute.port}"/>
    </bean>

    <bean id="returnAddress" class="java.lang.String">
        <constructor-arg value="tcp://${internal.service.host}:${response.compute.port}"/>
    </bean>

    <bean id="remoteComputeWorkflow" factory-method="getInstance" destroy-method="destroy"
    class="com.msi.tough.workflow.core.RemoteWorkflow">
        <property name="remoteEndpoint" ref="remoteEndpoint" />
        <property name="recvEndpoint" value="tcp://*:${response.compute.port}" />
        <property name="returnAddress" ref="returnAddress" />
        <property name="possibleTypes" ref="computePossibleTypes"/>
    </bean>

    <bean id="remoteIgniter"
        class="com.msi.tough.workflow.core.RemoteIgniter">
    </bean>

    <bean id="toCompute"
        class="com.msi.tough.workflow.WorkflowSubmitter">
        <property name="workflow" ref="remoteComputeWorkflow"/>
        <property name="workflowIgniter" ref="remoteIgniter"/>
    </bean>

    <!-- Run common annotations; e.g. PostConstruct/PreDestroy. -->
    <context:annotation-config />

    <bean id="appctx" factory-method="getInstanceForInjection"
        class="com.msi.tough.core.Appctx">
        <property name="configuration" ref="configuration"/>
    </bean>

    <bean class="com.msi.tough.core.AppctxInjector"/>

    <bean id="hibernateUtil" class="com.msi.tough.core.HibernateUtil">
        <property name="sessionFactory" ref="sessionFactory" />
    </bean>

    <tx:annotation-driven transaction-manager="txManager"/>

    <!-- Redefine session factory; this app uses annotations for transactions -->
    <bean id="sessionFactory"
        class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
        <property name="dataSource" ref="msiDS" />
        <property name="configLocation" value="classpath:hibernate.cfg.xml"></property>
        <property name="configurationClass" value="org.hibernate.cfg.AnnotationConfiguration"></property>
        <property name="hibernateProperties">
            <value>hibernate.dialect=org.hibernate.dialect.MySQL5InnoDBDialect
                hibernate.cache.provider_class=org.hibernate.cache.NoCacheProvider
                hibernate.show_sql=false
                hibernate.hbm2ddl.auto=update
            </value>
        </property>
    </bean>

</beans>


text:
from __future__ import (
    unicode_literals,
    print_function,
    division,
    absolute_import,
    )

# Make Py2's str equivalent to Py3's
str = type('')

import os
import io
import re
import math
import subprocess
from PIL import Image

RAW_FORMATS = {
    # name   bytes-per-pixel
    'yuv':  1.5,
    'rgb':  3,
    'rgba': 4,
    'bgr':  3,
    'bgra': 4,
    }

def verify_video(filename_or_obj, format, resolution):
    """
    Verify that the video in filename_or_obj has the specified format and
    resolution.
    """
    width, height = resolution
    if format in RAW_FORMATS:
        size = (
                math.ceil(width / 32) * 32
                * math.ceil(height / 16) * 16
                * RAW_FORMATS[format]
                )
        if isinstance(filename_or_obj, str):
            stream = io.open(filename_or_obj, 'rb')
        else:
            stream = filename_or_obj
        stream.seek(0, os.SEEK_END)
        assert stream.tell() > 0
        # Check the stream size is an exact multiple of the frame size
        assert stream.tell() % size == 0
    else:
        if isinstance(filename_or_obj, str):
            p = subprocess.Popen([
                'avconv',
                '-f', format,
                '-i', filename_or_obj,
                ], stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
        else:
            p = subprocess.Popen([
                'avconv',
                '-f', format,
                '-i', '-',
                ], stdin=filename_or_obj, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
        out = p.communicate()[0]
        assert p.returncode == 1, 'avconv returned unexpected code %d' % p.returncode
        state = 'start'
        for line in out.splitlines():
            line = line.decode('utf-8').strip()
            if state == 'start' and re.match(r'^Input #0', line):
                state = 'input'
            elif state == 'input' and re.match(r'^Duration', line):
                state = 'dur'
            elif state == 'dur' and re.match(r'^Stream #0\.0', line):
                assert re.match(
                    r'^Stream #0\.0: '
                    r'Video: %s( \(.*\))?, '
                    r'yuvj?420p, '
                    r'%dx%d( \[PAR \d+:\d+ DAR \d+:\d+\])?, '
                    r'\d+ fps, \d+ tbr, \d+k? tbn(, \d+k? tbc)?$' % (
                        format, width, height),
                    line
                    ), 'Unexpected avconv output: %s' % line
                return
        assert False, 'Failed to locate stream analysis in avconv output'

def verify_image(filename_or_obj, format, resolution):
    """
    Verify that the image in filename_or_obj has the specified format and
    resolution.
    """
    width, height = resolution
    if format in RAW_FORMATS:
        size = (
                math.ceil(width / 32) * 32
                * math.ceil(height / 16) * 16
                * RAW_FORMATS[format]
                )
        if isinstance(filename_or_obj, str):
            stream = io.open(filename_or_obj, 'rb')
        else:
            stream = filename_or_obj
        stream.seek(0, os.SEEK_END)
        assert stream.tell() == size
    else:
        img = Image.open(filename_or_obj)
        assert img.size == resolution
        assert img.format.lower() == format.lower()
        img.verify()

redpajama_set_name: RedPajamaGithub


text:
class CreateVenues < ActiveRecord::Migration
  def change
    create_table :explorer_venues do |t|
      t.string :name
      t.string :address1
      t.string :address2
      t.string :city
      t.string :state
      t.string :zip
      t.string :contact
      t.string :phone
      t.text :description

      t.timestamps null: false
    end

  end
end


text:
<?php

final class ProjectQueryConduitAPIMethod extends ProjectConduitAPIMethod {

  public function getAPIMethodName() {
    return 'project.query';
  }

  public function getMethodDescription() {
    return 'Execute searches for Projects.';
  }

  public function defineParamTypes() {

    $statuses = array(
      PhabricatorProjectQuery::STATUS_ANY,
      PhabricatorProjectQuery::STATUS_OPEN,
      PhabricatorProjectQuery::STATUS_CLOSED,
      PhabricatorProjectQuery::STATUS_ACTIVE,
      PhabricatorProjectQuery::STATUS_ARCHIVED,
    );

    $status_const = $this->formatStringConstants($statuses);

    return array(
      'ids'               => 'optional list<int>',
      'names'             => 'optional list<string>',
      'phids'             => 'optional list<phid>',
      'slugs'             => 'optional list<string>',
      'status'            => 'optional '.$status_const,

      'members'           => 'optional list<phid>',

      'limit'             => 'optional int',
      'offset'            => 'optional int',
    );
  }

  public function defineReturnType() {
    return 'list';
  }

  public function defineErrorTypes() {
    return array();
  }

  protected function execute(ConduitAPIRequest $request) {
    $query = new PhabricatorProjectQuery();
    $query->setViewer($request->getUser());
    $query->needMembers(true);
    $query->needSlugs(true);

    $ids = $request->getValue('ids');
    if ($ids) {
      $query->withIDs($ids);
    }

    $names = $request->getValue('names');
    if ($names) {
      $query->withNames($names);
    }

    $status = $request->getValue('status');
    if ($status) {
      $query->withStatus($status);
    }

    $phids = $request->getValue('phids');
    if ($phids) {
      $query->withPHIDs($phids);
    }

    $slugs = $request->getValue('slugs');
    if ($slugs) {
      $query->withSlugs($slugs);
    }

    $members = $request->getValue('members');
    if ($members) {
      $query->withMemberPHIDs($members);
    }

    $limit = $request->getValue('limit');
    if ($limit) {
      $query->setLimit($limit);
    }

    $offset = $request->getValue('offset');
    if ($offset) {
      $query->setOffset($offset);
    }

    $pager = $this->newPager($request);
    $results = $query->executeWithCursorPager($pager);
    $projects = $this->buildProjectInfoDictionaries($results);

    // TODO: This is pretty hideous.
    $slug_map = array();
    if ($slugs) {
      foreach ($slugs as $slug) {
        $normal = rtrim(PhabricatorSlug::normalize($slug), '/');
        foreach ($projects as $project) {
          if (in_array($normal, $project['slugs'])) {
            $slug_map[$slug] = $project['phid'];
          }
        }
      }
    }

    $result = array(
      'data' => $projects,
      'slugMap' => $slug_map,
    );

    return $this->addPagerResults($result, $pager);
  }

}


text:
layout: page
title: Polymer
img: p-logo.png
---

Índice

		{% for post_polymer in site.categories.polymer reversed %}

{{post_polymer.title}}

		{% endfor%}


text:
package types

import "github.com/traefik/paerser/types"

const (
	// AccessLogKeep is the keep string value.
	AccessLogKeep = "keep"
	// AccessLogDrop is the drop string value.
	AccessLogDrop = "drop"
	// AccessLogRedact is the redact string value.
	AccessLogRedact = "redact"
)

const (
	// CommonFormat is the common logging format (CLF).
	CommonFormat string = "common"

	// JSONFormat is the JSON logging format.
	JSONFormat string = "json"
)

// TraefikLog holds the configuration settings for the traefik logger.
type TraefikLog struct {
	Level    string `description:"Log level set to traefik logs." json:"level,omitempty" toml:"level,omitempty" yaml:"level,omitempty" export:"true"`
	FilePath string `description:"Traefik log file path. Stdout is used when omitted or empty." json:"filePath,omitempty" toml:"filePath,omitempty" yaml:"filePath,omitempty"`
	Format   string `description:"Traefik log format: json | common" json:"format,omitempty" toml:"format,omitempty" yaml:"format,omitempty" export:"true"`
}

// SetDefaults sets the default values.
func (l *TraefikLog) SetDefaults() {
	l.Format = CommonFormat
	l.Level = "ERROR"
}

// AccessLog holds the configuration settings for the access logger (middlewares/accesslog).
type AccessLog struct {
	FilePath      string            `description:"Access log file path. Stdout is used when omitted or empty." json:"filePath,omitempty" toml:"filePath,omitempty" yaml:"filePath,omitempty"`
	Format        string            `description:"Access log format: json | common" json:"format,omitempty" toml:"format,omitempty" yaml:"format,omitempty" export:"true"`
	Filters       *AccessLogFilters `description:"Access log filters, used to keep only specific access logs." json:"filters,omitempty" toml:"filters,omitempty" yaml:"filters,omitempty" export:"true"`
	Fields        *AccessLogFields  `description:"AccessLogFields." json:"fields,omitempty" toml:"fields,omitempty" yaml:"fields,omitempty" export:"true"`
	BufferingSize int64             `description:"Number of access log lines to process in a buffered way." json:"bufferingSize,omitempty" toml:"bufferingSize,omitempty" yaml:"bufferingSize,omitempty" export:"true"`
}

// SetDefaults sets the default values.
func (l *AccessLog) SetDefaults() {
	l.Format = CommonFormat
	l.FilePath = ""
	l.Filters = &AccessLogFilters{}
	l.Fields = &AccessLogFields{}
	l.Fields.SetDefaults()
}

// AccessLogFilters holds filters configuration.
type AccessLogFilters struct {
	StatusCodes   []string       `description:"Keep access logs with status codes in the specified range." json:"statusCodes,omitempty" toml:"statusCodes,omitempty" yaml:"statusCodes,omitempty" export:"true"`
	RetryAttempts bool           `description:"Keep access logs when at least one retry happened." json:"retryAttempts,omitempty" toml:"retryAttempts,omitempty" yaml:"retryAttempts,omitempty" export:"true"`
	MinDuration   types.Duration `description:"Keep access logs when request took longer than the specified duration." json:"minDuration,omitempty" toml:"minDuration,omitempty" yaml:"minDuration,omitempty" export:"true"`
}

// FieldHeaders holds configuration for access log headers.
type FieldHeaders struct {
	DefaultMode string            `description:"Default mode for fields: keep | drop | redact" json:"defaultMode,omitempty" toml:"defaultMode,omitempty" yaml:"defaultMode,omitempty" export:"true"`
	Names       map[string]string `description:"Override mode for headers" json:"names,omitempty" toml:"names,omitempty" yaml:"names,omitempty" export:"true"`
}

// AccessLogFields holds configuration for access log fields.
type AccessLogFields struct {
	DefaultMode string            `description:"Default mode for fields: keep | drop" json:"defaultMode,omitempty" toml:"defaultMode,omitempty" yaml:"defaultMode,omitempty"  export:"true"`
	Names       map[string]string `description:"Override mode for fields" json:"names,omitempty" toml:"names,omitempty" yaml:"names,omitempty" export:"true"`
	Headers     *FieldHeaders     `description:"Headers to keep, drop or redact" json:"headers,omitempty" toml:"headers,omitempty" yaml:"headers,omitempty" export:"true"`
}

// SetDefaults sets the default values.
func (f *AccessLogFields) SetDefaults() {
	f.DefaultMode = AccessLogKeep
	f.Headers = &FieldHeaders{
		DefaultMode: AccessLogDrop,
	}
}

// Keep check if the field need to be kept or dropped.
func (f *AccessLogFields) Keep(field string) bool {
	defaultKeep := true
	if f != nil {
		defaultKeep = checkFieldValue(f.DefaultMode, defaultKeep)

		if v, ok := f.Names[field]; ok {
			return checkFieldValue(v, defaultKeep)
		}
	}
	return defaultKeep
}

// KeepHeader checks if the headers need to be kept, dropped or redacted and returns the status.
func (f *AccessLogFields) KeepHeader(header string) string {
	defaultValue := AccessLogKeep
	if f != nil && f.Headers != nil {
		defaultValue = checkFieldHeaderValue(f.Headers.DefaultMode, defaultValue)

		if v, ok := f.Headers.Names[header]; ok {
			return checkFieldHeaderValue(v, defaultValue)
		}
	}
	return defaultValue
}

func checkFieldValue(value string, defaultKeep bool) bool {
	switch value {
	case AccessLogKeep:
		return true
	case AccessLogDrop:
		return false
	default:
		return defaultKeep
	}
}

func checkFieldHeaderValue(value, defaultValue string) string {
	if value == AccessLogKeep || value == AccessLogDrop || value == AccessLogRedact {
		return value
	}
	return defaultValue
}


text:
<?php

namespace Nosto\Test\Unit;

use Codeception\TestCase\Test;
use Exception;
use Nosto\NostoException;
use Nosto\Request\Http\Adapter\Curl;
use Nosto\Request\Http\Adapter\Socket;
use Nosto\Request\Http\HttpRequest;
use Nosto\Request\Http\HttpResponse;
use Nosto\Test\Support\MockUser;

class HttpRequestTest extends Test
{
    /**
     * This must be a port that is not listening
     * wherever the tests are run
     */
    const CURL_TEST_PORT = 9900;

    /**
     * Tests setting query params to the request.
     */
    public function testHttpRequestQueryParams()
    {
        $request = new HttpRequest();
        $request->setQueryParams([
            'param1' => 'first',
            'param2' => 'second',
        ]);
        $params = $request->getQueryParams();
        $this->assertArrayHasKey('param1', $params);
        $this->assertContains('first', $params);
        $this->assertArrayHasKey('param2', $params);
        $this->assertContains('second', $params);
    }

    /**
     * Tests setting the basic auth type.
     * @throws NostoException
     */
    public function testHttpRequestAuthBasic()
    {
        $request = new HttpRequest();
        $request->setAuthBasic('test', 'test');
        $headers = $request->getHeaders();
        $this->assertContains(
            'Authorization: Basic ' . base64_encode(implode(':', ['test', 'test']))
            , $headers
        );
    }

    /**
     * Tests that domain header is correct
     */
    public function testHttpRequestDomainHeader()
    {
        $request = new HttpRequest();
        $request->setActiveDomainHeader('test.nos.to');
        $headers = $request->getHeaders();
        $this->assertContains(
            'X-Nosto-active-domain: test.nos.to'
            , $headers
        );
    }

    /**
     * Test that account header is correct
     */
    public function testHttpRequestAccountHeader()
    {
        $request = new HttpRequest();
        $request->setNostoAccountHeader('test-account');
        $headers = $request->getHeaders();
        $this->assertContains(
            'X-Nosto-account: test-account'
            , $headers
        );
    }

    /**
     * Tests setting the bearer auth type.
     * @throws Exception
     */
    public function testHttpRequestAuthBearer()
    {
        $request = new HttpRequest();
        $request->setAuthBearer('test');
        $headers = $request->getHeaders();
        $this->assertContains('Authorization: Bearer test', $headers);
    }

    /**
     * Tests setting an invalid auth type.
     */
    public function testHttpRequestAuthInvalid()
    {
        $this->expectException('Nosto\NostoException');
        $request = new HttpRequest();
        $request->setAuth('test', 'test');
    }

    /**
     * Tests the "buildUri" helper method.
     */
    public function testHttpRequestBuildUri()
    {
        $uri = HttpRequest::buildUri(
            sprintf(
                'http://localhost:%d?param1={p1}&param2={p2}',
                self::CURL_TEST_PORT
            ),
            [
                '{p1}' => 'first',
                '{p2}' => 'second'
            ]
        );
        $this->assertEquals(
            sprintf(
                'http://localhost:%d?param1=first&param2=second',
                self::CURL_TEST_PORT
            ),
            $uri
        );
    }

    /**
     * Tests the "buildUrl" helper method.
     */
    public function testHttpRequestBuildUrl()
    {
        $url_parts = HttpRequest::parseUrl(
            sprintf(
                'http://localhost:%d/tmp/?param1=first&param2=second#fragment1=test',
                self::CURL_TEST_PORT
            )
        );
        $url = HttpRequest::buildUrl($url_parts);
        $this->assertEquals(
            sprintf(
                'http://localhost:%d/tmp/?param1=first&param2=second#fragment1=test',
                self::CURL_TEST_PORT
            ),
            $url
        );
    }

    /**
     * Tests the "parseQueryString" helper method.
     */
    public function testHttpRequestParseQueryString()
    {
        $query_string_parts = HttpRequest::parseQueryString('param1=first&param2=second');
        $this->assertArrayHasKey('param1', $query_string_parts);
        $this->assertContains('first', $query_string_parts);
        $this->assertArrayHasKey('param2', $query_string_parts);
        $this->assertContains('second', $query_string_parts);
    }

    /**
     * Tests the "replaceQueryParamInUrl" helper method.
     */
    public function testHttpRequestReplaceQueryParamInUrl()
    {
        $url = HttpRequest::replaceQueryParamInUrl(
            'param1',
            'replaced_first',
            sprintf(
                'http://localhost:%d/tmp/?param1=first&param2=second',
                self::CURL_TEST_PORT
            )
        );
        $this->assertEquals(
            sprintf(
                'http://localhost:%d/tmp/?param1=replaced_first&param2=second',
                self::CURL_TEST_PORT
            ),
            $url
        );
    }

    /**
     * Tests the "replaceQueryParam" helper method.
     */
    public function testHttpRequestReplaceQueryParam()
    {
        $query_string = HttpRequest::replaceQueryParam(
            'param2',
            'replaced_second',
            'param1=first&param2=second'
        );
        $this->assertEquals(
            'param1=first&param2=replaced_second',
            $query_string
        );
    }

    /**
     * Tests the http request response result.
     */
    public function testHttpRequestResponseResult()
    {
        $response = new HttpResponse([], json_encode(['test' => true]));
        $this->assertEquals('{"test":true}', $response->getResult());
        $result = $response->getJsonResult(true);
        $this->assertArrayHasKey('test', $result);
        $this->assertContains(true, $result);
    }

    /**
     * Tests the http request response error message.
     */
    public function testHttpRequestResponseErrorMessage()
    {
        $response = new HttpResponse([], '', 'error');
        $this->assertEquals('error', $response->getMessage());
    }

    /**
     * Tests the http request curl adapter.
     */
    public function testHttpRequestCurlAdapter()
    {
        $request = new HttpRequest(new Curl(HttpRequest::$userAgent));
        $request->setResponseTimeout(20);
        $request->setPath('/404');
        $response = $request->get();
        $this->assertEquals(404, $response->getCode());
        $response = $request->post(new MockUser());
        $this->assertEquals(404, $response->getCode());
        $request->setUrl(
            sprintf(
                'http://localhost:%d',
                self::CURL_TEST_PORT
            )
        );
        $response = $request->get();
        $this->assertEquals(
            sprintf(
                'Failed to connect to localhost port %d: Connection refused',
                self::CURL_TEST_PORT
            ),
            $response->getMessage()
        );
    }

    /**
     * Tests the http request socket adapter.
     */
    public function testHttpRequestSocketAdapter()
    {
        $request = new HttpRequest(new Socket(HttpRequest::$userAgent));
        $request->setPath('/404');
        $response = $request->get();
        $this->assertEquals(404, $response->getCode());
        $response = $request->post(new MockUser());
        $this->assertEquals(404, $response->getCode());
    }
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace tik4net.Objects.Ip
{
    /// <summary>
    /// ip/accounting/web-access: The web page report make it possible to use the standard Unix/Linux tool wget to collect the traffic data and save it to a file or to use MikroTik shareware Traffic Counter to display the table. If the web report is enabled and the web page is viewed, the snapshot will be made when connection is initiated to the web page. The snapshot will be displayed on the web page. TCP protocol, used by http connections with the wget tool guarantees that none of the traffic data will be lost. The snapshot image will be made when the connection from wget is initiated. Web browsers or wget should connect to URL: http://routerIP/accounting/ip.cgi
    /// </summary>
    [TikEntity("ip/accounting/web-access", IsSingleton = true)]
    public class AccountingWebAccess
    {
        /// <summary>
        /// accessible-via-web: whether the snapshot is available via web
        /// </summary>
        [TikProperty("accessible-via-web", DefaultValue = "no")]
        public string AccessibleViaWeb { get; set; }

        /// <summary>
        /// address: IP address range that is allowed to access the snapshot
        /// </summary>
        [TikProperty("address", DefaultValue = "0.0.0.0/0")]
        public string Address { get; set; }
    }
}


text:
select  i_item_id,
        avg(cs_quantity) agg1,
        avg(cs_list_price) agg2,
        avg(cs_coupon_amt) agg3,
        avg(cs_sales_price) agg4
 from catalog_sales, customer_demographics, date_dim, item, promotion
 where cs_sold_date_sk = d_date_sk and
       cs_item_sk = i_item_sk and
       cs_bill_cdemo_sk = cd_demo_sk and
       cs_promo_sk = p_promo_sk and
       cd_gender = 'M' and
       cd_marital_status = 'D' and
       cd_education_status = 'College' and
       (p_channel_email = 'N' or p_channel_event = 'N') and
       d_year = 2001 --and
       --removed Cloudera cheat
       --cs_sold_date_sk between 2451910 and 2452276
 group by i_item_id
 order by i_item_id
 limit 100;


text: ReconciliationUI::Application.config.session_store :cookie_store, key: '_ReconciliationUI_session'


text:
    <title>Notebook</title>

    <link href="../node_modules/bootstrap/dist/css/bootstrap.min.css" rel="stylesheet">

    <link href="grid.css" rel="stylesheet">

<?php
/**
 * Created by PhpStorm.
 * User: Maslor
 * Date: 06/12/15
 * Time: 19:17
 */

include("sigmaConnect.php");
$userid=$_REQUEST['userid'];

$userRegsQuery="SELECT typecounter, regcounter, nome FROM registo WHERE userid='$userid' AND ativo=true;";
$userRegsTypesQuery="SELECT typecnt, nome FROM tipo_registo WHERE userid='$userid' AND ativo=true;";

$sigma = new sigmaConnect();

$sigma->connect();
$sigma->submitSQLquery($userRegsQuery);
$userRegsResult=$sigma->getResult();
$sigma->submitSQLquery($userRegsTypesQuery);
$userRegsTypesResult=$sigma->getResult();

echo("
Registries that belong to user $userid:
");
echo("
\n"); foreach($userRegsResult as $row)
{
    echo("
\n");
    echo("Choose	\n");
    echo("{$row['nome']}	\n");
    echo("Remove Registry	\n");
    echo("
\n");
}
echo("
\n");
echo("
Insert a new Registry
");

echo("
Registry Types that belong to user $userid:
");
echo("
\n"); foreach($userRegsTypesResult as $row)
{
    echo("
\n");
    echo("Choose	\n");
    echo("{$row['nome']}	\n");
    echo("Remove Registry Type	\n");
    echo("
\n");
}
echo("
\n");
echo("
Insert a new Registry Type
");

$sigma->disconnect();
?>


text:
title: MySqlConnection.BeginDbTransactionAsync method
---

# MySqlConnection.BeginDbTransactionAsync method

Begins a database transaction asynchronously.

```csharp
protected override ValueTask<DbTransaction> BeginDbTransactionAsync(IsolationLevel isolationLevel,
    CancellationToken cancellationToken)
```

| parameter | description |
| --- | --- |
| isolationLevel | The IsolationLevel for the transaction. |
| cancellationToken | A token to cancel the asynchronous operation. |

## Return Value

A ValueTask representing the new database transaction.

## See Also

* class [MySqlConnection](../../MySqlConnectionType/)
* namespace [MySqlConnector](../../MySqlConnectionType/)
* assembly [MySqlConnector](../../../MySqlConnectorAssembly/)

<!-- DO NOT EDIT: generated by xmldocmd for MySqlConnector.dll -->


text:
<?php

namespace App\Notifications;

use Illuminate\Bus\Queueable;
use Illuminate\Notifications\Notification;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Notifications\Messages\MailMessage;

class PostLiked extends Notification
{
    use Queueable;
    private $post, $liker;

    /**
     * Create a new notification instance.
     *
     * @return void
     */
    public function __construct($post, $liker)
    {
        $this->post = $post;
        $this->liker = $liker;
    }

    /**
     * Get the notification's delivery channels.
     *
     * @param  mixed  $notifiable
     * @return array
     */
    public function via($notifiable)
    {
        return ['database'];
    }

    /**
     * Get the array representation of the notification.
     *
     * @param  mixed  $notifiable
     * @return array
     */
    public function toArray($notifiable)
    {
        return [
            'post_id' => $this->post->id,
            'liker_id' => $this->liker->id,
            'message' => $this->liker->name . ' tykkäsi viestistäsi!',
            'link' => url('/palsta/'.$this->post->thread->slug).'#'.$this->post->id
        ];
    }
}


text:
require 'chef/platform/provider_priority_map'

require 'poise_service/service_providers/dummy'
require 'poise_service/service_providers/inittab'
require 'poise_service/service_providers/systemd'
require 'poise_service/service_providers/sysvinit'
require 'poise_service/service_providers/upstart'

module PoiseService
  # Inversion providers for the poise_service resource.
  #
  # @since 1.0.0
  module ServiceProviders
    # Set up priority maps
    Chef::Platform::ProviderPriorityMap.instance.priority(:poise_service, [
      PoiseService::ServiceProviders::Systemd,
      PoiseService::ServiceProviders::Upstart,
      PoiseService::ServiceProviders::Sysvinit,
    ])
  end
end


text:
package com.acme.calculator.main;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.math.MathContext;
import java.util.Arrays;

/**
 * Entry point for this program to calculate the value of an expression provided on the command-line.
 *
 * The calculated result is printed to stdout.
 *
 * Future option: could add more cmd-line parameters to allow passing the desired precision & RoundingMode.
 *
 * Created by pturcotte on 1/8/16.
 */
public class Startup {
    private static final Logger logger = LogManager.getLogger(Startup.class);
    private static final String JAR_FILE_NAME = "simple.expression.calculator-1.0-SNAPSHOT.jar";
    static String NEWLINE = System.lineSeparator();

    /**
     * main() needed to run this program from the command line.
     * Verifies command-line arguments and prints usage to stdout
     * if the arguments are not as expected.
     *
     * @param args command-line arguments passed to this program
     */
    public static void main(final String[] args) {
        logger.info("main()");
        logger.debug("main(): arguments: {}", Arrays.asList(args));

        if (args.length == 1) {
            Calculator parser = new Calculator(MathContext.DECIMAL128);
            final String expression = args[0];
            final String result = parser.calculate(expression);
            logger.debug("Expression: '{}' -> result: '{}'", expression, result);
            System.out.println(result);
        } else {
            showUsage(args);
        }
    }

    /**
     * Prints usage information to stdout
     *
     * @param args command-line arguments passed to this program
     */
    static void showUsage(final String [] args) {
        logger.debug("showUsage()");
        final String className = Startup.class.getName();
        System.out.println(String.format("Unexpected number of arguments (%d)", args.length));
        System.out.println(String.format("usage:%s\tjava -cp %s %s \"[expression]\" ",NEWLINE, JAR_FILE_NAME, className));
        System.out.println(String.format("example:%s\tjava -cp %s %s \"let(a,7,add(a,div(10,2)))\"",NEWLINE, JAR_FILE_NAME, className));
    }
}


text:
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Xml.Serialization;

using Amazon.OpsWorks.Model;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
using Amazon.Runtime.Internal.Transform;
using Amazon.Runtime.Internal.Util;
using ThirdParty.Json.LitJson;

namespace Amazon.OpsWorks.Model.Internal.MarshallTransformations
{
    /// <summary>
    /// Clone Stack Request Marshaller
    /// </summary>
    internal class CloneStackRequestMarshaller : IMarshaller<IRequest, CloneStackRequest>
    {

        public IRequest Marshall(CloneStackRequest cloneStackRequest)
        {

            IRequest request = new DefaultRequest(cloneStackRequest, "AmazonOpsWorks");
            string target = "OpsWorks_20130218.CloneStack";
            request.Headers["X-Amz-Target"] = target;
            request.Headers["Content-Type"] = "application/x-amz-json-1.1";

            string uriResourcePath = "";

            if (uriResourcePath.Contains("?"))
            {
                string queryString = uriResourcePath.Substring(uriResourcePath.IndexOf("?") + 1);
                uriResourcePath    = uriResourcePath.Substring(0, uriResourcePath.IndexOf("?"));

                foreach (string s in queryString.Split('&', ';'))
                {
                    string[] nameValuePair = s.Split('=');
                    if (nameValuePair.Length == 2 && nameValuePair[1].Length > 0)
                    {
                        request.Parameters.Add(nameValuePair[0], nameValuePair[1]);
                    }
                    else
                    {
                        request.Parameters.Add(nameValuePair[0], null);
                    }
                }
            }

            request.ResourcePath = uriResourcePath;

            using (StringWriter stringWriter = new StringWriter())
            {
                JsonWriter writer = new JsonWriter(stringWriter);
                writer.WriteObjectStart();

                if (cloneStackRequest != null && cloneStackRequest.IsSetSourceStackId())
                {
                    writer.WritePropertyName("SourceStackId");
                    writer.Write(cloneStackRequest.SourceStackId);
                }
                if (cloneStackRequest != null && cloneStackRequest.IsSetName())
                {
                    writer.WritePropertyName("Name");
                    writer.Write(cloneStackRequest.Name);
                }
                if (cloneStackRequest != null && cloneStackRequest.IsSetRegion())
                {
                    writer.WritePropertyName("Region");
                    writer.Write(cloneStackRequest.Region);
                }
                if (cloneStackRequest != null && cloneStackRequest.IsSetVpcId())
                {
                    writer.WritePropertyName("VpcId");
                    writer.Write(cloneStackRequest.VpcId);
                }
                if (cloneStackRequest != null)
                {
                    if (cloneStackRequest.Attributes != null && cloneStackRequest.Attributes.Count > 0)
                    {
                        writer.WritePropertyName("Attributes");
                        writer.WriteObjectStart();
                        foreach (string cloneStackRequestAttributesKey in cloneStackRequest.Attributes.Keys)
                        {
                            string attributesListValue;
                            bool attributesListValueHasValue = cloneStackRequest.Attributes.TryGetValue(cloneStackRequestAttributesKey, out attributesListValue);
                            writer.WritePropertyName(cloneStackRequestAttributesKey);

                        writer.Write(attributesListValue);
                        }
                        writer.WriteObjectEnd();
                    }
                }
                if (cloneStackRequest != null && cloneStackRequest.IsSetServiceRoleArn())
                {
                    writer.WritePropertyName("ServiceRoleArn");
                    writer.Write(cloneStackRequest.ServiceRoleArn);
                }
                if (cloneStackRequest != null && cloneStackRequest.IsSetDefaultInstanceProfileArn())
                {
                    writer.WritePropertyName("DefaultInstanceProfileArn");
                    writer.Write(cloneStackRequest.DefaultInstanceProfileArn);
                }
                if (cloneStackRequest != null && cloneStackRequest.IsSetDefaultOs())
                {
                    writer.WritePropertyName("DefaultOs");
                    writer.Write(cloneStackRequest.DefaultOs);
                }
                if (cloneStackRequest != null && cloneStackRequest.IsSetHostnameTheme())
                {
                    writer.WritePropertyName("HostnameTheme");
                    writer.Write(cloneStackRequest.HostnameTheme);
                }
                if (cloneStackRequest != null && cloneStackRequest.IsSetDefaultAvailabilityZone())
                {
                    writer.WritePropertyName("DefaultAvailabilityZone");
                    writer.Write(cloneStackRequest.DefaultAvailabilityZone);
                }
                if (cloneStackRequest != null && cloneStackRequest.IsSetDefaultSubnetId())
                {
                    writer.WritePropertyName("DefaultSubnetId");
                    writer.Write(cloneStackRequest.DefaultSubnetId);
                }
                if (cloneStackRequest != null && cloneStackRequest.IsSetCustomJson())
                {
                    writer.WritePropertyName("CustomJson");
                    writer.Write(cloneStackRequest.CustomJson);
                }

                if (cloneStackRequest != null)
                {
                    StackConfigurationManager configurationManager = cloneStackRequest.ConfigurationManager;
                    if (configurationManager != null)
                    {
                        writer.WritePropertyName("ConfigurationManager");
                        writer.WriteObjectStart();
                        if (configurationManager != null && configurationManager.IsSetName())
                        {
                            writer.WritePropertyName("Name");
                            writer.Write(configurationManager.Name);
                        }
                        if (configurationManager != null && configurationManager.IsSetVersion())
                        {
                            writer.WritePropertyName("Version");
                            writer.Write(configurationManager.Version);
                        }
                        writer.WriteObjectEnd();
                    }
                }
                if (cloneStackRequest != null && cloneStackRequest.IsSetUseCustomCookbooks())
                {
                    writer.WritePropertyName("UseCustomCookbooks");
                    writer.Write(cloneStackRequest.UseCustomCookbooks);
                }

                if (cloneStackRequest != null)
                {
                    Source customCookbooksSource = cloneStackRequest.CustomCookbooksSource;
                    if (customCookbooksSource != null)
                    {
                        writer.WritePropertyName("CustomCookbooksSource");
                        writer.WriteObjectStart();
                        if (customCookbooksSource != null && customCookbooksSource.IsSetType())
                        {
                            writer.WritePropertyName("Type");
                            writer.Write(customCookbooksSource.Type);
                        }
                        if (customCookbooksSource != null && customCookbooksSource.IsSetUrl())
                        {
                            writer.WritePropertyName("Url");
                            writer.Write(customCookbooksSource.Url);
                        }
                        if (customCookbooksSource != null && customCookbooksSource.IsSetUsername())
                        {
                            writer.WritePropertyName("Username");
                            writer.Write(customCookbooksSource.Username);
                        }
                        if (customCookbooksSource != null && customCookbooksSource.IsSetPassword())
                        {
                            writer.WritePropertyName("Password");
                            writer.Write(customCookbooksSource.Password);
                        }
                        if (customCookbooksSource != null && customCookbooksSource.IsSetSshKey())
                        {
                            writer.WritePropertyName("SshKey");
                            writer.Write(customCookbooksSource.SshKey);
                        }
                        if (customCookbooksSource != null && customCookbooksSource.IsSetRevision())
                        {
                            writer.WritePropertyName("Revision");
                            writer.Write(customCookbooksSource.Revision);
                        }
                        writer.WriteObjectEnd();
                    }
                }
                if (cloneStackRequest != null && cloneStackRequest.IsSetDefaultSshKeyName())
                {
                    writer.WritePropertyName("DefaultSshKeyName");
                    writer.Write(cloneStackRequest.DefaultSshKeyName);
                }
                if (cloneStackRequest != null && cloneStackRequest.IsSetClonePermissions())
                {
                    writer.WritePropertyName("ClonePermissions");
                    writer.Write(cloneStackRequest.ClonePermissions);
                }

                if (cloneStackRequest != null && cloneStackRequest.CloneAppIds != null && cloneStackRequest.CloneAppIds.Count > 0)
                {
                    List<string> cloneAppIdsList = cloneStackRequest.CloneAppIds;
                    writer.WritePropertyName("CloneAppIds");
                    writer.WriteArrayStart();

                    foreach (string cloneAppIdsListValue in cloneAppIdsList)
                    {
                        writer.Write(StringUtils.FromString(cloneAppIdsListValue));
                    }

                    writer.WriteArrayEnd();
                }
                if (cloneStackRequest != null && cloneStackRequest.IsSetDefaultRootDeviceType())
                {
                    writer.WritePropertyName("DefaultRootDeviceType");
                    writer.Write(cloneStackRequest.DefaultRootDeviceType);
                }

                writer.WriteObjectEnd();

                string snippet = stringWriter.ToString();
                request.Content = System.Text.Encoding.UTF8.GetBytes(snippet);
            }

            return request;
        }
    }
}


text:
@interface IDEAppStatistics : NSObject
{
}

+ (void)recordDocDownloadInteraction:(id)arg1;
+ (void)recordDocViewNavigationForURL:(id)arg1;
+ (id)_setOfNavigatedSchemesUsedByDocViewer;
+ (void)recordAppDidShutdown:(id)arg1;
+ (void)recordAppAboutToShutdown;
+ (void)scheduleAppReportWithStartTime:(double)arg1;
+ (void)recordAppUsedGPUDebugger;
+ (void)_performAppReportWithStartupDuration:(double)arg1;
+ (id)_diskTypes;
+ (id)_diskTypeFor:(struct __DADisk *)arg1 withDiskManager:(id)arg2;
+ (unsigned long long)_memInUse;
+ (unsigned long long)_totalRam;

@end


text:
package pow.backend;

import pow.backend.dungeon.DungeonItem;

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

public class ShopData implements Serializable {
    public enum ShopState {
        NONE,
        INN,
        WEAPON_SHOP,
        MAGIC_SHOP,
        JEWELER_SHOP;

        public static ShopState parseFromString(String s) {
            switch (s.toLowerCase()) {
                case "inn": return INN;
                case "weaponshop": return WEAPON_SHOP;
                case "magicshop": return MAGIC_SHOP;
                case "jewelershop": return JEWELER_SHOP;
                default: return NONE;
            }
        }
    }

    public static class ShopEntry implements Serializable {
        public final DungeonItem item;
        public final int price;  // per item

        public ShopEntry(DungeonItem item, int price) {
            this.item = item;
            this.price = price;
        }
    }

    public ShopState state;
    public final int innCost;
    public final List<ShopEntry> weaponItems;
    public final List<ShopEntry> magicItems;

    public ShopData(int innCost, List<ShopEntry> weaponItems, List<ShopEntry> magicItems) {
        this.state = ShopState.NONE;
        this.innCost = innCost;
        this.weaponItems = weaponItems;
        this.magicItems = magicItems;
    }
}


text:
@interface ClassRollsStudentViewController : ByuViewController

@property (nonatomic) InstructorScheduleClassStudent *student;

@end


text:
#pragma once
#include "PolyGlobals.h"
#include "PolyVector2.h"
#include "PolyMatrix4.h"
#include "PolyRectangle.h"
#include "PolyInputKeys.h"
#include "PolyEntity.h"
#include "PolyObject.h"
#include "PolyEventDispatcher.h"

namespace Polycode {

	class _PolyExport MouseEventResult {
		public:
			bool hit;
			bool blocked;
	};

/**
* 2D Entity base.
*
* The ScreenEntity is the base class for all 2D elements in Polycode. They can be added to a screen or to other ScreenEntities and are rendered automatically. If you want to create custom screen objects, subclass this. ScreenEntity subclasses Entity, which use 3d positioning and tranformation, but provides some 2d-only versions of the transformation functions for convenience.
*/
class _PolyExport ScreenEntity : public Entity {

	public:
		using Entity::setPosition;
		using Entity::setScale;

		ScreenEntity();
		virtual ~ScreenEntity();

		virtual Entity *Clone(bool deepClone, bool ignoreEditorOnly) const;
		virtual void applyClone(Entity *clone, bool deepClone, bool ignoreEditorOnly) const;

		void addEntity(Entity *newChild);

		/**
		* Set 2d position.
		* @param x Horizontal position.
		* @param y Vertical position.
		*/
		void setPosition(Number x, Number y);

		/**
		* Set 2d position.
		* @param v New 2D position vector.
		*/
		void setPosition(const Vector2 &v);

		/**
		* Set 2d scale.
		* @param x Horizontal scale.
		* @param y Vertical scale.
		*/
		void setScale(Number x, Number y);

		/**
		* Set 2d scale.
		* @param v New 2D scale vector.
		*/
		void setScale(const Vector2 &v);

		/**
		* Set 2d rotation.
		* @param rotation New rotation value in degrees.
		*/
		void setRotation(Number rotation);

		/**
		* Returns current rotation.
		* @return Current rotation value.
		*/
		Number getRotation() const;

		MouseEventResult _onMouseDown(Number x, Number y, int mouseButton, int timestamp);
		MouseEventResult _onMouseUp(Number x, Number y, int mouseButton, int timestamp);
		MouseEventResult _onMouseMove(Number x, Number y, int timestamp);
		MouseEventResult _onMouseWheelUp(Number x, Number y, int timestamp);
		MouseEventResult _onMouseWheelDown(Number x, Number y, int timestamp);

		virtual void onMouseDown(Number x, Number y){}
		virtual void onMouseUp(Number x, Number y){}
		virtual	void onMouseMove(Number x, Number y){}
		virtual void onMouseWheelUp(Number x, Number y) {}
		virtual void onMouseWheelDown(Number x, Number y) {}

		void _onKeyDown(PolyKEY key, wchar_t charCode);
		void _onKeyUp(PolyKEY key, wchar_t charCode);

		Matrix4 getScreenConcatenatedMatrix() const;

		virtual void onKeyDown(PolyKEY key, wchar_t charCode){}
		virtual void onKeyUp(PolyKEY key, wchar_t charCode){}

		bool hitTest(Number x, Number y) const;
		bool hitTest(Vector2 v) const;

		Matrix4 buildPositionMatrix();
		void adjustMatrixForChildren();

		/**
		* Returns the width of the screen entity.
		* @return Height of the screen entity.
		*/
		Number getWidth() const;

		/**
		* Returns the height of the screen entity.
		*/
		Number getHeight() const;

		/**
		* Sets the width of the screen entity.
		* @param w New height value.
		*/
		void setWidth(Number w) { width = w; hit.w = w; hit.x = -w/2; }

		/**
		* Sets the height of the screen entity.
		* @param h New height value.
		*/
		void setHeight(Number h) { height = h; hit.h = h; hit.y = -h/2; }

		virtual void onGainFocus(){}
		virtual void onLoseFocus(){}

		void startDrag(Number xOffset, Number yOffset);
		void stopDrag();

		void setBlendingMode(int newBlendingMode);

		/**
		* Changes the positioning mode of the screen entity.

		If the positioning mode is ScreenEntity::POSITION_TOPLEFT, the entity is translated by half its width and half its height when it's rendered, making all other transformations relative to its top-left corner instead of the center.
		If the mode is ScreenEntity::POSITION_CENTER, the entity is rendered as is.
		Set to POSITION_CENTER by default.
		@param newPositionMode The new positioning mode.
		*/
		void setPositionMode(int newPositionMode);

		/**
		 * Get the position mode.
		 * @see setPositionMode()
		 */
		int getPositionMode() const;

		/**
		 * Set a rectangle to which dragging will be restricted.
		 *
		 * Dragging the item past the given rectangle will snap it
		 * back to the edge of the rectangle.
		 *
		 * @param rect The rectangle to restrict dragging to. Uses the
		 *              same positioning mode as `this->position`.
		 */
		void setDragLimits(Rectangle rect);

		/**
		 * Disable restricting where `this` can be dragged.
		 * @see setDragLimits()
		 */
		void clearDragLimits();

		/**
		 * Set options for `this` and all children recursively.
		 *
		 * @param snapToPixels Whether to snap entity positions to pixels before rendering.
		 */
		void setDefaultScreenOptions(bool snapToPixels);

		/*
		 * Make `child` take focus, which will cause certain events
		 * to be sent to it.
		 *
		 * Note that this is a global setting. Only one Entity per
		 * running instance can take focus.
		 */
		void focusChild(ScreenEntity *child);

		/*
		 * Make the next child in `this->children`, after the currently
		 * focused child entity take focus.
		 *
		 * Does nothing if no child of `this` has focus.
		 */
		void focusNextChild();

		/**
		 * Same semantics as getPosition(), but returns only the x and y coordinates.
		 *
		 * @see getPosition()
		 * @see getScreenPosition()
		 */
		Vector2 getPosition2D() const;

		/**
		 * Get the position of ScreenEntity in relation to the top-left
		 * corner of the Polycode screen it's on.
		 *
		 * This is unlike getPosition(), which will return the position
		 * of an Entity in relation to its parent Entity.
		 *
		 * @see getPosition()
		 */
		Vector2 getScreenPosition() const;

		/**
		 * Same semantics as getScale(), but returns only the x and y scale.
		 *
		 * @see getScale()
		 */
		Vector2 getScale2D() const;

		/**
		 * Positioning mode in which you specify an entity's topleft corner
		 * as coordinate for placement.
		 */
		static const int POSITION_TOPLEFT = 0;

		/**
		 * Positioning mode in which you specify an entity's center as
		 * coordinate for placement.
		 */
		static const int POSITION_CENTER = 1;

		bool isFocusable() const;

		bool hasFocus;

		/**
		 * Does the same as getEntityByID, but casts to ScreenEntity.
		 *
		 * Note: Make sure only entities of type ScreenEntity have the tag you're
		 *       querying, or otherwise you will be treating an Entity as ScreenEntity.
		 */
		ScreenEntity *getScreenEntityById(String id, bool recursive) const;

		/**
		 * Does the same as getEntitiesByID, but casts each result to ScreenEntity.
		 *
		 * Note: Make sure only entities of type ScreenEntity have the tag you're
		 *       querying, or otherwise you will be treating an Entity as ScreenEntity.
		 */
		std::vector<ScreenEntity*> getScreenEntitiesByTag(String tag, bool recursive) const;

		/**
		* If set to true, will block mouse events for underlaying entities.
		* (NOTE: processInputEvents must be set to true)
		*/
		bool blockMouseInput;

		/**
		* If this option is true, the screen entity's positions will be roudnded to whole pixels. This only works if the screen is using pixel coordinates.
		*/
		bool snapToPixels;
		bool processInputEvents;

		/**
		 * Get the hitbox of this ScreenEntity.
		 * @see setHitBox()
		 */
		Rectangle getHitbox() const;

		void setHitbox(Number width, Number height);

		/**
		 * Set the hitbox of this ScreenEntity.
		 *
		 * The hitbox determines the "physical" dimensions of the entity.
		 *
		 * For instance, when it is checked whether you clicked an entity,
		 * it is checked whether the mouse was pointing inside the hitbox.
		 *
		 * The hitbox is measured from the entity's center, so a hitbox covering
		 * a square would be `(-square.w/2, -square.h/2, square.w, square.h)`
		 *
		 * @param left The left of the hitbox, as measured from the entity's center.
		 * @param top The top of the hitbox, as measured from the entity's center.
		 * @param width The width of the hitbox.
		 * @param height The height of the hitbox.
		 */
		void setHitbox(Number width, Number height, Number left, Number top);

		Number width;
		Number height;

		/**
		 * Get the drag status (true if currently being dragged) of the entity.
		 */
		bool isDragged();

	protected:

		bool focusable;
		bool focusChildren;

		bool dragged;
		Number dragOffsetX;
		Number dragOffsetY;

		bool mouseOver;

		Rectangle hit;

		Number xmouse;
		Number ymouse;

		int positionMode;
		Rectangle *dragLimits;

		int lastClickTicks;

};

}


text:
A memory (RAM) time-released lock for asynchronous resources.

## Usage

The following will drop all requests that come in while
the lock has been taken out and not yet released. Note that
it is up to the client to choose what to do
when another resource has acquired the lease.

```js
var Lease = require('./'),
  lease = Lease(2000);

function get(cb) {
  function criticalSection(err, release) {
    if (err) {
      if ('AlreadyLeasedError' === err.name) return;
      return cb(err);
    }

    setTimeout(function () {
      release();
      cb(null, Math.random());
    }, 1000);
  }

  lease('key', criticalSection);
}
```

### API

  - `Lease(timeInMs)`

## License

[MIT](/LICENSE)


text:
class ServiceBinding
  attr_accessor :id, :service_instance

  USERNAME_PREFIX = 'CFU_'.freeze

  def initialize id
    @id=id.fetch(:id).to_s
    if( true == id.has_key?(:service_instance) )
      @service_instance=id.fetch(:service_instance)
    end
  end

  # Returns a given binding, if the SAP HANA user exists.
  #
  # NOTE: This method cannot currently check for the true existence of
  # the binding. A binding is the association of a SAP HANA user with a
  # database. We use the binding id to identify a user and the instance
  # id to identify a database. As such, we really need both ids to be
  # sure the binding exists. This problem is resolvable by persisting
  # both ids and their relationship in a separate management database.

  def self.find_by_id(id)
    binding = new(id: id)
    begin
      count = ServiceInstance.rdbi_select_single_value("SELECT COUNT(*) FROM SYS.USERS WHERE USER_NAME='#{binding.username}'");
      if count > 0
        binding
      else
        binding = nil
      end
      binding
    rescue Exception => e
      raise unless e.message =~ /no such grant/
    end
  end

  # Returns a given binding, if it exists.
  #
  # NOTE: This method is only necessary because of the current
  # shortcomings of +find_by_id+. And because it requires both
  # the binding id and the instance id, it cannot currently be
  # used by the binding controller.

  def self.find_by_id_and_service_instance_id(id, instance_id)
    instance = ServiceInstance.new(id: instance_id)
    binding = new(id: id, service_instance: instance)

    begin
      count = ServiceInstance.rdbi_select_single_value("SELECT COUNT(*) FROM SYS.GRANTED_PRIVILEGES WHERE SCHEMA_NAME='#{instance.database}' AND GRANTEE='#{binding.username}' AND PRIVILEGE='INSERT'")
      if count > 0
        binding
      else
        binding = nil
      end
    rescue Exception => e
      raise unless e.message =~ /no such grant/
    end
  end

  # Checks to see if the given binding exists.
  #
  # NOTE: This method uses +find_by_id_and_service_instance_id+ to
  # verify true existence, and thus cannot currently be used by the
  # binding controller.

  def self.exists?(conditions)
    id = conditions.fetch(:id)
    instance_id = conditions.fetch(:service_instance_id)
    find_by_id_and_service_instance_id(id, instance_id).present?
  end

  def dsn
    connection_config.fetch('dsn')
  end

  def host
    connection_config.fetch('host')
  end

  def port
    connection_config.fetch('port')
  end

  def database
    service_instance.database
  end

  def username
    @username ||= USERNAME_PREFIX + (Digest::MD5.base64digest(id).gsub(/[^a-zA-Z0-9]+/, '')[0...12]).to_s.upcase
    @username
  end

  def password
    @password ||= ( SecureRandom.base64(20).gsub(/[^a-zA-Z0-9]+/, '')[0...32] + SecureRandom.hex(20)[0...32] )
    @password
  end

  def save
    ServiceInstance.rdbi_create_user(username, password);
    ServiceInstance.rdbi_grant_full_access_to_user(username, database);
  end

  def destroy
    ServiceInstance.rdbi_drop_user(username)
  end

  def to_json(*)
    {
      'credentials' => {
      'hostname' => host,
      'port' => port,
      'name' => database,
      'username' => username,
      'password' => password,
      'uri' => uri,
      'jdbcUrl' => jdbc_url,
      'dsn' => dsn
      }
    }.to_json
  end

  private

  def uri
    "sap://#{username}:#{password}@#{host}:#{port}/#{database}?currentschema=#{database}"
  end

  def jdbc_url
    "jdbc:sap://#{username}:#{password}@#{host}:#{port}/#{database}?currentschema=#{database}"
  end

  def connection_config
    ServiceInstance.connection_config()
  end
end


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.Entity;

namespace DigitalesKlassenbuch.Models
{
    public class LehrgangContext : DbContext
    {

    }
}


text:
from runner.koan import *

class AboutMultipleInheritance(Koan):
    class Nameable(object):
        def __init__(self):
            self._name = None

        def set_name(self, new_name):
            self._name = new_name

        def here(self):
            return "In Nameable class"

    class Animal(object):
        def legs(self):
            return 4

        def can_climb_walls(self):
            return False

        def here(self):
            return "In Animal class"

    class Pig(Animal):
        def __init__(self):
            super(AboutMultipleInheritance.Animal, self).__init__()
            self._name = "Jasper"

        @property
        def name(self):
            return self._name

        def speak(self):
            return "OINK"

        def color(self):
            return 'pink'

        def here(self):
            return "In Pig class"

    class Spider(Animal):
        def __init__(self):
            super(AboutMultipleInheritance.Animal, self).__init__()
            self._name = "Boris"

        def can_climb_walls(self):
            return True

        def legs(self):
            return 8

        def color(self):
            return 'black'

        def here(self):
            return "In Spider class"

    class Spiderpig(Pig, Spider, Nameable):
        def __init__(self):
            super(AboutMultipleInheritance.Pig, self).__init__()
            super(AboutMultipleInheritance.Nameable, self).__init__()
            self._name = "Jeff"

        def speak(self):
            return "This looks like a job for Spiderpig!"

        def here(self):
            return "In Spiderpig class"

    #
    # Hierarchy:
    #               Animal
    #              /     \
    #            Pig   Spider  Nameable
    #              \      |      /
    #                 Spiderpig
    #
    # ------------------------------------------------------------------

    def test_normal_methods_are_available_in_the_object(self):
        jeff = self.Spiderpig()
        self.assertMatch(__, jeff.speak())

    def test_base_class_methods_are_also_available_in_the_object(self):
        jeff = self.Spiderpig()
        try:
            jeff.set_name("Rover")
        except:
            self.fail("This should not happen")
        self.assertEqual(____, jeff.can_climb_walls())

    def test_base_class_methods_can_affect_instance_variables_in_the_object(self):
        jeff = self.Spiderpig()
        self.assertEqual(__, jeff.name)

        jeff.set_name("Rover")
        self.assertEqual(__, jeff.name)

    def test_left_hand_side_inheritance_tends_to_be_higher_priority(self):
        jeff = self.Spiderpig()
        self.assertEqual(__, jeff.color())

    def test_super_class_methods_are_higher_priority_than_super_super_classes(self):
        jeff = self.Spiderpig()
        self.assertEqual(__, jeff.legs())

    def test_we_can_inspect_the_method_resolution_order(self):
        #
        # MRO = Method Resolution Order
        #
        mro = type(self.Spiderpig()).__mro__
        self.assertEqual('Spiderpig', mro[0].__name__)
        self.assertEqual('Pig', mro[1].__name__)
        self.assertEqual(__, mro[2].__name__)
        self.assertEqual(__, mro[3].__name__)
        self.assertEqual(__, mro[4].__name__)
        self.assertEqual(__, mro[5].__name__)

    def test_confirm_the_mro_controls_the_calling_order(self):
        jeff = self.Spiderpig()
        self.assertMatch('Spiderpig', jeff.here())

        next = super(AboutMultipleInheritance.Spiderpig, jeff)
        self.assertMatch('Pig', next.here())

        next = super(AboutMultipleInheritance.Pig, jeff)
        self.assertMatch(__, next.here())

        # Hang on a minute?!? That last class name might be a super class of
        # the 'jeff' object, but its hardly a superclass of Pig, is it?
        #
        # To avoid confusion it may help to think of super() as next_mro().


text:
local Message         = require "cp.spec.Message"

local Error         = Message:subclass("cp.spec.Error")

--- cp.spec.Error.is(other) -> boolean
--- Function
--- Checks if the `other` is an instance of the `Error` class.
---
--- Parameters:
---  * other - An object to check
---
--- Returns:
---  * A boolean
function Error.static.is(other)
    return other ~= nil and type(other) == "table" and other.isInstanceOf ~= nil and other:isInstanceOf(Error)
end

return Error


text:
package org.camunda.bpm.engine.test.jobexecutor;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;

import org.camunda.bpm.engine.ManagementService;
import org.camunda.bpm.engine.RuntimeService;
import org.camunda.bpm.engine.impl.ProcessEngineLogger;
import org.camunda.bpm.engine.impl.cfg.ProcessEngineConfigurationImpl;
import org.camunda.bpm.engine.impl.cmd.AcquireJobsCmd;
import org.camunda.bpm.engine.impl.jobexecutor.AcquiredJobs;
import org.camunda.bpm.engine.impl.jobexecutor.JobExecutor;
import org.camunda.bpm.engine.management.JobDefinition;
import org.camunda.bpm.engine.runtime.Job;
import org.camunda.bpm.engine.test.util.ProcessEngineTestRule;
import org.camunda.bpm.engine.test.util.ProvidedProcessEngineRule;
import org.camunda.bpm.model.bpmn.Bpmn;
import org.camunda.bpm.model.bpmn.BpmnModelInstance;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.slf4j.Logger;

/**
 * @author Daniel Meyer
 *
 */
public class JobDefinitionFunctionalTest {

  static Logger LOG = ProcessEngineLogger.TEST_LOGGER.getLogger();

  @Rule
  public ProvidedProcessEngineRule engineRule = new ProvidedProcessEngineRule();

  @Rule
  public ProcessEngineTestRule testRule = new ProcessEngineTestRule(engineRule);

  protected RuntimeService runtimeService;
  protected ManagementService managementService;
  protected ProcessEngineConfigurationImpl processEngineConfiguration;

  protected static final BpmnModelInstance SIMPLE_ASYNC_PROCESS = Bpmn.createExecutableProcess("simpleAsyncProcess")
      .startEvent()
      .serviceTask()
        .camundaExpression("${true}")
        .camundaAsyncBefore()
      .endEvent()
      .done();

  @Before
  public void initServices() {
    runtimeService = engineRule.getRuntimeService();
    managementService = engineRule.getManagementService();
    processEngineConfiguration = engineRule.getProcessEngineConfiguration();
  }

  @Test
  public void testCreateJobInstanceSuspended() {
    testRule.deploy(SIMPLE_ASYNC_PROCESS);

    // given suspended job definition:
    managementService.suspendJobDefinitionByProcessDefinitionKey("simpleAsyncProcess");

    // if I start a new instance
    runtimeService.startProcessInstanceByKey("simpleAsyncProcess");

    // then the new job instance is created as suspended:
    assertNotNull(managementService.createJobQuery().suspended().singleResult());
    assertNull(managementService.createJobQuery().active().singleResult());
  }

  @Test
  public void testCreateJobInstanceActive() {
    testRule.deploy(SIMPLE_ASYNC_PROCESS);

    // given that the job definition is not suspended:

    // if I start a new instance
    runtimeService.startProcessInstanceByKey("simpleAsyncProcess");

    // then the new job instance is created as active:
    assertNull(managementService.createJobQuery().suspended().singleResult());
    assertNotNull(managementService.createJobQuery().active().singleResult());
  }

  @Test
  public void testJobExecutorOnlyAcquiresActiveJobs() {
    testRule.deploy(SIMPLE_ASYNC_PROCESS);

    // given suspended job definition:
    managementService.suspendJobDefinitionByProcessDefinitionKey("simpleAsyncProcess");

    // if I start a new instance
    runtimeService.startProcessInstanceByKey("simpleAsyncProcess");

    // then the new job executor will not acquire the job:
    AcquiredJobs acquiredJobs = acquireJobs();
    assertEquals(0, acquiredJobs.size());

    // -------------------------

    // given a active job definition:
    managementService.activateJobDefinitionByProcessDefinitionKey("simpleAsyncProcess", true);

    // then the new job executor will not acquire the job:
    acquiredJobs = acquireJobs();
    assertEquals(1, acquiredJobs.size());
  }

  @Test
  public void testExclusiveJobs() {
    testRule.deploy(Bpmn.createExecutableProcess("testProcess")
        .startEvent()
        .serviceTask("task1")
          .camundaExpression("${true}")
          .camundaAsyncBefore()
        .serviceTask("task2")
          .camundaExpression("${true}")
          .camundaAsyncBefore()
        .endEvent()
        .done());

    JobDefinition jobDefinition = managementService.createJobDefinitionQuery()
      .activityIdIn("task2")
      .singleResult();

    // given that the second task is suspended
    managementService.suspendJobDefinitionById(jobDefinition.getId());

    // if I start a process instance
    runtimeService.startProcessInstanceByKey("testProcess");

    testRule.waitForJobExecutorToProcessAllJobs(10000);

    // then the second task is not executed
    assertEquals(1, runtimeService.createProcessInstanceQuery().count());
    // there is a suspended job instance
    Job job = managementService.createJobQuery()
      .singleResult();
    assertEquals(job.getJobDefinitionId(), jobDefinition.getId());
    assertTrue(job.isSuspended());

    // if I unsuspend the job definition, the job is executed:
    managementService.activateJobDefinitionById(jobDefinition.getId(), true);

    testRule.waitForJobExecutorToProcessAllJobs(10000);

    assertEquals(0, runtimeService.createProcessInstanceQuery().count());
  }

  protected AcquiredJobs acquireJobs() {
    JobExecutor jobExecutor = processEngineConfiguration.getJobExecutor();

    return processEngineConfiguration.getCommandExecutorTxRequired()
      .execute(new AcquireJobsCmd(jobExecutor));
  }

}