text:
<?php

namespace Agile\InvoiceBundle\Form\Extension;

use Symfony\Component\Form\AbstractTypeExtension;
use Symfony\Component\OptionsResolver\Options;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;
use Agile\InvoiceBundle\Utility\Utils as Utility;
use Symfony\Component\Intl\Intl;

class CurrencyTypeExtension extends AbstractTypeExtension
{
    private $translator;

    public function __construct($translator)
    {
        $this->translator = $translator;
    }

    /**
     * Returns the name of the type being extended.
     *
     * @return string The name of the type being extended
     */
    public function getExtendedType()
    {
        return 'currency';
    }

    /**
     * {@inheritdoc}
     */
    public function setDefaultOptions(OptionsResolverInterface $resolver)
    {

        $resolver->setDefaults(array(
            'choices' => function (Options $options) {
                return $this->getCurrencyChoices($options['view_account_default_currency']);
            },
            'preferred_choices' => array(
                'EUR', 'GBP', 'USD', 'CAD', 'AUD', 'NZD', 'SEK', 'DKK', 'NOK', 'CHF', 'ZAR'
            ),
            'view_account_default_currency' => null,
        ));

    }

    private function getCurrencyChoices($viewAccountDefaultCurrency = null)
    {
        $currenySymbols = Utility::getCurrencySymbols();

        // \Locale::setDefault('en');
        // $currencies = Intl::getCurrencyBundle()->getCurrencyNames();
        // $currency = Intl::getCurrencyBundle()->getCurrencyName('INR');
        // $symbol = Intl::getCurrencyBundle()->getCurrencySymbol('INR');
        // $fractionDigits = Intl::getCurrencyBundle()->getFractionDigits('INR');
        // $roundingIncrement = Intl::getCurrencyBundle()->getRoundingIncrement('INR');

        $currencyChoices = array();
        foreach ($currenySymbols as $symbol) {
            $currencyName = Intl::getCurrencyBundle()->getCurrencyName($symbol);
            if ($currencyName) {
                $currencyValue = $currencyName.' - '.$symbol;
                if ($viewAccountDefaultCurrency == $symbol) {
                    $currencyChoices[$symbol] = $this->translator->trans(
                        'account.default.%currencyValue%',
                        array('%currencyValue%' => $currencyValue)
                    );
                } else {
                    $currencyChoices[$symbol] = $currencyValue;
                }

            }
        }

        return $currencyChoices;
    }
}

redpajama_set_name: RedPajamaGithub


text:
require "abstract_unit"

module AbstractController
  module Testing
    class UrlForTest < ActionController::TestCase
      class W
        include ActionDispatch::Routing::RouteSet.new.tap { |r|
          r.draw {
            ActionDispatch.deprecator.silence {
              get ":controller(/:action(/:id(.:format)))"
            }
          }
        }.url_helpers
      end

      def teardown
        W.default_url_options.clear
      end

      def test_nested_optional
        klass = Class.new {
          include ActionDispatch::Routing::RouteSet.new.tap { |r|
            r.draw {
              get "/foo/(:bar/(:baz))/:zot", as: "fun",
                                             controller: :articles,
                                             action: :index
            }
          }.url_helpers
          default_url_options[:host] = "example.com"
        }

        path = klass.new.fun_path(controller: :articles,
                                   baz: "baz",
                                   zot: "zot")
        # :bar key isn't provided
        assert_equal "/foo/zot", path
      end

      def add_host!(app = W)
        app.default_url_options[:host] = "www.basecamphq.com"
      end

      def add_port!
        W.default_url_options[:port] = 3000
      end

      def add_numeric_host!
        W.default_url_options[:host] = "127.0.0.1"
      end

      def test_exception_is_thrown_without_host
        assert_raise ArgumentError do
          W.new.url_for controller: "c", action: "a", id: "i"
        end
      end

      def test_anchor
        assert_equal("/c/a#anchor",
          W.new.url_for(only_path: true, controller: "c", action: "a", anchor: "anchor")
        )
      end

      def test_nil_anchor
        assert_equal(
          "/c/a",
          W.new.url_for(only_path: true, controller: "c", action: "a", anchor: nil)
        )
      end

      def test_false_anchor
        assert_equal(
          "/c/a",
          W.new.url_for(only_path: true, controller: "c", action: "a", anchor: false)
        )
      end

      def test_anchor_should_call_to_param
        assert_equal("/c/a#anchor",
          W.new.url_for(only_path: true, controller: "c", action: "a", anchor: Struct.new(:to_param).new("anchor"))
        )
      end

      def test_anchor_should_escape_unsafe_pchar
        assert_equal("/c/a#%23anchor",
          W.new.url_for(only_path: true, controller: "c", action: "a", anchor: Struct.new(:to_param).new("#anchor"))
        )
      end

      def test_anchor_should_not_escape_safe_pchar
        assert_equal("/c/a#name=user&email=user@domain.com",
          W.new.url_for(only_path: true, controller: "c", action: "a", anchor: Struct.new(:to_param).new("name=user&email=user@domain.com"))
        )
      end

      def test_default_host
        add_host!
        assert_equal("http://www.basecamphq.com/c/a/i",
          W.new.url_for(controller: "c", action: "a", id: "i")
        )
      end

      def test_host_may_be_overridden
        add_host!
        assert_equal("http://37signals.basecamphq.com/c/a/i",
          W.new.url_for(host: "37signals.basecamphq.com", controller: "c", action: "a", id: "i")
        )
      end

      def test_subdomain_may_be_changed
        add_host!
        assert_equal("http://api.basecamphq.com/c/a/i",
          W.new.url_for(subdomain: "api", controller: "c", action: "a", id: "i")
        )
      end

      def test_subdomain_may_be_object
        model = Class.new { def self.to_param; "api"; end }
        add_host!
        assert_equal("http://api.basecamphq.com/c/a/i",
          W.new.url_for(subdomain: model, controller: "c", action: "a", id: "i")
        )
      end

      def test_subdomain_may_be_removed
        add_host!
        assert_equal("http://basecamphq.com/c/a/i",
          W.new.url_for(subdomain: false, controller: "c", action: "a", id: "i")
        )
      end

      def test_subdomain_may_be_removed_with_blank_string
        W.default_url_options[:host] = "api.basecamphq.com"
        assert_equal("http://basecamphq.com/c/a/i",
          W.new.url_for(subdomain: "", controller: "c", action: "a", id: "i")
        )
      end

      def test_multiple_subdomains_may_be_removed
        W.default_url_options[:host] = "mobile.www.api.basecamphq.com"
        assert_equal("http://basecamphq.com/c/a/i",
          W.new.url_for(subdomain: false, controller: "c", action: "a", id: "i")
        )
      end

      def test_subdomain_may_be_accepted_with_numeric_host
        add_numeric_host!
        assert_equal("http://127.0.0.1/c/a/i",
          W.new.url_for(subdomain: "api", controller: "c", action: "a", id: "i")
        )
      end

      def test_domain_may_be_changed
        add_host!
        assert_equal("http://www.37signals.com/c/a/i",
          W.new.url_for(domain: "37signals.com", controller: "c", action: "a", id: "i")
        )
      end

      def test_tld_length_may_be_changed
        add_host!
        assert_equal("http://mobile.www.basecamphq.com/c/a/i",
          W.new.url_for(subdomain: "mobile", tld_length: 2, controller: "c", action: "a", id: "i")
        )
      end

      def test_port
        add_host!
        assert_equal("http://www.basecamphq.com:3000/c/a/i",
          W.new.url_for(controller: "c", action: "a", id: "i", port: 3000)
        )
      end

      def test_default_port
        add_host!
        add_port!
        assert_equal("http://www.basecamphq.com:3000/c/a/i",
          W.new.url_for(controller: "c", action: "a", id: "i")
        )
      end

      def test_protocol
        add_host!
        assert_equal("https://www.basecamphq.com/c/a/i",
          W.new.url_for(controller: "c", action: "a", id: "i", protocol: "https")
        )
      end

      def test_protocol_with_and_without_separators
        add_host!
        assert_equal("https://www.basecamphq.com/c/a/i",
          W.new.url_for(controller: "c", action: "a", id: "i", protocol: "https")
        )
        assert_equal("https://www.basecamphq.com/c/a/i",
          W.new.url_for(controller: "c", action: "a", id: "i", protocol: "https:")
        )
        assert_equal("https://www.basecamphq.com/c/a/i",
          W.new.url_for(controller: "c", action: "a", id: "i", protocol: "https://")
        )
      end

      def test_without_protocol
        add_host!
        assert_equal("//www.basecamphq.com/c/a/i",
          W.new.url_for(controller: "c", action: "a", id: "i", protocol: "//")
        )
        assert_equal("//www.basecamphq.com/c/a/i",
          W.new.url_for(controller: "c", action: "a", id: "i", protocol: false)
        )
      end

      def test_without_protocol_and_with_port
        add_host!
        add_port!

        assert_equal("//www.basecamphq.com:3000/c/a/i",
          W.new.url_for(controller: "c", action: "a", id: "i", protocol: "//")
        )
        assert_equal("//www.basecamphq.com:3000/c/a/i",
          W.new.url_for(controller: "c", action: "a", id: "i", protocol: false)
        )
      end

      def test_trailing_slash
        add_host!
        options = { controller: "foo", trailing_slash: true, action: "bar", id: "33" }
        assert_equal("http://www.basecamphq.com/foo/bar/33/", W.new.url_for(options))
      end

      def test_trailing_slash_with_protocol
        add_host!
        options = { trailing_slash: true, protocol: "https", controller: "foo", action: "bar", id: "33" }
        assert_equal("https://www.basecamphq.com/foo/bar/33/", W.new.url_for(options))
        assert_equal "https://www.basecamphq.com/foo/bar/33/?query=string", W.new.url_for(options.merge(query: "string"))
      end

      def test_trailing_slash_with_only_path
        options = { controller: "foo", trailing_slash: true }
        assert_equal "/foo/", W.new.url_for(options.merge(only_path: true))
        options.update(action: "bar", id: "33")
        assert_equal "/foo/bar/33/", W.new.url_for(options.merge(only_path: true))
        assert_equal "/foo/bar/33/?query=string", W.new.url_for(options.merge(query: "string", only_path: true))
      end

      def test_trailing_slash_with_anchor
        options = { trailing_slash: true, controller: "foo", action: "bar", id: "33", only_path: true, anchor: "chapter7" }
        assert_equal "/foo/bar/33/#chapter7", W.new.url_for(options)
        assert_equal "/foo/bar/33/?query=string#chapter7", W.new.url_for(options.merge(query: "string"))
      end

      def test_trailing_slash_with_params
        url = W.new.url_for(trailing_slash: true, only_path: true, controller: "cont", action: "act", p1: "cafe", p2: "link")
        params = extract_params(url)
        assert_equal({ p1: "cafe" }.to_query, params[0])
        assert_equal({ p2: "link" }.to_query, params[1])
      end

      def test_relative_url_root_is_respected
        add_host!
        assert_equal("https://www.basecamphq.com/subdir/c/a/i",
          W.new.url_for(controller: "c", action: "a", id: "i", protocol: "https", script_name: "/subdir")
        )
      end

      def test_relative_url_root_is_respected_with_environment_variable
        # `config.relative_url_root` is set by ENV['RAILS_RELATIVE_URL_ROOT']
        w = Class.new {
          config = ActionDispatch::Routing::RouteSet::Config.new "/subdir"
          r = ActionDispatch::Routing::RouteSet.new(config)
          r.draw { ActionDispatch.deprecator.silence { get ":controller(/:action(/:id(.:format)))" } }
          include r.url_helpers
        }
        add_host!(w)
        assert_equal("https://www.basecamphq.com/subdir/c/a/i",
          w.new.url_for(controller: "c", action: "a", id: "i", protocol: "https")
        )
      end

      def test_named_routes
        with_routing do |set|
          set.draw do
            get "this/is/verbose", to: "home#index", as: :no_args
            get "home/sweet/home/:user", to: "home#index", as: :home
          end

          # We need to create a new class in order to install the new named route.
          kls = Class.new { include set.url_helpers }

          controller = kls.new
          assert_respond_to controller, :home_url
          assert_equal "http://www.basecamphq.com/home/sweet/home/again",
            controller.home_url(host: "www.basecamphq.com", user: "again")

          assert_equal("/home/sweet/home/alabama", controller.home_path(user: "alabama", host: "unused"))
          assert_equal("http://www.basecamphq.com/home/sweet/home/alabama", controller.home_url(user: "alabama", host: "www.basecamphq.com"))
          assert_equal("http://www.basecamphq.com/this/is/verbose", controller.no_args_url(host: "www.basecamphq.com"))
        end
      end

      def test_relative_url_root_is_respected_for_named_routes
        with_routing do |set|
          set.draw do
            get "/home/sweet/home/:user", to: "home#index", as: :home
          end

          kls = Class.new { include set.url_helpers }
          controller = kls.new

          assert_equal "http://www.basecamphq.com/subdir/home/sweet/home/again",
            controller.home_url(host: "www.basecamphq.com", user: "again", script_name: "/subdir")
        end
      end

      def test_using_nil_script_name_properly_concats_with_original_script_name
        add_host!
        assert_equal("https://www.basecamphq.com/subdir/c/a/i",
          W.new.url_for(controller: "c", action: "a", id: "i", protocol: "https", script_name: nil, original_script_name: "/subdir")
        )
      end

      def test_only_path
        with_routing do |set|
          set.draw do
            get "home/sweet/home/:user", to: "home#index", as: :home

            ActionDispatch.deprecator.silence do
              get ":controller/:action/:id"
            end
          end

          # We need to create a new class in order to install the new named route.
          kls = Class.new { include set.url_helpers }
          controller = kls.new
          assert_respond_to controller, :home_url
          assert_equal "/brave/new/world",
            controller.url_for(controller: "brave", action: "new", id: "world", only_path: true)

          assert_equal("/home/sweet/home/alabama", controller.home_path(user: "alabama", host: "unused"))
          assert_equal("/home/sweet/home/alabama", controller.home_path("alabama"))
        end
      end

      def test_one_parameter
        assert_equal("/c/a?param=val",
          W.new.url_for(only_path: true, controller: "c", action: "a", param: "val")
        )
      end

      def test_two_parameters
        url = W.new.url_for(only_path: true, controller: "c", action: "a", p1: "X1", p2: "Y2")
        params = extract_params(url)
        assert_equal({ p1: "X1" }.to_query, params[0])
        assert_equal({ p2: "Y2" }.to_query, params[1])
      end

      def test_params_option
        url = W.new.url_for(only_path: true, controller: "c", action: "a", params: { domain: "foo", id: "1" })
        params = extract_params(url)
        assert_equal("/c/a?domain=foo&id=1", url)
        assert_equal({ domain: "foo" }.to_query, params[0])
        assert_equal({ id: "1" }.to_query, params[1])
      end

      def test_params_option_strong_parameters
        request_params = ActionController::Parameters.new({ domain: "foo", id: "1", other: "BAD" })
        url = W.new.url_for(only_path: true, controller: "c", action: "a", params: request_params.permit(:domain, :id))
        params = extract_params(url)
        assert_equal("/c/a?domain=foo&id=1", url)
        assert_equal({ domain: "foo" }.to_query, params[0])
        assert_equal({ id: "1" }.to_query, params[1])
      end

      def test_non_hash_params_option
        url = W.new.url_for(only_path: true, controller: "c", action: "a", params: "p")
        params = extract_params(url)
        assert_equal("/c/a?params=p", url)
        assert_equal({ params: "p" }.to_query, params[0])
      end

      def test_hash_parameter
        url = W.new.url_for(only_path: true, controller: "c", action: "a", query: { name: "Bob", category: "prof" })
        params = extract_params(url)
        assert_equal({ "query[category]" => "prof" }.to_query, params[0])
        assert_equal({ "query[name]" => "Bob" }.to_query, params[1])
      end

      def test_array_parameter
        url = W.new.url_for(only_path: true, controller: "c", action: "a", query: ["Bob", "prof"])
        params = extract_params(url)
        assert_equal({ "query[]" => "Bob" }.to_query, params[0])
        assert_equal({ "query[]" => "prof" }.to_query, params[1])
      end

      def test_hash_recursive_parameters
        url = W.new.url_for(only_path: true, controller: "c", action: "a", query: { person: { name: "Bob", position: "prof" }, hobby: "piercing" })
        params = extract_params(url)
        assert_equal({ "query[hobby]"            => "piercing" }.to_query, params[0])
        assert_equal({ "query[person][name]"     => "Bob"     }.to_query, params[1])
        assert_equal({ "query[person][position]" => "prof"    }.to_query, params[2])
      end

      def test_hash_recursive_and_array_parameters
        url = W.new.url_for(only_path: true, controller: "c", action: "a", id: 101, query: { person: { name: "Bob", position: ["prof", "art director"] }, hobby: "piercing" })
        assert_match(%r(^/c/a/101), url)
        params = extract_params(url)
        assert_equal({ "query[hobby]"              => "piercing"    }.to_query, params[0])
        assert_equal({ "query[person][name]"       => "Bob"         }.to_query, params[1])
        assert_equal({ "query[person][position][]" => "art director" }.to_query, params[2])
        assert_equal({ "query[person][position][]" => "prof"        }.to_query, params[3])
      end

      def test_url_action_controller_parameters
        add_host!
        assert_raise(ActionController::UnfilteredParameters) do
          W.new.url_for(ActionController::Parameters.new(controller: "c", action: "a", protocol: "javascript", f: "%0Aeval(name)"))
        end
      end

      def test_path_generation_for_symbol_parameter_keys
        assert_generates("/image", controller: :image)
      end

      def test_named_routes_with_nil_keys
        with_routing do |set|
          set.draw do
            get "posts.:format", to: "posts#index", as: :posts
            get "/", to: "posts#index", as: :main
          end

          # We need to create a new class in order to install the new named route.
          kls = Class.new { include set.url_helpers }
          kls.default_url_options[:host] = "www.basecamphq.com"

          controller = kls.new
          params = { action: :index, controller: :posts, format: :xml }
          assert_equal("http://www.basecamphq.com/posts.xml", controller.url_for(params))
          params[:format] = nil
          assert_equal("http://www.basecamphq.com/", controller.url_for(params))
        end
      end

      def test_multiple_includes_maintain_distinct_options
        first_class = Class.new { include ActionController::UrlFor }
        second_class = Class.new { include ActionController::UrlFor }

        first_host, second_host = "firsthost.com", "secondhost.com"

        first_class.default_url_options[:host] = first_host
        second_class.default_url_options[:host] = second_host

        assert_equal first_host, first_class.default_url_options[:host]
        assert_equal second_host, second_class.default_url_options[:host]
      end

      def test_with_stringified_keys
        assert_equal("/c", W.new.url_for("controller" => "c", "only_path" => true))
        assert_equal("/c/a", W.new.url_for("controller" => "c", "action" => "a", "only_path" => true))
      end

      def test_with_hash_with_indifferent_access
        W.default_url_options[:controller] = "d"
        W.default_url_options[:only_path]  = false
        assert_equal("/c", W.new.url_for(ActiveSupport::HashWithIndifferentAccess.new("controller" => "c", "only_path" => true)))

        W.default_url_options[:action] = "b"
        assert_equal("/c/a", W.new.url_for(ActiveSupport::HashWithIndifferentAccess.new("controller" => "c", "action" => "a", "only_path" => true)))
      end

      def test_url_params_with_nil_to_param_are_not_in_url
        assert_equal("/c/a", W.new.url_for(only_path: true, controller: "c", action: "a", id: Struct.new(:to_param).new(nil)))
      end

      def test_false_url_params_are_included_in_query
        assert_equal("/c/a?show=false", W.new.url_for(only_path: true, controller: "c", action: "a", show: false))
      end

      def test_url_generation_with_array_and_hash
        with_routing do |set|
          set.draw do
            namespace :admin do
              resources :posts
            end
          end

          kls = Class.new { include set.url_helpers }
          kls.default_url_options[:host] = "www.basecamphq.com"

          controller = kls.new
          assert_equal("http://www.basecamphq.com/admin/posts/new?param=value",
            controller.url_for([:new, :admin, :post, { param: "value" }])
          )
        end
      end

      def test_url_for_with_array_is_unmodified
        with_routing do |set|
          set.draw do
            namespace :admin do
              resources :posts
            end
          end

          kls = Class.new { include set.url_helpers }
          kls.default_url_options[:host] = "www.basecamphq.com"

          original_components = [:new, :admin, :post, { param: "value" }]
          components = original_components.dup

          kls.new.url_for(components)

          assert_equal(original_components, components)
        end
      end

      def test_default_params_first_empty
        with_routing do |set|
          set.draw do
            get "(:param1)/test(/:param2)" => "index#index",
              defaults: {
                param1: 1,
                param2: 2
              },
              constraints: {
                param1: /\d*/,
                param2: /\d+/
              }
          end

          kls = Class.new { include set.url_helpers }
          kls.default_url_options[:host] = "www.basecamphq.com"

          assert_equal "http://www.basecamphq.com/test", kls.new.url_for(controller: "index", param1: "1")
        end
      end

      private
        def extract_params(url)
          url.split("?", 2).last.split("&").sort
        end
    end
  end
end


text:
const test = require('tape')

/**
 * Test an async function
 *
 * A convienience function that provides for consistent
 * handling of errors when testing async funcions
 *
 * @param  {String} name Name of test
 * @param  {Function} func Async test function
 */
var testAsync = (name, func) => {
  test(name, async assert => {
    try {
      await func(assert)
    } catch (error) {
      assert.fail(error.stack)
      assert.end()
    }
  })
}

module.exports = {
  test,
  testAsync
}


text:
uint64_t SbSystemGetRandomUInt64() {
  uint64_t number;
  SbSystemGetRandomData(&number, sizeof(number));
  return number;
}


text:
set -e

source toolversions.sh
declare -r CORE_PROTOS_ROOT=$PROTOBUF_TOOLS_ROOT/tools

# This script generates all APIs from the googleapis/googleapis github repository,
# using the code generator from googleapis/gapic-generator.
# It will fetch both repositories if necessary.

# Currently it will only work on Windows due to the way nuget packages installed;
# changing toolversions.sh could mitigate that, if it's ever necessary.
#
# Prerequisites
# - Bash as supplied with Windows git
# - git
# - wget
# - unzip
# - Java 9

OUTDIR=tmp

fetch_github_repos() {
  if [ -d "gapic-generator" ]
  then
    git -C gapic-generator pull -q
    git -C gapic-generator submodule update
  else
    git clone --recursive https://github.com/googleapis/gapic-generator \
      --config core.autocrlf=false \
      --config core.eol=lf
  fi

  if [ -d "googleapis" ]
  then
    git -C googleapis pull -q
  else
    # Auto-detect whether we're cloning the public or private googleapis repo.
    git remote -v | grep -q google-cloud-dotnet-private && repo=googleapis-private || repo=googleapis
    git clone --recursive https://github.com/googleapis/${repo} googleapis
  fi
}

generate_api() {
  API_TMP_DIR=$OUTDIR/$1
  API_OUT_DIR=apis
  API_SRC_DIR=googleapis/$2
  API_YAML=$API_SRC_DIR/../$3

  if [[ ! -f $API_YAML ]]
  then
    echo "$API_YAML doesn't exist. Please check inputs."
    exit 1
  fi

  echo Generating $1
  mkdir $API_TMP_DIR

  # There should be only one gapic yaml file...
  for i in $API_SRC_DIR/*_gapic.yaml
  do
    cp $i $API_TMP_DIR/gapic.yaml
  done

  jvm_args=()
  jvm_args+=(--add-opens=java.base/java.nio=ALL-UNNAMED)
  jvm_args+=(--add-opens=java.base/java.lang=ALL-UNNAMED)
  jvm_args+=(-cp gapic-generator/build/libs/gapic-generator-${GAPIC_GENERATOR_VERSION}-all.jar)

  args=()
  args+=(--descriptor_set=$OUTDIR/protos.desc)
  args+=(--service_yaml=$API_YAML)
  args+=(--gapic_yaml=$API_TMP_DIR/gapic.yaml)
  args+=(--output=$API_TMP_DIR)
  args+=(--language=csharp)

  # Suppress protobuf warnings in Java 9/10. By the time they
  # become a problem, we won't be using Java...
  java ${jvm_args[*]} com.google.api.codegen.GeneratorMain GAPIC_CODE ${args[*]} \
  2>&1 | grep -v "does not have control environment" || true # Ignore control environment warnings (and grep exit code)

  cp -r $API_TMP_DIR/$1 $API_OUT_DIR

  # Generate the C# protos/gRPC directly into the right directory
  # This assumes they all belong to the same API, and are in the same namespace...
  $PROTOC \
    --csharp_out=$API_OUT_DIR/$1/$1 \
    --grpc_out=$API_OUT_DIR/$1/$1 \
    -I googleapis \
    -I $CORE_PROTOS_ROOT \
    --plugin=protoc-gen-grpc=$GRPC_PLUGIN \
    $API_SRC_DIR/*.proto \
    2>&1 | grep -v "but not used" || true # Ignore import warnings (and grep exit code)

  if [[ -f $API_OUT_DIR/$1/postgeneration.sh ]]
  then
    echo "Running post-generation script for $1"
    (cd $API_OUT_DIR/$1; ./postgeneration.sh)
  fi
}

# Entry point

install_protoc
install_grpc
fetch_github_repos
GAPIC_GENERATOR_VERSION=$(cat gapic-generator/version.txt)

# Build GAPIC generator once with gradle so we can invoke it from Java directly
# once per API. We don't care that we're using deprecated Gradle features: we
# won't be using Gradle at all by the end of 2018, with any luck...
(cd gapic-generator; ./gradlew shadowJar --warning-mode=none)

OUTDIR=tmp
rm -rf $OUTDIR
mkdir $OUTDIR

# Generate a single descriptor file for all protos we may care about.
# We can then reuse that for all APIs.
$PROTOC \
  -I googleapis \
  -I $CORE_PROTOS_ROOT \
  --include_source_info \
  -o $OUTDIR/protos.desc \
  $CORE_PROTOS_ROOT/google/protobuf/*.proto \
  `find googleapis/google -name '*.proto'` \
  2>&1 | grep -v "but not used" || true # Ignore import warnings (and grep exit code)

# Generate LongRunning, after changing the license text (because we use
# Apache for LRO where other languages use BSD)
sed -i s/license-header-bsd-3-clause.txt/license-header-apache-2.0.txt/g googleapis/google/longrunning/longrunning_gapic.yaml
generate_api Google.LongRunning google/longrunning longrunning/longrunning.yaml
git -C googleapis checkout google/longrunning/longrunning_gapic.yaml

# IAM (just proto and grpc)
$PROTOC \
  --csharp_out=apis/Google.Cloud.Iam.V1/Google.Cloud.Iam.V1 \
  --grpc_out=apis/Google.Cloud.Iam.V1/Google.Cloud.Iam.V1 \
  -I googleapis \
  -I $CORE_PROTOS_ROOT \
  --plugin=protoc-gen-grpc=$GRPC_PLUGIN \
  googleapis/google/iam/v1/*.proto

# Logging version-agnostic types
$PROTOC \
  --csharp_out=apis/Google.Cloud.Logging.Type/Google.Cloud.Logging.Type \
  -I googleapis \
  -I $CORE_PROTOS_ROOT \
  googleapis/google/logging/type/*.proto

# OS Login version-agnostic types
$PROTOC \
  --csharp_out=apis/Google.Cloud.OsLogin.Common/Google.Cloud.OsLogin.Common \
  -I googleapis \
  -I $CORE_PROTOS_ROOT \
  googleapis/google/cloud/oslogin/common/*.proto

# Now the per-API codegen
generate_api Google.Cloud.Asset.V1Beta1 google/cloud/asset/v1beta1 asset_v1beta1.yaml
generate_api Google.Cloud.BigQuery.DataTransfer.V1 google/cloud/bigquery/datatransfer/v1 datatransfer.yaml
generate_api Google.Cloud.Bigtable.Admin.V2 google/bigtable/admin/v2 bigtableadmin.yaml
generate_api Google.Cloud.Bigtable.V2 google/bigtable/v2 bigtable.yaml
generate_api Google.Cloud.Container.V1 google/container/v1 container.yaml
generate_api Google.Cloud.Dataproc.V1 google/cloud/dataproc/v1 v1/dataproc.yaml
generate_api Google.Cloud.Datastore.V1 google/datastore/v1 datastore.yaml
generate_api Google.Cloud.Debugger.V2 google/devtools/clouddebugger/v2 clouddebugger.yaml
generate_api Google.Cloud.Dialogflow.V2 google/cloud/dialogflow/v2 dialogflow_v2.yaml
generate_api Google.Cloud.Dlp.V2 google/privacy/dlp/v2 dlp_v2.yaml
generate_api Google.Cloud.ErrorReporting.V1Beta1 google/devtools/clouderrorreporting/v1beta1 errorreporting.yaml
generate_api Google.Cloud.Firestore.V1Beta1 google/firestore/v1beta1 firestore.yaml
generate_api Google.Cloud.Kms.V1 google/cloud/kms/v1 cloudkms.yaml
generate_api Google.Cloud.Language.V1 google/cloud/language/v1 language_v1.yaml
generate_api Google.Cloud.Logging.V2 google/logging/v2 logging.yaml
generate_api Google.Cloud.Monitoring.V3 google/monitoring/v3 monitoring.yaml
generate_api Google.Cloud.OsLogin.V1 google/cloud/oslogin/v1 oslogin_v1.yaml
generate_api Google.Cloud.OsLogin.V1Beta google/cloud/oslogin/v1beta oslogin_v1beta.yaml
generate_api Google.Cloud.PubSub.V1 google/pubsub/v1 pubsub.yaml
generate_api Google.Cloud.Redis.V1 google/cloud/redis/v1 redis_v1.yaml
generate_api Google.Cloud.Redis.V1Beta1 google/cloud/redis/v1beta1 redis_v1beta1.yaml
generate_api Google.Cloud.Spanner.Admin.Database.V1 google/spanner/admin/database/v1 spanner_admin_database.yaml
generate_api Google.Cloud.Spanner.Admin.Instance.V1 google/spanner/admin/instance/v1 spanner_admin_instance.yaml
generate_api Google.Cloud.Spanner.V1 google/spanner/v1 spanner.yaml
generate_api Google.Cloud.Speech.V1 google/cloud/speech/v1 speech_v1.yaml
generate_api Google.Cloud.Speech.V1P1Beta1 google/cloud/speech/v1p1beta1 speech_v1p1beta1.yaml
generate_api Google.Cloud.Tasks.V2Beta2 google/cloud/tasks/v2beta2 cloudtasks_v2beta2.yaml
generate_api Google.Cloud.Tasks.V2Beta3 google/cloud/tasks/v2beta3 cloudtasks_v2beta3.yaml
generate_api Google.Cloud.TextToSpeech.V1 google/cloud/texttospeech/v1 tts_v1.yaml
generate_api Google.Cloud.Trace.V1 google/devtools/cloudtrace/v1 cloudtrace_v1.yaml
generate_api Google.Cloud.Trace.V2 google/devtools/cloudtrace/v2 cloudtrace_v2.yaml
generate_api Google.Cloud.VideoIntelligence.V1 google/cloud/videointelligence/v1 videointelligence_v1.yaml
generate_api Google.Cloud.Vision.V1 google/cloud/vision/v1 vision_v1.yaml
generate_api Google.Cloud.Vision.V1P1Beta1 google/cloud/vision/v1p1beta1 vision_v1p1beta1.yaml
generate_api Google.Cloud.Vision.V1P2Beta1 google/cloud/vision/v1p2beta1 vision_v1p2beta1.yaml


text:
import argparse
import sys
import os
import epros_file
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
import numpy as np
from outliers import smirnov_grubbs as grubbs

# argparse for information
parser = argparse.ArgumentParser()
parser.add_argument("-e", "--energy", help="input energy profile directory")
parser.add_argument("-g", "--glob", help="globular proteins only")
parser.add_argument("-t", "--transmembrane", help="transmembrane proteins only, enter path/to/pdbtm_all.list.txt")
args = parser.parse_args()

# sanity check
if not len(sys.argv) > 1:
    print "this script takes a folder of energy files and prints out the quantil ranges"
    parser.print_help()
    sys.exit(0)

def plot_boxplot(energy_dict):
    print "plotting violin_box_plot"
    index = []
    data = []
    for i, (key, val) in enumerate(energy_dict.iteritems()):
        index.append(key)
        data.append(map(float, val))
    fig, (ax, ax2) = plt.subplots(ncols=2)
    ax.boxplot(data)
    ax.set_xticklabels(index)
    ax2.violinplot(data)
    ax2.set_xticks(range(1, len(index) + 1))
    ax2.set_xticklabels(index)
    plt.savefig('box_violin_plot.pdf')

# inserts a key value pair into the dict, or adds the value if the key exists
def insert_into_data_structure(key, value, dict):
    if not key in dict:
        dict[key] = [(value)]
    else:
        dict[key].append((value))

# ------------------------------------------------- main script ------------------------------------------------------ #

# pdbtm_all.list.txt
pdbtm_list = []
energy_list = []
counter = 0
total_file_count = sum([len(files) for r, d, files in os.walk(top=args.energy)])
print "started for:", total_file_count, "files"

if args.transmembrane:
    with open(args.transmembrane, 'r') as pdbtm_list_handle:
        for line in pdbtm_list_handle:
            line_array = line.split("_")
            pdbtm_list.append(line_array[0])
    print pdbtm_list

for dirpath, dir, files in os.walk(top=args.energy):
    for energy_file in files:
        line_count = 0
        counter += 1
        if counter % 10000 == 0:
            print energy_file
            percentage = (float(counter) / float(total_file_count))*100
            print"{:.2f}".format(percentage), "%"
        if energy_file.endswith(".ep2"):
            if args.glob:
                name = energy_file.split(".ep2")[0]
                if name in pdbtm_list:
                    continue
            if args.transmembrane:
                name = energy_file.split(".ep2")[0]
                if name not in pdbtm_list:
                    continue
            with open(dirpath + "/" + energy_file, 'r') as energy_file_handle:  # with open(energy_dir + file, 'r') as energy_file:
                for line in energy_file_handle:
                    line_array = line.split("\t")
                    if not "REMK" in line_array:
                        if line_count == 0:
                            name = line_array[1]
                        elif line_count == 1:
                            typ = line_array[1]
                        elif line_count == 2:
                            header = line_array
                        else:
                            # just extract the A Chain
                            # if line_array[1] == "B":
                            #    break
                            energy_list.append(line_array[5].rstrip())
                    line_count += 1

energy_list = [float(x) for x in energy_list]
energy_list.sort()
# remove outliers with grubbs algorithm
energy_list = grubbs.test(energy_list, alpha=0.05)
print "Quantiles for: ", total_file_count, "files"
quant = len(energy_list)/4
print quant, "entries per quantil"
print energy_list[0]
print energy_list[quant]
print energy_list[2*quant]
print energy_list[3*quant]
print energy_list[-1]

plt.figure()
plt.boxplot(energy_list, 0, '')
plt.savefig('quantiles.pdf')

###################### OUT
'''
119460386
Quantil:  29865096
-118.303418308
-21.3328509911
-9.26231037705
-3.33429827376
11.5566432042

whithout outliers
Quantil:  29864995
-81,4800043161
-21,3326960217
-9,26223609962
-3,33428488184
11,5566432042

new Quantile for globular:
-81.2912287163
-21.5377154868
-9.50643383752
-3.44146165978
11.768577356

Quantile for membrane:

3101 files
-12.2373208162
4.49279516205
8.98564351117
13.4598691639
46.4967251975

'''


text:
package randoop.test;

import randoop.sequence.ExecutableSequence;
import randoop.sequence.Execution;

// A better name for Check would be SequenceDecoration.

/**
 * A Check represents the expected runtime behavior of a Sequence, at a
 * particular offset. When a unit test is run as a regression test, it should
 * have the same behavior as it did previously, and the Check objects represent
 * that previous, expected behavior. Some examples of Checks are:
 *

 *
{@link ExpectedExceptionCheck} -- an exception should be thrown
 *
{@link NoExceptionCheck} -- no exception should be thrown
 *
{@link ObjectCheck} -- a particular {@link randoop.contract.ObjectContract} should hold
 *

 *
 * The visitor classes decorate a sequence with Check objects. A
 * Check object is inserted as a decoration on a specific index of
 * an {@link ExecutableSequence}. Thus, a check is always associated with a
 * specific index in a sequence. A check at index i means that the check is to
 * be performed after statement i finishes executing.
 *
 *

 *
 * A check implements two methods that specify the code to be emitted before
 * and/or after a statement in a Sequence is executed.
 *
 *

 *
 * A check may require some code to be emitted before and/or after the statement
 * is printed. For example, a check for checking that x is not null
 * after the statement "Foo x =
 * m()" is executed might emit the assertion code
 * "assertNotNull(x);", and would do so after the statement is
 * printed. As a second example, a check for checking that an expected exception
 * is thrown by a statement would need to emit something like
 * "try {" before the statement, and the catch clause after the
 * statement.
 *
 */
public interface Check {

  /**
   * Returns a string of Java source code to be emitted before a statement
   * containing this check.
   *
   * @return the string to be included before the statement
   */
  String toCodeStringPreStatement();

  /**
   * Returns a string of Java source code to be emitted after a statement
   * containing this check.
   *
   * @return the string to be included following the statement
   */
  String toCodeStringPostStatement();

  /**
   * Returns a short string that can be used to uniquely identify this check.
   *
   * @return a string "value" for this check
   */
  String getValue();

  /**
   * Returns a unique string identifier for the check. Two checks are the same
   * if these identifiers match. The value is NOT included. with. Used to match
   * up checks between the same sequence run at different times. Note that
   * because of changes in the environment (e.g., static variables), two
   * executions of the same sequence may have different checks (because the
   * existence of some checks depends on the value of variables)
   *
   * @return a unique string identifier for this check
   */
  String getID();

  /**
   * Returns the offset in the sequence of this check
   *
   * @return statement index for this check
   */
  int getStatementIndex();

  /**
   * Evaluates this check on the given execution of a sequence.
   *
   * @param execution
   *          the execution of sequence on which to test this check
   * @return true if check succeeded, and false otherwise.
   */
  boolean evaluate(Execution execution);
}


text:
<?php

/**
 * @see Zend_Service_DeveloperGarden_Request_RequestAbstract
 */
#require_once 'Zend/Service/DeveloperGarden/Request/RequestAbstract.php';

/**
 * @category   Zend
 * @package    Zend_Service
 * @subpackage DeveloperGarden
 * @copyright  Copyright (c) 2005-2014 Zend Technologies USA Inc. (http://www.zend.com)
 * @author     Marco Kaiser
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Service_DeveloperGarden_Request_ConferenceCall_CreateConferenceTemplateRequest
    extends Zend_Service_DeveloperGarden_Request_RequestAbstract
{
    /**
     * unique owner id
     *
     * @var string
     */
    public $ownerId = null;

    /**
     * object with details for this conference
     *
     * @var Zend_Service_DeveloperGarden_ConferenceCall_ConferenceDetail
     */
    public $detail = null;

    /**
     * array with Zend_Service_DeveloperGarden_ConferenceCall_ParticipantDetail elements
     *
     * @var array
     */
    public $participants = null;

    /**
     * constructor
     *
     * @param integer $environment
     * @param string $ownerId
     * @param Zend_Service_DeveloperGarden_ConferenceCall_ConferenceDetail $conferenceDetails
     * @param array $conferenceParticipants
     */
    public function __construct($environment, $ownerId,
        Zend_Service_DeveloperGarden_ConferenceCall_ConferenceDetail $conferenceDetails,
        array $conferenceParticipants = null
    ) {
        parent::__construct($environment);
        $this->setOwnerId($ownerId)
             ->setDetail($conferenceDetails)
             ->setParticipants($conferenceParticipants);
    }

    /**
     * sets $participants
     *
     * @param array $participants
     * @return Zend_Service_DeveloperGarden_Request_ConferenceCall_CreateConferenceTemplateRequest
     */
    public function setParticipants(array $participants = null)
    {
        $this->participants = $participants;
        return $this;
    }

    /**
     * sets $detail
     *
     * @param Zend_Service_DeveloperGarden_ConferenceCall_ConferenceDetail $detail
     * @return Zend_Service_DeveloperGarden_Request_ConferenceCall_CreateConferenceTemplateRequest
     */
    public function setDetail(Zend_Service_DeveloperGarden_ConferenceCall_ConferenceDetail $detail)
    {
        $this->detail = $detail;
        return $this;
    }

    /**
     * sets $ownerId
     *
     * @param string $ownerId
     * @return Zend_Service_DeveloperGarden_Request_ConferenceCall_CreateConferenceTemplateRequest
     */
    public function setOwnerId($ownerId)
    {
        $this->ownerId = $ownerId;
        return $this;
    }
}


text:
<form class="uk-article uk-form uk-form-stacked" action="<?= $view->url('@user/resetpassword/request') ?>" method="post">

<?= __('Forgot password') ?>

<?= __('Please enter your email address. You will receive a link to create a new password via email.') ?>

        <?= __('Email') ?>

            <input id="form-username" type="text" name="email" value="" required autofocus>

        <button class="uk-button uk-button-primary" type="submit"><?= __('Submit') ?></button>

    <?php $view->token()->get() ?>

</form>


text:
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using Polly.Retry;
using Stardust.Manager.Extensions;
using Stardust.Manager.Interfaces;
using Stardust.Manager.Models;

namespace Stardust.Manager
{
	public class WorkerNodeRepository : IWorkerNodeRepository
	{
		private readonly string _connectionString;
		private readonly RetryPolicy _retryPolicy;

		public WorkerNodeRepository(ManagerConfiguration managerConfiguration,
		                            RetryPolicyProvider retryPolicyProvider)
		{
			_connectionString = managerConfiguration.ConnectionString;
			_retryPolicy = retryPolicyProvider.GetPolicy();
		}

		public void AddWorkerNode(WorkerNode workerNode)
		{
			const string selectWorkerNodeCommand = "INSERT INTO [Stardust].[WorkerNode] (Id, Url, Heartbeat, Alive) VALUES(@Id, @Url, @Heartbeat, @Alive)";
			try
			{
				using (var connection = new SqlConnection(_connectionString))
				{
                    _retryPolicy.Execute(connection.Open);

					using (var workerNodeCommand = new SqlCommand(selectWorkerNodeCommand, connection))
					{
						workerNodeCommand.Parameters.AddWithValue("@Id", workerNode.Id);
						workerNodeCommand.Parameters.AddWithValue("@Url", workerNode.Url.ToString());
						workerNodeCommand.Parameters.AddWithValue("@Heartbeat", workerNode.Heartbeat);
						workerNodeCommand.Parameters.AddWithValue("@Alive", workerNode.Alive);

                        _retryPolicy.Execute(workerNodeCommand.ExecuteNonQuery);
					}
				}
			}
			catch (Exception exp)
			{
				if (exp.Message.Contains("UQ_WorkerNodes_Url"))
				{
					using (var connection = new SqlConnection(_connectionString))
					{
                        _retryPolicy.Execute(connection.Open);
						const string updateCommandText = @"UPDATE [Stardust].[WorkerNode] SET Heartbeat = @Heartbeat,
											Alive = @Alive
											WHERE Url = @Url";

						using (var command = new SqlCommand(updateCommandText, connection))
						{
							command.Parameters.Add("@Heartbeat", SqlDbType.DateTime).Value = DateTime.UtcNow;
							command.Parameters.Add("@Alive", SqlDbType.Bit).Value = true;
							command.Parameters.Add("@Url", SqlDbType.NVarChar).Value = workerNode.Url.ToString();

                            _retryPolicy.Execute(command.ExecuteNonQuery);
						}
					}
					return;
				}

				this.Log().ErrorWithLineNumber(exp.Message, exp);
				throw;
			}
		}

		public List<string> CheckNodesAreAlive(TimeSpan timeSpan)
		{
			const string selectCommand = @"SELECT Id,
										 Url,
										 Heartbeat,
										 Alive
								 FROM [Stardust].[WorkerNode] WHERE Alive = 1";

			const string updateCommandText = @"UPDATE [Stardust].[WorkerNode]
											SET Alive = @Alive
										WHERE Url = @Url";

			var deadNodes = new List<string>();
			try
			{
				using (var connection = new SqlConnection(_connectionString))
				{
                    _retryPolicy.Execute(connection.Open);

					var allAliveNodes = new List<Tuple<DateTime,string>>();
					using (var commandSelectAll = new SqlCommand(selectCommand, connection))
					{
						using (var readAllWorkerNodes = _retryPolicy.Execute(commandSelectAll.ExecuteReader))
						{
							if (readAllWorkerNodes.HasRows)
							{
								var ordinalPosForHeartBeat = readAllWorkerNodes.GetOrdinal("Heartbeat");
								var ordinalPosForUrl = readAllWorkerNodes.GetOrdinal("Url");

								while (readAllWorkerNodes.Read())
								{
									allAliveNodes.Add(new Tuple<DateTime, string>(readAllWorkerNodes.GetDateTime(ordinalPosForHeartBeat),
										readAllWorkerNodes.GetString(ordinalPosForUrl)));
								}
							}
						}
					}

					if (allAliveNodes.Any())
					{
						using (var trans = connection.BeginTransaction())
						{
							using (var commandUpdate = new SqlCommand(updateCommandText, connection, trans))
							{
								commandUpdate.Parameters.Add("@Alive", SqlDbType.Bit);
								commandUpdate.Parameters.Add("@Url", SqlDbType.NVarChar);

								foreach (var node in allAliveNodes)
								{
									var heartBeatDateTime = node.Item1;
									var url = node.Item2;
									var currentDateTime = DateTime.UtcNow;
									var dateDiff = (currentDateTime - heartBeatDateTime).TotalSeconds;
									if (dateDiff <= timeSpan.TotalSeconds) continue;

									commandUpdate.Parameters["@Alive"].Value = false;
									commandUpdate.Parameters["@Url"].Value = url;
                                    _retryPolicy.Execute(commandUpdate.ExecuteNonQuery);
									deadNodes.Add(url);
								}
							}
							trans.Commit();
						}
					}
				}
			}
			catch (Exception exp)
			{
				this.Log().ErrorWithLineNumber(exp.Message, exp);
				throw;
			}

			return deadNodes;
		}

		public void RegisterHeartbeat(string nodeUri, bool updateStatus)
		{
			try
			{
				using (var connection = new SqlConnection(_connectionString))
				{
                    _retryPolicy.Execute(connection.Open);

					var updateCommandText = @"UPDATE [Stardust].[WorkerNode] SET Heartbeat = GETUTCDATE(),
											Alive = 1
											WHERE Url = @Url
											IF @@ROWCOUNT = 0
											BEGIN
											INSERT INTO [Stardust].[WorkerNode] (Id, Url, Heartbeat, Alive)
											VALUES(NEWID(), @Url, GETUTCDATE(), 1)
											END";

					if (!updateStatus)
					{
						updateCommandText = @"UPDATE [Stardust].[WorkerNode] SET Heartbeat = GETUTCDATE()
											WHERE Url = @Url";
					}

					using (var command = new SqlCommand(updateCommandText, connection))
					{
						command.Parameters.Add("@Url", SqlDbType.NVarChar).Value = nodeUri;
                        _retryPolicy.Execute(command.ExecuteNonQuery);
					}
				}
			}

			catch (Exception exp)
			{
				this.Log().ErrorWithLineNumber(exp.Message, exp);
				throw;
			}
		}
	}
}


text:
{% extends "profile/base.html" %}

{% load i18n %}
{% load crispy_forms_tags %}
{% load thumbnail %}

{% block head_title %}{% trans "Sign In" %}{% endblock %}

{% block content %}

      <form method="post" action="{% url 'profile:edit' userprofile.id %}" enctype="multipart/form-data">
        {% csrf_token %}
        {{ form.as_p }}
        <button class="btn btn-primary" type="submit">{% trans "Save" %}</button>
      </form>
      {% for item in ablum %}

        {% thumbnail item.image "200" as im %}

        {% endthumbnail %}
        <button class="deleteImage" data-url="{{item.get_absolute_url}}">Delete</button>

      {% endfor %}

<form id="upload" method="post" action="{% url 'profile:ablumList' userprofile.id %}" enctype="multipart/form-data">

        Drop Here

        Browse
        <input type="file" name="upload" multiple />

</form>

{% endblock %}

{% block extra_js %}

{% endblock extra_js %}


text:
using IIUWr.Fereol.Common;
using IIUWr.Fereol.Interface;
using IIUWr.ViewModels.Fereol;
using LionCub.Patterns.DependencyInjection;
using System;
using Windows.Storage;
using HTMLParsing = IIUWr.Fereol.HTMLParsing;

namespace IIUWr
{
    public static class DemoModeHelper
    {
        private const string Key = "demo-mode";

        public static bool IsDemoMode
        {
            get
            {
                ApplicationData.Current.LocalSettings.Values.TryGetValue(Key, out object demoMode);
                return demoMode != null && demoMode is bool demo && demo;
            }
            set
            {
                ApplicationData.Current.LocalSettings.Values[Key] = value;
            }
        }

        public static bool ToggleModeByLogin(string login)
        {
            if (login == "demo" && !IsDemoMode)
            {
                IsDemoMode = true;
                return true;
            }
            if (login == "notDemo" && IsDemoMode)
            {
                IsDemoMode = false;
                return true;
            }
            return false;
        }
    }

    public static class ConfigureIoC
    {
        public static void All()
        {
            if (DemoModeHelper.IsDemoMode)
            {
#if DEBUG
                IoC.AsInstance(new Uri(@"http://localhost:8002/"));
#else
                IoC.AsInstance(new Uri(@"http://soltysik.net.pl:8002/"));
#endif

            }
            else
            {
                IoC.AsInstance(new Uri(@"https://zapisy.ii.uni.wroc.pl/"));
            }

            ViewModels();
            Fereol.Common();

            Fereol.HTMLParsing();
            Fereol.WebAPI();
        }

        public static void ViewModels()
        {
            IoC.AsSingleton<SemestersViewModel>();
            IoC.AsSingleton<ScheduleViewModel>();
        }

        public static class Fereol
        {
            public static void Common()
            {
                IoC.AsSingleton<ICredentialsManager, CredentialsManager>();
                IoC.AsSingleton<ISessionManager, CredentialsManager>();
            }

            public static void HTMLParsing()
            {
                IoC.AsSingleton<IConnection, HTMLParsing.Connection>();
                IoC.AsSingleton<HTMLParsing.Interface.IHTTPConnection, HTMLParsing.Connection>();

                IoC.AsSingleton<ICoursesService, HTMLParsing.CoursesService>();
                IoC.AsSingleton<IScheduleService, HTMLParsing.ScheduleService>();
            }

            public static void WebAPI()
            {
                IoC.AsSingleton<IIUWr.Fereol.WebAPI.Interface.ICoursesService, IIUWr.Fereol.WebAPI.CoursesService>();
            }
        }
    }
}


text:
Provides access to the phone's system contacts.

# API documentation

- [Documentation for the master branch](https://github.com/expo/expo/blob/master/docs/pages/versions/unversioned/sdk/contacts.md)
- [Documentation for the latest stable release](https://docs.expo.io/versions/latest/sdk/contacts/)

# Installation in managed Expo projects

For [managed](https://docs.expo.io/versions/latest/introduction/managed-vs-bare/) Expo projects, please follow the installation instructions in the [API documentation for the latest stable release](https://docs.expo.io/versions/latest/sdk/contacts/).

# Installation in bare React Native projects

For bare React Native projects, you must ensure that you have [installed and configured the `expo` package](https://docs.expo.dev/bare/installing-expo-modules/) before continuing.

### Add the package to your npm dependencies

```
expo install expo-contacts
```

### Configure for iOS

Add `NSContactsUsageDescription` key to your `Info.plist`:

```xml
<key>NSContactsUsageDescription</key>
<string>Allow $(PRODUCT_NAME) to access your contacts</string>
```

Run `npx pod-install` after installing the npm package.

### Configure for Android

Add `android.permission.READ_CONTACTS` and optionally `android.permission.WRITE_CONTACTS` permissions to your manifest (`android/app/src/main/AndroidManifest.xml`):

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

# Contributing

Contributions are very welcome! Please refer to guidelines described in the [contributing guide](https://github.com/expo/expo#contributing).


text:
/**
 * Setup extra generator options
 */

'use strict';

var installConfig = function installConfig() {
  var self = this;

  this.on('end', function() {
    this.installDependencies({
      bower: false,
      skipInstall: this.options['skip-install'],
      callback: function() {
        self.log('\n' + 'Everything looks ready!'.blue +
          ' Get started by running "' + 'gulp serve'.green + '".\n'
        );
      }
    });
  });
};

module.exports = installConfig;


text:
package org.apache.camel.component.stitch.client;

import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.Map;

import org.apache.camel.component.stitch.StitchTestUtils;
import org.apache.camel.component.stitch.client.models.StitchException;
import org.apache.camel.component.stitch.client.models.StitchMessage;
import org.apache.camel.component.stitch.client.models.StitchRequestBody;
import org.apache.camel.component.stitch.client.models.StitchResponse;
import org.apache.camel.component.stitch.client.models.StitchSchema;
import org.junit.jupiter.api.Test;

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertThrows;

class StitchClientImplIT {

    @Test
    void testIfCreateBatch() throws Exception {
        final StitchClient client = StitchClientBuilder.builder()
                .withRegion(StitchRegion.EUROPE)
                .withToken(StitchTestUtils.loadStitchTokenFromJvmEnv().getProperty("token"))
                .build();

        final StitchMessage message1 = StitchMessage.builder()
                .withData("id", 2)
                .withData("name", "Jake")
                .withData("age", 6)
                .withData("has_magic", true)
                .withSequence(1565881320)
                .build();

        final Map<String, Object> properties = new LinkedHashMap<>();
        properties.put("id", Collections.singletonMap("type", "integer"));
        properties.put("name", Collections.singletonMap("type", "string"));
        properties.put("age", Collections.singletonMap("type", "integer"));
        properties.put("has_magic", Collections.singletonMap("type", "boolean"));

        final StitchSchema schema = StitchSchema.builder()
                .addKeyword("properties", properties)
                .build();

        final StitchRequestBody body = StitchRequestBody.builder()
                .withTableName("test")
                .addMessage(message1)
                .withSchema(schema)
                .withKeyNames("id")
                .build();

        StitchResponse response = client.batch(body).block();

        assertNotNull(response);
        assertEquals(201, response.getHttpStatusCode());
    }

    @Test
    void testIfThrowError() throws Exception {
        final StitchClient client = StitchClientBuilder.builder()
                .withRegion(StitchRegion.EUROPE)
                .withToken(StitchTestUtils.loadStitchTokenFromJvmEnv().getProperty("token"))
                .build();

        final StitchMessage message1 = StitchMessage.builder()
                .withData("id", 2)
                .withData("name", "Jake")
                .withData("age", 6)
                .withData("has_magic", true)
                .withSequence(1565881320)
                .build();

        final Map<String, Object> properties = new LinkedHashMap<>();
        properties.put("id", Collections.singletonMap("type", "integer"));
        properties.put("name", Collections.singletonMap("type", "string"));
        properties.put("age", Collections.singletonMap("type", "integer"));
        properties.put("has_magic", Collections.singletonMap("type", "integerr"));

        final StitchSchema schema = StitchSchema.builder()
                .addKeyword("properties", properties)
                .build();

        final StitchRequestBody body = StitchRequestBody.builder()
                .withTableName("test")
                .addMessage(message1)
                .withSchema(schema)
                .withKeyNames("id")
                .build();

        assertThrows(StitchException.class, () -> client.batch(body).block());
    }
}


text:
import { Component } from '@angular/core';
import {TaskService} from '../../services/task.service';
import {Task} from '../../../Task';
import {Router} from '@angular/router';

@Component({
  moduleId: module.id,
  selector: 'tasks',
  templateUrl: 'tasks.component.html'
})

export class TasksComponent {
    tasks: Task[];
    static id:Number=0;
    name: string;
    description:string;
    progress:string;
    books:string;
    uid:Number;
    constructor(private taskService:TaskService,private route:Router){
        this.taskService.getTasks()
            .subscribe(tasks => {
                console.log("Tasks received successfully");
                console.log(tasks);
                this.tasks = tasks;
            });
    }
    handleError(error:any):Promise<any>{
        console.error("An error occured",error);
        return Promise.reject(error.message || error);
    }
    get UserId(){
        return this.taskService.getUdata().subscribe(data=>{
            this.uid=+(data[0]['id']);
        })
    }
    addT(event:Event):void{
        event.preventDefault();
        var newTask = {
            name:this.name,
            description:this.description,
            progress:this.progress,
            books:this.books
        }
        this.taskService.addTask(this.name,this.description,this.progress,this.books,this.uid)
            .subscribe(task => {
                this.tasks.push(task);
                console.log("Request Succesful");
                console.log(task);
                this.name= '';
                this.description='',
                this.books=''
            },
            err=>this.handleError(err));
    }
    addT1(event:Event):void{
        event.preventDefault();
        var newTask = {
            name:this.name,
            description:this.description,
            progress:this.progress,
            books:this.books
        }
        this.taskService.addTask1(this.name,this.description,this.progress,this.books,this.uid)
            .subscribe(task => {
                this.tasks.push(task);
                console.log("Request Succesful");
                console.log(task);
                this.name= '';
                this.description='',
                this.books=''
            },
            err=>this.handleError(err));
    }
    goBack(){
        this.route.navigate(['/user',this.uid]);
    }
    deleteT(id:Number):void{
        var tasks = this.tasks;
        this.taskService.deleteTask(id).subscribe(data => {
                for(var i = 0;i < tasks.length;i++){
                    if(tasks[i]._id == id){
                        tasks.splice(i, 1);
                    }
                }

        },
        err=>this.handleError(err));
    }

    /*updateStatus(task:Task){
        var _task = {
            _id:task._id,
            title: task.title,
            isDone: !task.isDone
        };

        this.taskService.updateStatus(_task).subscribe(data => {
            task.isDone = !task.isDone;
        });
    }*/
}


text:
{% include "breadcrumbs" %}

{% if page.headline.size > 0 %}

{{ page.headline }}

{% endif %}

	{% if request.logged_in? %}

	  {% if request.current_signup.has_facebook_authorization? %}

	       You connected your Facebook account.

	      {% include "find_friends_facebook" %}

	  {% else %}

	     You have not connected your Facebook account.

 Sign in with Facebook

	  {% endif %}

	  {% if request.current_signup.has_twitter_authorization? %}

	     You connected your Twitter account.

	      {% include "find_friends_twitter" %}

	  {% else %}

	     You have not connected your Twitter account.

 Sign in with Twitter

	  {% endif %}

	{% else %}

	  You have not connected your Facebook account.

 Sign in with Facebook

	  You have not connected your Twitter account.

 Sign in with Twitter

	{% endif %}


text:
package mailyak

import (
	"bytes"
	"fmt"
	"io"
	"net/smtp"
	"strings"
	"testing"
)

// TestHTML ensures we can write to HTML as an io.Writer
func TestHTML(t *testing.T) {
	t.Parallel()

	tests := []struct {
		name string
		// Parameters.
		data []string
	}{
		{
			"Writer test",
			[]string{"Worst idea since someone said 'yeah let's take this suspiciously large " +
				"wooden horse into Troy, statues are all the rage this season'.",
			},
		},
		{
			"Writer test multiple",
			[]string{
				"Worst idea since someone said 'yeah let's take this suspiciously large " +
					"wooden horse into Troy, statues are all the rage this season'.",
				"Am I jumping the gun, Baldrick, or are the words 'I have a cunning plan' " +
					"marching with ill-deserved confidence in the direction of this conversation?",
			},
		},
	}
	for _, tt := range tests {
		tt := tt
		t.Run(tt.name, func(t *testing.T) {
			t.Parallel()

			mail := New("", smtp.PlainAuth("", "", "", ""))

			for _, data := range tt.data {
				if _, err := io.WriteString(mail.HTML(), data); err != nil {
					t.Errorf("%q. HTML() error = %v", tt.name, err)
					continue
				}
			}

			if !bytes.Equal([]byte(strings.Join(tt.data, "")), mail.html.Bytes()) {
				t.Errorf("%q. HTML() = %v, want %v", tt.name, mail.html.String(), tt.data)
			}
		})
	}
}

// TestPlain ensures we can write to Plain as an io.Writer
func TestPlain(t *testing.T) {
	t.Parallel()

	tests := []struct {
		name string
		// Parameters.
		data string
	}{
		{
			"Writer test",
			"Am I jumping the gun, Baldrick, or are the words 'I have a cunning plan' " +
				"marching with ill-deserved confidence in the direction of this conversation?",
		},
	}
	for _, tt := range tests {
		tt := tt
		t.Run(tt.name, func(t *testing.T) {
			t.Parallel()

			mail := New("", smtp.PlainAuth("", "", "", ""))

			if _, err := io.WriteString(mail.Plain(), tt.data); err != nil {
				t.Fatalf("%q. Plain() error = %v", tt.name, err)
			}

			if !bytes.Equal([]byte(tt.data), mail.plain.Bytes()) {
				t.Errorf("%q. Plain() = %v, want %v", tt.name, mail.plain.String(), tt.data)
			}
		})
	}
}

// TestWritableString ensures the writable type returns a string when called
// with fmt.Printx(), etc
func TestWritableString(t *testing.T) {
	t.Parallel()

	tests := []struct {
		name string
		// Parameters.
		data string
	}{
		{
			"String test",
			"Baldrick, does it have to be this way? " +
				"Our valued friendship ending with me cutting you up into strips and telling " +
				"the prince that you walked over a very sharp cattle grid in an extremely heavy hat?",
		},
	}
	for _, tt := range tests {
		tt := tt
		t.Run(tt.name, func(t *testing.T) {
			t.Parallel()

			mail := New("", smtp.PlainAuth("", "", "", ""))

			if _, err := io.WriteString(mail.Plain(), tt.data); err != nil {
				t.Fatalf("%q. Plain() error = %v", tt.name, err)
			}

			if tt.data != mail.plain.String() {
				t.Errorf("%q. writable.String() = %v, want %v", tt.name, mail.plain.String(), tt.data)
			}

			if out := fmt.Sprintf("%v", mail.plain.String()); out != tt.data {
				t.Errorf("%q. writable.String() via fmt.Sprintf = %v, want %v", tt.name, out, tt.data)
			}
		})
	}
}

// TestPlain_String ensures we can use the string setter
func TestPlain_String(t *testing.T) {
	t.Parallel()

	tests := []struct {
		name string
		// Parameters.
		data string
	}{
		{
			"Writer test",
			"Am I jumping the gun, Baldrick, or are the words 'I have a cunning plan' " +
				"marching with ill-deserved confidence in the direction of this conversation?",
		},
	}
	for _, tt := range tests {
		tt := tt
		t.Run(tt.name, func(t *testing.T) {
			t.Parallel()

			mail := New("", smtp.PlainAuth("", "", "", ""))

			if _, err := io.WriteString(mail.Plain(), tt.data); err != nil {
				t.Fatalf("%q. Plain() error = %v", tt.name, err)
			}

			if !bytes.Equal([]byte(tt.data), mail.plain.Bytes()) {
				t.Errorf("%q. Plain() = %v, want %v", tt.name, mail.plain.String(), tt.data)
			}
		})
	}
}


text:
using System;

namespace SharpDX.DirectWrite
{
    public partial class Typography
    {
        /// <summary>
        /// Creates a typography object for use in a text layout.
        /// </summary>
        /// <param name="factory">an instance of <see cref = "SharpDX.DirectWrite.Factory" /></param>
        /// <unmanaged>HRESULT IDWriteFactory::CreateTypography([Out] IDWriteTypography** typography)</unmanaged>
        public Typography(Factory factory)
        {
            factory.CreateTypography(this);
        }
    }
}


text:
.. Common library

Common library
==============

Overview
--------

Common library is a set of useful classes and traits that are in almost every class
in the entire Slick framework. They form a solid base to develop on top of and help
you remove the tedious work of create getters, setters, allow read end or write access
to the properties and inspect classes and properties.

Understanding the "Base" class
------------------------------

The ``Slick\Common\Base`` class is on of the most important classes of Slick. It is responsible for the
"magic" in classes that extends it. It is very important that you have a clear understanding of what
this class does to really speed up your development.

Defining class properties
~~~~~~~~~~~~~~~~~~~~~~~~~

When defining properties in classes that extend ``Slick\Common\Base`` you have to follow a simple convention:

* properties must be prefixed with an "_" (underscore);
* property visibility is defined as ``protected``;
* property names are camel cased;
* use one of ``@read``, ``@write`` or ``@readwrite`` notations to define the public access mode to those properties.

Lets see an example:

.. code-block:: php

    <?php

    use Slick\Common\Base;

    class MyClass extends Base
    {

        /**
         * @readwrite
         * @var string
         */
        protected $_name;

        ...
    }

    $myClass = new MyClass();

    $myClass->name = "Foo";
    echo $myClass->name;        // This will print out "Foo"

As you can see in this example, defining property ``MyClass::$_name`` is in fact very simple. The ``@readwrite``
notation says that it has read/write access to it and it is a protected property.

Did you notice the way we access the ``MyClass::$_name``? Yes, we access it as it was a ``public`` property!

This is the first feature of ``Slick\Common\Base``: to expose this properties in a ``public`` fashion
using the PHP ``__get()`` and ``__set()`` magic methods.

The notations used are defined as followed:

* ``@read`` The property can be accessed as a read only. Any attempt to assign a value to a read only property will raise a ``Slick\Common\Exception\ReadOnlyException`` exception. This is the default behavior if no notation is provided;
* ``@write`` A value can be assigned to the property. Any attempt to read the property value will raise a ``Slick\Common\Exception\WriteOnlyException`` exception;
* ``@readwrite`` The property can be read or changed as a ``public`` property.

.. note::

    This feature can be also achieved using ``private`` as visibility, however it will not work with objects
    of classes that extend the one using ``private`` visibility as it cannot be accessed by them.

.. warning::

    Any attempt to assign or read an undefined property on classes that extends ``Slick\Common\Base`` will
    raise a ``Slick\Common\Exception\UndefinedPropertyException`` exception. This is a great way to avoid
    dynamic change of objects.

Getters and Setters
~~~~~~~~~~~~~~~~~~~


text:
define([
        "lib/classy",
        "core/framework/CoreStringUtils",
        "core/framework/TundraLogging",
        "core/frame/AsyncHelper"
    ], function(Class, CoreStringUtils, TundraLogging, AsyncHelper) {

var WebSocketTester = Class.$extend(
/** @lends WebSocketTester.prototype */
{
    /**
        WebSocket connection tester.

        @constructs
    */
    __init__ : function()
    {
        this.log = TundraLogging.getLogger("WebSocketTester");
        this.timing = new AsyncHelper("WebSocketTester", this);
    },

    /**
        @param {String} eventName Available event names 'connected', 'disconnected', 'error', 'message'
        @return {jQuery.Promise}
    */
    on : function(eventName)
    {
        eventName = eventName.trim().toLowerCase();
        if (eventName === "connected" && this.isConnected())
            return this.timing.deferImmediate(eventName, true, {});
        return this.timing.defer(eventName);
    },

    /**
        @param {String} url
        @param {Object} options
    */
    connect : function(url, options)
    {
        this.options = $.extend({
            message : "", // Message to send after connected
            disconnectOnFirstMessage : true,
            showDialogOnError : true
        }, options);

        url = url.trim();
        if (CoreStringUtils.startsWith(url, "http://", true))
            url = url.substring(7);
        else if (CoreStringUtils.startsWith(url, "https://", true))
            url = url.substring(8);
        if (!CoreStringUtils.startsWith(url, "ws://") && !CoreStringUtils.startsWith(url, "wss://"))
            url = "ws://" + url;

        this.websocket = new WebSocket(url);
        this.websocket.onopen = this.onOpened.bind(this);
        this.websocket.onerror = this.onError.bind(this);
        this.websocket.onclose = this.onClosed.bind(this);
        this.websocket.onmessage = this.onMessage.bind(this);
    },

    /**
        @function
    */
    disconnect : function()
    {
        if (this.websocket !== undefined)
            this.websocket.close();
        this.websocket = undefined;
    },

    /**
        @return {Boolean}
    */
    isConnected : function()
    {
        if (this.websocket === undefined)
            return false;
        else if (this.websocket.readyState !== 3) // CLOSED
            return true;
        return false;
    },

    /**
        @param {String} msg
    */
    send : function(msg)
    {
        if (this.websocket !== undefined)
            this.websocket.send(msg);
    },

    onOpened : function(e)
    {
        this.log.debug("connected");
        this._dispatch("connected", true, e);

        if (typeof this.options.message === "string" && this.options.message !== "")
        {
            this.send(this.options.message)
            this.options.message = undefined;
        }
    },

    onError : function(e)
    {
        this.log.debug("error", e);
        this._dispatch("error", true, e);

        if (this.options.showDialogOnError === true)
        {
            Tundra.ui.openModalDialog({
                heading : "Restricted Network",
                html : '
Check your firewall settings or contact your network administrator.
' +
                       '
',
                icon : "warning",
                iconColor : "rgb(207, 190, 16)"
            });
        }
    },

    onClosed : function(e)
    {
        this.log.debug("disconnected");
        this._dispatch("disconnected", true, e);
    },

    onMessage : function(e)
    {
        this.log.debug("message", e);
        this._dispatch("message", true, e);

        if (this.options.disconnectOnFirstMessage === true)
            this.disconnect();
    },

    _dispatch : function(name, success, e)
    {
        try
        {
            this.timing.resolve(name, success, e)
        }
        catch(ex)
        {
            this.log.error("Exception in '" + name + "' handlers:", ex);
        }
    }
});

return WebSocketTester;

}); // require js


text:
class Array
  attr_accessor :from_cache

  def from_cache?
    @from_cache ||= false
  end
end


text:
import aiohttp
import asyncio
from bs4 import BeautifulSoup
from bs4 import NavigableString
from .errors import *
from .Parsing import *

class Shosetsu:
    def __init__(self, loop=None):
        self.session = aiohttp.ClientSession()
        self.base_url = "https://vndb.org"
        self.headers = {"User-Agent": "Shosetsu 1.0 / Aiohttp / Python 3"}
        self.stypes = {'v': 'Visual Novels', 'r': 'Releases', 'p': 'Producers',
                       's': 'Staff', 'c': 'Characters', 'g': 'Tags',
                       'i': 'Traits', 'u': 'Users'}

    async def search_vndb(self, stype, term):
        """
        Search vndb.org for a term and return matching results from type.

        :param stype: type to search for.
            Type should be one of:
                v - Visual Novels
                r - Releases
                p - Producers
                s - Staff
                c - Characters
                g - Tags
                i - traits
                u - Users
        :param term: string to search for
        :return: Results. Result format depends on what you searched for. See the Parsing.py module for more specific documentation.

        Exceptions:
            aiohttp.HttpBadRequest - On 404s
            VNDBOneResult - When you search for something but it instead redirects us to a direct content page
            VNDBNoResults - When nothing was found for that search
            VNDBBadStype - Raised when an incorrect search type is passed
        """
        fstype = ""
        if stype not in ['v', 'r', 'p', 's', 'c', 'g', 'i', 'u']:
            raise VNDBBadStype(stype)
        else:
            if stype in ['v', 'p', 's', 'c', 'u']:
                fstype = '/{}/all'.format(stype)
            elif stype in ['g', 'i']:
                fstype = '/{}/list'.format(stype)
            elif stype == 'r':
                fstype = '/r'
        async with self.session.get(self.base_url + "{}".format(fstype), params={"q": term}, headers=self.headers) as response:
            if response.status == 404:
                raise aiohttp.HttpBadRequest("VN Not Found")
            elif 'q=' not in response.url:
                raise VNDBOneResult(term, response.url.rsplit('/', 1)[1])
            text = await response.text()
            if 'No Results' in text:
                raise VNDBNoResults(term)
            soup = BeautifulSoup(text, 'lxml')
            resp = await self.parse_search(stype, soup)
            if resp == []:
                raise VNDBNoResults(term)
            return resp

    async def get_novel(self, term, **kwargs):
        """
        If term is an ID will return that specific ID. If it's a string, it will return the details of the first search result for that term.
        Returned Dictionary Has the following structure:
        Please note, if it says list or dict, it means the python types.
        Indentation indicates level. So English is ['Titles']['English']

        'Titles' - Contains all the titles found for the anime
            'English' - English title of the novel
            'Alt' - Alternative title (Usually the Japanese one, but other languages exist)
            'Aliases' - A list of str that define the aliases as given in VNDB.
        'Img' - Link to the Image shown on VNDB for that Visual Novel
        'Length' - Length given by VNDB
        'Developers' - A list containing the Developers of the VN.
        'Publishers' - A list containing the Publishers of the VN.
        'Tags' - Contains 3 lists of different tag categories
            'Content' - List of tags that have to do with the story's content as defined by VNDB. Ex: Edo Era
            'Technology' - List of tags that have to do with the VN's technology. Ex: Protagonist with a Face (Wew Lad, 21st century)
            'Erotic' - List of tags that have to do with the VN's sexual content. Ex: Tentacles
        'Releases' - A list of dictionaries. They have the following format.
            'Date' - Date VNDB lists for release
            'Ages' - Age group appropriate for as determined on VNDB
            'Platform' - Release Platform
            'Name' - The name for this particular Release
            'ID' - The id for this release, also doubles as the link if you append https://vndb.org/ to it
        'Description' - Contains novel description text if there is any.
        'ID' - The id for this novel, also doubles as the link if you append https://vndb.org/ to it

        :param term: id or name to get details of.
        :param hide_nsfw: bool if 'Img' should filter links flagged as NSFW or not.
        :return dict: Dictionary with the parsed results of a novel
        """
        hide_nsfw = kwargs.get('hide_nsfw')
        if not term.isdigit() and not term.startswith('v'):
            vnid = await self.search_vndb('v', term)
            vnid = vnid[0]['id']
        else:
            vnid = str(term)
            if not vnid.startswith('v'):
                vnid = 'v' + vnid
        async with self.session.get(self.base_url + "/{}".format(vnid), headers=self.headers) as response:
            if response.status == 404:
                raise aiohttp.HttpBadRequest("VNDB reported that there is no data for ID {}".format(vnid))
            text = await response.text()
            soup = BeautifulSoup(text, 'lxml')
            data = {'titles': {'english': [], 'alt': [], 'aliases': []}, 'img': None, 'length': None, 'developers': [], 'publishers': [], 'tags': {}, 'releases': {}, 'id': vnid}
            data['titles']['english'] = soup.find_all('div', class_='mainbox')[0].h1.string
            try:
                data['titles']['alt'] = soup.find_all('h2', class_='alttitle')[0].string
            except IndexError:
                data['titles']['alt'] = None
            try:
                imgdiv = soup.find_all('div', class_='vnimg')[0]
                if not (hide_nsfw and 'class' in imgdiv.p.attrs):
                    data['img'] = 'https:' + imgdiv.img.get('src')
            except AttributeError:
                pass
            for item in soup.find_all('tr'):
                if 'class' in item.attrs or len(list(item.children)) == 1:
                    continue
                if item.td.string == 'Aliases':
                    tlist = []
                    for alias in list(item.children)[1:]:
                        tlist.append(alias.string)
                    data['titles']['aliases'] = tlist
                elif item.td.string == 'Length':
                    data['length'] = list(item.children)[1].string
                elif item.td.string == 'Developer':
                    tl = []
                    for item in list(list(item.children)[1].children):
                        if isinstance(item, NavigableString):
                            continue
                        if 'href' in item.attrs:
                            tl.append(item.string)
                    data['developers'] = tl
                    del tl
                elif item.td.string == 'Publishers':
                    tl = []
                    for item in list(list(item.children)[1].children):
                        if isinstance(item, NavigableString):
                            continue
                        if 'href' in item.attrs:
                            tl.append(item.string)
                    data['publishers'] = tl
            conttags = []
            techtags = []
            erotags = []
            test = soup.find('div', attrs={'id': 'vntags'})
            if test:
                for item in list(test.children):
                    if isinstance(item, NavigableString):
                        continue
                    if 'class' not in item.attrs:
                        continue
                    if 'cont' in " ".join(item.get('class')):
                        conttags.append(item.a.string)
                    if 'tech' in " ".join(item.get('class')):
                        techtags.append(item.a.string)
                    if 'ero' in " ".join(item.get('class')):
                        erotags.append(item.a.string)
            data['tags']['content'] = conttags if len(conttags) else None
            data['tags']['technology'] = techtags if len(techtags) else None
            data['tags']['erotic'] = erotags if len(erotags) else None
            del conttags
            del techtags
            del erotags
            releases = []
            cur_lang = None
            for item in list(soup.find('div', class_='mainbox releases').table.children):
                if isinstance(item, NavigableString):
                    continue
                if 'class' in item.attrs:
                    if cur_lang is None:
                        cur_lang = item.td.abbr.get('title')
                    else:
                        data['releases'][cur_lang] = releases
                        releases = []
                        cur_lang = item.td.abbr.get('title')
                else:
                    temp_rel = {'date': 0, 'ages': 0, 'platform': 0, 'name': 0, 'id': 0}
                    children = list(item.children)
                    temp_rel['date'] = children[0].string
                    temp_rel['ages'] = children[1].string
                    temp_rel['platform'] = children[2].abbr.get('title')
                    temp_rel['name'] = children[3].a.string
                    temp_rel['id'] = children[3].a.get('href')[1:]
                    del children
                    releases.append(temp_rel)
                    del temp_rel
            if len(releases) > 0 and cur_lang is not None:
                data['releases'][cur_lang] = releases
            del releases
            del cur_lang
            desc = ""
            for item in list(soup.find_all('td', class_='vndesc')[0].children)[1].contents:
                if not isinstance(item, NavigableString):
                    continue
                if item.startswith('['):
                    continue
                if item.startswith(']'):
                    continue
                desc += item.string + "\n"
            data['description'] = desc
            return data

    async def parse_search(self, stype, soup):
        """
        This is our parsing dispatcher

        :param stype: Search type category
        :param soup: The beautifulsoup object that contains the parsed html
        """
        if stype == 'v':
            return await parse_vn_results(soup)
        elif stype == 'r':
            return await parse_release_results(soup)
        elif stype == 'p':
            return await parse_prod_staff_results(soup)
        elif stype == 's':
            return await parse_prod_staff_results(soup)
        elif stype == 'c':
            return await parse_character_results(soup)
        elif stype == 'g':
            return await parse_tag_results(soup)
        elif stype == 'i':
            return await parse_tag_results(soup)
        elif stype == 'u':
            return await parse_user_results(soup)


text:
import os
import pwd
import shutil
import yaml

from charmhelpers.core import hookenv, host
from charmhelpers.core.templating import render
from charms.reactive import hook, set_state, when, when_not, remove_state
import gobinary

@hook('install')
def install():
    config = gobinary.config()
    install_workload(config)
    set_state('gobinary.start')

@hook('upgrade-charm')
def upgrade():
    # TODO: get_state("go-binary.config")
    #       and compare with upgraded, remove old service if name has changed.
    config = gobinary.config()
    service = config["binary"]
    need_restart = False
    if host.service_running(service):
        need_restart = True
    if need_restart:
        host.service_stop(service)
    install_workload(config)
    if need_restart:
        host.service_start(service)

@when('gobinary.start')
@when_not('gobinary.started')
def start_gobinary():
    bin_config = gobinary.config()
    host.service_start(bin_config['binary'])
    set_state('gobinary.started')

@when('gobinary.started')
@when_not('gobinary.start')
def stop_gobinary():
    bin_config = gobinary.config()
    host.service_stop(bin_config['binary'])
    remove_state('gobinary.started')

def install_workload(config):
    local_binary = os.path.join(hookenv.charm_dir(), "files", config["binary"])
    install_binary = "/usr/bin/" + config["binary"]
    args = config["args"]
    shutil.copyfile(local_binary, install_binary)
    os.chmod(install_binary, 0o755)
    render(source="upstart",
        target="/etc/init/%s.conf" % (config["binary"]),
        owner="root",
        perms=0o644,
        context={
            "ctx": config,
            "install_binary": install_binary,
        })
    set_state('go-binary.config' % (config))


text:
/**
 * Package for util classes.
 * @author Eugene Lazarev mailto(helycopternicht@rambler.ru)
 * @since 27.06.17
 */
package ru.elazarev.util;


text:
import superagentBatch from '../../src/superagent-batch';

describe('superagentBatch', () => {
  describe('Greet function', () => {
    beforeEach(() => {
      spy(superagentBatch, 'greet');
      superagentBatch.greet();
    });

    it('should have been run once', () => {
      expect(superagentBatch.greet).to.have.been.calledOnce;
    });

    it('should have always returned hello', () => {
      expect(superagentBatch.greet).to.have.always.returned('hello');
    });
  });
});


text:
{{+bindTo:partials.standard_nacl_article}}

NaCl Dev Environment

Feature Status

Here is a summary of feature status. We hope to overcome these limitations
in the near future:

NaCl Development Environment

General

Supported:

Bash (built-in)

Python (built-in)

Git (built-in)

Make (built-in)

Vim (built-in)

Nano (built-in)

Curl (built-in) + geturl for web

GCC w/ GLibC (x86-32 and x86-64 only)

Lua (install with: package -i lua && . setup-environment)

Ruby (install with: package -i ruby && . setup-environment)

Nethack! (install with: package -i nethack && . setup-environment)

Unsupported:

Targeting Newlib

Targeting PNaCl (getting close...)

Forking in bash

Pipes / Redirection

Symbolic and hard links

Missing / broken on ARM:

GCC (unsupported)

Debugger

Open issue causing it to suck CPU cycles (even when not in use).

{{/partials.standard_nacl_article}}


text:
> .\publish.ps1 patch

"minor" and "major" are also available in place of "patch" to control the version number for cache-busting/auto-reloading


text:
layout: post
title: Effective Java
tags: [java]
---

# Reflection
- Pros:
  - Provides a programmatic way to introspect a class
  - Provides an "abnormal" and unique way to
    - Invoke class methods and constructors
    - Access and modify class fields
- Cons:
  - Performance overhead over non-reflective counterparts
  - Loss of compile-time type checking
  - Exposure of internals, e.g., `private` fields or methods can be accessed and modified
- General rule
  - Should always try to avoid using reflection in normal applications
  - If it is unavoidable, reflection should be used very cautiously. One acceptable way of using reflection is to create an instance, but after that normal invocation should be used on the created instance.
- References
  - [1] Item 53, Effective Java 2nd, Joshua Bloch
  - [2] https://docs.oracle.com/javase/tutorial/reflect/
  - [3] http://www.javaworld.com/article/2077015/java-se/take-an-in-depth-look-at-the-java-reflection-api.html


text:
#ifndef WebSocket_h
#define WebSocket_h

#if ENABLE(WEB_SOCKETS)

#include "ActiveDOMObject.h"
#include "EventListener.h"
#include "EventNames.h"
#include "EventTarget.h"
#include "KURL.h"
#include "WebSocketChannel.h"
#include "WebSocketChannelClient.h"
#include <wtf/Forward.h>
#include <wtf/OwnPtr.h>
#include <wtf/RefCounted.h>
#include <wtf/text/AtomicStringHash.h>

namespace WebCore {

class Blob;
class ThreadableWebSocketChannel;

class WebSocket : public RefCounted<WebSocket>, public EventTarget, public ActiveDOMObject, public WebSocketChannelClient {
public:
    static void setIsAvailable(bool);
    static bool isAvailable();
    static const char* subProtocolSeperator();
    static PassRefPtr<WebSocket> create(ScriptExecutionContext*);
    static PassRefPtr<WebSocket> create(ScriptExecutionContext*, const String& url, ExceptionCode&);
    static PassRefPtr<WebSocket> create(ScriptExecutionContext*, const String& url, const String& protocol, ExceptionCode&);
    static PassRefPtr<WebSocket> create(ScriptExecutionContext*, const String& url, const Vector<String>& protocols, ExceptionCode&);
    virtual ~WebSocket();

    enum State {
        CONNECTING = 0,
        OPEN = 1,
        CLOSING = 2,
        CLOSED = 3
    };

    void connect(const String& url, ExceptionCode&);
    void connect(const String& url, const String& protocol, ExceptionCode&);
    void connect(const String& url, const Vector<String>& protocols, ExceptionCode&);

    void send(const String& message, ExceptionCode&);
    void send(JSC::ArrayBuffer*, ExceptionCode&);
    void send(JSC::ArrayBufferView*, ExceptionCode&);
    void send(Blob*, ExceptionCode&);

    void close(int code, const String& reason, ExceptionCode&);
    void close(ExceptionCode& ec) { close(WebSocketChannel::CloseEventCodeNotSpecified, String(), ec); }
    void close(int code, ExceptionCode& ec) { close(code, String(), ec); }

    const KURL& url() const;
    State readyState() const;
    unsigned long bufferedAmount() const;

    String protocol() const;
    String extensions() const;

    String binaryType() const;
    void setBinaryType(const String&);

    DEFINE_ATTRIBUTE_EVENT_LISTENER(open);
    DEFINE_ATTRIBUTE_EVENT_LISTENER(message);
    DEFINE_ATTRIBUTE_EVENT_LISTENER(error);
    DEFINE_ATTRIBUTE_EVENT_LISTENER(close);

    // EventTarget functions.
    virtual EventTargetInterface eventTargetInterface() const OVERRIDE;
    virtual ScriptExecutionContext* scriptExecutionContext() const OVERRIDE;

    using RefCounted<WebSocket>::ref;
    using RefCounted<WebSocket>::deref;

    // WebSocketChannelClient functions.
    virtual void didConnect() OVERRIDE;
    virtual void didReceiveMessage(const String& message) OVERRIDE;
    virtual void didReceiveBinaryData(PassOwnPtr<Vector<char> >) OVERRIDE;
    virtual void didReceiveMessageError() OVERRIDE;
    virtual void didUpdateBufferedAmount(unsigned long bufferedAmount) OVERRIDE;
    virtual void didStartClosingHandshake() OVERRIDE;
    virtual void didClose(unsigned long unhandledBufferedAmount, ClosingHandshakeCompletionStatus, unsigned short code, const String& reason) OVERRIDE;

private:
    explicit WebSocket(ScriptExecutionContext*);

    // ActiveDOMObject functions.
    virtual void contextDestroyed() OVERRIDE;
    virtual bool canSuspend() const OVERRIDE;
    virtual void suspend(ReasonForSuspension) OVERRIDE;
    virtual void resume() OVERRIDE;
    virtual void stop() OVERRIDE;

    virtual void refEventTarget() OVERRIDE { ref(); }
    virtual void derefEventTarget() OVERRIDE { deref(); }
    virtual EventTargetData* eventTargetData() OVERRIDE;
    virtual EventTargetData& ensureEventTargetData() OVERRIDE;

    size_t getFramingOverhead(size_t payloadSize);

    enum BinaryType {
        BinaryTypeBlob,
        BinaryTypeArrayBuffer
    };

    RefPtr<ThreadableWebSocketChannel> m_channel;

    State m_state;
    KURL m_url;
    EventTargetData m_eventTargetData;
    unsigned long m_bufferedAmount;
    unsigned long m_bufferedAmountAfterClose;
    BinaryType m_binaryType;
    String m_subprotocol;
    String m_extensions;
};

} // namespace WebCore

#endif // ENABLE(WEB_SOCKETS)

#endif // WebSocket_h


text:
import warnings

from UserList import UserList

from celery import conf
from celery import registry
from celery.datastructures import AttributeDict
from celery.messaging import with_connection
from celery.messaging import TaskPublisher
from celery.result import TaskSetResult
from celery.utils import gen_unique_id

TASKSET_DEPRECATION_TEXT = """\
Using this invocation of TaskSet is deprecated and will be removed
in Celery v2.4!

TaskSets now supports multiple types of tasks, the API has to reflect
this so the syntax has been changed to:

    from celery.task.sets import TaskSet

    ts = TaskSet(tasks=[
            %(cls)s.subtask(args1, kwargs1, options1),
            %(cls)s.subtask(args2, kwargs2, options2),
            %(cls)s.subtask(args3, kwargs3, options3),
            ...
            %(cls)s.subtask(argsN, kwargsN, optionsN),
    ])

    result = ts.apply_async()

Thank you for your patience!

"""

class subtask(AttributeDict):
    """Class that wraps the arguments and execution options
    for a single task invocation.

    Used as the parts in a :class:`TaskSet` or to safely
    pass tasks around as callbacks.

    :param task: Either a task class/instance, or the name of a task.
    :keyword args: Positional arguments to apply.
    :keyword kwargs: Keyword arguments to apply.
    :keyword options: Additional options to
      :func:`celery.execute.apply_async`.

    Note that if the first argument is a :class:`dict`, the other
    arguments will be ignored and the values in the dict will be used
    instead.

        >>> s = subtask("tasks.add", args=(2, 2))
        >>> subtask(s)
        {"task": "tasks.add", args=(2, 2), kwargs={}, options={}}

    """

    def __init__(self, task=None, args=None, kwargs=None, options=None,
            **extra):
        init = super(subtask, self).__init__

        if isinstance(task, dict):
            # Use the values from a dict.
            return init(task)

        # Also supports using task class/instance instead of string name.
        try:
            task_name = task.name
        except AttributeError:
            task_name = task

        init(task=task_name, args=tuple(args or ()), kwargs=kwargs or (),
             options=options or ())

    def delay(self, *argmerge, **kwmerge):
        """Shortcut to ``apply_async(argmerge, kwargs)``."""
        return self.apply_async(args=argmerge, kwargs=kwmerge)

    def apply(self, args=(), kwargs={}, **options):
        """Apply this task locally."""
        # For callbacks: extra args are prepended to the stored args.
        args = tuple(args) + tuple(self.args)
        kwargs = dict(self.kwargs, **kwargs)
        options = dict(self.options, **options)
        return self.get_type().apply(args, kwargs, **options)

    def apply_async(self, args=(), kwargs={}, **options):
        """Apply this task asynchronously."""
        # For callbacks: extra args are prepended to the stored args.
        args = tuple(args) + tuple(self.args)
        kwargs = dict(self.kwargs, **kwargs)
        options = dict(self.options, **options)
        return self.get_type().apply_async(args, kwargs, **options)

    def get_type(self):
        # For JSON serialization, the task class is lazily loaded,
        # and not stored in the dict itself.
        return registry.tasks[self.task]

class TaskSet(UserList):
    """A task containing several subtasks, making it possible
    to track how many, or when all of the tasks has been completed.

    :param tasks: A list of :class:`subtask` instances.

    .. attribute:: total

        Total number of subtasks in this task set.

    Example::

        >>> from djangofeeds.tasks import RefreshFeedTask
        >>> from celery.task.sets import TaskSet, subtask
        >>> urls = ("http://cnn.com/rss",
        ...         "http://bbc.co.uk/rss",
        ...         "http://xkcd.com/rss")
        >>> subtasks = [RefreshFeedTask.subtask(kwargs={"feed_url": url})
        ...                 for url in urls]
        >>> taskset = TaskSet(tasks=subtasks)
        >>> taskset_result = taskset.apply_async()
        >>> list_of_return_values = taskset_result.join()

    """
    _task = None # compat
    _task_name = None # compat

    def __init__(self, task=None, tasks=None):
        if task is not None:
            if hasattr(task, "__iter__"):
                tasks = task
            else:
                # Previously TaskSet only supported applying one kind of task.
                # the signature then was TaskSet(task, arglist),
                # so convert the arguments to subtasks'.
                tasks = [subtask(task, *arglist) for arglist in tasks]
                task = self._task = registry.tasks[task.name]
                self._task_name = task.name
                warnings.warn(TASKSET_DEPRECATION_TEXT % {
                                "cls": task.__class__.__name__},
                              DeprecationWarning)

        self.data = list(tasks)
        self.total = len(self.tasks)

    @with_connection
    def apply_async(self, connection=None,
            connect_timeout=conf.BROKER_CONNECTION_TIMEOUT):
        """Run all tasks in the taskset.

        Returns a :class:`celery.result.TaskSetResult` instance.

        Example

            >>> ts = TaskSet(tasks=(
            ...         RefreshFeedTask.subtask(["http://foo.com/rss"]),
            ...         RefreshFeedTask.subtask(["http://bar.com/rss"]),
            ... ))
            >>> result = ts.apply_async()
            >>> result.taskset_id
            "d2c9b261-8eff-4bfb-8459-1e1b72063514"
            >>> result.subtask_ids
            ["b4996460-d959-49c8-aeb9-39c530dcde25",
            "598d2d18-ab86-45ca-8b4f-0779f5d6a3cb"]
            >>> result.waiting()
            True
            >>> time.sleep(10)
            >>> result.ready()
            True
            >>> result.successful()
            True
            >>> result.failed()
            False
            >>> result.join()
            [True, True]

        """
        if conf.ALWAYS_EAGER:
            return self.apply()

        taskset_id = gen_unique_id()
        publisher = TaskPublisher(connection=connection)
        try:
            results = [task.apply_async(taskset_id=taskset_id,
                                        publisher=publisher)
                            for task in self.tasks]
        finally:
            publisher.close()

        return TaskSetResult(taskset_id, results)

    def apply(self):
        """Applies the taskset locally."""
        taskset_id = gen_unique_id()

        # This will be filled with EagerResults.
        return TaskSetResult(taskset_id, [task.apply(taskset_id=taskset_id)
                                            for task in self.tasks])

    @property
    def tasks(self):
        return self.data

    @property
    def task(self):
        warnings.warn(
            "TaskSet.task is deprecated and will be removed in 1.4",
            DeprecationWarning)
        return self._task

    @property
    def task_name(self):
        warnings.warn(
            "TaskSet.task_name is deprecated and will be removed in 1.4",
            DeprecationWarning)
        return self._task_name