text:
using System;
using System.Collections.Immutable;
using System.Linq;
using System.Text;
using JetBrains.Annotations;
using JsonApiDotNetCore.Resources.Annotations;

namespace JsonApiDotNetCore.Queries.Expressions
{
    /// <summary>
    /// Represents an element in <see cref="IncludeExpression" />.
    /// </summary>
    [PublicAPI]
    public class IncludeElementExpression : QueryExpression
    {
        public RelationshipAttribute Relationship { get; }
        public IImmutableList<IncludeElementExpression> Children { get; }

        public IncludeElementExpression(RelationshipAttribute relationship)
            : this(relationship, ImmutableArray<IncludeElementExpression>.Empty)
        {
        }

        public IncludeElementExpression(RelationshipAttribute relationship, IImmutableList<IncludeElementExpression> children)
        {
            ArgumentGuard.NotNull(relationship, nameof(relationship));
            ArgumentGuard.NotNull(children, nameof(children));

            Relationship = relationship;
            Children = children;
        }

        public override TResult Accept<TArgument, TResult>(QueryExpressionVisitor<TArgument, TResult> visitor, TArgument argument)
        {
            return visitor.VisitIncludeElement(this, argument);
        }

        public override string ToString()
        {
            var builder = new StringBuilder();
            builder.Append(Relationship);

            if (Children.Any())
            {
                builder.Append('{');
                builder.Append(string.Join(",", Children.Select(child => child.ToString())));
                builder.Append('}');
            }

            return builder.ToString();
        }

        public override bool Equals(object obj)
        {
            if (ReferenceEquals(this, obj))
            {
                return true;
            }

            if (obj is null || GetType() != obj.GetType())
            {
                return false;
            }

            var other = (IncludeElementExpression)obj;

            return Relationship.Equals(other.Relationship) == Children.SequenceEqual(other.Children);
        }

        public override int GetHashCode()
        {
            var hashCode = new HashCode();
            hashCode.Add(Relationship);

            foreach (IncludeElementExpression child in Children)
            {
                hashCode.Add(child);
            }

            return hashCode.ToHashCode();
        }
    }
}


text:
require 'spec_helper'
require 'support/editor'
require 'support/playground_actions'

RSpec.feature "Navigating between pages", type: :feature, js: true do
  include PlaygroundActions

  RSpec::Matchers.define :be_at_url do |path, query = {}|
    match do |page|
      uri = URI::parse(page.current_url)
      expect(uri.path).to eql(path)

      query = query.map { |k, v| [k.to_s, Array(v).map(&:to_s)] }.to_h
      query_hash = CGI::parse(uri.query || '')
      expect(query_hash).to include(query)
    end

    failure_message do |page|
      "expected that #{page.current_url} would be #{path} with the query parameters #{query}"
    end
  end

  # This is kind of a test of the router library too, so if that ever
  # gets extracted, a chunk of these tests can be removed.

  scenario "Mode and channel buttons update the URL" do
    visit '/'
    expect(page).to have_content('RUN')

    editor.set("dummy")
    expect(page).to be_at_url('/')

    in_mode_menu { click_on('Release') }
    expect(page).to be_at_url('/', version: 'stable', mode: 'release')

    go_back
    expect(page).to be_at_url('/')

    in_mode_menu { click_on('Release') }
    in_channel_menu { click_on('Beta') }
    expect(page).to be_at_url('/', version: 'beta', mode: 'release')

    go_back
    expect(page).to be_at_url('/')
  end

  scenario "Navigating to help changes the URL", :flaky do
    visit '/'
    expect(page).to have_content('RUN')

    click_on 'View help'
    expect(page).to be_at_url('/help')
    expect(page).to have_content('The Rust Playground')

    go_back
    expect(page).to be_at_url('/')
    expect(page).to have_content('RUN')

    go_forward
    expect(page).to be_at_url('/help')
    expect(page).to have_content('The Rust Playground')

    click_on "Return to the playground"
    expect(page).to be_at_url('/')
    expect(page).to have_content('RUN')
  end

  scenario "Navigating from help changes the URL" do
    visit '/help'
    expect(page).to have_content('The Rust Playground')

    click_on "Return to the playground"
    expect(page).to be_at_url('/')
    expect(page).to have_content('RUN')
  end

  def editor
    Editor.new(page)
  end

  # It probably would be worth figuring out why
  # `page.go_{back,forward}` doesn't work... :-(
  # Maybe https://github.com/teampoltergeist/poltergeist/issues/624
  def go_back
    page.execute_script('window.history.go(-1);')
  end

  def go_forward
    page.execute_script('window.history.go(1);')
  end
end

redpajama_set_name: RedPajamaGithub


text:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <complex.h>
#include <math.h>
#include <assert.h>

#include "autotest/autotest.h"
#include "liquid.h"

// internal callback
//  _X          :   subcarrier symbols
//  _p          :   subcarrier allocation
//  _M          :   number of subcarriers
//  _userdata   :   user-defined data structure
int ofdmframesync_autotest_callback(float complex * _X,
                                    unsigned char * _p,
                                    unsigned int    _M,
                                    void * _userdata)
{
    printf("******** callback invoked!\n");

    // type cast _userdata as complex float array
    float complex * X = (float complex *)_userdata;

    // copy values and return
    memmove(X, _X, _M*sizeof(float complex));

    // return
    return 0;
}

// Helper function to keep code base small
//  _num_subcarriers    :   number of subcarriers
//  _cp_len             :   cyclic prefix lenght
//  _taper_len          :   taper length
void ofdmframesync_acquire_test(unsigned int _num_subcarriers,
                                unsigned int _cp_len,
                                unsigned int _taper_len)
{
    // options
    unsigned int M         = _num_subcarriers;  // number of subcarriers
    unsigned int cp_len    = _cp_len;           // cyclic prefix lenght
    unsigned int taper_len = _taper_len;        // taper length
    float tol              = 1e-2f;             // error tolerance

    //
    float dphi = 1.0f / (float)M;       // carrier frequency offset

    // subcarrier allocation (initialize to default)
    unsigned char p[M];
    ofdmframe_init_default_sctype(M, p);

    // derived values
    unsigned int num_samples = (3 + 1)*(M + cp_len);

    // create synthesizer/analyzer objects
    ofdmframegen fg = ofdmframegen_create(M, cp_len, taper_len, p);
    //ofdmframegen_print(fg);

    float complex X[M];         // original data sequence
    float complex X_test[M];    // recovered data sequence
    ofdmframesync fs = ofdmframesync_create(M,cp_len,taper_len,p,ofdmframesync_autotest_callback,(void*)X_test);

    unsigned int i;
    float complex y[num_samples];   // frame samples

    // assemble full frame
    unsigned int n=0;

    // write first S0 symbol
    ofdmframegen_write_S0a(fg, &y[n]);
    n += M + cp_len;

    // write second S0 symbol
    ofdmframegen_write_S0b(fg, &y[n]);
    n += M + cp_len;

    // write S1 symbol
    ofdmframegen_write_S1( fg, &y[n]);
    n += M + cp_len;

    // generate data symbol (random)
    for (i=0; i<M; i++) {
        X[i]      = cexpf(_Complex_I*2*M_PI*randf());
        X_test[i] = 0.0f;
    }

    // write data symbol
    ofdmframegen_writesymbol(fg, X, &y[n]);
    n += M + cp_len;

    // validate frame length
    assert(n == num_samples);

    // add carrier offset
    for (i=0; i<num_samples; i++)
        y[i] *= cexpf(_Complex_I*dphi*i);

    // run receiver
    ofdmframesync_execute(fs,y,num_samples);

    // check output
    for (i=0; i<M; i++) {
        if (p[i] == OFDMFRAME_SCTYPE_DATA) {
            float e = crealf( (X[i] - X_test[i])*conjf(X[i] - X_test[i]) );
            CONTEND_DELTA( cabsf(e), 0.0f, tol );
        }
    }

    // destroy objects
    ofdmframegen_destroy(fg);
    ofdmframesync_destroy(fs);
}

//
void autotest_ofdmframesync_acquire_n64()   { ofdmframesync_acquire_test(64,  8,  0); }
void autotest_ofdmframesync_acquire_n128()  { ofdmframesync_acquire_test(128, 16, 0); }
void autotest_ofdmframesync_acquire_n256()  { ofdmframesync_acquire_test(256, 32, 0); }
void autotest_ofdmframesync_acquire_n512()  { ofdmframesync_acquire_test(512, 64, 0); }


text:
using FluentAssertions;
using Microsoft.DotNet.TestFramework;
using Microsoft.DotNet.Tools.Test.Utilities;
using System.IO;
using Xunit;

namespace Microsoft.DotNet.Migration.Tests
{
    public class GivenThatIWantToMigrateAppsUsingGlobalJson : TestBase
    {
        [Fact]
        public void ItMigratesWhenBeingPassedAFullPathToGlobalJson()
        {
            var solutionDirectory = TestAssets
                .GetProjectJson("AppWithPackageNamedAfterFolder")
                .CreateInstance()
                .WithSourceFiles()
                .Root;

            var globalJsonPath = solutionDirectory.GetFile("global.json");

            new TestCommand("dotnet")
                    .WithForwardingToConsole()
                    .Execute($"migrate {globalJsonPath.FullName}")
                    .Should()
                    .Pass();
        }

        [Fact]
        public void WhenUsingGlobalJsonItOnlyMigratesProjectsInTheGlobalJsonNode()
        {
            var solutionDirectory = TestAssets
                .GetProjectJson("AppWithPackageNamedAfterFolder")
                .CreateInstance()
                .WithSourceFiles()
                .Root;

            var globalJsonPath = solutionDirectory.GetFile("global.json");

            new TestCommand("dotnet")
                    .WithForwardingToConsole()
                    .Execute($"migrate {globalJsonPath.FullName}")
                    .Should()
                    .Pass();

            solutionDirectory
                .Should().HaveFiles(new []
                    {
                        Path.Combine("src", "App", "App.csproj"),
                        Path.Combine("test", "App.Tests", "App.Tests.csproj"),
                        Path.Combine("TestAssets", "TestAsset", "project.json")
                    });

            solutionDirectory
                .Should().NotHaveFile(Path.Combine("TestAssets", "TestAsset", "TestAsset.csproj"));
        }

        [Fact]
        public void ItMigratesWhenBeingPassedJustGlobalJson()
        {
            var solutionDirectory = TestAssets
                .GetProjectJson("AppWithPackageNamedAfterFolder")
                .CreateInstance()
                .WithSourceFiles()
                .Root;

            var globalJsonPath = solutionDirectory.GetFile("global.json");

            new TestCommand("dotnet")
                    .WithWorkingDirectory(solutionDirectory)
                    .WithForwardingToConsole()
                    .Execute($"migrate global.json")
                    .Should()
                    .Pass();
        }
    }
}


text:
<resources>
    <string name="app_name">UnlockScreenByPath</string>

    <string name="hello_world">Hello world!</string>
    <string name="action_settings">Settings</string>
</resources>


text:
import urllib

from tempest.common import http
from tempest.common.rest_client import RestClient
from tempest import config
from tempest import exceptions

CONF = config.CONF

class ObjectClient(RestClient):
    def __init__(self, auth_provider):
        super(ObjectClient, self).__init__(auth_provider)

        self.service = CONF.object_storage.catalog_type

    def create_object(self, container, object_name, data, params=None):
        """Create storage object."""

        headers = dict(self.headers)
        if not data:
            headers['content-length'] = '0'
        url = "%s/%s" % (str(container), str(object_name))
        if params:
            url += '?%s' % urllib.urlencode(params)

        resp, body = self.put(url, data, headers)
        return resp, body

    def update_object(self, container, object_name, data):
        """Upload data to replace current storage object."""
        return self.create_object(container, object_name, data)

    def delete_object(self, container, object_name, params=None):
        """Delete storage object."""
        url = "%s/%s" % (str(container), str(object_name))
        if params:
            url += '?%s' % urllib.urlencode(params)
        resp, body = self.delete(url)
        return resp, body

    def update_object_metadata(self, container, object_name, metadata,
                               metadata_prefix='X-Object-Meta-'):
        """Add, remove, or change X-Object-Meta metadata for storage object."""

        headers = {}
        for key in metadata:
            headers["%s%s" % (str(metadata_prefix), str(key))] = metadata[key]

        url = "%s/%s" % (str(container), str(object_name))
        resp, body = self.post(url, None, headers=headers)
        return resp, body

    def list_object_metadata(self, container, object_name):
        """List all storage object X-Object-Meta- metadata."""

        url = "%s/%s" % (str(container), str(object_name))
        resp, body = self.head(url)
        return resp, body

    def get_object(self, container, object_name):
        """Retrieve object's data."""

        url = "{0}/{1}".format(container, object_name)
        resp, body = self.get(url)
        return resp, body

    def copy_object_in_same_container(self, container, src_object_name,
                                      dest_object_name, metadata=None):
        """Copy storage object's data to the new object using PUT."""

        url = "{0}/{1}".format(container, dest_object_name)
        headers = {}
        headers['X-Copy-From'] = "%s/%s" % (str(container),
                                            str(src_object_name))
        headers['content-length'] = '0'
        if metadata:
            for key in metadata:
                headers[str(key)] = metadata[key]

        resp, body = self.put(url, None, headers=headers)
        return resp, body

    def copy_object_across_containers(self, src_container, src_object_name,
                                      dst_container, dst_object_name,
                                      metadata=None):
        """Copy storage object's data to the new object using PUT."""

        url = "{0}/{1}".format(dst_container, dst_object_name)
        headers = {}
        headers['X-Copy-From'] = "%s/%s" % (str(src_container),
                                            str(src_object_name))
        headers['content-length'] = '0'
        if metadata:
            for key in metadata:
                headers[str(key)] = metadata[key]

        resp, body = self.put(url, None, headers=headers)
        return resp, body

    def copy_object_2d_way(self, container, src_object_name, dest_object_name,
                           metadata=None):
        """Copy storage object's data to the new object using COPY."""

        url = "{0}/{1}".format(container, src_object_name)
        headers = {}
        headers['Destination'] = "%s/%s" % (str(container),
                                            str(dest_object_name))
        if metadata:
            for key in metadata:
                headers[str(key)] = metadata[key]

        resp, body = self.copy(url, headers=headers)
        return resp, body

    def create_object_segments(self, container, object_name, segment, data):
        """Creates object segments."""
        url = "{0}/{1}/{2}".format(container, object_name, segment)
        resp, body = self.put(url, data, self.headers)
        return resp, body

class ObjectClientCustomizedHeader(RestClient):

    # TODO(andreaf) This class is now redundant, to be removed in next patch

    def __init__(self, auth_provider):
        super(ObjectClientCustomizedHeader, self).__init__(
            auth_provider)
        # Overwrites json-specific header encoding in RestClient
        self.service = CONF.object_storage.catalog_type
        self.format = 'json'

    def request(self, method, url, headers=None, body=None):
        """A simple HTTP request interface."""
        dscv = CONF.identity.disable_ssl_certificate_validation
        self.http_obj = http.ClosingHttp(
            disable_ssl_certificate_validation=dscv)
        if headers is None:
            headers = {}

        # Authorize the request
        req_url, req_headers, req_body = self.auth_provider.auth_request(
            method=method, url=url, headers=headers, body=body,
            filters=self.filters
        )
        # Use original method
        self._log_request(method, req_url, headers, body)
        resp, resp_body = self.http_obj.request(req_url, method,
                                                headers=req_headers,
                                                body=req_body)
        self._log_response(resp, resp_body)
        if resp.status == 401 or resp.status == 403:
            raise exceptions.Unauthorized()

        return resp, resp_body

    def get_object(self, container, object_name, metadata=None):
        """Retrieve object's data."""
        headers = {}
        if metadata:
            for key in metadata:
                headers[str(key)] = metadata[key]

        url = "{0}/{1}".format(container, object_name)
        resp, body = self.get(url, headers=headers)
        return resp, body

    def create_object(self, container, object_name, data, metadata=None):
        """Create storage object."""

        headers = {}
        if metadata:
            for key in metadata:
                headers[str(key)] = metadata[key]

        if not data:
            headers['content-length'] = '0'
        url = "%s/%s" % (str(container), str(object_name))
        resp, body = self.put(url, data, headers=headers)
        return resp, body

    def delete_object(self, container, object_name, metadata=None):
        """Delete storage object."""

        headers = {}
        if metadata:
            for key in metadata:
                headers[str(key)] = metadata[key]

        url = "%s/%s" % (str(container), str(object_name))
        resp, body = self.delete(url, headers=headers)
        return resp, body


text:
package com.intellij.xdebugger.impl.ui.tree.nodes;

import com.intellij.xdebugger.frame.XCompositeNode;
import com.intellij.xdebugger.frame.XValue;
import com.intellij.xdebugger.frame.XValueChildrenList;
import com.intellij.xdebugger.frame.XValueContainer;
import com.intellij.xdebugger.impl.evaluate.XDebuggerEvaluationDialog;
import com.intellij.xdebugger.impl.ui.tree.XDebuggerTree;
import org.jetbrains.annotations.NotNull;

/**
 * @author nik
 */
public class EvaluatingExpressionRootNode extends XValueContainerNode<EvaluatingExpressionRootNode.EvaluatingResultContainer> {
  public EvaluatingExpressionRootNode(XDebuggerEvaluationDialog evaluationDialog, final XDebuggerTree tree) {
    super(tree, null, new EvaluatingResultContainer(evaluationDialog));
    setLeaf(false);
  }

  protected MessageTreeNode createLoadingMessageNode() {
    return MessageTreeNode.createEvaluatingMessage(myTree, this);
  }

  public static class EvaluatingResultContainer extends XValueContainer {
    private final XDebuggerEvaluationDialog myDialog;

    public EvaluatingResultContainer(final XDebuggerEvaluationDialog dialog) {
      myDialog = dialog;
    }

    public void computeChildren(@NotNull final XCompositeNode node) {
      final String resultName = myDialog.getExpression();
      myDialog.startEvaluation(new XEvaluationCallbackBase() {
        public void evaluated(@NotNull final XValue result) {
          node.addChildren(XValueChildrenList.singleton(resultName, result), true);
        }

        public void errorOccurred(@NotNull final String errorMessage) {
          node.setErrorMessage(errorMessage);
        }
      });
    }
  }
}


text:
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var reader_1 = require("../reader");
describe("PGN parsing", function () {
    var reader;
    var pgnResult;
    function _parse(_pgn) {
        reader = new reader_1.PgnReader();
        return reader.parsePgn(_pgn);
    }
    beforeEach(function () {
    });
    describe("moves", function () {
        // Shows the minimal set of values included in every move
        it("should parse a short pgn string with one move only", function () {
            pgnResult = _parse("1. e4");
            // console.log(JSON.stringify(pgnResult[0]))
            expect(pgnResult.length).toEqual(1);
            expect(pgnResult[0].moveNumber).toEqual(1);
            expect(pgnResult[0].notation).toEqual("e4");
            expect(pgnResult[0].row).toEqual("4");
            expect(pgnResult[0].col).toEqual("e");
            expect(pgnResult[0].turn).toEqual("w");
            expect(pgnResult[0].variations.length).toEqual(0);
        });
        it("should parse a main line with 6 moves", function () {
            pgnResult = _parse("1. e4 e5 2. Nf3 Nc6 3. Bb5 a6");
            expect(pgnResult.length).toEqual(6);
        });
        it("should work with all kind of numbers (even nonsense ones, but syntactically correct)", function () {
            pgnResult = _parse("1. e4 2. e6 2. Nf4 1... Nc7");
            expect(pgnResult.length).toEqual(4);
        });
    });
    describe("NAGs", function () {
        // NAG section
        it("should accept some NAGs divided by spaces", function () {
            pgnResult = _parse("1. e4 ? !");
            // console.log(pgnResult[0])
            expect(pgnResult[0].nag.length).toEqual(2);
        });
        it("should accept NAGs not divided by spaces", function () {
            pgnResult = _parse("1. e4 ∞=??");
            expect(pgnResult[0].nag.length).toEqual(3);
        });
        it("should accept NAGs in $-notation", function () {
            pgnResult = _parse("1. e4 $1 $2 $3 $4 $5 $6");
            expect(pgnResult[0].nag.length).toEqual(6);
        });
        it("should accept NAGs in $-notation with and without spaces", function () {
            pgnResult = _parse("1. e4 $1$2 $3$4$5 $6");
            expect(pgnResult[0].nag.length).toEqual(6);
        });
        it("should map NAGs in normal notation to $-notation", function () {
            pgnResult = _parse("1. e4 ! ? !! ?? !? ?! = ∞");
            expect(pgnResult[0].nag.length).toEqual(8);
            expect(pgnResult[0].nag[0]).toBe('$1');
            expect(pgnResult[0].nag[1]).toBe('$2');
            expect(pgnResult[0].nag[2]).toBe('$3');
            expect(pgnResult[0].nag[3]).toBe('$4');
            expect(pgnResult[0].nag[4]).toBe('$5');
            expect(pgnResult[0].nag[5]).toBe('$6');
            expect(pgnResult[0].nag[6]).toBe('$10');
            expect(pgnResult[0].nag[7]).toBe('$13');
        });
        it("should accept NAGs not divided by spaces mixed with ones divided by spaces", function () {
            pgnResult = _parse("1. e4 ∞=?? ?");
            // console.log(pgnResult[0].nag)
            expect(pgnResult[0].nag.length).toEqual(4);
        });
    });
    describe("comments", function () {
        it("should show all possible comments of one move", function () {
            pgnResult = _parse("{ com1 } 1. { com2 } N1xf3+ ? { com3 }");
            expect(pgnResult.length).toEqual(1);
            expect(pgnResult[0].commentBefore).toEqual("com2");
            expect(pgnResult[0].commentAfter).toEqual("com3");
            expect(pgnResult[0].commentMove).toEqual("com1");
        });
    });
    describe("check and checkmate", function () {
        // Chess and mate marks
        it("should accept chess marks", function () {
            pgnResult = _parse("e4+ e5#");
            // console.log(pgnResult[0])
            expect(pgnResult.length).toEqual(2);
            expect(pgnResult[0].check).toEqual("+");
            expect(pgnResult[1].check).toEqual("#");
        });
    });
    describe("variations", function () {
        // Variations
        it("should read variations", function () {
            pgnResult = _parse("1. e4 e5 (1... d5 2. exd5) (1... c5 2. c3)");
            expect(pgnResult.length).toEqual(2); // main line moves
            expect(pgnResult[1].variations.length).toEqual(2); // 2nd move 2 variations
            expect(pgnResult[1].variations[0][0].notation).toEqual("d5");
            expect(pgnResult[1].variations[0][1].notation).toEqual("exd5");
            expect(pgnResult[1].variations[1][0].notation).toEqual("c5");
            expect(pgnResult[1].variations[1][1].notation).toEqual("c3");
        });
        it("should read hierarchical variations", function () {
            pgnResult = _parse("1. e4 e5 ( 1... d5 2. exd5 ( 2. e5 ))");
            expect(pgnResult.length).toEqual(2);
            expect(pgnResult[1].variations.length).toEqual(1);
            expect(pgnResult[1].variations[0][0].notation).toEqual("d5");
            expect(pgnResult[1].variations[0][1].notation).toEqual("exd5");
            expect(pgnResult[1].variations[0][1].variations[0][0].notation).toEqual("e5");
        });
        it("should read hierarchical variations without move number", function () {
            pgnResult = _parse("1. e4 e5 ( 1... d5 2. exd5 ( e5 ))");
            expect(pgnResult.length).toEqual(2);
            expect(pgnResult[1].variations.length).toEqual(1);
            expect(pgnResult[1].variations[0][0].notation).toEqual("d5");
            expect(pgnResult[1].variations[0][1].notation).toEqual("exd5");
            expect(pgnResult[1].variations[0][1].variations[0][0].notation).toEqual("e5");
        });
    });
    describe("results", function () {
        // Reading results
        it("should read games with result", function () {
            pgnResult = _parse("1. e4 1-0");
            expect(pgnResult.length).toEqual(2);
            //console.log(pgnResult)
            expect(pgnResult[1]).toEqual('1-0');
        });
    });
    describe("move numbers", function () {
        // Reading move numbers
        it("should understand no move number in pgn", function () {
            pgnResult = _parse("e4 e5");
            expect(pgnResult.length).toEqual(2);
        });
        it("should understand numbers with white space", function () {
            pgnResult = _parse("1 . e4 e5");
            expect(pgnResult.length).toEqual(2);
        });
        it("should understand more numbers anywhere", function () {
            pgnResult = _parse("1... e4 1.. e5 2...... d4 d5 3.. c4 3 c5");
            expect(pgnResult.length).toEqual(6);
        });
    });
    describe("disabmbiguation", function () {
        // Disabmbiguation
        it("should understand disambiguation", function () {
            pgnResult = _parse("e4 d5 d4 exd4");
            expect(pgnResult.length).toEqual(4);
        });
        it("should allow pawn moves with no disambiguation", function () {
            pgnResult = _parse("e4 d5 d4 xd4");
            expect(pgnResult.length).toEqual(4);
        });
        it("should allow knight moves with unnecessary disambiguation", function () {
            pgnResult = _parse("e4 d5 Ngf3 Nbc6");
            expect(pgnResult.length).toEqual(4);
        });
    });
    describe("strange formats", function () {
        it("should understand long notation", function () {
            pgnResult = _parse("e2-e4 d7-d6 d2-d4 Ng8-f6 Nb1-c3");
            expect(pgnResult.length).toEqual(5);
            expect(pgnResult[0].notation).toEqual("e2-e4");
            expect(pgnResult[1].notation).toEqual("d7-d6");
        });
        it("should understand long notation without dash", function () {
            pgnResult = _parse("e2e4 d7d6 d2d4 g8f6 b1c3");
            expect(pgnResult.length).toEqual(5);
            expect(pgnResult[0].notation).toEqual("e2-e4");
            expect(pgnResult[1].notation).toEqual("d7-d6");
            expect(pgnResult[3].notation).toEqual("g8-f6");
            expect(pgnResult[4].notation).toEqual("b1-c3");
        });
    });
    describe("special moves", function () {
        it("should understand castling", function () {
            pgnResult = _parse("1. O-O O-O-O");
            expect(pgnResult.length).toEqual(2);
            expect(pgnResult[0].notation).toEqual("O-O");
            expect(pgnResult[1].notation).toEqual("O-O-O");
        });
        it("should understand promotions", function () {
            pgnResult = _parse("1. h8=Q b1=R 2. g8=B a1=N");
            expect(pgnResult.length).toEqual(4);
            expect(pgnResult[0].notation).toEqual("h8=Q");
            expect(pgnResult[0].promotion).toEqual("Q");
            expect(pgnResult[1].notation).toEqual("b1=R");
            expect(pgnResult[1].promotion).toEqual("R");
            expect(pgnResult[2].notation).toEqual("g8=B");
            expect(pgnResult[2].promotion).toEqual("B");
            expect(pgnResult[3].notation).toEqual("a1=N");
            expect(pgnResult[3].promotion).toEqual("N");
        });
    });
});
//# sourceMappingURL=parse-spec.js.map


text:
install:
	npm install

lint:
	$(shell npm bin)/eslint src

build:
	$(shell npm bin)/rollup src/azazel.js --output.format cjs --output.file dist/azazel.js
	$(shell npm bin)/rollup src/azazel.js --output.format umd --output.file dist/azazel.min.js -n Azazel
	$(shell npm bin)/uglifyjs dist/azazel.min.js -o dist/azazel.min.js -c -m

install-build: install build

test.events:
	$(shell npm bin)/mocha tests

karma:
	@$(shell npm bin)/karma start karma.conf.js

test: build test.events karma

# release: test
# 	@echo "\nrunning https://gist.githubusercontent.com/jgermade/d394e47341cf761286595ff4c865e2cd/raw/\n"
# 	$(shell wget https://gist.githubusercontent.com/jgermade/d394e47341cf761286595ff4c865e2cd/raw/ -O - | sh -)

npm.increaseVersion:
	npm version patch --no-git-tag-version

npm.pushVersion: npm.increaseVersion
	git commit -a -n -m "v$(shell node -e "process.stdout.write(require('./package').version + '\n')")" 2> /dev/null; true
	git push origin $(master_branch)

git.tag: export PKG_VERSION=$(shell node -e "process.stdout.write('v'+require('./package.json').version);")
git.tag:
	git pull --tags
	git add dist -f --all
	- git commit -n -m "${PKG_VERSION}" 2> /dev/null; true
	git tag -a $(PKG_VERSION) -m "$(PKG_VERSION)"
	git push --tags
	# git push origin $(git_branch)

npm.publish: build test npm.pushVersion git.tag
	cp package.json dist
	cp README.md dist
	cp LICENSE dist
	- cd dist && npm publish --access public
	- node -e "var fs = require('fs'); var pkg = require('./dist/package.json'); pkg.name = 'azazel'; fs.writeFile('dist/package.json', JSON.stringify(pkg, null, '  '), 'utf8', function (err) { if( err ) console.log('Error: ' + err); });"
	- cd dist && npm publish
	cp package.json dist

github.release: export PKG_NAME=$(shell node -e "console.log(require('./package.json').name);")
github.release: export PKG_VERSION=$(shell node -e "process.stdout.write('v'+require('./package.json').version);")
github.release: export RELEASE_URL=$(shell curl -s -X POST -H "Content-Type: application/json" -H "Authorization: Bearer ${GITHUB_TOKEN}" \
	-d '{"tag_name": "${PKG_VERSION}", "target_commitish": "$(git_branch)", "name": "${PKG_VERSION}", "body": "", "draft": false, "prerelease": false}' \
	-w '%{url_effective}' "https://api.github.com/repos/kiltjs/azazel/releases" )
github.release:
	@echo ${RELEASE_URL}
	git reset --soft HEAD~1
	git reset HEAD
	# git reset --hard origin/$(git_branch)
	@git checkout $(git_branch)
	# @true

release: npm.publish github.release

# DEFAULT TASKS

.DEFAULT_GOAL := install-build


text:
<?php
namespace Grav\Plugin;

use Grav\Common\Plugin;
use Grav\Plugin\Taxonomylist;

class TaxonomylistPlugin extends Plugin
{

    /**
     * @return array
     */
    public static function getSubscribedEvents()
    {
        return [
            'onPluginsInitialized' => ['onPluginsInitialized', 0]
        ];
    }

    /**
     * Initialize configuration
     */
    public function onPluginsInitialized()
    {
        if ($this->isAdmin()) {
            $this->active = false;
            return;
        }

        $this->enable([
            'onTwigTemplatePaths' => ['onTwigTemplatePaths', 0],
            'onTwigSiteVariables' => ['onTwigSiteVariables', 0]
        ]);
    }

    /**
     * Add current directory to twig lookup paths.
     */
    public function onTwigTemplatePaths()
    {
        $this->grav['twig']->twig_paths[] = __DIR__ . '/templates';
    }

    /**
     * Set needed variables to display the taxonomy list.
     */
    public function onTwigSiteVariables()
    {
        require_once __DIR__ . '/classes/taxonomylist.php';

        $twig = $this->grav['twig'];
        $twig->twig_vars['taxonomylist'] = new Taxonomylist();
        $twig->twig_vars['list_url'] = $this->config->get(
            'site.blog.route',
            $this->config->get('plugins.taxonomylist.route')
        );
    }
}


text:
require 'chef/knife/swap_base'

class Chef
  # knife
  class Knife
    include Chef::Knife::SwapBase

    # default command without parameters
    class Swap < Knife
      # banner help
      banner 'knife swap CONFIG'

      # begin
      def run
        if @name_args.empty?
          print_current_configs
          print_available_configs
        else
          use_config(@name_args[0])
        end
      end
    end
  end
end


text:
/**
 * SequelizeMySQLController
 *
 * @description :: Server-side logic for managing Database Queries
 */

var h = require('../services/helper')
var Promise = require('bluebird')

var Sequelize = require('sequelize')
var sequelize = new Sequelize(
  'hello_world', 'benchmarkdbuser', 'benchmarkdbpass',
  {
    host: '127.0.0.1',
    dialect: 'mysql',
    pool: {
      max: 5000,
      min: 0,
      idle: 5000
    },
    // hide the SQL queries being run
    logging: false
  })

var Worlds = sequelize.define('World', {
  id: Sequelize.INTEGER,
  randomNumber: Sequelize.INTEGER
},
{
  // prevents sequelize from assuming the table is called 'Worlds'
  freezeTableName: true,
  timestamps: false
})

var Fortunes = sequelize.define('Fortune', {
  id: Sequelize.INTEGER,
  message: Sequelize.STRING
},
{
  // prevents sequelize from assuming the table is called 'Fortunes'
  freezeTableName: true,
  timestamps: false
})

var randomWorldPromise = function() {
  var promise = Worlds
    .findOne({
      where: { id: h.randomTfbNumber() }
    })
    .then(function (world) {
      return world
    })
    .catch(function (err) {
      process.exit(1)
    })
  return promise
}

var updateWorld = function(world) {
  var promise = Worlds
    .update(
      { randomNumber: world.randomNumber },
      { where: { id: world.id } }
    )
    .then(function (results) {
      return world
    })
    .catch(function (err) {
      process.exit(1)
    })
  return promise
}

module.exports = {

  /**
   * Test 2: Single Database Query
   */
  Single: function(req, res) {
    randomWorldPromise()
      .then(function (world) {
        res.json(world)
      })
  },

  /**
   * Test 3: Multiple Database Query
   */
  Multiple: function(req, res) {
    var queries = h.getQueries(req)
    var toRun = []

    for (var i = 0; i < queries; i++) {
      toRun.push(randomWorldPromise());
    }

    Promise
      .all(toRun)
      .then(function (worlds) {
        res.json(worlds)
      })
  },

  /**
   * Test 4: Fortunes
   */
  Fortunes: function(req, res) {
    Fortunes
      .findAll()
      .then(function (fortunes) {
        fortunes.push(h.ADDITIONAL_FORTUNE)
        fortunes.sort(function (a, b) {
          return a.message.localeCompare(b.message)
        })
        res.render('fortunes', { 'fortunes': fortunes })
      })
      .catch(function (err) {
        process.exit(1)
      })
  },

  /**
   * Test 5: Database Updates
   */
  Updates: function(req, res) {
    var queries = h.getQueries(req);
    var worldPromises = [];

    for (var i = 0; i < queries; i++) {
      worldPromises.push(randomWorldPromise())
    }

    Promise
      .all(worldPromises)
      .map(function (world) {
        return updateWorld(world)
      })
      .then(function (updated) {
        res.json(updated)
      })
      .catch(function (err) {
        process.exit(1)
      })
  }

};


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

    var app = angular.module('app');

    app.directive('ccImgPerson', ['config', function (config) {
        //Usage:
        //
        var basePath = config.imageSettings.imageBasePath;
        var unknownImage = config.imageSettings.unknownPersonImageSource;
        var directive = {
            link: link,
            restrict: 'A'
        };
        return directive;

        function link(scope, element, attrs) {
            attrs.$observe('ccImgPerson', function(value) {
                value = basePath + (value || unknownImage);
                attrs.$set('src', value);
            });
        }
    }]);

    app.directive('ccSidebar', function () {
        // Opens and clsoes the sidebar menu.
        // Usage:
        //

        // Creates:
        //

        var directive = {
            link: link,
            restrict: 'A'
        };
        return directive;

        function link(scope, element, attrs) {
            var $sidebarInner = element.find('.sidebar-inner');
            var $dropdownElement = element.find('.sidebar-dropdown a');
            element.addClass('sidebar');
            $dropdownElement.click(dropdown);

            function dropdown(e) {
                var dropClass = 'dropy';
                e.preventDefault();
                if (!$dropdownElement.hasClass(dropClass)) {
                    hideAllSidebars();
                    $sidebarInner.slideDown(350);
                    $dropdownElement.addClass(dropClass);
                } else if ($dropdownElement.hasClass(dropClass)) {
                    $dropdownElement.removeClass(dropClass);
                    $sidebarInner.slideUp(350);
                }

                function hideAllSidebars() {
                    $sidebarInner.slideUp(350);
                    $('.sidebar-dropdown a').removeClass(dropClass);
                }
            }
        }
    });

    app.directive('ccWidgetClose', function () {
        // Usage:
        //
        // Creates:
        //
        //
        //
        var directive = {
            link: link,
            template: '',
            restrict: 'A'
        };
        return directive;

        function link(scope, element, attrs) {
            attrs.$set('href', '#');
            attrs.$set('wclose');
            element.click(close);

            function close(e) {
                e.preventDefault();
                element.parent().parent().parent().hide(100);
            }
        }
    });

    app.directive('ccWidgetMinimize', function () {
        // Usage:
        //
        // Creates:
        //
        var directive = {
            link: link,
            template: '',
            restrict: 'A'
        };
        return directive;

        function link(scope, element, attrs) {
            //$('body').on('click', '.widget .wminimize', minimize);
            attrs.$set('href', '#');
            attrs.$set('wminimize');
            element.click(minimize);

            function minimize(e) {
                e.preventDefault();
                var $wcontent = element.parent().parent().next('.widget-content');
                var iElement = element.children('i');
                if ($wcontent.is(':visible')) {
                    iElement.removeClass('icon-chevron-up');
                    iElement.addClass('icon-chevron-down');
                } else {
                    iElement.removeClass('icon-chevron-down');
                    iElement.addClass('icon-chevron-up');
                }
                $wcontent.toggle(500);
            }
        }
    });

    app.directive('ccScrollToTop', ['$window',
        // Usage:
        //
        // Creates:
        //
        //
        //
        function ($window) {
            var directive = {
                link: link,
                template: '',
                restrict: 'A'
            };
            return directive;

            function link(scope, element, attrs) {
                var $win = $($window);
                element.addClass('totop');
                $win.scroll(toggleIcon);

                element.find('a').click(function (e) {
                    e.preventDefault();
                    // Learning Point: $anchorScroll works, but no animation
                    //$anchorScroll();
                    $('body').animate({ scrollTop: 0 }, 500);
                });

                function toggleIcon() {
                    $win.scrollTop() > 300 ? element.slideDown(): element.slideUp();
                }
            }
        }
    ]);

    app.directive('ccSpinner', ['$window', function ($window) {
        // Description:
        //  Creates a new Spinner and sets its options
        // Usage:
        //

        var directive = {
            link: link,
            restrict: 'A'
        };
        return directive;

        function link(scope, element, attrs) {
            scope.spinner = null;
            scope.$watch(attrs.ccSpinner, function (options) {
                if (scope.spinner) {
                    scope.spinner.stop();
                }
                scope.spinner = new $window.Spinner(options);
                scope.spinner.spin(element[0]);
            }, true);
        }
    }]);

    app.directive('ccWidgetHeader', function() {
        //Usage:
        //

        var directive = {
            link: link,
            scope: {
                'title': '@',
                'subtitle': '@',
                'rightText': '@',
                'allowCollapse': '@'
            },
            templateUrl: '/app/layout/widgetheader.html',
            restrict: 'A',
        };
        return directive;

        function link(scope, element, attrs) {
            attrs.$set('class', 'widget-head');
        }
    });

    app.directive('ccWip', ['$route', function ($route) {
        //Usage:
        //

        var wipRouteName = 'workinprogress';
        var directive = {
            controller: ['$scope', wipController],
            link: link,
            template: getTemplate(),
            scope: {
                'wip': '=',
                'changedEvent': '@',
                'routes': '='
            },
            restrict: 'A'
        };

        return directive;

        function link(scope, element, attrs) {
            scope.$watch(wipIsCurrent, function (value) {
                value ? element.addClass('current') : element.removeClass('current');
            });

            function wipIsCurrent() {
                if (!$route.current || !$route.current.title) {
                    return false;
                }
                return $route.current.title.substr(0, wipRouteName.length) === wipRouteName;
            }
        }

        function wipController($scope) {
            $scope.wipExists = function () { return !!$scope.wip.length; };
            $scope.wipRoute = undefined;
            $scope.getWipClass = function () {
                return $scope.wipExists() ? 'icon-asterisk-alert' : '';
            };

            activate();

            function activate() {
                var eventName = $scope.changedEvent;
                $scope.$on(eventName, function (event, data) {
                    $scope.wip = data.wip;
                });
                $scope.wipRoute = $scope.routes.filter(function (r) {
                    return r.config.title === wipRouteName;
                })[0];
            }
        }

        function getTemplate() {
            return ''
                + ''
                + 'Work in Progress ({{wip.length}})';
        }
    }]);
})();


text:
title: RS013
highlights: "Unable create user on account. The `account_id` {{accountId}} already has reached the maximum number of users per account. (limit 1000 users per `account_id`)"
slug: squatchjs/issue/RS013
sectionType: jsReference
template: pages/rscode.html
date: '2019-11-18'
---

### Tips To Fix This

 - Make sure that you have not erroneously grouped all of your users under a single `account_id`.

### Why is This Happening?

There is a limit (1000) on the number of users that can exist in an account. You're encountering this error because of one your accounts (identified by `account_id`) has hit this limit and can't create any more users in this account.


text:
module Auth0
  module Api
    module V2
      # Methods to use the blacklist endpoints
      module Blacklists
        attr_reader :blacklists_path

        # Retrieves the jti and aud of all tokens in the blacklist.
        # @see https://auth0.com/docs/api/v2#!/Blacklists/get_tokens
        # @param aud [string] The JWT's aud claim. The client_id of the client for which it was issued
        #
        # @return [json] Returns the blacklisted tokens
        #
        def blacklisted_tokens(aud = nil)
          request_params = {
            aud: aud
          }
          get(blacklists_path, request_params)
        end

        # Adds the token identified by the jti to a blacklist for the tenant.
        # @see https://auth0.com/docs/api/v2#!/blacklists/post_tokens
        # @param jti [string] The jti of the JWT to blacklist
        # @param aud [string] The JWT's aud claim. The client_id of the client for which it was issued
        # @return [json] Returns the blacklisted token
        #
        def add_token_to_blacklist(jti, aud = nil)
          raise Auth0::MissingParameter, 'Must specify a valid JTI' if jti.to_s.empty?
          request_params = {
            jti: jti,
            aud: aud
          }
          post(blacklists_path, request_params)
        end

        private

        # Blacklists API path
        def blacklists_path
          @blacklists_path ||= '/api/v2/blacklists/tokens'
        end
      end
    end
  end
end


text:
export function getImage({ filename }) {
  return fetch(`/api/images/${filename}`, {
    method: 'get'
  }).then(res => res.json());
}

export function getImages({ pageNumber = 0 }) {
  return fetch(`/api/pages/${pageNumber}`, {
    method: 'get'
  }).then(res => res.json());
}


text:
import { NgModule }      from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import {routing} from "./routes";
import { AppComponent }  from './app.component';
import {HttpModule} from "@angular/http";
import {RequestService} from "../common/request.service";
import {ReactiveFormsModule, FormsModule} from "@angular/forms";
import {HomeComponent} from "../home/home.component";
import {PublicationInputComponent} from "../home/publication-input/publication-input.component";
import {QueryBuilderService} from "../home/query.builder.service";
import {CompetitorsInputsComponent} from "../home/competitors-inputs/competitors-inputs.component";
import {SportInputComponent} from "../home/sport-input/sport-input.component";
import {MatchesComponent} from "../matches/matches.component";
import {MatchesService} from "../matches/matches.service";
import {MatchDetailsComponent} from "../match-details/match-details.component";

@NgModule({
  imports:      [
    BrowserModule,
    HttpModule,
    routing,
    ReactiveFormsModule,
    FormsModule
  ],
  providers: [
    RequestService,
    QueryBuilderService,
    MatchesService
  ],
  declarations: [
    AppComponent,
    HomeComponent,
    PublicationInputComponent,
    CompetitorsInputsComponent,
    SportInputComponent,
    MatchesComponent,
    MatchDetailsComponent
  ],
  bootstrap:    [ AppComponent ]
})
export class AppModule { }


text:
/*(Auto-generated)
 *  Created by TpmPrototypes; Version 3.0 July 18, 2017
 *  Date: Mar 28, 2019  Time: 08:25:19PM
 */

#ifndef    _TICKET_FP_H_
#define    _TICKET_FP_H_

//*** TicketIsSafe()
// This function indicates if producing a ticket is safe.
// It checks if the leading bytes of an input buffer is TPM_GENERATED_VALUE
// or its substring of canonical form.  If so, it is not safe to produce ticket
// for an input buffer claiming to be TPM generated buffer
//  Return Type: BOOL
//      TRUE(1)         safe to produce ticket
//      FALSE(0)        not safe to produce ticket
BOOL
TicketIsSafe(
    TPM2B           *buffer
);

//*** TicketComputeVerified()
// This function creates a TPMT_TK_VERIFIED ticket.
void
TicketComputeVerified(
    TPMI_RH_HIERARCHY    hierarchy,     // IN: hierarchy constant for ticket
    TPM2B_DIGEST        *digest,        // IN: digest
    TPM2B_NAME          *keyName,       // IN: name of key that signed the values
    TPMT_TK_VERIFIED    *ticket         // OUT: verified ticket
);

//*** TicketComputeAuth()
// This function creates a TPMT_TK_AUTH ticket.
void
TicketComputeAuth(
    TPM_ST               type,          // IN: the type of ticket.
    TPMI_RH_HIERARCHY    hierarchy,     // IN: hierarchy constant for ticket
    UINT64               timeout,       // IN: timeout
    BOOL                 expiresOnReset,// IN: flag to indicate if ticket expires on
                                        //      TPM Reset
    TPM2B_DIGEST        *cpHashA,       // IN: input cpHashA
    TPM2B_NONCE         *policyRef,     // IN: input policyRef
    TPM2B_NAME          *entityName,    // IN: name of entity
    TPMT_TK_AUTH        *ticket         // OUT: Created ticket
);

//*** TicketComputeHashCheck()
// This function creates a TPMT_TK_HASHCHECK ticket.
void
TicketComputeHashCheck(
    TPMI_RH_HIERARCHY    hierarchy,     // IN: hierarchy constant for ticket
    TPM_ALG_ID           hashAlg,       // IN: the hash algorithm for 'digest'
    TPM2B_DIGEST        *digest,        // IN: input digest
    TPMT_TK_HASHCHECK   *ticket         // OUT: Created ticket
);

//*** TicketComputeCreation()
// This function creates a TPMT_TK_CREATION ticket.
void
TicketComputeCreation(
    TPMI_RH_HIERARCHY    hierarchy,     // IN: hierarchy for ticket
    TPM2B_NAME          *name,          // IN: object name
    TPM2B_DIGEST        *creation,      // IN: creation hash
    TPMT_TK_CREATION    *ticket         // OUT: created ticket
);

#endif  // _TICKET_FP_H_


text:
ExFilePicker
============

ExFilePicker is an open source android library that allows developers to easily implement choosing files and directories in application.

## Screenshotes:

[![Screenshot](https://raw.github.com/bartwell/ExFilePicker/master/stuff/preview-screenshot1.png)](https://raw.github.com/bartwell/ExFilePicker/master/stuff/screenshot1.png) [![Screenshot](https://raw.github.com/bartwell/ExFilePicker/master/stuff/preview-screenshot2.png)](https://raw.github.com/bartwell/ExFilePicker/master/stuff/screenshot2.png) [![Screenshot](https://raw.github.com/bartwell/ExFilePicker/master/stuff/preview-screenshot3.png)](https://raw.github.com/bartwell/ExFilePicker/master/stuff/screenshot3.png)

## Features

It can:
* Choose one file
* Choose one directory
* Choose few files and/or directories
* Filter by file extension
* Creating directories

## Usage

__1.__ Add ExFilePicker library as a dependency to your project

__2.__ Add next code into your project where is needed:

```java
import ru.bartwell.exfilepicker.ExFilePicker;
import ru.bartwell.exfilepicker.ExFilePickerParcelObject;

// ...

	private static final int EX_FILE_PICKER_RESULT = 0;

	// ...

		Intent intent = new Intent(getApplicationContext(), ru.bartwell.exfilepicker.ExFilePickerActivity.class);
		startActivityForResult(intent, EX_FILE_PICKER_RESULT);

	// ...

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (requestCode == EX_FILE_PICKER_RESULT) {
			if (data != null) {
				ExFilePickerParcelObject object = (ExFilePickerParcelObject) data.getParcelableExtra(ExFilePickerParcelObject.class.getCanonicalName());
				if (object.count > 0) {
					// Here is object contains selected files names and path
				}
			}
		}
	}
```
__3.__ Add activity in your Manifest:

```xml
	<activity
		android:name="ru.bartwell.exfilepicker.ExFilePickerActivity"
		android:configChanges="orientation|screenSize"
		android:theme="@style/ExFilePickerThemeDark" />
```
__4.__ If you need a "New folder" button, add permission in your Manifest:

```xml
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
```

## Configuration

ExFilePicker can be configurated via intent extras.

* SET_ONLY_ONE_ITEM - boolean; if true, user can select only one item. False by default.

* SET_FILTER_BY_EXTENSION - removed. Use SET_FILTER_EXCLUDE or SET_FILTER_LISTED instead.

* SET_FILTER_LISTED - String[]; only files with this extensions will showed.

* SET_FILTER_EXCLUDE - String[]; files with this extensions will excluded.

* SET_CHOICE_TYPE - int; one of CHOICE_TYPE_ALL, CHOICE_TYPE_FILES or CHOICE_TYPE_DIRECTORIES. Set what user can select - only files, only directories or both. Both by default.

* SET_START_DIRECTORY - String. This path will be open when ExFilePicker activity will called.

* DISABLE_NEW_FOLDER_BUTTON - boolean; if true, button "New folder" will not showing.

Look example in ExFilePickerSample.

## Customization

ExFilePicker library provide two themes for ExFilePicker's activity: dark and light (ExFilePickerThemeDark and ExFilePickerThemeLight respectively). If you need to customize ExFilePicker's activity view, you can extend your own theme from any ExFilePicker's theme and override needed options.

## Sample Application

[![Get it on Google Play](http://www.android.com/images/brand/get_it_on_play_logo_small.png)](http://play.google.com/store/apps/details?id=ru.bartwell.exfilepickersample)

## License

The MIT License (MIT)

Copyright (c) 2013 Artem Bazhanov

Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.


text:
layout: dirindex
title: Projects
author: Matteo Mattei
sitemap:
  lastmod: 2014-07-27
  priority: 0.7
  changefreq: monthly
---

This is a (partial) list of projects I developed during the years in alphabetical order.


text:
package net.minecraft.server.management;

import net.minecraft.network.packet.Packet;

import java.net.SocketAddress;

public class ServerConfigurationManager {

    /** get kick reason, or null if player should not be kicked */
    public String func_72399_a(SocketAddress address, String username) {
        return null;
    }

    /** send packet to all nearby players */
    public void func_72393_a(double X, double Y, double Z, double range, int dimensionId, Packet packet) {

    }

    /** send packet to all players in dimension */
    public void func_72396_a(Packet packet, int dimId) {

    }

    /** send packet to all players */
    public void func_72384_a(Packet packet) {

    }
}


text:
require 'spec_helper'

describe Acfs::Collection do
  let(:model) { MyUser }

  describe 'Pagination' do
    let(:params) { Hash.new }
    let!(:collection) { model.all params }

    subject { Acfs.run; collection }

    context 'without explicit page parameter' do
      before do
        stub_request(:get, 'http://users.example.org/users')
          .to_return response([{id: 1, name: 'Anon', age: 12, born_at: 'Berlin'}],
            headers: {'X-Total-Pages' => '2'})
      end

      its(:total_pages) { should eq 2 }
      its(:current_page) { should eq 1 }
    end

    context 'with page parameter' do
      let(:params) { {page: 2} }
      before do
        stub_request(:get, 'http://users.example.org/users?page=2')
          .to_return response([{id: 1, name: 'Anon', age: 12, born_at: 'Berlin'}],
            headers: {'X-Total-Pages' => '2'})
      end

      its(:total_pages) { should eq 2 }
      its(:current_page) { should eq 2 }
    end

    context 'with non-numerical page parameter' do
      let(:params) { {page: 'e546f5'} }
      before do
        stub_request(:get, 'http://users.example.org/users?page=e546f5')
          .to_return response([{id: 1, name: 'Anon', age: 12, born_at: 'Berlin'}],
            headers: {'X-Total-Pages' => '2'})
      end

      its(:total_pages) { should eq 2 }
      its(:current_page) { should eq 'e546f5' }
    end

    describe '#next_page' do
      before do
        stub_request(:get, 'http://users.example.org/users')
          .to_return response([{id: 1, name: 'Anon', age: 12, born_at: 'Berlin'}],
            headers: {
              'X-Total-Pages' => '2',
              'Link'          => '<http://users.example.org/users?page=2>; rel="next"'
            })
      end
      let!(:req) do
        stub_request(:get, 'http://users.example.org/users?page=2').to_return response([])
      end
      let!(:collection) { model.all }
      subject { Acfs.run; collection.next_page }

      it { should be_a Acfs::Collection }

      it 'should have fetched page 2' do
        subject
        Acfs.run
        expect(req).to have_been_requested
      end
    end

    describe '#prev_page' do
      before do
        stub_request(:get, 'http://users.example.org/users?page=2')
          .to_return response([{id: 2, name: 'Anno', age: 1604, born_at: 'Santa Maria'}],
            headers: {
              'X-Total-Pages' => '2',
              'Link'          => '<http://users.example.org/users>; rel="prev"'
            })
      end
      let!(:req) do
        stub_request(:get, 'http://users.example.org/users').to_return response([])
      end
      let!(:collection) { model.all page: 2 }
      subject { Acfs.run; collection.prev_page }

      it { should be_a Acfs::Collection }

      it 'should have fetched page 1' do
        subject
        Acfs.run
        expect(req).to have_been_requested
      end
    end

    describe '#first_page' do
      before do
        stub_request(:get, 'http://users.example.org/users?page=2')
          .to_return response([{id: 2, name: 'Anno', age: 1604, born_at: 'Santa Maria'}],
            headers: {
              'X-Total-Pages' => '2',
              'Link'          => '<http://users.example.org/users>; rel="first"'
            })
      end
      let!(:req) do
        stub_request(:get, 'http://users.example.org/users').to_return response([])
      end
      let!(:collection) { model.all page: 2 }
      subject { Acfs.run; collection.first_page }

      it { should be_a Acfs::Collection }

      it 'should have fetched page 1' do
        subject
        Acfs.run
        expect(req).to have_been_requested
      end
    end

    describe '#last_page' do
      before do
        stub_request(:get, 'http://users.example.org/users?page=2')
          .to_return response([{id: 2, name: 'Anno', age: 1604, born_at: 'Santa Maria'}],
            headers: {
              'X-Total-Pages' => '2',
              'Link'          => '<http://users.example.org/users?page=12>; rel="last"'
            })
      end
      let!(:req) do
        stub_request(:get, 'http://users.example.org/users?page=12').to_return response([])
      end
      let!(:collection) { model.all page: 2 }
      subject { Acfs.run; collection.last_page }

      it { should be_a Acfs::Collection }

      it 'should have fetched page 1' do
        subject
        Acfs.run
        expect(req).to have_been_requested
      end
    end
  end
end


text:
//-----------------------------------------------------------------------------
// <copyright file="ActivationBehavior.cs" company="WheelMUD Development Team">
//   Copyright (c) WheelMUD Development Team.  See LICENSE.txt.  This file is
//   subject to the Microsoft Public License.  All other rights reserved.
// </copyright>
//
//   Created: June 2009 by Karak.
//   Updated: November 2009 by bengecko - AbstractItemBehavior
//
//-----------------------------------------------------------------------------

namespace WheelMUD.Universe
{
    using System;
    using System.Collections.Generic;
    using WheelMUD.Core;

    /// An activation item behavior adds the ability to trigger effects upon item activation.
    public class ActivationBehavior : Behavior
    {
        /// Initializes a new instance of the <see cref="ActivationBehavior"/> class.
        public ActivationBehavior()
            : base(null)
        {
        }

        /// Initializes a new instance of the <see cref="ActivationBehavior"/> class.
        /// <param name="instanceID">ID of the behavior instance.</param>
        /// <param name="instanceProperties">Dictionary of properties to spawn this behavior instance with, if any.</param>
        public ActivationBehavior(long instanceID, Dictionary<string, object> instanceProperties)
            : base(instanceProperties)
        {
            this.ID = instanceID;
        }

        /// Sets the default properties of this behavior instance.
        protected override void SetDefaultProperties()
        {
            throw new NotImplementedException();
        }
    }
}


text:
""" Provider that returns vector representation of features in a data source.

This is a provider that does not return an image, but rather queries
a data source for raw features and replies with a vector representation
such as GeoJSON. For example, it's possible to retrieve data for
locations of OpenStreetMap points of interest or street centerlines
contained within a tile's boundary.

Many Polymaps (http://polymaps.org) examples use GeoJSON vector data tiles,
which can be effectively created using this provider.

Vector functionality is provided by OGR (http://www.gdal.org/ogr/).
Thank you, Frank Warmerdam.

Currently two serializations and three encodings are supported for a total
of six possible kinds of output with these tile name extensions:

  GeoJSON (.geojson):
    See http://geojson.org/geojson-spec.html

  Arc GeoServices JSON (.arcjson):
    See http://www.esri.com/library/whitepapers/pdfs/geoservices-rest-spec.pdf

  GeoBSON (.geobson) and Arc GeoServices BSON (.arcbson):
    BSON-encoded GeoJSON and Arc JSON, see http://bsonspec.org/#/specification

  GeoAMF (.geoamf) and Arc GeoServices AMF (.arcamf):
    AMF0-encoded GeoJSON and Arc JSON, see:
    http://opensource.adobe.com/wiki/download/attachments/1114283/amf0_spec_121207.pdf

Possible future supported formats might include KML and others. Get in touch
via Github to suggest other formats: http://github.com/migurski/TileStache.

Common parameters:

  driver:
    String used to identify an OGR driver. Currently, "ESRI Shapefile",
    "PostgreSQL", "MySQL", Oracle, Spatialite and "GeoJSON" are supported as
     data source drivers, with "postgis" and "shapefile" accepted as synonyms.
     Not case-sensitive.

    OGR's complete list of potential formats can be found here:
    http://www.gdal.org/ogr/ogr_formats.html. Feel free to get in touch via
    Github to suggest new formats: http://github.com/migurski/TileStache.

  parameters:
    Dictionary of parameters for each driver.

    PostgreSQL:
    "dbname" parameter is required, with name of database.
    "host", "user", and "password" are optional connection parameters.
    One of "table" or "query" is required, with a table name in the first
    case and a complete SQL query in the second.

    Shapefile and GeoJSON:
    "file" parameter is required, with filesystem path to data file.

  properties:
    Optional list or dictionary of case-sensitive output property names.

    If omitted, all fields from the data source will be included in response.
    If a list, treated as a whitelist of field names to include in response.
    If a dictionary, treated as a whitelist and re-mapping of field names.

  clipped:
    Default is true.
    Boolean flag for optionally clipping the output geometries to the
    bounds of the enclosing tile, or the string value "padded" for clipping
    to the bounds of the tile plus 5%. This results in incomplete geometries,
    dramatically smaller file sizes, and improves performance and
    compatibility with Polymaps (http://polymaps.org).

  projected:
    Default is false.
    Boolean flag for optionally returning geometries in projected rather than
    geographic coordinates. Typically this means EPSG:900913 a.k.a. spherical
    mercator projection. Stylistically a poor fit for GeoJSON, but useful
    when returning Arc GeoServices responses.

  precision:
    Default is 6.
    Optional number of decimal places to use for floating point values.

  spacing:
    Optional number of tile pixels for spacing geometries in responses. Used
    to cut down on the number of returned features by ensuring that only those
    features at least this many pixels apart are returned. Order of features
    in the data source matters: early features beat out later features.

  verbose:
    Default is false.
    Boolean flag for optionally expanding output with additional whitespace
    for readability. Results in larger but more readable GeoJSON responses.

  id_property:
    Default is None.
    Sets the id of the geojson feature to the specified field of the data source.
    This can be used, for example, to identify a unique key field for the feature.

Example TileStache provider configuration:

  "vector-postgis-points":
  {
    "provider": {"name": "vector", "driver": "PostgreSQL",
                 "parameters": {"dbname": "geodata", "user": "geodata",
                                "table": "planet_osm_point"}}
  }

  "vector-postgis-lines":
  {
    "provider": {"name": "vector", "driver": "postgis",
                 "parameters": {"dbname": "geodata", "user": "geodata",
                                "table": "planet_osm_line"}}
  }

  "vector-shapefile-points":
  {
    "provider": {"name": "vector", "driver": "ESRI Shapefile",
                 "parameters": {"file": "oakland-uptown-point.shp"},
                 "properties": ["NAME", "HIGHWAY"]}
  }

  "vector-shapefile-lines":
  {
    "provider": {"name": "vector", "driver": "shapefile",
                 "parameters": {"file": "oakland-uptown-line.shp"},
                 "properties": {"NAME": "name", "HIGHWAY": "highway"}}
  }

  "vector-postgis-query":
  {
    "provider": {"name": "vector", "driver": "PostgreSQL",
                 "parameters": {"dbname": "geodata", "user": "geodata",
                                "query": "SELECT osm_id, name, highway, way FROM planet_osm_line WHERE SUBSTR(name, 1, 1) = '1'"}}
  }

  "vector-sf-streets":
  {
    "provider": {"name": "vector", "driver": "GeoJSON",
                 "parameters": {"file": "stclines.json"},
                 "properties": ["STREETNAME"]}
  }

Caveats:

Your data source must have a valid defined projection, or OGR will not know
how to correctly filter and reproject it. Although response tiles are typically
in web (spherical) mercator projection, the actual vector content of responses
is unprojected back to plain WGS84 latitude and longitude.

If you are using PostGIS and spherical mercator a.k.a. SRID 900913,
you can save yourself a world of trouble by using this definition:
  http://github.com/straup/postgis-tools/raw/master/spatial_ref_900913-8.3.sql
"""

from re import compile
from urlparse import urlparse, urljoin

try:
    from json import JSONEncoder, loads as json_loads
except ImportError:
    from simplejson import JSONEncoder, loads as json_loads

from osgeo import ogr, osr

from TileStache.Core import KnownUnknown
from TileStache.Geography import getProjectionByName
from Arc import reserialize_to_arc, pyamf_classes

class VectorResponse:
    """ Wrapper class for Vector response that makes it behave like a PIL.Image object.

        TileStache.getTile() expects to be able to save one of these to a buffer.

        Constructor arguments:
        - content: Vector data to be serialized, typically a dictionary.
        - verbose: Boolean flag to expand response for better legibility.
    """
    def __init__(self, content, verbose, precision=6):
        self.content = content
        self.verbose = verbose
        self.precision = precision

    def save(self, out, format):
        """
        """
        #
        # Serialize
        #
        if format == 'WKT':
            if 'wkt' in self.content['crs']:
                out.write(self.content['crs']['wkt'])
            else:
                out.write(_sref_4326().ExportToWkt())

            return

        if format in ('GeoJSON', 'GeoBSON', 'GeoAMF'):
            content = self.content

            if 'wkt' in content['crs']:
                content['crs'] = {'type': 'link', 'properties': {'href': '0.wkt', 'type': 'ogcwkt'}}
            else:
                del content['crs']

        elif format in ('ArcJSON', 'ArcBSON', 'ArcAMF'):
            content = reserialize_to_arc(self.content, format == 'ArcAMF')

        else:
            raise KnownUnknown('Vector response only saves .geojson, .arcjson, .geobson, .arcbson, .geoamf, .arcamf and .wkt tiles, not "%s"' % format)

        #
        # Encode
        #
        if format in ('GeoJSON', 'ArcJSON'):
            indent = self.verbose and 2 or None

            encoded = JSONEncoder(indent=indent).iterencode(content)
            float_pat = compile(r'^-?\d+\.\d+$')

            for atom in encoded:
                if float_pat.match(atom):
                    out.write(('%%.%if' % self.precision) % float(atom))
                else:
                    out.write(atom)

        elif format in ('GeoBSON', 'ArcBSON'):
            import bson

            encoded = bson.dumps(content)
            out.write(encoded)

        elif format in ('GeoAMF', 'ArcAMF'):
            import pyamf

            for class_name in pyamf_classes.items():
                pyamf.register_class(*class_name)

            encoded = pyamf.encode(content, 0).read()
            out.write(encoded)

def _sref_4326():
    """
    """
    sref = osr.SpatialReference()
    proj = getProjectionByName('WGS84')
    sref.ImportFromProj4(proj.srs)

    return sref

def _tile_perimeter(coord, projection, padded):
    """ Get a tile's outer edge for a coordinate and a projection.

        Returns a list of 17 (x, y) coordinates corresponding to a clockwise
        circumambulation of a tile boundary in a given projection. Projection
        is like those found in TileStache.Geography, used for tile output.

        If padded argument is True, pad bbox by 5% on all sides.
    """
    if padded:
        ul = projection.coordinateProj(coord.left(0.05).up(0.05))
        lr = projection.coordinateProj(coord.down(1.05).right(1.05))
    else:
        ul = projection.coordinateProj(coord)
        lr = projection.coordinateProj(coord.right().down())

    xmin, ymin, xmax, ymax = ul.x, ul.y, lr.x, lr.y
    xspan, yspan = xmax - xmin, ymax - ymin

    perimeter = [
        (xmin, ymin),
        (xmin + 1 * xspan/4, ymin),
        (xmin + 2 * xspan/4, ymin),
        (xmin + 3 * xspan/4, ymin),
        (xmax, ymin),
        (xmax, ymin + 1 * yspan/4),
        (xmax, ymin + 2 * yspan/4),
        (xmax, ymin + 3 * yspan/4),
        (xmax, ymax),
        (xmax - 1 * xspan/4, ymax),
        (xmax - 2 * xspan/4, ymax),
        (xmax - 3 * xspan/4, ymax),
        (xmin, ymax),
        (xmin, ymax - 1 * yspan/4),
        (xmin, ymax - 2 * yspan/4),
        (xmin, ymax - 3 * yspan/4),
        (xmin, ymin)
      ]

    return perimeter

def _tile_perimeter_width(coord, projection):
    """ Get the width in projected coordinates of the coordinate tile polygon.

        Uses _tile_perimeter().
    """
    perimeter = _tile_perimeter(coord, projection, False)
    return perimeter[8][0] - perimeter[0][0]

def _tile_perimeter_geom(coord, projection, padded):
    """ Get an OGR Geometry object for a coordinate tile polygon.

        Uses _tile_perimeter().
    """
    perimeter = _tile_perimeter(coord, projection, padded)
    wkt = 'POLYGON((%s))' % ', '.join(['%.3f %.3f' % xy for xy in perimeter])
    geom = ogr.CreateGeometryFromWkt(wkt)

    ref = osr.SpatialReference()
    ref.ImportFromProj4(projection.srs)
    geom.AssignSpatialReference(ref)

    return geom

def _feature_properties(feature, layer_definition, whitelist=None):
    """ Returns a dictionary of feature properties for a feature in a layer.

        Third argument is an optional list or dictionary of properties to
        whitelist by case-sensitive name - leave it None to include everything.
        A dictionary will cause property names to be re-mapped.

        OGR property types:
        OFTInteger (0), OFTIntegerList (1), OFTReal (2), OFTRealList (3),
        OFTString (4), OFTStringList (5), OFTWideString (6), OFTWideStringList (7),
        OFTBinary (8), OFTDate (9), OFTTime (10), OFTDateTime (11).
    """
    properties = {}
    okay_types = ogr.OFTInteger, ogr.OFTReal, ogr.OFTString, ogr.OFTWideString, ogr.OFTDate, ogr.OFTTime, ogr.OFTDateTime

    for index in range(layer_definition.GetFieldCount()):
        field_definition = layer_definition.GetFieldDefn(index)
        field_type = field_definition.GetType()

        name = field_definition.GetNameRef()

        if type(whitelist) in (list, dict) and name not in whitelist:
            continue

        if field_type not in okay_types:
            try:
                name = [oft for oft in dir(ogr) if oft.startswith('OFT') and getattr(ogr, oft) == field_type][0]
            except IndexError:
                raise KnownUnknown("Found an OGR field type I've never even seen: %d" % field_type)
            else:
                raise KnownUnknown("Found an OGR field type I don't know what to do with: ogr.%s" % name)

        property = type(whitelist) is dict and whitelist[name] or name
        properties[property] = feature.GetField(name)

    return properties

def _append_with_delim(s, delim, data, key):
    if key in data:
        return s + delim + str(data[key])
    else:
        return s

def _open_layer(driver_name, parameters, dirpath):
    """ Open a layer, return it and its datasource.

        Dirpath comes from configuration, and is used to locate files.
    """
    #
    # Set up the driver
    #
    okay_drivers = {'postgis': 'PostgreSQL', 'esri shapefile': 'ESRI Shapefile',
                    'postgresql': 'PostgreSQL', 'shapefile': 'ESRI Shapefile',
                    'geojson': 'GeoJSON', 'spatialite': 'SQLite', 'oracle': 'OCI', 'mysql': 'MySQL'}

    if driver_name.lower() not in okay_drivers:
        raise KnownUnknown('Got a driver type Vector doesn\'t understand: "%s". Need one of %s.' % (driver_name, ', '.join(okay_drivers.keys())))

    driver_name = okay_drivers[driver_name.lower()]
    driver = ogr.GetDriverByName(str(driver_name))

    #
    # Set up the datasource
    #
    if driver_name == 'PostgreSQL':
        if 'dbname' not in parameters:
            raise KnownUnknown('Need at least a "dbname" parameter for postgis')

        conn_parts = []

        for part in ('dbname', 'user', 'host', 'password', 'port'):
            if part in parameters:
                conn_parts.append("%s='%s'" % (part, parameters[part]))

        source_name = 'PG:' + ' '.join(conn_parts)

    elif driver_name == 'MySQL':
        if 'dbname' not in parameters:
            raise KnownUnknown('Need a "dbname" parameter for MySQL')
        if 'table' not in parameters:
            raise KnownUnknown('Need a "table" parameter for MySQL')

        conn_parts = []

        for part in ('host', 'port', 'user', 'password'):
            if part in parameters:
                conn_parts.append("%s=%s" % (part, parameters[part]))

        source_name = 'MySql:' + parameters["dbname"] + "," + ','.join(conn_parts) + ",tables=" + parameters['table']

    elif driver_name == 'OCI':
        if 'host' not in parameters:
            raise KnownUnknown('Need a "host" parameter for oracle')
        if 'table' not in parameters:
            raise KnownUnknown('Need a "table" parameter for oracle')
        source_name = 'OCI:'
        source_name = _append_with_delim(source_name, '', parameters, 'user')
        source_name = _append_with_delim(source_name, '/', parameters, 'password')
        if 'user' in parameters:
	        source_name = source_name + '@'
        source_name = source_name + parameters['host']
        source_name = _append_with_delim(source_name, ':', parameters, 'port')
        source_name = _append_with_delim(source_name, '/', parameters, 'dbname')
        source_name = source_name + ":" + parameters['table']

    elif driver_name in ('ESRI Shapefile', 'GeoJSON', 'SQLite'):
        if 'file' not in parameters:
            raise KnownUnknown('Need at least a "file" parameter for a shapefile')

        file_href = urljoin(dirpath, parameters['file'])
        scheme, h, file_path, q, p, f = urlparse(file_href)

        if scheme not in ('file', ''):
            raise KnownUnknown('Shapefiles need to be local, not %s' % file_href)

        source_name = file_path

    datasource = driver.Open(str(source_name))

    if datasource is None:
        raise KnownUnknown('Couldn\'t open datasource %s' % source_name)

    #
    # Set up the layer
    #
    if driver_name == 'PostgreSQL' or driver_name == 'OCI' or driver_name == 'MySQL':
        if 'query' in parameters:
            layer = datasource.ExecuteSQL(str(parameters['query']))
        elif 'table' in parameters:
            layer = datasource.GetLayerByName(str(parameters['table']))
        else:
            raise KnownUnknown('Need at least a "query" or "table" parameter for postgis or oracle')
    elif driver_name == 'SQLite':
        layer = datasource.GetLayerByName(str(parameters['layer']))
    else:
        layer = datasource.GetLayer(0)

    if layer.GetSpatialRef() is None and driver_name != 'SQLite':
        raise KnownUnknown('Couldn\'t get a layer from data source %s' % source_name)

    #
    # Return the layer and the datasource.
    #
    # Technically, the datasource is no longer needed
    # but layer segfaults when it falls out of scope.
    #
    return layer, datasource

def _get_features(coord, properties, projection, layer, clipped, projected, spacing, id_property):
    """ Return a list of features in an OGR layer with properties in GeoJSON form.

        Optionally clip features to coordinate bounding box, and optionally
        limit returned features to only those separated by number of pixels
        given as spacing.
    """
    #
    # Prepare output spatial reference - always WGS84.
    #
    if projected:
        output_sref = osr.SpatialReference()
        output_sref.ImportFromProj4(projection.srs)
    else:
        output_sref = _sref_4326()

    #
    # Load layer information
    #
    definition = layer.GetLayerDefn()
    layer_sref = layer.GetSpatialRef()
    if layer_sref == None:
        layer_sref = _sref_4326()

    #
    # Spatially filter the layer
    #
    bbox = _tile_perimeter_geom(coord, projection, clipped == 'padded')
    bbox.TransformTo(layer_sref)
    layer.SetSpatialFilter(bbox)

    features = []
    mask = None

    if spacing is not None:
        buffer = spacing * _tile_perimeter_width(coord, projection) / 256.

    for feature in layer:
        geometry = feature.geometry().Clone()

        if not geometry.Intersect(bbox):
            continue

        if mask and geometry.Intersect(mask):
            continue

        if clipped:
            geometry = geometry.Intersection(bbox)

        if geometry is None:
            # may indicate a TopologyException
            continue

        # mask out subsequent features if spacing is defined
        if mask and buffer:
            mask = geometry.Buffer(buffer, 2).Union(mask)
        elif spacing is not None:
            mask = geometry.Buffer(buffer, 2)

        geometry.AssignSpatialReference(layer_sref)
        geometry.TransformTo(output_sref)

        geom = json_loads(geometry.ExportToJson())
        prop = _feature_properties(feature, definition, properties)

        geojson_feature = {'type': 'Feature', 'properties': prop, 'geometry': geom}
        if id_property != None and id_property in prop:
           geojson_feature['id'] = prop[id_property]
        features.append(geojson_feature)

    return features

class Provider:
    """ Vector Provider for OGR datasources.

        See module documentation for explanation of constructor arguments.
    """

    def __init__(self, layer, driver, parameters, clipped, verbose, projected, spacing, properties, precision, id_property):
        self.layer      = layer
        self.driver     = driver
        self.clipped    = clipped
        self.verbose    = verbose
        self.projected  = projected
        self.spacing    = spacing
        self.parameters = parameters
        self.properties = properties
        self.precision  = precision
        self.id_property = id_property

    @staticmethod
    def prepareKeywordArgs(config_dict):
        """ Convert configured parameters to keyword args for __init__().
        """
        kwargs = dict()

        kwargs['driver'] = config_dict['driver']
        kwargs['parameters'] = config_dict['parameters']
        kwargs['id_property'] = config_dict.get('id_property', None)
        kwargs['properties'] = config_dict.get('properties', None)
        kwargs['projected'] = bool(config_dict.get('projected', False))
        kwargs['verbose'] = bool(config_dict.get('verbose', False))
        kwargs['precision'] = int(config_dict.get('precision', 6))

        if 'spacing' in config_dict:
            kwargs['spacing'] = float(config_dict.get('spacing', 0.0))
        else:
            kwargs['spacing'] = None

        if config_dict.get('clipped', None) == 'padded':
            kwargs['clipped'] = 'padded'
        else:
            kwargs['clipped'] = bool(config_dict.get('clipped', True))

        return kwargs

    def renderTile(self, width, height, srs, coord):
        """ Render a single tile, return a VectorResponse instance.
        """
        layer, ds = _open_layer(self.driver, self.parameters, self.layer.config.dirpath)
        features = _get_features(coord, self.properties, self.layer.projection, layer, self.clipped, self.projected, self.spacing, self.id_property)
        response = {'type': 'FeatureCollection', 'features': features}

        if self.projected:
            sref = osr.SpatialReference()
            sref.ImportFromProj4(self.layer.projection.srs)
            response['crs'] = {'wkt': sref.ExportToWkt()}

            if srs == getProjectionByName('spherical mercator').srs:
                response['crs']['wkid'] = 102113
        else:
            response['crs'] = {'srid': 4326, 'wkid': 4326}

        return VectorResponse(response, self.verbose, self.precision)

    def getTypeByExtension(self, extension):
        """ Get mime-type and format by file extension.

            This only accepts "geojson" for the time being.
        """
        if extension.lower() == 'geojson':
            return 'application/json', 'GeoJSON'

        elif extension.lower() == 'arcjson':
            return 'application/json', 'ArcJSON'

        elif extension.lower() == 'geobson':
            return 'application/x-bson', 'GeoBSON'

        elif extension.lower() == 'arcbson':
            return 'application/x-bson', 'ArcBSON'

        elif extension.lower() == 'geoamf':
            return 'application/x-amf', 'GeoAMF'

        elif extension.lower() == 'arcamf':
            return 'application/x-amf', 'ArcAMF'

        elif extension.lower() == 'wkt':
            return 'text/x-wkt', 'WKT'

        raise KnownUnknown('Vector Provider only makes .geojson, .arcjson, .geobson, .arcbson, .geoamf, .arcamf and .wkt tiles, not "%s"' % extension)


text: (function(t){t.effects.effect.fade=function(e,i){var s=t(this),n=t.effects.setMode(s,e.mode||"toggle");s.animate({opacity:n},{queue:!1,duration:e.duration,easing:e.easing,complete:i})}})(jQuery);


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

<title>FileListMap</title>
<meta name="date" content="2013-09-16">
<link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

com.jorisaerts.cscompiler.dependencies

Class FileListMap

java.lang.Object

com.jorisaerts.cscompiler.dependencies.FileListMap

All Implemented Interfaces:

java.util.Map<java.io.File,FileList>

public class FileListMap
extends java.lang.Object
implements java.util.Map<java.io.File,FileList>

Nested Class Summary

Nested classes/interfaces inherited from interface java.util.Map

java.util.Map.Entry<K,V>

Constructor Summary

Constructors

Constructor and Description

FileListMap()

Method Summary

Methods

Modifier and Type
Method and Description

void
clear()

boolean
containsKey(java.lang.Object key)

boolean
containsValue(java.lang.Object value)

java.util.Set<java.util.Map.Entry<java.io.File,FileList>>
entrySet()

FileList
get(java.lang.Object key)

boolean
isEmpty()

java.util.Set<java.io.File>
keySet()

FileList
put(java.io.File key,
   FileList value)

void
putAll(java.util.Map<? extends java.io.File,? extends FileList> m)

FileList
remove(java.lang.Object key)

int
size()

java.util.Collection<FileList>
values()

Methods inherited from class java.lang.Object

equals, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Methods inherited from interface java.util.Map

equals, hashCode

Constructor Detail

FileListMap

public FileListMap()

Method Detail

size

public int size()

Specified by:

size in interface java.util.Map<java.io.File,FileList>

isEmpty

public boolean isEmpty()

Specified by:

isEmpty in interface java.util.Map<java.io.File,FileList>

containsKey

public boolean containsKey(java.lang.Object key)

Specified by:

containsKey in interface java.util.Map<java.io.File,FileList>

containsValue

public boolean containsValue(java.lang.Object value)

Specified by:

containsValue in interface java.util.Map<java.io.File,FileList>

get

public FileList get(java.lang.Object key)

Specified by:

get in interface java.util.Map<java.io.File,FileList>

put

public FileList put(java.io.File key,
           FileList value)

Specified by:

put in interface java.util.Map<java.io.File,FileList>

remove

public FileList remove(java.lang.Object key)

Specified by:

remove in interface java.util.Map<java.io.File,FileList>

putAll

public void putAll(java.util.Map<? extends java.io.File,? extends FileList> m)

Specified by:

putAll in interface java.util.Map<java.io.File,FileList>

clear

public void clear()

Specified by:

clear in interface java.util.Map<java.io.File,FileList>

keySet

public java.util.Set<java.io.File> keySet()

Specified by:

keySet in interface java.util.Map<java.io.File,FileList>

values

public java.util.Collection<FileList> values()

Specified by:

values in interface java.util.Map<java.io.File,FileList>

entrySet

public java.util.Set<java.util.Map.Entry<java.io.File,FileList>> entrySet()

Specified by:

entrySet in interface java.util.Map<java.io.File,FileList>

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method


text:
const _ = require('lodash');

function removeExistingItemsIn(items, matchingEntries, property) {
    if (items.length) {
        let matchingEntriesByProperty = _.keyBy(matchingEntries, property);
        return items.filter(item => (!(item[property] in matchingEntriesByProperty)));
    }
    return items;
}

function nameToAttr(name) {
    return name.trim().replace(/\s+/g, '_').replace(/\//g, '_').replace(/-/g, '_').toLowerCase();
}

module.exports = {
    removeExistingItemsIn,
    nameToAttr,
};


text:
import unittest
import os
from os import path as osp
from examples_tester_env import AbstractExamplesTestCase
from examples_tester_env import example_tests_sort

class LammpsExamplesTestCase(AbstractExamplesTestCase):

    def test_lammps_binary(self):
        binary = os.environ.get('LAMMPS_EXEC')
        self.assertIsNotNone(binary)

    def test_example1(self):
        for p in self.path_generator(osp.join('01_methane', '*')):
            self.assertEqual(self.run_example(p), True)

    def test_example2(self):
        for p in self.path_generator(osp.join('02_methanol', '*')):
            self.assertEqual(self.run_example(p), True)

    def test_example3(self):
        for p in self.path_generator(osp.join('03_benzene', '*')):
            self.assertEqual(self.run_example(p), True)

    def test_example4(self):
        for p in self.path_generator(osp.join('04_polyethylene', '*')):
            self.assertEqual(self.run_example(p), True)

    def test_example5(self):
        for p in self.path_generator(osp.join('05_polyethylene-co-styrene', '*')):
            self.assertEqual(self.run_example(p), True)

    def test_example6(self):
        for p in self.path_generator(osp.join('06_polymethyl_methacryalte_multi', '*')):
            self.assertEqual(self.run_example(p), True)

    def test_example7(self):
        for p in self.path_generator(osp.join('07_lammps_simulation', '')):
            self.assertEqual(self.run_example(p), True)

    def test_example8(self):
        for p in self.path_generator(osp.join('08_ethanol_acetone_mixture', '')):
            self.assertEqual(self.run_example(p), True)

if __name__ == '__main__':
    my_tl = unittest.TestLoader()
    my_tl.sortTestMethodsUsing = example_tests_sort
    unittest.TextTestRunner(buffer=True, verbosity=2).run(my_tl.loadTestsFromTestCase(LammpsExamplesTestCase))


text:
<?php
/**
 * Adminコントローラー
 *
 * 注目まとめを追加する機能
 *
 *
 */

 class Controller_Login_Admin_Recommendarticle extends Controller_Login_Template {
	// ルーター
	public function router($method, $params) {
		$params = $params[0];
		$mail_array_data = array();
		// メール送信画面表示
		if($method == 'index') {
			return $this->action_index();
		}
			else if($method == 'submit') {
				return $this->action_submit();
			}
	}
	////////////////
	//通常アクション
	////////////////
	public function action_index() {
	// ログインチェック
	$login_check = Model_Login_Basis::login_check();
	if($login_check) {
		// viewテンプレート読み込み
		$this->login_admin_template            = View::forge('login/admin/template');
		$this->login_admin_template->view_data = array(
			'title'   => '注目まとめ追加|ポスト|アドミン|ログイン|'.TITLE,
			'content' => View::forge('login/admin/list/list'),
		);
		// コンテンツ挿入
		$this->login_admin_template->view_data["content"]->set('content_data',array(
			'content_html' => View::forge('login/admin/recommendarticle/recommendarticle'),
		),false);
		return $this->login_admin_template;
	}
		// ログインしていない場合
		else {
			header('Location: '.HTTP.'');
			exit;
		}
	}
	//////////////////
	//Submitアクション
	//////////////////
	public function action_submit() {
	// ログインチェック
	$login_check = Model_Login_Basis::login_check();
	if($login_check) {
		// viewテンプレート読み込み
		$this->login_admin_template            = View::forge('login/admin/template');
		$this->login_admin_template->view_data = array(
			'title'   => '注目まとめ追加|ポスト|アドミン|ログイン|'.TITLE,
			'content' => View::forge('login/admin/list/list'),
		);
		// セキュリティーポスト取得
		$post = Library_Security_Basis::post_security();
		if($post) {
			$recommend_article_list = $post['recommend_article_list'];
			// 注目まとめ追加するためのarray生成
			$recommend_article_list_array = Model_Login_Recommendarticle_Basis::recommend_article_array_get($recommend_article_list);
//var_dump($recommend_article_list_array);
			// 注目まとめ登録
			Model_Login_Recommendarticle_Basis::recommend_article_array_register($recommend_article_list_array);
			header('location: '.HTTP.'login/admin/');
			exit;
		}
		// コンテンツ挿入
		$this->login_admin_template->view_data["content"]->set('content_data',array(
			'content_html' => '注目まとめ追加いたしました。',
		),false);
		return $this->login_admin_template;
	}
		// ログインしていない場合
		else {
			header('Location: '.HTTP.'');
			exit;
		}
	}

}


text:
<?php

namespace Web\StockBundle\Admin;

use Sonata\AdminBundle\Admin\Admin;
use Sonata\AdminBundle\Datagrid\DatagridMapper;
use Sonata\AdminBundle\Datagrid\ListMapper;
use Sonata\AdminBundle\Form\FormMapper;
use Sonata\AdminBundle\Show\ShowMapper;

class ModelAdmin extends Admin
{
    /**
     * @param DatagridMapper $datagridMapper
     */
    protected function configureDatagridFilters(DatagridMapper $datagridMapper)
    {
        $datagridMapper
            ->add('name')
            ->add('titleENG')
//            ->add('size')
            ->add('productionTime')
        ;
    }

    /**
     * @param ListMapper $listMapper
     */
    protected function configureListFields(ListMapper $listMapper)
    {
        $listMapper
            ->add('id')
            ->addIdentifier('name')
//            ->add('size')
            ->add('productionTime')
            ->add('_action', 'actions', array(
                'actions' => array(
                    'show' => array(),
                    'edit' => array(),
                    'delete' => array(),
                )
            ))
        ;
    }

    /**
     * @param FormMapper $formMapper
     */
    protected function configureFormFields(FormMapper $formMapper)
    {
        $formMapper
            ->add('name')
            ->add('titleENG')
            ->add('description','text')
            ->add('descriptionENG','text')
            ->add('yarn','sonata_type_model_list', array(),array())
            ->add('sizes','sonata_type_model', array('expanded' => true, 'multiple' => true))
            ->add('productionTime', 'number')
            ->add('relatedModels', 'sonata_type_model', array('expanded' => true, 'multiple' => true))
            ->add('costRub', 'number')
            ->add('costUsd', 'number')
            ->add('gallery', 'sonata_type_model_list', array(
            ), array(
                'placeholder' => 'Галерея не выбрана'
            ))
        ;
    }

    /**
     * @param ShowMapper $showMapper
     */
    protected function configureShowFields(ShowMapper $showMapper)
    {
        $showMapper
            ->add('name')
            ->add('titleENG')
            ->add('description')
            ->add('descriptionENG')
            ->add('size')
            ->add('productionTime')
            ->add('id')
        ;
    }
}


text:
/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* vim: set ts=8 sts=2 et sw=2 tw=80: */
/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

#ifndef mozilla_dom_HTMLMenuItemElement_h
#define mozilla_dom_HTMLMenuItemElement_h

#include "mozilla/Attributes.h"
#include "nsIDOMHTMLMenuItemElement.h"
#include "nsGenericHTMLElement.h"

namespace mozilla {

class EventChainPreVisitor;

namespace dom {

class Visitor;

class HTMLMenuItemElement final : public nsGenericHTMLElement,
                                  public nsIDOMHTMLMenuItemElement
{
public:
  using mozilla::dom::Element::GetText;

  HTMLMenuItemElement(already_AddRefed<mozilla::dom::NodeInfo>& aNodeInfo,
                      mozilla::dom::FromParser aFromParser);

  NS_IMPL_FROMCONTENT_HTML_WITH_TAG(HTMLMenuItemElement, menuitem)

  // nsISupports
  NS_DECL_ISUPPORTS_INHERITED

  // nsIDOMHTMLMenuItemElement
  NS_DECL_NSIDOMHTMLMENUITEMELEMENT

  virtual nsresult PreHandleEvent(EventChainPreVisitor& aVisitor) override;
  virtual nsresult PostHandleEvent(
                     EventChainPostVisitor& aVisitor) override;

  virtual nsresult BindToTree(nsIDocument* aDocument, nsIContent* aParent,
                              nsIContent* aBindingParent,
                              bool aCompileEventHandlers) override;

  virtual bool ParseAttribute(int32_t aNamespaceID,
                                nsIAtom* aAttribute,
                                const nsAString& aValue,
                                nsAttrValue& aResult) override;

  virtual void DoneCreatingElement() override;

  virtual nsresult Clone(mozilla::dom::NodeInfo *aNodeInfo, nsINode **aResult) const override;

  uint8_t GetType() const { return mType; }

  /**
   * Syntax sugar to make it easier to check for checked and checked dirty
   */
  bool IsChecked() const { return mChecked; }
  bool IsCheckedDirty() const { return mCheckedDirty; }

  void GetText(nsAString& aText);

  // WebIDL

  // The XPCOM GetType is OK for us
  void SetType(const nsAString& aType, ErrorResult& aError)
  {
    SetHTMLAttr(nsGkAtoms::type, aType, aError);
  }

  // The XPCOM GetLabel is OK for us
  void SetLabel(const nsAString& aLabel, ErrorResult& aError)
  {
    SetAttrHelper(nsGkAtoms::label, aLabel);
  }

  // The XPCOM GetIcon is OK for us
  void SetIcon(const nsAString& aIcon, ErrorResult& aError)
  {
    SetAttrHelper(nsGkAtoms::icon, aIcon);
  }

  bool Disabled() const
  {
    return GetBoolAttr(nsGkAtoms::disabled);
  }
  void SetDisabled(bool aDisabled, ErrorResult& aError)
  {
    SetHTMLBoolAttr(nsGkAtoms::disabled, aDisabled, aError);
  }

  bool Checked() const
  {
    return mChecked;
  }
  void SetChecked(bool aChecked, ErrorResult& aError)
  {
    aError = SetChecked(aChecked);
  }

  // The XPCOM GetRadiogroup is OK for us
  void SetRadiogroup(const nsAString& aRadiogroup, ErrorResult& aError)
  {
    SetHTMLAttr(nsGkAtoms::radiogroup, aRadiogroup, aError);
  }

  bool DefaultChecked() const
  {
    return GetBoolAttr(nsGkAtoms::checked);
  }
  void SetDefaultChecked(bool aDefault, ErrorResult& aError)
  {
    SetHTMLBoolAttr(nsGkAtoms::checked, aDefault, aError);
  }

protected:
  virtual ~HTMLMenuItemElement();

  virtual JSObject* WrapNode(JSContext *aCx, JS::Handle<JSObject*> aGivenProto) override;

protected:
  virtual nsresult AfterSetAttr(int32_t aNamespaceID, nsIAtom* aName,
                                const nsAttrValue* aValue, bool aNotify) override;

  void WalkRadioGroup(Visitor* aVisitor);

  HTMLMenuItemElement* GetSelectedRadio();

  void AddedToRadioGroup();

  void InitChecked();

  friend class ClearCheckedVisitor;
  friend class SetCheckedDirtyVisitor;

  void ClearChecked() { mChecked = false; }
  void SetCheckedDirty() { mCheckedDirty = true; }

private:
  uint8_t mType : 2;
  bool mParserCreating : 1;
  bool mShouldInitChecked : 1;
  bool mCheckedDirty : 1;
  bool mChecked : 1;
};

} // namespace dom
} // namespace mozilla

#endif // mozilla_dom_HTMLMenuItemElement_h