text:
import copy

def list_of_list_to_dict(list_of_lists, key_index, value_index=None):
    """
        Function to convert list of list to dictionary of list/values
        :param list_of_lists: The list of list which is to be converted to dictionary
        :type list_of_lists: List of lists
        :param key_index: takes the key whose value will be the key value to the converted dictionary
        :type key_index: integer
        :param value_index:The key whose value will be used as resultant dict's value
        :type value_index:integer/list
        :returns:transformed_dict
    """
    try:
        transformed_dict = {}
        if value_index:
            if type(value_index) == list:
                for row in list_of_lists:
                    transformed_dict[row[key_index]] = [row[index]
                                                        for index in value_index]
            elif type(value_index) == int:
                for row in list_of_lists:
                    transformed_dict[row[key_index]] = row[value_index]
        else:
            for row in list_of_lists:
                temp_list = copy.deepcopy(row)
                del(temp_list[key_index])
                transformed_dict[row[key_index]] = temp_list
        return transformed_dict
    except Exception as e:
        msg = """Can't convert Given List of List to Dictionary for key_index:{key_index} and value_index:{value_index} due to Error: {error}""".format(
            key_index=key_index, value_index=value_index, error=str(e))
        raise Exception(msg)

def dict_to_list_of_list(input_dict):
    """
        Function to convert dictionary of list/values to list of list
        :param input_dict: The dictionary which is to be converted into list of list
        :type input_dict: dictionary
        :returns:transformed dictionary
    """
    try:
        return [[key, value] for key, value in input_dict.iteritems()]
    except Exception as e:
        msg = """Can't convert Given Dictionary to List of List due to Error: {error}""".format(
            error=str(e))
        raise Exception(msg)

def list_of_dict_to_dict(data, aggregate_key, select_key=None):
    """
        Converts list of dict to dict with aggregate_key's value as key
        :param data: The data to be transformed
        :type data: list of dict
        :param aggregate_key: The key whose value will be used as resultant dict's key
        :type aggregate_key: string
        :param select_key: The key whose value will be used as resultant dict's value
        :type select_key: string
        :returns tranformed dictionary
    """
    try:
        transformed_dict = {}
        if select_key:
            if type(select_key) == list:
                for row in data:
                    if row.get(aggregate_key):
                        transformed_dict[row[aggregate_key]] = [
                            row[key] for key in select_key]
            else:
                for row in data:
                    if row.get(aggregate_key):
                        transformed_dict[row[aggregate_key]] = row[select_key]
        else:
            for row in data:
                if row.get(aggregate_key):
                    transformed_dict[row[aggregate_key]] = copy.deepcopy(row)
        return transformed_dict
    except Exception as e:
        msg = """Can't convert Given List of Dict to Dictionary for aggregate_key: {a_key},select_key: {s_key } due to Error: {error}""".format(
            a_key=aggregate_key, s_key=select_key, error=str(e))
        raise Exception(msg)

def dict_of_dict_to_list_of_dict(input_dict, select_key_name):
    """
        Function to convert dictionary to list of dictionary
        :param input_dict: The dictionary which is to be converted into list of dictionary
        :type input_dict: dictionary
        :param select_key_name:the key whose value key of converted list of dictionary will be named
        :type select_key_name:string
        :returns:transformed list
    """
    try:
        transformed_list = []
        for key, value in input_dict.iteritems():
            temp_dict = copy.deepcopy(value)
            temp_dict[select_key_name] = key
            transformed_list.append(temp_dict)
        return transformed_list
    except Exception as e:
        msg = """Can't convert Given Dict to List of Dictionary for select_key_name: {select_key_name} due to Error: {error}""".format(
            select_key_name=select_key_name, error=str(e))
        raise Exception(msg)

def merge_dicts(merge_func, merge_type='or', *dicts):
    """
        Function to merge two/more Dictionaries
        :param merge_func:the functin to be performed(like addition/substraction/multiplication) for the same key values in the Dictionaries
        :type merge_func:function
        :param merge_type:Whether to perform union or intersection while merging Dictionaries
        :type merge_type:string ('or'/'and')
        :returns:merged_dict
    """
    try:
        if len(dicts) > 1:
            merged_dict = {}
            if merge_type == 'or':
                all_keys = set([])
                for input_dict in dicts:
                    all_keys = all_keys | set(input_dict.keys())
            elif merge_type == 'and':
                all_keys = set(dicts[0].keys())
                for input_dict in dicts:
                    all_keys = all_keys & set(input_dict.keys())
            else:
                msg = """Dictionaries can't be merged as merge_type:{merge_type} is other than 'or' and 'and' """.format(
                    merge_type=merge_type)
                raise Exception(msg)
            for key in all_keys:
                merged_dict[key] = merge_func(
                    [input_dict.get(key) for input_dict in dicts])
            return merged_dict
        elif len(dicts) == 1:
            return dicts[0]
        else:
            msg = """Please provide valid Dictionaries"""
            raise Exception(msg)
    except Exception as e:
        msg = """Dictionaries can't be merged due to Error: {error}""".format(
            error=str(e))
        raise Exception(msg)

def sum(input_list):
    """
        Function to add elements in the list
        :param input_list:list whose elementsare to be added
        :type input_list:list
        :returns: total
    """
    try:
        total = 0
        for value in input_list:
            if type(value) == int or type(value) == float:
                total += value
        return total
    except Exception as e:
        msg = """Sum function not working due to Error: {error}""".format(
            error=str(e))
        raise Exception(msg)


text:
require_relative 'test_helper'

class GitHubLdapReferralChaserTestCases < GitHub::Ldap::Test

  def setup
    @ldap = GitHub::Ldap.new(options)
    @chaser = GitHub::Ldap::ReferralChaser.new(@ldap)
  end

  def test_creates_referral_with_connection_credentials
    @ldap.expects(:search).yields({ search_referrals: ["ldap://dc1.ghe.local/"]}).returns([])

    referral = mock("GitHub::Ldap::ReferralChaser::Referral")
    referral.stubs(:search).returns([])

    GitHub::Ldap::ReferralChaser::Referral.expects(:new)
      .with("ldap://dc1.ghe.local/", "uid=admin,dc=github,dc=com", "passworD1", options[:port])
      .returns(referral)

    @chaser.search({})
  end

  def test_creates_referral_with_default_port
    @ldap.expects(:search).yields({
      search_referrals: ["ldap://dc1.ghe.local/CN=Maggie%20Mae,CN=Users,DC=dc4,DC=ghe,DC=local"]
    }).returns([])

    stub_referral_connection = mock("GitHub::Ldap")
    stub_referral_connection.stubs(:search).returns([])
    GitHub::Ldap::ConnectionCache.expects(:get_connection).with(has_entry(port: options[:port])).returns(stub_referral_connection)
    chaser = GitHub::Ldap::ReferralChaser.new(@ldap)
    chaser.search({})
  end

  def test_creates_referral_for_first_referral_string
    @ldap.expects(:search).multiple_yields([
      { search_referrals:
        ["ldap://dc1.ghe.local/CN=Maggie%20Mae,CN=Users,DC=dc4,DC=ghe,DC=local",
         "ldap://dc2.ghe.local/CN=Maggie%20Mae,CN=Users,DC=dc4,DC=ghe,DC=local"]
      }
    ],[
      { search_referrals:
        ["ldap://dc3.ghe.local/CN=Maggie%20Mae,CN=Users,DC=dc4,DC=ghe,DC=local",
         "ldap://dc4.ghe.local/CN=Maggie%20Mae,CN=Users,DC=dc4,DC=ghe,DC=local"]
      }
    ]).returns([])

    referral = mock("GitHub::Ldap::ReferralChaser::Referral")
    referral.stubs(:search).returns([])

    GitHub::Ldap::ReferralChaser::Referral.expects(:new)
      .with(
        "ldap://dc1.ghe.local/CN=Maggie%20Mae,CN=Users,DC=dc4,DC=ghe,DC=local",
        "uid=admin,dc=github,dc=com",
        "passworD1",
        options[:port])
      .returns(referral)

    @chaser.search({})
  end

  def test_returns_referral_search_results
    @ldap.expects(:search).multiple_yields([
      { search_referrals:
        ["ldap://dc1.ghe.local/CN=Maggie%20Mae,CN=Users,DC=dc4,DC=ghe,DC=local",
         "ldap://dc2.ghe.local/CN=Maggie%20Mae,CN=Users,DC=dc4,DC=ghe,DC=local"]
      }
    ],[
      { search_referrals:
        ["ldap://dc3.ghe.local/CN=Maggie%20Mae,CN=Users,DC=dc4,DC=ghe,DC=local",
         "ldap://dc4.ghe.local/CN=Maggie%20Mae,CN=Users,DC=dc4,DC=ghe,DC=local"]
      }
    ]).returns([])

    referral = mock("GitHub::Ldap::ReferralChaser::Referral")
    referral.expects(:search).returns(["result", "result"])

    GitHub::Ldap::ReferralChaser::Referral.expects(:new).returns(referral)

    results = @chaser.search({})
    assert_equal(["result", "result"], results)
  end

  def test_handle_blank_url_string_in_referral
    @ldap.expects(:search).yields({ search_referrals: [""] })

    results = @chaser.search({})
    assert_equal([], results)
  end

  def test_returns_referral_search_results
    @ldap.expects(:search).yields({ foo: ["not a referral"] })

    GitHub::Ldap::ReferralChaser::Referral.expects(:new).never
    results = @chaser.search({})
  end

  def test_referral_should_use_host_from_referral_string
    GitHub::Ldap::ConnectionCache.expects(:get_connection).with(has_entry(host: "dc4.ghe.local"))
    GitHub::Ldap::ReferralChaser::Referral.new("ldap://dc4.ghe.local/CN=Maggie%20Mae,CN=Users,DC=dc4,DC=ghe,DC=local", "", "")
  end
end

redpajama_set_name: RedPajamaGithub


text:
package com.alibaba.asyncload.domain;

import java.util.ArrayList;
import java.util.List;

/**
 * 一个测试AsyncLoad的默认实现
 *
 * @author jianghang 2011-1-21 下午10:46:19
 */
public class AsyncLoadTestServiceImpl implements AsyncLoadTestService {

    private AsyncLoadTestServiceDAO asyncLoadTestServiceDAO;

    public AsyncLoadTestModel getRemoteModel(String name, long sleep) {
        if (sleep > 0) {
            asyncLoadTestServiceDAO.doSleep(sleep);
        }
        AsyncLoadTestModel model = new AsyncLoadTestModel(1, name, name);
        return model;
    }

    public List<AsyncLoadTestModel> listRemoteModel(String name, long sleep) {
        List<AsyncLoadTestModel> models = new ArrayList<AsyncLoadTestModel>();
        for (int i = 0; i < 2; i++) {
            if (sleep > 0) {
                asyncLoadTestServiceDAO.doSleep(sleep);
            }
            AsyncLoadTestModel model = new AsyncLoadTestModel(1, name, name);
            models.add(model);
        }
        return models;
    }

    public int countRemoteModel(String name, long sleep) {
        if (sleep > 0) {
            asyncLoadTestServiceDAO.doSleep(sleep);
        }
        return 0;
    }

    public void updateRemoteModel(String name, long sleep) {
        if (sleep > 0) {
            asyncLoadTestServiceDAO.doSleep(sleep);
        }
    }

    public String getRemoteName(String name, long sleep) {
        if (sleep > 0) {
            asyncLoadTestServiceDAO.doSleep(sleep);
        }
        return name;
    }

    public Object getRemoteObject(String name, long sleep) {
        if (sleep > 0) {
            asyncLoadTestServiceDAO.doSleep(sleep);
        }
        return name;
    }

    public void setAsyncLoadTestServiceDAO(AsyncLoadTestServiceDAO asyncLoadTestServiceDAO) {
        this.asyncLoadTestServiceDAO = asyncLoadTestServiceDAO;
    }

}


text:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://www.springframework.org/schema/beans
           http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">

	<!-- Property File Configuration -->
	<bean id="propertyConfigurer"
		class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
		<property name="locations">
			<list>
				<value>classpath:resources/tides.properties</value>
				<value>classpath:resources/ideyatech.properties</value>
			</list>
		</property>
		<property name="ignoreUnresolvablePlaceholders" value="true" />
	</bean>
	<!-- Define dataSource as DBCP -->
	<bean id="dataSource"
		class="org.springframework.jdbc.datasource.DriverManagerDataSource">
		<property name="driverClassName" value="com.mysql.jdbc.Driver" />
		<property name="url" value="jdbc:mysql://localhost/javatest" />
		<property name="username" value="javauser" />
		<property name="password" value="javadude" />
	</bean>

	<bean id="reportDataSource"
		class="org.springframework.jdbc.datasource.DriverManagerDataSource">
		<property name="driverClassName" value="com.mysql.jdbc.Driver" />
		<property name="url" value="jdbc:mysql://localhost/javatest" />
		<property name="username" value="javauser" />
		<property name="password" value="javadude" />
	</bean>

	<!-- Hibernate Utility Option using ideyatech.properties -->
	<bean id="hibernateUtil" class="org.opentides.util.HibernateUtil">
		<property name="driverClassName" value="com.mysql.jdbc.Driver" />
		<property name="url" value="jdbc:mysql://localhost/javatest" />
		<property name="username" value="javauser" />
		<property name="password" value="javadude" />
	</bean>

	<bean id="evolveList"
		class="org.springframework.beans.factory.config.ListFactoryBean">
		<property name="sourceList">
			<list>
			</list>
		</property>
	</bean>

	<!-- List of user permissions -->
	<bean id="rolesMap" class="org.springframework.beans.factory.config.MapFactoryBean">
		<property name="sourceMap">
			<map>
				<entry key="ROLE_ADMIN">
					<value>Administrator</value>
				</entry>
				<entry key="ROLE_GUEST">
					<value>Guest</value>
				</entry>
			</map>
		</property>
	</bean>

	<bean id="passwordEncoder" class="org.springframework.security.authentication.encoding.ShaPasswordEncoder">
     	<constructor-arg value="256"/>
 	</bean>

	<!-- Bean for testing transaction -->
	<bean id="serviceTransaction" class="org.opentides.service.impl.ServiceTransactionImpl">
		<property name="dao">
			<ref bean="systemCodesDAO" />
		</property>
	</bean>
</beans>


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

namespace ReMi.Contracts.Plugins.Data.ReleaseContent
{
    public class ReleaseContentTicket
    {
        public string TicketName { get; set; }
        public string TicketDescription { get; set; }
        public string Assignee { get; set; }

        public Guid TicketId { get; set; }

        public string TicketUrl { get; set; }

        public IEnumerable<ReleaseContentTicket> SubTickets { get; set; }

        public override string ToString()
        {
            return String.Format("[TicketName={0},TicketDescription={1}, Assignee={2}, TicketId={3}, TicketUrl={4}, SubTickets={5}]",
                TicketName, TicketDescription, Assignee, TicketId, TicketUrl, SubTickets);
        }
    }
}


text:
using System;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework;
using System.Collections;
using Nez.Tweens;

namespace Nez
{
	public class CinematicLetterboxPostProcessor : PostProcessor
	{
		/// <summary>
		/// color of the letterbox
		/// </summary>
		/// <value>The color.</value>
		public Color color
		{
			get { return _color; }
			set
			{
				if( _color != value )
				{
					_color = value;

					if( effect != null )
						_colorParam.SetValue( _color.ToVector4() );
				}
			}
		}

		/// <summary>
		/// size in pixels of the letterbox
		/// </summary>
		/// <value>The size of the letterbox.</value>
		public float letterboxSize
		{
			get { return _letterboxSize; }
			set
			{
				if( _letterboxSize != value )
				{
					_letterboxSize = value;

					if( effect != null )
						_letterboxSizeParam.SetValue( _letterboxSize );
				}
			}
		}

		Color _color = Color.Black;
		float _letterboxSize = 0f;
		EffectParameter _colorParam;
		EffectParameter _letterboxSizeParam;
		bool _isAnimating;

		public CinematicLetterboxPostProcessor( int executionOrder ) : base( executionOrder )
		{}

		public override void onAddedToScene()
		{
			effect = scene.content.loadEffect<Effect>( "vignette", EffectResource.letterboxBytes );

			_colorParam = effect.Parameters["_color"];
			_letterboxSizeParam = effect.Parameters["_letterboxSize"];
			_colorParam.SetValue( _color.ToVector4() );
			_letterboxSizeParam.SetValue( _letterboxSize );
		}

		/// <summary>
		/// animates the letterbox in
		/// </summary>
		/// <returns>The in.</returns>
		/// <param name="letterboxSize">Letterbox size.</param>
		/// <param name="duration">Duration.</param>
		/// <param name="easeType">Ease type.</param>
		public IEnumerator animateIn( float letterboxSize, float duration = 2, EaseType easeType = EaseType.ExpoOut )
		{
			// wait for any current animations to complete
			while( _isAnimating )
				yield return null;

			_isAnimating = true;
			var elapsedTime = 0f;
			while( elapsedTime < duration )
			{
				elapsedTime += Time.deltaTime;
				this.letterboxSize = Lerps.ease( easeType, 0, letterboxSize, elapsedTime, duration );
				yield return null;
			}
			_isAnimating = false;
		}

		/// <summary>
		/// animates the letterbox out
		/// </summary>
		/// <returns>The out.</returns>
		/// <param name="duration">Duration.</param>
		/// <param name="easeType">Ease type.</param>
		public IEnumerator animateOut( float duration = 2, EaseType easeType = EaseType.ExpoIn )
		{
			// wait for any current animations to complete
			while( _isAnimating )
				yield return null;

			_isAnimating = true;
			var startSize = letterboxSize;
			var elapsedTime = 0f;
			while( elapsedTime < duration )
			{
				elapsedTime += Time.deltaTime;
				this.letterboxSize = Lerps.ease( easeType, startSize, 0, elapsedTime, duration );
				yield return null;
			}
			_isAnimating = false;
		}
	}
}


text:
module CumulogicClient
  VERSION = "0.0.6"
end


text:
   ```
   1.清除docker 旧版本

     rpm -qa |grep docker
     yum  -y  remove docker*

   2.安装新的docker

     yum install -y docker-engine

   3.systemctl  start docker

   4.docker info 查看docker状态
   ```

#### ubuntu

   ```
   1.更新apt包

     sudo apt-get update

   2.安装 Docker

     sudo apt-get install docker-engine

   3.sudo service docker start

   4.docker info 查看docker状态
   ```

#### mac

   请参考[https://docs.docker.com/docker-for-mac/](https://docs.docker.com/docker-for-mac/)

## 安装docker-compose

```
curl -L https://github.com/docker/compose/releases/download/1.13.0/docker-compose-`uname -s`-`uname -m` > /usr/local/bin/docker-compose
sudo chmod +x /usr/local/bin/docker-compose
docker-compose --version
```


text:
using UnityEngine;
using Fineness.Framework.Interfaces;
using System;
using System.Collections.Generic;

///
///
/// 核心类
///
/// 放置一些与平台和全局相关的数据和信息
///
/// add by Minghua.ji
///
///
public class  Core
{

    #region 静态方法
    /// 在运行的时候动态启动框架
    /// <param name="target"></param>
    /// <param name="started"></param>
    /// <param name="isBusUpdate"></param>
    public static IApplication StartupInRunning<T>(GameObject target = null, Action[] started = null, bool isBusUpdate = true) where T : IApplication
    {
        IsApplyBusUpdate = isBusUpdate;
        if (target == null)
            target = new GameObject();
        mApplication = (IApplication)target.AddComponent(typeof(T));
        int max = (started != null) ? started.Length : 0;
        for (int i = 0; i < max; i++)
            mApplication.AddStarted(started[i]);
        mGameObject = target;
        return mApplication;
    }
    #endregion

    #region 私有静态属性
    /// 正在运行的核心物件对象,用于挂载BaseApplication脚本的的物件
    private static GameObject mGameObject;
    /// 正在运行的应用对象
    private static IApplication mApplication;
    #endregion

    #region 静态属性
    /// 是否应用总线刷帧
    public static bool IsApplyBusUpdate = true;
    /// 重启次数
    private static int RestartCount = 0;
    #endregion

    #region 单例
    /// 核心单例对象引用
    protected static Core mInstance;

    /// 获取核心单例
    public static Core GetInstance()
    {
        if (mInstance == null)
            mInstance = new Core();
        return mInstance;
    }
    #endregion

    #region 构造函数
    public Core()
    {
    }
    #endregion

    /// 初始化各单例
    private void InitSingletons(ObjectArray clsList = null)
    {

        #region 预备即将初始化的各个管理器单例的类型列表
        var list = new List<Type>();
        if(RestartCount == 0)
        {
            list.Add(typeof(ObjectPoolManager));
            list.Add(typeof(GameObjectPoolManager));
            list.Add(typeof(FactoryManager));
            list.Add(typeof(ControllerManager));
            list.Add(typeof(NoticeManager));
            list.Add(typeof(DataProxyManager));
            list.Add(typeof(ComponentConfigManager));
            list.Add(typeof(StateMachineManager));
            list.Add(typeof(UIManager));
        }else
        {
            list.Add(typeof(ObjectPoolManager));
            list.Add(typeof(GameObjectPoolManager));
            list.Add(typeof(ControllerManager));
            list.Add(typeof(NoticeManager));
            list.Add(typeof(DataProxyManager));
            list.Add(typeof(ComponentConfigManager));
            list.Add(typeof(StateMachineManager));
            list.Add(typeof(UIManager));
        }
        #endregion

        int max = list.Count;
        ObjectArray types = new ObjectArray(max);
        for(int i = 0; i < max; i++)
        {
            types.Add(list[i]);
        }
        SingletonManager manager = SingletonManager.Manager;
        manager.AddSingleton(types);
        types.Release();

        if (clsList != null)
        {
            manager.AddSingleton(clsList);
            clsList.Release();
        }
    }

    /// 初始化各类型的工厂
    private void InitFactores(ObjectArray factories = null)
    {
        if (RestartCount > 0)
            return;

        FactoryManager manager = FactoryManager.Instance;

        manager.AddFactory(new ObjectArrayFactory());
        manager.AddFactory(new GameObjectFactory());

        if(factories != null)
        {
            int max = factories.ElementLength;
            for(int i = 0; i < max; i++)
                manager.AddFactory((IFactory)factories[i]);
            factories.Release();
        }
    }

    /// 运行内核
    /// <param name="main"></param>
    /// <param name="customSingletons"></param>
    /// <param name="customFactories"></param>
    public void Run(IApplication main, ObjectArray customSingletons = null, ObjectArray customFactories = null)
    {
        mApplication = main;
        mGameObject = mApplication.gameObject;

        InitSingletons(customSingletons);
        InitFactores(customFactories);
    }

    /// 获取当前应用脚本实体
    public static T GetMain<T>()
    {
        return (T)mApplication;
    }

    /// 关闭应用
    public void CloseUp(Action OnFinish = null)
    {
        mApplication.Notices.SendNotice(FConsts.FNOTICE_APPLICATION_EXITED);
        mApplication.ResetApplication();

        DontDestroyComponent.KillUndeads();

        SingletonManager.Manager.Dispose();

        mGameObject = null;
        mApplication = null;
        mInstance = null;

        RestartCount++;

        if (OnFinish != null)
            OnFinish.Invoke();

        GC.Collect();
    }
}


text:
class Ability
  include CanCan::Ability

  attr_accessor :user, :project

  def initialize(user, project=nil)
    @user = user
    @project = project

    live_updates_permissions

    if project.present?
      test_job_permissions
      test_run_permissions
      project_permissions
      tracked_branch_permissions
      project_participation_permissions
      project_files_permissions
      worker_group_permissions
    end
  end

  private

  def worker_group_permissions
    # TODO: Check if we should be more strict here.
    if user && project.members.include?(user)
      can :update, WorkerGroup, project_id: project.id
      can :create, WorkerGroup
      can :destroy, WorkerGroup, project_id: project.id
    end
  end

  def project_participation_permissions
    # Project owners can remove all users but themselves from a project
    if user.present?
      if project.user == user
        can :manage, ProjectParticipation, project_id: project.id
        cannot :destroy, ProjectParticipation, user_id: user.id
      elsif project.members.include?(user)
        can :read, ProjectParticipation, user_id: user.id
        can :destroy, ProjectParticipation, user_id: user.id
        can :update, ProjectParticipation, user_id: user.id
      end
    end
  end

  def project_files_permissions
    if user.present? && project.user == user
      can :manage, ProjectFile, project_id: project.id
    end

    if project.members.include?(user)
      can :read, ProjectFile, project_id: project.id
      can :update, ProjectFile, project_id: project.id
      can :destroy, ProjectFile, project_id: project.id
      can :create, ProjectFile, project_id: project.id
    end
  end

  def project_permissions
    if user.present? && project.user == user
      can :manage, project
    end

    if project.members.include?(user)
      can :read_docker_compose, project
      can :read_general_settings, project
      can :read, project
      can :update_own_notification_settings, project
      can :update, project
      can :update_worker_setup, project
    end

    if project.is_public?
      can :read, project
    end
  end

  def tracked_branch_permissions
    if user && project.members.include?(user)
      can :read, TrackedBranch, project_id: project.id
      can :create, TrackedBranch, project_id: project.id
      can :destroy, TrackedBranch, project_id: project.id
      can :untrack_branch, TrackedBranch, project_id: project.id
    end
  end

  def test_run_permissions
    can :read, TestRun if project.is_public?
    can :manage, TestRun if project.members.include?(user)
  end

  def test_job_permissions
    can :manage, TestJob if project.members.include?(user)
  end

  def live_updates_permissions
    can :read_live_updates, TestJob do |test_job|
      project = test_job.test_run.project
      project.members.include?(user) || project.is_public?
    end

    can :read_live_updates, TestRun do |test_run|
      project = test_run.project
      project.members.include?(user) || project.is_public?
    end

    can :read_live_updates, TrackedBranch do |branch|
      project = branch.project
      project.members.include?(user) || project.is_public?
    end

    can :read_live_updates, Project do |project|
      project.members.include?(user)
    end
  end
end


text:
<!DOCTYPE html>

<meta http-equiv="Content-Type" content="text/html;charset=utf-8">
<meta name="keywords" content="admin template, admin dashboard, inbox templte, calendar template, form validation">
<meta name="author" content="DazeinCreative">
<meta name="description" content="ORB - Powerfull and Massive Admin Dashboard Template with tonns of useful features">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>ORB | Form Plugins</title>

<link href="css/styles.css" rel="stylesheet" type="text/css">

<link rel="shortcut icon" type="image/x-icon" href="favicon.ico" />

 ORB

    <form action="#" id="inline-search">

      <input type="search" placeholder="Search">
    </form>

     Logged asAnton Durant

    <button type="button" class="btn btn-default hidden-xs pull-right" id="toggle-fullscreen">  </button>

      <button type="button" class="btn btn-default dropdown-toggle" data-toggle="dropdown"> </button>

Settings 6

                    <input type="checkbox" name="checkbox-toggle" checked>
                    Prevent Midnblow

                    <input type="checkbox" name="checkbox-toggle" checked>
                    Sleep All nights

                    <input type="checkbox" name="checkbox-toggle" checked>
                    Drink more Coffee

                    <input type="checkbox" name="checkbox-toggle" checked>
                    Auto feed cat

                    <input type="checkbox" name="checkbox-toggle" checked>
                    Dummy Checkbox

                    <input type="checkbox" name="checkbox-toggle" checked>
                    Read More Books

 Save

      <button type="button" class="btn btn-default dropdown-toggle" data-toggle="dropdown"> </button>

Notifications 8

Server Down

Server #435 was shut down (Power loss)

                   59 mins ago

Too Many Connections

Too many connections to Database Server

                   2 hours ago

Sausage Stolen

Someone stole your hot sausage

                   3 hours ago

Defragmentation Completed

Disc Defragmentation Completed on Server

                   3 hours ago

See All

      <button type="button" class="btn btn-default dropdown-toggle" data-toggle="dropdown"></button>

Inbox 32

Why don't u answer calls?

Listen, dude, time is off. I'll find you soon! Sounds good?...

                   59 mins ago

Rawrr, rawrrr...

Listen, dude, time is off. I'll find you soon! Sounds good?...

                   2 hours ago

Why so serious?

Listen, dude, time is off. I'll find you soon! Sounds good?...

                   3 hours ago

Save All

Main

Users

ToDo

Anton Durant Administrator

 Profile Settings Projects2

            Updates5 Messages12  Comments45

             Lock  Sign Out

                    <button type="button" class="btn btn-default">Friends</button>
                    <button type="button" class="btn btn-default">Work</button>
                    <button type="button" class="btn btn-default">Girls</button>

Gluck DorrisOnline5

Anton DurantOnline

SpidermanOnline

MuchuOffline

Mr. JokerOnline

ChewbaccaOnline

The PiggyOnline

Anton DurantOnline

SpidermanOnline

MuchuOnline

Anton DurantOnline

SpidermanOnline

MuchuOnline

Anton DurantOnline

SpidermanOnline

MuchuOnline

Anton DurantOffline

SpidermanOnline

MuchuOnline

                  <input id="new-todo" placeholder="Add ToDo" type="text" class="form-control">

                  <button id="add-todo" class="btn btn-default" type="button"></button>

ORB

 Dashboard

 Inbox 32

 Widgets

 Power Widgets

 Portlets

 Tables

 Tables

 Datatables

 Forms

 Forms

 Bootstrap Forms

 Form Plugins

 Form Validation

 Form Wizard

  Graph & Charts

 Morris Charts

 Flot Charts

 Others Charts

  Interface

 Typography

 Nestable

 Tree View

 Animation

 Components

 Elements

 Buttons

 Icons

 Awesome

 Glyphicons

 Entypo

  Pages

 MegaMenu New!

 Timeline

 Profile

 Gallery

 Items List

 Pricelists

 Forum

 Chat

 404 Error

 500 Error

 Login Page

 Carte blanche

 Calendar

 Search Results

 Invoice

  Maps

 Google Maps

 Vector Maps

 Front End Soon

10,8,8,7,8,9,7,8,10,9,7,5

project income

$23989

5,6,7,9,9,5,3,2,9,4,6,7

site traffic

122541

9,6,7,9,3,5,7,2,1,8,6,7

Processes

890

10,8,8,7,8,9,7,8,10,9,7,5

orders

$23989

1,2,3

active/new

500/200

3:6,2:8,8:4,5:8,3:6,9:4,8:1,5:7,4:8,9:5,3:5

fault/success

$23989

Dashboard

Data

FormsElements

X-EditablesAJAX Inline Edit

                <input type="checkbox" id="autoopen" style="vertical-align: baseline">
                 auto-open next field
              <button id="enable" class="btn btn-default">Enable / Disable</button>

                  Simple text field
                  superuser

                  Empty text field, required

                  Select, local array, custom display

                  Select, remote array, no buttons
                  Admin

                  Select, error while loading
                  Active

                  Combodate (date)

                  Combodate (datetime)

                  Textarea, buttons below. Submit by ctrl+enter
                  awesome
                    user!

                  Twitter typeahead.js

                  Checklist

                  Select2 (tags mode)
                  html, javascript

                  Select2 (dropdown mode)

                  Custom input, several fields

ORB Range SliderIon Range Slider

                <input type="text" id="ionrange_1" />

                <input type="text" id="ionrange_2" />

                <input type="text" id="ionrange_3" />

                <input type="text" id="ionrange_4" />

                <input type="text" id="ionrange_5" />

                <input type="text" id="ionrange_6" />

                <input type="text" id="ionrange_7" />

Inputs MaskingAvailable Masks

                <form action="" id="input-masking" class="orb-form">
                  <fieldset>

                      Date masking

                        <input type="text" name="date" id="date2">

                      Phone masking

                        <input type="tel" name="phone" id="phone">

                      Credit card masking

                        <input type="text" name="card" id="card">

                      Serial number masking

                        <input type="text" name="serial" id="serial">

                      Tax ID masking

                        <input type="text" name="tax" id="tax">

                  </fieldset>

                    <button type="submit" class="btn btn-default">Submit</button>
                    <button type="button" class="btn btn-default" onclick="window.history.back();">Back</button>

                </form>

Knob Dialwith Graph controls

                      <input class="knob" data-width="120" data-displayInput="false" data-fgColor="#5bc0de" data-thickness=".4" value="35">

                      <input class="knob2" data-width="120" data-cursor="true" data-bgColor="#969fa1" data-fgColor="#595f66" data-thickness=".4" value="29">

                      <input class="knob3" data-width="120" data-min="-100" data-fgColor="#f87aa0" data-thickness=".4" data-displayPrevious="true" value="44">

                      <input class="knob4" data-width="120" data-angleOffset="90" data-fgColor="#d24d33" data-thickness=".4" data-linecap="round" value="35">

                      <input class="knob5" data-width="120" data-angleOffset="-125" data-thickness=".4" data-angleArc="250" data-bgColor="#f4cc13" data-fgColor="#f0ad4e" data-rotation="anticlockwise" value="35">

                      <input class="knob6" data-width="120" data-fgColor="#969fa1" data-thickness=".4" readonly value="22">

UI SliderRange Slider

                <form action="" id="ui-sliders-form" class="orb-form">
                  <fieldset>

                      Regular slider (0)

                      Range slider (75 - 300)

                      Step slider (0)

                  </fieldset>

                    <button type="submit" class="btn btn-default">Send</button>

                </form>

Date PickersDate pickers

                <form action="" id="data-pickers" class="orb-form">
                  <fieldset>

                      Select single date

                        <input type="text" name="date" id="date">

                    Select date range

                          <input type="text" name="start" id="start" placeholder="Start date">

                          <input type="text" name="finish" id="finish" placeholder="Expected finish date">

                  </fieldset>
                  <fieldset>

                      Select single date with inline datepicker

                    Select date range with inline datepickers

                  </fieldset>

                    <button type="submit" class="btn btn-default">Send</button>
                    <button type="button" class="btn btn-default" onclick="window.history.back();">Back</button>

                </form>

        <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>

Are you sure to delete this widget?

        <button type="button" class="btn btn-default" data-dismiss="modal" id="trigger-deletewidget-reset">Cancel</button>
        <button type="button" class="btn btn-primary" id="trigger-deletewidget">Delete</button>

        <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>

Are You Sure Want To Sign Out?

        <button type="button" class="btn btn-default" id="yesigo">Ok</button>
        <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>

        <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>

Are You Sure Want To Lock Screen?

        <button type="button" class="btn btn-default" id="yesilock">Ok</button>
        <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>


text:
package http

import (
	"compress/gzip"
	"context"
	"errors"
	"fmt"
	"io"
	"io/ioutil"
	"net/http"

	"github.com/influxdata/httprouter"
	"github.com/influxdata/influxdb/v2"
	pcontext "github.com/influxdata/influxdb/v2/context"
	"github.com/influxdata/influxdb/v2/http/metric"
	kitio "github.com/influxdata/influxdb/v2/kit/io"
	"github.com/influxdata/influxdb/v2/kit/tracing"
	kithttp "github.com/influxdata/influxdb/v2/kit/transport/http"
	"github.com/influxdata/influxdb/v2/models"
	"github.com/influxdata/influxdb/v2/storage"
	"github.com/influxdata/influxdb/v2/tsdb"
	"github.com/opentracing/opentracing-go"
	"go.uber.org/zap"
	"istio.io/pkg/log"
)

var (
	// ErrMaxBatchSizeExceeded is returned when a points batch exceeds
	// the defined upper limit in bytes. This pertains to the size of the
	// batch after inflation from any compression (i.e. ungzipped).
	ErrMaxBatchSizeExceeded = errors.New("points batch is too large")
)

// WriteBackend is all services and associated parameters required to construct
// the WriteHandler.
type WriteBackend struct {
	influxdb.HTTPErrorHandler
	log                *zap.Logger
	WriteEventRecorder metric.EventRecorder

	PointsWriter        storage.PointsWriter
	BucketService       influxdb.BucketService
	OrganizationService influxdb.OrganizationService
}

// NewWriteBackend returns a new instance of WriteBackend.
func NewWriteBackend(log *zap.Logger, b *APIBackend) *WriteBackend {
	return &WriteBackend{
		HTTPErrorHandler:   b.HTTPErrorHandler,
		log:                log,
		WriteEventRecorder: b.WriteEventRecorder,

		PointsWriter:        b.PointsWriter,
		BucketService:       b.BucketService,
		OrganizationService: b.OrganizationService,
	}
}

// WriteHandler receives line protocol and sends to a publish function.
type WriteHandler struct {
	influxdb.HTTPErrorHandler
	BucketService       influxdb.BucketService
	OrganizationService influxdb.OrganizationService
	PointsWriter        storage.PointsWriter
	EventRecorder       metric.EventRecorder

	router            *httprouter.Router
	log               *zap.Logger
	maxBatchSizeBytes int64
	parserOptions     []models.ParserOption
}

// WriteHandlerOption is a functional option for a *WriteHandler
type WriteHandlerOption func(*WriteHandler)

// WithMaxBatchSizeBytes configures the maximum size for a
// (decompressed) points batch allowed by the write handler
func WithMaxBatchSizeBytes(n int64) WriteHandlerOption {
	return func(w *WriteHandler) {
		w.maxBatchSizeBytes = n
	}
}

func WithParserOptions(opts ...models.ParserOption) WriteHandlerOption {
	return func(w *WriteHandler) {
		w.parserOptions = opts
	}
}

// Prefix provides the route prefix.
func (*WriteHandler) Prefix() string {
	return prefixWrite
}

const (
	prefixWrite              = "/api/v2/write"
	msgInvalidGzipHeader     = "gzipped HTTP body contains an invalid header"
	msgInvalidPrecision      = "invalid precision; valid precision units are ns, us, ms, and s"
	msgUnableToReadData      = "unable to read data"
	msgWritingRequiresPoints = "writing requires points"
	msgUnexpectedWriteError  = "unexpected error writing points to database"

	opPointsWriter = "http/pointsWriter"
	opWriteHandler = "http/writeHandler"
)

// NewWriteHandler creates a new handler at /api/v2/write to receive line protocol.
func NewWriteHandler(log *zap.Logger, b *WriteBackend, opts ...WriteHandlerOption) *WriteHandler {
	h := &WriteHandler{
		HTTPErrorHandler:    b.HTTPErrorHandler,
		PointsWriter:        b.PointsWriter,
		BucketService:       b.BucketService,
		OrganizationService: b.OrganizationService,
		EventRecorder:       b.WriteEventRecorder,

		router: NewRouter(b.HTTPErrorHandler),
		log:    log,
	}

	for _, opt := range opts {
		opt(h)
	}

	h.router.HandlerFunc(http.MethodPost, prefixWrite, h.handleWrite)
	return h
}

func (h *WriteHandler) findBucket(ctx context.Context, orgID influxdb.ID, bucket string) (*influxdb.Bucket, error) {
	if id, err := influxdb.IDFromString(bucket); err == nil {
		b, err := h.BucketService.FindBucket(ctx, influxdb.BucketFilter{
			OrganizationID: &orgID,
			ID:             id,
		})
		if err != nil && influxdb.ErrorCode(err) != influxdb.ENotFound {
			return nil, err
		} else if err == nil {
			return b, err
		}
	}

	return h.BucketService.FindBucket(ctx, influxdb.BucketFilter{
		OrganizationID: &orgID,
		Name:           &bucket,
	})
}

func (h *WriteHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	h.router.ServeHTTP(w, r)
}

func (h *WriteHandler) handleWrite(w http.ResponseWriter, r *http.Request) {
	span, r := tracing.ExtractFromHTTPRequest(r, "WriteHandler")
	defer span.Finish()

	ctx := r.Context()
	auth, err := pcontext.GetAuthorizer(ctx)
	if err != nil {
		h.HandleHTTPError(ctx, err, w)
		return
	}

	req, err := decodeWriteRequest(ctx, r, h.maxBatchSizeBytes)
	if err != nil {
		h.HandleHTTPError(ctx, err, w)
		return
	}

	org, err := queryOrganization(ctx, r, h.OrganizationService)
	if err != nil {
		h.HandleHTTPError(ctx, err, w)
		return
	}
	span.LogKV("org_id", org.ID)

	sw := kithttp.NewStatusResponseWriter(w)
	recorder := NewWriteUsageRecorder(sw, h.EventRecorder)
	var requestBytes int
	defer func() {
		// Close around the requestBytes variable to placate the linter.
		recorder.Record(ctx, requestBytes, org.ID, r.URL.Path)
	}()

	bucket, err := h.findBucket(ctx, org.ID, req.Bucket)
	if err != nil {
		h.HandleHTTPError(ctx, err, sw)
		return
	}
	span.LogKV("bucket_id", bucket.ID)

	if err := checkBucketWritePermissions(auth, org.ID, bucket.ID); err != nil {
		h.HandleHTTPError(ctx, err, sw)
		return
	}

	opts := append([]models.ParserOption{}, h.parserOptions...)
	opts = append(opts, models.WithParserPrecision(req.Precision))
	parsed, err := NewPointsParser(opts...).ParsePoints(ctx, org.ID, bucket.ID, req.Body)
	if err != nil {
		h.HandleHTTPError(ctx, err, sw)
		return
	}
	requestBytes = parsed.RawSize

	if err := h.PointsWriter.WritePoints(ctx, parsed.Points); err != nil {
		h.HandleHTTPError(ctx, &influxdb.Error{
			Code: influxdb.EInternal,
			Op:   opWriteHandler,
			Msg:  "unexpected error writing points to database",
			Err:  err,
		}, sw)
		return
	}

	sw.WriteHeader(http.StatusNoContent)
}

// checkBucketWritePermissions checks an Authorizer for write permissions to a
// specific Bucket.
func checkBucketWritePermissions(auth influxdb.Authorizer, orgID, bucketID influxdb.ID) error {
	p, err := influxdb.NewPermissionAtID(bucketID, influxdb.WriteAction, influxdb.BucketsResourceType, orgID)
	if err != nil {
		return &influxdb.Error{
			Code: influxdb.EInternal,
			Op:   opWriteHandler,
			Msg:  fmt.Sprintf("unable to create permission for bucket: %v", err),
			Err:  err,
		}
	}
	if pset, err := auth.PermissionSet(); err != nil || !pset.Allowed(*p) {
		return &influxdb.Error{
			Code: influxdb.EForbidden,
			Op:   opWriteHandler,
			Msg:  "insufficient permissions for write",
			Err:  err,
		}
	}
	return nil
}

// PointBatchReadCloser (potentially) wraps an io.ReadCloser in Gzip
// decompression and limits the reading to a specific number of bytes.
func PointBatchReadCloser(rc io.ReadCloser, encoding string, maxBatchSizeBytes int64) (io.ReadCloser, error) {
	switch encoding {
	case "gzip", "x-gzip":
		var err error
		rc, err = gzip.NewReader(rc)
		if err != nil {
			return nil, err
		}
	}
	if maxBatchSizeBytes > 0 {
		rc = kitio.NewLimitedReadCloser(rc, maxBatchSizeBytes)
	}
	return rc, nil
}

// NewPointsParser returns a new PointsParser
func NewPointsParser(parserOptions ...models.ParserOption) *PointsParser {
	return &PointsParser{
		ParserOptions: parserOptions,
	}
}

// ParsedPoints contains the points parsed as well as the total number of bytes
// after decompression.
type ParsedPoints struct {
	Points  models.Points
	RawSize int
}

// PointsParser parses batches of Points.
type PointsParser struct {
	ParserOptions []models.ParserOption
}

// ParsePoints parses the points from an io.ReadCloser for a specific Bucket.
func (pw *PointsParser) ParsePoints(ctx context.Context, orgID, bucketID influxdb.ID, rc io.ReadCloser) (*ParsedPoints, error) {
	span, ctx := opentracing.StartSpanFromContext(ctx, "write points")
	defer span.Finish()
	return pw.parsePoints(ctx, orgID, bucketID, rc)
}

func (pw *PointsParser) parsePoints(ctx context.Context, orgID, bucketID influxdb.ID, rc io.ReadCloser) (*ParsedPoints, error) {
	data, err := readAll(ctx, rc)
	if err != nil {
		code := influxdb.EInternal
		if errors.Is(err, ErrMaxBatchSizeExceeded) {
			code = influxdb.ETooLarge
		} else if errors.Is(err, gzip.ErrHeader) || errors.Is(err, gzip.ErrChecksum) {
			code = influxdb.EInvalid
		}
		return nil, &influxdb.Error{
			Code: code,
			Op:   opPointsWriter,
			Msg:  msgUnableToReadData,
			Err:  err,
		}
	}

	requestBytes := len(data)
	if requestBytes == 0 {
		return nil, &influxdb.Error{
			Op:   opPointsWriter,
			Code: influxdb.EInvalid,
			Msg:  msgWritingRequiresPoints,
		}
	}

	span, _ := tracing.StartSpanFromContextWithOperationName(ctx, "encoding and parsing")
	encoded := tsdb.EncodeName(orgID, bucketID)
	mm := models.EscapeMeasurement(encoded[:])

	points, err := models.ParsePointsWithOptions(data, mm, pw.ParserOptions...)
	span.LogKV("values_total", len(points))
	span.Finish()
	if err != nil {
		log.Error("Error parsing points", zap.Error(err))

		code := influxdb.EInvalid
		if errors.Is(err, models.ErrLimitMaxBytesExceeded) ||
			errors.Is(err, models.ErrLimitMaxLinesExceeded) ||
			errors.Is(err, models.ErrLimitMaxValuesExceeded) {
			code = influxdb.ETooLarge
		}

		return nil, &influxdb.Error{
			Code: code,
			Op:   opPointsWriter,
			Msg:  "",
			Err:  err,
		}
	}

	return &ParsedPoints{
		Points:  points,
		RawSize: requestBytes,
	}, nil
}

func readAll(ctx context.Context, rc io.ReadCloser) (data []byte, err error) {
	defer func() {
		if cerr := rc.Close(); cerr != nil && err == nil {
			if errors.Is(cerr, kitio.ErrReadLimitExceeded) {
				cerr = ErrMaxBatchSizeExceeded
			}
			err = cerr
		}
	}()

	span, _ := tracing.StartSpanFromContextWithOperationName(ctx, "read request body")

	defer func() {
		span.LogKV("request_bytes", len(data))
		span.Finish()
	}()

	data, err = ioutil.ReadAll(rc)
	if err != nil {
		return nil, err

	}
	return data, nil
}

// writeRequest is a request object holding information about a batch of points
// to be written to a Bucket.
type writeRequest struct {
	Org       string
	Bucket    string
	Precision string
	Body      io.ReadCloser
}

// decodeWriteRequest extracts information from an http.Request object to
// produce a writeRequest.
func decodeWriteRequest(ctx context.Context, r *http.Request, maxBatchSizeBytes int64) (*writeRequest, error) {
	qp := r.URL.Query()
	precision := qp.Get("precision")
	if precision == "" {
		precision = "ns"
	}

	if !models.ValidPrecision(precision) {
		return nil, &influxdb.Error{
			Code: influxdb.EInvalid,
			Op:   "http/newWriteRequest",
			Msg:  msgInvalidPrecision,
		}
	}

	bucket := qp.Get("bucket")
	if bucket == "" {
		return nil, &influxdb.Error{
			Code: influxdb.ENotFound,
			Op:   "http/newWriteRequest",
			Msg:  "bucket not found",
		}
	}

	encoding := r.Header.Get("Content-Encoding")
	body, err := PointBatchReadCloser(r.Body, encoding, maxBatchSizeBytes)
	if err != nil {
		return nil, err
	}

	return &writeRequest{
		Bucket:    qp.Get("bucket"),
		Org:       qp.Get("org"),
		Precision: precision,
		Body:      body,
	}, nil
}

// WriteService sends data over HTTP to influxdb via line protocol.
type WriteService struct {
	Addr               string
	Token              string
	Precision          string
	InsecureSkipVerify bool
}

var _ influxdb.WriteService = (*WriteService)(nil)

func (s *WriteService) Write(ctx context.Context, orgID, bucketID influxdb.ID, r io.Reader) error {
	precision := s.Precision
	if precision == "" {
		precision = "ns"
	}

	if !models.ValidPrecision(precision) {
		return &influxdb.Error{
			Code: influxdb.EInvalid,
			Op:   "http/Write",
			Msg:  msgInvalidPrecision,
		}
	}

	u, err := NewURL(s.Addr, prefixWrite)
	if err != nil {
		return err
	}

	r, err = compressWithGzip(r)
	if err != nil {
		return err
	}

	req, err := http.NewRequestWithContext(ctx, http.MethodPost, u.String(), r)
	if err != nil {
		return err
	}

	req.Header.Set("Content-Type", "text/plain; charset=utf-8")
	req.Header.Set("Content-Encoding", "gzip")
	SetToken(s.Token, req)

	org, err := orgID.Encode()
	if err != nil {
		return err
	}

	bucket, err := bucketID.Encode()
	if err != nil {
		return err
	}

	params := req.URL.Query()
	params.Set("org", string(org))
	params.Set("bucket", string(bucket))
	params.Set("precision", string(precision))
	req.URL.RawQuery = params.Encode()

	hc := NewClient(u.Scheme, s.InsecureSkipVerify)

	resp, err := hc.Do(req)
	if err != nil {
		return err
	}
	defer resp.Body.Close()

	return CheckError(resp)
}

func compressWithGzip(data io.Reader) (io.Reader, error) {
	pr, pw := io.Pipe()
	gw := gzip.NewWriter(pw)
	var err error

	go func() {
		_, err = io.Copy(gw, data)
		gw.Close()
		pw.Close()
	}()

	return pr, err
}


text:
let configuration = {};

export function configure(settings) {
  configuration = settings;
}

export default function getConfig() {
  return configuration;
}


text:
const { vec3 } = require('../../../math')

const { geom3, poly3 } = require('../../../geometry')

const intersectGeom3Sub = require('../../booleans/intersectGeom3Sub')

const calculatePlane = require('./calculatePlane')

const toPolygon3D = (vector, edge) => {
  const points = [
    vec3.subtract(edge[0], vector),
    vec3.subtract(edge[1], vector),
    vec3.add(edge[1], vector),
    vec3.add(edge[0], vector)
  ]
  return poly3.fromPoints(points)
}

/**
 * Calculate the plane of the given slice.
 * NOTE: The points are assumed to be planar from the beginning.
 * @param {slice} slice - the slice
 * @returns {plane} the plane of the slice
 * @example
 * let myplane = toPlane(slice)
 */
const toPolygons = (slice) => {
  const splane = calculatePlane(slice)

  // find the midpoint of the slice, which will lie on the plane by definition
  const edges = slice.edges
  const midpoint = edges.reduce((point, edge) => vec3.add(point, edge[0]), vec3.create())
  vec3.scale(midpoint, 1 / edges.length, midpoint)

  // find the farthest edge from the midpoint, which will be on an outside edge
  let farthestEdge = [[NaN, NaN, NaN], [NaN, NaN, NaN]]
  let distance = 0
  edges.forEach((edge) => {
    let d = vec3.squaredDistance(midpoint, edge[0])
    if (d > distance) {
      farthestEdge = edge
      distance = d
    }
  })

  // create one LARGE polygon to encompass the side, i.e. base
  const direction = vec3.subtract(farthestEdge[0], midpoint)
  const perpendicular = vec3.cross(splane, direction)

  const p1 = vec3.add(midpoint, direction)
  vec3.add(p1, p1, direction)
  const p2 = vec3.add(midpoint, perpendicular)
  vec3.add(p2, p2, perpendicular)
  const p3 = vec3.subtract(midpoint, direction)
  vec3.subtract(p3, p3, direction)
  const p4 = vec3.subtract(midpoint, perpendicular)
  vec3.subtract(p4, p4, perpendicular)
  const poly1 = poly3.fromPoints([p1, p2, p3, p4])
  const base = geom3.create([poly1])

  const wallPolygons = edges.map((edge) => toPolygon3D(splane, edge))
  const walls = geom3.create(wallPolygons)

  // make an insection of the base and the walls, creating... a set of polygons!
  const geometry3 = intersectGeom3Sub(base, walls)

  // return only those polygons from the base
  let polygons = geom3.toPolygons(geometry3)
  polygons = polygons.filter((polygon) => {
    let a = vec3.angle(splane, polygon.plane)
    // walls should be PI / 2 radians rotated from the base
    return Math.abs(a) < (Math.PI / 90)
  })
  return polygons
}

module.exports = toPolygons


text:
<!DOCTYPE html>

	<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
	<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
	<title>Feedback</title>
	<meta name="viewport" content="width=device-width,initial-scale=1">
	<meta name="apple-mobile-web-app-capable" content="yes"/>
	<link rel="stylesheet" href="css/font-awesome.min.css">
	<link rel="stylesheet" href="css/settings.css" type="text/css"/>

			Feedback

				 Book list
				 Settings
				 Exit


text:
package java2typescript.jackson.module.writer;

import java.io.IOException;
import java.io.Writer;

import java2typescript.jackson.module.grammar.base.AbstractNamedType;

/**
 * Class implementing this interface can be used to customize how Java type is written to TypeScript
 * @author Ats Uiboupin
 */
public interface CustomAbstractTypeWriter {
	/**
	 * @return true if this class should handle writing the type to {@link Writer}
	 */
	boolean accepts(AbstractNamedType type, WriterPreferences preferences);

	void writeDef(AbstractNamedType type, Writer writer, WriterPreferences preferences) throws IOException;
}


text:
package com.tremolosecurity.provisioning.service;

import static org.apache.directory.ldap.client.api.search.FilterBuilder.equal;

import java.io.IOException;
import java.net.MalformedURLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.logging.log4j.Logger;

import com.google.gson.Gson;
import com.novell.ldap.LDAPAttribute;
import com.novell.ldap.LDAPAttributeSet;
import com.novell.ldap.LDAPEntry;
import com.novell.ldap.LDAPSearchResults;
import com.tremolosecurity.config.util.ConfigManager;
import com.tremolosecurity.config.xml.AzRuleType;
import com.tremolosecurity.config.xml.OrgType;
import com.tremolosecurity.config.xml.PortalUrlType;
import com.tremolosecurity.config.xml.PortalUrlsType;
import com.tremolosecurity.config.xml.ReportType;
import com.tremolosecurity.config.xml.ReportsType;
import com.tremolosecurity.provisioning.core.ProvisioningException;
import com.tremolosecurity.provisioning.service.util.Organization;
import com.tremolosecurity.provisioning.service.util.PortalURL;
import com.tremolosecurity.provisioning.service.util.PortalURLs;
import com.tremolosecurity.provisioning.service.util.ProvisioningError;
import com.tremolosecurity.provisioning.service.util.ProvisioningResult;
import com.tremolosecurity.provisioning.service.util.ReportInformation;
import com.tremolosecurity.provisioning.service.util.ReportResults;
import com.tremolosecurity.provisioning.service.util.ReportsList;
import com.tremolosecurity.proxy.auth.AuthInfo;
import com.tremolosecurity.proxy.auth.AzSys;
import com.tremolosecurity.proxy.az.AzRule;
import com.tremolosecurity.saml.Attribute;
import com.tremolosecurity.server.GlobalEntries;

public class ListReports extends HttpServlet {

	/**
	 *
	 */
	private static final long serialVersionUID = -6421832979913478507L;
	static Logger logger = org.apache.logging.log4j.LogManager.getLogger(ListReports.class.getName());

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		String userID = req.getParameter("uid");
		String uidAttr = req.getParameter("uidAttr");

		try {
			StringBuffer b = new StringBuffer();

			LDAPSearchResults res = GlobalEntries.getGlobalEntries().getConfigManager().getMyVD().search(GlobalEntries.getGlobalEntries().getConfigManager().getCfg().getLdapRoot(), 2, equal(uidAttr,userID).toString(), new ArrayList<String>());
			if (! res.hasMore()) {
				throw new ProvisioningException("Could not locate user '" + userID + "'");
			}
			LDAPEntry entry = res.next();

			AuthInfo auinfo = new AuthInfo();
			auinfo.setUserDN(entry.getDN());
			LDAPAttributeSet attrs = entry.getAttributeSet();
			for (Object obj : attrs) {
				LDAPAttribute attr = (LDAPAttribute) obj;

				Attribute attrib = new Attribute(attr.getName());
				String[] vals = attr.getStringValueArray();
				for (String val : vals) {
					attrib.getValues().add(val);
				}

				auinfo.getAttribs().put(attrib.getName(), attrib);
			}

			AzSys az = new AzSys();

			HashSet<String> allowedOrgs = new HashSet<String>();
			OrgType root = GlobalEntries.getGlobalEntries().getConfigManager().getCfg().getProvisioning().getOrg();

			this.checkOrg(allowedOrgs, root, az, auinfo);

			ReportsType reports = GlobalEntries.getGlobalEntries().getConfigManager().getCfg().getProvisioning().getReports();

			ReportsList reportsList = new ReportsList();
			reportsList.setReports(new ArrayList<ReportInformation>());

			for (ReportType report : reports.getReport()) {
				if (allowedOrgs.contains(report.getOrgID())) {
					ReportInformation ri = new ReportInformation();
					ri.setName(report.getName());
					ri.setDescription(report.getDescription());
					ri.setOrgID(report.getOrgID());
					ri.setParameters(new ArrayList<String>());
					ri.getParameters().addAll(report.getParamater());

					reportsList.getReports().add(ri);
				}
			}

			Gson gson = new Gson();

			ProvisioningResult pres = new ProvisioningResult();
			pres.setSuccess(true);
			pres.setReportsList(reportsList);

			resp.getOutputStream().print(gson.toJson(pres));
		} catch (Exception e) {
			ProvisioningError pe = new ProvisioningError();
			pe.setError("Could not load urls : " + e.getMessage());
			ProvisioningResult res = new ProvisioningResult();
			res.setSuccess(false);
			res.setError(pe);
			Gson gson = new Gson();

			resp.getWriter().write(gson.toJson(res));
			logger.error("Could not load urls",e);
		}
	}

	private void checkOrg(HashSet<String> allowedOrgs,OrgType ot, AzSys az, AuthInfo auinfo) throws MalformedURLException, ProvisioningException {
		ConfigManager cfgMgr = GlobalEntries.getGlobalEntries().getConfigManager();

		if (ot.getAzRules() != null && ot.getAzRules().getRule().size() > 0) {
			ArrayList<AzRule> rules = new ArrayList<AzRule>();

			for (AzRuleType art : ot.getAzRules().getRule()) {
				rules.add(new AzRule(art.getScope(),art.getConstraint(),art.getClassName(),cfgMgr,null));
			}

			if (! az.checkRules(auinfo, cfgMgr, rules,null)) {
				return;
			}
		}

		allowedOrgs.add(ot.getUuid());

		for (OrgType child : ot.getOrgs()) {
			checkOrg(allowedOrgs,child, az, auinfo);
		}
	}

}


text:
<?php

// autoload.php @generated by Composer

require_once __DIR__ . '/composer' . '/autoload_real.php';

return ComposerAutoloaderInit11a29cb343480d5f9718d213ff345290::getLoader();


text:
using System;

namespace Telerik.Data.Core.Fields
{
    /// <summary>
    /// A base class for various implementations of <see cref="IFieldDescriptionProvider"/>.
    /// </summary>
    internal abstract class FieldDescriptionProviderBase : IFieldDescriptionProvider
    {
        /// <summary>
        /// Initializes a new instance of the <see cref="FieldDescriptionProviderBase"/> class.
        /// </summary>
        protected FieldDescriptionProviderBase()
        {
        }

        /// <inheritdoc />
        public event EventHandler<GetDescriptionsDataCompletedEventArgs> GetDescriptionsDataAsyncCompleted;

        /// <inheritdoc />
        public bool IsBusy { get; protected set; }

        /// <summary>
        /// Gets a value indicating whether the provider is ready to be used. That is, to not be Busy and to be properly initialized.
        /// </summary>
        public abstract bool IsReady { get; }

        internal abstract bool IsDynamic { get; }

        /// <inheritdoc />
        public abstract void GetDescriptionsDataAsync(object state);

        /// <summary>
        /// Raise GetDescriptionsDataAsyncCompleted event.
        /// </summary>
        /// <param name="args">The event args used to invoke the event.</param>
        protected virtual void OnDescriptionsDataCompleted(GetDescriptionsDataCompletedEventArgs args)
        {
            this.IsBusy = false;

            if (this.GetDescriptionsDataAsyncCompleted != null)
            {
                this.GetDescriptionsDataAsyncCompleted(this, args);
            }
        }
    }
}


text:
extern crate regex;
extern crate getopts;

#[macro_use(try_read_lines)]
extern crate lines;

use std::env;
use std::fs::File;
use std::io::{Write, stderr, stdout};
use std::io::Result as IoResult;
use std::process;

use getopts::Options;

use regex::Regex;
use lines::linereader::LineReader;

fn main() {
    let (cfg, files) = match Config::from_cmdline(env::args().collect()) {
        Ok(cfg) => cfg,
        Err(e) => {
            let _ = stderr().write_all(e.as_ref());
            process::exit(1);
        }
    };
    for file in files {
        if let Err(e) = process_arg(&cfg, &file) {
            let _ = write!(&mut stderr(), "{}", e);
            process::exit(1);
        }
    }
}

// --------------------------------------------------------------------

struct Config {
    print_line_numbers: bool,
    print_filenames: bool,
    line_regex: Regex,
}

impl Config {
    fn from_cmdline(args: Vec<String>) -> Result<(Config, Vec<String>), String> {
        let mut opts = Options::new();
        opts.optflag("h", "help", "print this help screen");
        opts.optflag("n", "line-numbers", "print line numbers");
        opts.optflag("f", "filename", "print file name");
        opts.optopt("e", "entry", "identify regular lines", "regex");

        let matches = match opts.parse(&args[1..]) {
            Ok(m) => m,
            Err(f) => { return Err(format!("{}", f)); }
        };
        if matches.opt_present("h") || matches.free.len() < 1 {
            return Err(opts.usage("usage: [OPTIONS] <logfile> [<logfile> ...]"));
        }
        let re = {
            let s = matches.opt_str("e").unwrap_or_else(|| {
                r"^\d{4}-\d{2}-\d{2}\s+".to_owned()
            });
            match Regex::new(&s) {
                Ok(r) => r,
                Err(e) => { return Err(format!("{}", e)); }
            }
        };
        Ok((Config {
            print_line_numbers: matches.opt_present("n"),
            print_filenames: matches.opt_present("f"),
            line_regex: re
           },
           matches.free))
    }
}

// --------------------------------------------------------------------

const NEWLINE: &'static [u8] = &[b'\n'];
const SPACE: &'static [u8] = &[b' '];

fn process_arg(cfg: &Config, filename: &str) -> IoResult<()> {
    let f = try!(File::open(filename));

    let mut block = Vec::with_capacity(1024);
    let stdout = stdout();
    let mut stdout = stdout.lock();

    let mut line_no = 0usize;
    let mut collecting_block = false;
    let mut output_produced = false;

    // ~ Collect blocks of lines beloning together and spill them out.
    // ~ A block is defined by two or multiple successive lines of
    // which on the first matches the configured regular expression.
    try_read_lines!(line in LineReader::new(f), {
        line_no += 1;
        if cfg.line_regex.is_match(&String::from_utf8_lossy(line)) {
            if collecting_block {
                // ~ abort as soon as possible if the write didn't
                // succeed e.g. broken pipe
                try!(stdout.write_all(&block));
                output_produced = true;
                collecting_block = false;
            }

            // block.clear();
            unsafe { block.set_len(0); }

            if output_produced {
                let _ = block.write_all(NEWLINE);
            }
        } else {
            collecting_block = true;
        }

        // XXX prevent the buffer from becoming too large by flushing
        // it out as of a certain size

        if cfg.print_filenames {
            let _ = block.write_all(filename.as_ref());
            let _ = block.write_all(SPACE);
        }
        if cfg.print_line_numbers {
            let _ = write!(&mut block, "{:7} ", line_no);
        }
        let _ = block.write_all(line);
    });
    Ok(())
}


text:
using Microsoft.AspNetCore.Http;
using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.AspNetCore;
using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.DependencyInjection;

namespace Coral.Common.Web
{
    public static class HttpContext
    {
        private static HttpContextAccessor _accessor;

        public static Microsoft.AspNetCore.Http.HttpContext Current => _accessor.HttpContext;

        internal static void Configure(IHttpContextAccessor accessor)
        {
            // todo 变异错误,强转了下
            _accessor = accessor as HttpContextAccessor;
        }
    }

    public static class StaticHttpContextExtensions
    {
        public static void AddHttpContextAccessor(this IServiceCollection services)
        {
            services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
        }

        public static IApplicationBuilder UseStaticHttpContext(this IApplicationBuilder app)
        {
            var httpContextAccessor = app.ApplicationServices.GetRequiredService<IHttpContextAccessor>();
            HttpContext.Configure(httpContextAccessor);
            return app;
        }
    }
}


text:
/*
    GF100-optimized variant of the "Speculative while-while"
    kernel used in:

    "Understanding the Efficiency of Ray Traversal on GPUs",
    Timo Aila and Samuli Laine,
    Proc. High-Performance Graphics 2009
*/

#pragma once
#include <cuda.h>
#include <cuda_runtime.h>
#include <device_launch_parameters.h>
#include "CudaTracerDefines.h"
#ifdef __CUDACC__
#include <assert.h>
#include <stdio.h>
#include "../../helper_math.h"
#include <math_constants.h>
#endif

//------------------------------------------------------------------------
// Generic macros
//------------------------------------------------------------------------

#define WARP_SIZE 32
#define STR_VALUE(arg) #arg
#define STR(arg) STR_VALUE(arg)

//------------------------------------------------------------------------
// Debugging macros
//------------------------------------------------------------------------

//#define KEEP_ALL_TASKS // Each task is saved to a different location so that they are all visible afterwards
//#define DEBUG_INFO // Enables gathering of statistics for each task
#define COUNT_NODES // Enables gathering of emited number of nodes
//#define ONE_WARP_RUN
//#define DEBUG_PPS
#define TRAVERSAL_TEST
//#define LEAF_HISTOGRAM
//#define ONDEMAND_FULL_BUILD // Build entire data structure in the ondemand kernel - for overhead timing purpouses

//#define DIVERGENCE_TEST // Test whether all threads in a warp run in a lockstep

//#define SNAPSHOT_POOL 10000
//#define SNAPSHOT_WARP 3000

//#define COUNT_STEPS_LEFT
//#define COUNT_STEPS_RIGHT
//#define COUNT_STEPS_CACHE
//#define COUNT_STEPS_DEQUEUE
//#define COUNT_STEPS_ALLOC

#define WAIT_COUNT 100000 // How long should a warp wait before it assumes it is deadlocked

//------------------------------------------------------------------------
// Optimizations macros
//------------------------------------------------------------------------

#define ACTIVE_MAX (32*WARP_SIZE-1)
#define EMPTY_MAX (32*WARP_SIZE-1)

//------------------------------------------------------------------------
// Safety conditions
//------------------------------------------------------------------------

#if SCAN_TYPE == 2 && AABB_TYPE < 3
#error Conflicting use of c_bvh_in.sortTris
#endif

//------------------------------------------------------------------------
// Auxiliary types
//------------------------------------------------------------------------

// Enum for threshold values in header array
enum TaskHeader {TaskHeader_Empty = 0xA0000000, TaskHeader_Waiting = 0xC0000000, TaskHeader_Dependent = 0xE0000000, TaskHeader_Locked = -1, TaskHeader_Active = 0};
// Enum for various locking states
enum LockType {LockType_Free = 0, LockType_Set, LockType_None, LockType_Subtask};
// Enum for types of dependence
enum DependType {DependType_None = -2, DependType_Root};

// A work queue divided into two arrays with same indexing and other auxiliary global data
struct TaskStackBase
{
	int          *header;              // Holds state of each task
	int          top;                  // Top of the stack, points to the last filled element
	int          bottom;               // Bottom of the stack, points to the lowest empty element
	int          active[ACTIVE_MAX+1]; // Locations of the last used active elements
	unsigned int activeTop;            // Top of active stack
	unsigned int activeBottom;         // Bottom of active stack
	int          empty[EMPTY_MAX+1];   // Locations of the last opened elements
	unsigned int emptyTop;             // Top of empty stack
	unsigned int emptyBottom;          // Bottom of empty stack
	int          unfinished;           // Number of tasks that need to be finished before all work is done - NOT THE SAME AS THE NUMBER OF TASKS IN THE ARRAY
	int          sizePool;             // Size of the pool - FOR TESTING PURPOUSES ONLY
	int          sizeNodes;            // Size of the node memory - FOR TESTING PURPOUSES ONLY
	int          sizeTris;             // Size of the triangle memory - FOR TESTING PURPOUSES ONLY
	unsigned int leafHist[32];         // Histogram of leaf sizes
	int          launchFlag;
};

#ifdef SNAPSHOT_POOL
// A structure holding information about the state of the pool
struct PoolInfo
{
	int pool;
	int tasks;
	int active;
	int chunks;
	float depth;
	long long int clockStart;
	long long int clockEnd;
};
#endif

//------------------------------------------------------------------------

#ifdef SNAPSHOT_WARP
// A structure holding information about tasks processed by a warp
struct WarpInfo
{
	int reads;
	int rays;
	int tris;
	int type;
	int chunks;
	int popCount;
	int depth;
	int idx;
	int stackTop;
	long long int clockSearch;
	long long int clockDequeue;
	long long int clockFinished;
};
#endif

//------------------------------------------------------------------------

#ifdef __CUDACC__
#if defined(__CUDA_ARCH__) && (__CUDA_ARCH__ < 200)
#undef assert
#define assert(arg)
#define printf(f, ...) ((void)(f, __VA_ARGS__),0)
#endif

//------------------------------------------------------------------------

#ifdef DIVERGENCE_TEST
#if 0 // Ends on first divergence, cannot cause unknown error later
	#define ASSERT_DIVERGENCE(S, T) \
	{ \
		assert(__ballot(1) == 0xFFFFFFFF); \
	}
#else // Writes out all encountered divergences
	#define ASSERT_DIVERGENCE(S, T) \
	{ \
		unsigned int ballot = __ballot(1); \
		if(ballot != 0xFFFFFFFF) \
		{\
			printf("Divergence %s tid %d, %u!\n", S, T, ballot); \
		}\
	}
#endif
#else
	#define ASSERT_DIVERGENCE(S, T) ((void)0)
#endif

//------------------------------------------------------------------------

// Number of step counts
__shared__ volatile int maxSteps[NUM_WARPS_PER_BLOCK];
__shared__ volatile int sumSteps[NUM_WARPS_PER_BLOCK];
__shared__ volatile int numSteps[NUM_WARPS_PER_BLOCK];
__shared__ volatile int numReads[NUM_WARPS_PER_BLOCK];
__shared__ volatile int numRestarts[NUM_WARPS_PER_BLOCK];

#ifdef SNAPSHOT_WARP
#undef COUNT_STEPS_LEFT
#undef COUNT_STEPS_RIGHT
#undef COUNT_STEPS_CACHE
#undef COUNT_STEPS_DEQUEUE
#define COUNT_STEPS_DEQUEUE
#endif

#ifdef DEBUG_PPS
#undef PHASE_TEST
#define PHASE_TEST
#endif

//------------------------------------------------------------------------
// Common data items.
//------------------------------------------------------------------------

#ifdef SNAPSHOT_POOL
__device__ PoolInfo *g_snapshots;
#endif

#ifdef SNAPSHOT_WARP
__device__ WarpInfo *g_snapshots;
#endif

//------------------------------------------------------------------------
// Functions for computing number of warps needed for various tasks.
//------------------------------------------------------------------------

// Return the number of warp sized subtasks but at least 1 task
__device__ __forceinline__ int taskWarpSubtasks(int threads);

// Return the number of warp sized subtasks
__device__ __forceinline__ int taskWarpSubtasksZero(int threads);

// Computes the number of warps needed for the naive PPS
__device__ __forceinline__ int taskNextPhaseCountPPS(int step, int start, int end);

// Computes the number of levels in the tree defined by interval [start, end) and ceils the value to the multiple of LOG_WARP_SIZE
__device__ __forceinline__ int taskTopTreeLevel(int start, int end);

// Computes the number of warps needed for a specific level of a hierarchical algorithm
__device__ __forceinline__ int taskNextPhaseCountTree(int level, int start, int end);

// Computes the number of warps needed for the PPS up phase
__device__ __forceinline__ int taskNextPhaseCountPPSUp(int step, int start, int end);

// Computes the number of warps needed for the PPS down phase
__device__ __forceinline__ int taskNextPhaseCountPPSDown(int step, int start, int end);

// Computes the number of warps needed for the reduction level by level
__device__ __forceinline__ int taskNextPhaseCountReduce(int step, int start, int end);

// Computes the number of warps needed for the reduction multiplied by a constant
__device__ __forceinline__ int taskNextPhaseCountReduceMultiplied(int step, int start, int end, int multiply);

// Computes the number of warps needed for the reduction
__device__ __forceinline__ int taskNextPhaseCountReduceBlock(int step, int start, int end);

//------------------------------------------------------------------------
// Support for floating point minimums and maximums.
//------------------------------------------------------------------------

// Converts float to an orderable int
__device__ __forceinline__ int floatToOrderedInt(float floatVal);

// Converts an orderable int back to a float
__device__ __forceinline__ float orderedIntToFloat(int intVal);

// Atomic minimum on floats
__device__ __forceinline__ float atomicMinFloat(int* address, float value);

// Atomic maximum on floats
__device__ __forceinline__ float atomicMaxFloat(int* address, float value);

//------------------------------------------------------------------------
// Task enqueue and dequeue support.
//------------------------------------------------------------------------

// Adds a task into a global task queue in place of an empty task with position lower or equal of taskIdx and returns its position in taskIdx
__device__ void taskEnqueueRight(int tid, int *head, volatile int* sharedData, int taskStatus, int& beg, int end);

// Adds a task into a global task queue in place of an empty task with position lower or equal of taskIdx and returns its position in taskIdx
__device__ void taskEnqueueLeft(int tid, int *head, volatile int* sharedData, int taskStatus, int& beg, int* unfinished, int size);

// Adds a task into a global task queue in place of an empty task
__device__ void taskEnqueueCache(int tid, TaskStackBase* task, volatile int* s_sharedData, int& status, int& pos, int& beg, int& top);

// Checks whether there is more work chunks to process
__device__ __forceinline__ int reduceSubtask(int &subtask, const int& count, const int& popCount);

// Caches an item in the active cache
__device__ __forceinline__ void taskCacheActive(int taskIdx, int* activeCache, unsigned int* activeCacheTop);

// Uncaches an item in the active cache
__device__ __forceinline__ void taskUncacheActive(int tid, int taskIdx, int* activeCache, unsigned int* activeCacheTop);

// Caches an item in the empty cache
__device__ __forceinline__ void taskCacheEmpty(int taskIdx, int* emptyCache, unsigned int* emptyCacheTop);

//------------------------------------------------------------------------
// Prefix scan and sorting.
//------------------------------------------------------------------------

// Naive inclusive prefix scan
template<typename T>
__device__ void pps(int tid, int subtask, int step, T* dataSrc, T* dataBuff, volatile T* red, unsigned int start, unsigned int end, int test);

// Inclusive scan by Harris: up-sweep phase
template<typename T>
__device__ void scanUp(int tid, int subtask, int step, T* data, T* cls, volatile T* red, int start, int end, T test, T(*op)(T,T), T identity);

// Inclusive scan by Harris: down-sweep phase
template<typename T>
__device__ void scanDown(int tid, int subtask, int step, T* data, T* cls, volatile T* red, int start, int end, T test, T(*op)(T,T), T identity);

// Comments and variables are with regard to -1,0 to the left, 1 to the right
__device__ void sort(int tid, int subtask, int step, int* dataPPSSrc, int* dataPPSBuf, int* dataSort, int* dataIndex, int start, int end, int mid, int test, bool swapIndex);

#endif


text:
import gevent
import logging
import gevent.socket as _socket

import dhcpz.util
import dhcpz.packet
import dhcpz.options

class DhcpServerListener(gevent.Greenlet):
    """
    Binds to a socket and listens for DHCP requests, calling
    handle_packet on the specified handler class. Implemented as
    a gevent Greenlet.
    """

    bufsize = 1500

    def __init__(self, ip_address, handler, logger=None):
        """
        @param ip_address: The IP address we're listening on
        @param handler: The class/instance to call handle_packet on
        """
        gevent.Greenlet.__init__(self)

        self.ip_address = ip_address
        self.handler = handler
        self.logger = logger or logging.getLogger(self.__class__.__name__)

        self.iface_name, self.ip_config = dhcpz.util.network_config()[ip_address]
        self._keepgoing = True

        self.sock = _socket.socket(_socket.AF_INET, _socket.SOCK_DGRAM)
        self.sock.setsockopt(_socket.SOL_SOCKET, _socket.SO_BROADCAST, 1)
        self.sock.setsockopt(_socket.SOL_SOCKET, _socket.SO_BINDTODEVICE, self.iface_name)
        self.sock.setsockopt(_socket.SOL_SOCKET, _socket.SO_REUSEADDR, 1)
        self.sock.bind(('', 67))

    def _run(self):
        while self._keepgoing:
            data, addr = self.sock.recvfrom(self.bufsize)
            packet = dhcpz.packet.DhcpPacket(data)
            response = self.handler.handle_packet(self, packet)
            if response:
                self.respond(response)

    def respond(self, packet):
        """
        Although technically we should be able to unicast a response, the DHCP
        specification allows for either a unicast or a broadcast response.

        @param packet: The DHCP packet to send back to the client
        """
        del packet["params"]
        self.sock.sendto(packet.pack(), ('255.255.255.255', 68))

    def stop(self):
        self._keepgoing = False
        self.kill()

    def __repr__(self):
        return "<%s on %s (%s)>" % (self.__class__.__name__, self.ip_address, self.iface_name)

class DhcpServer(object):
    _listener_factory = DhcpServerListener

    def __init__(self, handler, logger=None):
        self.handler = handler
        self.logger = logger or logging.getLogger(self.__class__.__name__)
        self._listeners = []
        self._running = False

    def listen(self, ip_address):
        listener = self._listener_factory(ip_address, self.handler, self.logger)
        self._listeners.append(listener)
        if self._running:
            self._launch_listener(listener)

    def run(self):
        self._running = True
        map(self._launch_listener, self._listeners)
        for listener in self._listeners:
            listener.join()

    def stop(self):
        self._running = False
        for listener in self._listeners:
            listener.stop()

    def _launch_listener(self, listener):
        self.logger.info("listening on %s" % listener.ip_address)
        listener.start()


text:
<?php

namespace CachetHQ\Cachet\Handlers\Events\Incident;

use CachetHQ\Cachet\Events\Incident\IncidentWasReportedEvent;
use CachetHQ\Cachet\Models\Subscriber;
use Illuminate\Contracts\Mail\MailQueue;
use Illuminate\Mail\Message;
use McCool\LaravelAutoPresenter\Facades\AutoPresenter;

class SendIncidentEmailNotificationHandler
{
    /**
     * The mailer instance.
     *
     * @var \Illuminate\Contracts\Mail\Mailer
     */
    protected $mailer;

    /**
     * The subscriber instance.
     *
     * @var \CachetHQ\Cachet\Models\Subscriber
     */
    protected $subscriber;

    /**
     * Create a new send incident email notification handler.
     *
     * @param \Illuminate\Contracts\Mail\Mailer  $mailer
     * @param \CachetHQ\Cachet\Models\Subscriber $subscriber
     *
     * @return void
     */
    public function __construct(MailQueue $mailer, Subscriber $subscriber)
    {
        $this->mailer = $mailer;
        $this->subscriber = $subscriber;
    }

    /**
     * Handle the event.
     *
     * @param \CachetHQ\Cachet\Events\Incident\IncidentHasReportedEvent $event
     *
     * @return void
     */
    public function handle(IncidentWasReportedEvent $event)
    {
        if (!$event->incident->notify) {
            return false;
        }

        $incident = AutoPresenter::decorate($event->incident);
        $component = AutoPresenter::decorate($event->incident->component);

        // Only send emails for public incidents.
        if ($event->incident->visible === 1) {
            foreach ($this->subscriber->all() as $subscriber) {
                $mail = [
                    'email'            => $subscriber->email,
                    'subject'          => 'New incident reported.',
                    'has_component'    => ($event->incident->component) ? true : false,
                    'component_name'   => $component ? $component->name : null,
                    'status'           => $incident->humanStatus,
                    'html_content'     => $incident->formattedMessage,
                    'text_content'     => $incident->message,
                    'token'            => $subscriber->token,
                    'unsubscribe_link' => route('subscribe.unsubscribe', ['code' => $subscriber->verify_code]),
                ];

                $this->mailer->queue([
                    'html' => 'emails.incidents.new-html',
                    'text' => 'emails.incidents.new-text',
                ], $mail, function (Message $message) use ($mail) {
                    $message->to($mail['email'])->subject($mail['subject']);
                });
            }
        }
    }
}


text:
<?php

/* $Id: fluxdWatchSettings.php 2981 2007-05-11 21:54:43Z warion $ */

/*******************************************************************************

 LICENSE

 This program is free software; you can redistribute it and/or
 modify it under the terms of the GNU General Public License (GPL)
 as published by the Free Software Foundation; either version 2
 of the License, or (at your option) any later version.

 This program is distributed in the hope that it will be useful,
 but WITHOUT ANY WARRANTY; without even the implied warranty of
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 GNU General Public License for more details.

 To read the license please visit http://www.gnu.org/copyleft/gpl.html

*******************************************************************************/

// prevent direct invocation
if ((!isset($cfg['user'])) || (isset($_REQUEST['cfg']))) {
	@ob_end_clean();
	@header("location: ../../../index.php");
	exit();
}

/******************************************************************************/

// Watch
FluxdServiceMod::initializeServiceMod('Watch');

// init template-instance
tmplInitializeInstance($cfg["theme"], "page.admin.fluxdWatchSettings.tmpl");

// message section
$message = tfb_getRequestVar('m');
if ((isset($message)) && ($message != "")) {
	$tmpl->setvar('new_msg', 1);
	$tmpl->setvar('message', urldecode($message));
} else {
	$tmpl->setvar('new_msg', 0);
}

// pageop
//
// * default
//
// * addJob
// * editJob
// * saveJob
// * deleteJob
//

$with_profiles = $cfg['transfer_profiles'] >= 1 ? 1 : 0;
$tmpl->setvar('with_profiles', $with_profiles);

$wasWatchError = false;
function setWatchError($msg) {
	global $tmpl, $wasWatchError;
	$wasWatchError = true;
	$tmpl->setvar('new_msg', 1);
	$tmpl->setvar('message', $msg);
}

$pageop = tfb_getRequestVar('pageop');
$pageop2 = $pageop = (empty($pageop)) ? "default" : $pageop;
$tmpl->setvar('pageop', $pageop);

// op-switch
switch ($pageop) {

	default:
	case "default":
		// jobs
		$jobs = FluxdWatch::jobsGetList();
		if ($jobs === false)
			setWatchError('Error : could not load jobs.');
		else
			$tmpl->setloop('watch_jobs', $jobs);
		// title-bar
		tmplSetTitleBar("Administration - Fluxd Watch Settings");
		break;

	case "addJob":
	case "editJob":
	case "saveJob":
		$jobNumber = trim(tfb_getRequestVarRaw('job'));
		$isNew = empty($jobNumber);

		$watchdir = trim(tfb_getRequestVarRaw('watchdir'));
		$user = trim(tfb_getRequestVarRaw('user'));
		$profile = trim(tfb_getRequestVarRaw('profile'));
		$checkdir = trim(tfb_getRequestVarRaw('checkdir'));

		$postback = tfb_getRequestVarRaw('postback');
		$isPostback = $postback == '1';
		$refresh = tfb_getRequestVarRaw('refresh');
		$isRefresh = $refresh == '1';
		$isSave = $isPostback && !$isRefresh;
		$checkdir = ($checkdir == '1' || $checkdir == 'on' || $checkdir == 'true');

		if ($isSave) {	// saving (a new one or an existing one)
			$pageop2 = "saveJob";

			$paramErrors = 0;
			if (strlen($watchdir) == 0)
				$paramErrors++;
			if (strlen($user) == 0)
				$paramErrors++;
			if ($paramErrors != 0)
				setWatchError('Error : Argument-Error.');
			else {
				if ($isNew) {
					$result = FluxdWatch::jobAdd($watchdir, $user, $profile, $checkdir);
					if ($result !== false)
						$tmpl->setvar('watch_job_message', 'Job added.');
				} else {
					$result = FluxdWatch::jobUpdate($jobNumber, $watchdir, $user, $profile, $checkdir);
					if ($result !== false)
						$tmpl->setvar('watch_job_message', 'Job updated.');
				}
				if ($result === false) {
					$wasWatchError = true;
					$messages = array();
					$msgs = FluxdWatch::getMessages();
					foreach ($msgs as $msg)
						array_push($messages, array('msg' => $msg));
					$tmpl->setloop('messages', $messages);
				}
			}

			$tmpl->setvar('watch_job_saved', !$wasWatchError);

			// title-bar
			tmplSetTitleBar("Administration - Fluxd Watch - Save Job");
		} else {	// initial display, or refresh (of a new one or of an existing one)
			$pageop2 = "addJobOReditJob";

			// job number
			$tmpl->setvar('jobnumber', $jobNumber);

			// initial display of an existing job: load its contents
			if (!$isNew && !$isRefresh) {
				$job = FluxdWatch::jobGetContent($jobNumber);
				if ($job === false)
					$wasWatchError = true;
				else {
					$watchdir = $job['D'];
					$user = $job['U'];
					$profile = isset($job['P']) ? $job['P'] : '';
				}
			}

			if (!$wasWatchError) {
				// job number
				$tmpl->setvar('jobnumber', $jobNumber);
				// watchdir
				$tmpl->setvar('watchdir', $watchdir);
				// users
				$watchusers = array();
				$userCount = count($cfg['users']);
				$foundSel = false;
				for ($i = 0; $i < $userCount; $i++) {
					$tmp = $cfg['users'][$i];
					$sel = ((!$isNew || $isRefresh) && $user == $tmp) ? 1 : 0;
					if ($sel)
						$foundSel = true;
					array_push($watchusers, array(
						'name'        => $tmp,
						'is_selected' => $sel
					));
				}
				if (!$foundSel) {
					// no or invalid user, just set superadmin by default
					$user = GetSuperAdmin();
					foreach ($watchusers as $k => $watchuser)
						if ($user == $watchuser['name'])
							$watchusers[$k]['is_selected'] = 1;
				}
				$tmpl->setloop('watch_users', $watchusers);
				// profiles
				if ($with_profiles) {
					$profiles = GetProfilesByUserName($user, $profile);
					$public_profiles = GetPublicProfiles($profile);
					$tmpl->setloop('profiles', $profiles);
					$tmpl->setloop('public_profiles', $public_profiles);
				}
				// checkdir
				$tmpl->setvar('checkdir', (!$isRefresh || $checkdir) ? 1 : 0);
			}

			$tmpl->setvar('watch_job_loaded', !$wasWatchError);

			// title-bar
			tmplSetTitleBar("Administration - Fluxd Watch - ".($isNew ? "Add" : "Edit")." Job");
		}
		break;

	case "deleteJob":
		$jobNumber = trim(tfb_getRequestVar('job'));
		if (empty($jobNumber)) {
			setWatchError('Error : No Job-Number.');
			$tmpl->setvar('watch_job_deleted', 0);
		} else {
			$tmpl->setvar('watch_job_deleted', (FluxdWatch::jobDelete($jobNumber) === true) ? 1 : 0);
		}
		// title-bar
		tmplSetTitleBar("Administration - Fluxd Watch - Delete Job");
		break;
}

$tmpl->setvar('pageop2', $pageop2);
//
$tmpl->setvar('enable_dereferrer', $cfg["enable_dereferrer"]);
//
tmplSetAdminMenu();
tmplSetFoot();
tmplSetIidVars();

// parse template
$tmpl->pparse();

?>


text:
<?php

class Automobile
{
    private $vehicleMake;
    private $vehicleModel;

    /**
     * Automobile constructor.
     * @param string $make
     * @param string $model
     */
    public function __construct($make, $model)
    {
        $this->vehicleMake = $make;
        $this->vehicleModel = $model;
    }

    public function getMakeAndModel()
    {
        return $this->vehicleMake . ' ' . $this->vehicleModel;
    }
}

class AutomobileFactory
{
    public static function create($make, $model)
    {
        return new Automobile($make, $model);
    }
}

// have the factory create the Automobile object
$veyron = AutomobileFactory::create('Bugatti', 'Veyron');

print_r($veyron->getMakeAndModel()); // outputs "Bugatti Veyron"


text:
/*!
 * \file stackvm_module.cc
 */
#include "stackvm_module.h"

#include <dmlc/memory_io.h>
#include <tvm/runtime/module.h>
#include <tvm/runtime/registry.h>

#include <memory>
#include <unordered_map>
#include <utility>

#include "../file_utils.h"

namespace tvm {
namespace runtime {

class StackVMModuleNode : public runtime::ModuleNode {
 public:
  const char* type_key() const { return "stackvm"; }

  PackedFunc GetFunction(const std::string& name, const ObjectPtr<Object>& sptr_to_self) final {
    if (name == runtime::symbol::tvm_module_main) {
      return GetFunction(entry_func_, sptr_to_self);
    }
    auto it = fmap_.find(name);
    if (it == fmap_.end()) return PackedFunc();
    const StackVM& vm = it->second;
    // capture sptr_to_self to keep module node alive.
    return PackedFunc(
        [vm, sptr_to_self, this](TVMArgs args, TVMRetValue* rv) { vm.Run(args, this); });
  }

  std::string GetSource(const std::string& format) final {
    std::ostringstream os;
    for (const auto& kv : fmap_) {
      os << "Function: " << kv.first << '\n';
      os << kv.second;
    }
    return os.str();
  }

  void SaveToFile(const std::string& file_name, const std::string& format) final {
    std::string data, mblob;
    dmlc::MemoryStringStream writer(&data);
    dmlc::Stream* strm = &writer;
    strm->Write(fmap_);
    strm->Write(entry_func_);
    // also save imports
    uint64_t num_imports = static_cast<uint64_t>(imports_.size());
    strm->Write(num_imports);

    for (runtime::Module im : imports_) {
      ICHECK_EQ(im->imports().size(), 0U) << "Only support simply one-level hierarchy";
      std::string tkey = im->type_key();
      strm->Write(tkey);
      im->SaveToBinary(strm);
    }
    SaveBinaryToFile(file_name, data);
  }

  static Module Create(std::unordered_map<std::string, StackVM> fmap, std::string entry_func) {
    auto n = make_object<StackVMModuleNode>();
    n->fmap_ = std::move(fmap);
    n->entry_func_ = std::move(entry_func);
    return Module(n);
  }

  static Module Load(dmlc::Stream* strm) {
    std::unordered_map<std::string, StackVM> fmap;
    std::string entry_func, data;
    strm->Read(&fmap);
    strm->Read(&entry_func);
    auto n = make_object<StackVMModuleNode>();
    n->fmap_ = std::move(fmap);
    n->entry_func_ = std::move(entry_func);
    uint64_t num_imports;
    strm->Read(&num_imports);
    for (uint64_t i = 0; i < num_imports; ++i) {
      std::string tkey;
      ICHECK(strm->Read(&tkey));
      std::string loadkey = "runtime.module.loadbinary_";
      std::string fkey = loadkey + tkey;
      const PackedFunc* f = Registry::Get(fkey);
      if (f == nullptr) {
        std::string loaders = "";
        for (auto name : Registry::ListNames()) {
          if (name.rfind(loadkey, 0) == 0) {
            if (loaders.size() > 0) {
              loaders += ", ";
            }
            loaders += name.substr(loadkey.size());
          }
        }
        ICHECK(f != nullptr)
            << "Binary was created using " << tkey
            << " but a loader of that name is not registered. Available loaders are " << loaders
            << ". Perhaps you need to recompile with this runtime enabled.";
      }
      Module m = (*f)(static_cast<void*>(strm));
      n->imports_.emplace_back(std::move(m));
    }
    return Module(n);
  }

  static Module LoadFromFile(std::string file_name, std::string format) {
    std::string data;
    LoadBinaryFromFile(file_name, &data);
    dmlc::MemoryStringStream reader(&data);
    return Load(&reader);
  }

 private:
  // internal function map
  std::unordered_map<std::string, StackVM> fmap_;
  // entry function.
  std::string entry_func_;
};

Module StackVMModuleCreate(std::unordered_map<std::string, StackVM> fmap, std::string entry_func) {
  return StackVMModuleNode::Create(fmap, entry_func);
}

TVM_REGISTER_GLOBAL("runtime.module.loadfile_stackvm")
    .set_body_typed(StackVMModuleNode::LoadFromFile);

}  // namespace runtime
}  // namespace tvm


text:
package org.apache.bigtop.itest.hbase.util;

import java.io.IOException;
import java.security.MessageDigest;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.hbase.HBaseConfiguration;
import org.apache.hadoop.hbase.HColumnDescriptor;
import org.apache.hadoop.hbase.HTableDescriptor;
import org.apache.hadoop.hbase.KeyValue;
import org.apache.hadoop.hbase.MasterNotRunningException;
import org.apache.hadoop.hbase.ZooKeeperConnectionException;
import org.apache.hadoop.hbase.client.HBaseAdmin;
import org.apache.hadoop.hbase.client.HTable;
import org.apache.hadoop.hbase.client.Result;
import org.apache.hadoop.hbase.client.ResultScanner;
import org.apache.hadoop.hbase.client.Scan;
import org.apache.hadoop.hbase.io.hfile.CacheConfig;
import org.apache.hadoop.hbase.io.compress.Compression;
import org.apache.hadoop.hbase.io.hfile.HFile;
import org.apache.hadoop.hbase.io.hfile.HFileContext;
import org.apache.hadoop.hbase.util.Bytes;
import org.apache.hadoop.hbase.util.ChecksumType;

public class HBaseTestUtil {

  public static int BLOCKSIZE = 64*1024;
  public static String COMPRESSION =
    Compression.Algorithm.NONE.getName();

  private static String getTestPrefix() {
    return String.valueOf(System.currentTimeMillis());
  }

  public static byte[] getTestTableName(String testName) {
    return Bytes.toBytes(testName + "_" + getTestPrefix());
  }

  public static HTableDescriptor createTestTableDescriptor(String testName,
      byte[] familyName) {
    byte[] tableName = getTestTableName(testName);
    HTableDescriptor htd = new HTableDescriptor(tableName);
    htd.addFamily(new HColumnDescriptor(familyName));
    return htd;
  }

  public static HBaseAdmin getAdmin()
      throws MasterNotRunningException, ZooKeeperConnectionException {
    HBaseAdmin hAdmin = null;
    try {
      hAdmin = new HBaseAdmin(HBaseConfiguration.create());
    } catch (IOException e) {
      e.printStackTrace();
    }
    return hAdmin;
  }

  public static FileSystem getClusterFileSystem() throws IOException {
    return FileSystem.get(new Configuration());
  }

  public static Path getMROutputDir(String testName) throws IOException {
    Path p = new Path(testName + "_" + getTestPrefix());
    return p.makeQualified(getClusterFileSystem());
  }

  /**
   * Create an HFile with the given number of rows between a given
   * start key and end key.
   */
  public static void createHFile(
      Configuration conf,
      FileSystem fs, Path path,
      byte[] family, byte[] qualifier,
      byte[] startKey, byte[] endKey, int numRows) throws IOException
  {
      HFile.WriterFactory wf = HFile.getWriterFactory(conf, new CacheConfig(conf));
      HFileContext hFileContext = new HFileContext();
      wf.withFileContext(hFileContext);
      wf.withComparator(KeyValue.COMPARATOR);
      wf.withPath(fs, path);
    HFile.Writer writer = wf.create();
    long now = System.currentTimeMillis();
    try {
      // subtract 2 since iterateOnSplits doesn't include boundary keys
      for (byte[] key : Bytes.iterateOnSplits(startKey, endKey, numRows-2)) {
        KeyValue kv = new KeyValue(key, family, qualifier, now, key);
        writer.append(kv);
      }
    } finally {
      writer.close();
    }
  }

  /**
   * Return the number of rows in the given table.
   */
  public static int countRows(final HTable table) throws IOException {
    Scan scan = new Scan();
    ResultScanner results = table.getScanner(scan);
    int count = 0;
    for (@SuppressWarnings("unused") Result res : results) {
      count++;
    }
    results.close();
    return count;
  }

  /**
   * Return an md5 digest of the entire contents of a table.
   */
  public static String checksumRows(final HTable table) throws Exception {
    Scan scan = new Scan();
    ResultScanner results = table.getScanner(scan);
    MessageDigest digest = MessageDigest.getInstance("MD5");
    for (Result res : results) {
      digest.update(res.getRow());
    }
    results.close();
    return digest.toString();
  }
}