text:
MixpanelClient
===================

Basic Mixpanel iOS client to export data via the Mixpanel API using your API key and secret.

The code follows the Mixpanel documentation as close as possible, so naming and parameters are exactly as shown.

[Visit API documentation](https://mixpanel.com/docs/api-documentation/data-export-api)

The project includes a Podspec file for [AFNetworking](https://github.com/AFNetworking/AFNetworking), so make sure to run the installation for that library.

### Initialisations

    - (MixpanelClient *)initWithDelegate:(NSObject *)newDelegate;

### Setting authentication details

    - (void)setApiKey:(NSString *)key andSecret:(NSString *)secret;

### Delegates

There are just three methods that by adding `MixpanelClientDelegate` will allow you to use in your controllers. This returns any data that is received from the server:

#### requestSucceededForMethod:(NSString *)method

    - (void)requestSucceededForMethod:(NSString *)method
    {
        NSLog(@"The method %@ was successful.", method);
    }

#### requestFailedWithError:(NSError *)error

    - (void)requestFailedWithError:(NSError *)error
    {
        NSLog(@"An error occurred: %@", [error debugDescription]);
    }

#### @optional receivedData:(id)data

    - (void)receivedData:(id)data
    {
        // Data is either an NSDictionary or an NSArray
        NSLog(@"Data was received: %@", data);
    }

### Events

    /*
    METHOD: events
    URI: http://mixpanel.com/api/2.0/events/
    Parameters:
    'event'        NSArray
    'type'         NSString
    'unit'         NSString
    'interval'     NSInteger
    'format'       NSString
    */

    - (void)events:(NSDictionary *)params;

#### events/top

    /*
    METHOD: events/top
    URI: http://mixpanel.com/api/2.0/events/top/
    Parameters:
    'type'         NSString
    'limit'        NSInteger
    */

    - (void)eventsTop:(NSDictionary *)params;

#### events/names

    /*
    METHOD: events/names
    URI: http://mixpanel.com/api/2.0/events/names/
    Parameters:
    'type'         NSString
    'limit'        NSInteger
    */

    - (void)eventsNames:(NSDictionary *)params;

#### events/properties

    /*
    METHOD: events/properties
    URI: http://mixpanel.com/api/2.0/events/properties/
    Parameters:
    'event'        NSString
    'name'         NSString
    'values'       NSArray
    'type'         NSString
    'unit'         NSString
    'interval'     NSInteger
    'format'       NSString
    'limit'        NSInteger
    */

    - (void)eventsProperties:(NSDictionary *)params;

#### events/properties/top

    /*
    METHOD: events/properties/top
    URI: http://mixpanel.com/api/2.0/events/properties/top/
    Parameters:
    'event'        NSString
    'limit'        NSInteger
    */

    - (void)eventsPropertiesTop:(NSDictionary *)params;

#### events/properties/values

    /*
    METHOD: events/properties/values
    URI: http://mixpanel.com/api/2.0/events/properties/values/
    Parameters:
    'event'        NSString
    'name'         NSString
    'limit'        NSInteger
    'bucket'       NSString
    */

    - (void)eventsPropertiesValues:(NSDictionary *)params;

### Funnels

    /*
    METHOD: funnels
    URI: http://mixpanel.com/api/2.0/funnels/
    Parameters:
    'funnel_id'    NSInteger
    'from_date'    NSString
    'to_date'      NSString
    'length'       NSInteger
    'interval'     NSInteger
    'unit'         NSString
    'on'           NSString
    'where'        NSString
    'limit         NSInteger
    */

    - (void)funnels:(NSDictionary *)params;

#### funnels/list

    /*
    METHOD: funnels/list
    URI: http://mixpanel.com/api/2.0/funnels/list/
    */

    - (void)funnelsList;

### Segmentation

    /*
    METHOD: segmentation
    URI: http://mixpanel.com/api/2.0/segmentation/
    Parameters:
    'event'        NSString
    'from_date'    NSString
    'to_date'      NSString
    'on'           NSString
    'unit'         NSString
    'where'        NSString
    'limit'        NSInteger
    'type'         NSString
    */

    - (void)segmentation:(NSDictionary *)params;

#### segmentation/numeric

    /*
    METHOD: segmentation/numeric
    URI: http://mixpanel.com/api/2.0/segmentation/numeric/
    Parameters:
    'event'        NSString
    'from_date'    NSString
    'to_date'      NSString
    'on'           NSString
    'buckets'      NSInteger
    'unit'         NSString
    'where'        NSString
    'type'         NSString
    */

    - (void)segmentationNumeric:(NSDictionary *)params;

#### segmentation/sum

    /*
    METHOD: segmentation/sum
    URI: http://mixpanel.com/api/2.0/segmentation/sum/
    Parameters:
    'event'        NSString
    'from_date'    NSString
    'to_date'      NSString
    'on'           NSString
    'unit'         NSString
    'where'        NSString
    */

    - (void)segmentationSum:(NSDictionary *)params;

#### segmentation/average

    /*
    METHOD: segmentation/average
    URI: http://mixpanel.com/api/2.0/segmentation/average/
    Parameters:
    'event'        NSString
    'from_date'    NSString
    'to_date'      NSString
    'on'           NSString
    'unit'         NSString
    'where'        NSString
    */

    - (void)segmentationAverage:(NSDictionary *)params;

### Retention

    /*
    METHOD: retention
    URI: http://mixpanel.com/api/2.0/retention/
    Parameters:
    'from_date'        NSString
    'to_date'          NSString
    'retention_type'   NSString
    'born_event'       NSString
    'event'            NSString
    'born_where'       NSString
    'where'            NSString
    'interval'         NSInteger
    'interval_count'   NSInteger
    'unit'             NSString
    'on'               NSString
    'limit'            NSInteger
    */

    - (void)retention:(NSDictionary *)params;

### Engage

    /*
    METHOD: engage
    URI: http://mixpanel.com/api/2.0/engage/
    Parameters:
    'where'        NSString
    'session_id'   NSString
    'page'         NSInteger
    */

    - (void)engage:(NSDictionary *)params;


text:
<?xml version="1.0" encoding="UTF-8"?>
<tei xmlns="http://www.tei-c.org/ns/1.0" xmlns:xlink="http://www.w3.org/1999/xlink" xmlns:mml="http://www.w3.org/1998/Math/MathML">
	<teiHeader>
		<fileDesc>
			<sourceDesc>
				<biblStruct>
					<analytic>
						<author>

						<affiliation>
							<marker>1</marker>
							<orgName type="institution">University of Queensland</orgName>,
							<address>
								<settlement>Brisbane</settlement>,
								<region>Queensland</region>,
								<country>Australia</country>,
							</address>
						</affiliation>
						<affiliation>
							<marker>2</marker>
							<orgName type="department">Healthy Skepticism</orgName>,
							<address>
								<settlement>Willunga</settlement>,
								<region>South Australia</region>,
							</address>
						</affiliation>
						<affiliation>
							<marker>3</marker>
							<orgName type="institution">University of Adelaide</orgName>,
							<address>
								<settlement>Adelaide</settlement>,
								<region>South Australia</region>,
								<country>Australia</country>,
							</address>
						</affiliation>
						<affiliation>
							<marker>4</marker>
							<orgName type="department">School of Primary, Aboriginal and Rural Health Care</orgName>,
							<orgName type="institution">University of Western Australia</orgName>,
							<address>
								<settlement>Perth</settlement>,
								<region>Western Australia</region>,
								<country>Australia</country>,
							</address>
						</affiliation>
						<affiliation>
							<marker>5</marker>
							<orgName type="department">School of Health Policy and Management</orgName>,
							<orgName type="institution">York University</orgName>,
							<address>
								<settlement>Toronto</settlement>,
								<region>Ontario</region>,
								<country>Canada</country>,
							</address>
						</affiliation>
						<affiliation>
							<marker>6</marker>
							<orgName type="department">Faculty of Health Sciences and Medicine</orgName>,
							<orgName type="institution">Bond University</orgName>,
							<address>
								<addrLine>Gold Coast</addrLine>,
								<region>Queensland</region>,
								<country>Australia</country>,
							</address>
						</affiliation>
						<affiliation>
							<marker>7</marker>
							<orgName type="department">Kulliyyah of Pharmacy</orgName>,
							<orgName type="institution">International Islamic University Malaysia</orgName>,
							<address>
								<settlement>Kuantan</settlement>,
								<settlement>Pahang</settlement>,
								<country>Malaysia</country>,
							</address>
						</affiliation>
						<affiliation>
							<marker>8</marker>
							<orgName type="department">Quality Use of Medicines and Pharmacy Research Centre</orgName>,
							<orgName type="institution">Sansom Institute</orgName>,
							<orgName type="department">School of Pharmacy and Medical Sciences</orgName>,
							<orgName type="institution">University of South Australia</orgName>,
							<address>
								<settlement>Adelaide</settlement>,
								<region>South Australia</region>,
								<country>Australia</country>
							</address>
						</affiliation>

						</author>
					</analytic>
				</biblStruct>
			</sourceDesc>
		</fileDesc>
	</teiHeader>
</tei>

redpajama_set_name: RedPajamaGithub


text:
Messages = new Meteor.Collection("messages");
Usernames = new Meteor.Collection("usernames");

if (Meteor.isClient) {

  Template.main.messages = function() {
    return Messages.find();
  };

  Template.main.usernames = function() {
    return Usernames.find();
  };

  Template.main.events({
    'keypress #chatText' : function (e) {
      if(e.which == 13) {
        var message = $('#chatText').val();
        var username = $('#userholder').val();
        var time = new Date();
        time = (time.getHours() < 10 ? '0' : '' ) + time.getHours()+':'+(time.getMinutes() < 10 ? '0':'') + time.getMinutes();

      $('#userholder').attr('readonly','readonly');

      if ( !Usernames.findOne({ name: username}) ){
        Usernames.insert({ name: username });
        console.log('saved');
      }

        Messages.insert({
          username: username,
          message: message,
          time: time
        });

        $('#chatText').val(" ");
        var chat_room = $('#chatLineHolder');
        chat_room.scrollTop( chat_room[0].scrollHeight - chat_room.height() );
      }
    },
  });
}

if (Meteor.isServer) {
  Meteor.startup(function () {
      Messages.remove({});
      Usernames.remove({});
  });

}


text:
/**
 * Module dependencies.
 */

var pencil = require('../../pencil')
  ;

/**
 * Expose.
 *
 * @api public
 */

module.exports = pencil.define('pencil.tag.traversing', {

  /**
   * hasChildren
   *
   * Check if the current tab has child nodes.
   */

  'hasChildren': function () {
    // SHOULD USE THE WALKTHROUGH **************
    return !this.block.isEmpty();
  },

  /**
   * children
   *
   * Get the children of each element in the set of matched elements, optionally filtered by a selector.
   */

  'children': function (repeater) {
    if(!repeater && this.block){

      return this.block.nodes; //pencil.walkThrough(this.block, []);//this.block.nodes;
    }else if(repeater && this.hasChildren()){
      //
      // ***********************
      // USE WALKTHROUGH
      //
      for(var i=0;i<this.block.nodes.length;i++){
        this.block.nodes[i].index = i;
        //this.block.nodes[i].parent = this;

        repeater.call(this, this.block.nodes[i], i, this.block.nodes)
      }
    }

    return this;
  },

  /**
   * closest
   *
   * For each element in the set, get the first element that matches the selector by testing the element itself and traversing up through its ancestors in the DOM tree.
   */

  'closest': function () {

  },

  /**
   * contents
   *
   * Get the children of each element in the set of matched elements, including text and comment nodes.
   */

  'contents': function () {

  },

  /**
   * next
   *
   * Get the immediately following sibling of each element in the set of matched elements. If a selector is provided, it retrieves the next sibling only if it matches that selector.
   */

  'next': function () {

  },

  /**
   * nextAll
   *
   * Get all following siblings of each element in the set of matched elements, optionally filtered by a selector.
   */

  'nextAll': function () {

  },

  /**
   * .nextUntil
   *
   * Get all following siblings of each element up to but not including the element matched by the selector, DOM node, or jQuery object passed.
   */

  'nextUntil': function () {

  },

  /**
   * prev
   *
   * Get the immediately preceding sibling of each element in the set of matched elements, optionally filtered by a selector.
   */

  'prev': function () {

  },

  /**
   * prevAll
   *
   * Get all preceding siblings of each element in the set of matched elements, optionally filtered by a selector.
   */

  'prevAll': function () {

  },

  /**
   * prevUntil
   *
   * Get all preceding siblings of each element up to but not including the element matched by the selector, DOM node, or jQuery object.
   */

  'prevUntil': function () {

  },

  /**
   * siblings
   *
   * Get the siblings of each element in the set of matched elements, optionally filtered by a selector.
  */

  'siblings': function () {

  }

});


text:
package message

import "testing"

func TestMessage(t *testing.T) {
	var expected, actual string

	expected = " * foo"
	actual = NewAnnounceMsg("foo").String()
	if actual != expected {
		t.Errorf("Got: `%s`; Expected: `%s`", actual, expected)
	}

	u := NewUser(SimpleID("foo"))
	expected = "foo: hello"
	actual = NewPublicMsg("hello", u).String()
	if actual != expected {
		t.Errorf("Got: `%s`; Expected: `%s`", actual, expected)
	}

	expected = "** foo sighs."
	actual = NewEmoteMsg("sighs.", u).String()
	if actual != expected {
		t.Errorf("Got: `%s`; Expected: `%s`", actual, expected)
	}

	expected = "-> hello"
	actual = NewSystemMsg("hello", u).String()
	if actual != expected {
		t.Errorf("Got: `%s`; Expected: `%s`", actual, expected)
	}

	expected = "[PM from foo] hello"
	actual = NewPrivateMsg("hello", u, u).String()
	if actual != expected {
		t.Errorf("Got: `%s`; Expected: `%s`", actual, expected)
	}
}

// TODO: Add theme rendering tests


text:
http = require "socket.http"
cjson = require "cjson"
http.USERAGENT = "wordvis comment scraper by /u/Noncomment"
local bots = {}

function scrapeComments(numComments)
	local dataset = {}
	local seen = {}
	local nextId = ""
	local oldcomments, done = 0, false
	while true do
		local res, sts = http.request("http://www.reddit.com/r/all/comments.json?limit=100"..nextId)
		if sts == 200 then
			local children = cjson.decode(res).data.children
			done = false
			for k, v in ipairs(children) do
				if not seen[v.data.id] then seen[v.data.id] = true
				else done = true break end
				if v.data.author ~= "AutoModerator" then
					if not v.data.author:lower():find("bot") then
						table.insert(dataset, v.data.body)
					else
						if not bots[v.data.author] then
							print("Bot found: "..v.data.author)
							bots[v.data.author] = true
						end
					end
				end
			end
			if not (#children == 100) then done = true end
			if not done then nextId = "&after="..tostring(children[#children].data.name)
			else nextId = "" end
			if (#dataset-oldcomments == 100 and done) then error("Not possible to have 100 new unique comments and set off the detector for non unique comment found.", #children) end
			print(string.format("scraped %i new comments", #dataset-oldcomments))
			oldcomments = #dataset
		else print("error status "..sts) end
		print("\n\n\n"..dataset[#dataset])
		if #dataset >= numComments then break end
		socket.sleep(done and 10 or 2)
		print("\n"..(done and "Loading first page." or "Going to next page."))
	end
	return dataset
end

local function test(n)
	start = os.time()
	local dataset = scrapeComments(n)

	seconds = os.difftime(os.time(), start)
	total = 0
	for k, v in ipairs(dataset) do
		total = total + v:len()
	end
	average = total/#dataset

	print(string.format([[%i comments harvested in %i seconds. Or %.3f comments per second.\nAn average of %.2f characters per comment. %i characters total.\n%.3f characters per second. %.3f words per second at 5 characters per word.]],
	#dataset, seconds, #dataset/seconds, average, total, total/seconds, total/seconds/5))
	print("\nBots Found:")
	table.foreach(bots, function(a) print(a) end)
end

--test(500)

--[[14969 comments harvested in 2918 seconds. Or 5.130 comments per second.
An average of 162.85 characters per comment. 2437715 characters total.
835.406 characters per second. 167.081 words per second at 5 characters per word.]]


text:
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:aop="http://www.springframework.org/schema/aop"
    xmlns:tx="http://www.springframework.org/schema/tx"
    xmlns:util="http://www.springframework.org/schema/util"
    xmlns:extension="http://cattle.io/schemas/spring/extension"
    xsi:schemaLocation="http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
        http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.2.xsd
        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd
        http://cattle.io/schemas/spring/extension http://cattle.io/schemas/spring/extension-1.0.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd">

    <bean class="io.cattle.platform.servicediscovery.process.ServiceUpdateActivate" />
    <bean class="io.cattle.platform.servicediscovery.process.ServiceDeactivate" />
    <bean class="io.cattle.platform.servicediscovery.process.ServiceRemove" />
    <bean class="io.cattle.platform.servicediscovery.process.ServiceCreate" />
    <bean class="io.cattle.platform.servicediscovery.process.ServiceUpgrade" />
    <bean class="io.cattle.platform.servicediscovery.process.ServiceCancelupgrade" />

    <bean class="io.cattle.platform.servicediscovery.process.EnvironmentRemove" />

    <bean class="io.cattle.platform.servicediscovery.process.ServiceDiscoveryInstanceRemovePreListener" />
    <bean class="io.cattle.platform.servicediscovery.process.ServiceDiscoveryInstanceStartPostListener" />

    <bean class="io.cattle.platform.servicediscovery.process.ServiceDiscoveryLoadBalancerRemovePostListener" />
    <bean class="io.cattle.platform.servicediscovery.process.ServiceDiscoveryLoadBalancerTargetAddPostListener" />
    <bean class="io.cattle.platform.servicediscovery.process.ServiceDiscoveryLoadBalancerTargetRemovePostListener" />
    <bean class="io.cattle.platform.servicediscovery.process.LoadBalancerServiceActivatePostListener" />
    <bean class="io.cattle.platform.servicediscovery.process.LoadBalancerServiceActivatePreListener" />
    <bean class="io.cattle.platform.servicediscovery.process.LoadBalancerServiceDeactivatePreListener" />

    <bean class="io.cattle.platform.servicediscovery.process.ServicesReconcilePostTrigger" />
    <bean class="io.cattle.platform.servicediscovery.process.ServicesReconcileTrigger" />

    <bean class="io.cattle.platform.servicediscovery.process.ServiceLinkActivateHandler" />
    <bean class="io.cattle.platform.servicediscovery.process.ServiceLinkPreInstanceStateHandler" />

    <bean class="io.cattle.platform.servicediscovery.dao.impl.ServiceConsumeMapDaoImpl" />
    <bean class="io.cattle.platform.servicediscovery.dao.impl.ServiceExposeMapDaoImpl" />
    <bean class="io.cattle.platform.servicediscovery.dao.impl.ServiceDaoImpl" />

    <bean class="io.cattle.platform.servicediscovery.service.impl.ServiceDiscoveryServiceImpl" />
    <bean class="io.cattle.platform.servicediscovery.service.impl.GlobalHostActivateServiceLookup" />
    <bean class="io.cattle.platform.servicediscovery.service.impl.HostServiceLookup" />
    <bean class="io.cattle.platform.servicediscovery.service.impl.InstanceServiceLookup" />

    <bean class="io.cattle.platform.servicediscovery.deployment.impl.DeploymentManagerImpl" />
    <bean class="io.cattle.platform.servicediscovery.deployment.impl.DeploymentUnitInstanceFactoryImpl" />
    <bean class="io.cattle.platform.servicediscovery.deployment.impl.ServiceDeploymentPlannerFactoryImpl" />

    <bean class="io.cattle.platform.allocator.service.AllocatorServiceImpl" />

    <bean class="io.cattle.platform.process.progress.ProcessProgressImpl" />
    <bean class="io.cattle.platform.allocator.dao.impl.AllocatorDaoImpl" />

    <tx:advice id="ServiceMapDaoImplAdvice" transaction-manager="CoreTransactionManager">
        <tx:attributes>
            <tx:method name="createServiceInstance" isolation="READ_COMMITTED" />
            <tx:method name="createServiceLink" isolation="READ_COMMITTED" />
            <tx:method name="createServiceLinks" isolation="READ_COMMITTED" />
        </tx:attributes>
    </tx:advice>

    <aop:config>
        <aop:advisor advice-ref="ServiceMapDaoImplAdvice" pointcut="execution(* io.cattle.platform.servicediscovery.api.dao.ServiceExposeMapDao.*(..))" />
        <aop:advisor advice-ref="ServiceMapDaoImplAdvice" pointcut="execution(* io.cattle.platform.servicediscovery.api.dao.ServiceConsumeMapDao.*(..))" />
    </aop:config>
</beans>


text:
using CPLEX

include(joinpath(Pkg.dir("MathProgBase"),"test","linprog.jl"))
linprogtest(CplexSolver(CPX_PARAM_PREIND=0, CPX_PARAM_LPMETHOD=2))

include(joinpath(Pkg.dir("MathProgBase"),"test","mixintprog.jl"))
mixintprogtest(CplexSolver())

include(joinpath(Pkg.dir("MathProgBase"),"test","quadprog.jl"))
quadprogtest(CplexSolver())
socptest(CplexSolver())

include(joinpath(Pkg.dir("MathProgBase"),"test","linproginterface.jl"))
linprogsolvertest(CplexSolver())

include(joinpath(Pkg.dir("MathProgBase"),"test","conicinterface.jl"))
coniclineartest(CplexSolver())
conicSOCtest(CplexSolver())
conicSOCRotatedtest(CplexSolver())
conicSOCINTtest(CplexSolver())


text:
'''
执行此脚本时 必须在项目目录下 而不是tools 下
此脚本在有数据库表结构更改时使用 使用工具: South
使用方法:

git pull 之前

   python tools/south_migrate.py init app1,app2,app3

git pull 之后

   python tools/south_migrate.py auto app1,app2,app3

'''

import os
import sys
import subprocess

from os.path import realpath, dirname
from os.path import join as path_join
import shutil
sys.path.insert(
    0,
    realpath(path_join(dirname(__file__), '../'))
)

os.environ['DJANGO_SETTINGS_MODULE'] = 'django-scaffold.settings'

from django.db import connection
from django.conf import settings

def get_args(argvs):
    '''
        获取输入参数
        返回:
            操作action => init auto, truncate
            有变更的app => [app1, app2, app3]
    '''

    try:
        action = argvs[1]
        apps = [i.strip() for i in argvs[2].split(',') if i.strip()]
    except Exception:
        print 'ERROR: action and apps is needed!'
        exit()

    if action not in ('init', 'auto', 'truncate'):
        print 'ERROR: action must in (init, auto, truncate)'
        exit()

    not_in = False
    installed_apps = settings.INSTALLED_APPS
    for app in apps:
        if app not in installed_apps:
            not_in = True
            print 'ERROR: App %s is not exist !' % app

    if not_in:
        exit()

    return action, apps

def delete_south_migrationhistory():
    '''清空 south 之前的数据'''

    cursor = connection.cursor()
    count = cursor.execute('select * from south_migrationhistory')
    if count:
        print 'south_migrationhistory: ', count
        cursor.execute('delete from south_migrationhistory')

def delete_migrations_dir(apps):
    '''删除生成的 migrations 临时目录'''

    for app in apps:
        migrations = '%s/migrations' % app
        if os.path.exists(migrations):
            if os.path.exists('/tmp/migrations'):
                shutil.rmtree('/tmp/migrations')
            commond = 'mv %s/ /tmp/' % migrations
            print commond
            subprocess.check_output(commond.split(' '))

def init_migrate(apps):
    '''
        South 初始化 操作
    '''

    print 'Init START ...\n'

    delete_south_migrationhistory()
    for app in apps:
        commond = 'python manage.py schemamigration %s --initial' % app
        print commond
        print subprocess.check_output(commond.split(' ')), '\n'

        commond = 'python manage.py migrate %s 0001 --fake' % app
        print commond
        print subprocess.check_output(commond.split(' ')), '\n'

    print 'Init OK\n'

def auto_migrate(apps):

    print 'Auto START ...\n'

    for app in apps:
        commond = 'python manage.py schemamigration %s --auto' % app
        print commond
        print subprocess.check_output(commond.split(' ')), '\n'

        commond = 'python manage.py migrate %s' % app
        print commond
        print subprocess.check_output(commond.split(' ')), '\n'

    delete_south_migrationhistory()
    delete_migrations_dir(apps)

    print 'Auto OK\n'

def truncate(apps):
    print 'Truncate STAT ...\n'

    delete_south_migrationhistory()
    delete_migrations_dir(apps)

    print 'Truncate OK\n'

if __name__ == '__main__':

    action, apps = get_args(sys.argv)
    if action == 'init':
        init_migrate(apps)
    elif action == 'auto':
        auto_migrate(apps)
    elif action == 'truncate':
        truncate(apps)
    else:
        print 'No action'


text:
namespace Zu.ChromeDevTools.Overlay
{
    using Newtonsoft.Json;
    using Newtonsoft.Json.Converters;
    using System.Runtime.Serialization;

    /// <summary>
    ///
    /// </summary>
    [JsonConverter(typeof(StringEnumConverter))]
    public enum ContrastAlgorithm
    {
        [EnumMember(Value = "aa")]
        Aa,
        [EnumMember(Value = "aaa")]
        Aaa,
        [EnumMember(Value = "apca")]
        Apca,
    }
}


text:
<?php

namespace Google\AdsApi\Examples\AdWords\v201705\CampaignManagement;

require '../../../../vendor/autoload.php';

use Google\AdsApi\AdWords\AdWordsServices;
use Google\AdsApi\AdWords\AdWordsSession;
use Google\AdsApi\AdWords\AdWordsSessionBuilder;
use Google\AdsApi\AdWords\v201705\cm\CampaignCriterion;
use Google\AdsApi\AdWords\v201705\cm\CampaignCriterionOperation;
use Google\AdsApi\AdWords\v201705\cm\CampaignCriterionService;
use Google\AdsApi\AdWords\v201705\cm\Operator;
use Google\AdsApi\AdWords\v201705\cm\Platform;
use Google\AdsApi\Common\OAuth2TokenBuilder;

/**
 * This example sets a bid modifier on a campaign.
 */
class SetBidModifier {

  const CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE';
  // Bid modifiers are float number, not percentages, e.g., 1.5 means 50% more
  // bidding.
  const BID_MODIFIER = 'INSERT_BID_MODIFIER_HERE';

  public static function runExample(AdWordsServices $adWordsServices,
      AdWordsSession $session, $campaignId, $bidModifier) {
    $campaignCriterionService =
        $adWordsServices->get($session, CampaignCriterionService::class);

    // Create a mobile platform. The ID can be found in the documentation.
    // https://developers.google.com/adwords/api/docs/appendix/platforms
    $mobile = new Platform();
    $mobile->setId(30001); // HighEndMobile = 30001

    // Create a criterion with modified bid.
    $criterion = new CampaignCriterion();
    $criterion->setCampaignId($campaignId);
    $criterion->setCriterion($mobile);
    $criterion->setBidModifier($bidModifier);

    // Create a campaign criterion operation and add it to the operations list.
    $operation = new CampaignCriterionOperation();
    $operation->setOperator(Operator::SET);
    $operation->setOperand($criterion);
    $operations = [$operation];

    // Update campaign criteria on the server.
    $results = $campaignCriterionService->mutate($operations);

    // Print out some information about the updated campaign criterion.
    foreach ($results->getValue() as $campaignCriterion) {
      printf(
          "Campaign criterion with campaign ID %d, criterion ID %d, "
              . "and type '%s' was modified with bid %.2f.\n",
          $campaignCriterion->getCampaignId(),
          $campaignCriterion->getCriterion()->getId(),
          $campaignCriterion->getCriterion()->getType(),
          $campaignCriterion->getBidModifier());
    }
  }

  public static function main() {
    // Generate a refreshable OAuth2 credential for authentication.
    $oAuth2Credential = (new OAuth2TokenBuilder())
        ->fromFile()
        ->build();

    // Construct an API session configured from a properties file and the OAuth2
    // credentials above.
    $session = (new AdWordsSessionBuilder())
        ->fromFile()
        ->withOAuth2Credential($oAuth2Credential)
        ->build();
    self::runExample(new AdWordsServices(), $session, intval(self::CAMPAIGN_ID),
        floatval(self::BID_MODIFIER));
  }
}

SetBidModifier::main();


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

  /**
   * View that abstracts away the browser's DOM completely.
   * It has two simple entry points:
   *
   *   - bind(eventName, handler)
   *     Takes a todo application event and registers the handler
   *   - render(command, parameterObject)
   *     Renders the given command with the options
   */
  function View(template) {
    this.template = template;
  }

  View.prototype._drawPostData = function (parameter) {
    $('#post_container').append(this.template.showPost(parameter))
  };

  View.prototype._drawPostInfoData = function (parameter) {
    $('#post_info_container').append(this.template.showPostInfo(parameter))
  };

  View.prototype._drawCommentData = function (parameter) {
    $('#comment_list_container').append(this.template.showComment(parameter))
  };

  View.prototype.render = function (viewCmd, parameter) {
    var self = this;
    var viewCommands = {
      redraw: function () {
        self._drawPostData(parameter);
        self._drawPostInfoData(parameter);
        self._drawCommentData(parameter.comments);
      }
    };

    viewCommands[viewCmd]();
  };

  View.prototype.bind = function (event, handler) {
    var self = this;
    var pid = $('#post_container').data('id');
    if (event === 'votePost') {
      $('.post-like-label').unbind('click').click(function () {
        if ($(this).hasClass('active') || $('.post-dislike-label').hasClass('active')) {
          return alert("이미 투표한 글입니다.");
        }
        $(this).addClass('active');
        handler({ pid: pid, voteType: 'up' });
      });

      $('.post-dislike-label').unbind('click').click(function () {
        if ($(this).hasClass('active') || $('.post-like-label').hasClass('active')) {
          return alert("이미 투표한 글입니다.");
        }
        $(this).addClass('active');
        handler({ pid: pid, voteType: 'down' });
      });
    }

    if (event === 'voteComment') {
      $('.comment-like-btn').unbind('click').click(function () {
        if ($(this).hasClass('active')) {
          return alert("이미 투표한 댓글입니다.");
        }
        handler({ cid: $(this).parents('.comment-item').data('id') });
      });
    }

    if (event === 'writeComment') {
      $('#comment_write_btn').unbind('click').click(function () {
        handler({ text: $('#comment_write_input').val(), pid: pid });
      });
    }
  };

  // Export to window
  window.app = window.app || {};
  window.app.View = View;
} (window));


text:
from django.conf.urls import patterns, url
from .views import PDFDownloadView

urlpatterns = patterns('',  # noqa
    url(r'^download/$', PDFDownloadView.as_view(), name='download'),
)


text:
<!DOCTYPE html>
        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=Edge">
        <meta name="description">
        <meta name="keywords" content="static content generator,static site generator,static site,HTML,web development,.NET,C#,Razor,Markdown,YAML">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <link rel="shortcut icon" href="/KVLite/assets/img/favicon.ico" type="image/x-icon">
        <link rel="icon" href="/KVLite/assets/img/favicon.ico" type="image/x-icon">
        <title>PommaLabs.KVLite - API - ICache<TSettings> Interface</title>
        <link href="/KVLite/assets/css/mermaid.css" rel="stylesheet">
        <link href="/KVLite/assets/css/highlight.css" rel="stylesheet">
        <link href="/KVLite/assets/css/bootstrap/bootstrap.css" rel="stylesheet">
        <link href="/KVLite/assets/css/adminlte/AdminLTE.css" rel="stylesheet">
        <link href="/KVLite/assets/css/theme/theme.css" rel="stylesheet">
        <link href="//fonts.googleapis.com/css?family=Roboto+Mono:400,700|Roboto:400,400i,700,700i" rel="stylesheet">
        <link href="/KVLite/assets/css/font-awesome.min.css" rel="stylesheet" type="text/css">
        <link href="/KVLite/assets/css/override.css" rel="stylesheet">

                            PommaLabs.KVLite

                            Toggle side menu

                        <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar-collapse">
                            Toggle side menu

                        </button>

About This Project

Docs

Blog

API

On This Page

Summary

Syntax

Type Parameters

Properties

Extension Methods

            <input type="text" name="search" id="search" class="form-control" placeholder="Search Types...">

                <button class="btn btn-flat"></button>

Namespace

PommaLabs<wbr>.KVLite

Interface Types

IAsyncCache<wbr><TSettings><wbr>

IAsyncCache

IAsyncCacheSettings

ICache<wbr><TSettings><wbr>

ICache

ICacheItem<wbr><TVal><wbr>

ICacheSettings

IEssentialCache

I<wbr>Essential<wbr>Cache<wbr>Settings

Class Types

AbstractCache<wbr><TCache, <wbr>TSettings><wbr>

Abstract<wbr>Cache<wbr>Settings<wbr><TSettings><wbr>

AsyncCacheExtensions

CacheExtensions

CacheItem<wbr><TVal><wbr>

Struct Types

CacheKey

CacheResult<wbr><T><wbr>

Enum Types

CacheReadMode

ICache<wbr><TSettings><wbr> Interface

Summary

      A cache with specifically typed settings.

Namespace

PommaLabs<wbr>.KVLite

Interfaces

ICache

IEssentialCache

IDisposable

Implementing Types

PersistentCache

PostgreSqlCache

SqlServerCache

AbstractCache<wbr><TCache, <wbr>TSettings><wbr>

MySqlCache

OracleCache

MemoryCache

DbCache<wbr><TCache, <wbr>TSettings, <wbr>TConnectionFactory, <wbr>TConnection, <wbr>TCommand><wbr>

NoOpCache

VolatileCache

							graph TD
	Interface0["ICache"]-.->Type
	click Interface0 "/KVLite/api/PommaLabs.KVLite/ICache"
	Interface1["IEssentialCache"]-.->Type
	click Interface1 "/KVLite/api/PommaLabs.KVLite/IEssentialCache"
	Interface2["IDisposable"]-.->Type
	Type["ICache<TSettings>"]
class Type type-node
	Type-.->Implementing0["PersistentCache"]
	click Implementing0 "/KVLite/api/PommaLabs.KVLite.SQLite/PersistentCache"
	Type-.->Implementing1["PostgreSqlCache"]
	click Implementing1 "/KVLite/api/PommaLabs.KVLite.PostgreSql/PostgreSqlCache"
	Type-.->Implementing2["SqlServerCache"]
	click Implementing2 "/KVLite/api/PommaLabs.KVLite.SqlServer/SqlServerCache"
	Type-.->Implementing3["AbstractCache<TCache, TSettings>"]
	click Implementing3 "/KVLite/api/PommaLabs.KVLite/AbstractCache_2"
	Type-.->Implementing4["MySqlCache"]
	click Implementing4 "/KVLite/api/PommaLabs.KVLite.MySql/MySqlCache"
	Type-.->Implementing5["OracleCache"]
	click Implementing5 "/KVLite/api/PommaLabs.KVLite.Oracle/OracleCache"
	Type-.->Implementing6["MemoryCache"]
	click Implementing6 "/KVLite/api/PommaLabs.KVLite.Memory/MemoryCache"
	Type-.->Implementing7["DbCache<TCache, TSettings, TConnectionFactory, TConnection, TCommand>"]
	click Implementing7 "/KVLite/api/PommaLabs.KVLite.Database/DbCache_5"
	Type-.->Implementing8["NoOpCache"]
	click Implementing8 "/KVLite/api/PommaLabs.KVLite.NoOp/NoOpCache"
	Type-.->Implementing9["VolatileCache"]
	click Implementing9 "/KVLite/api/PommaLabs.KVLite.SQLite/VolatileCache"

Syntax

public interface ICache<out TSettings> : ICache, IEssentialCache, IDisposable
    where TSettings : ICacheSettings

Type Parameters

						Name
						Description

						TSettings
						The type of the cache settings.

Properties

								Name
								Value
								Summary

								Settings
								TSettings

      The settings available for the cache.

Extension Methods

								Name
								Value
								Summary

								AddSliding<wbr><TVal><wbr><wbr>(string, <wbr>TVal, <wbr>TimeSpan, <wbr>IList<wbr><string><wbr>)<wbr>
								void

      Adds a "sliding" value with given key and default partition. Value will last as much as
      specified in given interval and, if accessed before expiry, its lifetime will be
      extended by the interval itself.

From CacheExtensions

								AddStatic<wbr><TVal><wbr><wbr>(string, <wbr>TVal, <wbr>IList<wbr><string><wbr>)<wbr>
								void

      Adds a "static" value with given key and default partition. Value will last as much as
      specified in StaticInterval and, if accessed
      before expiry, its lifetime will be extended by that interval.

From CacheExtensions

								AddTimed<wbr><TVal><wbr><wbr>(string, <wbr>TVal, <wbr>DateTimeOffset, <wbr>IList<wbr><string><wbr>)<wbr>
								void

      Adds a "timed" value with given key and default partition. Value will last until the
      specified time and, if accessed before expiry, its lifetime will _not_ be extended.

From CacheExtensions

								AddTimed<wbr><TVal><wbr><wbr>(string, <wbr>TVal, <wbr>TimeSpan, <wbr>IList<wbr><string><wbr>)<wbr>
								void

      Adds a "timed" value with given key and default partition. Value will last for the
      specified lifetime and, if accessed before expiry, its lifetime will _not_ be extended.

From CacheExtensions

								Contains<wbr>(string)<wbr>
								bool

      Determines whether this cache contains the specified key in the default partition.

From CacheExtensions

								Get<wbr><TVal><wbr><wbr>(string)<wbr>
								CacheResult<wbr><T><wbr>

      Gets the value with default partition and specified key. If it is a "sliding" or
      "static" value, its lifetime will be increased by corresponding interval.

From CacheExtensions

								GetItem<wbr><TVal><wbr><wbr>(string)<wbr>
								CacheResult<wbr><T><wbr>

      Gets the cache item with default partition and specified key. If it is a "sliding" or
      "static" value, its lifetime will be increased by corresponding interval.

From CacheExtensions

								GetOrAddSliding<wbr><TVal><wbr><wbr>(string, <wbr>Func<wbr><TVal><wbr>, <wbr>TimeSpan, <wbr>IList<wbr><string><wbr>)<wbr>
								TVal

       At first, it tries to get the cache item with default partition and specified key. If
       it is a "sliding" or "static" value, its lifetime will be increased by corresponding interval.

       If the value is not found, then it adds a "sliding" value with given key and default
       partition. Value will last as much as specified in given interval and, if accessed
       before expiry, its lifetime will be extended by the interval itself.

From CacheExtensions

								GetOrAddStatic<wbr><TVal><wbr><wbr>(string, <wbr>Func<wbr><TVal><wbr>, <wbr>IList<wbr><string><wbr>)<wbr>
								TVal

       At first, it tries to get the cache item with default partition and specified key. If
       it is a "sliding" or "static" value, its lifetime will be increased by corresponding interval.

       If the value is not found, then it adds a "static" value with given key and default
       partition. Value will last as much as specified in
       StaticInterval and, if accessed before expiry,
       its lifetime will be extended by that interval.

From CacheExtensions

								GetOrAddTimed<wbr><TVal><wbr><wbr>(string, <wbr>Func<wbr><TVal><wbr>, <wbr>DateTimeOffset, <wbr>IList<wbr><string><wbr>)<wbr>
								TVal

       At first, it tries to get the cache item with default partition and specified key. If
       it is a "sliding" or "static" value, its lifetime will be increased by corresponding interval.

       If the value is not found, then it adds a "timed" value with given key and default
       partition. Value will last until the specified time and, if accessed before expiry, its
       lifetime will _not_ be extended.

From CacheExtensions

								GetOrAddTimed<wbr><TVal><wbr><wbr>(string, <wbr>Func<wbr><TVal><wbr>, <wbr>TimeSpan, <wbr>IList<wbr><string><wbr>)<wbr>
								TVal

       At first, it tries to get the cache item with default partition and specified key. If
       it is a "sliding" or "static" value, its lifetime will be increased by corresponding interval.

       If the value is not found, then it adds a "timed" value with given key and default
       partition. Value will last for the specified lifetime and, if accessed before expiry,
       its lifetime will _not_ be extended.

From CacheExtensions

								Peek<wbr><TVal><wbr><wbr>(string)<wbr>
								CacheResult<wbr><T><wbr>

      Gets the value corresponding to default partition and given key, without updating
      expiry date.

From CacheExtensions

								PeekItem<wbr><TVal><wbr><wbr>(string)<wbr>
								CacheResult<wbr><T><wbr>

      Gets the item corresponding to default partition and given key, without updating expiry date.

From CacheExtensions

								Remove<wbr>(string)<wbr>
								void

      Removes the item with specified key from default partition.

From CacheExtensions

                Generated by Wyam


text:
Feathers authentication has had a major overhaul in order to bring some much needed functionality, customization, and scalability going forward while also making it less complex. It is now simply an adapter over top of [Passport](http://passportjs.org/).

After usage by ourselves and others we realized that there were some limitations in the previous architecture. These new changes allow for some pretty awesome functionality and flexibility that are outlined in [New 1.0 Features](./new-1.0-features.md).

We've also decoupled the authentication strategies and permissions from the core authentication. While many apps need these, not **every** app does. This has also allowed us to better test each piece in isolation.

They are now located here:

- [feathers-authentication-client](https://github.com/feathersjs/feathers-authentication-client)
- [feathers-authentication-local](https://github.com/feathersjs/feathers-authentication-local)
- [feathers-authentication-jwt](https://github.com/feathersjs/feathers-authentication-jwt)
- [feathers-authentication-oauth1](https://github.com/feathersjs/feathers-authentication-oauth1)
- [feathers-authentication-oauth2](https://github.com/feathersjs/feathers-authentication-oauth2)
- [feathers-authentication-hooks](https://github.com/feathersjs/feathers-authentication-hooks)
- [feathers-permissions](https://github.com/feathersjs/feathers-permissions) **(experimental)**

For most of you, migrating your app should be fairly straight forward as there are only a couple breaking changes to the public interface.

---

# Breaking Changes

## Setting up authentication on the server

**The Old Way (< v0.8.0)**

```js
// feathers-authentication < v0.8.0

// In your config files
{
  "auth": {
    "token": {
      "secret": "xxxx"
    },
    "local": {},
    "facebook": {
      "clientID": "<your client id>",
      "clientSecret": "<your client secret>",
      "permissions": {
        "scope": ["public_profile","email"]
      }
    }
  }
}

// In your authentication service
const authentication = require('feathers-authentication');
const FacebookStrategy = require('passport-facebook').Strategy;

let config = app.get('authentication');
config.facebook.strategy = FacebookStrategy;
app.configure(authentication(config))
    .use('/users', memory()) // this use to be okay to be anywhere
```

**The New Way**

```js
// feathers-authentication >= v1.0.0

// In your config files
{
  "auth": {
    "secret": "xxxx"
    "facebook": {
      "clientID": "<your client id>",
      "clientSecret": "<your client secret>",
      "scope": ["public_profile","email"]
    }
  }
}

// In your app or authentication service, wherever you would like
const auth = require('feathers-authentication');
const local = require('feathers-authentication-local');
const jwt = require('feathers-authentication-jwt');
const oauth1 = require('feathers-authentication-oauth1');
const oauth2 = require('feathers-authentication-oauth2');
const FacebookStrategy = require('passport-facebook').Strategy;

// The services you are setting the `entity` param for need to be registered before authentication
app.configure(auth(app.get('authentication')))
    .configure(jwt())
    .configure(local())
    .configure(oauth1())
    .configure(oauth2({
      name: 'facebook', // if the name differs from your config key you need to pass your config options explicitly
      Strategy: FacebookStrategy
    }))
    .use('/users', memory());

// Authenticate the user using the a JWT or
// email/password strategy and if successful
// return a new JWT access token.
app.service('authentication').hooks({
  before: {
    create: [
      auth.hooks.authenticate(['jwt', 'local'])
    ]
  }
});
```

### Config Options

There are a number of breaking changes since the services have been removed:

- Change `auth.token` -> `auth.jwt` in your config
- Move `auth.token.secret` -> `auth.secret`
- `auth.token.payload` option has been removed. See [customizing JWT payload](#customizing-jwt-payload) for how to do this.
- `auth.idField` has been removed. It is now included in all services so we can pull it internally without you needing to specify it.
- `auth.shouldSetupSuccessRoute` has been removed. Success redirect middleware is registered automatically but only triggers if you explicitly set a redirect. [See redirecting]() for more details.
- `auth.shouldSetupFailureRoute` has been removed. Failure redirect middleware is registered automatically but only triggers if you explicitly set a redirect. [See redirecting]() for more details.
- `auth.tokenEndpoint` has been removed. There isn't a token service anymore.
- `auth.localEndpoint` has been removed. There isn't a local service anymore. It is a passport plugin and has turned into `feathers-authentication-local`.
- `auth.userEndpoint` has been removed. It is now part of `feathers-authentication-local` and is `auth.local.service`.
- Cookies are now disabled by default. If you need cookie support (ie. OAuth, Server Side Rendering, Redirection) then you need to explicitly enable it by setting `auth.cookie.enabled = true`.
- When setting up an OAuth strategy it used to be `strategy: FacebookStrategy` and is now capitalized `Strategy: FacebookStrategy`.
- Any passport strategy options are flattened. So previously you would have had this in your config:

  ```json
  {
    "auth": {
      "facebook": {
        "clientID": "<your client id>",
        "clientSecret": "<your client secret>",
        "permissions": {
          "scope": ["public_profile","email"]
        }
      }
    }
  }
  ```

  and now you have:

  ```json
  {
    "auth": {
      "facebook": {
        "clientID": "<your client id>",
        "clientSecret": "<your client secret>",
        "scope": ["public_profile","email"]
      }
    }
  }
  ```

## Setting up authentication on the client

Authenticating through the Feathers client is almost exactly the same with just a few keys changes:

- `type` is now `strategy` when calling `authenticate()` and must be an exact name match of one of your strategies registered server side.
- You must fetch your user explicitly (typically after authentication succeeds)
- You require `feathers-authentication-client` instead of `feathers-authentication/client`

You can use `feathers-authentication-compatibility` on the server to keep the old client functional, this helps to migrate large scale deployments where you can not update all clients/api consumers before migrating to `>=1.0.0` Check https://www.npmjs.com/package/feathers-authentication-compatibility for more information.

**The Old Way (< v0.8.0)**

```js
// feathers-authentication < v0.8.0
const auth = require('feathers-authentication/client');
app.configure(auth());

app.authenticate({
  type: 'local',
  email: 'admin@feathersjs.com',
  password: 'admin'
}).then(function(result){
  console.log('Authenticated!', result);
}).catch(function(error){
  console.error('Error authenticating!', error);
});
```

**The New Way (with `feathers-authentication-client`)**

```js
// feathers-authentication-client >= v1.0.0
const auth = require('feathers-authentication-client');
app.configure(auth(config));

app.authenticate({
  strategy: 'local',
  email: 'admin@feathersjs.com',
  password: 'admin'
})
.then(response => {
  console.log('Authenticated!', response);
  // By this point your accessToken has been stored in
  // localstorage
  return app.passport.verifyJWT(response.accessToken);
})
.then(payload => {
  console.log('JWT Payload', payload);
  return app.service('users').get(payload.userId);
})
.then(user => {
  app.set('user', user);
  console.log('User', app.get('user'));
  // Do whatever you want now
})
.catch(function(error){
  console.error('Error authenticating!', error);
});
```

### Config Options

- `localEndpoint` has been removed. There is just one endpoint called `service` which defaults to `/authentication`.
- `tokenEndpoint` has been removed. There is just one endpoint called `service` which defaults to `/authentication`.
- `tokenKey` -> `accessTokenKey`

## Response to `app.authenticate()` does not return `user`

We previously made the poor assumption that you are always authenticating a user. This is not always the case, or your app may not care about the current user as you already have their id in the accessToken payload or can encode some additional details in the JWT accessToken.  Therefore, if you need to get the current user you need to request it explicitly after authentication or populate it yourself in an after hook server side. See the new usage above for how to fetch your user.

## Customizing JWT Payload

By default the payload for your JWT is simply your entity id (ie. `{ userId }`). However, you can customize your JWT payloads however you wish by adding a `before` hook to the authentication service. For example:

```js
// This hook customizes your payload.
function customizeJWTPayload() {
  return function(hook) {
    console.log('Customizing JWT Payload');
    hook.params.payload = {
      // You need to make sure you have the right id.
      // You can put whatever you want to be encoded in
      // the JWT access token.
      customId: hook.params.user.id
    };

    return Promise.resolve(hook);
  };
}

// Authenticate the user using the a JWT or
// email/password strategy and if successful
// return a new JWT access token.
app.service('authentication').hooks({
  before: {
    create: [
      auth.hooks.authenticate(['jwt', 'local']),
      customizeJWTPayload()
    ]
  }
});
```

## JWT Parsing

The JWT is only parsed from the header and body by default now. It is no longer pulled from the query string unless you explicitly tell `feathers-authentication-jwt` to do so.

You can customize the header and body keys like so:

```js
app.configure(authentication({
  header: 'custom',
  bodyKey: 'custom'
}));
```

If you want to customize things further you can refer to the [`feathers-authentication-jwt`](https://github.com/feathersjs/feathers-authentication-jwt) module or implement your own custom passport JWT strategy.

## Hook Changes

### Hooks always return promises

This shouldn't really affect you unless you are testing, modifying or wrapping existing hooks but they **always** return promises now. This makes the interface more consistent, making it easier to test and reason as to what a hook does.

### Added Hooks

`auth.hooks.authenticate([...strategies])`: This hook takes the place of the `verifyToken` and `populateUser` hooks.

For the JWT strategy, this hook has different behavior from the old hooks: it will return a `401 Unauthorized` error if no JWT is present in the request. Include an anonymous JWT (a JWT with no associated user) to prevent a `401` response. Anonymous JWT's can created through by externally calling the `create` endpoint of the authentication service. Internally, they can be created through `app.service('authentication').create({})`.

### Removed Hooks

We have removed all of the old authentication hooks. If you still need these they have been moved to the [feathers-authentication-hooks](https://github.com/feathersjs/feathers-authentication-hooks) repo and some of them have been deprecated.

The following hooks have been removed:

- `verifyOrRestrict` -> use new `feathers-permissions` plugin
- `populateOrRestrict` -> use new `feathers-permissions` plugin
- `hashPassword` -> has been moved to `feathers-authentication-local` **This is important.**
- `populateUser` -> use new `populate` hook in `feathers-hooks-common`
- `verifyToken` -> use new `feathers-authentication-jwt` plugin to easily validate a JWT access token. You can also now call `app.passport.verifyJWT` anywhere in your app to do it explicitly.

**The Old Way (< v0.8.0)**

Typically you saw a lot of this in your hook definitions for a service:

```js
// feathers-authentication < v0.8.0
// Users service
const auth = require('feathers-authentication').hooks;
exports.before = {
  all: [],
  find: [
    auth.verifyToken(),
    auth.populateUser(),
    auth.restrictToAuthenticated(),
    auth.queryWithCurrentUser()
  ],
  get: [
    auth.verifyToken(),
    auth.populateUser(),
    auth.restrictToAuthenticated(),
    auth.restrictToOwner({ ownerField: '_id' })
  ],
  create: [
    auth.hashPassword()
  ],
  update: [
    auth.verifyToken(),
    auth.populateUser(),
    auth.restrictToAuthenticated(),
    auth.hashPassword()
  ],
  patch: [
    auth.verifyToken(),
    auth.populateUser(),
    auth.restrictToAuthenticated(),
    auth.hashPassword()
  ],
}
```

**The New Way**

```js
// feathers-authentication >= v1.0.0
const auth = require('feathers-authentication');
const local = require('feathers-authentication-local');
const {
  queryWithCurrentUser,
  restrictToOwner
} = require('feathers-authentication-hooks');

exports.before = {
  all: [],
  find: [
    auth.hooks.authenticate('jwt'),
    queryWithCurrentUser()
  ],
  get: [
    auth.hooks.authenticate('jwt'),
    restrictToOwner({ ownerField: '_id' })
  ],
  create: [
    local.hooks.hashPassword()
  ],
  update: [
    auth.hooks.authenticate('jwt'),
    restrictToOwner({ ownerField: '_id' }),
    local.hooks.hashPassword()
  ],
  patch: [
    auth.hooks.authenticate('jwt'),
    restrictToOwner({ ownerField: '_id' }),
    local.hooks.hashPassword()
  ],
}
```


text:
using System;
using EventStore.ClientAPI;

namespace Soloco.EventStore.Core.Infrastructure
{
    public class KnownEvent
    {
        public ConsoleColor Color { get; private set; }

        public KnownEvent(ConsoleColor color)
        {
            Color = color;
        }

        public virtual object Parse()
        {
            return null;
        }
    }

    public class KnownEvent<TEvent> : KnownEvent
    {
        private readonly RecordedEvent _recordedEvent;

        public KnownEvent(ConsoleColor color, RecordedEvent recordedEvent)
            : base(color)
        {
            if (recordedEvent == null) throw new ArgumentNullException("recordedEvent");

            _recordedEvent = recordedEvent;
        }

        public override object Parse()
        {
            return _recordedEvent.ParseJson<TEvent>().AsJsonString();
        }
    }
}


text:
/* start node id of a node block dedicated to the given node id */
#define	START_NID(nid) ((nid / NAT_ENTRY_PER_BLOCK) * NAT_ENTRY_PER_BLOCK)

/* node block offset on the NAT area dedicated to the given start node id */
#define	NAT_BLOCK_OFFSET(start_nid) (start_nid / NAT_ENTRY_PER_BLOCK)

/* # of pages to perform synchronous readahead before building free nids */
#define FREE_NID_PAGES 4

#define DEF_RA_NID_PAGES	4	/* # of nid pages to be readaheaded */

/* maximum readahead size for node during getting data blocks */
#define MAX_RA_NODE		128

/* control the memory footprint threshold (10MB per 1GB ram) */
#define DEF_RAM_THRESHOLD	10

/* control dirty nats ratio threshold (default: 10% over max nid count) */
#define DEF_DIRTY_NAT_RATIO_THRESHOLD		10

/* vector size for gang look-up from nat cache that consists of radix tree */
#define NATVEC_SIZE	64
#define SETVEC_SIZE	32

/* return value for read_node_page */
#define LOCKED_PAGE	1

/* For flag in struct node_info */
enum {
	IS_CHECKPOINTED,	/* is it checkpointed before? */
	HAS_FSYNCED_INODE,	/* is the inode fsynced before? */
	HAS_LAST_FSYNC,		/* has the latest node fsync mark? */
	IS_DIRTY,		/* this nat entry is dirty? */
};

/*
 * For node information
 */
struct node_info {
	nid_t nid;		/* node id */
	nid_t ino;		/* inode number of the node's owner */
	block_t	blk_addr;	/* block address of the node */
	unsigned char version;	/* version of the node */
	unsigned char flag;	/* for node information bits */
};

struct nat_entry {
	struct list_head list;	/* for clean or dirty nat list */
	struct node_info ni;	/* in-memory node information */
};

#define nat_get_nid(nat)		(nat->ni.nid)
#define nat_set_nid(nat, n)		(nat->ni.nid = n)
#define nat_get_blkaddr(nat)		(nat->ni.blk_addr)
#define nat_set_blkaddr(nat, b)		(nat->ni.blk_addr = b)
#define nat_get_ino(nat)		(nat->ni.ino)
#define nat_set_ino(nat, i)		(nat->ni.ino = i)
#define nat_get_version(nat)		(nat->ni.version)
#define nat_set_version(nat, v)		(nat->ni.version = v)

#define inc_node_version(version)	(++version)

static inline void copy_node_info(struct node_info *dst,
						struct node_info *src)
{
	dst->nid = src->nid;
	dst->ino = src->ino;
	dst->blk_addr = src->blk_addr;
	dst->version = src->version;
	/* should not copy flag here */
}

static inline void set_nat_flag(struct nat_entry *ne,
				unsigned int type, bool set)
{
	unsigned char mask = 0x01 << type;
	if (set)
		ne->ni.flag |= mask;
	else
		ne->ni.flag &= ~mask;
}

static inline bool get_nat_flag(struct nat_entry *ne, unsigned int type)
{
	unsigned char mask = 0x01 << type;
	return ne->ni.flag & mask;
}

static inline void nat_reset_flag(struct nat_entry *ne)
{
	/* these states can be set only after checkpoint was done */
	set_nat_flag(ne, IS_CHECKPOINTED, true);
	set_nat_flag(ne, HAS_FSYNCED_INODE, false);
	set_nat_flag(ne, HAS_LAST_FSYNC, true);
}

static inline void node_info_from_raw_nat(struct node_info *ni,
						struct f2fs_nat_entry *raw_ne)
{
	ni->ino = le32_to_cpu(raw_ne->ino);
	ni->blk_addr = le32_to_cpu(raw_ne->block_addr);
	ni->version = raw_ne->version;
}

static inline void raw_nat_from_node_info(struct f2fs_nat_entry *raw_ne,
						struct node_info *ni)
{
	raw_ne->ino = cpu_to_le32(ni->ino);
	raw_ne->block_addr = cpu_to_le32(ni->blk_addr);
	raw_ne->version = ni->version;
}

static inline bool excess_dirty_nats(struct f2fs_sb_info *sbi)
{
	return NM_I(sbi)->dirty_nat_cnt >= NM_I(sbi)->max_nid *
					NM_I(sbi)->dirty_nats_ratio / 100;
}

enum mem_type {
	FREE_NIDS,	/* indicates the free nid list */
	NAT_ENTRIES,	/* indicates the cached nat entry */
	DIRTY_DENTS,	/* indicates dirty dentry pages */
	INO_ENTRIES,	/* indicates inode entries */
	EXTENT_CACHE,	/* indicates extent cache */
	BASE_CHECK,	/* check kernel status */
};

struct nat_entry_set {
	struct list_head set_list;	/* link with other nat sets */
	struct list_head entry_list;	/* link with dirty nat entries */
	nid_t set;			/* set number*/
	unsigned int entry_cnt;		/* the # of nat entries in set */
};

/*
 * For free nid mangement
 */
enum nid_state {
	NID_NEW,	/* newly added to free nid list */
	NID_ALLOC	/* it is allocated */
};

struct free_nid {
	struct list_head list;	/* for free node id list */
	nid_t nid;		/* node id */
	int state;		/* in use or not: NID_NEW or NID_ALLOC */
};

static inline void next_free_nid(struct f2fs_sb_info *sbi, nid_t *nid)
{
	struct f2fs_nm_info *nm_i = NM_I(sbi);
	struct free_nid *fnid;

	spin_lock(&nm_i->free_nid_list_lock);
	if (nm_i->fcnt <= 0) {
		spin_unlock(&nm_i->free_nid_list_lock);
		return;
	}
	fnid = list_entry(nm_i->free_nid_list.next, struct free_nid, list);
	*nid = fnid->nid;
	spin_unlock(&nm_i->free_nid_list_lock);
}

/*
 * inline functions
 */
static inline void get_nat_bitmap(struct f2fs_sb_info *sbi, void *addr)
{
	struct f2fs_nm_info *nm_i = NM_I(sbi);
	memcpy(addr, nm_i->nat_bitmap, nm_i->bitmap_size);
}

static inline pgoff_t current_nat_addr(struct f2fs_sb_info *sbi, nid_t start)
{
	struct f2fs_nm_info *nm_i = NM_I(sbi);
	pgoff_t block_off;
	pgoff_t block_addr;
	int seg_off;

	block_off = NAT_BLOCK_OFFSET(start);
	seg_off = block_off >> sbi->log_blocks_per_seg;

	block_addr = (pgoff_t)(nm_i->nat_blkaddr +
		(seg_off << sbi->log_blocks_per_seg << 1) +
		(block_off & (sbi->blocks_per_seg - 1)));

	if (f2fs_test_bit(block_off, nm_i->nat_bitmap))
		block_addr += sbi->blocks_per_seg;

	return block_addr;
}

static inline pgoff_t next_nat_addr(struct f2fs_sb_info *sbi,
						pgoff_t block_addr)
{
	struct f2fs_nm_info *nm_i = NM_I(sbi);

	block_addr -= nm_i->nat_blkaddr;
	if ((block_addr >> sbi->log_blocks_per_seg) % 2)
		block_addr -= sbi->blocks_per_seg;
	else
		block_addr += sbi->blocks_per_seg;

	return block_addr + nm_i->nat_blkaddr;
}

static inline void set_to_next_nat(struct f2fs_nm_info *nm_i, nid_t start_nid)
{
	unsigned int block_off = NAT_BLOCK_OFFSET(start_nid);

	f2fs_change_bit(block_off, nm_i->nat_bitmap);
}

static inline void fill_node_footer(struct page *page, nid_t nid,
				nid_t ino, unsigned int ofs, bool reset)
{
	struct f2fs_node *rn = F2FS_NODE(page);
	unsigned int old_flag = 0;

	if (reset)
		memset(rn, 0, sizeof(*rn));
	else
		old_flag = le32_to_cpu(rn->footer.flag);

	rn->footer.nid = cpu_to_le32(nid);
	rn->footer.ino = cpu_to_le32(ino);

	/* should remain old flag bits such as COLD_BIT_SHIFT */
	rn->footer.flag = cpu_to_le32((ofs << OFFSET_BIT_SHIFT) |
					(old_flag & OFFSET_BIT_MASK));
}

static inline void copy_node_footer(struct page *dst, struct page *src)
{
	struct f2fs_node *src_rn = F2FS_NODE(src);
	struct f2fs_node *dst_rn = F2FS_NODE(dst);
	memcpy(&dst_rn->footer, &src_rn->footer, sizeof(struct node_footer));
}

static inline void fill_node_footer_blkaddr(struct page *page, block_t blkaddr)
{
	struct f2fs_checkpoint *ckpt = F2FS_CKPT(F2FS_P_SB(page));
	struct f2fs_node *rn = F2FS_NODE(page);

	rn->footer.cp_ver = ckpt->checkpoint_ver;
	rn->footer.next_blkaddr = cpu_to_le32(blkaddr);
}

static inline nid_t ino_of_node(struct page *node_page)
{
	struct f2fs_node *rn = F2FS_NODE(node_page);
	return le32_to_cpu(rn->footer.ino);
}

static inline nid_t nid_of_node(struct page *node_page)
{
	struct f2fs_node *rn = F2FS_NODE(node_page);
	return le32_to_cpu(rn->footer.nid);
}

static inline unsigned int ofs_of_node(struct page *node_page)
{
	struct f2fs_node *rn = F2FS_NODE(node_page);
	unsigned flag = le32_to_cpu(rn->footer.flag);
	return flag >> OFFSET_BIT_SHIFT;
}

static inline unsigned long long cpver_of_node(struct page *node_page)
{
	struct f2fs_node *rn = F2FS_NODE(node_page);
	return le64_to_cpu(rn->footer.cp_ver);
}

static inline block_t next_blkaddr_of_node(struct page *node_page)
{
	struct f2fs_node *rn = F2FS_NODE(node_page);
	return le32_to_cpu(rn->footer.next_blkaddr);
}

/*
 * f2fs assigns the following node offsets described as (num).
 * N = NIDS_PER_BLOCK
 *
 *  Inode block (0)
 *    |- direct node (1)
 *    |- direct node (2)
 *    |- indirect node (3)
 *    |            `- direct node (4 => 4 + N - 1)
 *    |- indirect node (4 + N)
 *    |            `- direct node (5 + N => 5 + 2N - 1)
 *    `- double indirect node (5 + 2N)
 *                 `- indirect node (6 + 2N)
 *                       `- direct node
 *                 ......
 *                 `- indirect node ((6 + 2N) + x(N + 1))
 *                       `- direct node
 *                 ......
 *                 `- indirect node ((6 + 2N) + (N - 1)(N + 1))
 *                       `- direct node
 */
static inline bool IS_DNODE(struct page *node_page)
{
	unsigned int ofs = ofs_of_node(node_page);

	if (f2fs_has_xattr_block(ofs))
		return false;

	if (ofs == 3 || ofs == 4 + NIDS_PER_BLOCK ||
			ofs == 5 + 2 * NIDS_PER_BLOCK)
		return false;
	if (ofs >= 6 + 2 * NIDS_PER_BLOCK) {
		ofs -= 6 + 2 * NIDS_PER_BLOCK;
		if (!((long int)ofs % (NIDS_PER_BLOCK + 1)))
			return false;
	}
	return true;
}

static inline int set_nid(struct page *p, int off, nid_t nid, bool i)
{
	struct f2fs_node *rn = F2FS_NODE(p);

	f2fs_wait_on_page_writeback(p, NODE, true);

	if (i)
		rn->i.i_nid[off - NODE_DIR1_BLOCK] = cpu_to_le32(nid);
	else
		rn->in.nid[off] = cpu_to_le32(nid);
	return set_page_dirty(p);
}

static inline nid_t get_nid(struct page *p, int off, bool i)
{
	struct f2fs_node *rn = F2FS_NODE(p);

	if (i)
		return le32_to_cpu(rn->i.i_nid[off - NODE_DIR1_BLOCK]);
	return le32_to_cpu(rn->in.nid[off]);
}

/*
 * Coldness identification:
 *  - Mark cold files in f2fs_inode_info
 *  - Mark cold node blocks in their node footer
 *  - Mark cold data pages in page cache
 */
static inline int is_cold_data(struct page *page)
{
	return PageChecked(page);
}

static inline void set_cold_data(struct page *page)
{
	SetPageChecked(page);
}

static inline void clear_cold_data(struct page *page)
{
	ClearPageChecked(page);
}

static inline int is_node(struct page *page, int type)
{
	struct f2fs_node *rn = F2FS_NODE(page);
	return le32_to_cpu(rn->footer.flag) & (1 << type);
}

#define is_cold_node(page)	is_node(page, COLD_BIT_SHIFT)
#define is_fsync_dnode(page)	is_node(page, FSYNC_BIT_SHIFT)
#define is_dent_dnode(page)	is_node(page, DENT_BIT_SHIFT)

static inline int is_inline_node(struct page *page)
{
	return PageChecked(page);
}

static inline void set_inline_node(struct page *page)
{
	SetPageChecked(page);
}

static inline void clear_inline_node(struct page *page)
{
	ClearPageChecked(page);
}

static inline void set_cold_node(struct inode *inode, struct page *page)
{
	struct f2fs_node *rn = F2FS_NODE(page);
	unsigned int flag = le32_to_cpu(rn->footer.flag);

	if (S_ISDIR(inode->i_mode))
		flag &= ~(0x1 << COLD_BIT_SHIFT);
	else
		flag |= (0x1 << COLD_BIT_SHIFT);
	rn->footer.flag = cpu_to_le32(flag);
}

static inline void set_mark(struct page *page, int mark, int type)
{
	struct f2fs_node *rn = F2FS_NODE(page);
	unsigned int flag = le32_to_cpu(rn->footer.flag);
	if (mark)
		flag |= (0x1 << type);
	else
		flag &= ~(0x1 << type);
	rn->footer.flag = cpu_to_le32(flag);
}
#define set_dentry_mark(page, mark)	set_mark(page, mark, DENT_BIT_SHIFT)
#define set_fsync_mark(page, mark)	set_mark(page, mark, FSYNC_BIT_SHIFT)


text:
The standard library for Ark should contain the bare
minimum for a programmer to accomplish their daily
tasks. The library should adopt a consistent style
guide and paradigm for the implementation.

At least, the library should contain libraries for:
* Input and output (buffered)
  * Reader
  * Writer
  * File IO wrappers on top of the basic reader/writer?
* Basic data structures
  * HashMap
  * List [x]
  * Linked List
  * Stack [x]
  * Ordered binary tree?
* Formatting for I/O
* Math
  * Big math
  * Psuedo-random generators
  * Complex (128 bit stuff)
* OS
  * Processes
  * Signals
  * System calls?
* Path
* Regex
* Sorting
* Compression
  * zlib
  * gzip
  * lzw
  * DEFLATE
* Concurrency
  * Threads
  * Mutexes
  * Channels
* Date/time
* Strings
* UTF-8 [-]
* Iterators

Probably an official external library"
* Cryptography
  * AES 128/256
  * SHA 1/256/512
  * MD4
  * RSA
  * Blowfish & Twofish?

### Notes
Cryptography will likely be done via a C library wrapper as an external library.

I'm open to adding more data structures, but right now they seem like the most
common data structures that we should implement.

For the HashMap I'm thinking we could has SipHash, though it is known to be
quite slow it's cryptographically secure. We could probably implement an
alternative HashMap that is faster and is used for cases where you don't
care about collisions, etc.

The Linked List would be a doubly linked list, which means it can be used
as a queue too and is quite fast.

The formatting library for IO would eventually take advantage of the macro
system that doesn't yet exist.

With regards to paths, I'm not sure if this should go under OS, or IO or maybe
an IO utility module?


text:
package com.spectralogic.dsbrowser.gui.components.deletefiles;

import com.airhacks.afterburner.views.FXMLView;
import com.spectralogic.dsbrowser.gui.util.Ds3Task;
import com.spectralogic.dsbrowser.gui.util.StringConstants;

public class DeleteItemView extends FXMLView {
    public DeleteItemView(final Ds3Task deleteTask) {
        super(name -> {
            if (name.equals(StringConstants.CASE_DELETETASK)) {
                return deleteTask;
            }
            return null;
        });
    }
}


text:
module SocialNetworking
  module Serializers
    # Abstract serializer.
    class Serializer
      attr_reader :model

      def self.from_collection(collection)
        collection.map { |i| new(i).to_serialized }.compact
      end

      def initialize(model)
        @model = model
      end
    end
  end
end


text:
package com.intellij.lang.javascript.formatter.blocks;

import com.intellij.formatting.*;
import com.intellij.lang.ASTNode;
import com.intellij.lang.javascript.JSElementTypes;
import com.intellij.lang.javascript.JSTokenTypes;
import com.intellij.lang.javascript.formatter.JSCodeStyleSettings;
import com.intellij.lang.javascript.formatter.JSSpacingProcessor;
import com.intellij.lang.javascript.types.JSFileElementType;
import com.intellij.openapi.util.TextRange;
import com.intellij.psi.PsiErrorElement;
import com.intellij.psi.PsiWhiteSpace;
import com.intellij.psi.codeStyle.CodeStyleSettingsManager;
import com.intellij.psi.codeStyle.CommonCodeStyleSettings;
import com.intellij.psi.tree.IElementType;

import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import java.util.List;

/**
 * @author ven
 */
public class JSBlock implements Block
{
	private ASTNode myNode;

	private final CommonCodeStyleSettings mySettings;

	private Alignment myAlignment;
	private Indent myIndent;
	private Wrap myWrap;
	private List<Block> mySubBlocks = null;

	public JSBlock(final ASTNode node, final Alignment alignment, final Indent indent, final Wrap wrap, final CommonCodeStyleSettings settings)
	{
		myAlignment = alignment;
		myIndent = indent;
		myNode = node;
		myWrap = wrap;
		mySettings = settings;
	}

	public ASTNode getNode()
	{
		return myNode;
	}

	@Override
	@Nonnull
	public TextRange getTextRange()
	{
		return myNode.getTextRange();
	}

	@Override
	@Nonnull
	public List<Block> getSubBlocks()
	{
		if(mySubBlocks == null)
		{
			SubBlockVisitor visitor = new SubBlockVisitor(getSettings());
			visitor.visit(myNode);
			mySubBlocks = visitor.getBlocks();
		}
		return mySubBlocks;
	}

	@Override
	@Nullable
	public Wrap getWrap()
	{
		return myWrap;
	}

	@Override
	@Nullable
	public Indent getIndent()
	{
		return myIndent;
	}

	@Override
	@Nullable
	public Alignment getAlignment()
	{
		return myAlignment;
	}

	@Override
	@Nullable
	public Spacing getSpacing(Block child1, Block child2)
	{
		if(child1 instanceof JSDocCommentBlock || child2 instanceof JSDocCommentBlock || child1 == null)
		{
			return null;
		}
		return new JSSpacingProcessor(getNode(), ((JSBlock) child1).getNode(), ((JSBlock) child2).getNode(), mySettings).getResult();
	}

	@Override
	@Nonnull
	public ChildAttributes getChildAttributes(final int newChildIndex)
	{
		Indent indent = null;
		final IElementType blockElementType = myNode.getElementType();

		if(blockElementType == JSTokenTypes.DOC_COMMENT)
		{
			return new ChildAttributes(Indent.getSpaceIndent(1), null);
		}

		if(blockElementType == JSElementTypes.PACKAGE_STATEMENT)
		{
			final JSCodeStyleSettings customSettings = CodeStyleSettingsManager.getSettings(myNode.getPsi().getProject()).getCustomSettings
					(JSCodeStyleSettings.class);
			if(customSettings.INDENT_PACKAGE_CHILDREN == JSCodeStyleSettings.INDENT)
			{
				indent = Indent.getNormalIndent();
			}
			else
			{
				indent = Indent.getNoneIndent();
			}
		}
		else if(blockElementType == JSElementTypes.BLOCK_STATEMENT ||
				blockElementType == JSElementTypes.CLASS ||
				blockElementType == JSElementTypes.OBJECT_LITERAL_EXPRESSION)
		{
			indent = Indent.getNormalIndent();
		}
		else if(blockElementType instanceof JSFileElementType || blockElementType == JSElementTypes.EMBEDDED_CONTENT)
		{
			indent = Indent.getNoneIndent();
		}
		else if(JSElementTypes.SOURCE_ELEMENTS.contains(blockElementType) ||
				blockElementType == JSElementTypes.FUNCTION_EXPRESSION ||
				blockElementType == JSElementTypes.ATTRIBUTE_LIST)
		{
			indent = Indent.getNoneIndent();
		}

		Alignment alignment = null;
		final List<Block> subBlocks = getSubBlocks();
		for(int i = 0; i < newChildIndex; i++)
		{
			if(i == subBlocks.size())
			{
				break;
			}
			final Alignment childAlignment = subBlocks.get(i).getAlignment();
			if(childAlignment != null)
			{
				alignment = childAlignment;
				break;
			}
		}

		// in for loops, alignment is required only for items within parentheses
		if(blockElementType == JSElementTypes.FOR_STATEMENT || blockElementType == JSElementTypes.FOR_IN_STATEMENT)
		{
			for(int i = 0; i < newChildIndex; i++)
			{
				if(((JSBlock) subBlocks.get(i)).getNode().getElementType() == JSTokenTypes.RPAR)
				{
					alignment = null;
					break;
				}
			}
		}

		return new ChildAttributes(indent, alignment);
	}

	@Override
	public boolean isIncomplete()
	{
		return isIncomplete(myNode);
	}

	private boolean isIncomplete(ASTNode node)
	{
		node.getPsi().getFirstChild(); // expand chameleon
		ASTNode lastChild = node.getLastChildNode();
		while(lastChild != null && lastChild.getPsi() instanceof PsiWhiteSpace)
		{
			lastChild = lastChild.getTreePrev();
		}
		if(lastChild == null)
		{
			return false;
		}
		if(lastChild.getPsi() instanceof PsiErrorElement)
		{
			return true;
		}
		return isIncomplete(lastChild);
	}

	public CommonCodeStyleSettings getSettings()
	{
		return mySettings;
	}

	@Override
	public boolean isLeaf()
	{
		if(myNode.getElementType() == JSTokenTypes.DOC_COMMENT)
		{
			return false;
		}
		return myNode.getFirstChildNode() == null;
	}
}


text:
{% comment %}
Usage: {% include video_entry.html video=video_object %}
{% endcomment %}

{{include.video.name}}

      {% if include.video.youtube-id %}

      {% endif %}

      {% if include.video.vimeo-id %}

      {% endif %}

      {% if include.video.file %}

  Download Video
      {% if include.video.subtitles %}
           Download Subtitles
      {% endif %}

      {% endif %}


text:
module Promotion
  module PromotionValidators
    class PlacementLimitValidator < ActiveModel::EachValidator
      def validate_each(record, attribute, value)
        return if value.nil? or !record.new_record? or !Promotion.config.placements[value].has_key?(:max)

        if Promotion::Promo.count(:conditions => get_conditions(record, value)) >= Promotion.config.placements[value][:max]
          record.errors[attribute] << "The maximum number of entries for this placement has already been reached"
        end
      end

      private
      def get_conditions(record, placement)
        conditions = { :placement => placement }

        conditions[:market] = record.market if Promotion.config.localisable

        conditions
      end
    end
  end
end


text:
require 'usmu/ui/console'
require 'open3'

step 'I have a site at :location' do |location|
  @location = "#{location}/usmu.yml"
end

step 'I run usmu with the arguments :args' do |args|
  args = args.split(' ')
  if @location
    args << '--config' << @location
  end
  args << '--trace'
  @site = Usmu::Ui::Console.new(args)
end

step 'the directory :destination should match :test_folder' do |destination, test_folder|
  run = %W{diff -ur --strip-trailing-cr #{test_folder} #{destination}}
  Open3.popen2e(*run) do |i, o, t|
    output = run.join(' ') + "\n" + o.read
    fail output if t.value != 0
  end
end

step 'the modification time for the input file :input should match the output file :output' do |input, output|
  input_mtime = File.stat(File.join(@site.configuration.source_path, input)).mtime
  output_mtime = File.stat(File.join(@site.configuration.destination_path, output)).mtime
  expect(input_mtime).to eq(output_mtime)
end


text:
using namespace jet;

TEST(Bvh3, Constructors) {
    Bvh3<Vector3D> bvh;
    EXPECT_EQ(bvh.begin(), bvh.end());
}

TEST(Bvh3, BasicGetters) {
    Bvh3<Vector3D> bvh;

    std::vector<Vector3D> points{Vector3D(0, 0, 0), Vector3D(1, 1, 1)};
    std::vector<BoundingBox3D> bounds(points.size());
    size_t i = 0;
    BoundingBox3D rootBounds;
    std::generate(bounds.begin(), bounds.end(), [&]() {
        auto c = points[i++];
        BoundingBox3D box(c, c);
        box.expand(0.1);
        rootBounds.merge(box);
        return box;
    });

    bvh.build(points, bounds);

    EXPECT_EQ(2u, bvh.numberOfItems());
    EXPECT_VECTOR3_EQ(points[0], bvh.item(0));
    EXPECT_VECTOR3_EQ(points[1], bvh.item(1));
    EXPECT_EQ(3u, bvh.numberOfNodes());
    EXPECT_EQ(1u, bvh.children(0).first);
    EXPECT_EQ(2u, bvh.children(0).second);
    EXPECT_FALSE(bvh.isLeaf(0));
    EXPECT_TRUE(bvh.isLeaf(1));
    EXPECT_TRUE(bvh.isLeaf(2));
    EXPECT_BOUNDING_BOX3_EQ(rootBounds, bvh.nodeBound(0));
    EXPECT_BOUNDING_BOX3_EQ(bounds[0], bvh.nodeBound(1));
    EXPECT_BOUNDING_BOX3_EQ(bounds[1], bvh.nodeBound(2));
    EXPECT_EQ(bvh.end(), bvh.itemOfNode(0));
    EXPECT_EQ(bvh.begin(), bvh.itemOfNode(1));
    EXPECT_EQ(bvh.begin() + 1, bvh.itemOfNode(2));
}

TEST(Bvh3, Nearest) {
    Bvh3<Vector3D> bvh;

    auto distanceFunc = [](const Vector3D& a, const Vector3D& b) {
        return a.distanceTo(b);
    };

    size_t numSamples = getNumberOfSamplePoints3();
    std::vector<Vector3D> points(getSamplePoints3(), getSamplePoints3() + numSamples);

    std::vector<BoundingBox3D> bounds(points.size());
    size_t i = 0;
    std::generate(bounds.begin(), bounds.end(), [&]() {
        auto c = points[i++];
        BoundingBox3D box(c, c);
        box.expand(0.1);
        return box;
    });

    bvh.build(points, bounds);

    Vector3D testPt(0.5, 0.5, 0.5);
    auto nearest = bvh.nearest(testPt, distanceFunc);
    ptrdiff_t answerIdx = 0;
    double bestDist = testPt.distanceTo(points[answerIdx]);
    for (i = 1; i < numSamples; ++i) {
        double dist = testPt.distanceTo(getSamplePoints3()[i]);
        if (dist < bestDist) {
            bestDist = dist;
            answerIdx = i;
        }
    }

    EXPECT_EQ(answerIdx, nearest.item - &bvh.item(0));
}

TEST(Bvh3, BBoxIntersects) {
    Bvh3<Vector3D> bvh;

    auto overlapsFunc = [](const Vector3D& pt, const BoundingBox3D& bbox) {
        BoundingBox3D box(pt, pt);
        box.expand(0.1);
        return bbox.overlaps(box);
    };

    size_t numSamples = getNumberOfSamplePoints3();
    std::vector<Vector3D> points(getSamplePoints3(), getSamplePoints3() + numSamples);

    std::vector<BoundingBox3D> bounds(points.size());
    size_t i = 0;
    std::generate(bounds.begin(), bounds.end(), [&]() {
        auto c = points[i++];
        BoundingBox3D box(c, c);
        box.expand(0.1);
        return box;
    });

    bvh.build(points, bounds);

    BoundingBox3D testBox({0.25, 0.15, 0.3}, {0.5, 0.6, 0.4});
    bool hasOverlaps = false;
    for (i = 0; i < numSamples; ++i) {
        hasOverlaps |= overlapsFunc(getSamplePoints3()[i], testBox);
    }

    EXPECT_EQ(hasOverlaps, bvh.intersects(testBox, overlapsFunc));

    BoundingBox3D testBox2({0.3, 0.2, 0.1}, {0.6, 0.5, 0.4});
    hasOverlaps = false;
    for (i = 0; i < numSamples; ++i) {
        hasOverlaps |= overlapsFunc(getSamplePoints3()[i], testBox2);
    }

    EXPECT_EQ(hasOverlaps, bvh.intersects(testBox2, overlapsFunc));
}

TEST(Bvh3, RayIntersects) {
    Bvh3<BoundingBox3D> bvh;

    auto intersectsFunc = [](const BoundingBox3D& a, const Ray3D& ray) {
        return a.intersects(ray);
    };

    size_t numSamples = getNumberOfSamplePoints3();
    std::vector<BoundingBox3D> items(numSamples / 2);
    size_t i = 0;
    std::generate(items.begin(), items.end(), [&]() {
        auto c = getSamplePoints3()[i++];
        BoundingBox3D box(c, c);
        box.expand(0.1);
        return box;
    });

    bvh.build(items, items);

    for (i = 0; i < numSamples / 2; ++i) {
        Ray3D ray(getSampleDirs3()[i + numSamples / 2],
                  getSampleDirs3()[i + numSamples / 2]);
        // ad-hoc search
        bool ansInts = false;
        for (size_t j = 0; j < numSamples / 2; ++j) {
            if (intersectsFunc(items[j], ray)) {
                ansInts = true;
                break;
            }
        }

        // bvh search
        bool octInts = bvh.intersects(ray, intersectsFunc);

        EXPECT_EQ(ansInts, octInts);
    }
}

TEST(Bvh3, ClosestIntersection) {
    Bvh3<BoundingBox3D> bvh;

    auto intersectsFunc = [](const BoundingBox3D& a, const Ray3D& ray) {
        auto bboxResult = a.closestIntersection(ray);
        if (bboxResult.isIntersecting) {
            return bboxResult.tNear;
        } else {
            return kMaxD;
        }
    };

    size_t numSamples = getNumberOfSamplePoints3();
    std::vector<BoundingBox3D> items(numSamples / 2);
    size_t i = 0;
    std::generate(items.begin(), items.end(), [&]() {
        auto c = getSamplePoints3()[i++];
        BoundingBox3D box(c, c);
        box.expand(0.1);
        return box;
    });

    bvh.build(items, items);

    for (i = 0; i < numSamples / 2; ++i) {
        Ray3D ray(getSamplePoints3()[i + numSamples / 2],
                  getSampleDirs3()[i + numSamples / 2]);
        // ad-hoc search
        ClosestIntersectionQueryResult3<BoundingBox3D> ansInts;
        for (size_t j = 0; j < numSamples / 2; ++j) {
            double dist = intersectsFunc(items[j], ray);
            if (dist < ansInts.distance) {
                ansInts.distance = dist;
                ansInts.item = &bvh.item(j);
            }
        }

        // bvh search
        auto bvhInts = bvh.closestIntersection(ray, intersectsFunc);

        EXPECT_DOUBLE_EQ(ansInts.distance, bvhInts.distance);
        EXPECT_EQ(ansInts.item, bvhInts.item);
    }
}

TEST(Bvh3, ForEachOverlappingItems) {
    Bvh3<Vector3D> bvh;

    auto overlapsFunc = [](const Vector3D& pt, const BoundingBox3D& bbox) {
        return bbox.contains(pt);
    };

    size_t numSamples = getNumberOfSamplePoints3();
    std::vector<Vector3D> points(getSamplePoints3(), getSamplePoints3() + numSamples);

    std::vector<BoundingBox3D> bounds(points.size());
    size_t i = 0;
    std::generate(bounds.begin(), bounds.end(), [&]() {
        auto c = points[i++];
        BoundingBox3D box(c, c);
        box.expand(0.1);
        return box;
    });

    bvh.build(points, bounds);

    BoundingBox3D testBox({0.3, 0.2, 0.1}, {0.6, 0.5, 0.4});
    size_t numOverlaps = 0;
    for (i = 0; i < numSamples; ++i) {
        numOverlaps += overlapsFunc(getSamplePoints3()[i], testBox);
    }

    size_t measured = 0;
    bvh.forEachIntersectingItem(testBox, overlapsFunc, [&](const Vector3D& pt) {
        EXPECT_TRUE(overlapsFunc(pt, testBox));
        ++measured;
    });

    EXPECT_EQ(numOverlaps, measured);
}


text:
namespace Handlebars.Core.Compiler.Lexer.Tokens
{
    internal class StaticToken : Token
    {
        private StaticToken(string value, string original)
        {
            Value = value;
            Original = original;
        }

        internal StaticToken(string value)
            : this(value, value)
        {
        }

        public override TokenType Type => TokenType.Static;

        public override string Value { get; }

        public string Original { get; }

        public StaticToken GetModifiedToken(string value)
        {
            return new StaticToken(value, Original);
        }
    }
}