text:
<?php

namespace Auth;

class SimpleUserUpdateException extends \Fuel_Exception {}

class SimpleUserWrongPassword extends \Fuel_Exception {}

/**
 * SimpleAuth basic login driver
 *
 * @package     Fuel
 * @subpackage  Auth
 */
class Auth_Login_SimpleAuth extends \Auth_Login_Driver {

	public static function _init()
	{
		\Config::load('simpleauth', true);
	}

	/**
	 * @var  Database_Result  when login succeeded
	 */
	protected $user = null;

	/**
	 * @var  array  value for guest login
	 */
	protected static $guest_login = array(
		'id' => 0,
		'username' => 'guest',
		'group' => '0',
		'login_hash' => false,
		'email' => false
	);

	/**
	 * @var  array  SimpleAuth class config
	 */
	protected $config = array(
		'drivers' => array('group' => array('SimpleGroup')),
		'additional_fields' => array('profile_fields'),
	);

	/**
	 * Check for login
	 *
	 * @return  bool
	 */
	public function perform_check()
	{
		$username    = \Session::get('username');
		$login_hash  = \Session::get('login_hash');

		if (is_null($this->user) or ($this->user['username'] != $username and $this->user != static::$guest_login))
		{
			$this->user = \DB::select()
				->where('username', '=', $username)
				->from(\Config::get('simpleauth.table_name'))
				->execute()->current();
		}

		if ($this->user and $this->user['login_hash'] === $login_hash)
		{
			return true;
		}

		$this->user = \Config::get('simpleauth.guest_login', true) ? static::$guest_login : false;
		\Session::delete('username');
		\Session::delete('login_hash');

		return false;
	}

	/**
	 * Login user
	 *
	 * @param   string
	 * @param   string
	 * @return  bool
	 */
	public function login($username = '', $password = '')
	{
		$username = trim($username) ?: trim(\Input::post('username'));
		$password = trim($password) ?: trim(\Input::post('password'));

		if (empty($username) or empty($password))
		{
			return false;
		}

		$password = $this->hash_password($password);
		$this->user = \DB::select()
			->where('username', '=', $username)
			->where('password', '=', $password)
			->from(\Config::get('simpleauth.table_name'))
			->execute()->current();

		if ($this->user == false)
		{
			$this->user = \Config::get('simpleauth.guest_login', true) ? static::$guest_login : false;
			\Session::delete('username');
			\Session::delete('login_hash');
			return false;
		}

		\Session::set('username', $username);
		\Session::set('login_hash', $this->create_login_hash());
		return true;
	}

	/**
	 * Logout user
	 *
	 * @return  bool
	 */
	public function logout()
	{
		$this->user = \Config::get('simpleauth.guest_login', true) ? static::$guest_login : false;
		\Session::delete('username');
		\Session::delete('login_hash');
		return true;
	}

	/**
	 * Create new user
	 *
	 * @param   string
	 * @param   string
	 * @param   string  must contain valid email address
	 * @param   int     group id
	 * @param   Array
	 * @return  bool
	 */
	public function create_user($username, $password, $email, $group = 1, Array $profile_fields = array())
	{
		$email = filter_var(trim($email), FILTER_VALIDATE_EMAIL);

		if (empty($username) or empty($password) or empty($email))
		{
			throw new \SimpleUserUpdateException('Username, password and emailaddress can\'t be empty.');
		}

		$same_users = \DB::select()
			->where('username', '=', $username)
			->or_where('email', '=', $email)
			->from(\Config::get('simpleauth.table_name'))
			->execute();

		if ($same_users->count() > 0)
		{
			if (in_array(strtolower($email), array_map('strtolower', $same_users->current())))
			{
				throw new \SimpleUserUpdateException('Email address already exists');
			}
			else
			{
				throw new \SimpleUserUpdateException('Username already exists');
			}
		}

		$user = array(
			'username'        => (string) $username,
			'password'        => $this->hash_password((string) $password),
			'email'           => $email,
			'group'           => (int) $group,
			'profile_fields'  => serialize($profile_fields)
		);
		$result = \DB::insert(\Config::get('simpleauth.table_name'))
			->set($user)
			->execute();

		return ($result[1] > 0) ? $result[0] : false;
	}

	/**
	 * Update a user's properties
	 * Note: Username cannot be updated, to update password the old password must be passed as old_password
	 *
	 * @param   Array  properties to be updated including profile fields
	 * @param   string
	 * @return  bool
	 */
	public function update_user($values, $username = null)
	{
		$username = $username ?: $this->user['username'];
		$current_values = \DB::select()
			->where('username', '=', $username)
			->from(\Config::get('simpleauth.table_name'))->execute();

		if (empty($current_values))
		{
			throw new \SimpleUserUpdateException('Username not found');
		}

		$update = array();
		if (array_key_exists('username', $values))
		{
			throw new \SimpleUserUpdateException('Username cannot be changed.');
		}
		if (array_key_exists('password', $values))
		{
			if ($current_values->get('password') != $this->hash_password(@$values['old_password']))
			{
				throw new \SimpleUserWrongPassword('Old password is invalid');
			}

			if ( ! empty($values['password']))
			{
				$update['password'] = $this->hash_password($values['password']);
			}
			unset($values['password']);
		}
		if (array_key_exists('old_password', $values))
		{
			unset($values['old_password']);
		}
		if (array_key_exists('email', $values))
		{
			$email = filter_var(trim($values['email']), FILTER_VALIDATE_EMAIL);
			if ( ! $email)
			{
				throw new \SimpleUserUpdateException('Email address is not valid');
			}
			$update['email'] = $email;
			unset($values['email']);
		}
		if (array_key_exists('group', $values))
		{
			if (is_numeric($values['group']))
			{
				$update['group'] = (int) $values['group'];
			}
			unset($values['group']);
		}
		if ( ! empty($values))
		{
			$profile_fields = @unserialize($current_values->get('profile_fields')) ?: array();
			foreach ($values as $key => $val)
			{
				if ($val === null)
				{
					unset($profile_fields[$key]);
				}
				else
				{
					$profile_fields[$key] = $val;
				}
			}
			$update['profile_fields'] = serialize($profile_fields);
		}

		$affected_rows = \DB::update(\Config::get('simpleauth.table_name'))
			->set($update)
			->where('username', '=', $username)
			->execute();

		// Refresh user
		if ($this->user['username'] == $username)
		{
			$this->user = \DB::select()
				->where('username', '=', $username)
				->from(\Config::get('simpleauth.table_name'))
				->execute()->current();
		}

		return $affected_rows > 0;
	}

	/**
	 * Change a user's password
	 *
	 * @param   string
	 * @param   string
	 * @param   string  username or null for current user
	 * @return  bool
	 */
	public function change_password($old_password, $new_password, $username = null)
	{
		try
		{
			return (bool) $this->update_user(array('old_password' => $old_password, 'password' => $new_password), $username);
		}
		// Only catch the wrong password exception
		catch (SimpleUserWrongPassword $e)
		{
			return false;
		}
	}

	/**
	 * Deletes a given user
	 *
	 * @param   string
	 * @return  bool
	 */
	public function delete_user($username)
	{
		if (empty($username))
		{
			throw new \SimpleUserUpdateException('Cannot delete user with empty username');
		}

		$affected_rows = \DB::delete(\Config::get('simpleauth.table_name'))
			->where('username', '=', $username)
			->execute();

		return $affected_rows > 0;
	}

	/**
	 * Creates a temporary hash that will validate the current login
	 *
	 * @return  string
	 */
	public function create_login_hash()
	{
		if (empty($this->user))
		{
			throw new \SimpleUserUpdateException('User not logged in, can\'t create login hash.');
		}

		$last_login = \Date::factory()->get_timestamp();
		$login_hash = sha1(\Config::get('simpleauth.login_hash_salt').$this->user['username'].$last_login);

		\DB::update(\Config::get('simpleauth.table_name'))
			->set(array('last_login' => $last_login, 'login_hash' => $login_hash))
			->where('username', '=', $this->user['username'])->execute();

		$this->user['login_hash'] = $login_hash;

		return $login_hash;
	}

	/**
	 * Get the user's ID
	 *
	 * @return  Array  containing this driver's ID & the user's ID
	 */
	public function get_user_id()
	{
		if (empty($this->user))
		{
			return false;
		}

		return array($this->id, (int) $this->user['id']);
	}

	/**
	 * Get the user's groups
	 *
	 * @return  Array  containing the group driver ID & the user's group ID
	 */
	public function get_groups()
	{
		if (empty($this->user))
		{
			return false;
		}

		return array(array('SimpleGroup', $this->user['group']));
	}

	/**
	 * Get the user's emailaddress
	 *
	 * @return  string
	 */
	public function get_email()
	{
		if (empty($this->user))
		{
			return false;
		}

		return $this->user['email'];
	}

	/**
	 * Get the user's screen name
	 *
	 * @return  string
	 */
	public function get_screen_name()
	{
		if (empty($this->user))
		{
			return false;
		}

		return $this->user['username'];
	}

	/**
	 * Get the user's profile fields
	 *
	 * @return  Array
	 */
	public function get_profile_fields()
	{
		if (empty($this->user))
		{
			return false;
		}

		return @unserialize($this->user['profile_fields']) ?: array();
	}

	/**
	 * Extension of base driver method to default to user group instead of user id
	 */
	public function has_access($condition, $driver = null, $user = null)
	{
		if (is_null($user))
		{
			$groups = $this->get_groups();
			$user = reset($groups);
		}
		return parent::has_access($condition, $driver, $user);
	}

	/**
	 * Extension of base driver because this supports a guest login when switched on
	 */
	public function guest_login()
	{
		return \Config::get('simpleauth.guest_login', true);
	}
}

// end of file simpleauth.php


text:
{% extends "v9/layoutv9.html" %}

{% set title = "Water abstraction licence" %}

{% block page_title %}
    {{title}} - GOV.UK
{% endblock %}

{% block content %}

      BETA
      This is an BETA prototype, details may be missing whilst we build the service. Your feedback will help us improve this service.

      Back

      <form action="/v12_2/change_password/new_password_confirm.html" method="get" class="form" id="password_reset" data-parsley-validate="" data-parsley-errors-messages-disabled>

                Please enter a valid password

                  Your password must contain:

8 characters

less than 250 characters

1 symbol (like ?!£%)

1 capital letter

                  The passwords you entered didn't match

Re-enter your password

          Change your password

            <fieldset>

Your new password must have at least:

8 characters

less than 250 characters

1 symbol (like ?!£%)

1 capital letter

            </fieldset>

          Enter a new password
          Re-enter your new password
          <input type="password" class="form-control" id="password" data-parsley-password="" data-parsely-trigger="keyup change" required="" />

          Confirm your new password
          Confirm your new password
          <input type="password" class="form-control" id="confirm-password" data-parsley-equalto="#password" required="" data-parsley-maxlength="255"/>

        <input type="submit" value="Change password" class="button button-start" role="button"/>

      </form>

{% endblock %}

redpajama_set_name: RedPajamaGithub


text:
#ifndef INCLUDED_haxe_io_Output
#define INCLUDED_haxe_io_Output

#ifndef HXCPP_H
#include <hxcpp.h>
#endif

HX_DECLARE_CLASS2(haxe,io,Bytes)
HX_DECLARE_CLASS2(haxe,io,Output)
namespace haxe{
namespace io{

class HXCPP_CLASS_ATTRIBUTES  Output_obj : public hx::Object{
	public:
		typedef hx::Object super;
		typedef Output_obj OBJ_;
		Output_obj();
		Void __construct();

	public:
		inline void *operator new( size_t inSize, bool inContainer=false,const char *inName="haxe.io.Output")
			{ return hx::Object::operator new(inSize,inContainer,inName); }
		static hx::ObjectPtr< Output_obj > __new();
		static Dynamic __CreateEmpty();
		static Dynamic __Create(hx::DynamicArray inArgs);
		//~Output_obj();

		HX_DO_RTTI_ALL;
		Dynamic __Field(const ::String &inString, hx::PropertyAccess inCallProp);
		static void __register();
		::String __ToString() const { return HX_HCSTRING("Output","\x21","\x83","\x15","\x41"); }

		virtual Void writeByte( int c);
		Dynamic writeByte_dyn();

		virtual int writeBytes( ::haxe::io::Bytes s,int pos,int len);
		Dynamic writeBytes_dyn();

		virtual Void close( );
		Dynamic close_dyn();

		virtual Void write( ::haxe::io::Bytes s);
		Dynamic write_dyn();

		virtual Void writeFullBytes( ::haxe::io::Bytes s,int pos,int len);
		Dynamic writeFullBytes_dyn();

		virtual Void writeString( ::String s);
		Dynamic writeString_dyn();

};

} // end namespace haxe
} // end namespace io

#endif /* INCLUDED_haxe_io_Output */


text:
using System.Collections.Generic;
using Newtonsoft.Json;

namespace Citrina.Models
{
    internal class ErrorResponse
    {
        [JsonProperty("error_code")]
        public int? Code { get; set; }

        [JsonProperty("error_msg")]
        public string Message { get; set; }

        [JsonProperty("request_params")]
        public IEnumerable<KeyValuePair<string, string>> RequestParameters { get; set; }
    }
}


text:
title: Regional grants
description: Regional grants under the BID programme seek to establish or strengthen international collaborations that increase biodiversity data mobilization.
category: Calls
subCategory: Africa 2015
---
# Regional grants

_Sub-Saharan Africa, 2015 (closed)_

**Note: This call for proposals is closed**

Regional grants under the BID programme seek to establish or strengthen international collaborations that increase biodiversity data mobilization.

----------------------
## Submission procedure

The deadline for submitting initial concept notes from sub-Saharan Africa was 20 November 2015. GBIF and the BID evaluation panel have provided feedback and recommendations to applicants invited to prepare full proposals.

Full proposals are due 26 Feb 2016, 12:00 pm CET / 11:00 am UTC/GMT, and GBIF will announce the selected projects in April 2016.

**Applications must be submitted in English and by using the appropriate template**.

Applications received late or incomplete will not be reviewed by the evaluation panel.

-----

## Objectives

The objectives of the BID regional biodiversity data mobilization grants are to:

+ Establish or strengthen international collaborations to mobilize biodiversity data
+ Increase available biodiversity data, within and beyond the grant period
+ Apply biodiversity data in response to conservation priorities

The overall BID programme targets two key outcomes:

1. Enhanced capacity for effective mobilization and use of biodiversity information
2. Enhanced availability of information resources and best practice guidance for mobilization and application of biodiversity information for key policy needs

-----

## Key documents

+ [Proposal template](https://www.gbif.org/sites/default/files/gbif_project/files/BID-Regional-Grant-Proposal-Template.doc)
+ [First Call For Proposals](https://www.gbif.org/sites/default/files/gbif_project/files/BID%20Call%20For%20Proposals%20Africa.pdf)
+ [First Call for Proposals - Annex A](https://www.gbif.org/sites/default/files/gbif_project/files/BID-call-for-proposals-Annex-A.pdf)
+ [Africa Rising declaration](https://www.gbif.org/sites/default/files/gbif_event/files/AfricaRising-Declaration-EN.pdf)

----

## Evaluation criteria

Proposals will be assessed using the following criteria:

1. Alignment of the project with BID objectives and priorities.
2. Alignment of the project with clearly stated needs for biodiversity information and capacity development within the proposal.
3. The project's complementary contributions to regional data needs, including those stated in the [Africa Rising declaration and action plan](https://www.gbif.org/sites/default/files/gbif_event/files/AfricaRising-Declaration-EN.pdf).
4. Demonstrated success and past experience delivering similar projects.
5. Likelihood that the project will provide examples of best practice in the application of biodiversity information in decision-making.
6. Quantity, quality and relevance of the biodiversity data proposed for mobilization, with preference given to projects that mobilize biodiversity data relating to protected areas, threatened species and invasive alien species.
7. Strength of the plans to develop and sustain institutional capacity after the project actions.
8. Level of institutional support and cost effectiveness of the proposed actions; the balance between the level of funding requested from BID and the cofunding contributed by the consortium partners.
9. Anticipated value of the project deliverables to both the national and regional context and the broader GBIF community.
10. Choice and complementarity of consortium partners.
11. Quality of project design and risk assessment; monitoring and evaluation plans will be assessed in the full proposals

-----

## Project duration

Selected regional projects may begin their activities in June 2016, with project activity continuing for up to two years (ending in June 2018), and with a final six-month reporting and evaluation period (ending in December 2018). All projects must end by 31 December 2018.

-----

## Funding

A minimum of three partners, each from a different African ACP country, must be involved in a regional consortium. Each partner may receive up to €20,000, and one consortium coordinator may receive up to €10,000 in additional funding to coordinate the activities of the partners. During the course of the BID programme, the maximum total project funding that any single applicant can receive is €60,000.

### Regional grant activity types

Regional grants must include activities contributing to each of three component categories. Each category presented below includes a non-exclusive list of possible types of activity:

1. Establishing or strengthening networks to support long-term data mobilization and inter-institutional data sharing:
+ Assessing biodiversity data holdings and user needs through a survey or study to develop a strategy for the consortium.
+ Organizing regional workshops to promote inter-institutional collaboration.
+ Formalizing partnerships through institutional agreements, data sharing policies and public endorsement of mobilization strategies.
+ Adopting a data publishing process, possibly including installing data publishing informatics tools (e.g. [GBIF Integrated Publishing Toolkit](https://www.gbif.org/ipt)).
+ Training data managers and collections staff within key data holding institutions on data mobilization and management, for example, through workshops to share the knowledge gained through attending the two BID capacity enhancement workshops.

2. Activities to mobilize biodiversity data relevant to protected areas, invasive alien species and/or threatened species:
+ Compiling inventories of biodiversity data holdings (for example, implementing metadata catalogues).
+ Digitizing and publishing natural history collections and biodiversity information from literature.
+ Mobilizing species occurrence and sample-based data from observation networks and monitoring systems, such as invasive alien species, Red Listed species or endemic species.
+ Validating and publishing regional, national and local species checklists, invasive species lists or threatened species lists.
+ Preparing [data papers](https://www.gbif.org/publishing-data/data-papers) to improve the reusability of the mobilized biodiversity data.

3. Integrating biodiversity information into policy and decision-making processes:
+ Leading surveys or workshops to understand the biodiversity data requirements for specific use cases.
+ Setting up user groups to guide project implementation on identified priority themes, such as agrobiodiversity, urban biodiversity and protected areas.
+ Directing workshops and advocacy actions that promote the use of openly accessible data, for example, in national-level biodiversity reporting.
+ Hosting workshops on data analysis techniques.
+ Applying biodiversity data in decision-making processes.
+ Documenting use cases and sharing them with partners in the region.

---------

```styledYaml
templates:
- path: eufund.html
```


text:
import React from 'react';
import PatternsLeftPaneComponent from './PatternsLeftPaneComponent'
import {connect} from 'react-redux'

class _PatternsLeftPaneContainer extends React.Component {
	constructor(props) {
		super(props);
		this.data = {
			    id: 'Patterns',
			    name: 'React Patterns',
			    children: [{
			        id: 'Container',
			        name: 'Container/Component',
			        children: [{
			    	        id: 'Photo',
			    	        name: 'Photo Player'
			    	    }, {
			    	        id: 'Video',
			    	        name: 'Video Player'
			    	    }]
			    	}, {
			        id: 'Popup Pattern',
			        name: 'Popup Pattern'
			    },{
			        id: 'Pubsub Pattern',
			        name: 'Pubsub Pattern'
			    }]
			};
	}

	render() {
	    return (
	      < PatternsLeftPaneComponent data={this.data} currentPage = {this.props.currentPage}
	        />
	    )
	  }
}
const PatternsLeftPaneContainer = connect(
		  store => {

			    return {
			    	currentPage: store.PatternsRightPaneReducer.currentPage
			    };
			  }
			)(_PatternsLeftPaneContainer);
export default PatternsLeftPaneContainer


text:
import elasticsearch
import configparser

# Configuration
config = configparser.RawConfigParser()
config.read("config.conf")

# Setup Elasticsearch
es_host = config.get("Elastic", "es_host")
elastic = elasticsearch.Elasticsearch([es_host])

def get_params():
    index_string = 'social_profile'

    params = {
        'index': index_string,
        'type': 'tweet',
        'timeout': 300,
    }

    return params

def run_query(query):
    # This is an example query
    # query = {
    #     "from": 0,
    #     "size": 1000,
    #     "sort": [
    #         {"@timestamp": {"order": "desc"}}
    #
    #     ],
    #     "query": {
    #         "bool": {
    #             "must": [
    #                 {"range": {"@timestamp": {"gte": "now-{}".format(time_range), "lte": "now"}}},
    #                 {"term": {"jsonEvent": "IDS"}},
    #                 {"term": {"event.event_type": "alert"}}
    #             ]
    #         },
    #     }
    # }

    params = get_params()
    result_json = elastic.search(index=params['index'], doc_type=params['type'], request_timeout=params['timeout'],
                                 body=query)
    return result_json

def get_document(doc_id, time_range="6h"):
    query = {
        "query": {
            "ids": {
                "values": [doc_id]
            }
        }
    }

    params = get_params()
    result_json = elastic.search(index=params['index'], doc_type=params['type'], request_timeout=params['timeout'],
                                 body=query)
    return result_json


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

    angular.module('sandbox', ['ngRoute', 'playground'])

        .config(function($routeProvider) {
            $routeProvider
                .when('/', {
                    controller: 'HomeCtrl',
                    templateUrl: 'view/home.html'
                })
                .when('/play', {
                    controller: 'PlaygroundCtrl',
                    templateUrl: 'view/play.html'
                });
        })

        .controller('HomeCtrl', function($log) {
            $log.info('Home Controller');
        });

})(window.angular);


text:
package com.arm4j.weixin.request.customservice.entity.msg.video;

import com.alibaba.fastjson.annotation.JSONField;

/**
 * Created by liwenhe on 16/11/16.
 */
public class VideoMsgEntity {

    private String mediaId;

    private String thumbMediaId;

    private String title;

    private String description;

    @JSONField(name = "media_id")
    public String getMediaId() {
        return mediaId;
    }

    @JSONField(name = "thumb_media_id")
    public String getThumbMediaId() {
        return thumbMediaId;
    }

    @JSONField(name = "title")
    public String getTitle() {
        return title;
    }

    @JSONField(name = "description")
    public String getDescription() {
        return description;
    }

    public void setMediaId(String mediaId) {
        this.mediaId = mediaId;
    }

    public void setThumbMediaId(String thumbMediaId) {
        this.thumbMediaId = thumbMediaId;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public void setDescription(String description) {
        this.description = description;
    }
}


text:
namespace blink {

class HyphenationCF final : public Hyphenation {
 public:
  HyphenationCF(base::ScopedCFTypeRef<CFLocaleRef>& locale_cf)
      : locale_cf_(locale_cf) {
    DCHECK(locale_cf_);
  }

  wtf_size_t LastHyphenLocation(const StringView& text,
                                wtf_size_t before_index) const override {
    if (!ShouldHyphenateWord(text))
      return 0;

    CFIndex result = CFStringGetHyphenationLocationBeforeIndex(
        text.ToString().Impl()->CreateCFString(), before_index,
        CFRangeMake(0, text.length()), 0, locale_cf_, 0);
    return static_cast<wtf_size_t>(result == kCFNotFound ? 0 : result);
  }

  // While Hyphenation::FirstHyphenLocation() works good, it computes all
  // locations and discards ones after |after_index|.
  // This version minimizes the computation for platforms that supports
  // LastHyphenLocation() but does not support HyphenLocations().
  wtf_size_t FirstHyphenLocation(const StringView& text,
                                 wtf_size_t after_index) const override {
    if (!ShouldHyphenateWord(text))
      return 0;

    after_index = std::max(after_index,
                           static_cast<wtf_size_t>(kMinimumPrefixLength - 1));
    wtf_size_t hyphen_location = text.length();
    if (hyphen_location <= kMinimumSuffixLength)
      return 0;
    wtf_size_t max_hyphen_location = hyphen_location - kMinimumSuffixLength;
    hyphen_location = max_hyphen_location;
    for (;;) {
      wtf_size_t previous = LastHyphenLocation(text, hyphen_location);
      if (previous <= after_index)
        break;
      hyphen_location = previous;
    }
    return hyphen_location >= max_hyphen_location ? 0 : hyphen_location;
  }

 private:
  base::ScopedCFTypeRef<CFLocaleRef> locale_cf_;
};

scoped_refptr<Hyphenation> Hyphenation::PlatformGetHyphenation(
    const AtomicString& locale) {
  base::ScopedCFTypeRef<CFStringRef> locale_cf_string(
      locale.Impl()->CreateCFString());
  base::ScopedCFTypeRef<CFLocaleRef> locale_cf(
      CFLocaleCreate(kCFAllocatorDefault, locale_cf_string));
  if (!CFStringIsHyphenationAvailableForLocale(locale_cf))
    return nullptr;
  scoped_refptr<Hyphenation> hyphenation(
      base::AdoptRef(new HyphenationCF(locale_cf)));
  if (locale.StartsWithIgnoringASCIICase("de"))
    hyphenation->hyphenate_capitalized_word_ = true;
  return hyphenation;
}

}  // namespace blink


text:
package okhttp3.internal.tls;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.security.PublicKey;
import java.security.cert.TrustAnchor;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import javax.net.ssl.X509TrustManager;
import javax.security.auth.x500.X500Principal;

public abstract class TrustRootIndex {
  /** Returns the trusted CA certificate that signed {@code cert}. */
  abstract X509Certificate findByIssuerAndSignature(X509Certificate cert);

  public static TrustRootIndex get(X509TrustManager trustManager) {
    try {
      // From org.conscrypt.TrustManagerImpl, we want the method with this signature:
      // private TrustAnchor findTrustAnchorByIssuerAndSignature(X509Certificate lastCert);
      Method method = trustManager.getClass().getDeclaredMethod(
          "findTrustAnchorByIssuerAndSignature", X509Certificate.class);
      method.setAccessible(true);
      return new AndroidTrustRootIndex(trustManager, method);
    } catch (NoSuchMethodException e) {
      return get(trustManager.getAcceptedIssuers());
    }
  }

  public static TrustRootIndex get(X509Certificate... caCerts) {
    return new BasicTrustRootIndex(caCerts);
  }

  /**
   * An index of trusted root certificates that exploits knowledge of Android implementation
   * details. This class is potentially much faster to initialize than {@link BasicTrustRootIndex}
   * because it doesn't need to load and index trusted CA certificates.
   *
   * <p>This class uses APIs added to Android in API 14 (Android 4.0, released October 2011). This
   * class shouldn't be used in Android API 17 or better because those releases are better served by
   * {@link CertificateChainCleaner.AndroidCertificateChainCleaner}.
   */
  static final class AndroidTrustRootIndex extends TrustRootIndex {
    private final X509TrustManager trustManager;
    private final Method findByIssuerAndSignatureMethod;

    AndroidTrustRootIndex(X509TrustManager trustManager, Method findByIssuerAndSignatureMethod) {
      this.findByIssuerAndSignatureMethod = findByIssuerAndSignatureMethod;
      this.trustManager = trustManager;
    }

    @Override public X509Certificate findByIssuerAndSignature(X509Certificate cert) {
      try {
        TrustAnchor trustAnchor = (TrustAnchor) findByIssuerAndSignatureMethod.invoke(
            trustManager, cert);
        return trustAnchor != null
            ? trustAnchor.getTrustedCert()
            : null;
      } catch (IllegalAccessException e) {
        throw new AssertionError();
      } catch (InvocationTargetException e) {
        return null;
      }
    }
  }

  /** A simple index that of trusted root certificates that have been loaded into memory. */
  static final class BasicTrustRootIndex extends TrustRootIndex {
    private final Map<X500Principal, List<X509Certificate>> subjectToCaCerts;

    public BasicTrustRootIndex(X509Certificate... caCerts) {
      subjectToCaCerts = new LinkedHashMap<>();
      for (X509Certificate caCert : caCerts) {
        X500Principal subject = caCert.getSubjectX500Principal();
        List<X509Certificate> subjectCaCerts = subjectToCaCerts.get(subject);
        if (subjectCaCerts == null) {
          subjectCaCerts = new ArrayList<>(1);
          subjectToCaCerts.put(subject, subjectCaCerts);
        }
        subjectCaCerts.add(caCert);
      }
    }

    @Override public X509Certificate findByIssuerAndSignature(X509Certificate cert) {
      X500Principal issuer = cert.getIssuerX500Principal();
      List<X509Certificate> subjectCaCerts = subjectToCaCerts.get(issuer);
      if (subjectCaCerts == null) return null;

      for (X509Certificate caCert : subjectCaCerts) {
        PublicKey publicKey = caCert.getPublicKey();
        try {
          cert.verify(publicKey);
          return caCert;
        } catch (Exception ignored) {
        }
      }

      return null;
    }
  }
}


text:
<?php
/**
 * WC API Client Reports resource class
 *
 * @since 2.0
 */
class WC_API_Client_Resource_Reports extends WC_API_Client_Resource {

	/**
	 * Setup the resource
	 *
	 * @since 2.0
	 * @param WC_API_Client $client class instance
	 */
	public function __construct( $client ) {

		parent::__construct( 'reports', '', $client );
	}

	/**
	 * Get list of reports
	 *
	 * GET /reports
	 *
	 * @since 2.0
	 * @return array|object list of reports!
	 */
	public function get() {

		$this->set_request_args( array(
			'method' => 'GET',
		) );

		return $this->do_request();
	}

	/**
	 * Get Sales report
	 *
	 * GET /reports/sales
	 *
	 * @since 2.0
	 * @param array $args acceptable reports endpoint args, like `filter[period]`
	 * @return array|object sales report!
	 */
	public function get_sales( $args = array() ) {

		$this->set_request_args( array(
			'method' => 'GET',
			'path'   => 'sales',
			'params' => $args,
		) );

		return $this->do_request();
	}

	/**
	 * Get Top Sellers report
	 *
	 * GET /reports/sales/top_sellers
	 *
	 * @since 2.0
	 * @param array $args acceptable reports endpoint args, like `filter[period]`
	 * @return array|object sales report!
	 */
	public function get_top_sellers( $args = array() ) {

		$this->set_request_args( array(
			'method' => 'GET',
			'path'   => array( 'sales', 'top_sellers' ),
			'params' => $args,
		) );

		return $this->do_request();
	}

	/** Convenience methods - these do not map directly to an endpoint ********/

	// none yet

}


text:
import numpy as np
import pandas as pd
from scipy import stats
from numba import jit, prange

__all__ = ['bootci_nb',
           'permtest_nb']

@jit(nopython=True, parallel=True, error_model='numpy')
def _bootstrap_jit(dat, statfunction, nstraps, nstats):
    n = dat.shape[0]
    res = np.zeros((nstraps, nstats))
    for booti in range(nstraps):
        rind = np.random.choice(np.arange(n), n)
        res[booti, :] = statfunction(dat[rind, :])
    """Sort each stat independently"""
    for stati in range(nstats):
        res[:, stati].sort()
    return res
'''
@jit(nopython=True, parallel=True, error_model='numpy')
def _jackknife_jit(dat, statfunction, nstats):
    n = dat.shape[0]
    jstats = np.zeros((n, nstats))
    #jind = np.ones(n, dtype=np.bool_)
    for i in prange(n):
        jind = np.ones(n, dtype=np.bool_)
        jind[i] = False
        jstats[i, :] = statfunction(dat[jind, :])
        #jind[i] = True

    bca_accel = np.zeros(nstats)
    for coli in range(nstats):
        jmean = np.nanmean(jstats[:, coli])
        bca_accel[coli] = np.nansum((jmean - jstats[:, coli])**3) / (6.0 * np.nansum((jmean - jstats[:, coli])**2)**1.5)
    return bca_accel
'''
@jit(nopython=True, parallel=True, error_model='numpy')
def _jackknife_jit(dat, statfunction, nstats):
    n = dat.shape[0]
    jstats = np.zeros((n, nstats))
    jind = np.ones(n, dtype=np.bool_)
    for i in range(n):
        jind[i] = False
        jstats[i, :] = statfunction(dat[jind, :])
        jind[i] = True

    bca_accel = np.zeros(nstats)
    for coli in range(nstats):
        jmean = np.nanmean(jstats[:, coli])
        bca_accel[coli] = np.nansum((jmean - jstats[:, coli])**3) / (6.0 * np.nansum((jmean - jstats[:, coli])**2)**1.5)
    return bca_accel

def bootci_nb(dat, statfunction, alpha=0.05, n_samples=10000, method='bca'):
    """Estimate bootstrap CIs for a statfunction that operates along the rows of
    a np.ndarray matrix and returns a np.ndarray vector of results.

    Parameters
    ----------
    dat : np.ndarray
        Data that will be passed to statfunction as a single parameter.
    statfunction : function
        Function that should operate along the rows of dat and return a vector
    alpha : float [0, 1]
        Specify CI: [alpha/2, 1-alpha/2]
    n_samples : int
        Number of bootstrap samples.
    method : str
        Specify bias-corrected and accelerated ("bca") or percentile ("pi")
        bootstrap.

    Returns
    -------
    cis : np.ndarray [est, lcl, ucl] x [nstats]
        Point-estimate and CI of statfunction of dat"""

    ostat = statfunction(dat)
    nstats = len(ostat)

    alphas = np.array([alpha/2, 1-alpha/2])

    """boot_res.shape --> (n_samples, nstats)"""
    boot_res = _bootstrap_jit(dat, statfunction, nstraps=n_samples, nstats=nstats)

    if method == 'pi':
        """Percentile Interval Method
        avals.shape --> (2, nstats)"""
        avals = np.tile(alphas, (boot_res.shape[1], 1)).T
    elif method == 'bca':
        """Bias-Corrected Accelerated Method
        bca_accel.shape --> (nstats, )"""
        bca_accel = _jackknife_jit(dat, statfunction, nstats)

        z0 = stats.distributions.norm.ppf( (np.sum(boot_res < ostat[None, :], axis=0)) / np.sum(~np.isnan(boot_res), axis=0) )
        zs = z0[None, :] + stats.distributions.norm.ppf(alphas).reshape(alphas.shape + (1,) * z0.ndim)
        avals = stats.distributions.norm.cdf(z0[None, :] + zs / (1 - bca_accel[None, :] * zs))

    non_nan_ind = ~np.isnan(boot_res)
    nvals = np.round((np.sum(non_nan_ind, axis=0) - 1) * avals).astype(int)

    """cis.shape --> (nstats, 3)"""
    cis = np.zeros((boot_res.shape[1], len(avals) + 1))
    for i in range(boot_res.shape[1]):
        cis[i, 0] = ostat[i]
        if np.all(np.isnan(avals[:, i])):
            print('No bootstrap variation in stat %d: LCL = UCL = observed stat' % (i))
            cis[i, 1:1+len(alphas)] = ostat[i] * np.ones(len(alphas))
        else:
            cis[i, 1:1+len(alphas)] = boot_res[nvals[:, i], i]
            if np.any(nvals[:, i] < 10) or np.any(nvals[:, i] > n_samples-10):
                print('Extreme samples used for stat %d: [%d, %d]. Results unstable.' % (i, nvals[0,i], nvals[1,i]))
    return cis

@jit(nopython=True, parallel=True, error_model='numpy')
def _perm_jit(d, sf, pcs, n):
    res = sf(d)
    samples = np.zeros((len(res), n))
    """Using prange here means we have to make a copy of d inside each loop
    Cost is memory, but this should be fine with reasonably sized matrices.
    Speed up is about 10x"""
    for sampi in prange(n):
        d_copy = d.copy()
        rind = np.random.permutation(d_copy.shape[0])
        for coli in pcs:
            d_copy[:, coli] = d_copy[rind, coli]
        samples[:, sampi] = sf(d_copy)
    return samples

def permtest_nb(dat, statfunction, perm_cols, n_samples=9999, alternative='two-sided'):
    """Estimate p-values for the results of statfunction against the permutation null.

    Parameters
    ----------
    dat : np.ndarray matrix
        Observed data required as sole input for statfunction.
    statfunction : function
        Operates on dat and returns a vector of statistics.
    perm_cols : array of indices
        Columns that need to be permuted in dat to generate a null dataset
    n_samples : int
        Number of permutations to test
    alternative : str
        Specify a "two-sided" test or one that tests that the observed data is "less" than
        or "greater" than the null statistics.

    Returns
    -------
    pvalue : float"""

    samples = _perm_jit(dat.copy(), statfunction, np.array(perm_cols, dtype=np.int), int(n_samples))
    if alternative == 'two-sided':
        #pvalues = ((np.abs(samples) > np.abs(statfunction(dat)[None, :])).sum(axis=1) + 1) / (n_samples + 1)
        pvalues = ((np.abs(samples) > np.abs(statfunction(dat)[:, None])).sum(axis=1) + 1) / (n_samples + 1)
    elif alternative == 'greater':
        pvalues = ((samples > statfunction(dat)[None, :]).sum(axis=1) + 1) / (n_samples + 1)
    elif alternative == 'less':
        pvalues = ((samples < statfunction(dat)[None, :]).sum(axis=1) + 1) / (n_samples + 1)
    return pvalues

def _test_permtest(effect=0.5, n_samples=9999):
    from scipy import stats
    import time

    dat = np.random.randn(1000, 5)
    dat[:, 0] = np.random.randint(2, size=dat.shape[0])

    dat[dat[:, 0] == 0, 1] = dat[dat[:, 0] == 0, 1] + effect

    @jit(nopython=True)
    def func(d):
        return np.array([np.mean(d[d[:, 0] == 0, 1]) - np.mean(d[d[:, 0] == 1, 1])])

    res = func(dat)
    st = time.time()
    res = permtest_nb(dat, func, perm_cols=[0], n_samples=n_samples)
    et = (time.time() - st)
    print(res)
    print('Time: %1.2f sec' % et)

    print(stats.ttest_ind(dat[dat[:, 0] == 0, 1], dat[dat[:, 0] == 1, 1]))

def _test_bootci(n_samples=10000, method='bca'):
    import scikits.bootstrap as boot
    import time

    np.random.seed(110820)
    dat = np.random.randn(1000, 5)

    @jit(nopython=True)
    def func(d):
        return np.array([np.mean(d[:, 0]), np.median(d[:, 1]), np.max(d[:, 2])])

    st = time.time()
    res = bootci_nb(dat, func, alpha=0.05, n_samples=n_samples, method=method)
    et = (time.time() - st)
    print(res)
    print('Time: %1.2f sec' % et)

    st = time.time()
    a = boot.ci(dat[:, 0], statfunction=np.mean, n_samples=n_samples, method=method)
    b = boot.ci(dat[:, 1], statfunction=np.median, n_samples=n_samples, method=method)
    c = boot.ci(dat[:, 2], statfunction=np.max, n_samples=n_samples, method=method)
    et = (time.time() - st)

    print('Mean_0', a)
    print('Median_1', b)
    print('Median_2', c)
    print('Time: %1.2f sec' % et)


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

<TITLE>
IntegerLiteral (JSP 2.0 Expression Language Implementation (Version 1.0))
</TITLE>
<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../stylesheet.css" TITLE="Style">

      Overview
      Package
    Class
      Tree
      Deprecated
      Index
      Help

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

All Classes

  SUMMARY: NESTED | FIELD | CONSTR | METHOD

DETAIL: FIELD | CONSTR | METHOD

org.apache.commons.el

Class  IntegerLiteral

java.lang.Object
  |
  +--org.apache.commons.el.Expression
        |
        +--org.apache.commons.el.Literal
              |
              +--org.apache.commons.el.IntegerLiteral

public class IntegerLiteral
extends Literal

An expression representing an integer literal value.  The value
 is stored internally as a long.

Version:
$Change: 181177 $$DateTime: 2001/06/26 08:45:09 $$Author: luehe $

Author:
Nathan Abramson - Art Technology Group

Field Summary

Fields inherited from class org.apache.commons.el.Literal

mValue

Constructor Summary

IntegerLiteral(java.lang.String pToken)

          Constructor

Method Summary

 java.lang.String
getExpressionString()

          Returns the expression in the expression language syntax

(package private) static java.lang.Object
getValueFromToken(java.lang.String pToken)

          Parses the given token into the literal value

Methods inherited from class org.apache.commons.el.Literal

evaluate, getValue, setValue

Methods inherited from class java.lang.Object

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

Constructor Detail

IntegerLiteral

public IntegerLiteral(java.lang.String pToken)

Constructor

Method Detail

getValueFromToken

static java.lang.Object getValueFromToken(java.lang.String pToken)

Parses the given token into the literal value

getExpressionString

public java.lang.String getExpressionString()

Returns the expression in the expression language syntax

Specified by:
getExpressionString in class Expression

      Overview
      Package
    Class
      Tree
      Deprecated
      Index
      Help

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

All Classes

  SUMMARY: NESTED | FIELD | CONSTR | METHOD

DETAIL: FIELD | CONSTR | METHOD

Copyright (c) 2001-2002 - Apache Software Foundation


text:
begin
	require 'pg_ext'
rescue LoadError
	# If it's a Windows binary gem, try the <major>.<minor> subdirectory
	if RUBY_PLATFORM =~/(mswin|mingw)/i
		major_minor = RUBY_VERSION[ /^(\d+\.\d+)/ ] or
			raise "Oops, can't extract the major/minor version from #{RUBY_VERSION.dump}"
		require "#{major_minor}/pg_ext"
	else
		raise
	end

end

# The top-level PG namespace.
module PG

	# Library version
	VERSION = '0.16.0'

	# VCS revision
	REVISION = %q$Revision$

	### Get the PG library version. If +include_buildnum+ is +true+, include the build ID.
	def self::version_string( include_buildnum=false )
		vstring = "%s %s" % [ self.name, VERSION ]
		vstring << " (build %s)" % [ REVISION[/: ([[:xdigit:]]+)/, 1] || '0' ] if include_buildnum
		return vstring
	end

	### Convenience alias for PG::Connection.new.
	def self::connect( *args )
		return PG::Connection.new( *args )
	end

	require 'pg/exceptions'
	require 'pg/constants'
	require 'pg/connection'
	require 'pg/result'

end # module PG

# Backward-compatible aliase
PGError = PG::Error


text:
"""
Django settings for Hackerhane project.

For more information on this file, see
https://docs.djangoproject.com/en/dev/topics/settings/

For the full list of settings and their values, see
https://docs.djangoproject.com/en/dev/ref/settings/
"""

# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
import os
BASE_DIR = os.path.dirname(os.path.dirname(__file__))

ADMINS = (
     ('Elif T. Kus', 'elifkus@gmail.com'),
     ('Kasa', 'kasa@istanbulhs.org'),
)

MANAGERS = ADMINS

# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/dev/howto/deployment/checklist/

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True

TEMPLATE_DEBUG = True

ALLOWED_HOSTS = []

# Application definition

INSTALLED_APPS = (
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'common',
    'accounting',
    'members',
    'membership',
    'bootstrapform',
    'allauth',
    'allauth.account',
    'allauth.socialaccount',
    'allauth.socialaccount.providers.facebook',
    #'allauth.socialaccount.providers.github',
    'allauth.socialaccount.providers.google',
    #'allauth.socialaccount.providers.linkedin',
    #'allauth.socialaccount.providers.openid',
    #'allauth.socialaccount.providers.stackexchange',
    #'allauth.socialaccount.providers.twitter',
    'django.contrib.sites', #added for allauth
)

MIDDLEWARE_CLASSES = (
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
)

ROOT_URLCONF = 'hackerhane.urls'

WSGI_APPLICATION = 'hackerhane.wsgi.application'

# Database
# https://docs.djangoproject.com/en/dev/ref/settings/#databases

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
    },
}

# Internationalization
# https://docs.djangoproject.com/en/dev/topics/i18n/

LANGUAGE_CODE = 'tr'

TIME_ZONE = 'Europe/Istanbul'

USE_I18N = True

USE_L10N = True

USE_TZ = True

# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/dev/howto/static-files/

STATIC_URL = '/static/'

AUTH_USER_MODEL = 'members.HsUser'

TEMPLATE_DIRS = [os.path.join(BASE_DIR, 'templates')]

TEMPLATE_LOADERS = (
    'django.template.loaders.filesystem.Loader',
    'django.template.loaders.app_directories.Loader',
    'django.template.loaders.eggs.Loader',
)

TEMPLATE_CONTEXT_PROCESSORS = (
    "django.contrib.auth.context_processors.auth",
    "django.core.context_processors.debug",
    "django.core.context_processors.i18n",
    "django.core.context_processors.media",
    "django.core.context_processors.static",
    "django.core.context_processors.tz",
    "django.contrib.messages.context_processors.messages",
    "django.core.context_processors.request",
    "allauth.account.context_processors.account",
    "allauth.socialaccount.context_processors.socialaccount",
)

AUTHENTICATION_BACKENDS = (
    "django.contrib.auth.backends.ModelBackend",
    "allauth.account.auth_backends.AuthenticationBackend",
)

DATE_FORMAT = 'j N Y'

#allauth settings
ACCOUNT_AUTHENTICATION_METHOD = "email"

ACCOUNT_EMAIL_REQUIRED = True

ACCOUNT_EMAIL_VERIFICATION = "mandatory"

ACCOUNT_EMAIL_SUBJECT_PREFIX = "[Ist Hackerspace Üye] "

ACCOUNT_LOGOUT_ON_GET = True
ACCOUNT_LOGOUT_REDIRECT_URL ="/"
ACCOUNT_SIGNUP_FORM_CLASS = 'members.forms.SignupForm'
#A string pointing to a custom form class (e.g. 'myapp.forms.SignupForm') that is used during signup to ask the user for additional input (e.g. newsletter signup, birth date). This class should implement a 'save' method, accepting the newly signed up user as its only parameter.
ACCOUNT_SIGNUP_PASSWORD_VERIFICATION = True
ACCOUNT_UNIQUE_EMAIL = True
ACCOUNT_USER_MODEL_USERNAME_FIELD = "email"
ACCOUNT_USER_MODEL_EMAIL_FIELD = "email"
#ACCOUNT_USER_DISPLAY (=a callable returning user.username)
#A callable (or string of the form 'some.module.callable_name') that takes a user as its only argument and returns the display name of the user. The default implementation returns user.username.
ACCOUNT_USERNAME_MIN_LENGTH = 5
#ACCOUNT_USERNAME_BLACKLIST (=[])
ACCOUNT_USERNAME_REQUIRED = False
#ACCOUNT_PASSWORD_INPUT_RENDER_VALUE (=False)
#render_value parameter as passed to PasswordInput fields.
ACCOUNT_PASSWORD_MIN_LENGTH = 6
SOCIALACCOUNT_QUERY_EMAIL = ACCOUNT_EMAIL_REQUIRED
SOCIALACCOUNT_AUTO_SIGNUP = False
#Attempt to bypass the signup form by using fields (e.g. username, email) retrieved from the social account provider. If a conflict arises due to a duplicate e-mail address the signup form will still kick in.
#SOCIALACCOUNT_AVATAR_SUPPORT (= 'avatar' in settings.INSTALLED_APPS)
#Enable support for django-avatar. When enabled, the profile image of the user is copied locally into django-avatar at signup.
SOCIALACCOUNT_EMAIL_REQUIRED = ACCOUNT_EMAIL_REQUIRED
SOCIALACCOUNT_EMAIL_VERIFICATION = False

SITE_ID = 1

SOCIALACCOUNT_PROVIDERS = \
    { 'facebook':
        { 'SCOPE': ['email',],
          'AUTH_PARAMS': { 'auth_type': 'reauthenticate' },
          'METHOD': 'oauth2' ,
          'LOCALE_FUNC': lambda request: 'tr'},
      'google':
        { 'SCOPE': ['https://www.googleapis.com/auth/userinfo.profile',
                    'https://www.googleapis.com/auth/userinfo.email'],
          'AUTH_PARAMS': { 'access_type': 'online' } }
    }

STATICFILES_FINDERS = (
    'django.contrib.staticfiles.finders.FileSystemFinder',
    'django.contrib.staticfiles.finders.AppDirectoriesFinder',
)

LOGIN_REDIRECT_URL="/"

try:
    from hackerhane.local_settings import *
except ImportError:
    pass


text:
'use strict';

var util = require('util'),
    HttpEntity = require('./http_entity');

/**
 * Improving proxy entity
 * @param logger
 * @param requestObject
 * @param customCallback
 * @param timeout
 * @param cleaner
 * @constructor
 */
function ProxyEntity(logger, requestObject, customCallback, timeout, cleaner)
{
    this.data = {};

    this.logger = logger;
    this.request = requestObject;
    this.response = customCallback;
    this.timeout = timeout;
    this.timeoutHandler = null;
    this.cleaner = cleaner;

    if(this.validate()) {
        this.timeoutHandler = setTimeout((this.timeout || 60) * 1000, this.entityTimeout.bind(this));
        this.parseRequestData();
    }
}

util.inherits(ProxyEntity, HttpEntity);

/**
 * Validate params
 * @returns {boolean}
 */
ProxyEntity.prototype.validate = function()
{
    if(this.request && typeof this.request != 'object') this.request = null;
    if(typeof this.response != 'function') this.response = null;

    if(! (this.request && this.response)) {
        this.logger.warn('JSON-RPC entity: Invalid entity params');
        this.destroy();
    }

    return !!(this.request && this.response);
};

/**
 * Parse request payload
 */
ProxyEntity.prototype.parseRequestData = function()
{
    this.data = {
        method: this.request.method,
        rawHeaders: this.request.headers,
        rawData: this.request.payload,
        content: this.request.payload,
        requestId: this.request.payload.id, //TODO: would be not 'undefined' for batch requests
        isBatch: Array.isArray(this.request.payload),
        url: this.request.url
    };

    this.emit('ready');
};

/**
 * Send response
 * @param httpCode
 * @param headers
 * @param payload
 */
ProxyEntity.prototype.sendResponse = function(httpCode, headers, payload)
{
    clearTimeout(this.timeoutHandler);

    var response = {
        httpCode: httpCode,
        headers: headers,
        payload: payload
    };

    this.getResponse()(JSON.parse(JSON.stringify(response)));
};

module.exports = ProxyEntity;


text:
#include "ecma-globals.h"

#define ECMA_BUILTINS_INTERNAL
#include "ecma-builtins-internal.h"

#define BUILTIN_INC_HEADER_NAME "ecma-builtin-generator.inc.h"
#define BUILTIN_UNDERSCORED_ID  generator
#include "ecma-builtin-internal-routines-template.inc.h"

/** \addtogroup ecma ECMA
 * @{
 *
 * \addtogroup ecmabuiltins
 * @{
 *
 * \addtogroup generator ECMA Generator object built-in
 * @{
 */

/**
 * @}
 * @}
 * @}
 */


text:
'use strict';

/* Controllers */

var controllers = angular.module('myApp.controllers', []);
controllers.controller('Controller1', function($scope) {

	$scope.helloMessageOne = "Hello from Controller 1";

})

controllers.controller('Controller2', function($scope) {

	$scope.helloMessageOne = "Hello from Controller 2";

})

controllers.controller('Controller1Child', function($scope) {

})


text:
<?php

namespace Tests\PHP\Manipulator\TokenFinder;

use PHP\Manipulator\TokenFinder\Result;
use PHP\Manipulator\TokenFinder\__classname__;
use PHP\Manipulator\TokenContainer;
use PHP\Manipulator\Token;

/**
 * @group TokenFinder\__classname__
 */
class __classname__Test
extends \Tests\TestCase
{

    /**
     * @return array
     */
    public function findProvider()
    {
        $data = array();
        $path = '/TokenFinder/__classname__/';

        #0
        $data[] = array(
            $container = $this->getContainerFromFixture($path . 'input0.php'),
            $container[1],
            array(),
            Result::factory(array($container[1], $container[2], $container[3], $container[4])),
        );

        return $data;
    }

    /**
     * @dataProvider findProvider
     * @covers \PHP\Manipulator\TokenFinder\__classname__::find
     * @covers \PHP\Manipulator\TokenFinder\__classname__::<protected>
     */
    public function testFind($container, $token, $params, $expectedResult)
    {
        $finder = new __classname__();
        $actualResult = $finder->find($token, $container, $params);
        $this->assertFinderResultsMatch($expectedResult, $actualResult);
    }
}


text:
var EndGate;
(function (EndGate) {
    (function (MapLoaders) {
        (function (_) {
            (function (TMX) {
                var OrthogonalLoader = (function () {
                    function OrthogonalLoader() {
                    }
                    OrthogonalLoader.prototype.Load = function (data, propertyHooks, onComplete) {
                        var _this = this;
                        // We're initially at 0%.
                        var percent = 0, tileCount = 0, onPartialLoad = new EndGate.EventHandler1();

                        // Load all the sources referenced within the data
                        this.LoadTilesetSources(data.tilesets, function (tileset) {
                            percent += (1 / data.tilesets.length) * OrthogonalLoader._imagePercentMax;

                            onPartialLoad.Trigger(percent);
                        }, function (tilesetSources) {
                            // Triggered once all the sources have completed loading
                            // All the tiles extracted represent our resource list
                            var resources = _this.ExtractTilesetTiles(data.tilesets, tilesetSources, propertyHooks), mappings, layers = new Array(), layerPercentValue = (1 - OrthogonalLoader._imagePercentMax) / data.layers.length;

                            percent = OrthogonalLoader._imagePercentMax;

                            asyncLoop(function (next, i) {
                                if (data.layers[i].type !== "tilelayer") {
                                    throw new Error("Invalid layer type.  The layer type '" + data.layers[i].type + "' is not supported.");
                                }

                                _this.AsyncBuildLayer(data, i, propertyHooks, resources, function (details, percentLoaded) {
                                    onPartialLoad.Trigger(percent + percentLoaded * layerPercentValue);
                                }, function (layer) {
                                    percent += layerPercentValue;

                                    onPartialLoad.Trigger(percent);

                                    layers.push(layer);

                                    next();
                                });
                            }, data.layers.length, function () {
                                // All layers loaded
                                onComplete({
                                    Layers: layers
                                });
                            });
                        });

                        for (var i = 0; i < data.layers.length; i++) {
                            tileCount += data.layers[i].data.length;
                        }

                        return {
                            TileCount: tileCount,
                            LayerCount: data.layers.length,
                            ResourceSheetCount: data.tilesets.length,
                            OnPercentLoaded: onPartialLoad
                        };
                    };

                    OrthogonalLoader.prototype.LoadTilesetSources = function (tilesets, onTilesetLoad, onComplete) {
                        var tilesetSources = {}, loadedCount = 0, onLoaded = function (source) {
                            onTilesetLoad(source);

                            // If everything has loaded
                            if (++loadedCount === tilesets.length) {
                                onComplete(tilesetSources);
                            }
                        };

                        for (var i = 0; i < tilesets.length; i++) {
                            tilesetSources[tilesets[i].name] = new EndGate.Graphics.ImageSource(tilesets[i].image, tilesets[i].imagewidth, tilesets[i].imageheight);
                            tilesetSources[tilesets[i].name].OnLoaded.Bind(onLoaded);
                        }
                    };

                    OrthogonalLoader.prototype.ExtractTilesetTiles = function (tilesets, tilesetSources, propertyHooks) {
                        var tilesetTiles = new Array(), resourceHooks = new Array(), sources, index;

                        tilesets.sort(function (a, b) {
                            return a.firstgid - b.firstgid;
                        });

                        for (var i = 0; i < tilesets.length; i++) {
                            sources = EndGate.Graphics.SquareTileMap.ExtractTiles(tilesetSources[tilesets[i].name], tilesets[i].tilewidth, tilesets[i].tileheight);

                            for (var property in tilesets[i].properties) {
                                if (typeof propertyHooks.ResourceSheetHooks[property] !== "undefined") {
                                    for (var j = tilesets[i].firstgid - 1; j < tilesets[i].firstgid - 1 + sources.length; j++) {
                                        if (typeof resourceHooks[j] === "undefined") {
                                            resourceHooks[j] = new Array();
                                        }

                                        resourceHooks[j].push(this.BuildHookerFunction(tilesets[i].properties[property], propertyHooks.ResourceSheetHooks[property]));
                                    }
                                }
                            }

                            for (var tileIndex in tilesets[i].tileproperties) {
                                for (var property in tilesets[i].tileproperties[tileIndex])
                                    if (typeof propertyHooks.ResourceTileHooks[property] !== "undefined") {
                                        index = parseInt(tileIndex) + tilesets[i].firstgid - 1;

                                        if (typeof resourceHooks[index] === "undefined") {
                                            resourceHooks[index] = new Array();
                                        }

                                        resourceHooks[index].push(this.BuildHookerFunction(tilesets[i].tileproperties[tileIndex][property], propertyHooks.ResourceTileHooks[property]));
                                    }
                            }

                            tilesetTiles = tilesetTiles.concat(sources);
                        }

                        return {
                            Resources: tilesetTiles,
                            ResourceHooks: resourceHooks
                        };
                    };

                    // Not true async but it frees up the DOM
                    OrthogonalLoader.prototype.AsyncBuildLayer = function (tmxData, layerIndex, propertyHooks, resources, onTileLoad, onComplete) {
                        var _this = this;
                        setTimeout(function () {
                            // Convert the layer data to a 2 dimensional array and subtract 1 from all the data points (to make it 0 based)
                            var tmxLayer = tmxData.layers[layerIndex], mappings = _this.NormalizeLayerData(tmxLayer.data, tmxData.width), layer = new EndGate.Graphics.SquareTileMap(tmxLayer.x, tmxLayer.y, tmxData.tilewidth, tmxData.tileheight, resources.Resources, mappings), layerHooks = new Array();

                            for (var property in tmxLayer.properties) {
                                if (typeof propertyHooks.LayerHooks[property] !== "undefined") {
                                    layerHooks.push(_this.BuildHookerFunction(tmxLayer.properties[property], propertyHooks.LayerHooks[property]));
                                }
                            }

                            layer.ZIndex = layerIndex;
                            layer.Visible = tmxLayer.visible;
                            layer.Opacity = tmxLayer.opacity;

                            // Enough delay to ensure that the page doesn't freeze
                            layer.RowLoadDelay = EndGate.TimeSpan.FromMilliseconds(5);

                            layer.OnTileLoad.Bind(function (details, percentComplete) {
                                if (resources.ResourceHooks[details.ResourceIndex]) {
                                    for (var i = 0; i < resources.ResourceHooks[details.ResourceIndex].length; i++) {
                                        resources.ResourceHooks[details.ResourceIndex][i](details);
                                    }
                                }

                                for (var i = 0; i < layerHooks.length; i++) {
                                    layerHooks[i](details);
                                }

                                onTileLoad(details, percentComplete);
                            });

                            layer.OnLoaded.Bind(function () {
                                onComplete(layer);
                            });
                        }, 0);
                    };

                    OrthogonalLoader.prototype.BuildHookerFunction = function (propertyValue, fn) {
                        return function (details) {
                            return fn(details, propertyValue);
                        };
                    };

                    OrthogonalLoader.prototype.NormalizeLayerData = function (data, columns) {
                        var normalized = new Array(), index;

                        for (var i = 0; i < data.length; i++) {
                            index = Math.floor(i / columns);

                            if (!(normalized[index] instanceof Array)) {
                                normalized[index] = new Array();
                            }

                            // Subtract 1 because TMX format starts at 1
                            normalized[index].push(data[i] - 1);
                        }

                        return normalized;
                    };
                    OrthogonalLoader._imagePercentMax = .2;
                    return OrthogonalLoader;
                })();
                TMX.OrthogonalLoader = OrthogonalLoader;
            })(_.TMX || (_.TMX = {}));
            var TMX = _.TMX;
        })(MapLoaders._ || (MapLoaders._ = {}));
        var _ = MapLoaders._;
    })(EndGate.MapLoaders || (EndGate.MapLoaders = {}));
    var MapLoaders = EndGate.MapLoaders;
})(EndGate || (EndGate = {}));


text:
package com.emitrom.lienzo.client.widget;

import com.emitrom.lienzo.client.core.LienzoGlobals;
import com.emitrom.lienzo.client.core.event.OrientationChangeEvent;
import com.emitrom.lienzo.client.core.event.OrientationChangeEvent.Orientation;
import com.emitrom.lienzo.client.core.event.ResizeChangeEvent;
import com.emitrom.lienzo.client.core.event.ResizeEndEvent;
import com.emitrom.lienzo.client.core.event.ResizeStartEvent;
import com.emitrom.lienzo.client.core.i18n.MessageConstants;
import com.emitrom.lienzo.client.core.mediator.IMediator;
import com.emitrom.lienzo.client.core.mediator.Mediators;
import com.emitrom.lienzo.client.core.shape.Layer;
import com.emitrom.lienzo.client.core.shape.Scene;
import com.emitrom.lienzo.client.core.shape.Viewport;
import com.emitrom.lienzo.shared.core.types.DataURLType;
import com.emitrom.lienzo.shared.core.types.IColor;
import com.google.gwt.core.client.Scheduler;
import com.google.gwt.core.client.Scheduler.ScheduledCommand;
import com.google.gwt.dom.client.Style.Cursor;
import com.google.gwt.event.logical.shared.ResizeEvent;
import com.google.gwt.event.logical.shared.ResizeHandler;
import com.google.gwt.user.client.Timer;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.ui.FocusPanel;
import com.google.gwt.user.client.ui.Label;

/**
 * LienzoPanel acts as a Container for a {@link Viewport}.
 *
 *

 *
An application will typically be composed of one or more LienzoPanels.

 *
A LienzoPanel takes width and height as input parameters.

 *
A {@link Viewport} will contain one main {@link Scene}

 *
The main {@link Scene} can contain multiple {@link Layer}.

 *

 */
public class LienzoPanel extends FocusPanel
{
    private final LienzoHandlerManager m_events;

    private final int                  m_wide;

    private final int                  m_high;

    private Viewport                   m_view;

    private boolean                    m_resizing                     = false;

    private Timer                      m_resize_timer;

    private int                        m_resize_check_repeat_interval = 750;

    private Orientation                m_orientation;

    public LienzoPanel(int wide, int high)
    {
        m_wide = wide;

        m_high = high;

        m_view = new Viewport(wide, high);

        if (LienzoGlobals.getInstance().isCanvasSupported())
        {
            getElement().appendChild(m_view.getElement());

            setPixelSize(wide, high);

            m_events = new LienzoHandlerManager(this);

            initResizeTimer();

            addHandlers();

        }
        else
        {
            add(new Label(MessageConstants.MESSAGES.getCanvasUnsupportedMessage()));

            m_events = null;
        }

    }

    /**
     * Adds a layer to the {@link LienzoPanel}.
     * It should be noted that this action will cause a {@link Layer} draw operation, painting all children in the Layer.
     *
     * @param layer
     * @return
     */
    public LienzoPanel add(Layer layer)
    {
        getScene().add(layer);

        return this;
    }

    /**
     * Removes a layer from the {@link LienzoPanel}.
     * It should be noted that this action will cause a {@link Layer} draw operation, painting all children in the Layer.
     *
     * @param layer
     * @return
     */
    public LienzoPanel remove(Layer layer)
    {
        getScene().remove(layer);

        return this;
    }

    /**
     * Removes all layer from the {@link LienzoPanel}.
     * It should be noted that this action will cause a {@link Layer} draw operation, painting all children in the Layer.
     *
     * @param layer
     * @return
     */
    public LienzoPanel removeAll()
    {
        getScene().removeAll();

        return this;
    }

    /**
     * Sets the size in pixels of the {@link LienzoPanel}
     * Sets the size in pixels of the {@link Viewport} contained and automatically added to the instance of the {@link LienzoPanel}
     */
    @Override
    public void setPixelSize(int wide, int high)
    {
        super.setPixelSize(wide, high);

        m_view.setPixelSize(wide, high);
    }

    /**
     * Sets the type of cursor to be used when hovering above the element.
     * @param cursor
     */
    public void setCursor(final Cursor cursor)
    {
        Scheduler.get().scheduleDeferred(new ScheduledCommand()
        {
            @Override
            public void execute()
            {
                getElement().getStyle().setCursor(cursor);
            }
        });
    }

    /**
     * Returns the {@link Viewport} main {@link Scene}
     * @return
     */
    public Scene getScene()
    {
        return m_view.getScene();
    }

    /**
     * Returns the automatically create {@link Viewport} instance.
     * @return
     */
    public Viewport getViewport()
    {
        return m_view;
    }

    /**
     * Sets the {@link Viewport} background {@link Layer}
     *
     * @param layer
     */
    public void setBackgroundLayer(Layer layer)
    {
        m_view.setBackgroundLayer(layer);
    }

    /**
     * Returns the {@link Viewport} Drag {@link Layer}
     *
     * @return
     */
    public Layer getDragLayer()
    {
        return m_view.getDraglayer();
    }

    /**
     * Sets the frequency in milliseconds at which the
     * timer will check to see if a resize operation is taking place.
     *
     * Default value is 750 milliseconds.
     *
     * The value is used to determine when to trigger a ResizeEndEvent
     *
     * @param resizeCheckRepeatInterval
     */
    public void setResizeCheckRepeatInterval(int resizeCheckRepeatInterval)
    {
        m_resize_check_repeat_interval = resizeCheckRepeatInterval;
    }

    /**
     * Returns the resize check repeat interval that is being used
     * to check if there is a resize operation taking place.
     *
     * The value is used to determine when to trigger a ResizeEndEvent
     *
     * @return
     */
    public int setResizeCheckRepeatInterval()
    {
        return m_resize_check_repeat_interval;
    }

    /**
     * Gets the width in pixels.
     *
     * @return
     */
    public int getWidth()
    {
        return m_wide;
    }

    /**
     * Returns the height.
     *
     * @return
     */
    public int getHeight()
    {
        return m_high;
    }

    /**
     * Returns a JSON representation of the {@link Viewport} children.
     * @return
     */
    public String toJSONString()
    {
        return m_view.toJSONString();
    }

    public final String toDataURL()
    {
        return m_view.toDataURL();
    }

    public final String toDataURL(boolean includeBackgroundLayer)
    {
        return m_view.toDataURL(includeBackgroundLayer);
    }

    public final String toDataURL(DataURLType mimetype)
    {
        return m_view.toDataURL(mimetype);
    }

    public final String toDataURL(DataURLType mimetype, boolean includeBackgroundLayer)
    {
        return m_view.toDataURL(mimetype, includeBackgroundLayer);
    }

    /**
     * Sets the background color of the LienzoPanel.
     *
     * @param color String
     * @return this LienzoPanel
     */
    public LienzoPanel setBackgroundColor(String color)
    {
        getElement().getStyle().setBackgroundColor(color);

        return this;
    }

    /**
     * Sets the background color of the LienzoPanel.
     *
     * @param color IColor, i.e. ColorName or Color
     * @return this LienzoPanel
     */
    public LienzoPanel setBackgroundColor(IColor color)
    {
        return setBackgroundColor(color.getColorString());
    }

    /**
     * Returns the background color of this LienzoPanel.
     * Will return null if no color was set, in which case it's probably "white",
     * unless it was changed via CSS rules.
     *
     * @return String
     */
    public String getBackgroundColor()
    {
        return getElement().getStyle().getBackgroundColor();
    }

    /**
     * Returns the {@link Mediators} for this panels {@link Viewport}.
     * Mediators can be used to e.g. to add zoom operations.
     *
     * @return Mediators
     */
    public Mediators getMediators()
    {
        return m_view.getMediators();
    }

    /**
     * Add a mediator to the stack of {@link Mediators} for this panels {@link Viewport}.
     * The one that is added last, will be called first.
     *
     * Mediators can be used to e.g. to add zoom operations.
     *
     * @param mediator IMediator
     */
    public void pushMediator(IMediator mediator)
    {
        m_view.pushMediator(mediator);
    }

    public static native void enableWindowMouseWheelScroll(boolean enabled)
    /*-{
		$wnd.mousewheel = function() {
			return enabled;
		}
    }-*/;

    private void initResizeTimer()
    {
        m_resize_timer = new Timer()
        {
            @Override
            public void run()
            {
                m_resizing = false;

                if (!m_resizing)
                {
                    int w = getElement().getParentElement().getClientWidth();

                    int h = getElement().getParentElement().getClientHeight();

                    getViewport().getHandlerManager().fireEvent(new ResizeEndEvent(w, h));

                    cancel();
                }
            }
        };
    }

    private void addHandlers()
    {
        Window.addResizeHandler(new ResizeHandler()
        {
            @Override
            public void onResize(ResizeEvent event)
            {
                int w = getElement().getParentElement().getClientWidth();

                int h = getElement().getParentElement().getClientHeight();

                setPixelSize(w, h);

                if (!m_resizing)
                {
                    m_resizing = true;

                    getViewport().getHandlerManager().fireEvent(new ResizeStartEvent(w, h));

                    m_resize_timer.scheduleRepeating(m_resize_check_repeat_interval);
                }
                m_resizing = true;

                getViewport().getHandlerManager().fireEvent(new ResizeChangeEvent(w, h));

                Orientation orientation;

                if (w > h)
                {
                    orientation = Orientation.LANDSCAPE;
                }
                else
                {
                    orientation = Orientation.PORTRAIT;
                }
                if (orientation != m_orientation)
                {
                    m_orientation = orientation;

                    getViewport().getHandlerManager().fireEvent(new OrientationChangeEvent(w, h));
                }
                Scheduler.get().scheduleDeferred(new ScheduledCommand()
                {
                    @Override
                    public void execute()
                    {
                        m_view.draw();
                    }
                });
            }
        });
    }
}


text:
using System;
using System.Threading.Tasks;
using Windows.UI.Core;
using Windows.UI.Popups;
using GoG.Shared;
using GoG.Shared.Engine;
using Prism.Windows.Mvvm;

namespace GoG.WinRT.ViewModels
{
    public class BaseViewModel : ViewModelBase
    {
        #region Helpers

        protected static readonly CoreDispatcher Dispatcher;

        static BaseViewModel()
        {
            Dispatcher = CoreWindow.GetForCurrentThread().Dispatcher;
        }

        protected void RunOnUiThread(Action a)
        {
            Dispatcher?.RunAsync(CoreDispatcherPriority.Low, () => a());
        }

        protected static async Task DisplayMessage(string title, string msg)
        {
            var dialog = new MessageDialog(msg, title);
            await dialog.ShowAsync();
        }

        protected static async Task<string> DisplayQuery(string title, string msg, params string[] buttons)
        {
            var dialog = new MessageDialog(msg, title);
            for (var i = 0; i < buttons.Length; i++)
                dialog.Commands.Add(new UICommand(buttons[i], null, i));
            var c = await dialog.ShowAsync();
            return c.Label;
        }

        protected static async Task DisplayErrorCode(GoResultCode code)
        {
            var msg = EngineHelpers.GetResultCodeFriendlyMessage(code);
            await DisplayMessage("Whoops", msg);
        }

        #endregion Helpers
    }
}


text:
package io.gravitee.rest.api.services.dynamicproperties;

import io.gravitee.common.component.Lifecycle;
import io.gravitee.common.event.Event;
import io.gravitee.common.event.EventListener;
import io.gravitee.common.event.EventManager;
import io.gravitee.common.service.AbstractService;
import io.gravitee.definition.model.services.dynamicproperty.DynamicPropertyProvider;
import io.gravitee.definition.model.services.dynamicproperty.DynamicPropertyService;
import io.gravitee.node.api.Node;
import io.gravitee.rest.api.model.api.ApiEntity;
import io.gravitee.rest.api.service.ApiService;
import io.gravitee.rest.api.service.event.ApiEvent;
import io.gravitee.rest.api.services.dynamicproperties.provider.http.HttpProvider;
import io.vertx.core.Vertx;
import java.util.HashMap;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * @author Alexandre FARIA (lusoalex on github.com)
 */
public class DynamicPropertiesService extends AbstractService implements EventListener<ApiEvent, ApiEntity> {

    /**
     * Logger.
     */
    private final Logger logger = LoggerFactory.getLogger(DynamicPropertiesService.class);

    @Autowired
    private EventManager eventManager;

    @Autowired
    private ApiService apiService;

    @Autowired
    private Vertx vertx;

    @Autowired
    private Node node;

    private final Map<ApiEntity, CronHandler> handlers = new HashMap<>();

    @Override
    protected String name() {
        return "Dynamic Properties Service";
    }

    @Override
    protected void doStart() throws Exception {
        super.doStart();

        eventManager.subscribeForEvents(this, ApiEvent.class);
    }

    @Override
    protected void doStop() throws Exception {
        super.doStop();
    }

    @Override
    public void onEvent(Event<ApiEvent, ApiEntity> event) {
        final ApiEntity api = event.content();

        switch (event.type()) {
            case DEPLOY:
                startDynamicProperties(api);
                break;
            case UNDEPLOY:
                stopDynamicProperties(api);
                break;
            case UPDATE:
                stopDynamicProperties(api);
                startDynamicProperties(api);
                break;
        }
    }

    private void startDynamicProperties(ApiEntity api) {
        if (api.getState() == Lifecycle.State.STARTED) {
            DynamicPropertyService dynamicPropertyService = api.getServices().get(DynamicPropertyService.class);
            if (dynamicPropertyService != null && dynamicPropertyService.isEnabled()) {
                DynamicPropertyUpdater updater = new DynamicPropertyUpdater(api);

                if (dynamicPropertyService.getProvider() == DynamicPropertyProvider.HTTP) {
                    HttpProvider provider = new HttpProvider(dynamicPropertyService);
                    provider.setVertx(vertx);
                    provider.setNode(node);

                    updater.setProvider(provider);
                    updater.setApiService(apiService);
                    logger.info("Add a scheduled task to poll dynamic properties each {}", dynamicPropertyService.getSchedule());

                    // Force the first refresh, and then run it periodically
                    updater.handle(null);
                    CronHandler cronHandler = new CronHandler(vertx, dynamicPropertyService.getSchedule());
                    cronHandler.schedule(updater);
                    handlers.put(api, cronHandler);
                }
            } else {
                logger.info("Dynamic properties service is disabled for: {} [{}]", api.getName(), api.getVersion());
            }
        }
    }

    private void stopDynamicProperties(ApiEntity api) {
        CronHandler handler = handlers.remove(api);
        if (handler != null) {
            logger.info("Stop Dynamic properties service for API id[{}] name[{}]", api.getId(), api.getName());
            handler.cancel();
        }
    }
}


text:
'use strict';

var _supertestAsPromised = require('supertest-as-promised');

var _supertestAsPromised2 = _interopRequireDefault(_supertestAsPromised);

var _httpStatus = require('http-status');

var _httpStatus2 = _interopRequireDefault(_httpStatus);

var _jsonwebtoken = require('jsonwebtoken');

var _jsonwebtoken2 = _interopRequireDefault(_jsonwebtoken);

var _chai = require('chai');

var _chai2 = _interopRequireDefault(_chai);

var _index = require('../../index');

var _index2 = _interopRequireDefault(_index);

var _config = require('../../config/config');

var _config2 = _interopRequireDefault(_config);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

_chai2.default.config.includeStack = true;

describe('## Auth APIs', function () {
  var validUserCredentials = {
    username: 'react',
    password: 'express'
  };

  var invalidUserCredentials = {
    username: 'react',
    password: 'IDontKnow'
  };

  var jwtToken = void 0;

  describe('# POST /api/auth/login', function () {
    it('should return Authentication error', function (done) {
      (0, _supertestAsPromised2.default)(_index2.default).post('/api/auth/login').send(invalidUserCredentials).expect(_httpStatus2.default.UNAUTHORIZED).then(function (res) {
        (0, _chai.expect)(res.body.message).to.equal('Authentication error');
        done();
      }).catch(done);
    });

    it('should get valid JWT token', function (done) {
      (0, _supertestAsPromised2.default)(_index2.default).post('/api/auth/login').send(validUserCredentials).expect(_httpStatus2.default.OK).then(function (res) {
        (0, _chai.expect)(res.body).to.have.property('token');
        _jsonwebtoken2.default.verify(res.body.token, _config2.default.jwtSecret, function (err, decoded) {
          (0, _chai.expect)(err).to.not.be.ok; // eslint-disable-line no-unused-expressions
          (0, _chai.expect)(decoded.username).to.equal(validUserCredentials.username);
          jwtToken = 'Bearer ' + res.body.token;
          done();
        });
      }).catch(done);
    });
  });

  describe('# GET /api/auth/random-number', function () {
    it('should fail to get random number because of missing Authorization', function (done) {
      (0, _supertestAsPromised2.default)(_index2.default).get('/api/auth/random-number').expect(_httpStatus2.default.UNAUTHORIZED).then(function (res) {
        (0, _chai.expect)(res.body.message).to.equal('Unauthorized');
        done();
      }).catch(done);
    });

    it('should fail to get random number because of wrong token', function (done) {
      (0, _supertestAsPromised2.default)(_index2.default).get('/api/auth/random-number').set('Authorization', 'Bearer inValidToken').expect(_httpStatus2.default.UNAUTHORIZED).then(function (res) {
        (0, _chai.expect)(res.body.message).to.equal('Unauthorized');
        done();
      }).catch(done);
    });

    it('should get a random number', function (done) {
      (0, _supertestAsPromised2.default)(_index2.default).get('/api/auth/random-number').set('Authorization', jwtToken).expect(_httpStatus2.default.OK).then(function (res) {
        (0, _chai.expect)(res.body.num).to.be.a('number');
        done();
      }).catch(done);
    });
  });
});
//# sourceMappingURL=auth.test.js.map


text:
class Admin::Config::AccountsController < Admin::Config::BaseController
  # GET /accounts
  def index
    @accounts = Account.all
  end

  # GET /accounts/1
  def show
    @account = Account.find(params[:id])
  end

  # GET /accounts/new
  def new
    @account = Account.new
  end

  # GET /accounts/1/edit
  def edit
    @account = Account.find(params[:id])
  end

  # POST /accounts
  def create
    @account = Account.new(params[:account])

    respond_to do |format|
      if @account.save
        format.html { redirect_to(admin_config_accounts_url(), :notice => 'Account was successfully created.') }
      else
        format.html { render :action => "new" }
      end
    end
  end

  # PUT /accounts/1
  def update
    @account = Account.find(params[:id])

    respond_to do |format|
      if @account.update_attributes(params[:account])
        format.html { redirect_to(admin_config_accounts_url(), :notice => 'Account was successfully updated.') }
      else
        format.html { render :action => "edit" }
      end
    end
  end

  # DELETE /accounts/1
  def destroy
    @account = Account.find(params[:id])
    @account.destroy
    redirect_to(admin_config_accounts_url)
  end
end


text:
const Tree = require('functional-red-black-tree')
const Account = require('ethereumjs-account')
const async = require('async')

var Cache = module.exports = function (trie) {
  this._cache = Tree()
  this._checkpoints = []
  this._deletes = []
  this._trie = trie
}

Cache.prototype.put = function (key, val, fromTrie) {
  var modified = !fromTrie
  this._update(key, val, modified, true)
}

// returns the queried account or an empty account
Cache.prototype.get = function (key) {
  var account = this.lookup(key)
  if (!account) {
    account = new Account()
    account.exists = false
  }
  return account
}

// returns the queried account or undefined
Cache.prototype.lookup = function (key) {
  key = key.toString('hex')

  var it = this._cache.find(key)
  if (it.node) {
    var account = new Account(it.value.val)
    account.exists = it.value.exists
    return account
  }
}

Cache.prototype._lookupAccount = function (address, cb) {
  var self = this
  self._trie.get(address, function (err, raw) {
    if (err) return cb(err)
    var account = new Account(raw)
    var exists = !!raw
    account.exists = exists
    cb(null, account, exists)
  })
}

Cache.prototype.getOrLoad = function (key, cb) {
  var self = this
  var account = this.lookup(key)
  if (account) {
    cb(null, account)
  } else {
    self._lookupAccount(key, function (err, account, exists) {
      if (err) return cb(err)
      self._update(key, account, false, exists)
      cb(null, account)
    })
  }
}

Cache.prototype.warm = function (addresses, cb) {
  var self = this
  // shim till async supports iterators
  var accountArr = []
  addresses.forEach(function (val) {
    if (val) accountArr.push(val)
  })

  async.eachSeries(accountArr, function (addressHex, done) {
    var address = new Buffer(addressHex, 'hex')
    self._lookupAccount(address, function (err, account) {
      if (err) return done(err)
      self._update(address, account, false, account.exists)
      done()
    })
  }, cb)
}

Cache.prototype.flush = function (cb) {
  var it = this._cache.begin
  var self = this
  var next = true
  async.whilst(function () {
    return next
  }, function (done) {
    if (it.value.modified) {
      it.value.modified = false
      it.value.val = it.value.val.serialize()
      self._trie.put(new Buffer(it.key, 'hex'), it.value.val, function () {
        next = it.hasNext
        it.next()
        done()
      })
    } else {
      next = it.hasNext
      it.next()
      done()
    }
  }, function () {
    async.eachSeries(self._deletes, function (address, done) {
      self._trie.del(address, done)
    }, function () {
      self._deletes = []
      cb()
    })
  })
}

Cache.prototype.checkpoint = function () {
  this._checkpoints.push(this._cache)
}

Cache.prototype.revert = function () {
  this._cache = this._checkpoints.pop(this._cache)
}

Cache.prototype.commit = function () {
  this._checkpoints.pop()
}

Cache.prototype.clear = function () {
  this._deletes = []
  this._cache = Tree()
}

Cache.prototype.del = function (key) {
  this._deletes.push(key)
  key = key.toString('hex')
  this._cache = this._cache.remove(key)
}

Cache.prototype._update = function (key, val, modified, exists) {
  key = key.toString('hex')
  var it = this._cache.find(key)
  if (it.node) {
    this._cache = it.update({
      val: val,
      modified: modified,
      exists: true
    })
  } else {
    this._cache = this._cache.insert(key, {
      val: val,
      modified: modified,
      exists: exists
    })
  }
}


text:
/*! @file picnic.h
 *  @brief Public API for the Picnic signature scheme.
 *
 *  This file is part of the reference implementation of the Picnic and Fish
 *  signature schemes, described in the paper:
 *
 *  Post-Quantum Zero-Knowledge and Signatures from Symmetric-Key Primitives

 *  Melissa Chase and David Derler and Steven Goldfeder and Claudio Orlandi and
 *  Sebastian Ramacher and Christian Rechberger and Daniel Slamanig and Greg
 *  Zaverucha

 *  Cryptology ePrint Archive: Report 2017/279

 *  http://eprint.iacr.org/2017/279

 *
 *  The code is provided under the MIT license, see LICENSE for
 *  more details.
 *
 */

// Doxygen mainpage:
/** @mainpage
 *
 *  This is a reference implementation of the Picnic and Fish signature
 *  schemes, described in the paper:
 *
 *  Post-Quantum Zero-Knowledge and Signatures from Symmetric-Key Primitives

 *  Melissa Chase and David Derler and Steven Goldfeder and Claudio Orlandi and
 *  Sebastian Ramacher and Christian Rechberger and Daniel Slamanig and Greg
 *  Zaverucha

 *  Cryptology ePrint Archive: Report 2017/279

 *  http://eprint.iacr.org/2017/279

 *
 *  The library API is documented in \ref picnic.h.
 *
 *  Authors: Steven Goldfeder and Greg Zaverucha

 *  May 2017
 */

#ifndef PICNIC_H
#define PICNIC_H

#ifdef __cplusplus
extern "C" {
#endif

#include <stdint.h>
#include <stdlib.h>

/* Maximum lengths in bytes */
#define PICNIC_MAX_PUBLICKEY_SIZE 64            /**< Largest public key size, in bytes */
#define PICNIC_MAX_PRIVATEKEY_SIZE 64           /**< Largest private key size, in bytes */

#define PICNIC_MAX_SIGNATURE_SIZE  195458  //GUANG - largest for 10_38_UR scheme
//#define PICNIC_MAX_SIGNATURE_SIZE  263786       /**< Largest signature size, in bytes */

/** Parameter sets */
typedef enum picnic_params_t {
    PARAMETER_SET_INVALID = 0,
    LowMC_256_256_10_38_UR = 6,         /**< LowMC with Unruh balanced number of s-boxes (10) and rounds (38). */
    PARAMETER_SET_MAX_INDEX = 7
} picnic_params_t;

/** Public key */
typedef struct {
    picnic_params_t params;                                     /**< The parameter set used with this public key. */
    uint8_t pubInput[PICNIC_MAX_PUBLICKEY_SIZE / 2];            /**< The input plaintext block to LowMC. */
    uint8_t ciphertext[PICNIC_MAX_PUBLICKEY_SIZE / 2];          /**< The encryption of pubInput under the private key. */
} picnic_publickey_t;

/** Private key */
typedef struct {
    picnic_params_t params;                             /**< The parameter set used with this private key. */
    uint8_t data[PICNIC_MAX_PRIVATEKEY_SIZE];           /**< The private key data. */
    picnic_publickey_t* pk;                             /**< The corresponding public key.  */
} picnic_privatekey_t;

/**
 * Library initialization.
 * Must be called before calling any of the other functions.
 *
 * Used to initialize OpenSSL and load LowMC constants and precomputed tables.
 * Initialization is specific to a parameter set.
 *
 * @param[in] params The parameter set that will be used.
 * @param[in] path   (optional) a path where pre-computed data is stored. If
 * provided, must contain the trailing slash character(s) ('/' or '\\').
 * @param[in] flags  (optional) If flags is 1, OpenSSL is not initialized. This
 * is useful if the application using picnic.h also uses OpenSSL, and does not
 * want the picnic_init to perform OpenSSL initialization.  If flags is 1,
 * fucntions in picnic.h assume that OpenSSL has been initialized, and that the
 * SHA-256, and AES algorithms are available.
 *
 * @return 0 on success, nonzero for error
 *
 * @see picnic_shutdown()
 */
int picnic_init(picnic_params_t params, const char* path, unsigned int flags);

/**
 * Free resources allocated by picnic_init().
 *
 * @param[in] flags  If flags is 1, the OpenSSL shutdown steps are not
 * performed. This is useful if the application using picnic.h also uses
 * OpenSSL, and does not want picnic_shutdown to shutdown OpenSSL.
 *
 * @see picnic_init()
 */
void picnic_shutdown(unsigned int flags);

/**
 * Get a string representation of the parameter set.
 *
 * @param parameters A parameter set
 *
 * @return A null-terminated string describing the parameter set.
 */
const char* picnic_get_param_name(picnic_params_t parameters);

/* Signature API */

/**
 * Key generation function.
 * Generates a public and private key pair, for the specified parameter set.
 *
 * @param[in]  parameters The parameter set to use when generating a key.
 * @param[out] pk         The new public key.
 * @param[out] sk         The new private key.
 *
 * @return Returns 0 for success, or a nonzero value indicating an error.
 *
 * @see picnic_verify(), picnic_sign()
 */
int picnic_keygen(picnic_params_t parameters, picnic_publickey_t* pk,
                  picnic_privatekey_t* sk);

/**
 * Signature function.
 * Signs a message with the given keypair.
 *
 * @param[in] sk      The signer's private key.
 * @param[in] message The message to be signed.
 * @param[in] message_len The length of the message, in bytes.
 * @param[out] signature A buffer to hold the signature. The required size does
 * not exceed PICNIC_MAX_SIGNATURE_SIZE bytes.  The specific max number of
 * bytes required for a parameter set is given by picnic_signature_size(). Note
 * that the length of each signature varies slightly, for the parameter sets
 * using the FS transform.  The parameter sets using the Unruh transform have a
 * fixed length.
 * @param[in,out] signature_len The length of the provided signature buffer.
 * On success, this is set to the number of bytes written to the signature buffer.
 *
 * @return Returns 0 for success, or a nonzero value indicating an error.
 *
 * @see picnic_verify(), picnic_keygen(), picnic_signature_size()
 */
int picnic_sign(picnic_privatekey_t* sk, const uint8_t* message, size_t message_len,
                uint8_t* signature, size_t* signature_len);

/**
 * Get the number of bytes required to hold a signature.
 *
 * @param[in] parameters The parameter set of the signature.
 *
 * @return The number of bytes required to hold the signature created by
 * picnic_sign
 *
 * @note The size of signatures with parameter sets using the FS transform vary
 *       slightly based on the random choices made during signing.  This function
 *       will return a suffcient number of bytes to hold a signature, and the
 *       picnic_sign() function returns the exact number used for a given signature.
 *
 * @see picnic_sign()
 */
size_t picnic_signature_size(picnic_params_t parameters);

/**
 * Verification function.
 * Verifies a signature is valid with respect to a public key and message.
 *
 * @param[in] pk      The signer's public key.
 * @param[in] message The message the signature purpotedly signs.
 * @param[in] message_len The length of the message, in bytes.
 * @param[in] signature The signature to verify.
 * @param[in] signature_len The length of the signature.
 *
 * @return Returns 0 for success, indicating a valid signature, or a nonzero
 * value indicating an error or an invalid signature.
 *
 * @see picnic_sign(), picnic_keygen()
 */
int picnic_verify(picnic_publickey_t* pk, const uint8_t* message, size_t message_len,
                  const uint8_t* signature, size_t signature_len);

/**
 * Serialize a public key.
 *
 * @param[in]  key The public key to serialize
 * @param[out] buf The buffer to write the key to.
 *                 Must have size at least PICNIC_MAX_PUBLICKEY_SIZE + 1 bytes.
 * @param[in]  buflen The length of buf, in bytes
 *
 * @return Returns the number of bytes written.
 */
int picnic_write_public_key(const picnic_publickey_t* key, uint8_t* buf, size_t buflen);

/**
 * De-serialize a public key.
 *
 * @param[out]  key The public key object to be populated.
 * @param[in] buf The buffer to read the public key from.
 *                 Must be at least PICNIC_MAX_PUBLICKEY_SIZE + 1 bytes.
 * @param[in]  buflen The length of buf, in bytes
 *
 * @return Returns the number of bytes written.
 */
int picnic_read_public_key(picnic_publickey_t* key, const uint8_t* buf, size_t buflen);

/**
 * Serialize a private key.
 *
 * @param[in]  key The private key to serialize
 * @param[out] buf The buffer to write the key to.
 *                 Must have size at least PICNIC_MAX_PRIVATEKEY_SIZE + 1 bytes.
 * @param[in]  buflen The length of buf, in bytes
 *
 * @return Returns the number of bytes written.
 */
int picnic_write_private_key(const picnic_privatekey_t* key, uint8_t* buf, size_t buflen);

/**
 * De-serialize a private key.
 *
 * @param[out]  key The private key object to be populated
 * @param[in] buf The buffer to read the key from.
 *                 Must have size at least PICNIC_MAX_PRIVATEKEY_SIZE + 1 bytes.
 * @param[in]  buflen The length of buf, in bytes
 * @param[in]  publickey The corresponding public key
 *
 * @return Returns 0 on success, or a nonzero value indicating an error.
 */
int picnic_read_private_key(picnic_privatekey_t* key, const uint8_t* buf, size_t buflen, picnic_publickey_t* publickey);

/**
 * Check that a key pair is valid.
 *
 * @param[in] privatekey The private key to check
 * @param[in] publickey The public key to check
 *
 * @return Returns 0 if the key pair is valid, or a nonzero value indicating an error
 */
int picnic_validate_keypair(const picnic_privatekey_t* privatekey, const picnic_publickey_t* publickey);

/**
 * picnic_random_bytes is used to generate random bytes in key generation and
 * signing. See the provided implementation "random_bytes_default_openssl"
 * based on OpenSSL's RAND_bytes.
 *
 * To use another RNG, make sure it has the same behavior as
 * random_bytes_default_openssl, and change the definition of
 * picnic_random_bytes.
 */
#define picnic_random_bytes random_bytes_default_openssl

/*
 * Note signing digests and streaming APIs
 *
 * Sometimes signaure APIs include "sign_digest" and "verify_digest" functions,
 * that allow the caller to hash the message themselves and provide the digest
 * to the sign/verify functions.  Example use cases for these APIs are
 * applications that must sign very large messages, which don't fit in memory,
 * or that must signa long stream data.  Applications that really need this
 * behavior could  provide a digest to the sign/verify APIs provided here.
 * This is discouraged however, because the message will then be hashed twice,
 * the challenge used in the proof will be:
 *    c = H(random, per-signature values || H(M))
 * instead of
 *    c = H(random, per-signature values || M).
 * In the former case, a collision for H immediately gives a forgery (in the
 * GMR security game, but not necessarily in all applications). For this reason
 * the latter case arguably provides better security.
 *
 * A better way to implement a streaming API (not provided by this library)
 * would be to hash the first part of the challenge, then continue hashing the
 * message as a stream, then finish computing the signature.
 *
 */

#ifdef __cplusplus
}
#endif

#endif /*PICNIC_H*/