text:
#include "ThreadPool.hpp"
#include "../log/Log.hpp"

#ifdef WIN32

#include <process.h>

#else

volatile int threadid_count = 0;
int GenerateThreadId() {
	int i = ++threadid_count;
	return i;
}

#endif

#define THREAD_RESERVE 10
EXPORT CThreadPool ThreadPool;

CThreadPool::CThreadPool() {
	_threadsExitedSinceLastCheck = 0;
	_threadsRequestedSinceLastCheck = 0;
	_threadsEaten = 0;
	_threadsFreedSinceLastCheck = 0;
}

bool CThreadPool::ThreadExit(Thread* t) {
	_mutex.Acquire();

	// we're definitely no longer active
	m_activeThreads.erase(t);

	// do we have to kill off some threads?
	if (_threadsToExit > 0) {
		// kill us.
		--_threadsToExit;
		++_threadsExitedSinceLastCheck;
		if (t->DeleteAfterExit)
			m_freeThreads.erase(t);

		_mutex.Release();
		delete t;
		return false;
	}

	// enter the "suspended" pool
	++_threadsExitedSinceLastCheck;
	++_threadsEaten;
	std::set<Thread*>::iterator itr = m_freeThreads.find(t);

	if (itr != m_freeThreads.end()) {
		sLog.outError("Thread %u duplicated with thread %u", (*itr)->ControlInterface.GetId(), t->ControlInterface.GetId());
	}
	m_freeThreads.insert(t);

	Log.Debug("ThreadPool", "Thread %u entered the free pool.", t->ControlInterface.GetId());
	_mutex.Release();
	return true;
}

void CThreadPool::ExecuteTask(ThreadBase* ExecutionTarget) {
	Thread* t;
	_mutex.Acquire();
	++_threadsRequestedSinceLastCheck;
	--_threadsEaten;

	// grab one from the pool, if we have any.
	if (m_freeThreads.size()) {
		t = *m_freeThreads.begin();
		m_freeThreads.erase(m_freeThreads.begin());

		// execute the task on this thread.
		t->ExecutionTarget = ExecutionTarget;

		// resume the thread, and it should start working.
		t->ControlInterface.Resume();
		Log.Debug("ThreadPool", "Thread %u left the thread pool.", t->ControlInterface.GetId());
	}else {
		// creating a new thread means it heads straight to its task.
		// no need to resume it :)
		t = StartThread(ExecutionTarget);
	}

	// add the thread to the active set
#ifdef WIN32
	Log.Debug("ThreadPool", "Thread %u is now executing task at 0x%p.", t->ControlInterface.GetId(), ExecutionTarget);
#else
	Log.Debug("ThreadPool", "Thread %u is now executing task at %p.", t->ControlInterface.GetId(), ExecutionTarget);
#endif
	m_activeThreads.insert(t);
	_mutex.Release();
}

void CThreadPool::Startup() {
	int i;
	int tcount = THREAD_RESERVE;

	for (i = 0; i < tcount; ++i)
		StartThread(NULL);

	Log.Debug("ThreadPool", "Startup, launched %u threads.", tcount);
}

void CThreadPool::ShowStats() {
	_mutex.Acquire();
	Log.Debug("ThreadPool", "============ ThreadPool Status =============");
	Log.Debug("ThreadPool", "Active Threads: %u", m_activeThreads.size());
	Log.Debug("ThreadPool", "Suspended Threads: %u", m_freeThreads.size());
	Log.Debug("ThreadPool", "Requested-To-Freed Ratio: %.3f%% (%u/%u)", float(float(_threadsRequestedSinceLastCheck + 1) / float(_threadsExitedSinceLastCheck + 1) * 100.0f), _threadsRequestedSinceLastCheck, _threadsExitedSinceLastCheck);
	Log.Debug("ThreadPool", "Eaten Count: %d (negative is bad!)", _threadsEaten);
	Log.Debug("ThreadPool", "============================================");
	_mutex.Release();
}

void CThreadPool::IntegrityCheck() {
	_mutex.Acquire();
	int32 gobbled = _threadsEaten;

	if (gobbled < 0) {
		// this means we requested more threads than we had in the pool last time.
		// spawn "gobbled" + THREAD_RESERVE extra threads.
		uint32 new_threads = abs(gobbled) + THREAD_RESERVE;
		_threadsEaten = 0;

		for (uint32 i = 0; i < new_threads; ++i)
			StartThread(NULL);

		Log.Debug("ThreadPool", "IntegrityCheck: (gobbled < 0) Spawning %u threads.", new_threads);
	}else if (gobbled < THREAD_RESERVE) {
		// this means while we didn't run out of threads, we were getting damn low.
		// spawn enough threads to keep the reserve amount up.
		uint32 new_threads = (THREAD_RESERVE - gobbled);
		for (uint32 i = 0; i < new_threads; ++i)
			StartThread(NULL);

		Log.Debug("ThreadPool", "IntegrityCheck: (gobbled <= 5) Spawning %u threads.", new_threads);
	}else if (gobbled > THREAD_RESERVE) {
		// this means we had "excess" threads sitting around doing nothing.
		// lets kill some of them off.
		uint32 kill_count = (gobbled - THREAD_RESERVE);
		KillFreeThreads(kill_count);
		_threadsEaten -= kill_count;
		Log.Debug("ThreadPool", "IntegrityCheck: (gobbled > 5) Killing %u threads.", kill_count);
	}else {
		// perfect! we have the ideal number of free threads.
		Log.Debug("ThreadPool", "IntegrityCheck: Perfect!");
	}

	_threadsExitedSinceLastCheck = 0;
	_threadsRequestedSinceLastCheck = 0;
	_threadsFreedSinceLastCheck = 0;

	_mutex.Release();
}

void CThreadPool::KillFreeThreads(uint32 count) {
	Log.Debug("ThreadPool", "Killing %u excess threads.", count);
	_mutex.Acquire();
	Thread* t;
	ThreadSet::iterator itr;
	uint32 i;
	for (i = 0, itr = m_freeThreads.begin(); i < count && itr != m_freeThreads.end(); ++i, ++itr) {
		t = *itr;
		t->ExecutionTarget = NULL;
		t->DeleteAfterExit = true;
		++_threadsToExit;
		t->ControlInterface.Resume();
	}
	_mutex.Release();
}

void CThreadPool::Shutdown() {
	_mutex.Acquire();
	size_t tcount = m_activeThreads.size() + m_freeThreads.size();		// exit all
	Log.Debug("ThreadPool", "Shutting down %u threads.", tcount);
	KillFreeThreads((uint32)m_freeThreads.size());
	_threadsToExit += (uint32)m_activeThreads.size();

	for (std::set< Thread* >::iterator itr = m_activeThreads.begin(); itr != m_activeThreads.end(); ++itr) {

		Thread* t = *itr;

		if (t->ExecutionTarget)
			t->ExecutionTarget->OnShutdown();
		else
			t->ControlInterface.Resume();
	}
	_mutex.Release();

	for (int i = 0;; i++) {
		_mutex.Acquire();
		if (m_activeThreads.size() || m_freeThreads.size()) {
			if (i != 0 && m_freeThreads.size() != 0) {
				/*if we are here then a thread in the free pool checked if it was being shut down just before CThreadPool::Shutdown() was called,
				but called Suspend() just after KillFreeThreads(). All we need to do is to resume it.*/
				Thread* t;
				ThreadSet::iterator itr;
				for (itr = m_freeThreads.begin(); itr != m_freeThreads.end(); ++itr) {
					t = *itr;
					t->ControlInterface.Resume();
				}
			}
			Log.Debug("ThreadPool", "%u active and %u free threads remaining...", m_activeThreads.size(), m_freeThreads.size());
			_mutex.Release();
			sleep(1000);
			continue;
		}

		_mutex.Release();
		break;
	}
}

/* this is the only platform-specific code. neat, huh! */
#ifdef WIN32

static unsigned long WINAPI thread_proc(void* param) {
	Thread* t = (Thread*)param;
	t->SetupMutex.Acquire();
	uint32 tid = t->ControlInterface.GetId();
	bool ht = (t->ExecutionTarget != NULL);
	t->SetupMutex.Release();
	Log.Debug("ThreadPool", "Thread %u started.", t->ControlInterface.GetId());

	for (;;) {
		if (t->ExecutionTarget != NULL) {
			if (t->ExecutionTarget->run())
				delete t->ExecutionTarget;

			t->ExecutionTarget = NULL;
		}

		if (!ThreadPool.ThreadExit(t)) {
			Log.Debug("ThreadPool", "Thread %u exiting.", tid);
			break;
		}else {
			if (ht)
				Log.Debug("ThreadPool", "Thread %u waiting for a new task.", tid);
			// enter "suspended" state. when we return, the threadpool will either tell us to fuk off, or to execute a new task.
			t->ControlInterface.Suspend();
			// after resuming, this is where we will end up. start the loop again, check for tasks, then go back to the threadpool.
		}
	}

	// at this point the t pointer has already been freed, so we can just cleanly exit.
	ExitThread(0);
}

Thread* CThreadPool::StartThread(ThreadBase* ExecutionTarget) {
	HANDLE h;
	Thread* t = new Thread;

	t->DeleteAfterExit = false;
	t->ExecutionTarget = ExecutionTarget;
	//h = (HANDLE)_beginthreadex(NULL, 0, &thread_proc, (void*)t, 0, NULL);
	t->SetupMutex.Acquire();
	h = CreateThread(NULL, 0, &thread_proc, (LPVOID)t, 0, (LPDWORD)&t->ControlInterface.thread_id);
	t->ControlInterface.Setup(h);
	t->SetupMutex.Release();

	return t;
}

#else

static void* thread_proc(void* param) {
	Thread* t = (Thread*)param;
	t->SetupMutex.Acquire();
	Log.Debug("ThreadPool", "Thread %u started.", t->ControlInterface.GetId());
	t->SetupMutex.Release();

	for (;;) {
		if (t->ExecutionTarget != NULL) {
			if (t->ExecutionTarget->run())
				delete t->ExecutionTarget;

			t->ExecutionTarget = NULL;
		}

		if (!ThreadPool.ThreadExit(t))
			break;
		else {
			// enter "suspended" state. when we return, the threadpool will either tell us to fuk off, or to execute a new task.
			t->ControlInterface.Suspend();
			// after resuming, this is where we will end up. start the loop again, check for tasks, then go back to the threadpool.
		}
	}

	pthread_exit(0);
}

Thread* CThreadPool::StartThread(ThreadBase* ExecutionTarget) {
	pthread_t target;
	Thread* t = new Thread;
	t->ExecutionTarget = ExecutionTarget;
	t->DeleteAfterExit = false;

	// lock the main mutex, to make sure id generation doesn't get messed up
	_mutex.Acquire();
	t->SetupMutex.Acquire();
	pthread_create(&target, NULL, &thread_proc, (void*)t);
	t->ControlInterface.Setup(target);
	pthread_detach(target);
	t->SetupMutex.Release();
	_mutex.Release();
	return t;
}

#endif


text:
/* IBM_PROLOG_BEGIN_TAG                                                   */
/* This is an automatically generated prolog.                             */
/*                                                                        */
/* $Source: src/import/chips/p9/procedures/hwp/perv/p9_getecid.H $        */
/*                                                                        */
/* OpenPOWER HostBoot Project                                             */
/*                                                                        */
/* Contributors Listed Below - COPYRIGHT 2016,2017                        */
/* [+] International Business Machines Corp.                              */
/*                                                                        */
/*                                                                        */
/* Licensed under the Apache License, Version 2.0 (the "License");        */
/* you may not use this file except in compliance with the License.       */
/* You may obtain a copy of the License at                                */
/*                                                                        */
/*     http://www.apache.org/licenses/LICENSE-2.0                         */
/*                                                                        */
/* Unless required by applicable law or agreed to in writing, software    */
/* distributed under the License is distributed on an "AS IS" BASIS,      */
/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or        */
/* implied. See the License for the specific language governing           */
/* permissions and limitations under the License.                         */
/*                                                                        */
/* IBM_PROLOG_END_TAG                                                     */
//------------------------------------------------------------------------------
/// @file  p9_getecid.H
///
/// @brief Get ECID string from target using SCOM
//------------------------------------------------------------------------------
// *HWP HW Owner        : Abhishek Agarwal <abagarw8@in.ibm.com>
// *HWP HW Backup Owner : Srinivas V Naga <srinivan@in.ibm.com>
// *HWP FW Owner        : sunil kumar <skumar8j@in.ibm.com>
// *HWP Team            : Perv
// *HWP Level           : 3
// *HWP Consumed by     : SBE
//------------------------------------------------------------------------------

#ifndef _GETECID_H_
#define _GETECID_H_

#include <fapi2.H>

enum P9_GETECID_Public_Constants
{
    p9_getecid_fuseString_len = 192,       // fuse string length
};

typedef fapi2::ReturnCode (*p9_getecid_FP_t)(const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>&,
        fapi2::variable_buffer& fuseString);

/// @brief Get ECID string from target using SCOM
///
/// @param[in]     i_target_chip   Reference to TARGET_TYPE_PROC_CHIP target
/// @return  FAPI2_RC_SUCCESS if success, else error code.
extern "C"
{
    fapi2::ReturnCode p9_getecid(const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& i_target_chip,
                                 fapi2::variable_buffer& o_fuseString);
}

#endif

redpajama_set_name: RedPajamaGithub


text:
<?php

namespace Biz\Content\Type;

class ContentTypeFactory
{
    /**
     * @param $alias
     *
     * @return ContentType
     */
    public static function create($alias)
    {
        $alias = ucfirst($alias);
        $class = __NAMESPACE__."\\{$alias}ContentType";

        return new $class();
    }
}


text:
var settings_notifications = (function () {

var exports = {};

var stream_notification_settings = [
    "enable_stream_desktop_notifications",
    "enable_stream_audible_notifications",
    "enable_stream_push_notifications",
    "enable_stream_email_notifications",
];

var pm_mention_notification_settings = [
    "enable_desktop_notifications",
    "enable_sounds",
    "enable_offline_push_notifications",
    "enable_offline_email_notifications",
];

var desktop_notification_settings = [
    "pm_content_in_desktop_notifications",
];

var mobile_notification_settings = [
    "enable_online_push_notifications",
];

var email_notification_settings = [
    "enable_digest_emails",
    "enable_login_emails",
    "message_content_in_email_notifications",
    "realm_name_in_notifications",
];

var other_notification_settings = desktop_notification_settings.concat(
    mobile_notification_settings,
    email_notification_settings,
    ["notification_sound"]
);

var notification_settings_status = [
    {status_label: "pm-mention-notify-settings-status", settings: pm_mention_notification_settings},
    {status_label: "other-notify-settings-status", settings: other_notification_settings},
    {status_label: "stream-notify-settings-status", settings: stream_notification_settings},
];

exports.all_notification_settings_labels = other_notification_settings.concat(
    pm_mention_notification_settings,
    stream_notification_settings
);

exports.all_notifications = {
    settings: {
        stream_notification_settings: stream_notification_settings,
        pm_mention_notification_settings: pm_mention_notification_settings,
        desktop_notification_settings: desktop_notification_settings,
        mobile_notification_settings: mobile_notification_settings,
        email_notification_settings: email_notification_settings,
    },
    push_notification_tooltip: {
        enable_stream_push_notifications: true,
        enable_offline_push_notifications: true,
        enable_online_push_notifications: true,
    },
};

function change_notification_setting(setting, setting_data, status_element) {
    var data = {};
    data[setting] = JSON.stringify(setting_data);
    settings_ui.do_settings_change(channel.patch, '/json/settings/notifications', data, status_element);
}

exports.set_enable_digest_emails_visibility = function () {
    if (page_params.realm_digest_emails_enabled) {
        $('#enable_digest_emails_label').parent().show();
    } else {
        $('#enable_digest_emails_label').parent().hide();
    }
};

exports.set_up = function () {
    _.each(notification_settings_status, function (setting) {
        _.each(setting.settings, function (sub_setting) {
            $("#" + sub_setting).change(function () {
                var value;

                if (sub_setting === "notification_sound") {
                    // `notification_sound` is not a boolean.
                    value = $(this).val();
                } else {
                    value = $(this).prop('checked');
                }
                change_notification_setting(sub_setting, value,
                                            "#" + setting.status_label);
            });
        });
    });

    $("#play_notification_sound").click(function () {
        $("#notifications-area").find("audio")[0].play();
    });

    var notification_sound_dropdown = $("#notification_sound");
    notification_sound_dropdown.val(page_params.notification_sound);

    $("#enable_sounds, #enable_stream_audible_notifications").change(function () {
        if ($("#enable_stream_audible_notifications").prop("checked") || $("#enable_sounds").prop("checked")) {
            notification_sound_dropdown.prop("disabled", false);
            notification_sound_dropdown.parent().removeClass("control-label-disabled");
        } else {
            notification_sound_dropdown.prop("disabled", true);
            notification_sound_dropdown.parent().addClass("control-label-disabled");
        }
    });
    exports.set_enable_digest_emails_visibility();
};

exports.update_page = function () {
    _.each(exports.all_notification_settings_labels, function (setting) {
        if (setting === 'enable_offline_push_notifications'
            && !page_params.realm_push_notifications_enabled) {
            // If push notifications are disabled at the realm level,
            // we should just leave the checkbox always off.
            return;
        }
        $("#" + setting).prop('checked', page_params[setting]);
    });
};

return exports;
}());

if (typeof module !== 'undefined') {
    module.exports = settings_notifications;
}
window.settings_notifications = settings_notifications;


text:
package com.nhl.link.move.mapper;

import java.util.Map;

import org.apache.cayenne.DataObject;
import org.apache.cayenne.exp.Expression;

/**
 * A mapper that does transparent conversion between object key value and a
 * map-friendly key.
 *
 * @since 1.1
 */
public class SafeMapKeyMapper implements Mapper {

	private Mapper delegate;
	private KeyAdapter keyAdapter;

	public SafeMapKeyMapper(Mapper delegate, KeyAdapter keyAdapter) {
		this.delegate = delegate;
		this.keyAdapter = keyAdapter;
	}

	@Override
	public Object keyForTarget(DataObject target) {
		return keyAdapter.toMapKey(delegate.keyForTarget(target));
	}

	@Override
	public Object keyForSource(Map<String, Object> source) {
		return keyAdapter.toMapKey(delegate.keyForSource(source));
	}

	@Override
	public Expression expressionForKey(Object key) {
		key = keyAdapter.fromMapKey(key);
		return delegate.expressionForKey(key);
	}
}


text:
<?php
namespace LeagueWrap\Api;

use LeagueWrap\Dto\RecentGames;

class Game extends AbstractApi {

	/**
	 * Valid version for this api call.
	 *
	 * @var array
	 */
	protected $versions = [
		'v1.3',
	];

	/**
	 * A list of all permitted regions for the Champion api call.
	 *
	 * @param array
	 */
	protected $permittedRegions = [
		'br',
		'eune',
		'euw',
		'lan',
		'las',
		'na',
		'oce',
		'kr',
		'ru',
		'tr',
		'jp'
	];

	/**
	 * @return String domain used for the request
	 */
	function getDomain()
	{
		return $this->getRegion()->getDefaultDomain();
	}

	/**
	 * The amount of time we intend to remember the response for.
	 *
	 * @var int
	 */
	protected $defaultRemember = 1800;

	/**
	 * Get the recent games by summoner id.
	 *
	 * @param Summoner|Int $identity
	 * @return array
	 */
	public function recent($identity)
	{
		$summonerId = $this->extractId($identity);

		$info  = $this->request('game/by-summoner/'.$summonerId.'/recent');
		$games = $this->attachStaticDataToDto(new RecentGames($info));

		$this->attachResponse($identity, $games, 'recentGames');

		return $games;
	}
}


text:
% [robot, scenedata] = SetupPA10Scene(scene,realrobot,randomize)

% Copyright (C) 2008-2010 Rosen Diankov
%
% Licensed under the Apache License, Version 2.0 (the "License");
% you may not use this file except in compliance with the License.
% You may obtain a copy of the License at
%     http://www.apache.org/licenses/LICENSE-2.0
%
% Unless required by applicable law or agreed to in writing, software
% distributed under the License is distributed on an "AS IS" BASIS,
% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
% See the License for the specific language governing permissions and
% limitations under the License.
function [robot, scenedata] = SetupPA10Scene(scene,randomize)
global updir probs robothome
if( ~exist('randomize','var') )
    randomize = [];
end

scenedata = [];

orEnvLoadScene('', 1);
pause(1);
while(1)
    orEnvLoadScene(scene);
    robots = orEnvGetRobots();
    if( length(robots) > 0 )
        break;
    end
    warning('no robots in scene');
end

robot = robots{1};
robot.activemanip = 1;
robot.manips = orRobotGetManipulators(robot.id);
robot.CreateHandFn = [];%@RobotCreateSchunkHand;
robot.testhandname = 'testhand';
robot.dof = orBodyGetDOF(robot.id);
orRobotSensorSend(robot.id,0,'power','0')

SetupProblems(robot.name);
orBodySetJointValues (robot.id,0.03,7); % move the gripper

orRobotSensorSend(robot.id,0,'power','0');

SwitchModelPatterns = {};
% objind = 1;
% SwitchModelPatterns{objind}.pattern = '^ricebox(\d)+$';
% SwitchModelPatterns{objind}.fatfilename = 'data/riceboxf.kinbody.xml';
% objind = objind + 1;

scenedata.convexfile = fullfile(tempdir(),'pa10gripper_convex.mat');
scenedata.visibilityfile = fullfile(tempdir(),'cereal_visibility_pa10.mat');
scenedata.graspsetfile = fullfile(tempdir(),'cereal_grasps_pa10.mat');
load('pa10_cereal.mat');
save('-ascii',scenedata.convexfile,'gripper_convex');
save('-ascii',scenedata.visibilityfile,'visibility');
save('-ascii',scenedata.graspsetfile,'grasps');

scenedata.targetid = orEnvGetBody ('frootloops');
scenedata.FindTarget = @() FindTarget('^frootloops');
[scenedata.targetname,scenedata.targetid] = scenedata.FindTarget();
scenedata.SwitchModelPatterns = SwitchModelPatterns;
scenedata.dests = [];
scenedata.home = orBodyGetJointValues(robot.id);

%% randomize robot position
if( ~isempty(randomize) )
    Trobot = reshape(orBodyGetTransform(robot.id),[3 4]);
    while(1)
        Tnew = Trobot;
        Tnew(1:2,4) = Tnew(1:2,4) + [-0.1;-0.5]+rand(2,1).*[0.3;1];
        orBodySetTransform(robot.id, Tnew);
        if( ~orEnvCheckCollision(robot.id) )
            break;
        end
    end
end

tablepattern = '^table$';
tableid = [];
bodies = orEnvGetBodies();
for i = 1:length(bodies)
    if( regexp(bodies{i}.name, tablepattern) )
        tableid = bodies{i}.id;
        break;
    end
end

if( ~isempty(tableid) )
    scenedata.dests = InsertRandomObjects(randomize,tableid,[scenedata.targetid robot.id],scenedata.targetid);
end


text:
<?php

/**
 * Interface providing list of contained values and an optional cache key to go along with it.
 */
interface EchoContainmentList {
	/**
	 * @return string[] The values contained within this list.
	 */
	public function getValues();

	/**
	 * @return string A string suitable for appending to the cache key prefix to facilitate
	 *                cache busting when the underlying data changes, or a blank string if
	 *                not relevant.
	 */
	public function getCacheKey();
}


text:
package org.apache.ignite.ml.tree.data;

import java.util.ArrayList;
import java.util.List;
import org.apache.ignite.ml.tree.TreeFilter;

/**
 * A partition {@code data} of the containing matrix of features and vector of labels stored in heap.
 */
public class DecisionTreeData implements AutoCloseable {
    /** Matrix with features. */
    private final double[][] features;

    /** Vector with labels. */
    private final double[] labels;

    /** Copy of vector with original labels. Auxiliary for Gradient Boosting on Trees.*/
    private double[] copyOfOriginalLabels;

    /** Indexes cache. */
    private final List<TreeDataIndex> indexesCache;

    /** Build index. */
    private final boolean buildIndex;

    /**
     * Constructs a new instance of decision tree data.
     *
     * @param features Matrix with features.
     * @param labels Vector with labels.
     * @param buildIdx Build index.
     */
    public DecisionTreeData(double[][] features, double[] labels, boolean buildIdx) {
        assert features.length == labels.length : "Features and labels have to be the same length";

        this.features = features;
        this.labels = labels;
        this.buildIndex = buildIdx;

        indexesCache = new ArrayList<>();
        if (buildIdx)
            indexesCache.add(new TreeDataIndex(features, labels));
    }

    /**
     * Filters objects and returns only data that passed filter.
     *
     * @param filter Filter.
     * @return Data passed filter.
     */
    public DecisionTreeData filter(TreeFilter filter) {
        int size = 0;

        for (int i = 0; i < features.length; i++)
            if (filter.test(features[i]))
                size++;

        double[][] newFeatures = new double[size][];
        double[] newLabels = new double[size];

        int ptr = 0;

        for (int i = 0; i < features.length; i++) {
            if (filter.test(features[i])) {
                newFeatures[ptr] = features[i];
                newLabels[ptr] = labels[i];

                ptr++;
            }
        }

        return new DecisionTreeData(newFeatures, newLabels, buildIndex);
    }

    /**
     * Sorts data by specified column in ascending order.
     *
     * @param col Column.
     */
    public void sort(int col) {
        sort(col, 0, features.length - 1);
    }

    /** */
    private void sort(int col, int from, int to) {
        if (from < to) {
            double pivot = features[(from + to) / 2][col];

            int i = from, j = to;

            while (i <= j) {
                while (features[i][col] < pivot)
                    i++;
                while (features[j][col] > pivot)
                    j--;

                if (i <= j) {
                    double[] tmpFeature = features[i];
                    features[i] = features[j];
                    features[j] = tmpFeature;

                    double tmpLb = labels[i];
                    labels[i] = labels[j];
                    labels[j] = tmpLb;

                    i++;
                    j--;
                }
            }

            sort(col, from, j);
            sort(col, i, to);
        }
    }

    /** */
    public double[][] getFeatures() {
        return features;
    }

    /** */
    public double[] getLabels() {
        return labels;
    }

    public double[] getCopyOfOriginalLabels() {
        return copyOfOriginalLabels;
    }

    public void setCopyOfOriginalLabels(double[] copyOfOriginalLabels) {
        this.copyOfOriginalLabels = copyOfOriginalLabels;
    }

    /** {@inheritDoc} */
    @Override public void close() {
        // Do nothing, GC will clean up.
    }

    /**
     * Builds index in according to current tree depth and cached indexes in upper levels. Uses depth as key of cached
     * index and replaces cached index with same key.
     *
     * @param depth Tree Depth.
     * @param filter Filter.
     */
    public TreeDataIndex createIndexByFilter(int depth, TreeFilter filter) {
        assert depth >= 0 && depth <= indexesCache.size();

        if (depth > 0 && depth <= indexesCache.size() - 1) {
            for (int i = indexesCache.size() - 1; i >= depth; i--)
                indexesCache.remove(i);
        }

        if (depth == indexesCache.size()) {
            if (depth == 0)
                indexesCache.add(new TreeDataIndex(features, labels));
            else {
                TreeDataIndex lastIndex = indexesCache.get(depth - 1);
                indexesCache.add(lastIndex.filter(filter));
            }
        }

        return indexesCache.get(depth);
    }
}


text:
using Rhea.Data;
using Rhea.Data.Account;
using Rhea.Data.Mongo;
using Rhea.Data.Mongo.Account;
using Rhea.Model;
using Rhea.Model.Account;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Rhea.Business.Account
{
    /// <summary>
    /// 权限业务类
    /// </summary>
    public class PrivilegeBusiness
    {
        #region Field
        /// <summary>
        /// 权限Repository
        /// </summary>
        private IPrivilegeRepository privilegeRepository;
        #endregion //Field

        #region Constructor
        /// <summary>
        /// 权限业务
        /// </summary>
        public PrivilegeBusiness()
        {
            this.privilegeRepository = new MongoPrivilegeRepository();
        }
        #endregion //Constructor

        #region Method
        /// <summary>
        /// 获取所有权限
        /// </summary>
        /// <returns></returns>
        public IEnumerable<Privilege> Get()
        {
            return this.privilegeRepository.Get().OrderBy(r => r.Sort);
        }

        /// <summary>
        /// 获取权限
        /// </summary>
        /// <param name="id">权限ID</param>
        /// <returns></returns>
        public Privilege Get(string id)
        {
            return this.privilegeRepository.Get(id);
        }

        /// <summary>
        /// 获取权限
        /// </summary>
        /// <param name="name">权限名称</param>
        /// <returns></returns>
        public Privilege GetByName(string name)
        {
            return this.privilegeRepository.GetByName(name);
        }

        /// <summary>
        /// 添加权限
        /// </summary>
        /// <param name="data">权限对象</param>
        /// <returns></returns>
        public ErrorCode Create(Privilege data)
        {
            data.Status = 0;
            return this.privilegeRepository.Create(data);
        }

        /// <summary>
        /// 编辑权限
        /// </summary>
        /// <param name="data">权限对象</param>
        /// <returns></returns>
        public ErrorCode Update(Privilege data)
        {
            return this.privilegeRepository.Update(data);
        }

        /// <summary>
        /// 删除权限
        /// </summary>
        /// <param name="id">权限ID</param>
        /// <returns></returns>
        public ErrorCode Delete(string id)
        {
            return this.privilegeRepository.Delete(id);
        }
        #endregion //Method
    }
}


text:
<!DOCTYPE html>
<html lang='en'>
  <head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
  </head>
  <body><script type="text/javascript" src="manifest.8a4dc9d2787e55669582.js"></script><script type="text/javascript" src="vendor.69806c38924e3a6c97ea.js"></script><script type="text/javascript" src="demo.799ad2817cb028ed4d8d.js"></script></body>
</html>


text:
@implementation SCGeneralNotification

+ (NSString *)object {
  return @"General.Notifications";
}

@end


text:
require 'rails/generators/active_record'

module ActiveRecord
  module Generators
    class TwoFactorAuthenticationGenerator < ActiveRecord::Generators::Base
      source_root File.expand_path("../templates", __FILE__)

      def copy_two_factor_authentication_migration
        migration_template "migration.rb", "db/migrate/two_factor_authentication_add_to_#{table_name}.rb"
      end

    end
  end
end


text:
short CVcColor::GetRed()
{
	short result;
	InvokeHelper(0x1, DISPATCH_PROPERTYGET, VT_I2, (void*)&result, NULL);
	return result;
}

void CVcColor::SetRed(short nNewValue)
{
	static BYTE parms[] =
		VTS_I2;
	InvokeHelper(0x1, DISPATCH_PROPERTYPUT, VT_EMPTY, NULL, parms,
		 nNewValue);
}

short CVcColor::GetGreen()
{
	short result;
	InvokeHelper(0x2, DISPATCH_PROPERTYGET, VT_I2, (void*)&result, NULL);
	return result;
}

void CVcColor::SetGreen(short nNewValue)
{
	static BYTE parms[] =
		VTS_I2;
	InvokeHelper(0x2, DISPATCH_PROPERTYPUT, VT_EMPTY, NULL, parms,
		 nNewValue);
}

short CVcColor::GetBlue()
{
	short result;
	InvokeHelper(0x3, DISPATCH_PROPERTYGET, VT_I2, (void*)&result, NULL);
	return result;
}

void CVcColor::SetBlue(short nNewValue)
{
	static BYTE parms[] =
		VTS_I2;
	InvokeHelper(0x3, DISPATCH_PROPERTYPUT, VT_EMPTY, NULL, parms,
		 nNewValue);
}

BOOL CVcColor::GetAutomatic()
{
	BOOL result;
	InvokeHelper(0x4, DISPATCH_PROPERTYGET, VT_BOOL, (void*)&result, NULL);
	return result;
}

void CVcColor::SetAutomatic(BOOL bNewValue)
{
	static BYTE parms[] =
		VTS_BOOL;
	InvokeHelper(0x4, DISPATCH_PROPERTYPUT, VT_EMPTY, NULL, parms,
		 bNewValue);
}

void CVcColor::Set(short Red, short Green, short Blue)
{
	static BYTE parms[] =
		VTS_I2 VTS_I2 VTS_I2;
	InvokeHelper(0x5, DISPATCH_METHOD, VT_EMPTY, NULL, parms,
		 Red, Green, Blue);
}


text:
The sample source codes on this page shows how to add barcode to report in Microsoft Access. Want to add barcode to report in your Microsoft Access app? ByteScout QR Code is designed for it. ByteScout QR Code is QR Code generation library. It provides full control on the quality, features and encoding. Can embed logo image right into QR Code itself. Batch barcode generation, and many special features like vCard or URL encoding are also supported.

You will save a lot of time on writing and testing code as you may just take the Microsoft Access code from ByteScout QR Code for add barcode to report below and use it in your application. In your Microsoft Access project or application you may simply copy & paste the code and then run your app! Test Microsoft Access sample code examples whether they respond your needs and requirements for the project.

ByteScout free trial version is available for download from our website. It includes all these programming tutorials along with source code samples.

## REQUEST FREE TECH SUPPORT

[Click here to get in touch](https://bytescout.zendesk.com/hc/en-us/requests/new?subject=ByteScout%20QR%20Code%20Question)

or just send email to [support@bytescout.com](mailto:support@bytescout.com?subject=ByteScout%20QR%20Code%20Question)

## ON-PREMISE OFFLINE SDK

[Get Your 60 Day Free Trial](https://bytescout.com/download/web-installer?utm_source=github-readme)
[Explore SDK Docs](https://bytescout.com/documentation/index.html?utm_source=github-readme)
[Sign Up For Online Training](https://academy.bytescout.com/)

## ON-DEMAND REST WEB API

[Get your API key](https://pdf.co/documentation/api?utm_source=github-readme)
[Explore Web API Documentation](https://pdf.co/documentation/api?utm_source=github-readme)
[Explore Web API Samples](https://github.com/bytescout/ByteScout-SDK-SourceCode/tree/master/PDF.co%20Web%20API)

## VIDEO REVIEW

[https://www.youtube.com/watch?v=A5hB9ul3tX0](https://www.youtube.com/watch?v=A5hB9ul3tX0)

<!-- code block begin -->

##### ****Barcode in Report.txt:**

```
1. Add reference to "ByteScout QRCode SDK" ActiveX object to your database project (in menu Tools->References).
2. Put Picture object on the Details section of the report.
3. Handle the Format event of the Details section and set barcode image to the Picture control.

Option Compare Database

Dim BarCodeGenerator

Private Sub Report_Open(Cancel As Integer)

    ' Setup the barcode generator
    Set BarCodeGenerator = CreateObject("Bytescout.BarCode.QRCode")
    BarCodeGenerator.RegistrationName = "demo"
    BarCodeGenerator.RegistrationKey = "demo"

End Sub

Private Sub Detail_Format(Cancel As Integer, FormatCount As Integer)

    ' Set barcode value
    BarCodeGenerator.Value = Me.Field1
    ' Set generated barcode image to Picture object
    Me.BarcodeImage.PictureData = BarCodeGenerator.GetImageBytesPNG()

End Sub

Private Sub Report_Close()

    ' Cleanup
    Set BarCodeGenerator = Nothing

End Sub

```

<!-- code block end -->


text:
module Octokit
  class Client

    # Methods for licenses API
    #
    module Licenses

      # List all licenses
      #
      # @see https://developer.github.com/v3/licenses/#list-all-licenses
      # @return [Array<Sawyer::Resource>] A list of licenses
      # @example
      #   Octokit.licenses
      def licenses(options = {})
        options = ensure_api_media_type(:licenses, options)
        paginate "licenses", options
      end

      # List an individual license
      #
      # @see https://developer.github.com/v3/licenses/#get-an-individual-license
      # @param license_name [String] The license name
      # @return <Sawyer::Resource> An individual license
      # @example
      #   Octokit.license 'mit'
      def license(license_name, options = {})
        options = ensure_api_media_type(:licenses, options)
        get "licenses/#{license_name}", options
      end
    end
  end
end


text:
/* Scheduler includes. */
#include "FreeRTOS.h"
#include "task.h"

/*-----------------------------------------------------------
 * Implementation of functions defined in portable.h for the MSP430 port.
 *----------------------------------------------------------*/

/* Constants required for hardware setup.  The tick ISR runs off the ACLK,
not the MCLK. */
#define portACLK_FREQUENCY_HZ			( ( portTickType ) 32768 )
#define portINITIAL_CRITICAL_NESTING	( ( unsigned short ) 10 )
#define portFLAGS_INT_ENABLED			( ( portSTACK_TYPE ) 0x08 )

/* We require the address of the pxCurrentTCB variable, but don't want to know
any details of its type. */
typedef void tskTCB;
extern volatile tskTCB * volatile pxCurrentTCB;

/* Each task maintains a count of the critical section nesting depth.  Each
time a critical section is entered the count is incremented.  Each time a
critical section is exited the count is decremented - with interrupts only
being re-enabled if the count is zero.

usCriticalNesting will get set to zero when the scheduler starts, but must
not be initialised to zero as this will cause problems during the startup
sequence. */
volatile unsigned short usCriticalNesting = portINITIAL_CRITICAL_NESTING;
/*-----------------------------------------------------------*/

/*
 * Sets up the periodic ISR used for the RTOS tick.  This uses timer 0, but
 * could have alternatively used the watchdog timer or timer 1.
 */
void prvSetupTimerInterrupt( void );
/*-----------------------------------------------------------*/

/*
 * Initialise the stack of a task to look exactly as if a call to
 * portSAVE_CONTEXT had been called.
 *
 * See the header file portable.h.
 */
portSTACK_TYPE *pxPortInitialiseStack( portSTACK_TYPE *pxTopOfStack, pdTASK_CODE pxCode, void *pvParameters )
{
	/*
		Place a few bytes of known values on the bottom of the stack.
		This is just useful for debugging and can be included if required.

		*pxTopOfStack = ( portSTACK_TYPE ) 0x1111;
		pxTopOfStack--;
		*pxTopOfStack = ( portSTACK_TYPE ) 0x2222;
		pxTopOfStack--;
		*pxTopOfStack = ( portSTACK_TYPE ) 0x3333;
		pxTopOfStack--;
	*/

	/* The msp430 automatically pushes the PC then SR onto the stack before
	executing an ISR.  We want the stack to look just as if this has happened
	so place a pointer to the start of the task on the stack first - followed
	by the flags we want the task to use when it starts up. */
	*pxTopOfStack = ( portSTACK_TYPE ) pxCode;
	pxTopOfStack--;
	*pxTopOfStack = portFLAGS_INT_ENABLED;
	pxTopOfStack--;

	/* Next the general purpose registers. */
	*pxTopOfStack = ( portSTACK_TYPE ) 0x4444;
	pxTopOfStack--;
	*pxTopOfStack = ( portSTACK_TYPE ) 0x5555;
	pxTopOfStack--;
	*pxTopOfStack = ( portSTACK_TYPE ) 0x6666;
	pxTopOfStack--;
	*pxTopOfStack = ( portSTACK_TYPE ) 0x7777;
	pxTopOfStack--;
	*pxTopOfStack = ( portSTACK_TYPE ) 0x8888;
	pxTopOfStack--;
	*pxTopOfStack = ( portSTACK_TYPE ) 0x9999;
	pxTopOfStack--;
	*pxTopOfStack = ( portSTACK_TYPE ) 0xaaaa;
	pxTopOfStack--;
	*pxTopOfStack = ( portSTACK_TYPE ) 0xbbbb;
	pxTopOfStack--;
	*pxTopOfStack = ( portSTACK_TYPE ) 0xcccc;
	pxTopOfStack--;
	*pxTopOfStack = ( portSTACK_TYPE ) 0xdddd;
	pxTopOfStack--;
	*pxTopOfStack = ( portSTACK_TYPE ) 0xeeee;
	pxTopOfStack--;

	/* When the task starts is will expect to find the function parameter in
	R15. */
	*pxTopOfStack = ( portSTACK_TYPE ) pvParameters;
	pxTopOfStack--;

	/* A variable is used to keep track of the critical section nesting.
	This variable has to be stored as part of the task context and is
	initially set to zero. */
	*pxTopOfStack = ( portSTACK_TYPE ) portNO_CRITICAL_SECTION_NESTING;

	/* Return a pointer to the top of the stack we have generated so this can
	be stored in the task control block for the task. */
	return pxTopOfStack;
}
/*-----------------------------------------------------------*/

void vPortEndScheduler( void )
{
	/* It is unlikely that the MSP430 port will get stopped.  If required simply
	disable the tick interrupt here. */
}
/*-----------------------------------------------------------*/

/*
 * Hardware initialisation to generate the RTOS tick.  This uses timer 0
 * but could alternatively use the watchdog timer or timer 1.
 */
void prvSetupTimerInterrupt( void )
{
	/* Ensure the timer is stopped. */
	TACTL = 0;

	/* Run the timer of the ACLK. */
	TACTL = TASSEL_1;

	/* Clear everything to start with. */
	TACTL |= TACLR;

	/* Set the compare match value according to the tick rate we want. */
	TACCR0 = portACLK_FREQUENCY_HZ / configTICK_RATE_HZ;

	/* Enable the interrupts. */
	TACCTL0 = CCIE;

	/* Start up clean. */
	TACTL |= TACLR;

	/* Up mode. */
	TACTL |= MC_1;
}
/*-----------------------------------------------------------*/


text:
import Ember from 'ember';

export default Ember.View.extend({
  classNames: ["application", "pushable"],

  // ---------------------------------- プロパティ

  sidebar: null,

  // ---------------------------------- アクション

  actions: {
    // サイドバーを表示
    showSidebar: function() {
      this.$(".sidebar.menu").sidebar("show");
    }
  },

  // ---------------------------------- メソッド

  // サイドバーを初期化する
  initSidebar: function() {
    this.set("sidebar", this.$(".sidebar.menu").sidebar({
      context: this.$(),
      transition: "uncover"
    }));
  }.on("didInsertElement"),

  // サイドバーを破壊する
  destroySidebar: function() {
    this.get("sidebar").sidebar("destroy");
  }.on("willDestroyElement"),

  // 選択を行った後、サイドバーを閉じる
  click: function() {
    if (this.get("sidebar").sidebar("is visible"))
      this.get("sidebar").sidebar("hide");
  }
});


text:
===========================
Wagtail 1.8.2 release notes
===========================

*April 21, 2017*

.. contents::
    :local:
    :depth: 1

What's changed
==============

Bug fixes
~~~~~~~~~

* Removed erroneous ``|safe`` filter from search results template in project template (Karl Hobley)
* Avoid indexing unsaved field content on ``save(update_fields=[...])`` operations (Matt Westcott)
* Prevent pages from being recursively copied into themselves (Matheus Bratfisch)


text:
~~Set of scripts~~ Microservice for controlling my garage door from a Raspberry Pi

![alt text](https://frinkiac.com/meme/S06E23/1075707.jpg?b64lines=IEhFWSwgRkVMTEFTLCBUSEUgR0FSQUdFLgogT09ILCBMQS1ESS1EQSwgTVIuIEZSRU5DSAogTUFOLiAKCgoKCgpXSEFUIERPIFlPVSBDQUxMIElUPwoKCiBBIENBUiBIT0xFLg== "A counterfit jeans ring operating out of my carhole!")

Wiring instructions from [Idiot's Guide to a Raspberry Pi Garage Door Opener by Chris Driscoll](https://web.archive.org/web/20161108145900/http://www.driscocity.com/idiots-guide-to-a-raspberry-pi-garage-door-opener/)

Site is currently flagged for malware, link goes to [Internet Archive](https://archive.org/web/) cache.

## Installation

1. Wire up the Raspberry Pi with the guide above
2. sudo apt-get install python-pip
3. sudo pip install flask
4. Copy SSL cert and key to directory or generate a self-signed one: `openssl req -x509 -newkey rsa:4096 -keyout carholekey.pem -out carholecert.pem -days 3650 -nodes`
5. Edit `config-example` and save as `config.py`
6. sudo python carhole.py

The server runs https on port 443

There is a secret key configured in `config.py` that must be included in `application/x-www-form-urlencoded` content type in each request or the request will return a `Invalid Key` error.

A `POST` request to `/operate` will operate the door.

A `POST` request to `/checkdoor` will return `Open` or `Closed`

**Security Warning!**

While this script makes efforts to operate securely, nothing is perfect and new vulnerabilites are discovered all the time, be sure to evaluate and mitigate the potential risks by blocking all, or limiting to only port 443, exposure to the Internet and apply updates to keep all components as new fixes are released.

Example of a Python script to check door status

```python
import requests

r = requests.post('https://YOUR ADDRESS/checkdoor', data={'key':'YOUR KEY'}, verify='YOUR CERTFILE')

print r.text
```

## Using with [Home Assistant](https://home-assistant.io/)
Example script and configuration.yaml files for using in conjunction with Home Assistant are included in ./homeassistant

## Stand Alone Scripts
These scripts can be run from the shell independently of carhole.py

### checkdoor.py
Checks state of door, returns `Open` or `Closed`

### useedoor.py
Operates the door

### tasker.xml
Task to import into Tasker to operate the door


text:
Extensibility Points
----
There are are a few points in Kaiseki where you can extend the build repertoire.
### Custom Tasks ###
As part of the build process, when Load-Modules.ps1 is invoked, all Task-*.ps1 are invoked. This facilitates the loading of custom defined tasks.

To actually invoke the task, modify the .\kaiseki-bootstrap\build.ps1 and supply a list of tasks through the "tasklist" parameter; for example:
```
.\packages\psake.x.x.x\tools\psake.ps1 .\packages\Kaiseki.x.x.x\tools\Load-Modules.ps1 -tasklist Execute-MsBuild,Copy-NUnit
```
This place also allows you to pass in additional parameters and properties. For full documentation, please visit [PSake](https://github.com/psake/psake)

###Extra assets to be user in later pipeline stages###
Kaiseki automatically scans the nuget packages for folders that starts with "kkm-" and copies those folders into the CiArtefact folder. One such example is the "kkm-defaults" folder that comes with Kaiseki which facilitate recursive WebDeploy, NUnit testing with target category, recursive nuget package publishing.


text:
package apple.avfaudio;

import apple.NSObject;
import apple.avfaudio.protocol.AVAudioMixing;
import apple.avfaudio.struct.AVAudio3DPoint;
import apple.foundation.NSArray;
import apple.foundation.NSMethodSignature;
import apple.foundation.NSSet;
import org.moe.natj.c.ann.FunctionPtr;
import org.moe.natj.general.NatJ;
import org.moe.natj.general.Pointer;
import org.moe.natj.general.ann.ByValue;
import org.moe.natj.general.ann.Generated;
import org.moe.natj.general.ann.Library;
import org.moe.natj.general.ann.Mapped;
import org.moe.natj.general.ann.NInt;
import org.moe.natj.general.ann.NUInt;
import org.moe.natj.general.ann.Owned;
import org.moe.natj.general.ann.Runtime;
import org.moe.natj.general.ptr.VoidPtr;
import org.moe.natj.objc.Class;
import org.moe.natj.objc.ObjCRuntime;
import org.moe.natj.objc.SEL;
import org.moe.natj.objc.ann.ObjCBlock;
import org.moe.natj.objc.ann.ObjCClassBinding;
import org.moe.natj.objc.ann.Selector;
import org.moe.natj.objc.map.ObjCObjectMapper;

/**
 * AVAudioPlayerNode
 *

 * Play buffers or segments of audio files.
 *

 * AVAudioPlayerNode supports scheduling the playback of `AVAudioBuffer` instances,
 * or segments of audio files opened via `AVAudioFile`. Buffers and segments may be
 * scheduled at specific points in time, or to play immediately following preceding segments.
 *

 * FORMATS
 *

 * Normally, you will want to configure the node's output format with the same number of
 * channels as are in the files and buffers to be played. Otherwise, channels will be dropped
 * or added as required. It is usually better to use an `AVAudioMixerNode` to
 * do this.
 *

 * Similarly, when playing file segments, the node will sample rate convert if necessary, but
 * it is often preferable to configure the node's output sample rate to match that of the file(s)
 * and use a mixer to perform the rate conversion.
 *

 * When playing buffers, there is an implicit assumption that the buffers are at the same
 * sample rate as the node's output format.
 *

 * TIMELINES
 *

 * The usual `AVAudioNode` sample times (as observed by `lastRenderTime`)
 * have an arbitrary zero point. AVAudioPlayerNode superimposes a second "player timeline" on
 * top of this, to reflect when the player was started, and intervals during which it was
 * paused. The methods `nodeTimeForPlayerTime:` and `playerTimeForNodeTime:`
 * convert between the two.
 *

 * This class' `stop` method unschedules all previously scheduled buffers and
 * file segments, and returns the player timeline to sample time 0.
 *

 * TIMESTAMPS
 *

 * The "schedule" methods all take an `AVAudioTime` "when" parameter. This is
 * interpreted as follows:
 *

 * 1. nil:
 * - if there have been previous commands, the new one is played immediately following the
 * last one.
 * - otherwise, if the node is playing, the event is played in the very near future.
 * - otherwise, the command is played at sample time 0.
 * 2. sample time:
 * - relative to the node's start time (which begins at 0 when the node is started).
 * 3. host time:
 * - ignored unless the sample time is invalid when the engine is rendering to an audio
 * device.
 * - ignored in manual rendering mode.
 *

 * ERRORS
 *

 * The "schedule" methods can fail if:
 *

 * 1. a buffer's channel count does not match that of the node's output format.
 * 2. a file can't be accessed.
 * 3. an AVAudioTime specifies neither a valid sample time or host time.
 * 4. a segment's start frame or frame count is negative.
 *

 * BUFFER/FILE COMPLETION HANDLERS
 *

 * The buffer or file completion handlers (see scheduling methods) are a means to schedule
 * more data if available on the player node. See `AVAudioPlayerNodeCompletionCallbackType`
 * for details on the different buffer/file completion callback types.
 *

 * Note that a player should not be stopped from within a completion handler callback because
 * it can deadlock while trying to unschedule previously scheduled buffers.
 *

 * OFFLINE RENDERING
 *

 * When a player node is used with the engine operating in the manual rendering mode, the
 * buffer/file completion handlers, `lastRenderTime` and the latencies (`latency` and
 * `outputPresentationLatency`) can be used to track how much data the player has rendered and
 * how much more data is left to render.
 */
@Generated
@Library("AVFAudio")
@Runtime(ObjCRuntime.class)
@ObjCClassBinding
public class AVAudioPlayerNode extends AVAudioNode implements AVAudioMixing {
    static {
        NatJ.register();
    }

    @Generated
    protected AVAudioPlayerNode(Pointer peer) {
        super(peer);
    }

    @Generated
    @Selector("accessInstanceVariablesDirectly")
    public static native boolean accessInstanceVariablesDirectly();

    @Generated
    @Owned
    @Selector("alloc")
    public static native AVAudioPlayerNode alloc();

    @Owned
    @Generated
    @Selector("allocWithZone:")
    public static native AVAudioPlayerNode allocWithZone(VoidPtr zone);

    @Generated
    @Selector("automaticallyNotifiesObserversForKey:")
    public static native boolean automaticallyNotifiesObserversForKey(String key);

    @Generated
    @Selector("cancelPreviousPerformRequestsWithTarget:")
    public static native void cancelPreviousPerformRequestsWithTarget(@Mapped(ObjCObjectMapper.class) Object aTarget);

    @Generated
    @Selector("cancelPreviousPerformRequestsWithTarget:selector:object:")
    public static native void cancelPreviousPerformRequestsWithTargetSelectorObject(
            @Mapped(ObjCObjectMapper.class) Object aTarget, SEL aSelector,
            @Mapped(ObjCObjectMapper.class) Object anArgument);

    @Generated
    @Selector("classFallbacksForKeyedArchiver")
    public static native NSArray<String> classFallbacksForKeyedArchiver();

    @Generated
    @Selector("classForKeyedUnarchiver")
    public static native Class classForKeyedUnarchiver();

    @Generated
    @Selector("debugDescription")
    public static native String debugDescription_static();

    @Generated
    @Selector("description")
    public static native String description_static();

    @Generated
    @Selector("destinationForMixer:bus:")
    public native AVAudioMixingDestination destinationForMixerBus(AVAudioNode mixer, @NUInt long bus);

    @Generated
    @Selector("hash")
    @NUInt
    public static native long hash_static();

    @Generated
    @Selector("init")
    public native AVAudioPlayerNode init();

    @Generated
    @Selector("instanceMethodForSelector:")
    @FunctionPtr(name = "call_instanceMethodForSelector_ret")
    public static native NSObject.Function_instanceMethodForSelector_ret instanceMethodForSelector(SEL aSelector);

    @Generated
    @Selector("instanceMethodSignatureForSelector:")
    public static native NSMethodSignature instanceMethodSignatureForSelector(SEL aSelector);

    @Generated
    @Selector("instancesRespondToSelector:")
    public static native boolean instancesRespondToSelector(SEL aSelector);

    /**
     * [@property] playing
     *

     * Indicates whether or not the player is playing.
     */
    @Generated
    @Selector("isPlaying")
    public native boolean isPlaying();

    @Generated
    @Selector("isSubclassOfClass:")
    public static native boolean isSubclassOfClass(Class aClass);

    @Generated
    @Selector("keyPathsForValuesAffectingValueForKey:")
    public static native NSSet<String> keyPathsForValuesAffectingValueForKey(String key);

    @Generated
    @Owned
    @Selector("new")
    public static native AVAudioPlayerNode new_objc();

    /**
     * nodeTimeForPlayerTime:
     *

     * Convert from player time to node time.
     *

     * This method and its inverse `playerTimeForNodeTime:` are discussed in the
     * introduction to this class.
     *

     * If the player is not playing when this method is called, nil is returned.
     *
     * @param playerTime a time relative to the player's start time
     * @return a node time
     */
    @Generated
    @Selector("nodeTimeForPlayerTime:")
    public native AVAudioTime nodeTimeForPlayerTime(AVAudioTime playerTime);

    @Generated
    @Selector("obstruction")
    public native float obstruction();

    @Generated
    @Selector("occlusion")
    public native float occlusion();

    @Generated
    @Selector("pan")
    public native float pan();

    /**
     * pause
     *

     * Pause playback.
     *

     * The player's sample time does not advance while the node is paused.
     *

     * Note that pausing or stopping all the players connected to an engine does not pause or stop
     * the engine or the underlying hardware. The engine must be explicitly paused or stopped for
     * the hardware to stop.
     */
    @Generated
    @Selector("pause")
    public native void pause();

    /**
     * play
     *

     * Start or resume playback immediately.
     *

     * equivalent to playAtTime:nil
     */
    @Generated
    @Selector("play")
    public native void play();

    /**
     * playAtTime:
     *

     * Start or resume playback at a specific time.
     *

     * This node is initially paused. Requests to play buffers or file segments are enqueued, and
     * any necessary decoding begins immediately. Playback does not begin, however, until the player
     * has started playing, via this method.
     *

     * Note that providing an AVAudioTime which is past (before lastRenderTime) will cause the
     * player to begin playback immediately.
     *

     * E.g. To start a player X seconds in future:
     *

     * // start engine and player
     * NSError *nsErr = nil;
     * [_engine startAndReturnError:&nsErr];
     * if (!nsErr) {
     * const float kStartDelayTime = 0.5; // sec
     * AVAudioFormat *outputFormat = [_player outputFormatForBus:0];
     * AVAudioFramePosition startSampleTime = _player.lastRenderTime.sampleTime + kStartDelayTime *
     * outputFormat.sampleRate;
     * AVAudioTime *startTime = [AVAudioTime timeWithSampleTime:startSampleTime atRate:outputFormat.sampleRate];
     * [_player playAtTime:startTime];
     * }
     *

     *
     * @param when the node time at which to start or resume playback. nil signifies "now".
     */
    @Generated
    @Selector("playAtTime:")
    public native void playAtTime(AVAudioTime when);

    /**
     * playerTimeForNodeTime:
     *

     * Convert from node time to player time.
     *

     * This method and its inverse `nodeTimeForPlayerTime:` are discussed in the
     * introduction to this class.
     *

     * If the player is not playing when this method is called, nil is returned.
     *
     * @param nodeTime a node time
     * @return a time relative to the player's start time
     */
    @Generated
    @Selector("playerTimeForNodeTime:")
    public native AVAudioTime playerTimeForNodeTime(AVAudioTime nodeTime);

    @Generated
    @Selector("pointSourceInHeadMode")
    @NInt
    public native long pointSourceInHeadMode();

    @Generated
    @Selector("position")
    @ByValue
    public native AVAudio3DPoint position();

    /**
     * prepareWithFrameCount:
     *

     * Prepares previously scheduled file regions or buffers for playback.
     *
     * @param frameCount The number of sample frames of data to be prepared before returning.
     */
    @Generated
    @Selector("prepareWithFrameCount:")
    public native void prepareWithFrameCount(int frameCount);

    @Generated
    @Selector("rate")
    public native float rate();

    @Generated
    @Selector("renderingAlgorithm")
    @NInt
    public native long renderingAlgorithm();

    @Generated
    @Selector("resolveClassMethod:")
    public static native boolean resolveClassMethod(SEL sel);

    @Generated
    @Selector("resolveInstanceMethod:")
    public static native boolean resolveInstanceMethod(SEL sel);

    @Generated
    @Selector("reverbBlend")
    public native float reverbBlend();

    /**
     * scheduleBuffer:atTime:options:completionCallbackType:completionHandler:
     *

     * Schedule playing samples from an AVAudioBuffer.
     *
     * @param buffer            the buffer to play
     * @param when              the time at which to play the buffer. see the discussion of timestamps, above.
     * @param options           options for looping, interrupting other buffers, etc.
     * @param callbackType      option to specify when the completion handler must be called
     * @param completionHandler called after the buffer has been consumed by the player or has finished playing back or
     *                          the player is stopped. may be nil.
     */
    @Generated
    @Selector("scheduleBuffer:atTime:options:completionCallbackType:completionHandler:")
    public native void scheduleBufferAtTimeOptionsCompletionCallbackTypeCompletionHandler(AVAudioPCMBuffer buffer,
            AVAudioTime when, @NUInt long options, @NInt long callbackType,
            @ObjCBlock(name = "call_scheduleBufferAtTimeOptionsCompletionCallbackTypeCompletionHandler") Block_scheduleBufferAtTimeOptionsCompletionCallbackTypeCompletionHandler completionHandler);

    @Runtime(ObjCRuntime.class)
    @Generated
    public interface Block_scheduleBufferAtTimeOptionsCompletionCallbackTypeCompletionHandler {
        @Generated
        void call_scheduleBufferAtTimeOptionsCompletionCallbackTypeCompletionHandler(@NInt long callbackType);
    }

    /**
     * scheduleBuffer:atTime:options:completionHandler:
     *

     * Schedule playing samples from an AVAudioBuffer.
     *

     * It is possible for the completionHandler to be called before rendering begins
     * or before the buffer is played completely.
     *
     * @param buffer            the buffer to play
     * @param when              the time at which to play the buffer. see the discussion of timestamps, above.
     * @param options           options for looping, interrupting other buffers, etc.
     * @param completionHandler called after the buffer has been consumed by the player or the player is stopped. may be
     *                          nil.
     */
    @Generated
    @Selector("scheduleBuffer:atTime:options:completionHandler:")
    public native void scheduleBufferAtTimeOptionsCompletionHandler(AVAudioPCMBuffer buffer, AVAudioTime when,
            @NUInt long options,
            @ObjCBlock(name = "call_scheduleBufferAtTimeOptionsCompletionHandler") Block_scheduleBufferAtTimeOptionsCompletionHandler completionHandler);

    @Runtime(ObjCRuntime.class)
    @Generated
    public interface Block_scheduleBufferAtTimeOptionsCompletionHandler {
        @Generated
        void call_scheduleBufferAtTimeOptionsCompletionHandler();
    }

    /**
     * scheduleBuffer:completionCallbackType:completionHandler:
     *

     * Schedule playing samples from an AVAudioBuffer.
     *

     * Schedules the buffer to be played following any previously scheduled commands.
     *
     * @param buffer            the buffer to play
     * @param callbackType      option to specify when the completion handler must be called
     * @param completionHandler called after the buffer has been consumed by the player or has finished playing back or
     *                          the player is stopped. may be nil.
     */
    @Generated
    @Selector("scheduleBuffer:completionCallbackType:completionHandler:")
    public native void scheduleBufferCompletionCallbackTypeCompletionHandler(AVAudioPCMBuffer buffer,
            @NInt long callbackType,
            @ObjCBlock(name = "call_scheduleBufferCompletionCallbackTypeCompletionHandler") Block_scheduleBufferCompletionCallbackTypeCompletionHandler completionHandler);

    @Runtime(ObjCRuntime.class)
    @Generated
    public interface Block_scheduleBufferCompletionCallbackTypeCompletionHandler {
        @Generated
        void call_scheduleBufferCompletionCallbackTypeCompletionHandler(@NInt long callbackType);
    }

    /**
     * scheduleBuffer:completionHandler:
     *

     * Schedule playing samples from an AVAudioBuffer.
     *

     * Schedules the buffer to be played following any previously scheduled commands.
     *

     * It is possible for the completionHandler to be called before rendering begins
     * or before the buffer is played completely.
     *
     * @param buffer            the buffer to play
     * @param completionHandler called after the buffer has been consumed by the player or the player is stopped. may be
     *                          nil.
     */
    @Generated
    @Selector("scheduleBuffer:completionHandler:")
    public native void scheduleBufferCompletionHandler(AVAudioPCMBuffer buffer,
            @ObjCBlock(name = "call_scheduleBufferCompletionHandler") Block_scheduleBufferCompletionHandler completionHandler);

    @Runtime(ObjCRuntime.class)
    @Generated
    public interface Block_scheduleBufferCompletionHandler {
        @Generated
        void call_scheduleBufferCompletionHandler();
    }

    /**
     * scheduleFile:atTime:completionCallbackType:completionHandler:
     *

     * Schedule playing of an entire audio file.
     *
     * @param file              the file to play
     * @param when              the time at which to play the file. see the discussion of timestamps, above.
     * @param callbackType      option to specify when the completion handler must be called
     * @param completionHandler called after the file has been consumed by the player or has finished playing back or
     *                          the player is stopped. may be nil.
     */
    @Generated
    @Selector("scheduleFile:atTime:completionCallbackType:completionHandler:")
    public native void scheduleFileAtTimeCompletionCallbackTypeCompletionHandler(AVAudioFile file, AVAudioTime when,
            @NInt long callbackType,
            @ObjCBlock(name = "call_scheduleFileAtTimeCompletionCallbackTypeCompletionHandler") Block_scheduleFileAtTimeCompletionCallbackTypeCompletionHandler completionHandler);

    @Runtime(ObjCRuntime.class)
    @Generated
    public interface Block_scheduleFileAtTimeCompletionCallbackTypeCompletionHandler {
        @Generated
        void call_scheduleFileAtTimeCompletionCallbackTypeCompletionHandler(@NInt long callbackType);
    }

    /**
     * scheduleFile:atTime:completionHandler:
     *

     * Schedule playing of an entire audio file.
     *

     * It is possible for the completionHandler to be called before rendering begins
     * or before the file is played completely.
     *
     * @param file              the file to play
     * @param when              the time at which to play the file. see the discussion of timestamps, above.
     * @param completionHandler called after the file has been consumed by the player or the player is stopped. may be
     *                          nil.
     */
    @Generated
    @Selector("scheduleFile:atTime:completionHandler:")
    public native void scheduleFileAtTimeCompletionHandler(AVAudioFile file, AVAudioTime when,
            @ObjCBlock(name = "call_scheduleFileAtTimeCompletionHandler") Block_scheduleFileAtTimeCompletionHandler completionHandler);

    @Runtime(ObjCRuntime.class)
    @Generated
    public interface Block_scheduleFileAtTimeCompletionHandler {
        @Generated
        void call_scheduleFileAtTimeCompletionHandler();
    }

    /**
     * scheduleSegment:startingFrame:frameCount:atTime:completionCallbackType:completionHandler:
     *

     * Schedule playing a segment of an audio file.
     *
     * @param file              the file to play
     * @param startFrame        the starting frame position in the stream
     * @param numberFrames      the number of frames to play
     * @param when              the time at which to play the region. see the discussion of timestamps, above.
     * @param callbackType      option to specify when the completion handler must be called
     * @param completionHandler called after the segment has been consumed by the player or has finished playing back or
     *                          the player is stopped. may be nil.
     */
    @Generated
    @Selector("scheduleSegment:startingFrame:frameCount:atTime:completionCallbackType:completionHandler:")
    public native void scheduleSegmentStartingFrameFrameCountAtTimeCompletionCallbackTypeCompletionHandler(
            AVAudioFile file, long startFrame, int numberFrames, AVAudioTime when, @NInt long callbackType,
            @ObjCBlock(name = "call_scheduleSegmentStartingFrameFrameCountAtTimeCompletionCallbackTypeCompletionHandler") Block_scheduleSegmentStartingFrameFrameCountAtTimeCompletionCallbackTypeCompletionHandler completionHandler);

    @Runtime(ObjCRuntime.class)
    @Generated
    public interface Block_scheduleSegmentStartingFrameFrameCountAtTimeCompletionCallbackTypeCompletionHandler {
        @Generated
        void call_scheduleSegmentStartingFrameFrameCountAtTimeCompletionCallbackTypeCompletionHandler(
                @NInt long callbackType);
    }

    /**
     * scheduleSegment:startingFrame:frameCount:atTime:completionHandler:
     *

     * Schedule playing a segment of an audio file.
     *

     * It is possible for the completionHandler to be called before rendering begins
     * or before the segment is played completely.
     *
     * @param file              the file to play
     * @param startFrame        the starting frame position in the stream
     * @param numberFrames      the number of frames to play
     * @param when              the time at which to play the region. see the discussion of timestamps, above.
     * @param completionHandler called after the segment has been consumed by the player or the player is stopped. may
     *                          be nil.
     */
    @Generated
    @Selector("scheduleSegment:startingFrame:frameCount:atTime:completionHandler:")
    public native void scheduleSegmentStartingFrameFrameCountAtTimeCompletionHandler(AVAudioFile file, long startFrame,
            int numberFrames, AVAudioTime when,
            @ObjCBlock(name = "call_scheduleSegmentStartingFrameFrameCountAtTimeCompletionHandler") Block_scheduleSegmentStartingFrameFrameCountAtTimeCompletionHandler completionHandler);

    @Runtime(ObjCRuntime.class)
    @Generated
    public interface Block_scheduleSegmentStartingFrameFrameCountAtTimeCompletionHandler {
        @Generated
        void call_scheduleSegmentStartingFrameFrameCountAtTimeCompletionHandler();
    }

    @Generated
    @Selector("setObstruction:")
    public native void setObstruction(float value);

    @Generated
    @Selector("setOcclusion:")
    public native void setOcclusion(float value);

    @Generated
    @Selector("setPan:")
    public native void setPan(float value);

    @Generated
    @Selector("setPointSourceInHeadMode:")
    public native void setPointSourceInHeadMode(@NInt long value);

    @Generated
    @Selector("setPosition:")
    public native void setPosition(@ByValue AVAudio3DPoint value);

    @Generated
    @Selector("setRate:")
    public native void setRate(float value);

    @Generated
    @Selector("setRenderingAlgorithm:")
    public native void setRenderingAlgorithm(@NInt long value);

    @Generated
    @Selector("setReverbBlend:")
    public native void setReverbBlend(float value);

    @Generated
    @Selector("setSourceMode:")
    public native void setSourceMode(@NInt long value);

    @Generated
    @Selector("setVersion:")
    public static native void setVersion_static(@NInt long aVersion);

    @Generated
    @Selector("setVolume:")
    public native void setVolume(float value);

    @Generated
    @Selector("sourceMode")
    @NInt
    public native long sourceMode();

    /**
     * stop
     *

     * Clear all of the node's previously scheduled events and stop playback.
     *

     * All of the node's previously scheduled events are cleared, including any that are in the
     * middle of playing. The node's sample time (and therefore the times to which new events are
     * to be scheduled) is reset to 0, and will not proceed until the node is started again (via
     * play or playAtTime).
     *

     * Note that pausing or stopping all the players connected to an engine does not pause or stop
     * the engine or the underlying hardware. The engine must be explicitly paused or stopped for
     * the hardware to stop.
     */
    @Generated
    @Selector("stop")
    public native void stop();

    @Generated
    @Selector("superclass")
    public static native Class superclass_static();

    @Generated
    @Selector("version")
    @NInt
    public static native long version_static();

    @Generated
    @Selector("volume")
    public native float volume();
}


text:
<?php

namespace Omnipay\Ceca\Message;

use Omnipay\Common\Message\AbstractResponse;
use Omnipay\RedSys\ResponseCode;

/**
 * RedSys Complete Purchase Response     SWISNL
 */
class CompletePurchaseResponse extends AbstractResponse
{
    public function isSuccessful()
    {
        return $this->getCode();
        return preg_match('/^00[0-9][0-9]$/', $this->getCode());
    }

    public function getCode()
    {
        return $this->data == 200;
        return $this->data['Ds_Response'];
    }

    public function getMessage()
    {
        $responseCode = ResponseCode::find($this->getCode());
        return $responseCode ? $responseCode->getDescription() : null;
    }

    public function getTransactionReference()
    {
        return $this->data['Ds_Order'];
    }

    public function getTransactionId()
    {
        return $this->data['Ds_Order'];
    }
}


text:
package org.thoughtslive.jenkins.plugins.jira.api;

import java.io.Serializable;

import org.kohsuke.stapler.DataBoundConstructor;

import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;

import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.ToString;

@Data
@ToString
@NoArgsConstructor
@AllArgsConstructor(onConstructor = @__({@DataBoundConstructor}))
@JsonInclude(JsonInclude.Include.NON_DEFAULT)
@JsonIgnoreProperties(ignoreUnknown = true)
@Builder
public class Priority implements Serializable {

	private static final long serialVersionUID = -2000658126252180101L;

	@JsonProperty("name")
	private String name;

	@JsonProperty("id")
	private String id;

}


text:
require 'pstore'

module DasCatalog
  module Store
    class UUIDMismatch < StandardError; end

    extend self

    def pstore
      @pstore ||= PStore.new(DasCatalog.tracker_file)
    end

    def reset
      pstore.transaction do
        pstore.roots.each do |key|
          pstore.delete key
        end
      end
    end

    def find(id)
      pstore.transaction(true) do
        pstore[id]
      end
    end

    def all
      pstore.transaction(true) do
        pstore.roots.collect do |name|
          pstore[name]
        end
      end
    end

    def store(screencast_data)
      if sd = find(screencast_data.id)
        raise UUIDMismatch if sd.uuid && sd.uuid != screencast_data.uuid
      end

      pstore.transaction do
        pstore[screencast_data.id] = screencast_data
      end
    end
  end
end


text:
<?php
namespace App\Commands;
use App\Build\GitPullWorker;
use App\Utils\ValidateArgs;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Style\SymfonyStyle;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;

/**
 * User: mike
 * @version 7/4/17
 */class PullCommand extends Command {

     use ValidateArgs;

	public function configure () {
		$this->setName("pull")
             ->setDescription("Pull changes from a git repository.")
             ->addArgument('repo', InputArgument::REQUIRED, 'The Repo to clone or pull in changes from')
             ->addArgument('target', InputArgument::OPTIONAL, 'Where to put the code (synonymous with --target option).', './')
             ->addOption('keyfile', 'i', InputOption::VALUE_OPTIONAL, 'Path to SSH private Keyfile (if required for pulling.) NOTE: You can alternatively use an ssh config file host in your repo name, i.e. github:foo/bar.git')
             ->addOption('branch', 'b', InputOption::VALUE_OPTIONAL, 'The Branch to pull from', 'master');
	}

	public function execute (InputInterface $in, OutputInterface $out) {
		$this->validate("has:target,dir", $in);
	    new GitPullWorker($in, $out);
	}
}


text:
package Mojo::Server::Daemon;
use Mojo::Base 'Mojo::Server';

use Carp 'croak';
use Mojo::IOLoop;
use Mojo::Transaction::WebSocket;
use Mojo::URL;
use Mojo::Util qw(deprecated term_escape);
use Mojo::WebSocket 'server_handshake';
use Scalar::Util 'weaken';

use constant DEBUG => $ENV{MOJO_DAEMON_DEBUG} || 0;

has acceptors => sub { [] };
has [qw(backlog max_clients silent)];
has inactivity_timeout => sub { $ENV{MOJO_INACTIVITY_TIMEOUT} // 15 };
has ioloop => sub { Mojo::IOLoop->singleton };
has listen => sub { [split ',', $ENV{MOJO_LISTEN} || 'http://*:3000'] };
has max_requests => 100;

sub DESTROY {
  return if Mojo::Util::_global_destruction();
  my $self = shift;
  $self->_remove($_) for keys %{$self->{connections} || {}};
  my $loop = $self->ioloop;
  $loop->remove($_) for @{$self->acceptors};
}

# DEPRECATED!
sub multi_accept {
  deprecated 'Mojo::Server::Daemon::multi_accept is DEPRECATED';
  @_ > 1 ? $_[0] : undef;
}

sub run {
  my $self = shift;

  # Make sure the event loop can be stopped in regular intervals
  my $loop = $self->ioloop;
  my $int = $loop->recurring(1 => sub { });
  local $SIG{INT} = local $SIG{TERM} = sub { $loop->stop };
  $self->start->ioloop->start;
  $loop->remove($int);
}

sub start {
  my $self = shift;

  my $loop = $self->ioloop;
  if (my $max = $self->max_clients) { $loop->max_connections($max) }

  # Resume accepting connections
  if (my $servers = $self->{servers}) {
    push @{$self->acceptors}, $loop->acceptor(delete $servers->{$_})
      for keys %$servers;
  }

  # Start listening
  elsif (!@{$self->acceptors}) { $self->_listen($_) for @{$self->listen} }

  return $self;
}

sub stop {
  my $self = shift;

  # Suspend accepting connections but keep listen sockets open
  my $loop = $self->ioloop;
  while (my $id = shift @{$self->acceptors}) {
    my $server = $self->{servers}{$id} = $loop->acceptor($id);
    $loop->remove($id);
    $server->stop;
  }

  return $self;
}

sub _build_tx {
  my ($self, $id, $c) = @_;

  my $tx = $self->build_tx->connection($id);
  $tx->res->headers->server('Mojolicious (Perl)');
  my $handle = $self->ioloop->stream($id)->handle;
  $tx->local_address($handle->sockhost)->local_port($handle->sockport);
  $tx->remote_address($handle->peerhost)->remote_port($handle->peerport);
  $tx->req->url->base->scheme('https') if $c->{tls};

  weaken $self;
  $tx->on(
    request => sub {
      my $tx = shift;

      # WebSocket
      if ($tx->req->is_handshake) {
        my $ws = $self->{connections}{$id}{next}
          = Mojo::Transaction::WebSocket->new(handshake => $tx);
        $self->emit(request => server_handshake $ws);
      }

      # HTTP
      else { $self->emit(request => $tx) }

      # Last keep-alive request or corrupted connection
      my $c = $self->{connections}{$id};
      $tx->res->headers->connection('close')
        if $c->{requests} >= $self->max_requests || $tx->req->error;

      $tx->on(resume => sub { $self->_write($id) });
      $self->_write($id);
    }
  );

  # Kept alive if we have more than one request on the connection
  return ++$c->{requests} > 1 ? $tx->kept_alive(1) : $tx;
}

sub _close {
  my ($self, $id) = @_;
  if (my $tx = $self->{connections}{$id}{tx}) { $tx->closed }
  delete $self->{connections}{$id};
}

sub _debug { $_[0]->app->log->debug($_[2]) if $_[0]{connections}{$_[1]}{tx} }

sub _finish {
  my ($self, $id) = @_;

  # Always remove connection for WebSockets
  my $c = $self->{connections}{$id};
  return unless my $tx = $c->{tx};
  return $self->_remove($id) if $tx->is_websocket;

  # Finish transaction
  delete($c->{tx})->closed;

  # Upgrade connection to WebSocket
  if (my $ws = delete $c->{next}) {

    # Successful upgrade
    if ($ws->handshake->res->code == 101) {
      $c->{tx} = $ws->established(1);
      weaken $self;
      $ws->on(resume => sub { $self->_write($id) });
      $self->_write($id);
    }

    # Failed upgrade
    else { $ws->closed }
  }

  # Close connection if necessary
  return $self->_remove($id) if $tx->error || !$tx->keep_alive;

  # Build new transaction for leftovers
  return unless length(my $leftovers = $tx->req->content->leftovers);
  $tx = $c->{tx} = $self->_build_tx($id, $c);
  $tx->server_read($leftovers);
}

sub _listen {
  my ($self, $listen) = @_;

  my $url   = Mojo::URL->new($listen);
  my $proto = $url->protocol;
  croak qq{Invalid listen location "$listen"} unless $proto =~ /^https?$/;

  my $query   = $url->query;
  my $options = {
    address       => $url->host,
    backlog       => $self->backlog,
    single_accept => $query->param('single_accept'),
    reuse         => $query->param('reuse')
  };
  if (my $port = $url->port) { $options->{port} = $port }
  $options->{"tls_$_"} = $query->param($_) for qw(ca ciphers version);
  /^(.*)_(cert|key)$/ and $options->{"tls_$2"}{$1} = $query->param($_)
    for @{$query->names};
  if (my $cert = $query->param('cert')) { $options->{'tls_cert'}{''} = $cert }
  if (my $key  = $query->param('key'))  { $options->{'tls_key'}{''}  = $key }
  my $verify = $query->param('verify');
  $options->{tls_verify} = hex $verify if defined $verify;
  delete $options->{address} if $options->{address} eq '*';
  my $tls = $options->{tls} = $proto eq 'https';

  weaken $self;
  push @{$self->acceptors}, $self->ioloop->server(
    $options => sub {
      my ($loop, $stream, $id) = @_;

      $self->{connections}{$id} = {tls => $tls};
      warn "-- Accept $id (@{[$stream->handle->peerhost]})\n" if DEBUG;
      $stream->timeout($self->inactivity_timeout);

      $stream->on(close => sub { $self && $self->_close($id) });
      $stream->on(error =>
          sub { $self && $self->app->log->error(pop) && $self->_close($id) });
      $stream->on(read => sub { $self->_read($id => pop) });
      $stream->on(timeout => sub { $self->_debug($id, 'Inactivity timeout') });
    }
  );

  return if $self->silent;
  $self->app->log->info(qq{Listening at "$url"});
  $query->pairs([]);
  $url->host('127.0.0.1') if $url->host eq '*';
  say "Server available at $url";
}

sub _read {
  my ($self, $id, $chunk) = @_;

  # Make sure we have a transaction
  my $c = $self->{connections}{$id};
  my $tx = $c->{tx} ||= $self->_build_tx($id, $c);
  warn term_escape "-- Server <<< Client (@{[_url($tx)]})\n$chunk\n" if DEBUG;
  $tx->server_read($chunk);
}

sub _remove {
  my ($self, $id) = @_;
  $self->ioloop->remove($id);
  $self->_close($id);
}

sub _url { shift->req->url->to_abs }

sub _write {
  my ($self, $id) = @_;

  # Protect from resume event recursion
  my $c = $self->{connections}{$id};
  return if !(my $tx = $c->{tx}) || $c->{writing};
  local $c->{writing} = 1;
  my $chunk = $tx->server_write;
  warn term_escape "-- Server >>> Client (@{[_url($tx)]})\n$chunk\n" if DEBUG;
  my $next = $tx->is_finished ? '_finish' : length $chunk ? '_write' : undef;
  return $self->ioloop->stream($id)->write($chunk) unless $next;
  weaken $self;
  $self->ioloop->stream($id)->write($chunk => sub { $self->$next($id) });
}

1;

=encoding utf8

=head1 NAME

Mojo::Server::Daemon - Non-blocking I/O HTTP and WebSocket server

=head1 SYNOPSIS

  use Mojo::Server::Daemon;

  my $daemon = Mojo::Server::Daemon->new(listen => ['http://*:8080']);
  $daemon->unsubscribe('request')->on(request => sub {
    my ($daemon, $tx) = @_;

    # Request
    my $method = $tx->req->method;
    my $path   = $tx->req->url->path;

    # Response
    $tx->res->code(200);
    $tx->res->headers->content_type('text/plain');
    $tx->res->body("$method request for $path!");

    # Resume transaction
    $tx->resume;
  });
  $daemon->run;

=head1 DESCRIPTION

L<Mojo::Server::Daemon> is a full featured, highly portable non-blocking I/O
HTTP and WebSocket server, with IPv6, TLS, SNI, Comet (long polling), keep-alive
and multiple event loop support.

For better scalability (epoll, kqueue) and to provide non-blocking name
resolution, SOCKS5 as well as TLS support, the optional modules L<EV> (4.0+),
L<Net::DNS::Native> (0.15+), L<IO::Socket::Socks> (0.64+) and
L<IO::Socket::SSL> (1.94+) will be used automatically if possible. Individual
features can also be disabled with the C<MOJO_NO_NDN>, C<MOJO_NO_SOCKS> and
C<MOJO_NO_TLS> environment variables.

See L<Mojolicious::Guides::Cookbook/"DEPLOYMENT"> for more.

=head1 SIGNALS

The L<Mojo::Server::Daemon> process can be controlled at runtime with the
following signals.

=head2 INT, TERM

Shut down server immediately.

=head1 EVENTS

L<Mojo::Server::Daemon> inherits all events from L<Mojo::Server>.

=head1 ATTRIBUTES

L<Mojo::Server::Daemon> inherits all attributes from L<Mojo::Server> and
implements the following new ones.

=head2 acceptors

  my $acceptors = $daemon->acceptors;
  $daemon       = $daemon->acceptors(['6be0c140ef00a389c5d039536b56d139']);

Active acceptor ids.

  # Check port
  mu $port = $daemon->ioloop->acceptor($daemon->acceptors->[0])->port;

=head2 backlog

  my $backlog = $daemon->backlog;
  $daemon     = $daemon->backlog(128);

Listen backlog size, defaults to C<SOMAXCONN>.

=head2 inactivity_timeout

  my $timeout = $daemon->inactivity_timeout;
  $daemon     = $daemon->inactivity_timeout(5);

Maximum amount of time in seconds a connection can be inactive before getting
closed, defaults to the value of the C<MOJO_INACTIVITY_TIMEOUT> environment
variable or C<15>. Setting the value to C<0> will allow connections to be
inactive indefinitely.

=head2 ioloop

  my $loop = $daemon->ioloop;
  $daemon  = $daemon->ioloop(Mojo::IOLoop->new);

Event loop object to use for I/O operations, defaults to the global
L<Mojo::IOLoop> singleton.

=head2 listen

  my $listen = $daemon->listen;
  $daemon    = $daemon->listen(['https://127.0.0.1:8080']);

Array reference with one or more locations to listen on, defaults to the value
of the C<MOJO_LISTEN> environment variable or C<http://*:3000> (shortcut for
C<http://0.0.0.0:3000>).

  # Listen on all IPv4 interfaces
  $daemon->listen(['http://*:3000']);

  # Listen on all IPv4 and IPv6 interfaces
  $daemon->listen(['http://[::]:3000']);

  # Listen on IPv6 interface
  $daemon->listen(['http://[::1]:4000']);

  # Listen on IPv4 and IPv6 interfaces
  $daemon->listen(['http://127.0.0.1:3000', 'http://[::1]:3000']);

  # Allow multiple servers to use the same port (SO_REUSEPORT)
  $daemon->listen(['http://*:8080?reuse=1']);

  # Listen on two ports with HTTP and HTTPS at the same time
  $daemon->listen(['http://*:3000', 'https://*:4000']);

  # Use a custom certificate and key
  $daemon->listen(['https://*:3000?cert=/x/server.crt&key=/y/server.key']);

  # Domain specific certificates and keys (SNI)
  $daemon->listen(
    ['https://*:3000?example.com_cert=/x/my.crt&example.com_key=/y/my.key']);

  # Or even a custom certificate authority
  $daemon->listen(
    ['https://*:3000?cert=/x/server.crt&key=/y/server.key&ca=/z/ca.crt']);

These parameters are currently available:

=over 2

=item ca

  ca=/etc/tls/ca.crt

Path to TLS certificate authority file used to verify the peer certificate.

=item cert

  cert=/etc/tls/server.crt
  mojolicious.org_cert=/etc/tls/mojo.crt

Path to the TLS cert file, defaults to a built-in test certificate.

=item ciphers

  ciphers=AES128-GCM-SHA256:RC4:HIGH:!MD5:!aNULL:!EDH

TLS cipher specification string. For more information about the format see
L<https://www.openssl.org/docs/manmaster/apps/ciphers.html#CIPHER-STRINGS>.

=item key

  key=/etc/tls/server.key
  mojolicious.org_key=/etc/tls/mojo.key

Path to the TLS key file, defaults to a built-in test key.

=item reuse

  reuse=1

Allow multiple servers to use the same port with the C<SO_REUSEPORT> socket
option.

=item single_accept

  single_accept=1

Only accept one connection at a time.

=item verify

  verify=0x00

TLS verification mode, defaults to C<0x03>.

=item version

  version=TLSv1_2

TLS protocol version.

=back

=head2 max_clients

  my $max = $daemon->max_clients;
  $daemon = $daemon->max_clients(100);

Maximum number of accepted connections this server is allowed to handle
concurrently, before stopping to accept new incoming connections, passed along
to L<Mojo::IOLoop/"max_connections">.

=head2 max_requests

  my $max = $daemon->max_requests;
  $daemon = $daemon->max_requests(250);

Maximum number of keep-alive requests per connection, defaults to C<100>.

=head2 silent

  my $bool = $daemon->silent;
  $daemon  = $daemon->silent($bool);

Disable console messages.

=head1 METHODS

L<Mojo::Server::Daemon> inherits all methods from L<Mojo::Server> and
implements the following new ones.

=head2 run

  $daemon->run;

Run server and wait for L</"SIGNALS">.

=head2 start

  $daemon = $daemon->start;

Start or resume accepting connections through L</"ioloop">.

  # Listen on random port
  my $id   = $daemon->listen(['http://127.0.0.1'])->start->acceptors->[0];
  my $port = $daemon->ioloop->acceptor($id)->port;

  # Run multiple web servers concurrently
  my $daemon1 = Mojo::Server::Daemon->new(listen => ['http://*:3000'])->start;
  my $daemon2 = Mojo::Server::Daemon->new(listen => ['http://*:4000'])->start;
  Mojo::IOLoop->start unless Mojo::IOLoop->is_running;

=head2 stop

  $daemon = $daemon->stop;

Stop accepting connections through L</"ioloop">.

=head1 DEBUGGING

You can set the C<MOJO_DAEMON_DEBUG> environment variable to get some advanced
diagnostics information printed to C<STDERR>.

  MOJO_DAEMON_DEBUG=1

=head1 SEE ALSO

L<Mojolicious>, L<Mojolicious::Guides>, L<http://mojolicious.org>.

=cut


text:
[![NuGet version](https://badge.fury.io/nu/DotNetKit.Wpf.AutoCompleteComboBox.svg)](https://badge.fury.io/nu/DotNetKit.Wpf.AutoCompleteComboBox)

Provides a lightweight combobox with filtering (auto-complete).

## Screenshot
![](documents/images/screenshot.gif)

## Usage
[Install via NuGet](https://www.nuget.org/packages/DotNetKit.Wpf.AutoCompleteComboBox).

Declare XML namespace.

```xml
<Window
    ...
    xmlns:dotNetKitControls="clr-namespace:DotNetKit.Windows.Controls;assembly=DotNetKit.Wpf.AutoCompleteComboBox"
    ... >
```

Then you can use `AutoCompleteComboBox`. It's like a normal `ComboBox` because of inheritance.

```xml
<dotNetKitControls:AutoCompleteComboBox
    SelectedValuePath="Id"
    TextSearch.TextPath="Name"
    ItemsSource="{Binding Items}"
    SelectedItem="{Binding SelectedItem}"
    SelectedValue="{Binding SelectedValue}"
    />
```

Note that:

- Set a property path to ``TextSearch.TextPath`` property.
    - The path leads to a property whose getter produces a string value to identify items. For example, assume each item is an instance of `Person`, which has `Name` property, and the property path is "Name". If the user input "va", the combobox filters the items to remove ones (persons) whose `Name` don't contain "va".
    - No support for ``TextSeach.Text``.
- Don't use ``ComboBox.Items`` property directly. Use `ItemsSource` instead.
- Although the Demo project uses DataTemplate to display items, you can also use `DisplayMemberPath`.

### Configuration
This library works fine in the default setting, however, it also provides how to configure.

- Define a class derived from [DotNetKit.Windows.Controls.AutoCompleteComboBoxSetting](DotNetKit.Wpf.AutoCompleteComboBox/Windows/Controls/AutoCompleteComboBoxSetting.cs) to override some of properties.
- Set the instance to ``AutoCompleteComboBox.Setting`` property.

```xml
<dotNetKitControls:AutoCompleteComboBox
    Setting="..."
    ...
    />
```

- Or set to ``AutoCompleteComboBoxSetting.Default`` to apply to all comboboxes.

### Performance
Filtering allows you to add a lot of items to a combobox without loss of usability, however, that makes the performance poor. To get rid of the issue, we recommend you to use `VirtualizingStackPanel` as the panel.

Use `ItemsPanel` property:

```csharp
<dotNetKitControls:AutoCompleteComboBox ...>
    <dotNetKitControls:AutoCompleteComboBox.ItemsPanel>
        <ItemsPanelTemplate>
            <VirtualizingStackPanel />
        </ItemsPanelTemplate>
    </dotNetKitControls:AutoCompleteComboBox.ItemsPanel>
</dotNetKitControls:AutoCompleteComboBox>
```

or declare a style in resources as the Demo app does.

See also [WPF: Using a VirtualizingStackPanel to Improve ComboBox Performance](http://vbcity.com/blogs/xtab/archive/2009/12/15/wpf-using-a-virtualizingstackpanel-to-improve-combobox-performance.aspx) for more detailed explanation.