text:
package com.tosinogunrinde.cql.statementbuilder.converter;

import com.google.common.base.Strings;
import com.tosinogunrinde.cql.statementbuilder.util.ObjectValidator;

import java.lang.reflect.*;
import java.util.*;

/**
 * @author Tosin Ogunrinde
 */
abstract class CollectionToCqlCollectionConverter implements Converter<Field, String> {

    @Override
    public String convert(Field field) {
        ObjectValidator.validateNotNull(field);
        StringBuilder builder = new StringBuilder(getType()).append("<");
        Type[] types = getTypesFromType(field.getGenericType());
        convert(types[0], EntryType.KEY, false, builder);
        if (types.length > 1) {
            builder.append(", ");
            convert(types[1], EntryType.VALUE, false, builder);
        }
        builder.append(">");
        return builder.toString();
    }

    private Type[] getTypesFromType(Type type) {
        return ((ParameterizedType) type).getActualTypeArguments();
    }

    private void convert(Type type, EntryType entryType, boolean frozen, StringBuilder builder) {
        if (type instanceof Class) {
            String cqlType = new TypeToCqlTypeConverter().convert(type.getTypeName());
            if (!Strings.isNullOrEmpty(cqlType)) {
                builder.append(cqlType);
            } else if (!frozen) {  // Must be a UDT.
                builder.append(freezeField(type));
            } else {
                if (entryType == EntryType.VALUE) {
                    builder.append(", ");
                }
                builder.append(((Class) type).getSimpleName().toLowerCase());
            }
        } else {
            builder.append("frozen<").append(getCollectionType(type)).append("<");
            Type[] types = getTypesFromType(type);
            for (int index = 0; index < types.length; index++) {
                convert(types[index], index == 0 ? EntryType.KEY : EntryType.VALUE, true, builder);
            }
            builder.append(">>");
        }
    }

    private String freezeField(Type type) {
        return "frozen<" + ((Class) type).getSimpleName().toLowerCase() + ">";
    }

    private String getCollectionType(Type type) {
        Type rawType = ((ParameterizedType) type).getRawType();
        if (List.class.isAssignableFrom((Class<?>) rawType)) {
            return "list";
        } else if (Set.class.isAssignableFrom((Class<?>) rawType)) {
            return "set";
        } else if (Map.class.isAssignableFrom((Class<?>) rawType)) {
            return "map";
        }
        throw new UnsupportedOperationException("type is not supported: " + type);
    }

    protected abstract String getType();

    private enum EntryType {KEY, VALUE}
}


text:
package main

import (
	"fmt"
	"io/ioutil"
	"log"
	"strings"

	"github.com/codegangsta/cli"
	"github.com/drone/drone/model"
)

var orgSecretAddCmd = cli.Command{
	Name:      "add",
	Usage:     "adds a secret",
	ArgsUsage: "[org] [key] [value]",
	Action: func(c *cli.Context) {
		if err := orgSecretAdd(c); err != nil {
			log.Fatalln(err)
		}
	},
	Flags: []cli.Flag{
		cli.StringSliceFlag{
			Name:  "event",
			Usage: "inject the secret for these event types",
			Value: &cli.StringSlice{
				model.EventPush,
				model.EventTag,
				model.EventDeploy,
			},
		},
		cli.StringSliceFlag{
			Name:  "image",
			Usage: "inject the secret for these image types",
			Value: &cli.StringSlice{},
		},
		cli.StringFlag{
			Name:  "input",
			Usage: "input secret value from a file",
		},
	},
}

func orgSecretAdd(c *cli.Context) error {
	if len(c.Args()) != 3 {
		cli.ShowSubcommandHelp(c)
		return nil
	}

	team := c.Args().First()
	name := c.Args().Get(1)
	value := c.Args().Get(2)

	secret := &model.Secret{}
	secret.Name = name
	secret.Value = value
	secret.Images = c.StringSlice("image")
	secret.Events = c.StringSlice("event")

	if len(secret.Images) == 0 {
		return fmt.Errorf("Please specify the --image parameter")
	}

	// TODO(bradrydzewski) below we use an @ sybmol to denote that the secret
	// value should be loaded from a file (inspired by curl). I'd prefer to use
	// a --input flag to explicitly specify a filepath instead.

	if strings.HasPrefix(secret.Value, "@") {
		path := secret.Value[1:]
		out, ferr := ioutil.ReadFile(path)
		if ferr != nil {
			return ferr
		}
		secret.Value = string(out)
	}

	client, err := newClient(c)
	if err != nil {
		return err
	}

	return client.TeamSecretPost(team, secret)
}

redpajama_set_name: RedPajamaGithub


text:
require '_test_env.rb'

module FolderTemplate
  describe Context do

    describe "it implements DSL to support value lazzy definition" do
      let( :filename ) { 'path/to/context_file' }
      let( :content ) { "let( :bbb ) { aaa + 1 if aaa }" }
      subject { Context.load_from_content( content, filename ) }

      it "holds definition for values declared in context DSL file" do
        subject.merge!( aaa:123 )
        subject[:bbb].must_equal( 124 )
      end
    end

    describe "it behaves like a Hash" do
      subject {
        ctx = Context.new
        ctx.let( :bbb ) { aaa + 1 }
        ctx.let( :aaa ) { 123 }
        ctx
      }

      it "supports value accessor with symbols" do
        subject[:bbb].must_equal( 124 )
      end

      it "supports value assignment with symbols" do
        subject[:aaa] = 112
        subject[:aaa].must_equal( 112 )
      end

      it "updates evaluation of dependent variables after value assignment" do
        subject[:aaa] = 112
        subject[:bbb].must_equal( 113 )
      end

      it "responds to values like a Hash" do
        Set.new(subject.values).must_equal( Set.new([123, 124]) )
      end

      it "responds to each like a Hash" do
        kv_pairs = subject.each.to_a
        kv_pairs.must_equal( [[:bbb, 124], [:aaa, 123]] )
      end
    end # it behaves like a Hash

    describe "it can be copies with all definies variables" do
      subject {
        ctx = Context.new
        ctx.let( :ccc ) { aaa + bbb }
        ctx.let( :aaa ) { 123 }
        ctx
      }

      it "creates an independant contexts for each copy" do
        ctx1 = subject.dup
        ctx2 = subject.dup
        ctx1[:bbb] = 1
        ctx2[:bbb] = 2
        ctx1[:ccc].must_equal( 124 )
        ctx2[:ccc].must_equal( 125 )
      end

      it "merge() creates a duplicated instance of the conext" do
        ctx1 = subject.merge( bbb:1 )
        ctx2 = subject.merge( bbb:2 )
        ctx1[:ccc].must_equal( 124 )
        ctx2[:ccc].must_equal( 125 )
      end
    end

    describe "it caches pre-evaluated values" do
      subject { Context.new }

      it "evaluates values only once" do
        subject.let( :aaa ) { 123 }
        subject.aaa.must_equal( 123 )
        subject.definitions.delete( :aaa )
        subject.aaa.must_equal( 123 )
      end

      it "clears cached values when variables are re-declared" do
        subject.let( :aaa ) { 123 }
        subject.aaa.must_equal( 123 )
        subject.let( :aaa ) { 124 }
        subject.aaa.must_equal( 124 )
      end

      it "re-evalutes dependant values after a change of definition" do
        subject.let( :aaa ) { 123 }
        subject.let( :bbb ) { aaa + 1 }
        subject.bbb.must_equal( 124 )
        subject.let( :aaa ) { 124 }
        subject.bbb.must_equal( 125 )
      end
    end

  end # describe Context
end


text:
/*! @file   CoreLib.h   Eclipse CoreLib declaration
 */
#ifndef CoreLib_H
#define CoreLib_H
#include "core_global.h"

#include <base/ModuleInfo.h>
#include <core/Singleton.h>

/*! @class CoreLib
 * @brief The CoreLib is the base class in the eirCore library.
 *
 * The CoreLib is...
 *
 */
class CORESHARED_EXPORT CoreLib : public ModuleInfo
{
    DECLARE_SINGLETON(CoreLib) // ctor & more
public:
};

#endif // CoreLib_H


text:
<?php

namespace Gamegos\JWT;

class Token
{
    private $jwtString = null;

    private $claims = array();

    private $headers = array(
        'typ' => 'JWT'
    );

    public function __construct(array $claims = array(), array $headers = array(), $jwtString = null)
    {
        $this->setClaims($claims);
        $this->setHeaders($headers);
        if ($jwtString) {
            $this->setJWT($jwtString);
        }
    }

    //claims

    public function getClaims()
    {
        return $this->claims;
    }

    public function setClaims($claims)
    {
        foreach ($claims as $claim => $value) {
            $this->setClaim($claim, $value);
        }
    }

    public function getClaim($claim)
    {
        return $this->hasClaim($claim) ? $this->claims[$claim] : null;
    }

    public function setClaim($claim, $value)
    {
        $this->claims[$claim] = $value;
    }

    public function hasClaim($claim)
    {
        return isset($this->claims[$claim]);
    }

    //headers

    public function getHeaders()
    {
        return $this->headers;
    }

    public function setHeaders($headers)
    {
        foreach ($headers as $header => $value) {
            $this->setHeader($header, $value);
        }
    }

    public function getHeader($header)
    {
        return $this->hasHeader($header) ? $this->headers[$header] : null;
    }

    public function setHeader($header, $value)
    {
        $this->headers[$header] = $value;
    }

    public function hasHeader($header)
    {
        return isset($this->headers[$header]);
    }

    public function setJWT($jwtString)
    {
        $this->jwtString = $jwtString;
    }

    public function getJWT()
    {
        return $this->jwtString;
    }

    public function __toString()
    {
        return (string) $this->getJWT();
    }

    public function isSigned()
    {
        return $this->jwtString !== null;
    }

    public function isExpired()
    {
        $exp = $this->getClaim('exp');

        return time() > $exp;
    }

    // "Long" getters and setters for *Registered Claim Names* defined in
    // http://tools.ietf.org/html/draft-ietf-oauth-json-web-token-25#section-4.1

    public function getIssuer()
    {
        return $this->getClaim("iss");
    }

    public function setIssuer($val)
    {
        $this->setClaim("iss", $val);
    }

    public function getSubject()
    {
        return $this->getClaim("sub");
    }

    public function setSubject($val)
    {
        $this->setClaim("sub", $val);
    }

    public function getAudience()
    {
        return $this->getClaim("aud");
    }

    public function setAudience($val)
    {
        $this->setClaim("aud", $val);
    }

    public function getExpirationTime()
    {
        return $this->getClaim("exp");
    }

    public function setExpirationTime($val)
    {
        $this->setClaim("exp", $val);
    }

    public function getNotBefore()
    {
        return $this->getClaim("nbf");
    }

    public function setNotBefore($val)
    {
        $this->setClaim("nbf", $val);
    }

    public function getIssuedAt()
    {
        return $this->getClaim("iat");
    }

    public function setIssuedAt($val)
    {
        $this->setClaim("iat", $val);
    }

    public function getJWTID()
    {
        return $this->getClaim("jti");
    }

    public function setJWTID($val)
    {
        $this->setClaim("jti", $val);
    }

}


text: node node/starttime.js


text:
#ifndef LIST_H
#define LIST_H
/*
	abstract base class for lists to be used on avr
*/

template<typename T>
class List{
protected:
	List(){};
public:
	virtual uint16_t size();
	virtual uint16_t maxSize();
	virtual bool add(uint16_t index, T item);
	virtual bool add(T item);
	virtual bool pushTop(T item);
	virtual bool pushBottom(T item);
	virtual bool set(uint16_t index, T item);
	virtual T get(uint16_t index);
	virtual T remove(uint16_t index);
	virtual T popTop();
	virtual T popBottom();
	virtual void clear();
};
#endif


text:
package org.broadleafcommerce.profile.core.service;

import org.broadleafcommerce.profile.core.dao.CountrySubdivisionDao;
import org.broadleafcommerce.profile.core.domain.CountrySubdivision;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
import javax.annotation.Resource;

/**
 * @author Elbert Bautista (elbertbautista)
 */
@Service("blCountrySubdivisionService")
public class CountrySubdivisionServiceImpl implements CountrySubdivisionService {

    @Resource(name="blCountrySubdivisionDao")
    protected CountrySubdivisionDao countrySubdivisionDao;

    @Override
    public List<CountrySubdivision> findSubdivisions() {
        return countrySubdivisionDao.findSubdivisions();
    }

    @Override
    public List<CountrySubdivision> findSubdivisions(String countryAbbreviation) {
        return countrySubdivisionDao.findSubdivisions(countryAbbreviation);
    }

    @Override
    public List<CountrySubdivision> findSubdivisionsByCountryAndCategory(String countryAbbreviation, String category) {
        return countrySubdivisionDao.findSubdivisionsByCountryAndCategory(countryAbbreviation, category);
    }

    @Override
    public CountrySubdivision findSubdivisionByAbbreviation(String abbreviation) {
        return countrySubdivisionDao.findSubdivisionByAbbreviation(abbreviation);
    }

    @Override
    @Transactional("blTransactionManager")
    public CountrySubdivision save(CountrySubdivision subdivision) {
        return countrySubdivisionDao.save(subdivision);
    }
}


text:
JSON Graph Evaluator
====================

> A library of classes to handle querying JSONGraph data asynchronously

Summary
-------

Installation
------------

~~~
% npm install jgl-e
~~~

Documentation
-------------

* [API documentation](API.md)

Dependencies
------------

These are installed when **jgl-e** is installed.

~~~
underscore: 1.x.x
rx:         2.x.x
jgl:        0.x.x
protean:    0.x.x
~~~

### Development Dependencies ###

Installed when you run `npm install` in the package directory.

~~~
mocha:             1.x.x
should:            3.x.x
del:               *
gulp:              3.x.x
gulp-util:         *
gulp-ejs:          0.x.x
gulp-concat:       *
gulp-jsdoc:        0.x.x
jsdoc-to-markdown: 0.x.x
~~~

Report an Issue
---------------

* [Bugs](http://github.com/jhamlet/jgl-e/issues)
* Contact the author: <jerry@hamletink.com>

License
-------

> Copyright (c) 2013 Jerry Hamlet <jerry@hamletink.com>
>
> Permission is hereby granted, free of charge, to any person
> obtaining a copy of this software and associated documentation
> files (the "Software"), to deal in the Software without
> restriction, including without limitation the rights to use,
> copy, modify, merge, publish, distribute, sublicense, and/or sell
> copies of the Software, and to permit persons to whom the
> Software is furnished to do so, subject to the following
> conditions:
>
> The above copyright notice and this permission notice shall be
> included in all copies or substantial portions of the Software.
>
> The Software shall be used for Good, not Evil.
>
> THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
> EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
> OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
> NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
> HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
> WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
> FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
> OTHER DEALINGS IN THE SOFTWARE.


text:
package org.pathvisio.visualization.plugins;

import com.jgoodies.forms.builder.ButtonStackBuilder;
import com.jgoodies.forms.layout.CellConstraints;
import com.jgoodies.forms.layout.FormLayout;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.net.URL;
import java.util.List;

import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.SwingConstants;

import org.pathvisio.core.util.Resources;
import org.pathvisio.data.ISample;
import org.pathvisio.desktop.gex.GexManager;

/**
 * A SampleCheckList with buttons on the right side to
 * change the order of the samples.
 * @author thomas
 *
 */
public class SortSampleCheckList extends JPanel implements ActionListener {
	static final String ACTION_TOP = "Top";
	static final String ACTION_UP = "Up";
	static final String ACTION_DOWN = "Down";
	static final String ACTION_BOTTOM = "Bottom";

	static final URL ICON_TOP = Resources.getResourceURL("top.gif");
	static final URL ICON_UP = Resources.getResourceURL("up.gif");
	static final URL ICON_DOWN = Resources.getResourceURL("down.gif");
	static final URL ICON_BOTTOM = Resources.getResourceURL("bottom.gif");

	SampleCheckList checkList;

	public SortSampleCheckList(List<? extends ISample> selected, GexManager gexManager) {
		checkList = new SampleCheckList(selected, gexManager);

		setLayout(new FormLayout(
				"fill:pref:grow, 2dlu, pref",
				"fill:pref:grow"
		));

		CellConstraints cc = new CellConstraints();
		add(new JScrollPane(checkList), cc.xy(1, 1));

		JButton top = new JButton();
		top.setActionCommand(ACTION_TOP);
		top.addActionListener(this);
		top.setIcon(new ImageIcon(ICON_TOP));
	    top.setHorizontalTextPosition(SwingConstants.CENTER);

		JButton up = new JButton();
		up.setActionCommand(ACTION_UP);
		up.addActionListener(this);
		up.setIcon(new ImageIcon(ICON_UP));
		up.setHorizontalTextPosition(SwingConstants.CENTER);

		JButton down = new JButton();
		down.setActionCommand(ACTION_DOWN);
		down.addActionListener(this);
		down.setIcon(new ImageIcon(ICON_DOWN));
		down.setHorizontalTextPosition(SwingConstants.CENTER);

		JButton bottom = new JButton();
		bottom.setActionCommand(ACTION_BOTTOM);
		bottom.addActionListener(this);
		bottom.setIcon(new ImageIcon(ICON_BOTTOM));
		bottom.setHorizontalTextPosition(SwingConstants.CENTER);

		JPanel btnPanel = new JPanel();

		ButtonStackBuilder builder = new ButtonStackBuilder(
				new FormLayout("28px"), btnPanel
		);
		builder.addGridded(top);
		builder.addUnrelatedGap();
		builder.addGridded(up);
		builder.addRelatedGap();
		builder.addGridded(down);
		builder.addRelatedGap();
		builder.addGridded(bottom);

		add(btnPanel, cc.xy(3,1, "c, c"));
	}

	public SampleCheckList getList() {
		return checkList;
	}

	public void actionPerformed(ActionEvent e) {
		ISample s = checkList.getSelectedSample();
		String action = e.getActionCommand();
		if(s != null) {
			if(ACTION_TOP.equals(action)) {
				checkList.moveToTop(s);
			} else if(ACTION_UP.equals(action)) {
				checkList.moveUp(s);
			} else if(ACTION_DOWN.equals(action)) {
				checkList.moveDown(s);
			} else if(ACTION_BOTTOM.equals(action)) {
				checkList.moveToBottom(s);
			}
		}
	}
}


text:
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
	<item>
		<rotate xmlns:android="http://schemas.android.com/apk/res/android"
				android:pivotX="50%" android:pivotY="50%" android:fromDegrees="0"
				android:toDegrees="360">
			<shape android:shape="ring" android:thickness="3dp" android:useLevel="false">

				<size android:width="24dp" android:height="24dp" />
				<gradient android:type="sweep" android:useLevel="false"
						  android:startColor="#AAFFFFFF"
						  android:endColor="#70737373"
						  android:angle="0"
						/>
			</shape>
		</rotate></item>
	<item>
		<rotate xmlns:android="http://schemas.android.com/apk/res/android"
				android:pivotX="50%" android:pivotY="50%" android:fromDegrees="360"
				android:toDegrees="0">
			<shape android:shape="ring" android:thickness="3dp" android:useLevel="false">

				<size android:width="24dp" android:height="24dp" />
				<gradient android:type="sweep" android:useLevel="false"
						  android:startColor="#AAFFFFFF"
						  android:endColor="#70737373"
						  android:angle="0"
						/>
			</shape>
		</rotate></item>
</layer-list>


text:
import sys
import warnings

from pyspark import since, _NoValue
from pyspark.sql.session import _monkey_patch_RDD, SparkSession
from pyspark.sql.dataframe import DataFrame
from pyspark.sql.readwriter import DataFrameReader
from pyspark.sql.streaming import DataStreamReader
from pyspark.sql.udf import UDFRegistration  # noqa: F401
from pyspark.sql.utils import install_exception_handler

__all__ = ["SQLContext", "HiveContext"]

class SQLContext(object):
    """The entry point for working with structured data (rows and columns) in Spark, in Spark 1.x.

    As of Spark 2.0, this is replaced by :class:`SparkSession`. However, we are keeping the class
    here for backward compatibility.

    A SQLContext can be used create :class:`DataFrame`, register :class:`DataFrame` as
    tables, execute SQL over tables, cache tables, and read parquet files.

    :param sparkContext: The :class:`SparkContext` backing this SQLContext.
    :param sparkSession: The :class:`SparkSession` around which this SQLContext wraps.
    :param jsqlContext: An optional JVM Scala SQLContext. If set, we do not instantiate a new
        SQLContext in the JVM, instead we make all calls to this object.
    """

    _instantiatedContext = None

    def __init__(self, sparkContext, sparkSession=None, jsqlContext=None):
        """Creates a new SQLContext.

        .. note:: Deprecated in 3.0.0. Use :func:`SparkSession.builder.getOrCreate()` instead.

        >>> from datetime import datetime
        >>> from pyspark.sql import Row
        >>> sqlContext = SQLContext(sc)
        >>> allTypes = sc.parallelize([Row(i=1, s="string", d=1.0, l=1,
        ...     b=True, list=[1, 2, 3], dict={"s": 0}, row=Row(a=1),
        ...     time=datetime(2014, 8, 1, 14, 1, 5))])
        >>> df = allTypes.toDF()
        >>> df.createOrReplaceTempView("allTypes")
        >>> sqlContext.sql('select i+1, d+1, not b, list[1], dict["s"], time, row.a '
        ...            'from allTypes where b and i > 0').collect()
        [Row((i + CAST(1 AS BIGINT))=2, (d + CAST(1 AS DOUBLE))=2.0, (NOT b)=False, list[1]=2, \
            dict[s]=0, time=datetime.datetime(2014, 8, 1, 14, 1, 5), a=1)]
        >>> df.rdd.map(lambda x: (x.i, x.s, x.d, x.l, x.b, x.time, x.row.a, x.list)).collect()
        [(1, 'string', 1.0, 1, True, datetime.datetime(2014, 8, 1, 14, 1, 5), 1, [1, 2, 3])]
        """
        if sparkSession is None:
            warnings.warn(
                "Deprecated in 3.0.0. Use SparkSession.builder.getOrCreate() instead.",
                DeprecationWarning)

        self._sc = sparkContext
        self._jsc = self._sc._jsc
        self._jvm = self._sc._jvm
        if sparkSession is None:
            sparkSession = SparkSession.builder.getOrCreate()
        if jsqlContext is None:
            jsqlContext = sparkSession._jwrapped
        self.sparkSession = sparkSession
        self._jsqlContext = jsqlContext
        _monkey_patch_RDD(self.sparkSession)
        install_exception_handler()
        if (SQLContext._instantiatedContext is None
                or SQLContext._instantiatedContext._sc._jsc is None):
            SQLContext._instantiatedContext = self

    @property
    def _ssql_ctx(self):
        """Accessor for the JVM Spark SQL context.

        Subclasses can override this property to provide their own
        JVM Contexts.
        """
        return self._jsqlContext

    @property
    def _conf(self):
        """Accessor for the JVM SQL-specific configurations"""
        return self.sparkSession._jsparkSession.sessionState().conf()

    @classmethod
    @since(1.6)
    def getOrCreate(cls, sc):
        """
        Get the existing SQLContext or create a new one with given SparkContext.

        :param sc: SparkContext

        .. note:: Deprecated in 3.0.0. Use :func:`SparkSession.builder.getOrCreate()` instead.
        """
        warnings.warn(
            "Deprecated in 3.0.0. Use SparkSession.builder.getOrCreate() instead.",
            DeprecationWarning)

        if (cls._instantiatedContext is None
                or SQLContext._instantiatedContext._sc._jsc is None):
            jsqlContext = sc._jvm.SparkSession.builder().sparkContext(
                sc._jsc.sc()).getOrCreate().sqlContext()
            sparkSession = SparkSession(sc, jsqlContext.sparkSession())
            cls(sc, sparkSession, jsqlContext)
        return cls._instantiatedContext

    @since(1.6)
    def newSession(self):
        """
        Returns a new SQLContext as new session, that has separate SQLConf,
        registered temporary views and UDFs, but shared SparkContext and
        table cache.
        """
        return self.__class__(self._sc, self.sparkSession.newSession())

    @since(1.3)
    def setConf(self, key, value):
        """Sets the given Spark SQL configuration property.
        """
        self.sparkSession.conf.set(key, value)

    @since(1.3)
    def getConf(self, key, defaultValue=_NoValue):
        """Returns the value of Spark SQL configuration property for the given key.

        If the key is not set and defaultValue is set, return
        defaultValue. If the key is not set and defaultValue is not set, return
        the system default value.

        >>> sqlContext.getConf("spark.sql.shuffle.partitions")
        '200'
        >>> sqlContext.getConf("spark.sql.shuffle.partitions", "10")
        '10'
        >>> sqlContext.setConf("spark.sql.shuffle.partitions", "50")
        >>> sqlContext.getConf("spark.sql.shuffle.partitions", "10")
        '50'
        """
        return self.sparkSession.conf.get(key, defaultValue)

    @property
    @since("1.3.1")
    def udf(self):
        """Returns a :class:`UDFRegistration` for UDF registration.

        :return: :class:`UDFRegistration`
        """
        return self.sparkSession.udf

    @since(1.4)
    def range(self, start, end=None, step=1, numPartitions=None):
        """
        Create a :class:`DataFrame` with single :class:`pyspark.sql.types.LongType` column named
        ``id``, containing elements in a range from ``start`` to ``end`` (exclusive) with
        step value ``step``.

        :param start: the start value
        :param end: the end value (exclusive)
        :param step: the incremental step (default: 1)
        :param numPartitions: the number of partitions of the DataFrame
        :return: :class:`DataFrame`

        >>> sqlContext.range(1, 7, 2).collect()
        [Row(id=1), Row(id=3), Row(id=5)]

        If only one argument is specified, it will be used as the end value.

        >>> sqlContext.range(3).collect()
        [Row(id=0), Row(id=1), Row(id=2)]
        """
        return self.sparkSession.range(start, end, step, numPartitions)

    @since(1.2)
    def registerFunction(self, name, f, returnType=None):
        """An alias for :func:`spark.udf.register`.
        See :meth:`pyspark.sql.UDFRegistration.register`.

        .. note:: Deprecated in 2.3.0. Use :func:`spark.udf.register` instead.
        """
        warnings.warn(
            "Deprecated in 2.3.0. Use spark.udf.register instead.",
            DeprecationWarning)
        return self.sparkSession.udf.register(name, f, returnType)

    @since(2.1)
    def registerJavaFunction(self, name, javaClassName, returnType=None):
        """An alias for :func:`spark.udf.registerJavaFunction`.
        See :meth:`pyspark.sql.UDFRegistration.registerJavaFunction`.

        .. note:: Deprecated in 2.3.0. Use :func:`spark.udf.registerJavaFunction` instead.
        """
        warnings.warn(
            "Deprecated in 2.3.0. Use spark.udf.registerJavaFunction instead.",
            DeprecationWarning)
        return self.sparkSession.udf.registerJavaFunction(name, javaClassName, returnType)

    # TODO(andrew): delete this once we refactor things to take in SparkSession
    def _inferSchema(self, rdd, samplingRatio=None):
        """
        Infer schema from an RDD of Row or tuple.

        :param rdd: an RDD of Row or tuple
        :param samplingRatio: sampling ratio, or no sampling (default)
        :return: :class:`pyspark.sql.types.StructType`
        """
        return self.sparkSession._inferSchema(rdd, samplingRatio)

    @since(1.3)
    def createDataFrame(self, data, schema=None, samplingRatio=None, verifySchema=True):
        """
        Creates a :class:`DataFrame` from an :class:`RDD`, a list or a :class:`pandas.DataFrame`.

        When ``schema`` is a list of column names, the type of each column
        will be inferred from ``data``.

        When ``schema`` is ``None``, it will try to infer the schema (column names and types)
        from ``data``, which should be an RDD of :class:`Row`,
        or :class:`namedtuple`, or :class:`dict`.

        When ``schema`` is :class:`pyspark.sql.types.DataType` or a datatype string it must match
        the real data, or an exception will be thrown at runtime. If the given schema is not
        :class:`pyspark.sql.types.StructType`, it will be wrapped into a
        :class:`pyspark.sql.types.StructType` as its only field, and the field name will be "value",
        each record will also be wrapped into a tuple, which can be converted to row later.

        If schema inference is needed, ``samplingRatio`` is used to determined the ratio of
        rows used for schema inference. The first row will be used if ``samplingRatio`` is ``None``.

        :param data: an RDD of any kind of SQL data representation(e.g. :class:`Row`,
            :class:`tuple`, ``int``, ``boolean``, etc.), or :class:`list`, or
            :class:`pandas.DataFrame`.
        :param schema: a :class:`pyspark.sql.types.DataType` or a datatype string or a list of
            column names, default is None.  The data type string format equals to
            :class:`pyspark.sql.types.DataType.simpleString`, except that top level struct type can
            omit the ``struct<>`` and atomic types use ``typeName()`` as their format, e.g. use
            ``byte`` instead of ``tinyint`` for :class:`pyspark.sql.types.ByteType`.
            We can also use ``int`` as a short name for :class:`pyspark.sql.types.IntegerType`.
        :param samplingRatio: the sample ratio of rows used for inferring
        :param verifySchema: verify data types of every row against schema.
        :return: :class:`DataFrame`

        .. versionchanged:: 2.0
           The ``schema`` parameter can be a :class:`pyspark.sql.types.DataType` or a
           datatype string after 2.0.
           If it's not a :class:`pyspark.sql.types.StructType`, it will be wrapped into a
           :class:`pyspark.sql.types.StructType` and each record will also be wrapped into a tuple.

        .. versionchanged:: 2.1
           Added verifySchema.

        >>> l = [('Alice', 1)]
        >>> sqlContext.createDataFrame(l).collect()
        [Row(_1='Alice', _2=1)]
        >>> sqlContext.createDataFrame(l, ['name', 'age']).collect()
        [Row(name='Alice', age=1)]

        >>> d = [{'name': 'Alice', 'age': 1}]
        >>> sqlContext.createDataFrame(d).collect()
        [Row(age=1, name='Alice')]

        >>> rdd = sc.parallelize(l)
        >>> sqlContext.createDataFrame(rdd).collect()
        [Row(_1='Alice', _2=1)]
        >>> df = sqlContext.createDataFrame(rdd, ['name', 'age'])
        >>> df.collect()
        [Row(name='Alice', age=1)]

        >>> from pyspark.sql import Row
        >>> Person = Row('name', 'age')
        >>> person = rdd.map(lambda r: Person(*r))
        >>> df2 = sqlContext.createDataFrame(person)
        >>> df2.collect()
        [Row(name='Alice', age=1)]

        >>> from pyspark.sql.types import *
        >>> schema = StructType([
        ...    StructField("name", StringType(), True),
        ...    StructField("age", IntegerType(), True)])
        >>> df3 = sqlContext.createDataFrame(rdd, schema)
        >>> df3.collect()
        [Row(name='Alice', age=1)]

        >>> sqlContext.createDataFrame(df.toPandas()).collect()  # doctest: +SKIP
        [Row(name='Alice', age=1)]
        >>> sqlContext.createDataFrame(pandas.DataFrame([[1, 2]])).collect()  # doctest: +SKIP
        [Row(0=1, 1=2)]

        >>> sqlContext.createDataFrame(rdd, "a: string, b: int").collect()
        [Row(a='Alice', b=1)]
        >>> rdd = rdd.map(lambda row: row[1])
        >>> sqlContext.createDataFrame(rdd, "int").collect()
        [Row(value=1)]
        >>> sqlContext.createDataFrame(rdd, "boolean").collect() # doctest: +IGNORE_EXCEPTION_DETAIL
        Traceback (most recent call last):
            ...
        Py4JJavaError: ...
        """
        return self.sparkSession.createDataFrame(data, schema, samplingRatio, verifySchema)

    @since(1.3)
    def registerDataFrameAsTable(self, df, tableName):
        """Registers the given :class:`DataFrame` as a temporary table in the catalog.

        Temporary tables exist only during the lifetime of this instance of :class:`SQLContext`.

        >>> sqlContext.registerDataFrameAsTable(df, "table1")
        """
        df.createOrReplaceTempView(tableName)

    @since(1.6)
    def dropTempTable(self, tableName):
        """ Remove the temporary table from catalog.

        >>> sqlContext.registerDataFrameAsTable(df, "table1")
        >>> sqlContext.dropTempTable("table1")
        """
        self.sparkSession.catalog.dropTempView(tableName)

    @since(1.3)
    def createExternalTable(self, tableName, path=None, source=None, schema=None, **options):
        """Creates an external table based on the dataset in a data source.

        It returns the DataFrame associated with the external table.

        The data source is specified by the ``source`` and a set of ``options``.
        If ``source`` is not specified, the default data source configured by
        ``spark.sql.sources.default`` will be used.

        Optionally, a schema can be provided as the schema of the returned :class:`DataFrame` and
        created external table.

        :return: :class:`DataFrame`
        """
        return self.sparkSession.catalog.createExternalTable(
            tableName, path, source, schema, **options)

    @since(1.0)
    def sql(self, sqlQuery):
        """Returns a :class:`DataFrame` representing the result of the given query.

        :return: :class:`DataFrame`

        >>> sqlContext.registerDataFrameAsTable(df, "table1")
        >>> df2 = sqlContext.sql("SELECT field1 AS f1, field2 as f2 from table1")
        >>> df2.collect()
        [Row(f1=1, f2='row1'), Row(f1=2, f2='row2'), Row(f1=3, f2='row3')]
        """
        return self.sparkSession.sql(sqlQuery)

    @since(1.0)
    def table(self, tableName):
        """Returns the specified table or view as a :class:`DataFrame`.

        :return: :class:`DataFrame`

        >>> sqlContext.registerDataFrameAsTable(df, "table1")
        >>> df2 = sqlContext.table("table1")
        >>> sorted(df.collect()) == sorted(df2.collect())
        True
        """
        return self.sparkSession.table(tableName)

    @since(1.3)
    def tables(self, dbName=None):
        """Returns a :class:`DataFrame` containing names of tables in the given database.

        If ``dbName`` is not specified, the current database will be used.

        The returned DataFrame has two columns: ``tableName`` and ``isTemporary``
        (a column with :class:`BooleanType` indicating if a table is a temporary one or not).

        :param dbName: string, name of the database to use.
        :return: :class:`DataFrame`

        >>> sqlContext.registerDataFrameAsTable(df, "table1")
        >>> df2 = sqlContext.tables()
        >>> df2.filter("tableName = 'table1'").first()
        Row(database='', tableName='table1', isTemporary=True)
        """
        if dbName is None:
            return DataFrame(self._ssql_ctx.tables(), self)
        else:
            return DataFrame(self._ssql_ctx.tables(dbName), self)

    @since(1.3)
    def tableNames(self, dbName=None):
        """Returns a list of names of tables in the database ``dbName``.

        :param dbName: string, name of the database to use. Default to the current database.
        :return: list of table names, in string

        >>> sqlContext.registerDataFrameAsTable(df, "table1")
        >>> "table1" in sqlContext.tableNames()
        True
        >>> "table1" in sqlContext.tableNames("default")
        True
        """
        if dbName is None:
            return [name for name in self._ssql_ctx.tableNames()]
        else:
            return [name for name in self._ssql_ctx.tableNames(dbName)]

    @since(1.0)
    def cacheTable(self, tableName):
        """Caches the specified table in-memory."""
        self._ssql_ctx.cacheTable(tableName)

    @since(1.0)
    def uncacheTable(self, tableName):
        """Removes the specified table from the in-memory cache."""
        self._ssql_ctx.uncacheTable(tableName)

    @since(1.3)
    def clearCache(self):
        """Removes all cached tables from the in-memory cache. """
        self._ssql_ctx.clearCache()

    @property
    @since(1.4)
    def read(self):
        """
        Returns a :class:`DataFrameReader` that can be used to read data
        in as a :class:`DataFrame`.

        :return: :class:`DataFrameReader`
        """
        return DataFrameReader(self)

    @property
    @since(2.0)
    def readStream(self):
        """
        Returns a :class:`DataStreamReader` that can be used to read data streams
        as a streaming :class:`DataFrame`.

        .. note:: Evolving.

        :return: :class:`DataStreamReader`

        >>> text_sdf = sqlContext.readStream.text(tempfile.mkdtemp())
        >>> text_sdf.isStreaming
        True
        """
        return DataStreamReader(self)

    @property
    @since(2.0)
    def streams(self):
        """Returns a :class:`StreamingQueryManager` that allows managing all the
        :class:`StreamingQuery` StreamingQueries active on `this` context.

        .. note:: Evolving.
        """
        from pyspark.sql.streaming import StreamingQueryManager
        return StreamingQueryManager(self._ssql_ctx.streams())

class HiveContext(SQLContext):
    """A variant of Spark SQL that integrates with data stored in Hive.

    Configuration for Hive is read from ``hive-site.xml`` on the classpath.
    It supports running both SQL and HiveQL commands.

    :param sparkContext: The SparkContext to wrap.
    :param jhiveContext: An optional JVM Scala HiveContext. If set, we do not instantiate a new
        :class:`HiveContext` in the JVM, instead we make all calls to this object.

    .. note:: Deprecated in 2.0.0. Use SparkSession.builder.enableHiveSupport().getOrCreate().
    """

    def __init__(self, sparkContext, jhiveContext=None):
        warnings.warn(
            "HiveContext is deprecated in Spark 2.0.0. Please use " +
            "SparkSession.builder.enableHiveSupport().getOrCreate() instead.",
            DeprecationWarning)
        if jhiveContext is None:
            sparkContext._conf.set("spark.sql.catalogImplementation", "hive")
            sparkSession = SparkSession.builder._sparkContext(sparkContext).getOrCreate()
        else:
            sparkSession = SparkSession(sparkContext, jhiveContext.sparkSession())
        SQLContext.__init__(self, sparkContext, sparkSession, jhiveContext)

    @classmethod
    def _createForTesting(cls, sparkContext):
        """(Internal use only) Create a new HiveContext for testing.

        All test code that touches HiveContext *must* go through this method. Otherwise,
        you may end up launching multiple derby instances and encounter with incredibly
        confusing error messages.
        """
        jsc = sparkContext._jsc.sc()
        jtestHive = sparkContext._jvm.org.apache.spark.sql.hive.test.TestHiveContext(jsc, False)
        return cls(sparkContext, jtestHive)

    def refreshTable(self, tableName):
        """Invalidate and refresh all the cached the metadata of the given
        table. For performance reasons, Spark SQL or the external data source
        library it uses might cache certain metadata about a table, such as the
        location of blocks. When those change outside of Spark SQL, users should
        call this function to invalidate the cache.
        """
        self._ssql_ctx.refreshTable(tableName)

def _test():
    import os
    import doctest
    import tempfile
    from pyspark.context import SparkContext
    from pyspark.sql import Row, SQLContext
    import pyspark.sql.context

    os.chdir(os.environ["SPARK_HOME"])

    globs = pyspark.sql.context.__dict__.copy()
    sc = SparkContext('local[4]', 'PythonTest')
    globs['tempfile'] = tempfile
    globs['os'] = os
    globs['sc'] = sc
    globs['sqlContext'] = SQLContext(sc)
    globs['rdd'] = rdd = sc.parallelize(
        [Row(field1=1, field2="row1"),
         Row(field1=2, field2="row2"),
         Row(field1=3, field2="row3")]
    )
    globs['df'] = rdd.toDF()
    jsonStrings = [
        '{"field1": 1, "field2": "row1", "field3":{"field4":11}}',
        '{"field1" : 2, "field3":{"field4":22, "field5": [10, 11]},"field6":[{"field7": "row2"}]}',
        '{"field1" : null, "field2": "row3", "field3":{"field4":33, "field5": []}}'
    ]
    globs['jsonStrings'] = jsonStrings
    globs['json'] = sc.parallelize(jsonStrings)
    (failure_count, test_count) = doctest.testmod(
        pyspark.sql.context, globs=globs,
        optionflags=doctest.ELLIPSIS | doctest.NORMALIZE_WHITESPACE)
    globs['sc'].stop()
    if failure_count:
        sys.exit(-1)

if __name__ == "__main__":
    _test()


text:
/*
 * Deed API
 *
 * Land Registry Deed API
 *
 * OpenAPI spec version: 1.3.8
 *
 * Generated by: https://github.com/swagger-api/swagger-codegen.git
 *
 * 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 System;
using System.Linq;
using System.IO;
using System.Text;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Runtime.Serialization;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;

namespace IO.Swagger.Model
{
    /// <summary>
    /// ChargeClause
    /// </summary>
    [DataContract]
    public partial class ChargeClause :  IEquatable<ChargeClause>
    {
        /// <summary>
        /// Initializes a new instance of the <see cref="ChargeClause" /> class.
        /// </summary>
        /// <param name="CreCode">CreCode.</param>
        /// <param name="Description">Description.</param>
        public ChargeClause(string CreCode = null, string Description = null)
        {
            this.CreCode = CreCode;
            this.Description = Description;
        }

        /// <summary>
        /// Gets or Sets CreCode
        /// </summary>
        [DataMember(Name="cre_code", EmitDefaultValue=false)]
        public string CreCode { get; set; }
        /// <summary>
        /// Gets or Sets Description
        /// </summary>
        [DataMember(Name="description", EmitDefaultValue=false)]
        public string Description { get; set; }
        /// <summary>
        /// Returns the string presentation of the object
        /// </summary>
        /// <returns>String presentation of the object</returns>
        public override string ToString()
        {
            var sb = new StringBuilder();
            sb.Append("class ChargeClause {\n");
            sb.Append("  CreCode: ").Append(CreCode).Append("\n");
            sb.Append("  Description: ").Append(Description).Append("\n");
            sb.Append("}\n");
            return sb.ToString();
        }

        /// <summary>
        /// Returns the JSON string presentation of the object
        /// </summary>
        /// <returns>JSON string presentation of the object</returns>
        public string ToJson()
        {
            return JsonConvert.SerializeObject(this, Formatting.Indented);
        }

        /// <summary>
        /// Returns true if objects are equal
        /// </summary>
        /// <param name="obj">Object to be compared</param>
        /// <returns>Boolean</returns>
        public override bool Equals(object obj)
        {
            // credit: http://stackoverflow.com/a/10454552/677735
            return this.Equals(obj as ChargeClause);
        }

        /// <summary>
        /// Returns true if ChargeClause instances are equal
        /// </summary>
        /// <param name="other">Instance of ChargeClause to be compared</param>
        /// <returns>Boolean</returns>
        public bool Equals(ChargeClause other)
        {
            // credit: http://stackoverflow.com/a/10454552/677735
            if (other == null)
                return false;

            return
                (
                    this.CreCode == other.CreCode ||
                    this.CreCode != null &&
                    this.CreCode.Equals(other.CreCode)
                ) &&
                (
                    this.Description == other.Description ||
                    this.Description != null &&
                    this.Description.Equals(other.Description)
                );
        }

        /// <summary>
        /// Gets the hash code
        /// </summary>
        /// <returns>Hash code</returns>
        public override int GetHashCode()
        {
            // credit: http://stackoverflow.com/a/263416/677735
            unchecked // Overflow is fine, just wrap
            {
                int hash = 41;
                // Suitable nullity checks etc, of course :)
                if (this.CreCode != null)
                    hash = hash * 59 + this.CreCode.GetHashCode();
                if (this.Description != null)
                    hash = hash * 59 + this.Description.GetHashCode();
                return hash;
            }
        }
    }

}


text:
\section{Measurements}
\label{sec:experiments:measurements}

Using the set-up described in section \ref{sec:experiments:approach}, we have performed several experiments.

\begin{figure}[t]
	\centering
	\includegraphics[width=0.85\textwidth]{graphics/cpu.pdf}
	\caption{CPU measurements for various tunnel configurations without cryptography.}
	\label{fig:cpu_measurements}
\end{figure}

By looking at the CPU usage we can determine whether running the anontunnels is too computationally expensive for the application of video streaming. Even without cryptography, we are seeing a CPU utilization of about 75\% when downloading (see Figure \ref{fig:cpu_measurements}). Due to the fact that we are not using cryptography, the amount of hops or circuits does not impact the CPU performance.

It is also interesting to look at the download speed of the application. This indicates whether we can accomplish the necessary bitrate to stream video, which is about 1000 Kb/s (see Subsection \ref{sec:experiments:theoretical:bitrates}). We managed to achieve a download speed on our test set-up of around 500 - 600 KB/s, which corresponds to 4000 - 4800 Kb/s (see Figure \ref{fig:download_measurements}). This is sufficient for the application of video streaming. Due to the fact that all stand-alone anontunnels are running on the same computer, they will all perform equally well. Not a single tunnel will act as a bottleneck. Additionally, the computer running the anontunnels is connected to the internet with a high speed connection of 100 Mb/s. Because of these factors, the impact of the amount of circuits or hops is negligible. The computer is capable of relaying data fast enough to not impact the download speed of the Android device.

The time between when the download is triggered and when it actually receives its first byte is about 140 - 150 seconds when using one circuit. With three circuits, this takes about 180 - 190 seconds. This difference can be explained by the fact that more circuits take more time to set up.

\begin{figure}[t]
	\centering
	\includegraphics[width=0.85\textwidth]{graphics/downloadspeed.pdf}
	\caption{Download speed measured for various tunnel configurations without cryptography. The plot has been smoothed with a moving average of 10 seconds.}
	\label{fig:download_measurements}
\end{figure}


text:
OC.L10N.register(
    "lib",
    {
    "Cannot write into \"config\" directory!" : "Nie można zapisać do katalogu \"config\"!",
    "This can usually be fixed by giving the webserver write access to the config directory" : "Można to zwykle rozwiązać przez dodanie serwerowi www uprawnień zapisu do katalogu config.",
    "See %s" : "Zobacz %s",
    "This can usually be fixed by %sgiving the webserver write access to the config directory%s." : "Można to zwykle rozwiązać przez %sdodanie serwerowi www uprawnień zapisu do katalogu config%s.",
    "Sample configuration detected" : "Wykryto przykładową konfigurację",
    "It has been detected that the sample configuration has been copied. This can break your installation and is unsupported. Please read the documentation before performing changes on config.php" : "Wykryto skopiowanie przykładowej konfiguracji. To może popsuć Twoją instalację i nie jest wspierane. Proszę przeczytać dokumentację przed dokonywaniem zmian w config.php",
    "PHP %s or higher is required." : "PHP %s lub wyższe jest wymagane.",
    "PHP with a version lower than %s is required." : "Wersja PHP jest niższa niż %s, która jest wymagana.",
    "Following databases are supported: %s" : "Obsługiwane są następujące bazy danych: %s",
    "The command line tool %s could not be found" : "Narzędzie konsoli %s nie zostało znalezione",
    "The library %s is not available." : "Biblioteka %s nie jest dostępna.",
    "Library %s with a version higher than %s is required - available version %s." : "Biblioteka %s w wersji wyższej niż %s, która jest wymagana - dostępna wersja %s.",
    "Library %s with a version lower than %s is required - available version %s." : "Biblioteka w wersji %s jest niższa niż %s, która jest wymagana - dostępna wersja %s.",
    "Following platforms are supported: %s" : "Obsługiwane są następujące platformy: %s",
    "ownCloud %s or higher is required." : "ownCloud %s jest w wersji nowszej niż wymagana.",
    "ownCloud %s or lower is required." : "ownCloud %s jest w wersji starszej niż wymagana.",
    "Unknown filetype" : "Nieznany typ pliku",
    "Invalid image" : "Błędne zdjęcie",
    "Avatar image is not square" : "Obrazek awatara nie jest kwadratowy",
    "today" : "dziś",
    "yesterday" : "wczoraj",
    "_%n day ago_::_%n days ago_" : ["%d dzień temu","%n dni temu","%n dni temu","%n dni temu"],
    "last month" : "w zeszłym miesiącu",
    "_%n month ago_::_%n months ago_" : ["%n miesiąc temu","%n miesięcy temu","%n miesięcy temu","%n miesięcy temu"],
    "last year" : "w zeszłym roku",
    "_%n year ago_::_%n years ago_" : ["%n rok temu","%n lata temu","%n lat temu","%n lat temu"],
    "_%n hour ago_::_%n hours ago_" : ["%n godzinę temu","%n godzin temu","%n godzin temu","%n godzin temu"],
    "_%n minute ago_::_%n minutes ago_" : ["%n minute temu","%n minut temu","%n minut temu","%n minut temu"],
    "seconds ago" : "sekund temu",
    "None" : "Brak.",
    "Username and password" : "Użytkownik i hasło",
    "Username" : "Użytkownik",
    "Password" : "Hasło",
    "Empty filename is not allowed" : "Pusta nazwa nie jest dozwolona.",
    "4-byte characters are not supported in file names" : "Znaki 4-bajtowe są niedozwolone w nazwach plików",
    "File name contains at least one invalid character" : "Nazwa pliku zawiera co najmniej jeden nieprawidłowy znak",
    "File name is too long" : "Nazwa pliku zbyt długa",
    "__language_name__" : "polski",
    "App directory already exists" : "Katalog aplikacji już isnieje",
    "Can't create app folder. Please fix permissions. %s" : "Nie mogę utworzyć katalogu aplikacji. Proszę popraw uprawnienia. %s",
    "Archive does not contain a directory named %s" : "Archiwum nie zawiera ścieżki o nazwie %s",
    "No source specified when installing app" : "Nie określono źródła  podczas instalacji aplikacji",
    "No href specified when installing app from http" : "Nie określono linku skąd aplikacja ma być zainstalowana",
    "No path specified when installing app from local file" : "Nie określono lokalnego pliku z którego miała być instalowana aplikacja",
    "Archives of type %s are not supported" : "Typ archiwum %s nie jest obsługiwany",
    "Failed to open archive when installing app" : "Nie udało się otworzyć archiwum podczas instalacji aplikacji",
    "App does not provide an info.xml file" : "Aplikacja nie posiada pliku info.xml",
    "Signature could not get checked. Please contact the app developer and check your admin screen." : "Sygnatura nie mogła zostać sprawdzona. Proszę o skontaktownie się z twórcą aplikacji i sprawdzenie panelu administratora.",
    "App can't be installed because it is not compatible with this version of ownCloud" : "Aplikacja nie może zostać zainstalowana ponieważ jest niekompatybilna z tą wersja ownCloud",
    "App can't be installed because it contains the <shipped>true</shipped> tag which is not allowed for non shipped apps" : "Aplikacja nie może być zainstalowana ponieważ true tag nie jest <shipped>true</shipped> , co nie jest dozwolone dla aplikacji nie wysłanych",
    "Apps" : "Aplikacje",
    "General" : "Ogólne",
    "Storage" : "Magazyn",
    "Security" : "Bezpieczeństwo",
    "Encryption" : "Szyfrowanie",
    "Sharing" : "Udostępnianie",
    "Search" : "Wyszukaj",
    "Help & Tips" : "Pomoc & Podpowiedzi",
    "Additional" : "Dodatki",
    "%s enter the database username." : "%s wpisz nazwę użytkownika do  bazy",
    "%s enter the database name." : "%s wpisz nazwę bazy.",
    "Oracle connection could not be established" : "Nie można ustanowić połączenia z bazą Oracle",
    "Oracle username and/or password not valid" : "Oracle: Nazwa użytkownika i/lub hasło jest niepoprawne",
    "DB Error: \"%s\"" : "Błąd DB: \"%s\"",
    "Offending command was: \"%s\"" : "Niepoprawna komenda: \"%s\"",
    "You need to enter either an existing account or the administrator." : "Należy wprowadzić istniejące konto użytkownika lub  administratora.",
    "Offending command was: \"%s\", name: %s, password: %s" : "Niepoprawne polecania:  \"%s\", nazwa: %s, hasło: %s",
    "PostgreSQL username and/or password not valid" : "PostgreSQL: Nazwa użytkownika i/lub hasło jest niepoprawne",
    "For the best results, please consider using a GNU/Linux server instead." : "Aby uzyskać najlepsze rezultaty, rozważ w to miejsce użycie serwera GNU/Linux.",
    "Set an admin username." : "Ustaw nazwę administratora.",
    "Set an admin password." : "Ustaw hasło administratora.",
    "Can't create or write into the data directory %s" : "Nie można tworzyć ani zapisywać w katalogu %s",
    "Invalid Federated Cloud ID" : "Niewłaściwe ID stowarzyszonej chmury",
    "%s shared »%s« with you" : "%s Współdzielone »%s« z tobą",
    "%s via %s" : "%s przez %s",
    "Sharing %s failed, because the file does not exist" : "Wspóldzielenie %s nie powiodło się. ponieważ plik nie istnieje",
    "You are not allowed to share %s" : "Nie masz uprawnień aby udostępnić %s",
    "Sharing %s failed, because the user %s does not exist" : "Współdzielenie %s nie powiodło się, ponieważ użytkownik %s nie istnieje",
    "Sharing %s failed, because the user %s is not a member of any groups that %s is a member of" : "Współdzielenie %s nie powiodło się, ponieważ użytkownik %s nie jest członkiem żadnej grupy której członkiem jest %s",
    "Sharing %s failed, because this item is already shared with %s" : "Współdzielenie %s nie powiodło się, ponieważ element jest już współdzielony z %s",
    "Sharing %s failed, because the group %s does not exist" : "Współdzielenie %s nie powiodło się, ponieważ grupa %s nie istnieje",
    "Sharing %s failed, because %s is not a member of the group %s" : "Współdzielenie %s nie powiodło się, ponieważ %s nie jest członkiem grupy %s",
    "You need to provide a password to create a public link, only protected links are allowed" : "Musisz zapewnić hasło aby utworzyć link publiczny, dozwolone są tylko linki chronione",
    "Sharing %s failed, because sharing with links is not allowed" : "Współdzielenie %s nie powiodło się, ponieważ współdzielenie z linkami nie jest dozwolone",
    "Share type %s is not valid for %s" : "Typ udziału %s nie jest właściwy dla %s",
    "Setting permissions for %s failed, because the permissions exceed permissions granted to %s" : "Ustawienie uprawnień dla %s nie powiodło się, ponieważ uprawnienia wykraczają poza przydzielone %s",
    "Setting permissions for %s failed, because the item was not found" : "Ustawienie uprawnień dla %s nie powiodło się, ponieważ element nie został znaleziony",
    "Cannot set expiration date. Shares cannot expire later than %s after they have been shared" : "Nie można ustawić daty wygaśnięcia. Udziały nie mogą wygasać później niż %s od momentu udostępnienia",
    "Cannot set expiration date. Expiration date is in the past" : "Nie można ustawić daty wygaśnięcia. Data wygaśnięcia jest w przeszłości.",
    "Sharing backend %s must implement the interface OCP\\Share_Backend" : "Zaplecze do współdzielenia %s musi implementować interfejs OCP\\Share_Backend",
    "Sharing backend %s not found" : "Zaplecze %s do współdzielenia nie zostało znalezione",
    "Sharing backend for %s not found" : "Zaplecze do współdzielenia %s nie zostało znalezione",
    "Sharing %s failed, because the permissions exceed permissions granted to %s" : "Współdzielenie %s nie powiodło się, ponieważ uprawnienia przekraczają te udzielone %s",
    "Sharing %s failed, because resharing is not allowed" : "Współdzielenie %s nie powiodło się, ponieważ ponowne współdzielenie nie jest dozwolone",
    "Sharing %s failed, because the sharing backend for %s could not find its source" : "Współdzielenie %s nie powiodło się, ponieważ zaplecze współdzielenia dla %s nie mogło znaleźć jego źródła",
    "Sharing %s failed, because the file could not be found in the file cache" : "Współdzielenie %s nie powiodło się, ponieważ plik nie może zostać odnaleziony w buforze plików",
    "Cannot remove all permissions" : "Nie można usunąć wszystkich uprawnień",
    "Could not find category \"%s\"" : "Nie można odnaleźć kategorii \"%s\"",
    "A valid username must be provided" : "Należy podać prawidłową nazwę użytkownika",
    "A valid password must be provided" : "Należy podać prawidłowe hasło",
    "The username is already being used" : "Ta nazwa użytkownika jest już używana",
    "User disabled" : "Użytkownik zablokowany",
    "Settings" : "Ustawienia",
    "Users" : "Użytkownicy",
    "A safe home for all your data" : "Bezpieczne miejsce dla wszystkich Twoich danych",
    "Imprint" : "Stopka",
    "Privacy Policy" : "Polityka prywatności",
    "File is currently busy, please try again later" : "Plik jest obecnie niedostępny, proszę spróbować ponownie później",
    "Application is not enabled" : "Aplikacja nie jest włączona",
    "Authentication error" : "Błąd uwierzytelniania",
    "Token expired. Please reload page." : "Token wygasł. Proszę ponownie załadować stronę.",
    "Unknown user" : "Nieznany użytkownik",
    "No database drivers (sqlite, mysql, or postgresql) installed." : "Brak sterowników bazy danych (sqlite, mysql or postgresql).",
    "Cannot write into \"config\" directory" : "Nie można zapisać do katalogu \"config\"",
    "Permissions can usually be fixed by %sgiving the webserver write access to the root directory%s." : "Problemy z uprawnieniami można zwykle naprawić  przez %sdodanie serwerowi www uprawnień zapisu do katalogu głównego%s.",
    "Setting locale to %s failed" : "Nie udało się zmienić języka na %s",
    "Please install one of these locales on your system and restart your webserver." : "Proszę zainstalować jedno z poniższych locale w Twoim systemie i uruchomić ponownie serwer www.",
    "Please ask your server administrator to install the module." : "Proszę poproś administratora serwera aby zainstalował ten moduł.",
    "PHP module %s not installed." : "Moduł PHP %s nie jest zainstalowany.",
    "This is probably caused by a cache/accelerator such as Zend OPcache or eAccelerator." : "Dzieje się tak prawdopodobnie przez cache lub akcelerator taki jak Zend OPcache lub eAccelerator.",
    "PHP modules have been installed, but they are still listed as missing?" : "Moduły PHP zostały zainstalowane, ale nadal brakuje ich na liście?",
    "Please ask your server administrator to restart the web server." : "Poproś administratora serwera o restart serwera www.",
    "PostgreSQL >= 9 required" : "Wymagany PostgreSQL >= 9",
    "Please upgrade your database version" : "Uaktualnij wersję bazy danych",
    "Please change the permissions to 0770 so that the directory cannot be listed by other users." : "Zmień uprawnienia na 0770, żeby ukryć zawartość katalogu przed innymi użytkownikami.",
    "Please check that the data directory contains a file \".ocdata\" in its root." : "Sprawdź, czy katalog danych zawiera plik \".ocdata\".",
    "Could not obtain lock type %d on \"%s\"." : "Nie można uzyskać blokady typu %d na \"%s\".",
    "Storage is temporarily not available" : "Składowisko danych tymczasowo niedostępne"
},
"nplurals=4; plural=(n==1 ? 0 : (n%10>=2 && n%10<=4) && (n%100<12 || n%100>14) ? 1 : n!=1 && (n%10>=0 && n%10<=1) || (n%10>=5 && n%10<=9) || (n%100>=12 && n%100<=14) ? 2 : 3);");


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

    angular.module('pmajs.pages.intro', [
      'pmajs'
  ]).controller('IntroController', ['$scope', '$rootScope', '$state', 'appDataService', 'appService',
      function ($scope, $rootScope, $state, appDataService, appService) {
          var ctrl = this;
          ctrl.status = {};
          ctrl.data = {};
          ctrl.actions = {};

          ctrl.actions.syncApiDocs = syncApiDocs;

          appService.clearData();

          ctrl.data.frameworks = appService.getFrameworks();
		  ctrl.data.framework = JSON.stringify(ctrl.data.frameworks[0]);

          $scope.$watch(function () {
              return ctrl.data.localApiDocsJson;
          }, function (newLocalApiDocsJson) {
              if (!newLocalApiDocsJson) {
                  appService.clearData();
                  return;
              }

              var reader = new FileReader();
              reader.onload = function (e) {
                  var localApiDocsJson = JSON.parse(reader.result);
                  appService.setLocalApiDocs(localApiDocsJson);
              }
              reader.readAsText(newLocalApiDocsJson);
          });

          $scope.$watch(function () {
              return ctrl.data.framework;
          }, function (newFramework) {
              if (!newFramework) {
                  return;
              }

              newFramework = JSON.parse(newFramework);
              appService.setFramework(newFramework);

              if (newFramework.id == 'angular_v2') {
				  alert('Angular 2 is not fully supported - TO BE IMPLEMENTED');
			  }
          });

          // implementations
          function syncApiDocs(itemAppName, itemApiDocUrl) {
              ctrl.status.isLoading = true;
              $rootScope.appName = itemAppName;
              appDataService.getApiDocs(itemApiDocUrl).then(function (resultApiDocs) {
                  appService.setApiDocs(resultApiDocs);
                  $state.go('models');
              }, function (resultErrorMessage) {
                  alert(resultErrorMessage);
              }).finally(function () {
                  ctrl.status.isLoading = false;
              });
          }
      }
    ]);
})();


text:
"""
Implements eventual (low) consistency and high availability.
"""

##########################################################################
## Imports
##########################################################################

import random

from cloudscope.config import settings
from cloudscope.dynamo import Bernoulli
from cloudscope.replica import Consistency
from cloudscope.replica.eventual import Gossip
from cloudscope.replica.eventual import EventualReplica
from cloudscope.exceptions import SimulationException

##########################################################################
## Module Constants
##########################################################################

## Fetch simulation settings from defaults
SYNC_PROB  = settings.simulation.sync_prob
LOCAL_PROB = settings.simulation.local_prob

##########################################################################
## Federated Eventual Replica
##########################################################################

class FederatedEventualReplica(EventualReplica):
    """
    Implements eventual consistency while allowing for integration with
    strongly consistent replicas.
    """

    def __init__(self, simulation, **kwargs):
        super(FederatedEventualReplica, self).__init__(simulation, **kwargs)

        # Federated settings
        self.do_sync  = Bernoulli(kwargs.get('sync_prob', SYNC_PROB))
        self.do_local = Bernoulli(kwargs.get('local_prob', LOCAL_PROB))

    def select_anti_entropy_neighbor(self):
        """
        Selects a neighbor to perform anti-entropy with, prioritizes local
        neighbors over remote ones and also actively selects the sequential
        consistency nodes to perform anti-entropy with.
        """
        # Decide if we should sync with the core consensus group
        if self.do_sync.get():

            # Find a strong consensus node that is local
            neighbors = self.neighbors(
                consistency=Consistency.STRONG, location=self.location
            )

            # If we have local nodes, choose one of them
            if neighbors: return random.choice(neighbors)

            # Otherwise choose any strong node that exists
            neighbors = self.neighbors(consistency=Consistency.STRONG)
            if neighbors: return random.choice(neighbors)

        # Decide if we should do anti-entropy locally or across the wide area.
        if self.do_local.get():
            # Find all local nodes with the same consistency.
            neighbors = self.neighbors(
                consistency=[Consistency.EVENTUAL, Consistency.STENTOR],
                location=self.location
            )

            # If we have local nodes, choose one of them
            if neighbors: return random.choice(neighbors)
            return random.choice(self.neighbors())

        # At this point return a wide area node that doesn't have strong consistency
        neighbors = self.neighbors(
            consistency=Consistency.STRONG, location=self.location, exclude=True
        )

        # If we have wide area nodes, choose one of them
        if neighbors: return random.choice(neighbors)

        # Last resort, simply choose any neighbor we possibly can!
        return random.choice(self.neighbors())

##########################################################################
## Stentor Eventual Replica
##########################################################################

class StentorEventualReplica(EventualReplica):
    """
    Stentor replicas perform anti-entropy twice - one in the local area and
    one in the wide area for each anti-entropy round.
    """

    def select_anti_entropy_neighbor(self):
        """
        This is a No-Op for this type of replica.
        """
        raise SimulationException(
            "Stentor replicas do not have a single neighbor selection policy."
        )

    def get_anti_entropy_neighbors(self):
        """
        Selects a neighbor to perform anti-entropy with.
        """

        # Choose a neighbor in the local area to gossip with.
        neighbors = list(self.neighbors(location=self.location))

        # If we have local nodes, choose one of them
        if neighbors: yield random.choice(neighbors)

        # Choose a neighbor in the wide area to gossip with.
        neighbors = list(self.neighbors(location=self.location, exclude=True))

        # If we have wide nodes, choose one of them
        if neighbors: yield random.choice(neighbors)


text:
using System.Data;
using System.Data.SqlClient;
using Appleseed.Framework.Settings;

namespace Appleseed.Framework.Content.Data
{
    /// <summary>
    /// Class that encapsulates all data logic necessary to add/query/delete
    /// links within the Portal database.
    /// </summary>
    public class LinkDB
    {
        /// <summary>
        /// The GetLinks method returns a SqlDataReader containing all of the
        /// links for a specific portal module from the announcements
        /// database.
        /// </summary>
        /// <param name="moduleID">The module ID.</param>
        /// <param name="version">The version.</param>
        /// <returns></returns>
        public SqlDataReader GetLinks(int moduleID, WorkFlowVersion version)
        {
            // Create Instance of Connection and Command Object
            SqlConnection myConnection = Config.SqlConnectionString;
            SqlCommand myCommand = new SqlCommand("rb_GetLinks", myConnection);

            // Mark the Command as a SPROC
            myCommand.CommandType = CommandType.StoredProcedure;

            // Add Parameters to SPROC
            SqlParameter parameterModuleID = new SqlParameter("@ModuleID", SqlDbType.Int, 4);
            parameterModuleID.Value = moduleID;
            myCommand.Parameters.Add(parameterModuleID);

            // Change by Geert.Audenaert@Syntegra.Com
            // Date: 7/2/2003
            SqlParameter parameterWorkflowVersion = new SqlParameter("@WorkflowVersion", SqlDbType.Int, 4);
            parameterWorkflowVersion.Value = (int) version;
            myCommand.Parameters.Add(parameterWorkflowVersion);
            // End Change Geert.Audenaert@Syntegra.Com

            // Execute the command
            myConnection.Open();
            SqlDataReader result = myCommand.ExecuteReader(CommandBehavior.CloseConnection);

            // Return the datareader
            return result;
        }

        /// <summary>
        /// The GetSingleLink method returns a SqlDataReader containing details
        /// about a specific link from the Links database table.
        /// </summary>
        /// <param name="itemID">The item ID.</param>
        /// <param name="version">The version.</param>
        /// <returns></returns>
        public SqlDataReader GetSingleLink(int itemID, WorkFlowVersion version)
        {
            // Create Instance of Connection and Command Object
            SqlConnection myConnection = Config.SqlConnectionString;
            SqlCommand myCommand = new SqlCommand("rb_GetSingleLink", myConnection);

            // Mark the Command as a SPROC
            myCommand.CommandType = CommandType.StoredProcedure;

            // Add Parameters to SPROC
            SqlParameter parameterItemID = new SqlParameter("@ItemID", SqlDbType.Int, 4);
            parameterItemID.Value = itemID;
            myCommand.Parameters.Add(parameterItemID);

            // Change by Geert.Audenaert@Syntegra.Com
            // Date: 7/2/2003
            SqlParameter parameterWorkflowVersion = new SqlParameter("@WorkflowVersion", SqlDbType.Int, 4);
            parameterWorkflowVersion.Value = (int) version;
            myCommand.Parameters.Add(parameterWorkflowVersion);
            // End Change Geert.Audenaert@Syntegra.Com

            // Execute the command
            myConnection.Open();
            SqlDataReader result = myCommand.ExecuteReader(CommandBehavior.CloseConnection);

            // Return the datareader
            return result;
        }

        /// <summary>
        /// The DeleteLink method deletes a specified link from
        /// the Links database table.
        /// </summary>
        /// <param name="itemID">The item ID.</param>
        public void DeleteLink(int itemID)
        {
            // Create Instance of Connection and Command Object
            SqlConnection myConnection = Config.SqlConnectionString;
            SqlCommand myCommand = new SqlCommand("rb_DeleteLink", myConnection);

            // Mark the Command as a SPROC
            myCommand.CommandType = CommandType.StoredProcedure;

            // Add Parameters to SPROC
            SqlParameter parameterItemID = new SqlParameter("@ItemID", SqlDbType.Int, 4);
            parameterItemID.Value = itemID;
            myCommand.Parameters.Add(parameterItemID);

            myConnection.Open();
            try
            {
                myCommand.ExecuteNonQuery();
            }
            finally
            {
                myConnection.Close();
            }
        }

        /// <summary>
        /// The AddLink method adds a new link within the
        /// links database table, and returns ItemID value as a result.
        /// </summary>
        /// <param name="moduleID">The module ID.</param>
        /// <param name="itemID">The item ID.</param>
        /// <param name="userName">Name of the user.</param>
        /// <param name="title">The title.</param>
        /// <param name="url">The URL.</param>
        /// <param name="mobileUrl">The mobile URL.</param>
        /// <param name="viewOrder">The view order.</param>
        /// <param name="description">The description.</param>
        /// <param name="target">The target.</param>
        /// <returns></returns>
        public int AddLink(int moduleID, int itemID, string userName, string title, string url, string mobileUrl,
                           int viewOrder, string description, string target)
        {
            if (userName.Length < 1)
            {
                userName = "unknown";
            }

            // Create Instance of Connection and Command Object
            SqlConnection myConnection = Config.SqlConnectionString;
            SqlCommand myCommand = new SqlCommand("rb_AddLink", myConnection);

            // Mark the Command as a SPROC
            myCommand.CommandType = CommandType.StoredProcedure;

            // Add Parameters to SPROC
            SqlParameter parameterItemID = new SqlParameter("@ItemID", SqlDbType.Int, 4);
            parameterItemID.Direction = ParameterDirection.Output;
            myCommand.Parameters.Add(parameterItemID);

            SqlParameter parameterModuleID = new SqlParameter("@ModuleID", SqlDbType.Int, 4);
            parameterModuleID.Value = moduleID;
            myCommand.Parameters.Add(parameterModuleID);

            SqlParameter parameterUserName = new SqlParameter("@UserName", SqlDbType.NVarChar, 100);
            parameterUserName.Value = userName;
            myCommand.Parameters.Add(parameterUserName);

            SqlParameter parameterTitle = new SqlParameter("@Title", SqlDbType.NVarChar, 100);
            parameterTitle.Value = title;
            myCommand.Parameters.Add(parameterTitle);

            SqlParameter parameterDescription = new SqlParameter("@Description", SqlDbType.NVarChar, 100);
            parameterDescription.Value = description;
            myCommand.Parameters.Add(parameterDescription);

            SqlParameter parameterTarget = new SqlParameter("@Target", SqlDbType.NVarChar, 10);
            parameterTarget.Value = target;
            myCommand.Parameters.Add(parameterTarget);

            SqlParameter parameterUrl = new SqlParameter("@Url", SqlDbType.NVarChar, 800);
            parameterUrl.Value = url;
            myCommand.Parameters.Add(parameterUrl);

            SqlParameter parameterMobileUrl = new SqlParameter("@MobileUrl", SqlDbType.NVarChar, 250);
            parameterMobileUrl.Value = mobileUrl;
            myCommand.Parameters.Add(parameterMobileUrl);

            SqlParameter parameterViewOrder = new SqlParameter("@ViewOrder", SqlDbType.Int, 4);
            parameterViewOrder.Value = viewOrder;
            myCommand.Parameters.Add(parameterViewOrder);

            myConnection.Open();
            try
            {
                myCommand.ExecuteNonQuery();
            }
            finally
            {
                myConnection.Close();
            }

            return (int) parameterItemID.Value;
        }

        /// <summary>
        /// The UpdateLink method updates a specified link within
        /// the Links database table.
        /// </summary>
        /// <param name="moduleID">The module ID.</param>
        /// <param name="itemID">The item ID.</param>
        /// <param name="userName">Name of the user.</param>
        /// <param name="title">The title.</param>
        /// <param name="url">The URL.</param>
        /// <param name="mobileUrl">The mobile URL.</param>
        /// <param name="viewOrder">The view order.</param>
        /// <param name="description">The description.</param>
        /// <param name="target">The target.</param>
        public void UpdateLink(int moduleID, int itemID, string userName, string title, string url, string mobileUrl,
                               int viewOrder, string description, string target)
        {
            if (userName.Length < 1)
            {
                userName = "unknown";
            }

            // Create Instance of Connection and Command Object
            SqlConnection myConnection = Config.SqlConnectionString;
            SqlCommand myCommand = new SqlCommand("rb_UpdateLink", myConnection);

            // Mark the Command as a SPROC
            myCommand.CommandType = CommandType.StoredProcedure;

            // Add Parameters to SPROC
            SqlParameter parameterItemID = new SqlParameter("@ItemID", SqlDbType.Int, 4);
            parameterItemID.Value = itemID;
            myCommand.Parameters.Add(parameterItemID);

            SqlParameter parameterUserName = new SqlParameter("@UserName", SqlDbType.NVarChar, 100);
            parameterUserName.Value = userName;
            myCommand.Parameters.Add(parameterUserName);

            SqlParameter parameterTitle = new SqlParameter("@Title", SqlDbType.NVarChar, 100);
            parameterTitle.Value = title;
            myCommand.Parameters.Add(parameterTitle);

            SqlParameter parameterDescription = new SqlParameter("@Description", SqlDbType.NVarChar, 100);
            parameterDescription.Value = description;
            myCommand.Parameters.Add(parameterDescription);

            SqlParameter parameterUrl = new SqlParameter("@Url", SqlDbType.NVarChar, 800);
            parameterUrl.Value = url;
            myCommand.Parameters.Add(parameterUrl);

            SqlParameter parameterMobileUrl = new SqlParameter("@MobileUrl", SqlDbType.NVarChar, 250);
            parameterMobileUrl.Value = mobileUrl;
            myCommand.Parameters.Add(parameterMobileUrl);

            SqlParameter parameterViewOrder = new SqlParameter("@ViewOrder", SqlDbType.Int, 4);
            parameterViewOrder.Value = viewOrder;
            myCommand.Parameters.Add(parameterViewOrder);

            SqlParameter parameterTarget = new SqlParameter("@Target", SqlDbType.NVarChar, 10);
            parameterTarget.Value = target;
            myCommand.Parameters.Add(parameterTarget);

            myConnection.Open();
            try
            {
                myCommand.ExecuteNonQuery();
            }
            finally
            {
                myConnection.Close();
            }
        }
    }
}


text:
Check TypeScript sourcemaps are being generated correctly.

## Install and build

```
$ cd ts
$ npm install
$ npm run build
```

Then check the `build/TestEmitter.js` and `build/TestEmitter.js.map` sourcemap in the visualizer: http://sokra.github.io/source-map-visualization/

For comparison there is a js version that compiles with Babel:

```
$ cd js
$ npm install
$ npm run build
```


text:
START_ATF_NAMESPACE
    struct  DispHTMLLinkElement : IDispatch
    {
    };
END_ATF_NAMESPACE


text:
package com.twitter.zipkin.storage.cassandra

import com.twitter.cassie
import com.twitter.cassie._
import com.twitter.cassie.codecs.{Codec, LongCodec, Utf8Codec}
import com.twitter.conversions.time._
import com.twitter.finagle.stats.{DefaultStatsReceiver, StatsReceiver}
import com.twitter.util.{Future, FuturePool, Duration, Time}
import com.twitter.zipkin.Constants
import com.twitter.zipkin.common.Span
import com.twitter.zipkin.conversions.thrift._
import com.twitter.zipkin.gen.{Span => ThriftSpan}
import com.twitter.zipkin.storage.{TraceIdDuration, IndexedTraceId, SpanStore}
import com.twitter.zipkin.util.Util
import java.nio.ByteBuffer
import scala.collection.JavaConverters._

case class ZipkinColumnFamilyNames(
  traces: String = "Traces",
  serviceNames: String = "ServiceNames",
  spanNames: String = "SpanNames",
  serviceNameIndex: String = "ServiceNameIndex",
  serviceSpanNameIndex: String = "ServiceSpanNameIndex",
  annotationsIndex: String = "AnnotationsIndex",
  durationIndex: String = "DurationIndex")

object CassieSpanStoreDefaults {
  val KeyspaceName = "Zipkin"
  val ColumnFamilyNames = ZipkinColumnFamilyNames()
  val WriteConsistency = cassie.WriteConsistency.One
  val ReadConsistency = cassie.ReadConsistency.One
  val SpanTtl = 7.days
  val IndexTtl = 3.days
  val IndexBuckets = 10
  val MaxTraceCols = 100000
  val ReadBatchSize = 500
  val SpanCodec = new SnappyCodec(new ScroogeThriftCodec[ThriftSpan](ThriftSpan))
}

class CassieSpanStore(
  keyspace: Keyspace,
  stats: StatsReceiver = DefaultStatsReceiver.scope("CassieSpanStore"),
  cfs: ZipkinColumnFamilyNames = CassieSpanStoreDefaults.ColumnFamilyNames,
  writeConsistency: WriteConsistency = CassieSpanStoreDefaults.WriteConsistency,
  readConsistency: ReadConsistency = CassieSpanStoreDefaults.ReadConsistency,
  spanTtl: Duration = CassieSpanStoreDefaults.SpanTtl,
  indexTtl: Duration = CassieSpanStoreDefaults.IndexTtl,
  bucketsCount: Int = CassieSpanStoreDefaults.IndexBuckets,
  maxTraceCols: Int = CassieSpanStoreDefaults.MaxTraceCols,
  readBatchSize: Int = CassieSpanStoreDefaults.ReadBatchSize,
  spanCodec: Codec[ThriftSpan] = CassieSpanStoreDefaults.SpanCodec
) extends SpanStore {
  private[this] val ServiceNamesKey = "servicenames"
  private[this] val IndexDelimiter = ":"
  private[this] val IndexDelimiterBytes = IndexDelimiter.getBytes
  private[this] val SomeIndexTtl = Some(indexTtl)

  /**
   * Internal helper methods
   */
  private[this] def createSpanColumnName(span: Span): String =
    "%d_%d".format(span.id, span.annotations.hashCode)

  private[this] def newBCF[N, V](cf: String, nCodec: Codec[N], vCodec: Codec[V]) =
    BucketedColumnFamily(keyspace, cf, nCodec, vCodec, writeConsistency, readConsistency)

  private[this] def idxCol[Name, Value](n: Name, v: Value): Column[Name, Value] =
    Column[Name, Value](n, v, None, SomeIndexTtl)

  private[this] def nameKey(serviceName: String, spanName: Option[String]): String =
    (serviceName + spanName.map("." + _).getOrElse("")).toLowerCase

  private[this] def annotationKey(serviceName: String, annotation: String, value: Option[ByteBuffer]): ByteBuffer = {
    ByteBuffer.wrap(
      serviceName.getBytes ++ IndexDelimiterBytes ++ annotation.getBytes ++
      value.map { v => IndexDelimiterBytes ++ Util.getArrayFromBuffer(v) }.getOrElse(Array()))
  }

  private[this] def colToIndexedTraceId(cols: Seq[Column[Long, Long]]): Seq[IndexedTraceId] =
    cols map { c => IndexedTraceId(traceId = c.value, timestamp = c.name) }

  /**
   * Column Families
   * and type aliases to their batch types
   */
  private type BatchTraces = BatchMutationBuilder[Long, String, Span]
  private[this] val Traces = keyspace
    .columnFamily(cfs.traces, LongCodec, Utf8Codec, spanCodec)
    .consistency(writeConsistency)
    .consistency(readConsistency)

  private type BatchServiceNames = BatchMutationBuilder[String, String, String]
  private[this] val ServiceNames = new StringBucketedColumnFamily(
    newBCF(cfs.serviceNames, Utf8Codec, Utf8Codec), bucketsCount)

  private type BatchSpanNames = BatchMutationBuilder[String, String, String]
  private[this] val SpanNames = new StringBucketedColumnFamily(
    newBCF(cfs.spanNames, Utf8Codec, Utf8Codec), bucketsCount)

  private type BatchServiceNameIndex = BatchMutationBuilder[String, Long, Long]
  private[this] val ServiceNameIndex = new StringBucketedColumnFamily(
    newBCF(cfs.serviceNameIndex, LongCodec, LongCodec), bucketsCount)

  private type BatchServiceSpanNameIndex = BatchMutationBuilder[String, Long, Long]
  private[this] val ServiceSpanNameIndex = keyspace
    .columnFamily(cfs.serviceSpanNameIndex, Utf8Codec, LongCodec, LongCodec)
    .consistency(writeConsistency)
    .consistency(readConsistency)

  private type BatchAnnotationsIndex = BatchMutationBuilder[ByteBuffer, Long, Long]
  private[this] val AnnotationsIndex = new ByteBufferBucketedColumnFamily(
    newBCF(cfs.annotationsIndex, LongCodec, LongCodec), bucketsCount)

  private type BatchDurationIndex = BatchMutationBuilder[Long, Long, String]
  private[this] val DurationIndex = keyspace
    .columnFamily(cfs.durationIndex, LongCodec, LongCodec, Utf8Codec)
    .consistency(writeConsistency)
    .consistency(readConsistency)

  /**
   * Stats
   */
  private[this] val SpansStats = stats.scope("spans")
  private[this] val SpansStoredCounter = SpansStats.counter("stored")
  private[this] val SpansIndexedCounter = SpansStats.counter("indexed")
  private[this] val IndexStats = stats.scope("index")
  private[this] val IndexServiceNameCounter = IndexStats.counter("serviceName")
  private[this] val IndexServiceNameNoNameCounter = IndexStats.scope("serviceName").counter("noName")
  private[this] val IndexSpanNameCounter = IndexStats.scope("serviceName").counter("spanName")
  private[this] val IndexSpanNameNoNameCounter = IndexStats.scope("serviceName").scope("spanName").counter("noName")
  private[this] val IndexTraceStats = IndexStats.scope("trace")
  private[this] val IndexTraceNoLastAnnotationCounter = IndexTraceStats.counter("noLastAnnotation")
  private[this] val IndexTraceByServiceNameCounter = IndexTraceStats.counter("serviceName")
  private[this] val IndexTraceBySpanNameCounter = IndexTraceStats.counter("spanName")
  private[this] val IndexAnnotationCounter = IndexStats.scope("annotation").counter("standard")
  private[this] val IndexAnnotationNoLastAnnotationCounter = IndexStats.scope("annotation").counter("noLastAnnotation")
  private[this] val IndexBinaryAnnotationCounter = IndexStats.scope("annotation").counter("binary")
  private[this] val IndexDurationCounter = IndexStats.counter("duration")
  private[this] val QueryStats = stats.scope("query")
  private[this] val QueryGetTtlCounter = QueryStats.counter("getTimeToLive")
  private[this] val QueryTracesExistStat = QueryStats.stat("tracesExist")
  private[this] val QueryGetSpansByTraceIdsStat = QueryStats.stat("getSpansByTraceIds")
  private[this] val QueryGetSpansByTraceIdsTooBigCounter = QueryStats.scope("getSpansByTraceIds").counter("tooBig")
  private[this] val QueryGetServiceNamesCounter = QueryStats.counter("getServiceNames")
  private[this] val QueryGetSpanNamesCounter = QueryStats.counter("getSpanNames")
  private[this] val QueryGetTraceIdsByNameCounter = QueryStats.counter("getTraceIdsByName")
  private[this] val QueryGetTraceIdsByAnnotationCounter = QueryStats.counter("getTraceIdsByAnnotation")
  private[this] val QueryGetTracesDurationStat = QueryStats.stat("getTracesDuration")

  /**
   * Internal indexing helpers
   */
  private[this] def indexServiceName(idx: BatchServiceNames, span: Span) {
    IndexServiceNameCounter.incr()
    span.serviceNames foreach {
      case "" =>
        IndexServiceNameNoNameCounter.incr()
      case s =>
        idx.insert(ServiceNamesKey, idxCol(s.toLowerCase, ""))
    }
  }

  private[this] def indexSpanNameByService(idx: BatchSpanNames, span: Span) {
    if (span.name == "") {
      IndexSpanNameNoNameCounter.incr()
    } else {
      IndexSpanNameCounter.incr()
      val spanNameCol = idxCol(span.name.toLowerCase, "")
      span.serviceNames foreach { idx.insert(_, spanNameCol) }
    }
  }

  private[this] def indexTraceIdByName(
    serviceNameIdx: BatchServiceNameIndex,
    serviceSpanNameIdx: BatchServiceSpanNameIndex,
    span: Span
  ) {
    if (span.lastAnnotation.isEmpty)
      IndexTraceNoLastAnnotationCounter.incr()

    span.lastAnnotation foreach { lastAnnotation =>
      val timestamp = lastAnnotation.timestamp
      val serviceNames = span.serviceNames

      serviceNames foreach { serviceName =>
        val col = idxCol(timestamp, span.traceId)

        IndexTraceByServiceNameCounter.incr()
        serviceNameIdx.insert(nameKey(serviceName, None), col)

        if (span.name != "") {
          IndexTraceBySpanNameCounter.incr()
          serviceSpanNameIdx.insert(nameKey(serviceName, Some(span.name)), col)
        }
      }
    }
  }

  private[this] def indexByAnnotations(idx: BatchAnnotationsIndex, span: Span) {
    if (span.lastAnnotation.isEmpty)
      IndexAnnotationNoLastAnnotationCounter.incr()

    span.lastAnnotation foreach { lastAnnotation =>
      val timestamp = lastAnnotation.timestamp

      // skip core annotations since that query can be done by service name/span name anyway
      span.annotations
        .filter { a => !Constants.CoreAnnotations.contains(a.value) }
        .groupBy(_.value)
        .foreach { case (_, as) =>
          val a = as.min
          a.host foreach { endpoint =>
            IndexAnnotationCounter.incr()
            idx.insert(
              annotationKey(endpoint.serviceName, a.value, None),
              idxCol(a.timestamp, span.traceId))
          }
        }

      span.binaryAnnotations foreach { ba =>
        ba.host foreach { endpoint =>
          IndexBinaryAnnotationCounter.incr()
          val col = idxCol(timestamp, span.traceId)
          idx.insert(annotationKey(endpoint.serviceName, ba.key, Some(ba.value)), col)
          idx.insert(annotationKey(endpoint.serviceName, ba.key, None), col)
        }
      }
    }
  }

  private[this] def indexSpanDuration(idx: BatchDurationIndex, span: Span) {
    Seq(span.firstAnnotation, span.lastAnnotation).flatten foreach { a =>
      IndexDurationCounter.incr()
      idx.insert(span.traceId, idxCol(a.timestamp, ""))
    }
  }

  private[this] def getSpansByTraceIds(traceIds: Seq[Long], count: Int): Future[Seq[Seq[Span]]] = {
    val results = traceIds.grouped(readBatchSize) map { idBatch =>
      Traces.multigetRows(idBatch.toSet.asJava, None, None, Order.Normal, count) map { rowSet =>
        val rows = rowSet.asScala
        idBatch flatMap { id =>
          rows(id).asScala match {
            case cols if cols.isEmpty =>
              None

            case cols if cols.size > maxTraceCols =>
              QueryGetSpansByTraceIdsTooBigCounter.incr()
              None

            case cols =>
              Some(cols.toSeq map { case (_, col) => col.value.toSpan })
          }
        }
      }
    }

    Future.collect(results.toSeq).map(_.flatten)
  }

  /**
   * API Implementation
   */
  override def close(deadline: Time): Future[Unit] =
    FuturePool.unboundedPool { keyspace.close() }

  // TODO: break these into smaller batches?
  def apply(spans: Seq[Span]): Future[Unit] = {
    SpansStoredCounter.incr(spans.size)

    val traces = Traces.batch()
    val serviceNames = ServiceNames.batch()
    val spanNames = SpanNames.batch()
    val serviceNameIdx = ServiceNameIndex.batch()
    val serviceSpanNameIdx = ServiceSpanNameIndex.batch()
    val annotationsIdx = AnnotationsIndex.batch()
    val durationIdx = DurationIndex.batch()

    spans foreach { span =>
      traces.insert(span.traceId, Column[String, ThriftSpan](createSpanColumnName(span), span.toThrift, None, Some(spanTtl)))
      if (shouldIndex(span)) {
        SpansIndexedCounter.incr()
        indexServiceName(serviceNames, span)
        indexSpanNameByService(spanNames, span)
        indexTraceIdByName(serviceNameIdx, serviceSpanNameIdx, span)
        indexByAnnotations(annotationsIdx, span)
        indexSpanDuration(durationIdx, span)
      }
    }

    Future.collect(Seq(
      traces,
      serviceNames,
      spanNames,
      serviceNameIdx,
      serviceSpanNameIdx,
      annotationsIdx,
      durationIdx
    ).map(_.execute())).unit
  }

  def setTimeToLive(traceId: Long, ttl: Duration): Future[Unit] = {
    Traces.getRow(traceId) flatMap { row =>
      val traces = Traces.batch()
      row.values.asScala foreach { col =>
        traces.insert(traceId, col.copy(timestamp = None, ttl = Some(ttl)))
      }
      traces.execute().unit
    }
  }

  def getTimeToLive(traceId: Long): Future[Duration] = {
    QueryGetTtlCounter.incr()
    Traces.getRow(traceId) flatMap { row =>
      val ttl = row.values.asScala.foldLeft(Int.MaxValue) { (ttl, col) =>
        math.min(ttl, col.ttl.map(_.inSeconds).getOrElse(Int.MaxValue))
      }

      if (ttl == Int.MaxValue)
        Future.exception(new IllegalArgumentException("The trace " + traceId + " does not have any ttl set!"))
      else
        Future.value(ttl.seconds)
    }
  }

  def tracesExist(traceIds: Seq[Long]): Future[Set[Long]] = {
    QueryTracesExistStat.add(traceIds.size)
    getSpansByTraceIds(traceIds, 1) map {
      _.flatMap(_.headOption.map(_.traceId)).toSet
    }
  }

  def getSpansByTraceId(traceId: Long): Future[Seq[Span]] =
    getSpansByTraceIds(Seq(traceId)).map(_.head)

  def getSpansByTraceIds(traceIds: Seq[Long]): Future[Seq[Seq[Span]]] = {
    QueryGetSpansByTraceIdsStat.add(traceIds.size)
    getSpansByTraceIds(traceIds, maxTraceCols)
  }

  def getAllServiceNames: Future[Set[String]] = {
    QueryGetServiceNamesCounter.incr()
    ServiceNames.getRow(ServiceNamesKey).map(_.values.asScala.map(_.name).toSet)
  }

  def getSpanNames(service: String): Future[Set[String]] = {
    QueryGetSpanNamesCounter.incr()
    SpanNames.getRow(service).map(_.values.asScala.map(_.name).toSet)
  }

  def getTraceIdsByName(
    serviceName: String,
    spanName: Option[String],
    endTs: Long,
    limit: Int
  ): Future[Seq[IndexedTraceId]] = {
    QueryGetTraceIdsByNameCounter.incr()
    val key = nameKey(serviceName, spanName)

    // if we have a span name, look up in the service + span name index
    // if not, look up by service name only
    val idx: ColumnFamily[String, Long, Long] =
      spanName.map(_ => ServiceSpanNameIndex).getOrElse(ServiceNameIndex)
    // TODO: endTs seems wrong here
    idx.getRowSlice(key, Some(endTs), None, limit, Order.Reversed) map colToIndexedTraceId
  }

  def getTraceIdsByAnnotation(
    serviceName: String,
    annotation: String,
    value: Option[ByteBuffer],
    endTs: Long,
    limit: Int
  ): Future[Seq[IndexedTraceId]] = {
    QueryGetTraceIdsByAnnotationCounter.incr()
    val key = annotationKey(serviceName, annotation, value)
    AnnotationsIndex.getRowSlice(key, None, Some(endTs), limit, Order.Reversed) map colToIndexedTraceId
  }

  def getTracesDuration(traceIds: Seq[Long]): Future[Seq[TraceIdDuration]] = {
    QueryGetTracesDurationStat.add(traceIds.size)

    val traceIdSet = traceIds.toSet.asJava

    Future.collect(Seq(
      DurationIndex.multigetRows(traceIdSet, None, None, Order.Normal, 1),
      DurationIndex.multigetRows(traceIdSet, None, None, Order.Reversed, 1)
    )) map { results =>
      val Seq(startRows, endRows) = results map { rows =>
        rows.asScala.toSeq map { case (traceId, cols) =>
          cols.asScala.headOption map { case (_, col) => (traceId, col.name) }
        }
      }
      startRows zip(endRows) collect {
        case (Some((startId, startTs)), Some((endId, endTs))) if (startId == endId) =>
          TraceIdDuration(endId, endTs - startTs, startTs)
      }
    }
  }
}