text:
/**
 * This software is released as part of the Pumpernickel project.
 *
 * All com.pump resources in the Pumpernickel project are distributed under the
 * MIT License:
 * https://github.com/mickleness/pumpernickel/raw/master/License.txt
 *
 * More information about the Pumpernickel project is available here:
 * https://mickleness.github.io/pumpernickel/
 */
package com.pump.icon.button;

import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;

import javax.swing.AbstractButton;

import com.pump.util.Property;

/**
 * This provides a snapshot of a button's state (is it pressed, enabled,
 * selected, focused, etc.). This should capture all the information that will
 * be used by a {@link ButtonIconColors} object to assign colors to render a
 * {@link ButtonIcon}.
 */
public class ButtonState implements Serializable {
	private static final long serialVersionUID = 1L;

	final Map<String, Object> map = new HashMap<>();

	final boolean armed, enabled, focusOwner, pressed, rollover, selected;

	/**
	 *
	 * @param button
	 * @param properties
	 *            an optional set of properties that can be identified by
	 *            calling {@link #getProperties()}.
	 */
	public ButtonState(AbstractButton button, Property... properties) {
		this(button.getModel().isArmed(), button.getModel().isEnabled(), button
				.isFocusOwner(), button.getModel().isPressed(), button
				.getModel().isRollover(), button.getModel().isSelected(),
				properties);
	}

	/**
	 *
	 * @param armed
	 * @param enabled
	 * @param focusOwner
	 * @param pressed
	 * @param rollover
	 * @param selected
	 * @param properties
	 *            an optional set of properties that can be identified by
	 *            calling {@link #getProperties()}.
	 */
	public ButtonState(boolean armed, boolean enabled, boolean focusOwner,
			boolean pressed, boolean rollover, boolean selected,
			Property... properties) {
		this.armed = armed;
		this.enabled = enabled;
		this.focusOwner = focusOwner;
		this.pressed = pressed;
		this.rollover = rollover;
		this.selected = selected;

		for (Property property : properties) {
			map.put(property.getName(), property.getValue());
		}
	}

	/**
	 * Return all the properties (if any) that were provided as Property objects
	 * in the constructor.
	 */
	public Map<String, Object> getProperties() {
		return new HashMap<>(map);
	}

	@Override
	public int hashCode() {
		int k = 0;
		if (isArmed())
			k += 1;
		if (isEnabled())
			k += 2;
		if (isFocusOwner())
			k += 4;
		if (isPressed())
			k += 8;
		if (isRollover())
			k += 16;
		if (isSelected())
			k += 32;
		return k;
	}

	public boolean isArmed() {
		return armed;
	}

	public boolean isEnabled() {
		return enabled;
	}

	public boolean isFocusOwner() {
		return focusOwner;
	}

	public boolean isPressed() {
		return pressed;
	}

	public boolean isRollover() {
		return rollover;
	}

	public boolean isSelected() {
		return selected;
	}

	@Override
	public boolean equals(Object obj) {
		if (!(obj instanceof ButtonState))
			return false;
		ButtonState other = (ButtonState) obj;
		return hashCode() == other.hashCode() && map.equals(other.map);
	}

	@Override
	public String toString() {
		StringBuilder sb = new StringBuilder();
		sb.append("ButtonState[ ");
		if (isArmed())
			sb.append("armed ");
		if (isEnabled())
			sb.append("enabled ");
		if (isFocusOwner())
			sb.append("focusOwner ");
		if (isPressed())
			sb.append("pressed ");
		if (isRollover())
			sb.append("rollover ");
		if (isSelected())
			sb.append("selected ");
		sb.append(map);
		sb.append("]");
		return sb.toString();
	}

	public Object getProperty(String propertyName) {
		return map.get(propertyName);
	}

}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;
using DocuSign.Models;
using Newtonsoft.Json;

namespace DocuSign
{
    public class AuthenticationClient
    {
        public string BaseUrl;
        public string DocuSignCredentials;

        private HttpClient _httpClient;
        private const string LoginInformationUrl = "https://demo.docusign.net/restapi/v2/login_information";

        public AuthenticationClient(string username, string password, string integratorKey)
            : this(username, password, integratorKey, new HttpClient())
        {
        }

        public AuthenticationClient(string username, string password, string integratorKey, HttpClient httpClient)
        {
            if (httpClient == null) throw new ArgumentNullException("httpClient");

            DocuSignCredentials = CreateDocuSignCredentials(username, password, integratorKey);

            _httpClient = httpClient;

            _httpClient.DefaultRequestHeaders.Add("X-DocuSign-Authentication", DocuSignCredentials);
            _httpClient.DefaultRequestHeaders.Accept.Clear();
            _httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
        }

        private string CreateDocuSignCredentials(string username, string password, string integratorKey)
        {
            var docuSignCredentials =
                "<DocuSignCredentials>" +
                    "<Username>" + username + "</Username>" +
                    "<Password>" + password + "</Password>" +
                    "<IntegratorKey>" + integratorKey + "</IntegratorKey>" +
                    "</DocuSignCredentials>";

            return docuSignCredentials;
        }

        public async Task<LoginAccount> LoginInformationAsync()
        {
            var request = new HttpRequestMessage
            {
                Method = HttpMethod.Get,
                RequestUri = new Uri(LoginInformationUrl)
            };

            var responseMessage = await _httpClient.SendAsync(request).ConfigureAwait(false);
            var response = await responseMessage.Content.ReadAsStringAsync().ConfigureAwait(false);

            if (responseMessage.IsSuccessStatusCode)
            {
                var loginInformation = JsonConvert.DeserializeObject<LoginAccounts>(response);
                this.BaseUrl = loginInformation.loginAccounts[0].baseUrl;

                return loginInformation.loginAccounts[0];
            }

            // implement error handling
            return null;
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
#include "vixen.h"
#include "vxutil.h"

namespace Vixen {

/*!
 * @fn int QuadTree::CullData(Box2 bound, QuadRoot *root)
 * @param bound	bounds to cull within
 * @param root	root of quad tree
 *
 * Compares each model in the local set and culls those which
 * are not within the input bounds
 *
 * @return number of models kept
 */
int QuadTree::CullData(Box2 bound, QuadRoot *root)
{
	for (int i = 0; i < m_Prims.GetSize(); i++)
	{
		if (!root->BoundCheck(bound, m_Prims[i]))
		{
			m_Prims.RemoveAt(i);
			--i;
		}
	}
	return (int) m_Prims.GetSize();
}

QuadRoot::QuadRoot(int thresh, int limit) : SharedObj()
{
	SetThreshold(thresh);
	SetLimit(limit);
}

/*!
 * @fn Vec2 QuadRoot::Planify(const Vec3 &vert)
 *
 * Projects the input vertex onto the ground plane.
 * Currently, the ground plane is hard-coded as the XZ plane
 * so the routine returns Vec2(vert.x, vert.z)
 */
Vec2 QuadRoot::Planify(const Vec3 &vert)
{
	return Vec2(vert.x, vert.z);
}

/*!
 * @fn QuadTree* QuadRoot::Descend(const Vec3 &location)
 * @param location	location to check
 *
 * Find the node which contains a list of possible hits for
 * the input point
 */
const QuadTree* QuadRoot::Descend(const Vec3 &location) const
{
	Vec2 loc = Planify(location);

	if (m_pRoot == (const QuadTree*) NULL)		// if there is currently no tree, bail out
		return NULL;

	Box2 loc_bound = m_Bound;				//  if original location is out of bounds, bail
	if ((loc.x < loc_bound.min.x) || (loc.x >= loc_bound.max.x) ||
		(loc.y < loc_bound.min.y) || (loc.y >= loc_bound.max.y))
		return NULL;

	const QuadTree* pCurrent = m_pRoot;

	while (pCurrent && pCurrent->NodeType() == QN_INTERNAL)
	{
		Vec2 center = loc_bound.Center();
		if (loc.x < center.x)
		{
			if (loc.y < center.y)
			{
				//quad 0
				loc_bound.max = center;
				pCurrent = pCurrent->m_apNode[0];
			}
			else
			{
				//quad 2
				loc_bound.min.y = center.y;
				loc_bound.max.x = center.x;
				pCurrent = pCurrent->m_apNode[2];
			}
		}
		else
		{
			if (loc.y < center.y)
			{
				//quad 1
				loc_bound.min.x = center.x;
				loc_bound.max.y = center.y;
				pCurrent = pCurrent->m_apNode[1];
			}
			else
			{
				//quad 3
				loc_bound.min = center;
				pCurrent = pCurrent->m_apNode[3];
			}
		}
	}
	return pCurrent;
}

bool QuadRoot::BuildTree()
{
	int i;

	VX_ASSERT(m_Size >0);
	if (m_Size <= 0)					// make sure size has been properly set
		return false;
	m_pRoot = new QuadTree(QN_CONTAINER);
	VX_ASSERT(m_pRoot != NULL);
	if (m_pRoot == (const QuadTree*) NULL)
		return false;
	for (i = 0; i < m_Size; i++)		// create root node initialized to contain every prim.
		m_pRoot->m_Prims.Append(i);
	m_pRoot = BuildRecurse(m_pRoot, m_Bound, m_Threshold, 0, m_Limit);
	if (m_pRoot == (const QuadTree*) NULL)	// expand tree from seed node using recursion
		return false;
	DebugTreeData(&m_debugData);
	return true;
}

QuadTree* QuadRoot::BuildRecurse(QuadTree *node, const Box2& bound, int thresh, int depth, int limit)
{
	int tmp;
	if ((tmp = node->CullData(bound, this)) == 0)	// base case 1: node is empty, return zero node
	{
//		node->Delete();
		return NULL;
	}
	if (tmp < thresh)								// base case 2: threshold reached, node does not need to be divided
		return node;
	if (depth >= limit)								// base case 3: depth limit reached, do not divided any further
		return node;

	QuadTree* new_node = new QuadTree();		// make new internal node
	for (int i = 0; i < 4; i++)
	{
		QuadTree* child_node = new QuadTree(QN_CONTAINER);
		VX_ASSERT(child_node != NULL);			// create new child container node
		child_node->SetData(&(node->m_Prims));	// give it the parent node's data
		Box2 subBound = QuadTree::SubBound(bound, i);	// get bound for new child node
		new_node->m_apNode[i] = BuildRecurse(child_node, subBound, thresh, depth + 1, limit);
	}
//	node->Delete();								// delete old container and return new internal node
	return new_node;
}

const IntArray* QuadRoot::GetHitList(Vec3 testPoint) const
{
	const QuadTree* node = Descend(testPoint);
	if (node == NULL)
		return NULL;
	if (node->m_Prims.GetSize() == 0)
		return NULL;
	return &(node->m_Prims);
}

Box2 QuadTree::SubBound(const Box2 &bound, int which)
{
	Box2 new_bound;
	Vec2 center = bound.Center();

	switch (which)
	{
		case 0:
		new_bound.min = bound.min;
		new_bound.max = center;
		break;

		case 1:
		new_bound.min.x = center.x;
		new_bound.min.y = bound.min.y;
		new_bound.max.x = bound.max.x;
		new_bound.max.y = center.y;
		break;

		case 2:
		new_bound.min.x = bound.min.x;
		new_bound.min.y = center.y;
		new_bound.max.x = center.x;
		new_bound.max.y = bound.max.y;
		break;

		case 3:
		new_bound.min = center;
		new_bound.max = bound.max;
		break;

		default:
		VX_ASSERT(0);
	}
	return new_bound;
}

void QuadRoot::RecurseTreeData(QuadTree* node, TreeData *data)
{
	if (node == NULL)
	{
		data->numZero++;
        data->sumContDepth += data->depth;
        data->maxDepth = (data->depth > data->maxDepth) ? data->depth : data->maxDepth;
		return;
	}

	int type = node->NodeType();
    switch (type)
    {
		case QN_INTERNAL:
        data->numInternal++;
        data->depth++;

        RecurseTreeData(node->m_apNode[0], data);
        RecurseTreeData(node->m_apNode[1], data);
        RecurseTreeData(node->m_apNode[2], data);
        RecurseTreeData(node->m_apNode[3], data);
        data->depth--;
        break;

		case QN_CONTAINER:
        data->numContainer++;
        data->sumListSize += (int) node->m_Prims.GetSize();
        data->sumContDepth += data->depth;
        data->maxDepth = (data->depth > data->maxDepth) ? data->depth : data->maxDepth;
        break;

		default:
        VX_ASSERT(0);
        break;
    }
    return;
}

void QuadRoot::DebugTreeData(TreeData* data)
{
    if (m_pRoot != NULL)
        RecurseTreeData(m_pRoot, data);
    if (data->numContainer != 0)
    {
        data->aveContDepth = data->sumContDepth / (float) data->numContainer;
        data->aveListSize  = data->sumListSize / (float) data->numContainer;
    }
}
}	// end Vixen


text:
actions :enable, :disable, :restart, :reload
default_action :enable

attribute :name, kind_of: String, default: nil, name_attribute: true

def initialize(*args)
  super
  @provider = Chef::Provider::GraphiteServiceRunit
end

def service_name
  "carbon-" + name.tr(":", "-")
end

def type
  t, _ = name.split(":")
  t
end

def instance
  _, i = name.split(":")
  i
end


text:
Quantum plugin specific files
=============================
Quantum plugins require plugin specific behavior.
The files under the directory, ``lib/quantum_plugins/``, will be used
when their service is enabled.
Each plugin has ``lib/quantum_plugins/$Q_PLUGIN`` and define the following
functions.
Plugin specific configuration variables should be in this file.

* filename: ``$Q_PLUGIN``
  * The corresponding file name MUST be the same to plugin name ``$Q_PLUGIN``.
    Plugin specific configuration variables should be in this file.

functions
---------
``lib/quantum`` calls the following functions when the ``$Q_PLUGIN`` is enabled

* ``quantum_plugin_create_nova_conf`` :
  set ``NOVA_VIF_DRIVER`` and optionally set options in nova_conf
  e.g.
  NOVA_VIF_DRIVER=${NOVA_VIF_DRIVER:-"nova.virt.libvirt.vif.LibvirtGenericVIFDriver"}
* ``quantum_plugin_install_agent_packages`` :
  install packages that is specific to plugin agent
  e.g.
  install_package bridge-utils
* ``quantum_plugin_configure_common`` :
  set plugin-specific variables, ``Q_PLUGIN_CONF_PATH``, ``Q_PLUGIN_CONF_FILENAME``,
  ``Q_DB_NAME``, ``Q_PLUGIN_CLASS``
* ``quantum_plugin_configure_debug_command``
* ``quantum_plugin_configure_dhcp_agent``
* ``quantum_plugin_configure_l3_agent``
* ``quantum_plugin_configure_plugin_agent``
* ``quantum_plugin_configure_service``
* ``quantum_plugin_setup_interface_driver``
* ``has_quantum_plugin_security_group``:
  return 0 if the plugin support quantum security group otherwise return 1


text:
package com.xem.mzbphoneapp.atys;

import android.content.Context;
import android.os.Bundle;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;

import com.loopj.android.http.RequestParams;
import com.xem.mzbphoneapp.R;
import com.xem.mzbphoneapp.entity.EmployeData;
import com.xem.mzbphoneapp.utils.Config;
import com.xem.mzbphoneapp.utils.GetPushagrs;
import com.xem.mzbphoneapp.utils.MzbUrlFactory;
import com.xem.mzbphoneapp.utils.NetCallBack;
import com.xem.mzbphoneapp.utils.RequestUtils;
import com.xem.mzbphoneapp.utils.TitleBuilder;
import com.xem.mzbphoneapp.view.MzbProgressDialog;

import org.json.JSONException;
import org.json.JSONObject;

import butterknife.ButterKnife;
import butterknife.InjectView;
import butterknife.OnClick;

/**
 * Created by xuebing on 15/6/24.
 */
public class E0_EmployeeBindAty extends MzbActivity {

    @InjectView(R.id.titlebar_iv_left)
    ImageView back;
    @InjectView(R.id.account_num)
    EditText accounNum;
    @InjectView(R.id.all_bind)
    View allBind;
    @InjectView(R.id.account_pwd)
    EditText accounPwd;
    @InjectView(R.id.brand_num)
    EditText brandNum;
    @InjectView(R.id.btnBind)
    Button btn_sure;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.employee_bind_aty);
        ButterKnife.inject(this);
        new TitleBuilder(this).setTitleText("我是员工").setLeftImage(R.mipmap.top_view_back);
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    @OnClick({R.id.titlebar_iv_left, R.id.btnBind,R.id.all_bind})
    public void onDo(View v) {
        switch (v.getId()) {
            case R.id.titlebar_iv_left:
                finish();
                break;
            case R.id.all_bind:
                InputMethodManager imm = (InputMethodManager)
                        getSystemService(Context.INPUT_METHOD_SERVICE);
                imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
                break;
            case R.id.btnBind:
                if (brandNum.getText().toString().trim().equals("")) {
                    showToast("输入品牌编号");
                    return;
                } else if (accounNum.getText().toString().trim().equals("")) {
                    showToast("输入账号");
                    return;
                } else if (accounPwd.getText().toString().trim().equals("")) {
                    showToast("输入密码");
                    return;
                }

                hideKeyboard(v);
                DoLogin(brandNum.getText().toString(), accounNum.getText().toString(), accounPwd.getText().toString());
                break;
        }
    }

    public void DoLogin(String brand, String account, String password) {
        RequestParams params1 = new RequestParams();
        params1.put("type","B");
        params1.put("ppno", brand);
        params1.put("account", account);
        params1.put("password", password);
        params1.put("uid", Config.getCachedUid(E0_EmployeeBindAty.this));

        RequestUtils.ClientTokenPost(E0_EmployeeBindAty.this, MzbUrlFactory.BASE_URL + MzbUrlFactory.BRAND_BIND, params1, new NetCallBack(this) {
            @Override
            public void onMzbSuccess(String result) {

                try {
                    JSONObject obj = new JSONObject(result);

                    if (obj.getInt("code") == 0) {

                        JSONObject data = obj.getJSONObject("data");
                        EmployeData employeData = gson.fromJson(data.toString(),EmployeData.class);
                        Config.cachedBrandAccid(E0_EmployeeBindAty.this, employeData.getAccid());
                        Config.cachedBrandEmpid(E0_EmployeeBindAty.this, employeData.getEmpid());
                        Config.cachedBrandCodes(E0_EmployeeBindAty.this, employeData.getRoles());
                        Config.cachedBrandRights(E0_EmployeeBindAty.this, employeData.getRights());
                        Config.cachedIsemploye(E0_EmployeeBindAty.this, true);
                        intent2Aty(E1_EmployeeInfoAty.class);
                        showToast("绑定成功!");
                        new GetPushagrs(E0_EmployeeBindAty.this).refreshPushagrs();
                        finish();
                    } else {
                        showToast(obj.getString("message"));
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onMzbFailues(Throwable arg0) {
                showToast("请求失败");
            }
        });
    }

}


text:
from rest_framework.status import HTTP_403_FORBIDDEN
from rest_framework.status import HTTP_201_CREATED, HTTP_200_OK

from rest_framework.status import HTTP_400_BAD_REQUEST
import pytest

from accounts.models import User, LostKey
from accounts.tests.testutils.test_api_utils import *

@pytest.mark.django_db
class TestApiLostKey(object):
    """
    Exercise the lost_key API
    """

    def test_should_not_create_resource_with_wrong_email(self):
        """
        Test create view with invalid email
        :return:
        """
        response = create_lost_keys_api_call(email="nonexistent@ema.il")
        assert (response.status_code == HTTP_400_BAD_REQUEST)

    def test_hash_should_be_unique(self, lostkey1, lostkey2):
        # retrieve first lost key resource
        lost_key_1 = LostKey.objects.get(pk=lostkey1.pk)
        # retrieve second lost key resource
        lost_key_2 = LostKey.objects.get(pk=lostkey2.pk)

        assert lost_key_1.hash != lost_key_2.hash

    def test_should_create_a_new_lostkey_resource(self, user1):
        """
        Exercise the creation of a lost key resource
        :return:
        """
        response = create_lost_keys_api_call(email=user1.email)
        assert response.status_code == HTTP_201_CREATED

        assert response.data.get('email'), user1.email
        # id should not be null
        assert response.data.get('id') is not None

    def test_should_not_retrieve_user_without_hash(self, lostkey1):
        """
        Check authentication base on hash
        :param
        :return:
        """
        # with proper hash
        response = retrieve_lost_key_api_call(lostkey1.pk,
                                              lostkey1.hash)
        assert response.status_code == HTTP_200_OK
        # without proper hash
        response = retrieve_lost_key_api_call(lostkey1.pk,
                                              '1nv4l1d_h4sh')
        assert response.status_code == HTTP_403_FORBIDDEN

    def test_should_not_update_user_without_hash(self, lostkey1):
        """
        Check authentication base on hash
        :return:
        """
        # update call update without hash
        response = update_lost_key_api_rebuild_call(lostkey1.pk,
                                                    '')
        assert response.status_code, HTTP_403_FORBIDDEN

    def test_should_update_the_user(self, lostkey1, user1):
        """
        Update a user public key
        :return:
        """
        new_public_key = 'AnOtHer PuBlIc KeY'

        response = update_lost_key_api_rebuild_call(lostkey1.id, lostkey1.hash,
                                                    public_key=new_public_key)

        fresh_select_user = User.objects.get(pk=user1.pk)
        fresh_select_lostkey = LostKey.objects.get(pk=lostkey1.pk)
        # The user has been updated
        assert response.status_code == HTTP_200_OK
        # The lost key row must be marked as used
        assert fresh_select_lostkey.used is True
        # The user public_key field must be updated
        assert fresh_select_user.public_key == new_public_key

    def test_cannot_use_lost_key_resource_twice(self, lostkey1):
        response = update_lost_key_api_rebuild_call(
            lostkey1.id, lostkey1.hash, 'Some changes on the public key'
        )
        # the resource was correctly updated
        assert response.status_code, HTTP_200_OK

        response = update_lost_key_api_rebuild_call(
            lostkey1.id, lostkey1.hash, 'Random changes on the public key'
        )
        # Once used the resource can not be used again
        assert response.status_code == HTTP_403_FORBIDDEN


text:
package edu.psu.compbio.seqcode.projects.multigps.hitloaders;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;

import edu.psu.compbio.seqcode.projects.multigps.framework.*;

public class IDXFileHitLoader extends FileHitLoader {

	public IDXFileHitLoader(File f, boolean nonUnique) {
    	super(f, nonUnique);
	}

	/**
	 * Get the reads from the appropriate source (implementation-specific).
	 * Loads data to the fivePrimesList and hitsCountList
	 */
	public void sourceReads() {
		this.initialize();
		try {
			totalHits=0;
			BufferedReader reader = new BufferedReader(new FileReader(file));
			String line;
			Read posRead=null, negRead=null;
	        while ((line = reader.readLine()) != null) {
	        	line = line.trim();
	        	String[] words = line.split("\\s+");
	        	if(line.charAt(0)!='#' && words.length>=4 && !words[0].equals("chrom")){
		            String chr="."; char strand = '.';
		            int fivePrime=0;
		            float posWeight=0, negWeight=0;
		            try{
            			chr = words[0];
            			String[] tmp = chr.split("\\.");
            			chr=tmp[0].replaceFirst("chr", "");
            			chr=chr.replaceFirst("^>", "");
            			fivePrime = new Integer(words[1]).intValue();
            			posWeight = new Integer(words[2]).floatValue();
            			negWeight = new Integer(words[3]).floatValue();
            			if(posWeight>0){
            				ReadHit posHit = new ReadHit(chr, fivePrime, fivePrime, '+', posWeight);
            				posRead = new Read();
            				//Add the hit, but don't update weight since the weight is used here for representing the read count
            				posRead.addHit(posHit, false);
            				addHits(posRead);
            			}
            			if(negWeight>0){
            				ReadHit negHit = new ReadHit(chr, fivePrime, fivePrime, '-', negWeight);
            				negRead = new Read();
            				//Add the hit, but don't update weight since the weight is used here for representing the read count
            				negRead.addHit(negHit, false);
            				addHits(negRead);
            			}
	            	} catch (NumberFormatException e){
	            		// skip reading this line for header or comment lines
	           		}
	    		}
            }
	        reader.close();
		}
		catch (IOException e) {
			e.printStackTrace();
		}
	}//end of countReads method

}//end of BEDFileReader class


text:
# Copyright 2002 Dave Abrahams
# Copyright 2003, 2004 Vladimir Prus
# Distributed under the Boost Software License, Version 1.0.
# (See accompanying file LICENSE_1_0.txt or http://www.boost.org/LICENSE_1_0.txt)

import BoostBuild
import os.path
import re

def check_for_existing_boost_build_jam(t):
    """
      This test depends on no boost-build.jam file existing in any of the
    folders along the current folder's path. If it does exist, not only would
    this test fail but it could point to a completely wrong Boost Build
    installation, thus causing headaches when attempting to diagnose the
    problem. That is why we explicitly check for this scenario.

    """
    problem = find_up_to_root(t.workdir, "boost-build.jam")
    if problem:
        BoostBuild.annotation("misconfiguration", """\
This test expects to be run from a folder with no 'boost-build.jam' file in any
of the folders along its path.

Working folder:
  '%s'

Problematic boost-build.jam found at:
  '%s'

Please remove this file or change the test's working folder and rerun the test.
""" % (t.workdir, problem))
        t.fail_test(1, dump_stdio=False, dump_stack=False)

def find_up_to_root(folder, name):
    last = ""
    while last != folder:
        candidate = os.path.join(folder, name)
        if os.path.exists(candidate):
            return candidate
        last = folder
        folder = os.path.dirname(folder)

def match_re(actual, expected):
    return re.match(expected, actual, re.DOTALL) != None

t = BoostBuild.Tester(match=match_re, boost_build_path="", pass_toolset=0)
t.set_tree("startup")
check_for_existing_boost_build_jam(t)

t.run_build_system(status=1, stdout=
r"""Unable to load Boost\.Build: could not find "boost-build\.jam"
.*Attempted search from .* up to the root""")

t.run_build_system(status=1, subdir="no-bootstrap1",
    stdout=r"Unable to load Boost\.Build: could not find build system\."
    r".*attempted to load the build system by invoking"
    r".*'boost-build ;'"
    r'.*but we were unable to find "bootstrap\.jam"')

# Descend to a subdirectory which /does not/ contain a boost-build.jam file,
# and try again to test the crawl-up behavior.
t.run_build_system(status=1, subdir=os.path.join("no-bootstrap1", "subdir"),
    stdout=r"Unable to load Boost\.Build: could not find build system\."
    r".*attempted to load the build system by invoking"
    r".*'boost-build ;'"
    r'.*but we were unable to find "bootstrap\.jam"')

t.run_build_system(status=1, subdir="no-bootstrap2",
    stdout=r"Unable to load Boost\.Build: could not find build system\."
    r".*attempted to load the build system by invoking"
    r".*'boost-build \. ;'"
    r'.*but we were unable to find "bootstrap\.jam"')

t.run_build_system(status=1, subdir='no-bootstrap3', stdout=
r"""Unable to load Boost.Build
.*boost-build\.jam" was found.*
However, it failed to call the "boost-build" rule""")

# Test bootstrapping based on BOOST_BUILD_PATH.
t.run_build_system(["-sBOOST_BUILD_PATH=../boost-root/build"],
    subdir="bootstrap-env", stdout="build system bootstrapped")

# Test bootstrapping based on an explicit path in boost-build.jam.
t.run_build_system(subdir="bootstrap-explicit",
    stdout="build system bootstrapped")

t.cleanup()


text:
var sys = require('sys');
var _ = require('underscore');
var users = require('../../users');
var badge_template = require('./badge');
// badge key, must be unique.
var name = "1000page";

exports.badge_info =
    {
        id: name,
        name: "1,000 Pages",
        achievement: "Reading over 1,000 pages."
    }

// the in-work state of a badge for a user
function Badge (userid) {
    badge_template.Badge.apply(this,arguments);
    this.id = name;
    this.page_goal = 1000;
};
// inherit from the badge template
sys.inherits(Badge, badge_template.Badge);

// Steps to perform when a book is added or modified in the read list
Badge.prototype.add_reading_transform = function(reading,callback) {
    var pages = parseInt(reading.book.pages);
    if (_.isNumber(pages)) {
        this.state[reading.book_id] = pages
    }
    callback();
};

// Steps to perform when a book is removed from the read list.
Badge.prototype.remove_book_transform = function(book,callback) {
    delete(this.state[book.id]);
    callback();
};

// determine if the badge should be awarded, and if yes, do so
Badge.prototype.should_award = function(callback) {
    // sum all page counts in state
    var pagecount = 0;
    for (bookid in this.state) {
        pagecount += this.state[bookid]
    }
    return (pagecount >= this.page_goal);
}

exports.Badge = Badge;


text:
package org.nd4j.linalg.ops.reduceops.complex;

import org.nd4j.linalg.api.complex.IComplexNDArray;
import org.nd4j.linalg.api.complex.IComplexNumber;
import org.nd4j.linalg.factory.Nd4j;

/**
 *
 * @author Adam Gibson
 */
public class Max extends BaseScalarOp {
    public Max() {
        super(Nd4j.createDouble(Double.MIN_VALUE, 0));
    }

    @Override
    public IComplexNumber accumulate(IComplexNDArray arr, int i, IComplexNumber soFar) {
        IComplexNumber curr = (IComplexNumber) arr.getScalar(i).element();
        return soFar.absoluteValue().doubleValue() > curr.absoluteValue().doubleValue() ? soFar : curr;
    }
}


text:
package com.uiuc.dslogs;

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

import com.uiuc.dslogs.grep.GrepCommand;
import com.uiuc.dslogs.listener.CommandListener;
import com.uiuc.dslogs.model.Node;
import com.uiuc.dslogs.service.ConnectorService;
import com.uiuc.dslogs.service.IConnectorService;

public class Test {
	public static void main(String[] args) {
		CommandListener commandListener = new CommandListener();

		commandListener.startService(5989);

		//GrepCommand ExecGrep = new GrepCommand();
		//ExecGrep.executeGrep(true);

	}
}


text:
from django.db import migrations, models

class Migration(migrations.Migration):

    dependencies = [
        ('devilry_compressionutil', '0006_compressedarchivemeta_created_by_role'),
    ]

    operations = [
        migrations.AlterField(
            model_name='compressedarchivemeta',
            name='archive_size',
            field=models.BigIntegerField(),
        ),
    ]


text:
layout: page
title: Mccullough Aerospace Show
date: 2016-05-24
author: Anthony Roberts
tags: weekly links, java
status: published
summary: Aenean lobortis, nunc at accumsan.
banner: images/banner/wedding.jpg
booking:
  startDate: 07/12/2019
  endDate: 07/13/2019
  ctyhocn: BHBEWHX
  groupCode: MAS
published: true
---
Nullam suscipit metus ipsum, sit amet tempus dolor elementum et. Suspendisse scelerisque lobortis felis, eget tristique libero euismod in. In hac habitasse platea dictumst. Praesent volutpat iaculis erat, ut sollicitudin arcu aliquet at. Sed vulputate dui egestas libero suscipit, et tempor magna tincidunt. Vestibulum dapibus odio a posuere dictum. Praesent auctor vulputate tortor sed sollicitudin. In laoreet auctor mattis. Ut arcu eros, facilisis iaculis vestibulum et, tempor vel diam. Quisque elementum risus eu ipsum venenatis, vel dignissim felis tempus.
Sed augue tellus, rutrum eu lacus vel, accumsan malesuada turpis. Maecenas volutpat ante non tellus tincidunt suscipit. Proin euismod posuere aliquet. Aliquam pharetra euismod urna vitae suscipit. Aenean ultricies hendrerit imperdiet. Nullam in fringilla sem. Cras elementum maximus urna, quis mattis magna porta id. Pellentesque semper dui vel eros tincidunt, lacinia eleifend augue dignissim. Proin in scelerisque augue, at suscipit mi. Ut laoreet tristique cursus. Nunc blandit tincidunt velit, id efficitur ligula ullamcorper eget. Nam et posuere velit, sed maximus lacus.

* Donec et leo sit amet massa mollis lobortis id non tellus
* Sed posuere est quis venenatis euismod
* Donec non ex ullamcorper, lacinia diam in, interdum arcu.

In viverra iaculis mi vel faucibus. Nunc aliquet, odio sed lobortis vehicula, erat eros vestibulum massa, consectetur laoreet nunc nibh vel nunc. Maecenas consectetur viverra ipsum quis sodales. Nam ut augue fringilla, malesuada urna ut, blandit velit. Phasellus consequat pharetra felis at facilisis. Nulla facilisi. Nunc feugiat rutrum justo sed luctus. Aenean congue felis vel consectetur scelerisque. Quisque vestibulum nunc quis ex placerat, in blandit nulla molestie. Ut faucibus egestas dolor.


text:
<?php
namespace Modules\Calendar;
use \Module as Module;

(defined('BASEPATH')) OR exit('No direct script access allowed');

/**
 * Content Module
 *
 * @link        http://pagestudiocms.com
 * @author      PageStudioCMS Dev Team
 * @package     Modules
 */
class Details extends Module
{
    public static function info()
    {
        return [
            'name'          => 'Calendar',
            'slug'          => 'calendar',
            'description'   => 'The Events Calendar allows you to create and manage your calendar of events with ease. It also comes with an extensible plugin that lets you easily share your events accross your site.',
            'version'       => '1.0',
            'addon_uri'     => 'http://pagestudiocms.com',
            'license'       => 'GPL2',
            'license_uri'   => '',
            'author'        => 'Cosmo Mathieu',
            'author_uri'    => 'http://pagestudiocms.com',
            'plugable'      => 0,
            'is_core'       => 0,
        ];
    }

    /**
     * Returns an array containing the module level menu items to be
     * hooked into the admin menu
     *
     * @return array
     */
    public static function admin_menu()
    {
        return [[
            'label' => 'Calendar',
            'url'   => 'calendar/entries',
            "menu_order" => 89,
        ]];
    }

    /**
     * Static method that either returns or instantiates the object
     *
     * @return object
     */
    public static function run()
    {
        if( ! isset(self::$_instance)) {
            self::$_instance = new Details();
        }

        return self::$_instance;
    }

    public function enable()
    {

    }

    public function disable()
    {

    }

    public function install()
	{
        extract($this->info());
        $this->dbforge->drop_table('calendar');
        $this->db->delete('modules', ['module_slug' => $slug]);

        // Create table to store the events
        $fields = [
            'id' => [
                'type' => 'INT',
                'constraint' => '11',
                'auto_increment' => TRUE
            ],
            'title' => [
                'type' => 'VARCHAR',
                'constraint' => '100'
            ],
            'description' => [
                'type' => 'TEXT',
                'null' => TRUE
            ],
            'start' => [
                'type' => 'DATETIME',
                'default' => '1900-01-01 00:00:00',
                'null' => FALSE,
            ],
            'end' => [
                'type' => 'DATETIME',
                'default' => '1900-01-01 00:00:00',
                'null' => FALSE,
            ],
        ];

        log_message('error', '-- -- Will go ahead and create the [calendar] table.');
        $this->dbforge->add_field($fields);
        $this->dbforge->add_field("created TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP");
        $this->dbforge->add_field('modified DATETIME DEFAULT NULL');
        $this->dbforge->add_field('url VARCHAR(255) NOT NULL');
        $this->dbforge->add_field('location VARCHAR(250) NOT NULL');
        $this->dbforge->add_field('featured_image VARCHAR(255) NOT NULL');
        $this->dbforge->add_field('event_author int(11) NOT NULL');
        $this->dbforge->add_field('allDay VARCHAR(35) NOT NULL');
        $this->dbforge->add_field('recurrence VARCHAR(35) DEFAULT NULL');
        $this->dbforge->add_field('series_id int(64) DEFAULT NULL');

        $this->dbforge->add_key('id', TRUE);
        $this->dbforge->add_key('series_id', FALSE);

        // TODO: Document this...
        $data = [
            'module_slug' => $slug,
            'module_name' => $name,
            'module_description' => $description,
            'module_version' => $version,
            'module_options' => '',
            'has_backend' => 1,
            'has_plugin' => $plugable,
            'has_widget' => 0,
            'is_core' => $is_core,
            'is_enabled' => 1,
            'is_required' => 1,
            // 'menu_order' => 0,
		];

        $atts = array('ENGINE' => 'InnoDB'); // TODO: This doesn't work as this feature only exists in CI 3.

        // Let's try running our DB Forge Table and inserting some settings
        if ( ! $this->dbforge->create_table('calendar', FALSE, $atts) OR ! $this->db->insert('modules', $data)) {
            log_message('error', '-- -- Could not create the [calendar] table. Or unable to insert [calendar] settings into [modules] table.');
            return false;
        }
		return true;
	}

    public function uninstall()
	{
        $info = $this->info();

        if( ! $this->dbforge->drop_table('calendar')) {
            log_message('error', '-- -- Unable to drop the [calendar] table.');
            return false;
        }

        if ( ! $this->db->delete('modules', ['module_slug' => $info['slug']])) {
            log_message('error', '-- -- Unable to remove the [calendar] entry from the [modules] table.');
            return false;
        }
		return true;
	}

	public function upgrade($old_version)
	{
		return true;
	}
}


text:
class AddLatitudeAndLongitudeToParlors < ActiveRecord::Migration[5.0]
  def change
    add_column :parlors, :latitude, :float
    add_column :parlors, :longitude, :float
  end
end


text:
//
//  WDECSegment.h
//  WDeCom
//
//  Created by Vrana, Jozef on 20/09/2018.
//  Copyright © 2018 Wirecard Technologies GmbH. All rights reserved.
//

#import <Foundation/Foundation.h>

@interface WDECSegment : NSObject

/** Carrier code
 @brief The 2-letter airline code (e.g. LH, BA, KL) supplied by IATA for each leg of a flight.
 @details Max. length 3. It is optional.
 */
@property (strong, nonatomic) NSString *carrierCode;

/** Departure airport code
 @brief The departure airport code. IATA assigns the airport codes.
 @details Max. length 3. It is optional.
 */
@property (strong, nonatomic) NSString *departureAirportCode;

/** Departure city code
 @brief The departure city code of the itinerary segment. IATA assigns the airport codes.
 @details Max. length 32. It is optional.
 */
@property (strong, nonatomic) NSString *departureCityCode;

/** Arrival code
 @brief The arrival airport code of the itinerary segment. IATA assigns the airport codes.
 @details Max. length 3. It is optional.
 */
@property (strong, nonatomic) NSString *arrivalAirportCode;

/** Arrival city code
 @brief The arrival city code of the itinerary segment. IATA assigns the airport codes.
 @details Max. length 32. It is optional.
 */
@property (strong, nonatomic) NSString *arrivalCityCode;

/** Departure date
 @brief The departure date for a given leg.
 */
@property (strong, nonatomic) NSDate *departureDate;

/** Arrival date
 @brief The arrival date of the itinerary segment. IATA assigns the airport codes.
 */
@property (strong, nonatomic) NSDate *arrivalDate;

/** Flight number
 @brief The city of the address of the airline transaction issuer.
 @details Max. length 6. It is optional.
 */
@property (strong, nonatomic) NSString *flightNumber;

/** Fare class
 @brief Used to distinguish between First Class, Business Class and Economy Class, but also used to distinguish between different fares and booking codes within the same type of service.
 @details Max. length 3. It is optional.
 */
@property (strong, nonatomic) NSString *fareClass;

/** Fare basis
 @brief Represents a specific fare and class of service with letters, numbers, or a combination of both.
 @details Max. length 6. It is optional.
 */
@property (strong, nonatomic) NSString *fareBasis;

/** Stop over code
 @brief 0 = allowed, 1 = not allowed
 */
@property (strong, nonatomic) NSString *stopOverCode;

/** Currency
 @brief The currency of tax amount.
 @details It is mandatory if tax amount is specified.
 */
@property (strong, nonatomic) NSString *currency;

/** Tax amount
 @brief The amount of the value added tax levied on the transaction amount in the specified currency.
 */
@property (strong, nonatomic) NSDecimalNumber *taxAmount;

@end


text:
/**
 * @fileoverview Fields and methods of the helma.Ssh class.
 *

 * To use this optional module, its repository needs to be added to the
 * application, for example by calling app.addRepository('modules/helma/Ssh.js')
 */

// take care of any dependencies
app.addRepository('modules/helma/File.js');
app.addRepository('modules/helma/ganymed-ssh2.jar');

// define the helma namespace, if not existing
if (!global.helma) {
    global.helma = {};
}

/**
 * Creates a new instance of helma.Ssh
 * @class This class provides methods for connecting to a remote
 * server via secure shell (ssh) and copying files from/to a remote
 * server using secure copy (scp). It utilizes "Ganymed SSH-2 for Java"
 * (see http://www.ganymed.ethz.ch/ssh2/).
 * @param {String} server The server to connect to
 * @param {helma.File|java.io.File|String} hosts Either a file
 * containing a list of known hosts, or the path pointing to a
 * file. This argument is optional.
 * @constructor
 * @returns A newly created instance of helma.Ssh
 * @author Robert Gaggl <robert@nomatic.org>
 */
helma.Ssh = function(server, hosts) {
    var SSHPKG = Packages.ch.ethz.ssh2;
    var SSHPKGNAME = "ganymed-ssh2.jar";
    var SSHPKGURL = "http://www.ganymed.ethz.ch/ssh2";
    var className = "helma.Ssh";
    var paranoid = false;
    var verifier = null;
    var knownHosts, connection;

    // check if necessary jar file is in classpath
    try {
        knownHosts = new SSHPKG.KnownHosts();
        connection = new SSHPKG.Connection(server);
    } catch (e) {
        if (e instanceof TypeError == false)
            throw(e);
        throw("helma.Ssh needs " + SSHPKGNAME +
              " in lib/ext or application directory " +
              "[" + SSHPKGURL + "]");
    }

    /**
     * A simple verifier for verifying host keys
     * @private
     */
    var SimpleVerifier = {
        verifyServerHostKey: function(hostname, port, serverHostKeyAlgorithm, serverHostKey) {
            var result = knownHosts.verifyHostkey(hostname, serverHostKeyAlgorithm, serverHostKey);
            switch (result) {
                case SSHPKG.KnownHosts.HOSTKEY_IS_OK:
                    debug("verifyServerHostKey", "received known host key, proceeding");
                    return true;
                case SSHPKG.KnownHosts.HOSTKEY_IS_NEW:
                    if (paranoid == true) {
                        debug("verifyServerHostKey", "received unknown host key, rejecting");
                        return false;
                    } else {
                        debug("verifyServerHostKey", "received new host key, adding temporarily to known hosts");
                        var hn = java.lang.reflect.Array.newInstance(java.lang.String, 1);
                        hn[0] = hostname;
                        knownHosts.addHostkey(hn, serverHostKeyAlgorithm, serverHostKey);
                        return true;
                    }
                case SSHPKG.KnownHosts.HOSTKEY_HAS_CHANGED:
                    debug("verifyServerHostKey", "WARNING: host key has changed, rejecting");
                default:
                    return false;
            }
            return;
        }
    };

    /**
     * Converts the argument into an instance of java.io.File
     * @param {helma.File|java.io.File|String} file Either a file
     * object or the path to a file as string
     * @returns The argument converted into a file object
     * @type java.io.File
     * @private
     */
    var getFile = function(file) {
        if (file instanceof helma.File) {
            return new java.io.File(file.getAbsolutePath());
        } else if (file instanceof java.io.File) {
            return file;
        } else if (file.constructor == String) {
            return new java.io.File(file);
        }
        return null;
    };

    /**
     * Connects to the remote server
     * @return Boolean
     * @private
     */
    var connect = function() {
        try {
            var info = connection.connect(verifier);
            debug("connect", "connected to server " + server);
            return true;
        } catch (e) {
            error("connect", "connection to " + server + " failed.");
        }
        return false;
    };

    /**
     * Private helper method for debugging output using app.logger
     * @param {String} methodName The name of the method
     * @param {String} msg The debug message to write to event log file
     * @private
     */
    var debug = function(methodName, msg) {
        var msg = msg ? " " + msg : "";
        app.logger.debug(className + ":" + methodName + msg);
        return;
    };

    /**
     * Private helper method for error output using app.logger
     * @param {String} methodName The name of the method
     * @param {String} msg The error message to write to event log file
     * @private
     */
    var error = function(methodName, msg) {
        var tx = java.lang.Thread.currentThread();
        tx.dumpStack();
        app.logger.error(className + ":" + methodName + ": " + msg);
        return;
    };

    /**
     * Opens the file passed as argument and adds the known hosts
     * therein to the list of known hosts for this client.
     * @param {helma.File|java.io.File|String} file Either a file object
     * or the path to a file containing a list of known hosts
     * @returns True if adding the list was successful, false otherwise
     * @type Boolean
     */
    this.addKnownHosts = function(file) {
        try {
            knownHosts.addHostkeys(getFile(file));
            verifier = new SSHPKG.ServerHostKeyVerifier(SimpleVerifier);
            return true;
        } catch (e) {
            error("addKnownHosts", "Missing or invalid known hosts file '" + file + "'");
        }
        return false;
    };

    /**
     * Connects to a remote host using plain username/password authentication.
     * @param {String} username The username
     * @param {String} password The password
     * @returns True in case the connection attempt was successful, false otherwise.
     * @type Boolean
     */
    this.connect = function(username, password) {
        if (!username || !password) {
            error("connect", "Insufficient arguments.");
        } else if (connect() && connection.authenticateWithPassword(username, password)) {
            debug("connect", "authenticated using password");
            return true;
        } else {
            error("connect", "Authentication failed!");
        }
        return false;
    };

    /**
     * Connects to a remote host using a private key and the corresponding
     * passphrase.
     * @param {String} username The username
     * @param {helma.File|java.io.File|String} key Either a file object
     * representing the private key file, or the path to it.
     * @param {String} passphrase The passphrase of the private key, if necessary.
     * @returns True in case the connection attempt was successful, false otherwise.
     * @type Boolean
     */
    this.connectWithKey = function(username, key, passphrase) {
        var keyFile;
        if (!username || !(keyFile = getFile(key))) {
            error("connectWithKey", "Insufficient or wrong arguments.");
        } else if (connect() && connection.authenticateWithPublicKey(username, keyFile, passphrase)) {
            debug("connectWithKey", "authenticated with key");
            return true;
        } else {
            error("connectWithKey", "Authentication failed!");
        }
        return false;
    };

    /**
     * Disconnects this client from the remote server.
     */
    this.disconnect = function() {
        connection.close();
        debug("disconnect", "disconnected from server " + server);
        return;
    };

    /**
     * Returns true if this client is currently connected.
     * @returns True in case this client is connected, false otherwise.
     * @type Boolean
     */
    this.isConnected = function() {
        return (connection != null && connection.isAuthenticationComplete());
    };

    /**
     * Copies a local file to the remote server
     * @param {String|Array} localFile Either the path to a single local
     * file or an array containing multiple file paths that should be
     * copied to the remote server.
     * @param {String} remoteDir The path to the remote destination directory
     * @param {String} mode An optional 4-digit permission mode string (eg.
     * 0755);
     * @returns True in case the operation was successful, false otherwise.
     * @type Boolean
     */
    this.put = function(localFile, remoteDir, mode) {
        if (!localFile || !remoteDir) {
            error("put", "Insufficient arguments.");
        } else if (!this.isConnected()) {
            error("put", "Not connected. Please establish a connection first.");
        } else {
            try {
                var scp = connection.createSCPClient();
                if (mode != null)
                    scp.put(localFile, remoteDir, mode);
                else
                    scp.put(localFile, remoteDir);
                debug("put", "copied '" + localFile + "' to '" + remoteDir + "'");
                return true;
            } catch (e) {
                error("put", e);
            }
        }
        return false;
    };

    /**
     * Retrieves a file from the remote server and stores it locally.
     * @param {String|Array} remoteFile Either the path to a single remote
     * file or an array containing multiple file paths that should be
     * copied onto the local disk.
     * @param {String} targetDir The path to the local destination directory
     * @returns True if the copy process was successful, false otherwise.
     * @type Boolean
     */
    this.get = function(remoteFile, targetDir) {
        if (!remoteFile || !targetDir) {
            error("get", "Insufficient arguments.");
        } else if (!this.isConnected()) {
            error("get", "Not connected. Please establish a connection first.");
        } else {
            try {
                var scp = connection.createSCPClient();
                scp.get(remoteFile, targetDir);
                debug("get", "copied '" + remoteFile + "' to '" + targetDir + "'");
                return true;
            } catch (e) {
                error("get", e);
            }
        }
        return false;
    };

    /**
     * Executes a single command on the remote server.
     * @param {String} cmd The command to execute on the remote server.
     * @return The result of the command execution
     * @type String
     */
    this.execCommand = function(cmd) {
        if (!this.isConnected()) {
            error("execCommand", "Not connected. Please establish a connection first.");
        } else {
            var session = connection.openSession();
            try {
                session.execCommand(cmd);
                var stdout = new SSHPKG.StreamGobbler(session.getStdout());
                var br = new java.io.BufferedReader(new java.io.InputStreamReader(stdout));
                res.push();
    			while (true) {
    				if (!(line = br.readLine()))
    					break;
    				res.writeln(line);
    			}
                debug("execCommand", "executed command '" + cmd + "'");
                return res.pop();
            } catch (e) {
                error("execCommand", e);
            } finally {
                session.close();
            }
        }
    };

    /**
     * Toggles paranoid mode. If set to true this client tries to
     * verify the host key against the its list of known hosts
     * during connection and rejects if the host key is not found
     * therein or is different.
     * @param {Boolean} p Either true or false
     */
    this.setParanoid = function(p) {
        paranoid = (p === true);
        return;
    };

    /**
     * Returns true if this client is in paranoid mode.
     * @return Boolean
     * @see #setParanoid
     */
    this.isParanoid = function() {
        return paranoid;
    };

    /**
     * main constructor body
     */
    if (hosts) {
        this.addKnownHosts(hosts);
    }

    for (var i in this)
        this.dontEnum(i);
    return this;
};

/** @ignore */
helma.Ssh.toString = function() {
    return "[helma.Ssh]";
};

helma.lib = "Ssh";
helma.dontEnum(helma.lib);
for (var i in helma[helma.lib])
    helma[helma.lib].dontEnum(i);
for (var i in helma[helma.lib].prototype)
    helma[helma.lib].prototype.dontEnum(i);
delete helma.lib;


text:
// ----------------------------------------------------------------------------------
//
// Copyright Microsoft Corporation
// 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.
// ----------------------------------------------------------------------------------

using AutoMapper;
using Microsoft.Azure.Commands.Compute.Common;
using Microsoft.Azure.Commands.Compute.Models;
using Microsoft.Azure.Management.Compute;
using Microsoft.Azure.Management.Compute.Models;
using Newtonsoft.Json;
using System.Collections.Generic;
using System.Linq;
using System.Management.Automation;
using System;
using Microsoft.Azure.Commands.ResourceManager.Common.ArgumentCompleters;

namespace Microsoft.Azure.Commands.Compute.Extension.AzureDiskEncryption
{
    [Cmdlet("Get", ResourceManager.Common.AzureRMConstants.AzureRMPrefix + "VmssVMDiskEncryption"), OutputType(typeof(PSVmssVMDiskEncryptionStatusContext))]
    [Alias("Get-" + ResourceManager.Common.AzureRMConstants.AzureRMPrefix + "VmssVMDiskEncryptionStatus")]
    public class GetAzureVmssVMDiskEncryptionStatusCommand : VirtualMachineScaleSetExtensionBaseCmdlet
    {
        [Parameter(
           Mandatory = true,
           Position = 0,
           ValueFromPipelineByPropertyName = true,
           HelpMessage = "Resource group name of the virtual machine scale set.")]
        [ResourceGroupCompleter]
        [ValidateNotNullOrEmpty]
        public string ResourceGroupName { get; set; }

        [Alias("Name")]
        [Parameter(
            Mandatory = true,
            Position = 1,
            ValueFromPipelineByPropertyName = true,
            HelpMessage = "The virtual machine scale set name.")]
        [ResourceNameCompleter("Microsoft.Compute/virtualMachineScaleSets", "ResourceGroupName")]
        [ValidateNotNullOrEmpty]
        public string VMScaleSetName { get; set; }

        [Parameter(
            Mandatory = false,
            Position = 2,
            ValueFromPipelineByPropertyName = true,
            ValueFromPipeline = false)]
        public string InstanceId { get; set; }

        [Parameter(
          Mandatory = false,
          ValueFromPipelineByPropertyName = true,
          HelpMessage = "The extension name. If this parameter is not specified, default values used are AzureDiskEncryption for windows VMs and AzureDiskEncryptionForLinux for Linux VMs")]
        [ValidateNotNullOrEmpty]
        public string ExtensionName { get; set; }

        public override void ExecuteCmdlet()
        {
            base.ExecuteCmdlet();

            ExecuteClientAction(() =>
            {
                if (string.IsNullOrWhiteSpace(this.InstanceId))
                {
                    var result = this.VirtualMachineScaleSetVMsClient.List(this.ResourceGroupName, this.VMScaleSetName);
                    List<VirtualMachineScaleSetVM> resultList = result.ToList();
                    var nextPageLink = result.NextPageLink;
                    while (!string.IsNullOrEmpty(nextPageLink))
                    {
                        var pageResult = VirtualMachineScaleSetVMsClient.ListNext(nextPageLink);
                        foreach (var pageItem in pageResult)
                        {
                            resultList.Add(pageItem);
                        }
                        nextPageLink = pageResult.NextPageLink;
                    }

                    var psResultList = new List<PSVmssVMDiskEncryptionStatusContextList>();
                    foreach (var vm in resultList)
                    {
                        var diskStatus = GetDiskStatus(this.ResourceGroupName, this.VMScaleSetName, vm.InstanceId);
                        var psResult = ComputeAutoMapperProfile.Mapper.Map<PSVmssVMDiskEncryptionStatusContextList>(diskStatus);
                        psResultList.Add(psResult);
                    }
                    WriteObject(psResultList);
                }
                else
                {
                    var psResult = GetDiskStatus(this.ResourceGroupName, this.VMScaleSetName, this.InstanceId);
                    WriteObject(psResult);
                }
            });
        }

        private PSVmssVMDiskEncryptionStatusContext GetDiskStatus(string rgName, string vmssName, string instanceID)
        {
            PSVmssVMDiskEncryptionStatusContext psResult = new PSVmssVMDiskEncryptionStatusContext
            {
                InstanceId = instanceID
            };

            var vmssVMInstanceView = this.VirtualMachineScaleSetVMsClient.GetInstanceView(rgName, vmssName, instanceID);
            var vmssVM = this.VirtualMachineScaleSetVMsClient.Get(rgName, vmssName, instanceID);

            SetOSType(vmssVM);

            if (string.IsNullOrWhiteSpace(this.ExtensionName))
            {
                this.ExtensionName = (this.CurrentOSType == OperatingSystemTypes.Windows)
                                     ? AzureVmssDiskEncryptionExtensionContext.ExtensionDefaultName
                                     : AzureVmssDiskEncryptionExtensionContext.LinuxExtensionDefaultName;
            }

            psResult.Disks = new List<DiskInstanceView>();
            foreach (var disk in vmssVMInstanceView.Disks)
            {
                psResult.Disks.Add(disk);
            }

            psResult.Extension = null;
            psResult.DiskEncryptionStatus = string.Format("The Extension, {0}, is not installed.", this.ExtensionName);

            // replace defaults with extension and status data for the instance if found
            if (vmssVMInstanceView != null && vmssVMInstanceView.Extensions != null)
            {
                psResult.Extension = vmssVMInstanceView.Extensions.DefaultIfEmpty(null).FirstOrDefault(e => e.Name.Equals(this.ExtensionName));
                if (psResult.Extension != null
                    && psResult.Extension.Statuses != null
                    && psResult.Extension.Statuses.Count > 0)
                {
                    psResult.DiskEncryptionStatus = psResult.Extension.Statuses[0].DisplayStatus;
                }
            }

            psResult.OsVolumeEncrypted = GetOsDiskEncryptionStatus(psResult.Disks, vmssVM.StorageProfile);
            psResult.DataVolumesEncrypted = GetDataDiskEncryptionStatus(psResult.Disks, vmssVM.StorageProfile);

            return psResult;
        }

        private EncryptionStatus GetOsDiskEncryptionStatus(List<DiskInstanceView> disks, StorageProfile storage)
        {
            if (storage == null || storage.OsDisk == null)
            {
                return EncryptionStatus.NotMounted;
            }

            InstanceViewStatus status = null;
            try
            {
                var disk = disks.First(e => e.Name.Equals(storage.OsDisk.Name));

                if (disk == null)
                {
                    return EncryptionStatus.Unknown;
                }
                status = disk.Statuses.First(s => s.Code.Contains(AzureVmssDiskEncryptionExtensionContext.EncryptionStateString));
            }
            catch (InvalidOperationException)
            {
                return EncryptionStatus.NotEncrypted;
            }

            return (status == null)
                ? EncryptionStatus.NotEncrypted
                : ConvertToEncryptionStatus(status.Code.Replace(AzureVmssDiskEncryptionExtensionContext.EncryptionStateString, ""));
        }

        private EncryptionStatus GetDataDiskEncryptionStatus(List<DiskInstanceView> disks, StorageProfile storage)
        {
            if (storage == null || storage.DataDisks == null || storage.DataDisks.Count == 0)
            {
                return EncryptionStatus.NotMounted;
            }

            try
            {
                InstanceViewStatus status = null;
                try
                {
                    var disk = disks.First(e => e.Name.Equals(storage.DataDisks[0].Name));

                    if (disk == null)
                    {
                        return EncryptionStatus.Unknown;
                    }
                    status = disk.Statuses.First(s => s.Code.Contains(AzureVmssDiskEncryptionExtensionContext.EncryptionStateString));
                }
                catch (InvalidOperationException)
                {
                    return EncryptionStatus.NotEncrypted;
                }

                return (status == null)
                    ? EncryptionStatus.NotEncrypted
                    : ConvertToEncryptionStatus(status.Code.Replace(AzureVmssDiskEncryptionExtensionContext.EncryptionStateString, ""));
            }
            catch (InvalidOperationException)
            {
                return EncryptionStatus.Unknown;
            }
        }

        private EncryptionStatus ConvertToEncryptionStatus(string encryptionStatusString)
        {
            string status_string = encryptionStatusString.ToLowerInvariant();
            switch (status_string)
            {
                case "notencrypted":
                    return EncryptionStatus.NotEncrypted;
                case "encrypted":
                    return EncryptionStatus.Encrypted;
                case "notmounted":
                    return EncryptionStatus.NotMounted;
                case "decryptioninprogress":
                    return EncryptionStatus.DecryptionInProgress;
                case "encryptioninprogress":
                    return EncryptionStatus.EncryptionInProgress;
                case "vmrestartpending":
                    return EncryptionStatus.VMRestartPending;
                default:
                    return EncryptionStatus.Unknown;
            }
        }
    }
}


text:
/*
 * 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.
 */
/*
 * This code was generated by https://github.com/googleapis/google-api-java-client-services/
 * Modify at your own risk.
 */

package com.google.api.services.contentwarehouse.v1.model;

/**
 * Set only when hyper_reliable is true. These are gcids and scores for hyper-reliable categories in
 * ariane/182060. These are overridden for a few hyper-reliable categories, and may not be present
 * everywhere.
 *
 *
 This is the Java data model class that specifies how to parse/serialize into the JSON that is
 * transmitted over HTTP when working with the contentwarehouse API. For a detailed explanation see:
 * https://developers.google.com/api-client-library/java/google-http-java-client/json
 *

 *
 * @author Google, Inc.
 */
@SuppressWarnings("javadoc")
public final class NlpSemanticParsingLocalHyperReliableDataGCIDSynsOverride extends com.google.api.client.json.GenericJson {

  /**
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key
  private java.lang.Float gcidScore;

  /**
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key
  private java.lang.String hyperReliableGcid;

  /**
   * @return value or {@code null} for none
   */
  public java.lang.Float getGcidScore() {
    return gcidScore;
  }

  /**
   * @param gcidScore gcidScore or {@code null} for none
   */
  public NlpSemanticParsingLocalHyperReliableDataGCIDSynsOverride setGcidScore(java.lang.Float gcidScore) {
    this.gcidScore = gcidScore;
    return this;
  }

  /**
   * @return value or {@code null} for none
   */
  public java.lang.String getHyperReliableGcid() {
    return hyperReliableGcid;
  }

  /**
   * @param hyperReliableGcid hyperReliableGcid or {@code null} for none
   */
  public NlpSemanticParsingLocalHyperReliableDataGCIDSynsOverride setHyperReliableGcid(java.lang.String hyperReliableGcid) {
    this.hyperReliableGcid = hyperReliableGcid;
    return this;
  }

  @Override
  public NlpSemanticParsingLocalHyperReliableDataGCIDSynsOverride set(String fieldName, Object value) {
    return (NlpSemanticParsingLocalHyperReliableDataGCIDSynsOverride) super.set(fieldName, value);
  }

  @Override
  public NlpSemanticParsingLocalHyperReliableDataGCIDSynsOverride clone() {
    return (NlpSemanticParsingLocalHyperReliableDataGCIDSynsOverride) super.clone();
  }

}


text: INSERT INTO nought VALUES(2, 1, 2)


text:
@class WSCDDataProtectionProvider;
@protocol WSCDIDataProtectionProvider, WSCDIDataProtectionProviderFactory;

#include "WindowsFoundation.h"
#include "WindowsStorageStreams.h"

#import <Foundation/Foundation.h>

// Windows.Security.Cryptography.DataProtection.DataProtectionProvider
#ifndef __WSCDDataProtectionProvider_DEFINED__
#define __WSCDDataProtectionProvider_DEFINED__

OBJCUWPWINDOWSSECURITYCRYPTOGRAPHYDATAPROTECTIONEXPORT
@interface WSCDDataProtectionProvider : RTObject
+ (instancetype)make __attribute__ ((ns_returns_retained));
+ (WSCDDataProtectionProvider*)makeOverloadExplicit:(NSString *)protectionDescriptor ACTIVATOR;
#if defined(__cplusplus)
+ (instancetype)createWith:(IInspectable*)obj __attribute__ ((ns_returns_autoreleased));
#endif
- (void)protectAsync:(RTObject<WSSIBuffer>*)data success:(void (^)(RTObject<WSSIBuffer>*))success failure:(void (^)(NSError*))failure;
- (void)unprotectAsync:(RTObject<WSSIBuffer>*)data success:(void (^)(RTObject<WSSIBuffer>*))success failure:(void (^)(NSError*))failure;
- (RTObject<WFIAsyncAction>*)protectStreamAsync:(RTObject<WSSIInputStream>*)src dest:(RTObject<WSSIOutputStream>*)dest;
- (RTObject<WFIAsyncAction>*)unprotectStreamAsync:(RTObject<WSSIInputStream>*)src dest:(RTObject<WSSIOutputStream>*)dest;
@end

#endif // __WSCDDataProtectionProvider_DEFINED__


text:
/**
 * This file is part of the CernVM File System.
 */

#ifndef CVMFS_CATALOG_TRAVERSAL_H_
#define CVMFS_CATALOG_TRAVERSAL_H_

#include <cassert>
#include <stack>
#include <string>
#include <limits>

#include "catalog.h"
#include "util.h"
#include "util_concurrency.h"
#include "logging.h"
#include "compression.h"

#include "manifest.h"
#include "signature.h"
#include "history_sqlite.h"

#include "object_fetcher.h"

namespace catalog {
  class Catalog;
  class WritableCatalog;
}

namespace swissknife {

/**
 * Callback data which has to be implemented by the registered callback
 * functions/methods (see Observable<> for further details)
 * @param catalog             the catalog object which needs to be processed
 * @param catalog_hash        the content hash of the catalog
 * @param tree_level          the depth in the nested catalog tree
 *                            (starting at zero)
 * @param file_size           the size of the downloaded catalog database file
 * @param history_depth       the distance from the current HEAD revision
 *                            (current HEAD has history_depth 0)
 */
template <class CatalogT>
struct CatalogTraversalData {
  CatalogTraversalData(const CatalogT     *catalog,
                       const shash::Any   &catalog_hash,
                       const unsigned      tree_level,
                       const size_t        file_size,
                       const unsigned int  history_depth)
  : catalog(catalog)
  , catalog_hash(catalog_hash)
  , tree_level(tree_level)
  , file_size(file_size)
  , history_depth(history_depth) {}

  const CatalogT     *catalog;
  const shash::Any    catalog_hash;
  const unsigned int  tree_level;
  const size_t        file_size;
  const unsigned int  history_depth;
};

/**
 * This class traverses the catalog hierarchy of a CVMFS repository recursively.
 * Also historic catalog trees can be traversed. The user needs to specify a
 * callback which is called for each catalog on the way.
 *
 * CatalogTraversal<> can be configured and used in various ways:
 *   -> Historic catalog traversal
 *   -> Prune catalogs below a certain history level
 *   -> Prune catalogs older than a certain threshold timestamp
 *   -> Never traverse a certain catalog twice
 *   -> Breadth First Traversal or Depth First Traversal
 *   -> Optional catalog memory management (no_close)
 *   -> Use all Named Snapshots of a repository as traversal entry point
 *   -> Traverse starting from a provided catalog
 *   -> Traverse catalogs that were previously skipped
 *   -> Produce various flavours of catalogs (writable, mocked, ...)
 *
 * Breadth First Traversal Strategy
 *   Catalogs are handed out to the user identical as they are traversed.
 *   Say: From top to buttom. When you would simply print each received catalog
 *        the result would be a nice representation of the catalog tree.
 *   This method is more efficient, because catalogs are opened, processed and
 *   thrown away directly afterwards.
 *
 * Depth First Traversal Strategy
 *   The user gets the catalog tree starting from the leaf nodes.
 *   Say: From bottom to top. A user can assume that he got all children or
 *        historical ancestors of a catalog before.
 *   This method climbs down the full catalog tree and hands it out 'in reverse
 *   order'. Thus, catalogs on the way are opened, checked for their descendants
 *   and closed. Once all children and historical ancestors are processed, it is
 *   re-opened and handed out to the user.
 *   Note: This method needs more disk space to temporarily store downloaded but
 *         not yet processed catalogs.
 *
 * Note: Since all CVMFS catalog files together can grow to several gigabytes in
 *       file size, each catalog is loaded, processed and removed immediately
 *       afterwards. Except if no_close is specified, which allows the user to
 *       choose when a catalog should be closed. Keep in mind, that a user is
 *       responsible for both deletion of the delivered catalog objects as well
 *       as unlinking of the catalog database file.
 *
 *
 * @param ObjectFetcherT  Strategy Pattern implementation that defines how to
 *                        retrieve catalogs from various backend storage types.
 *                        Furthermore the ObjectFetcherT::CatalogTN is the type
 *                        of catalog to be instantiated by CatalogTraversal<>.
 *
 * CAUTION: the CatalogTN* pointer passed into the callback becomes invalid
 *          directly after the callback method returns, unless you create the
 *          CatalogTraversal object with no_close = true.
 */
template<class ObjectFetcherT>
class CatalogTraversal
  : public Observable<CatalogTraversalData<typename ObjectFetcherT::CatalogTN> >
{
 public:
  typedef ObjectFetcherT                      ObjectFetcherTN;
  typedef typename ObjectFetcherT::CatalogTN  CatalogTN;
  typedef CatalogTraversalData<CatalogTN>     CallbackDataTN;

  /**
   * @param repo_url             the path to the repository to be traversed:
   *                             -> either absolute path to the local catalogs
   *                             -> or an URL to a remote repository
   * @param repo_name            fully qualified repository name (used for remote
   *                             repository signature check) (optional)
   * @param repo_keys            a comma separated list of public key file
   *                             locations to verify the repository manifest file
   * @param history              depth of the desired catalog history traversal
   *                             (default: 0 - only HEAD catalogs are traversed)
   * @param timestamp            timestamp of history traversal threshold
   *                             (default: 0 - no threshold, traverse everything)
   * @param no_repeat_history    keep track of visited catalogs and don't re-visit
   *                             them in previous revisions
   * @param no_close             do not close catalogs after they were attached
   *                             (catalogs retain their parent/child pointers)
   * @param ignore_load_failure  suppressed an error message if a catalog file
   *                             could not be loaded (i.e. was sweeped before by
   *                             a garbage collection run)
   * @param quiet                silence messages that would go to stderr
   * @param tmp_dir              path to the temporary directory to be used
   *                             (default: /tmp)
   */
  struct Parameters {
    Parameters()
      : object_fetcher(NULL)
      , history(kNoHistory)
      , timestamp(kNoTimestampThreshold)
      , no_repeat_history(false)
      , no_close(false)
      , ignore_load_failure(false)
      , quiet(false) {}

    static const unsigned int kFullHistory;
    static const unsigned int kNoHistory;
    static const time_t       kNoTimestampThreshold;

    ObjectFetcherT *object_fetcher;

    unsigned int    history;
    time_t          timestamp;
    bool            no_repeat_history;
    bool            no_close;
    bool            ignore_load_failure;
    bool            quiet;
  };

 public:
  enum TraversalType {
    kBreadthFirstTraversal,
    kDepthFirstTraversal
  };

 protected:
  typedef std::set<shash::Any> HashSet;

 protected:
  /**
   * This struct keeps information about a catalog that still needs to be
   * traversed by a currently running catalog traversal process.
   */
  struct CatalogJob {
    CatalogJob(const std::string  &path,
               const shash::Any   &hash,
               const unsigned      tree_level,
               const unsigned      history_depth,
                     CatalogTN    *parent = NULL) :
      path(path),
      hash(hash),
      tree_level(tree_level),
      history_depth(history_depth),
      parent(parent),
      catalog_file_size(0),
      ignore(false),
      catalog(NULL),
      referenced_catalogs(0),
      postponed(false) {}

    bool IsRootCatalog() const { return tree_level == 0; }

    CallbackDataTN GetCallbackData() const {
      return CallbackDataTN(catalog, hash, tree_level,
                            catalog_file_size, history_depth);
    }

    // initial state description
    const std::string   path;
    const shash::Any    hash;
    const unsigned      tree_level;
    const unsigned      history_depth;
          CatalogTN    *parent;

    // dynamic processing state (used internally)
    std::string   catalog_file_path;
    size_t        catalog_file_size;
    bool          ignore;
    CatalogTN    *catalog;
    unsigned int  referenced_catalogs;
    bool          postponed;
  };

  typedef std::stack<CatalogJob> CatalogJobStack;

  /**
   * This struct represents a catalog traversal context. It needs to be re-
   * created for each catalog traversal process and contains information to this
   * specific catalog traversal run.
   *
   * @param history_depth   the history traversal threshold
   * @param traversal_type  either breadth or depth first traversal strategy
   * @param catalog_stack   the call stack for catalogs to be traversed
   * @param callback_stack  used in depth first traversal for deferred yielding
   */
  struct TraversalContext {
    TraversalContext(const unsigned       history_depth,
                     const time_t         timestamp_threshold,
                     const TraversalType  traversal_type) :
      history_depth(history_depth),
      timestamp_threshold(timestamp_threshold),
      traversal_type(traversal_type) {}

    const unsigned       history_depth;
    const time_t         timestamp_threshold;
    const TraversalType  traversal_type;
    CatalogJobStack      catalog_stack;
    CatalogJobStack      callback_stack;
  };

 public:
  /**
   * Constructs a new catalog traversal engine based on the construction
   * parameters described in struct ConstructionParams.
   */
	CatalogTraversal(const Parameters &params) :
    object_fetcher_(params.object_fetcher),
    no_close_(params.no_close),
    ignore_load_failure_(params.ignore_load_failure),
    no_repeat_history_(params.no_repeat_history),
    default_history_depth_(params.history),
    default_timestamp_threshold_(params.timestamp),
    error_sink_((params.quiet) ? kLogDebug : kLogStderr)
  {
    assert (object_fetcher_ != NULL);
  }

  /**
   * Starts the traversal process.
   * After calling this methods CatalogTraversal will go through all catalogs
   * and call the registered callback methods for each found catalog.
   * If something goes wrong in the process, the traversal will be cancelled.
   *
   * @param type   breadths or depth first traversal
   * @return       true, when all catalogs were successfully processed. On
   *               failure the traversal is cancelled and false is returned.
   */
  bool Traverse(const TraversalType type = kBreadthFirstTraversal) {
    TraversalContext ctx(default_history_depth_,
                         default_timestamp_threshold_,
                         type);
    const shash::Any root_catalog_hash = GetRepositoryRootCatalogHash();
    if (root_catalog_hash.IsNull()) {
      return false;
    }
    Push(ctx, root_catalog_hash);
    return DoTraverse(ctx);
  }

  /**
   * Starts the traversal process at the catalog pointed to by the given hash
   *
   * @param root_catalog_hash  the entry point into the catalog traversal
   * @param type               breadths or depth first traversal
   * @return                   true when catalogs were successfully traversed
   */
  bool Traverse(const shash::Any     &root_catalog_hash,
                const TraversalType   type = kBreadthFirstTraversal) {
    // add the root catalog of the repository as the first element on the job
    // stack
    TraversalContext ctx(default_history_depth_,
                         default_timestamp_threshold_,
                         type);
    Push(ctx, root_catalog_hash);
    return DoTraverse(ctx);
  }

  /**
   * Figures out all named tags in a repository and uses all of them as entry
   * points into the traversal process.
   *
   * @param type  breadths or depth first traversal
   * @return      true when catalog traversal successfully finished
   */
  bool TraverseNamedSnapshots(const TraversalType type = kBreadthFirstTraversal) {
    typedef std::vector<shash::Any> HashList;

    TraversalContext ctx(Parameters::kNoHistory,
                         Parameters::kNoTimestampThreshold,
                         type);
    const UniquePtr<history::History> tag_db(object_fetcher_->FetchHistory());
    if (! tag_db.IsValid()) {
      LogCvmfs(kLogCatalogTraversal, kLogDebug, "didn't find a history database "
                                                "to traverse");
      return true;
    }

    HashList root_hashes;
    bool success = tag_db->GetHashes(&root_hashes);
    assert (success);

    // traversing referenced named root hashes in reverse chronological order
    // to make sure that overlapping history traversals don't leave out catalog
    // revisions accidentially
          HashList::const_reverse_iterator i    = root_hashes.rbegin();
    const HashList::const_reverse_iterator iend = root_hashes.rend();
    for (; i != iend; ++i) {
      Push(ctx, *i);
    }

    return DoTraverse(ctx);
  }

  /**
   * This traverses all catalogs that were left out by previous traversal runs.
   *
   * Note: This method asserts that previous traversal runs left out certain
   *       catalogs due to history_depth or timestamp restrictions.
   *       CatalogTraversal keeps track of the root catalog hashes of catalog
   *       revisions that have been pruned before. TraversePruned() will use
   *       those as entry points.
   *
   * Note: TraversaPruned() will neither take the history nor the timestamp
   *       based thresholds into account but traverse all catalogs in can reach
   *       from the catalogs previously been pruned by those thresholds.
   *
   * @param type  breadths or depth first traversal
   * @return      true on successful traversal of all necessary catalogs or
   *              false in case of failure or no_repeat_history == false
   */
  bool TraversePruned(const TraversalType type = kBreadthFirstTraversal) {
    TraversalContext ctx(Parameters::kFullHistory,
                         Parameters::kNoTimestampThreshold,
                         type);
    if (pruned_revisions_.empty()) {
      return false;
    }

          HashSet::const_iterator i    = pruned_revisions_.begin();
    const HashSet::const_iterator iend = pruned_revisions_.end();
    for (; i != iend; ++i) {
      Push(ctx, *i);
    }
    pruned_revisions_.clear();
    return DoTraverse(ctx);
  }

  size_t pruned_revision_count() const { return pruned_revisions_.size(); }

 protected:
  /**
   * This controls the actual traversal. Using a stack to traverse down the
   * catalog hierarchy. This method implements the traversal itself, but not
   * in which way catalogs are handed out to the user code.
   *
   * Each catalog is processed in these steps:
   *  1.) Pop the next catalog from the stack
   *        Catalogs are always traversed from latest to oldest revision and
   *        from root to leaf nested catalogs
   *  2.) Prepare the catalog for traversing
   *    2.1.) Check if it was visited before
   *    2.2.) Fetch the catalog database from the backend storage
   *            This might fail and produce an error. For root catalogs this
   *            error can be ignored (might be garbage collected before)
   *    2.3.) Open the catalog database
   *    2.4.) Check if the catalog is older than the timestamp threshold
   *        After these steps the catalog is opened either opened and ready for
   *        the traversal to continue, or it was marked for ignore (job.ignore)
   *  3.) Check if the catalog is marked to be ignored
   *        Catalog might not be loadable (sweeped root catalog) or is too old
   *        Note: ignored catalogs can still trigger postponed yields
   *  4.) Mark the catalog as visited to be able to skip it later on
   *  5.) Find and push referencing catalogs
   *        This pushes all descendents of the current catalog onto the stack.
   *        Note that this is dependent on the strategy (depth or breadth first)
   *        and on the history threshold (see history_depth).
   *  6.) Hand the catalog out to the user code
   *        Depending on the traversal strategy (depth of breadths first) this
   *        might immediately yield zero to N catalogs to the user code.
   *
   * Note: If anything unexpected goes wrong during the traversal process, it
   *       is aborted immediately.
   *
   * @param ctx   the traversal context that steers the whole traversal process
   * @return      true on successful traversal and false on abort
   */
  bool DoTraverse(TraversalContext &ctx) {
    assert (ctx.callback_stack.empty());

    while (! ctx.catalog_stack.empty()) {
      // Get the top most catalog for the next processing step
      CatalogJob job = Pop(ctx);

      // download and open the catalog for processing
      if (! PrepareCatalog(ctx, job)) {
        return false;
      }

      // ignored catalogs don't need to be processed anymore but they might
      // release postponed yields
      if (job.ignore) {
        if (! HandlePostponedYields(ctx, job)) {
          return false;
        }
        continue;
      }

      // push catalogs referenced by the current catalog (onto stack)
      MarkAsVisited(job);
      PushReferencedCatalogs(ctx, job);

      // notify listeners
      if (! YieldToListeners(ctx, job)) {
        return false;
      }
    }

    // invariant: after the traversal finshed, there should be no more catalogs
    //            to traverse or to yield!
    assert (ctx.catalog_stack.empty());
    assert (ctx.callback_stack.empty());
    return true;
  }

  bool PrepareCatalog(TraversalContext &ctx, CatalogJob &job) {
    // skipping duplicate catalogs might also yield postponed catalogs
    if (ShouldBeSkipped(job)) {
      job.ignore = true;
      return true;
    }

    job.catalog = object_fetcher_->FetchCatalog(job.hash,
                                                job.path,
                                                ! job.IsRootCatalog(),
                                                job.parent);
    if (! job.catalog) {
      if (ignore_load_failure_) {
        LogCvmfs(kLogCatalogTraversal, kLogDebug, "ignoring missing catalog %s "
                                                  "(possibly swept before)",
                 job.hash.ToString().c_str());
        job.ignore = true;
        return true;
      } else {
        LogCvmfs(kLogCatalogTraversal, error_sink_, "failed to load catalog %s",
                 job.hash.ToString().c_str());
        return false;
      }
    }

    // catalogs returned by ObjectFetcher<> are managing their database files by
    // default... we need to manage this file manually here
    job.catalog->DropDatabaseFileOwnership();

    job.catalog_file_path = job.catalog->database_path();
    job.catalog_file_size = GetFileSize(job.catalog->database_path());

    return true;
  }

  bool ReopenCatalog(CatalogJob &job) {
    assert (! job.ignore);
    assert (job.catalog == NULL);

    job.catalog = CatalogTN::AttachFreely(job.path,
                                          job.catalog_file_path,
                                          job.hash,
                                          job.parent,
                                          ! job.IsRootCatalog());

    if (job.catalog == NULL) {
      LogCvmfs(kLogCatalogTraversal, error_sink_, "failed to re-open catalog %s",
               job.hash.ToString().c_str());
      return false;
    }

    return true;
  }

  bool CloseCatalog(CatalogJob &job, const bool unlink_db = true) {
    delete job.catalog; job.catalog = NULL;
    if (! job.catalog_file_path.empty() && unlink_db) {
      const int retval = unlink(job.catalog_file_path.c_str());
      if (retval != 0) {
        LogCvmfs(kLogCatalogTraversal, error_sink_, "Failed to unlink %s - %d",
                 job.catalog_file_path.c_str(), errno);
        return false;
      }
    }

    return true;
  }

  /**
   * Checks if a root catalog is below one of the pruning thresholds.
   * Pruning thesholds can be either the catalog's history depth or a timestamp
   * threshold applied to the last modified timestamp of the catalog.
   *
   * @param ctx  traversal context for traversal-specific state
   * @param job  the job defining the current catalog
   * @return     true if either history or timestamp threshold are satisfied
   */
  bool IsBelowPruningThresholds(TraversalContext &ctx, const CatalogJob &job) {
    assert (job.IsRootCatalog());
    assert (job.catalog != NULL);

    const bool h = job.history_depth >= ctx.history_depth;
    assert(ctx.timestamp_threshold >= 0);
    const bool t =
      job.catalog->GetLastModified() < unsigned(ctx.timestamp_threshold);

    return t || h;
  }

  void PushReferencedCatalogs(TraversalContext &ctx, CatalogJob &job) {
    assert (! job.ignore);
    assert (job.catalog != NULL);
    assert (ctx.traversal_type == kBreadthFirstTraversal ||
            ctx.traversal_type == kDepthFirstTraversal);

    // this differs, depending on the traversal strategy.
    //
    // Breadths First Traversal
    //   Catalogs are traversed from top (root catalog) to bottom (leaf catalogs)
    //   and from more recent (HEAD revision) to older (historic revisions)
    //
    // Depth First Traversal
    //   Catalogs are traversed from oldest revision (depends on the configured
    //   maximal history depth) to the HEAD revision and from bottom (leafs) to
    //   top (root catalogs)
    job.referenced_catalogs = (ctx.traversal_type == kBreadthFirstTraversal)
      ?   PushPreviousRevision(ctx, job)
        + PushNestedCatalogs  (ctx, job)

      :   PushNestedCatalogs  (ctx, job)
        + PushPreviousRevision(ctx, job);
  }

  /**
   * Pushes the previous revision of a (root) catalog.
   * @return  the number of catalogs pushed on the processing stack
   */
  unsigned int PushPreviousRevision(      TraversalContext  &ctx,
                                    const CatalogJob        &job)
  {
    // only root catalogs are used for entering a previous revision (graph)
    if (! job.catalog->IsRoot()) {
      return 0;
    }

    const shash::Any previous_revision = job.catalog->GetPreviousRevision();
    if (previous_revision.IsNull()) {
      return 0;
    }

    // check if the next deeper history level is actually requested
    // Note: otherwise it is marked to be 'pruned' for possible later traversal
    //       (see: TraversePruned())
    // Note: if the current catalog is below the timestamp threshold it will be
    //       traversed and only its ancestor revision will not be pushed anymore
    if (IsBelowPruningThresholds(ctx, job)) {
      MarkAsPrunedRevision(previous_revision);
      return 0;
    }

    Push(ctx, CatalogJob("",
                         previous_revision,
                         0,
                         job.history_depth + 1,
                         NULL));
    return 1;
  }

  /**
   * Pushes all the referenced nested catalogs.
   * @return  the number of catalogs pushed on the processing stack
   */
  unsigned int PushNestedCatalogs(      TraversalContext  &ctx,
                                  const CatalogJob        &job)
  {
    typedef typename CatalogTN::NestedCatalogList NestedCatalogList;
    const NestedCatalogList &nested = job.catalog->ListNestedCatalogs();
    typename NestedCatalogList::const_iterator i    = nested.begin();
    typename NestedCatalogList::const_iterator iend = nested.end();
    for (; i != iend; ++i) {
      CatalogTN* parent = (no_close_) ? job.catalog : NULL;
      const CatalogJob new_job(i->path.ToString(),
                               i->hash,
                               job.tree_level + 1,
                               job.history_depth,
                               parent);
      Push(ctx, new_job);
    }

    return nested.size();
  }

  void Push(TraversalContext &ctx, const shash::Any &root_catalog_hash) {
    Push(ctx, CatalogJob("", root_catalog_hash, 0, 0));
  }

  bool YieldToListeners(TraversalContext &ctx, CatalogJob &job) {
    assert (! job.ignore);
    assert (job.catalog != NULL);
    assert (ctx.traversal_type == kBreadthFirstTraversal ||
            ctx.traversal_type == kDepthFirstTraversal);

    // in breadth first search mode, every catalog is simply handed out once
    // it is visited. No extra magic required...
    if (ctx.traversal_type == kBreadthFirstTraversal) {
      return Yield(job);
    }

    // in depth first search mode, catalogs might need to wait until all of
    // their referenced catalogs are yielded (ctx.callback_stack)...
    assert (ctx.traversal_type == kDepthFirstTraversal);
    if (job.referenced_catalogs > 0) {
      PostponeYield(ctx, job);
      return true;
    }

    // this catalog can be yielded
    return Yield(job) && HandlePostponedYields(ctx, job);
  }

 private:
  /**
   * This actually hands out a catalog to the user code
   * It is not called by DoTraversa() directly but by wrapper functions in order
   * to provide higher level yielding behaviour.
   */
  bool Yield(CatalogJob &job) {
    assert (! job.ignore);
    assert (job.catalog != NULL || job.postponed);

    // catalog was pushed on ctx.callback_stack before, it might need to be re-
    // opened. If CatalogTraversal<> is configured with no_close, it was not
    // closed before, hence does not need a re-open.
    if (job.postponed && ! no_close_ && ! ReopenCatalog(job)) {
      return false;
    }

    // hand the catalog out to the user code (see Observable<>)
    assert (job.catalog != NULL);
    this->NotifyListeners(job.GetCallbackData());

    // skip the catalog closing procedure if asked for
    // Note: In this case it is the user's responsibility to both delete the
    //       yielded catalog object and the underlying database temp file
    if (no_close_) {
      return true;
    }

    // we can close the catalog here and delete the temporary file
    return CloseCatalog(job);
  }

  /**
   * Pushes a catalog to the callback_stack for later yielding
   * Note: this is only used for the Depth First Traversal strategy!
   */
  void PostponeYield(TraversalContext &ctx, CatalogJob &job) {
    assert (job.referenced_catalogs > 0);

    job.postponed = true;
    if (! no_close_) {
      const bool unlink_db = false; // will reopened just before yielding
      CloseCatalog(job, unlink_db);
    }
    ctx.callback_stack.push(job);
  }

  /**
   * Determines if there are postponed yields that can be set free based on
   * the catalog currently being yielded
   *
   * Note: the CatalogJob being handed into this method does not necessarily
   *       have an open Catalog attached to it.
   *
   * @param ctx   the TraversalContext
   * @param job   the catalog job that was just yielded
   * @return      true on successful execution
   */
  bool HandlePostponedYields(TraversalContext &ctx, CatalogJob &job) {
    if (ctx.traversal_type == kBreadthFirstTraversal) {
      return true;
    }

    assert (ctx.traversal_type == kDepthFirstTraversal);
    assert (job.referenced_catalogs == 0);

    // walk through the callback_stack and yield all catalogs that have no un-
    // yielded referenced_catalogs anymore. Every time a CatalogJob in the
    // callback_stack gets yielded it decrements the referenced_catalogs of the
    // next top of the stack (it's parent CatalogJob waiting for yielding)
    CatalogJobStack &clbs = ctx.callback_stack;
    while (! clbs.empty()) {
      CatalogJob &postponed_job = clbs.top();
      if (--postponed_job.referenced_catalogs > 0) {
        break;
      }

      if (! Yield(postponed_job)) {
        return false;
      }
      clbs.pop();
    }

    return true;
  }

  void Push(TraversalContext &ctx, const CatalogJob &job) {
    ctx.catalog_stack.push(job);
  }

  CatalogJob Pop(TraversalContext &ctx) {
    CatalogJob job = ctx.catalog_stack.top(); ctx.catalog_stack.pop();
    return job;
  }

  void MarkAsPrunedRevision(const shash::Any &root_catalog_hash) {
    pruned_revisions_.insert(root_catalog_hash);
  }

  void MarkAsVisited(const CatalogJob &job) {
    if (no_repeat_history_) {
      visited_catalogs_.insert(job.hash);
    }
  }

  /**
   * Checks the traversal history if the given catalog was traversed or at least
   * seen before. If 'no_repeat_history' is not set this is always 'false'.
   *
   * @param job   the job to be checked against the traversal history
   * @return      true if the specified catalog was hit before
   */
  bool ShouldBeSkipped(const CatalogJob &job) {
    return no_repeat_history_ && (visited_catalogs_.count(job.hash) > 0);
  }

  shash::Any GetRepositoryRootCatalogHash() {
    // get the manifest of the repository to learn about the entry point or the
    // root catalog of the repository to be traversed
    UniquePtr<manifest::Manifest> manifest(object_fetcher_->FetchManifest());
    if (! manifest) {
      return shash::Any();
    }

    return manifest->catalog_hash();
  }

 private:
  ObjectFetcherT         *object_fetcher_;
  const bool              no_close_;
  const bool              ignore_load_failure_;
  const bool              no_repeat_history_;
  const unsigned int      default_history_depth_;
  const time_t            default_timestamp_threshold_;
  HashSet                 visited_catalogs_;
  HashSet                 pruned_revisions_;
  LogFacilities           error_sink_;
};

template <class ObjectFetcherT>
const unsigned int
  CatalogTraversal<ObjectFetcherT>::Parameters::kFullHistory =
    std::numeric_limits<unsigned int>::max();

template <class ObjectFetcherT>
const unsigned int
  CatalogTraversal<ObjectFetcherT>::Parameters::kNoHistory = 0;

template <class ObjectFetcherT>
const time_t
  CatalogTraversal<ObjectFetcherT>::Parameters::kNoTimestampThreshold = 0;

}

#endif /* CVMFS_CATALOG_TRAVERSAL_H_*/


text:
class nebulaEye : public ofBaseApp
{
  public:
    void setup  ();
    void update ();
    void draw   ();
    void exit   ();
    void mouseMoved(ofMouseEventArgs& mouse);
    void mouseDragged(ofMouseEventArgs& mouse);
    void mousePressed(ofMouseEventArgs& mouse);
    void mouseReleased(ofMouseEventArgs& mouse);
    void mouseScrolled(ofMouseEventArgs& mouse);
    void mouseEntered(ofMouseEventArgs& mouse);
    void mouseExited(ofMouseEventArgs& mouse);
    void keyPressed(int key);

    void learningTimeChanged(int & _time);
    void thresholdChanged(int & tresh);

    void sendOSC();
    void updateOSC();

    void recordCSVData();
    void setupCSVrecorder();
    void csvRecordCb(bool & flag);
    string getDate(), getHour();
    void clearTestImg(bool & flag);

    ofxPanel gui, recordPanel;
    ofParameterGroup displayGuiGrp;
    ofParameter<bool> showGui, showVideo, showBgSub, showContour, showFlow, showZone, record, mouseTest;
    ofParameter<int> bgSubIntensity, showDebug;
    ofxOscParameterSync parameterSync;

    nebulaVideoSrc video;
    nebulaFlow flow;
    nebulaBackground bgSub;
    nebulaContourFinder contour;
    nebula::Zone zone;

    ofPixels img;
    cv::Mat testimg;
    ofxOscSender sender;
    ofxOscReceiver receiver;
    wng::ofxCsv csvRecorder;

    vector<float> flowZone;

    nebulaPix_share pix_share;
};