text:
<!--
   This file is part of the X12Parser library that provides tools to
   manipulate X12 messages using Ruby native syntax.

   http://x12parser.rubyforge.org

   Copyright (C) 2009 APP Design, Inc.

   This library is free software; you can redistribute it and/or
   modify it under the terms of the GNU Lesser General Public
   License as published by the Free Software Foundation; either
   version 2.1 of the License, or (at your option) any later version.

   This library is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
   Lesser General Public License for more details.

   You should have received a copy of the GNU Lesser General Public
   License along with this library; if not, write to the Free Software
   Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA

   $Id: HCP.xml 78 2009-05-12 22:27:26Z ikk $
-->

<Segment name="HCP" comment="To specify pricing or repricing information about a health care claim or line item">
  <Field name="PricingMethodology" required="y" min="2" max="2" validation="T1473" comment="Code specifying pricing methodology at which the claim or line item has been priced or repriced"/>
  <Field name="MonetaryAmount1" type="double" required="y" min="1" max="18" comment="Monetary amount"/>
  <Field name="MonetaryAmount2" type="double" required="y" min="1" max="18" comment="Monetary amount"/>
  <Field name="ReferenceIdentification1" required="y" min="1" max="50" comment="Reference information as defined for a particular Transaction Set or as specified by the Reference Identification Qualifier"/>
  <Field name="Rate" type="double" required="y" min="1" max="9" comment="Rate expressed in the standard monetary denomination for the currency specified"/>
  <Field name="ReferenceIdentification2" required="y" min="1" max="50" comment="Reference information as defined for a particular Transaction Set or as specified by the Reference Identification Qualifier"/>
  <Field name="MonetaryAmount3" type="double" required="y" min="1" max="18" comment="Monetary amount"/>
  <Field name="ProductServiceId1" required="y" min="1" max="48" comment="Identifying number for a product or service"/>
  <Field name="ProductServiceIdQualifier" required="y" min="2" max="2" validation="T235" comment="Code identifying the type/source of the descriptive number used in Product/Service ID (234)"/>
  <Field name="ProductServiceId2" required="y" min="1" max="48" comment="Identifying number for a product or service"/>
  <Field name="UnitOrBasisForMeasurementCode" required="y" min="2" max="2" validation="T355" comment="Code specifying the units in which a value is being expressed, or manner in which a measurement has been taken"/>
  <Field name="Quantity" type="double" required="y" min="1" max="15" comment="Numeric value of quantity"/>
  <Field name="RejectReasonCode" required="y" min="2" max="2" validation="T901" comment="Code assigned by issuer to identify reason for rejection"/>
  <Field name="PolicyComplianceCode" required="y" min="1" max="2" validation="T1526" comment="Code specifying policy compliance"/>
  <Field name="ExceptionCode" required="y" min="1" max="2" validation="T1527" comment="Code specifying the exception reason for consideration of out-of-network health care services"/>
</Segment>


text:
<?xml version="1.0" encoding="UTF-8"?>
<info:toolkitInfoModel xmlns:common="http://www.ibm.com/xmlns/prod/streams/spl/common"
 xmlns:info="http://www.ibm.com/xmlns/prod/streams/spl/toolkitInfo">
<info:identity>
  <info:name>com.ibm.streamsx.topology.pysamples</info:name>
  <info:description>Sample toolkit for Python support demonstrating translation</info:description>
  <info:version>1.0.0</info:version>
  <info:requiredProductVersion>4.0.1.0</info:requiredProductVersion>
</info:identity>
<info:dependencies>
</info:dependencies>
  <info:resources>
    <info:messageSet name="TopologySplpyResource">
      <info:lang default="true">en_US/TopologySplpyResource.xlf</info:lang>
      <info:lang>de_DE/TopologySplpyResource.xlf</info:lang>
      <info:lang>es_ES/TopologySplpyResource.xlf</info:lang>
      <info:lang>fr_FR/TopologySplpyResource.xlf</info:lang>
      <info:lang>it_IT/TopologySplpyResource.xlf</info:lang>
      <info:lang>ja_JP/TopologySplpyResource.xlf</info:lang>
      <info:lang>ko_KR/TopologySplpyResource.xlf</info:lang>
      <info:lang>pt_BR/TopologySplpyResource.xlf</info:lang>
      <info:lang>ru_RU/TopologySplpyResource.xlf</info:lang>
      <info:lang>zh_CN/TopologySplpyResource.xlf</info:lang>
      <info:lang>zh_TW/TopologySplpyResource.xlf</info:lang>
    </info:messageSet>
  </info:resources>
</info:toolkitInfoModel>

redpajama_set_name: RedPajamaGithub


text:
This tweak enables all iOS Notification Center bulletins to be sent to bluetooth devices implementing the Message Access Protocol. First implemented in iOS 6, MAP is a protocol that enables bluetooth devices to receive message notifications. This tweak allows devices like the [Pebble](http://getpebble.com) watch to receive all notifications that would normally appear on an iOS device's lockscreen.

This tweak functions by eliminating the filter in Apple's MAP implementation so that all notifications are considered 'interesting', not just Message notifications, and thus the name.

## Getting Started

### Prequisites

- [Xcode 4.6](https://itunes.apple.com/us/app/xcode/id497799835), which includes the iOS 6.1 SDK
- A jailbroken device running iOS 6 or later

### Building

The first step to build the project is to clone the repository and initialize all of its submodules:

``` sh
git clone git://github.com/conradev/BTNotificationEnabler.git
cd BTNotificationEnabler
git submodule update --init
```

To build the project, you need only run

```
make
```

### Installing

To install this on a jailbroken device, some additional tools are needed.

The first tool is `ldid`, which is used for fakesigning binaries. Ryan Petrich has a build on his [Github mirror](https://github.com/rpetrich/ldid):

``` sh
curl -O http://cloud.github.com/downloads/rpetrich/ldid/ldid.zip
unzip ldid.zip
mv ldid theos/bin/
rm ldid.zip
```

To build a Debian package, `dpkg` is required. You can install it from [Homebrew](http://mxcl.github.com/homebrew/):

``` sh
brew install dpkg
```

To build a package in the project directory, you can run:

``` sh
make package
```

and to automatically install this package on your jailbroken device (over SSH), you can run:

``` sh
make package install THEOS_DEVICE_IP=xxx.xxx.xxx.xxx
```

## License

BTNotificationEnabler is available under the MIT license. See the LICENSE file for more info.


text:
package orwell.proxy.config.elements;

import java.util.ArrayList;

/**
 * Created by Michaël Ludmann on 03/05/15.
 */
public interface IConfigRobots {
    IConfigRobot getConfigRobot(String tempRoutingID) throws Exception;

    ArrayList<IConfigRobot> getConfigRobotsToRegister();
}


text:
			Templating

						No template variables defined

									${{variable.name}}

								{{variable.query}}

									Edit

							Variable name
							<input type="text" class="input-medium"
								   ng-model='current.name' placeholder="name"
								   required></input>

							Type
							<select class="input-medium" ng-model="current.type"
									ng-options="f for f in ['query', 'interval', 'custom']"
									ng-change="typeChanged()"></select>

							Datasource
							<select class="input input-medium"
									ng-model="current.datasource"
									ng-options="f.value as f.name for f in datasources"></select>

						<editor-opt-bool text="Refresh on load"
										 show-if="current.type === 'query'"
										 tip="Check if you want values to be updated on dashboard load, will slow down dashboard load time"
										 model="current.refresh"></editor-opt-bool>

								Values
								<input type="text" class="input-xxlarge"
									   ng-model='current.query'
									   ng-blur="runQuery()"
									   placeholder="name"></input>

							<editor-opt-bool text="Include auto interval"
											 model="current.auto"
											 change="runQuery()"></editor-opt-bool>

								Auto interval steps
									<tip>How many steps, roughly, the interval
										is rounded and will not always match
										this count
										<tip>

								<select class="input-mini"
										ng-model="current.auto_count"
										ng-options="f for f in [3,5,10,30,50,100,200]"
										ng-change="runQuery()"></select>

								Values seperated by
									comma
								<input type="text" class="input-xxlarge"
									   ng-model='current.query'
									   ng-blur="runQuery()"
									   placeholder="1, 10, 20, myvalue"></input>

								Variable values
									query
								<input type="text" class="input-xxlarge"
									   ng-model='current.query'
									   placeholder="apps.servers.*"></input>
								<button class="btn btn-small btn-success"
										ng-click="runQuery()"
										bs-tooltip="'Execute query'"
										data-placement="right"></button>

								regex (optional, if you
									want to extract part of a series name or
									metric node segment)
								<input type="text" class="input-xxlarge"
									   ng-model='current.regex'
									   placeholder="/.*-(.*)-.*/"></input>
								<button class="btn btn-small btn-success"
										ng-click="runQuery()"
										bs-tooltip="'execute query'"
										data-placement="right"></button>

							<editor-opt-bool text="All option"
											 model="current.includeAll"
											 change="runQuery()"></editor-opt-bool>

								All format
								<select class="input-medium"
										ng-model="current.allFormat"
										ng-change="runQuery()"
										ng-options="f for f in ['glob', 'wildcard', 'regex wildcard', 'regex values']"></select>

								All value
								<input type="text" class="input-xlarge"
									   ng-model='current.options[0].value'></input>

							Variable values (showing
								20/{{current.options.length}})

									{{option.text}}

		<button type="button" class="btn btn-success pull-left"
				ng-show="editor.index === 2" ng-click="update();">Update
		</button>
		<button type="button" class="btn btn-success pull-left"
				ng-show="editor.index === 1" ng-click="add();">Add
		</button>
		<button type="button" class="btn btn-success pull-right"
				ng-click="dismiss();">Close
		</button>


text:
require 'spec_helper'

describe Docxtor do
  context 'prerequisites' do
    it 'has a version number' do
      expect { Docxtor::VERSION != nil }
    end
  end
end


text:
public class Constructor2 {
	public static int test() {
		Constructor2Aux c = new Constructor2Aux(2);
		return c.field;
	}
}

public class Constructor2Aux {
	public int field*;

	public Constructor2Aux(int field) {
		this.field = field;
	}
}


text:
import type Documentation from '../Documentation';

import getMemberValuePath from '../utils/getMemberValuePath';
import recast from 'recast';
import resolveToValue from '../utils/resolveToValue';

var {types: {namedTypes: types}} = recast;

export default function displayNameHandler(
  documentation: Documentation,
  path: NodePath
) {
  var displayNamePath = getMemberValuePath(path, 'displayName');
  if (!displayNamePath) {
    return;
  }
  displayNamePath = resolveToValue(displayNamePath);
  if (!displayNamePath || !types.Literal.check(displayNamePath.node)) {
    return;
  }
  documentation.set('displayName', displayNamePath.node.value);
}


text:
package com.dangdang.ddframe.rdb.sharding.api.strategy.slave;

import com.dangdang.ddframe.rdb.sharding.fixture.TestDataSource;
import org.junit.Test;

import javax.sql.DataSource;
import java.util.Arrays;

import static org.hamcrest.core.Is.is;
import static org.junit.Assert.assertThat;

public final class RoundRobinSlaveLoadBalanceStrategyTest {

    private RoundRobinSlaveLoadBalanceStrategy roundRobinSlaveLoadBalanceStrategy = new RoundRobinSlaveLoadBalanceStrategy();

    @Test
    public void assertGetDataSource() {
        DataSource slaveDataSource1 = new TestDataSource("test_ds_slave_1");
        DataSource slaveDataSource2 = new TestDataSource("test_ds_slave_2");
        assertThat(roundRobinSlaveLoadBalanceStrategy.getDataSource("ds", Arrays.asList(slaveDataSource1, slaveDataSource2)), is(slaveDataSource1));
        assertThat(roundRobinSlaveLoadBalanceStrategy.getDataSource("ds", Arrays.asList(slaveDataSource1, slaveDataSource2)), is(slaveDataSource2));
        assertThat(roundRobinSlaveLoadBalanceStrategy.getDataSource("ds", Arrays.asList(slaveDataSource1, slaveDataSource2)), is(slaveDataSource1));
    }
}


text:
package com.touchgraph.graphlayout.graphelements;

import  com.touchgraph.graphlayout.Node;
import  com.touchgraph.graphlayout.Edge;
import  com.touchgraph.graphlayout.TGException;

import  java.util.*;

/** GESUtils is a set of functions that return information about a GraphEltSet
  *
  * @author   Alexander Shapiro
  * @version  1.21  $Id: GESUtils.java,v 1.1.1.1 2007/01/07 07:58:19 andrew Exp $
  */
public class GESUtils {

   /** Returns a hashtable of Node-Integer pairs, where integers are the minimum
     * distance from the focusNode to any given Node, and the Nodes in the Hashtable
     * are all within radius distance from the focusNode.
     *
     * Nodes with edge degrees of more then maxAddEdgeCount are not added to the hashtable, and those
     * with edge degrees of more then maxExpandEdgeCount are added but not expanded.
     *
     * If unidirectional is set to true, then edges are only follewed in the forward direction.
     *
     */

    public static Hashtable calculateDistances(GraphEltSet ges, Node focusNode, int radius,
                                               int maxAddEdgeCount, int maxExpandEdgeCount,
                                               boolean unidirectional ) {
        Hashtable distHash = new Hashtable();
        distHash.put(focusNode,new Integer(0));

        TGNodeQueue nodeQ = new TGNodeQueue();
        nodeQ.push(focusNode);

        while (!nodeQ.isEmpty()) {
            Node n = nodeQ.pop();
            int currDist = ((Integer) distHash.get(n)).intValue();

            if (currDist>=radius) break;

            for (int i = 0 ; i < n.edgeCount(); i++) {
                Edge e=n.edgeAt(i);
                if(n!=n.edgeAt(i).getFrom() && unidirectional) continue;
                Node adjNode = e.getOtherEndpt(n);
                if(ges.contains(e) && !distHash.containsKey(adjNode) && adjNode.edgeCount()<=maxAddEdgeCount) {
                    if (adjNode.edgeCount()<=maxExpandEdgeCount) nodeQ.push(adjNode);
                    distHash.put(adjNode,new Integer(currDist+1));
                }
            }
        }
        return distHash;
    }

    public static Hashtable calculateDistances(GraphEltSet ges, Node focusNode, int radius ) {
        return calculateDistances(ges, focusNode, radius, 1000, 1000, false);
    }

   /** A temporary function that returns the largest connected subgraph in a GraphEltSet.
     */

    public static Collection getLargestConnectedSubgraph(GraphEltSet ges) {
        int nodeCount = ges.nodeCount();
        if(nodeCount==0) return null;

        Vector subgraphVector = new Vector();
        for(int i=0; i<nodeCount; i++) {
            Node n = ges.nodeAt(i);
            boolean skipNode=false;
            for (int j = 0; j<subgraphVector.size();j++) {
                if(((Collection) subgraphVector.elementAt(j)).contains(n)) {
                    skipNode=true;
                }
            }
            Collection subgraph = calculateDistances(ges,n,1000).keySet();
            if(subgraph.size()>nodeCount/2) return subgraph; //We are done
            if (!skipNode) subgraphVector.add(subgraph);

        }

        int maxSize=0;
        int maxIndex=0;
        for (int j = 0; j<subgraphVector.size();j++) {
            if(((Collection) subgraphVector.elementAt(j)).size()>maxSize) {
                maxSize = ((Collection) subgraphVector.elementAt(j)).size();
                maxIndex = j;
            }
        }

        return (Collection) subgraphVector.elementAt(maxIndex);
    }

} // end com.touchgraph.graphlayout.graphelements.GraphEltSet


text:
"""This module contains the SQLAlchemy based key/value storage system.

Needs special initialization procedure before usage.
please refer to README.rst of the package for more information.

public functions: initialize.
"""
from collections import namedtuple
import sys

from sqlalchemy import (
    and_,
    inspect,
    Integer,
    String,
)
from sqlalchemy.orm import (
    aliased,
    class_mapper,
    query,
    relation,
)
from sqlalchemy.schema import (
    Column,
    ForeignKey,
    Index,
    UniqueConstraint,
)

from metalchemy.types import JSONEncodedText

_root_path = '[root]'
_index_path = ''

# Tuple class describing the return value of the initialization function
Attributes = namedtuple('Attributes', ['Object', 'Field', 'Value', 'FieldWrapper', 'Metadata'])

# True if we are running on Python 3.
PY3 = sys.version_info[0] == 3

class UnicodeMixin(object):

    """Mixin class to handle defining the proper __str__/__unicode__ methods in Python 2 or 3."""

    if PY3:
        def __str__(self):
            return self.__unicode__()
    else:
        def __str__(self):
            return self.__unicode__().encode('utf8')

def get_object_id(obj):
    """Get object's id (primary key)."""
    if not isinstance(obj, type):
        cls = obj.__class__
    else:
        cls = obj
    return getattr(obj, class_mapper(cls).primary_key[0].name)

def initialize(base, table_name_prefix='metalchemy_'):
    """Initialize using given declarative base.

    :param base: SQLAlchemy declarative base class
    :param table_name_prefix: `str` prefix to use for table names
    :return: `Attributes` object which contains:
        * Object class
        * Field class
        * Value class
        * FieldWrapper class
        * Metadata class
    """
    class Object(base):

        """An alchemy model to assign a unique id to a Python object path.

        This model also initializes the hierarchical structure of the fields.

        Property:
        path (<str>) - A dotted path to the class we store metadata for.
        """

        __tablename__ = table_name_prefix + 'object'

        id = Column(Integer, primary_key=True)
        path = Column(String(length=60), nullable=False, unique=True)

        def __getattribute__(self, name):
            if name == 'fields' and 'fields' not in self.__dict__:
                # Expand the flat list of fields to a hierarchical structure
                nodes = {}
                for node in self._fieldnodes:
                    node.children = {}
                    nodes[node.id] = node

                fields = None
                for node in self._fieldnodes:
                    if node.parent_id is None:
                        fields = node
                    else:
                        nodes[node.parent_id].children[node.name] = node

                self.fields = fields
                return self.fields
            else:
                return super(Object, self).__getattribute__(name)

        def __repr__(self):
            return '<Object for instances of ' + self.path + '>'

    class Field(base):

        """Alchemy model for a single field definition.

        Fields can be nested in other fields.

        Properties:
        object - The <Object> to which this field belongs.
        parent - The parent <Field>, or None if this is the root field for an object.
        name   - The attribute name under which this field is available.
        title  - A string that can be used as a label when displaying this field.

        children - A dictionary of child <Fields>, where the key is the name of that child.
        """

        __tablename__ = table_name_prefix + 'field'

        id = Column(Integer, primary_key=True)
        obj_id = Column(
            Integer, ForeignKey(Object.__table__.c.id), nullable=False)
        name = Column(String(length=60), nullable=False, index=True)
        parent_id = Column(Integer, ForeignKey(id))
        title = Column(String(length=30), nullable=False, default='')

        object = relation(
            Object, backref='_fieldnodes', lazy=False, order_by=parent_id)
        parent = relation('Field', remote_side=id)

        __table_args__ = (UniqueConstraint(
            'obj_id', 'name', 'parent_id'), getattr(base, '__table_args__', {}))

        def __init__(self, *args, **kwargs):
            super(Field, self).__init__(*args, **kwargs)
            self.children = {}

        def __unicode__(self):
            return self.name

    class Value(base):

        """An alchemy model representing a value assigned to a metadata field for a specific object instance.

        Properties:
        instance_id - The primary key for the class instance to which this metadata value belongs.
        field       - The <Field> for which this is a value.
        idx         - The index in the array of values for the field.
        parent      - The parent <Value> (for hierarchical arrays)
        value       - The actual stored value.
        """

        __tablename__ = table_name_prefix + 'values'

        id = Column(Integer, primary_key=True)
        instance_id = Column(Integer, nullable=False, index=True)
        field_id = Column(
            Integer, ForeignKey(Field.__table__.c.id), nullable=False)
        idx = Column(Integer, nullable=False)
        parent_idx = Column(Integer, ForeignKey(id))
        value = Column(JSONEncodedText, nullable=True)

        field = relation(Field)
        parent = relation('Value', remote_side=id)

        def __unicode__(self):
            return u'id={0}, field={1}, idx={2}, parent={3}, value={4}'.format(
                self.id,
                repr(self.field), self.idx, self.parent_idx, self.value
            )
    Index('value', Value.value, mysql_length=8)

    class FieldWrapper(UnicodeMixin):

        """A helper class for a field for a specific object instance."""

        def __init__(self, parent, idxpath, indexed, wrapped, instance):
            """Initialize field wrapper instance.

            :param parent: `FieldWrapper` wrapper containing this wrapper, or None if this is the root.
            :param idxpath: - `str` index path to reach this specific field
            :param indexed: `int` indicates the index for this wrapper instance, or None if it is an unindexed instance
            :param wrapped: `Field` - The field to wrap.
            :param instance: - An instance of the class containing metadata.
            """
            self.__parent = parent
            self.__idxpath = idxpath
            self.__indexed = indexed
            self.__wrapped = wrapped
            self.__instance = instance
            self.__fields = {}

        def _get_name(self):
            """Return the name of this field."""
            if isinstance(self.__wrapped, Field):
                return self.__wrapped.name
            else:
                return self.__wrapped

        def _get_real_parent(self):
            """Return the parent wrapper that is not indexed."""
            if self.__indexed is not None:
                return self.__parent._get_real_parent()
            if self.__parent is not None and self.__parent.__indexed is not None:
                return self.__parent.__parent
            else:
                return self.__parent

        def _path(self):
            """Return a string describing the complete path to this field."""
            if self.__indexed is not None:
                return self.__parent._path()
            path = self._get_name()
            curr = self.__parent
            while curr is not None:
                if curr.__indexed is None:
                    path = (curr._get_name() or '') + '.' + path
                curr = curr.__parent
            return path

        def _init_values(self):
            """Load all metadata values for the wrapped object instance."""
            # Find a field node which has an actual Field instance associated with it, we need that
            # for its *object* property.
            field = self
            while not isinstance(field.__wrapped, Field):
                field = field.__parent
                if field.__parent is None:
                    # rare case, but happens
                    break

            values = {}
            try:
                objlist = (
                    inspect(self.__instance).session.query(Value)
                    .join(Field).filter(and_(
                        Field.obj_id == field.__wrapped.obj_id,
                        Value.instance_id == get_object_id(self.__instance))
                    ).all()
                )
            except Exception:
                objlist = []

            for v in objlist:
                if v.field_id not in values:
                    values[v.field_id] = []
                values[v.field_id].append(v)

            indexes = {}

            def set_values(path, field):
                if field.id in values:
                    for val in values[field.id]:
                        if val.parent is None:
                            idxpath = ''
                        else:
                            idxpath = indexes[val.parent]
                        idxpath += '.' + str(val.idx)
                        indexes[val] = idxpath
                        if path not in self.__instance._meta_values:
                            self.__instance._meta_values[path] = {}
                        self.__instance._meta_values[path][idxpath] = val

                for name, child in field.children.items():
                    set_values(path + '.' + name, child)

            self.__instance._meta_values = {_root_path: {}}
            set_values(
                field.__wrapped.object.fields.name, field.__wrapped.object.fields)
            self.__instance._meta_inited = True

        def _get_value(self):
            """Return the <Value> wrapped by this particular FieldWrapper."""
            path = self._path()
            idxpath = self.__idxpath
            if self.__indexed is not None:
                idxpath += '.' + str(self.__indexed)
            else:
                idxpath += '.0'
            if idxpath not in self.__instance._meta_values.get(path, ()):
                return None
            return self.__instance._meta_values[path][idxpath]

        def get_value(self):
            """Return the field's contained value."""
            if not self.__instance._meta_inited:
                self._init_values()

            value = self._get_value()

            return value.value if value is not None else None

        def __contains__(self, item):
            return item in self.get_value()

        def __getitem__(self, key):
            """Retrieve a `FieldWrapper` for a specific index of the current wrapper."""
            if not isinstance(key, int):
                raise TypeError(
                    'list indices must be integers, not ' + key.__class__.__name__)

            if self.__indexed is None:
                return FieldWrapper(self, self.__idxpath, key, self.__wrapped, self.__instance)
            else:
                return getattr(self, _index_path)[key]

        def __getattr__(self, name):
            """Handle getting attribute values of a field - i.e., retrieving child fields.

            This is equivalent to requesting the named attribute from the zeroth index: field.attr == field[0].attr
            """
            if name[:1] == '_':
                return self.__dict__[name]

            elif self.__indexed is None:
                return getattr(self[0], name)

            else:
                if name not in self.__fields:
                    # The requested attribute has not yet been wrapped
                    if isinstance(self.__wrapped, Field) and name in self.__wrapped.children:
                        # The requested attribute already exists in the hierarchy
                        # as a Field
                        self.__fields[name] = FieldWrapper(self, self.__idxpath + '.' + str(self.__indexed), None,
                                                           self.__wrapped.children[name], self.__instance)
                    else:
                        # The requested attribute does not yet exist in the
                        # hierarchy
                        self.__fields[name] = FieldWrapper(self, self.__idxpath + '.' + str(self.__indexed), None,
                                                           name, self.__instance)

                return self.__fields[name]

        def __bool__(self):
            return bool(self.get_value())

        def __nonzero__(self):
            return self.__bool__()

        def __setitem__(self, key, value):
            """Handle writing to an indexed value."""
            if self.__indexed is not None:
                # Writing to an already-indexed field requires getting the implicit
                # child for sub-indexing
                getattr(self, _index_path)[key] = value
                return

            if not isinstance(key, int):
                raise TypeError(
                    'list indices must be integers, not ' + key.__class__.__name__)

            if not self.__instance._meta_inited:
                self._init_values()

            self._ensure_writable()

            val = self[key]._get_value()
            session = inspect(self.__instance).session
            if val:
                val.value = value
            else:
                # There is no Value for the attribute and index yet, so create
                # one.
                assert get_object_id(self.__instance) is not None, (
                    'Metadata cannot be associated with an object '
                    'that does not yet have an id')
                newvalue = Value(
                    instance_id=get_object_id(self.__instance),
                    field=self.__wrapped,
                    idx=key,
                    parent=self.__parent._get_value(
                    ) if self.__parent is not None else None,
                    value=value
                )
                if self._path() not in self.__instance._meta_values:
                    self.__instance._meta_values[self._path()] = {}
                self.__instance._meta_values[
                    self._path()][self.__idxpath + '.' + str(key)] = newvalue
                val = newvalue
                session.add(val)
            session.flush()

        def __setattr__(self, name, value):
            """setattr handles setting of attribute values on a field - i.e. assigning values to child fields."""
            if name[:1] == '_':
                super(FieldWrapper, self).__setattr__(name, value)
            elif self.__indexed is None:
                setattr(self[0], name, value)
            else:
                # Assert there are no dots in the name, as this can potentially
                # lead to some horrible problems.
                assert name.find(
                    '.') == -1, 'Cannot assign to names with a dot in them'
                getattr(self, name)[0] = value

        def __repr__(self):
            if isinstance(self.__wrapped, Field):
                if not self.__instance._meta_inited:
                    value = 'unknown value'
                else:
                    value = repr(self.get_value())
            else:
                value = '\'\''
            return '<Metadata field {0}[{1}]{2}: {3}>'.format(
                self._path(),
                self.__idxpath,
                '[' + str(self.__indexed) +
                ']' if self.__indexed is not None else '',
                value
            )

        def _force_hierarchy(self):
            """Ensure that the path in the <Field> structure to the contained field exists.

            Create any missing fields.
            """
            if isinstance(self.__wrapped, Field):
                return

            if self.__indexed is not None:
                self.__parent._force_hierarchy()
                # Indexed wrappers wrap the exact same instance as the non-indexed
                # wrapper
                self.__wrapped = self.__parent.__wrapped
            else:
                # We need to make a Field in the hierarchy.
                # If parent is None, we are the root node, and the root node should always be created whenever
                # an Object is created. So in that case, there is no need to
                # create anything.
                if self.__parent is not None:
                    self.__parent._ensure_writable()
                    name = self.__wrapped
                    self.__wrapped = Field(
                        name=name, object=self.__parent.__wrapped.object, parent=self.__parent.__wrapped)
                    self.__parent.__wrapped.children[name] = self.__wrapped
                    session = inspect(self.__wrapped).session
                    session.add(self.__wrapped)
                    session.flush()

        def _force_values(self):
            """Ensure that for each point in the path to the wrapped value a value exists."""
            if self.__parent is not None:
                self.__parent._force_values()

            if self.__indexed is not None:
                path = self._path()
                idxpath = self.__idxpath + '.' + str(self.__indexed)

                if (path not in self.__instance._meta_values or
                        idxpath not in self.__instance._meta_values[path]):
                    self.__parent[self.__indexed] = ''

        def _ensure_writable(self):
            """Ensure that the `Field` path exists (see `_force_hierarchy`).

            Then ensure values exists for the entire path (`_force_values`).
            """
            self._force_hierarchy()
            if self.__parent is not None:
                self.__parent._force_values()

        def append(self, value):
            """Append the given value to the list."""
            if self.__indexed is not None:
                getattr(self, _index_path).append(value)
            else:
                self._init_values()
                idx = None
                if self._path() in self.__instance._meta_values:
                    for idxkey in self.__instance._meta_values[self._path()]:
                        idx = max(idx, int(idxkey.rsplit('.', 1)[-1]))
                if idx is None:
                    self[0] = value
                else:
                    self[idx + 1] = value

        # Iteration-related methods
        def _iteritems(self):
            """The actual generator used for <iteritems>. Only valid on nonindexed wrappers."""
            if not self.__instance._meta_inited:
                self._init_values()
            try:
                for idxkey, value in self.__instance._meta_values[self._path()].items():
                    yield int(idxkey.rsplit('.', 1)[-1]), value.value
            except KeyError:
                pass

        def iteritems(self):
            """Iterate over both the keys and values of the list.

            Note that there is no guarantee of ordering!
            """
            if self.__indexed is not None:
                return getattr(self, _index_path).items()
            else:
                return self._iteritems()

        def _iter(self):
            if not self.__instance._meta_inited:
                self._init_values()
            for item in self.__instance._meta_values[self._path()].values():
                yield item.value

        def __iter__(self):
            """Iterator over the list's values.

            Note that there is no guarantee of ordering!
            """
            if self.__indexed is not None:
                return getattr(self, _index_path).__iter__()
            else:
                return self._iter()

        def _iterchildren(self):
            if not self.__instance._meta_inited:
                self._init_values()
            if isinstance(self.__wrapped, Field):
                for name in self.__wrapped.children.iterkeys():
                    yield getattr(self, name)

        def iterchildren(self):
            """Iterate over the child fields of this field.

            Yield (fieldname, `FieldWrapper`) tuples.
            """
            if self.__indexed is None:
                return self[0].iterchildren()
            else:
                return self._iterchildren()

    class Metadata(object):

        """A descriptor class providing access to the metadata system.

        Any object whishes to have a metadata property must add an attribute with an instance of this class.

        :see: http://docs.python.org/reference/datamodel.html#implementing-descriptors
        """

        def __init__(self):
            self.fields = None

        def __get__(self, instance, owner):
            if instance is None:
                return self

            if self.fields is None:
                session = inspect(instance).session
                path = owner.__module__ + '.' + owner.__name__
                self.fields = session.query(Object).filter_by(path=path).first()
                if not self.fields:
                    self.fields = session.query(Object).filter_by(path=path).first()
                if self.fields is None:
                    # No meta yet
                    self.fields = Object(path=path)
                    Field(object=self.fields, name=_root_path)
                    session.add(self.fields)
                    session.flush([self.fields])

            if not hasattr(instance, '_meta_fields'):
                instance._meta_fields = FieldWrapper(
                    None, '', None, self.fields.fields, instance)
                instance._meta_values = {}
                instance._meta_inited = not get_object_id(instance)

            return instance._meta_fields

        def __set__(self, instance, owner):
            raise AttributeError('Cannot write directly to a metadata instance')

        def __delete__(self, instance):
            raise AttributeError('Cannot delete a metadata instance')

        def filter(self, owner, field, value):
            """Search the metadata. It returns a query on the owner class.

            :param owner: - The owner class model (e.g Order)
            :param field: - The field to search on (e.g sparq.ticketware.user_id)
            :param value: - The value to search for
            :param operator: - The operator to apply to the field and value. Optional; defaults to equality.
            """
            if not field.startswith('[root]'):
                field = '.'.join(['[root]', field])
            value_alias = aliased(Value)
            session = inspect(owner).session
            query = (
                session.query(owner.__class__)
                .join((value_alias, value_alias.instance_id == get_object_id(owner)))
                .join((Object, Object.path == format('.'.join([owner.__module__, owner.__name__]))))
            )
            query = query.filter(Value.value == value)
            parents = field.split('.')

            prev = None
            for parent_name in parents:
                f = aliased(Field)
                cond = f.obj_id == Object.id
                if prev is not None:
                    cond = and_(cond, f.parent_id == prev.id)
                query = query.join((f, cond)).filter(f.name == parent_name)
                prev = f
            query = query.filter(value_alias.field_id == f.id)

            return query

    class Query(query.Query):

        """Provides a filter_by_meta command for sqlalchemy's query.

        Extend your query class from this, together with sqlalchemy.orm.Query.
        """

        def filter_by_meta(self, field, value):
            """Search the metadata.

            It will be always searched from the root (you don't need to add [root]).

            :param field: - The field to search on (e.g sparq.ticketware.user_id)
            :param value: - The value to search for. It will be converted to string.
            """
            from paylogic.core.metadata import Object, Field, Value

            if not field.startswith('[root]'):
                field = '[root].' + field

            value = str(value)
            owner = self._mapper_adapter_map.keys()[0]
            query = (
                self
                .join((Value, Value.instance_id == owner.id))
                .join((Object, Object.path == '.'.join([owner.__module__, owner.__name__])))
            )
            query = query.filter(Value.value == value)

            prev = None
            for name in field.split('.'):
                f = aliased(Field)
                cond = f.obj_id == Object.id
                if prev is not None:
                    cond = and_(cond, f.parent_id == prev.id)
                query = query.join((f, cond)).filter(f.name == name)
                prev = f

            query = query.filter(Value.field_id == f.id)

            return query

        def meta_outerjoin(self, cls, name, value_cls=None):
            """Perform an outerjoin with the metadata system.

            The join is done in such a way that if the object has no metadata value, it's not dropped from the result.

            :param cls: - The class whose metadata is to be joined in.
            :param name: - The name of the metadata property to join in (may be in dotted notation (foo.bar.baz)).
            :param value_cls: - Optional; the class of the metadata value. When omitted,
                this defaults to paylogic.core.metadata.Value. The
                parameter is provided, because this class must be aliased if
                you want multiple metavalues in the join. (See the second
                example below.)

            :returns: A `Query` object with the join applied.

            Examples:
            If you want all Foo objects with the value of their 'a.b.c' metadata
            property, use the following code:

              session.query(Value).meta_outerjoin(Foo, 'a.b.c').all()

            This will return a list of tuples of Foo and Value objects. If a Foo
            instance has no 'a.b.c' metadata property, the second element of the
            tuple will be None.

            If you want to join in multiple metadata properties, they need to be
            aliased:

              from sqlalchemy.orm import aliased
              V1 = aliased(Value)
              V2 = aliased(Value)
              session.query(V1, V2).meta_outerjoin(Foo, 'a.b.c', V1).meta_outerjoin(Foo, 'c.b.a', V2).all()

            This will return a list of tuples consisting of a Foo instance and two
            Value instances. Missing metadata values are None values in the tuples.
            """
            # Get the Object corresponding to the class whose metadata is to be retrieved
            obj = self.session.query(Object).filter(Object.path == cls.get_path()).first()

            # Get the Field corresponding to the specified name
            parts = name.split('.')

            # Get the root field
            field = self.session.query(Field).filter(and_(Field.object == obj, Field.parent.is_(None))).first()
            for part in parts:
                # Iterate through the path to find the correct field
                field = self.session.query(Field).filter(and_(Field.name == part, Field.parent == field)).first()

            # Get the value class
            if not value_cls:
                value_cls = Value

            # Append the join to the current query and return
            return self.outerjoin((value_cls, and_(value_cls.field == field, value_cls.instance_id == cls.id)))

    query.Query = Query

    return Attributes(Object=Object, Field=Field, Value=Value, FieldWrapper=FieldWrapper, Metadata=Metadata)


text:
'''resequencing class'''
from copy import copy
#sbaas lims
from SBaaS_LIMS.lims_biologicalMaterial_query import lims_biologicalMaterial_query
#SBaaS models
from SBaaS_models.models_COBRA_query import models_COBRA_query
from SBaaS_models.models_BioCyc_execute import models_BioCyc_execute
#sbaas
from .stage01_resequencing_mutations_io import stage01_resequencing_mutations_io
from .stage01_resequencing_gd_query import stage01_resequencing_gd_query
from .stage01_resequencing_omniExpressExome_query import stage01_resequencing_omniExpressExome_query
#sbaas models
from .stage01_resequencing_mutations_postgresql_models import *
#resources
from sequencing_analysis.genome_diff import genome_diff
from sequencing_analysis.genome_annotations import genome_annotations
from python_statistics.calculate_interface import calculate_interface

class stage01_resequencing_mutations_execute(stage01_resequencing_mutations_io,
                                      lims_biologicalMaterial_query,
                                      models_COBRA_query):
    #TODO:
    #1. add in query_object_I
    #2. add in query_func_I
    #3. add in query_object_annotation_I
    #4. add in query_object_annotation_func_I
    #5. split into queryData, transformData, storeData functions
    #6.
    def execute_annotateFilteredMutations_v01(self,
        experiment_id,sample_names_I=[],
        annotation_I='data/U00096.2.gb',
        annotation_ref_I = 'genbank',
        biologicalmaterial_id_I='MG1655',
        query_object_I = 'stage01_resequencing_gd_query',
        query_func_I = 'get_mutations_experimentID_dataStage01ResequencingMutationsFiltered',
        ):
        '''Annotate filtered mutations using a reference annotation
        INPUT:
        experiment_id = string
        sample_names_I = [] of strings
        annotation_I = string, reference file for the sequencing annotation
        annotation_ref_I = string, reference file data base source
        biologicalmaterial_id_I = string
        '''

        #read in the annotations file
        genomeannotation = genome_annotations(
            annotation_I=annotation_I,
            annotation_ref_I=annotation_ref_I
            );

        # intantiate the query object:
        query_objects = {'stage01_resequencing_gd_query':stage01_resequencing_gd_query,
                         'stage01_resequencing_omniExpressExome_query':stage01_resequencing_omniExpressExome_query,
                        };
        if query_object_I in query_objects.keys():
            query_object = query_objects[query_object_I];
            query_instance = query_object(self.session,self.engine,self.settings);
            query_instance.initialize_supportedTables();

        print('Executing annotation of filtered mutations...')
        ## query sample names
        #if sample_names_I:
        #    sample_names = sample_names_I;
        #else:
        #    sample_names = [];
        #    sample_names = self.get_sampleNames_experimentID_dataStage01ResequencingMutationsFiltered(experiment_id);
        #for sn in sample_names:
        #    print('analyzing sample_name ' + sn);
        #    # query mutation data:
        #    mutations = [];
        #    mutations = self.get_mutations_experimentIDAndSampleName_dataStage01ResequencingMutationsFiltered(experiment_id,sn);

        #query the data:
        data_listDict = [];
        if hasattr(query_instance, query_func_I):
            query_func = getattr(query_instance, query_func_I);
            try:
                data_listDict = query_func(
                    #analysis_id_I,
                    experiment_id_I=experiment_id,
                    sample_names_I=sample_names_I,
                    );
            except AssertionError as e:
                print(e);
        else:
            print('query instance does not have the required method.');

        mutation_data_O = [];
        for end_cnt,mutation in enumerate(mutations):
            print('analyzing mutations')
            data_tmp = {};
            # annotate each mutation based on the position
            annotation = {};
            annotation = genomeannotation._find_genesFromMutationPosition(mutation['mutation_data']['position']);
            data_tmp['mutation_genes'] = annotation['gene']
            data_tmp['mutation_locations'] = annotation['location']
            data_tmp['mutation_annotations'] = annotation['product']
            # generate a link to ecogene for the genes
            data_tmp['mutation_links'] = [];
            if biologicalmaterial_id_I and not biologicalmaterial_id_I is None:
                for bnumber in annotation['locus_tag']:
                    if bnumber:
                        ecogenes = [];
                        ecogenes = self.get_ecogeneAccessionNumber_biologicalmaterialIDAndOrderedLocusName_biologicalMaterialGeneReferences(biologicalmaterial_id_I,bnumber);
                        if ecogenes:
                            ecogene = ecogenes[0];
                            ecogene_link = genomeannotation._generate_httplink2gene_ecogene(ecogene['ecogene_accession_number']);
                            data_tmp['mutation_links'].append(ecogene_link)
                        else: print('no ecogene_accession_number found for ordered_locus_location ' + bnumber);
            data_tmp['experiment_id'] = mutation['experiment_id'];
            data_tmp['sample_name'] = mutation['sample_name'];
            frequency = 1.0;
            if 'frequency' in mutation['mutation_data']:
                frequency = mutation['mutation_data']['frequency'];
            data_tmp['mutation_frequency'] = frequency
            data_tmp['mutation_position'] = mutation['mutation_data']['position']
            data_tmp['mutation_type'] = mutation['mutation_data']['type']
            data_tmp['mutation_data'] = mutation['mutation_data'];
            data_tmp['mutation_chromosome'] = 1;
            mutation_data_O.append(data_tmp);

        if mutation_data_O:
            self.add_rows_table('data_stage01_resequencing_mutationsAnnotated',mutation_data_O);
    def execute_annotateFilteredMutations(self,
        experiment_id,sample_names_I=[],
        annotation_dir_I='data/',
        annotation_files_I=['U00096.2.gb'],
        annotation_chromosome2File_I = {'1':'U00096.2.gb'},
        annotation_ref_I = 'genbank',
        biologicalmaterial_id_I='MG1655',
        query_object_I = 'stage01_resequencing_gd_query',
        query_func_I = 'get_mutations_experimentID_dataStage01ResequencingMutationsFiltered',
        ):
        '''Annotate filtered mutations using a reference annotation
        INPUT:
        experiment_id = string
        sample_names_I = [] of strings
        annotation_I = string, reference file for the sequencing annotation
        annotation_ref_I = string, reference file data base source
        biologicalmaterial_id_I = string
        '''

        #read in the annotations files
        genomeannotation_dict = {}; #{subfile#:
        for annotation_file in annotation_files_I:
            annotation_filename = annotation_dir_I + annotation_file;
            genomeannotation = genome_annotations(
                annotation_I=annotation_filename,
                annotation_ref_I=annotation_ref_I
                );
            genomeannotation_dict[annotation_file] = genomeannotation;

        # intantiate the query object:
        query_objects = {'stage01_resequencing_gd_query':stage01_resequencing_gd_query,
                         'stage01_resequencing_omniExpressExome_query':stage01_resequencing_omniExpressExome_query,
                        };
        if query_object_I in query_objects.keys():
            query_object = query_objects[query_object_I];
            query_instance = query_object(self.session,self.engine,self.settings);
            query_instance.initialize_supportedTables();

        print('Executing annotation of filtered mutations...')

        #list out the number of chromosomes
        chromosomes = None;
        if annotation_chromosome2File_I:
            chromosomes = list(annotation_chromosome2File_I.keys());

        #TODO: break into seperate function
        #query the data:
        data_listDict = [];
        if hasattr(query_instance, query_func_I):
            query_func = getattr(query_instance, query_func_I);
            try:
                data_listDict = query_func(
                    #analysis_id_I,
                    experiment_id_I=experiment_id,
                    sample_names_I=sample_names_I,
                    chromosomes_I=chromosomes,
                    );
            except AssertionError as e:
                print(e);
        else:
            print('query instance does not have the required method.');

        ##Testing only
        ##read in the data:
        #from io_utilities.base_importData import base_importData
        #filename_I = self.settings['workspace_data']+\
        #    '/tmp/test.csv'
        #iobase = base_importData();
        #iobase.read_csv(filename_I);
        #data_listDict = iobase.data;

        mutation_data_O = [];
        for end_cnt,mutation in enumerate(data_listDict):
            #print('analyzing mutations')
            data_tmp = {};

            # annotate each mutation based on the position
            annotation = {};
            if 'chromosome' in mutation['mutation_data'].keys():
                chromosome = mutation['mutation_data']['chromosome']
            else:
                chromosome = '1';
            if not chromosome in annotation_chromosome2File_I.keys(): continue;
            if chromosome in annotation_chromosome2File_I.keys() and \
                not annotation_chromosome2File_I[chromosome] in genomeannotation_dict.keys(): continue;
            annotation = genomeannotation_dict[annotation_chromosome2File_I[chromosome]]._find_genesFromMutationPosition(
                mutation['mutation_data']['position']);

            # generate a link to ecogene for the genes
            data_tmp['mutation_links'] = [];
            if biologicalmaterial_id_I and not biologicalmaterial_id_I is None:
                for bnumber in annotation['locus_tag']:
                    if bnumber:
                        ecogenes = [];
                        ecogenes = self.get_ecogeneAccessionNumber_biologicalmaterialIDAndOrderedLocusName_biologicalMaterialGeneReferences(biologicalmaterial_id_I,bnumber);
                        if ecogenes:
                            ecogene = ecogenes[0];
                            ecogene_link = genomeannotation._generate_httplink2gene_ecogene(ecogene['ecogene_accession_number']);
                            data_tmp['mutation_links'].append(ecogene_link)
                        else: print('no ecogene_accession_number found for ordered_locus_location ' + bnumber);
            elif annotation['locus_tag'] and not annotation['locus_tag'][0] is None:
                data_tmp['mutation_links'] = annotation['locus_tag'];

            # record the data
            data_tmp['mutation_genes'] = annotation['gene']
            data_tmp['mutation_locations'] = annotation['location']
            data_tmp['mutation_annotations'] = annotation['product']
            data_tmp['experiment_id'] = mutation['experiment_id'];
            data_tmp['sample_name'] = mutation['sample_name'];
            frequency = 1.0;
            if 'frequency' in mutation['mutation_data']:
                frequency = mutation['mutation_data']['frequency'];
            data_tmp['mutation_frequency'] = frequency
            data_tmp['mutation_position'] = mutation['mutation_data']['position']
            data_tmp['mutation_type'] = mutation['mutation_data']['type']
            data_tmp['mutation_data'] = mutation['mutation_data'];
            data_tmp['mutation_chromosome'] = chromosome;
            mutation_data_O.append(data_tmp);

        if mutation_data_O:
            self.add_rows_table('data_stage01_resequencing_mutationsAnnotated',mutation_data_O);
    def execute_mutateFilteredMutations(self,experiment_id,sample_names_I=[],
                                                 annotation_I='data/U00096.2.gb',
                                                 annotation_ref_I = 'genbank',
                                                 sequence_I='data/U00096.2.fas',
                                                 sequence_ref_I = 'fasta',
                                                 codonUsageTable_I='data/ecoli_codonUsageTable.csv',
                                                IS_sequences_I='data/ecoli_IS_sequences.fasta',
                                                IS_sequences_ref_I = 'fasta',
                                                 translation_table_I='Bacterial',
                                                 ):
        '''Mutate filtered mutations to determine the change in dna, rna, and peptide sequences
        INPUT:
        experiment_id = string
        sample_names_I = [] of strings
        annotation_I = string, reference file for the sequencing annotation
        annotation_ref_I = string, reference file data base source
        sequence_I = string, reference file for the sequence
        sequence_I = string, reference file format
        codonUsageTable_I = string, reference file for the codon usage table
        IS_sequences_I = string, reference file for the insertion element sequences
        IS_sequences_ref_I = string, reference file format
        translation_table_I = string, translation table to use when converting from rna to peptide sequence
        '''

        genomeannotation = genome_annotations(annotation_I=annotation_I,annotation_ref_I=annotation_ref_I,
                                              sequence_I=sequence_I,sequence_ref_I=sequence_ref_I,
                                              IS_sequences_I=IS_sequences_I,IS_sequences_ref_I=IS_sequences_ref_I,
                                              codonUsageTable_I=codonUsageTable_I);

        print('Executing annotation of filtered mutations...')
        data_O = [];
        # query sample names
        if sample_names_I:
            sample_names = sample_names_I;
        else:
            sample_names = [];
            sample_names = self.get_sampleNames_experimentID_dataStage01ResequencingMutationsFiltered(experiment_id);
        for sn in sample_names:
            print('analyzing sample_name ' + sn);
            data_O = [];
            data_codon_O=[];
            # query mutation data:
            mutations = [];
            mutations = self.get_mutations_experimentIDAndSampleName_dataStage01ResequencingMutationsFiltered(experiment_id,sn);
            for end_cnt,mutation in enumerate(mutations):
                print('analyzing mutations')
                data_tmp = {};
                # annotate each mutation based on the position
                annotation = {};
                annotation = genomeannotation._mutate_peptideFromMutationData(mutation['mutation_data'],translation_table_I=translation_table_I);
                if not annotation['gene']: continue;
                data_tmp['mutation_genes'] = annotation['gene']
                data_tmp['mutation_locations'] = annotation['location']
                data_tmp['mutation_data'] = annotation['mutation_data']
                data_tmp['dna_sequence_ref'] = annotation['dna_sequence_ref'];
                data_tmp['dna_sequence_new'] = annotation['dna_sequence_new'];
                data_tmp['rna_sequence_ref'] = annotation['rna_sequence_ref'];
                data_tmp['rna_sequence_new'] = annotation['rna_sequence_new'];
                data_tmp['peptide_sequence_ref'] = annotation['peptide_sequence_ref'];
                data_tmp['peptide_sequence_new'] = annotation['peptide_sequence_new'];
                data_tmp['mutation_class'] = annotation['mutation_class'];
                data_tmp['dna_feature_position'] = annotation['dna_feature_position']
                data_tmp['dna_feature_ref'] = annotation['dna_feature_ref']
                data_tmp['dna_feature_new'] = annotation['dna_feature_new']
                data_tmp['rna_feature_position'] = annotation['rna_feature_position']
                data_tmp['rna_feature_ref'] = annotation['rna_feature_ref']
                data_tmp['rna_feature_new'] = annotation['rna_feature_new']
                data_tmp['peptide_feature_position'] = annotation['peptide_feature_position']
                data_tmp['peptide_feature_ref'] = annotation['peptide_feature_ref']
                data_tmp['peptide_feature_new'] = annotation['peptide_feature_new']
                data_tmp['experiment_id'] = mutation['experiment_id'];
                data_tmp['sample_name'] = mutation['sample_name'];
                data_tmp['dna_features_region'] = None;
                data_tmp['rna_features_region'] = None;
                data_tmp['peptide_features_region'] = None;
                frequency = 1.0;
                if 'frequency' in mutation['mutation_data']:
                    frequency = mutation['mutation_data']['frequency'];
                data_tmp['mutation_frequency'] = frequency
                data_tmp['mutation_position'] = mutation['mutation_data']['position']
                data_tmp['mutation_type'] = mutation['mutation_data']['type']
                #data_tmp['mutation_data'] = mutation['mutation_data'];
                data_tmp['used_'] = True;
                data_tmp['comment_'] = None;
                #split into different tables depending on whether the peptide sequence changed
                if mutation['mutation_data']['type']=='SNP' and 'synonymous' in annotation['mutation_class']:
                    data_tmp['codon_triplet_ref'] = annotation['codon_triplet_ref'];
                    data_tmp['codon_triplet_new'] = annotation['codon_triplet_new'];
                    data_tmp['codon_triplet_position'] = annotation['codon_triplet_position']
                    data_tmp['codon_fraction_ref'] = annotation['codon_fraction_ref']
                    data_tmp['codon_fraction_new'] = annotation['codon_fraction_new']
                    data_tmp['codon_frequency_ref'] = annotation['codon_frequency_ref']
                    data_tmp['codon_frequency_new'] = annotation['codon_frequency_new']
                    data_tmp['codon_frequency_units'] = annotation['codon_frequency_units']
                    data_codon_O.append(data_tmp);
                else:
                    data_O.append(data_tmp);
            #upload the data to the database (each sample)
            if data_O:
                self.add_dataStage01ResequencingMutationsSeqChanges(data_O);
            if data_codon_O:
                self.add_rows_table('data_stage01_resequencing_mutationsCodonChanges',data_codon_O);

    def map_geneName2ModelReaction(self,
            biologicalmaterial_id_I,gene_name_I,
            model_id_I,):
        """return the model reaction rows whose enzymes are produced by a given gene
        INPUT:
        biologicalmaterial_id_I = string, e.g. MG1655
        gene_name_I = string, e.g. pgi
        model_id_I = string, e.g. iJO1366
        OUTPUT:
        rows_O = rows from data_stage02_physiology_modelReactions
        """

        rows_O = [];
        orderedLocusNames = [];
        orderedLocusNames = self.get_orderedLocusName_biologicalmaterialIDAndGeneName_biologicalMaterialGeneReferences(biologicalmaterial_id_I,gene_name_I);
        for oln in orderedLocusNames:
            rows_tmp = [];
            rows_tmp = self.get_rows_modelIDAndOrderedLocusName_dataStage02PhysiologyModelReactions(model_id_I,oln['ordered_locus_name']);
            for r in rows_tmp:
                r['mutation_gene'] = gene_name_I;
                rows_O.append(r);
        return rows_O;
    def execute_mapGeneName2ModelReaction_mutationsAnnotated(self,
            experiment_id,filename_O,
            biologicalmaterial_id_I,
            model_id_I,
            sample_names_I=[],
            gene_names_I=[]):
        """return the model reaction rows whose enzymes are produced by a given gene
        INPUT:
        biologicalmaterial_id_I = string, e.g. MG1655
        gene_name_I = string, e.g. pgi
        model_id_I = string, e.g. iJO1366
        OUTPUT:
        filename_O = name of output file
                    rows from data_stage02_physiology_modelReactions in a .csv file
        """

        data_O = [];
        # query sample names from the experiment
        if sample_names_I:
            sample_names = sample_names_I;
        else:
            sample_names = [];
            sample_names = self.get_sampleNames_experimentID_dataStage01ResequencingMetadata(experiment_id);
        for sn in sample_names:
            #query the mutations from the experiment
            mutations = [];
            mutations = self.get_mutations_experimentIDAndSampleName_dataStage01ResequencingMutationsAnnotated(experiment_id,sn);
            for mutation in mutations:
                for gene_name in mutation['mutation_genes']:
                    if gene_names_I:
                        if not gene_name in gene_names_I:
                            continue
                    rows = [];
                    rows = self.map_geneName2ModelReaction(
                                    biologicalmaterial_id_I,gene_name,
                                    model_id_I);
                    if rows:
                        for r in rows:
                            r['experiment_id']=mutation['experiment_id'];
                            r['sample_name']=mutation['sample_name'];
                            r['mutation_frequency']=mutation['mutation_frequency'];
                            r['mutation_type']=mutation['mutation_type'];
                            r['mutation_position']=mutation['mutation_position'];
                            r['mutation_data']=mutation['mutation_data'];
                            r['mutation_annotations']=mutation['mutation_annotations'];
                            r['mutation_genes']=mutation['mutation_genes'];
                            r['mutation_locations']=mutation['mutation_locations'];
                            r['mutation_links']=mutation['mutation_links'];
                            r['used_']=mutation['used_'];
                            r['comment_']=mutation['comment_'];
                            r['biologicalmaterial_id'] = biologicalmaterial_id_I;
                            r['model_id'] = model_id_I;
                            data_O.append(r);
        #export the data to .csv
        self.export_mapGeneName2ModelReaction_csv(data_O,filename_O);

    def calculate_distributionOfMutationsInBioCycParentClasses(
        self,
        experiment_ids_I,
        sample_names_I,
        parent_classes_I=['Transcription related'],
        database_I='ECOLI',
        names_I=[],
        unique_I=True,
        ):
        '''calculate the percentages of mutations in each BioCyc parent_classes
        INPUT:
        '''
        #BioCyc dependencies
        biocyc01 = models_BioCyc_execute(self.session,self.engine,self.settings);
        biocyc01.initialize_supportedTables()
        biocyc01.initialize_tables()

        from SBaaS_models.models_BioCyc_dependencies import models_BioCyc_dependencies
        biocyc01_dep = models_BioCyc_dependencies();

        if parent_classes_I:
            parent_classes = parent_classes_I;
        else:
            parent_classes = [];
            parent_classes = biocyc01.getParsed_parentClasses_modelsBioCycPolymerSegments(
                database_I='ECOLI'
                );

        pc2Genes = {};
        for pc in parent_classes:
            #join list of genes with alternative identifiers
            biocyc_genes = biocyc01.getParsed_genesAndAccessionsAndSynonyms_namesAndParentClassesAndDatabase_modelsBioCycPolymerSegments(
                names_I=names_I,
                database_I=database_I,
                parent_classes_I='%s"%s"%s'%('%',pc,'%'),
                query_I={},
                output_O='listDict',
                dictColumn_I=None);
            if biocyc_genes:
                gene_ids = list(set([g['gene'] for g in biocyc_genes if g['gene']] +\
                    [g['common_name'] for g in biocyc_genes if g['common_name']] +\
                    [g['synonym'] for g in biocyc_genes if g['synonym']]));
                pc2Genes[pc] = gene_ids;

        #query all of the resequencing data
        mutations_rows = self.get_mutations_experimentIDsAndSampleNames_dataStage01ResequencingMutationsAnnotated(
        experiment_ids_I = experiment_ids_I,
        sample_names_I = sample_names_I);
        mutated_genes = [];
        for row in mutations_rows:
            if row['mutation_genes']: #exclude non-annotated regions
                mutated_genes.extend(row['mutation_genes']);
        if unique_I:
            mutations_genes_cnt = len(list(set(mutated_genes)))
        else :
            mutations_genes_cnt = len(mutated_genes)

        #calculate the distributions for each parent_class
        data_O = [];
        for parent_class,gene_ids in pc2Genes.items():
            if unique_I:
                pc_genes_cnt = len(list(set([d for d in mutated_genes if d in gene_ids])))
            else:
                pc_genes_cnt = len([d for d in mutated_genes if d in gene_ids])
            genes_ratio = pc_genes_cnt/mutations_genes_cnt;
            tmp = {
                'analysis_id':None,
                'feature_id':'parent_class',
                'feature_units':None,
                'element_id':parent_class,
                'frequency':pc_genes_cnt,
                'fraction':genes_ratio,
                'used_':True,
                'comment_':None}
            #tmp = {'parent_class':parent_class,
            #       'mutation_genes_count':mutations_genes_cnt,
            #       'genes_count':pc_genes_cnt,
            #       'genes_fraction':genes_ratio};
            data_O.append(tmp);

        return data_O;
    def calculate_fractionOfMutationLocations(
        self,
        experiment_id_I,
        sample_names_I,
        mutation_locations_I = []
        ):
        '''calculate the percentages of mutations in each mutation_location
        INPUT:
        EXAMPLE:
        sample_names = '140807_11_OxicEvo04Evo01EPEcoliGlcM9_Broth-1,\
        140807_11_OxicEvo04Evo02EPEcoliGlcM9_Broth-1,\
        140807_11_OxicEvo04gndEvo01EPEcoliGlcM9_Broth-1,\
        140807_11_OxicEvo04gndEvo02EPEcoliGlcM9_Broth-1,\
        140807_11_OxicEvo04gndEvo03EPEcoliGlcM9_Broth-1,\
        140807_11_OxicEvo04pgiEvo01EPEcoliGlcM9_Broth-1,\
        140807_11_OxicEvo04pgiEvo02EPEcoliGlcM9_Broth-1,\
        140807_11_OxicEvo04pgiEvo03EPEcoliGlcM9_Broth-1,\
        140807_11_OxicEvo04pgiEvo04EPEcoliGlcM9_Broth-1,\
        140807_11_OxicEvo04pgiEvo05EPEcoliGlcM9_Broth-1,\
        140807_11_OxicEvo04pgiEvo06EPEcoliGlcM9_Broth-1,\
        140807_11_OxicEvo04pgiEvo07EPEcoliGlcM9_Broth-1,\
        140807_11_OxicEvo04pgiEvo08EPEcoliGlcM9_Broth-1,\
        140807_11_OxicEvo04ptsHIcrrEvo01EPEcoliGlcM9_Broth-1,\
        140807_11_OxicEvo04ptsHIcrrEvo02EPEcoliGlcM9_Broth-1,\
        140807_11_OxicEvo04ptsHIcrrEvo03EPEcoliGlcM9_Broth-1,\
        140807_11_OxicEvo04ptsHIcrrEvo04EPEcoliGlcM9_Broth-1,\
        140807_11_OxicEvo04sdhCBEvo01EPEcoliGlcM9_Broth-1,\
        140807_11_OxicEvo04sdhCBEvo02EPEcoliGlcM9_Broth-1,\
        140807_11_OxicEvo04sdhCBEvo03EPEcoliGlcM9_Broth-1,\
        140807_11_OxicEvo04tpiAEvo01EPEcoliGlcM9_Broth-1,\
        140807_11_OxicEvo04tpiAEvo02EPEcoliGlcM9_Broth-1,\
        140807_11_OxicEvo04tpiAEvo03EPEcoliGlcM9_Broth-1,\
        140807_11_OxicEvo04tpiAEvo04EPEcoliGlcM9_Broth-1';
        mutation_locations_fractions = mut01.calculate_fractionOfMutationLocations(
            experiment_id_I = 'ALEsKOs01',
            sample_names_I = sample_names,);
        #export the data to disk
        from io_utilities.base_exportData import base_exportData
        iobase = base_exportData(parent_classes_fractions);
        iobase.write_dict2json(
            pg_settings.datadir_settings['workspace_data']+\
            '/_output/ALEsKOs01_0_11_parent_classes_fractions.json');
        iobase.write_dict2csv(
            pg_settings.datadir_settings['workspace_data']+\
            '/_output/ALEsKOs01_0_11_parent_classes_fractions.csv');
        '''

        #query all of the resequencing data
        mutations_rows = self.get_mutations_experimentIDAndSampleNames_dataStage01ResequencingMutationsAnnotated(
        experiment_id_I = experiment_id_I,
        sample_names_I = sample_names_I);

        mutation_locations = {};
        mutated_genes_coding = [];
        for row in mutations_rows:
            if row['mutation_genes'] : #exclude non-annotated regions
                mutated_genes.extend(row['mutation_genes']);
                if not row['mutation_location'] in mutation_locations:
                    mutation_locations[row['mutation_location']]= [];
                if mutation_locations_I and not row['mutation_location'] in mutation_locations_I:
                    continue;
                mutation_locations[row['mutation_location']].extend(row['mutation_genes'])
        mutations_genes_cnt = len(list(set(mutated_genes)))

        #calculate the distributions for each parent_class
        data_O = [];
        for parent_class,gene_ids in mutation_locations.items():
            pc_genes_cnt = len(list(set([d for d in mutated_genes if d in gene_ids])))
            genes_ratio = pc_genes_cnt/mutations_genes_cnt;
            tmp = {'parent_class':parent_class,
                   'mutation_genes_count':mutations_genes_cnt,
                   'genes_count':pc_genes_cnt,
                   'genes_fraction':genes_ratio};
            data_O.append(tmp);

        return data_O;


text:
/**
 * This class was created by <Vazkii>. It's distributed as
 * part of the Botania Mod. Get the Source Code in github:
 * https://github.com/Vazkii/Botania
 *
 * Botania is Open Source and distributed under the
 * Botania License: http://botaniamod.net/license.php
 *
 * File Created @ [May 25, 2014, 7:32:10 PM (GMT)]
 */
package vazkii.botania.api.mana;

import net.minecraft.item.ItemStack;

/**
 * Any item that implements this interface is an item that would use mana
 * from the player's inventory. If there's any items in the inventory or
 * equipped in either the baubles or armor inventories that implement
 * this interface, a mana bar will be rendered.
 */
public interface IManaUsingItem {

	public boolean usesMana(ItemStack stack);

}


text:
package com.nearme.base.stat.parse;

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

import com.nearme.base.stat.ExecutorStat;
import com.oppo.base.file.FileOperate;
import com.oppo.base.time.TimeFormat;

/**
 * ExecutorStatParserForOld

 * 老版本执行时间统计文件解析

 *
 * @author   80036381
 * @version
 * @since    Ver 1.1
 * @Date	 2013-4-11  下午1:50:40
 */
public class ExecutorStatParserForOld extends AbstractExecutorStatParser {

	public ExecutorStatParserForOld() {
		super(null, StatInterval.DAY);
	}

	public ExecutorStatParserForOld(File sourceFile) {
		super(sourceFile, StatInterval.DAY);
	}

	public ExecutorStatParserForOld(File sourceFile, StatInterval statInterval) {
		super(sourceFile, statInterval);
	}

	/**
	 * 解析单个文件
	 * @param
	 * @return
	 */
	@Override
	protected void parseFile(File file) throws IOException {
		BufferedReader br = null;

		try {
			br = new BufferedReader(new FileReader(file));

			//按行读取
			String line;
			ParseStep step = ParseStep.INIT; //单个统计解析到的行数(从标记行开始)
			ExecutorStat lastStat = null;
			while(null != (line = br.readLine())) {
				switch(step) {
				case INIT://还未开始解析或前一次数据解析完
					String identifier = getInfoFromLine(line, "identifier:", '\t');
					if(null == identifier) {
						step = ParseStep.INIT;
						continue;
					}
					String startTimeString = getInfoFromLine(line, "start at ", '\t');

					lastStat = this.getExecutorStat(identifier, startTimeString);

					//设置开始时间
					long startTime = Math.min(Timestamp.valueOf(startTimeString).getTime(), lastStat.getStartTime());
					lastStat.setStartTime(startTime);
					//设置输出时间
					String outputTimeString = getInfoFromLine(line, "output at ", END_CHAR);
					long outputTime = Math.max(Timestamp.valueOf(outputTimeString).getTime(), lastStat.getOutputTime());
					lastStat.setOutputTime(outputTime);

					step = ParseStep.TOTAL;
					break;
				case TOTAL: //第一行,总数据
					int execTimes = getIntFromLine(line, ExecutorStat.STAT_EXEC_TIMES, '\t');
					//double execAvg = getDoubleFromLine(line, ExecutorStat.STAT_EXEC_AVG, END_CHAR);

					lastStat.setExecutorTimes(lastStat.getExecutorTimes() + execTimes);
					step = ParseStep.SUCC;
					break;
				case SUCC: //第二行,成功数据
					int succTimes = getIntFromLine(line, ExecutorStat.STAT_SUCC_TIMES, '\t');
					//double succAvg = getDoubleFromLine(line, ExecutorStat.STAT_SUCC_AVG, ExecutorStat.COLUMN_SPLIT_CHAR);
					int succMax = getIntFromLine(line, ExecutorStat.STAT_SUCC_MAX, '\t');
					int succMin = getIntFromLine(line, ExecutorStat.STAT_SUCC_MIN, END_CHAR);

					lastStat.setSuccessTimes(lastStat.getSuccessTimes() + succTimes);
					lastStat.setMaxSuccessTime(Math.max(succMax, lastStat.getMaxSuccessTime()));
					lastStat.setMinSuccessTime(Math.min(succMin, lastStat.getMinSuccessTime()));

					step = ParseStep.FAIL;
					break;
				case FAIL: //第三号,失败数据
					int failTimes = getIntFromLine(line, ExecutorStat.STAT_FAIL_TIMES, '\t');
					//double failAvg = getDoubleFromLine(line, ExecutorStat.STAT_FAIL_AVG, ExecutorStat.COLUMN_SPLIT_CHAR);
					int failMax = getIntFromLine(line, ExecutorStat.STAT_FAIL_MAX, '\t');
					int failMin = getIntFromLine(line, ExecutorStat.STAT_FAIL_MIN, END_CHAR);

					lastStat.setFailTimes(lastStat.getFailTimes() + failTimes);
					lastStat.setMaxFailTime(Math.max(failMax, lastStat.getMaxFailTime()));
					lastStat.setMinFailTime(Math.min(failMin, lastStat.getMinFailTime()));

					step = ParseStep.INIT;
					break;
				default:
					step = ParseStep.INIT;
					break;
				}
			}
		} finally {
			FileOperate.close(br);
		}
	}

	enum ParseStep {
		INIT,
		TOTAL,
		SUCC,
		FAIL
	}

	/**
	 * Function Description here
	 * @param
	 * @return
	 * @throws IOException
	 */

	public static void main(String[] args) throws IOException {
		ExecutorStatParserForOld esp = new ExecutorStatParserForOld(new File("h:\\market_core_execstat_2013-07-26.0.log"), StatInterval.ALL);
		esp.setStatInterval(StatInterval.HOUR);
		esp.parse();

		ExecutorStat e0 = esp.getExecutorStatInfo(
				"com.nearme.market.core.product.upgrade.CheckUpgradeHandler",
				"2013-08-06 21");
		System.out.println(e0.toStatString(false, false));

		for (int i = 0; i < 24; i++) {
			ExecutorStat e1 = esp.getExecutorStatInfo("2013-08-06 " + (i < 10 ? "0" + String.valueOf(i) : String.valueOf(i)));
			System.out.println(TimeFormat.getTimeString(e1.getStartTime()) + " " + e1.toStatString(false, false));
		}
	}
}


text:
package ru.r2cloud.jradio.huskysat1;

import java.io.IOException;

import ru.r2cloud.jradio.util.LsbBitInputStream;

public class SoftwareCommandCount {

	private int timeMarker;
	private int softwareCommands;

	public SoftwareCommandCount() {
		// do nothing
	}

	public SoftwareCommandCount(LsbBitInputStream dis) throws IOException {
		int rawValue = dis.readBitsAsInt(6);
		// 1 bit for Reply Time Checking bit
		timeMarker = (rawValue) & 0x1;
		// 11 MSBs are software command number
		softwareCommands = (rawValue >> 1) & 0xfff;
	}

	public int getTimeMarker() {
		return timeMarker;
	}

	public void setTimeMarker(int timeMarker) {
		this.timeMarker = timeMarker;
	}

	public int getSoftwareCommands() {
		return softwareCommands;
	}

	public void setSoftwareCommands(int softwareCommands) {
		this.softwareCommands = softwareCommands;
	}

}


text:
@interface JMViewController () <UIWebViewDelegate, JMHoledViewDelegate>
@property (weak) IBOutlet JMHoledView *holedView;
@property (weak) IBOutlet UIWebView *webView;
@end

@implementation JMViewController

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    NSURL *url = [NSURL URLWithString:@"http://www.google.fr"];
    NSURLRequest *rquest = [[NSURLRequest alloc] initWithURL:url];
    [self.webView loadRequest:rquest];
    self.webView.delegate = self;
}

- (void)webViewDidFinishLoad:(UIWebView *)webView
{
    self.holedView.holeViewDelegate = self;
    [self.holedView addHoleCircleCenteredOnPosition:CGPointMake(25.0f, 25.0f) andDiameter:40.0f];
    [self.holedView addHoleRectOnRect:CGRectMake(10.0f, 250.0f, 300.0f, 30.0f)];
    [self.holedView addHCustomView:[self viewForDemo] onRect:CGRectMake(60.0f, 350.0f, 200.0f, 50.0f)];
}

- (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error
{
    self.holedView.holeViewDelegate = self;
    [self.holedView addHoleRoundedRectOnRect:CGRectMake(10.0f, 250.0f, 300.0f, 30.0f) withCornerRadius:10.0f];
}

#pragma mark - JMHoledViewDelegate

- (void)holedView:(JMHoledView *)holedView didSelectHoleAtIndex:(NSUInteger)index
{
    NSLog(@"%s %ld", __PRETTY_FUNCTION__,(long)index);
}

#pragma marl - helper

- (UIView *)viewForDemo
{
    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(20.0f, 350.0F, 200.0f, 50.0f)];
    [label setBackgroundColor:[UIColor clearColor]];
    label.layer.borderColor = [UIColor whiteColor].CGColor;
    label.layer.borderWidth = 1.0f;
    label.layer.cornerRadius = 10.0f;
    [label setTextColor:[UIColor whiteColor]];
    label.text = @"This control can be use to Highlight informations.";
    label.numberOfLines = 2;
    label.font = [UIFont systemFontOfSize:14.0f];
    label.textAlignment = NSTextAlignmentCenter;
    return label;
}

@end


text:
var telegram = require('telegram-bot-api');
var request = require('ajax-request');
var t_token = require('./telegram-token.js');
var MongoClient = require('mongodb').MongoClient
  , assert = require('assert');

// Connection URL
var url = 'mongodb://localhost:27017/pschub';
// Use connect method to connect to the Server
MongoClient.connect(url, function(err, db) {
  assert.equal(null, err);
  console.log("Connected correctly to MongoDB");
});

var api = new telegram({
  token: t_token.token(),
  updates: {
    enabled: true,
    get_interval: 40,
    limit: 5
  }
});

var getRandom = function getRandomArbitrary() {
  return Math.random() * (9600 - 100) + 100;
}

api.on('message', function(message)
{
  var chat_id = message.chat.id;
  message.text = message.text ? message.text : "this is bad";

  if(message.text == '/start') {
    api.sendMessage({
      chat_id: message.chat.id,
      text: "Yes lets start :) \n \n /quiz - Start a Quiz section \n /statistics - Get my statistics \n /help - Get help from people behind PSC HUB \n /about - about the developers \n /pegke - A Customer Loyalty Software\n /end - Stop Quiz\n"
    });
  } else if(message.text == '/quiz') {

    MongoClient.connect(url, function(err, db) {
      var collection = db.collection('questions');
      // Find some documents
      collection.ensureIndex( { _id : 1, uid:1 } )
      collection.find({}).toArray(function(err, docs) {
        var qcollection = db.collection('quizlive');
        // Insert some documents
        qcollection.update(
          {uid : message.from.id},
          {uid : message.from.id, question: docs[0]},
          {upsert: true }
        );
        var body = docs[0],
            msgTxt = {"keyboard": [["A", "B"], ["C", "D"], ["Report"]], "one_time_keyboard": true},
            theQuestion = body.qst + "\n\nA) " + body.a +  "\nB) " + body.b + "\nC) " + body.c + "\nD) " + body.d;
          api.sendMessage({
            chat_id: message.chat.id,
            reply_markup: JSON.stringify(msgTxt),
            text: theQuestion,
            parse_mode: "Markdown"
          });
      });

    });

  } else if(message.text.match(/^[abcdr]$/i) ) {
    MongoClient.connect(url, function(err, db) {
      var collection = db.collection('quizlive');
      // Find some documents
      collection.ensureIndex( { _id : 1, uid: 1} );
      collection.find({uid: message.from.id}).toArray(function(err, docs) {
        var corrAns = docs[0].question.ans || 'x',
            text = '',
            reply = message.text,
            lastQ = docs[0].question.qid;
        if(corrAns == reply) {
          var text = '👍 Correct !!';
        } else {
          var text = '👎 Wrong !!, ' + corrAns;
        }

        var qcollection = db.collection('questions');
        // Find some documents
        qcollection.ensureIndex( { _id : 1, uid: 1} );
        qcollection.find({ qid: { $lt: lastQ } } ).limit(1).toArray(function(err, cdocs) {
          // Insert some documents
          collection.update(
            {uid : message.from.id},
            {uid : message.from.id, question: cdocs[0]},
            {upsert: true }
          );
          var body = cdocs[0],
              msgTxt = {"keyboard": [["A", "B"], ["C", "D"], ["Report"]], "one_time_keyboard": true},
              theQuestion = text + "\n\n" + body.qst + "\n\nA) " + body.a +  "\nB) " + body.b + "\nC) " + body.c + "\nD) " + body.d;
            api.sendMessage({
              chat_id: message.chat.id,
              reply_markup: JSON.stringify(msgTxt),
              text: theQuestion,
              parse_mode: "Markdown"
            });
        });

      });
    });

  } else if(message.text == '/pegke') {
    api.sendMessage({
      chat_id: message.chat.id,
      text: 'Pegke Everything your Business need to create a Successful Loyalty Program and build Customer Relationships https://pegke.com'
    });
  } else if(message.text == 'Report') {
    api.sendMessage({
      chat_id: message.chat.id,
      text: 'We are working on it, please contact our admin @niksmac or @sibizulu if you have any suggestions.'
    });
  } else if(message.text == '/statistics') {
    api.sendMessage({
      chat_id: message.chat.id,
      text: 'We are working on it, please contact our admin @niksmac or @sibizulu if you have any suggestions.'
    });
  } else if(message.text == '/about') {
    api.sendMessage({
      chat_id: message.chat.id,
      text: 'With bundle of questions in General English, Numerical ability , Computer knowledge and many more in various categories.Each category consists of various subcategories consisting of 100 or more questions. http://bit.ly/pschubapp'
    });
  } else if(message.text == '/end') {
    MongoClient.connect(url, function(err, db) {
      var collection = db.collection('quizlive');
      collection.remove({uid : message.from.id}, function(err, result) { });
      api.sendMessage({
        chat_id: message.chat.id,
        text: 'Please feel free to share @pschub_bot with your friends. \n Thank you. 😊'
      });
    });
  } else {
    api.sendMessage({
      chat_id: message.chat.id,
      text: "Bots are simply Telegram accounts operated by software – not people – and they'll often have Artificial intelligence features. \nBut, sorry I really dont know what to do with -" + message.text + "-"
    });
  }

  // It'd be good to check received message type here
  // And react accordingly
  // We consider that only text messages can be received here

});

var insertDocuments = function(db, callback) {
  // Get the documents collection
  var collection = db.collection('documents');
  // Insert some documents
  collection.insert([
    {a : 1}, {a : 2}, {a : 3}
  ], function(err, result) {
    assert.equal(err, null);
    assert.equal(3, result.result.n);
    assert.equal(3, result.ops.length);
    console.log("Inserted 3 documents into the document collection");
    callback(result);
  });
};

var findDocuments = function(db, callback) {
  // Get the documents collection
  var collection = db.collection('questions');
  // Find some documents
  collection.find({}).toArray(function(err, docs) {
    assert.equal(err, null);
    assert.equal(2, docs.length);
    console.log("Found the following records");
    console.dir(docs);
    callback(docs);
  });
}

var insertQuestions = function(db, callback) {
  // Get the documents collection
  var collection = db.collection('questions');
  // Insert some documents
  collection.insert([
    {
    "qst": "Name the Telugu Desam Party founder whose statue will be installed in Parliament House in India.",
    "a": "Rajshekhar Reddy",
    "b": "N.T.Rama Rao ",
    "c": " ChandraBabu Naidu",
    "d": "Rajnikanth ",
    "ans": "1"
},
{
    "qst": "The Grass Court King, Roger Federer on 16 June 2013 won Gerry Weber Open Halle ATP final after defeating Mikhail Youzhny of Russia by 6-7 (5/7), 6-3, 6-4 at the Gerry Weber Stadium in Halle, Germany. This is the _________ title won by Federer in the year 2013 and sixth Halle Title and 77th title of the career.",
    "a": "Second",
    "b": "Third",
    "c": "Fourth",
    "d": "first",
    "ans": "3"
},
{
    "qst": "The minister who resinged from Central Cabinet during the wake off Chinese aggression",
    "a": "H.K.L Bhagat",
    "b": "V.C Shukla",
    "c": "V.K Krishna Menon",
    "d": "Jaffer Sheriff",
    "ans": "2"
}
  ], function(err, result) {
    assert.equal(err, null);
    assert.equal(3, result.result.n);
    assert.equal(3, result.ops.length);
    console.log("Inserted 3 documents into the document collection");
    callback(result);
  });
};

var findRandomQuestion = function(db, callback) {
  // Get the documents collection
  var collection = db.collection('questions');
  // Find some documents
  collection.find({}).toArray(function(err, docs) {
    console.dir(docs[0]);
    callback(docs[0]);
  });
}


text:
find_package(CURL REQUIRED)
include_directories(${CURL_INCLUDE_DIR})
LIST(APPEND DRIVESHAFT_LINK_LIBRARIES curl)


text:
.class public final Lorg/codehaus/jackson/map/ser/std/StdJdkSerializers$FileSerializer;
.super Lorg/codehaus/jackson/map/ser/std/ScalarSerializerBase;
.source "StdJdkSerializers.java"

# annotations
.annotation system Ldalvik/annotation/EnclosingClass;
    value = Lorg/codehaus/jackson/map/ser/std/StdJdkSerializers;
.end annotation

.annotation system Ldalvik/annotation/InnerClass;
    accessFlags = 0x19
    name = "FileSerializer"
.end annotation

.annotation system Ldalvik/annotation/Signature;
    value = {
        "Lorg/codehaus/jackson/map/ser/std/ScalarSerializerBase",
        "<",
        "Ljava/io/File;",
        ">;"
    }
.end annotation

# direct methods
.method public constructor <init>()V
    .locals 1

    .prologue
    .line 157
    const-class v0, Ljava/io/File;

    invoke-direct {p0, v0}, Lorg/codehaus/jackson/map/ser/std/ScalarSerializerBase;-><init>(Ljava/lang/Class;)V

    return-void
.end method

# virtual methods
.method public getSchema(Lorg/codehaus/jackson/map/SerializerProvider;Ljava/lang/reflect/Type;)Lorg/codehaus/jackson/JsonNode;
    .locals 2
    .param p1, "provider"    # Lorg/codehaus/jackson/map/SerializerProvider;
    .param p2, "typeHint"    # Ljava/lang/reflect/Type;

    .prologue
    .line 169
    const-string v0, "string"

    const/4 v1, 0x1

    invoke-virtual {p0, v0, v1}, Lorg/codehaus/jackson/map/ser/std/StdJdkSerializers$FileSerializer;->createSchemaNode(Ljava/lang/String;Z)Lorg/codehaus/jackson/node/ObjectNode;

    move-result-object v0

    return-object v0
.end method

.method public serialize(Ljava/io/File;Lorg/codehaus/jackson/JsonGenerator;Lorg/codehaus/jackson/map/SerializerProvider;)V
    .locals 1
    .param p1, "value"    # Ljava/io/File;
    .param p2, "jgen"    # Lorg/codehaus/jackson/JsonGenerator;
    .param p3, "provider"    # Lorg/codehaus/jackson/map/SerializerProvider;
    .annotation system Ldalvik/annotation/Throws;
        value = {
            Ljava/io/IOException;,
            Lorg/codehaus/jackson/JsonGenerationException;
        }
    .end annotation

    .prologue
    .line 163
    invoke-virtual {p1}, Ljava/io/File;->getAbsolutePath()Ljava/lang/String;

    move-result-object v0

    invoke-virtual {p2, v0}, Lorg/codehaus/jackson/JsonGenerator;->writeString(Ljava/lang/String;)V

    .line 164
    return-void
.end method

.method public bridge synthetic serialize(Ljava/lang/Object;Lorg/codehaus/jackson/JsonGenerator;Lorg/codehaus/jackson/map/SerializerProvider;)V
    .locals 0
    .param p1, "x0"    # Ljava/lang/Object;
    .param p2, "x1"    # Lorg/codehaus/jackson/JsonGenerator;
    .param p3, "x2"    # Lorg/codehaus/jackson/map/SerializerProvider;
    .annotation system Ldalvik/annotation/Throws;
        value = {
            Ljava/io/IOException;,
            Lorg/codehaus/jackson/JsonGenerationException;
        }
    .end annotation

    .prologue
    .line 154
    check-cast p1, Ljava/io/File;

    .end local p1    # "x0":Ljava/lang/Object;
    invoke-virtual {p0, p1, p2, p3}, Lorg/codehaus/jackson/map/ser/std/StdJdkSerializers$FileSerializer;->serialize(Ljava/io/File;Lorg/codehaus/jackson/JsonGenerator;Lorg/codehaus/jackson/map/SerializerProvider;)V

    return-void
.end method