text:
import base64
import copy
import json
import sys
from keen import persistence_strategies, exceptions
from keen.api import KeenApi
from keen.persistence_strategies import BasePersistenceStrategy

__author__ = 'dkador'

class Event(object):
    """
    An event in Keen.
    """

    def __init__(self, project_id, event_collection, event_body,
                 timestamp=None):
        """ Initializes a new Event.

        :param project_id: the Keen project ID to insert the event to
        :param event_collection: the Keen collection name to insert the event to
        :param event_body: a dict that contains the body of the event to insert
        :param timestamp: optional, specify a datetime to override the
        timestamp associated with the event in Keen
        """
        super(Event, self).__init__()
        self.project_id = project_id
        self.event_collection = event_collection
        self.event_body = event_body
        self.timestamp = timestamp

    def to_json(self):
        """ Serializes the event to JSON.

        :returns: a string
        """
        event_as_dict = copy.deepcopy(self.event_body)
        if self.timestamp:
            event_as_dict["keen"] = {"timestamp": self.timestamp.isoformat()}
        return json.dumps(event_as_dict)

class KeenClient(object):
    """ The Keen Client is the main object to use to interface with Keen. It
    requires a project ID and one or both of write_key and read_key.

    Optionally, you can also specify a persistence strategy to elect how
    events are handled when they're added. The default strategy is to send
    the event directly to Keen, in-line. This may not always be the best
    idea, though, so we support other strategies (such as persisting
    to a local Redis queue for later processing).

    GET requests will timeout after 305 seconds by default.

    POST requests will timeout after 305 seconds by default.
    """

    def __init__(self, project_id, write_key=None, read_key=None,
                 persistence_strategy=None, api_class=KeenApi, get_timeout=305, post_timeout=305):
        """ Initializes a KeenClient object.

        :param project_id: the Keen IO project ID
        :param write_key: a Keen IO Scoped Key for Writes
        :param read_key: a Keen IO Scoped Key for Reads
        :param persistence_strategy: optional, the strategy to use to persist
        the event
        :param get_timeout: optional, the timeout on GET requests
        :param post_timeout: optional, the timeout on POST requests
        """
        super(KeenClient, self).__init__()

        # do some validation
        self.check_project_id(project_id)

        # Set up an api client to be used for querying and optionally passed
        # into a default persistence strategy.
        self.api = api_class(project_id, write_key=write_key, read_key=read_key,
                             get_timeout=get_timeout, post_timeout=post_timeout)

        if persistence_strategy:
            # validate the given persistence strategy
            if not isinstance(persistence_strategy, BasePersistenceStrategy):
                raise exceptions.InvalidPersistenceStrategyError()
        if not persistence_strategy:
            # setup a default persistence strategy
            persistence_strategy = persistence_strategies \
                .DirectPersistenceStrategy(self.api)

        self.project_id = project_id
        self.persistence_strategy = persistence_strategy
        self.get_timeout = get_timeout
        self.post_timeout = post_timeout

    if sys.version_info[0] < 3:
        @staticmethod
        def check_project_id(project_id):

            ''' Python 2.x-compatible string typecheck. '''

            if not project_id or not isinstance(project_id, basestring):
                raise exceptions.InvalidProjectIdError(project_id)
    else:
        @staticmethod
        def check_project_id(project_id):

            ''' Python 3.x-compatible string typecheck. '''

            if not project_id or not isinstance(project_id, str):
                raise exceptions.InvalidProjectIdError(project_id)

    def add_event(self, event_collection, event_body, timestamp=None):
        """ Adds an event.

        Depending on the persistence strategy of the client,
        this will either result in the event being uploaded to Keen
        immediately or will result in saving the event to some local cache.

        :param event_collection: the name of the collection to insert the
        event to
        :param event_body: dict, the body of the event to insert the event to
        :param timestamp: datetime, optional, the timestamp of the event
        """
        event = Event(self.project_id, event_collection, event_body,
                      timestamp=timestamp)
        self.persistence_strategy.persist(event)

    def add_events(self, events):
        """ Adds a batch of events.

        Depending on the persistence strategy of the client,
        this will either result in the event being uploaded to Keen
        immediately or will result in saving the event to some local cache.

        :param events: dictionary of events
        """
        self.persistence_strategy.batch_persist(events)

    def generate_image_beacon(self, event_collection, event_body, timestamp=None):
        """ Generates an image beacon URL.

        :param event_collection: the name of the collection to insert the
        event to
        :param event_body: dict, the body of the event to insert the event to
        :param timestamp: datetime, optional, the timestamp of the event
        """
        event = Event(self.project_id, event_collection, event_body,
                      timestamp=timestamp)
        event_json = event.to_json()
        return "{0}/{1}/projects/{2}/events/{3}?api_key={4}&data={5}".format(
            self.api.base_url, self.api.api_version, self.project_id, self._url_escape(event_collection),
            self.api.write_key.decode(sys.getdefaultencoding()), self._base64_encode(event_json)
        )

    def _base64_encode(self, string_to_encode):
        """ Base64 encodes a string, with either Python 2 or 3.

        :param string_to_encode: the string to encode
        """
        try:
            # python 2
            return base64.b64encode(string_to_encode)
        except TypeError:
            # python 3
            encoding = sys.getdefaultencoding()
            base64_bytes = base64.b64encode(bytes(string_to_encode, encoding))
            return base64_bytes.decode(encoding)

    def _url_escape(self, url):
        try:
            import urllib
            return urllib.quote(url)
        except AttributeError:
            import urllib.parse
            return urllib.parse.quote(url)

    def count(self, event_collection, timeframe=None, timezone=None, interval=None,
              filters=None, group_by=None, max_age=None):
        """ Performs a count query

        Counts the number of events that meet the given criteria.

        :param event_collection: string, the name of the collection to query
        :param timeframe: string or dict, the timeframe in which the events
        happened example: "previous_7_days"
        :param timezone: int, the timezone you'd like to use for the timeframe
        and interval in seconds
        :param interval: string, the time interval used for measuring data over
        time example: "daily"
        :param filters: array of dict, contains the filters you'd like to apply to the data
        example: [{"property_name":"device", "operator":"eq", "property_value":"iPhone"}]
        :param group_by: string or array of strings, the name(s) of the properties you would
        like to group you results by.  example: "customer.id" or ["browser","operating_system"]
        :param max_age: an integer, greater than 30 seconds, the maximum 'staleness' you're
        willing to trade for increased query performance, in seconds

        """
        params = self.get_params(event_collection=event_collection, timeframe=timeframe, timezone=timezone,
                                 interval=interval, filters=filters, group_by=group_by, max_age=max_age)
        return self.api.query("count", params)

    def sum(self, event_collection, target_property, timeframe=None, timezone=None, interval=None, filters=None,
            group_by=None, max_age=None):
        """ Performs a sum query

        Adds the values of a target property for events that meet the given criteria.

        :param event_collection: string, the name of the collection to query
        :param target_property: string, the name of the event property you would like use
        :param timeframe: string or dict, the timeframe in which the events
        happened example: "previous_7_days"
        :param timezone: int, the timezone you'd like to use for the timeframe
        and interval in seconds
        :param interval: string, the time interval used for measuring data over
        time example: "daily"
        :param filters: array of dict, contains the filters you'd like to apply to the data
        example: [{"property_name":"device", "operator":"eq", "property_value":"iPhone"}]
        :param group_by: string or array of strings, the name(s) of the properties you would
        like to group you results by.  example: "customer.id" or ["browser","operating_system"]
        :param max_age: an integer, greater than 30 seconds, the maximum 'staleness' you're
        willing to trade for increased query performance, in seconds

        """
        params = self.get_params(event_collection=event_collection, timeframe=timeframe, timezone=timezone,
                                 interval=interval, filters=filters, group_by=group_by,
                                 target_property=target_property, max_age=max_age)
        return self.api.query("sum", params)

    def minimum(self, event_collection, target_property, timeframe=None, timezone=None, interval=None,
                filters=None, group_by=None, max_age=None):
        """ Performs a minimum query

        Finds the minimum value of a target property for events that meet the given criteria.

        :param event_collection: string, the name of the collection to query
        :param target_property: string, the name of the event property you would like use
        :param timeframe: string or dict, the timeframe in which the events
        happened example: "previous_7_days"
        :param timezone: int, the timezone you'd like to use for the timeframe
        and interval in seconds
        :param interval: string, the time interval used for measuring data over
        time example: "daily"
        :param filters: array of dict, contains the filters you'd like to apply to the data
        example: [{"property_name":"device", "operator":"eq", "property_value":"iPhone"}]
        :param group_by: string or array of strings, the name(s) of the properties you would
        like to group you results by.  example: "customer.id" or ["browser","operating_system"]
        :param max_age: an integer, greater than 30 seconds, the maximum 'staleness' you're
        willing to trade for increased query performance, in seconds

        """
        params = self.get_params(event_collection=event_collection, timeframe=timeframe, timezone=timezone,
                                 interval=interval, filters=filters, group_by=group_by,
                                 target_property=target_property, max_age=max_age)
        return self.api.query("minimum", params)

    def maximum(self, event_collection, target_property, timeframe=None, timezone=None, interval=None,
                filters=None, group_by=None, max_age=None):
        """ Performs a maximum query

        Finds the maximum value of a target property for events that meet the given criteria.

        :param event_collection: string, the name of the collection to query
        :param target_property: string, the name of the event property you would like use
        :param timeframe: string or dict, the timeframe in which the events
        happened example: "previous_7_days"
        :param timezone: int, the timezone you'd like to use for the timeframe
        and interval in seconds
        :param interval: string, the time interval used for measuring data over
        time example: "daily"
        :param filters: array of dict, contains the filters you'd like to apply to the data
        example: [{"property_name":"device", "operator":"eq", "property_value":"iPhone"}]
        :param group_by: string or array of strings, the name(s) of the properties you would
        like to group you results by.  example: "customer.id" or ["browser","operating_system"]
        :param max_age: an integer, greater than 30 seconds, the maximum 'staleness' you're
        willing to trade for increased query performance, in seconds

        """
        params = self.get_params(event_collection=event_collection, timeframe=timeframe, timezone=timezone,
                                 interval=interval, filters=filters, group_by=group_by,
                                 target_property=target_property, max_age=max_age)
        return self.api.query("maximum", params)

    def average(self, event_collection, target_property, timeframe=None, timezone=None, interval=None,
                filters=None, group_by=None, max_age=None):
        """ Performs a average query

        Finds the average of a target property for events that meet the given criteria.

        :param event_collection: string, the name of the collection to query
        :param target_property: string, the name of the event property you would like use
        :param timeframe: string or dict, the timeframe in which the events
        happened example: "previous_7_days"
        :param timezone: int, the timezone you'd like to use for the timeframe
        and interval in seconds
        :param interval: string, the time interval used for measuring data over
        time example: "daily"
        :param filters: array of dict, contains the filters you'd like to apply to the data
        example: [{"property_name":"device", "operator":"eq", "property_value":"iPhone"}]
        :param group_by: string or array of strings, the name(s) of the properties you would
        like to group you results by.  example: "customer.id" or ["browser","operating_system"]
        :param max_age: an integer, greater than 30 seconds, the maximum 'staleness' you're
        willing to trade for increased query performance, in seconds

        """
        params = self.get_params(event_collection=event_collection, timeframe=timeframe, timezone=timezone,
                                 interval=interval, filters=filters, group_by=group_by,
                                 target_property=target_property, max_age=max_age)
        return self.api.query("average", params)

    def percentile(self, event_collection, target_property, percentile, timeframe=None, timezone=None,
                   interval=None, filters=None, group_by=None, max_age=None):
        """ Performs a percentile query

        Finds the percentile of a target property for events that meet the given criteria.

        :param event_collection: string, the name of the collection to query
        :param target_property: string, the name of the event property you would like use
        :param percentile: float, the specific percentile you wish to calculate,
        supporting 0-100 with two decimal places of precision for example, 99.99
        :param timeframe: string or dict, the timeframe in which the events
        happened example: "previous_7_days"
        :param timezone: int, the timezone you'd like to use for the timeframe
        and interval in seconds
        :param interval: string, the time interval used for measuring data over
        time example: "daily"
        :param filters: array of dict, contains the filters you'd like to apply to the data
        example: [{"property_name":"device", "operator":"eq", "property_value":"iPhone"}]
        :param group_by: string or array of strings, the name(s) of the properties you would
        like to group you results by.  example: "customer.id" or ["browser","operating_system"]
        :param max_age: an integer, greater than 30 seconds, the maximum 'staleness' you're
        willing to trade for increased query performance, in seconds

        """
        params = self.get_params(
            event_collection=event_collection,
            timeframe=timeframe,
            percentile=percentile,
            timezone=timezone,
            interval=interval,
            filters=filters,
            group_by=group_by,
            target_property=target_property,
            max_age=max_age,
        )
        return self.api.query("percentile", params)

    def count_unique(self, event_collection, target_property, timeframe=None, timezone=None, interval=None,
                     filters=None, group_by=None, max_age=None):
        """ Performs a count unique query

        Counts the unique values of a target property for events that meet the given criteria.

        :param event_collection: string, the name of the collection to query
        :param target_property: string, the name of the event property you would like use
        :param timeframe: string or dict, the timeframe in which the events
        happened example: "previous_7_days"
        :param timezone: int, the timezone you'd like to use for the timeframe
        and interval in seconds
        :param interval: string, the time interval used for measuring data over
        time example: "daily"
        :param filters: array of dict, contains the filters you'd like to apply to the data
        example: [{"property_name":"device", "operator":"eq", "property_value":"iPhone"}]
        :param group_by: string or array of strings, the name(s) of the properties you would
        like to group you results by.  example: "customer.id" or ["browser","operating_system"]
        :param max_age: an integer, greater than 30 seconds, the maximum 'staleness' you're
        willing to trade for increased query performance, in seconds

        """
        params = self.get_params(event_collection=event_collection, timeframe=timeframe, timezone=timezone,
                                 interval=interval, filters=filters, group_by=group_by,
                                 target_property=target_property, max_age=max_age)
        return self.api.query("count_unique", params)

    def select_unique(self, event_collection, target_property, timeframe=None, timezone=None, interval=None,
                      filters=None, group_by=None, max_age=None):
        """ Performs a select unique query

        Returns an array of the unique values of a target property for events that meet the given criteria.

        :param event_collection: string, the name of the collection to query
        :param target_property: string, the name of the event property you would like use
        :param timeframe: string or dict, the timeframe in which the events
        happened example: "previous_7_days"
        :param timezone: int, the timezone you'd like to use for the timeframe
        and interval in seconds
        :param interval: string, the time interval used for measuring data over
        time example: "daily"
        :param filters: array of dict, contains the filters you'd like to apply to the data
        example: [{"property_name":"device", "operator":"eq", "property_value":"iPhone"}]
        :param group_by: string or array of strings, the name(s) of the properties you would
        like to group you results by.  example: "customer.id" or ["browser","operating_system"]
        :param max_age: an integer, greater than 30 seconds, the maximum 'staleness' you're
        willing to trade for increased query performance, in seconds

        """
        params = self.get_params(event_collection=event_collection, timeframe=timeframe, timezone=timezone,
                                 interval=interval, filters=filters, group_by=group_by,
                                 target_property=target_property, max_age=max_age)
        return self.api.query("select_unique", params)

    def extraction(self, event_collection, timeframe=None, timezone=None, filters=None, latest=None,
                   email=None, property_names=None):
        """ Performs a data extraction

        Returns either a JSON object of events or a response
         indicating an email will be sent to you with data.

        :param event_collection: string, the name of the collection to query
        :param timeframe: string or dict, the timeframe in which the events
        happened example: "previous_7_days"
        :param timezone: int, the timezone you'd like to use for the timeframe
        and interval in seconds
        :param filters: array of dict, contains the filters you'd like to apply to the data
        example: [{"property_name":"device", "operator":"eq", "property_value":"iPhone"}]
        :param latest: int, the number of most recent records you'd like to return
        :param email: string, optional string containing an email address to email results to
        :param property_names: string or list of strings, used to limit the properties returned

        """
        params = self.get_params(event_collection=event_collection, timeframe=timeframe, timezone=timezone,
                                 filters=filters, latest=latest, email=email, property_names=property_names)
        return self.api.query("extraction", params)

    def funnel(self, steps, timeframe=None, timezone=None, max_age=None):
        """ Performs a Funnel query

        Returns an object containing the results for each step of the funnel.

        :param steps: array of dictionaries, one for each step. example:
        [{"event_collection":"signup","actor_property":"user.id"},
        {"event_collection":"purchase","actor_property:"user.id"}]
        :param timeframe: string or dict, the timeframe in which the events
        happened example: "previous_7_days"
        :param timezone: int, the timezone you'd like to use for the timeframe
        and interval in seconds
        :param max_age: an integer, greater than 30 seconds, the maximum 'staleness' you're
        willing to trade for increased query performance, in seconds

        """
        params = self.get_params(steps=steps, timeframe=timeframe, timezone=timezone, max_age=max_age)
        return self.api.query("funnel", params)

    def multi_analysis(self, event_collection, analyses, timeframe=None, interval=None, timezone=None, filters=None,
                       group_by=None, max_age=None):
        """ Performs a multi-analysis query

        Returns a dictionary of analysis results.

        :param event_collection: string, the name of the collection to query
        :param analyses: dict, the types of analyses you'd like to run.  example:
        {"total money made":{"analysis_type":"sum","target_property":"purchase.price",
        "average price":{"analysis_type":"average","target_property":"purchase.price"}
        :param timeframe: string or dict, the timeframe in which the events
        happened example: "previous_7_days"
        :param interval: string, the time interval used for measuring data over
        time example: "daily"
        :param timezone: int, the timezone you'd like to use for the timeframe
        and interval in seconds
        :param filters: array of dict, contains the filters you'd like to apply to the data
        example: [{"property_name":"device", "operator":"eq", "property_value":"iPhone"}]
        :param group_by: string or array of strings, the name(s) of the properties you would
        like to group you results by.  example: "customer.id" or ["browser","operating_system"]
        :param max_age: an integer, greater than 30 seconds, the maximum 'staleness' you're
        willing to trade for increased query performance, in seconds

        """
        params = self.get_params(
            event_collection=event_collection,
            timeframe=timeframe,
            interval=interval,
            timezone=timezone,
            filters=filters,
            group_by=group_by,
            analyses=analyses,
            max_age=max_age,
        )

        return self.api.query("multi_analysis", params)

    def get_params(self, event_collection=None, timeframe=None, timezone=None, interval=None, filters=None,
                   group_by=None, target_property=None, latest=None, email=None, analyses=None, steps=None,
                   property_names=None, percentile=None, max_age=None):
        params = {}
        if event_collection:
            params["event_collection"] = event_collection
        if timeframe:
            if type(timeframe) is dict:
                params["timeframe"] = json.dumps(timeframe)
            else:
                params["timeframe"] = timeframe
        if timezone:
            params["timezone"] = timezone
        if interval:
            params["interval"] = interval
        if filters:
            params["filters"] = json.dumps(filters)
        if group_by:
            if type(group_by) is list:
                params["group_by"] = json.dumps(group_by)
            else:
                params["group_by"] = group_by
        if target_property:
            params["target_property"] = target_property
        if latest:
            params["latest"] = latest
        if email:
            params["email"] = email
        if analyses:
            params["analyses"] = json.dumps(analyses)
        if steps:
            params["steps"] = json.dumps(steps)
        if property_names:
            params["property_names"] = json.dumps(property_names)
        if percentile:
            params["percentile"] = percentile
        if max_age:
            params["max_age"] = max_age

        return params


text:
package Communications;

import DataObjects.CurrentLaunchInformation;

public class MessageListener implements Observer
{
    static final float TWO_PI = 2.0f * (float) Math.PI;

    //for now, leave these defined here. I am working on a constant loader that will let you define
    // these in a file then have them globally accessible
    static final int ID_OFFSET = 21;
    static final int ID_SCALE = 1 << ID_OFFSET;
    static final int TIME_MESSAGE_ID = 256 * ID_SCALE;              // 0x200
    static final int MOTOR_MESSAGE_ID = 292 * ID_SCALE;             // 0x248
    static final int TORQUE_COMMAND_MESSAGE_ID = 300 * ID_SCALE;    // 0x258
    static final int STATE_MESSAGE_ID = 304 * ID_SCALE;             // 0x260
    static final int PARAM_REQUEST_MESSAGE_ID = 312 * ID_SCALE;     // 0x270
    static final int LAUNCH_PARAM_MESSAGE_ID = 320 * ID_SCALE;      // 0x280
    static final int CP_CL_RMT_MESSAGE_ID = 328 * ID_SCALE;         // 0x290
    static final int CP_CL_LCL_MESSAGE_ID = 329 * ID_SCALE;         // 0x292
    static final int CP_INPUTS_RMT_MESSAGE_ID = 330 * ID_SCALE;     // 0x294
    static final int CP_INPUTS_LCL_MESSAGE_ID = 331 * ID_SCALE;     // 0x296
    static final int CP_OUTPUTS_MESSAGE_ID = 336 * ID_SCALE;        // 0x2A0
    static final int ORIENTATION_ID = 385 * ID_SCALE;               // 0x302
    static final int DRUM_MESSAGE_ID = 432 * ID_SCALE;              // 0x360
    static final int TENSION_MESSAGE_ID = 448 * ID_SCALE;           // 0x380
    static final int CABLE_ANGLE_MESSAGE_ID = 464 * ID_SCALE;       // 0x3a0
    static final int ZERO_ODOMETER_ID = 672 * ID_OFFSET;            // 0x540
    static final int ZERO_TENSIOMETER_ID = 681 * ID_OFFSET;         // 0x552
    static final int DENSITY_ALTITUDE_ID = 689 * ID_SCALE;          // 0x562
    static final int WIND_ID = 690 * ID_SCALE;                      // 0x564
    static final int BATTERY_SYSTEM_ID = 704 * ID_SCALE;            // 0x580

    private final int NUMBER_DRUMS = 1;
    private final int NUMBER_CICS = 5;
    private final int NUMBER_MOTORS = 1;
    private float[] torqueGain = new float[NUMBER_MOTORS];

    static final int ticsPerSec = 16;   //  should be power of 2
    static final float secPerTic = 1.0f / ticsPerSec;

    private int currentState;
    //private int lastState;

    public int intUnixTime;

    private int activeDrum = 0;

    private double currentUnixTime;

    private DataRelay relay = null;

    //  variables for CIC3 filters,
    static final int filterOuputsPerSecond = 4;

    private final int decimationFactor = ticsPerSec / filterOuputsPerSecond;
    private final float gainCIC = decimationFactor * decimationFactor
            * decimationFactor;
    private final float cicGroupDelaySamples = ((decimationFactor - 1) / 2.0f)
            * 3.0f;
    //  Actual computations use sample values at one tic prior
    private final float groupDelay = (cicGroupDelaySamples - 1) * secPerTic;
    private int downCounter;

    private long[] i1 = new long[NUMBER_CICS];
    private long[] i2 = new long[NUMBER_CICS];
    private long[] i3 = new long[NUMBER_CICS];
    private long[] c1 = new long[NUMBER_CICS];
    private long[] c2 = new long[NUMBER_CICS];
    private long[] c3 = new long[NUMBER_CICS];

    private int nullMessageCnt = 0;
    private int cpOutputCnt = 0;

    //  variables, scales, and offsets for last measurements recieved in messages
    private float[] motorTorque = new float[NUMBER_MOTORS];
    private float lastCommandedDrumTorque = 0;   //  composite drum torque commanded (no losses)
    private final float cicTorqueScale = 100;

    private float lastCableTension = 0;
    private final float cicTensionScale = 100;

    private float lastCableSpeed = 0;
    private final float cicCableSpeedScale = 100;

    private float lastCableAngle = 0;
    private final float cicCableAngleScale = 100;

    private float lastCableOut = 0;
    private final float cicCableOutScale = 100;

    private float[] filteredData = new float[NUMBER_CICS];
    private float[] cicScale = new float[NUMBER_CICS];

    //  status history valables
    private byte previousTimeStatus;
    private byte previousTensionStatus;
    private byte previousDrumStatus;
    private byte previousCableAngleStatus;

    public MessageListener()
    {
        currentUnixTime = 0.0;
        torqueGain[0] = 7.0f;

        cicScale[0] = cicTorqueScale;
        cicScale[1] = cicTensionScale;
        cicScale[2] = cicCableSpeedScale;
        cicScale[3] = cicCableAngleScale;
        cicScale[4] = cicCableOutScale;
    }

    //my code will call this function
    public void attachRelay(DataRelay rIn)
    {
        relay = rIn;
    }

    public void update(String msg)
    {
        byte status;

        //  check for empty string
        if (msg.equals("") || (relay == null))
        {
            // System.out.println("Null message received: " + ++nullMessageCnt);
            return;
        }
        //decode the CANBUS message here
        CanCnvt canIn = new CanCnvt();//I believe this is the correct call
        canIn.convert_msgtobin(msg);

        switch (canIn.id)
        {
            case TIME_MESSAGE_ID:
            {
                if (canIn.dlc == 1)
                {
                    currentUnixTime = (double)intUnixTime + (double)(canIn.get_byte(0) * secPerTic);
                } else
                {
                    intUnixTime = canIn.get_int(0);
                    currentUnixTime = intUnixTime;
                    status = canIn.get_byte(4);
                    if (previousTimeStatus != status)
                    {
                        //relay.sendTimeStatus(status,
                        //        intUnixTime);
                        previousTimeStatus = status;
                    }
                }
                //   0 - torque, 1 -  tension, 2 - cable speed, 3 - cable angle,
                //   4 - cable out
                updateIntegrators(0, lastCommandedDrumTorque * cicScale[0]);
                updateIntegrators(1, lastCableTension * cicScale[1]);
                updateIntegrators(2, lastCableSpeed * cicScale[2]);
                updateIntegrators(3, lastCableAngle * cicScale[3]);
                updateIntegrators(4, lastCableOut * cicScale[4]);
                if (--downCounter < 0)
                {
                    downCounter = decimationFactor - 1; //  reset down counter
                    for (int i = 0; i < NUMBER_CICS; i++)
                    {
                        filteredData[i] = updateCombs(i)
                                / (gainCIC * cicScale[i]);
                    }
                    //  send filtered values
                    relay.sendFilteredData(filteredData, groupDelay);

                    //System.out.println("Filtered Outputs: " + filteredData[0]
                    //        + " " + filteredData[1] + " " + filteredData[2]
                    //        + " " + filteredData[3] + " " + filteredData[4]);
                }
            return;
            }

            case ORIENTATION_ID:
                {
                    float pitch = canIn.get_halffloat(0);
                    float roll = canIn.get_halffloat(2);
                    float magnetic = canIn.get_halffloat(4);
                    status = canIn.get_byte(2);
                    //System.out.println("Orientation: " + pitch
                        //+ " " +  roll + " " + magnetic);
                    //relay.sendMagneticStatus(status,
                    //        pitch, roll, magnetic);
                    return;
                }

            case STATE_MESSAGE_ID:
            {
                currentState = canIn.get_byte(0) & 0x1f;
                activeDrum = (canIn.get_byte(0) >> 5) & 0x7;
                System.out.println("State and Active Drum: " + currentState
                        + "  " +  activeDrum);
                relay.sendState(currentState, activeDrum);
                return;
            }

            case PARAM_REQUEST_MESSAGE_ID:
            {
                relay.sendLaunchParameterRequest();
                System.out.println("Launch Parameter Request Message Received");
                return;
            }
        }

        {   //  IDs with 3 mapped lsbs
            int messageDrum = (canIn.id & 0x00e00000) >> ID_OFFSET;
            switch (canIn.id & 0xff000000)
            {
                case (DRUM_MESSAGE_ID):
                {
                    status = canIn.get_byte(6);
                    if (status >= 0)
                    {
                        if (messageDrum == activeDrum) //  3 lsbs match active drum
                        {
                            lastCableOut = canIn.get_halffloat(0);
                            lastCableSpeed = canIn.get_halffloat(2)
                                    * canIn.get_halffloat(4) * TWO_PI;
                        }
                    } else if (previousDrumStatus != status)
                    {
                        //relay.sendDrumStatus(status, messageDrum,
                        //  canIn.get_halffloat(0), canIn.get_halffloat(2),
                        //  canIn.get_halffloat(4, ));
                        previousDrumStatus = status;
                    }
                    return;
                }

                case (TENSION_MESSAGE_ID):
                {
                    status = canIn.get_byte(3);
                    if (status >= 0)
                    {
                        if (messageDrum == activeDrum) //  3 lsbs match active drum
                        {
                            lastCableTension = canIn.get_halffloat(0);
                        }
                    } else if(previousTensionStatus != status)
                    {
                        //relay.sendTensionStatus(status,
                        //        messageDrum, canIn.get_halffloat(0));
                        previousTensionStatus = status;
                    }
                    return;
                }

                case (CABLE_ANGLE_MESSAGE_ID):
                {
                    status = canIn.get_byte(3);
                    if (status >= 0)
                    {
                        if (messageDrum == activeDrum) //  3 lsbs match active drum
                        {
                            lastCableAngle = canIn.get_halffloat(0);
                        }
                    } else if (previousCableAngleStatus != status)
                    {
                        //relay.CableAngleStatus(status,
                        //        messageDrum, canIn.get_halffloat(0));
                        previousCableAngleStatus = status;
                    }
                    return;
                }
            }
        }

        {   //  IDs with 2 mapped lsbs
            int messageMotor = (canIn.id & 0x00600000) >> ID_OFFSET;
            switch (canIn.id & 0xff800000)
            {
                case MOTOR_MESSAGE_ID:
                {
                    float rps = canIn.get_halffloat(0);
                    float revolutions = canIn.get_halffloat(2);
                    float temperature = (float) canIn.get_byte(4);
                    status = canIn.get_byte(5);
                    if (status >= 0)
                    {
                        //  nothing needed now
                    } else if (status != 0)
                    {
                        //relay.sendMotorStatus(status,
                        //        messageMotor, speed, revolutions,
                        //        temperature);
                    }
                    return;
                }

                case TORQUE_COMMAND_MESSAGE_ID: //  command message, no status
                {
                    motorTorque[messageMotor] = canIn.get_halffloat(0);
                    lastCommandedDrumTorque = 0;
                    //System.out.println("Commanded Motor Torque: " + motorTorque[messageMotor]
                    //        + "  " + messageMotor);
                    for (int i = 0; i < NUMBER_MOTORS; i++)
                    {
                        lastCommandedDrumTorque += motorTorque[i] * torqueGain[i];
                    }
                    return;
                }

                case BATTERY_SYSTEM_ID:
                {
                    float voltage = canIn.get_halffloat(0);
                    float current = canIn.get_halffloat(2);
                    float temperature = (float) canIn.get_byte(4);
                    status = canIn.get_byte(5);
                    System.out.println("Battery System: " + voltage
                        + " " +  current + " " + temperature);
                    //relay.sendBatteryStatus(status,
                    //        messageMotor, voltage, current, temperature);                    messageProcessed = true;
                    return;
                }
            }
        }

        {   //  lower priority and occurence messages
            switch (canIn.id)
            {
                case DENSITY_ALTITUDE_ID:
                {
                    float pressure = canIn.get_halffloat(0);
                    float temperature = (float) canIn.get_byte(2);
                    float humidity = (float) canIn.get_byte(3);
                    status = canIn.get_byte(4);
                    System.out.println("Density Altitude: " + pressure
                        + " " +  temperature + " " + humidity);
                    relay.sendDensityAltitudeStatus(status, pressure, temperature, humidity);
                    return;
                }

                case WIND_ID:
                {
                    float direction = (float) canIn.get_byte(0);
                    float speed = canIn.get_halffloat(2);
                    float gust = (float) canIn.get_byte(4);
                    status = canIn.get_byte(6);
                    System.out.println("Wind: " + direction
                        + " " +  speed + " " + gust);
                    relay.sendWindStatus(status,speed, direction, gust);
                    return;
                }
            }
        }
    }

    private void updateIntegrators(int filterIndex, float filterInput)
    {
        i1[filterIndex] += Math.round(filterInput);
        i2[filterIndex] += i1[filterIndex];
        i3[filterIndex] += i2[filterIndex];
    }

    private float updateCombs(int filterIndex)
    {
        long ctmpe, ctmpo;
        ctmpo = i3[filterIndex] - c1[filterIndex];
        c1[filterIndex] = i3[filterIndex];
        ctmpe = ctmpo - c2[filterIndex];
        c2[filterIndex] = ctmpo;
        ctmpo = ctmpe - c3[filterIndex];
        c3[filterIndex] = ctmpe;
        return ((float) ctmpo);
    }

    public void update()
    {
    } //this guy is not used, but needed because we are implementing Observer

    public double getCurrentUnixTime()
    {
        return currentUnixTime;
    }

    public boolean calculateLaunchParameters()
    {
        CurrentLaunchInformation cli = CurrentLaunchInformation.getCurrentLaunchInformation();
        boolean isReady = cli.IsReady();
        if(!isReady) return false;
        //we can use cli to get all the info needed...
        //and set our array of doubles with the necessary values.

        return true;
    }

    public void sendLaunchParameters(boolean launchReady)
    {
        if(!launchReady)
        {
            //here we can alert the operator
            //or send any necessary msgs back to the MC
        }
        else
        {
            MessagePipeline pipe = MessagePipeline.getInstance();
            CanCnvt testMsg = new CanCnvt();
            testMsg.id = LAUNCH_PARAM_MESSAGE_ID;
            testMsg.set_int(-1, 0);
            testMsg.set_int(255, 4);
            testMsg.dlc = 5;

            pipe.WriteToSocket(testMsg.msg_prep());
            //....
            //....send all messages needed
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
"""
ROSALIND - Counting DNA Nucleotides

Given: A DNA string  of length at most 1000 nt.

Return: Four integers (separated by spaces) counting the respective number of times
that the symbols 'A', 'C', 'G', and 'T' occur in.
"""
from __future__ import print_function
from __future__ import division

def nucleotide_counter(input_file):
    for line in input_file:
        line = line.strip()
        total_counts = [0]*4

        for nt in line:
            if nt == 'A':
                total_counts[0] += 1
            elif nt == 'C':
                total_counts[1] += 1
            elif nt == 'G':
                total_counts[2] += 1
            else:
                total_counts[3] += 1

    return ' '.join(str(c) for c in total_counts)

infile = open('rosalind_dna.txt', 'r')
print('A\tC\tG\tT')
print(nucleotide_counter(infile))


text:
START_ATF_NAMESPACE
    namespace std
    {
        struct _Locinfo
        {
            _Lockit _Lock;
            basic_string<char,char_traits<char>,allocator<char> > _Days;
            basic_string<char,char_traits<char>,allocator<char> > _Months;
            basic_string<char,char_traits<char>,allocator<char> > _Oldlocname;
            basic_string<char,char_traits<char>,allocator<char> > _Newlocname;
        };
    }; // end namespace std
END_ATF_NAMESPACE


text:
package org.hyperledger.indy.sdk.ledger;

import org.hyperledger.indy.sdk.IndyIntegrationTestWithSingleWallet;
import org.hyperledger.indy.sdk.InvalidStructureException;
import org.hyperledger.indy.sdk.did.Did;
import org.hyperledger.indy.sdk.did.DidResults.CreateAndStoreMyDidResult;
import org.hyperledger.indy.sdk.wallet.WalletItemNotFoundException;
import org.json.JSONObject;
import org.junit.Test;

import java.util.concurrent.ExecutionException;

import static org.hamcrest.CoreMatchers.isA;
import static org.junit.Assert.assertEquals;

public class MultiSignRequestTest extends IndyIntegrationTestWithSingleWallet {

	@Test
	public void testMultiSignWorks() throws Exception {
		CreateAndStoreMyDidResult result = Did.createAndStoreMyDid(wallet, TRUSTEE_IDENTITY_JSON).get();
		String did1 = result.getDid();

		result = Did.createAndStoreMyDid(wallet, MY1_IDENTITY_JSON).get();
		String did2 = result.getDid();

		String msg = String.format("{\n" +
				"                \"reqId\":1496822211362017764,\n" +
				"                \"identifier\":\"%s\",\n" +
				"                \"operation\":{\n" +
				"                    \"type\":\"1\",\n" +
				"                    \"dest\":\"VsKV7grR1BUE29mG2Fm2kX\",\n" +
				"                    \"verkey\":\"GjZWsBLgZCR18aL468JAT7w9CZRiBnpxUPPgyQxh4voa\"\n" +
				"                }\n" +
				"            }", did1);

		String signedMessageJson = Ledger.multiSignRequest(wallet, did1, msg).get();
		signedMessageJson = Ledger.multiSignRequest(wallet, did2, signedMessageJson).get();

		JSONObject signedMessage = new JSONObject(signedMessageJson);

		assertEquals("3YnLxoUd4utFLzeXUkeGefAqAdHUD7rBprpSx2CJeH7gRYnyjkgJi7tCnFgUiMo62k6M2AyUDtJrkUSgHfcq3vua",
				signedMessage.getJSONObject("signatures").getString(did1));
		assertEquals("4EyvSFPoeQCJLziGVqjuMxrbuoWjAWUGPd6LdxeZuG9w3Bcbt7cSvhjrv8SX5e8mGf8jrf3K6xd9kEhXsQLqUg45",
				signedMessage.getJSONObject("signatures").getString(did2));
	}

	@Test
	public void testMultiSignWorksForUnknownDid() throws Exception {
		thrown.expect(ExecutionException.class);
		thrown.expectCause(isA(WalletItemNotFoundException.class));

		String msg = "{\"reqId\":1496822211362017764}";
		Ledger.multiSignRequest(wallet, DID, msg).get();
	}

	@Test
	public void testMultiSignWorksForInvalidMessageFormat() throws Exception {
		thrown.expect(ExecutionException.class);
		thrown.expectCause(isA(InvalidStructureException.class));

		CreateAndStoreMyDidResult result = Did.createAndStoreMyDid(wallet, TRUSTEE_IDENTITY_JSON).get();
		String did = result.getDid();

		String msg = "\"reqId\":1496822211362017764";
		Ledger.multiSignRequest(wallet, did, msg).get();
	}

}


text:
package com.smcb.simulatedstock.page;

import android.app.DatePickerDialog;
import android.view.View;
import android.view.ViewGroup;
import android.widget.DatePicker;
import android.widget.TextView;
import android.widget.ListView;

import com.smcb.simulatedstock.R;
import com.smcb.simulatedstock.TradeMainUtil;
import com.smcb.simulatedstock.base.BaseFragment;
import com.smcb.simulatedstock.base.IReqData;
import com.smcb.simulatedstock.library.commonadapter.CommonAdapter;
import com.smcb.simulatedstock.utils.DataUtil;
import com.smcb.simulatedstock.utils.TradeServiceUtil;
import com.smcb.tl.entity.HisTradeEntity;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by Administrator on 2017/3/13.
 */

public class HistoryCompletedFragment extends BaseFragment {

    private IReqData activity;
    private View mEmpty;

    // Content View Elements

    private TextView mStartTime;
    private TextView mEndTime;
    private View leftView;
    private View rightView;
    private ListView mListView;
    private List<Object> mBillStocks = new ArrayList<>();
    private CommonAdapter<Object> mBillStockCommonAdapter;
    private View mStartTimeC;
    private View mEndTimeC;

    // End Of Content View Elements

    private void bindViews() {
        activity = (IReqData) TradeMainUtil.getInstance();
        mEmpty =  rootView.findViewById(R.id.empty);
        mListView = (ListView) rootView.findViewById(R.id.listView);
        mStartTime = (TextView) rootView.findViewById(R.id.startTime);
        mEndTime = (TextView) rootView.findViewById(R.id.endTime);
        mStartTimeC = rootView.findViewById(R.id.startTimeC);
        mEndTimeC = rootView.findViewById(R.id.endTimeC);

        leftView=mInflater.inflate(R.layout.back_view,null);
        addLeftView(leftView);
        leftView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                getFragmentManager().popBackStack();
            }
        });
        rightView =mInflater.inflate(R.layout.refresh_view,null);
        addRightView(rightView);
        rightView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                refresh();
            }
        });
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        Calendar instance = Calendar.getInstance();
        int mYear = instance.get(Calendar.YEAR);
        int mMonth = instance.get(Calendar.MONTH);
        int mDay = instance.get(Calendar.DAY_OF_MONTH)-7;
        instance.set(mYear,mMonth,mDay);
        String date = sdf.format(instance.getTime());
        mStartTime.setText(date);
        instance.set(mYear,mMonth,mDay+7);
        date = sdf.format(instance.getTime());
        mEndTime.setText(date);

        mStartTimeC.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                final Calendar ca = Calendar.getInstance();
                int mYear = ca.get(Calendar.YEAR);
                int mMonth = ca.get(Calendar.MONTH);
                int mDay = ca.get(Calendar.DAY_OF_MONTH)-7;
                new DatePickerDialog(act,new DatePickerDialog.OnDateSetListener(){

                    @Override
                    public void onDateSet(DatePicker datePicker, int y, int M, int d) {
                        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
                        Calendar instance = Calendar.getInstance();
                        instance.set(y,M,d);
                        String date = sdf.format(instance.getTime());
                        mStartTime.setText(date);
                        refresh();
                    }
                }, mYear, mMonth, mDay).show();
            }
        });
        mEndTimeC.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                final Calendar ca = Calendar.getInstance();
                int mYear = ca.get(Calendar.YEAR);
                int mMonth = ca.get(Calendar.MONTH);
                int mDay = ca.get(Calendar.DAY_OF_MONTH);
                new DatePickerDialog(act,new DatePickerDialog.OnDateSetListener(){

                    @Override
                    public void onDateSet(DatePicker datePicker, int y, int M, int d) {
                        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
                        Calendar instance = Calendar.getInstance();
                        instance.set(y,M,d);
                        String date = sdf.format(instance.getTime());
                        mEndTime.setText(date);
                        refresh();
                    }
                }, mYear, mMonth, mDay).show();
            }
        });
    }

    @Override
    public void addChildView(ViewGroup contentLayout) {
        rootView = mInflater.inflate(R.layout.history_completed_fragment,null);
        contentLayout.addView(rootView,layoutParamsFF);
        setTitleText("历史成交");
        bindViews();
        initViews();
        refresh();
    }

    private void initViews() {
        mBillStockCommonAdapter = DataUtil.initBillStocks(TradeServiceUtil.M_DEAL_HIS, mListView, mBillStocks, new View.OnClickListener() {
            @Override
            public void onClick(View view) {

            }
        });
    }

    @Override
    public void refresh() {
        reqListData(mStartTime.getText().toString(),mEndTime.getText().toString());
    }

    private void reqListData(String startTime,String endTime) {
        Map<String, String> args = new HashMap<>();
        args.put("startTime",startTime);
        args.put("endTime",endTime);
        activity.sendMsg(this, TradeServiceUtil.M_DEAL_HIS,args);
    }

    @Override
    public void onFragmentResult(int requestid, int responeid, Object o) {
        if (requestid == TradeServiceUtil.M_DEAL_HIS) {
            if (o instanceof String) {
                showToast((String) o);
                return;
            }
            List<HisTradeEntity> data = (List<HisTradeEntity>) o;
            if (data != null && data.size() >0) {
                mEmpty.setVisibility(View.GONE);
                mListView.setVisibility(View.VISIBLE);
                mBillStocks.clear();
                mBillStocks.addAll(data);
                mBillStockCommonAdapter.notifyDataSetChanged();
            } else {
                mEmpty.setVisibility(View.VISIBLE);
                mListView.setVisibility(View.GONE);
            }
        }
    }
}


text:
module CrawlStation
  module Adapters
    module ProxyAdapters
      class AbstractAdapter
        def push(_item)
        end

        def pop
        end

        def empty?
        end

        def closed(_item)
        end
      end
    end
  end
end


text:
<?xml version="1.0" encoding="UTF-8"?>
<!-- *************************GO-LICENSE-START******************************
 * Copyright 2017 ThoughtWorks, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *************************GO-LICENSE-END******************************* -->
<cruise xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="cruise-config.xsd" schemaVersion="108">
  <server artifactsdir="artifacts" serverId="twist" tokenGenerationKey="token">
      <security>
          <authConfigs>
              <authConfig id="bc2ff922-eb8d-4a96-9791-22fd85104a43" pluginId="cd.go.authentication.ldap">
                  <property>
                      <key>Url</key>
                      <value>ldap://does_not_exist.com</value>
                  </property>
                  <property>
                      <key>ManagerDN</key>
                      <value>cn=Active Directory Ldap User,ou=InformationSystems,ou=SharedAccounts,ou=Principal,dc=corporate,dc=thoughtworks,dc=com
                      </value>
                  </property>
                  <property>
                      <key>SearchBases</key>
                      <value>ou=Employees,ou=Enterprise,ou=Principal,dc=organisation,dc=company,dc=com
                      </value>
                  </property>
                  <property>
                      <key>UserLoginFilter</key>
                      <value>(sAMAccountName={0})</value>
                  </property>
                  <property>
                      <key>Password</key>
                      <value>password</value>
                  </property>
              </authConfig>
              <authConfig id="cc1cb954-5f97-4339-a353-1d9e23a9f29b" pluginId="cd.go.authentication.passwordfile">
                  <property>
                      <key>PasswordFilePath</key>
                      <value>$password_properties</value>
                  </property>
              </authConfig>
          </authConfigs>
      </security>
  </server>
</cruise>


text:
import operator
import argparse

import praw

parser = argparse.ArgumentParser()
parser.add_argument("--subreddit", help="which subreddit to use", default="funny")
parser.add_argument("-n","--num", help="How many posts to test", default=10)
parser.add_argument("--type", help="What type of posts, hot/new/top", default='hot')
args = parser.parse_args()

glob_words = {}

def gather_words(text,score):
    global glob_words
    words = text.split(' ')
    for word in words:
        if word in glob_words.keys():
            glob_words[word]+= score/len(words)
        else:
            glob_words[word] = score/len(words)

r = praw.Reddit(user_agent='my_cool_application')

if args.type == 'new':
    submissions = r.get_subreddit(args.subreddit).get_new(limit=int(args.num))
elif args.type == 'top':
    submissions = r.get_subreddit(args.subreddit).get_top(limit=int(args.num))
else:
    submissions = r.get_subreddit(args.subreddit).get_hot(limit=int(args.num))

for x in submissions:
    score = x.score
    text = x.selftext
    gather_words(text,score)

sorted_x = sorted(glob_words.items(), key=operator.itemgetter(1))
print sorted_x[-20:]