text:
class ArticlesController < ApplicationController
  before_action :logged_in_user, only: [:new, :edit]
  before_action :admin_user,     only: [:create, :new, :edit, :update, :destroy]

  def index
    @articles = Article.paginate(page: params[:page])
  end

  def show
    get_article
    article_published?
  end

  def new
    @article = Article.new
  end

  def create
    @article = Article.new(article_params)
    if @article.save
      flash[:success] = "Успешно създаване на статия."
      redirect_to @article
    else
      render 'new'
    end
  end

  def edit
    get_article
  end

  def update
    get_article
    if @article.update_attributes(article_params)
      flash[:success] = "Успешно обновяване на статията."
      redirect_to @article
    else
      render 'edit'
    end
  end

  def destroy
    Article.find(params[:id]).destroy
    flash[:success] = "Статия изтрита."
    redirect_to articles_path
  end

  private

    def get_article # to fix
      begin
        @article = Article.find(params[:id])
      rescue ActiveRecord::RecordNotFound
        redirect_to root_url
        return
      end
    end

    def article_params
      params.require(:article).permit(:title, :content, :published)
    end

    def article_published?
      unless (@article && @article.published?) || (current_user && current_user.admin)
        flash[:warning] = "Страницата не е намерена."
        redirect_to root_url
      end
    end

    # Confirms a logged-in user.
    def logged_in_user
      unless logged_in?
        store_location
        flash[:danger] = "Влез в профила си."
        redirect_to login_url
      end
    end

    # Confirms an admin user.
    def admin_user
      redirect_to(root_url) unless current_user.admin?
    end
end


text:
layout : person
name : Joseph Franc
categories : alumni
uniquename: jfranc
major: Computer Science
title: Undergraduate Student
level: undergrad
bio: "I am an undergraduate student at the University of Michigan that expects to graduate with a Bachelor in Computer Science & Engineering in 2018.  I develop software to analyze the digitized motion of Grapsus crabs."
---

redpajama_set_name: RedPajamaGithub


text:
import logging

from django.contrib.auth.models import User
from nose.tools import assert_equal

import desktop.conf as desktop_conf
from desktop.lib.test_utils import reformat_xml

from liboozie import conf
from liboozie.types import WorkflowAction, Coordinator
from liboozie.utils import config_gen
from oozie.tests import MockOozieApi

LOG = logging.getLogger(__name__)

def test_valid_external_id():
  action = WorkflowAction(MockOozieApi.JSON_WORKFLOW_LIST[0])
  assert_equal('job_201208072118_0044', action.externalId)
  assert_equal('/jobbrowser/jobs/job_201208072118_0044/single_logs', action.get_absolute_log_url())
  assert_equal('/jobbrowser/jobs/job_201208072118_0044', action.get_external_id_url())

  action = WorkflowAction(MockOozieApi.JSON_WORKFLOW_LIST[1])
  assert_equal('-', action.externalId)
  assert_equal(None, action.get_absolute_log_url())
  assert_equal(None, action.get_external_id_url())

  action = WorkflowAction(MockOozieApi.JSON_WORKFLOW_LIST[2])
  assert_equal('', action.externalId)
  assert_equal(None, action.get_absolute_log_url())
  assert_equal(None, action.get_external_id_url())

  action = WorkflowAction(MockOozieApi.JSON_WORKFLOW_LIST[3])
  assert_equal(None, action.externalId)
  assert_equal(None, action.get_absolute_log_url())
  assert_equal(None, action.get_external_id_url())

def aggregate_coordinator_instances():
  dates = ['1', '2', '3', '6', '7', '8', '10', '12', '15', '16', '20', '23', '30', '40']
  assert_equal(['1-3', '6-8', '10-10', '12-12', '15-16', '20-20', '23-23', '30-30', '40-40'], Coordinator.aggreate(dates))

def test_config_gen():
  properties = {
    'user.name': 'hue',
    'test.1': 'http://localhost/test?test1=test&test2=test'
  }
  assert_equal(reformat_xml("""<configuration>
<property>
  <name>test.1</name>
  <value><![CDATA[http://localhost/test?test1=test&test2=test]]></value>
</property>
<property>
  <name>user.name</name>
  <value><![CDATA[hue]]></value>
</property>
</configuration>"""), reformat_xml(config_gen(properties)))

def test_ssl_validate():
  for desktop_kwargs, conf_kwargs, expected in [
      ({'present': False}, {'present': False}, True),
      ({'present': False}, {'data': False}, False),
      ({'present': False}, {'data': True}, True),

      ({'data': False}, {'present': False}, False),
      ({'data': False}, {'data': False}, False),
      ({'data': False}, {'data': True}, True),

      ({'data': True}, {'present': False}, True),
      ({'data': True}, {'data': False}, False),
      ({'data': True}, {'data': True}, True),
      ]:
    resets = [
      desktop_conf.SSL_VALIDATE.set_for_testing(**desktop_kwargs),
      conf.SSL_CERT_CA_VERIFY.set_for_testing(**conf_kwargs),
    ]

    try:
      assert_equal(conf.SSL_CERT_CA_VERIFY.get(), expected,
          'desktop:%s conf:%s expected:%s got:%s' % (desktop_kwargs, conf_kwargs, expected, conf.SSL_CERT_CA_VERIFY.get()))
    finally:
      for reset in resets:
        reset()


text:
import express from 'express';
import validate from 'express-validation';
import paramValidation from '../../config/param-validation';
import mapperCtrl from '../controllers/mapper.controller';

const router = express.Router(); // eslint-disable-line new-cap

router.route('/')
  /** GET /api/mapper - Get list of mapper */
  .get(mapperCtrl.list)

router.route('/:templateId')
  /** GET /api/mapper/:templateId - Get mapper */
  .get(mapperCtrl.getMapperByTemplateId)

export default router;


text:
div.dropdown-anchor {
    position:relative;
}

.dropdown-anchor > div.uat-sliding-panel {
    position: absolute;
}

.dropdown-anchor > .uat-sliding-panel ul.uat-dropdown-input-items-list{
    display:flex;
    flex:1;
    flex-direction:column;
    padding-left:0;
    list-style:none;
}


text:
<?php

if (!defined('CCADMIN')) { echo "NO DICE"; exit; }

$navigation = <<<EOD

		One-on-one chat plugins
		Chatroom plugins

EOD;

function index() {
	global $body;
	global $plugins;
	global $navigation;
        global $ts;
        global $plugininfo;

	$aplugins = array();

	if ($handle = opendir(dirname(dirname(__FILE__)).DIRECTORY_SEPARATOR.'plugins')) {
		while (false !== ($file = readdir($handle))) {
			if ($file != "." && $file != ".." && is_dir(dirname(dirname(__FILE__)).DIRECTORY_SEPARATOR.'plugins'.DIRECTORY_SEPARATOR.$file) && file_exists(dirname(dirname(__FILE__)).DIRECTORY_SEPARATOR.'plugins'.DIRECTORY_SEPARATOR.$file.DIRECTORY_SEPARATOR.'code.php') && file_exists(dirname(dirname(__FILE__)).DIRECTORY_SEPARATOR.'plugins'.DIRECTORY_SEPARATOR.$file.DIRECTORY_SEPARATOR.'init.js') && $file != 'style') {
				$aplugins[] = $file;
			}
		}
		closedir($handle);
	}

	$pluginslist = '';

	foreach ($aplugins as $plugin) {
		include_once( dirname(dirname(__FILE__)).DIRECTORY_SEPARATOR.'plugins'.DIRECTORY_SEPARATOR.$plugin.DIRECTORY_SEPARATOR.'code.php');
		$titles[$plugin] = $plugininfo;
		$pluginhref = 'href="?module=plugins&action=addplugin&data='.$plugininfo[0].'&ts='.$ts.'"';
		if (in_array($plugin, $plugins)) {
			$pluginhref = 'href="javascript: void(0)" style="opacity: 0.5;cursor: default;"';
		}

		$pluginslist .= '

'.$plugininfo[1].'add

';
	}

	$activeplugins = '';
	$no_plugins = '';
	$no = 0;

	foreach ($plugins as $ti) {

		$title = ucwords($ti);

		if (file_exists(dirname(dirname(__FILE__)).DIRECTORY_SEPARATOR.'plugins'.DIRECTORY_SEPARATOR.$ti.DIRECTORY_SEPARATOR.'code.php')) {
			$title = $titles[$ti][1];
		}

		++$no;

		$config = '';

		if (file_exists(dirname(dirname(__FILE__)).DIRECTORY_SEPARATOR.'plugins'.DIRECTORY_SEPARATOR.$ti.DIRECTORY_SEPARATOR.'settings.php')) {
			$config = ' ';
		}

		$activeplugins .= '

'.stripslashes($title).' '.$config.'

';
	}

	if(!$activeplugins){
		$no_plugins .= '
You have no Plugins activated at the moment. To activate a plugin, please add the plugin from the list of available plugins.
';
	}
	else{
		$activeplugins = '
'.$activeplugins.'
';
	}

	$body = <<<EOD
	$navigation

One-on-one Chat Plugins

Use your mouse to change the order in which the plugins appear in the chatbox (left-to-right). You can add available plugins from the right.

			{$no_plugins}
			{$activeplugins}

Available plugins

				$pluginslist

		<input type="button" onclick="javascript:plugins_updateorder()" value="Update order" class="button">  or cancel

EOD;

	template();

}

function updateorder() {

	if (!empty($_POST['order'])) {

		$plugindata = '$plugins = array(';

		$plugindata .= $_POST['order'];

		$plugindata = substr($plugindata,0,-1).');';

		configeditor('PLUGINS',$plugindata);
	} else {

		$plugindata = '$plugins = array();';
		configeditor('PLUGINS',$plugindata);

	}

	echo "1";

}

function addplugin() {
        global $ts;
	global $plugins;

	if (!empty($_GET['data'])) {

		$plugindata = '$plugins = array(';

		foreach ($plugins as $plugin) {
			$plugindata .= "'$plugin',";
		}

		$plugindata .= "'{$_GET['data']}',";

		$plugindata = substr($plugindata,0,-1).');';

		configeditor('PLUGINS',$plugindata);
	}

	header("Location:?module=plugins&ts={$ts}");
}

function chatroomplugins() {
	global $body;
	global $crplugins;
	global $navigation;
	global $lang;
        global $ts;
        global $plugininfo;

	$aplugins = array();

	if ($handle = opendir(dirname(dirname(__FILE__)).DIRECTORY_SEPARATOR.'plugins')) {
		while (false !== ($file = readdir($handle))) {
			if ($file != "." && $file != ".." && is_dir(dirname(dirname(__FILE__)).DIRECTORY_SEPARATOR.'plugins'.DIRECTORY_SEPARATOR.$file) && file_exists(dirname(dirname(__FILE__)).DIRECTORY_SEPARATOR.'plugins'.DIRECTORY_SEPARATOR.$file.DIRECTORY_SEPARATOR.'code.php') && file_exists(dirname(dirname(__FILE__)).DIRECTORY_SEPARATOR.'plugins'.DIRECTORY_SEPARATOR.$file.DIRECTORY_SEPARATOR.'crcompatible.php')) {
				$aplugins[] = $file;
			}
		}
		closedir($handle);
	}

	$pluginslist = '';

	foreach ($aplugins as $plugin) {
		include_once(dirname(dirname(__FILE__)).DIRECTORY_SEPARATOR.'plugins'.DIRECTORY_SEPARATOR.$plugin.DIRECTORY_SEPARATOR.'code.php');
		$crpluginhref = 'href="?module=plugins&action=addchatroomplugin&data='.$plugininfo[0].'&ts='.$ts.'"';
        if (in_array($plugin, $crplugins)) {
           $crpluginhref = 'href="javascript: void(0)" style="opacity: 0.5;cursor: default;"';
        }
        $pluginslist .= '

'.$plugininfo[1].'add

';

	}

	$activeplugins = '';
	$no_plugins = '';
	$no = 0;

	foreach ($crplugins as $ti) {

		$title = ucwords($ti);

		if (file_exists(dirname(dirname(__FILE__)).DIRECTORY_SEPARATOR.'plugins'.DIRECTORY_SEPARATOR.$ti.DIRECTORY_SEPARATOR.'lang'.DIRECTORY_SEPARATOR.'en.php')) {
			include_once(dirname(dirname(__FILE__)).DIRECTORY_SEPARATOR.'plugins'.DIRECTORY_SEPARATOR.$ti.DIRECTORY_SEPARATOR.'lang'.DIRECTORY_SEPARATOR.'en.php');
			$title = ${$ti."_language"}[0];
		}

		if (file_exists(dirname(dirname(__FILE__)).DIRECTORY_SEPARATOR.'plugins'.DIRECTORY_SEPARATOR.$ti.DIRECTORY_SEPARATOR.'lang'.DIRECTORY_SEPARATOR.$lang.'.php')) {
			include_once(dirname(dirname(__FILE__)).DIRECTORY_SEPARATOR.'plugins'.DIRECTORY_SEPARATOR.$ti.DIRECTORY_SEPARATOR.'lang'.DIRECTORY_SEPARATOR.$lang.'.php');
			$title = ${$ti."_language"}[0];
		}

		++$no;
		$config = '';

		if (file_exists(dirname(dirname(__FILE__)).DIRECTORY_SEPARATOR.'plugins'.DIRECTORY_SEPARATOR.$ti.DIRECTORY_SEPARATOR.'settings.php')) {
			$config = ' ';
		}

		$activeplugins .= '

'.stripslashes($title).''.$config.'

';
	}

	if(!$activeplugins){
		$no_plugins .= '
You do not have any Chatroom Plugins activated at the moment. To activate a plugin, please add the plugin from the list of available chatroom plugins.
';
	}
	else{
		$activeplugins = '
'.$activeplugins.'
';
	}

	$body = <<<EOD
	$navigation

Chatroom Plugins

Use your mouse to change the order in which the plugins appear in the chatroom (left-to-right). You can add available plugins from the right.

			{$no_plugins}
			{$activeplugins}

Available Chatroom plugins

				$pluginslist

		<input type="button" onclick="javascript:plugins_updatechatroomorder()" value="Update order" class="button">  or cancel

EOD;

	template();

}

function updatechatroomorder() {

	if (!empty($_POST['order'])) {

		$plugindata = '$crplugins = array(';

		$plugindata .= $_POST['order'];

		$plugindata = substr($plugindata,0,-1).');';

		configeditor('CHATROOMPLUGINS',$plugindata);
	} else {

		$plugindata = '$crplugins = array();';
		configeditor('CHATROOMPLUGINS',$plugindata);

	}

	echo "1";

}

function addchatroomplugin() {
        global $ts;
	global $crplugins;

	if (!empty($_GET['data'])) {

		$plugindata = '$crplugins = array(';

		foreach ($crplugins as $plugin) {
			$plugindata .= "'$plugin',";
		}

		$plugindata .= "'{$_GET['data']}',";

		$plugindata = substr($plugindata,0,-1).');';

		configeditor('CHATROOMPLUGINS',$plugindata);
	}

	header("Location:?module=plugins&action=chatroomplugins&ts={$ts}");
}


text:
#include "spirv_cross_parsed_ir.hpp"
#include <algorithm>
#include <assert.h>

using namespace std;
using namespace spv;

namespace SPIRV_CROSS_NAMESPACE
{
ParsedIR::ParsedIR()
{
	// If we move ParsedIR, we need to make sure the pointer stays fixed since the child Variant objects consume a pointer to this group,
	// so need an extra pointer here.
	pool_group.reset(new ObjectPoolGroup);

	pool_group->pools[TypeType].reset(new ObjectPool<SPIRType>);
	pool_group->pools[TypeVariable].reset(new ObjectPool<SPIRVariable>);
	pool_group->pools[TypeConstant].reset(new ObjectPool<SPIRConstant>);
	pool_group->pools[TypeFunction].reset(new ObjectPool<SPIRFunction>);
	pool_group->pools[TypeFunctionPrototype].reset(new ObjectPool<SPIRFunctionPrototype>);
	pool_group->pools[TypeBlock].reset(new ObjectPool<SPIRBlock>);
	pool_group->pools[TypeExtension].reset(new ObjectPool<SPIRExtension>);
	pool_group->pools[TypeExpression].reset(new ObjectPool<SPIRExpression>);
	pool_group->pools[TypeConstantOp].reset(new ObjectPool<SPIRConstantOp>);
	pool_group->pools[TypeCombinedImageSampler].reset(new ObjectPool<SPIRCombinedImageSampler>);
	pool_group->pools[TypeAccessChain].reset(new ObjectPool<SPIRAccessChain>);
	pool_group->pools[TypeUndef].reset(new ObjectPool<SPIRUndef>);
	pool_group->pools[TypeString].reset(new ObjectPool<SPIRString>);
}

// Should have been default-implemented, but need this on MSVC 2013.
ParsedIR::ParsedIR(ParsedIR &&other) SPIRV_CROSS_NOEXCEPT
{
	*this = move(other);
}

ParsedIR &ParsedIR::operator=(ParsedIR &&other) SPIRV_CROSS_NOEXCEPT
{
	if (this != &other)
	{
		pool_group = move(other.pool_group);
		spirv = move(other.spirv);
		meta = move(other.meta);
		for (int i = 0; i < TypeCount; i++)
			ids_for_type[i] = move(other.ids_for_type[i]);
		ids_for_constant_or_type = move(other.ids_for_constant_or_type);
		ids_for_constant_or_variable = move(other.ids_for_constant_or_variable);
		declared_capabilities = move(other.declared_capabilities);
		declared_extensions = move(other.declared_extensions);
		block_meta = move(other.block_meta);
		continue_block_to_loop_header = move(other.continue_block_to_loop_header);
		entry_points = move(other.entry_points);
		ids = move(other.ids);
		addressing_model = other.addressing_model;
		memory_model = other.memory_model;

		default_entry_point = other.default_entry_point;
		source = other.source;
		loop_iteration_depth_hard = other.loop_iteration_depth_hard;
		loop_iteration_depth_soft = other.loop_iteration_depth_soft;
	}
	return *this;
}

ParsedIR::ParsedIR(const ParsedIR &other)
    : ParsedIR()
{
	*this = other;
}

ParsedIR &ParsedIR::operator=(const ParsedIR &other)
{
	if (this != &other)
	{
		spirv = other.spirv;
		meta = other.meta;
		for (int i = 0; i < TypeCount; i++)
			ids_for_type[i] = other.ids_for_type[i];
		ids_for_constant_or_type = other.ids_for_constant_or_type;
		ids_for_constant_or_variable = other.ids_for_constant_or_variable;
		declared_capabilities = other.declared_capabilities;
		declared_extensions = other.declared_extensions;
		block_meta = other.block_meta;
		continue_block_to_loop_header = other.continue_block_to_loop_header;
		entry_points = other.entry_points;
		default_entry_point = other.default_entry_point;
		source = other.source;
		loop_iteration_depth_hard = other.loop_iteration_depth_hard;
		loop_iteration_depth_soft = other.loop_iteration_depth_soft;
		addressing_model = other.addressing_model;
		memory_model = other.memory_model;

		// Very deliberate copying of IDs. There is no default copy constructor, nor a simple default constructor.
		// Construct object first so we have the correct allocator set-up, then we can copy object into our new pool group.
		ids.clear();
		ids.reserve(other.ids.size());
		for (size_t i = 0; i < other.ids.size(); i++)
		{
			ids.emplace_back(pool_group.get());
			ids.back() = other.ids[i];
		}
	}
	return *this;
}

void ParsedIR::set_id_bounds(uint32_t bounds)
{
	ids.reserve(bounds);
	while (ids.size() < bounds)
		ids.emplace_back(pool_group.get());

	block_meta.resize(bounds);
}

// Roll our own versions of these functions to avoid potential locale shenanigans.
static bool is_alpha(char c)
{
	return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z');
}

static bool is_alphanumeric(char c)
{
	return is_alpha(c) || (c >= '0' && c <= '9');
}

static string ensure_valid_identifier(const string &name, bool member)
{
	// Functions in glslangValidator are mangled with name(<mangled> stuff.
	// Normally, we would never see '(' in any legal identifiers, so just strip them out.
	auto str = name.substr(0, name.find('('));

	for (uint32_t i = 0; i < str.size(); i++)
	{
		auto &c = str[i];

		if (member)
		{
			// _m<num> variables are reserved by the internal implementation,
			// otherwise, make sure the name is a valid identifier.
			if (i == 0)
				c = is_alpha(c) ? c : '_';
			else if (i == 2 && str[0] == '_' && str[1] == 'm')
				c = is_alpha(c) ? c : '_';
			else
				c = is_alphanumeric(c) ? c : '_';
		}
		else
		{
			// _<num> variables are reserved by the internal implementation,
			// otherwise, make sure the name is a valid identifier.
			if (i == 0 || (str[0] == '_' && i == 1))
				c = is_alpha(c) ? c : '_';
			else
				c = is_alphanumeric(c) ? c : '_';
		}
	}
	return str;
}

const string &ParsedIR::get_name(ID id) const
{
	auto *m = find_meta(id);
	if (m)
		return m->decoration.alias;
	else
		return empty_string;
}

const string &ParsedIR::get_member_name(TypeID id, uint32_t index) const
{
	auto *m = find_meta(id);
	if (m)
	{
		if (index >= m->members.size())
			return empty_string;
		return m->members[index].alias;
	}
	else
		return empty_string;
}

void ParsedIR::set_name(ID id, const string &name)
{
	auto &str = meta[id].decoration.alias;
	str.clear();

	if (name.empty())
		return;

	// Reserved for temporaries.
	if (name[0] == '_' && name.size() >= 2 && isdigit(name[1]))
		return;

	str = ensure_valid_identifier(name, false);
}

void ParsedIR::set_member_name(TypeID id, uint32_t index, const string &name)
{
	meta[id].members.resize(max(meta[id].members.size(), size_t(index) + 1));

	auto &str = meta[id].members[index].alias;
	str.clear();
	if (name.empty())
		return;

	// Reserved for unnamed members.
	if (name[0] == '_' && name.size() >= 3 && name[1] == 'm' && isdigit(name[2]))
		return;

	str = ensure_valid_identifier(name, true);
}

void ParsedIR::set_decoration_string(ID id, Decoration decoration, const string &argument)
{
	auto &dec = meta[id].decoration;
	dec.decoration_flags.set(decoration);

	switch (decoration)
	{
	case DecorationHlslSemanticGOOGLE:
		dec.hlsl_semantic = argument;
		break;

	default:
		break;
	}
}

void ParsedIR::set_decoration(ID id, Decoration decoration, uint32_t argument)
{
	auto &dec = meta[id].decoration;
	dec.decoration_flags.set(decoration);

	switch (decoration)
	{
	case DecorationBuiltIn:
		dec.builtin = true;
		dec.builtin_type = static_cast<BuiltIn>(argument);
		break;

	case DecorationLocation:
		dec.location = argument;
		break;

	case DecorationComponent:
		dec.component = argument;
		break;

	case DecorationOffset:
		dec.offset = argument;
		break;

	case DecorationXfbBuffer:
		dec.xfb_buffer = argument;
		break;

	case DecorationXfbStride:
		dec.xfb_stride = argument;
		break;

	case DecorationArrayStride:
		dec.array_stride = argument;
		break;

	case DecorationMatrixStride:
		dec.matrix_stride = argument;
		break;

	case DecorationBinding:
		dec.binding = argument;
		break;

	case DecorationDescriptorSet:
		dec.set = argument;
		break;

	case DecorationInputAttachmentIndex:
		dec.input_attachment = argument;
		break;

	case DecorationSpecId:
		dec.spec_id = argument;
		break;

	case DecorationIndex:
		dec.index = argument;
		break;

	case DecorationHlslCounterBufferGOOGLE:
		meta[id].hlsl_magic_counter_buffer = argument;
		meta[argument].hlsl_is_magic_counter_buffer = true;
		break;

	case DecorationFPRoundingMode:
		dec.fp_rounding_mode = static_cast<FPRoundingMode>(argument);
		break;

	default:
		break;
	}
}

void ParsedIR::set_member_decoration(TypeID id, uint32_t index, Decoration decoration, uint32_t argument)
{
	meta[id].members.resize(max(meta[id].members.size(), size_t(index) + 1));
	auto &dec = meta[id].members[index];
	dec.decoration_flags.set(decoration);

	switch (decoration)
	{
	case DecorationBuiltIn:
		dec.builtin = true;
		dec.builtin_type = static_cast<BuiltIn>(argument);
		break;

	case DecorationLocation:
		dec.location = argument;
		break;

	case DecorationComponent:
		dec.component = argument;
		break;

	case DecorationBinding:
		dec.binding = argument;
		break;

	case DecorationOffset:
		dec.offset = argument;
		break;

	case DecorationXfbBuffer:
		dec.xfb_buffer = argument;
		break;

	case DecorationXfbStride:
		dec.xfb_stride = argument;
		break;

	case DecorationSpecId:
		dec.spec_id = argument;
		break;

	case DecorationMatrixStride:
		dec.matrix_stride = argument;
		break;

	case DecorationIndex:
		dec.index = argument;
		break;

	default:
		break;
	}
}

// Recursively marks any constants referenced by the specified constant instruction as being used
// as an array length. The id must be a constant instruction (SPIRConstant or SPIRConstantOp).
void ParsedIR::mark_used_as_array_length(ID id)
{
	switch (ids[id].get_type())
	{
	case TypeConstant:
		get<SPIRConstant>(id).is_used_as_array_length = true;
		break;

	case TypeConstantOp:
	{
		auto &cop = get<SPIRConstantOp>(id);
		if (cop.opcode == OpCompositeExtract)
			mark_used_as_array_length(cop.arguments[0]);
		else if (cop.opcode == OpCompositeInsert)
		{
			mark_used_as_array_length(cop.arguments[0]);
			mark_used_as_array_length(cop.arguments[1]);
		}
		else
			for (uint32_t arg_id : cop.arguments)
				mark_used_as_array_length(arg_id);
		break;
	}

	case TypeUndef:
		break;

	default:
		assert(0);
	}
}

Bitset ParsedIR::get_buffer_block_flags(const SPIRVariable &var) const
{
	auto &type = get<SPIRType>(var.basetype);
	assert(type.basetype == SPIRType::Struct);

	// Some flags like non-writable, non-readable are actually found
	// as member decorations. If all members have a decoration set, propagate
	// the decoration up as a regular variable decoration.
	Bitset base_flags;
	auto *m = find_meta(var.self);
	if (m)
		base_flags = m->decoration.decoration_flags;

	if (type.member_types.empty())
		return base_flags;

	Bitset all_members_flags = get_member_decoration_bitset(type.self, 0);
	for (uint32_t i = 1; i < uint32_t(type.member_types.size()); i++)
		all_members_flags.merge_and(get_member_decoration_bitset(type.self, i));

	base_flags.merge_or(all_members_flags);
	return base_flags;
}

const Bitset &ParsedIR::get_member_decoration_bitset(TypeID id, uint32_t index) const
{
	auto *m = find_meta(id);
	if (m)
	{
		if (index >= m->members.size())
			return cleared_bitset;
		return m->members[index].decoration_flags;
	}
	else
		return cleared_bitset;
}

bool ParsedIR::has_decoration(ID id, Decoration decoration) const
{
	return get_decoration_bitset(id).get(decoration);
}

uint32_t ParsedIR::get_decoration(ID id, Decoration decoration) const
{
	auto *m = find_meta(id);
	if (!m)
		return 0;

	auto &dec = m->decoration;
	if (!dec.decoration_flags.get(decoration))
		return 0;

	switch (decoration)
	{
	case DecorationBuiltIn:
		return dec.builtin_type;
	case DecorationLocation:
		return dec.location;
	case DecorationComponent:
		return dec.component;
	case DecorationOffset:
		return dec.offset;
	case DecorationXfbBuffer:
		return dec.xfb_buffer;
	case DecorationXfbStride:
		return dec.xfb_stride;
	case DecorationBinding:
		return dec.binding;
	case DecorationDescriptorSet:
		return dec.set;
	case DecorationInputAttachmentIndex:
		return dec.input_attachment;
	case DecorationSpecId:
		return dec.spec_id;
	case DecorationArrayStride:
		return dec.array_stride;
	case DecorationMatrixStride:
		return dec.matrix_stride;
	case DecorationIndex:
		return dec.index;
	case DecorationFPRoundingMode:
		return dec.fp_rounding_mode;
	default:
		return 1;
	}
}

const string &ParsedIR::get_decoration_string(ID id, Decoration decoration) const
{
	auto *m = find_meta(id);
	if (!m)
		return empty_string;

	auto &dec = m->decoration;

	if (!dec.decoration_flags.get(decoration))
		return empty_string;

	switch (decoration)
	{
	case DecorationHlslSemanticGOOGLE:
		return dec.hlsl_semantic;

	default:
		return empty_string;
	}
}

void ParsedIR::unset_decoration(ID id, Decoration decoration)
{
	auto &dec = meta[id].decoration;
	dec.decoration_flags.clear(decoration);
	switch (decoration)
	{
	case DecorationBuiltIn:
		dec.builtin = false;
		break;

	case DecorationLocation:
		dec.location = 0;
		break;

	case DecorationComponent:
		dec.component = 0;
		break;

	case DecorationOffset:
		dec.offset = 0;
		break;

	case DecorationXfbBuffer:
		dec.xfb_buffer = 0;
		break;

	case DecorationXfbStride:
		dec.xfb_stride = 0;
		break;

	case DecorationBinding:
		dec.binding = 0;
		break;

	case DecorationDescriptorSet:
		dec.set = 0;
		break;

	case DecorationInputAttachmentIndex:
		dec.input_attachment = 0;
		break;

	case DecorationSpecId:
		dec.spec_id = 0;
		break;

	case DecorationHlslSemanticGOOGLE:
		dec.hlsl_semantic.clear();
		break;

	case DecorationFPRoundingMode:
		dec.fp_rounding_mode = FPRoundingModeMax;
		break;

	case DecorationHlslCounterBufferGOOGLE:
	{
		auto &counter = meta[id].hlsl_magic_counter_buffer;
		if (counter)
		{
			meta[counter].hlsl_is_magic_counter_buffer = false;
			counter = 0;
		}
		break;
	}

	default:
		break;
	}
}

bool ParsedIR::has_member_decoration(TypeID id, uint32_t index, Decoration decoration) const
{
	return get_member_decoration_bitset(id, index).get(decoration);
}

uint32_t ParsedIR::get_member_decoration(TypeID id, uint32_t index, Decoration decoration) const
{
	auto *m = find_meta(id);
	if (!m)
		return 0;

	if (index >= m->members.size())
		return 0;

	auto &dec = m->members[index];
	if (!dec.decoration_flags.get(decoration))
		return 0;

	switch (decoration)
	{
	case DecorationBuiltIn:
		return dec.builtin_type;
	case DecorationLocation:
		return dec.location;
	case DecorationComponent:
		return dec.component;
	case DecorationBinding:
		return dec.binding;
	case DecorationOffset:
		return dec.offset;
	case DecorationXfbBuffer:
		return dec.xfb_buffer;
	case DecorationXfbStride:
		return dec.xfb_stride;
	case DecorationSpecId:
		return dec.spec_id;
	case DecorationIndex:
		return dec.index;
	default:
		return 1;
	}
}

const Bitset &ParsedIR::get_decoration_bitset(ID id) const
{
	auto *m = find_meta(id);
	if (m)
	{
		auto &dec = m->decoration;
		return dec.decoration_flags;
	}
	else
		return cleared_bitset;
}

void ParsedIR::set_member_decoration_string(TypeID id, uint32_t index, Decoration decoration, const string &argument)
{
	meta[id].members.resize(max(meta[id].members.size(), size_t(index) + 1));
	auto &dec = meta[id].members[index];
	dec.decoration_flags.set(decoration);

	switch (decoration)
	{
	case DecorationHlslSemanticGOOGLE:
		dec.hlsl_semantic = argument;
		break;

	default:
		break;
	}
}

const string &ParsedIR::get_member_decoration_string(TypeID id, uint32_t index, Decoration decoration) const
{
	auto *m = find_meta(id);
	if (m)
	{
		if (!has_member_decoration(id, index, decoration))
			return empty_string;

		auto &dec = m->members[index];

		switch (decoration)
		{
		case DecorationHlslSemanticGOOGLE:
			return dec.hlsl_semantic;

		default:
			return empty_string;
		}
	}
	else
		return empty_string;
}

void ParsedIR::unset_member_decoration(TypeID id, uint32_t index, Decoration decoration)
{
	auto &m = meta[id];
	if (index >= m.members.size())
		return;

	auto &dec = m.members[index];

	dec.decoration_flags.clear(decoration);
	switch (decoration)
	{
	case DecorationBuiltIn:
		dec.builtin = false;
		break;

	case DecorationLocation:
		dec.location = 0;
		break;

	case DecorationComponent:
		dec.component = 0;
		break;

	case DecorationOffset:
		dec.offset = 0;
		break;

	case DecorationXfbBuffer:
		dec.xfb_buffer = 0;
		break;

	case DecorationXfbStride:
		dec.xfb_stride = 0;
		break;

	case DecorationSpecId:
		dec.spec_id = 0;
		break;

	case DecorationHlslSemanticGOOGLE:
		dec.hlsl_semantic.clear();
		break;

	default:
		break;
	}
}

uint32_t ParsedIR::increase_bound_by(uint32_t incr_amount)
{
	auto curr_bound = ids.size();
	auto new_bound = curr_bound + incr_amount;

	ids.reserve(ids.size() + incr_amount);
	for (uint32_t i = 0; i < incr_amount; i++)
		ids.emplace_back(pool_group.get());

	block_meta.resize(new_bound);
	return uint32_t(curr_bound);
}

void ParsedIR::remove_typed_id(Types type, ID id)
{
	auto &type_ids = ids_for_type[type];
	type_ids.erase(remove(begin(type_ids), end(type_ids), id), end(type_ids));
}

void ParsedIR::reset_all_of_type(Types type)
{
	for (auto &id : ids_for_type[type])
		if (ids[id].get_type() == type)
			ids[id].reset();

	ids_for_type[type].clear();
}

void ParsedIR::add_typed_id(Types type, ID id)
{
	if (loop_iteration_depth_hard != 0)
		SPIRV_CROSS_THROW("Cannot add typed ID while looping over it.");

	if (loop_iteration_depth_soft != 0)
	{
		if (!ids[id].empty())
			SPIRV_CROSS_THROW("Cannot override IDs when loop is soft locked.");
		return;
	}

	if (ids[id].empty() || ids[id].get_type() != type)
	{
		switch (type)
		{
		case TypeConstant:
			ids_for_constant_or_variable.push_back(id);
			ids_for_constant_or_type.push_back(id);
			break;

		case TypeVariable:
			ids_for_constant_or_variable.push_back(id);
			break;

		case TypeType:
		case TypeConstantOp:
			ids_for_constant_or_type.push_back(id);
			break;

		default:
			break;
		}
	}

	if (ids[id].empty())
	{
		ids_for_type[type].push_back(id);
	}
	else if (ids[id].get_type() != type)
	{
		remove_typed_id(ids[id].get_type(), id);
		ids_for_type[type].push_back(id);
	}
}

const Meta *ParsedIR::find_meta(ID id) const
{
	auto itr = meta.find(id);
	if (itr != end(meta))
		return &itr->second;
	else
		return nullptr;
}

Meta *ParsedIR::find_meta(ID id)
{
	auto itr = meta.find(id);
	if (itr != end(meta))
		return &itr->second;
	else
		return nullptr;
}

ParsedIR::LoopLock ParsedIR::create_loop_hard_lock() const
{
	return ParsedIR::LoopLock(&loop_iteration_depth_hard);
}

ParsedIR::LoopLock ParsedIR::create_loop_soft_lock() const
{
	return ParsedIR::LoopLock(&loop_iteration_depth_soft);
}

ParsedIR::LoopLock::~LoopLock()
{
	if (lock)
		(*lock)--;
}

ParsedIR::LoopLock::LoopLock(uint32_t *lock_)
    : lock(lock_)
{
	if (lock)
		(*lock)++;
}

ParsedIR::LoopLock::LoopLock(LoopLock &&other) SPIRV_CROSS_NOEXCEPT
{
	*this = move(other);
}

ParsedIR::LoopLock &ParsedIR::LoopLock::operator=(LoopLock &&other) SPIRV_CROSS_NOEXCEPT
{
	if (lock)
		(*lock)--;
	lock = other.lock;
	other.lock = nullptr;
	return *this;
}

} // namespace SPIRV_CROSS_NAMESPACE


text:
'use strict';

angular.module('scrumbo')
.directive('drag', ['$rootScope', '$timeout', function($rootScope, $timeout) {

    // Define actions for events
    function dragStart(event, element, dragStyle) {
        // We wait a little bit so the browser has
        // the time to copy the original element
        // before we hide it
        $timeout(function() {
            element.addClass(dragStyle);
        }, 100);
        event.dataTransfer.setData("id", event.target.id);
        event.dataTransfer.effectAllowed = 'move';
    }

    function dragEnd(event, element, dragStyle) {
        element.removeClass(dragStyle);
    }

    return {
        restrict: 'A',
        link: function(scope, element, attrs) {
            attrs.$set('draggable', 'true');

            // Get the attributes from the element
            scope.dragData  = scope[attrs['drag']];
            scope.dragStyle = attrs['dragStyle'];

            // Bind the events to the elements
            element.bind('dragstart', function(event) {
                $rootScope.draggedElement = scope.dragData;
                dragStart(event, element, scope.dragStyle);
            });

            element.bind('dragend', function(event) {
                dragEnd(event, element, scope.dragStyle);
            });
        },
    }
}])
.directive('drop', ['$rootScope', function($rootScope) {

    // Define actions for events
    function dragEnter(event, element, dropStyle) {
        event.preventDefault();
        element.addClass(dropStyle);
    }

    function dragLeave(event, element, dropStyle) {
        event.preventDefault();
        element.removeClass(dropStyle);
    }

    function dragOver(event) {
        event.preventDefault();
    }

    function drop(event, element, dropStyle) {
        event.preventDefault();
        element.removeClass(dropStyle);
    }

    return {
        restrict: 'A',
        link: function(scope, element, attrs) {

            // Get the attributes from the element
            scope.dropData   = scope[attrs['drop']];
            scope.dropStyle  = attrs['dropStyle'];
            scope.afterStory = scope[attrs['dropPositionAfter']];

            // Bind the events to the elements
            element.bind('dragenter', function(event) {
                dragEnter(event, element, scope.dropStyle);
            });

            element.bind('dragleave', function(event) {
                dragLeave(event, element, scope.dropStyle);
            });

            element.bind('dragover', dragOver); // Needed to be a valid drop element

            element.bind('drop', function(event) {
                drop(event, element, scope.dropStyle);
                $rootScope.$broadcast('dropEvent', $rootScope.draggedElement, scope.dropData, scope.afterStory);
            });
        },
    }
}]);


text:
<!doctype html>

		<title>Modifier keys selecting dropEffect with 'copyMove'</title>

Drag the orange square over the blue square

Press the relevant modifier keys for your platform

Continue dragging over the pink square

Release the drag, then the keys

Check that the correct drop effect is produced in each case. If the mouse cursor can change to indicate the final type of drop effect that will take place, it should change to the relevant type (the one in bold) once the modifier keys are pressed.

Windows

Modifier	Drop effect

None	copy

Ctrl	copy

Shift	copy=>move

Alt	copy=>link=>none

Ctrl+Shift	copy=>link=>none

Ctrl+Alt	copy

Alt+Shift	copy

Ctrl+Alt+Shift	copy

Unix/Linux

Modifier	Drop effect

none	copy

Ctrl	copy

Shift	copy=>move

Alt	copy

Ctrl+Shift	copy=>link=>none

Ctrl+Alt	copy

Alt+Shift	copy=>move

Ctrl+Alt+Shift	copy=>link=>none

Mac

Modifier	Drop effect

none	copy

Ctrl	copy

Shift	copy

Option/alt	copy

Command	copy=>move

Ctrl+Shift	copy

Ctrl+Option	copy

Ctrl+Command	copy=>move

Shift+Option	copy

Shift+Command	copy=>move

Command+Option	copy=>link=>none

Ctrl+Shift+Option	copy

Ctrl+Shift+Command	copy=>move

Ctrl+Command+Option	copy=>link=>none

Shift+Command+Option	copy=>link=>none

Ctrl+Shift+Command+Option	copy=>link=>none

Enable JavaScript and reload


text:
#include "testOPCUA.h"
#if LO_TEST_OPCUA

#include <stdio.h>
#include <open62541.h>

static void opcua_client(MadVptr exData);

void Init_TestOPCUA(void)
{
    madThreadCreate(opcua_client, NULL, 1024 * 2, THREAD_PRIO_TEST_OPCUA);
}

static void opcua_client(MadVptr exData)
{
    UA_Variant value; /* Variants can hold scalar values and arrays of any type */
    UA_Client *client;
    UA_StatusCode status;
    (void)exData;

    madTimeDly(5 * 1000);
    MAD_LOG("[OPCUA] opcua_client\n");

    /* Create a client and connect */
    client = UA_Client_new();
    UA_ClientConfig_setDefault(UA_Client_getConfig(client));
    status = UA_Client_connect(client, "opc.tcp://localhost:4840");
    if(status != UA_STATUSCODE_GOOD) {
        UA_Client_delete(client);
        MAD_LOG("[OPCUA] UA_Client_connect ... Error\n");
        madThreadPend(MAD_THREAD_SELF);
    }

    while (1) {
        /* Read the value attribute of the node. UA_Client_readValueAttribute is a
        * wrapper for the raw read service available as UA_Client_Service_read. */
        UA_Variant_init(&value);
        status = UA_Client_readValueAttribute(client, UA_NODEID_STRING(1, "the.answer"), &value);
        if(status == UA_STATUSCODE_GOOD) {
            if(UA_Variant_hasScalarType(&value, &UA_TYPES[UA_TYPES_INT32])) {
                printf("the value is: %li\n", *(UA_Int32*)value.data);
            }
            madTimeDly(1000 * 3);
        } else {
            break;
        }
    }

    /* Clean up */
    UA_Variant_deleteMembers(&value);
    UA_Client_delete(client); /* Disconnects the client internally */
    MAD_LOG("[OPCUA] UA_Client ... Close\n");
    madThreadDelete(MAD_THREAD_SELF);
}

#endif /* LO_TEST_OPCUA */


text:
package org.apache.camel.component.xj;

import java.io.File;

import com.fasterxml.jackson.core.JsonFactory;
import org.apache.camel.Exchange;
import org.apache.camel.component.xslt.ResultHandler;
import org.apache.camel.component.xslt.ResultHandlerFactory;
import org.apache.camel.support.ExchangeHelper;

/**
 * A {@link JsonFileResultHandler} factory
 */
public class JsonFileResultHandlerFactory implements ResultHandlerFactory {
    private final JsonFactory jsonFactory;

    /**
     * Creates a new json to file result handler factory
     *
     * @param jsonFactory the {@link JsonFactory} to use to write the json.
     */
    public JsonFileResultHandlerFactory(JsonFactory jsonFactory) {
        this.jsonFactory = jsonFactory;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public ResultHandler createResult(Exchange exchange) throws Exception {
        final String fileName = ExchangeHelper.getMandatoryHeader(exchange, XJConstants.XSLT_FILE_NAME, String.class);
        return new JsonFileResultHandler(jsonFactory, new File(fileName));
    }
}


text:
package hex.tfidf;

import water.fvec.Frame;
import water.rapids.ast.prims.mungers.AstGroup;

/**
 * Task class using map-reduce to compute term frequency values for words in given documents.
 */
public class TermFrequencyTask {

    /**
     * Column names to be used for output frame.
     */
    private static final String[] OUTPUT_FRAME_COL_NAMES = new String[] { "DocID", "Word", "TF" };

    /**
     * Computes term frequency values for given words in documents.
     *
     * @param wordFrame input frame of words for which term frequency
     *                  values should be computed. For exact format
     *                  see {@link TfIdfPreprocessorTask}.
     *
     * @return frame containing term frequency values for given words.
     */
    public static Frame compute(final Frame wordFrame) {
        AstGroup.AGG[] aggs = new AstGroup.AGG[1];
        aggs[0] = new AstGroup.AGG(AstGroup.FCN.nrow, 0, AstGroup.NAHandling.ALL, -1);

        int[] groupByColumns = new int[]{ 0, 1 };

        Frame tfFrame = new AstGroup().performGroupingWithAggregations(wordFrame,
                                                                       groupByColumns,
                                                                       aggs).getFrame();
        tfFrame.setNames(OUTPUT_FRAME_COL_NAMES);

        return tfFrame;
    }
}


text:
There're no hard rules about when to release ruby-enum. Release bug fixes frequently, features not so frequently and breaking API changes rarely.

### Release

Run tests, check that all tests succeed locally.

```
bundle install
rake
```

Check that the last build succeeded in [Travis CI](https://travis-ci.org/dblock/ruby-enum) for all supported platforms.

Increment the version, modify [lib/ruby-enum/version.rb](lib/ruby-enum/version.rb).

*  Increment the third number if the release has bug fixes and/or very minor features, only (eg. change `0.2.1` to `0.2.2`).
*  Increment the second number if the release contains major features or breaking API changes (eg. change `0.2.1` to `0.3.0`).

Change "Next Release" in [CHANGELOG.md](CHANGELOG.md) to the new version.

```
### 0.2.2 (7/10/2015)
```

Remove the line with "Your contribution here.", since there will be no more contributions to this release.

Commit your changes.

```
git add README.md CHANGELOG.md lib/ruby-enum/version.rb
git commit -m "Preparing for release, 0.2.2."
git push origin master
```

Release.

```
$ rake release

ruby-enum 0.2.2 built to pkg/ruby-enum-0.2.2.gem.
Tagged v0.2.2.
Pushed git commits and tags.
Pushed ruby-enum 0.2.2 to rubygems.org.
```

### Prepare for the Next Version

Add the next release to [CHANGELOG.md](CHANGELOG.md).

```
Next Release
============

* Your contribution here.
```

Increment the third version number in [lib/ruby-enum/version.rb](lib/ruby-enum/version.rb).

Commit your changes.

```
git add CHANGELOG.md lib/ruby-enum/version.rb
git commit -m "Preparing for next development iteration, 0.2.3."
git push origin master
```


text:
<resources>
    <string name="app_name">Sqlite2 Example</string>
</resources>


text:
package com.xeiam.xchange.gatecoin.service.polling;

import java.io.IOException;

import com.xeiam.xchange.Exchange;
import com.xeiam.xchange.currency.CurrencyPair;
import com.xeiam.xchange.dto.marketdata.OrderBook;
import com.xeiam.xchange.dto.marketdata.Ticker;
import com.xeiam.xchange.dto.marketdata.Trades;
import com.xeiam.xchange.gatecoin.GatecoinAdapters;
import com.xeiam.xchange.service.polling.marketdata.PollingMarketDataService;

/**
 * @author Sumedha
 */
public class GatecoinMarketDataService extends GatecoinMarketDataServiceRaw implements PollingMarketDataService {

  /**
   * Constructor
   *
   * @param exchange
   */
  public GatecoinMarketDataService(Exchange exchange) {

    super(exchange);

  }

  @Override
  public Ticker getTicker(CurrencyPair currencyPair, Object... args) throws IOException {

    return GatecoinAdapters.adaptTicker(getGatecoinTicker().getTicker(), currencyPair);
  }

  @Override
  public OrderBook getOrderBook(CurrencyPair currencyPair, Object... args) throws IOException {

    return GatecoinAdapters.adaptOrderBook(getGatecoinOrderBook(currencyPair.toString()), currencyPair, 1000);
  }

  @Override
  public Trades getTrades(CurrencyPair currencyPair, Object... args) throws IOException {
      if(args.length == 0)
      {
          return GatecoinAdapters.adaptTrades( getGatecoinTransactions(currencyPair.toString()).getTransactions(), currencyPair);
      }
      else if(args.length == 1)
      {
          return GatecoinAdapters.adaptTrades( getGatecoinTransactions(currencyPair.toString(),(Integer)args[0],0).getTransactions(), currencyPair);
      }
      else if(args.length == 2)
      {
          return GatecoinAdapters.adaptTrades( getGatecoinTransactions(currencyPair.toString(),(Integer)args[0],(Long)args[1]).getTransactions(), currencyPair);
      }
    throw new IllegalArgumentException("Illegal number of arguments: " + args.length);
  }

}


text:
status: publish
tags:
- thoughts
- websights
published: true
title: Abendkleider-Statik und arbeitslose Architekten
type: post
meta:
  tags: ""
layout: post
---
Das wäre doch eine Geschäftsidee für die von Arbeitslosigkeit bedrohten Architekturstudenten:

Sie könnten die Statik trägerloser Abendkleider berechnen und damit der Kleidungsindustrie einen unvergleichlichen Dienst erweisen, unzählige Modedesigner glücklich machen und damit unermesslich reich werden, oder so.

Traumhaft, nicht?

Denn:

so wirkungsvoll ein trägerloses Abendkleid auch sein mag, wenn es gilt, die Aufmerksamkeit maskuliner Zeitgenossen zu erregen, so oft bereitet es seinem Statiker und Konstrukteur endloses Kopfzerbrechen.
(luftpiraten.de)

Dass die Dame nämlich sonst ganz schnell mehr Luft ums Herz hat, als ihr lieb ist, hat Pepino herausgefunden.


text:
using System;
using System.Collections.Generic;
using System.IO;
using System.Threading;
using Endeca.Control.EacToolkit;
using EndecaControl.EacToolkit.Services;

#endregion

namespace EndecaControl.EacToolkit.Components
{
    public sealed class DgraphCluster
    {
        private const int PollInterval = 10000;
        private const string CleanDirCmdTemplate = @"del /s /q {0}\. > nul";
        private readonly EndecaApplication _app;
        //One Dgraph per host collection. Needed for index distribution and local archives
        private readonly List<DgraphComponent> _hostDgraphs = new List<DgraphComponent>();

        public DgraphCluster(EndecaApplication app)
        {
            _app = app;
            foreach (var host in app.Hosts)
            {
                var component = app.Dgraphs.FindOne(host.HostId);
                if (component != null)
                {
                    _hostDgraphs.Add(component);
                }
            }
        }

        #region Baseline Update

        /// <summary>
        /// Distributes the index to all hosts (local and remote) in parallel
        /// </summary>
        public void DistributeIndex()
        {
            var source = String.Format(@"{0}\*", _app.Dgidx.OutputDirectory.Substring(0,_app.Dgidx.OutputDirectory.LastIndexOf(@"\")));
            var copyOps = new List<HostOperation>();
            foreach (var dgraph in _hostDgraphs)
            {
                var token = EacGateway.Instance.StartCopyFiles(
                    _app.AppId, _app.Dgidx.HostId, source, dgraph.HostId, dgraph.IndexDistributionDir, true);
                copyOps.Add(new HostOperation(dgraph.HostId, token, null));
                Logger.Debug(String.Format("Started copy operation on host {0}. Token: {1}.", dgraph.HostId, token));
            }
            WaitComplete(copyOps);
        }

        /// <summary>
        /// </summary>
        /// <param name="pauseBetweenDgraphs">seconds between drgraph updates</param>
        public void ApplyIndex(int pauseBetweenDgraphs)
        {
            foreach (var dgraph in _app.Dgraphs)
            {
                if (dgraph.IndexApplied) continue;

                Logger.Debug(String.Format("Applying index on {0}:{1} dgraph instance.", dgraph.HostName,
                                           dgraph.Port));
                if (dgraph.ApplyIndex())
                {
                    Logger.Info(String.Format("{0}:{1} - Dgraph started.", dgraph.HostName, dgraph.Port));
                    if (pauseBetweenDgraphs > 0)
                    {
                        Logger.Info(String.Format("Pausing for {0} seconds", pauseBetweenDgraphs));
                        Thread.Sleep(pauseBetweenDgraphs*1000);
                    }
                }
                else
                {
                    Logger.Error(String.Format("{0}:{1} - Dgraph FAILED to start!!!", dgraph.HostName, dgraph.Port));
                }
            }
        }

        /// <summary>
        ///     Applies index to the specified dgraphs
        /// </summary>
        /// <param name="hostIDs">Host Ids index to be applied</param>
        /// <returns>False if at least one of Dgraphs fails to update</returns>
        public bool ApplyIndex(string[] hostIDs)
        {
            var allOk = true;
            foreach (var hostId in hostIDs)
            {
                foreach (var dgraph in _app.Dgraphs.FindAll(hostId))
                {
                    if (dgraph.IndexApplied) continue;

                    Logger.Debug(String.Format("Applying index on {0}:{1} dgraph instance.", dgraph.HostName,
                                               dgraph.Port));
                    if (dgraph.ApplyIndex())
                    {
                        Logger.Info(String.Format("{0}:{1} - Dgraph started.", dgraph.HostName, dgraph.Port));
                    }
                    else
                    {
                        Logger.Error(String.Format("{0}:{1} - Dgraph FAILED to start!!!", dgraph.HostName,
                                                   dgraph.Port));
                        allOk = false;
                    }
                }
            }
            return allOk;
        }

        #endregion

        #region Partial Update

        /// <summary>
        ///     Distributes the update to all hosts.
        /// </summary>
        /// <param name="partialForge">Partial forge instance.</param>
        public void DistributeUpdate(ForgeComponent partialForge)
        {
            //stamp partial update to ensure all partial updates are kept in the dgraph update folder until baseline update run
            var stampedName = partialForge.StampPartialUpdate();
            var updateFileName = Path.Combine(partialForge.OutputDirectory, stampedName);
            //get forge host
            var forgeHost = _app.Hosts[partialForge.HostId];

            var copyOps = new List<HostOperation>();
            foreach (var dgraph in _hostDgraphs)
            {
                var dgraph1 = dgraph;
                //find dgraph host
                var dgraphHost = _app.Hosts[dgraph1.HostId];

                // Update was already created on the Partial Forge hosts,
                // so we'll copy update only to the remote hosts
                if (forgeHost.EacHostName == dgraphHost.EacHostName) continue;

                var token = EacGateway.Instance.StartCopyFiles(_app.AppId, forgeHost.HostId, updateFileName,
                                                               dgraph.HostId,
                                                               dgraph.UpdateDir, false);
                copyOps.Add(new HostOperation(dgraph.HostId, token, null));
                Logger.Debug(String.Format("Started copy operation on host {0}. Token: {1}.", dgraph.HostId, token));
            }
            //Wait until all operations finish
            WaitComplete(copyOps);
        }

        /// <summary>
        ///     Applies the update to the entire dgraph cluster.
        /// </summary>
        public void ApplyUpdate()
        {
            foreach (var dgraph in _app.Dgraphs)
            {
                if (dgraph.UpdateApplied) continue;

                if (!dgraph.IsAlive())
                {
                    Logger.Error(
                        string.Format(
                            "Dgraph instance on {0}:{1} - is not reachable. The server might be down or offline.",
                            dgraph.HostName, dgraph.Port));
                }
                else if (dgraph.ApplyUpdate())
                {
                    Logger.Info(String.Format("{0}:{1} - updated successfully.", dgraph.HostName, dgraph.Port));
                }
                else
                {
                    throw new ControlScriptException(String.Format(
                        "Dgraph instance on {0}:{1} - failed to update.", dgraph.HostName, dgraph.Port));
                }
            }
        }

        #endregion

        #region Folder archive/cleanup methods

        public void CleanLocalIndexDistributionDir()
        {
            var cleanOps = new List<HostOperation>();
            foreach (var dgraph in _hostDgraphs)
            {
                try
                {
                    var cmd = String.Format(CleanDirCmdTemplate, dgraph.IndexDistributionDir);
                    var token = EacGateway.Instance.ShellCmd(_app.AppId, dgraph.HostId, cmd);
                    cleanOps.Add(new HostOperation(dgraph.HostId, token, null));
                    Logger.Debug(
                        String.Format(
                            "Started local index distribution folder cleaning on host {0}. Token: {1}. Command: {2}",
                            dgraph.HostId, token, cmd));
                }
                catch (Exception e)
                {
                    throw new ControlScriptException(
                        String.Format("Local index distribution folder cleaning failed on host {0}.\n\n{1}.",
                                      dgraph.HostId, e));
                }
            }
            WaitComplete(cleanOps);
        }

        public void CleanLocalUpdatesDir()
        {
            var cleanOps = new List<HostOperation>();
            foreach (var dgraph in _hostDgraphs)
            {
                try
                {
                    var cmd = String.Format(CleanDirCmdTemplate,
                                            dgraph.InputDirectory.Substring(0,
                                                                            dgraph.InputDirectory.LastIndexOf(@"\",
                                                                                StringComparison
                                                                                .InvariantCulture)));
                    var token = EacGateway.Instance.ShellCmd(_app.AppId, dgraph.HostId, cmd);
                    cleanOps.Add(new HostOperation(dgraph.HostId, token, null));
                    Logger.Debug(
                        String.Format("Started local updates foder cleaning on host {0}. Token: {1}. Command: {2}",
                                      dgraph.HostId, token, cmd));
                }
                catch (Exception e)
                {
                    throw new ControlScriptException(
                        String.Format("Local updates folder cleaning failed on host {0}.\n\n{1}", dgraph.HostId, e));
                }
            }
            WaitComplete(cleanOps);
        }

        #endregion

        #region Helper methods

        private void WaitComplete(IEnumerable<HostOperation> operations)
        {
            var done = false;
            while (!done)
            {
                done = true;
                foreach (var hostOperation in operations)
                {
                    // check previuos status to avoid the case where EAC has discarted the token which will result in exception
                    if (hostOperation.Status == null ||
                        (hostOperation.State == StateType.Running || hostOperation.State == StateType.Starting))
                    {
                        hostOperation.Status = EacGateway.Instance.GetUtilityStatus(_app.AppId, hostOperation.Token);
                    }
                    Logger.Debug(hostOperation.ToString());
                    if (hostOperation.State == StateType.Running)
                    {
                        done = false;
                    }
                    else if (hostOperation.State == StateType.Failed)
                    {
                        Logger.Error(String.Format("Host {0}: {1}", hostOperation.Host, hostOperation.FailureMessage));
                    }
                }
                if (!done)
                {
                    Thread.Sleep(PollInterval);
                }
            }
        }

        #endregion
    }

    internal class HostOperation
    {
        private string _host;
        private BatchStatusType _status;
        private string _token;

        public HostOperation(string host, string token, BatchStatusType status)
        {
            _host = host;
            _token = token;
            _status = status;
        }

        public HostOperation(string host, string token)
        {
            _host = host;
            _token = token;
            _status = null;
        }

        public string Host
        {
            get { return _host; }
            set { _host = value; }
        }

        public string Token
        {
            get { return _token; }
            set { _token = value; }
        }

        public BatchStatusType Status
        {
            get { return _status; }
            set { _status = value; }
        }

        /// <remarks />
        public StateType State
        {
            get { return _status.state; }
        }

        /// <remarks />
        public string FailureMessage
        {
            get { return _status.failureMessage; }
        }

        public override string ToString()
        {
            return string.Format("{0}:{1} - {2}", _host, _token, State);
        }
    }
}


text:
do

local BASE_URL = "http://api.openweathermap.org/data/2.5/weather"

local function get_weather(location)
  print("Finding weather in ", location)
  location = string.gsub(location," ","+")
  local url = BASE_URL
  url = url..'?q='..location
  url = url..'&units=metric'
  url = url..'&appid=bd82977b86bf27fb59a04b61b657fb6f'

  local b, c, h = http.request(url)
  if c ~= 200 then return nil end

  local weather = json:decode(b)
  local city = weather.name
  local country = weather.sys.country
  local temp = 'The temperature in '..city
    ..' (' ..country..')'
    ..' is '..weather.main.temp..'°C'
  local conditions = 'Current conditions are: '
    .. weather.weather[1].description

  if weather.weather[1].main == 'Clear' then
    conditions = conditions .. ' ☀'
  elseif weather.weather[1].main == 'Clouds' then
    conditions = conditions .. ' ☁☁'
  elseif weather.weather[1].main == 'Rain' then
    conditions = conditions .. ' ☔'
  elseif weather.weather[1].main == 'Thunderstorm' then
    conditions = conditions .. ' ☔☔☔☔'
  end

  return temp .. '\n' .. conditions
end

local function run(msg, matches)
  local city = 'Madrid,ES'

  if matches[1] ~= '!weather' then
    city = matches[1]
  end
  local text = get_weather(city)
  if not text then
    text = 'Can\'t get weather from that city.'
  end
  return text
end

return {
  description = "weather in that city (Madrid is default)",
  usage = "!weather (city)",
  patterns = {
    "^!weather$",
    "^!weather (.*)$"
  },
  run = run
}

end


text:
""" Filesystem utilities
"""
import contextlib
import os
import re
import shutil
from subprocess import check_call, CalledProcessError, Popen, PIPE

RUN_RE = '^\d{6}_[a-zA-Z\d\-]+_\d{4}_[AB0][A-Z\d\-]+$'
PROJECT_RE = '[a-zA-Z]+\.[a-zA-Z]+_\d{2}_\d{2}'

@contextlib.contextmanager
def chdir(new_dir):
    """Context manager to temporarily change to a new directory.
    """
    cur_dir = os.getcwd()
    # This is weird behavior. I'm removing and and we'll see if anything breaks.
    #safe_makedir(new_dir)
    os.chdir(new_dir)
    try:
        yield
    finally:
        os.chdir(cur_dir)

def create_folder(target_folder):
    """ Ensure that a folder exists and create it if it doesn't, including any
        parent folders, as necessary.

        :param target_folder: the target folder
        :returns: True if the folder exists or was created, False if the folder
        does not exists and could not be created
    """
    try:
        os.makedirs(target_folder)
    except OSError as e:
        pass
    return os.path.exists(target_folder)

def touch(file):
    open(file, "w").close()

def do_symlink(src_file, dst_file):
    do_link(src_file, dst_file, 'soft')

def do_hardlink(src_file, dst_file):
    do_link(src_file, dst_file, 'hard')

def do_link(src_file, dst_file, link_type='soft'):
    if link_type == 'hard':
        link_f=os.link
    else:
        link_f=os.symlink
    if not os.path.isfile(dst_file):
        link_f(os.path.realpath(src_file), dst_file)

def do_copy(src_path, dst_path):
    # copies folder structure and files (recursively)
    # if symlinks, will copy content, not the links
    # dst_path will be created, it must NOT exist
    shutil.copytree(src_path, dst_path)

def is_in_swestore(f):
    """ Checks if a file exists in Swestore

    :param f str: File to check
    :returns bool: True if the file is already in Swestore, False otherwise
    """
    with open(os.devnull, 'w') as null:
        try:
            check_call(['ils', f], stdout=null, stderr=null)
        except CalledProcessError:
            # ils will fail if the file does not exist in swestore
            return False
        else:
            return True

def list_runs_in_swestore(path, pattern=RUN_RE, no_ext=False):
    """
        Will list runs that exist in swestore

        :param str path: swestore path to list runs
        :param str pattern: regex pattern for runs
    """
    try:
        status = check_call(['icd', path])
        proc = Popen(['ils'], stdout=PIPE)
        contents = [c.strip() for c in proc.stdout.readlines()]
        runs = [r for r in contents if re.match(pattern, r)]
        if no_ext:
            runs = [r.split('.')[0] for r in runs]
        return runs
    except CalledProcessError:
        return []

def is_in_file(file_path, text):
    """ Looks for text appearing in a file.

    :param str file_path: Path to the source file
    :param str text: Text to find in the file
    :raises OSError: If the file does not exist
    :returns bool: True is text is in file, False otherwise
    """
    with open(file_path, 'r') as f:
        content = f.read()
    return text in content

def control_fastq_filename(demux_folder):
    """Looks for fastq files with a hyphen in the sample nsame
    and turns it in an underscore.

    :param str demux_folder: path to the demultiplexed folder
    """
    pattern=re.compile("^(P[0-9]+)-([0-9]{3,4}).+fastq.*$")
    for root, dirs, files in os.walk(demux_folder):
        for f in files:
            matches=pattern.search(f)
            if matches:
                new_name=f.replace("{}-{}".format(matches.group(1), matches.group(2)), "{}_{}".format(matches.group(1), matches.group(2)))
                os.rename(os.path.join(root, f), os.path.join(root, new_name))


text:
<?php

namespace Sylius\Migrations;

use Doctrine\DBAL\Migrations\AbstractMigration;
use Doctrine\DBAL\Schema\Schema;

/**
 * Auto-generated Migration: Please modify to your needs!
 */
class Version20160225115200 extends AbstractMigration
{
    /**
     * @param Schema $schema
     */
    public function up(Schema $schema)
    {
        // this up() migration is auto-generated, please modify it to your needs
        $this->abortIf($this->connection->getDatabasePlatform()->getName() != 'mysql', 'Migration can only be executed safely on \'mysql\'.');

        $this->addSql('CREATE TABLE sylius_theme (id INT AUTO_INCREMENT NOT NULL, name VARCHAR(255) NOT NULL, title VARCHAR(255) NOT NULL, path VARCHAR(255) NOT NULL, code VARCHAR(255) NOT NULL, description VARCHAR(255) DEFAULT NULL, authors LONGTEXT DEFAULT NULL COMMENT \'(DC2Type:object)\', UNIQUE INDEX UNIQ_3CAD5695E237E06 (name), INDEX IDX_3CAD5695E237E06 (name), PRIMARY KEY(id)) DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE = InnoDB');
        $this->addSql('CREATE TABLE sylius_theme_parents (child_id INT NOT NULL, parent_id INT NOT NULL, INDEX IDX_48942C67DD62C21B (child_id), INDEX IDX_48942C67727ACA70 (parent_id), PRIMARY KEY(child_id, parent_id)) DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE = InnoDB');
        $this->addSql('ALTER TABLE sylius_theme_parents ADD CONSTRAINT FK_48942C67DD62C21B FOREIGN KEY (child_id) REFERENCES sylius_theme (id)');
        $this->addSql('ALTER TABLE sylius_theme_parents ADD CONSTRAINT FK_48942C67727ACA70 FOREIGN KEY (parent_id) REFERENCES sylius_theme (id) ON DELETE CASCADE');
    }

    /**
     * @param Schema $schema
     */
    public function down(Schema $schema)
    {
        // this down() migration is auto-generated, please modify it to your needs
        $this->abortIf($this->connection->getDatabasePlatform()->getName() != 'mysql', 'Migration can only be executed safely on \'mysql\'.');

        $this->addSql('ALTER TABLE sylius_theme_parents DROP FOREIGN KEY FK_48942C67DD62C21B');
        $this->addSql('ALTER TABLE sylius_theme_parents DROP FOREIGN KEY FK_48942C67727ACA70');
        $this->addSql('DROP TABLE sylius_theme');
        $this->addSql('DROP TABLE sylius_theme_parents');
    }
}


text:
namespace Manager.IntegrationTest.Console.Host.Interfaces
{
    public interface IAppDomain
    {
        string GetAppDomainUniqueId();
    }
}


text:
use std::io::{Result};
use std::net::{SocketAddr, SocketAddrV4, Ipv4Addr};

use mio::{EventLoop, Sender, EventLoopConfig};
use mio::udp::{UdpSocket};

use dispatcher::{Dispatcher, DispatchHandler};

const DEFAULT_BUFFER_SIZE:      usize = 1500;
const DEFAULT_CHANNEL_CAPACITY: usize = 4096;
const DEFAULT_TIMER_CAPACITY:   usize = 65536;

/// Builder for specifying attributes of an event loop.
pub struct ELoopBuilder {
    channel_capacity: usize,
    timer_capacity:   usize,
    buffer_size:      usize,
    bind_address:     SocketAddr
}

impl ELoopBuilder {
    /// Create a new event loop builder.
    pub fn new() -> ELoopBuilder {
        let default_addr = SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::new(0, 0, 0, 0), 0));

        ELoopBuilder{ channel_capacity: DEFAULT_CHANNEL_CAPACITY, timer_capacity: DEFAULT_TIMER_CAPACITY,
            buffer_size: DEFAULT_BUFFER_SIZE, bind_address: default_addr }
    }

    /// Manually set the maximum channel message capacity.
    pub fn channel_capacity(mut self, capacity: usize) -> ELoopBuilder {
        self.channel_capacity = capacity;

        self
    }

    /// Manually set the maximum timer capacity.
    pub fn timer_capacity(mut self, capacity: usize) -> ELoopBuilder {
        self.timer_capacity = capacity;

        self
    }

    /// Manually set the bind address for the udp socket in the event loop.
    pub fn bind_address(mut self, address: SocketAddr) -> ELoopBuilder {
        self.bind_address = address;

        self
    }

    /// Manually set the length of buffers provided by the event loop.
    pub fn buffer_length(mut self, length: usize) -> ELoopBuilder {
        self.buffer_size = length;

        self
    }

    /// Build the event loop with the current builder.
    pub fn build<D: Dispatcher>(self) -> Result<ELoop<D>> {
        ELoop::from_builder(self)
    }
}

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

/// Wrapper around the main application event loop.
pub struct ELoop<D: Dispatcher> {
    buffer_size: usize,
    socket_addr: SocketAddr,
    event_loop:  EventLoop<DispatchHandler<D>>
}

impl<D: Dispatcher> ELoop<D> {
    fn from_builder(builder: ELoopBuilder) -> Result<ELoop<D>> {
        let mut event_loop_config = EventLoopConfig::new();
        event_loop_config.notify_capacity(builder.channel_capacity)
            .timer_capacity(builder.timer_capacity);

        let event_loop = try!(EventLoop::configured(event_loop_config));

        Ok(ELoop{ buffer_size: builder.buffer_size, socket_addr: builder.bind_address,
            event_loop: event_loop })
    }

    /// Grab a channel to send messages to the event loop.
    pub fn channel(&self) -> Sender<D::Message> {
        self.event_loop.channel()
    }

    /// Run the event loop with the given dispatcher until a shutdown occurs.
    pub fn run(&mut self, dispatcher: D) -> Result<()> {
        let udp_socket = try!(UdpSocket::bound(&self.socket_addr));
        let mut dispatch_handler = DispatchHandler::new(udp_socket, self.buffer_size, dispatcher,
            &mut self.event_loop);

        self.event_loop.run(&mut dispatch_handler)
    }
}


text:
<?php

// Joaquin-V/Chatter - Telegram API for PHP 7.
// License: GNU General Public License <http://www.gnu.org/licenses/>
// Copyright (C) 2016 Joaquín Varela

namespace JoaquinV\Chatter\result;
use JoaquinV\Chatter\TelegramException;

/**
 * Erroneous Telegram API result.
 */
class Error extends Result{

	protected $code=0;
	protected $desc='';

	public function __construct($json){
		$json = $this->parseJSON($json);
		if($json['ok'])
			throw new TelegramException('Tried to make an Error object of a non-error');

		$this->code = $json['error_code'] ?? 0;
		$this->desc = $json['description'] ?? '';
	}

	/**
	 * Makes a throwable exception of this error.
	 * @return TelegramException
	 */
	public function mkException(){
		return new TelegramException($this->desc, $this->code);
	}

	public function getCode(): int{
		return $this->code;
	}

	public function getDescription(): string{
		return $this->desc;
	}
}


text:
/*
 * @test
 * @author Gary Ellison
 * @bug 4170635
 * @summary Verify equals()/hashCode() contract honored
 */

import java.io.*;
import sun.security.util.*;
import sun.security.x509.*;

public class DerValueEqualsHashCode {

    public static void main(String[] args) throws Exception {

        String name = "CN=user";
        X500Name dn = new X500Name(name);

        DerOutputStream deros;
        byte[] ba;
        //
        // get busy
        deros = new DerOutputStream();
        dn.encode(deros);
        ba = deros.toByteArray();

        DerValue dv1 = new DerValue(ba);
        DerValue dv2 = new DerValue(ba);

        if ( (dv1.equals(dv2)) == (dv1.hashCode()==dv2.hashCode()) )
            System.out.println("PASSED");
        else
            throw new Exception("FAILED equals()/hashCode() contract");

    }

}


text:
int compile_regex(regex_t* r, const char* regex_text);
bool match_regex(regex_t* r, const char* to_match);


text:
#region License

#endregion
using System.Interop.MediaInfo.Native_;
using System.IO;
namespace System.Interop.MediaInfo
{
    /// <summary>
    /// MediaVisitor
    /// </summary>
    public class MediaVisitor : IDisposable
    {
        private string _path;
        internal IntPtr _handle;

        /// <summary>
        /// Initializes a new instance of the <see cref="MediaVisitor"/> class.
        /// </summary>
        public MediaVisitor() { }

        /// <summary>
        /// Opens the specified path.
        /// </summary>
        /// <param name="path">The path.</param>
        public void Open(string path)
        {
            if (!File.Exists(path))
                throw new FileNotFoundException("File not found :" + path, path);
            _path = path;
            if (_handle != null)
                MediaInfo.Close(_handle);
            _handle = MediaInfo.New();
            MediaInfo.Open(_handle, path);
            AudioTracks = MediaInfo.GetCount(_handle, StreamKind.Audio, -1);
            VideoTracks = MediaInfo.GetCount(_handle, StreamKind.Video, -1);
            GeneralTracks = MediaInfo.GetCount(_handle, StreamKind.General, -1);
            TextTracks = MediaInfo.GetCount(_handle, StreamKind.Text, -1);
            ChaptersTracks = MediaInfo.GetCount(_handle, StreamKind.Chapters, -1);
        }

        /// <summary>
        /// Releases unmanaged resources and performs other cleanup operations before the
        /// <see cref="MediaVisitor"/> is reclaimed by garbage collection.
        /// </summary>
        ~MediaVisitor()
        {
            Dispose(false);
        }

        /// <summary>
        /// Releases unmanaged and - optionally - managed resources
        /// </summary>
        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }

        /// <summary>
        /// Releases unmanaged and - optionally - managed resources
        /// </summary>
        /// <param name="disposing"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
        protected virtual void Dispose(bool disposing)
        {
            //if (disposing)
            //{
            //}
            MediaInfo.Close(_handle);
            MediaInfo.Delete(_handle);
        }

        /// <summary>
        /// Gets or sets the audio count.
        /// </summary>
        /// <value>The audio count.</value>
        public int AudioTracks { get; private set; }
        /// <summary>
        /// Gets or sets the video count.
        /// </summary>
        /// <value>The video count.</value>
        public int VideoTracks { get; private set; }
        /// <summary>
        /// Gets or sets the general count.
        /// </summary>
        /// <value>The general count.</value>
        public int GeneralTracks { get; private set; }
        /// <summary>
        /// Gets or sets the text count.
        /// </summary>
        /// <value>The text count.</value>
        public int TextTracks { get; private set; }
        /// <summary>
        /// Gets or sets the chapters count.
        /// </summary>
        /// <value>The chapters count.</value>
        public int ChaptersTracks { get; private set; }
    }
}


text:
<?php

class Shineisp_Commons_Morris {

	/**
	 * @api
	 * http://www.oesmith.co.uk/morris.js/lines.html
	 * @since 1.0.0
	 */
	const TYPE_AREA = 'Area';

	/**
	 * @api
	 * http://www.oesmith.co.uk/morris.js/bars.html
	 * @since 1.0.0
	 */
	const TYPE_BAR = 'Bar';

	/**
	 * @api
	 * http://www.oesmith.co.uk/morris.js/donuts.html
	 * @since 1.0.0
	 */
	const TYPE_DONUT = 'Donut';

	/**
	 * @api
	 * http://www.oesmith.co.uk/morris.js/lines.html
	 * @since 1.0.0
	 */
	const TYPE_LINE = 'Line';

	/**
	 * @var string[] An arry of the TYPE_* constants defined in this class
	 */
	private static $types = array(
								self::TYPE_AREA,
								self::TYPE_BAR,
								self::TYPE_DONUT,
								self::TYPE_LINE,
							);

	protected $element = "morris-";
	protected $data = array();
	protected $xkey;
	protected $ykeys;
	protected $parseTime = false;
	protected $options = array();
	protected $labels = array();
	protected $type = "Line";

	/**
	 * @return the $parseTime
	 */
	public function getParseTime() {
		return $this->parseTime;
	}

	/**
	 * @param field_type $parseTime
	 */
	public function setParseTime($parseTime = false) {
		$this->parseTime = $parseTime;
		return $this;
	}

	/**
	 * @return the $element
	 */
	public function getElement() {
		return $this->element;
	}

	/**
	 * @return the $data
	 */
	public function getData() {
		return $this->data;
	}

	/**
	 * @return the $xkey
	 */
	public function getXkey() {
		return $this->xkey;
	}

	/**
	 * @return the $ykeys
	 */
	public function getYkeys() {
		return $this->ykeys;
	}

	/**
	 * @return the $labels
	 */
	public function getLabels() {
		return $this->labels;
	}

	/**
	 * @return the $type
	 */
	public function getType() {
		return $this->type;
	}

	/**
	 * @param string $type
	 */
	public function setType($type) {

		if (!in_array($type, self::$types)) {
			throw new Exception("'$type' is not a valid chart type!");
		}

		$this->type = $type;
		return $this;
	}

	/**
	 * @param string $element
	 */
	public function setElement($element) {
		$this->element = $element;
		return $this;
	}

	/**
	 * @param multitype: $data
	 */
	public function setData($data) {
		$this->data = $data;
		return $this;
	}

	/**
	 * @param field_type $xkey
	 */
	public function setXkey($xkey) {
		$this->xkey = $xkey;
		return $this;
	}

	/**
	 * @param field_type $ykeys
	 */
	public function setYkeys($ykeys) {
		$this->ykeys = $ykeys;
		return $this;
	}

	/**
	 * @param field_type $labels
	 */
	public function setLabels($labels) {
		$this->labels = $labels;
		return $this;
	}

	/**
	 * @return the $options
	 */
	public function getOptions() {
		return $this->options;
	}

	/**
	 * @param field_type $options
	 */
	public function setOptions(array $options) {
		$this->options = array_merge($this->options, $options);
		return $this;
	}

	/**
	 * Constructor
	 */
	public function __construct() {}

	/**
	 * Convert the array data in a json string for the morris graph
	 */
	private function convertData(){
		$parsedata = array();
		$data = $this->getData();

		foreach ($data as $xvalue => $yvalues){
			if(is_array($yvalues)){
				$parsedata[] = array('xdata' => $xvalue) + $yvalues;
			}
		}

		$this->setData($parsedata);
		return true;
	}

	/**
	 * Get the YKeys indexes
	 */
	private function getYkeysIndexes(){
		$data = $this->getData();
		$keys = array();
		if(!empty($data)){
			$firstlevel = array_keys($data);

			if(!empty($firstlevel[0]) && is_array($firstlevel)){
				$keys = array_keys($data[$firstlevel[0]]);
			}
		}

		$this->setYkeys($keys);
	}

	/**
	 * Create the Javascript code
	 */
	private function createJs($graphdata){

		$output = "<script>";
		$output .= "new Morris." . $this->getType() . "({";
		$output .= substr($graphdata, 1);
		$output .= ")</script>";

		return $output;
	}

	/**
	 * Plot the data on screen
	 */
	public function plot($debug=false){

		$graph = null;

		$graph['element'] = $this->getElement();

		// if the graph is a Line, Bar or Area add the axis
		if(("Line" == $this->getType()) || ("Area" == $this->getType() || ("Bar" == $this->getType()))){
			$this->getYkeysIndexes();
			$this->convertData();
			$graph['xkey'] = $this->getXkey();
			$graph['ykeys'] = $this->getYkeys();
		}

		$graph['labels'] = $this->getLabels();
		$graph['data'] = $this->getData();
		$graph['parseTime'] = $this->getParseTime();

		foreach ($this->getOptions() as $option => $value) {
			$graph[$option] = $value;
		}

		$jsondata = json_encode($graph);

		if($debug){
			Zend_Debug::dump(Shineisp_Commons_Utilities::jsonBeautifier($jsondata));
		}
		return $this->createJs($jsondata);
	}

}

?>


text:
<?php

namespace Workflow;

// Add these import statements:
use Zend\Db\ResultSet\ResultSet;
use Zend\Db\TableGateway\TableGateway;
use Zend\ModuleManager\Feature\ConfigProviderInterface;

use Workflow\Model\NmtWfWorkflow;
use Workflow\Model\NmtWfWorkflowTable;
use Zend\Mvc\MvcEvent;

class Module implements ConfigProviderInterface{
	const VERSION = '3.0.3-dev';

	public function getConfig() {
		return include __DIR__ . '/../config/module.config.php';
	}

	// Add this method:
	public function getServiceConfig() {
		return [
				'factories' => [
						'NmtWfWorkflowTable' => function ($container) {
						$tableGateway = $container->get ('NmtWfWorkflowTableGateway');
							return new Model\NmtWfWorkflowTable( $tableGateway );
						},
						'NmtWfWorkflowTableGateway' => function ($container) {
							$dbAdapter = $container->get ('Db\Mla');
							$resultSetPrototype = new ResultSet ();
							$resultSetPrototype->setArrayObjectPrototype ( new Model\NmtWfWorkflow() );
							return new TableGateway ( 'nmt_wf_workflow', $dbAdapter, null, $resultSetPrototype );
						}
				]
		];
	}

}


text:
import { Component, Directive, Input, ContentChildren, OnInit, OnDestroy, forwardRef, Inject,
         QueryList, SecurityContext, Optional } from '@angular/core';
import { Router } from '@angular/router';
import { SafeResourceUrl, SafeStyle, DomSanitizer } from '@angular/platform-browser';
import { Subscription } from 'rxjs/Subscription';

import { MdSidenavToggleResult } from '@angular/material';

import { TdLayoutComponent } from '../layout.component';

import { TdCollapseAnimation } from '../../common/animations/collapse/collapse.animation';

@Directive({
  selector: '[td-navigation-drawer-menu]',
})
export class TdNavigationDrawerMenuDirective {

}

@Directive({
  selector: '[td-navigation-drawer-toolbar]',
})
export class TdNavigationDrawerToolbarDirective {

}

@Component({
  selector: 'td-navigation-drawer',
  styleUrls: ['./navigation-drawer.component.scss' ],
  templateUrl: './navigation-drawer.component.html',
  animations: [ TdCollapseAnimation() ],
})
export class TdNavigationDrawerComponent implements OnInit, OnDestroy {

  private _closeSubscription: Subscription;
  private _menuToggled: boolean = false;
  private _backgroundImage: SafeStyle;

  get menuToggled(): boolean {
    return this._menuToggled;
  }

  @ContentChildren(TdNavigationDrawerMenuDirective) _drawerMenu: QueryList<TdNavigationDrawerMenuDirective>;

  @ContentChildren(TdNavigationDrawerToolbarDirective) _toolbar: QueryList<TdNavigationDrawerToolbarDirective>;

  /**
   * Checks if there is a [TdNavigationDrawerMenuDirective] has content.
   */
  get isMenuAvailable(): boolean {
    return this._drawerMenu ? this._drawerMenu.length > 0 : false;
  }

  /**
   * Checks if there is a [TdNavigationDrawerToolbarDirective] has content.
   */
  get isCustomToolbar(): boolean {
    return this._toolbar ? this._toolbar.length > 0 : false;
  }

  /**
   * Checks if there is a background image for the toolbar.
   */
  get isBackgroundAvailable(): boolean {
    return !!this._backgroundImage;
  }

  /**
   * sidenavTitle?: string
   * Title set in sideNav.
   */
  @Input('sidenavTitle') sidenavTitle: string;

  /**
   * icon?: string
   *
   * icon name to be displayed before the title
   */
  @Input('icon') icon: string;

  /**
   * logo?: string
   *
   * logo icon name to be displayed before the title.
   * If [icon] is set, then this will not be shown.
   */
  @Input('logo') logo: string;

  /**
   * color?: string
   *
   * toolbar color option: primary | accent | warn.
   * If [color] is not set, default is used.
   */
  @Input('color') color: string;

  /**
   * navigationRoute?: string
   *
   * option to set the combined route for the icon, logo, and sidenavTitle.
   */
  @Input('navigationRoute') navigationRoute: string;

  /**
   * backgroundUrl?: SafeResourceUrl
   *
   * image to be displayed as the background of the toolbar.
   * URL used will be sanitized, but it should be always from a trusted source to avoid XSS.
   */
  @Input('backgroundUrl')
  // TODO angular complains with warnings if this is type [SafeResourceUrl].. so we will make it <any> until its fixed.
  // https://github.com/webpack/webpack/issues/2977
  set backgroundUrl(backgroundUrl: any) {
    if (backgroundUrl) {
      let sanitizedUrl: string = this._sanitize.sanitize(SecurityContext.RESOURCE_URL, backgroundUrl);
      this._backgroundImage = this._sanitize.sanitize(SecurityContext.STYLE, 'url(' + sanitizedUrl + ')');
    }
  }
  get backgroundImage(): SafeStyle {
    return this._backgroundImage;
  }

  /**
   * name?: string
   *
   * string to be displayed as part of the navigation drawer sublabel.
   * if [email] is not set, then [name] will be the toggle menu text.
   */
  @Input('name') name: string;

  /**
   * email?: string
   *
   * string to be displayed as part of the navigation drawer sublabel in the [toggle] menu text.
   * if [email] and [name] are not set, then the toggle menu is not rendered.
   */
  @Input('email') email: string;

  /**
   * Checks if router was injected.
   */
  get routerEnabled(): boolean {
    return !!this._router && !!this.navigationRoute;
  }

  constructor(@Inject(forwardRef(() => TdLayoutComponent)) private _layout: TdLayoutComponent,
              @Optional() private _router: Router,
              private _sanitize: DomSanitizer) {}

  ngOnInit(): void {
    this._closeSubscription = this._layout.sidenav.onClose.subscribe(() => {
      this._menuToggled = false;
    });
  }

  ngOnDestroy(): void {
    if (this._closeSubscription) {
      this._closeSubscription.unsubscribe();
      this._closeSubscription = undefined;
    }
  }

  toggleMenu(): void {
    if (this.isMenuAvailable) {
      this._menuToggled = !this._menuToggled;
    }
  }

  handleNavigationClick(): void {
    if (this.routerEnabled) {
      this._router.navigateByUrl(this.navigationRoute);
      this.close();
    }
  }

  /**
   * Proxy toggle method to access sidenav from outside (from td-layout template).
   */
  public toggle(): Promise<MdSidenavToggleResult> {
    return this._layout.toggle();
  }

  /**
   * Proxy open method to access sidenav from outside (from td-layout template).
   */
  public open(): Promise<MdSidenavToggleResult> {
    return this._layout.open();
  }

  /**
   * Proxy close method to access sidenav from outside (from td-layout template).
   */
  public close(): Promise<MdSidenavToggleResult> {
    return this._layout.close();
  }
}


text:
<link href="style.css" rel="stylesheet">

# Google Fonts Guide

🦜 This guide aims to help people to navigate requirements and recommendations to contribute to Google Fonts. The contents covered here range from general knowledge to contextualize the what and why of some of the requirements as well as the specifics regarding technical aspects with some suggestions on how to comply with them. It covers different levels of information for both newcomers and more experienced contributors.

Therefore, this documentation is not meant to be read at once. If you are already familiar with some of the concepts, for example, some people are more empowered with the use of Github please you can skip some chapters and jump to the other bits that you may be looking for. The guidelines have been separated into small bits to facilitate the search of specific informations that you would need at a specific stage of the font production.

If you are a newcomer and you want to contribute fonts to Google Fonts, whether commissioned or as a voluntary contribution, you should read the chapters marked with
  start and must→. Additional resources are available under the learn label.

  If you are an experienced user or are onboarding fonts to Google Fonts, the chapters marked with team  and nerd  are for you.

  The guide also provide details on required documents, some of them as templates you could copy paste in your repository, these are marked with the templ label.

## Introduction: getting familiar with the basics

The most basic concepts, tools, or knowledge you will need to cover to begin contributing with Google Fonts.

* start
  [Libre Font Culture](culture.md)
* start
  [Required Knowledge](https://googlefonts.github.io/gf-guide/tools.html#required-knowledge)
* start
  [Setting up a working environment](https://googlefonts.github.io/gf-guide/tools.html#setting-up-a-working-environment)
* start
  [Installing the required tools](https://googlefonts.github.io/gf-guide/tools.html#installing-the-required-tools)
* learn
  [Hosting projects on Github](hosting.md)

## The Upstream Repo: administrate your project files

To improve and facilitate the open collaboration as well as the publishing process, we require a specific structure for your files on the GitHub repository.

* must→
  [Upstream repository structure](upstream.md)
* must→
  [README file](readmefile.md)
* learn
  [Maintaining your font repo](maintaining.md)
* templ
  [Authors and Contributors](authors.md)
* templ
   [License file](license-file.md)

## Pre-production: Getting your fonts ready for GF

Know the particularities about mastering your font project to meet the Google Fonts specifications and get them ready for production.

* start
  [New fonts specifics](https://googlefonts.github.io/gf-guide/onboarding.html#new-fonts)
* start
  [Upgrading fonts specifics](https://googlefonts.github.io/gf-guide/onboarding.html#font-upgrades)
* must→
  [Overall font files requirements](requirements.md)
* must→
  [Static fonts specifics](statics.md)
* must→
  [Variable fonts specifics](variable.md)
* must→
  [Vertical metrics](metrics.md)
* learn
  [Outline Quality](outlines.md)
* learn
  [Diacritics requirements](diacritics.md)

## Production: compiling your fonts for GF

Context, requirements, and tools to produce the fonts and get them ready for publishing.

* start
  [Massively distribution implications](https://googlefonts.github.io/gf-guide/production.html#fonts-are-massively-distributed)
* must→
  [Scalable font production](https://googlefonts.github.io/gf-guide/production.html#scalable-font-production)
* learn
  [Build the fonts](build.md)
* learn
  [QA tools](qa.md)
* learn
  [Local testing](testing.md)

## The google/fonts repository

Details on the Google Fonts repository that hosts the fonts projects already included in the Catalogue.

* nerd
  [google/fonts repository explained](googlefonts.md)

## Onboarding Fonts to GF

Advanced content for experienced contributors or team members with the details on the publishing process.

* nerd
  [Making a PR to Google Fonts](making-pr.md)
* team
  [Package the fonts](package.md)
* team
  [METADATA file](metadata.md)
* team
  [Description file](description.md)
* team
  [Onboarder workflow guide](onboarder-workflow.md)
* team
  [Reviewing PRs and sandbox](sandbox.md)
* templ
  [Designer Profile](profile.md)
* templ
  [Promo / Marketing](marketing.md)


text:
Lightweight  Genetic Algorithm Framework

Resources

Contains Validation Tests :

http://www.eis.mdx.ac.uk/staffpages/rvb/teaching/BIS3226/sol15.pdf