text:
typedef CGAL::Simple_cartesian<double> Kernel;

typedef Kernel::Point_3 Point_3;
typedef std::size_t Point;

//definition of the property map and get
//function as friend function to have access to
//private member
class My_point_property_map{
  const std::vector<Point_3>& points;
public:
  typedef Point_3 value_type;
  typedef const value_type& reference;
  typedef Point key_type;
  typedef boost::lvalue_property_map_tag category;

  My_point_property_map(const std::vector<Point_3>& pts):points(pts){}

  friend reference get(const My_point_property_map& ppmap,key_type i)
  {return ppmap.points[i];}
};
typedef CGAL::Search_traits_3<Kernel> Traits_base;
typedef CGAL::Search_traits_adapter<Point,My_point_property_map,Traits_base> Traits;

typedef CGAL::Orthogonal_k_neighbor_search<Traits> K_neighbor_search;
typedef K_neighbor_search::Tree       Tree;
typedef Tree::Splitter              Splitter;
typedef K_neighbor_search::Distance Distance;

int main() {
  const unsigned int N = 50;
  CGAL::Timer timer;
  timer.start();

  std::vector<Point_3> points, queries;
  Point_3 p;

  std::ifstream point_stream("points.xyz");
  while(point_stream >> p){
    points.push_back(p);

  }

  My_point_property_map ppmap(points);
  Distance tr_dist(ppmap);

  std::ifstream query_stream("queries.xyz");
  while(query_stream >> p ){
    queries.push_back(p);

  }
  timer.stop();
  std::cerr << "reading points took " << timer.time() << " sec." << std::endl;

  timer.reset();
  timer.start();
  Tree tree( boost::counting_iterator<std::size_t>(0),
             boost::counting_iterator<std::size_t>(points.size()),
             Splitter(),
             Traits(ppmap));
  tree.build();
  timer.stop();
  std::cerr << "tree construction took " << timer.time() << " sec." << std::endl;

  // Initialize the search structure, and search all N points

  double d = 0;
  timer.reset();
  timer.start();
  for(int i = 0; i < queries.size(); i++){
    K_neighbor_search search(tree, queries[i], 50, 0, true, tr_dist);

    // report the N nearest neighbors and their distance
    // This should sort all N points by increasing distance from origin
    for(K_neighbor_search::iterator it = search.begin(); it != search.end(); ++it){
      //std::cout << it->first << std::endl;
      d += get(ppmap,it->first).x();
    }
  }
  timer.stop();
  std::cerr << d << std::endl;
  std::cerr << queries.size() << " queries in " << timer.time() << " sec." << std::endl;

  return 0;
}


text:
using UnityEngine;
using UnityEditor;

[CanEditMultipleObjects, CustomEditor(typeof(MegaStretchWarp))]
public class MegaStretchWarpEditor : MegaWarpEditor
{
	[MenuItem("GameObject/Create Other/MegaFiers/Warps/Stretch")]
	static void CreateStarShape() { CreateWarp("Stretch", typeof(MegaStretchWarp)); }

	public override string GetHelpString() { return "Stretch Warp Modifier by Chris West"; }
	public override Texture LoadImage() { return (Texture)EditorGUIUtility.LoadRequired("MegaFiers\\stretch_help.png"); }

	public override bool Inspector()
	{
		MegaStretchWarp mod = (MegaStretchWarp)target;

#if !UNITY_5
		EditorGUIUtility.LookLikeControls();
#endif
		mod.amount = EditorGUILayout.FloatField("Amount", mod.amount);
		mod.amplify		= EditorGUILayout.FloatField("Amplify", mod.amplify);
		mod.axis		= (MegaAxis)EditorGUILayout.EnumPopup("Axis", mod.axis);
		mod.doRegion	= EditorGUILayout.Toggle("Do Region", mod.doRegion);
		mod.from		= EditorGUILayout.FloatField("From", mod.from);
		mod.to			= EditorGUILayout.FloatField("To", mod.to);
		return false;
	}
}

redpajama_set_name: RedPajamaGithub


text:
package com.google.android.libraries.mobiledatadownload.account;

import static com.google.common.truth.Truth.assertThat;

import android.accounts.Account;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.robolectric.RobolectricTestRunner;

/** Unit tests for {@link AccountUtil}. */
@RunWith(RobolectricTestRunner.class)
public class AccountUtilTest {

  @Test
  public void createAccount() {
    String name = "account-name";
    String type = "account-type";

    Account account = AccountUtil.create(name, type);

    assertThat(account).isNotNull();
    assertThat(account.name).isEqualTo(name);
    assertThat(account.type).isEqualTo(type);
  }

  @Test
  public void createAccount_emptyField() {
    String name = "account-name";
    String type = "account-type";

    // Neither name nor type can be empty.
    assertThat(AccountUtil.create("" /* name */, type)).isNull();
    assertThat(AccountUtil.create(null /* name */, type)).isNull();
    assertThat(AccountUtil.create(name, "" /* type */)).isNull();
    assertThat(AccountUtil.create(name, null /* type */)).isNull();
  }

  @Test
  public void createAccount_containDelimiter() {
    String name = "account-name";
    String type = "account-type";

    // Neither name or type can contain account delimiter.
    assertThat(AccountUtil.create("prefix:suffix" /* name */, type)).isNull();
    assertThat(AccountUtil.create(name, "prefix:suffix" /* type */)).isNull();
  }

  @Test
  public void createAccount_containSplitChar() {
    String name = "account-name";
    String type = "account-type";

    // Neither name or type can contain split char.
    assertThat(AccountUtil.create("prefix|suffix" /* name */, type)).isNull();
    assertThat(AccountUtil.create(name, "prefix|suffix" /* type */)).isNull();
  }

  @Test
  public void serializeAccount() {
    String name = "account-name";
    String type = "account-type";

    Account account = new Account(name, type);
    String serialized = AccountUtil.serialize(account);

    assertThat(serialized).isEqualTo("account-type:account-name");
  }

  @Test
  public void deserializeAccount() {
    String accountStr = "foo:bar";
    Account account = AccountUtil.deserialize(accountStr);

    assertThat(account.type).isEqualTo("foo");
    assertThat(account.name).isEqualTo("bar");
  }

  @Test
  public void deserializeAccount_noDelimiter() {
    // No account delimiter is found.
    assertThat(AccountUtil.deserialize("type and name")).isNull();
  }

  @Test
  public void deserializeAccount_multipleDelimiter() {
    // Multiple account delimiters are found.
    assertThat(AccountUtil.deserialize("type:name:foo")).isNull();
    assertThat(AccountUtil.deserialize("type::name")).isNull();
  }

  @Test
  public void deserializeAccount_containsSplitchar() {
    // Neither name or type can contain split char.
    assertThat(AccountUtil.deserialize("type:na|me")).isNull();
    assertThat(AccountUtil.deserialize("ty|pe:name")).isNull();
  }
}


text:
Lightwight Docker image for the (latest) PHP-FPM and Nginx based on [AlpineLinux](http://alpinelinux.org)

* Image size only ~100MB !
* Very new packages (alpine:edge) 2015-04-03:
  * [PHP](http://pkgs.alpinelinux.org/package/main/x86/php) 5.6.7
  * [Nginx](http://pkgs.alpinelinux.org/package/main/x86/nginx) 1.6.2

### Usage
```bash
sudo docker run -v /data:/DATA -p 80:80 psitrax/php-nginx
```

### Volume structure

* `htdocs`: Webroot
* `logs`: Nginx/PHP error logs


text:
"""Accesses the google.cloud.asset.v1beta1 AssetService API."""

import pkg_resources
import warnings

from google.oauth2 import service_account
import google.api_core.gapic_v1.client_info
import google.api_core.gapic_v1.config
import google.api_core.gapic_v1.method
import google.api_core.grpc_helpers
import google.api_core.operation
import google.api_core.operations_v1
import google.api_core.path_template
import grpc

from google.cloud.asset_v1beta1.gapic import asset_service_client_config
from google.cloud.asset_v1beta1.gapic import enums
from google.cloud.asset_v1beta1.gapic.transports import asset_service_grpc_transport
from google.cloud.asset_v1beta1.proto import asset_service_pb2
from google.cloud.asset_v1beta1.proto import asset_service_pb2_grpc
from google.cloud.asset_v1beta1.proto import assets_pb2
from google.longrunning import operations_pb2
from google.protobuf import timestamp_pb2

_GAPIC_LIBRARY_VERSION = pkg_resources.get_distribution("google-cloud-asset").version

class AssetServiceClient(object):
    """Asset service definition."""

    SERVICE_ADDRESS = "cloudasset.googleapis.com:443"
    """The default address of the service."""

    # The name of the interface for this client. This is the key used to
    # find the method configuration in the client_config dictionary.
    _INTERFACE_NAME = "google.cloud.asset.v1beta1.AssetService"

    @classmethod
    def from_service_account_file(cls, filename, *args, **kwargs):
        """Creates an instance of this client using the provided credentials
        file.

        Args:
            filename (str): The path to the service account private key json
                file.
            args: Additional arguments to pass to the constructor.
            kwargs: Additional arguments to pass to the constructor.

        Returns:
            AssetServiceClient: The constructed client.
        """
        credentials = service_account.Credentials.from_service_account_file(filename)
        kwargs["credentials"] = credentials
        return cls(*args, **kwargs)

    from_service_account_json = from_service_account_file

    @classmethod
    def project_path(cls, project):
        """Return a fully-qualified project string."""
        return google.api_core.path_template.expand(
            "projects/{project}", project=project
        )

    def __init__(
        self,
        transport=None,
        channel=None,
        credentials=None,
        client_config=None,
        client_info=None,
    ):
        """Constructor.

        Args:
            transport (Union[~.AssetServiceGrpcTransport,
                    Callable[[~.Credentials, type], ~.AssetServiceGrpcTransport]): A transport
                instance, responsible for actually making the API calls.
                The default transport uses the gRPC protocol.
                This argument may also be a callable which returns a
                transport instance. Callables will be sent the credentials
                as the first argument and the default transport class as
                the second argument.
            channel (grpc.Channel): DEPRECATED. A ``Channel`` instance
                through which to make calls. This argument is mutually exclusive
                with ``credentials``; providing both will raise an exception.
            credentials (google.auth.credentials.Credentials): The
                authorization credentials to attach to requests. These
                credentials identify this application to the service. If none
                are specified, the client will attempt to ascertain the
                credentials from the environment.
                This argument is mutually exclusive with providing a
                transport instance to ``transport``; doing so will raise
                an exception.
            client_config (dict): DEPRECATED. A dictionary of call options for
                each method. If not specified, the default configuration is used.
            client_info (google.api_core.gapic_v1.client_info.ClientInfo):
                The client info used to send a user-agent string along with
                API requests. If ``None``, then default info will be used.
                Generally, you only need to set this if you're developing
                your own client library.
        """
        # Raise deprecation warnings for things we want to go away.
        if client_config is not None:
            warnings.warn(
                "The `client_config` argument is deprecated.",
                PendingDeprecationWarning,
                stacklevel=2,
            )
        else:
            client_config = asset_service_client_config.config

        if channel:
            warnings.warn(
                "The `channel` argument is deprecated; use " "`transport` instead.",
                PendingDeprecationWarning,
                stacklevel=2,
            )

        # Instantiate the transport.
        # The transport is responsible for handling serialization and
        # deserialization and actually sending data to the service.
        if transport:
            if callable(transport):
                self.transport = transport(
                    credentials=credentials,
                    default_class=asset_service_grpc_transport.AssetServiceGrpcTransport,
                )
            else:
                if credentials:
                    raise ValueError(
                        "Received both a transport instance and "
                        "credentials; these are mutually exclusive."
                    )
                self.transport = transport
        else:
            self.transport = asset_service_grpc_transport.AssetServiceGrpcTransport(
                address=self.SERVICE_ADDRESS, channel=channel, credentials=credentials
            )

        if client_info is None:
            client_info = google.api_core.gapic_v1.client_info.ClientInfo(
                gapic_version=_GAPIC_LIBRARY_VERSION
            )
        else:
            client_info.gapic_version = _GAPIC_LIBRARY_VERSION
        self._client_info = client_info

        # Parse out the default settings for retry and timeout for each RPC
        # from the client configuration.
        # (Ordinarily, these are the defaults specified in the `*_config.py`
        # file next to this one.)
        self._method_configs = google.api_core.gapic_v1.config.parse_method_configs(
            client_config["interfaces"][self._INTERFACE_NAME]
        )

        # Save a dictionary of cached API call functions.
        # These are the actual callables which invoke the proper
        # transport methods, wrapped with `wrap_method` to add retry,
        # timeout, and the like.
        self._inner_api_calls = {}

    # Service calls
    def export_assets(
        self,
        parent,
        output_config,
        read_time=None,
        asset_types=None,
        content_type=None,
        retry=google.api_core.gapic_v1.method.DEFAULT,
        timeout=google.api_core.gapic_v1.method.DEFAULT,
        metadata=None,
    ):
        """
        Exports assets with time and resource types to a given Cloud Storage
        location. The output format is newline-delimited JSON. This API
        implements the ``google.longrunning.Operation`` API allowing you to keep
        track of the export.

        Example:
            >>> from google.cloud import asset_v1beta1
            >>>
            >>> client = asset_v1beta1.AssetServiceClient()
            >>>
            >>> parent = client.project_path('[PROJECT]')
            >>>
            >>> # TODO: Initialize `output_config`:
            >>> output_config = {}
            >>>
            >>> response = client.export_assets(parent, output_config)
            >>>
            >>> def callback(operation_future):
            ...     # Handle result.
            ...     result = operation_future.result()
            >>>
            >>> response.add_done_callback(callback)
            >>>
            >>> # Handle metadata.
            >>> metadata = response.metadata()

        Args:
            parent (str): Required. The relative name of the root asset. This can only be an organization
                number (such as "organizations/123"), a project ID (such as
                "projects/my-project-id"), or a project number (such as "projects/12345").
            output_config (Union[dict, ~google.cloud.asset_v1beta1.types.OutputConfig]): Required. Output configuration indicating where the results will be output
                to. All results will be in newline delimited JSON format.

                If a dict is provided, it must be of the same form as the protobuf
                message :class:`~google.cloud.asset_v1beta1.types.OutputConfig`
            read_time (Union[dict, ~google.cloud.asset_v1beta1.types.Timestamp]): Timestamp to take an asset snapshot. This can only be set to a timestamp in
                the past or of the current time. If not specified, the current time will be
                used. Due to delays in resource data collection and indexing, there is a
                volatile window during which running the same query may get different
                results.

                If a dict is provided, it must be of the same form as the protobuf
                message :class:`~google.cloud.asset_v1beta1.types.Timestamp`
            asset_types (list[str]): A list of asset types of which to take a snapshot for. For example:
                "google.compute.disk". If specified, only matching assets will be returned.
            content_type (~google.cloud.asset_v1beta1.types.ContentType): Asset content type. If not specified, no content but the asset name will be
                returned.
            retry (Optional[google.api_core.retry.Retry]):  A retry object used
                to retry requests. If ``None`` is specified, requests will not
                be retried.
            timeout (Optional[float]): The amount of time, in seconds, to wait
                for the request to complete. Note that if ``retry`` is
                specified, the timeout applies to each individual attempt.
            metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata
                that is provided to the method.

        Returns:
            A :class:`~google.cloud.asset_v1beta1.types._OperationFuture` instance.

        Raises:
            google.api_core.exceptions.GoogleAPICallError: If the request
                    failed for any reason.
            google.api_core.exceptions.RetryError: If the request failed due
                    to a retryable error and retry attempts failed.
            ValueError: If the parameters are invalid.
        """
        # Wrap the transport method to add retry and timeout logic.
        if "export_assets" not in self._inner_api_calls:
            self._inner_api_calls[
                "export_assets"
            ] = google.api_core.gapic_v1.method.wrap_method(
                self.transport.export_assets,
                default_retry=self._method_configs["ExportAssets"].retry,
                default_timeout=self._method_configs["ExportAssets"].timeout,
                client_info=self._client_info,
            )

        request = asset_service_pb2.ExportAssetsRequest(
            parent=parent,
            output_config=output_config,
            read_time=read_time,
            asset_types=asset_types,
            content_type=content_type,
        )
        operation = self._inner_api_calls["export_assets"](
            request, retry=retry, timeout=timeout, metadata=metadata
        )
        return google.api_core.operation.from_gapic(
            operation,
            self.transport._operations_client,
            asset_service_pb2.ExportAssetsResponse,
            metadata_type=asset_service_pb2.ExportAssetsRequest,
        )

    def batch_get_assets_history(
        self,
        parent,
        content_type,
        read_time_window,
        asset_names=None,
        retry=google.api_core.gapic_v1.method.DEFAULT,
        timeout=google.api_core.gapic_v1.method.DEFAULT,
        metadata=None,
    ):
        """
        Batch gets the update history of assets that overlap a time window. For
        RESOURCE content, this API outputs history with asset in both non-delete
        or deleted status. For IAM\_POLICY content, this API outputs history
        when the asset and its attached IAM POLICY both exist. This can create
        gaps in the output history.

        Example:
            >>> from google.cloud import asset_v1beta1
            >>> from google.cloud.asset_v1beta1 import enums
            >>>
            >>> client = asset_v1beta1.AssetServiceClient()
            >>>
            >>> parent = client.project_path('[PROJECT]')
            >>>
            >>> # TODO: Initialize `content_type`:
            >>> content_type = enums.ContentType.CONTENT_TYPE_UNSPECIFIED
            >>>
            >>> # TODO: Initialize `read_time_window`:
            >>> read_time_window = {}
            >>>
            >>> response = client.batch_get_assets_history(parent, content_type, read_time_window)

        Args:
            parent (str): Required. The relative name of the root asset. It can only be an
                organization number (such as "organizations/123"), a project ID (such as
                "projects/my-project-id")", or a project number (such as "projects/12345").
            content_type (~google.cloud.asset_v1beta1.types.ContentType): Required. The content type.
            read_time_window (Union[dict, ~google.cloud.asset_v1beta1.types.TimeWindow]): Required. The time window for the asset history. The start time is
                required. The returned results contain all temporal assets whose time
                window overlap with read\_time\_window.

                If a dict is provided, it must be of the same form as the protobuf
                message :class:`~google.cloud.asset_v1beta1.types.TimeWindow`
            asset_names (list[str]): A list of the full names of the assets. For example:
                ``//compute.googleapis.com/projects/my_project_123/zones/zone1/instances/instance1``.
                See `Resource
                Names <https://cloud.google.com/apis/design/resource_names#full_resource_name>`__
                for more info.

                The request becomes a no-op if the asset name list is empty, and the max
                size of the asset name list is 100 in one request.
            retry (Optional[google.api_core.retry.Retry]):  A retry object used
                to retry requests. If ``None`` is specified, requests will not
                be retried.
            timeout (Optional[float]): The amount of time, in seconds, to wait
                for the request to complete. Note that if ``retry`` is
                specified, the timeout applies to each individual attempt.
            metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata
                that is provided to the method.

        Returns:
            A :class:`~google.cloud.asset_v1beta1.types.BatchGetAssetsHistoryResponse` instance.

        Raises:
            google.api_core.exceptions.GoogleAPICallError: If the request
                    failed for any reason.
            google.api_core.exceptions.RetryError: If the request failed due
                    to a retryable error and retry attempts failed.
            ValueError: If the parameters are invalid.
        """
        # Wrap the transport method to add retry and timeout logic.
        if "batch_get_assets_history" not in self._inner_api_calls:
            self._inner_api_calls[
                "batch_get_assets_history"
            ] = google.api_core.gapic_v1.method.wrap_method(
                self.transport.batch_get_assets_history,
                default_retry=self._method_configs["BatchGetAssetsHistory"].retry,
                default_timeout=self._method_configs["BatchGetAssetsHistory"].timeout,
                client_info=self._client_info,
            )

        request = asset_service_pb2.BatchGetAssetsHistoryRequest(
            parent=parent,
            content_type=content_type,
            read_time_window=read_time_window,
            asset_names=asset_names,
        )
        return self._inner_api_calls["batch_get_assets_history"](
            request, retry=retry, timeout=timeout, metadata=metadata
        )


text:
' Copyright (c) Microsoft.  All Rights Reserved.  Licensed under the Apache License, Version 2.0.  See License.txt in the project root for license information.

Imports Microsoft.CodeAnalysis.Text
Imports Microsoft.CodeAnalysis.VisualBasic
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Imports Roslyn.Test.Utilities
Imports Xunit

Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.Recommendations.Statements
    Public Class CatchKeywordRecommenderTests
        <Fact>
        <Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
        Public Sub CatchNotInMethodBody()
            VerifyRecommendationsMissing(<MethodBody>|</MethodBody>, "Catch")
        End Sub

        <Fact>
        <Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
        Public Sub CatchInTryBlock()
            VerifyRecommendationsContain(<MethodBody>
Try
|
Finally
End Try</MethodBody>, "Catch")
        End Sub

        <Fact>
        <Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
        Public Sub CatchInCatchBlock()
            VerifyRecommendationsContain(<MethodBody>
Try
Catch ex As Exception
|
Finally
End Try</MethodBody>, "Catch")
        End Sub

        <Fact>
        <Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
        Public Sub CatchNotInFinallyBlock()
            VerifyRecommendationsMissing(<MethodBody>
Try
Finally
|
End Try</MethodBody>, "Catch")
        End Sub
    End Class
End Namespace


text:
var PhAdjective = function(parent, dividePoint) {
	this.construct(parent, dividePoint);
};

(function() {
	PhProtoWord.registrPhTyp(PhAdjective, PhProtoStage, Adjective, user.adjectives, 'PhAdjective');
	PhAdjective.prototype.emphasisWordsCollection = user.emphasis.adjectives;
	PhAdjective.prototype.wordsCollections = [PhAdjective.prototype.emphasisWordsCollection, PhAdjective.prototype.wordsCollection];

	PhAdjective.prototype.construct = function(parent, dividePoint) {
		PhProtoStage.prototype.construct.call(this, parent, dividePoint);
	};

	PhAdjective.prototype.gen = function(settings, wordsCollection) {
		// Подбирает случайные слова и обороты
		this.setBySettings(settings);
		if(!this.mathCountWords(settings) || this.parent && this.parent.noSubwords) return;
		var ret;
		if(this.parent && this.parent.constructorFunc === PhNoun) {
			this.genStage(settings);
			ret = PhProtoStage.prototype.gen.call(this, settings, wordsCollection, this.parent.commonFlags);
		} else if(this.parent && this.parent === this.dividePoint && this.parent.toBe.adjectives === this) {
			if(!this.parent.nouns) this.parent.genNouns();
			var parNoun = this.parent.nouns;
			if(parNoun) {
				var flags = parNoun.commonFlags;
				console.log('adj', flags);
				ret = PhProtoStage.prototype.gen.call(this, settings, wordsCollection, flags);
			} else {
				ret = PhProtoStage.prototype.gen.apply(this, arguments);
			}
		} else {
			ret = PhProtoStage.prototype.gen.apply(this, arguments);
		}
		return ret;
	};

	PhAdjective.prototype.mathRank = function(settings) {
		var ret = settings.sPhAdjective;
		return ret;
	};

	PhAdjective.prototype.writeEn = function() {
		// Возвращает часть предложения, относящуюся к этому слову или этим словам
		var en = this.en; // Хранятся переменные для английской фразы
		writeCommon(this, en);
		PhProtoStage.prototype.writeEn.apply(this, arguments);
		en.comparativeStr = ''; // comparative формируется внутри слова (ведь может быть не "он более быстрый" а "он быстрее").
		var ret = joins(en.noStr, en.veryStr, en.comparativeStr, en.wordsStr, en.thanStr);
		if(!this.parent) ret = trim(ret);
		return ret;
	};

	PhAdjective.prototype.getFormedWordEn = function() {
		// Возвращает строковое предсавление основного слова в нужном падеже(и т.п.).
		return this.word[0].getFormed(this.en.comparative);
	};

	var writeCommon = function(th, wr) {
	};

	PhAdjective.prototype.writeRu = function(gender, padej) {
		// Возвращает часть предложения, относящуюся к этому слову или этим словам
		var ru = this.ru; // Хранятся переменные для русской фразы
		writeCommon(this, ru);
		if(this.inListing) {
			if(this.parent.ru.gender !== undefined) ru.gender = this.parent.ru.gender;
			if(this.parent.ru.padej !== undefined) ru.padej = this.parent.ru.padej;
		}
		if(gender !== undefined) ru.gender = gender;
		if(padej !== undefined) ru.padej = padej;
		PhProtoStage.prototype.writeRu.apply(this, arguments);
		ru.comparativeStr = ''; // comparative формируется внутри слова (ведь может быть не "он более быстрый" а "он быстрее").
		var ret = joins(ru.noStr, ru.veryStr, ru.comparativeStr, ru.wordsStr, ru.thanStr);
		if(!this.parent) ret = trim(ret);
		return ret;
	};

	PhAdjective.prototype.getFormedWordRu = function() {
		// Возвращает строковое предсавление основного слова в нужном падеже(и т.п.).
		/*var ru = this.ru;
		if(!this.ru.comparative && this.dividePoint && this.dividePoint.nouns.why) {
			var why = this.dividePoint.nouns.why.val;
			if(why > 1) {
				if(why % 100 > 4 && why % 100 < 21) {
				} else if(why % 10 === 1) {
					return this.word[1].getFormed(0, this.ru.gender, 0); // 31 черная палка
				} else if(why % 10 > 1 && why % 10 < 5) {
					return this.word[1].getFormed(0, this.ru.gender, 0); // 44 черные палки
				}
				return this.word[1].getFormed(0, this.ru.gender, 1); // 111 черных палок 19 палок // 30 палок, 35 палок
			}
		}*/
		return this.word[1].getFormed(this.ru.comparative, this.ru.gender || 0, this.ru.padej || 0);
	};

})();


text:
var randomInt = (function (min,max)
{
    return Math.floor(Math.random()*(max-min+1)+min);
});

var randomFloat = (function (min,max)
{
    return Math.random()*(max-min)+min;
});

var randomBool = (function ()
{
    return randomFloat(0, 1) > 0.5;
});

exports.randomInt = randomInt;
exports.randomFloat = randomFloat;
exports.randomBool = randomBool;


text:
<!doctype html>

  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
  <meta name="viewport" content="width=device-width">
  <meta name="description" content="Cascading grid layout library">

  <title>Masonry · Extras</title>

    <link rel="stylesheet" href="css/masonry-docs.css" media="screen">

          Masonry

          Layout

          Options

          Methods

          Events

          Extras

          FAQ

Extras

Extra examples

RequireJS

Browserify

Webpack

Bootstrap

Animating item size

Web fonts

Typekit

Issues

Reduced test cases

Submitting issues

Browser support

Upgrading from v3

Additional resources

Extra examples

Iteratively reveal items after each image is loaded. See explanation on issue #501

Drag and drop in and out of Masonry (sort of)

RequireJS

Masonry supports RequireJS.

You can require masonry.pkgd.js.

requirejs( [
  'path/to/masonry.pkgd.js',
], function( Masonry ) {
  new Masonry( '.grid', {...});
});

To use Masonry as a jQuery plugin with RequireJS and masonry.pkgd.js, you need to use jQuery Bridget.

// require the require function
requirejs( [ 'require', 'jquery', 'path/to/masonry.pkgd.js' ],
  function( require, $, Masonry ) {
    // require jquery-bridget, it's included in masonry.pkgd.js
    require( [ 'jquery-bridget/jquery-bridget' ],
    function( jQueryBridget ) {
      // make Masonry a jQuery plugin
      jQueryBridget( 'masonry', Masonry, $ );
      // now you can use $().masonry()
      $('.grid').masonry({...});
    }
  );
});

Or, you can manage dependencies with Bower. Set baseUrl to bower_components and set a path config for all your application code.

requirejs.config({
  baseUrl: 'bower_components/',
  paths: {
    app: '../'
  }
});

requirejs( [
  'masonry/masonry',
  'app/my-component.js'
], function( Masonry, myComp ) {
  new Masonry( '.grid', {...});
});

You can require Bower dependencies and use Masonry as a jQuery plugin with jQuery Bridget.

requirejs.config({
  baseUrl: '../bower_components',
  paths: {
    jquery: 'jquery/jquery'
  }
});

requirejs( [
    'jquery',
    'masonry/masonry',
    'jquery-bridget/jquery-bridget'
  ],
  function( $, Masonry, jQueryBridget ) {
    // make Masonry a jQuery plugin
    jQueryBridget( 'masonry', Masonry, $ );
    // now you can use $().masonry()
    $('.grid').masonry({...});
});

Browserify

Masonry works with Browserify. Install Masonry with npm.

npm install masonry-layout

var Masonry = require('masonry-layout');

var msnry = new Masonry( '.grid', {
  // options...
});

To use Masonry as a jQuery plugin with Browserify, you need to use jQuery Bridget

npm install jquery
npm install jquery-bridget

var $ = require('jquery');
var jQueryBridget = require('jquery-bridget');
var Masonry = require('masonry-layout');
// make Masonry a jQuery plugin
jQueryBridget( 'masonry', Masonry, $ );
// now you can use $().masonry()
$('.grid').masonry({
  columnWidth: 80
});

Webpack

Install Masonry with npm.

npm install masonry-layout

You can then require('masonry-layout').

// main.js
var Masonry = require('masonry-layout');

var msnry = new Masonry( '.grid', {
  // options...
});

Run webpack.

webpack main.js bundle.js

jQuery plugin functionality needs to be installed separately, similar to using Browserify.

npm install jquery-bridget

var $ = require('jquery');
var jQueryBridget = require('jquery-bridget');
var Masonry = require('masonry-layout');
// make Masonry a jQuery plugin
jQueryBridget( 'masonry', Masonry, $ );
// now you can use $().masonry()
$('.grid').masonry({
  columnWidth: 80
});

Bootstrap

You can use Masonry layouts with Bootstrap grid system. This example will display a fluid grid of 3 columns, using col-xs-4 as columnWidth.

<div class="container-fluid">
  <!-- add extra container element for Masonry -->
  <div class="grid">
    <!-- add sizing element for columnWidth -->
    <div class="grid-sizer col-xs-4"></div>
    <!-- items use Bootstrap .col- classes -->
    <div class="grid-item col-xs-8">
      <!-- wrap item content in its own element -->
      <div class="grid-item-content">...</div>
    </div>
    <div class="grid-item col-xs-4">
      <div class="grid-item-content">...</div>
    </div>
    ...
  </div>
</div>

$('.grid').masonry({
  itemSelector: '.grid-item', // use a separate class for itemSelector, other than .col-
  columnWidth: '.grid-sizer',
  percentPosition: true
});

        Edit this demo on CodePen

Use multiple .col- classes on item elements to use Bootstrap’s grid media queries to responsively change column sizes. This example will use 2, then 3, then 4 columns at different screen sizes.

<div class="container-fluid">
  <div class="grid">
    <!-- 2 col grid @ xs, 3 col grid @ sm, 4 col grid @ md -->
    <div class="grid-sizer col-xs-6 col-sm-4 col-md-3"></div>
    <!-- 1 col @ xs, 2 col @ sm, 2 col @ md -->
    <div class="grid-item col-xs-6 col-sm-8 col-md-6">
      <div class="grid-item-content">...</div>
    </div>
    <!-- 1 col @ xs, 1 col @ sm, 1 col @ md -->
    <div class="grid-item col-xs-6 col-sm-4 col-md-3">
      <div class="grid-item-content">...</div>
    </div>
    ...
  </div>
</div>

        Edit this demo on CodePen

Animating item size

You cannot transition or animate the size of an item element and properly lay out. But there is a trick — you can animate a child element of the item element.

<div class="grid">
  <!-- items have grid-item-content child elements -->
  <div class="grid-item">
    <div class="grid-item-content"></div>
  </div>
  ...

/* item is invisible, but used for layout
item-content is visible, and transitions size */
.grid-item,
.grid-item-content {
  width: 60px;
  height: 60px;
}
.grid-item-content {
  background: #09D;
  transition: width 0.4s, height 0.4s;
}

/* both item and item content change size */
.grid-item.is-expanded,
.grid-item.is-expanded .grid-item-content {
  width: 180px;
  height: 120px;
}

Click to item to toggle size

        Edit this demo
        or vanilla JS demo on CodePen

This technique works on items with responsive, percentage widths. Although, it does require a bit more JS. Check out the example on CodePen to see how it’s done.

.grid-item {
  width: 20%;
  height: 60px;
}

.grid-item-content {
  width:  100%;
  height: 100%;
  background: #09D;
  transition: width 0.4s, height 0.4s;
}
/* item has expanded size */
.grid-item.is-expanded {
  width: 60%;
  height: 120px;
}

Click to item to toggle size

        Edit this demo
        or vanilla JS demo on CodePen

Web fonts

Like images, unloaded web fonts can throw off Masonry. To resolve this, trigger layout after fonts have been loaded. Both Typekit and Google WebFont Loader provide font events to control scripts based on how fonts are loaded.

Typekit font events

Google WebFont Loader: Events

Typekit

Try the script below when using Masonry on a page with Typekit. This will trigger Masonry when the document is ready and again when fonts have loaded. Be sure to remove Typekit’s default script, try{Typekit.load();}catch(e){}.

var msnry;

function triggerMasonry() {
  // don't proceed if masonry has not been initialized
  if ( !msnry ) {
    return;
  }
  msnry.layout();
}
// initialize masonry on document ready
docReady( function() {
  var container = document.querySelector('.grid');
  msnry = new Masonry( container, {
    // options...
  });
});
// trigger masonry when fonts have loaded
Typekit.load({
  active: triggerMasonry,
  inactive: triggerMasonry
});

// or with jQuery
var $grid;

function triggerMasonry() {
  // don't proceed if $grid has not been selected
  if ( !$grid ) {
    return;
  }
  // init Masonry
  $grid.masonry({
    // options...
  });
}
// trigger masonry on document ready
$(function(){
  $grid = $('.grid');
  triggerMasonry();
});
// trigger masonry when fonts have loaded
Typekit.load({
  active: triggerMasonry,
  inactive: triggerMasonry
});

Issues

Reduced test cases

Creating a reduced test case is the best way to debug problems and report issues. Read CSS Tricks on why they’re so great.

Create a reduced test case for Masonry by forking any one of the CodePen demos from these docs.

A reduced test case clearly demonstrates the bug or issue.

It contains the bare minimum HTML, CSS, and JavaScript required to demonstrate the bug.

A link to your production site is not a reduced test case.

Creating a reduced test case is the best way to get your issue addressed. They help you point out the problem. They help us debug the problem. They help others understand the problem.

Submitting issues

Report issues on GitHub. Make sure to include a reduced test case. Without a reduced test case, your issue may be closed.

Browser support

Masonry v4 supports IE10+, Android 4+, Safari for iOS 5+, Firefox 16+, and Chrome 12+.

For IE8+ and Android 2.3 support, try Masonry v3.

Upgrading from v3

Masonry v4 dropped browser support for IE8, IE9, and Android 2.3. All options, methods, and code for Masonry v3 is backwards compatibile with Masonry v4.

isOptionName options renamed to optionName. Masonry v4 is backwards compatible with the old isOptionName options.

isFitWidth → fitWidth

isOriginLeft → originLeft

isOriginTop → originTop

isResizeBound → resize

isInitLayout → initLayout

HTML initialization can be done with data-masonry.  Masonry v4 is backwards compatible with previous code: js-masonry class and data-masonry-options  attribute.

IE8 helper dependencies removed: eventie, get-style-property, doc-ready

jquery-bridget/jquery.bridget path renamed to jquery-bridget/jquery-bridget

Additional resources

Masonry CodePens

The Metafizzy blog has posts that cover specialized use cases

My answers on Stack Overflow

Sites using Masonry on Delicious

Stack Overflow questions about Masonry

Related Masonry links

Other resources that are like Masonry but not

          Masonry

          Layout

          Options

          Methods

          Events

          Extras

          FAQ

        Masonry is made by David DeSandro.
        Make something rad with it.

                    <svg class="isotope-illo" xmlns="http://www.w3.org/2000/svg" viewbox="0 0 350 350" width="100" height="100">
                      <path class="isotope-illo__color1" fill="#6C6" d="M80 170H30c-6 0-10-5-10-10v-50c0-6 5-10 10-10h50c6 0 10 5 10 10v50C90 166 86 170 80 170z"/>
                      <path class="isotope-illo__color1" fill="#6C6" d="M80 90H30c-6 0-10-5-10-10V30c0-6 5-10 10-10h50c6 0 10 5 10 10v50C90 86 86 90 80 90z"/>
                      <path class="isotope-illo__color1" fill="#6C6" d="M160 90h-50c-6 0-10-5-10-10V30c0-6 5-10 10-10h50c6 0 10 5 10 10v50C170 86 166 90 160 90z"/>
                      <path class="isotope-illo__color1" fill="#6C6" d="M240 90h-50c-6 0-10-5-10-10V30c0-6 5-10 10-10h50c6 0 10 5 10 10v50C250 86 246 90 240 90z"/>
                      <path class="isotope-illo__color1" fill="#6C6" d="M320 90h-50c-6 0-10-5-10-10V30c0-6 5-10 10-10h50c6 0 10 5 10 10v50C330 86 326 90 320 90z"/>
                      <path class="isotope-illo__color1" fill="#6C6" d="M155 165h-40c-6 0-10-5-10-10v-40c0-6 5-10 10-10h40c6 0 10 5 10 10v40 C165 161 161 165 155 165z"/>
                      <path class="isotope-illo__color1" fill="#6C6" d="M230 160h-30c-6 0-10-5-10-10v-30c0-6 5-10 10-10h30c6 0 10 5 10 10v30 C240 156 236 160 230 160z"/>
                      <path class="isotope-illo__color1" fill="#6C6" d="M305 155h-20c-6 0-10-5-10-10v-20c0-6 5-10 10-10h20c6 0 10 5 10 10v20 C315 151 311 155 305 155z"/>
                      <path class="isotope-illo__color1" fill="#6C6" d="M65 235H45c-6 0-10-5-10-10v-20c0-6 5-10 10-10h20c6 0 10 5 10 10v20C75 231 71 235 65 235z"/>
                      <path class="isotope-illo__color1" fill="#6C6" d="M140 230h-10c-6 0-10-5-10-10v-10c0-6 5-10 10-10h10c6 0 10 5 10 10v10 C150 226 146 230 140 230z"/>
                      <path class="isotope-illo__color2" fill="#19F" d="M305 235h-20c-6 0-10-5-10-10v-20c0-6 5-10 10-10h20c6 0 10 5 10 10v20 C315 231 311 235 305 235z"/>
                      <path class="isotope-illo__color2" fill="#19F" d="M65 315H45c-6 0-10-5-10-10v-20c0-6 5-10 10-10h20c6 0 10 5 10 10v20C75 311 71 315 65 315z"/>
                      <path class="isotope-illo__color2" fill="#19F" d="M150 320h-30c-6 0-10-5-10-10v-30c0-6 5-10 10-10h30c6 0 10 5 10 10v30 C160 316 156 320 150 320z"/>
                      <path class="isotope-illo__color2" fill="#19F" d="M220 230h-10c-6 0-10-5-10-10v-10c0-6 5-10 10-10h10c6 0 10 5 10 10v10 C230 226 226 230 220 230z"/>
                      <path class="isotope-illo__color2" fill="#19F" d="M235 325h-40c-6 0-10-5-10-10v-40c0-6 5-10 10-10h40c6 0 10 5 10 10v40 C245 321 241 325 235 325z"/>
                      <path class="isotope-illo__color2" fill="#19F" d="M320 330h-50c-6 0-10-5-10-10v-50c0-6 5-10 10-10h50c6 0 10 5 10 10v50 C330 326 326 330 320 330z"/>
                    </svg>

Isotope

Filter & sort magical layouts

                    <svg class="flickity-illo" xmlns="http://www.w3.org/2000/svg" viewbox="0 0 360 360" width="100" height="100">
                      <path class="flickity-illo__color1" fill="#19F" d="M300 220L300 220c-11 0-20-9-20-20v-80c0-11 9-20 20-20h0V220z"/>
                      <path class="flickity-illo__color1" fill="#19F" d="M340 220L340 220c-11 0-20-9-20-20v-80c0-11 9-20 20-20h0V220z"/>
                      <path class="flickity-illo__color2" fill="#333" d="M320 290V180c0-18-10-35-27-43L240 110v180H320z"/>
                      <path class="flickity-illo__color3" fill="white" d="M240 300H120c-11 0-20-9-20-20V40c0-11 9-20 20-20h120c11 0 20 9 20 20v240C260 291 251 300 240 300z"/>
                      <path class="flickity-illo__color4" fill="#ED0" d="M230 260H130c-6 0-10-5-10-10V70c0-6 5-10 10-10h100c6 0 10 5 10 10v180 C240 256 236 260 230 260z"/>
                      <path class="flickity-illo__color2" fill="#333" d="M260 200h60v81c0 32-26 59-59 59h0c-34 0-61-27-61-61V240h20 C242 240 260 222 260 200L260 200z"/>
                      <path class="flickity-illo__color5" fill="#C25" d="M180 220h-60V100h60c6 0 10 5 10 10v100C190 216 186 220 180 220z"/>
                      <path class="flickity-illo__color1" fill="#19F" d="M240 220h-20c-6 0-10-5-10-10V110c0-6 5-10 10-10h20V220z"/>
                      <rect class="flickity-illo__color2" fill="#333" x="230" y="280" width="90" height="80"/>
                      <circle class="flickity-illo__color4" fill="#ED0" cx="180" cy="280" r="10"/>
                      <line class="flickity-illo__thumb" stroke="#333" stroke-width="60" stroke-linecap="round" x1="262" y1="290" x2="152" y2="240"/>
                      <path class="flickity-illo__color4" fill="#ED0" d="M190 50h-20c-6 0-10-5-10-10v0c0-6 5-10 10-10h20c6 0 10 5 10 10v0C200 46 196 50 190 50z"/>
                      <path class="flickity-illo__color5" fill="#C25" d="M80 220L80 220c-11 0-20-9-20-20v-80c0-11 9-20 20-20h0V220z"/>
                      <path class="flickity-illo__color5" fill="#C25" d="M40 220L40 220c-11 0-20-9-20-20v-80c0-11 9-20 20-20h0V220z"/>
                    </svg>

Flickity

Touch, responsive, flickable carousels

                    <svg class="packery-illo" xmlns="http://www.w3.org/2000/svg" viewbox="0 0 700 700" width="100" height="100">
                      <path class="packery-illo__item" fill="#C09" d="M172 180H48c-4 0-8-4-8-8V48c0-4 4-8 8-8h124c4 0 8 4 8 8v124C180 176 176 180 172 180z"/>
                      <path class="packery-illo__item" fill="#C09" d="M172 340H48c-4 0-8-4-8-8V208c0-4 4-8 8-8h124c4 0 8 4 8 8v124C180 336 176 340 172 340z"/>
                      <path class="packery-illo__item" fill="#C09" d="M492 660H368c-4 0-8-4-8-8V528c0-4 4-8 8-8h124c4 0 8 4 8 8v124C500 656 496 660 492 660z"/>
                      <path class="packery-illo__item" fill="#C09" d="M652 660H528c-4 0-8-4-8-8V528c0-4 4-8 8-8h124c4 0 8 4 8 8v124C660 656 656 660 652 660z"/>
                      <path class="packery-illo__item" fill="#C09" d="M652 500H368c-4 0-8-4-8-8V368c0-4 4-8 8-8h284c4 0 8 4 8 8v124C660 496 656 500 652 500z"/>
                      <path class="packery-illo__item" fill="#C09" d="M332 660H48c-4 0-8-4-8-8V368c0-4 4-8 8-8h284c4 0 8 4 8 8v284C340 656 336 660 332 660z"/>
                      <path class="packery-illo__item" fill="#C09" d="M652 340H528c-4 0-8-4-8-8V48c0-4 4-8 8-8h124c4 0 8 4 8 8v284C660 336 656 340 652 340z"/>
                      <path class="packery-illo__draggie" fill="#EA0" d="M572 440H288c-4 0-8-4-8-8V148c0-4 4-8 8-8h284c4 0 8 4 8 8v284C580 436 576 440 572 440z"/>
                      <g>
                        <path class="packery-illo__hand" fill="white" d="M530 250c-11 0-20 9-20 20v-10c0-11-9-20-20-20s-20 9-20 20c0-11-9-20-20-20s-20 9-20 20c0-11-9-20-20-20
                          s-20 9-20 20v20c-17 0-30 13-30 30c0 11 6 20 14 25l19 35c10 18 30 30 51 30h28
                          c43 0 78-35 78-78V270C550 259 541 250 530 250z"/>
                        <line class="packery-illo__hand-line" stroke="#EA0" fill="none" stroke-width="16" stroke-linecap="round" x1="430" y1="300" x2="430" y2="340"/>
                        <line class="packery-illo__hand-line" stroke="#EA0" fill="none" stroke-width="16" stroke-linecap="round" x1="470" y1="300" x2="470" y2="340"/>
                        <line class="packery-illo__hand-line" stroke="#EA0" fill="none" stroke-width="16" stroke-linecap="round" x1="510" y1="300" x2="510" y2="340"/>
                      </g>
                    </svg>

Packery

Gapless, draggable grid layouts

                    <svg class="huebee-illo" xmlns="http://www.w3.org/2000/svg" viewbox="0 0 200 200" width="100" height="100">
                      <polygon class="huebee-illo__stripe4" fill="#19F" points="100,170 65,135 135,135 "/>
                      <rect class="huebee-illo__stripe3" fill="#EA0" x="65" y="110" width="70" height="25"/>
                      <rect class="huebee-illo__stripe2" fill="#E62" x="65" y="85" width="70" height="25"/>
                      <polygon class="huebee-illo__stripe1" fill="#C25" points="135,85 65,85 65,70 80,55 120,55 135,70 "/>
                      <path class="huebee-illo__line" stroke="#333" fill="none" stroke-width="15" d="M140 90c0-22-18-40-39-40C78 50 60 68 60 91V110c0 14 5 27 15 37
                        l25 25l25-25c10-10 15-23 15-37V90z"/>
                      <path class="huebee-illo__line" stroke="#333" fill="none" stroke-width="15" d="M60 74v50c0 11-9 21-21 21h0c-18 0-27-22-15-35L60 74z"/>
                      <path class="huebee-illo__line" stroke="#333" fill="none" stroke-width="15" d="M140 74v50c0 11 9 21 21 21h0c18 0 27-22 15-35L140 74z"/>
                      <line class="huebee-illo__line huebee-illo__antenna" stroke="#333" fill="none" stroke-width="15" stroke-linecap="round" x1="60" y1="30" x2="80" y2="50"/>
                      <line class="huebee-illo__line huebee-illo__antenna" stroke="#333" fill="none" stroke-width="15" stroke-linecap="round" x1="140" y1="30" x2="120" y2="50"/>
                    </svg>

Huebee

One-click color picker

                    <svg class="logo-pizza-illo" xmlns="http://www.w3.org/2000/svg" viewbox="0 0 700 700" width="100" height="100">
                      <path class="logo-pizza-illo__outline" fill="#C25" d="M513 91c-9-0-17 5-21 12l-80 160c-3 5-6 10-11 15l-47 47
                        c-5 5-12-1-9-7l32-64c5-11-2-23-14-23h-0c-121 0-268 70-327 180
                        C-9 497 35 609 196 609c138 0 279-85 327-180v0c5-11-2-23-14-23h-77c-13 0-19-15-10-24
                        l81-81c5-5 11-8 18-8l0 0c13 0 19 15 10 24L494 354c-6 6-6 14 0 20c3 3 6 4 10 4
                        c4 0 7-1 10-4l80-80h53c9 0 17-5 21-13C707 190 656 97 513 91z M334 281l-59 117
                        c-2 5-7 8-13 8H97c-4 0-6-4-3-7c49-64 143-114 236-124C333 275 335 278 334 281z
                         M70 441c2-4 6-7 10-7h168c4 0 7 4 5 8l-59 118c-2 4-6 6-11 6
                        C106 565 38 521 70 441z M466 441c-49 64-143 114-236 124c-3 0-6-3-4-6l59-117
                        c2-5 7-8 13-8h166C466 434 468 438 466 441z M446 318l-81 81c-5 5-11 8-18 8l0 0
                        c-13 0-19-15-10-24l81-81c5-5 11-8 18-8l0 0C449 294 455 309 446 318z M447 258L506 139
                        c2-4 6-7 11-6c101 7 140 60 114 126c-2 4-6 7-10 7H452C448 266 445 262 447 258z"/>
                      <path class="logo-pizza-illo__slice" fill="#ED0" d="M334 281l-59 117c-2 5-7 8-13 8H97c-4 0-6-4-3-7
                        c49-64 143-114 236-124C333 275 335 278 334 281z"/>
                      <path class="logo-pizza-illo__slice" fill="#ED0" d="M70 441c2-4 6-7 10-7h168c4 0 7 4 5 8l-59 118c-2 4-6 6-11 6
                        C106 565 38 521 70 441z"/>
                      <path class="logo-pizza-illo__slice" fill="#ED0" d="M466 441c-49 64-143 114-236 124c-3 0-6-3-4-6l59-117
                        c2-5 7-8 13-8h166C466 434 468 438 466 441z"/>
                      <path class="logo-pizza-illo__slice" fill="#ED0" d="M447 258L506 139c2-4 6-7 11-6c101 7 140 60 114 126c-2 4-6 7-10 7H452
                        C448 266 445 262 447 258z"/>
                    </svg>

Logo Pizza

Hot & ready logos for sale


text:
require 'fileutils'
require 'csv'
require 'mysql'

#Patch to make mysql 2.8 utf8 friendly
class Mysql::Result
  def encode(value, encoding = "utf-8")
    String === value ? value.force_encoding(encoding) : value
  end

  def each_utf8(&block)
    each_orig do |row|
      yield row.map {|col| encode(col) }
    end
  end
  alias each_orig each
  alias each each_utf8

  def each_hash_utf8(&block)
    each_hash_orig do |row|
      row.each {|k, v| row[k] = encode(v) }
      yield(row)
    end
  end
  alias each_hash_orig each_hash
  alias each_hash each_hash_utf8
end

def load_db_dim_arrays()
  begin
    @dbTables_hash.each_key do |key|
      array = @dbTables_hash[key]
      load_db_array(key,array)
    end
  ensure
    $db.close
  end
end

def load_db_array (table,array)
  @db_dim_hash[array] = {}
  $db.query("SET NAMES utf8")
  results = $db.query "SELECT * FROM #{table}"
  if results.num_rows > 0
    results.each do |row|
      id, value = row
      @db_dim_hash[array][value] = Integer(id)
    end
    results.free
  end
end

def removeDuplicateValues()
  @dim_hash.each_key do |key|
    aux = @dim_hash[key].uniq
    @dim_hash[key] = aux
  end
end

def sortValues()
  @dim_hash.each_key do |key|
    aux = @dim_hash[key].sort
    @dim_hash[key] = aux
  end
end

def debugLengths()
  @dim_hash.each_key do |key|
    puts "#{key}: #{@dim_hash[key].length}"
  end
end

def writeOutputFiles()
  @dim_hash.each_key do |key|
    output_file = File.open("#{OUTPUT_FILES_SUBDIR}/#{@filenames_hash[key]}", 'w')
    @dim_hash[key].each{|item| output_file.puts(item)}
    output_file.close
  end
end

LOG_SUBDIR = '../logs'
INPUT_FILES_SUBDIR = '../txt'
SHIP_INPUT_FILE = 'shipData.csv'
DOCK_INPUT_FILE = 'dockData.csv'
OPER_INPUT_FILE = 'operData.csv'
OUTPUT_FILES_SUBDIR = '../updateDim'
FileUtils.makedirs(LOG_SUBDIR)
FileUtils.makedirs(OUTPUT_FILES_SUBDIR)

@filenames_hash = {"array_sCode"=>"DIM_SHIPID_UPDATE.txt",
                  "array_sType"=>"DIM_SHIPTYPE_UPDATE.txt",
                  "array_country" => "DIM_COUNTRY_UPDATE.txt",
                  "array_place" => "DIM_PLACE_UPDATE.txt",
                  "array_dCode"=>"DIM_DOCKID_UPDATE.txt",
                  "array_dConsignee" => "DIM_CONSIGNEE_UPDATE.txt",
                  "array_oType"=>"DIM_OPERTYPE_UPDATE.txt",
                  "array_oMerchandise"=>"DIM_MERCHANDISE_UPDATE.txt",
                  "array_oLongShore"=>"DIM_LONGSHORE_UPDATE.txt"}

@dbTables_hash = {"DIM_SHIPID"=>"dbShipId",
                  "DIM_DOCKID"=>"dbDockId",
                  "DIM_SHIPTYPE" => "dbShipType",
                  "DIM_COUNTRY" => "dbCountry",
                  "DIM_PLACE"=>"dbPlace",
                  "DIM_CONSIGNEE" => "dbConsignee",
                  "DIM_LONGSHORE"=>"dbLongshore",
                  "DIM_MERCHANDISE"=>"dbMerchandise",
                  "DIM_OPERTYPE"=>"dbOperType"}

@dim_hash = Hash.new {|h,k| h[k] = [] }
@db_dim_hash = Hash.new {|h,k| h[k] = {} }

$log_file = File.open("#{LOG_SUBDIR}/extractDimFiles.log", 'w')
begin
  $db = Mysql.init
  $db.options(Mysql::SET_CHARSET_NAME, 'utf8')
  $db.real_connect('localhost','enrique', '', 'APVigo_ShipMovs')
  $db.query("SET NAMES utf8")
rescue Mysql::Error
  $log_file.puts("#We could not connect with the DB")
  exit 1
end
#Load the existing db dimension tables
load_db_dim_arrays()

#process the ship file
CSV.foreach("#{INPUT_FILES_SUBDIR}/#{SHIP_INPUT_FILE}", :quote_char => '"', :col_sep =>'|', :row_sep =>:auto) do |row|
    shipCode,shipName,shipLength,shipWidth,shipDraught,
    shipGrossTonnage,shipType,shipFlag,shipCode2,shipLLoydsId = row
    if !(@db_dim_hash["dbShipId"].has_key?(shipCode))
      @dim_hash["array_sCode"].push(shipCode)
      if !(@db_dim_hash["dbShipType"].has_key?(shipType))
        @dim_hash["array_sType"].push(shipType) if shipType.length>0
      end
      if !(@db_dim_hash["dbCountry"].has_key?(shipFlag))
        @dim_hash["array_country"].push(shipFlag)
      end
    end
end
puts "#{INPUT_FILES_SUBDIR}/#{SHIP_INPUT_FILE}: processed"

#process the docking file
CSV.foreach("#{INPUT_FILES_SUBDIR}/#{DOCK_INPUT_FILE}", :quote_char => '"', :col_sep =>'|', :row_sep =>:auto) do |row|
    shipCode,dockCode,stop,bollards,quay,
    arrival,departure,consignee,origin,destination = row
    if !(@db_dim_hash["dbDockId"].has_key?(dockCode))
      @dim_hash["array_dCode"].push(dockCode)
      if !(@db_dim_hash["dbConsignee"].has_key?(consignee))
        @dim_hash["array_dConsignee"].push(consignee) if consignee.length>0
      end

      #process the origin field
      if origin
        #looking from the end find the first opening parenthesis
        bef, mat, aft = origin.rpartition("(")
        if aft.length > 0
          #We remove the closing parenthesis
          country = aft.split(")")[0].strip
          if !(@db_dim_hash["dbCountry"].has_key?(country))
            @dim_hash["array_country"].push(country)
          end
        else
          #log
        end
        #looking from the beginning find the first opening parenthesis
        bef, mat, aft = origin.partition("(")
        if bef.length > 0
          #We remove the additional spaces if needed
          place = bef.strip
          if !(@db_dim_hash["dbPlace"].has_key?(place))
            @dim_hash["array_place"].push(place)
          end
        else
          #log
        end
      else
        #log
      end

      #process the destination field
      if destination
        #looking from the end find the first opening parenthesis
        bef, mat, aft = destination.rpartition("(")
        if aft.length > 0
          #We remove the closing parenthesis
          country = aft.split(")")[0].strip
          if !(@db_dim_hash["dbCountry"].has_key?(country))
            @dim_hash["array_country"].push(country)
          end
        else
          #log
        end
        #looking from the beginning find the first opening parenthesis
        bef, mat, aft = destination.partition("(")
        if bef.length > 0
          #We remove the additional spaces if needed
          place = bef.strip
          if !(@db_dim_hash["dbPlace"].has_key?(place))
            @dim_hash["array_place"].push(place)
          end
        else
          #log
        end
      else
        #log
      end
    end #If include dockCode
end

puts "#{INPUT_FILES_SUBDIR}/#{DOCK_INPUT_FILE}: processed"

#process the operations file
CSV.foreach("#{INPUT_FILES_SUBDIR}/#{OPER_INPUT_FILE}", :quote_char => '"', :col_sep =>'|', :row_sep =>:auto) do |row|
    shipCode,dockCode,operSec,operType,
    operDesc,tons,merchandise,longShore = row
    if !(@db_dim_hash["dbDockId"].has_key?(dockCode))
      if !(@db_dim_hash["dbOperType"].has_key?(operType))
        @dim_hash["array_oType"].push(operType) if operType.length>0
      end
      if !(@db_dim_hash["dbMerchandise"].has_key?(merchandise))
        @dim_hash["array_oMerchandise"].push(merchandise) if merchandise.length>0
      end
      if !(@db_dim_hash["dbLongshore"].has_key?(longShore))
        @dim_hash["array_oLongShore"].push(longShore) if longShore.length>0
      end
    end #If include dockCode
end
puts "#{INPUT_FILES_SUBDIR}/#{OPER_INPUT_FILE}: processed"

removeDuplicateValues()
sortValues()
writeOutputFiles()


text:
<?php

namespace spec\Knp\Rad\AutoRegistration\DefinitionBuilder;

use Knp\Rad\AutoRegistration\Finder\BundleFinder;
use Knp\Rad\AutoRegistration\Kernel\KernelWrapper;
use Knp\Rad\AutoRegistration\Reflection\ClassAnalyzer;
use PhpSpec\ObjectBehavior;
use Prophecy\Argument;

class TwigExtensionBuilderSpec extends ObjectBehavior
{
    function let(KernelWrapper $kernel, BundleFinder $finder, ClassAnalyzer $analyzer)
    {
        $this->beConstructedWith($kernel, $finder, $analyzer);
    }

    function it_is_initializable()
    {
        $this->shouldHaveType('Knp\Rad\AutoRegistration\DefinitionBuilder\TwigExtensionBuilder');
    }

    function it_create_definitions_from_constructable_twig_extensions($finder, $analyzer)
    {
        $finder->findClasses(Argument::cetera())->willReturn([
            'spec\Knp\Rad\AutoRegistration\DefinitionBuilder\TwigExtension1',
            'spec\Knp\Rad\AutoRegistration\DefinitionBuilder\TwigExtension2',
            'spec\Knp\Rad\AutoRegistration\DefinitionBuilder\TwigExtension3',
        ]);

        $analyzer->canBeConstructed('spec\Knp\Rad\AutoRegistration\DefinitionBuilder\TwigExtension1')->willReturn(true);
        $analyzer->canBeConstructed('spec\Knp\Rad\AutoRegistration\DefinitionBuilder\TwigExtension2')->willReturn(false);
        $analyzer->canBeConstructed('spec\Knp\Rad\AutoRegistration\DefinitionBuilder\TwigExtension3')->willReturn(true);

        $definitions = $this->buildDefinitions(['public' => false]);

        $definition = $definitions['spec\Knp\Rad\AutoRegistration\DefinitionBuilder\TwigExtension1'];
        $definition->shouldHaveType('Symfony\Component\DependencyInjection\Definition');
        $definition->getClass()->shouldReturn('spec\Knp\Rad\AutoRegistration\DefinitionBuilder\TwigExtension1');
        $definition->isPublic()->shouldReturn(false);
        $definition->hasTag('twig.extension')->shouldReturn(true);

        $definition = $definitions['spec\Knp\Rad\AutoRegistration\DefinitionBuilder\TwigExtension3'];
        $definition->shouldHaveType('Symfony\Component\DependencyInjection\Definition');
        $definition->getClass()->shouldReturn('spec\Knp\Rad\AutoRegistration\DefinitionBuilder\TwigExtension3');
        $definition->isPublic()->shouldReturn(false);
        $definition->hasTag('twig.extension')->shouldReturn(true);

        expect(array_key_exists('spec\Knp\Rad\AutoRegistration\DefinitionBuilder\TwigExtension2', $definition))->toBe(false);
    }
}

class TwigExtension1
{
}

class TwigExtension2
{
}

class TwigExtension3
{
}


text:
""" Perform post-generation tasks.

This is executed in the new project directory. Before execution it is rendered
with the template engine, so it has access to all template variables.

"""
from os import makedirs
from os import rename
from os.path import join

def make_source(repo):
    """ Crete the source directory under lib/.

    """
    namespace, module = repo.split("-")
    root = join("lib", namespace)
    makedirs(root)
    rename(repo + ".pm", join(root, module + ".pm"))
    return

def main():
    """ Execute all tasks.

    """
    make_source("{{ cookiecutter.repo_name }}")
    return 0

# Make the script executable from the command line.

if __name__ == "__main__":
    raise SystemExit(main())


text: from pygame.gp2x.constants import *


text:
using System.IO;

namespace Revenj.DatabasePersistence.Postgres.Npgsql
{
	internal sealed class NpgsqlConnectedState : NpgsqlState
	{
		public static readonly NpgsqlConnectedState Instance = new NpgsqlConnectedState();

		private NpgsqlConnectedState()
		{
		}

		public override void Startup(NpgsqlConnector context)
		{
			NpgsqlStartupPacket startupPacket = new NpgsqlStartupPacket(296, //Not used.
																		context.Database,
																		context.UserName, "", "", "");

			startupPacket.WriteToStream(new BufferedStream(context.Stream));
			context.RequireReadyForQuery = false;
			// This still makes part of the connection stablishment handling.
			// So we use the connectiontimeout here too.
			context.Mediator.CommandTimeout = context.ConnectionTimeout;
			context.Stream.Flush();
			ProcessBackendResponses(context);
		}

		public override void CancelRequest(NpgsqlConnector context)
		{
			NpgsqlCancelRequest CancelRequestMessage = new NpgsqlCancelRequest(context.BackEndKeyData);

			CancelRequestMessage.WriteToStream(context.Stream);
		}
	}
}


text:
//Apache2, 2017, WinterDev
//Apache2, 2009, griffm, FO.NET
using System;

namespace Fonet.Pdf.Gdi.Font
{
    ///
    ///     Class that represents the OS/2 ('OS/2') table
    ///
    /// <remarks>
    ///
For detailed information on the OS/2 table, visit the following link:
    ///     http://www.microsoft.com/typography/otspec/os2.htm

    ///
For more details on the Panose classification metrics, visit the following URL:
    ///     http://www.panose.com/hardware/pan2.asp

    /// </remarks>
    internal class OS2Table : FontTable
    {
        private const int OldStyleSerifs = 1;
        private const int TransitionalSerifs = 2;
        private const int ModernSerifs = 3;
        private const int ClarendonSerifs = 4;
        private const int SlabSerifs = 5;
        private const int FreeformSerifs = 7;
        private const int SansSerif = 8;
        private const int Scripts = 10;
        private const int Symbolic = 12;

        private ushort version;
        private short avgCharWidth;
        private ushort usWeightClass;
        private ushort usWidthClass;
        private ushort fsType;
        private short subscriptXSize;
        private short subscriptYSize;
        private short subscriptXOffset;
        private short subscriptYOffset;
        private short superscriptXSize;
        private short superscriptYSize;
        private short superscriptXOffset;
        private short superscriptYOffset;
        private short strikeoutSize;
        private short strikeoutPosition;
        private byte classID;
        private byte subclassID;
        private byte[] panose = new byte[10];
        private uint unicodeRange1;
        private uint unicodeRange2;
        private uint unicodeRange3;
        private uint unicodeRange4;
        private sbyte[] vendorID = new sbyte[4];
        private ushort fsSelection;
        private ushort usFirstCharIndex;
        private ushort usLastCharIndex;
        private short typoAscender;
        private short typoDescender;
        private short typoLineGap;
        private ushort usWinAscent;
        private ushort usWinDescent;
        private uint codePageRange1;
        private uint codePageRange2;
        private short sxHeight;
        private short sCapHeight;
        private ushort usDefaultChar;
        private ushort usBreakChar;
        private ushort usMaxContext;

        public OS2Table(DirectoryEntry entry) : base(TableNames.Os2, entry) { }

        ///
        ///     Gets a boolean value that indicates whether this font contains
        ///     italic characters.
        ///
        public bool IsItalic
        {
            get { return ((fsSelection & 0x01) == 0x01); }
        }

        ///
        ///     Gets a boolean value that indicates whether characters are
        ///     in the standard weight/style.
        ///
        public bool IsRegular
        {
            get { return ((fsSelection & 0x40) == 0x40); }
        }

        ///
        ///     Gets a boolean value that indicates whether characters possess
        ///     a weight greater than or equal to 700.
        ///
        public bool IsBold
        {
            get { return ((fsSelection & 0x20) == 0x20) || (usWeightClass >= 700); }
        }

        ///
        ///     Gets a boolean value that indicates whether this font contains
        ///     characters that all have the same width.
        ///
        public bool IsMonospaced
        {
            get { return (panose[3] == 9); }
        }

        ///
        ///     Gets a boolean value that indicates whether this font contains
        ///     special characters such as dingbats, icons, etc.
        ///
        public bool IsSymbolic
        {
            get { return (classID == Symbolic); }
        }

        ///
        ///     Gets a boolean value that indicates whether characters
        ///     do possess serifs
        ///
        public bool IsSerif
        {
            get
            {
                return (classID == OldStyleSerifs ||
                    classID == TransitionalSerifs ||
                    classID == ModernSerifs ||
                    classID == ClarendonSerifs ||
                    classID == SlabSerifs ||
                    classID == FreeformSerifs);
            }
        }

        ///
        ///     Gets a boolean value that indicates whether characters
        ///     are designed to simulate hand writing.
        ///
        public bool IsScript
        {
            get { return (classID == Scripts); }
        }

        ///
        ///     Gets a boolean value that indicates whether characters
        ///     do not possess serifs
        ///
        public bool IsSansSerif
        {
            get { return (classID == SansSerif); }
        }

        ///
        ///     Gets a boolean value that indicates whether this font may be
        ///     legally embedded.
        ///
        public bool IsEmbeddable
        {
            get { return (InstallableEmbedding || EditableEmbedding || PreviewAndPrintEmbedding); }
        }

        public bool InstallableEmbedding
        {
            get { return (fsType == 0); }
        }

        public bool RestricedLicenseEmbedding
        {
            get { return ((fsType & 0x0002) == 0x0002); }
        }

        public bool EditableEmbedding
        {
            get { return ((fsType & 0x0008) == 0x0008); }
        }

        public bool PreviewAndPrintEmbedding
        {
            get { return ((fsType & 0x0004) == 0x0004); }
        }

        ///
        ///     Gets a boolean value that indicates whether this font may be
        ///     subsetted.
        ///
        public bool IsSubsettable
        {
            get { return ((fsType & 0x0100) != 0x0100); }
        }

        public int CapHeight
        {
            get { return sCapHeight; }
        }

        public int XHeight
        {
            get { return sxHeight; }
        }

        public ushort FirstChar
        {
            get { return usFirstCharIndex; }
        }

        public ushort LastChar
        {
            get { return usLastCharIndex; }
        }

        ///
        ///     Reads the contents of the "os/2" table from the supplied stream
        ///     at the current position.
        ///
        /// <param name="reader"></param>
        protected internal override void Read(FontFileReader reader)
        {
            FontFileStream stream = reader.Stream;
            version = stream.ReadUShort();
            avgCharWidth = stream.ReadShort();
            usWeightClass = stream.ReadUShort();
            usWidthClass = stream.ReadUShort();
            // According to the OpenType spec, bit 0 must be zero.
            fsType = (ushort)(stream.ReadUShort() & ~1);
            subscriptXSize = stream.ReadShort();
            subscriptYSize = stream.ReadShort();
            subscriptXOffset = stream.ReadShort();
            subscriptYOffset = stream.ReadShort();
            superscriptXSize = stream.ReadShort();
            superscriptYSize = stream.ReadShort();
            superscriptXOffset = stream.ReadShort();
            superscriptYOffset = stream.ReadShort();
            strikeoutSize = stream.ReadShort();
            strikeoutPosition = stream.ReadShort();
            short familyClass = stream.ReadShort();
            classID = (byte)(familyClass >> 8);
            subclassID = (byte)(familyClass & 255);
            stream.Read(panose, 0, panose.Length);
            unicodeRange1 = stream.ReadULong();
            unicodeRange2 = stream.ReadULong();
            unicodeRange3 = stream.ReadULong();
            unicodeRange4 = stream.ReadULong();
            vendorID[0] = stream.ReadChar();
            vendorID[1] = stream.ReadChar();
            vendorID[2] = stream.ReadChar();
            vendorID[3] = stream.ReadChar();
            fsSelection = stream.ReadUShort();
            usFirstCharIndex = stream.ReadUShort();
            usLastCharIndex = stream.ReadUShort();
            typoAscender = stream.ReadShort();
            typoDescender = stream.ReadShort();
            typoLineGap = stream.ReadShort();
            usWinAscent = stream.ReadUShort();
            usWinDescent = stream.ReadUShort();
            codePageRange1 = stream.ReadULong();
            codePageRange2 = stream.ReadULong();
            sxHeight = stream.ReadShort();
            sCapHeight = stream.ReadShort();
            usDefaultChar = stream.ReadUShort();
            usBreakChar = stream.ReadUShort();
            usMaxContext = stream.ReadUShort();
        }

        protected internal override void Write(FontFileWriter writer)
        {
            throw new NotImplementedException("Write is not implemented.");
        }
    }
}


text:
"""
Utilities for working with nexus tokens.

Helps with generating tokens, validating tokens.
"""
import binascii
from collections import Mapping
from datetime import datetime
import hashlib
import json
import logging
import os
import re
import sys
import time
import urllib
import urlparse

import requests
import rsa

log = logging.getLogger()

class DictObj(Mapping):
    """
    Simple dictionary wrapper
    """
    def __init__(self, delegate):
        self.delegate = delegate

    def __len__(self):
        return len(self.delegate)

    def __iter__(self):
        return self.delegate.__iter__()

    def __getitem__(self, item):
        return self.delegate[item]

    def __getattr__(self, attrname):
        try:
            return self.delegate[attrname]
        except KeyError:
            raise AttributeError()

class InMemoryCache(object):
    """
    Simple cache implementation for signing certificates.
    """

    def __init__(self):
        self.cache_map = {}

    def save_public_key(self, key_id, key):
        self.cache_map[key_id] = key

    def has_public_key(self, key_id):
        return key_id in self.cache_map

    def get_public_key(self, key_id):
        return rsa.PublicKey.load_pkcs1(self.cache_map[key_id])

class FileSystemCache(object):
    """
    Cache signing certificates to the filesystem.
    """

    def __init__(self, cache_path):
        self.cache_path = cache_path
        if not os.path.exists(self.cache_path):
            os.makedirs(self.cache_path)

    def save_public_key(self, key_id, key):
        cached_cert_path = os.path.join(self.cache_path,
            "{0}.pem".format(key_id))
        with open(cached_cert_path, 'w') as cert:
            cert.write(str(key))

    def has_public_key(self, key_id):
        cached_cert_path = os.path.join(self.cache_path,
            "{0}.pem".format(key_id))
        return os.path.exists(cached_cert_path)

    def get_public_key(self, key_id):
        cached_cert_path = os.path.join(self.cache_path,
            "{0}.pem".format(key_id))
        with open(cached_cert_path, 'r') as cert:
            return rsa.PublicKey.load_pkcs1(cert.read())

class LoggingCacheWrapper(object):

    def __init__(self, cache):
        self.cache = cache

    def save_public_key(self, key_id, key):
        message = "{0}: Saving public key {1}:{2}"
        log.debug(message.format(self.cache.__class__.__name__,
                    key_id, key))
        self.cache.save_public_key(key_id, key)

    def has_public_key(self, key_id):
        return self.cache.has_public_key(key_id)

    def get_public_key(self, key_id):
        message = "{0}: Getting public key {1}"
        log.debug(message.format(self.cache.__class__.__name__, key_id))
        return self.cache.get_public_key(key_id)

def validate_token(token, cache=InMemoryCache(), verify=True):
    """
    Given a request or access token validate it.

    Keyword arguments:
    :param tokens: A signed authentication token which was provided by Nexus

    :raises ValueError: If the signature is invalid, the token is expired or
    the public key could not be gotten.
    """
    unencoded_token = urllib.unquote(token)
    token_map = {}
    for entry in unencoded_token.split('|'):
        key, value = entry.split('=')
        token_map[key] = value

    # If the public key is not already in the cache, cache it keyed by the signing subject.
    if not cache.has_public_key(token_map['SigningSubject']):
        response = requests.get(token_map['SigningSubject'], verify=verify)
        if response.status_code != 200:
            message = "Could not get SigningSubject public key"
            log.debug(message)
            raise ValueError(message)
        key_struct = response.content
        public_key = json.loads(key_struct)['pubkey']
        cache.save_public_key(token_map['SigningSubject'], public_key)

    public_key = cache.get_public_key(token_map['SigningSubject'])
    sig = token_map.pop('sig')
    match = re.match('^(.+)\|sig=.*', unencoded_token)
    signed_data = match.group(1)
    try:
        sig = binascii.a2b_hex(sig)
        rsa.verify(signed_data, sig, public_key)
    except rsa.VerificationError:
        exc_value, exc_traceback = sys.exc_info()[1:]
        log.debug('RSA Verification error')
        log.debug(exc_value)
        log.debug(exc_traceback)
        raise ValueError('Invalid Signature')
    now = time.mktime(datetime.utcnow().timetuple())
    if token_map['expiry'] < now:
        raise ValueError('TokenExpired')
    urlparts = urlparse.urlparse(token_map['SigningSubject'])
    return (
        token_map['un'],
        token_map['client_id'],
        urlparts.hostname
    )

def request_access_token(client_id, client_secret,
        auth_code, auth_uri="https://graph.api.globusonline.org/token",
        verify=False):
    """
    Given an authorization code, request an access token.

    :param client_id: The client's api id
    :param client_secret: The client's api secret
    :param auth_code: The authorization code given to the resource owner by nexus
    :param auth_uri: The url of the authentication endpoint

    :returns: A dictionary of the access code response.  This will include the
    fields: access_token, refresh_token and expires_in
    :raises TokenRequestError: If the request for an access token fails
    """
    payload = {
            'grant_type': 'authorization_code',
            'code': auth_code,
            }
    response = requests.post(auth_uri,
            auth=(client_id, client_secret),
            data=payload, verify=verify)
    if response.status_code == requests.codes.created:
        return DictObj(response.json)
    raise TokenRequestError(response.json)

def get_token_refresh(client_id, client_secret,
        refresh_token, auth_uri="https://graph.api.globuscs.info/authorize",
        verify=True):
    """
    Update the access token using the refresh token from a previous request.

    :param client_id: The client's api id
    :param client_secret: The client's api secret
    :param refresh_token: The refresh token issued in a previous authentication.
    :param auth_uri: The url of the authentication endpoint.
    """
    payload = {
            'grant_type': 'refresh_token',
            'refresh_token': refresh_token,
            }
    response = requests.post(auth_uri,
            auth=(client_id, client_secret),
            data=payload, verify=verify)
    if response.status_code == requests.codes.ok:
        return DictObj(response.json)
    raise TokenRequestError(response.json)

class TokenRequestError(Exception):
    """
    Just an Error class that takes a json response as a property.
    """

    def __init__(self, error):
        super(TokenRequestError, self).__init__()
        self.error = error


text:
package com.dickthedeployer.dick.web.controller;

import com.dickthedeployer.dick.web.exception.NameTakenException;
import com.dickthedeployer.dick.web.exception.NotFoundException;
import com.dickthedeployer.dick.web.exception.RepositoryParsingException;
import com.dickthedeployer.dick.web.exception.RepositoryUnavailableException;
import com.dickthedeployer.dick.web.model.BuildModel;
import com.dickthedeployer.dick.web.model.ProjectModel;
import com.dickthedeployer.dick.web.service.BuildService;
import com.dickthedeployer.dick.web.service.ProjectService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;

import static org.springframework.web.bind.annotation.RequestMethod.*;

/**
 *
 * @author mariusz
 */
@RestController
@RequestMapping("/api/projects")
public class ProjectController {

    @Autowired
    ProjectService projectService;

    @Autowired
    BuildService buildService;

    @RequestMapping(method = POST)
    public void createProject(@RequestBody @Valid ProjectModel projectModel) throws NameTakenException, RepositoryUnavailableException, RepositoryParsingException {
        projectService.createProject(projectModel);
    }

    @RequestMapping(method = PUT, value = "{projectId}")
    public void updateProject(@PathVariable("projectId") Long projectId,
                              @RequestBody ProjectModel model) throws RepositoryUnavailableException,
            RepositoryParsingException, NotFoundException {
        projectService.updateProject(projectId, model);
    }

    @RequestMapping(method = DELETE, value = "{projectId}")
    public void deleteProject(@PathVariable("projectId") Long projectId) throws NotFoundException {
        projectService.deleteProject(projectId);
    }

    @RequestMapping(method = PUT, value = "{projectId}/name")
    public void renameProject(@PathVariable("projectId") Long projectId,
                              @RequestBody ProjectModel model) throws NameTakenException, NotFoundException {
        projectService.renameProject(projectId, model);
    }

    @RequestMapping(method = PUT, value = "{projectId}/namespace")
    public void moveProject(@PathVariable("projectId") Long projectId,
                            @RequestBody ProjectModel model) throws NameTakenException, NotFoundException {
        projectService.moveProject(projectId, model);
    }

    @RequestMapping(method = GET)
    public List<ProjectModel> getProjects(@RequestParam("page") int page, @RequestParam("size") int size,
                                          @RequestParam(required = false, name = "name") String name) {
        if (StringUtils.isEmpty(name)) {
            return projectService.getProjects(page, size);
        } else {
            return projectService.getProjectsLikeName(name, page, size);
        }
    }

    @RequestMapping(method = GET, value = "/all")
    public List<ProjectModel> getProjects(@RequestParam("ids") List<Long> ids) {
        return projectService.getProjects(ids);
    }

    @RequestMapping(method = GET, value = "/{namespace}/{name}")
    public ProjectModel getProject(@PathVariable("namespace") String namespace, @PathVariable("name") String name) throws NotFoundException {
        return projectService.getProject(namespace, name);
    }

    @RequestMapping(method = GET, value = "/{namespace}/{name}/builds")
    public List<BuildModel> getBuilds(@PathVariable("namespace") String namespace, @PathVariable("name") String name,
                                      @RequestParam("page") int page, @RequestParam("size") int size) {
        return buildService.getBuilds(namespace, name, page, size);
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/activity_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="io.github.xr86.android_musicalstructure.MainActivity">

    <TextView
        android:id="@+id/track_title"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:text="Music title"
        android:textSize="20sp" />

    <ImageView
        android:id="@+id/track_logo"
        android:layout_width="match_parent"
        android:layout_height="200dp"
        android:layout_below="@id/track_title"
        android:background="#DDD"
        android:src="@drawable/ic_audiotrack_black_24dp" />

    <LinearLayout
        android:id="@+id/track_seekbar_layout"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:layout_below="@id/track_logo">
        <TextView
            android:id="@+id/track_time_current"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="0:00"/>

        <android.support.v7.widget.AppCompatSeekBar
            android:id="@+id/track_seekbar"
            android:layout_toRightOf="@id/track_time_current"
            android:layout_width="wrap_content"
            android:layout_weight="1"
            android:layout_height="wrap_content" />

        <TextView
            android:id="@+id/track_time_final"
            android:layout_toRightOf="@id/track_seekbar"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="0:00"/>
    </LinearLayout>

    <LinearLayout
        android:id="@+id/track_controls_layout"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@id/track_seekbar_layout"
        android:layout_centerInParent="true">

        <Button
            android:id="@+id/prev"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:onClick="buttonClickPlaceholder"
            android:text="prev" />

        <Button
            android:id="@+id/play"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_toRightOf="@id/prev"
            android:text="Play" />

        <Button
            android:id="@+id/next"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_toRightOf="@id/play"
            android:onClick="buttonClickPlaceholder"
            android:text="next" />
    </LinearLayout>

</RelativeLayout>


text:
'use strict'

import serviceStore from '../store/services/serviceStore.js'

let actions = {

    initNewFilter(){
        serviceStore.initNewFilter()
    },

    cancelCreation(){
        serviceStore.cancelCreation()
    },

    addFilter(f){
        serviceStore.addFilter(f)
    },

    updateFilter(filter){
        serviceStore.updateFilter(filter)
    },

    removeFilter(filter){
        serviceStore.removeFilter(filter)
    },

    toggleEnable(){
        serviceStore.toggleEnable()
    }

}

export default actions


text: """Certbot compatibility test Apache configurators"""


text:
<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;

use App\Http\Requests;

class SettingController extends Controller
{
    public function __construct()
	{
		$this->middleware('auth');
		$this->middleware('admin');
	}

    /**
     *  Show the general view
     *
     *  @return Response
     */
    public function getGeneral()
    {
        $getSetting = app('Settings')->get([
            'site_title',
            'email',
            'search_engine_visibility',
        ]);
        return view('admin.settings.general', ['setting' => $getSetting]);
    }

    /**
     *  Update the general settings
     *
     *  @return Response
     */
    public function postGeneral(Request $request)
    {
        app('Settings')->add('site_title', $request->input('site_title'));
        app('Settings')->add('email', $request->input('email'));
        app('Settings')->add('search_engine_visibility', $request->input('search_engine_visibility', 'false'));

        session()->flash('success', 'Successfully updated settings!');
        return redirect()->back();
    }
}


text:
#pragma once
#include <aws/ds/DirectoryService_EXPORTS.h>
#include <aws/core/utils/memory/stl/AWSString.h>
#include <utility>

namespace Aws
{
template<typename RESULT_TYPE>
class AmazonWebServiceResult;

namespace Utils
{
namespace Json
{
  class JsonValue;
} // namespace Json
} // namespace Utils
namespace DirectoryService
{
namespace Model
{
  class AWS_DIRECTORYSERVICE_API ShareDirectoryResult
  {
  public:
    ShareDirectoryResult();
    ShareDirectoryResult(const Aws::AmazonWebServiceResult<Aws::Utils::Json::JsonValue>& result);
    ShareDirectoryResult& operator=(const Aws::AmazonWebServiceResult<Aws::Utils::Json::JsonValue>& result);

    /**
     *
Identifier of the directory that is stored in the directory consumer account
     * that is shared from the specified directory (DirectoryId).

     */
    inline const Aws::String& GetSharedDirectoryId() const{ return m_sharedDirectoryId; }

    /**
     *
Identifier of the directory that is stored in the directory consumer account
     * that is shared from the specified directory (DirectoryId).

     */
    inline void SetSharedDirectoryId(const Aws::String& value) { m_sharedDirectoryId = value; }

    /**
     *
Identifier of the directory that is stored in the directory consumer account
     * that is shared from the specified directory (DirectoryId).

     */
    inline void SetSharedDirectoryId(Aws::String&& value) { m_sharedDirectoryId = std::move(value); }

    /**
     *
Identifier of the directory that is stored in the directory consumer account
     * that is shared from the specified directory (DirectoryId).

     */
    inline void SetSharedDirectoryId(const char* value) { m_sharedDirectoryId.assign(value); }

    /**
     *
Identifier of the directory that is stored in the directory consumer account
     * that is shared from the specified directory (DirectoryId).

     */
    inline ShareDirectoryResult& WithSharedDirectoryId(const Aws::String& value) { SetSharedDirectoryId(value); return *this;}

    /**
     *
Identifier of the directory that is stored in the directory consumer account
     * that is shared from the specified directory (DirectoryId).

     */
    inline ShareDirectoryResult& WithSharedDirectoryId(Aws::String&& value) { SetSharedDirectoryId(std::move(value)); return *this;}

    /**
     *
Identifier of the directory that is stored in the directory consumer account
     * that is shared from the specified directory (DirectoryId).

     */
    inline ShareDirectoryResult& WithSharedDirectoryId(const char* value) { SetSharedDirectoryId(value); return *this;}

  private:

    Aws::String m_sharedDirectoryId;
  };

} // namespace Model
} // namespace DirectoryService
} // namespace Aws


text:
layout: default
category: makeup
name: Naked Palette
type: eyes
image: eyes/naked_palette.jpg
---

**What it is:**
An award-winning eye shadow palette.

**What it does:**
full of neutral colours perfect for everyday use. Urban Decays eyeshadows are luxiorious, creamy, and long-lasting.

Add to Cart


text:
package cn.edu.sjtu.songyuke.mental.ir;

import cn.edu.sjtu.songyuke.mental.ir.data.DataAddress;
import cn.edu.sjtu.songyuke.mental.ir.data.DataStringLiteral;
import cn.edu.sjtu.songyuke.mental.ir.data.DataValue;
import cn.edu.sjtu.songyuke.mental.translator.MIPSMachine;

import java.util.LinkedList;

/**
 * Created by Songyu on 16/4/25.
 */
public class Load extends Instruction {
    public DataAddress src;
    public DataValue dest;
    public int loadSize;
    public Load() {
        this.src = null;
        this.dest = null;
        this.loadSize = 4;
    }
    public Load(DataAddress src) {
        this.loadSize = 4;
        this.src = src;
        if (!(this.src instanceof DataStringLiteral)) {
            this.src.address.refCount++;
        }
        this.dest = new DataValue();
    }
    public Load(DataAddress src, int loadSize) {
        this.src = src;
        if (!(this.src instanceof DataStringLiteral)) {
            this.src.address.refCount++;
        }
        this.dest = new DataValue();
        this.loadSize = loadSize;
    }

    @Override
    public String toMips(MIPSMachine mipsMachine) {
        LinkedList<String> mipsInstructions = new LinkedList<>();

        if (this.label != null) {
            mipsInstructions.add(this.label.toString() + ":");
        }

        if (this.src instanceof DataStringLiteral) {
            if (((DataStringLiteral) this.src).registerName == -1) {
                mipsInstructions.add(mipsMachine.storeFirstLoadRegister());
                mipsInstructions.add(mipsMachine.replaceFirstLoadRegisterWithLoad(this.src));
            }
            if (this.dest.registerName == -1) {
                mipsInstructions.add(mipsMachine.storeFirstLoadRegister());
                mipsMachine.rewriteFirstLoadRegister(this.dest);
            } else {
                mipsMachine.updateRegister(this.dest.registerName);
            }
            mipsInstructions.add(
                    String.format("\tmove %s, %s", this.dest.toRegister(), this.src.toRegister())
            );
            ((DataStringLiteral) this.src).registerName = -1;
        } else {
            this.src.address.refCount--;
            if (this.src.address.registerName == -1) {
                mipsInstructions.add(mipsMachine.storeFirstLoadRegister());
                mipsInstructions.add(mipsMachine.replaceFirstLoadRegisterWithLoad(this.src.address));
            } else {
                mipsMachine.refreshRegister(this.src.address.registerName);
            }
            if (this.dest.registerName == -1) {
                mipsInstructions.add(mipsMachine.storeFirstLoadRegister());
                mipsMachine.rewriteFirstLoadRegister(this.dest);
            } else {
                mipsMachine.updateRegister(this.dest.registerName);
            }
            if (this.loadSize == 4) {
                mipsInstructions.add(
                        String.format("\tlw %s, 0(%s)", this.dest.toRegister(), this.src.address.toRegister())
                );
            } else {
                mipsInstructions.add(
                        String.format("\tlb %s, 0(%s)", this.dest.toRegister(), this.src.address.toRegister())
                );
            }
        }

        String str = "";
        for (String statement : mipsInstructions) {
            if (statement.length() > 0) {
                str += statement + "\n";
            }
        }
        return str.substring(0, str.length() - 1);
    }

    // for cisc code generation.
    @Override
    public String toMips() {
        LinkedList<String> mipsInstructions = new LinkedList<>();

        if (this.label != null) {
            mipsInstructions.add(this.label.toString() + ":");
        }
        if (this.src instanceof DataStringLiteral) {
            mipsInstructions.add(
                    String.format("\tla $t0, %s", this.src.toAddress())
            );
        } else {
            mipsInstructions.add(
                    String.format("\tlw $t0, %s", this.src.address.toAddress())
            );
            if (this.loadSize == 4) {
                mipsInstructions.add(
                        String.format("\tlw $t0, 0($t0)")
                );
            } else {
                mipsInstructions.add(
                        String.format("\tlb $t0, 0($t0)")
                );
            }
        }
        mipsInstructions.add(
                String.format("\tsw $t0, %s", this.dest.toAddress())
        );

        String str = "";
        for (String statement : mipsInstructions) {
            if (statement.length() > 0) {
                str += statement + "\n";
            }
        }
        return str.substring(0, str.length() - 1);
    }
}


text:
package org.apache.skywalking.apm.collector.core.define;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Objects;
import java.util.Properties;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @author peng-yongsheng
 */
public class DefinitionLoader<D> implements Iterable<D> {

    private final Logger logger = LoggerFactory.getLogger(DefinitionLoader.class);

    private final Class<D> definition;
    private final DefinitionFile definitionFile;

    protected DefinitionLoader(Class<D> svc, DefinitionFile definitionFile) {
        this.definition = Objects.requireNonNull(svc, "definition interface cannot be null");
        this.definitionFile = definitionFile;
    }

    public static <D> DefinitionLoader<D> load(Class<D> definition, DefinitionFile definitionFile) {
        return new DefinitionLoader(definition, definitionFile);
    }

    @Override public final Iterator<D> iterator() {
        logger.info("load definition file: {}", definitionFile.get());
        List<String> definitionList = new LinkedList<>();
        try {
            Enumeration<URL> urlEnumeration = this.getClass().getClassLoader().getResources(definitionFile.get());
            while (urlEnumeration.hasMoreElements()) {
                URL definitionFileURL = urlEnumeration.nextElement();
                logger.info("definition file url: {}", definitionFileURL.getPath());
                BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(definitionFileURL.openStream()));
                Properties properties = new Properties();
                properties.load(bufferedReader);

                Enumeration defineItem = properties.propertyNames();
                while (defineItem.hasMoreElements()) {
                    String fullNameClass = (String)defineItem.nextElement();
                    definitionList.add(fullNameClass);
                }
            }
        } catch (IOException e) {
            logger.error(e.getMessage(), e);
        }

        Iterator<String> moduleDefineIterator = definitionList.iterator();

        return new Iterator<D>() {
            @Override public boolean hasNext() {
                return moduleDefineIterator.hasNext();
            }

            @Override public D next() {
                String definitionClass = moduleDefineIterator.next();
                logger.info("definitionClass: {}", definitionClass);
                try {
                    Class c = Class.forName(definitionClass);
                    return (D)c.newInstance();
                } catch (Exception e) {
                    logger.error(e.getMessage(), e);
                }
                return null;
            }
        };
    }
}


text:
INSERT INTO quizz.user (name) VALUES ('test')

//Sélectionnez un utilisateur
SELECT id, name, score FROM user WHERE id=

//Sélectionnez une question aléatoirement
SELECT id, question, reponse FROM questions ORDER BY rand() LIMIT 1

//Afficher la réponse
SELECT reponse FROM questions WHERE id=

//Mise à jour du score
UPDATE quizz.user SET score = '' WHERE user.id =

//Afficher les joueurs classé par le score
SELECT id, name, score FROM user ORDER BY score DESC

//Ajout d'une nouvelle question
INSERT INTO quizz.questions (question, reponse) VALUES ('','')