text:
<!doctype html>

		<meta charset="utf-8">

		<title>Docker Networking - Addressing a Sore Point in the OSS Ecosystem</title>

		<meta name="description" content="Slides about getting overlay networking in Docker">
		<meta name="author" content="Antoni Segura Puimedon">

		<meta name="apple-mobile-web-app-capable" content="yes" />
		<meta name="apple-mobile-web-app-status-bar-style" content="black-translucent" />

		<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no, minimal-ui">

		<link rel="stylesheet" href="css/reveal.css">
		<link rel="stylesheet" href="css/theme/black.css" id="theme">

		<link rel="stylesheet" href="lib/css/zenburn.css">

                         <object type="image/svg+xml"
                                 data="assets/docker_logo.svg"></object>

Networking

Addressing a Sore Point in the OSS Ecosystem

						Created by

                                      Antoni Segura Puimedon
                                   /
                                      @celebdor

Docker

Containers made easy

Daemon based

multiple backends

                              Explain containers vs VM

                         <object type="image/svg+xml"
                                 data="assets/docker_linux_stack.svg"
                                 height="500em"></object>

Docker networking

libcontainer(builtin):

NAT Bridge

None

Host

Container

Overlay

NAT Bridge

                         <object type="image/svg+xml"
                                 data="assets/docker_bridged.svg"
                                 height="500em"></object>

Private Subnet rfc1918

Host side:

docker0 Linux bridge

veth0 on docker0

Container side

veth1 as eth0

loopback

Address in the private subnet

Can expose ports in the host

NAT Bridge

Advantages:

Isolation from underlay

Simple

Drawbacks:

no easy cross-host

no advanced networking

Host

Advantages:

Directly on the underlay

Full capabilities

Drawbacks:

Lack of isolation

Container

                         <object type="image/svg+xml"
                                 data="assets/docker_container.svg"
                                 height="500em"></object>

Container

Advantages:

Isolation from the underlay

Full communication containers

Drawbacks:

no easy cross-host

no advanced networking

Overlay

Cross-host networking for containers

Advanced network opportunities

Flannel

                         <object type="image/svg+xml"
                                 data="assets/flannel.svg"
                                 height="500em"></object>

                              talk about kubernetes

Flannel

Advantages:

Overlay for the hosts

Each docker0 gets a routable /24

UDP and VXLAN backends

Provides configuration file for
                                         dockerd

Drawbacks:

Lack of flexibility

no advanced networking

Extending docker networking

Current way:

wrap around the docker API/cli,
                                         or

Hook to the event stream and
                                         react

Future way:

libnetwork (core or remote)

Wrapping around

Advanced networking as extra
                                 commands/params

Write a wrapping API

Write wrapping cli

Make sure users target the wrappers

Examples

Socketplane(cli)

Weave(cli)

Nova-docker(both)

Wrapping around: socketplane

                         <object type="image/svg+xml"
                                 data="assets/wrapping_cli.svg"
                                 height="500em"></object>

advantages:

cohesive experience

drawbacks:

Can't use the docker API/cli

Can expose ports in the host

Evented: MidoNet PoC

                         <object type="image/svg+xml"
                                 data="assets/event_midonet_poc.svg"
                                 height="500em"></object>

advantages:

Can plug networking that doesn't
                                             know about it

drawbacks:

Must create nets with a separate API/cli

Can expose ports in the host

Nova-docker

                         <object type="image/svg+xml"
                                 data="assets/nova_docker.svg"
                                 height="500em"></object>

advantages:

OpenStack

Can plug networking that doesn't
                                             know about it

Some of the Neutron vendors.
                                             MidoNet!

drawbacks:

not useful for non-openstack
                                             deployments

Libnetwork

Refactor libcontainer networking into a
                                 separate library

Extends docker API/cli

Written in Go by Docker for docker

Multiple drivers:

bridge

host

null

overlay*

remote

                              Mention CoreOS CNI

Libnetwork: entities

Driver

Sandbox

Network

Create

Delete

Endpoint

Create

Join

Leave

Delete

Libnetwork: remote

Open to external vendors

Containerized

RPC dockerd<-->remote driver

Implements the driver entities

Libnetwork neutron driver proposal

                         <object type="image/svg+xml"
                                 data="assets/docker_neutron_proposal.svg"
                                 height="500em"></object>

Libnetwork neutron driver proposal

Gives Swarm an overlay

Maps libnetwork entities to Neutron

Gets IPAM from Neutron

Vendor interface plugging configurable

Extra entities via labels

Opens Docker to advanced networking

Open Source and open to contributors

Libnetwork neutron driver proposal + MidoNet

Distributed containerizable SDN Controller

No SPOF

Layer 4 load balancing with health monitor

Native security groups

Distributed stateful NAT

OpenStack Magnum

Containers as a First-class OSt resource

Containers are ants, not cattle

Multi-tenant Control and Data Planes

Brings the Hybrid Cloud

OpenStack Magnum

                         <object type="image/svg+xml"
                                 data="assets/magnum_bays.svg"
                                 height="500em"></object>

                              Explain how it differs for swarm

OpenStack Magnum

Two levels of encapsulation!!!

Solution: Use only neutron

OpenStack Magnum

                         <object type="image/svg+xml"
                                 data="assets/magnum_proposal.svg"
                                 height="500em"></object>

credit OVN container proposal and ask them to
                              join in bringing it to magnum

Join us

                        <object type="image/svg+xml" data="assets/all_logos.svg" height="200em"></object>

MidoNet Magnum

https://slack.midonet.org

#openstack-containers@irc.freenode.net


text:
"""Functions to parse datetime objects."""

# We're using regular expressions rather than time.strptime because:
# - They provide both validation and parsing.
# - They're more flexible for datetimes.
# - The date/datetime/time constructors produce friendlier error messages.

import datetime
import re
from django.utils import six
from django.utils.timezone import utc, get_fixed_timezone

date_re = re.compile(
    r'(?P<year>\d{4})-(?P<month>\d{1,2})-(?P<day>\d{1,2})$'
)

time_re = re.compile(
    r'(?P<hour>\d{1,2}):(?P<minute>\d{1,2})'
    r'(?::(?P<second>\d{1,2})(?:\.(?P<microsecond>\d{1,6})\d{0,6})?)?'
)

datetime_re = re.compile(
    r'(?P<year>\d{4})-(?P<month>\d{1,2})-(?P<day>\d{1,2})'
    r'[T ](?P<hour>\d{1,2}):(?P<minute>\d{1,2})'
    r'(?::(?P<second>\d{1,2})(?:\.(?P<microsecond>\d{1,6})\d{0,6})?)?'
    r'(?P<tzinfo>Z|[+-]\d{2}(?::?\d{2})?)?$'
)

def parse_date(value):
    """Parses a string and return a datetime.date.

    Raises ValueError if the input is well formatted but not a valid date.
    Returns None if the input isn't well formatted.
    """
    match = date_re.match(value)
    if match:
        kw = dict((k, int(v)) for k, v in six.iteritems(match.groupdict()))
        return datetime.date(**kw)

def parse_time(value):
    """Parses a string and return a datetime.time.

    This function doesn't support time zone offsets.

    Raises ValueError if the input is well formatted but not a valid time.
    Returns None if the input isn't well formatted, in particular if it
    contains an offset.
    """
    match = time_re.match(value)
    if match:
        kw = match.groupdict()
        if kw['microsecond']:
            kw['microsecond'] = kw['microsecond'].ljust(6, '0')
        kw = dict((k, int(v)) for k, v in six.iteritems(kw) if v is not None)
        return datetime.time(**kw)

def parse_datetime(value):
    """Parses a string and return a datetime.datetime.

    This function supports time zone offsets. When the input contains one,
    the output uses a timezone with a fixed offset from UTC.

    Raises ValueError if the input is well formatted but not a valid datetime.
    Returns None if the input isn't well formatted.
    """
    match = datetime_re.match(value)
    if match:
        kw = match.groupdict()
        if kw['microsecond']:
            kw['microsecond'] = kw['microsecond'].ljust(6, '0')
        tzinfo = kw.pop('tzinfo')
        if tzinfo == 'Z':
            tzinfo = utc
        elif tzinfo is not None:
            offset_mins = int(tzinfo[-2:]) if len(tzinfo) > 3 else 0
            offset = 60 * int(tzinfo[1:3]) + offset_mins
            if tzinfo[0] == '-':
                offset = -offset
            tzinfo = get_fixed_timezone(offset)
        kw = dict((k, int(v)) for k, v in six.iteritems(kw) if v is not None)
        kw['tzinfo'] = tzinfo
        return datetime.datetime(**kw)

redpajama_set_name: RedPajamaGithub


text:
module.exports = function(grunt) {

  // Project configuration.
  grunt.initConfig({
    pkg: grunt.file.readJSON('package.json'),
    uglify: {
        dist: {
            options: {
                banner: '/*! GeneValidator API <%= grunt.template.today("yyyy-mm-dd") %> */\n',
                preserveComments: false,
                mangle: {
                    sort: true,
                },
                sourceMap: false,
                compress: {
                    sequences: true,
                    dead_code: true,
                    conditionals: true,
                    booleans: true,
                    unused: true,
                    if_return: true,
                    join_vars: true,
                    drop_console: false
                }
            },
            files: {
                'build/genevalidatorappAPI.min.js': ['src/genevalidatorappAPI.js']
            },
        },
    }
  });

  // Load the plugin that provides the "uglify" task.
  grunt.loadNpmTasks('grunt-contrib-uglify');

  // Default task(s).
  grunt.registerTask('default', ['uglify']);

};


text:
from abc import ABCMeta
from numbers import Integral
import numpy as np
import sqlite3
from sqlite3 import Row
import warnings

from logbook import Logger
import pandas as pd
from pandas.tseries.tools import normalize_date
from six import with_metaclass, string_types

from zipline.errors import (
    ConsumeAssetMetaDataError,
    InvalidAssetType,
    MultipleSymbolsFound,
    RootSymbolNotFound,
    SidAssignmentError,
    SidNotFound,
    SymbolNotFound,
    MapAssetIdentifierIndexError,
)
from zipline.assets._assets import (
    Asset, Equity, Future
)

log = Logger('assets.py')

# Expected fields for an Asset's metadata
ASSET_FIELDS = [
    'sid',
    'asset_type',
    'symbol',
    'root_symbol',
    'asset_name',
    'start_date',
    'end_date',
    'first_traded',
    'exchange',
    'notice_date',
    'expiration_date',
    'contract_multiplier',
    # The following fields are for compatibility with other systems
    'file_name',  # Used as symbol
    'company_name',  # Used as asset_name
    'start_date_nano',  # Used as start_date
    'end_date_nano',  # Used as end_date
]

# Expected fields for an Asset's metadata
ASSET_TABLE_FIELDS = [
    'sid',
    'symbol',
    'asset_name',
    'start_date',
    'end_date',
    'first_traded',
    'exchange',
]

# Expected fields for an Asset's metadata
FUTURE_TABLE_FIELDS = ASSET_TABLE_FIELDS + [
    'root_symbol',
    'notice_date',
    'expiration_date',
    'contract_multiplier',
]

EQUITY_TABLE_FIELDS = ASSET_TABLE_FIELDS

# Create the query once from the fields, so that the join is not done
# repeatedly.
FUTURE_BY_SID_QUERY = 'select {0} from futures where sid=?'.format(
    ", ".join(FUTURE_TABLE_FIELDS))

EQUITY_BY_SID_QUERY = 'select {0} from equities where sid=?'.format(
    ", ".join(EQUITY_TABLE_FIELDS))

class AssetFinder(object):

    def __init__(self,
                 metadata=None,
                 allow_sid_assignment=True,
                 fuzzy_char=None,
                 db_path=':memory:',
                 create_table=True):

        self.fuzzy_char = fuzzy_char

        # This flag controls if the AssetFinder is allowed to generate its own
        # sids. If False, metadata that does not contain a sid will raise an
        # exception when building assets.
        self.allow_sid_assignment = allow_sid_assignment

        if allow_sid_assignment:
            self.end_date_to_assign = normalize_date(
                pd.Timestamp('now', tz='UTC'))

        self.conn = sqlite3.connect(db_path)
        self.conn.text_factory = str
        self.cursor = self.conn.cursor()

        # The AssetFinder also holds a nested-dict of all metadata for
        # reference when building Assets
        self.metadata_cache = {}

        # Create table and read in metadata.
        # Should we use flags like 'r', 'w', instead?
        # What we need to support is:
        # - A 'throwaway' mode where the metadata is read each run.
        # - A 'write' mode where the data is written to the provided db_path
        # - A 'read' mode where the asset finder uses a prexisting db.
        if create_table:
            self.create_db_tables()
            if metadata is not None:
                self.consume_metadata(metadata)

        # Cache for lookup of assets by sid, the objects in the asset lookp may
        # be shared with the results from equity and future lookup caches.
        #
        # The top level cache exists to minimize lookups on the asset type
        # routing.
        #
        # The caches are read through, i.e. accessing an asset through
        # retrieve_asset, _retrieve_equity etc. will populate the cache on
        # first retrieval.
        self._asset_cache = {}
        self._equity_cache = {}
        self._future_cache = {}

        self._asset_type_cache = {}

        # Populated on first call to `lifetimes`.
        self._asset_lifetimes = None

    def create_db_tables(self):
        c = self.conn.cursor()

        c.execute("""
        CREATE TABLE equities(
        sid integer,
        symbol text,
        asset_name text,
        start_date integer,
        end_date integer,
        first_traded integer,
        exchange text,
        fuzzy text
        )""")

        c.execute('CREATE INDEX equities_sid on equities(sid)')
        c.execute('CREATE INDEX equities_symbol on equities(symbol)')
        c.execute('CREATE INDEX equities_fuzzy on equities(fuzzy)')

        c.execute("""
        CREATE TABLE futures(
        sid integer,
        symbol text,
        asset_name text,
        start_date integer,
        end_date integer,
        first_traded integer,
        exchange text,
        root_symbol text,
        notice_date integer,
        expiration_date integer,
        contract_multiplier real
        )""")

        c.execute('CREATE INDEX futures_sid on futures(sid)')
        c.execute('CREATE INDEX futures_root_symbol on equities(symbol)')

        c.execute("""
        CREATE TABLE asset_router
        (sid integer,
        asset_type text)
        """)

        c.execute('CREATE INDEX asset_router_sid on asset_router(sid)')

        self.conn.commit()

    def asset_type_by_sid(self, sid):
        try:
            return self._asset_type_cache[sid]
        except KeyError:
            pass

        c = self.conn.cursor()
        # Python 3 compatibility required forcing to int for sid = 0.
        t = (int(sid),)
        query = 'select asset_type from asset_router where sid=:sid'
        c.execute(query, t)
        data = c.fetchone()
        if data is None:
            return

        asset_type = data[0]
        self._asset_type_cache[sid] = asset_type

        return asset_type

    def retrieve_asset(self, sid, default_none=False):
        if isinstance(sid, Asset):
            return sid

        try:
            asset = self._asset_cache[sid]
        except KeyError:
            asset_type = self.asset_type_by_sid(sid)
            if asset_type == 'equity':
                asset = self._retrieve_equity(sid)
            elif asset_type == 'future':
                asset = self._retrieve_futures_contract(sid)
            else:
                asset = None

            self._asset_cache[sid] = asset

        if asset is not None:
            return asset
        elif default_none:
            return None
        else:
            raise SidNotFound(sid=sid)

    def _retrieve_equity(self, sid):
        try:
            return self._equity_cache[sid]
        except KeyError:
            pass

        c = self.conn.cursor()
        c.row_factory = Row
        t = (int(sid),)
        c.execute(EQUITY_BY_SID_QUERY, t)
        data = dict(c.fetchone())
        if data:
            if data['start_date']:
                data['start_date'] = pd.Timestamp(data['start_date'], tz='UTC')

            if data['end_date']:
                data['end_date'] = pd.Timestamp(data['end_date'], tz='UTC')

            if data['first_traded']:
                data['first_traded'] = pd.Timestamp(
                    data['first_traded'], tz='UTC')

            equity = Equity(**data)
        else:
            equity = None

        self._equity_cache[sid] = equity
        return equity

    def _retrieve_futures_contract(self, sid):
        try:
            return self._future_cache[sid]
        except KeyError:
            pass

        c = self.conn.cursor()
        t = (int(sid),)
        c.row_factory = Row
        c.execute(FUTURE_BY_SID_QUERY, t)
        data = dict(c.fetchone())
        if data:
            if data['start_date']:
                data['start_date'] = pd.Timestamp(data['start_date'], tz='UTC')

            if data['end_date']:
                data['end_date'] = pd.Timestamp(data['end_date'], tz='UTC')

            if data['first_traded']:
                data['first_traded'] = pd.Timestamp(
                    data['first_traded'], tz='UTC')

            if data['notice_date']:
                data['notice_date'] = pd.Timestamp(
                    data['notice_date'], tz='UTC')

            if data['expiration_date']:
                data['expiration_date'] = pd.Timestamp(
                    data['expiration_date'], tz='UTC')

            future = Future(**data)
        else:
            future = None

        self._future_cache[sid] = future
        return future

    def lookup_symbol_resolve_multiple(self, symbol, as_of_date=None):
        """
        Return matching Asset of name symbol in database.

        If multiple Assets are found and as_of_date is not set,
        raises MultipleSymbolsFound.

        If no Asset was active at as_of_date, and allow_expired is False
        raises SymbolNotFound.
        """
        if as_of_date is not None:
            as_of_date = pd.Timestamp(normalize_date(as_of_date))

        c = self.conn.cursor()

        if as_of_date:
            # If one SID exists for symbol, return that symbol
            t = (symbol, as_of_date.value, as_of_date.value)
            query = ("select sid from equities "
                     "where symbol=? "
                     "and start_date<=? "
                     "and end_date>=?")
            c.execute(query, t)
            candidates = c.fetchall()

            if len(candidates) == 1:
                return self._retrieve_equity(candidates[0][0])

            # If no SID exists for symbol, return SID with the
            # highest-but-not-over end_date
            if len(candidates) == 0:
                t = (symbol, as_of_date.value)
                query = ("select sid from equities "
                         "where symbol=? "
                         "and start_date<=? "
                         "order by end_date desc "
                         "limit 1")
                c.execute(query, t)
                data = c.fetchone()

                if data:
                    return self._retrieve_equity(data[0])

            # If multiple SIDs exist for symbol, return latest start_date with
            # end_date as a tie-breaker
            if len(candidates) > 1:
                t = (symbol, as_of_date.value)
                query = ("select sid from equities "
                         "where symbol=? " +
                         "and start_date<=? " +
                         "order by start_date desc, end_date desc " +
                         "limit 1")
                c.execute(query, t)
                data = c.fetchone()

                if data:
                    return self._retrieve_equity(data[0])

            raise SymbolNotFound(symbol=symbol)

        else:
            t = (symbol,)
            query = ("select sid from equities where symbol=?")
            c.execute(query, t)
            data = c.fetchall()

            if len(data) == 1:
                return self._retrieve_equity(data[0][0])
            elif not data:
                raise SymbolNotFound(symbol=symbol)
            else:
                options = []
                for row in data:
                    sid = row[0]
                    asset = self._retrieve_equity(sid)
                    options.append(asset)
                raise MultipleSymbolsFound(symbol=symbol,
                                           options=options)

    def lookup_symbol(self, symbol, as_of_date, fuzzy=False):
        """
        If a fuzzy string is provided, then we try various symbols based on
        the provided symbol.  This is to facilitate mapping from a broker's
        symbol to ours in cases where mapping to the broker's symbol loses
        information. For example, if we have CMCS_A, but a broker has CMCSA,
        when the broker provides CMCSA, it can also provide fuzzy='_',
        so we can find a match by inserting an underscore.
        """
        symbol = symbol.upper()
        as_of_date = normalize_date(as_of_date)

        if not fuzzy:
            try:
                return self.lookup_symbol_resolve_multiple(symbol, as_of_date)
            except SymbolNotFound:
                return None
        else:
            c = self.conn.cursor()
            fuzzy = symbol.replace(self.fuzzy_char, '')
            t = (fuzzy, as_of_date.value, as_of_date.value)
            query = ("select sid from equities "
                     "where fuzzy=? " +
                     "and start_date<=? " +
                     "and end_date>=?")
            c.execute(query, t)
            candidates = c.fetchall()

            # If one SID exists for symbol, return that symbol
            if len(candidates) == 1:
                return self._retrieve_equity(candidates[0][0])

            # If multiple SIDs exist for symbol, return latest start_date with
            # end_date as a tie-breaker
            if len(candidates) > 1:
                t = (symbol, as_of_date.value)
                query = ("select sid from equities "
                         "where symbol=? " +
                         "and start_date<=? " +
                         "order by start_date desc, end_date desc" +
                         "limit 1")
                c.execute(query, t)
                data = c.fetchone()
                if data:
                    return self._retrieve_equity(data[0])

    def lookup_future_chain(self, root_symbol, as_of_date, knowledge_date):
        """ Return the futures chain for a given root symbol.

        Parameters
        ----------
        root_symbol : str
            Root symbol of the desired future.
        as_of_date : pd.Timestamp or pd.NaT
            Date at which the chain determination is rooted. I.e. the
            existing contract whose notice date is first after this
            date is the primary contract, etc. If NaT is given, the
            chain is unbounded, and all contracts for this root symbol
            are returned.
        knowledge_date : pd.Timestamp or pd.NaT
            Date for determining which contracts exist for inclusion in
            this chain. Contracts exist only if they have a start_date
            on or before this date. If NaT is given and as_of_date is
            is not NaT, the value of as_of_date is used for
            knowledge_date.

        Returns
        -------
        list
            A list of Future objects, the chain for the given
            parameters.

        Raises
        ------
        RootSymbolNotFound
            Raised when a future chain could not be found for the given
            root symbol.
        """
        c = self.conn.cursor()

        if as_of_date is pd.NaT:
            # If the as_of_date is NaT, get all contracts for this
            # root symbol.
            t = {'root_symbol': root_symbol}
            c.execute("""
            select sid from futures
            where root_symbol=:root_symbol
            order by notice_date asc
            """, t)
        else:
            if knowledge_date is pd.NaT:
                # If knowledge_date is NaT, default to using as_of_date
                t = {'root_symbol': root_symbol,
                     'as_of_date': as_of_date.value,
                     'knowledge_date': as_of_date.value}
            else:
                t = {'root_symbol': root_symbol,
                     'as_of_date': as_of_date.value,
                     'knowledge_date': knowledge_date.value}

            c.execute("""
            select sid from futures
            where root_symbol=:root_symbol
            and :as_of_date < notice_date
            and start_date <= :knowledge_date
            order by notice_date asc
            """, t)
        sids = [r[0] for r in c.fetchall()]
        if not sids:
            # Check if root symbol exists.
            c.execute("""
            select count(sid) from futures where root_symbol=:root_symbol
            """, t)
            count = c.fetchone()[0]
            if count == 0:
                raise RootSymbolNotFound(root_symbol=root_symbol)
            else:
                # If symbol exists, return empty future chain.
                return []
        return [self._retrieve_futures_contract(sid) for sid in sids]

    @property
    def sids(self):
        c = self.conn.cursor()
        query = 'select sid from asset_router'
        c.execute(query)
        return [r[0] for r in c.fetchall()]

    def _lookup_generic_scalar(self,
                               asset_convertible,
                               as_of_date,
                               matches,
                               missing):
        """
        Convert asset_convertible to an asset.

        On success, append to matches.
        On failure, append to missing.
        """
        try:
            if isinstance(asset_convertible, Asset):
                matches.append(asset_convertible)

            elif isinstance(asset_convertible, Integral):
                result = self.retrieve_asset(int(asset_convertible))
                if result is None:
                    raise SymbolNotFound(symbol=asset_convertible)
                matches.append(result)

            elif isinstance(asset_convertible, string_types):
                # Throws SymbolNotFound on failure to match.
                matches.append(
                    self.lookup_symbol_resolve_multiple(
                        asset_convertible,
                        as_of_date,
                    )
                )
            else:
                raise NotAssetConvertible(
                    "Input was %s, not AssetConvertible."
                    % asset_convertible
                )

        except SymbolNotFound:
            missing.append(asset_convertible)
            return None

    def lookup_generic(self,
                       asset_convertible_or_iterable,
                       as_of_date):
        """
        Convert a AssetConvertible or iterable of AssetConvertibles into
        a list of Asset objects.

        This method exists primarily as a convenience for implementing
        user-facing APIs that can handle multiple kinds of input.  It should
        not be used for internal code where we already know the expected types
        of our inputs.

        Returns a pair of objects, the first of which is the result of the
        conversion, and the second of which is a list containing any values
        that couldn't be resolved.
        """
        matches = []
        missing = []

        # Interpret input as scalar.
        if isinstance(asset_convertible_or_iterable, AssetConvertible):
            self._lookup_generic_scalar(
                asset_convertible=asset_convertible_or_iterable,
                as_of_date=as_of_date,
                matches=matches,
                missing=missing,
            )
            try:
                return matches[0], missing
            except IndexError:
                if hasattr(asset_convertible_or_iterable, '__int__'):
                    raise SidNotFound(sid=asset_convertible_or_iterable)
                else:
                    raise SymbolNotFound(symbol=asset_convertible_or_iterable)

        # Interpret input as iterable.
        try:
            iterator = iter(asset_convertible_or_iterable)
        except TypeError:
            raise NotAssetConvertible(
                "Input was not a AssetConvertible "
                "or iterable of AssetConvertible."
            )

        for obj in iterator:
            self._lookup_generic_scalar(obj, as_of_date, matches, missing)
        return matches, missing

    def map_identifier_index_to_sids(self, index, as_of_date):
        """
        This method is for use in sanitizing a user's DataFrame or Panel
        inputs.

        Takes the given index of identifiers, checks their types, builds assets
        if necessary, and returns a list of the sids that correspond to the
        input index.

        Parameters
        __________
        index : Iterable
            An iterable containing ints, strings, or Assets
        as_of_date : pandas.Timestamp
            A date to be used to resolve any dual-mapped symbols

        Returns
        _______
        List
            A list of integer sids corresponding to the input index
        """
        # This method assumes that the type of the objects in the index is
        # consistent and can, therefore, be taken from the first identifier
        first_identifier = index[0]

        # Ensure that input is AssetConvertible (integer, string, or Asset)
        if not isinstance(first_identifier, AssetConvertible):
            raise MapAssetIdentifierIndexError(obj=first_identifier)

        # If sids are provided, no mapping is necessary
        if isinstance(first_identifier, Integral):
            return index

        # If symbols or Assets are provided, construction and mapping is
        # necessary
        self.consume_identifiers(index)

        # Look up all Assets for mapping
        matches = []
        missing = []
        for identifier in index:
            self._lookup_generic_scalar(identifier, as_of_date,
                                        matches, missing)

        # Handle missing assets
        if len(missing) > 0:
            warnings.warn("Missing assets for identifiers: " + missing)

        # Return a list of the sids of the found assets
        return [asset.sid for asset in matches]

    def _insert_metadata(self, identifier, **kwargs):
        """
        Inserts the given metadata kwargs to the entry for the given
        identifier. Matching fields in the existing entry will be overwritten.
        :param identifier: The identifier for which to insert metadata
        :param kwargs: The keyed metadata to insert
        """
        if identifier in self.metadata_cache:
            # Multiple pass insertion no longer supported.
            # This could and probably should raise an Exception, but is
            # currently just a short-circuit for compatibility with existing
            # testing structure in the test_algorithm module which creates
            # multiple sources which all insert redundant metadata.
            return

        entry = {}

        for key, value in kwargs.items():
            # Do not accept invalid fields
            if key not in ASSET_FIELDS:
                continue
            # Do not accept Nones
            if value is None:
                continue
            # Do not accept empty strings
            if value == '':
                continue
            # Do not accept nans from dataframes
            if isinstance(value, float) and np.isnan(value):
                continue
            entry[key] = value

        # Check if the sid is declared
        try:
            entry['sid']
        except KeyError:
            # If the identifier is not a sid, assign one
            if hasattr(identifier, '__int__'):
                entry['sid'] = identifier.__int__()
            else:
                if self.allow_sid_assignment:
                    # Assign the sid the value of its insertion order.
                    # This assumes that we are assigning values to all assets.
                    entry['sid'] = len(self.metadata_cache)
                else:
                    raise SidAssignmentError(identifier=identifier)

        # If the file_name is in the kwargs, it will be used as the symbol
        try:
            entry['symbol'] = entry.pop('file_name')
        except KeyError:
            pass

        # If the identifier coming in was a string and there is no defined
        # symbol yet, set the symbol to the incoming identifier
        try:
            entry['symbol']
            pass
        except KeyError:
            if isinstance(identifier, string_types):
                entry['symbol'] = identifier

        # If the company_name is in the kwargs, it may be the asset_name
        try:
            company_name = entry.pop('company_name')
            try:
                entry['asset_name']
            except KeyError:
                entry['asset_name'] = company_name
        except KeyError:
            pass

        # If dates are given as nanos, pop them
        try:
            entry['start_date'] = entry.pop('start_date_nano')
        except KeyError:
            pass
        try:
            entry['end_date'] = entry.pop('end_date_nano')
        except KeyError:
            pass
        try:
            entry['notice_date'] = entry.pop('notice_date_nano')
        except KeyError:
            pass
        try:
            entry['expiration_date'] = entry.pop('expiration_date_nano')
        except KeyError:
            pass

        # Process dates to Timestamps
        try:
            entry['start_date'] = pd.Timestamp(entry['start_date'], tz='UTC')
        except KeyError:
            # Set a default start_date of the EPOCH, so that all date queries
            # work when a start date is not provided.
            entry['start_date'] = pd.Timestamp(0, tz='UTC')
        try:
            # Set a default end_date of 'now', so that all date queries
            # work when a end date is not provided.
            entry['end_date'] = pd.Timestamp(entry['end_date'], tz='UTC')
        except KeyError:
            entry['end_date'] = self.end_date_to_assign
        try:
            entry['notice_date'] = pd.Timestamp(entry['notice_date'],
                                                tz='UTC')
        except KeyError:
            pass
        try:
            entry['expiration_date'] = pd.Timestamp(entry['expiration_date'],
                                                    tz='UTC')
        except KeyError:
            pass

        # Build an Asset of the appropriate type, default to Equity
        asset_type = entry.pop('asset_type', 'equity')
        if asset_type.lower() == 'equity':
            try:
                fuzzy = entry['symbol'].replace(self.fuzzy_char, '') \
                    if self.fuzzy_char else None
            except KeyError:
                fuzzy = None
            asset = Equity(**entry)
            c = self.conn.cursor()
            t = (asset.sid,
                 asset.symbol,
                 asset.asset_name,
                 asset.start_date.value if asset.start_date else None,
                 asset.end_date.value if asset.end_date else None,
                 asset.first_traded.value if asset.first_traded else None,
                 asset.exchange,
                 fuzzy)
            c.execute("""INSERT INTO equities(
            sid,
            symbol,
            asset_name,
            start_date,
            end_date,
            first_traded,
            exchange,
            fuzzy)
            VALUES(?, ?, ?, ?, ?, ?, ?, ?)""", t)

            t = (asset.sid,
                 'equity')
            c.execute("""INSERT INTO asset_router(sid, asset_type)
            VALUES(?, ?)""", t)

        elif asset_type.lower() == 'future':
            asset = Future(**entry)
            c = self.conn.cursor()
            t = (asset.sid,
                 asset.symbol,
                 asset.asset_name,
                 asset.start_date.value if asset.start_date else None,
                 asset.end_date.value if asset.end_date else None,
                 asset.first_traded.value if asset.first_traded else None,
                 asset.exchange,
                 asset.root_symbol,
                 asset.notice_date.value if asset.notice_date else None,
                 asset.expiration_date.value
                 if asset.expiration_date else None,
                 asset.contract_multiplier)
            c.execute("""INSERT INTO futures(
            sid,
            symbol,
            asset_name,
            start_date,
            end_date,
            first_traded,
            exchange,
            root_symbol,
            notice_date,
            expiration_date,
            contract_multiplier)
            VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)""", t)

            t = (asset.sid,
                 'future')
            c.execute("""INSERT INTO asset_router(sid, asset_type)
            VALUES(?, ?)""", t)
        else:
            raise InvalidAssetType(asset_type=asset_type)

        self.metadata_cache[identifier] = entry

    def consume_identifiers(self, identifiers):
        """
        Consumes the given identifiers in to the metadata cache of this
        AssetFinder.
        """
        for identifier in identifiers:
            # Handle case where full Assets are passed in
            # For example, in the creation of a DataFrameSource, the source's
            # 'sid' args may be full Assets
            if isinstance(identifier, Asset):
                sid = identifier.sid
                metadata = identifier.to_dict()
                metadata['asset_type'] = identifier.__class__.__name__
                self.insert_metadata(identifier=sid, **metadata)
            else:
                self.insert_metadata(identifier)

    def consume_metadata(self, metadata):
        """
        Consumes the provided metadata in to the metadata cache. The
        existing values in the cache will be overwritten when there
        is a conflict.
        :param metadata: The metadata to be consumed
        """
        # Handle dicts
        if isinstance(metadata, dict):
            self._insert_metadata_dict(metadata)
        # Handle DataFrames
        elif isinstance(metadata, pd.DataFrame):
            self._insert_metadata_dataframe(metadata)
        # Handle readables
        elif hasattr(metadata, 'read'):
            self._insert_metadata_readable(metadata)
        else:
            raise ConsumeAssetMetaDataError(obj=metadata)

    def clear_metadata(self):
        """
        Used for testing.
        """
        self.metadata_cache = {}

        self.conn = sqlite3.connect(':memory:')
        self.create_db_tables()

    def insert_metadata(self, identifier, **kwargs):
        self._insert_metadata(identifier, **kwargs)
        self.conn.commit()

    def _insert_metadata_dataframe(self, dataframe):
        for identifier, row in dataframe.iterrows():
            self._insert_metadata(identifier, **row)
        self.conn.commit()

    def _insert_metadata_dict(self, dict):
        for identifier, entry in dict.items():
            self._insert_metadata(identifier, **entry)
        self.conn.commit()

    def _insert_metadata_readable(self, readable):
        for row in readable.read():
            # Parse out the row of the readable object
            metadata_dict = {}
            for field in ASSET_FIELDS:
                try:
                    row_value = row[field]
                    # Avoid passing placeholders
                    if row_value and (row_value != 'None'):
                        metadata_dict[field] = row[field]
                except KeyError:
                    continue
                except IndexError:
                    continue
            # Locate the identifier, fail if not found
            if 'sid' in metadata_dict:
                identifier = metadata_dict['sid']
            elif 'symbol' in metadata_dict:
                identifier = metadata_dict['symbol']
            else:
                raise ConsumeAssetMetaDataError(obj=row)
            self._insert_metadata(identifier, **metadata_dict)
        self.conn.commit()

    def _compute_asset_lifetimes(self):
        """
        Compute and cache a recarry of asset lifetimes.

        FUTURE OPTIMIZATION: We're looping over a big array, which means this
        probably should be in C/Cython.
        """
        with self.conn as transaction:
            results = transaction.execute(
                'SELECT sid, start_date, end_date from equities'
            ).fetchall()

            lifetimes = np.recarray(
                shape=(len(results),),
                dtype=[('sid', 'i8'), ('start', 'i8'), ('end', 'i8')],
            )

            # TODO: This is **WAY** slower than it could be because we have to
            # check for None everywhere.  If we represented "no start date" as
            # 0, and "no end date" as MAX_INT in our metadata, this would be
            # significantly faster.
            NO_START = 0
            NO_END = np.iinfo(int).max
            for idx, (sid, start, end) in enumerate(results):
                lifetimes[idx] = (
                    sid,
                    start if start is not None else NO_START,
                    end if end is not None else NO_END,
                )
        return lifetimes

    def lifetimes(self, dates):
        """
        Compute a DataFrame representing asset lifetimes for the specified date
        range.

        Parameters
        ----------
        dates : pd.DatetimeIndex
            The dates for which to compute lifetimes.

        Returns
        -------
        lifetimes : pd.DataFrame
            A frame of dtype bool with `dates` as index and an Int64Index of
            assets as columns.  The value at `lifetimes.loc[date, asset]` will
            be True iff `asset` existed on `data`.

        See Also
        --------
        numpy.putmask
        """
        # This is a less than ideal place to do this, because if someone adds
        # assets to the finder after we've touched lifetimes we won't have
        # those new assets available.  Mutability is not my favorite
        # programming feature.
        if self._asset_lifetimes is None:
            self._asset_lifetimes = self._compute_asset_lifetimes()
        lifetimes = self._asset_lifetimes

        raw_dates = dates.asi8[:, None]
        mask = (lifetimes.start <= raw_dates) & (raw_dates <= lifetimes.end)
        return pd.DataFrame(mask, index=dates, columns=lifetimes.sid)

class AssetConvertible(with_metaclass(ABCMeta)):
    """
    ABC for types that are convertible to integer-representations of
    Assets.

    Includes Asset, six.string_types, and Integral
    """
    pass

AssetConvertible.register(Integral)
AssetConvertible.register(Asset)
# Use six.string_types for Python2/3 compatibility
for _type in string_types:
    AssetConvertible.register(_type)

class NotAssetConvertible(ValueError):
    pass


text:
#include "../common/platform.h"
#include "dance_ui.h"

#include "../display/background.h"
#include "../display/context_menu.h"
#include "../display/device.h"
#include "../display/grid.h"
#include "../display/label.h"
#include "../display/scrollbar.h"
#include "../display/window.h"
#include "call.h"

namespace dance {

display::Font titleCardFont("Times New Roman", 14, true, false, false, null, null);

const char* PlayListEditor::tabLabel() {
	if (_playList->label().size() > 0)
		return _playList->label().c_str();
	else
		return "<unnamed>";
}

display::Canvas* PlayListEditor::tabBody() {
	if (_body == null) {
		display::Grid* infoArea = new display::Grid();
			infoArea->cell(new display::Spacer(0, 5, 0, 0, new display::Label("Description: ")));
			display::Label* playListName = new display::Label(_playList->label());
			playListName->setBackground(&display::editableBackground);
			infoArea->cell(new display::Spacer(5, new display::Bevel(2, true, playListName)));
			infoArea->row();
			infoArea->cell(new display::Label("Created:"));
			string cDate, mDate;
			cDate.localTime(_playList->created, "%a %b %d, %Y %I:%M:%S %p");
			infoArea->cell(new display::Label(cDate));
			infoArea->row();
			infoArea->cell(new display::Label("Modified:"));
			if (_playList->modified != 0)
				mDate.localTime(_playList->modified, "%a %b %d, %Y %I:%M:%S %p");
			infoArea->cell(new display::Label(mDate));
		infoArea->complete();
		infoArea->setBackground(&display::buttonFaceBackground);
		display::Grid* g = new display::Grid();
			g->cell(infoArea);
			g->row();
			g->cell(commonTabBody(false));
		g->complete();
		_body = g;
		_body->functionKey.addHandler((DanceEditor*)this, &DanceEditor::onFunctionKey);
	}
	return _body;
}

const char* LibraryEditor::tabLabel() {
	return "My Library";
}

display::Canvas* LibraryEditor::tabBody() {
	if (_body == null) {
		_body = commonTabBody(true);
		_body->functionKey.addHandler((DanceEditor*)this, &DanceEditor::onFunctionKey);
	}
	return _body;
}

DanceFileEditor::DanceFileEditor(Dance* dance, DanceFrame* frame) : DanceEditor(dance, frame) {
	_label = fileSystem::basename(dance->filename());
	_nameLabel = null;
}

DanceFileEditor::~DanceFileEditor() {
	delete dance();
}

const char* DanceFileEditor::tabLabel() {
	return _label.c_str();
}

display::Canvas* DanceFileEditor::tabBody() {
	if (_body == null) {
		_nameLabel = new display::Label(dance()->filename());
		display::Grid* infoArea = new display::Grid();
			infoArea->cell(new display::Spacer(0, 5, 0, 5, new display::Label("Filename: ")));
			infoArea->cell(new display::Spacer(5, _nameLabel));
		infoArea->complete();
		infoArea->setBackground(&display::buttonFaceBackground);
		display::Grid* g = new display::Grid();
			g->cell(infoArea);
			g->row();
			g->cell(commonTabBody(true));
		g->complete();

		_nameLabel->setBackground(&display::editableBackground);
		_body = g;
		_body->functionKey.addHandler((DanceEditor*)this, &DanceEditor::onFunctionKey);
	}
	return _body;
}

DanceEditor::DanceEditor(Dance* dance, DanceFrame* frame) {
	selected.addHandler(this, &DanceEditor::onSelected);
	_dance = dance;
	_frame = frame;
	_body = null;
	_commonBody = null;
	_printJob = null;
	_listening = false;
	_scrollerHandler = null;
}

DanceEditor::~DanceEditor() {
	delete _scrollerHandler;
	for (int i = 0; i < _sequenceMap.size(); i++) {
		delete _sequenceMap[i].checked;
		delete _sequenceMap[i].checkedHandler;
	}
	delete _body;
	_undoStack.clear();
}

bool DanceEditor::deleteTab() {
	return false;
}

void DanceEditor::onSelected() {
	display::RootCanvas* c = _body->rootCanvas();
	if (c)
		c->setKeyboardFocus(_body);
}

bool DanceEditor::needsSave() {
	return !_undoStack.atSavedState();
}

bool DanceEditor::save() {
	if (_dance->filename().size() == 0) {
		OPENFILENAME o;
		char buffer[1024];

		memset(&o, 0, sizeof o);
		buffer[0] = 0;
		o.lStructSize = sizeof o;
		o.lpstrDefExt = "dnc";
		display::RootCanvas* rc = _body->rootCanvas();
		if (rc == null)
			rc = _frame->rootCanvas();
		o.hwndOwner = rc->handle();
		o.lpstrFile = buffer;
		o.nMaxFile = sizeof buffer;
		if (GetSaveFileName(&o)) {
			string ext = fileSystem::extension(buffer);
			if (ext != ".dnc")
				_frame->setStatus("Saving dance file with non-standard extension");
			_dance->setFilename(buffer);
		}
	}
	if (!fileSystem::createBackupFile(_dance->filename())) {
		_frame->setStatus("Could not create backup for " + _dance->filename());
		return false;
	}
	if (_dance->save()) {
		_frame->setStatus(_dance->label() + " saved to " + _dance->filename());
		tabModified();
		_undoStack.markSavedState();
		return true;
	} else {
		_frame->setStatus("FAILED: " + _dance->label() + " save to " + _dance->filename());
		return false;
	}
}

bool DanceEditor::calculateOneSequence() {
	const vector<Sequence*>& sequences = _dance->sequences();
	for (int i = 0; i < sequences.size(); i++) {
		Sequence* s = sequences[i];
		if (s->updateStatus(myDefinitions)) {
			touch(s);
			return true;
		}
	}
	return false;
}

display::Canvas* DanceEditor::commonTabBody(bool editPlayLists) {
	if (_body == null) {
		editPlayLists = false;
		defaultDefinitions->changed.addHandler(this, &DanceEditor::grammarChanged);
		myDefinitions->changed.addHandler(this, &DanceEditor::grammarChanged);
		display::Grid* playListHeaders;
		display::Grid* playListAreaGrid;
		if (editPlayLists) {
			playListHeaders = new display::Grid();
				display::Label* titleCard = new display::Label("Play Lists");
				titleCard->setBackground(&display::buttonFaceBackground);
				titleCard->set_format(DT_CENTER);
				titleCard->set_font(&titleCardFont);
				playListHeaders->cell(display::dimension(4, 1), titleCard);
				playListHeaders->row();
				playListHeaders->cell(new display::Label("",2));
				playListHeaders->cell(new display::Label("  Level", 6));
				playListHeaders->cell(new display::Label("Date Created", 8));
				playListHeaders->cell(new display::Label("Description"));
			playListHeaders->complete();
			playListHeaders->setBackground(&display::buttonFaceBackground);
			_playListArea = new display::Grid();
				for (int i = 0; i < _dance->playLists().size(); i++) {
					PlayList* playList = _dance->playLists()[i];
					if (i != 0)
						_playListArea->row();
					showPlayListInfo(i, playList);
				}
			_playListArea->complete();
			_playListArea->mouseCursor = display::standardCursor(display::HAND);
			_playListArea->click.addHandler(this, &DanceEditor::onPlayListClick);
			_playListArea->openContextMenu.addHandler(this, &DanceEditor::onOpenPlayListContextMenu);
			display::Label* morePlayList = new display::Label("Add another play list...");
			morePlayList->mouseCursor = display::standardCursor(display::HAND);
			morePlayList->click.addHandler(this, &DanceEditor::onAddPlayList);
			playListAreaGrid = new display::Grid();
				playListAreaGrid->row();
				playListAreaGrid->cell(_playListArea);
				playListAreaGrid->row();
				playListAreaGrid->cell(morePlayList);
			playListAreaGrid->complete();
		}
		display::Grid* sequenceHeaders = new display::Grid();
			if (editPlayLists) {
				display::Label* titleCard = new display::Label("Sequences");
				titleCard->setBackground(&display::buttonFaceBackground);
				titleCard->set_format(DT_CENTER);
				titleCard->set_font(&titleCardFont);
				sequenceHeaders->cell(display::dimension(6, 1), titleCard);
				sequenceHeaders->row();
			}
			sequenceHeaders->cell(new display::Label("ID",4));
			sequenceHeaders->cell(new display::Label("",2));
			sequenceHeaders->cell(new display::Label("Status",7));
			sequenceHeaders->cell(new display::Label("  Level", 6));
			sequenceHeaders->cell(new display::Label("Date Created", 8));
			sequenceHeaders->cell(new display::Label("Comment"));
		sequenceHeaders->complete();
		sequenceHeaders->setBackground(&display::buttonFaceBackground);
		_sequenceArea = new display::Grid();
			for (int i = 0; i < _dance->sequences().size(); i++) {
				Sequence* sequence = _dance->sequences()[i];
				if (i != 0)
					_sequenceArea->row();
				showSequenceInfo(i, sequence);
			}
		_sequenceArea->complete();
		_sequenceArea->mouseCursor = display::standardCursor(display::HAND);
		_sequenceArea->click.addHandler(this, &DanceEditor::onClick);
		_sequenceArea->openContextMenu.addHandler(this, &DanceEditor::onOpenContextMenu);
		display::Label* moreSeq = new display::Label("Add another sequence...");
		moreSeq->mouseCursor = display::standardCursor(display::HAND);
		moreSeq->click.addHandler(this, &DanceEditor::onAddSequence);
		display::Grid* seqAreaGrid = new display::Grid();
			seqAreaGrid->cell(_sequenceArea);
			seqAreaGrid->row();
			seqAreaGrid->cell(new display::Filler(moreSeq));
		seqAreaGrid->complete();
		display::Grid* g = new display::Grid();
			if (editPlayLists) {
				g->cell(playListHeaders);
				g->row();
				g->cell(playListAreaGrid);
				g->row();
			}
			g->cell(sequenceHeaders);
			g->row();
			g->cell(seqAreaGrid);
		g->complete();

		display::ScrollableCanvas* scroller = new display::ScrollableCanvas();
		scroller->setBackground(&display::editableBackground);
		scroller->append(g);
		_scrollerHandler = new display::ScrollableCanvasHandler(scroller);
		_body = scroller;
	}
	return _body;
}

bool DanceEditor::startPrinting() {
	_printJob = danceWindow->openPrintDialog();
	if (_printJob) {
		_printJob->startPrinting();
		return true;
	} else
		return false;
}

display::Font printerCallFont("Times New Roman", 16, false, false, false, null, null);
display::Font printerCommentFont("Times New Roman", 12, false, false, false, null, null);
display::Font printerVersionFont("Times New Roman", 12, false, false, false, null, null);
display::Font printerDateFont("Times New Roman", 12, false, false, false, null, null);
display::Font printerLevelFont("Times New Roman", 12, false, false, false, null, null);
display::Measure topMargin(0.5, display::INCH);
display::Measure headerMargin(0.25, display::INCH);
display::Measure leftMargin(0.5, display::INCH);
display::Measure rightMargin(0.5, display::INCH);
display::Measure bottomMargin(0.5, display::INCH);

void DanceEditor::print(Sequence* sequence) {
	if (_printJob == null)
		return;
	if (!loadPrinterFonts()) {
		_frame->setStatus("Could not load printer fonts");
		return;
	}
//	sequence->updateStages(myDefinitions);
	string cDate;
	cDate.localTime(sequence->modified, "%a %b %d, %Y %I:%M:%S %p");
	display::Label* creationDate = new display::Label(cDate, &printerDateFont);
	display::Grid* infoArea = new display::Grid();
		infoArea->cell(creationDate);
		infoArea->cell();
		display::Label* level = new display::Label(levels[sequence->level()], &printerLevelFont);
		level->set_format(DT_RIGHT);
		infoArea->cell(level);
		infoArea->row();
		infoArea->cell(new display::Label(sequence->createdWith, &printerVersionFont));
		infoArea->cell();
		display::Label* comment = new display::Label(sequence->comment, &printerCommentFont);
		comment->set_format(DT_RIGHT);
		infoArea->cell(comment);
	infoArea->complete();
	infoArea->resizeColumn(1);
	display::Grid* callArea = new display::Grid();
		for (int i = 0; i < sequence->text().size(); i++) {
			callArea->row();
			display::Label* call = new display::Label(sequence->text()[i], &printerCallFont);
			callArea->cell(new display::Spacer(0, 10, 0, 0, call));
//			Picture* p = new Picture(sequence->stages()[i]->final(), 16);
//			callArea->cell(p);
		}
	callArea->complete();
	display::Grid* g = new display::Grid();
		g->cell(new display::Spacer(leftMargin.pixels(_printJob), topMargin.pixels(_printJob), 0, 0));
		g->cell();
		g->cell(new display::Spacer(rightMargin.pixels(_printJob), 0, 0, 0));
		g->row();
		g->cell();
		g->cell(infoArea);
		g->cell();
		g->row();
		g->cell(new display::Spacer(0, headerMargin.pixels(_printJob), 0, 0));
		g->row();
		g->cell();
		g->cell(callArea);
		g->cell();
		g->row();
		g->cell(new display::Spacer(0, bottomMargin.pixels(_printJob), 0, 0));
	g->complete();
	g->resizeColumn(1);
	g->resizeRow(3);
	_printJob->append(g);
	_printJob->startPage();
	_printJob->paint();
	_printJob->endPage();
/*
	display::Spacer* s = new display::Spacer(0, g);
	s->setBackground(&display::editableBackground);
	display::Window* w = new display::Window();
	w->append(s);
	w->show();
	warningMessage("When done click OK");
	w->hide();
	delete w;
 */
}

void DanceEditor::donePrinting() {
	if (_printJob) {
		_printJob->close();
		delete _printJob;
		_printJob = null;
	}
}

void DanceEditor::touch(Sequence* sequence) {
	for (int i = 0; i < _sequenceMap.size(); i++)
		if (_sequenceMap[i].sequence == sequence) {
			_sequenceMap[i].comment->set_value(sequence->comment);
			_sequenceMap[i].level->set_value(levels[sequence->level()]);
			setSequenceStatus(_sequenceMap[i].status, sequence);
			break;
		}
	tabModified();
}

void DanceEditor::onFunctionKey(display::FunctionKey fk, display::ShiftState ss) {
	switch (fk) {
	case	display::FK_Y:
		if (ss == display::SS_CONTROL) {
			if (_undoStack.nextRedo())
				_undoStack.redo();
			else
				_frame->setStatus("No more redo");
		}
		break;

	case	display::FK_Z:
		if (ss == display::SS_CONTROL) {
			if (_undoStack.nextUndo())
				_undoStack.undo();
			else
				_frame->setStatus("No more undo");
		}
		break;

	case	display::FK_A:
		if (_body->rootCanvas() &&
			_body->rootCanvas()->keyFocus() == _body) {
			for (int i = 0; i < _playListMap.size(); i++)
				_playListMap[i].checked->set_value(true);
			for (int i = 0; i < _sequenceMap.size(); i++)
				_sequenceMap[i].checked->set_value(true);
		}
		break;
	}
}

void DanceEditor::showSequenceInfo(int i, Sequence* sequence) {
	SequenceMapEntry sme;

	sme.sequence = sequence;
	display::Label* x;
	sme.checked = new data::Boolean(false);
	display::Toggle* check = new display::Toggle(sme.checked);
	sme.checkedHandler = new display::ToggleHandler(check);
	sme.checked->changed.addHandler(this, &DanceEditor::onChecked, sme.checked, i);
	_sequenceArea->cell(new display::Label(string(i + 1), 4));
	_sequenceArea->cell(new display::Spacer(0, 1, 10, 1, check));
	x = new display::Label("", 7);
//	sequence->updateStages(myDefinitions);
	setSequenceStatus(x, sequence);
	sme.status = x;
	_sequenceArea->cell(x);
	sme.level = new display::Label(levels[sequence->level()], 6);
	_sequenceArea->cell(sme.level);
	string date;
	date.localTime(sequence->created, "%m/%d/%Y");
	_sequenceArea->cell(new display::Label(date, 8));
	sme.comment = new display::Label(sequence->comment);
	_sequenceArea->cell(sme.comment);
	_sequenceMap.push_back(sme);
}

void DanceEditor::showPlayListInfo(int i, PlayList* playList) {
	PlayListMapEntry pme;

	pme.playList = playList;
	display::Label* x;
	pme.checked = new data::Boolean(false);
	display::Toggle* check = new display::Toggle(pme.checked);
	new display::ToggleHandler(check);
	pme.checked->changed.addHandler(this, &DanceEditor::onPlayListChecked, pme.checked, i);
	_playListArea->cell(new display::Spacer(0, 1, 10, 1, check));
	pme.level = new display::Label(levels[playList->level()], 6);
	_playListArea->cell(pme.level);
	string date;
	date.localTime(playList->created, "%m/%d/%Y");
	_playListArea->cell(new display::Label(date, 8));
	pme.comment = new display::Label(playList->comment);
	_playListArea->cell(pme.comment);
	_playListMap.push_back(pme);
}

void DanceEditor::onClick(display::MouseKeys mKeys, display::point p, display::Canvas* target) {
	editSequence(p, target);
}

void DanceEditor::onAddSequence(display::MouseKeys mKeys, display::point p, display::Canvas* target) {
	Sequence* sequence = _dance->newSequence();
	string levelName = getPreference("defaultLevel");
	sequence->setLevelName(levelName);
	_sequenceArea->reopen(-1, -1);
		showSequenceInfo(_sequenceMap.size(), sequence);
	_sequenceArea->complete();
	SequenceEditor* se = _frame->edit(this, _dance->sequences().size(), sequence);
	_frame->rootCanvas()->run(se, &SequenceEditor::select, 0);
}

void DanceEditor::onOpenContextMenu(display::point p, display::Canvas* target) {
	display::ContextMenu* c = new display::ContextMenu(_sequenceArea->rootCanvas(), p, target);
	int hitRow = hitSequence(p);
	const vector<Sequence*>& sequences = _dance->sequences();
	Sequence* sequence = sequences[hitRow];
	c->choice("Edit this sequence")->click.addHandler(this, &DanceEditor::editSequence);
	c->choice("Perform this sequence")->click.addHandler(this, &DanceEditor::performSequence, sequence);
	c->choice("Print this sequence")->click.addHandler(this, &DanceEditor::printSequence, sequence);

	if (sequence->lastChecked() < defaultDefinitions->lastChanged() ||
		sequence->lastChecked() < myDefinitions->lastChanged())
		c->choice("Recheck this sequence")->click.addHandler(this, &DanceEditor::recheckSequence);

	for (int i = 0; i < sequences.size(); i++) {
		Sequence* s = sequences[i];
		if (s->lastChecked() < defaultDefinitions->lastChanged() ||
			s->lastChecked() < myDefinitions->lastChanged()) {
			c->choice("Recheck all sequences")->click.addHandler(this, &DanceEditor::recheckAllSequences);
			break;
		}
	}
	const vector<PlayList*>& playLists = _dance->playLists();
	bool listSelected = false;
	for (int i = 0; i < playLists.size(); i++) {
		if (_playListMap[i].checked->value()) {
			listSelected = true;
			break;
		}
	}
	for (int i = 0; i < sequences.size(); i++) {
		if (_sequenceMap[i].checked->value()) {
			if (listSelected) {
				c->choice("Print selected play lists and sequences")->click.addHandler(this, &DanceEditor::printSelected);
				c->choice("Perform selected play lists and sequences")->click.addHandler(this, &DanceEditor::performSelected);
			} else {
				c->choice("Print selected sequences")->click.addHandler(this, &DanceEditor::printSelected);
				c->choice("Perform selected sequences")->click.addHandler(this, &DanceEditor::performSelected);
			}
			break;
		}
	}
	c->show();
}

void DanceEditor::onChecked(data::Boolean* b, int index) {
	_body->rootCanvas()->setKeyboardFocus(_body);
	if (b->value())
		_sequenceMap[index].status->setBackground(&display::buttonFaceBackground);
	else
		_sequenceMap[index].status->setBackground(&display::editableBackground);
}

void DanceEditor::onPlayListClick(display::MouseKeys mKeys, display::point p, display::Canvas* target) {
	editPlayList(p, target);
}

void DanceEditor::onAddPlayList(display::MouseKeys mKeys, display::point p, display::Canvas* target) {
	PlayList* playList = _dance->newPlayList();
	_playListArea->reopen(-1, -1);
		showPlayListInfo(_playListMap.size(), playList);
	_playListArea->complete();
}

void DanceEditor::onOpenPlayListContextMenu(display::point p, display::Canvas* target) {
	display::ContextMenu* c = new display::ContextMenu(_playListArea->rootCanvas(), p, target);
	int hitRow = hitPlayList(p);
	const vector<PlayList*>& playLists = _dance->playLists();
	PlayList* playList = playLists[hitRow];
	c->choice("Edit this play list")->click.addHandler(this, &DanceEditor::editPlayList);
	c->choice("Perform this play list")->click.addHandler(this, &DanceEditor::performPlayList, playList);
	c->choice("Print this play list's sequences")->click.addHandler(this, &DanceEditor::printPlayList, playList);
	if (playList->lastChecked() < defaultDefinitions->lastChanged() ||
		playList->lastChecked() < myDefinitions->lastChanged())
		c->choice("Recheck this play list")->click.addHandler(this, &DanceEditor::recheckPlayList);

	const vector<Sequence*>& sequences = _dance->sequences();
	bool seqSelected = false;
	for (int i = 0; i < sequences.size(); i++) {
		if (_sequenceMap[i].checked->value()) {
			seqSelected = true;
			break;
		}
	}
	for (int i = 0; i < playLists.size(); i++) {
		if (_playListMap[i].checked->value()) {
			if (seqSelected) {
				c->choice("Print selected play lists and sequences")->click.addHandler(this, &DanceEditor::printSelected);
				c->choice("Perform selected play lists and sequences")->click.addHandler(this, &DanceEditor::performSelected);
			} else {
				c->choice("Print selected play lists")->click.addHandler(this, &DanceEditor::printSelected);
				c->choice("Perform selected play lists")->click.addHandler(this, &DanceEditor::performSelected);
			}
			break;
		}
	}
	c->show();
}

void DanceEditor::onPlayListChecked(data::Boolean* b, int index) {
	_body->rootCanvas()->setKeyboardFocus(_body);
	if (b->value())
		_playListMap[index].comment->setBackground(&display::buttonFaceBackground);
	else
		_playListMap[index].comment->setBackground(&display::editableBackground);
}

display::Color unchecked(0xff8000);

void DanceEditor::grammarChanged() {
	for (int i = 0; i < _sequenceMap.size(); i++) {
		_sequenceMap[i].status->set_value("Unchecked");
		_sequenceMap[i].status->set_textColor(&unchecked);
	}
}

int DanceEditor::hitSequence(display::point p) {
	int deltaY = p.y - _sequenceArea->bounds.topLeft.y;
	int rows = _sequenceArea->rows();
	int hitRow;
	if (rows == 1)
		hitRow = 0;
	else {
		int rowHeight = _sequenceArea->y(1);
		hitRow = deltaY / rowHeight;
	}
	return hitRow;
}

int DanceEditor::hitPlayList(display::point p) {
	int deltaY = p.y - _playListArea->bounds.topLeft.y;
	int rows = _playListArea->rows();
	int hitRow;
	if (rows == 1)
		hitRow = 0;
	else {
		int rowHeight = _playListArea->y(1);
		hitRow = deltaY / rowHeight;
	}
	return hitRow;
}

void DanceEditor::editSequence(display::point p, display::Canvas* target) {
	if (!_listening) {
		_body->rootCanvas()->afterInputEvent.addHandler(&_undoStack, &display::UndoStack::rememberCurrentUndo);
		_listening = true;
	}
	int hitRow = hitSequence(p);
	Sequence* sequence = _dance->sequences()[hitRow];
	_frame->edit(this, hitRow, sequence);
}

void DanceEditor::editPlayList(display::point p, display::Canvas* target) {
	if (!_listening) {
		_body->rootCanvas()->afterInputEvent.addHandler(&_undoStack, &display::UndoStack::rememberCurrentUndo);
		_listening = true;
	}
	int hitRow = hitPlayList(p);
	PlayList* playList = _dance->playLists()[hitRow];
	_frame->edit(this, hitRow, playList);
}

void DanceEditor::printSequence(display::point p, display::Canvas* target, Sequence* sequence) {
	if (startPrinting()) {
		print(sequence);
		donePrinting();
	}
}

void DanceEditor::printPlayList(display::point p, display::Canvas* target, PlayList* playList) {
	vector<Sequence*> sequences;
	playList->fetchSequences(&sequences);
	if (sequences.size() > 0) {
		if (startPrinting()) {
			for (int i = 0; i < sequences.size(); i++)
				print(sequences[i]);
			donePrinting();
		}
	} else
		_frame->setStatus("No sequences to print");
}

void DanceEditor::performSequence(display::point p, display::Canvas* target, Sequence* sequence) {
	vector<PlayList*> playLists;
	vector<Sequence*> sequences;

	sequences.push_back(sequence);
	Performance* perf = new Performance(_frame, _dance, playLists, sequences);
	_frame->start(perf);
}

void DanceEditor::performPlayList(display::point p, display::Canvas* target, PlayList* playList) {
	vector<PlayList*> playLists;
	vector<Sequence*> sequences;

	playLists.push_back(playList);
	Performance* perf = new Performance(_frame, _dance, playLists, sequences);
	_frame->start(perf);
}

void DanceEditor::recheckSequence(display::point p, display::Canvas* target) {
	int hitRow = hitSequence(p);
	recheckSequence(_dance->sequences()[hitRow]);
}

void DanceEditor::recheckPlayList(display::point p, display::Canvas* target) {
	int hitRow = hitPlayList(p);
	PlayList* playList = _dance->playLists()[hitRow];
	vector<Sequence*> sequences;
	playList->fetchSequences(&sequences);
	if (sequences.size()) {
		for (int i = 0; i < sequences.size(); i++)
			recheckSequence(sequences[i]);
	} else
		_frame->setStatus("No sequences to recheck");
}

void DanceEditor::recheckAllSequences(display::point p, display::Canvas* target) {
	for (int i = 0; i < _sequenceMap.size(); i++) {
		Sequence* sequence = _sequenceMap[i].sequence;

		sequence->updateStatus(myDefinitions);
		setSequenceStatus(_sequenceMap[i].status, sequence);
	}
}

void DanceEditor::recheckSequence(Sequence* sequence) {
	sequence->updateStatus(myDefinitions);
	_frame->refreshSequenceEditor(sequence);
	for (int i = 0; i < _sequenceMap.size(); i++)
		if (_sequenceMap[i].sequence == sequence) {
			setSequenceStatus(_sequenceMap[i].status, sequence);
			break;
		}
}

void DanceEditor::printSelected(display::point p, display::Canvas* target) {
	if (startPrinting()) {
		for (int i = 0; i < _sequenceMap.size(); i++) {
			if (_sequenceMap[i].checked->value()) {
				Sequence* sequence = _sequenceMap[i].sequence;

				print(sequence);
			}
		}
		donePrinting();
	}
}

void DanceEditor::performSelected(display::point p, display::Canvas* target) {
	vector<PlayList*> playLists;
	vector<Sequence*> sequences;
	for (int i = 0; i < _playListMap.size(); i++)
		if (_playListMap[i].checked->value())
			playLists.push_back(_playListMap[i].playList);
	for (int i = 0; i < _sequenceMap.size(); i++)
		if (_sequenceMap[i].checked->value())
			sequences.push_back(_sequenceMap[i].sequence);
	Performance* p = new Performance(_frame, _dance, playLists, sequences);
	_frame->start(p);
}

void DanceEditor::setSequenceStatus(display::Label* label, Sequence* sequence) {
	switch (sequence->status) {
	case	SEQ_UNCHECKED:
		label->set_value("Unchecked");
		label->set_textColor(&unchecked);
		break;

	case	SEQ_FAILED:
		label->set_value("Failed");
		label->set_textColor(&display::red);
		break;

	case	SEQ_UNRESOLVED:
		label->set_value("Unresolved");
		label->set_textColor(&display::blue);
		break;

	case	SEQ_READY:
		label->set_value("Ready");
		label->set_textColor(&display::black);
		break;

	default:
		label->set_value("Bad value: " + int(sequence->status));
		label->set_textColor(&display::red);
	}
}

}  // namespace dance


text:
@protocol EnglishProtocol <DoHomeworkProtocol>

-(void)reciteWords;
-(void)practiceExchanges;
@end


text:
import { AnyType, RequiredRuntype, ErrorThrower } from "./runtype";
import { Helpers } from "./helpers";

export class TupleRuntype<TS extends AnyType[], T extends Array<any>> extends RequiredRuntype<T> {
    constructor(protected innerTypes: TS) {
        super("object", `tuple of [${innerTypes.map(type => type.metadata.runtimeType).join(", ")}]`);

        this.constraint((array) => Array.isArray(array) || `should be a ${this.metadata.runtimeType}, not an object`);
        this.constraint((array) => (array.length === innerTypes.length) || `has ${array.length} elements but it should have exactly ${this.innerTypes.length}`);
    }

    decode(value: any, thrower: ErrorThrower = Error, attributeName?: string): T {
        const array: T = super.decode(value, thrower, attributeName);
        if (array) {
            const results = new Array<any>(this.innerTypes.length);
            for (let i = 0; i < array.length; i++) {
                try {
                    results[i] = this.innerTypes[i].decode(array[i], Error, "");
                } catch (err) {
                    throw new thrower(Helpers.formatErrorMessage(attributeName, `is a tuple, but its element at position ${i} is invalid because ${err.message}`));
                }
            }

            return results as any;
        } else {
            return array;
        }
    }

}


text:
from setuptools.command import easy_install
easy_install.main(["-U", "virtualenv"])
easy_install.main(["-U", "gdata"])
easy_install.main(["-U", "flask"])
easy_install.main(["-U", "pyparsing"])
easy_install.main(["-U", "google-api-python-client"])


text:
Unfortunately, AppFlower doesn't provide an automated method for adding/removing plug-ins (yet!). But there is still some good news, since Symfony has such mechanisms. You can use these to install or uninstall any general purpose Symfony plug-in.

If you don't know how to do this, please consult the related part of the Symfony documentation.

It is important to note however, that AppFlower specific plug-ins ***must be installed and uninstalled manually*** for now, since they are not available as PEAR packages. We will provide an easy to use installer in the near future, but until then you should follow the general method described here.

# Adding AppFlower Plug-ins

This is relatively simple, just follow the steps below:

1. Download the package from our website
2. Add the plug-in to the ./plugins folder of your application
3. See the README file (./README or ./docs/readme.txt) for further instructions.

You should always check the plug-in README file, since many plug-ins require some configuration changes or other customization to work properly.

The configuration files must be edited with a normal plain text editor! The most convenient solution is Studio's integrated editor, but you may also use applications like Notepad (Windows), TextEdit (Mac) or Emacs (Linux). Anyway, using something like MS Word is not recommended:-).


text:
package text.analyse.common.utils.properties;

public class Config {
	private Config() {
	}

}


text:
using System.Collections.Generic;

namespace JoeriBekker.PuttyTunnelManager
{
    class Core
    {
        private static Core instance = null;

        public static Session EmptySession = new EmptySession();

        public static Core Instance()
        {
            if (Core.instance == null)
                Core.instance = new Core();

            return Core.instance;
        }

        private List<Session> sessions;

        private Core()
        {
            this.sessions = new List<Session>();

            Initialize();
        }

        public void Refresh()
        {
            this.sessions.Clear();

            Initialize();
        }

        private void Initialize()
        {
            foreach (string sessionName in PuttySettings.Instance().Sessions)
            {
                this.sessions.Add(Session.Load(sessionName));
            }
        }

        public List<Session> Sessions
        {
            get { return this.sessions; }
        }

        public List<Tunnel> Tunnels
        {
            get
            {
                List<Tunnel> tunnels = new List<Tunnel>();
                foreach (Session session in this.Sessions)
                {
                    foreach (Tunnel tunnel in session.Tunnels)
                    {
                        tunnels.Add(tunnel);
                    }
                }
                return tunnels;
            }
        }
    }
}


text:
// Decompiled by Jad v1.5.8g. Copyright 2001 Pavel Kouznetsov.
// Jad home page: http://www.kpdus.com/jad.html
// Decompiler options: packimports(3)

package gov.nih.nci.qi.util;

import com.oroinc.net.ftp.FTPClient;
import com.oroinc.net.ftp.FTPReply;
import java.io.*;
import java.util.Hashtable;

public class FTPUtil extends FTPClient
    implements Runnable
{

    public static synchronized FTPUtil getInstance()
    {
        if(onlyInstance == null)
            onlyInstance = new FTPUtil();
        return onlyInstance;
    }

    public FTPUtil()
    {
    }

    public static void transfer(File afile[], File afile1[], Long long1, String s, String s1, String s2, String s3)
    {
        serverURL_ = s;
        serverUsername_ = s2;
        serverPassword_ = s3;
        fileArray_ = afile;
        fileArray2_ = afile1;
        path_ = s1;
        imageUID_ = long1;
        transfer_ = new Thread(new FTPUtil());
        transfer_.run();
    }

    public void run()
    {
        Object obj = null;
        try
        {
            connect(serverURL_);
            login(serverUsername_, serverPassword_);
            changeWorkingDirectory(path_);
            int i = getReplyCode();
            if(!FTPReply.isPositiveCompletion(i))
            {
                disconnect();
                System.err.println("FTP server refused connection.");
            }
            Hashtable hashtable = getFilename(fileArray_);
            Hashtable hashtable1 = getFilename(fileArray2_);
            if(hashtable != null && hashtable.size() > 0)
            {
                for(int j = 0; j < hashtable.size(); j++)
                {
                    String s = (String)hashtable.get((new StringBuilder()).append("\"").append(j).append("\"").toString());
                    System.out.println((new StringBuilder()).append("111111str1:").append(s).toString());
                    System.out.println((new StringBuilder()).append("files2.size():").append(hashtable1.size()).toString());
                    if(hashtable1 != null && hashtable1.size() == 0)
                    {
                        setFileType(2);
                        System.out.println((new StringBuilder()).append("str1 is 999999:").append(s).append("fileArray_[i]:").append(fileArray_[j]).toString());
                        boolean flag = storeFile(s, new FileInputStream(fileArray_[j]));
                        if(flag)
                            System.out.println((new StringBuilder()).append("\n").append(s).append(" successfully transferred...").toString());
                        else
                            System.out.println((new StringBuilder()).append("Transfer failed for file...").append(s).toString());
                    }
                    if(hashtable1 == null || hashtable1.size() <= 0)
                        continue;
                    for(int l = 0; l < hashtable1.size(); l++)
                    {
                        String s2 = (String)hashtable1.get((new StringBuilder()).append("\"").append(l).append("\"").toString());
                        boolean flag1 = deleteFile(s2);
                        setFileType(2);
                        System.out.println((new StringBuilder()).append("str1 is 999999:").append(s).append("fileArray_[i]:").append(fileArray_[j]).toString());
                        flag1 = storeFile(s, new FileInputStream(fileArray_[j]));
                        if(flag1)
                            System.out.println((new StringBuilder()).append("\n").append(s2).append(" successfully  deleted.. and ").append(s).append("sucessfully transferred").toString());
                        else
                            System.out.println("Transfer failed for file...");
                    }

                }

            }
            if(hashtable.size() == 0 && hashtable1 != null && hashtable1.size() > 0)
            {
                for(int k = 0; k < hashtable1.size(); k++)
                {
                    String s1 = (String)hashtable1.get((new StringBuilder()).append("\"").append(k).append("\"").toString());
                    System.out.println((new StringBuilder()).append("files2.size():").append(hashtable1.size()).append("str2:").append(s1).toString());
                    if(hashtable != null && hashtable.size() == 0)
                    {
                        System.out.println("---I am here---");
                        boolean flag2 = deleteFile(s1);
                        if(flag2)
                            System.out.println((new StringBuilder()).append("\n").append(s1).append(" successfully deleted...").toString());
                        else
                            System.out.println((new StringBuilder()).append("Delete failed for file...").append(s1).toString());
                    }
                }

            }
        }
        catch(IOException ioexception)
        {
            if(isConnected())
            {
                try
                {
                    disconnect();
                    System.out.println("disconnect ftp");
                }
                catch(IOException ioexception2) { }
                System.err.println("Could not connect to server.");
                ioexception.printStackTrace();
            }
        }
        try
        {
            disconnect();
        }
        catch(IOException ioexception1) { }
    }

    private Hashtable getFilename(File afile[])
    {
        Hashtable hashtable = new Hashtable();
        if(afile != null)
        {
            for(int i = 0; i < afile.length; i++)
            {
                File file = afile[i];
                String s = file.getName().trim();
                System.out.println((new StringBuilder()).append("file2:").append(s).toString());
                System.out.println((new StringBuilder()).append("imageUID_:").append(imageUID_).toString());
                if(imageUID_ != null)
                {
                    String s1 = (new StringBuilder()).append(imageUID_).append(".").append(s.substring(s.lastIndexOf(".") + 1)).toString();
                    System.out.println((new StringBuilder()).append("file3:").append(s1).toString());
                    hashtable.put((new StringBuilder()).append("\"").append(i).append("\"").toString(), s1);
                } else
                {
                    System.out.println("this is for deleting");
                    hashtable.put((new StringBuilder()).append("\"").append(i).append("\"").toString(), s);
                }
            }

        }
        return hashtable;
    }

    public void deleteAllFiles(File afile[], File afile1[], String s, String s1, String s2, String s3, String s4)
    {
        serverURL_ = s;
        serverUsername_ = s3;
        serverPassword_ = s4;
        fileArray_ = afile;
        fileArray2_ = afile1;
        path_ = s1;
        path2_ = s2;
        imageUID_ = null;
        delete();
    }

    private void delete()
    {
        Object obj = null;
        boolean flag = false;
        boolean flag1 = false;
        try
        {
            connect(serverURL_);
            System.out.println(serverURL_);
            System.out.print(getReplyString());
            login(serverUsername_, serverPassword_);
            if(fileArray_ != null && fileArray_.length > 0 && !flag1)
            {
                System.out.println("this is for modelImg");
                flag = changeWorkingDirectory(path_);
            }
            if(flag && !flag1)
            {
                Hashtable hashtable = getFilename(fileArray_);
                for(int j = 0; j < hashtable.size(); j++)
                {
                    String s = (String)hashtable.get((new StringBuilder()).append("\"").append(j).append("\"").toString());
                    System.out.println((new StringBuilder()).append("files.size():").append(hashtable.size()).toString());
                    boolean flag3 = deleteFile(s);
                    if(flag3)
                        System.out.println((new StringBuilder()).append("\n").append(s).append(" successfully deleted...").toString());
                    else
                        System.out.println((new StringBuilder()).append("Delete failed for file...").append(s).toString());
                }

                flag = false;
            }
            if(fileArray2_ != null && fileArray2_.length > 0 && !flag)
            {
                System.out.println((new StringBuilder()).append("this is for constructsImg").append(printWorkingDirectory()).toString());
                flag1 = changeWorkingDirectory(path2_);
                System.out.println((new StringBuilder()).append("this is for constructsImg after ").append(printWorkingDirectory()).toString());
            }
            if(flag1 && !flag)
            {
                System.out.println("Test Msg...");
                Hashtable hashtable1 = getFilename(fileArray2_);
                for(int k = 0; k < hashtable1.size(); k++)
                {
                    String s1 = (String)hashtable1.get((new StringBuilder()).append("\"").append(k).append("\"").toString());
                    System.out.println((new StringBuilder()).append("files2.size():").append(hashtable1.size()).toString());
                    boolean flag4 = deleteFile(s1);
                    if(flag4)
                        System.out.println((new StringBuilder()).append("\n").append(s1).append(" successfully deleted...").toString());
                    else
                        System.out.println((new StringBuilder()).append("Delete failed for file...").append(s1).toString());
                }

                boolean flag2 = false;
            }
            int i = getReplyCode();
            System.out.println((new StringBuilder()).append("reply:").append(i).toString());
            if(!FTPReply.isPositiveCompletion(i))
            {
                disconnect();
                System.err.println("FTP server refused connection.");
            }
        }
        catch(IOException ioexception)
        {
            if(isConnected())
            {
                try
                {
                    disconnect();
                    System.out.println("disconnect ftp");
                }
                catch(IOException ioexception2) { }
                System.err.println("Could not connect to server.");
                ioexception.printStackTrace();
            }
        }
        try
        {
            disconnect();
        }
        catch(IOException ioexception1) { }
    }

    private static File fileArray_[];
    private static File fileArray2_[];
    private static String serverURL_ = null;
    private static String serverPassword_ = null;
    private static String serverUsername_ = null;
    private static Thread transfer_ = null;
    private static Thread delete_ = null;
    private static String path_ = null;
    private static String path2_ = null;
    private static Long imageUID_ = null;
    private static FTPUtil onlyInstance = null;

}


text:
/*
 * @(#)DocContainer.java
 *
 * @project    : org.fugerit.java.core.doc
 * @package    : org.fugerit.java.core.doc
 * @creation   : 06/set/06
 * @license	   : META-INF/LICENSE.TXT
 */
package org.fugerit.java.core.doc;

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

/**
 *

 *
 * @author mfranci
 *
 */
public class DocContainer extends DocElement {

	private List<DocElement> elementList;

	public DocContainer() {
		this.elementList = new ArrayList<DocElement>();
	}

	public Iterator<DocElement> docElements() {
		return this.elementList.iterator();
	}

	public int containerSize() {
		return this.elementList.size();
	}

	public void addElement( DocElement docElement ) {
		this.elementList.add( docElement );
	}

}


text:
using System;
using System.ComponentModel;

namespace SharpKit.DotNet.Html.workers
{

    using SharpKit.JavaScript;
    using SharpKit.DotNet.JavaScript;
    using SharpKit.DotNet.Html.fileapi;
    using SharpKit.DotNet.Html.html.shadow;
    using SharpKit.DotNet.Html.html.track;
    using SharpKit.DotNet.Html.inspector;
    using SharpKit.DotNet.Html.loader.appcache;
    using SharpKit.DotNet.Html.battery;
    using SharpKit.DotNet.Html.gamepad;
    using SharpKit.DotNet.Html.geolocation;
    using SharpKit.DotNet.Html.indexeddb;
    using SharpKit.DotNet.Html.intents;
    using SharpKit.DotNet.Html.mediasource;
    using SharpKit.DotNet.Html.mediastream;
    using SharpKit.DotNet.Html.networkinfo;
    using SharpKit.DotNet.Html.notifications;
    using SharpKit.DotNet.Html.proximity;
    using SharpKit.DotNet.Html.quota;
    using SharpKit.DotNet.Html.speech;
    using SharpKit.DotNet.Html.webaudio;
    using SharpKit.DotNet.Html.webdatabase;
    using SharpKit.DotNet.Html.plugins;
    using SharpKit.DotNet.Html.storage;
    using SharpKit.DotNet.Html.svg;
    using SharpKit.DotNet.Html.workers;

    [JsType(JsMode.Prototype, Export = false, PropertiesAsFields = true, NativeCasts = true, Name = "AbstractWorker")]
    public partial class AbstractWorker : EventTarget,
                        IEventTarget<ErrorEventType, ErrorEvent<AbstractWorker, AbstractWorker>>
    {
#if COMP_WITH_EVENTS_PROP
#if HIDE_EVENTS_PROP
        [EditorBrowsable(EditorBrowsableState.Never)]
#endif
        [JsProperty(Name = "onerror", NativeField = true)]
        public EventListener<ErrorEvent<AbstractWorker, AbstractWorker>> onError { get; set; }
#endif
        public event EventListener<ErrorEvent<AbstractWorker, AbstractWorker>> OnError
        {
            [JsMethod(Name = "addEventListener", InsertArg0 = "\"error\"", InsertArg1 = "false")]
            add { }
            [JsMethod(Name = "removeEventListener", InsertArg0 = "\"error\"", InsertArg1 = "false")]
            remove { }
        }

        [JsMethod(Name = "addEventListener")]
        public void AddEventListener(ErrorEventType type, EventListener<ErrorEvent<AbstractWorker, AbstractWorker>> listener, bool useCapture = false) { }
        [JsMethod(Name = "dispatchEvent")]
        public bool DispatchEvent(ErrorEvent<AbstractWorker, AbstractWorker> evt) { return default(bool); }
        [JsMethod(Name = "removeEventListener")]
        public void RemoveEventListener(ErrorEventType type, EventListener<ErrorEvent<AbstractWorker, AbstractWorker>> listener, bool useCapture = false) { }

        #region Properties and methods inherited to hide for Intellisense
        [EditorBrowsable(EditorBrowsableState.Never)]
        [JsMethod(Name = "addEventListener")]
        public new void AddEventListener(JsString type, EventListener listener, bool useCapture = false) { }
        [EditorBrowsable(EditorBrowsableState.Never)]
        [JsMethod(Name = "dispatchEvent")]
        public new bool DispatchEvent(Event evt) { return default(bool); }
        [EditorBrowsable(EditorBrowsableState.Never)]
        [JsMethod(Name = "removeEventListener")]
        public new void RemoveEventListener(JsString type, EventListener listener, bool useCapture = false) { }
        #endregion

    }

}


text:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<!--
 Copyright 2013 Oliver Schmid
 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.
-->
	<modelVersion>4.0.0</modelVersion>
	<groupId>ch.unifr.pai.twice.dragndrop</groupId>
	<artifactId>DragNDrop</artifactId>
	<name>DragNDrop</name>
	<description >A multi-pointer and touch capable drag and drop library. The library relies on the extra information added to native mouse events through the multi-pointer functionality and allows - with a touch sensitive implementation to provide drag and drop functionalities on touch-based devices with the same API.</description>
	<dependencies>
		<dependency>
			<groupId>ch.unifr.pai.twice.multipointer</groupId>
			<artifactId>Multipointer</artifactId>
		</dependency>
	</dependencies>
	<parent>
		<groupId>ch.unifr.pai.twice</groupId>
		<artifactId>TWICE-Lib</artifactId>
		<version>1.0.0-FIXED</version>
		<relativePath>../TWICE-Lib</relativePath>
	</parent>
	<version>${twice.version}</version>
</project>


text:
#include <aws/email/model/GetSendStatisticsRequest.h>
#include <aws/core/utils/StringUtils.h>
#include <aws/core/utils/memory/stl/AWSStringStream.h>

using namespace Aws::SES::Model;
using namespace Aws::Utils;

GetSendStatisticsRequest::GetSendStatisticsRequest()
{
}

Aws::String GetSendStatisticsRequest::SerializePayload() const
{
  Aws::StringStream ss;
  ss << "Action=GetSendStatistics&";
  ss << "Version=2010-12-01";
  return ss.str();
}

void  GetSendStatisticsRequest::DumpBodyToUrl(Aws::Http::URI& uri ) const
{
  uri.SetQueryString(SerializePayload());
}


text:
class StaticPagesController < ApplicationController
  skip_before_filter :require_login

  layout "top"

  def top
  end
end


text:
    <meta http-equiv="Content-Type" content="text/html; charset=Windows-1252" />
    <meta name="vs_targetSchema" content="http://schemas.microsoft.com/intellisense/ie5" />
    <title>ILayout.Format Method</title>
    <xml>
    </xml>
    <link rel="stylesheet" type="text/css" href="MSDN.css" />

            log4net SDK Reference

ILayout.Format Method

 Implement this method to create your own layout format.

        [Visual Basic]

Sub Format( _
   ByVal writer As TextWriter, _
   ByVal loggingEvent As LoggingEvent _
)

        [C#]

        void Format(
   TextWriter writer,
   LoggingEvent loggingEvent
);

Parameters

          writer

The TextWriter to write the formatted event to

          loggingEvent

The event to format

Remarks

 This method is called by an appender to format the loggingEvent as text and output to a writer.

 If the caller does not have a TextWriter and prefers the event to be formatted as a String then the following code can be used to format the event into a StringWriter.

[C#]
StringWriter writer = new StringWriter();
Layout.Format(writer, loggingEvent);
string formattedEvent = writer.ToString();

See Also

ILayout Interface | log4net.Layout Namespace

Copyright 2001-2006 The Apache Software Foundation.

Generated from assembly log4net [1.2.10.0]