text:
import array
import itertools
import socket
import struct

class ScratchError(Exception): pass
class ScratchConnectionError(ScratchError): pass

class Scratch(object):

    prefix_len = 4
    broadcast_prefix_len = prefix_len + len('broadcast ')
    sensorupdate_prefix_len = prefix_len + len('sensor-update ')

    msg_types = set(['broadcast', 'sensor-update'])

    def __init__(self, host='localhost', port=42001):
        self.host = host
        self.port = port
        self.socket = None
        self.connected = False
        self.connect()

    def __repr__(self):
        return "Scratch(host=%r, port=%r)" % (self.host, self.port)

    def _pack(self, msg):
        """
        Packages msg according to Scratch message specification (encodes and
        appends length prefix to msg). Credit to chalkmarrow from the
        scratch.mit.edu forums for the prefix encoding code.
        """
        n = len(msg)
        a = array.array('c')
        a.append(chr((n >> 24) & 0xFF))
        a.append(chr((n >> 16) & 0xFF))
        a.append(chr((n >>  8) & 0xFF))
        a.append(chr(n & 0xFF))
        return a.tostring() + msg

    def _extract_len(self, prefix):
        """
        Extracts the length of a Scratch message from the given message prefix.
        """
        return struct.unpack(">L", prefix)[0]

    def _get_type(self, s):
        """
        Converts a string from Scratch to its proper type in Python. Expects a
        string with its delimiting quotes in place. Returns either a string,
        int or float.
        """
        # TODO: what if the number is bigger than an int or float?
        if s.startswith('"') and s.endswith('"'):
            return s[1:-1]
        elif s.find('.') != -1:
            return float(s)
        else:
            return int(s)

    def _escape(self, msg):
        """
        Escapes double quotes by adding another double quote as per the Scratch
        protocol. Expects a string without its delimiting quotes. Returns a new
        escaped string.
        """
        escaped = ''
        for c in msg:
            escaped += c
            if c == '"':
                escaped += '"'
        return escaped

    def _unescape(self, msg):
        """
        Removes double quotes that were used to escape double quotes. Expects
        a string without its delimiting quotes, or a number. Returns a new
        unescaped string.
        """
        if isinstance(msg, (int, float, long)):
            return msg

        unescaped = ''
        i = 0
        while i < len(msg):
            unescaped += msg[i]
            if msg[i] == '"':
                i+=1
            i+=1
        return unescaped

    def _is_msg(self, msg):
        """
        Returns True if message is a proper Scratch message, else return False.
        """
        if not msg or len(msg) < self.prefix_len:
            return False
        length = self._extract_len(msg[:self.prefix_len])
        msg_type = msg[self.prefix_len:].split(' ', 1)[0]
        if length == len(msg[self.prefix_len:]) and msg_type in self.msg_types:
            return True
        return False

    def _parse_broadcast(self, msg):
        """
        Given a broacast message, returns the message that was broadcast.
        """
        # get message, remove surrounding quotes, and unescape
        return self._unescape(self._get_type(msg[self.broadcast_prefix_len:]))

    def _parse_sensorupdate(self, msg):
        """
        Given a sensor-update message, returns the sensors/variables that were
        updated as a dict that maps sensors/variables to their updated values.
        """
        update = msg[self.sensorupdate_prefix_len:]
        parsed = [] # each element is either a sensor (key) or a sensor value
        curr_seg = '' # current segment (i.e. key or value) being formed
        numq = 0 # number of double quotes in current segment
        for seg in update.split(' ')[:-1]: # last char in update is a space
            numq += seg.count('"')
            curr_seg += seg
            # even number of quotes means we've finished parsing a segment
            if numq % 2 == 0:
                parsed.append(curr_seg)
                curr_seg = ''
                numq = 0
            else: # segment has a space inside, so add back it in
                curr_seg += ' '
        unescaped = [self._unescape(self._get_type(x)) for x in parsed]
        # combine into a dict using iterators (both elements in the list
        # inputted to izip have a reference to the same iterator). even
        # elements are keys, odd are values
        return dict(itertools.izip(*[iter(unescaped)]*2))

    def _parse(self, msg):
        """
        Parses a Scratch message and returns a tuple with the first element
        as the message type, and the second element as the message payload. The
        payload for a 'broadcast' message is a string, and the payload for a
        'sensor-update' message is a dict whose keys are variables, and values
        are updated variable values. Returns None if msg is not a message.
        """
        if not self._is_msg(msg):
            return None
        msg_type = msg[self.prefix_len:].split(' ')[0]
        if msg_type == 'broadcast':
            return ('broadcast', self._parse_broadcast(msg))
        else:
            return ('sensor-update', self._parse_sensorupdate(msg))

    def _write(self, data):
        """
        Writes string data out to Scratch
        """
        total_sent = 0
        length = len(data)
        while total_sent < length:
            try:
                sent = self.socket.send(data[total_sent:])
            except socket.error as (err, msg):
                self.connected = False
                raise ScratchError("[Errno %d] %s" % (err, msg))
            if sent == 0:
                self.connected = False
                raise ScratchConnectionError("Connection broken")
            total_sent += sent

    def _send(self, data):
        """
        Sends a message to Scratch
        """
        self._write(self._pack(data))

    def _read(self, size):
        """
        Reads size number of bytes from Scratch and returns data as a string
        """
        data = ''
        while len(data) < size:
            try:
                chunk = self.socket.recv(size-len(data))
            except socket.error as (err, msg):
                self.connected = False
                raise ScratchError("[Errno %d] %s" % (err, msg))
            if chunk == '':
                self.connected = False
                raise ScratchConnectionError("Connection broken")
            data += chunk
        return data

    def _recv(self):
        """
        Receives and returns a message from Scratch
        """
        prefix = self._read(self.prefix_len)
        msg = self._read(self._extract_len(prefix))
        return prefix + msg

    def connect(self):
        """
        Connects to Scratch.
        """
        self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        try:
            self.socket.connect((self.host, self.port))
        except socket.error as (err, msg):
            self.connected = False
            raise ScratchError("[Errno %d] %s" % (err, msg))
        self.connected = True

    def disconnect(self):
        """
        Closes connection to Scratch
        """
        try: # connection may already be disconnected, so catch exceptions
            self.socket.shutdown(socket.SHUT_RDWR) # a proper disconnect
        except socket.error:
            pass
        self.socket.close()
        self.connected = False

    def sensorupdate(self, data):
        """
        Given a dict of sensors and values, updates those sensors with the
        values in Scratch.
        """
        if not isinstance(data, dict):
            raise TypeError('Expected a dict')
        msg = 'sensor-update '
        for key in data.keys():
            msg += '"%s" "%s" ' % (self._escape(str(key)),
                                    self._escape(str(data[key])))
        self._send(msg)

    def broadcast(self, msg):
        """
        Broadcasts msg to Scratch. msg can be a single message or an iterable
        (list, tuple, set, generator, etc.) of messages.
        """
        if getattr(msg, '__iter__', False): # iterable
            for m in msg:
                self._send('broadcast "%s"' % self._escape(str(m)))
        else: # probably a string or number
            self._send('broadcast "%s"' % self._escape(str(msg)))

    def receive(self):
        """
        Receives broadcasts and sensor updates from Scratch. Returns a tuple
        with the first element as the message type and the second element
        as the message payload. broadcast messages have a string as payload,
        and the sensor-update messages have a dict as payload. Returns None if
        message received could not be parsed. Raises exceptions on connection
        errors.
        """
        return self._parse(self._recv())


text:
        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.1/css/bootstrap.min.css">

NCGA: Summary Info for Representative Jason Saine (R) - District 97

Sponsored Bills (51 total)

Bill Keywords

Co-Sponsors

redpajama_set_name: RedPajamaGithub


text:
from __future__ import division

from six import python_2_unicode_compatible
from . import numbertheory

@python_2_unicode_compatible
class CurveFp(object):
  """Elliptic Curve over the field of integers modulo a prime."""
  def __init__(self, p, a, b):
    """The curve of points satisfying y^2 = x^3 + a*x + b (mod p)."""
    self.__p = p
    self.__a = a
    self.__b = b

  def p(self):
    return self.__p

  def a(self):
    return self.__a

  def b(self):
    return self.__b

  def contains_point(self, x, y):
    """Is the point (x,y) on this curve?"""
    return (y * y - (x * x * x + self.__a * x + self.__b)) % self.__p == 0

  def __str__(self):
    return "CurveFp(p=%d, a=%d, b=%d)" % (self.__p, self.__a, self.__b)

class Point(object):
  """A point on an elliptic curve. Altering x and y is forbidding,
     but they can be read by the x() and y() methods."""
  def __init__(self, curve, x, y, order=None):
    """curve, x, y, order; order (optional) is the order of this point."""
    self.__curve = curve
    self.__x = x
    self.__y = y
    self.__order = order
    # self.curve is allowed to be None only for INFINITY:
    if self.__curve:
      assert self.__curve.contains_point(x, y)
    if order:
      assert self * order == INFINITY

  def __eq__(self, other):
    """Return True if the points are identical, False otherwise."""
    if self.__curve == other.__curve \
       and self.__x == other.__x \
       and self.__y == other.__y:
      return True
    else:
      return False

  def __add__(self, other):
    """Add one point to another point."""

    # X9.62 B.3:

    if other == INFINITY:
      return self
    if self == INFINITY:
      return other
    assert self.__curve == other.__curve
    if self.__x == other.__x:
      if (self.__y + other.__y) % self.__curve.p() == 0:
        return INFINITY
      else:
        return self.double()

    p = self.__curve.p()

    l = ((other.__y - self.__y) * \
         numbertheory.inverse_mod(other.__x - self.__x, p)) % p

    x3 = (l * l - self.__x - other.__x) % p
    y3 = (l * (self.__x - x3) - self.__y) % p

    return Point(self.__curve, x3, y3)

  def __mul__(self, other):
    """Multiply a point by an integer."""

    def leftmost_bit(x):
      assert x > 0
      result = 1
      while result <= x:
        result = 2 * result
      return result // 2

    e = other
    if self.__order:
      e = e % self.__order
    if e == 0:
      return INFINITY
    if self == INFINITY:
      return INFINITY
    assert e > 0

    # From X9.62 D.3.2:

    e3 = 3 * e
    negative_self = Point(self.__curve, self.__x, -self.__y, self.__order)
    i = leftmost_bit(e3) // 2
    result = self
    # print_("Multiplying %s by %d (e3 = %d):" % (self, other, e3))
    while i > 1:
      result = result.double()
      if (e3 & i) != 0 and (e & i) == 0:
        result = result + self
      if (e3 & i) == 0 and (e & i) != 0:
        result = result + negative_self
      # print_(". . . i = %d, result = %s" % ( i, result ))
      i = i // 2

    return result

  def __rmul__(self, other):
    """Multiply a point by an integer."""

    return self * other

  def __str__(self):
    if self == INFINITY:
      return "infinity"
    return "(%d,%d)" % (self.__x, self.__y)

  def double(self):
    """Return a new point that is twice the old."""

    if self == INFINITY:
      return INFINITY

    # X9.62 B.3:

    p = self.__curve.p()
    a = self.__curve.a()

    l = ((3 * self.__x * self.__x + a) * \
         numbertheory.inverse_mod(2 * self.__y, p)) % p

    x3 = (l * l - 2 * self.__x) % p
    y3 = (l * (self.__x - x3) - self.__y) % p

    return Point(self.__curve, x3, y3)

  def x(self):
    return self.__x

  def y(self):
    return self.__y

  def curve(self):
    return self.__curve

  def order(self):
    return self.__order

# This one point is the Point At Infinity for all purposes:
INFINITY = Point(None, None, None)


text:
Pythonic Interface for AWS boto3 that gives you autocomplete on all AWS services

The code is not to be imported. you can only use it as a typehint for autocomplete in pycharm.

This package will minimize the time you have to look for AWS documentation online. You shouldn't leave your coding environment.

# Screenshots
## Ctrl+Space

![Ctrl+Space Autocomplete Image](https://github.com/gehadshaat/pyboto3/blob/master/img/autocomplete.png)

## Ctrl+Q

![Ctrl+Q Documentation](https://github.com/gehadshaat/pyboto3/blob/master/img/documentation.png)

# Installation
```
pip install pyboto3
```

# Usage
```python
import boto3
s3 = boto3.client('s3')
""" :type : pyboto3.s3 """
# s3. -> will give you autocomplete for s3 methods in pycharm
```
enjoy autocomplete and navigate to class to read documentation from S3 class code

# Update services to latest version
* Clone repo
* Install virtual environment
```
cd <repo source>
virtualenv .venv
source .venv/bin/activate
pip install -r requirements.txt
```
* Run boto3_interface_generator
```
cd pyboto3
python boto3_interface_generator.py
```
* Add new & modified files to git
# Release Instructions
```
python setup.py sdist
twine upload dist/*
```

# Contributing

We need your help! The code needs work and testing to make it friendly with python 3 and other systems. Feel free to test, commit and push changes!

# Issues
The package have been tested on Python 2.7 only


text:
import Ember from 'ember';

export default Ember.Controller.extend({
  queryParams: ['filename'],
  filename: null
});


text:
<?xml version="1.0" encoding="UTF-8"?>
<tei xmlns="http://www.tei-c.org/ns/1.0" xmlns:xlink="http://www.w3.org/1999/xlink" xmlns:mml="http://www.w3.org/1998/Math/MathML">
	<teiHeader>
		<fileDesc>
			<sourceDesc>
				<biblStruct>
					<analytic>
						<author>

						<affiliation>
							<marker>a</marker>
							<orgName type="department">Center for Advanced Biomaterials and Tissue Engineering</orgName>,
							<orgName type="department">Department of Chemical Engineering</orgName>,
							<orgName type="institution">Drexel University</orgName>,
							<address>
								<addrLine>Room # 383</addrLine>,
							<lb/>
								<addrLine>CAT Building</addrLine>,
								<addrLine>3141 Chestnut Street</addrLine>,
								<settlement>Philadelphia</settlement>,
								<region>PA</region>
								<postCode>19104</postCode>,
								<country>USA</country>
							<lb/>
							</address>
						</affiliation>
						<affiliation>
							<marker>b</marker>
							<orgName type="department">Department of Orthopaedic Surgery</orgName>,
							<orgName type="institution">Thomas Jefferson University</orgName>,
							<address>
								<settlement>Philadelphia</settlement>,
								<region>PA</region>,
								<country>USA</country>
							<lb/>
							</address>
						</affiliation>
						<affiliation>
							<marker>c</marker>
							<orgName type="department">Department of Orthopaedic Surgery</orgName>,
							<orgName type="institution">Drexel University</orgName>,
							<orgName type="department">College of Medicine</orgName>,
							<address>
								<settlement>Philadelphia</settlement>,
								<region>PA</region>,
								<country>USA</country>
							</address>
						</affiliation>

						</author>
					</analytic>
				</biblStruct>
			</sourceDesc>
		</fileDesc>
	</teiHeader>
</tei>


text:
<?xml version="1.0" encoding="UTF-8"?>

<recipeml version="0.5">
  <recipe>
    <head>
      <title>Artichoke Puffs</title>
      <categories>
        <cat>Vegetables</cat></categories>
      <yield>1</yield></head>
    <ingredients>
      <ing>
        <amt>
          <qty>1</qty>
          <unit>cup</unit></amt>
        <item>Skim milk</item></ing>
      <ing>
        <amt>
          <qty>2</qty>
          <unit>tablespoons</unit></amt>
        <item>Vegetable oil</item></ing>
      <ing>
        <amt>
          <qty>1/4</qty>
          <unit>teaspoons</unit></amt>
        <item>Salt</item></ing>
      <ing>
        <amt>
          <qty>1</qty>
          <unit>cup</unit></amt>
        <item>Flour</item></ing>
      <ing>
        <amt>
          <qty>2</qty>
          <unit/></amt>
        <item>Eggs</item></ing>
      <ing>
        <amt>
          <qty>3</qty>
          <unit/></amt>
        <item>Egg whites</item></ing>
      <ing>
        <amt>
          <qty/>
          <unit/></amt>
        <item>Artichoke Filling</item></ing></ingredients>
    <directions>
      <step>  Preheat oven to 450. Coat baking sheets with nonstick cooking spray.
  Heat milk, oil & salt in medium sized heavy saucepan. As soon as mix
  comes to a boil, remove from heat. Immediately stir in flour with
  wooden spoon; beat until dough pulls away from sides of pan. Bet in
  eggs & whites, one at a time, beating after each addition, until mix
  is smooth & glossy. Place mounds of dough ( about the size of a large
  walnut) on sheets, leaving 1 1/2" between. Flatten with moistened
  fingertips to 1/2" thickness. Bake in 450 oven for 10 minutes. Reduce
  temp to 400. Bake 20 minutes or more until puffed, golden & lightly
  crusty. Remove puffs from sheets to rack to cool. To fill, cut tops
  from puffs. Spoon in Artichoke filling. Replace tops. To heat, place
  puffs on sheet. Cover lightly with foil. Bake in preheated 375 oven
  10 minutes. The stuffed puffs can be frozen. To reheat, place frozen
  on baking sheets. Cover lightly with foil. Bake in preheated 375 oven
  for 20 minutes.

  File ftp://ftp.idiscover.co.uk/pub/food/mealmaster/recipes/mmkah001.zip

</step></directions></recipe></recipeml>


text:
set -e
set -u

DIR=$1

#if ! dpkg -l ceph ; then
# wget -q -O- 'https://ceph.com/git/?p=ceph.git;a=blob_plain;f=keys/release.asc' | sudo apt-key add -
# echo deb http://ceph.com/debian-dumpling/ $(lsb_release -sc) main | sudo tee /etc/apt/sources.list.d/ceph.list
# sudo apt-get update
# sudo apt-get --yes install ceph ceph-common
#fi

# get rid of process and directories leftovers
pkill ceph-mon || true
pkill ceph-osd || true
pkill ceph-mds || true
rm -fr $DIR

# cluster wide parameters
mkdir -p ${DIR}/log
cat >> $DIR/ceph.conf <<EOF
[global]
fsid = $(uuidgen)
osd crush chooseleaf type = 0
run dir = ${DIR}/run
auth cluster required = none
auth service required = none
auth client required = none
osd pool default size = 1
EOF
export CEPH_ARGS="--conf ${DIR}/ceph.conf"

# single monitor
MON_DATA=${DIR}/mon
mkdir -p $MON_DATA

cat >> $DIR/ceph.conf <<EOF
[mon.0]
log file = ${DIR}/log/mon.log
chdir = ""
mon cluster log file = ${DIR}/log/mon-cluster.log
mon data = ${MON_DATA}
mon addr = 127.0.0.1
EOF

ceph-mon --id 0 --mkfs --keyring /dev/null
touch ${MON_DATA}/keyring
ceph-mon --id 0

# single osd
OSD_DATA=${DIR}/osd
mkdir ${OSD_DATA}

cat >> $DIR/ceph.conf <<EOF
[osd.0]
log file = ${DIR}/log/osd.log
chdir = ""
osd data = ${OSD_DATA}
osd journal = ${OSD_DATA}.journal
osd journal size = 100
osd objectstore = memstore
EOF

OSD_ID=$(ceph osd create)
ceph osd crush add osd.${OSD_ID} 1 root=default host=localhost
ceph-osd --id ${OSD_ID} --mkjournal --mkfs
ceph-osd --id ${OSD_ID}

# we don't need mds since we are not using cephfs - right?

# check that it works
rados --pool rbd put group /etc/group
rados --pool rbd get group ${DIR}/group
diff /etc/group ${DIR}/group
ceph osd tree

export CEPH_CONF="${DIR}/ceph.conf"


text:
<?php

require_once('config.php');
require_once(PATH . CLASSES . 'alkaline.php');

$alkaline = new Alkaline;
$alkaline->recordStat('set');

$id = $alkaline->findID($_GET['id']);
if(!$id){ $alkaline->addError('No set was found.', 'Try searching for the set you were seeking.', null, null, 404); }

$set = new Set($id);
$set = @$set->sets[0];
if(!$set){ $alkaline->addError('No set was found.', 'Try searching for the set you were seeking.', null, null, 404); }

$set['set_created'] = $alkaline->formatTime($set['set_created']);
$set['set_modified'] = $alkaline->formatTime($set['set_modified']);

$image_ids = new Find('images');
$image_ids->page(null, 0);
$image_ids->published();
$image_ids->privacy('public');
$image_ids->sets(intval($set['set_id']));
$image_ids->find();

$images = new Image($image_ids);
$images->formatTime();
$images->getSizes('small');
$images->getEXIF();
$images->getTags();
$images->getRights();

$header = new Canvas;
$header->load('header');
$header->setTitle(@$set['set_title']);
$header->assign('Canonical', $set['set_uri']);
$header->display();

$content = new Canvas;
$content->load('set');
$content->loop($images);
$content->assignArray($set);
$content->display();

$footer = new Canvas;
$footer->load('footer');
$footer->display();

?>


text:
raii_resource
=============

Can std::unique_ptr be better?


text:
<?php

// Search for an autoloader

// in phar environment
if (extension_loaded('phar') && method_exists('Phar', 'running') && file_exists($file = Phar::running() . '/vendor/autoload.php')) {
    $loader = require_once $file;
} elseif (file_exists($file = __DIR__ . '/../../autoload.php')) {

    // Composer standard location
    $loader = require_once $file;
    $loader->add('Liip\RMT\Tests', __DIR__ . '/test');
    $loader->add('Liip', __DIR__ . '/src');
} elseif (file_exists($file = __DIR__ . '/vendor/autoload.php')) {

    // Composer when on RMT standalone install (used in travis.ci)
    $loader = require $file;
    $loader->add('Liip\RMT\Tests', __DIR__.'/test');
    $loader->add('Liip', __DIR__.'/src');
} elseif (file_exists($file = __DIR__ . '/../symfony/src/Symfony/Component/ClassLoader/UniversalClassLoader.php')) {

    // Symfony 2.0
    require_once $file;
    $loader = new \Symfony\Component\ClassLoader\UniversalClassLoader();
    $loader->registerNamespaces(array(
        'Liip' => array(__DIR__ . '/src', __DIR__ . '/test'),
        'Symfony' => __DIR__ . '/../symfony/src',
    ));
    $loader->register();
} else {
    throw new \Exception("Unable to find the an autoloader");
}


text:
A command-line tool for fast, parallel mass (bulk) uploading blobs to your Azure storage.

### Downloads

 * C#
   * [azupload-csharp](http://www.mediafire.com/download/n5tt0nhdaiq9za5/azupload-csharp-20140908.7z)
   * [Microsoft .NET Framework 4.5](http://www.microsoft.com/en-us/download/details.aspx?id=30653) or [Mono MRE 3.6](http://www.mono-project.com/download/)
 * Java
   * [azupload-java](http://www.mediafire.com/download/q2jrn5weoxlf0ys/azupload-java-20140829.7z)
   * [JRE 8](http://www.oracle.com/technetwork/java/javase/downloads/index.html)

### Usage

 * C#
   * open *azupload.exe.config* and fix your connection string accordingly
   * `azupload.exe --upload <sourceDir> <azureContainer> [ttlMinutes]`

 * Java
   * open *app.properties* and fix your connection string accordingly
   * `java -jar azupload.jar --upload <threadCount> <sourceDir> <azureContainer> [containerPrefix]`

**WARNING**: if the files you try to upload already exist in the container, *azupload* WILL overwrite anything without asking, so use carefully!

### Building

 * C#
   * [Visual Studio 2013](http://www.visualstudio.com/downloads/download-visual-studio-vs) (you'll need Windows Desktop **and** Web) or [Mono MDK 3.6](http://www.mono-project.com/download/) + [MonoDevelop 5](http://monodevelop.com/Download)
 * Java
   * [JDK 8](http://www.oracle.com/technetwork/java/javase/downloads/index.html)
   * [NetBeans 8 Java SE](https://netbeans.org/downloads/index.html) or [Ant](http://ant.apache.org/bindownload.cgi) zip

### Differences between the C# and Java versions

 * In the Java version you need to specify the number of uploader threads. The C# version does this automatically.
 * In the Java version you can specify a container prefix that is prepended to filenames. This allows you to upload files to subfolders under the container root.
 * In the C# version you can specify the TTL for uploaded blobs, i.e. the time it takes for a cache refresh to occur on the CDN nodes.

Of course these could be eliminated, it just fits our needs the way it is. PRs are welcome.

### Speed

For my personal tests I've used a folder containing about 3000 files with a total size of about 300 MiB.

* (unnamed commercial GUI application): 20 minutes
* azupload: 8 minutes

### Improvements

* [How to use Blob Storage from .NET](http://azure.microsoft.com/en-us/documentation/articles/storage-dotnet-how-to-use-blobs/)
* [How to use Blob Storage from Java](http://azure.microsoft.com/en-us/documentation/articles/storage-java-how-to-use-blob-storage/)

### Why not PowerShell?

In fact the initial version used PowerShell. I came to the following conclusions:

 * It's s-l-o-w.
 * It's extremely poorly documented.
 * It seems to be impossible to run jobs in parallel properly thanks to *InitializationScript*'s *Import-Module* directive being completely ignored when trying to *Start-Job* and thus rendering Azure commands unavailable to the child jobs.

### Does it work on Linux or OS X?

Yes, it does!


text:
<!DOCTYPE html>
<html>
<head>
  <script type="text/javascript" src="../../lib/store.min.js"></script>
  <script type="text/javascript" src="background.js"></script>
</head>
</html>


text:
//ActionBar-This is android specific, won't show up in iOS;
$.index.addEventListener("open", function() {
	var actionbar =  require('actionBarAndroid');
	var ab = new actionbar();
	ab.actionbar($.index);
	//var actionBar = require('actionBarAndroid');
	//var actionBar = require('menu');
   /*if (Ti.Platform.osname === "android") {
        if (!$.index.activity) {
            Ti.API.error("Can't access action bar on a lightweight window.");
        } else {
          var  actionBar = $.index.activity.actionBar;
            if (actionBar) {
                     actionBar.displayHomeAsUp = true;
                    actionBar.onHomeIconItemSelected = function() {
                    	Titanium.Android.currentActivity.finish();
                	alert("I am action bar in android");
                    Ti.API.info("Home icon clicked!");

                };
            }
        }
    }*/

});

function homeMenuClicked() {
      homeWin= Alloy.createController('index', {
      }).getView();
		homeWin.open();
}

// Ensure menu is displayed
function doOpen(e) {
    $.win.invalidateOptionsMenu();
}

function buttonClicked() {
$.helloLabel.text="This window implements Action bar,menu bar, labels, text field. PLease enter your credentials and submit them to go further";
$.userInfoFormTitle.text="Please enter your personal information below";
$.userForm.setVisible("TRUE");

}

function submitUserData(){
		//alert("Clicked");
		var userDetailsOk = storeUserData();
		if(userDetailsOk){

		newwin= Alloy.createController('newWin').getView();
		newwin.open();
		}
}

function goWebView (){
	webview= Alloy.createController('webView').getView();
		webview.open();
}

function storeUserData(){
	var user = {};
	user.userName = $.userNameInput.getValue();
	user.userEmail = $.userEmailInput.getValue();
	user.userPhone = $.userPhoneInput.getValue();
	if(!user.userName || !user.userEmail || !user.userPhone){
		alert("please enter valid credentials");
		var userDetailsComplete = false;
	}
	else {
	var user_JSON = JSON.stringify(user);
	var file = Ti.Filesystem.getFile(Ti.Filesystem.applicationDataDirectory, 'details.json');
	if(file.exists)
	file.deleteFile();
	file.write(user_JSON);
	var userDetailsComplete = true;
	}
	return userDetailsComplete;
}
 /*function showUserData(){

	var file = Ti.Filesystem.getFile(Ti.Filesystem.applicationDataDirectory,'details.json');

	var userFile = JSON.parse(file.read().text);
	if(!file){
	alert("user details not available");
	}
	else{
		alert(userFile.userName);
	}
}*/

/*$.main.addEventListener('open', function(e) {
	if( Alloy.Globals.Android.Api >= 11 ) {
        activity.actionBar.title = "DemoApp";
        activity.actionBar.displayHomeAsUp = true;
       activity.actionBar.onHomeIconItemSelected = function() {
            alert("Home icon clicked!");
        };
    }
});*/
function showData (){
	showDatawin= Alloy.createController('showDataWin').getView();
		showDatawin.open();
}

$.index.open();


text:
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

// Copyright 2007 Google Inc. All Rights Reserved.

/**
 * @fileoverview Component for an input field with bidi direction automatic
 * detection. The input element directionality is automatically set according
 * to the contents (value) of the element.
 *
 * @see ../demos/bidiinput.html
 */

goog.provide('goog.ui.BidiInput');

goog.require('goog.events');
goog.require('goog.events.InputHandler');
goog.require('goog.i18n.bidi');
goog.require('goog.ui.Component');

/**
 * Default implementation of BidiInput.
 *
 * @param {goog.dom.DomHelper=} opt_domHelper  Optional DOM helper.
 * @constructor
 * @extends {goog.ui.Component}
 */
goog.ui.BidiInput = function(opt_domHelper) {
  goog.ui.Component.call(this, opt_domHelper);
};
goog.inherits(goog.ui.BidiInput, goog.ui.Component);

/**
 * The input handler that provides the input event.
 * @type {goog.events.InputHandler?}
 * @private
 */
goog.ui.BidiInput.prototype.inputHandler_ = null;

/**
 * Decorates the given HTML element as a BidiInput. The HTML element
 * must be an input element with type='text' or a textarea element.
 * Overrides {@link goog.ui.Component#decorateInternal}.  Considered protected.
 * @param {Element} element  Element (HTML Input element) to decorate.
 * @protected
 */
goog.ui.BidiInput.prototype.decorateInternal = function(element) {
  goog.ui.BidiInput.superClass_.decorateInternal.call(this, element);
  this.init_();
};

/**
 * Creates the element for the text input.
 * @protected
 */
goog.ui.BidiInput.prototype.createDom = function() {
  this.setElementInternal(
      this.getDomHelper().createDom('input', {'type': 'text'}));
  this.init_();
};

/**
 * Initializes the events and initial text direction.
 * Called from either decorate or createDom, after the input field has
 * been created.
 * @private
 */
goog.ui.BidiInput.prototype.init_ = function() {
  // Set initial direction by current text
  this.setDirection_();

  // Listen to value change events
  this.inputHandler_ = new goog.events.InputHandler(this.getElement());
  goog.events.listen(this.inputHandler_,
      goog.events.InputHandler.EventType.INPUT,
      this.setDirection_, false, this);
};

/**
 * Set the direction of the input element based on the current value.
 * This method is called when the user changes the input element value, or
 * when a program changes the value using
 * {@link goog.ui.BidiInput#setValue}
 * @private
 */
goog.ui.BidiInput.prototype.setDirection_ = function() {
  var element = this.getElement();
  var text = element.value;
  var dir = ''; // Default for no direction, inherit from document
  if (goog.i18n.bidi.isRtlText(text) || goog.i18n.bidi.isLtrText(text)) {
    if (goog.i18n.bidi.detectRtlDirectionality(text)) {
      dir = 'rtl';
    } else {
      dir = 'ltr';
    }
  }
  element.dir = dir;
};

/**
 * Returns the direction of the input element.
 * @return {?string} Return 'rtl' for right-to-left text,
 *     'ltr' for left-to-right text, or null if the value itself is not
 *     enough to determine directionality (e.g. an empty value), and the
 *     direction is inherited from a parent element (typically the body
 *     element).
 */
goog.ui.BidiInput.prototype.getDirection = function() {
  var dir = this.getElement().dir;
  if (dir == '') {
    dir = null;
  }
  return dir;
};

/**
 * Sets the value of the underlying input field, and sets the direction
 * according to the given value.
 * @param {string} value  The Value to set in the underlying input field.
 */
goog.ui.BidiInput.prototype.setValue = function(value) {
  this.getElement().value = value;
  this.setDirection_();
};

/**
 * Returns the value of the underlying input field.
 * @return {string} Value of the underlying input field.
 */
goog.ui.BidiInput.prototype.getValue = function() {
  return this.getElement().value;
};

/** @inheritDoc */
goog.ui.BidiInput.prototype.disposeInternal = function() {
  if (this.inputHandler_) {
    goog.events.removeAll(this.inputHandler_);
    this.inputHandler_.dispose();
    this.inputHandler_ = null;
    goog.ui.BidiInput.superClass_.disposeInternal.call(this);
  }
};


text:
// Styles
import '../../stylus/components/_text-fields.styl'

// Extensions
import VInput from '../VInput'

// Components
import VCounter from '../VCounter'
import VLabel from '../VLabel'

// Mixins
import Maskable from '../../mixins/maskable'
import Loadable from '../../mixins/loadable'

// Directives
import Ripple from '../../directives/ripple'

// Utilities
import {
  keyCodes
} from '../../util/helpers'
import { deprecate } from '../../util/console'

const dirtyTypes = ['color', 'file', 'time', 'date', 'datetime-local', 'week', 'month']

/* @vue/component */
export default VInput.extend({
  name: 'v-text-field',

  directives: { Ripple },

  mixins: [Maskable, Loadable],

  inheritAttrs: false,

  props: {
    appendOuterIcon: String,
    /** @deprecated */
    appendOuterIconCb: Function,
    autofocus: Boolean,
    box: Boolean,
    browserAutocomplete: String,
    clearable: Boolean,
    clearIcon: {
      type: String,
      default: '$vuetify.icons.clear'
    },
    clearIconCb: Function,
    color: {
      type: String,
      default: 'primary'
    },
    counter: [Boolean, Number, String],
    flat: Boolean,
    fullWidth: Boolean,
    label: String,
    outline: Boolean,
    placeholder: String,
    prefix: String,
    prependInnerIcon: String,
    /** @deprecated */
    prependInnerIconCb: Function,
    reverse: Boolean,
    singleLine: Boolean,
    solo: Boolean,
    soloInverted: Boolean,
    suffix: String,
    type: {
      type: String,
      default: 'text'
    }
  },

  data: () => ({
    badInput: false,
    initialValue: null,
    internalChange: false,
    isClearing: false
  }),

  computed: {
    classes () {
      return {
        'v-text-field': true,
        'v-text-field--full-width': this.fullWidth,
        'v-text-field--prefix': this.prefix,
        'v-text-field--single-line': this.isSingle,
        'v-text-field--solo': this.isSolo,
        'v-text-field--solo-inverted': this.soloInverted,
        'v-text-field--solo-flat': this.flat,
        'v-text-field--box': this.box,
        'v-text-field--enclosed': this.isEnclosed,
        'v-text-field--reverse': this.reverse,
        'v-text-field--outline': this.hasOutline,
        'v-text-field--placeholder': this.placeholder
      }
    },
    counterValue () {
      return (this.internalValue || '').toString().length
    },
    directivesInput () {
      return []
    },
    // TODO: Deprecate
    hasOutline () {
      return this.outline || this.textarea
    },
    internalValue: {
      get () {
        return this.lazyValue
      },
      set (val) {
        if (this.mask && val !== this.lazyValue) {
          this.lazyValue = this.unmaskText(this.maskText(this.unmaskText(val)))
          this.setSelectionRange()
        } else {
          this.lazyValue = val
          this.$emit('input', this.lazyValue)
        }
      }
    },
    isDirty () {
      return (this.lazyValue != null &&
        this.lazyValue.toString().length > 0) ||
        this.badInput
    },
    isEnclosed () {
      return (
        this.box ||
        this.isSolo ||
        this.hasOutline ||
        this.fullWidth
      )
    },
    isLabelActive () {
      return this.isDirty || dirtyTypes.includes(this.type)
    },
    isSingle () {
      return this.isSolo || this.singleLine
    },
    isSolo () {
      return this.solo || this.soloInverted
    },
    labelPosition () {
      const offset = (this.prefix && !this.labelValue) ? this.prefixWidth : 0

      return (!this.$vuetify.rtl !== !this.reverse) ? {
        left: 'auto',
        right: offset
      } : {
        left: offset,
        right: 'auto'
      }
    },
    showLabel () {
      return this.hasLabel && (!this.isSingle || (!this.isLabelActive && !this.placeholder && !this.prefixLabel))
    },
    labelValue () {
      return !this.isSingle &&
        Boolean(this.isFocused || this.isLabelActive || this.placeholder || this.prefixLabel)
    },
    prefixWidth () {
      if (!this.prefix && !this.$refs.prefix) return

      return this.$refs.prefix.offsetWidth
    },
    prefixLabel () {
      return (this.prefix && !this.value)
    }
  },

  watch: {
    isFocused (val) {
      // Sets validationState from validatable
      this.hasColor = val

      if (val) {
        this.initialValue = this.lazyValue
      } else if (this.initialValue !== this.lazyValue) {
        this.$emit('change', this.lazyValue)
      }
    },
    value (val) {
      if (this.mask && !this.internalChange) {
        const masked = this.maskText(this.unmaskText(val))
        this.lazyValue = this.unmaskText(masked)

        // Emit when the externally set value was modified internally
        String(val) !== this.lazyValue && this.$nextTick(() => {
          this.$refs.input.value = masked
          this.$emit('input', this.lazyValue)
        })
      } else this.lazyValue = val
    }
  },

  mounted () {
    this.autofocus && this.onFocus()
  },

  methods: {
    /** @public */
    focus () {
      this.onFocus()
    },
    /** @public */
    blur () {
      this.$refs.input ? this.$refs.input.blur() : this.onBlur()
    },
    clearableCallback () {
      this.internalValue = null
      this.$nextTick(() => this.$refs.input.focus())
    },
    genAppendSlot () {
      const slot = []

      if (this.$slots['append-outer']) {
        slot.push(this.$slots['append-outer'])
      } else if (this.appendOuterIcon) {
        slot.push(this.genIcon('appendOuter'))
      }

      return this.genSlot('append', 'outer', slot)
    },
    genPrependInnerSlot () {
      const slot = []

      if (this.$slots['prepend-inner']) {
        slot.push(this.$slots['prepend-inner'])
      } else if (this.prependInnerIcon) {
        slot.push(this.genIcon('prependInner'))
      }

      return this.genSlot('prepend', 'inner', slot)
    },
    genIconSlot () {
      const slot = []

      if (this.$slots['append']) {
        slot.push(this.$slots['append'])
      } else if (this.appendIcon) {
        slot.push(this.genIcon('append'))
      }

      return this.genSlot('append', 'inner', slot)
    },
    genInputSlot () {
      const input = VInput.options.methods.genInputSlot.call(this)

      const prepend = this.genPrependInnerSlot()
      prepend && input.children.unshift(prepend)

      return input
    },
    genClearIcon () {
      if (!this.clearable) return null

      const icon = !this.isDirty
        ? false
        : 'clear'

      if (this.clearIconCb) deprecate(':clear-icon-cb', '@click:clear', this)

      return this.genSlot('append', 'inner', [
        this.genIcon(
          icon,
          (!this.$listeners['click:clear'] && this.clearIconCb) || this.clearableCallback,
          false
        )
      ])
    },
    genCounter () {
      if (this.counter === false || this.counter == null) return null

      const max = this.counter === true ? this.$attrs.maxlength : this.counter

      return this.$createElement(VCounter, {
        props: {
          dark: this.dark,
          light: this.light,
          max,
          value: this.counterValue
        }
      })
    },
    genDefaultSlot () {
      return [
        this.genTextFieldSlot(),
        this.genClearIcon(),
        this.genIconSlot(),
        this.genProgress()
      ]
    },
    genLabel () {
      if (!this.showLabel) return null

      const data = {
        props: {
          absolute: true,
          color: this.validationState,
          dark: this.dark,
          disabled: this.disabled,
          focused: !this.isSingle && (this.isFocused || !!this.validationState),
          left: this.labelPosition.left,
          light: this.light,
          right: this.labelPosition.right,
          value: this.labelValue
        }
      }

      if (this.$attrs.id) data.props.for = this.$attrs.id

      return this.$createElement(VLabel, data, this.$slots.label || this.label)
    },
    genInput () {
      const listeners = Object.assign({}, this.$listeners)
      delete listeners['change'] // Change should not be bound externally

      const data = {
        style: {},
        domProps: {
          value: this.maskText(this.lazyValue)
        },
        attrs: {
          'aria-label': (!this.$attrs || !this.$attrs.id) && this.label, // Label `for` will be set if we have an id
          ...this.$attrs,
          autofocus: this.autofocus,
          disabled: this.disabled,
          readonly: this.readonly,
          type: this.type
        },
        on: Object.assign(listeners, {
          blur: this.onBlur,
          input: this.onInput,
          focus: this.onFocus,
          keydown: this.onKeyDown
        }),
        ref: 'input'
      }

      if (this.placeholder) data.attrs.placeholder = this.placeholder
      if (this.mask) data.attrs.maxlength = this.masked.length
      if (this.browserAutocomplete) data.attrs.autocomplete = this.browserAutocomplete

      return this.$createElement('input', data)
    },
    genMessages () {
      if (this.hideDetails) return null

      return this.$createElement('div', {
        staticClass: 'v-text-field__details'
      }, [
        VInput.options.methods.genMessages.call(this),
        this.genCounter()
      ])
    },
    genTextFieldSlot () {
      return this.$createElement('div', {
        staticClass: 'v-text-field__slot'
      }, [
        this.genLabel(),
        this.prefix ? this.genAffix('prefix') : null,
        this.genInput(),
        this.suffix ? this.genAffix('suffix') : null
      ])
    },
    genAffix (type) {
      return this.$createElement('div', {
        'class': `v-text-field__${type}`,
        ref: type
      }, this[type])
    },
    onBlur (e) {
      this.isFocused = false
      // Reset internalChange state
      // to allow external change
      // to persist
      this.internalChange = false

      this.$emit('blur', e)
    },
    onClick () {
      if (this.isFocused || this.disabled) return

      this.$refs.input.focus()
    },
    onFocus (e) {
      if (!this.$refs.input) return

      if (document.activeElement !== this.$refs.input) {
        return this.$refs.input.focus()
      }

      if (!this.isFocused) {
        this.isFocused = true
        this.$emit('focus', e)
      }
    },
    onInput (e) {
      this.internalChange = true
      this.mask && this.resetSelections(e.target)
      this.internalValue = e.target.value
      this.badInput = e.target.validity && e.target.validity.badInput
    },
    onKeyDown (e) {
      this.internalChange = true

      if (e.keyCode === keyCodes.enter) this.$emit('change', this.internalValue)

      this.$emit('keydown', e)
    },
    onMouseDown (e) {
      // Prevent input from being blurred
      if (e.target !== this.$refs.input) {
        e.preventDefault()
        e.stopPropagation()
      }

      VInput.options.methods.onMouseDown.call(this, e)
    },
    onMouseUp (e) {
      if (this.hasMouseDown) this.focus()

      VInput.options.methods.onMouseUp.call(this, e)
    }
  }
})


text:
using System;
using System.IO;
using System.Net;
using System.Web;
using NUnit.Framework;
using ServiceStack.Common;
using ServiceStack.Common.Web;
using ServiceStack.ServiceClient.Web;
using ServiceStack.Text;
using ServiceStack.WebHost.Endpoints.Tests.Support.Host;
using ServiceStack.WebHost.Endpoints.Tests.Support.Operations;

namespace ServiceStack.WebHost.Endpoints.Tests
{
	[TestFixture]
	public class CustomRequestDataTests
	{
		private const string ListeningOn = "http://localhost:82/";

		ExampleAppHostHttpListener appHost;
		readonly JsonServiceClient client = new JsonServiceClient(ListeningOn);
		private string customUrl = ListeningOn.CombineWith("customrequestbinder");
		private string predefinedUrl = ListeningOn.CombineWith("json/syncreply/customrequestbinder");

		[TestFixtureSetUp]
		public void OnTestFixtureSetUp()
		{
			appHost = new ExampleAppHostHttpListener();
			appHost.Init();
			appHost.Start(ListeningOn);
		}

		[TestFixtureTearDown]
		public void OnTestFixtureTearDown()
		{
			appHost.Dispose();
		}

		/// <summary>
		/// first-name=tom&item-0=blah&item-1-delete=1
		/// </summary>
		[Test]
		public void Can_parse_custom_form_data()
		{
			var webReq = (HttpWebRequest)WebRequest.Create("http://localhost:82/customformdata?format=json");
			webReq.Method = HttpMethods.Post;
			webReq.ContentType = ContentType.FormUrlEncoded;

			try
			{
				using (var sw = new StreamWriter(webReq.GetRequestStream()))
				{
					sw.Write("&first-name=tom&item-0=blah&item-1-delete=1");
				}
				var response = new StreamReader(webReq.GetResponse().GetResponseStream()).ReadToEnd();

				Assert.That(response, Is.EqualTo("{\"FirstName\":\"tom\",\"Item0\":\"blah\",\"Item1Delete\":\"1\"}"));
			}
			catch (WebException webEx)
			{
				var errorWebResponse = ((HttpWebResponse)webEx.Response);
				var errorResponse = new StreamReader(errorWebResponse.GetResponseStream()).ReadToEnd();

				Assert.Fail(errorResponse);
			}
		}

		[Test]
		public void Does_use_request_binder_for_GET()
		{
			var response = client.Get<CustomRequestBinderResponse>("/customrequestbinder");
			Assert.That(response.FromBinder);
		}

		[Test]
		public void Does_use_request_binder_for_predefined_GET()
		{
			var responseStr = predefinedUrl.DownloadJsonFromUrl();
			Console.WriteLine(responseStr);
			var response = responseStr.FromJson<CustomRequestBinderResponse>();
			Assert.That(response.FromBinder);
		}

		[Test]
		public void Does_use_request_binder_for_predefined_GET_with_QueryString()
		{
			var customUrlWithQueryString = customUrl + "?IsFromBinder=false";
			var responseStr = customUrlWithQueryString.DownloadJsonFromUrl();
			Console.WriteLine(responseStr);
			var response = responseStr.FromJson<CustomRequestBinderResponse>();
			Assert.That(response.FromBinder);
		}

		[Test]
		public void Does_use_request_binder_for_Send()
		{
			var response = client.Send<CustomRequestBinderResponse>(new CustomRequestBinder());
			Assert.That(response.FromBinder);
		}

		[Test]
		public void Does_use_request_binder_for_POST()
		{
			var response = client.Post<CustomRequestBinderResponse>("/customrequestbinder", new CustomRequestBinder());
			Assert.That(response.FromBinder);
		}

		[Test]
		public void Does_use_request_binder_for_POST_FormData()
		{
			var responseStr = customUrl.PostToUrl("IsFromBinder=false", ContentType.FormUrlEncoded, ContentType.Json);
			Console.WriteLine(responseStr);
			var response = responseStr.FromJson<CustomRequestBinderResponse>();
			Assert.That(response.FromBinder);
		}

		[Test]
		public void Does_use_request_binder_for_POST_FormData_without_ContentType()
		{
			var responseStr = customUrl.PostToUrl("{\"IsFromBinder\":false}", ContentType.Json, ContentType.Json);
			Console.WriteLine(responseStr);
			var response = responseStr.FromJson<CustomRequestBinderResponse>();
			Assert.That(response.FromBinder);
		}

		[Test]
		public void Does_use_request_binder_for_POST_FormData_without_ContentType_with_QueryString()
		{
			string customUrlWithQueryString = customUrl + "?IsFromBinder=false";
			var responseStr = customUrlWithQueryString.PostToUrl("k=v", acceptContentType: ContentType.Json);
			var response = responseStr.FromJson<CustomRequestBinderResponse>();
			Assert.That(response.FromBinder);
		}

		[Test]
		public void Does_use_request_binder_for_predefined_POST()
		{
			var responseStr = predefinedUrl.PostJsonToUrl(new CustomRequestBinder());
			Console.WriteLine(responseStr);
			var response = responseStr.FromJson<CustomRequestBinderResponse>();
			Assert.That(response.FromBinder);
		}

		[Test]
		public void Does_use_request_binder_for_predefined_POST_FormData()
		{
			var responseStr = predefinedUrl.PostToUrl("k=v", ContentType.FormUrlEncoded, ContentType.Json);
			Console.WriteLine(responseStr);
			var response = responseStr.FromJson<CustomRequestBinderResponse>();
			Assert.That(response.FromBinder);
		}

		[Test]
		public void Does_use_request_binder_for_PUT()
		{
			var response = client.Put<CustomRequestBinderResponse>("/customrequestbinder", new CustomRequestBinder());
			Assert.That(response.FromBinder);
		}

		[Test]
		public void Does_use_request_binder_for_DELETE()
		{
			var response = client.Delete<CustomRequestBinderResponse>("/customrequestbinder");
			Assert.That(response.FromBinder);
		}

	}

}


text:
@implementation CHArticle_info_list
+(NSDictionary*)mj_replacedKeyFromPropertyName
{
    return @{@"myid": @"id"};
}
@end


text:
<!doctype html>

	<meta charset="UTF-8">
	<meta name="viewport" content="width=device-width, initial-scale=1">

	<link href='http://fonts.googleapis.com/css?family=PT+Sans:400,700|Merriweather:400italic,400' rel='stylesheet' type='text/css'>

	<link rel="stylesheet" href="css/reset.css">
	<link rel="stylesheet" href="css/style.css">

	<title>Renaissance Study Materials</title>

	Menu

Geography

The Geography of Italy

Project 2

Brief description of the project here

Project 3

Brief description of the project here

Project 4

Brief description of the project here

Geography

The geography of Italy

Peninsula on Mediterranean Sea

Italy = 2 islands (Sicily and Sardinia)

Boot-shaped

Tuscany is next to italy

Covered by mountains

Dolomite mtns = part of Alps

Appenine mtns cut down center of Italy

Po valley = home to Po Basin

Medici family  = ruling family of Florence

Project 2

Brief description of the project here

						Lorem ipsum dolor sit amet, consectetur adipisicing elit. Minima, quod dicta aliquid nemo repellendus distinctio minus dolor aperiam suscipit, ea enim accusantium, deleniti qui sequi sint nihil modi amet eligendi, quidem animi error labore voluptatibus sed. Qui magnam labore, iusto nostrum. Praesentium non, impedit accusantium consequatur officia architecto, mollitia placeat aperiam tenetur pariatur voluptatibus corrupti vitae deserunt! Nostrum non mollitia deserunt ipsam. Sunt quaerat natus cupiditate iure ipsa voluptatibus recusandae ratione vitae amet distinctio, voluptas, minus vero expedita ea fugit similique sit cumque ad id facere? Ab quas, odio neque quis ratione. Natus labore sit esse, porro placeat eum hic.
						Lorem ipsum dolor sit amet, consectetur adipisicing elit. Minima, quod dicta aliquid nemo repellendus distinctio minus dolor aperiam suscipit, ea enim accusantium, deleniti qui sequi sint nihil modi amet eligendi, quidem animi error labore voluptatibus sed. Qui magnam labore, iusto nostrum. Praesentium non, impedit accusantium consequatur officia architecto, mollitia placeat aperiam tenetur pariatur voluptatibus corrupti vitae deserunt! Nostrum non mollitia deserunt ipsam. Sunt quaerat natus cupiditate iure ipsa voluptatibus recusandae ratione vitae amet distinctio, voluptas, minus vero expedita ea fugit similique sit cumque ad id facere? Ab quas, odio neque quis ratione. Natus labore sit esse, porro placeat eum hic.
						Lorem ipsum dolor sit amet, consectetur adipisicing elit. Minima, quod dicta aliquid nemo repellendus distinctio minus dolor aperiam suscipit, ea enim accusantium, deleniti qui sequi sint nihil modi amet eligendi, quidem animi error labore voluptatibus sed. Qui magnam labore, iusto nostrum. Praesentium non, impedit accusantium consequatur officia architecto, mollitia placeat aperiam tenetur pariatur voluptatibus corrupti vitae deserunt! Nostrum non mollitia deserunt ipsam. Sunt quaerat natus cupiditate iure ipsa voluptatibus recusandae ratione vitae amet distinctio, voluptas, minus vero expedita ea fugit similique sit cumque ad id facere? Ab quas, odio neque quis ratione. Natus labore sit esse, porro placeat eum hic.
						Lorem ipsum dolor sit amet, consectetur adipisicing elit. Minima, quod dicta aliquid nemo repellendus distinctio minus dolor aperiam suscipit, ea enim accusantium, deleniti qui sequi sint nihil modi amet eligendi, quidem animi error labore voluptatibus sed. Qui magnam labore, iusto nostrum. Praesentium non, impedit accusantium consequatur officia architecto, mollitia placeat aperiam tenetur pariatur voluptatibus corrupti vitae deserunt! Nostrum non mollitia deserunt ipsam. Sunt quaerat natus cupiditate iure ipsa voluptatibus recusandae ratione vitae amet distinctio, voluptas, minus vero expedita ea fugit similique sit cumque ad id facere? Ab quas, odio neque quis ratione. Natus labore sit esse, porro placeat eum hic.

Project 3

Brief description of the project here

						Lorem ipsum dolor sit amet, consectetur adipisicing elit. Minima, quod dicta aliquid nemo repellendus distinctio minus dolor aperiam suscipit, ea enim accusantium, deleniti qui sequi sint nihil modi amet eligendi, quidem animi error labore voluptatibus sed. Qui magnam labore, iusto nostrum. Praesentium non, impedit accusantium consequatur officia architecto, mollitia placeat aperiam tenetur pariatur voluptatibus corrupti vitae deserunt! Nostrum non mollitia deserunt ipsam. Sunt quaerat natus cupiditate iure ipsa voluptatibus recusandae ratione vitae amet distinctio, voluptas, minus vero expedita ea fugit similique sit cumque ad id facere? Ab quas, odio neque quis ratione. Natus labore sit esse, porro placeat eum hic.
						Lorem ipsum dolor sit amet, consectetur adipisicing elit. Minima, quod dicta aliquid nemo repellendus distinctio minus dolor aperiam suscipit, ea enim accusantium, deleniti qui sequi sint nihil modi amet eligendi, quidem animi error labore voluptatibus sed. Qui magnam labore, iusto nostrum. Praesentium non, impedit accusantium consequatur officia architecto, mollitia placeat aperiam tenetur pariatur voluptatibus corrupti vitae deserunt! Nostrum non mollitia deserunt ipsam. Sunt quaerat natus cupiditate iure ipsa voluptatibus recusandae ratione vitae amet distinctio, voluptas, minus vero expedita ea fugit similique sit cumque ad id facere? Ab quas, odio neque quis ratione. Natus labore sit esse, porro placeat eum hic.
						Lorem ipsum dolor sit amet, consectetur adipisicing elit. Minima, quod dicta aliquid nemo repellendus distinctio minus dolor aperiam suscipit, ea enim accusantium, deleniti qui sequi sint nihil modi amet eligendi, quidem animi error labore voluptatibus sed. Qui magnam labore, iusto nostrum. Praesentium non, impedit accusantium consequatur officia architecto, mollitia placeat aperiam tenetur pariatur voluptatibus corrupti vitae deserunt! Nostrum non mollitia deserunt ipsam. Sunt quaerat natus cupiditate iure ipsa voluptatibus recusandae ratione vitae amet distinctio, voluptas, minus vero expedita ea fugit similique sit cumque ad id facere? Ab quas, odio neque quis ratione. Natus labore sit esse, porro placeat eum hic.
						Lorem ipsum dolor sit amet, consectetur adipisicing elit. Minima, quod dicta aliquid nemo repellendus distinctio minus dolor aperiam suscipit, ea enim accusantium, deleniti qui sequi sint nihil modi amet eligendi, quidem animi error labore voluptatibus sed. Qui magnam labore, iusto nostrum. Praesentium non, impedit accusantium consequatur officia architecto, mollitia placeat aperiam tenetur pariatur voluptatibus corrupti vitae deserunt! Nostrum non mollitia deserunt ipsam. Sunt quaerat natus cupiditate iure ipsa voluptatibus recusandae ratione vitae amet distinctio, voluptas, minus vero expedita ea fugit similique sit cumque ad id facere? Ab quas, odio neque quis ratione. Natus labore sit esse, porro placeat eum hic.

Project 4

Brief description of the project here

						Lorem ipsum dolor sit amet, consectetur adipisicing elit. Minima, quod dicta aliquid nemo repellendus distinctio minus dolor aperiam suscipit, ea enim accusantium, deleniti qui sequi sint nihil modi amet eligendi, quidem animi error labore voluptatibus sed. Qui magnam labore, iusto nostrum. Praesentium non, impedit accusantium consequatur officia architecto, mollitia placeat aperiam tenetur pariatur voluptatibus corrupti vitae deserunt! Nostrum non mollitia deserunt ipsam. Sunt quaerat natus cupiditate iure ipsa voluptatibus recusandae ratione vitae amet distinctio, voluptas, minus vero expedita ea fugit similique sit cumque ad id facere? Ab quas, odio neque quis ratione. Natus labore sit esse, porro placeat eum hic.
						Lorem ipsum dolor sit amet, consectetur adipisicing elit. Minima, quod dicta aliquid nemo repellendus distinctio minus dolor aperiam suscipit, ea enim accusantium, deleniti qui sequi sint nihil modi amet eligendi, quidem animi error labore voluptatibus sed. Qui magnam labore, iusto nostrum. Praesentium non, impedit accusantium consequatur officia architecto, mollitia placeat aperiam tenetur pariatur voluptatibus corrupti vitae deserunt! Nostrum non mollitia deserunt ipsam. Sunt quaerat natus cupiditate iure ipsa voluptatibus recusandae ratione vitae amet distinctio, voluptas, minus vero expedita ea fugit similique sit cumque ad id facere? Ab quas, odio neque quis ratione. Natus labore sit esse, porro placeat eum hic.
						Lorem ipsum dolor sit amet, consectetur adipisicing elit. Minima, quod dicta aliquid nemo repellendus distinctio minus dolor aperiam suscipit, ea enim accusantium, deleniti qui sequi sint nihil modi amet eligendi, quidem animi error labore voluptatibus sed. Qui magnam labore, iusto nostrum. Praesentium non, impedit accusantium consequatur officia architecto, mollitia placeat aperiam tenetur pariatur voluptatibus corrupti vitae deserunt! Nostrum non mollitia deserunt ipsam. Sunt quaerat natus cupiditate iure ipsa voluptatibus recusandae ratione vitae amet distinctio, voluptas, minus vero expedita ea fugit similique sit cumque ad id facere? Ab quas, odio neque quis ratione. Natus labore sit esse, porro placeat eum hic.
						Lorem ipsum dolor sit amet, consectetur adipisicing elit. Minima, quod dicta aliquid nemo repellendus distinctio minus dolor aperiam suscipit, ea enim accusantium, deleniti qui sequi sint nihil modi amet eligendi, quidem animi error labore voluptatibus sed. Qui magnam labore, iusto nostrum. Praesentium non, impedit accusantium consequatur officia architecto, mollitia placeat aperiam tenetur pariatur voluptatibus corrupti vitae deserunt! Nostrum non mollitia deserunt ipsam. Sunt quaerat natus cupiditate iure ipsa voluptatibus recusandae ratione vitae amet distinctio, voluptas, minus vero expedita ea fugit similique sit cumque ad id facere? Ab quas, odio neque quis ratione. Natus labore sit esse, porro placeat eum hic.

		<button class="scroll cd-text-replace">Scroll</button>

Navigation

The team

Our services

Our projects

Contact us


text:
import argparse
import os.path
import sys

from dectree.config import CONFIG_DEFAULTS, VECTORIZE_PROP
from dectree.transpiler import transpile

def main(args=None):
    if args is None:
        args = sys.argv[1:]

    parser = argparse.ArgumentParser(prog=__package__,
                                     description="Generates a Python module in directory OUTPUT_DIR "
                                                 "from each decision tree given in SOURCE_FILE. If OUTPUT_DIR "
                                                 "is not given, Python modules are created next to their "
                                                 "SOURCE_FILE.")
    parser.add_argument("src",
                        metavar='SOURCE_FILE',
                        nargs='+',
                        help="source file containing a decision tree (YAML format)")
    parser.add_argument("-o", "--out",
                        metavar='OUTPUT_DIR',
                        help="target directory for generated Python files")

    for option_name, option_def in CONFIG_DEFAULTS.items():
        default, help_pattern, choices = option_def
        if choices:
            parser.add_argument('--' + option_name,
                                default=default,
                                help=help_pattern.format(default=default),
                                choices=choices)
        else:
            parser.add_argument('--' + option_name,
                                default=default,
                                action='store_true' if isinstance(default, bool) else None,
                                help=help_pattern.format(default=default))

    args = parser.parse_args(args=args)
    options = {k: v for k, v in vars(args).items() if k in CONFIG_DEFAULTS and v != CONFIG_DEFAULTS[k][0]}

    if args.no_jit and args.vectorize == VECTORIZE_PROP:
        print('error: --no_jit is illegal because --vectorize "' + VECTORIZE_PROP + '" requires JIT')
        exit(1)

    out_dir = args.out
    if out_dir is not None:
        os.makedirs(out_dir, exist_ok=True)

    for src_file in args.src:
        out_file = None
        if out_dir is not None:
            basename = os.path.splitext(os.path.basename(src_file))[0] + '.py'
            out_file = os.path.join(out_dir, basename)
        out_file = transpile(src_file, out_file=out_file, **options)
        print('generated', out_file)

if __name__ == '__main__':
    main()


text:
<?php
/**
 * IDE-Helper code documentation options.
 *
 * @see IdeHelperConfig
 */

use Spiral\IdeHelper\Locators;
use Spiral\IdeHelper\Renderer;
use Spiral\IdeHelper\Writers;

return [
    // locators are responsible for searching classes and their members
    'locators' => [
        'containers' => bind(Locators\ContainersLocator::class, [
            'targets' => [
                \Interop\Container\ContainerInterface::class . '::get',
                'spiral',
            ],
        ]),
        'bindings'   => Locators\BindingsLocator::class,
        'requests'   => Locators\RequestsLocator::class,
        'documents'  => Locators\DocumentsLocator::class,
        'records'    => Locators\RecordsLocator::class,
    ],
    // writers are responsible for storing data collected by locators
    'writers'  => [
        'phpProperty' => bind(Writers\FilePerClassWriter::class, [
            'outputDirectory' => directory('runtime') . 'ide-helper/',
            'renderer'        => bind(Renderer\ReactorBasedPropertyRenderer::class),
        ]),
        'phpDoc'      => bind(Writers\FilePerClassWriter::class, [
            'outputDirectory' => directory('runtime') . 'ide-helper/',
            'renderer'        => bind(Renderer\ReactorBasedDocRenderer::class),
        ]),
        'meta'        => bind(Writers\SingleFileWriter::class, [
            'outputFile' => directory('runtime') . 'ide-helper/virtual.meta.php',
            'renderer'   => bind(Renderer\PhpstormMetaRenderer::class),
        ]),
    ],
    // each scope is a combination of locators and writers, first each locator is executed to
    // collect data, then each writer is executed with all collected data
    'scopes'   => [
        'container' => [
            'locators' => ['bindings'],
            'writers'  => ['phpProperty'],
        ],
        'entity'    => [
            'locators' => [
                'requests',
                'documents',
                'records'
            ],
            'writers'  => ['phpDoc'],
        ],
        'meta'      => [
            'locators' => ['containers'],
            'writers'  => ['meta'],
        ],
    ],
];


text:
module Pacproxy
  VERSION = '0.0.10dev'
end


text:
package org.apache.camel.component.zookeepermaster.group.internal;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.util.List;
import java.util.Map;

import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.camel.component.zookeepermaster.group.NodeState;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.retry.RetryOneTime;
import org.apache.zookeeper.data.Stat;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.notNullValue;
import static org.junit.Assert.assertThat;

public class ZooKeeperGroupTest {

    private static final String PATH = "/singletons/test/" + ZooKeeperGroupTest.class.getSimpleName();

    private CuratorFramework curator;
    private ZooKeeperGroup<NodeState> group;

    private int findFreePort() throws Exception {
        ServerSocket ss = new ServerSocket(0);
        int port = ss.getLocalPort();
        ss.close();
        return port;
    }

    @Before
    public void setUp() throws Exception {
        int port = findFreePort();
        curator = CuratorFrameworkFactory.builder()
            .connectString("localhost:" + port)
            .retryPolicy(new RetryOneTime(1))
            .build();
        //curator.start();
        group = new ZooKeeperGroup<>(curator, PATH, NodeState.class);
        //group.start();
        // Starting curator and group is not necessary for the current tests.
    }

    @After
    public void tearDown() throws IOException {
        group.close();
        curator.close();
        group = null;
        curator = null;
    }

    private static void putChildData(ZooKeeperGroup<NodeState> group, String path, String container) throws Exception {
        NodeState node = new NodeState("test", container);
        ByteArrayOutputStream data = new ByteArrayOutputStream();
        new ObjectMapper().disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES).writeValue(data, node);
        ChildData<NodeState> child = new ChildData<>(path, new Stat(), data.toByteArray(), node);
        group.putCurrentData(path, child);
    }

    @Test
    public void testMembers() throws Exception {
        putChildData(group, PATH + "/001", "container1");
        putChildData(group, PATH + "/002", "container2");
        putChildData(group, PATH + "/003", "container3");

        Map<String, NodeState> members = group.members();
        assertThat(members.size(), equalTo(3));
        assertThat(members.get(PATH + "/001").getContainer(), equalTo("container1"));
        assertThat(members.get(PATH + "/002").getContainer(), equalTo("container2"));
        assertThat(members.get(PATH + "/003").getContainer(), equalTo("container3"));
    }

    @Test
    public void testMembersWithStaleNodes() throws Exception {
        putChildData(group, PATH + "/001", "container1"); // stale
        putChildData(group, PATH + "/002", "container1");
        putChildData(group, PATH + "/003", "container2"); // stale
        putChildData(group, PATH + "/004", "container3"); // stale
        putChildData(group, PATH + "/005", "container2");
        putChildData(group, PATH + "/006", "container3");

        Map<String, NodeState> members = group.members();
        assertThat(members.size(), equalTo(3));
        assertThat(members.get(PATH + "/002").getContainer(), equalTo("container1"));
        assertThat(members.get(PATH + "/005").getContainer(), equalTo("container2"));
        assertThat(members.get(PATH + "/006").getContainer(), equalTo("container3"));
    }

    @Test
    public void testIsMaster() throws Exception {
        putChildData(group, PATH + "/001", "container1");
        putChildData(group, PATH + "/002", "container2");
        putChildData(group, PATH + "/003", "container3");

        group.setId(PATH + "/001");
        assertThat(group.isMaster(), equalTo(true));
        group.setId(PATH + "/002");
        assertThat(group.isMaster(), equalTo(false));
    }

    @Test
    public void testIsMasterWithStaleNodes1() throws Exception {
        putChildData(group, PATH + "/001", "container1"); // stale
        putChildData(group, PATH + "/002", "container1");
        putChildData(group, PATH + "/003", "container2"); // stale
        putChildData(group, PATH + "/004", "container3"); // stale
        putChildData(group, PATH + "/005", "container2");
        putChildData(group, PATH + "/006", "container3");

        group.setId(PATH + "/002");
        assertThat(group.isMaster(), equalTo(true));
        group.setId(PATH + "/005");
        assertThat(group.isMaster(), equalTo(false));
    }

    @Test
    public void testIsMasterWithStaleNodes2() throws Exception {
        putChildData(group, PATH + "/001", "container1"); // stale
        putChildData(group, PATH + "/002", "container2");
        putChildData(group, PATH + "/003", "container1");
        putChildData(group, PATH + "/004", "container3"); // stale
        putChildData(group, PATH + "/005", "container3");

        group.setId(PATH + "/002");
        assertThat(group.isMaster(), equalTo(true));
        group.setId(PATH + "/003");
        assertThat(group.isMaster(), equalTo(false));
    }

    @Test
    public void testMaster() throws Exception {
        putChildData(group, PATH + "/001", "container1");
        putChildData(group, PATH + "/002", "container2");
        putChildData(group, PATH + "/003", "container3");

        NodeState master = group.master();
        assertThat(master, notNullValue());
        assertThat(master.getContainer(), equalTo("container1"));
    }

    @Test
    public void testMasterWithStaleNodes1() throws Exception {
        putChildData(group, PATH + "/001", "container1"); // stale
        putChildData(group, PATH + "/002", "container1");
        putChildData(group, PATH + "/003", "container2"); // stale
        putChildData(group, PATH + "/004", "container3"); // stale
        putChildData(group, PATH + "/005", "container2");
        putChildData(group, PATH + "/006", "container3");

        NodeState master = group.master();
        assertThat(master, notNullValue());
        assertThat(master.getContainer(), equalTo("container1"));
    }

    @Test
    public void testMasterWithStaleNodes2() throws Exception {
        putChildData(group, PATH + "/001", "container1"); // stale
        putChildData(group, PATH + "/002", "container2");
        putChildData(group, PATH + "/003", "container1");
        putChildData(group, PATH + "/004", "container3"); // stale
        putChildData(group, PATH + "/005", "container3");

        NodeState master = group.master();
        assertThat(master, notNullValue());
        assertThat(master.getContainer(), equalTo("container2"));
    }

    @Test
    public void testSlaves() throws Exception {
        putChildData(group, PATH + "/001", "container1");
        putChildData(group, PATH + "/002", "container2");
        putChildData(group, PATH + "/003", "container3");

        List<NodeState> slaves = group.slaves();
        assertThat(slaves.size(), equalTo(2));
        assertThat(slaves.get(0).getContainer(), equalTo("container2"));
        assertThat(slaves.get(1).getContainer(), equalTo("container3"));
    }

    @Test
    public void testSlavesWithStaleNodes1() throws Exception {
        putChildData(group, PATH + "/001", "container1"); // stale
        putChildData(group, PATH + "/002", "container1");
        putChildData(group, PATH + "/003", "container2"); // stale
        putChildData(group, PATH + "/004", "container3"); // stale
        putChildData(group, PATH + "/005", "container2");
        putChildData(group, PATH + "/006", "container3");

        List<NodeState> slaves = group.slaves();
        assertThat(slaves.size(), equalTo(2));
        assertThat(slaves.get(0).getContainer(), equalTo("container2"));
        assertThat(slaves.get(1).getContainer(), equalTo("container3"));
    }

    @Test
    public void testSlavesWithStaleNodes2() throws Exception {
        putChildData(group, PATH + "/001", "container1"); // stale
        putChildData(group, PATH + "/002", "container2");
        putChildData(group, PATH + "/003", "container1");
        putChildData(group, PATH + "/004", "container3"); // stale
        putChildData(group, PATH + "/005", "container3");

        List<NodeState> slaves = group.slaves();
        assertThat(slaves.size(), equalTo(2));
        assertThat(slaves.get(0).getContainer(), equalTo("container1"));
        assertThat(slaves.get(1).getContainer(), equalTo("container3"));
    }

}


text:
package main

import (
	"bufio"
	"flag"
	"fmt"
	"os"
	"runtime"
	"strings"
)

const (
	keyCtrlC     = 3
	keyCtrlD     = 4
	keyCtrlN     = 14
	keyCtrlP     = 16
	keyCtrlU     = 21
	keyCtrlW     = 23
	keyEnter     = '\r'
	keyNL        = '\n'
	keyEscape    = 27
	keyUp        = 38
	keyDown      = 40
	keyBackspace = 127
)

var (
	SaveCursorPosition     = []byte{keyEscape, '[', 's'}
	RestoreCursorPosition  = []byte{keyEscape, '[', 'u'}
	EraseDisplayFromCursor = []byte{keyEscape, '[', 'J'}
	ReverseColor           = []byte{keyEscape, '[', '7', 'm'}
	ResetColor             = []byte{keyEscape, '[', '0', 'm'}
	HideCursor             = []byte{keyEscape, '[', '?', '2', '5', 'l'}
	ShowCursor             = []byte{keyEscape, '[', '?', '2', '5', 'h'}
)

type TTY struct {
	*os.File
}

func OpenTTY() (*TTY, error) {
	file, err := os.OpenFile("/dev/tty", os.O_RDWR, 0)
	if err != nil {
		return nil, err
	}
	return &TTY{file}, nil
}

type steps struct {
	Up    int
	Down  int
	Left  int
	Right int
}

func (tty *TTY) moveCursor(step steps) {
	count := step.Down + step.Up + step.Left + step.Right
	movement := make([]byte, 3*(count))
	m := movement
	for i := 0; i < step.Up; i++ {
		m[0] = keyEscape
		m[1] = '['
		m[2] = 'A'
		m = m[3:]
	}
	for i := 0; i < step.Down; i++ {
		m[0] = keyEscape
		m[1] = '['
		m[2] = 'B'
		m = m[3:]
	}
	for i := 0; i < step.Left; i++ {
		m[0] = keyEscape
		m[1] = '['
		m[2] = 'D'
		m = m[3:]
	}
	for i := 0; i < step.Right; i++ {
		m[0] = keyEscape
		m[1] = '['
		m[2] = 'C'
		m = m[3:]
	}

	tty.Write(movement)
}

func (tty *TTY) HideCursor() {
	tty.Write(HideCursor)
}

func (tty *TTY) ShowCursor() {
	tty.Write(ShowCursor)
}

func (tty *TTY) SaveCursorPosition() {
	tty.Write(SaveCursorPosition)
}

func (tty *TTY) RestoreCursorPosition() {
	tty.Write(RestoreCursorPosition)
}

func (tty *TTY) EraseDisplayFromCursor() {
	tty.Write(EraseDisplayFromCursor)
}

// XXX: The renderer work is still spread across the file.
type Renderer struct {
	tty     *TTY
	width   int
	height  int
	visible int
}

func (r *Renderer) PrepareForTerminalVim() {
	// start from the bottom of the screen
	r.tty.moveCursor(steps{
		Left: r.width,
		Down: r.height,
	})
}

func (r *Renderer) focusWritingPoint(view *PickerView) {
	r.tty.RestoreCursorPosition()
	r.tty.moveCursor(steps{
		Right: len(view.input),
	})
}

func cutAt(str string, width int) string {
	if len(str) > width {
		return str[:width]
	}
	return str
}

func TTYReverse(str string) string {
	return string(ReverseColor) + str + string(ResetColor)
}

func (r *Renderer) renderPickerView(view *PickerView) {
	view.input = cutAt(view.input, r.width)
	for i := range view.lines {
		view.lines[i] = cutAt(view.lines[i], r.width)
	}
	view.lines[view.selected] = TTYReverse(view.lines[view.selected])

	r.tty.WriteString(view.input + "\n" + strings.Join(view.lines, "\n"))
}

func (r *Renderer) renderFirstFrame(view *PickerView) {
	r.tty.HideCursor()
	r.renderPickerView(view)

	// going width time to the left is more than necessary but it works in all
	// situations and is simpler
	r.tty.moveCursor(steps{
		Up:   r.visible,
		Left: r.width,
	})

	// We already rendered the first view but that was to find the right
	// point so now we can save it erase the display from the point to the
	// end of the terminal and then re-render the picker.
	r.tty.SaveCursorPosition()
	r.tty.EraseDisplayFromCursor()
	r.renderPickerView(view)

	r.focusWritingPoint(view)
	r.tty.ShowCursor()
}

func (r *Renderer) Start(channel chan *PickerView) {
	// we special case the first picker to render since we have to save a
	// position for later uses
	r.renderFirstFrame(<-channel)

	for view := range channel {
		r.tty.HideCursor()
		r.tty.RestoreCursorPosition()
		r.tty.EraseDisplayFromCursor()

		r.renderPickerView(view)
		r.focusWritingPoint(view)
		r.tty.ShowCursor()
	}
}

var (
	visible int
	vim     bool
)

func main() {
	runtime.GOMAXPROCS(runtime.NumCPU())
	flag.IntVar(&visible, "v", 20, "Number of visible candidates")
	flag.BoolVar(&vim, "vim", false, "Print at bottom of screen")
	flag.Parse()

	tty, err := OpenTTY()
	if err != nil {
		panic(err)
	}

	old, err := tty.MakeRaw()
	if err != nil {
		panic(err)
	}
	defer tty.Restore(old)

	width, height, err := tty.GetSize()
	if err != nil {
		panic(err)
	}

	if height < visible {
		visible = height
	}

	renderChan := make(chan *PickerView)
	renderer := &Renderer{
		tty:     tty,
		height:  height,
		width:   width,
		visible: visible,
	}

	if vim {
		renderer.PrepareForTerminalVim()
	}
	go renderer.Start(renderChan)

	picker := NewPicker("> ", visible, os.Stdin, renderChan)

	input := make(chan rune)
	go func() {
		reader := bufio.NewReader(tty)
		for {
			r, _, err := reader.ReadRune()
			if err != nil || r == keyEscape || r == keyCtrlC {
				tty.RestoreCursorPosition()
				tty.EraseDisplayFromCursor()
				os.Exit(1)
			}
			input <- r
		}
	}()

	for r := range input {
		switch r {
		case keyEnter, keyNL:
			tty.RestoreCursorPosition()
			selected, err := picker.Selected()
			if err != nil {
				os.Exit(1)
			}
			fmt.Println(selected)
			return
		case keyCtrlU, keyCtrlW:
			picker.Clear()
		case keyCtrlN, keyDown:
			picker.Down()
		case keyCtrlP, keyUp:
			picker.Up()
		case keyBackspace:
			picker.Back()
		default:
			picker.More(r)
		}
	}
}


text:
require 'helper'
require 'json'
require 'response'
require 'resource/helper'

module Polyseerio
  module Middleware
    # Pre request middleware.
    module Pre
      # Requests arguments run through there.
      def self.format_arguments
        proc do |*args|
          new_args = args

          if new_args.size > 1
            new_args[1] = Helper.format_payload new_args[1]
            new_args[1] = new_args[1].to_json
          end

          new_args
        end
      end
    end

    # Post request middleware.
    module Post
      # Takes rest-client and response and converts it to internal response.
      def self.to_response
        proc do |response|
          Response.new(response)
        end
      end

      # Request results run through there.
      def self.parse_response
        proc do |response|
          Resource::Helper.parse_response(response, 0) # TODO: need a cid
        end
      end
    end

    # Request rejection (error) middleware.
    module Reject
      def self.handle_rejection
        proc do |error|
          error
        end
      end
    end
  end
end


text:
No documentation exists.

# following binary_string of <binary position> : binary_substring

No documentation exists.

# preceding binary_string of <binary position> : binary_substring

No documentation exists.


text:
Using PUQ Read
==============

Use **puq read** to read parameters, PDFs, and response surfaces from json files or
python control scripts.  ::

	~/puq/examples/basic> puq read -h
	Usage: puq read [options] [object] ...
	    where 'object' is a URI, python file, or JSON file

	Options:
	  -h, --help  show this help message and exit
	  -c          Compare plots.

	~/puq/examples/basic> puq read basic.py

	List PDFs you want displayed, separated by commas.

	Found the following PDFs:
	0: x
	1: y
	Which one(s) to display? (* for all) *

You can use *puq analyze* to save PDFs to json files, then *puq read* to compare them.
Or you can compare input parameters from a control file. ::

	~/puq/examples/basic> puq read -c f.json g.json

.. figure:: images/compare.png
   :align: left


text:
class CreateReminders < ActiveRecord::Migration
  def change
    create_table :reminders do |t|
      t.string :name
      t.integer :interval
      t.string :source_url

      t.timestamps null: false
    end
  end
end


text:
/**
 *
 */
package com.civica.grads.boardgames.display;

import com.civica.grads.boardgames.exceptions.GameSetupException;
import com.civica.grads.boardgames.exceptions.RenderException;
import com.civica.grads.boardgames.interfaces.Renderer;
import com.civica.grads.boardgames.model.Board;

import java.io.ByteArrayOutputStream;
import java.io.PrintStream;
import java.io.UnsupportedEncodingException;
import java.nio.charset.StandardCharsets;

/**
 * @author Bruce.Mundin
 *
 */
public class StringBufferBoardRenderer implements Renderer
{
    private final ByteArrayOutputStream baos = new ByteArrayOutputStream();
    private final Renderer parentRenderer ;

    public StringBufferBoardRenderer() throws GameSetupException {

        try {
            PrintStream ps = new PrintStream(baos, true, "utf-8");
            this.parentRenderer = new AsciiBoardRenderer(ps);
        } catch (UnsupportedEncodingException ex) {
            throw new GameSetupException("Unable to set up the rendered.",ex);
        }

    }

    @Override
    public void render(Board board) throws RenderException {
        this.parentRenderer.render(board);
    }

    /* (non-Javadoc)
     * @see java.lang.Object#toString()
     */
    @Override
    public String toString() {
        String content = asString();
        return "StringBufferBoardRenderer [" + content + "]";
    }

    public String asString() {
        return new String(baos.toByteArray(), StandardCharsets.UTF_8);
    }

}


text:
package main

import (
	"fmt"
	"net/http"
	"github.com/mazaziz/endpoint"
)

func home(w http.ResponseWriter, r *http.Request) {
	w.Header().Set("Content-Type", "application/json")
	fmt.Fprintln(w, "Hello World")
}

func noteList(w http.ResponseWriter, r *http.Request) {
	fmt.Fprintln(w, "note list")
}

func noteCreate(w http.ResponseWriter, r *http.Request) {
	fmt.Fprintln(w, "note create")
}

func noteRetrieve(w http.ResponseWriter, r *http.Request) {
	fmt.Fprintln(w, "note retrieve")
}

func noteDelete(w http.ResponseWriter, r *http.Request) {
	fmt.Fprintln(w, "note delete")
}

func underConstruction(w http.ResponseWriter, r *http.Request) {
	w.WriteHeader(503)
	fmt.Fprintln(w, "Under Construction. Please try again later.")
}

func main() {
	e := endpoint.New()
	e.Handler404 = func(w http.ResponseWriter, r *http.Request) {
		w.Header().Set("Content-Type", "application/json")
		w.WriteHeader(404)
		fmt.Fprint(w, "{\"success\":false,\"code\":404,\"message\":\"Not Found\"}")
	}
	e.Handler405 = func(w http.ResponseWriter, r *http.Request) {
		w.Header().Set("Content-Type", "application/json")
		w.WriteHeader(405)
		fmt.Fprint(w, "{\"success\":false,\"code\":405,\"message\":\"Method Not Allowed\"}")
	}
	e.Match("id", `^\d+$`)
	e.Match("tag", `^[[:alnum:]]+$`)
	e.Route("GET /", home)
	e.Route("GET /note", noteList)
	e.Route("POST /note", noteCreate)
	e.Route("GET /note/:id", noteRetrieve)
	e.Route("DELETE /note/:id", noteDelete)
	e.Route("GET /note/:id/tag/:tag", underConstruction)
	e.Serve("127.0.0.1:3333")
}


text:
import asyncio
import sys
from contextlib import suppress
from asynccmd import Cmd

async def sleep_n_print(loop, time_to_sleep=None):
    """
    This is our simple coroutine.
    :param time_to_sleep: time to sleep in seconds
    :return: await sleep for time_to_sleep seconds
    """
    asyncio.set_event_loop(loop)  # set correct event loop
    await asyncio.sleep(int(time_to_sleep))
    print("Wake up! I was slept for {0}s".format(time_to_sleep))

class Commander(Cmd):

    def __init__(self, intro, prompt):
        super().__init__(mode=mode)
        self.intro = intro
        self.prompt = prompt
        self.loop = None

    def do_sleep(self, arg):
        """
        Our example cmd-command-method for sleep. sleep <arg>
        :param arg: contain args that go after command
        :return: None
        """
        self.loop.create_task(sleep_n_print(self.loop, arg))

    def do_tasks(self, arg):
        """
        Our example method. Type "tasks <arg>"
        :param arg: contain args that go after command
        :return: None
        """
        for task in asyncio.Task.all_tasks(loop=self.loop):
            print(task)

    def start(self, loop=None):
        self.loop = loop
        super().cmdloop(loop)

if sys.platform == 'win32':
    loop = asyncio.ProactorEventLoop()
    mode = "Run"
else:
    loop = asyncio.get_event_loop()
    mode = "Reader"
# asyncio.set_event_loop(loop)
cmd = Commander(intro="This is example", prompt="example> ")
cmd.start(loop)
try:
    loop.run_forever()
except KeyboardInterrupt:
    loop.stop()
    pending = asyncio.Task.all_tasks(loop=loop)
    for task in pending:
        task.cancel()
        with suppress(asyncio.CancelledError):
            loop.run_until_complete(task)
    loop.close()


text:
#ifndef __S390_ETR_H
#define __S390_ETR_H

/* ETR attachment control register */
struct etr_eacr {
	unsigned int e0		: 1;	/* port 0 stepping control */
	unsigned int e1		: 1;	/* port 1 stepping control */
	unsigned int _pad0	: 5;	/* must be 00100 */
	unsigned int dp		: 1;	/* data port control */
	unsigned int p0		: 1;	/* port 0 change recognition control */
	unsigned int p1		: 1;	/* port 1 change recognition control */
	unsigned int _pad1	: 3;	/* must be 000 */
	unsigned int ea		: 1;	/* ETR alert control */
	unsigned int es		: 1;	/* ETR sync check control */
	unsigned int sl		: 1;	/* switch to local control */
} __attribute__ ((packed));

/* Port state returned by steai */
enum etr_psc {
	etr_psc_operational = 0,
	etr_psc_semi_operational = 1,
	etr_psc_protocol_error =  4,
	etr_psc_no_symbols = 8,
	etr_psc_no_signal = 12,
	etr_psc_pps_mode = 13
};

/* Logical port state returned by stetr */
enum etr_lpsc {
	etr_lpsc_operational_step = 0,
	etr_lpsc_operational_alt = 1,
	etr_lpsc_semi_operational = 2,
	etr_lpsc_protocol_error =  4,
	etr_lpsc_no_symbol_sync = 8,
	etr_lpsc_no_signal = 12,
	etr_lpsc_pps_mode = 13
};

/* ETR status words */
struct etr_esw {
	struct etr_eacr eacr;		/* attachment control register */
	unsigned int y		: 1;	/* stepping mode */
	unsigned int _pad0	: 5;	/* must be 00000 */
	unsigned int p		: 1;	/* stepping port number */
	unsigned int q		: 1;	/* data port number */
	unsigned int psc0	: 4;	/* port 0 state code */
	unsigned int psc1	: 4;	/* port 1 state code */
} __attribute__ ((packed));

/* Second level data register status word */
struct etr_slsw {
	unsigned int vv1	: 1;	/* copy of validity bit data frame 1 */
	unsigned int vv2	: 1;	/* copy of validity bit data frame 2 */
	unsigned int vv3	: 1;	/* copy of validity bit data frame 3 */
	unsigned int vv4	: 1;	/* copy of validity bit data frame 4 */
	unsigned int _pad0	: 19;	/* must by all zeroes */
	unsigned int n		: 1;	/* EAF port number */
	unsigned int v1		: 1;	/* validity bit ETR data frame 1 */
	unsigned int v2		: 1;	/* validity bit ETR data frame 2 */
	unsigned int v3		: 1;	/* validity bit ETR data frame 3 */
	unsigned int v4		: 1;	/* validity bit ETR data frame 4 */
	unsigned int _pad1	: 4;	/* must be 0000 */
} __attribute__ ((packed));

/* ETR data frames */
struct etr_edf1 {
	unsigned int u		: 1;	/* untuned bit */
	unsigned int _pad0	: 1;	/* must be 0 */
	unsigned int r		: 1;	/* service request bit */
	unsigned int _pad1	: 4;	/* must be 0000 */
	unsigned int a		: 1;	/* time adjustment bit */
	unsigned int net_id	: 8;	/* ETR network id */
	unsigned int etr_id	: 8;	/* id of ETR which sends data frames */
	unsigned int etr_pn	: 8;	/* port number of ETR output port */
} __attribute__ ((packed));

struct etr_edf2 {
	unsigned int etv	: 32;	/* Upper 32 bits of TOD. */
} __attribute__ ((packed));

struct etr_edf3 {
	unsigned int rc		: 8;	/* failure reason code */
	unsigned int _pad0	: 3;	/* must be 000 */
	unsigned int c		: 1;	/* ETR coupled bit */
	unsigned int tc		: 4;	/* ETR type code */
	unsigned int blto	: 8;	/* biased local time offset */
					/* (blto - 128) * 15 = minutes */
	unsigned int buo	: 8;	/* biased utc offset */
					/* (buo - 128) = leap seconds */
} __attribute__ ((packed));

struct etr_edf4 {
	unsigned int ed		: 8;	/* ETS device dependent data */
	unsigned int _pad0	: 1;	/* must be 0 */
	unsigned int buc	: 5;	/* biased ut1 correction */
					/* (buc - 16) * 0.1 seconds */
	unsigned int em		: 6;	/* ETS error magnitude */
	unsigned int dc		: 6;	/* ETS drift code */
	unsigned int sc		: 6;	/* ETS steering code */
} __attribute__ ((packed));

/*
 * ETR attachment information block, two formats
 * format 1 has 4 reserved words with a size of 64 bytes
 * format 2 has 16 reserved words with a size of 96 bytes
 */
struct etr_aib {
	struct etr_esw esw;
	struct etr_slsw slsw;
	unsigned long long tsp;
	struct etr_edf1 edf1;
	struct etr_edf2 edf2;
	struct etr_edf3 edf3;
	struct etr_edf4 edf4;
	unsigned int reserved[16];
} __attribute__ ((packed,aligned(8)));

/* ETR interruption parameter */
struct etr_irq_parm {
	unsigned int _pad0	: 8;
	unsigned int pc0	: 1;	/* port 0 state change */
	unsigned int pc1	: 1;	/* port 1 state change */
	unsigned int _pad1	: 3;
	unsigned int eai	: 1;	/* ETR alert indication */
	unsigned int _pad2	: 18;
} __attribute__ ((packed));

/* Query TOD offset result */
struct etr_ptff_qto {
	unsigned long long physical_clock;
	unsigned long long tod_offset;
	unsigned long long logical_tod_offset;
	unsigned long long tod_epoch_difference;
} __attribute__ ((packed));

/* Inline assembly helper functions */
static inline int etr_setr(struct etr_eacr *ctrl)
{
	int rc = -EOPNOTSUPP;

	asm volatile(
		"	.insn	s,0xb2160000,%1\n"
		"0:	la	%0,0\n"
		"1:\n"
		EX_TABLE(0b,1b)
		: "+d" (rc) : "Q" (*ctrl));
	return rc;
}

/* Stores a format 1 aib with 64 bytes */
static inline int etr_stetr(struct etr_aib *aib)
{
	int rc = -EOPNOTSUPP;

	asm volatile(
		"	.insn	s,0xb2170000,%1\n"
		"0:	la	%0,0\n"
		"1:\n"
		EX_TABLE(0b,1b)
		: "+d" (rc) : "Q" (*aib));
	return rc;
}

/* Stores a format 2 aib with 96 bytes for specified port */
static inline int etr_steai(struct etr_aib *aib, unsigned int func)
{
	register unsigned int reg0 asm("0") = func;
	int rc = -EOPNOTSUPP;

	asm volatile(
		"	.insn	s,0xb2b30000,%1\n"
		"0:	la	%0,0\n"
		"1:\n"
		EX_TABLE(0b,1b)
		: "+d" (rc) : "Q" (*aib), "d" (reg0));
	return rc;
}

/* Function codes for the steai instruction. */
#define ETR_STEAI_STEPPING_PORT		0x10
#define ETR_STEAI_ALTERNATE_PORT	0x11
#define ETR_STEAI_PORT_0		0x12
#define ETR_STEAI_PORT_1		0x13

static inline int etr_ptff(void *ptff_block, unsigned int func)
{
	register unsigned int reg0 asm("0") = func;
	register unsigned long reg1 asm("1") = (unsigned long) ptff_block;
	int rc = -EOPNOTSUPP;

	asm volatile(
		"	.word	0x0104\n"
		"	ipm	%0\n"
		"	srl	%0,28\n"
		: "=d" (rc), "=m" (ptff_block)
		: "d" (reg0), "d" (reg1), "m" (ptff_block) : "cc");
	return rc;
}

/* Function codes for the ptff instruction. */
#define ETR_PTFF_QAF	0x00	/* query available functions */
#define ETR_PTFF_QTO	0x01	/* query tod offset */
#define ETR_PTFF_QSI	0x02	/* query steering information */
#define ETR_PTFF_ATO	0x40	/* adjust tod offset */
#define ETR_PTFF_STO	0x41	/* set tod offset */
#define ETR_PTFF_SFS	0x42	/* set fine steering rate */
#define ETR_PTFF_SGS	0x43	/* set gross steering rate */

/* Functions needed by the machine check handler */
int etr_switch_to_local(void);
int etr_sync_check(void);
void etr_queue_work(void);

/* notifier for syncs */
extern struct atomic_notifier_head s390_epoch_delta_notifier;

/* STP interruption parameter */
struct stp_irq_parm {
	unsigned int _pad0	: 14;
	unsigned int tsc	: 1;	/* Timing status change */
	unsigned int lac	: 1;	/* Link availability change */
	unsigned int tcpc	: 1;	/* Time control parameter change */
	unsigned int _pad2	: 15;
} __attribute__ ((packed));

#define STP_OP_SYNC	1
#define STP_OP_CTRL	3

struct stp_sstpi {
	unsigned int rsvd0;
	unsigned int rsvd1 : 8;
	unsigned int stratum : 8;
	unsigned int vbits : 16;
	unsigned int leaps : 16;
	unsigned int tmd : 4;
	unsigned int ctn : 4;
	unsigned int rsvd2 : 3;
	unsigned int c : 1;
	unsigned int tst : 4;
	unsigned int tzo : 16;
	unsigned int dsto : 16;
	unsigned int ctrl : 16;
	unsigned int rsvd3 : 16;
	unsigned int tto;
	unsigned int rsvd4;
	unsigned int ctnid[3];
	unsigned int rsvd5;
	unsigned int todoff[4];
	unsigned int rsvd6[48];
} __attribute__ ((packed));

/* Functions needed by the machine check handler */
int stp_sync_check(void);
int stp_island_check(void);
void stp_queue_work(void);

#endif /* __S390_ETR_H */