text:
namespace GraphClimber
{
    /// <summary>
    /// Defines a processor that handles all the enumeration values.
    /// </summary>
    public interface IEnumProcessor
    {

        /// <summary>
        /// Process an enumeration value that placed inside
        /// a field of the same type as the enum
        /// </summary>
        /// <typeparam name="TEnum">The type of the enum</typeparam>
        /// <typeparam name="TUnderlying">The underlying type of the enum</typeparam>
        /// <remarks>
        /// It is safe to cast the given <see cref="descriptor"/>.<see cref="IReadOnlyValueDescriptor{TRuntime}.Get"/> to <typeparamref name="TUnderlying"/>
        /// </remarks>
        /// <param name="descriptor"></param>
        void Process<TEnum, TUnderlying>(IReadWriteValueDescriptor<TEnum> descriptor);
    }
}


text:
<?php

namespace Larabros\Elogram\Providers;

use GuzzleHttp\Client;
use GuzzleHttp\HandlerStack;
use Larabros\Elogram\Http\Clients\AdapterInterface;
use Larabros\Elogram\Http\Clients\GuzzleAdapter;
use Larabros\Elogram\Http\Clients\MockAdapter;
use League\Container\Argument\RawArgument;
use League\Container\ServiceProvider\AbstractServiceProvider;

/**
 * Adds Guzzle to the project.
 *
 * @package    Elogram
 * @author     Hassan Khan <contact@hassankhan.me>
 * @link       https://github.com/larabros/elogram
 * @license    MIT
 */
class GuzzleServiceProvider extends AbstractServiceProvider
{
    /**
     * The provides array is a way to let the container
     * know that a service is provided by this service
     * provider. Every service that is registered via
     * this service provider must have an alias added
     * to this array or it will be ignored.
     *
     * @var array
     */
    protected $provides = [
        Client::class,
        AdapterInterface::class,
    ];

    /**
     * Use the register method to register items with the container via the
     * protected ``$this->container`` property or the ``getContainer`` method
     * from the ``ContainerAwareTrait``.
     *
     * @return void
     */
    public function register()
    {
        $container = $this->getContainer();
        $config    = $container->get('config');

        $container->share(Client::class)
            ->withArgument(new RawArgument([
                'base_uri' => $config->get('base_uri'),
                'handler'  => $container->get(HandlerStack::class),
            ]));

        if ($config->get('http_adapter') === GuzzleAdapter::class) {
            $container->share(AdapterInterface::class, function () use ($container) {
                return new GuzzleAdapter($container->get(Client::class));
            });
        }

        if ($config->get('http_adapter') === MockAdapter::class) {
            $path = realpath(__DIR__.'/../../tests/fixtures').'/';
            $container->share(AdapterInterface::class, new MockAdapter($path));
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
package br.jus.trf2.balcaojus;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.UnsupportedEncodingException;
import java.nio.charset.StandardCharsets;
import java.util.logging.Logger;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.w3c.tidy.Tidy;
import org.xhtmlrenderer.pdf.ITextRenderer;

public class Html2Pdf {
	private static Logger logger = Logger.getLogger(Html2Pdf.class.getCanonicalName());

	static String cleanHtmlJSoup(String html, boolean fBodyOnly) {
		if (html.startsWith("<?xml "))
			return html;
		final Document document = Jsoup.parse(html);
		document.outputSettings().syntax(Document.OutputSettings.Syntax.xml);
		document.outputSettings().escapeMode(org.jsoup.nodes.Entities.EscapeMode.xhtml);
		if (fBodyOnly)
			return document.body().html();
		else
			return document.html();
	}

	public String cleanHtml(String data) throws UnsupportedEncodingException {
		if (data.startsWith("<?xml "))
			return data;

//		System.err.println("transformando HTML em XHTML");
		Tidy tidy = new Tidy();
		tidy.setXHTML(true);
		tidy.setInputEncoding("UTF-8");
		tidy.setOutputEncoding("UTF-8");
		// tidy.setWraplen(Integer.MAX_VALUE);
		// tidy.setPrintBodyOnly(true);
		// tidy.setXmlOut(true);
		tidy.setSmartIndent(true);
		tidy.setTidyMark(false);
		tidy.setShowErrors(0);
		tidy.setQuiet(true);
		// tidy.setErrout(null);
		ByteArrayInputStream inputStream = new ByteArrayInputStream(data.getBytes("UTF-8"));
		ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
		tidy.parseDOM(inputStream, outputStream);
//		System.err.println("retornando XHTML");
		String s = outputStream.toString("UTF-8");
		s = s.replace(
				" PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\"\n\"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\"",
				"");
		s = s.replace(" xmlns=\"http://www.w3.org/1999/xhtml\"", "");
		return s;
	}

//	private static class ResourceLoaderUserAgent extends ITextUserAgent {
//		public ResourceLoaderUserAgent(ITextOutputDevice outputDevice) {
//			super(outputDevice);
//		}
//
//		protected InputStream resolveAndOpenStream(String uri) {
//			System.err.println("buscando recurso externo: " + uri);
//
//			String entry = "pdf-resource-" + uri;
//
//			byte ab[] = (byte[]) Dao.syncCache().get(entry);
//			if (ab == null) {
//				try {
//					System.err.println("fazendo o download de recurso externo: " + uri);
//					ab = HttpGAE.fetch(new URL(uri));
//				} catch (Exception e) {
//					throw new RuntimeException(e);
//				}
//				Dao.syncCache().put(entry, ab);
//			}
//
//			System.err.println("retornando recurso externo: " + uri);
//			ByteArrayInputStream bais = new ByteArrayInputStream(ab);
//			return bais;
//		}
//	}

	public static String extraiBody(final String sSource) {
		Document d = Jsoup.parse(sSource);
		return d.body().toString();
	}

	public byte[] converter(String sHtml, boolean apenasBody) throws Exception {
//		System.err.println("iniciando a conversão");
		String pagina = null;
		if (apenasBody)
			pagina = Utils.convertStreamToString(this.getClass().getResourceAsStream("pagina.html"));
//		System.err.println("resource carregado");
		if (sHtml != null && pagina != null) {
			String prefix = pagina.substring(0, pagina.indexOf(""));
			String sufix = pagina.substring(pagina.indexOf("") + 7);

			sHtml = cleanHtml(prefix + extraiBody(sHtml) + sufix);
//			System.err.println("HTML calculado");
		} else {
			sHtml = cleanHtml(sHtml);
		}
//		System.err.println(sHtml);

		try (ByteArrayOutputStream baos = new ByteArrayOutputStream()) {
			ITextRenderer renderer = new ITextRenderer();
			// Habilitar para carregar recursos externos
			// ResourceLoaderUserAgent callback = new
			// ResourceLoaderUserAgent(renderer.getOutputDevice());
			// callback.setSharedContext(renderer.getSharedContext());
			// renderer.getSharedContext().setUserAgentCallback(callback);

			renderer.setDocumentFromString(sHtml);
			renderer.layout();
			renderer.createPDF(baos);
//			System.err.println("PDF gerado");

			return baos.toByteArray();
		}
	}

	public byte[] converterJsoup(String sHtml, boolean apenasBody) throws Exception {
//		System.err.println("iniciando a conversão");
		String pagina = null;
		sHtml = sHtml.replace("", ">");
		sHtml = sHtml.replace(" ", ">");

		if (apenasBody)
			pagina = Utils.convertStreamToString(this.getClass().getResourceAsStream("pagina.html"));
//		System.err.println("resource carregado");
		if (sHtml != null && pagina != null) {
			String prefix = pagina.substring(0, pagina.indexOf(""));
			String sufix = pagina.substring(pagina.indexOf("") + 7);

			sHtml = prefix + extraiBody(sHtml) + sufix;

			sHtml = cleanHtmlJSoup(sHtml, false);
//			System.err.println("HTML calculado");
		} else {
			sHtml = cleanHtml(sHtml);
		}
//		System.err.println(sHtml);

		try (ByteArrayOutputStream baos = new ByteArrayOutputStream()) {
			ITextRenderer renderer = new ITextRenderer();
			// Habilitar para carregar recursos externos
			// ResourceLoaderUserAgent callback = new
			// ResourceLoaderUserAgent(renderer.getOutputDevice());
			// callback.setSharedContext(renderer.getSharedContext());
			// renderer.getSharedContext().setUserAgentCallback(callback);

			renderer.setDocumentFromString(sHtml);
			renderer.layout();
			renderer.createPDF(baos);
//			System.err.println("PDF gerado");

			return baos.toByteArray();
		}
	}

}


text:
// Copyright 2015 The Bazel Authors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//    http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.devtools.build.lib.packages;

import static com.google.common.truth.Truth.assertThat;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;

import com.google.common.base.Function;
import com.google.common.base.Predicate;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Iterables;
import com.google.common.collect.Sets;
import com.google.devtools.build.lib.cmdline.Label;
import com.google.devtools.build.lib.cmdline.ResolvedTargets;
import com.google.devtools.build.lib.cmdline.TargetParsingException;
import com.google.devtools.build.lib.events.ExtendedEventHandler;
import com.google.devtools.build.lib.packages.util.PackageLoadingTestCase;
import com.google.devtools.build.lib.pkgcache.TargetProvider;
import com.google.devtools.build.lib.skyframe.TestSuiteExpansionValue;
import com.google.devtools.build.skyframe.EvaluationResult;
import com.google.devtools.build.skyframe.SkyKey;
import java.util.Collection;
import java.util.EnumSet;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;

@RunWith(JUnit4.class)
public class TestTargetUtilsTest extends PackageLoadingTestCase {
  private Target test1;
  private Target test2;
  private Target test1b;
  private Target suite;

  @Before
  public final void createTargets() throws Exception {
    scratch.file(
        "tests/BUILD",
        "py_test(name = 'small_test_1',",
        "        srcs = ['small_test_1.py'],",
        "        data = [':xUnit'],",
        "        size = 'small',",
        "        tags = ['tag1'])",
        "",
        "sh_test(name = 'small_test_2',",
        "        srcs = ['small_test_2.sh'],",
        "        data = ['//testing/shbase:googletest.sh'],",
        "        size = 'small',",
        "        tags = ['tag2'])",
        "",
        "sh_test(name = 'large_test_1',",
        "        srcs = ['large_test_1.sh'],",
        "        data = ['//testing/shbase:googletest.sh', ':xUnit'],",
        "        size = 'large',",
        "        tags = ['tag1'])",
        "",
        "py_binary(name = 'notest',",
        "        srcs = ['notest.py'])",
        "cc_library(name = 'xUnit', data = ['//tools:test_sharding_compliant'])",
        "",
        "test_suite( name = 'smallTests', tags=['small'])");

    test1 = getTarget("//tests:small_test_1");
    test2 = getTarget("//tests:small_test_2");
    test1b = getTarget("//tests:large_test_1");
    suite = getTarget("//tests:smallTests");
  }

  @Test
  public void testFilterBySize() throws Exception {
    Predicate<Target> sizeFilter =
        TestTargetUtils.testSizeFilter(EnumSet.of(TestSize.SMALL, TestSize.LARGE));
    assertTrue(sizeFilter.apply(test1));
    assertTrue(sizeFilter.apply(test2));
    assertTrue(sizeFilter.apply(test1b));
    sizeFilter = TestTargetUtils.testSizeFilter(EnumSet.of(TestSize.SMALL));
    assertTrue(sizeFilter.apply(test1));
    assertTrue(sizeFilter.apply(test2));
    assertFalse(sizeFilter.apply(test1b));
  }

  @Test
  public void testFilterByTimeout() throws Exception {
    scratch.file(
        "timeouts/BUILD",
        "sh_test(name = 'long_timeout',",
        "          srcs = ['a.sh'],",
        "          size = 'small',",
        "          timeout = 'long')",
        "sh_test(name = 'short_timeout',",
        "          srcs = ['b.sh'],",
        "          size = 'small')",
        "sh_test(name = 'moderate_timeout',",
        "          srcs = ['c.sh'],",
        "          size = 'small',",
        "          timeout = 'moderate')");
    Target longTest = getTarget("//timeouts:long_timeout");
    Target shortTest = getTarget("//timeouts:short_timeout");
    Target moderateTest = getTarget("//timeouts:moderate_timeout");

    Predicate<Target> timeoutFilter =
        TestTargetUtils.testTimeoutFilter(EnumSet.of(TestTimeout.SHORT, TestTimeout.LONG));
    assertTrue(timeoutFilter.apply(longTest));
    assertTrue(timeoutFilter.apply(shortTest));
    assertFalse(timeoutFilter.apply(moderateTest));
  }

  @Test
  public void testExpandTestSuites() throws Exception {
    assertExpandedSuites(Sets.newHashSet(test1, test2), Sets.newHashSet(test1, test2));
    assertExpandedSuites(Sets.newHashSet(test1, test2), Sets.newHashSet(suite));
    assertExpandedSuites(
        Sets.newHashSet(test1, test2, test1b), Sets.newHashSet(test1, suite, test1b));
    // The large test if returned as filtered from the test_suite rule, but should still be in the
    // result set as it's explicitly added.
    assertExpandedSuites(
        Sets.newHashSet(test1, test2, test1b), ImmutableSet.<Target>of(test1b, suite));
  }

  @Test
  public void testSkyframeExpandTestSuites() throws Exception {
    assertExpandedSuitesSkyframe(
        Sets.newHashSet(test1, test2), ImmutableSet.<Target>of(test1, test2));
    assertExpandedSuitesSkyframe(Sets.newHashSet(test1, test2), ImmutableSet.<Target>of(suite));
    assertExpandedSuitesSkyframe(
        Sets.newHashSet(test1, test2, test1b), ImmutableSet.<Target>of(test1, suite, test1b));
    // The large test if returned as filtered from the test_suite rule, but should still be in the
    // result set as it's explicitly added.
    assertExpandedSuitesSkyframe(
        Sets.newHashSet(test1, test2, test1b), ImmutableSet.<Target>of(test1b, suite));
  }

  @Test
  public void testExpandTestSuitesKeepGoing() throws Exception {
    reporter.removeHandler(failFastHandler);
    scratch.file("broken/BUILD", "test_suite(name = 'broken', tests = ['//missing:missing_test'])");
    ResolvedTargets<Target> actual =
        TestTargetUtils.expandTestSuites(
            getPackageManager(),
            reporter,
            Sets.newHashSet(getTarget("//broken")), /*strict=*/
            false, /*keep_going=*/
            true);
    assertTrue(actual.hasError());
    assertThat(actual.getTargets()).isEmpty();
  }

  private void assertExpandedSuites(Iterable<Target> expected, Collection<Target> suites)
      throws Exception {
    ResolvedTargets<Target> actual =
        TestTargetUtils.expandTestSuites(
            getPackageManager(), reporter, suites, /*strict=*/ false, /*keep_going=*/ true);
    assertFalse(actual.hasError());
    assertThat(actual.getTargets()).containsExactlyElementsIn(expected);
  }

  private static final Function<Target, Label> TO_LABEL =
      new Function<Target, Label>() {
        @Override
        public Label apply(Target input) {
          return input.getLabel();
        }
      };

  private void assertExpandedSuitesSkyframe(Iterable<Target> expected, Collection<Target> suites)
      throws Exception {
    ImmutableSet<Label> suiteLabels = ImmutableSet.copyOf(Iterables.transform(suites, TO_LABEL));
    SkyKey key = TestSuiteExpansionValue.key(suiteLabels);
    EvaluationResult<TestSuiteExpansionValue> result =
        getSkyframeExecutor()
            .getDriverForTesting()
            .evaluate(ImmutableList.of(key), false, 1, reporter);
    ResolvedTargets<Target> actual = result.get(key).getTargets();
    assertFalse(actual.hasError());
    assertThat(actual.getTargets()).containsExactlyElementsIn(expected);
  }

  @Test
  public void testExpandTestSuitesInterrupted() throws Exception {
    reporter.removeHandler(failFastHandler);
    scratch.file("broken/BUILD", "test_suite(name = 'broken', tests = ['//missing:missing_test'])");
    try {
      TestTargetUtils.expandTestSuites(
          new TargetProvider() {
            @Override
            public Target getTarget(ExtendedEventHandler eventHandler, Label label)
                throws InterruptedException {
              throw new InterruptedException();
            }
          },
          reporter,
          Sets.newHashSet(getTarget("//broken")), /*strict=*/
          false, /*keep_going=*/
          true);
    } catch (TargetParsingException e) {
      assertNotNull(e.getMessage());
    }
    assertTrue(Thread.currentThread().isInterrupted());
  }
}


text:
package problem.percolation;

/**
 * @author: xichen0603@gmail.com
 */
public class PercolationStats {
    // perform trials independent experiments on an n-by-n grid
    public PercolationStats(int n, int trials) {

    }

    // sample mean of percolation threshold
    public double mean() {
        return 0;
    }

    // sample standard deviation of percolation threshold
    public double stddev() {
        return 0;
    }

    // low  endpoint of 95% confidence interval
    public double confidenceLo() {

        return 0;
    }

    // high endpoint of 95% confidence interval
    public double confidenceHi() {

        return 0;
    }

    // test client (described below)
    public static void main(String[] args) {

    }
}


text:
layout: compress
---

<!DOCTYPE html>

  {% include head.html %}

    {% include header.html %}

        {{ content }}

    {% include footer.html %}

    {% javascript_asset_tag global %}
      - _js/example.js
    {% endjavascript_asset_tag %}


text:
var Localization = require('i18n-2');

var length = require('./validations/length.js');
var required = require('./validations/required.js');
var string = require('./validations/string.js');
var type = require('./validations/type.js');
var value = require('./validations/value.js');

var validations = {
  type: type,
  minLength: length.min,
  maxLength: length.max,
  required: required,
  string: string,
  lessThan: value.lessThan,
  lessThanOrEqual: value.lessThanOrEqual,
  moreThan: value.moreThan,
  moreThanOrEqual: value.moreThanOrEqual
};

/**
 * MValidate uses a Json to validate another Json.
 *
 * @class MValidate
 * @param {object} localesConfig Object with the localization config.
 * @param  {string} locale        The locale to be used
 * @constructor
 * @module MValidate
 * @example
 * ```javascript
 * var localesConfig = {
 *   locales: ['pt-BR', 'en-US', 'es-ES'],
 *   directory: './locales',
 *   extension: '.json'
 * };
 * var validator = new MValidate(localesConfig, 'pt-BR');
 * ```
 */
var MValidate = function(localesConfig, locale) {
  this.i18n = new Localization(localesConfig);
  this.i18n.setLocale(locale);
};

/**
 * Validate the content fields using the properties Json
 * @method validate
 * @param  {object} content    The Json with each field to be validated
 * @param  {Json} properties The Json with each field definition
 * @return {object}            An object with each validated field and the
 * found errors. If no error is found, an empty object is returned
 * @example
 **content** example:
 ```javascript
 var content = {
   password: "1234",
   title: "Hi there!",
   text: "Hello there",
   color: "#FFGG32",
   backgroundColor: ""
 };
 ```
 **properties** example:
 ```json
 "fields": [
   {
     "name": "password",
     "type": "number",
     "min-length": 6,
     "max-length": 30
   },
   {
     "name": "title",
     "type": "text",
     "min-length": 2,
     "max-length": 144,
     "string": "alphaSpace",
     "required": true
   },
   {
     "name": "text",
     "type": "text-area",
     "min-length": 2,
     "max-length": 3000,
     "string": "alphaSpace"
   },
   {
     "name": "color",
     "type": "color"
     "required": true
   },
   {
     "name": "backgroundColor",
     "type": "color"
     "required": true
   }
 ]
 ```
 Using this content with this validator and no translation you should get the
 following response:
 ```javascript
 {
  password: {
    min-length: 'must_be_min: 6'
  },
  title: {
    string: 'not_an_alpha_space'
  },
  text: {},
  color: {
    type: 'not_a_color'
  },
  backgroundColor: {
    required: 'field_is_required'
  }
 }
 ```

 * You can check how to create the translation Json in the [spec/locales](https://github.com/moblets/m-validate/tree/develop/spec/locales) folder.

 * Check all possible validations and usage in the [readme documentation](https://github.com/moblets/m-validate#m-validate).
 */
MValidate.prototype.validate = function(content, properties) {
  var error = false;
  var response = {};
    // Iterate the array with the PROPERTIES
  for (var i = 0; i < properties.length; i++) {
    var property = properties[i];

      // Iterate the RULES of a PROPERTY
    for (var rule in property) {
      if (property.hasOwnProperty(rule)) {
        var fieldName = property.name;

          // Create the object for the results of a property
        if (typeof response[fieldName] === 'undefined') {
          response[fieldName] = {};
        }

          // Convert the rule to camelCase to respect Google Style
        var ccRule = rule.replace(/-([a-z])/g, function(g) {
          return g[1].toUpperCase();
        });

          // Validate all rules existing in the validation functions
          // Ignore "name" and keys that don't have a validation deffined
        if (
            rule !== 'name' &&
            typeof validations[ccRule] !== 'undefined') {
          var validationResult = validations[ccRule](
              property[rule],
              content[fieldName],
              property.values
            );
          if (validationResult !== true) {
            var splitedResponse = validationResult.split(': ');
            if (splitedResponse.length > 1) {
              var res = this.i18n.__n(
                  splitedResponse[0] + ': %f',
                  Number(splitedResponse[1])
                );

              if (!res) {
                res = this.i18n.__(
                  splitedResponse[0] + ': %f',
                  Number(splitedResponse[1])
                );
              }

              (response[fieldName])[rule] = res;
            } else {
              (response[fieldName])[rule] = this.i18n
              .__(validationResult);
            }
            error = true;
          }
        }
      }
    }
  }
  return {
    error: error,
    result: response
  };
};

/**
MValidate module
@module MValidate
@class MValidate
@main MValidate
**/
module.exports = MValidate;


text:
using System.Collections.Generic;
using NBitcoin;
using Newtonsoft.Json.Linq;
using WalletWasabi.BitcoinCore.Rpc.Models;

namespace WalletWasabi.BitcoinCore.Rpc
{
	public static class RpcParser
	{
		public static RpcPubkeyType ConvertPubkeyType(string pubKeyType)
		{
			return pubKeyType switch
			{
				"nonstandard" => RpcPubkeyType.TxNonstandard,
				"pubkey" => RpcPubkeyType.TxPubkey,
				"pubkeyhash" => RpcPubkeyType.TxPubkeyhash,
				"scripthash" => RpcPubkeyType.TxScripthash,
				"multisig" => RpcPubkeyType.TxMultisig,
				"nulldata" => RpcPubkeyType.TxNullData,
				"witness_v0_keyhash" => RpcPubkeyType.TxWitnessV0Keyhash,
				"witness_v0_scripthash" => RpcPubkeyType.TxWitnessV0Scripthash,
				"witness_unknown" => RpcPubkeyType.TxWitnessUnknown,
				_ => RpcPubkeyType.Unknown
			};
		}

		public static VerboseBlockInfo ParseVerboseBlockResponse(string getBlockResponse)
		{
			var blockInfoJson = JObject.Parse(getBlockResponse);
			var previousBlockHash = blockInfoJson.Value<string>("previousblockhash");
			var transaction = new List<VerboseTransactionInfo>();

			var blockInfo = new VerboseBlockInfo(
				hash: uint256.Parse(blockInfoJson.Value<string>("hash")),
				prevBlockHash: previousBlockHash is { } ? uint256.Parse(previousBlockHash) : uint256.Zero,
				confirmations: blockInfoJson.Value<ulong>("confirmations"),
				height: blockInfoJson.Value<ulong>("height"),
				blockTime: Utils.UnixTimeToDateTime(blockInfoJson.Value<uint>("time")),
				transactions: transaction
			);

			foreach (var txJson in blockInfoJson["tx"])
			{
				var inputs = new List<VerboseInputInfo>();
				var outputs = new List<VerboseOutputInfo>();
				var tx = new VerboseTransactionInfo(uint256.Parse(txJson.Value<string>("txid")), inputs, outputs);

				foreach (var txinJson in txJson["vin"])
				{
					VerboseInputInfo input;
					if (txinJson["coinbase"] is { })
					{
						input = new VerboseInputInfo(txinJson["coinbase"].Value<string>());
					}
					else
					{
						input = new VerboseInputInfo(
							outPoint: new OutPoint(uint256.Parse(txinJson.Value<string>("txid")), txinJson.Value<uint>("vout")),
							prevOutput: new VerboseOutputInfo(
								value: Money.Coins(txinJson["prevout"].Value<decimal>("value")),
								scriptPubKey: Script.FromHex(txinJson["prevout"]["scriptPubKey"].Value<string>("hex")),
								pubkeyType: txinJson["prevout"]["scriptPubKey"].Value<string>("type"))
						);
					}

					inputs.Add(input);
				}

				foreach (var txoutJson in txJson["vout"])
				{
					var output = new VerboseOutputInfo(
						value: Money.Coins(txoutJson.Value<decimal>("value")),
						scriptPubKey: Script.FromHex(txoutJson["scriptPubKey"].Value<string>("hex")),
						pubkeyType: txoutJson["scriptPubKey"].Value<string>("type")
					);

					outputs.Add(output);
				}

				transaction.Add(tx);
			}

			return blockInfo;
		}
	}
}


text:
package org.terasology.logic.players;

import org.terasology.audio.AudioManager;
import org.terasology.entitySystem.entity.EntityRef;
import org.terasology.entitySystem.event.ReceiveEvent;
import org.terasology.entitySystem.systems.BaseComponentSystem;
import org.terasology.entitySystem.systems.RegisterMode;
import org.terasology.entitySystem.systems.RegisterSystem;
import org.terasology.input.ButtonState;
import org.terasology.input.binds.general.OnlinePlayersButton;
import org.terasology.input.binds.general.PauseButton;
import org.terasology.input.binds.general.ScreenshotButton;
import org.terasology.logic.characters.events.DeathEvent;
import org.terasology.logic.characters.events.PlayerDeathEvent;
import org.terasology.network.ClientComponent;
import org.terasology.registry.CoreRegistry;
import org.terasology.registry.In;
import org.terasology.rendering.nui.NUIManager;
import org.terasology.rendering.nui.layers.ingame.DeathScreen;
import org.terasology.rendering.nui.layers.ingame.OnlinePlayersOverlay;
import org.terasology.rendering.opengl.ScreenGrabber;
import org.terasology.utilities.Assets;

/**
 * This system controls the client's in-game menus (Pause screen, Death screen, HUDs and overlays).
 */
@RegisterSystem(RegisterMode.CLIENT)
public class MenuControlSystem extends BaseComponentSystem {

    @In
    private NUIManager nuiManager;

    @Override
    public void initialise() {
        nuiManager.getHUD().addHUDElement("dropItemRegion");  //Ensure the drop region is behind the toolbar
        nuiManager.getHUD().addHUDElement("toolbar");
    }

    @ReceiveEvent(components = ClientComponent.class)
    public void onTogglePause(PauseButton event, EntityRef entity) {
        if (event.getState() == ButtonState.DOWN) {
            nuiManager.toggleScreen("engine:pauseMenu");
            event.consume();
        }
    }

    @ReceiveEvent(components = ClientComponent.class)
    public void onScreenshotCapture(ScreenshotButton event, EntityRef entity) {
        if (event.getState() == ButtonState.DOWN) {
            CoreRegistry.get(ScreenGrabber.class).takeScreenshot();
            CoreRegistry.get(AudioManager.class).playSound(Assets.getSound("engine:camera").get());
            event.consume();
        }
    }

    @ReceiveEvent(components = {ClientComponent.class})
    public void onPlayerDeath(PlayerDeathEvent event, EntityRef entity) {
        if (entity.getComponent(ClientComponent.class).local) {
            nuiManager.pushScreen("engine:deathScreen");
            if (event.damageTypeName != null) {
                ((DeathScreen) nuiManager.getScreen("engine:deathScreen")).setDeathDetails(event.instigatorName, event.damageTypeName);
            }
        }
    }

    @ReceiveEvent(components = ClientComponent.class)
    public void onShowOnlinePlayers(OnlinePlayersButton event, EntityRef entity) {
        boolean show = event.isDown();
        String onlinePlayersOverlay = "engine:onlinePlayersOverlay";

        if (show) {
            nuiManager.addOverlay(onlinePlayersOverlay, OnlinePlayersOverlay.class);
        } else {
            nuiManager.removeOverlay(onlinePlayersOverlay);
        }
        event.consume();
    }

}


text:
package com.kotcrab.vis.editor.proxy;

import com.artemis.Component;
import com.artemis.ComponentMapper;
import com.artemis.Entity;
import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.math.Rectangle;
import com.badlogic.gdx.math.Vector2;
import com.badlogic.gdx.utils.Array;
import com.badlogic.gdx.utils.IntArray;
import com.kotcrab.vis.editor.entity.EntityScheme;
import com.kotcrab.vis.editor.entity.UUIDComponent;
import com.kotcrab.vis.editor.module.scene.VisUUIDManager;
import com.kotcrab.vis.editor.module.scene.entitymanipulator.tool.PolygonTool;
import com.kotcrab.vis.editor.util.polygon.Clipper;
import com.kotcrab.vis.runtime.accessor.*;
import com.kotcrab.vis.runtime.assets.VisAssetDescriptor;
import com.kotcrab.vis.runtime.component.*;
import com.kotcrab.vis.runtime.util.UnsupportedAssetDescriptorException;

import java.util.UUID;

/** @author Kotcrab */
public abstract class EntityProxy {
	private ComponentMapper<PolygonComponent> polygonCm;

	protected Entity entity;
	protected VisUUIDManager uuidManager;
	protected UUID uuid;

	protected BasicPropertiesAccessor basicAccessor;

	protected SizePropertiesAccessor sizeAccessor;
	protected OriginPropertiesAccessor originAccessor;
	protected ScalePropertiesAccessor scaleAccessor;
	protected ColorPropertiesAccessor colorAccessor;
	protected RotationPropertiesAccessor rotationAccessor;
	protected FlipPropertiesAccessor flipAccessor;

	public EntityProxy (Entity entity) {
		this.entity = entity;
		init();

		if (entity != null) {
			uuidManager = entity.getWorld().getManager(VisUUIDManager.class);
			uuid = entity.getComponent(UUIDComponent.class).getUUID();

			polygonCm = entity.getWorld().getMapper(PolygonComponent.class);
		}
	}

	protected void init () {
		if (entity.getComponent(RenderableComponent.class) == null || entity.getComponent(LayerComponent.class) == null)
			throw new IllegalArgumentException("Proxy cannot be used for non renderable entities. Entity must contain RenderableComponent and LayerComponent");

		basicAccessor = initAccessors();
	}

	protected abstract BasicPropertiesAccessor initAccessors ();

	/** Reloads this proxy, must be called if there is chance that this entity was removed and then radded by UndoableAction. */
	public void reload () {
		entity = uuidManager.get(uuid);
		basicAccessor = initAccessors();
	}

	public EntityScheme getScheme () {
		return new EntityScheme(entity);
	}

	public void addGroup (int groupId) {
		addGroup(groupId, -1);
	}

	public void addGroup (int groupId, int parentGroupId) {
		IntArray groupIds = getGroupComponent().groupIds;
		if (groupIds.contains(groupId) == false) {
			if (parentGroupId != -1)
				groupIds.insert(groupIds.indexOf(parentGroupId), groupId);
			else
				groupIds.add(groupId);
		}
	}

	public void removeGroup (int groupId) {
		IntArray groupIds = getGroupComponent().groupIds;
		if (groupIds.contains(groupId)) groupIds.removeValue(groupId);
	}

	public int getLastGroupId () {
		GroupComponent gdc = entity.getComponent(GroupComponent.class);

		if (gdc == null || gdc.groupIds.size == 0) {
			return -1;
		}

		return gdc.groupIds.peek();
	}

	public int getGroupIdBefore (int gid) {
		IntArray groupIds = getGroupComponent().groupIds;
		int index = groupIds.indexOf(gid) - 1;

		if (index < 0)
			return -1;
		else
			return groupIds.get(index);
	}

	public boolean groupsContains (int gid) {
		return getGroupComponent().groupIds.contains(gid);
	}

	public IntArray getGroupsIds () {
		return new IntArray(getGroupComponent().groupIds);
	}

	private GroupComponent getGroupComponent () {
		GroupComponent gdc = entity.getComponent(GroupComponent.class);

		if (gdc == null) {
			gdc = new GroupComponent();
			entity.edit().add(gdc);
		}

		return gdc;
	}

	public String getId () {
		IDComponent idc = entity.getComponent(IDComponent.class);
		if (idc != null)
			return idc.id;
		else
			return null;
	}

	public void setId (String id) {
		IDComponent idc = entity.getComponent(IDComponent.class);

		if (idc != null)
			idc.id = id;
		else
			entity.edit().add(new IDComponent(id));
	}

	public boolean hasComponent (Class<? extends Component> clazz) {
		return entity.getComponent(clazz) != null;
	}

	public int getZIndex () {
		return entity.getComponent(RenderableComponent.class).zIndex;
	}

	public void setZIndex (int zIndex) {
		entity.getComponent(RenderableComponent.class).zIndex = zIndex;
	}

	public int getLayerID () {
		return entity.getComponent(LayerComponent.class).layerId;
	}

	public void setLayerId (int layerId) {
		entity.getComponent(LayerComponent.class).layerId = layerId;
	}

	//basic properties

	public float getX () {
		return basicAccessor.getX();
	}

	public void setX (float x) {
		updatePolygon(x, getY());
		basicAccessor.setX(x);
	}

	public float getY () {
		return basicAccessor.getY();
	}

	public void setY (float y) {
		updatePolygon(getX(), y);
		basicAccessor.setY(y);
	}

	public void setPosition (float x, float y) {
		updatePolygon(x, y);
		basicAccessor.setPosition(x, y);
	}

	protected void updatePolygon (float x, float y) {
		PolygonComponent polygon = polygonCm.getSafe(entity);
		float dx = getX() - x;
		float dy = getY() - y;
		if (polygon != null) {
			for (Vector2 vertex : polygon.vertices) {
				vertex.sub(dx, dy);
			}

			polygon.faces = Clipper.polygonize(PolygonTool.DEFAULT_POLYGONIZER, polygon.vertices.toArray(Vector2.class));
		}
	}

	public float getWidth () {
		return basicAccessor.getWidth();
	}

	public float getHeight () {
		return basicAccessor.getHeight();
	}

	public Rectangle getBoundingRectangle () {
		return basicAccessor.getBoundingRectangle();
	}

	//resize properties

	protected void enableResize (SizePropertiesAccessor sizeAccessor) {
		this.sizeAccessor = sizeAccessor;
	}

	public boolean isResizeSupported () {
		return sizeAccessor != null;
	}

	public void setSize (float width, float height) {
		sizeAccessor.setSize(width, height);
	}

	//origin properties

	protected void enableOrigin (OriginPropertiesAccessor originAccessor) {
		this.originAccessor = originAccessor;
	}

	public boolean isOriginSupported () {
		return originAccessor != null;
	}

	public float getOriginX () {
		return originAccessor.getOriginX();
	}

	public float getOriginY () {
		return originAccessor.getOriginY();
	}

	public void setOrigin (float x, float y) {
		originAccessor.setOrigin(x, y);
	}

	//scale properties

	protected void enableScale (ScalePropertiesAccessor scaleAccessor) {
		this.scaleAccessor = scaleAccessor;
	}

	public boolean isScaleSupported () {
		return scaleAccessor != null;
	}

	public float getScaleX () {
		return scaleAccessor.getScaleX();
	}

	public float getScaleY () {
		return scaleAccessor.getScaleY();
	}

	public void setScale (float x, float y) {
		scaleAccessor.setScale(x, y);
	}

	//color properties

	protected void enableColor (ColorPropertiesAccessor colorAccessor) {
		this.colorAccessor = colorAccessor;
	}

	public boolean isColorSupported () {
		return colorAccessor != null;
	}

	public Color getColor () {
		return colorAccessor.getColor();
	}

	public void setColor (Color color) {
		colorAccessor.setColor(color);
	}

	//rotation properties

	protected void enableRotation (RotationPropertiesAccessor rotationAccessor) {
		this.rotationAccessor = rotationAccessor;
	}

	public boolean isRotationSupported () {
		return rotationAccessor != null;
	}

	public float getRotation () {
		return rotationAccessor.getRotation();
	}

	public void setRotation (float rotation) {
		rotationAccessor.setRotation(rotation);
	}

	//flip properties

	protected void enableFlip (FlipPropertiesAccessor flipAccessor) {
		this.flipAccessor = flipAccessor;
	}

	public boolean isFlipSupported () {
		return flipAccessor != null;
	}

	public boolean isFlipX () {
		return flipAccessor.isFlipX();
	}

	public boolean isFlipY () {
		return flipAccessor.isFlipY();
	}

	public void setFlip (boolean x, boolean y) {
		flipAccessor.setFlip(x, y);
	}

	//others

	public abstract String getEntityName ();

	VisAssetDescriptor getAssetDescriptor () {
		return entity.getComponent(AssetComponent.class).asset;
	}

	public void setAssetDescriptor (VisAssetDescriptor asset) {
		checkAssetDescriptor(asset);

		AssetComponent adc = entity.getComponent(AssetComponent.class);

		if (adc != null)
			adc.asset = asset;
		else
			entity.edit().add(new AssetComponent(asset));
	}

	public void checkAssetDescriptor (VisAssetDescriptor assetDescriptor) {
		if (isAssetsDescriptorSupported(assetDescriptor) == false)
			throw new UnsupportedAssetDescriptorException(assetDescriptor);
	}

	protected abstract boolean isAssetsDescriptorSupported (VisAssetDescriptor assetDescriptor);

	public Array<Entity> getEntities () {
		Array<Entity> entities = new Array<>(1);
		entities.add(entity);
		return entities;
	}

	public boolean compareProxyByID (EntityProxy other) {
		return uuid.equals(other.uuid);
	}
}


text:
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

def plot_rolling_percentile(start_end, values, label=None,
                            batch_window_size=128, percentile=(1, 99),
                            percentile_alpha=0.5,
                            ax=None, color=None, **kwargs):
    start, end = start_end
    if ax is None:
        ax = plt

    rolling_args = {
        'window': batch_window_size,
        'min_periods': 0,
        'center': True
    }
    rolling = pd.Series(values).rolling(**rolling_args)
    means = rolling.mean()

    epoch_labels = np.linspace(start, end, len(means))
    base_line, = ax.plot(epoch_labels, means, label=label, color=color, **kwargs)
    if percentile is not None:
        upper = pd.Series(rolling.apply(np.percentile, args=[percentile[1]]))
        upper = upper.rolling(**rolling_args).mean()
        lower = pd.Series(rolling.apply(np.percentile, args=[percentile[0]]))
        lower = lower.rolling(**rolling_args).mean()
        ax.fill_between(epoch_labels, lower, upper,
                        facecolor=base_line.get_color(), alpha=percentile_alpha)


text:
[![CI Status](http://img.shields.io/travis/leoMobileDeveloper/LeoMaskAnimationKit.svg?style=flat)](https://travis-ci.org/leoMobileDeveloper/LeoMaskAnimationKit)
[![Version](https://img.shields.io/cocoapods/v/LeoMaskAnimationKit.svg?style=flat)](http://cocoapods.org/pods/LeoMaskAnimationKit)
[![License](https://img.shields.io/cocoapods/l/LeoMaskAnimationKit.svg?style=flat)](http://cocoapods.org/pods/LeoMaskAnimationKit)
[![Platform](https://img.shields.io/cocoapods/p/LeoMaskAnimationKit.svg?style=flat)](http://cocoapods.org/pods/LeoMaskAnimationKit)

##Gif

With the methods,you can easy create a tableview cell like this

## Requirements

- ARC

## Installation

LeoMaskAnimationKit is available through [CocoaPods](http://cocoapods.org). To install
it, simply add the following line to your Podfile:

```ruby
pod "LeoMaskAnimationKit"
```
## How to use

Should in same coordinate when using mask

Gradient mask

```
- (void)leo_animateGradienDuration:(NSTimeInterval)duration
                             delay:(NSTimeInterval)delay
                           options:(LeoMaskAnimationOptions)options
                       compeletion:(void(^)(void))completion;
```
Circle view mask

```
-(void)leo_animateCircleMaskWithduration:(NSTimeInterval)duration
                                   delay:(NSTimeInterval)delay
                               clockwise:(BOOL)clockwise
                                 options:(LeoMaskAnimationOptions)options
                             compeletion:(void(^)(void))completion;
```
Mask a view from any direction

```
-(void)leo_animateRectExpandDirection:(LeoMaskAnimationDirections)directions
                             duration:(NSTimeInterval)duration
                                delay:(NSTimeInterval)delay
                              options:(LeoMaskAnimationOptions)options
                          compeletion:(void(^)(void))completion;
```

Mask between rects

```
-(void)leo_animateMaskFromRect:(CGRect)fromRect
                    toRect:(CGRect)toRect
                  duration:(NSTimeInterval)duration
                     delay:(NSTimeInterval)delay
                       options:(LeoMaskAnimationOptions)options
                   compeletion:(void(^)(void))completion;
```

Mask between path

```

-(void)leo_animateMaskFromPath:(UIBezierPath *)fromPath
                    toPath:(UIBezierPath *)toPath
                  duration:(NSTimeInterval)duration
                     delay:(NSTimeInterval)delay
                       options:(LeoMaskAnimationOptions)options
                   compeletion:(void(^)(void))completion;
```

## Author

leoMobileDeveloper, leomobiledeveloper@gmail.com

## License

LeoMaskAnimationKit is available under the MIT license. See the LICENSE file for more info.


text:
using GGProductions.LetterStorm.Data.Collections;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;

namespace Test.GGProductions.LetterStorm.Data.Collections
{
    [TestClass]
    public class LessonCollectionTests
    {
        [TestMethod]
        public void GetLessonByIdTest()
        {
            // Create a new lesson collection and three lessons
            LessonCollection lessonCollection = new LessonCollection();
            Lesson testLesson1 = new Lesson("testLesson1");
            Lesson testLesson2 = new Lesson("testLesson2");
            Lesson testLesson3 = new Lesson("testLesson3");

            // Add the lessons to the lesson collection
            lessonCollection.Add(testLesson1);
            lessonCollection.Add(testLesson2);
            lessonCollection.Add(testLesson3);

            // Verify the three lessons can be retrieved by their IDs
            Assert.AreEqual(testLesson3.Name, lessonCollection.GetLessonById(testLesson3.ID).Name);
            Assert.AreEqual(testLesson2.Name, lessonCollection.GetLessonById(testLesson2.ID).Name);
            Assert.AreEqual(testLesson1.Name, lessonCollection.GetLessonById(testLesson1.ID).Name);
        }
    }
}


text:
<!DOCTYPE html>

   <title>CSS Animations - changing animation-name during animation</title>
   <link rel="author" title="Opera Software ASA" href="http://www.opera.com/">
   <link rel="help" href="http://dev.w3.org/csswg/css3-animations/#animations">
   <meta name="flags" content="dom">
   <meta name="assert" content="Changing the value of 'animation-name' does not
   necessarily restart an animation">

The square below should slide right exactly one time, switching color
   abruptly while moving.

Testing...


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

namespace PrintHost.model.geom
{
    public class TopoEdge
    {
        public TopoVertex v1;
        public TopoVertex v2;
        public LinkedList<TopoTriangle> faces = new LinkedList<TopoTriangle>();
        public int algHelper;

        public TopoEdge(TopoVertex _v1, TopoVertex _v2)
        {
            v1 = _v1;
            v2 = _v2;
        }
        public bool isBuildOf(TopoVertex _v1, TopoVertex _v2)
        {
            return (v1 == _v1 && v2 == _v2) || (v1 == _v2 && v2 == _v1);
        }
        public int connectedFaces
        {
            get { return faces.Count; }
        }
        public void connectFace(TopoTriangle face)
        {
            faces.AddLast(face);
        }
        public void disconnectFace(TopoTriangle face,TopoModel model)
        {
            faces.Remove(face);
            if (faces.Count == 0)
                model.edges.Remove(this);
        }
        public void MarkConnectedFacesBad()
        {
            foreach (TopoTriangle triangle in faces)
                triangle.bad = true;
        }
        public double DihedralAngle()
        {
            if (faces.Count != 2) throw new Exception("DihedralAngle requires edge with 2 faces");
            return faces.First.Value.normal.AngleForNormalizedVectors(faces.Last.Value.normal);
        }
        public bool ContainsVertex(TopoVertex v)
        {
            return v1==v || v2==v;
        }
        public List<TopoEdge> FindNeighbourEdgesWithOneFace()
        {
            List<TopoEdge> list = null;
            TopoTriangle thisFace = faces.First.Value;
            foreach (TopoTriangle face in v1.connectedFacesList)
            {
                if (face == thisFace) continue;
                for (int e = 0; e < 3; e++)
                {
                    TopoEdge testEdge = face.edges[e];
                    if(testEdge.connectedFaces!=1) continue;
                    if (testEdge.ContainsVertex(v1))
                    {
                        if (list == null) list = new List<TopoEdge>();
                        list.Add(testEdge);
                    }
                }
            }
            foreach (TopoTriangle face in v2.connectedFacesList)
            {
                if (face == thisFace) continue;
                for (int e = 0; e < 3; e++)
                {
                    TopoEdge testEdge = face.edges[e];
                    if (testEdge.connectedFaces != 1) continue;
                    if (testEdge.ContainsVertex(v2))
                    {
                        if (list == null) list = new List<TopoEdge>();
                        list.Add(testEdge);
                    }
                }
            }
            return list;
        }
        public double EdgeLength
        {
            get { return v1.pos.Subtract(v2.pos).Length; }
        }
        public TopoTriangle GetFaceExcept(TopoTriangle notThis)
        {
            foreach (TopoTriangle test in faces)
            {
                if (test != notThis)
                    return test;
            }
            return null;
        }
        /// <summary>
        /// Splits an edge and changes the connected triangles to maintain
        /// a topological correct system.
        /// </summary>
        /// <param name="model"></param>
        /// <param name="vertex"></param>
        public void InsertVertex(TopoModel model,TopoVertex vertex) {
            LinkedList<TopoTriangle> delList = new LinkedList<TopoTriangle>();
            LinkedList<TopoTriangle> testFaces = new LinkedList<TopoTriangle>();
            foreach (TopoTriangle oldTriangle in faces)
                testFaces.AddLast(oldTriangle);
            foreach (TopoTriangle oldTriangle in testFaces)
            {
                delList.AddLast(oldTriangle);
                for (int i = 0; i < 3; i++)
                {
                    if (oldTriangle.vertices[i] != v1 && oldTriangle.vertices[i] != v2)
                    {
                        TopoTriangle newTriangle = new TopoTriangle(model, v1, vertex, oldTriangle.vertices[i]);
                        if (newTriangle.IsDegenerated())
                            newTriangle.Unlink(model);
                        else
                        {
                            // Test orientation
                            for (int e = 0; e < 3; e++)
                            {
                                TopoTriangle neigbour = newTriangle.edges[i].GetFaceExcept(newTriangle);
                                if (neigbour != null)
                                {
                                    if(!newTriangle.SameNormalOrientation(neigbour))
                                        newTriangle.FlipDirection();
                                    break;
                                }
                            }
                            model.AddTriangle(newTriangle);
                        }
                        newTriangle = new TopoTriangle(model, vertex, v2, oldTriangle.vertices[i]);
                        if (newTriangle.IsDegenerated())
                            newTriangle.Unlink(model);
                        else
                        {
                            // Test orientation
                            for (int e = 0; e < 3; e++)
                            {
                                TopoTriangle neigbour = newTriangle.edges[i].GetFaceExcept(newTriangle);
                                if (neigbour != null)
                                {
                                    if (!newTriangle.SameNormalOrientation(neigbour))
                                        newTriangle.FlipDirection();
                                    break;
                                }
                            }
                            model.AddTriangle(newTriangle);
                        }
                    }
                }
            }
            foreach (TopoTriangle tri in delList)
            {
                tri.Unlink(model);
                model.removeTriangle(tri);
            }
        }
        public TopoTriangle FirstTriangle
        {
            get
            {
                if (faces.Count == 0) return null;
                return faces.First.Value;
            }
        }
        public bool ProjectPoint(RHVector3 p, out double lambda, RHVector3 pProjected)
        {
            RHVector3 u = v2.pos.Subtract(v1.pos);
            lambda = p.Subtract(v1.pos).ScalarProduct(u)/u.ScalarProduct(u);
            pProjected.x = v1.pos.x + lambda * u.x;
            pProjected.y = v1.pos.y + lambda * u.y;
            pProjected.z = v1.pos.z + lambda * u.z;
            return lambda >= 0 && lambda <= 1;
        }
        public TopoVertex this[int pos]
        {
            get
            {
                if (pos == 0) return v1;
                else return v2;
            }
        }
        public override string ToString()
        {
            return "Edge(" + connectedFaces + ") = [" + v1.pos + "," + v2.pos + "]";
        }
    }

    public class TopoEdgePair: IComparer<TopoEdgePair>,IComparable<TopoEdgePair>
    {
        public TopoEdge edgeA, edgeB;
        public double alphaBeta; // Sum of dihedral angles to a virtual shared triangle

        public TopoEdgePair(TopoEdge _edgeA, TopoEdge _edgeB)
        {
            edgeA = _edgeA;
            edgeB = _edgeB;
            RHVector3 sharedPoint = null;
            RHVector3 p1 = null, p2 = null;
            if (edgeA.v1 == edgeB.v1)
            {
                sharedPoint = edgeA.v1.pos;
                p1 = edgeA.v2.pos;
                p2 = edgeB.v2.pos;
            }
            else if (edgeA.v1 == edgeB.v2)
            {
                sharedPoint = edgeA.v1.pos;
                p1 = edgeA.v2.pos;
                p2 = edgeB.v1.pos;
            }
            else if (edgeA.v2 == edgeB.v1)
            {
                sharedPoint = edgeA.v1.pos;
                p1 = edgeA.v1.pos;
                p2 = edgeB.v2.pos;
            }
            else if (edgeA.v2 == edgeB.v2)
            {
                sharedPoint = edgeA.v2.pos;
                p1 = edgeA.v1.pos;
                p2 = edgeB.v1.pos;
            }
            RHVector3 d1 = p1.Subtract(sharedPoint);
            RHVector3 d2 = p2.Subtract(sharedPoint);
            RHVector3 normal = d1.CrossProduct(d2);
            normal.NormalizeSafe();
            alphaBeta = normal.AngleForNormalizedVectors(edgeA.faces.First.Value.normal) + normal.AngleForNormalizedVectors(edgeB.faces.First.Value.normal);
            if (alphaBeta > Math.PI) // normal was wrong direction
                alphaBeta = 2 * Math.PI - alphaBeta;
        }
        public bool ContainsEdge(TopoEdge edge)
        {
            return edgeA == edge || edgeB == edge;
        }
        public bool ContainsEdgePair(TopoEdge a, TopoEdge b)
        {
            return ContainsEdge(a) && ContainsEdge(b);
        }
        public static bool ContainsListPair(List<TopoEdgePair> list, TopoEdge a, TopoEdge b)
        {
            foreach (TopoEdgePair pair in list)
            {
                if (pair.ContainsEdgePair(a, b)) return true;
            }
            return false;
        }
        public TopoEdge CommonThirdEdge()
        {
            TopoVertex v1 = edgeA.v1;
            if (edgeB.v1 == v1 || edgeB.v2 == v1)
                v1 = edgeA.v2;
            TopoVertex v2 = edgeB.v1;
            if (edgeA.v1 == v2 || edgeA.v2 == v2)
                v2 = edgeB.v2;
            foreach (TopoTriangle t in v1.connectedFacesList)
            {
                TopoEdge e = t.EdgeWithVertices(v1, v2);
                if (e != null)
                    return e;
            }
            return null;
        }
        public TopoTriangle BuildTriangle(TopoModel model)
        {
            TopoVertex sharedPoint = null;
            TopoVertex p1 = null, p2 = null;
            if (edgeA.v1 == edgeB.v1)
            {
                sharedPoint = edgeA.v1;
                p1 = edgeA.v2;
                p2 = edgeB.v2;
            }
            else if (edgeA.v1 == edgeB.v2)
            {
                sharedPoint = edgeA.v1;
                p1 = edgeA.v2;
                p2 = edgeB.v1;
            }
            else if (edgeA.v2 == edgeB.v1)
            {
                sharedPoint = edgeA.v1;
                p1 = edgeA.v1;
                p2 = edgeB.v2;
            }
            else if (edgeA.v2 == edgeB.v2)
            {
                sharedPoint = edgeA.v2;
                p1 = edgeA.v1;
                p2 = edgeB.v1;
            }
            TopoTriangle faceA = edgeA.faces.First.Value;
            TopoTriangle newTriangle = new TopoTriangle(model, sharedPoint, p1, p2, 0, 0, 1);
            if (newTriangle.SameNormalOrientation(faceA) == false)
                newTriangle.FlipDirection();
            newTriangle.RecomputeNormal();
            model.AddTriangle(newTriangle);
            return newTriangle;
        }
        public int Compare(TopoEdgePair pair1, TopoEdgePair pair2)
        {
            int returnValue = 1;
            if (pair1 != null && pair2 == null)
            {
                returnValue = 0;
            }
            else if (pair1 == null && pair2 != null)
            {
                returnValue = 0;
            }
            else if (pair1 != null && pair2 != null)
            {
                returnValue = pair1.alphaBeta.CompareTo(pair2.alphaBeta);
            }
            return returnValue;
        }
        public bool Valid()
        {
            return edgeA.connectedFaces == 1 && edgeB.connectedFaces == 1;
        }
        public int CompareTo(TopoEdgePair pair)
        {
            return Compare(this, pair);
        }
        public override string ToString()
        {
            return "EdgePair:" + edgeA + " - " + edgeB+" ab = "+alphaBeta;
        }
    }
}


text:
var fs = require('fs'),
    headline = require('./headline'),
    article = require('./article'),
    bcrypt = require('bcrypt');

function authenticateRequest(req, options){
  bcrypt.compare(req.body.pass, process.env.SEED_UPLOAD_PASS_HASH, function(err, response){
    if(!response){
      if(options && options.error){
        options.error();
      }
    }else{
      if(options && options.success){
        options.success();
      }
    }
  });
}

exports.uploadImage = function(req, res){
  req.pipe(req.busboy);
  req.busboy.on('file', function(fieldname, file, filename, encoding, mimetype){
    var fstream = fs.createWriteStream(__dirname + '/../../../assets/imgs/content/' + filename);
    var fstream2 = fs.createWriteStream(__dirname + '/../../../public/imgs/content/' + filename);
    file.pipe(fstream);
    file.pipe(fstream2);
    fstream.on('close', function(){
      fstream2.on('close', function(){
        res.status(200).json({'msg': 'success'});
      });
    });
  });
};
exports.uploadArticle = function(req, res){
  authenticateRequest(req, {success: function(){
    article.upload(req.body, function(err, data){
      if(!err){
        res.status(200).json({'msg': 'success'});
      }else{
        res.status(500).json({'err': err});
      }
    });
  }, error: function(){
    res.status(500).json({'err': 'invalid_pass'});
  }});
};
exports.uploadHeadline = function(req, res){
  authenticateRequest(req, {success: function(){
    headline.upload(req.body, function(err, data){
      if(!err){
        res.status(200).json({'msg': 'success'});
      }else{
        res.status(500).json({'err': err});
      }
    });
  }, error: function(){
    res.status(500).json({'err': 'invalid_pass'});
  }});
};


text:
#include <unistd.h>
#include <stdio.h>
#include <signal.h>

#include <ppd42ns.h>

int shouldRun = true;

void sig_handler(int signo)
{
    if (signo == SIGINT)
        shouldRun = false;
}

int main()
{
    signal(SIGINT, sig_handler);

//! [Interesting]
    // Instantiate a dust sensor on GPIO pin D8
    ppd42ns_context dust = ppd42ns_init(8);

    ppd42ns_dust_data data;
    printf("This program will give readings every 30 seconds until "
           "you stop it\n");

    while (shouldRun)
    {
        data = ppd42ns_get_data(dust);
        printf("Low pulse occupancy: %d\n", data.lowPulseOccupancy);
        printf("Ratio: %f\n", data.ratio);
        printf("Concentration: %f\n\n", data.concentration);
    }

    printf("Exiting...\n");

    ppd42ns_close(dust);

//! [Interesting]
    return 0;
}


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

namespace SpeechApp
{
    public class LUISResponse
    {
        public string query { get; set; }
        public lIntent[] intents { get; set; }
        public lEntity[] entities { get; set; }
    }

    public class lIntent
    {
        public string intent { get; set; }
        public float score { get; set; }
    }

    public class lEntity
    {
        public string entity { get; set; }
        public string type { get; set; }
        public int startIndex { get; set; }
        public int endIndex { get; set; }
        public float score { get; set; }
    }
}


text:
from unittest import mock
import uuid

from cinder import context
from cinder.tests.functional.api import client
from cinder.tests.functional import functional_helpers

class DefaultVolumeTypesTest(functional_helpers._FunctionalTestBase):
    _vol_type_name = 'functional_test_type'
    _osapi_version = '3.62'

    def setUp(self):
        super(DefaultVolumeTypesTest, self).setUp()
        self.volume_type = self.api.create_type(self._vol_type_name)
        self.project = self.FakeProject()
        # Need to mock out Keystone so the functional tests don't require other
        # services
        _keystone_client = mock.MagicMock()
        _keystone_client.version = 'v3'
        _keystone_client.projects.get.side_effect = self._get_project
        _keystone_client_get = mock.patch(
            'cinder.api.api_utils._keystone_client',
            lambda *args, **kwargs: _keystone_client)
        _keystone_client_get.start()
        self.addCleanup(_keystone_client_get.stop)

    def _get_project(self, project_id, *args, **kwargs):
        return self.project

    class FakeProject(object):
        def __init__(self, name=None):
            self.id = uuid.uuid4().hex
            self.name = name
            self.description = 'fake project description'
            self.domain_id = 'default'

    @mock.patch.object(context.RequestContext, 'authorize')
    def test_default_type_set(self, mock_authorize):
        default_type = self.api.set_default_type(
            self.project.id, {'volume_type': self._vol_type_name})
        self.assertEqual(self.project.id, default_type['project_id'])
        self.assertEqual(self.volume_type['id'],
                         default_type['volume_type_id'])

    @mock.patch.object(context.RequestContext, 'authorize')
    def test_default_type_get(self, mock_authorize):
        self.api.set_default_type(self.project.id,
                                  {'volume_type': self._vol_type_name})
        default_type = self.api.get_default_type(project_id=self.project.id)

        self.assertEqual(self.project.id, default_type['project_id'])
        self.assertEqual(self.volume_type['id'],
                         default_type['volume_type_id'])

    @mock.patch.object(context.RequestContext, 'authorize')
    def test_default_type_get_all(self, mock_authorize):
        self.api.set_default_type(self.project.id,
                                  {'volume_type': self._vol_type_name})
        default_types = self.api.get_default_type()

        self.assertEqual(1, len(default_types))
        self.assertEqual(self.project.id, default_types[0]['project_id'])
        self.assertEqual(self.volume_type['id'],
                         default_types[0]['volume_type_id'])

    @mock.patch.object(context.RequestContext, 'authorize')
    def test_default_type_unset(self, mock_authorize):
        self.api.set_default_type(self.project.id,
                                  {'volume_type': self._vol_type_name})

        default_types = self.api.get_default_type()
        self.assertEqual(1, len(default_types))
        self.api.unset_default_type(self.project.id)
        default_types = self.api.get_default_type()
        self.assertEqual(0, len(default_types))

    @mock.patch.object(context.RequestContext, 'authorize')
    def test_default_type_set_volume_type_not_found(self, mock_authorize):
        self.assertRaises(client.OpenStackApiException400,
                          self.api.set_default_type,
                          self.project.id,
                          {'volume_type': 'fake_type'})

    @mock.patch.object(context.RequestContext, 'authorize')
    def test_cannot_delete_project_default_type(self, mock_authorize):
        default_type = self.api.set_default_type(
            self.project.id, {'volume_type': self._vol_type_name})
        self.assertRaises(client.OpenStackApiException400,
                          self.api.delete_type,
                          default_type['volume_type_id'])


text:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>thecarlhall.broke</groupId>
    <artifactId>base</artifactId>
    <packaging>pom</packaging>
    <version>1.0-SNAPSHOT</version>
    <name>Broke application base</name>
    <build>
        <plugins>
            <plugin>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.1</version>
                <configuration>
                    <source>1.7</source>
                    <target>1.7</target>
                </configuration>
            </plugin>
        </plugins>
    </build>
    <dependencies>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.9</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-api</artifactId>
            <version>1.7.5</version>
        </dependency>
    </dependencies>
    <modules>
        <module>parsers</module>
        <module>web</module>
    </modules>
</project>


text:
<!DOCTYPE html>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <link href="../css/print.css" rel="stylesheet" type="text/css" media="print">

  <meta name="description" content="Documentation for the chrome.experimental.serial module, which is part of the Google Chrome  extension APIs."><title>chrome.experimental.serial - Google Chrome Extensions - Google Code</title>
    <link href="../css/ApiRefStyles.css" rel="stylesheet" type="text/css">
  <link href="../css/shared.css" rel="stylesheet" type="text/css">

    You are viewing extension docs in chrome via the 'file:' scheme: are you expecting to see local changes when you refresh? You'll need run chrome with --allow-file-access-from-files.

    WARNING: This is the BETA documentation.
    It may not work with the stable release of Chrome.
    <select id="branchChooser">
      <option>Choose a different version...
      </option><option value="">Stable
      </option><option value="beta">Beta
      </option><option value="dev">Dev
      </option><option value="trunk">Trunk
    </option></select>

    WARNING: This is unofficial documentation. It may not work with the
    current release of Chrome.
    <button id="goToOfficialDocs">Go to the official docs</button>

      Skip to page content
      Skip to main navigation

          <form action="http://www.google.com/cse" id="cse" style="margin-top:0.5em">

              <input type="hidden" name="cx" value="002967670403910741006:61_cvzfqtno">
              <input type="hidden" name="ie" value="UTF-8">
              <input type="text" name="q" value="" size="55">
              <input class="gsc-search-button" type="submit" name="sa" value="Search">

              e.g. "page action" or "tabs"

          </form>

Google Chrome Extensions (Labs)

            Home

            Docs

            FAQ

            Samples

            Group

            Questions?

Getting Started

Overview

What's New?

Developer's Guide

Browser UI

Browser Actions

Context Menus

Desktop Notifications

Omnibox

Options Pages

Override Pages

Page Actions

Browser Interaction

Bookmarks

Cookies

Developer Tools

Events

History

Management

Tabs

Windows

Implementation

Accessibility

Background Pages

Content Scripts

Cross-Origin XHR

Internationalization

Message Passing

Optional Permissions

NPAPI Plugins

Finishing

Hosting

Other Deployment Options

Packaged Apps

Tutorials

Debugging

Google Analytics

OAuth

Reference

Formats

Manifest Files

Match Patterns

Permission Warnings

chrome.* APIs

Other APIs

Samples

More

Chrome Web Store

Hosted Apps

Themes

chrome.experimental.serial

Contents

                API reference: chrome.experimental.serial

            Methods

                close

                flush

                getControlSignals

                getPorts

                open

                read

                setControlSignals

                write

            Types

                OpenOptions

                OpenInfo

                ReadInfo

                WriteInfo

                ControlSignalOptions

          For information on how to use experimental APIs, see the chrome.experimental.* APIs page.

API reference: chrome.experimental.serial

Methods

close

                  chrome.experimental.serial.close(integer
                      <var>connectionId</var>, function
                      <var>CloseCallback</var>)

Closes an open connection.

Parameters

            <var>connectionId</var>

                  (

                        integer

                  )

The id of the opened connection.

            <var>CloseCallback</var>

                  (

                        function

                  )

Returns true if operation was successful.

Parameters

            <var>result</var>

                  (

                        boolean

                  )

            Undocumented.

Callback function

                    The callback parameter should specify a function
                    that looks like this:

function(boolean result) {...};

            <var>result</var>

                  (

                        boolean

                  )

            Undocumented.

flush

                  chrome.experimental.serial.flush(integer
                      <var>connectionId</var>, function
                      <var>FlushCallback</var>)

Flushes all bytes in the given connection's input and output buffers.

Parameters

            <var>connectionId</var>

                  (

                        integer

                  )

The id of the connection.

            <var>FlushCallback</var>

                  (

                        function

                  )

Returns true if operation was successful.

Parameters

            <var>result</var>

                  (

                        boolean

                  )

            Undocumented.

Callback function

                    The callback parameter should specify a function
                    that looks like this:

function(boolean result) {...};

            <var>result</var>

                  (

                        boolean

                  )

            Undocumented.

getControlSignals

                  chrome.experimental.serial.getControlSignals(integer
                      <var>connectionId</var>, function
                      <var>GetControlSignalsCallback</var>)

Parameters

            <var>connectionId</var>

                  (

                        integer

                  )

            Undocumented.

            <var>GetControlSignalsCallback</var>

                  (

                        function

                  )

Returns a snapshot of current control signals.

Parameters

            <var>options</var>

                  (

                        experimental.serial.ControlSignalOptions

                  )

            Undocumented.

Callback function

                    The callback parameter should specify a function
                    that looks like this:

function(experimental.serial.ControlSignalOptions options) {...};

            <var>options</var>

                  (

                        experimental.serial.ControlSignalOptions

                  )

            Undocumented.

getPorts

                  chrome.experimental.serial.getPorts(function
                      <var>GetPortsCallback</var>)

Returns names of valid ports on this machine, each of which is likely to be valid to pass as the port argument to open(). The list is regenerated each time this method is called, as port validity is dynamic.

Parameters

            <var>GetPortsCallback</var>

                  (

                        function

                  )

            Undocumented.

Parameters

            <var>ports</var>

                  (

                          array of

                        string

                  )

            Undocumented.

Callback function

                    The callback parameter should specify a function
                    that looks like this:

function(array of string ports) {...};

            <var>ports</var>

                  (

                          array of

                        string

                  )

            Undocumented.

open

                  chrome.experimental.serial.open(string
                      <var>port</var>, experimental.serial.OpenOptions
                      <var>options</var>, function
                      <var>OpenCallback</var>)

Opens a connection to the given serial port.

Parameters

            <var>port</var>

                  (

                        string

                  )

The name of the serial port to open.

            <var>options</var>

                  (
                    optional

                        experimental.serial.OpenOptions

                  )

Connection options.

            <var>OpenCallback</var>

                  (

                        function

                  )

            Undocumented.

Parameters

            <var>openInfo</var>

                  (

                        experimental.serial.OpenInfo

                  )

            Undocumented.

Callback function

                    The callback parameter should specify a function
                    that looks like this:

function(experimental.serial.OpenInfo openInfo) {...};

            <var>openInfo</var>

                  (

                        experimental.serial.OpenInfo

                  )

            Undocumented.

read

                  chrome.experimental.serial.read(integer
                      <var>connectionId</var>, function
                      <var>ReadCallback</var>)

Reads a byte from the given connection.

Parameters

            <var>connectionId</var>

                  (

                        integer

                  )

The id of the connection.

            <var>ReadCallback</var>

                  (

                        function

                  )

            Undocumented.

Parameters

            <var>readInfo</var>

                  (

                        experimental.serial.ReadInfo

                  )

            Undocumented.

Callback function

                    The callback parameter should specify a function
                    that looks like this:

function(experimental.serial.ReadInfo readInfo) {...};

            <var>readInfo</var>

                  (

                        experimental.serial.ReadInfo

                  )

            Undocumented.

setControlSignals

                  chrome.experimental.serial.setControlSignals(integer
                      <var>connectionId</var>, experimental.serial.ControlSignalOptions
                      <var>options</var>, function
                      <var>SetControlSignalsCallback</var>)

Parameters

            <var>connectionId</var>

                  (

                        integer

                  )

            Undocumented.

            <var>options</var>

                  (

                        experimental.serial.ControlSignalOptions

                  )

            Undocumented.

            <var>SetControlSignalsCallback</var>

                  (

                        function

                  )

Returns true if operation was successful.

Parameters

            <var>result</var>

                  (

                        boolean

                  )

            Undocumented.

Callback function

                    The callback parameter should specify a function
                    that looks like this:

function(boolean result) {...};

            <var>result</var>

                  (

                        boolean

                  )

            Undocumented.

write

                  chrome.experimental.serial.write(integer
                      <var>connectionId</var>, ArrayBuffer
                      <var>data</var>, function
                      <var>WriteCallback</var>)

Writes a string to the given connection.

Parameters

            <var>connectionId</var>

                  (

                        integer

                  )

The id of the connection.

            <var>data</var>

                  (

                        ArrayBuffer

                  )

The string to write.

            <var>WriteCallback</var>

                  (

                        function

                  )

            Undocumented.

Parameters

            <var>writeInfo</var>

                  (

                        experimental.serial.WriteInfo

                  )

            Undocumented.

Callback function

                    The callback parameter should specify a function
                    that looks like this:

function(experimental.serial.WriteInfo writeInfo) {...};

            <var>writeInfo</var>

                  (

                        experimental.serial.WriteInfo

                  )

            Undocumented.

Types

experimental.serial.OpenOptions

                  (

                        object

                  )

            Undocumented.

            <var>bitrate</var>

                  (

                        integer

                  )

The requested bitrate of the connection to be opened. For compatibility with the widest range of hardware, this number should match one of commonly-available bitrates, such as 110, 300, 1200, 2400, 4800, 9600, 14400, 19200, 38400, 57600, 115200. There is no guarantee, of course, that the device connected to the serial port will support the requested bitrate, even if the port itself supports that bitrate.

experimental.serial.OpenInfo

                  (

                        object

                  )

            Undocumented.

            <var>connectionId</var>

                  (

                        integer

                  )

The id of the opened connection.

experimental.serial.ReadInfo

                  (

                        object

                  )

            Undocumented.

            <var>bytesRead</var>

                  (

                        integer

                  )

The number of bytes received, or a negative number if an error occurred.

            <var>data</var>

                  (

                        ArrayBuffer

                  )

The data received.

experimental.serial.WriteInfo

                  (

                        object

                  )

            Undocumented.

            <var>bytesWritten</var>

                  (

                        integer

                  )

The number of bytes written.

experimental.serial.ControlSignalOptions

                  (

                        object

                  )

            Undocumented.

            <var>cts</var>

                  (
                    optional

                        boolean

                  )

            Undocumented.

            <var>dcd</var>

                  (
                    optional

                        boolean

                  )

Serial control signals that your machine can receive. If a get operation fails, success will be false, and these fields will be absent. DCD (Data Carrier Detect) is equivalent to RLSD (Receive Line Signal Detect) on some platforms.

            <var>dtr</var>

                  (
                    optional

                        boolean

                  )

Serial control signals that your machine can send. Missing fields will be set to false.

            <var>rts</var>

                  (
                    optional

                        boolean

                  )

            Undocumented.

  Except as otherwise noted,
  the content of this page is licensed under the Creative Commons
  Attribution 3.0 License, and code samples are licensed under the
  BSD License.

  ©2011 Google


text:
using System;
using System.Collections.Generic;
using System.Collections.Concurrent;
using System.Diagnostics.CodeAnalysis; // SuppressMessageAttribute
using System.IO;
using System.IO.Compression;
using System.Linq; // OrderBy
using System.Reflection; // GetCustomAttribute<T>
using System.Threading; // Thread, Barrier, CancellationToken
using System.Threading.Tasks; // Task, TaskCreationOptions, TaskScheduler
using FDA.Attributes;
using FDA.IO; // Hash
using FDA.Extensions;

namespace FDA
{
    /// <summary>
    /// Converts CSV from text to object using threads and concurrent structure
    /// </summary>
    /// <typeparam name="T"></typeparam>
	public static class CsvConverter<T>
        where T: BinaryDatapoint, new()
	{
        private static Barrier endBarrier;
        private static Barrier startBarrier;
        private static ConcurrentQueue<string> inputQueue;
        private static ConcurrentQueue<T> outputQueue;
        private static ConcurrentQueue<Tuple<DateTime, int>> flightTimes;

        private static int validLineCount = 0;
        private static int Fields = typeof(T).GetCustomAttribute<CsvRecordAttribute>().Count;

        private static Action<T, string[]> parser = CsvParser.GetParser<T>();

        private static readonly object _locker = new object();

        public static async Task LoadAsync(string path, string outputPath)
        {
            await Task.Factory.StartNew(() => Load(path, outputPath), CancellationToken.None, TaskCreationOptions.AttachedToParent, TaskScheduler.FromCurrentSynchronizationContext());
        }

        private static void Initialize()
        {
            endBarrier = new Barrier(Environment.ProcessorCount + 1);
            startBarrier = new Barrier(Environment.ProcessorCount + 1);

            inputQueue = new ConcurrentQueue<string>();
            outputQueue = new ConcurrentQueue<T>();
            flightTimes = new ConcurrentQueue<Tuple<DateTime, int>>();
        }

        private static void VerifyPath(string path, ref string outputDirectory)
        {
            if (string.IsNullOrWhiteSpace(path))
            {
                throw new ArgumentNullException("path");
            }

            if (string.IsNullOrWhiteSpace(outputDirectory))
            {
                throw new ArgumentNullException("outputDirectory");
            }

            if (!Directory.Exists(outputDirectory))
            {
                throw new DirectoryNotFoundException();
            }

            var hash = Hash.ComputeHash(path);
            outputDirectory = Path.Combine(outputDirectory, BitConverter.ToString(hash).Replace("-", ""));
        }

        /// <summary>
        /// Loads and processes a CSV file
        /// </summary>
        /// <param name="path">Path of incoming file</param>
        /// <param name="outputDirectory">Output directory</param>
        public static void Load(string path, string outputDirectory)
        {
            Initialize();

            VerifyPath(path, ref outputDirectory);

            Thread producer = new Thread(ProducerThread);
            Thread consumer = new Thread(ConsumerThread);
            Thread[] workers = new Thread[Environment.ProcessorCount];

            for (int i = 0; i < workers.Length; i++)
            {
                workers[i] = new Thread(WorkerRead);
                workers[i].Start();
            }

            producer.Start(path);
            producer.Join(); // Producer has a barrier that is associated with the worker threads, so this blocks until all workers are done

            // TODO: Write output information in JSON format

            // TODO: allow the consumer to write to the output file while the other threads are still working
            consumer.Start(outputDirectory);
            consumer.Join();
        }

        /// <summary>
        /// Writes objects to a compressed filestream
        /// </summary>
        /// <param name="path">path of output</param>
        [SuppressMessage("Microsoft.Usage","CA2202:Do not dispose objects multiple times")]
        private static void ConsumerThread(object path)
        {
            var ms = new MemoryStream();
            byte[] data = new byte[] { };
            long compressSize, normalSize;

            Action<T, BinaryWriter> write = BinaryDatapoint.GetWriteAction<T>();

            string filePath = path as string;

            if (string.IsNullOrWhiteSpace(filePath))
            {
                throw new ArgumentNullException("path");
            }

            // Make sure elements are ordered by DateTime and Timestamp
            // DateTime is not guaranteed to be unique
            // TimeStamp is unique by value, but values eventually cycle. Thus the order cannot be trusted
            var ordered = from dp in outputQueue
                          //orderby /*dp.DateTime,*/ dp.Timestamp
                          select dp;

            // TODO: inheritance hierarchy was changed. Ordering is broken and needs to be fixed

            // TODO: Keep track of an index to improve lookup speeds.

            // Write datapoints to MemoryStream (not directly to FileStream)
            // Note: this cannot be done inside of a 'using(GZipStream)' block because the data will not be correctly written
            using (var writer = new BinaryWriter(ms))
            {
                foreach (var dp in ordered)
                {
                    write(dp, writer);
                }

                data = ms.ToArray();
                normalSize = ms.Length;
            }

            // TODO: Add switch for enabling/disabling compression

            // Compress to GZipStream (backed by FileStream)
            using (var file = File.Open(filePath, FileMode.Create))
            using (var compress = new GZipStream(file, CompressionMode.Compress))
            {
                compress.Write(data, 0, data.Length);
                compressSize = compress.BaseStream.Length;  // keep track of size for writing info to a JSON object
            }

            /*lock (_locker)
            {
                // TODO: Write output information in JSON format, not flat string
            }*/
        }

        static void ProducerThread(object path)
        {
            var filePath = path as string;
            bool ReadySet = false;

            if (filePath == null)
            {
                throw new ArgumentNullException("path");
            }

            if (!File.Exists(filePath))
            {
                throw new FileNotFoundException();
            }

            using (var reader = new StreamReader(filePath))
            {
                reader.ReadLine(); // The first line is the name of fields

                while (!reader.EndOfStream)
                {
                    inputQueue.Enqueue(reader.ReadLine());

                    if (!ReadySet)
                    {
                        ReadySet = true; // GO!
                        startBarrier.SignalAndWait();
                    }
                }
            }

            endBarrier.SignalAndWait();
            inputQueue = null;
        }

        /// <summary>
        /// Thread reads and parses a single line
        /// </summary>
		static void WorkerRead()
		{
			string result;
			//var tid = Thread.CurrentThread.ManagedThreadId; // used only for debugging

            // Wait for the go signal
            try
            {
                startBarrier.SignalAndWait();
            }
            catch (EntryPointNotFoundException ex) // this is an infrequent exception that happens time to time
            {
                startBarrier.RemoveParticipant();
                endBarrier.RemoveParticipant();
                Thread.CurrentThread.Abort();
                Console.WriteLine(ex.Message);
                return;
            }
            catch (Exception)
            {
                throw; // preserve stack trace
            }

            while (!inputQueue.IsEmpty)
            {
                if (inputQueue.TryDequeue(out result))
                {
                    var value = result.Split(new char[] { ',' }, StringSplitOptions.None);

                    // Only parse if the number of elements is correct
                    if (value.Length == Fields)
                    {
                        T dp = Activator.CreateInstance<T>();
                        parser(dp, value); // This is the generated

                        outputQueue.Enqueue(dp);
                        Interlocked.Increment(ref validLineCount);
                    }
                    else if (value.Length == 4 && value[3].Contains("POWER ON"))
                    {
                        // A new flight is indicated by the presence of "POWER ON" in the 4th element
                        flightTimes.Enqueue(
                            new Tuple<DateTime, int>(
                                value[1].AsDateTime(value[2].AsTimeSpan()),
                                value[3].AsInt()
                                ));
                    }
                    else
                    {
                        // Skip meaningless data
                    }
                }
            }

            endBarrier.SignalAndWait();
		}
	}
}


text:
package org.mini2Dx.tiled.exception;

/**
 * Thrown when the orientation of the map isn't supported by mini2Dx
 */
public class UnsupportedOrientationException extends TiledException {
	private static final long serialVersionUID = -9049756951472753561L;

	public UnsupportedOrientationException(String orientation) {
		super(
				orientation
						+ " is not a supported orientation. This map will not be renderable");
	}
}


text:
package io.crnk.core.resource.meta;

import com.fasterxml.jackson.databind.node.ObjectNode;

public interface MetaContainer {

	ObjectNode getMeta();

	void setMeta(ObjectNode meta);
}


text:
require 'open3'
require_relative './shp_helper'

module CartoDB
  module Importer2
    class Ogr2ogr
      ENCODING  = 'UTF-8'
      SCHEMA    = 'cdb_importer'

      OUTPUT_FORMAT_OPTION  = '-f PostgreSQL'
      PG_COPY_OPTION        = 'PG_USE_COPY=YES'
      NEW_LAYER_TYPE_OPTION = '-nlt PROMOTE_TO_MULTI'
      OSM_INDEXING_OPTION   = 'OSM_USE_CUSTOM_INDEXING=NO'
      APPEND_MODE_OPTION    = '-append'

      DEFAULT_BINARY = 'which ogr2ogr'

      def initialize(table_name, filepath, pg_options, layer=nil, options={})
        self.filepath   = filepath
        self.pg_options = pg_options
        self.table_name = table_name
        self.layer      = layer
        self.options    = options
        self.command_output = ''
        self.exit_code = 0
        set_default_properties
      end

      def set_default_properties
        self.append_mode = false
        self.overwrite = false
        self.ogr2ogr2_binary = options.fetch(:ogr2ogr_binary, DEFAULT_BINARY)
        self.csv_guessing = options.fetch(:ogr2ogr_csv_guessing, false)
        self.quoted_fields_guessing = options.fetch(:quoted_fields_guessing, true)
        self.encoding = options.fetch(:encoding, ENCODING)
        self.shape_encoding = ''
        self.shape_coordinate_system = options.fetch(:shape_coordinate_system, '')
      end

      def command_for_import
        "#{OSM_INDEXING_OPTION} #{PG_COPY_OPTION} #{client_encoding_option} #{shape_encoding_option} " +
        "#{executable_path} #{OUTPUT_FORMAT_OPTION} #{overwrite_option} #{guessing_option} #{postgres_options} #{projection_option} " +
        "#{layer_creation_options} #{filepath} #{layer} #{layer_name_option} #{NEW_LAYER_TYPE_OPTION}" +
        " #{shape_coordinate_option} "
      end

      def command_for_append
        "#{OSM_INDEXING_OPTION} #{PG_COPY_OPTION} #{client_encoding_option} " +
        "#{executable_path} #{APPEND_MODE_OPTION} #{OUTPUT_FORMAT_OPTION} #{postgres_options} " +
        "#{projection_option} #{filepath} #{layer} #{layer_name_option} #{NEW_LAYER_TYPE_OPTION}"
      end

      def executable_path
        (is_csv? || is_geojson?) ? `#{ogr2ogr2_binary}`.strip : `#{DEFAULT_BINARY}`.strip
      end

      def command
        append_mode ? command_for_append : command_for_import
      end

      def run(use_append_mode=false)
        @append_mode = use_append_mode
        stdout, stderr, status  = Open3.capture3(command)
        self.command_output     = (stdout + stderr).encode('UTF-8', 'binary', invalid: :replace, undef: :replace, replace: '?????')
        self.exit_code          = status.to_i
        self
      end

      def generic_error?
        command_output =~ /ERROR 1:/ || command_output =~ /ERROR:/
      end

      def encoding_error?
        command_output =~ /has no equivalent in encoding/ || command_output =~ /invalid byte sequence for encoding/
      end

      def invalid_dates?
        command_output =~ /date\/time field value out of range/
      end

      def duplicate_column?
        command_output =~ /column (.*) of relation (.*) already exists/ || command_output =~ /specified more than once/
      end

      def invalid_geojson?
        command_output =~ /nrecognized GeoJSON/
      end

      def too_many_columns?
        command_output =~ /tables can have at most 1600 columns/
      end

      def unsupported_format?
        exit_code == 256 && command_output =~ /Unable to open(.*)with the following drivers/
      end

      def file_too_big?
        (exit_code == 256 && command_output =~ /calloc failed/) ||
        (exit_code == 35072 && command_output =~ /Killed/)
      end

      def statement_timeout?
        command_output =~ /canceling statement due to statement timeout/i
      end

      def segfault_error?
        exit_code == 35584 && command_output =~ /Segmentation fault/
      end

      def kml_style_missing?
        is_kml? && command_output =~/Parseing kml Style: No id/
      end

      attr_accessor :append_mode, :filepath, :csv_guessing, :overwrite, :encoding, :shape_encoding,
                    :shape_coordinate_system
      attr_reader   :exit_code, :command_output

      private

      attr_writer   :exit_code, :command_output
      attr_accessor :pg_options, :options, :table_name, :layer, :ogr2ogr2_binary, :quoted_fields_guessing

      def is_csv?
        !(filepath =~ /\.csv$/i).nil?
      end

      def is_kml?
        !(filepath =~ /\.kml$/i).nil?
      end

      def is_geojson?
        !(filepath =~ /\.geojson$/i).nil?
      end

      def is_shp?
        !(filepath =~ /\.shp$/i).nil?
      end

      def guessing_option
        if csv_guessing && is_csv?
          # Inverse of the selection: if I want guessing I must NOT leave quoted fields as string
          "-oo AUTODETECT_TYPE=YES -oo QUOTED_FIELDS_AS_STRING=#{quoted_fields_guessing ? 'NO' : 'YES' }"
        else
          ''
        end
      end

      def overwrite_option
        overwrite ? "-overwrite" : ''
      end

      def client_encoding_option
        "PGCLIENTENCODING=#{encoding}"
      end

      def shape_encoding_option
        !shape_encoding.nil? && !shape_encoding.empty? ? "SHAPE_ENCODING=#{shape_encoding}" : ''
      end

      def shape_coordinate_option
        shape_coordinate_system.empty? ? '' : "-s_srs EPSG:#{shape_coordinate_system}"
      end

      def layer_name_option
        "-nln #{SCHEMA}.#{table_name}"
      end

      # @see http://www.gdal.org/drv_pg.html
      # @see http://www.gdal.org/drv_pg_advanced.html
      def postgres_options
        %Q{PG:"host=#{pg_options.fetch(:host)} }      +
        %Q{port=#{pg_options.fetch(:port)} }          +
        %Q{user=#{pg_options.fetch(:user)} }          +
        %Q{dbname=#{pg_options.fetch(:database)} }    +
        %Q{password=#{pg_options.fetch(:password)}"}
        # 'schemas=#{SCHEMA},cartodb' param is no longer needed, let the DB build the proper one
      end

      def layer_creation_options
        # Dimension option, precision option
        "-lco DIM=2 -lco PRECISION=NO"
      end

      def projection_option
        is_csv? || filepath =~ /\.ods/ ? nil : '-t_srs EPSG:4326 '
      end
    end
  end
end


text:
using System;
using System.Threading.Tasks;
using Newtonsoft.Json;
using RestSharp;

namespace MyPolitics.Sunlight.CongressApi.Legislators
{
    public class SunlightLegislatorLocateService : ILegislatorLocateService
    {
        private readonly IRestClient _client;
        private readonly IApiKeyProvider _apiKeyProvider;

        public SunlightLegislatorLocateService(IRestClient client, IApiKeyProvider apiKeyProvider)
        {
            _client = client;
            _apiKeyProvider = apiKeyProvider;
        }

        public async Task<LegislatorLocateResult> LocateBy(LegislatorsLocateOptions options)
        {
            var request = new RestRequest("legislators/locate", Method.GET);
            request.AddQueryParameter("apikey", await _apiKeyProvider.GetApiKey());

            if (!string.IsNullOrWhiteSpace(options.ZipCode))
            {
                request.AddQueryParameter("zip", options.ZipCode);
            }
            else if (options.Latitude.HasValue && options.Longitude.HasValue)
            {
                request.AddQueryParameter("latitude", options.Latitude.ToString());
                request.AddQueryParameter("longitude", options.Longitude.ToString());
            }

            var result = await _client.ExecuteTaskAsync(request);
            return JsonConvert.DeserializeObject<LegislatorLocateResult>(result.Content);
        }
    }
}


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

<title>U-Index</title>
<meta name="date" content="2015-07-23">
<link rel="stylesheet" type="text/css" href="../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Letter

Next Letter

Frames

No Frames

All Classes

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

U

UIComponent<C,L,A,M> - Interface in org.jacpfx.api.component

Represents an basic UI component handled by a perspective.

UIType - Enum in org.jacpfx.api.util

To avoid definition of several interface/abstract class types of UI component this ENUM can
 be used to distinguish component.

unregisterComponent(T) - Method in interface org.jacpfx.api.component.RootComponent

Unregister component from current perspective.

updatePositions(int, int) - Method in interface org.jacpfx.api.component.Perspective

defines the position of an active perspective in workspace

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

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Letter

Next Letter

Frames

No Frames

All Classes


text:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<feed><tipo>Rua</tipo><logradouro>Atenas</logradouro><bairro>Dois Unidos</bairro><cidade>Recife</cidade><uf>PE</uf><cep>52160085</cep></feed>