text:
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using TGlyph = System.Text.Rune;
using CSharpMath.Display;

namespace CSharpMath.CoreTests.FrontEnd {
  class TestGlyphBoundsProvider : Display.FrontEnd.IGlyphBoundsProvider<TestFont, TGlyph> {
    // all constants were chosen to bear some resemblance to a real font.
    private const float WidthPerCharacterPerFontSize = 0.5f; // "m" and "M" get double width.
    private const float AscentPerFontSize = 0.7f;
    private const float DescentPerFontSize = 0.2f;

    TestGlyphBoundsProvider() { }
    public static TestGlyphBoundsProvider Instance { get; } = new TestGlyphBoundsProvider();

    static readonly HashSet<TGlyph> M =
      new HashSet<TGlyph> { new TGlyph('M'), new TGlyph('m'), TGlyph.GetRuneAt("𝑀", 0), TGlyph.GetRuneAt("𝑚", 0), };
    private int GetEffectiveLength(IEnumerable<TGlyph> enumerable) {
      int length = 0;
      foreach (var c in enumerable)
        if (M.Contains(c)) length += 2;
        else length++;
      return length;
    }

    private int GetEffectiveLength(ReadOnlySpan<TGlyph> span) {
      int length = 0;
      for(int i = 0; i < span.Length; i++)
        if (M.Contains(span[i])) length += 2;
        else length++;
      return length;
    }

    public float GetTypographicWidth(TestFont font, AttributedGlyphRun<TestFont, TGlyph> run) =>
      font.PointSize * GetEffectiveLength(run.Glyphs) * WidthPerCharacterPerFontSize
      + run.GlyphInfos.Sum(g => g.KernAfterGlyph);

    public IEnumerable<RectangleF> GetBoundingRectsForGlyphs
      (TestFont font, IEnumerable<TGlyph> glyphs, int nGlyphs) =>
      glyphs.Select(glyph => {
        ReadOnlySpan<TGlyph> span = stackalloc[] { glyph };
        float width = font.PointSize * GetEffectiveLength(span) * WidthPerCharacterPerFontSize;
        float ascent = font.PointSize * AscentPerFontSize;
        float descent = font.PointSize * DescentPerFontSize;
        // The y axis is NOT inverted. So our y coordinate is minus the descent,
        // i.e. the rect bottom is the descent below the axis.
        return new RectangleF(0, -descent, width, ascent + descent);
      });

    public (IEnumerable<float> Advances, float Total) GetAdvancesForGlyphs
      (TestFont font, IEnumerable<TGlyph> glyphs, int nGlyphs) {
      var r = new float[nGlyphs];
      var total = 0f;
      int i = 0;
      foreach(var glyph in glyphs) {
        ReadOnlySpan<TGlyph> span = stackalloc[] { glyph };
        total += r[i] = GetEffectiveLength(span) * font.PointSize * WidthPerCharacterPerFontSize;
        i++;
      }
      return (r, total);
    }
  }
}


text:
class Level(object):
    """Represents user level
    """
    def __init__(self, level=1):
        """Level class initializer

        :param level: int positive number that represents level
        """
        self.level = level

    def __repr__(self):
        return "<Level '{0}' at {1}>".format(self.level, hex(id(self)))

    def set_level(self, points):
        """Set level according to the number of points a user has

        :param points: int total number of points a user has
        :return: int level
        """
        if points < 0:
            raise ValueError("Number of points must be a positive integer, "
                             "got <{0}>".format(points))
        self.level = int(points/100) + 1
        return self.level

    def reset(self):
        """Reset the level, set level to 1

        :return: the current instance
        """
        self.level = 1
        return self

redpajama_set_name: RedPajamaGithub


text:
require_relative 'app\main'

application = Main.new
application.start ARGV


text:
import {Component,ViewChild,Input,ElementRef} from 'angular2/core';

@Component({
  selector: 'match',
  template:'
<ng-content></ng-content>
'
})
export class HighlightMatch{
  @Input('matchon') matchOn: string;
  @ViewChild('defaultContent') defaultContent: ElementRef;

   ngAfterViewInit() {

     var myDiv: HTMLDivElement = this.defaultContent.nativeElement;
     var replaceWith="" +  this.matchOn + "";
      myDiv.innerHTML = myDiv.innerHTML.replace(new RegExp(this.matchOn, 'gi'), replaceWith);

   }

}


text:
package com.platform.common.cache;

import com.platform.common.utils.TimeLength;

public interface CacheRegistry {

    void addCache(String cacheName, TimeLength expirationTime);

    /**
     * Only used for in memory cache, ehcache
     *
     * @param cacheName        the name of cache
     * @param expirationTime   expiration time
     * @param maxEntriesInHeap max entries in heap
     */
    void addCache(String cacheName, TimeLength expirationTime, int maxEntriesInHeap);
}


text:
import logging
import numpy as np
import scipy.interpolate as spi
import pandas as pd
import arrow
import geojson as gj

# Our imports
import emission.storage.decorations.timeline as esdtl
import emission.storage.decorations.trip_queries as esdtq
import emission.storage.decorations.analysis_timeseries_queries as esda
import emission.storage.decorations.local_date_queries as esdl
import emission.storage.decorations.place_queries as esdp

import emission.storage.timeseries.abstract_timeseries as esta

import emission.storage.pipeline_queries as epq

import emission.analysis.intake.cleaning.location_smoothing as eaicl

import emission.core.wrapper.entry as ecwe
import emission.core.wrapper.cleanedtrip as ecwct
import emission.core.wrapper.cleanedplace as ecwcp
import emission.core.wrapper.cleanedsection as ecwcs
import emission.core.wrapper.stop as ecwst
import emission.core.wrapper.location as ecwl
import emission.core.wrapper.recreatedlocation as ecwrl

import emission.core.our_geocoder as eco

import attrdict as ad

filtered_trip_excluded = ["start_place", "end_place"]
# We are not copying over any of the exit information from the raw place because
# we may want to squish a bunch of places together, and then the end information
# will come from the final squished place
filtered_place_excluded = ["exit_ts", "exit_local_dt", "exit_fmt_time",
                           "starting_trip", "ending_trip", "duration", "_id"]
filtered_section_excluded = ["trip_id", "start_stop", "end_stop", "distance", "_id"]
filtered_stop_excluded = ["trip_id", "ending_section", "starting_section", "_id"]
filtered_location_excluded = ["speed", "distance", "_id"]

def clean_and_resample(user_id):
    time_query = epq.get_time_range_for_clean_resampling(user_id)
    try:
        last_raw_place = save_cleaned_segments_for_ts(user_id, time_query.startTs, time_query.endTs)
        epq.mark_clean_resampling_done(user_id, last_raw_place)
    except:
        logging.exception("Cleaning and resampling failed for user %s" % user_id)
        epq.mark_clean_resampling_failed(user_id)

def save_cleaned_segments_for_ts(user_id, start_ts, end_ts):
    """
    Take an unfiltered timeline and filter it by:
    - Removing trip_entries with no section_entries (typically caused by erroneous geofence exits)
    - Merging places on the two sides of a removed trip
    - Removing outlier points
    - Resampling at a fixed frequency, so that the heatmaps are consistent even
      if the raw data was sampled at different frequencies
    - Joining section_entries to each other by adding "transition" section_entries
    """
    tl = esdtl.get_raw_timeline(user_id, start_ts, end_ts)
    tl.fill_start_end_places()
    return save_cleaned_segments_for_timeline(user_id, tl)

def save_cleaned_segments_for_timeline(user_id, tl):
    ts = esta.TimeSeries.get_time_series(user_id)
    trip_map = {}
    id_or_none = lambda wrapper: wrapper.get_id() if wrapper is not None else None
    for trip in tl.trips:
        try:
            filtered_trip = get_filtered_trip(ts, trip)
            logging.debug("For raw trip %s, found filtered trip %s" %
                          (id_or_none(trip), id_or_none(filtered_trip)))
            if filtered_trip is not None:
                trip_map[trip.get_id()] = filtered_trip
        except KeyError, e:
            # We ran into key errors while dealing with mixed filter trip_entries.
            # I think those should be resolved for now, so we can raise the error again
            # But if this is preventing us from making progress, we can comment out the raise
            logging.exception("Found key error %s while processing trip %s" % (e, trip))
            # raise e
        except Exception, e:
            logging.exception("Found error %s while processing trip %s" % (e, trip))
            raise e

    (last_cleaned_place, filtered_tl) = create_and_link_timeline(tl, user_id, trip_map)

    # We have updated the first place entry in the filtered_tl, but everything
    # else is new and needs to be inserted
    if last_cleaned_place is not None:
        logging.debug("last cleaned_place %s was already in database, updating..." %
            last_cleaned_place)
        ts.update(last_cleaned_place)
    if filtered_tl is not None:
        for entry in filtered_tl:
            ts.insert(entry)

    return tl.last_place()

def get_filtered_trip(ts, trip):
    logging.debug("Filtering trip %s" % trip)
    trip_tl = esdtq.get_raw_timeline_for_trip(trip.user_id, trip.get_id())
    # trip_tl is the timeline for this particular trip, which contains the
    # section_entries and trip_entries
    if len(trip_tl.trips) == 0:
        logging.info("Found zero section trip %s " % trip)
        return None

    # Else, this is a non-zero section trip
    filtered_trip_data = ecwct.Cleanedtrip()

    _copy_non_excluded(old_data=trip.data,
                       new_data=filtered_trip_data,
                       excluded_list=filtered_trip_excluded)

    filtered_trip_data.raw_trip = trip.get_id()
    filtered_trip_entry = ecwe.Entry.create_entry(trip.user_id, esda.CLEANED_TRIP_KEY,
                                                  filtered_trip_data,
                                                  create_id = True)

    # Map from old section id -> new section object
    section_map = {}
    for section in trip_tl.trips:
        section_map[section.get_id()] = get_filtered_section(filtered_trip_entry, section)

    stop_map = {}
    for stop in trip_tl.places:
        stop_map[stop.get_id()] = get_filtered_stop(filtered_trip_entry, stop)

    # TODO: DO we need to add the stop distances too? They should be small...
    trip_distance = sum([section.data.distance for section in section_map.values()])
    filtered_trip_data.distance = trip_distance
    filtered_trip_entry["data"] = filtered_trip_data

    # After we have linked everything back together. NOW we can save the entries
    linked_tl = link_trip_timeline(trip_tl, section_map, stop_map)
    for entry in linked_tl:
        ts.insert(entry)

    return filtered_trip_entry

def get_filtered_place(raw_place):
    filtered_place_data = ecwcp.Cleanedplace()

    _copy_non_excluded(old_data=raw_place.data,
                       new_data=filtered_place_data,
                       excluded_list=filtered_place_excluded)

    filtered_place_data.raw_places = []
    filtered_place_data.append_raw_place(raw_place.get_id())

    try:
        reverse_geocoded_json = eco.Geocoder.get_json_reverse(filtered_place_data.location.coordinates[1],
                                                              filtered_place_data.location.coordinates[0])
        if reverse_geocoded_json is not None:
            filtered_place_data.display_name = format_result(reverse_geocoded_json)
    except:
        logging.exception("Unable to pre-fill reverse geocoded information, client has to do it")

    logging.debug("raw_place.user_id = %s" % raw_place.user_id)
    curr_cleaned_end_place = ecwe.Entry.create_entry(raw_place.user_id,
                                                     esda.CLEANED_PLACE_KEY,
                                                     filtered_place_data,
                                                     create_id=True)
    return curr_cleaned_end_place

def get_filtered_section(new_trip_entry, section):
    """
    Save the filtered points associated with this section.
    Do I need a cleaned section as well?
    At first glance, it doesn't seem necessary, since all sections are valid.
    But don't we need a cleaned section that has a trip id == the cleaned trip.
    Otherwise, we need to modify the trip_id of the raw section, which means
    that this is no longer a progressive system that we can recreate.
    So let's create a new entry for the cleaned section that is identical to
    the old section, but pointing to the cleaned trip.
    :param ts: the timeseries for this user
    :param trip: the trip that this section is a part of
    :param section: the section that we are saving
    :return: None
    """
    filtered_section_data = ecwcs.Cleanedsection()

    _copy_non_excluded(old_data=section.data,
                       new_data=filtered_section_data,
                       excluded_list=filtered_section_excluded)

    filtered_section_data.trip_id = new_trip_entry.get_id()

    # Now that we have constructed the section object, we have to filter and
    # store the related data points
    with_speeds_df = get_filtered_points(section, filtered_section_data)
    speeds = list(with_speeds_df.speed)
    distances = list(with_speeds_df.distance)
    filtered_section_data.speeds = speeds
    filtered_section_data.distances = distances
    filtered_section_data.distance = sum(distances)
    filtered_section_entry = ecwe.Entry.create_entry(section.user_id,
                                    esda.CLEANED_SECTION_KEY,
                                    filtered_section_data, create_id=True)

    ts = esta.TimeSeries.get_time_series(section.user_id)
    for row in with_speeds_df.to_dict('records'):
        loc_row = ecwrl.Recreatedlocation(row)
        loc_row.mode = section.data.sensed_mode
        loc_row.section = filtered_section_entry.get_id()
        ts.insert_data(section.user_id, esda.CLEANED_LOCATION_KEY, loc_row)

    return filtered_section_entry

def get_filtered_stop(new_trip_entry, stop):
    """
    If we have filtered sections, I guess we need to have filtered stops as well.
    These should also point to the new trip

    :param new_trip_trip: the trip that this stop is part of
    :param stop: the section that this is part of
    :return: None
    """
    filtered_stop_data = ecwst.Stop()
    filtered_stop_data['_id'] = new_trip_entry.get_id()
    filtered_stop_data.trip_id = new_trip_entry.get_id()
    _copy_non_excluded(old_data=stop.data,
                       new_data=filtered_stop_data,
                       excluded_list=filtered_stop_excluded)
    return ecwe.Entry.create_entry(stop.user_id, esda.CLEANED_STOP_KEY,
                                   filtered_stop_data, create_id=True)

def get_filtered_points(section, filtered_section_data):
    logging.debug("Getting filtered points for section %s" % section)
    ts = esta.TimeSeries.get_time_series(section.user_id)
    loc_entry_it = ts.find_entries(["background/filtered_location"],
                                   esda.get_time_query_for_trip_like(
                                       esda.RAW_SECTION_KEY, section.get_id()))

    loc_entry_list = [ecwe.Entry(e) for e in loc_entry_it]

    # We know that the assertion fails in the geojson conversion code and we
    # handle it there, so we are just going to comment this out for now.
    # assert (loc_entry_list[-1].data.loc == section.data.end_loc,
    #         "section_location_array[-1].loc != section.end_loc even after df.ts fix",
    #         (loc_entry_list[-1].data.loc, section.data.end_loc))

    # Find the list of points to filter
    filtered_points_entry_doc = ts.get_entry_at_ts("analysis/smoothing",
                                                   "data.section",
                                                   section.get_id())

    if filtered_points_entry_doc is None:
        logging.debug("No filtered_points_entry, filtered_points_list is empty")
        filtered_point_id_list = []
    else:
        # TODO: Figure out how to make collections work for the wrappers and then change this to an Entry
        filtered_points_entry = ad.AttrDict(filtered_points_entry_doc)
        filtered_point_id_list = list(filtered_points_entry.data.deleted_points)
        logging.debug("deleting %s points from section points" % len(
            filtered_point_id_list))

    filtered_loc_list = remove_outliers(loc_entry_list, filtered_point_id_list)

    # filtered_loc_list has removed the outliers. Now, we resample the data at
    # 30 sec intervals
    resampled_loc_df = resample(filtered_loc_list, interval=30)
    # If this is the first section, we need to find the start place of the parent trip
    # and actually start from there. That will fix the distances but not the duration
    # because we haven't yet figured out how to get the correct start time.
    # TODO: Fix this!!
    # For now, we will fudge this in the geojson converter, as always

    with_speeds_df = eaicl.add_dist_heading_speed(resampled_loc_df)
    with_speeds_df["idx"] = np.arange(0, len(with_speeds_df))
    with_speeds_df_nona = with_speeds_df.dropna()
    logging.info("removed %d entries containing n/a" %
        (len(with_speeds_df_nona) - len(with_speeds_df)))
    return with_speeds_df_nona

def _copy_non_excluded(old_data, new_data, excluded_list):
    for key in old_data:
        if key not in excluded_list:
            new_data[key] = old_data[key]

def remove_outliers(raw_loc_entry_list, filtered_point_id_list):
    filtered_loc_list = []
    for loc_entry in raw_loc_entry_list:
        if loc_entry.get_id() not in filtered_point_id_list:
            filtered_location_data = ecwl.Location()
            _copy_non_excluded(old_data=loc_entry.data,
                               new_data=filtered_location_data,
                               excluded_list=filtered_location_excluded)
            filtered_loc_list.append(filtered_location_data)
    return filtered_loc_list

def resample(filtered_loc_list, interval):
    """
    TODO: There is a problem with working on this on a section by section basis.
    Namely, how do we deal with the ends. In particular, note that our sections
    are generated by looking at motion activity while our points are generated
    by looking at locations, and the two streams are not synchronized. So we have
    "transition areas" between sections that have no points. Resampling will
    help with this because we can ensure that arbitrary time point - for example,
    the transition between sections, has an associated location point. But that
    fix really needs to be made in the segmentation code - by this point, the
    original timestamps have been replaced by the timestamps of the start and
    end location points. But we can also have a gap if the duration of the section
    is not a multiple of the interval, as it is likely to be. In this case, we will
    manually add the last entry to ensure that we adequately capture the end point.
    :param filtered_loc_list:
    :param interval:
    :return:
    """
    loc_df = pd.DataFrame(filtered_loc_list)
    # See https://github.com/e-mission/e-mission-server/issues/268 for log traces
    #
    # basically, on iOS, due to insufficient smoothing, it is possible for us to
    # have very small segments. Some of these contain zero points, and we skip them
    # in the segmentation stage. Some of them contain one point, and we don't.
    # Ideally, we would strip these sections too and merge the stops on the two sides
    # But that is going to take more time and effort than I have here.
    #
    # So let's just return the one point without resampling in that case, and move on for now
    if len(loc_df) == 0 or len(loc_df) == 1:
        return loc_df
    logging.debug("Resampling entry list %s of size %s" % (loc_df.head(), len(filtered_loc_list)))
    start_ts = loc_df.ts.iloc[0]
    end_ts = loc_df.ts.iloc[-1]
    tz_ranges_df = _get_tz_ranges(loc_df)
    logging.debug("tz_ranges_df = %s" % tz_ranges_df)

    lat_fn = spi.interp1d(x=loc_df.ts, y=loc_df.latitude, bounds_error=False,
                          fill_value='extrapolate')

    lng_fn = spi.interp1d(x=loc_df.ts, y=loc_df.longitude, bounds_error=False,
                          fill_value='extrapolate')

    altitude_fn = spi.interp1d(x=loc_df.ts, y=loc_df.altitude, bounds_error=False,
                          fill_value='extrapolate')

    ts_new = np.append(np.arange(start_ts, end_ts, 30), [end_ts])
    logging.debug("After resampling, using %d points" % ts_new.size)
    lat_new = lat_fn(ts_new)
    lng_new = lng_fn(ts_new)
    alt_new = altitude_fn(ts_new)
    tz_new = [_get_timezone(ts, tz_ranges_df) for ts in ts_new]
    ld_new = [esdl.get_local_date(ts, tz) for (ts, tz) in zip(ts_new, tz_new)]
    loc_new = [gj.Point((lng, lat)) for (lng, lat) in zip(lng_new, lat_new)]
    fmt_time_new = [arrow.get(ts).to(tz).isoformat() for
                        (ts, tz) in zip(ts_new, tz_new)]
    loc_df_new = pd.DataFrame({"latitude": lat_new, "longitude": lng_new,
                               "loc": loc_new, "ts": ts_new, "local_dt": ld_new,
                               "fmt_time": fmt_time_new, "altitude": alt_new})
    return loc_df_new

def _get_timezone(ts, tz_ranges_df):
    # TODO: change this to a dataframe query instead
    sel_entry = tz_ranges_df[(tz_ranges_df.start_ts <= ts) &
                        (tz_ranges_df.end_ts >= ts)]
    if len(sel_entry) != 1:
        logging.warning("len(sel_entry) = %d, using the one with the bigger duration" % len(sel_entry))
        sel_entry["duration"] = sel_entry.end_ts - sel_entry.start_ts
        sel_entry = sel_entry[sel_entry.duration == sel_entry.duration.max()]
    return sel_entry.timezone.iloc[0]

def _get_tz_ranges(loc_df):
    tz_ranges = []
    if len(loc_df) == 0:
        return tz_ranges

    # We know that there is at least one entry, so we can access it with impunity
    curr_start_ts = loc_df.ts.iloc[0]
    curr_tz = loc_df.local_dt.iloc[0]["timezone"]
    for row in loc_df.to_dict('records'):
        loc_data = ecwl.Location(row)
        if loc_data.local_dt["timezone"] != curr_tz:
            tz_ranges.append({'timezone': curr_tz,
                              'start_ts': curr_start_ts,
                              'end_ts': loc_data.ts})
            curr_start_ts = loc_data.ts
            curr_tz = loc_data.local_dt["timezone"]

    # At the end, always add an entry
    # For cases in which there is only one timezone (common case),
    # this will be the only entry
    tz_ranges.append({'timezone': curr_tz,
                      'start_ts': curr_start_ts,
                      'end_ts': loc_df.ts.iloc[-1]})
    logging.debug("tz_ranges = %s" % tz_ranges)
    return pd.DataFrame(tz_ranges)

def link_trip_timeline(tl, section_map, stop_map):
    filled_in_sections = [_fill_section(s, section_map[s.get_id()], stop_map) for s in tl.trips]
    filled_in_stops = [_fill_stop(s, stop_map[s.get_id()], section_map) for s in tl.places]
    return esdtl.Timeline(esda.CLEANED_STOP_KEY, esda.CLEANED_SECTION_KEY,
                          filled_in_stops, filled_in_sections)

def _fill_section(old_section, new_section, stop_map):
    section_data = new_section.data
    # the first section will have the start_stop == None and the last section
    # will have the end_stop == None, so we handle those by a simple check
    if old_section.data.start_stop is not None:
        section_data.start_stop = stop_map[old_section.data.start_stop].get_id()
    if old_section.data.end_stop is not None:
        section_data.end_stop = stop_map[old_section.data.end_stop].get_id()
    new_section["data"] = section_data
    return new_section

def _fill_stop(old_stop, new_stop, section_map):
    stop_data = new_stop.data
    stop_data.ending_section = section_map[old_stop.data.ending_section].get_id()
    stop_data.starting_section = section_map[old_stop.data.starting_section].get_id()
    new_stop["data"] = stop_data
    return new_stop

def create_and_link_timeline(tl, user_id, trip_map):
    last_cleaned_place = esdp.get_last_place_entry(esda.CLEANED_PLACE_KEY, user_id)
    cleaned_places = []
    curr_cleaned_start_place = last_cleaned_place
    if curr_cleaned_start_place is None:
        # If it is not present - maybe this user is getting started for the first
        # time, we create an entry based on the first trip from the timeline
        curr_cleaned_start_place = get_filtered_place(tl.first_place())
        logging.debug("no last cleaned place found, created place with id %s" % curr_cleaned_start_place.get_id())
        # We just created this place here, so lets add it to the created places
        # and insert rather than update it
        cleaned_places.append(curr_cleaned_start_place)
    else:
        logging.debug("Cleaned place %s found, using it" % curr_cleaned_start_place.get_id())

    if curr_cleaned_start_place is None:
        # If the timeline has no entries, we give up and return
        return (None, None)

    unsquished_trips = []

    for raw_trip in tl.trips:
        if raw_trip.get_id() in trip_map:
            # there is a clean representation for this trip, so we can link its
            # start to the curr_cleaned_start_place
            curr_cleaned_trip = trip_map[raw_trip.get_id()]
            raw_start_place = tl.get_object(raw_trip.data.start_place)
            link_trip_start(curr_cleaned_trip, curr_cleaned_start_place, raw_start_place)

            raw_end_place = tl.get_object(raw_trip.data.end_place)
            curr_cleaned_end_place = get_filtered_place(raw_end_place)
            cleaned_places.append(curr_cleaned_end_place)
            link_trip_end(curr_cleaned_trip, curr_cleaned_end_place, raw_end_place)

            curr_cleaned_start_place = curr_cleaned_end_place
            logging.debug("Found mapping %s -> %s, added links" %
                          (raw_trip.get_id(), curr_cleaned_trip.get_id()))
            unsquished_trips.append(curr_cleaned_trip)
        else:
            # this is a squished trip, so we combine the start place with the
            # current start place we do not need to combine both start and end
            # places, since the end place of one trip is the start place of another. We combine start places instead of end places
            # because when the squishy part ends, we combine the start place of the un-squished trip
            # with the existing cleaned start and create a new entry for the un-squished end
            logging.debug("Found squished trip, linking raw start place %s to new cleaned place %s" %
                          (raw_trip.data.start_place, curr_cleaned_start_place.get_id()))
            link_squished_place(curr_cleaned_start_place,
                                tl.get_object(raw_trip.data.start_place))

    logging.debug("Finished creating and linking timeline, returning %d places and %d trips" % (len(cleaned_places), len(trip_map.values())))
    return (last_cleaned_place, esdtl.Timeline(esda.CLEANED_PLACE_KEY,
                                               esda.CLEANED_TRIP_KEY,
                                               cleaned_places,
                                               unsquished_trips))

def link_squished_place(cleaned_place, raw_place):
    cleaned_place_data = cleaned_place.data
    cleaned_place_data.append_raw_place(raw_place.get_id())
    cleaned_place["data"] = cleaned_place_data

def link_trip_start(cleaned_trip, cleaned_start_place, raw_start_place):
    logging.debug("for trip %s start, converting %s to %s" %
                  (cleaned_trip, cleaned_start_place, raw_start_place))
    cleaned_start_place_data = cleaned_start_place.data
    cleaned_trip_data = cleaned_trip.data

    cleaned_trip_data.start_place = cleaned_start_place.get_id()

    # We have now reached the end of the squishing. Let's hook up the end information
    for key in raw_start_place.data:
        if key in ["exit_ts", "exit_local_dt", "exit_fmt_time"]:
            cleaned_start_place_data[key] = raw_start_place.data[key]
    cleaned_start_place_data.starting_trip = cleaned_trip.get_id()
    if cleaned_start_place_data.enter_ts is not None and \
		cleaned_start_place_data.exit_ts is not None:
           cleaned_start_place_data.duration = cleaned_start_place_data.exit_ts - \
                                            cleaned_start_place_data.enter_ts
    else:
           logging.debug("enter_ts = %s, exit_ts = %s, unknown duration" %
		(cleaned_start_place_data.enter_ts, cleaned_start_place_data.enter_ts))

    # Appended while creating the start place, or while handling squished
    # TODO: Don't think I need this?
    # cleaned_start_place_data.append_raw_place(raw_trip.data.start_place)

    cleaned_start_place["data"] = cleaned_start_place_data
    cleaned_trip["data"] = cleaned_trip_data

def link_trip_end(cleaned_trip, cleaned_end_place, raw_end_place):
    cleaned_end_place_data = cleaned_end_place.data
    cleaned_trip_data = cleaned_trip.data

    cleaned_trip_data.end_place = cleaned_end_place.get_id()
    cleaned_end_place_data.ending_trip = cleaned_trip.get_id()

    cleaned_end_place["data"] = cleaned_end_place_data
    cleaned_trip["data"] = cleaned_trip_data

def format_result(rev_geo_result):
    get_fine = lambda rgr: get_with_fallbacks(rgr["address"], ["road", "neighbourhood"])
    get_coarse = lambda rgr: get_with_fallbacks(rgr["address"], ["city", "town", "county"])
    name = "%s, %s" % (get_fine(rev_geo_result), get_coarse(rev_geo_result))
    return name

def get_with_fallbacks(json, fallback_key_list):
    for key in fallback_key_list:
        if key in json:
            return json[key]
    return ""


text:
/**
 * 1. 在父组件MessageBox组件里定义一个状态对象,{messages:[]}
 * 2. 把此messages数组传递给MessageList来显示 消息列表
 * 3. 给MessageForm中的按钮绑定点击事件,当点击按钮的时候,得到input框的内容,然后调用父组件的方法来把此内容添加到messages数组中
 * 4. 因为messages内容改变了,会重新渲染MessageList组件中的消息列表
 */
var MessageBox = React.createClass({
    getInitialState(){
        return {messages:[]}
    },
    handleClick(msg){
        this.state.messages.push(msg);
        this.setState({messages:this.state.messages});
    },

  // 放置form list   panel panel-default
    render(){
        return

            <MessageForm click={this.handleClick}></MessageForm>
            <MessageList messages={this.state.messages}></MessageList>

    }
});
var MessageForm = React.createClass({
    handleClick(){
       var value =  this.refs.myInput.value;
        this.props.click(value);
        this.refs.myInput.value = '';
    },
  //放置表单 input form-control button btn btn-primary panel-heading
    render(){
        return (

                <input ref="myInput" type="text" className="form-control"/>
                <button onClick={this.handleClick} className="btn btn-primary">发言</button>

        )
    }
});
var MessageList = React.createClass({
  //列表  list-group list-group-item panel-body
    render(){
        return (

                    {
                        this.props.messages.map(function(item){
                            return
{item}

                        })
                    }

        )
    }
});

ReactDOM.render(<MessageBox/>,document.getElementById('app'));


text:
<?php

namespace Antvel\Tests\Unit\Products;

use Antvel\Tests\TestCase;
use Antvel\Product\Models\Product;
use Antvel\Product\Suggestions\Suggest;

class SuggestionsTest extends TestCase
{
	public function setUp()
	{
		parent::setUp();

		$this->products = $this->createProducts();
	}

	protected function tagsToArray($tags)
	{
		return explode(',', $tags->implode(','));
	}

	protected function createProducts($tags = ['incidunt', 'qui', 'et', 'dolorem', 'id', 'ut'])
	{
		factory(Product::class, 16)->create();

		//We create 3 last new products to compare against and see if what is returned is correct.
		//These products have to be at the end in order for us to validate that suggestions do
		//not contain listed products
		foreach ($tags as $tag) {
			factory(Product::class)->create(['tags' => $tag]);
		}

		return Product::get();
	}

	/** @test */
	function it_always_returns_a_collection_object()
	{
		$this->signIn([
			'preferences' => '{"product_shared":"incidunt,et,qui"}'
		]);

		$suggestions = Suggest::for('product_shared')->shake();

		$this->assertInstanceOf('\Illuminate\Support\Collection', $suggestions);
	}

	/** @test */
	function it_suggests_products_based_on_user_preferences_for_a_given_key()
	{
		$user = factory('Antvel\User\Models\User')->make([
			'preferences' => '{"my_searches":"incidunt,et,qui"}'
		]);

		$listedProducts = $this->products->take(10);

		$suggestions = Suggest::for('my_searches')->actingAs($user)
			->excluding($listedProducts)
			->shake()
			->get('my_searches');

		$suggestionsTags = $this->tagsToArray(
			$suggestions->pluck('tags')
		);

		$foundProducts = $this->products->whereIn(
			'id', $suggestions->pluck('id')->all()
		);

		$this->assertTrue($foundProducts->count() <= 4);
		$this->assertCount(0, array_intersect(
			$foundProducts->pluck('id')->all(), $listedProducts->pluck('id')->all()
		));
	}

	/** @test */
	function it_suggests_products_based_on_signed_user_preferences_for_a_given_key()
	{
		$user = $this->signIn([
			'preferences' => '{"product_shared":"incidunt,et,qui"}'
		]);

		$listedProducts = $this->products->take(10);

		$suggestions = Suggest::for('my_searches')
			->excluding($listedProducts)
			->shake()
			->get('my_searches');

		$suggestionsTags = $this->tagsToArray(
			$suggestions->pluck('tags')
		);

		$foundProducts = $this->products->whereIn(
			'id', $suggestions->pluck('id')->all()
		);

		$this->assertTrue($foundProducts->count() <= 4);
		$this->assertCount(0, array_intersect(
			$foundProducts->pluck('id')->all(), $listedProducts->pluck('id')->all()
		));
	}

	/** @test */
	function it_completes_suggestion_with_random_for_a_given_key_if_the_limit_was_not_fulfill()
	{
		$user = $this->signIn([
			'preferences' => '{"product_viewed":"incidunt,et,qui"}'
		]);

		$suggestions = Suggest::for('product_viewed')->shake()->get('product_viewed');

		$this->assertCount(4, $suggestions);
	}

	/** @test */
	function it_is_able_to_suggest_for_a_list_of_given_keys()
	{
		$this->signIn([
			'preferences' => '{"product_shared":"dolorem,id,ut", "product_viewed":"incidunt,et,qui"}'
		]);

		$suggestions = Suggest::for('product_viewed', 'product_shared')->shake();

		$this->assertNotNull($suggestions->get('product_viewed'));
		$this->assertNotNull($suggestions->get('product_shared'));
		$this->assertCount(4, $suggestions->get('product_viewed'));
		$this->assertCount(4, $suggestions->get('product_shared'));
	}

	/** @test */
	function it_can_suggest_products_based_on_a_given_input()
	{
		$suggestions = Suggest::shakeFor($this->products->take(10));

		$this->assertInstanceOf('\Illuminate\Support\Collection', $suggestions);
		$this->assertCount(4, $suggestions);
	}
}


text:
'use strict';

const LayoutPropTypes = require('LayoutPropTypes');
const PropTypes = require('react/lib/ReactPropTypes');
const TransformPropTypes = require('TransformPropTypes');

/**
 * Warning: Some of these properties may not be supported in all releases.
 */
const LayoutAndTransformOpacityPropTypes = {
  ...LayoutPropTypes,
  ...TransformPropTypes,
  opacity: PropTypes.number,
};

module.exports = LayoutAndTransformOpacityPropTypes;


text:
package com.withwiz.plankton.network.message2;

/**
 * Default message extended interface
 */
public interface IDefaultMessageEx<TYPE_RAW_DATA> extends IDefaultMessage<TYPE_RAW_DATA> {
    /**
     * get tail
     *
     * @return IDefaultMessageTail
     */
    IDefaultMessageTail<TYPE_RAW_DATA> getTail();
}


text:
<?php

namespace App\Http\Controllers\Bugtracker;

use App\Http\Requests\BoardCreateForm;
use Illuminate\Http\Request;
use App\Http\Controllers\BugtrackerBaseController;

use App\Board;
use App\Project;

class BoardsController extends BugtrackerBaseController
{

    /**
     * Show all boards, assigned to the project.
     *
     * @param Project $project
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function index(Project $project)
    {
        $boards = $project->boards;

        return view('bugtracker.project.boards', compact('boards', 'project'));
    }

    /**
     * Create board, and store it in DataBase.
     *
     * @param BoardCreateForm $request
     * @param Project $project
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function create(BoardCreateForm $request, Project $project)
    {
        $board = $project->boards()->create($request->all());

        if($request->ajax()) {
            return view('bugtracker.editor.partials.board-box', compact('board','project'));
        }

        return redirect()->back();
    }

    /**
     * Delete board.
     *
     * @param Request $request
     * @param Project $project
     * @param Board $board
     * @return \Illuminate\Http\RedirectResponse
     */
    public function delete(Request $request, Project $project, Board $board)
    {
        $board->delete();

        if($request->ajax()) {
            return response("", 200);
        }

        return redirect()->back();
    }

}


text:
#include <aws/ce/model/TerminateRecommendationDetail.h>
#include <aws/core/utils/json/JsonSerializer.h>

#include <utility>

using namespace Aws::Utils::Json;
using namespace Aws::Utils;

namespace Aws
{
namespace CostExplorer
{
namespace Model
{

TerminateRecommendationDetail::TerminateRecommendationDetail() :
    m_estimatedMonthlySavingsHasBeenSet(false),
    m_currencyCodeHasBeenSet(false)
{
}

TerminateRecommendationDetail::TerminateRecommendationDetail(JsonView jsonValue) :
    m_estimatedMonthlySavingsHasBeenSet(false),
    m_currencyCodeHasBeenSet(false)
{
  *this = jsonValue;
}

TerminateRecommendationDetail& TerminateRecommendationDetail::operator =(JsonView jsonValue)
{
  if(jsonValue.ValueExists("EstimatedMonthlySavings"))
  {
    m_estimatedMonthlySavings = jsonValue.GetString("EstimatedMonthlySavings");

    m_estimatedMonthlySavingsHasBeenSet = true;
  }

  if(jsonValue.ValueExists("CurrencyCode"))
  {
    m_currencyCode = jsonValue.GetString("CurrencyCode");

    m_currencyCodeHasBeenSet = true;
  }

  return *this;
}

JsonValue TerminateRecommendationDetail::Jsonize() const
{
  JsonValue payload;

  if(m_estimatedMonthlySavingsHasBeenSet)
  {
   payload.WithString("EstimatedMonthlySavings", m_estimatedMonthlySavings);

  }

  if(m_currencyCodeHasBeenSet)
  {
   payload.WithString("CurrencyCode", m_currencyCode);

  }

  return payload;
}

} // namespace Model
} // namespace CostExplorer
} // namespace Aws


text:
<?php

require_once("config.inc");
require_once("auth.inc");
require_once("xmlrpc.inc");

/**
 * do a basic authentication, uses $_SERVER['HTTP_AUTHORIZATION'] to validate user.
 * @param string $http_auth_header content of the Authorization HTTP header
 * @return bool
 */
function http_basic_auth($http_auth_header)
{
    $tags = explode(' ', $http_auth_header);
    if (count($tags) >= 2) {
        $userinfo= explode(':', base64_decode($tags[1]), 2);
        if (count($userinfo) == 2) {
            $username = authenticate_user($userinfo[0], $userinfo[1]);
            if ($username !== false) {
                $aclObj = new \OPNsense\Core\ACL();
                return $aclObj->isPageAccessible($username, '/xmlrpc.php');
            }
        }
    }

    /* not authenticated */
    return false;
}

function authenticate_user($username, $password)
{
    $authFactory = new OPNsense\Auth\AuthenticationFactory();

    foreach(['Local Database', 'Local API'] as $authName) {
        $authenticator = $authFactory->get($authName);
        if ($authenticator != null && $authenticator->authenticate($username, $password)) {
            $authResult = $authenticator->getLastAuthProperties();
            if (array_key_exists('username', $authResult)) {
                 $username = $authResult['username'];
            }
            return $username;
        }
    }

    log_msg('Unable to retrieve authenticator for ' . $username, LOG_ERR);

    return false;
}

/**
 *   Simple XML-RPC server using IXR_Library
 */
if (!isset($_SERVER['HTTP_AUTHORIZATION']) ||               // check for an auth header
    !http_basic_auth($_SERVER['HTTP_AUTHORIZATION']) ||     // user authentication failure (basic auth)
    $_SERVER['SERVER_ADDR'] == $_SERVER['REMOTE_ADDR']      // do not accept request from server's own address
) {
    // Authentication failure, bail out.
    $xml = <<<EOD
<methodResponse>
<params>
    <param>
      <value>Authentication failed</value>
    </param>
  </params>
</methodResponse>

EOD;

    $xml = '<?xml version="1.0"?>'."\n".$xml;
    $length = strlen($xml);
    header('Connection: close');
    header('Content-Length: '.$length);
    header('Content-Type: text/xml');
    header('Date: '.date('r'));
    echo $xml;
} else {
    $server = new XMLRPCServer();
    $server->start();
}


text:
Administration de la boutique

                        Ajouter un article.

							<form class="form" id="form-shop-add" method="post" autocomplete="off">

									Titre:
									<input type="text" placeholder="Titre de l'article" name="title" id="title" class="form-control" />

									Coût:
									<input type="text" placeholder="Coût de l'article" name="cost" id="cost" class="form-control" />

										Note:

									<textarea type="text" placeholder="Note" name="note" id="note" class="form-control" row="4"></textarea>

										Visible:

										<input type="checkbox" name="visible" id="visible" value="1" checked/>

										Description:

									<textarea type="text" placeholder="Description de l'article" name="description" id="description" class="form-control" row="4"></textarea>

										Image:

										<input type="text" placeholder="Image" name="img" id="img" class="form-control" disabled/>

										<button type="button" class="btn btn-sm btn-info" onclick="showGallery()" style="margin-left: 10px;">Galerie</button>

										-

									<input type="submit" name="submit" id="submit" class="btn btn-success" value="Ajouter"/>

							</form>

                        Liste des articles
                        <button class="btn btn-xs pull-right btn-default" id="shop-btn-refresh"></button>

                        Liste des achats
                        <button class="btn btn-xs pull-right btn-default" id="purchases-btn-refresh"></button>

Afin d'éviter un chargement trop long, les requêtes ont été bloquées. Veuillez cliquer sur le bouton en haut à droite pour charger les données.

                        Liste des achats de gemmes
                        <button class="btn btn-xs pull-right btn-default" id="credits-purchases-btn-refresh"></button>

Afin d'éviter un chargement trop long, les requêtes ont été bloquées. Veuillez cliquer sur le bouton en haut à droite pour charger les données.


text:
package com.github.xiaofei_dev.gank.ui.fragment;

import android.app.Activity;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.View;
import android.widget.Toast;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.github.xiaofei_dev.gank.R;
import com.github.xiaofei_dev.gank.model.GankSearchResult;
import com.github.xiaofei_dev.gank.model.bean.GankSearchResultBean;
import com.github.xiaofei_dev.gank.presenter.impl.GankSearchPresenterImpl;
import com.github.xiaofei_dev.gank.ui.adapter.SearchResultAdapter;
import com.github.xiaofei_dev.gank.ui.view.RefreshView;
import com.github.xiaofei_dev.gank.ui.view.GankSearchView;
import com.github.xiaofei_dev.gank.ui.view.base.GankBaseView;
import com.github.xiaofei_dev.gank.util.ToastUtils;

import java.util.ArrayList;

import io.reactivex.disposables.CompositeDisposable;

/**
 * Created by Administrator on 2017/4/22.
 */

public final class GankSearchFragment extends GankBaseFragment implements GankSearchView,GankBaseView{

    private int page = 1;
    private static final int PAGE_SIZE = 10;

    private int mCurrentCounter = 0;//当前项目数
    private static final int TOTAL_COUNTER = 10000;//最多项目数
    private boolean isErr = true;

    private ArrayList<GankSearchResultBean> gankList = new ArrayList<>();
    private GankSearchPresenterImpl mGankSearchPresenterImpl;
    private SearchResultAdapter mSearchResultAdapter;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        initSearchResultAdapter();
        mGankSearchPresenterImpl = new GankSearchPresenterImpl(new CompositeDisposable(),this);
        mGankSearchPresenterImpl.subscribeSearch(mCategory,PAGE_SIZE,page++);
    }

    @Override
    public void firstGetDate() {
        page = 1;
        mGankSearchPresenterImpl.subscribeSearch(mCategory,PAGE_SIZE,page++);
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        recyclerView.setAdapter(mSearchResultAdapter);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        mGankSearchPresenterImpl.unsubscribe();
    }

    @Override
    public void setSearchInfo(GankSearchResult gankSearchResult) {
        mSearchResultAdapter.setNewData(gankSearchResult.dataList);
        Activity activity = getActivity();
        if(activity instanceof RefreshView){
            ((RefreshView) activity).hideRefresh();
        }
    }

    @Override
    public void setLoadMoreErr(boolean err) {
        isErr = err;

    }

    @Override
    public void showNetworkError() {
        Activity activity = getActivity();
        if(activity instanceof RefreshView){
            ((RefreshView) activity).hideRefresh();
        }
        if (getUserVisibleHint()) {
            ToastUtils.showShort(R.string.networkfailure);
        }
    }

    @Override
    public void loadMoreGankData(GankSearchResult gankSearchResult) {
        if(gankSearchResult == null){
            //获取更多数据失败
            loadMoreDateFail();
            return;
        }
        if(isErr){
            gankList = gankSearchResult.dataList;
            if(gankList == null){
                //获取更多数据失败
                loadMoreDateFail();
                return;
            }
            //到了数据尾页
            if(gankList.size()<PAGE_SIZE){
                mCurrentCounter = TOTAL_COUNTER;
                mSearchResultAdapter.loadMoreEnd();
            }
            //获取数据成功
            mSearchResultAdapter.addData(gankList);
            mCurrentCounter = mSearchResultAdapter.getData().size();
            mSearchResultAdapter.loadMoreComplete();
        }else {
            //获取更多数据失败
            loadMoreDateFail();
        }
    }

    /**
     * 获取更多数据失败
     */
    @Override
    public void loadMoreDateFail() {
        ToastUtils.showShort(R.string.failure);
        mSearchResultAdapter.loadMoreFail();
    }

    private  void initSearchResultAdapter(){
        mSearchResultAdapter = new SearchResultAdapter(R.layout.item_search,gankList);
        mSearchResultAdapter.openLoadAnimation(BaseQuickAdapter.SCALEIN);
        mSearchResultAdapter.setOnLoadMoreListener(new BaseQuickAdapter.RequestLoadMoreListener() {
            @Override
            public void onLoadMoreRequested() {
                if(mCurrentCounter >= TOTAL_COUNTER){
                    //数据全部加载完毕
                    mSearchResultAdapter.loadMoreEnd();
                }else {
                    mGankSearchPresenterImpl.getMoreData(mCategory,PAGE_SIZE,page++);
                }
            }
        },recyclerView);
        mSearchResultAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                final String url = mSearchResultAdapter.getItem(position).url;
                final String title = mSearchResultAdapter.getItem(position).desc;
                if(getActivity() instanceof ItemClickListener){
                    ((ItemClickListener) getActivity()).onItemClick(url,title);
                }else {
                    return;
                }
            }
        });
    }

    public static GankSearchFragment newInstance(String argument){
        Bundle bundle = new Bundle();
        bundle.putString(ARGUMENT,argument);
        GankSearchFragment gankSearchFragment = new GankSearchFragment();
        gankSearchFragment.setArguments(bundle);
        return  gankSearchFragment;
    }
}


text:
package apple.struct;

import org.moe.natj.c.StructObject;
import org.moe.natj.c.ann.Structure;
import org.moe.natj.c.ann.StructureField;
import org.moe.natj.general.NatJ;
import org.moe.natj.general.Pointer;
import org.moe.natj.general.ann.Generated;

@Generated
@Structure()
public final class in_addr extends StructObject {
    private static long __natjCache;

    static {
        NatJ.register();
    }

    @Generated
    public in_addr() {
        super(in_addr.class);
    }

    @Generated
    protected in_addr(Pointer peer) {
        super(peer);
    }

    @Generated
    public in_addr(int s_addr) {
        super(in_addr.class);
        setS_addr(s_addr);
    }

    @Generated
    @StructureField(order = 0, isGetter = true)
    public native int s_addr();

    @Generated
    @StructureField(order = 0, isGetter = false)
    public native void setS_addr(int value);
}


text:
package uk.co.vurt.hakken.providers;

import android.net.Uri;
import android.provider.BaseColumns;

public class Dataitem {

	private Dataitem(){}

	public final static class Definitions implements BaseColumns {
		private Definitions(){}

		public static final String PATH = "dataitem";

		public static final Uri CONTENT_URI = Uri.parse("content://" + TaskProvider.AUTHORITY + "/" + PATH);

		public static final String CONTENT_TYPE = "vnd.android.cursor.dir/vnd.vurt.hakken.dataitem";

		public static final String CONTENT_ITEM_TYPE = "vnd.android.cursor.item/vnd.vurt.hakken.dataitem";

		public static final String JOB_ID = "jobid";

		public static final String PAGENAME = "pagename";

		public static final String NAME = "name";

		public static final String TYPE = "type";

		public static final String VALUE = "value";

		public static final String DEFAULT_SORT_ORDER = NAME + " ASC";
	}

	public final static class Instance implements BaseColumns {

	}
}


text:
- Change `ActiveRecord::Base#[]=` => `Object::__send__`

## v0.2.0
- To consider the type of the previous type.

## v0.1.2
- rename String#trim => String#trim_white_spaces.


text:
"use strict";
var __extends = (this && this.__extends) || (function () {
    var extendStatics = function (d, b) {
        extendStatics = Object.setPrototypeOf ||
            ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
            function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
        return extendStatics(d, b);
    }
    return function (d, b) {
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();
Object.defineProperty(exports, "__esModule", { value: true });
var Subscriber_1 = require("../Subscriber");
function sequenceEqual(compareTo, comparator) {
    return function (source) { return source.lift(new SequenceEqualOperator(compareTo, comparator)); };
}
exports.sequenceEqual = sequenceEqual;
var SequenceEqualOperator = (function () {
    function SequenceEqualOperator(compareTo, comparator) {
        this.compareTo = compareTo;
        this.comparator = comparator;
    }
    SequenceEqualOperator.prototype.call = function (subscriber, source) {
        return source.subscribe(new SequenceEqualSubscriber(subscriber, this.compareTo, this.comparator));
    };
    return SequenceEqualOperator;
}());
exports.SequenceEqualOperator = SequenceEqualOperator;
var SequenceEqualSubscriber = (function (_super) {
    __extends(SequenceEqualSubscriber, _super);
    function SequenceEqualSubscriber(destination, compareTo, comparator) {
        var _this = _super.call(this, destination) || this;
        _this.compareTo = compareTo;
        _this.comparator = comparator;
        _this._a = [];
        _this._b = [];
        _this._oneComplete = false;
        _this.destination.add(compareTo.subscribe(new SequenceEqualCompareToSubscriber(destination, _this)));
        return _this;
    }
    SequenceEqualSubscriber.prototype._next = function (value) {
        if (this._oneComplete && this._b.length === 0) {
            this.emit(false);
        }
        else {
            this._a.push(value);
            this.checkValues();
        }
    };
    SequenceEqualSubscriber.prototype._complete = function () {
        if (this._oneComplete) {
            this.emit(this._a.length === 0 && this._b.length === 0);
        }
        else {
            this._oneComplete = true;
        }
        this.unsubscribe();
    };
    SequenceEqualSubscriber.prototype.checkValues = function () {
        var _c = this, _a = _c._a, _b = _c._b, comparator = _c.comparator;
        while (_a.length > 0 && _b.length > 0) {
            var a = _a.shift();
            var b = _b.shift();
            var areEqual = false;
            try {
                areEqual = comparator ? comparator(a, b) : a === b;
            }
            catch (e) {
                this.destination.error(e);
            }
            if (!areEqual) {
                this.emit(false);
            }
        }
    };
    SequenceEqualSubscriber.prototype.emit = function (value) {
        var destination = this.destination;
        destination.next(value);
        destination.complete();
    };
    SequenceEqualSubscriber.prototype.nextB = function (value) {
        if (this._oneComplete && this._a.length === 0) {
            this.emit(false);
        }
        else {
            this._b.push(value);
            this.checkValues();
        }
    };
    SequenceEqualSubscriber.prototype.completeB = function () {
        if (this._oneComplete) {
            this.emit(this._a.length === 0 && this._b.length === 0);
        }
        else {
            this._oneComplete = true;
        }
    };
    return SequenceEqualSubscriber;
}(Subscriber_1.Subscriber));
exports.SequenceEqualSubscriber = SequenceEqualSubscriber;
var SequenceEqualCompareToSubscriber = (function (_super) {
    __extends(SequenceEqualCompareToSubscriber, _super);
    function SequenceEqualCompareToSubscriber(destination, parent) {
        var _this = _super.call(this, destination) || this;
        _this.parent = parent;
        return _this;
    }
    SequenceEqualCompareToSubscriber.prototype._next = function (value) {
        this.parent.nextB(value);
    };
    SequenceEqualCompareToSubscriber.prototype._error = function (err) {
        this.parent.error(err);
        this.unsubscribe();
    };
    SequenceEqualCompareToSubscriber.prototype._complete = function () {
        this.parent.completeB();
        this.unsubscribe();
    };
    return SequenceEqualCompareToSubscriber;
}(Subscriber_1.Subscriber));
//# sourceMappingURL=sequenceEqual.js.map


text:
package org.csc.phynixx.spring.jta;

import org.csc.phynixx.common.exceptions.DelegatedRuntimeException;
import org.springframework.jdbc.datasource.ConnectionProxy;
import org.springframework.jdbc.datasource.DataSourceUtils;
import org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy;
import org.springframework.transaction.support.TransactionSynchronizationManager;
import org.springframework.util.Assert;
import org.springframework.util.ReflectionUtils;

import javax.sql.DataSource;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;

/**
 * Created by christoph on 14.12.2014.
 */
public class TransactionAwareXAResource<C> {

	ReflectionUtils reflectionUtils;

    Object targetConnectionFactory =null;

    Class<C>  connectionType;

    /**
     * Create a new TransactionAwareDataSourceProxy.
     */
    public TransactionAwareXAResource() {
    }

    /**
     * Create a new TransactionAwareDataSourceProxy.
     * @param connectionFactory wrapped physical connection
     */
    public TransactionAwareXAResource(Object connectionFactory) {
      this.targetConnectionFactory=connectionFactory;
    }

    public Object getTargetConnectionFactory() {
        return targetConnectionFactory;
    }

    public void setTargetConnectionFactory(Object targetConnectionFactory, Class<C> connectionType) {
        this.targetConnectionFactory = targetConnectionFactory;
        this.connectionType=connectionType;
    }

    public Class<?> getConnectionType() {
        return connectionType;
    }

    public void setConnectionType(Class<C> connectionType) {
        this.connectionType = connectionType;
    }

    /**
     * Delegates to DataSourceUtils for automatically participating in Spring-managed
     * transactions. Throws the original SQLException, if any.
     *
The returned Connection handle implements the ConnectionProxy interface,
     * allowing to retrieve the underlying target Connection.
     * @return a transactional Connection if any, a new one else
     * @see org.springframework.jdbc.datasource.DataSourceUtils#doGetConnection
     * @see org.springframework.jdbc.datasource.ConnectionProxy#getTargetConnection
     */
//    @Override
//    public C getConnection()  {
//        Object ds = getTargetConnectionFactory();
//        Assert.state(ds != null, "'targetDataSource' is required");
//        return getTransactionAwareConnectionProxy(ds);
//    }
//
//    /**
//     * Wraps the given Connection with a proxy that delegates every method call to it
//     * but delegates {@code close()} calls to DataSourceUtils.
//     * @param targetDataSource DataSource that the Connection came from
//     * @return the wrapped Connection
//     * @see java.sql.Connection#close()
//     * @see org.springframework.jdbc.datasource.DataSourceUtils#doReleaseConnection
//     */
//    protected C getTransactionAwareConnectionProxy(Object targetDataSource, Class<C> connectionType) {
//        return (Connection) Proxy.newProxyInstance(
//                ConnectionProxy.class.getClassLoader(),
//                new Class[]{ConnectionProxy.class, IObject.class, IConnectionDelegate.class},
//                new TransactionAwareInvocationHandler(targetDataSource,connectionType));
//    }
//
//    /**
//     * Determine whether to obtain a fixed target Connection for the proxy
//     * or to reobtain the target Connection for each operation.
//     *
The default implementation returns {@code true} for all
//     * standard cases. This can be overridden through the
//     * {@link #setReobtainTransactionalConnections "reobtainTransactionalConnections"}
//     * flag, which enforces a non-fixed target Connection within an active transaction.
//     * Note that non-transactional access will always use a fixed Connection.
//     * @param targetDataSource the target DataSource
//     */
//    protected boolean shouldObtainFixedConnection(DataSource targetDataSource) {
//        return (!TransactionSynchronizationManager.isSynchronizationActive() ||
//                !this.reobtainTransactionalConnections);
//    }
//
//
//    /**
//     * Invocation handler that delegates close calls on JDBC Connections
//     * to DataSourceUtils for being aware of thread-bound transactions.
//     */
//    private class TransactionAwareInvocationHandler<CC> implements InvocationHandler {
//
//
//        Object targetConnectionFactory =null;
//
//        Class<CC>  connectionType;
//
//
//        private CC target;
//
//        private boolean closed = false;
//
//        public TransactionAwareInvocationHandler(DataSource targetDataSource, Class<CC> connectionType) {
//            this.targetConnectionFactory = targetConnectionFactory;
//            this.connectionType=connectionType;
//        }
//
//        private boolean ismplementedBy(Method method, Class<?> iface) {
//            try {
//                return iface.getDeclaredMethod(method.getName(), method.getParameterTypes()) != null;
//            } catch (NoSuchMethodException e) {
//                return false;
//            }
//        }
//
//        public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
//            // Invocation on ConnectionProxy interface coming in...
//
//            if (method.getName().equals("equals")) {
//                // Only considered as equal when proxies are identical.
//                return (proxy == args[0]);
//            }
//            else if (method.getName().equals("hashCode")) {
//                // Use hashCode of Connection proxy.
//                return System.identityHashCode(proxy);
//            }
//            else if (method.getName().equals("toString")) {
//                // Allow for differentiating between the proxy and the raw Connection.
//                StringBuilder sb = new StringBuilder("Transaction-aware proxy for target Connection ");
//                if (this.target != null) {
//                    sb.append("[").append(this.target.toString()).append("]");
//                }
//                else {
//                    sb.append(" from DataSource [").append(this.targetDataSource).append("]");
//                }
//                return sb.toString();
//            }
//           else if (method.getName().equals("close")) {
//                // Handle close method: only close if not within a transaction.
//                DataSourceUtils.doReleaseConnection(this.target, this.targetDataSource);
//                this.closed = true;
//                return null;
//            }
//            else if (method.getName().equals("isClosed")) {
//                return this.closed;
//            }
//
//            if (this.target == null) {
//                if (this.closed) {
//                    throw new DelegatedRuntimeException()n("Connection handle already closed");
//                }
//                this.target = DataSourceUtils.doGetConnection(this.targetDataSource);
//                            }
//            Connection actualTarget = this.target;
//            if (actualTarget == null) {
//                actualTarget = DataSourceUtils.doGetConnection(this.targetDataSource);
//            }
//
//            if (method.getName().equals("getTargetConnection")) {
//                // Handle getTargetConnection method: return underlying Connection.
//                return actualTarget;
//            }
//
//            // Invoke method on target Connection.
//            try {
//                Object retVal = method.invoke(actualTarget, args);
//
//                // If return value is a Statement, apply transaction timeout.
//                // Applies to createStatement, prepareStatement, prepareCall.
//                if (retVal instanceof Statement) {
//                    DataSourceUtils.applyTransactionTimeout((Statement) retVal, this.targetDataSource);
//                }
//
//                return retVal;
//            }
//            catch (InvocationTargetException ex) {
//                throw ex.getTargetException();
//            }
//            finally {
//                if (actualTarget != this.target) {
//                    DataSourceUtils.doReleaseConnection(actualTarget, this.targetDataSource);
//                }
//            }
//        }
//    }
}


text:
PolyMainWindow::PolyMainWindow()
	: PolyWindow()
{
	setWindowTitle("PolyEditor");
	resize(1280, 720);;

	// menu bar
	MenuBar = std::make_unique<QMenuBar>();
	setMenuBar(MenuBar.get());

		// file menu
		FileMenu = std::make_unique<QMenu>();
		MenuBar->addAction(FileMenu->menuAction());
		FileMenu->setTitle("File");

			QuitAction = std::make_unique<QAction>();
			FileMenu->addAction(QuitAction.get());
			QuitAction->setText("Quit");
			connect(QuitAction.get(), &QAction::triggered, this, &PolyMainWindow::Quit);

		// view menu
		ViewMenu = std::make_unique<QMenu>();
		MenuBar->addAction(ViewMenu->menuAction());
		ViewMenu->setTitle("View");

			AddWindowAction = std::make_unique<QAction>();
			ViewMenu->addAction(AddWindowAction.get());
			AddWindowAction->setText("Add Window");
			connect(AddWindowAction.get(), &QAction::triggered, this, &PolyMainWindow::AddWindow);

		// Project menu
		ProjectMenu = std::make_unique<QMenu>();
		MenuBar->addAction(ProjectMenu->menuAction());
		ProjectMenu->setTitle("Project");

			EditProjectAction = std::make_unique<QAction>();
			ProjectMenu->addAction(EditProjectAction.get());
			EditProjectAction->setText("Edit");
			connect(EditProjectAction.get(), &QAction::triggered, this, &PolyMainWindow::EditProject);

			PlayProjectAction = std::make_unique<QAction>();
			ProjectMenu->addAction(PlayProjectAction.get());
			PlayProjectAction->setText("Play");
			connect(PlayProjectAction.get(), &QAction::triggered, this, &PolyMainWindow::PlayProject);
}

void PolyMainWindow::Quit()
{
	close();
}

void PolyMainWindow::Undo()
{
}

void PolyMainWindow::Redo()
{
}

void PolyMainWindow::AddWindow()
{
	gApp->Ui.AddWindow();
}

void PolyMainWindow::EditProject()
{
	gApp->ProjectMgr->Edit();
}

void PolyMainWindow::PlayProject()
{
	gApp->ProjectMgr->Play();
}

void PolyMainWindow::ContactUs()
{
}

void PolyMainWindow::closeEvent(QCloseEvent* event)
{
	if (gApp->ProjectMgr->IsOpened())
	{
		QMessageBox::StandardButton resBtn = QMessageBox::question(this, "PolyEditor",
			tr("Do you want to save your changes before closing?\n"),
			QMessageBox::Cancel | QMessageBox::No | QMessageBox::Yes,
			QMessageBox::Yes);

		if (resBtn == QMessageBox::Yes)
		{
			event->accept();
		}
		else if (resBtn == QMessageBox::No)
		{
			event->accept();
		}
		else
			event->ignore();

	}
	else
	{
		QMessageBox::StandardButton resBtn = QMessageBox::question(this, "PolyEditor",
			tr("Do you really want to exit?\n"),
			QMessageBox::No | QMessageBox::Yes,
			QMessageBox::Yes);

		if (resBtn != QMessageBox::Yes)
			event->ignore();
		else
			event->accept();
	}
}


text:
package org.ubercraft.sucre.attributes;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertSame;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import org.junit.Test;
import org.ubercraft.sucre.coercer.CoercerException;

public class AttributesTest {

    private static interface TestMe {

        String getHello();

        String getNumber();

        @AttributeKey("my.key")
        String getSomeString();

        @AttributeDefaultInt(42)
        int getTheAnswer();

        void setTheAnswer(int answer);

        long getNotFussy();

        void setNotFussy(String string);
    }

    @Test
    public void testMe() {
        // start with a map
        Map<Object, Object> values = new HashMap<Object, Object>();
        values.put("hello", "World");
        values.put("number", 12345);
        values.put("my.key", "my.value");
        values.put("notFussy", (byte)3);

        // test me
        TestMe me = Attributes.backedBy(values).proxy(TestMe.class);

        // hello world
        assertEquals("World", me.getHello());

        // coerce int to String
        assertEquals("12345", me.getNumber());

        // use a non-default key
        assertEquals("my.value", me.getSomeString());

        // use a default value
        assertEquals(42, me.getTheAnswer());

        // modify a value
        me.setTheAnswer(101);
        assertEquals(101, me.getTheAnswer());

        // not fussy
        assertEquals(3L, me.getNotFussy());

        // still not
        me.setNotFussy("4");
        assertEquals(4L, me.getNotFussy());
    }

    private static enum TestEnum {
        ABC,
        XYZ
    }

    private static interface TestAPI {

        String getString();

        void setString(String value);

        boolean getBoolean();

        void setBoolean(boolean value);

        int getInt();

        void setInt(int value);

        double getDouble();

        void setDouble(double value);

        long getLong();

        void setLong(long value);

        @AttributeKey("string.key")
        String getReadOnlyString();

        TestEnum getEnum();

        void setEnum(TestEnum value);
    }

    @Test
    public void testAttributesProxy() throws Exception {
        Attributes attr = new Attributes();
        TestAPI test = attr.proxy(TestAPI.class);
        assertEquals(null, test.getString());
        assertEquals(false, test.getBoolean());
        assertEquals(0, test.getInt());
        assertEquals(0.0D, test.getDouble(), 0.0D);
        assertEquals(0L, test.getLong());
        assertEquals(null, test.getReadOnlyString());
        assertEquals(null, test.getEnum());
        test.setString("x");
        test.setBoolean(true);
        test.setInt(7);
        test.setDouble(7.7D);
        test.setLong(7L);
        test.setEnum(TestEnum.ABC);
        Map<Object, Object> values = new HashMap<Object, Object>();
        values.put("string.key", "hello");
        attr.addAll(values);
        assertEquals("x", test.getString());
        assertEquals(true, test.getBoolean());
        assertEquals(7, test.getInt());
        assertEquals(7.7D, test.getDouble(), 0.0D);
        assertEquals(7L, test.getLong());
        assertEquals("hello", test.getReadOnlyString());
        assertEquals(TestEnum.ABC, test.getEnum());
    }

    private static interface TestAPIWithDefaults {

        @AttributeDefaultString("x")
        String getString();

        void setString(String value);

        @AttributeDefaultBoolean(true)
        boolean getBoolean();

        void setBoolean(boolean value);

        @AttributeDefaultInt(7)
        int getInt();

        void setInt(int value);

        @AttributeDefaultDouble(7.7D)
        double getDouble();

        void setDouble(double value);

        @AttributeDefaultLong(7L)
        long getLong();

        void setLong(long value);

        @AttributeKey("string.key")
        @AttributeDefaultString("y")
        String getReadOnlyString();

        @AttributeDefaultString("XYZ")
        TestEnum getEnum();

        @AttributeDefaultClass(java.util.List.class)
        Class<?> getType();

        void setType(Class<?> type);

        @AttributeDefaultString("java.util.Set")
        Class<?> getReadOnlyType();
    }

    @Test
    public void testAttributesProxyWithDefaults() throws Exception {
        Attributes attr = new Attributes();
        TestAPIWithDefaults test = attr.proxy(TestAPIWithDefaults.class);
        assertEquals("x", test.getString());
        assertEquals(true, test.getBoolean());
        assertEquals(7, test.getInt());
        assertEquals(7.7D, test.getDouble(), 0.0D);
        assertEquals(7L, test.getLong());
        assertEquals("y", test.getReadOnlyString());
        assertEquals(TestEnum.XYZ, test.getEnum());
        assertSame(java.util.List.class, test.getType());
        assertSame(java.util.Set.class, test.getReadOnlyType());
        test.setString(null);
        test.setBoolean(false);
        test.setInt(0);
        test.setDouble(0.0D);
        test.setLong(0L);
        test.setType(java.util.Map.class);
        Map<Object, Object> values = new HashMap<Object, Object>();
        values.put("string.key", "world");
        attr.addAll(values);
        assertEquals(null, test.getString());
        assertEquals(false, test.getBoolean());
        assertEquals(0, test.getInt());
        assertEquals(0.0D, test.getDouble(), 0.0D);
        assertEquals(0L, test.getLong());
        assertEquals("world", test.getReadOnlyString());
        assertSame(java.util.Map.class, test.getType());
    }

    private static interface TestBigAPI {

        Boolean getBoolean();

        void setBoolean(Boolean value);

        Integer getInt();

        void setInt(Integer value);

        Double getDouble();

        void setDouble(Double value);
    }

    @Test
    public void testBigAttributesProxy() throws Exception {
        Attributes attr = new Attributes();
        TestBigAPI test = attr.proxy(TestBigAPI.class);
        assertEquals(null, test.getBoolean());
        assertEquals(null, test.getInt());
        assertEquals(null, test.getDouble());
        test.setBoolean(true);
        test.setInt(7);
        test.setDouble(7.7D);
        assertEquals(true, test.getBoolean());
        assertEquals(new Integer(7), test.getInt());
        assertEquals(new Double(7.7D), test.getDouble(), 0.0D);
    }

    private static interface TestBigAPIWithDefaults {

        @AttributeDefaultBoolean(true)
        Boolean getBoolean();

        void setBoolean(Boolean value);

        @AttributeDefaultInt(7)
        Integer getInt();

        void setInt(Integer value);

        @AttributeDefaultDouble(7.7D)
        Double getDouble();

        void setDouble(Double value);
    }

    @Test
    public void testBigAttributesProxyWithDefaults() throws Exception {
        Attributes attr = new Attributes();
        TestBigAPIWithDefaults test = attr.proxy(TestBigAPIWithDefaults.class);
        assertEquals(true, test.getBoolean());
        assertEquals(new Integer(7), test.getInt());
        assertEquals(new Double(7.7D), test.getDouble(), 0.0D);
        test.setBoolean(null);
        test.setInt(null);
        test.setDouble(null);
        assertEquals(null, test.getBoolean());
        assertEquals(null, test.getInt());
        assertEquals(null, test.getDouble());
    }

    private static interface TestAutoCoerceAPI {

        @AttributeKey("int.key")
        int getInt();

        @AttributeKey("double.key")
        double getDouble();

        @AttributeKey("bool.key")
        boolean getBoolean();
    }

    @Test
    public void testProxyAutoCoerce() throws Exception {
        Map<String, String> values = new HashMap<String, String>();
        values.put("int.key", "5");
        values.put("double.key", "6.3");
        values.put("bool.key", "true");
        Attributes attr = new Attributes(values);
        TestAutoCoerceAPI test = attr.proxy(TestAutoCoerceAPI.class);
        assertEquals(new Integer(5), new Integer(test.getInt()));
        assertEquals(new Double(6.3D), new Double(test.getDouble()));
        assertEquals(new Boolean(true), test.getBoolean());
    }

    private static interface TestBigAutoCoerceAPI {

        @AttributeKey("int.key")
        Integer getInt();

        @AttributeKey("double.key")
        Double getDouble();

        @AttributeKey("bool.key")
        Boolean getBoolean();
    }

    @Test
    public void testBigProxyAutoCoerce() throws Exception {
        Map<String, String> values = new HashMap<String, String>();
        values.put("int.key", "5");
        values.put("double.key", "6.3");
        values.put("bool.key", "true");
        Attributes attr = new Attributes(values);
        TestBigAutoCoerceAPI test = attr.proxy(TestBigAutoCoerceAPI.class);
        assertEquals(new Integer(5), new Integer(test.getInt()));
        assertEquals(new Double(6.3D), new Double(test.getDouble()));
        assertEquals(new Boolean(true), test.getBoolean());
    }

    public static interface TestSuperInterface {

        @AttributeKey("int.key")
        int getInt();
    }

    public static interface TestSubInterface extends TestSuperInterface {

    }

    @Test
    public void testProxySubInterface() throws Exception {
        Map<String, String> values = new HashMap<String, String>();
        values.put("int.key", "5");
        Attributes attr = new Attributes(values);
        TestSuperInterface test = attr.proxy(TestSubInterface.class);
        assertEquals(5, test.getInt());
    }

    public static interface TestDateInterface {

        @AttributeDateFormats({
                "yyyy/MM/dd", "yyyy MMM dd"
        })
        @AttributeDateTimeZone("DEFAULT")
        Date getDate();

        Date setDate(Date date);
    }

    @Test
    public void testDateFormats() throws Exception {
        Map<String, String> values = new HashMap<String, String>();
        Attributes attr = Attributes.backedBy(values);
        TestDateInterface test = attr.proxy(TestDateInterface.class);
        assertEquals(null, test.getDate());
        String dateString = "2011/06/12";
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd");
        Date date = dateFormat.parse(dateString);
        values.put("date", dateString);
        assertEquals(date, test.getDate());
        dateString = "2011 Jun 12";
        dateFormat = new SimpleDateFormat("yyyy MMM dd");
        date = dateFormat.parse(dateString);
        values.put("date", dateString);
        assertEquals(date, test.getDate());
        values.put("date", "lkjsdf");
        assertEquals(null, test.getDate());
    }

    public static interface TestStrictInterface {

        @AttributeDateFormats({
            "yyyy MMM dd"
        })
        @AttributeCoerceStrict
        Date getStrictDate();
    }

    @Test(expected = CoercerException.class)
    public void testStrictDateFormats() throws Exception {
        Map<String, String> values = new HashMap<String, String>();
        Attributes attr = Attributes.backedBy(values);
        TestStrictInterface test = attr.proxy(TestStrictInterface.class);
        values.put("strictDate", "lkjsdf");
        test.getStrictDate();
    }
}


text:
DruggableGene::Application.routes.draw do
  get 'interactions/:id' => 'interactions#show', constraints: { name: /[^\/]+/ }
  get 'gene_claims/:source_db_name/:name' => 'gene_claims#show'
  get 'drug_claims/:source_db_name/:name' => 'drug_claims#show'
  get 'gene_names' => 'genes#names'
  # add a drug_names thing here, so that they can be pulled via json?
  get 'drug_names' => 'drugs#names'
  get 'genes/:name' => 'genes#show', as: 'gene'
  get 'interaction_claims/:id' => 'interaction_claims#show', as: 'interaction_claims'
  get 'druggable_gene_categories/:name' => 'genes#druggable_gene_category', as: 'gene_by_category'
  get 'druggable_gene_categories' => 'genes#druggable_gene_categories'
  get 'drugs/:name' => 'drugs#show', as: 'drug', name: /.*/
  get 'sources/:source_db_name' => 'sources#show', as: 'source'
  get 'sources' => 'sources#sources'
  get 'search_results' => 'search#search_results'
  get 'cache/invalidate' => 'utilities#invalidate_cache'
  get 'downloads' => 'downloads#show'
  get 'interaction_types' => 'interaction_types#show'
  post  'download_table' => 'utilities#download_request_content'
  scope 'api' do
    scope 'v1' do
      post  'interactions' => 'services_v1#interactions'
      post  'related_genes' => 'services_v1#related_genes'
      get 'gene_categories' => 'services_v1#gene_categories'
      get 'drug_types' => 'services_v1#drug_types'
      get 'interaction_types' => 'services_v1#interaction_types'
      get 'interaction_sources' => 'services_v1#interaction_sources'
      get 'source_trust_levels' => 'services_v1#source_trust_levels'
      get 'gene_categories_for_sources' => 'services_v1#gene_categories_for_sources'
      get 'genes_in_category' => 'services_v1#genes_in_category'
      get 'related_genes' => 'services_v1#related_genes'
      get 'interactions' => 'services_v1#interactions'
      get 'gene_id_mapping' => 'services_v1#gene_id_mapping'
    end
    scope 'v2' do
      post  'interactions' => 'services_v2#interactions'
      post  'related_genes' => 'services_v2#related_genes'
      get 'genes' => 'services_v2#genes'
      get 'drugs' => 'services_v2#drugs'
      get 'interactions' => 'services_v2#interactions'
      get 'related_genes' => 'services_v2#related_genes'
      get 'gene_id_mapping' => 'services_v2#gene_id_mapping'
      get 'gene_categories' => 'services_v2#gene_categories'
      get 'interaction_types' => 'services_v2#interaction_types'
      get 'interaction_sources' => 'services_v2#interaction_sources'
      get 'source_trust_levels' => 'services_v2#source_trust_levels'
      get 'gene_categories_for_sources' => 'services_v2#gene_categories_for_sources'
      get 'genes_in_category' => 'services_v2#genes_in_category'
      get   'genes/:entrez_id' => 'services_v2#gene_details'
      get   'drugs/:concept_id' => 'services_v2#drug_details'
      get   'interactions/:id' => 'services_v2#interaction_details'
    end
    require 'sidekiq/web'
    require 'sidekiq/cron/web'
    mount Sidekiq::Web, at: '/jobs'
  end
  match 'interaction_search_results/:name' => 'interaction_claims#interaction_search_results', name: /.*[^#]/, via: [:get, :post]
  match 'interaction_search_results' => 'interaction_claims#interaction_search_results', via: [:get, :post]
  match 'interactions_for_related_genes' => 'interaction_claims#interactions_for_related_genes', via: [:get, :post]
  match 'categories_search_results' => 'genes#categories_search_results', via: [:get, :post]
  get 'home' => 'static#home'
  get 'search_categories' => 'static#search_categories'
  get 'search_interactions' => 'static#search_interactions'
  get 'news' => 'static#news'
  get 'api' => 'static#api'
  get 'api_v1' => 'static#api_v1'
  get 'contact' => 'static#contact'
  get 'downloads' => 'static#downloads'
  get 'faq' => 'static#faq'
  get 'getting_started' => 'static#getting_started'
  get 'search' => 'static#search'
  get 'statistics' => 'static#statistics'
  get 'about' => 'static#about'
  get 'publications' => 'static#publications'
  get 'data_clients' => 'static#data_clients'
  get 'score' => 'static#score'
  root :to => 'static#home'
end


text:
package org.springframework.test.context.support;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import org.springframework.beans.factory.support.BeanDefinitionReader;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.AnnotationConfigUtils;
import org.springframework.context.support.GenericApplicationContext;
import org.springframework.util.StringUtils;

/**
 *

 * Abstract, generic extension of {@link AbstractContextLoader} which loads a
 * {@link GenericApplicationContext} from the locations provided to
 * {@link #loadContext(String...)}.
 *

 *

 * Concrete subclasses must provide an appropriate
 * {@link #createBeanDefinitionReader(GenericApplicationContext) BeanDefinitionReader}.
 *

 *
 * @author Sam Brannen
 * @since 2.5
 * @see #loadContext(String...)
 */
public abstract class AbstractGenericContextLoader extends AbstractContextLoader {

	protected static final Log logger = LogFactory.getLog(AbstractGenericContextLoader.class);

	/**
	 *

	 * Loads a Spring ApplicationContext from the supplied
	 * locations.
	 *

	 *

	 * Implementation details:
	 *

	 *

	 *
Creates a standard {@link GenericApplicationContext} instance.

	 *
Populates it from the specified config locations through a
	 * {@link #createBeanDefinitionReader(GenericApplicationContext) BeanDefinitionReader}.

	 *
Calls {@link #customizeBeanFactory(DefaultListableBeanFactory)} to
	 * allow for customizing the context's DefaultListableBeanFactory.

	 *
Delegates to {@link AnnotationConfigUtils} for
	 * {@link AnnotationConfigUtils#registerAnnotationConfigProcessors(org.springframework.beans.factory.support.BeanDefinitionRegistry) registering}
	 * annotation configuration processors.

	 *
Calls {@link #customizeContext(GenericApplicationContext)} to allow
	 * for customizing the context before it is refreshed.

	 *
{@link ConfigurableApplicationContext#refresh() Refreshes} the
	 * context and registers a JVM shutdown hook for it.

	 *

	 *

	 *

	 * Subclasses must provide an appropriate implementation of
	 * {@link #createBeanDefinitionReader(GenericApplicationContext)}.
	 *

	 *
	 * @return a new application context
	 * @see org.springframework.test.context.ContextLoader#loadContext
	 * @see GenericApplicationContext
	 * @see #customizeBeanFactory(DefaultListableBeanFactory)
	 * @see #createBeanDefinitionReader(GenericApplicationContext)
	 * @see BeanDefinitionReader
	 */
	public final ConfigurableApplicationContext loadContext(final String... locations) throws Exception {

		if (logger.isDebugEnabled()) {
			logger.debug("Loading ApplicationContext for locations ["
					+ StringUtils.arrayToCommaDelimitedString(locations) + "].");
		}

		final GenericApplicationContext context = new GenericApplicationContext();
		customizeBeanFactory(context.getDefaultListableBeanFactory());
		createBeanDefinitionReader(context).loadBeanDefinitions(locations);
		AnnotationConfigUtils.registerAnnotationConfigProcessors(context);
		customizeContext(context);
		context.refresh();
		context.registerShutdownHook();
		return context;
	}

	/**
	 *

	 * Customize the internal bean factory of the ApplicationContext created by
	 * this ContextLoader.
	 *

	 *

	 * The default implementation is empty but can be overridden in subclasses
	 * to customize DefaultListableBeanFactory's standard settings.
	 *

	 *
	 * @param beanFactory the bean factory created by this ContextLoader
	 * @see #loadContext(String...)
	 * @see org.springframework.beans.factory.support.DefaultListableBeanFactory#setAllowBeanDefinitionOverriding(boolean)
	 * @see org.springframework.beans.factory.support.DefaultListableBeanFactory#setAllowEagerClassLoading(boolean)
	 * @see org.springframework.beans.factory.support.DefaultListableBeanFactory#setAllowCircularReferences(boolean)
	 * @see org.springframework.beans.factory.support.DefaultListableBeanFactory#setAllowRawInjectionDespiteWrapping(boolean)
	 */
	protected void customizeBeanFactory(final DefaultListableBeanFactory beanFactory) {
		/* no-op */
	}

	/**
	 * Factory method for creating new {@link BeanDefinitionReader}s for
	 * loading bean definitions into the supplied
	 * {@link GenericApplicationContext context}.
	 *
	 * @param context The context for which the BeanDefinitionReader should be
	 *        created.
	 * @return A BeanDefinitionReader for the supplied context.
	 * @see #loadContext(String...)
	 * @see BeanDefinitionReader
	 */
	protected abstract BeanDefinitionReader createBeanDefinitionReader(final GenericApplicationContext context);

	/**
	 *

	 * Customize the {@link GenericApplicationContext} created by this
	 * ContextLoader after bean definitions have been loaded into the context
	 * but before the context is refreshed.
	 *

	 *

	 * The default implementation is empty but can be overridden in subclasses
	 * to customize the application context.
	 *

	 *
	 * @param context the newly created application context
	 * @see #loadContext(String...)
	 */
	protected void customizeContext(final GenericApplicationContext context) {
		/* no-op */
	}

}


text: require "priority_queue/CPriorityQueue"