text:
/**
 *
 */
package com.qshuttle.passenger;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

/**
 * @author wangpeifeng
 *
 */
public class ListAdapterInstanceSelect extends BaseAdapter{

	/////////////////////////////////////////////////
    // PROPERTIES, PRIVATE
    /////////////////////////////////////////////////

	private Context context;
	private JSONArray arrayItems;

	/**
	 * @param context
	 * @param arrayItems
	 * @param selectedItem
	 */
	public ListAdapterInstanceSelect(Context context, JSONArray arrayItems) {
		super();
		this.context = context;
		this.arrayItems = arrayItems;
	}

	/* (non-Javadoc)
	 * @see android.widget.Adapter#getCount()
	 */
	public int getCount() {
		// TODO Auto-generated method stub
		return arrayItems.length();
	}

	/* (non-Javadoc)
	 * @see android.widget.Adapter#getItem(int)
	 */
	public Object getItem(int position) {
		// TODO Auto-generated method stub
		try {
			return arrayItems.get(position);
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return null;
		}
	}

	/* (non-Javadoc)
	 * @see android.widget.Adapter#getItemId(int)
	 */
	public long getItemId(int position) {
		// TODO Auto-generated method stub
		try {
			JSONObject item = (JSONObject) arrayItems.get(position);
			return ((long)(item.getInt(WebApi.API_RESP_INSTANCE_SERIAL)));
		}
		catch(JSONException e){
			return -1;
		}
	}

	public String getItemDeparture(int position) {
		// TODO Auto-generated method stub
		try {
			JSONObject item = (JSONObject) arrayItems.get(position);
			String time = item.getString(WebApi.API_RESP_TIME_DEPARTURE);
			return time.substring(0, "HH:MM".length());

		}
		catch(JSONException e){
			e.printStackTrace();
			return "";
		}
	}

	public String getItemArrive(int position) {
		// TODO Auto-generated method stub
		try {
			JSONObject item = (JSONObject) arrayItems.get(position);
			String time =  item.getString(WebApi.API_RESP_TIME_ARRIVE);
			return time.substring(0, "HH:MM".length());
		}
		catch(JSONException e){
			e.printStackTrace();
			return "";
		}
	}

	public int getItemPrice(int position) {
		// TODO Auto-generated method stub
		try {
			JSONObject item = (JSONObject) arrayItems.get(position);
			return item.getInt(WebApi.API_RESP_PRICE);
		}
		catch(JSONException e){
			e.printStackTrace();
			return 0;
		}
	}

	public int getItemTickets(int position) {
		// TODO Auto-generated method stub
		try {
			JSONObject item = (JSONObject) arrayItems.get(position);
			return item.getInt(WebApi.API_RESP_TICKETS);
		}
		catch(JSONException e){
			e.printStackTrace();
			return 0;
		}
	}

	/* (non-Javadoc)
	 * @see android.widget.Adapter#getView(int, android.view.View, android.view.ViewGroup)
	 */
	public View getView(int position, View convertView, ViewGroup parent) {
		// TODO Auto-generated method stub

		try{

			convertView = LayoutInflater.from(context).inflate(R.layout.listitem_instance, null);

			((TextView)(convertView.findViewById(R.id.textViewTimeDeparture))).setText(getItemDeparture(position));
			((TextView)(convertView.findViewById(R.id.textViewTimeArrive))).setText(getItemArrive(position));
			((TextView)(convertView.findViewById(R.id.textViewPrice))).setText(""+getItemPrice(position));
			((TextView)(convertView.findViewById(R.id.textViewTickets))).setText(""+getItemTickets(position));

			return convertView;
		}
		catch(Exception e){
			e.printStackTrace();
			return null;
		}

	}

}


text:
export * from './payments'
export * from './settings'

redpajama_set_name: RedPajamaGithub


text:
import * as globBase from "glob-base";

const result = globBase("**/*.ts");

const isGlob = result.isGlob;
const glob = result.glob;
const base = result.base;


text:
<?php

namespace SetBased\Abc\Core\TableAction\Babel;

use SetBased\Abc\Core\Page\Babel\WordTranslateWordsPage;
use SetBased\Abc\Core\TableAction\TableAction;
use SetBased\Abc\Helper\Html;

/**
 * Table action action for translation all words in a word group.
 */
class WordTranslateWordsTableAction implements TableAction
{
  //--------------------------------------------------------------------------------------------------------------------
  /**
   * The title of the icon of the table action.
   *
   * @var string
   */
  protected $title;

  /**
   * The URL of the table action.
   *
   * @var string
   */
  protected $url;

  //--------------------------------------------------------------------------------------------------------------------
  /**
   * Object constructor.
   *
   * @param int $wdgId       The ID of the word group of the new word.
   * @param int $targetLanId The ID of the target language.
   */
  public function __construct(int $wdgId, int $targetLanId)
  {
    $this->url = WordTranslateWordsPage::getUrl($wdgId, $targetLanId);

    $this->title = 'Translate words';
  }

  //--------------------------------------------------------------------------------------------------------------------
  /**
   * @inheritdoc
   */
  public function getHtml(): string
  {
    $ret = '<a';
    $ret .= Html::generateAttribute('href', $this->url);
    $ret .= '><img';
    $ret .= Html::generateAttribute('title', $this->title);
    $ret .= Html::generateAttribute('src', ICON_BABEL_FISH);
    $ret .= ' width="16" height="16" alt="translate"/></a>';

    return $ret;
  }

  //--------------------------------------------------------------------------------------------------------------------
}

//----------------------------------------------------------------------------------------------------------------------


text:
#region AOT_ONLY_DEFINE
#define AOT_ONLY
#if (UNITY_EDITOR || UNITY_STANDALONE || UNITY_ANDROID) && !ENABLE_IL2CPP
#undef AOT_ONLY
#endif
#endregion

#if !AOT_ONLY

using System;

namespace Expanse.Utilities
{
    /// <summary>
    /// Helper utility class that caches emitted constructor and casting delegates.
    /// </summary>
    /// <typeparam name="TTarget">Target type.</typeparam>
    public static class EmitHelper<TTarget>
    {
        /// <summary>
        /// Creates a new instance of <see cref="TTarget"/> using an emitted default constructor delegate.
        /// </summary>
        /// <typeparam name="TSource">Non-abstract type of <see cref="TTarget"/> to create an instance of.</typeparam>
        /// <returns>Returns an new instance of <see cref="TSource"/></returns>
        public static TSource CreateInstance<TSource>()
            where TSource : TTarget, new()
        {
            return ConstructorCache<TSource>.constructor();
        }

        /// <summary>
        /// Casts <see cref="TSource"/> to <see cref="TTarget"/>.
        /// This does not cause boxing for value types making it useful in generic methods.
        /// </summary>
        /// <see cref="https://stackoverflow.com/questions/1189144/c-sharp-non-boxing-conversion-of-generic-enum-to-int"/>
        /// <typeparam name="TSource">Source type to cast from. Usually a generic type.</typeparam>
        /// <param name="source">Source object to cast.</param>
        /// <returns>Returns a casted instance of type <see cref="TTarget"/>.</returns>
        public static TTarget CastFrom<TSource>(TSource source)
        {
            return CastCache<TSource>.caster(source);
        }

        /// <summary>
        /// Responsible for caching and emitting a default constructor delegate for type <see cref="TSource"/>.
        /// </summary>
        /// <typeparam name="TSource">Type to create a default constructor of.</typeparam>
        private static class ConstructorCache<TSource> where TSource : new()
        {
            public static readonly EmitUtil.DefaultConstructorDelegate<TSource> constructor = GetConstructor();

            private static EmitUtil.DefaultConstructorDelegate<TSource> GetConstructor()
            {
                return EmitUtil.GenerateDefaultConstructorDelegate<TSource>();
            }
        }

        /// <summary>
        /// Responsible for caching the casting delegate from <see cref="TSource"/> to <see cref="TTarget"/>.
        /// </summary>
        /// <typeparam name="TSource">Source type.</typeparam>
        private static class CastCache<TSource>
        {
            public static readonly EmitUtil.TypeCastDelegate<TSource, TTarget> caster = GetCaster();

            private static EmitUtil.TypeCastDelegate<TSource, TTarget> GetCaster()
            {
                return EmitUtil.GenerateTypeCastDelegate<TSource, TTarget>();
            }
        }
    }
}
#endif


text:
<?php

/**
 * Created by PhpStorm.
 * User: Davis Peixoto
 * Date: 16/04/2014
 * Time: 19:48 PM
 */
class BaseClass
{
    const BAR = 'BAR';

    public $bfo;
    protected $bza;
    private $bba;

    public static $boo;
    protected static $baa;
    private static $bzz;

    public function noParamsMethodShouldNotExist()
    {
        //asd
    }

    public function withParamsMethodShouldNotExist($param1, $param2)
    {
        //asd
    }

    protected function noParamsProtectedMethodShouldNotExist()
    {
        //asd
    }

    protected function withParamsProtectedMethodShouldNotExist($param1, $param2)
    {
        //asd
    }

    private function noParamsPrivateMethodShouldNotExist()
    {
        //asd
    }

    private function withParamsPrivateMethodShouldNotExist($param1, $param2)
    {
        //asd
    }

    public static function noParamsStaticMethodShouldNotExist()
    {
        //asd
    }

    public static function withParamsStaticMethodShouldNotExist($param1, $param2)
    {
        //asd
    }

    protected static function noParamsProtectedStaticMethodShouldNotExist()
    {
        //asd
    }

    protected static function withParamsProtectedStaticMethodShouldNotExist($param1, $param2)
    {
        //asd
    }

    private static function noParamsPrivateStaticMethodShouldNotExist()
    {
        //asd
    }

    private static function withParamsPrivateStaticMethodShouldNotExist($param1, $param2)
    {
        //asd
    }
}


text:
var rawdata;
    var objdata = [];
    var matchDateEvents;
    var matchedEvents;
    var datefilter = {
        eventdate: null
    }

    var QueryString = function () {
        // This function is anonymous, is executed immediately and
        // the return value is assigned to QueryString!
        var query_string = {};
        var query = window.location.search.substring(1);
        var vars = query.split("&");
        for (var i=0;i<vars.length;i++) {
            var pair = vars[i].split("=");
            // If first entry with this name
            if (typeof query_string[pair[0]] === "undefined") {
                query_string[pair[0]] = pair[1];
                // If second entry with this name
            } else if (typeof query_string[pair[0]] === "string") {
            var arr = [ query_string[pair[0]], pair[1] ];
            query_string[pair[0]] = arr;
            // If third or later entry with this name
            } else {
                query_string[pair[0]].push(pair[1]);
            }
        }
        return query_string;
    } ();

    var getData = function(month, year) {
        // console.log(objdata);
        var ajaxUrl = 'https://smgapps.bu.edu/calendar/getmonth.cfm';
        if (month && year) {
            ajaxUrl += '?month=' + month + '&year=' + year;
        };
        $.ajax({
            url: ajaxUrl,
            type: 'get',
            dataType: 'json'
        }).done(function (data) {
            rawdata = data;
            convertData(rawdata)
        });
    };

    var convertData = function (data) {
        // setting objdata
        for (var i = 0 ; i < data.DATA.length ; i++) {
            objdata[i] = {};
            objdata[i]['id'] = data.DATA[i][0];
            objdata[i]['title'] = data.DATA[i][1];
            objdata[i]['message'] = data.DATA[i][2];
            objdata[i]['isPending'] = data.DATA[i][3];
            objdata[i]['approved'] = data.DATA[i][4];
            objdata[i]['sector'] = data.DATA[i][5];
            objdata[i]['eventdate'] = moment(data.DATA[i][6]).format('YYYY-MM-DD');
            objdata[i]['untildate'] = data.DATA[i][7];
            objdata[i]['recurrance'] = data.DATA[i][8];
            objdata[i]['recurrenceDay'] = data.DATA[i][9];
            objdata[i]['isAllDayEvent'] = data.DATA[i][10];
            objdata[i]['start_time'] = moment(data.DATA[i][11]).format('h:mma');
            objdata[i]['end_time'] = moment(data.DATA[i][12]).format('h:mma');
            objdata[i]['location'] = data.DATA[i][13];
            objdata[i]['weblink'] = data.DATA[i][14];
            objdata[i]['contactName'] = data.DATA[i][15];
            objdata[i]['contactEmail'] = data.DATA[i][16];
            objdata[i]['sponsors'] = data.DATA[i][17];
            objdata[i]['category'] = String(data.DATA[i][18]).split(",");
            objdata[i]['ad'] = data.DATA[i][19];
            objdata[i]['calText'] = "";
            // define overall category as string
            var deptCat = [];
            if (_.indexOf(objdata[i]['category'],'30') !== -1) {
                deptCat.push('undergrad');
            };
            if (_.indexOf(objdata[i]['category'],'18') !== -1) {
                deptCat.push('graduate');
            };
            if (_.indexOf(objdata[i]['category'],'11') !== -1) {
                deptCat.push('executive');
            };
            if (_.indexOf(objdata[i]['category'],'42') !== -1) {
                deptCat.push('alumni');
            };
            if (_.indexOf(objdata[i]['category'],'516') !== -1) {
                deptCat.push('faculty');
            };
            if (_.indexOf(objdata[i]['category'],'517') !== -1) {
                deptCat.push('staff');
            };
            if (_.indexOf(objdata[i]['category'],'518') !== -1) {
                deptCat.push('other');
            };
            if (deptCat.length >4) {
                objdata[i]['calText'] = 'All'
            } else { objdata[i]['calText'] = deptCat.join(" | ")};
        };
        console.log(objdata);
        // display dates with events
        var eventDateArr = _.uniq(_.pluck(objdata,'eventdate'));
        for (var i = eventDateArr.length - 1; i >= 0; i--) {
            var tmp = '.calendar-day-' + eventDateArr[i];
            $(tmp).addClass('event');
        };

        // If Date Specified
        if (QueryString.date) {
            datefilter.eventdate = QueryString.date;
            renderEventList();
        } else {
            $('.today').trigger('click');
        };

    };

    var renderEventList = function () {
        // hide currentevent
        $('#eventContainer').hide();
        $('#eventAd').html('');
        $('#eventTemp').fadeIn();

        // get category filters
        var catfilter = $('input.sub-event:checkbox:checked').map(
            function () {
              return $(this).val()
            }
          ).get();
        // get events with category from objdata
        if (catfilter.length === 0 ) {
          // catfilter = [""];
          matchedCatEvents = objdata;
        } else {
          matchedCatEvents = _.filter(objdata, function (evnt) {
            // console.log(evnt.category);
            // var arr = evnt.category;
            return _.intersection(evnt.category, catfilter).length > 0;
          });
        };

        // first match date
        matchedEvents = _.filter(matchedCatEvents, function (evnt) {
          return (moment(evnt.eventdate).isSame(datefilter.eventdate) || moment(evnt.eventdate).isAfter(datefilter.eventdate));
        });

        matchedEvents = _.sortBy(matchedEvents, function (evnt) {
          return evnt.eventdate;
        });

        console.log(matchedEvents);

        // compile html
        var startingdate = datefilter.eventdate;
        var html = '
'+moment(startingdate).format("ddd, MMM Do")+'
';

        var listLen = 15;
        if (matchedEvents.length < 15) { listLen = matchedEvents.length; }

        for (var i = 0; i < listLen; i++) {
            if (matchedEvents[i].eventdate !== startingdate) {
              html += '
'+moment(matchedEvents[i].eventdate).format("ddd, MMM Do")+'
';
              startingdate = matchedEvents[i].eventdate;
            };
            html += '
';
            html += '' + matchedEvents[i].title + '';
            html += '' + matchedEvents[i].calText + '';
            html += ''+ parseTime(matchedEvents[i]['start_time']) + '';
            html += '
';
        };
        // show events
        $('#eventlist').hide().html(html).fadeIn();
        addEventHandlers();
    }

    // function to add item addEventHandlers
    function addEventHandlers () {
        $('.eventitem').click(function (e) {
            $('.eventitem .badge').removeClass('select-badge');
            $(this).find('.badge').addClass('select-badge');
            var zid = $(this).attr('data-id');
            var zdate = $(this).attr('data-date');

            // console.log(zyear); console.log(zmonth); console.log(zday);
            window.history.pushState("","", window.location.pathname + '?date=' + zdate + '&id=' + zid);
            displayEvent(zid, zdate);
            $('html, body').animate({
                    scrollTop: $("#eventContainer").offset().top - 120
                }, 500);
        });

        // If id specified, trigger the click
        if (QueryString.date && QueryString.id) {
            var tmp = '.eventitem[data-id="' + QueryString.id + '"][data-date="' + QueryString.date + '"]';
            $(tmp).trigger('click');
            // QueryString.id = false;
        };
    }

    function displayEvent (zid, zdate) {

        zid = parseInt(zid);
        var selectedEvent = _.findWhere(matchedEvents, {id: zid, eventdate: zdate});

        // hide default
        $('#eventTemp').hide();

        //set the event title
        $('h1.eventTitle').html(selectedEvent.title);

        //set the event description
        $('p.eventDescription').html(selectedEvent.message);

        //set the event time
        var ttime = parseTime(selectedEvent['start_time']);
        if (ttime == 'All day') {
            $('td#eventWhen').html(ttime + ' on ' + moment(selectedEvent.eventdate).format('MMM Do, YYYY'));
        } else {
            $('td#eventWhen').html(ttime + ' to ' + parseTime(selectedEvent['end_time']) + ' on ' + moment(selectedEvent.eventdate).format('MMM Do, YYYY'));
        }

        //set the event location
        $('#eventLocation').html(selectedEvent.location);

        //set the event weblink
        var hasLink = (selectedEvent.weblink !== "http://" && selectedEvent.weblink);
        if (hasLink) {
            $('#eventLink').attr('href', selectedEvent.weblink).show();
        } else {
            $('#eventLink').hide();
        }

        //set the event sponsor
        $('#eventSponsor').html(selectedEvent.sponsors);

        //show event contact name and email
        $('#eventContact').attr('href', 'mailto:' + selectedEvent.contactEmail).html(selectedEvent.contactName)

        //display gcal and ics links
        var gcaldate = moment(selectedEvent['eventdate']).format('YYYYMMDD');
        var gcalstarttime = moment(selectedEvent['start_time'],'h:mma').utc().format('HHmmss')+'Z';
        var gcalendtime = moment(selectedEvent['end_time'],'h:mma').utc().format('HHmmss')+'Z';
        var gcalstartdatetime = gcaldate+'T'+gcalstarttime;
        var gcalenddatetime = gcaldate+'T'+gcalendtime;
        // console.log(gcaldate);console.log(gcalstarttime);console.log(gcalendtime);console.log(gcalstartdatetime);console.log(gcalenddatetime);
        var gcalhref = 'http://www.google.com/calendar/event?action=TEMPLATE';
        if (ttime === "All day") {
            gcalhref += "&dates=" + gcaldate + "/" + gcaldate;
        } else {
            gcalhref += "&dates=" + gcalstartdatetime + "/" + gcalenddatetime;
        };
        gcalhref += "&text=" + encodeURIComponent(selectedEvent.title) +
        "&details=" + encodeURIComponent(selectedEvent.message) +
        (selectedEvent.location && "&location=" + encodeURIComponent(selectedEvent.location));
        // set gcal href
        $('#addgcal').attr('href',gcalhref);

        var icsdateStart="", icsdateEnd="";
        // Reformat dates for ICS
        if(ttime === "All day") {
            icsdateStart = "DTSTART;VALUE=DATE:" + gcaldate;
            icsdateEnd = "DTEND;VALUE=DATE:" + gcaldate;
        } else {
            icsdateStart = "DTSTART:" + gcalstartdatetime;
            icsdateEnd = "DTEND:" + gcalenddatetime;
        }

        // Generate the ICS file
        var icshref = [
            "BEGIN:VCALENDAR",
            "PRODID:-//Microsoft Corporation//Outlook 12.0 MIMEDIR//EN",
            "VERSION:2.0",
            "METHOD:PUBLISH",
            "BEGIN:VEVENT",icsdateStart,icsdateEnd,
            "SUMMARY:" + escapeICS(selectedEvent.title),
            selectedEvent.location && ("LOCATION:" + escapeICS(selectedEvent.location)),
            "DESCRIPTION:" + escapeICS(selectedEvent.message),
            hasLink ? "URL:" + escapeICS(selectedEvent.weblink) : "",
            "END:VEVENT","END:VCALENDAR"
        ].join("\n");
        // set ics href
        $("#addics").attr('href','data:text/calendar;charset=utf8,' + escape(icshref));

        //show event ad
        if (selectedEvent.ad != null) {
            $('#eventAd').html(
                '' +
                ''
                );
        } else {
            $('#eventAd').html('');
        }

        //show the event container
        $('#eventContainer').hide().fadeIn();
        QueryString.id = false;
    }

    function triggerClick (day) {
        var tmp = '.calendar-day-' + day;
        $(tmp).trigger('click');
    }

    function parseTime (time) {
        if (time == '12:00am') {
            return 'All day';
        } else {
            return time;
        }
    }

// CALENDAR
    $('#calendarView').clndr({
        template: $('#calendar-template').html(),
        startWithMonth: QueryString.date || moment(),
        clickEvents: {
            click: function (target) {
                var selectedDate = moment(target.date).format('YYYY-MM-DD');
                datefilter.eventdate = selectedDate;
                // console.log(datefilter.eventdate);
                $('.day').removeClass('highlighted');
                $(target.element).addClass('highlighted');
                renderEventList();
                window.history.pushState("","", window.location.pathname + '?date=' + datefilter.eventdate );
            },
            nextMonth: function(target) {
                var zmonth = moment(target).format('MM');
                var zyear = moment(target).format('YYYY');
                window.history.pushState("","", window.location.pathname + '?date=' + moment(target).format('YYYY-MM-DD') );
                QueryString.date = moment(target).format('YYYY-MM-DD');
                // window.location.href = window.location.pathname + '?year=' + zyear + '&month=' + zmonth + '&day=01';
                getData(zmonth, zyear);
                triggerClick(QueryString.date);
            },
            previousMonth: function(target) {
                var zmonth = moment(target).format('MM');
                var zyear = moment(target).format('YYYY');
                window.history.pushState("","", window.location.pathname + '?date=' + moment(target).format('YYYY-MM-DD') );
                QueryString.date = moment(target).format('YYYY-MM-DD');
                // window.location.href = window.location.pathname + '?year=' + zyear + '&month=' + zmonth + '&day=01';
                getData(zmonth, zyear);
                triggerClick(QueryString.date);
            },
        },
        doneRendering: function(){
            if (QueryString.date) {
                triggerClick(QueryString.date);
            };
        },
        forceSixRows: true,
        showAdjacentMonths: true,
        adjacentDaysChangeMonth: false
    });

    if (QueryString.date) {
        var zmonth = moment(QueryString.date).format('MM');
        var zyear = moment(QueryString.date).format('YYYY');
        getData(zmonth, zyear);
    } else {
        getData();
        $('.today').trigger('click');
    }

    function escapeICS(text) {
        return text.replace(/(\\|;|,)/g,"\\$0").replace(/(\r\n|\r|\n|
|
)/g,"\\n")
    }
    function dateICS(text) {
        return text.replace(/[:-]|\.[0-9]{3}/g,"");
    }


text:
from __future__ import unicode_literals

from django.db import migrations

class Migration(migrations.Migration):

    dependencies = [
        ('topics', '0059_auto_20170528_0757'),
    ]

    operations = [
        migrations.AlterModelOptions(
            name='learningoutcome',
            options={'ordering': ['curriculum_areas__number', 'curriculum_areas__name', 'text']},
        ),
    ]


text:
package DDG::Spice::Airlines;
# ABSTRACT: Information about airplane flights

use strict;
use DDG::Spice;

primary_example_queries "AA 102";
secondary_example_queries "Delta 3684";
description "Flight information";
name "Flight Info";
icon_url "/i/flightstats.com.ico";
source "FlightStats";
code_url "https://github.com/duckduckgo/zeroclickinfo-spice/blob/master/lib/DDG/Spice/Airlines.pm";
topics "economy_and_finance", "travel", "everyday";
category "time_sensitive";
attribution web => [ 'https://www.duckduckgo.com', 'DuckDuckGo' ],
            github => [ 'https://github.com/duckduckgo', 'DuckDuckGo'],
            twitter => ['http://twitter.com/duckduckgo', 'DuckDuckGo'];

spice to => 'https://api.flightstats.com/flex/flightstatus/rest/v2/jsonp/flight/status/$1/$2/arr/$3/$4/$5?hourOfDay=$6&utc=true&appId={{ENV{DDG_SPICE_FLIGHTS_API_ID}}}&appKey={{ENV{DDG_SPICE_FLIGHTS_APIKEY}}}&callback={{callback}}';
spice from => '(.*)/(.*)/(.*)/(.*)/(.*)/(.*)';
spice proxy_cache_valid => '418 1d';

triggers any => '///***never trigger***///';
# triggers query_lc => qr/^(\d+)\s+(.*?)(?:[ ]air.*?)?$|^(.*?)(?:[ ]air.*?)?\s+(\d+)$/;

# Get the list of airlines and strip out the words.
my %airlines = ();
my @airlines_lines = share('airlines.txt')->slurp;
foreach my $line (@airlines_lines) {
  chomp($line);
  my @line = split(/,/, $line);

  $line[1] =~ s/\s+air.*$//i;

  #American (Airlines <- regex removed) => AA
  $airlines{lc $line[1]} = $line[0];
  #AA => AA
  $airlines{lc $line[0]} = $line[0];
}

# Get the list of elements because an airline name can be an element.
my %elements = ();
my @elements_lines = share('symbols.txt')->slurp;
foreach my $line (@elements_lines) {
    chomp $line;
    my @line = split(/,/, $line);
    $elements{$line[0]} = 1;
    $elements{$line[1]} = 1;
}

sub checkAirlines {
    my ($airline, $flightno, $year, $month, $dayOfMonth, $hour) = @_;

    # Check if we found something and if it's not an element.
    if($airline && !exists $elements{$airline}) {
        return $airline, $flightno, $year, $month, $dayOfMonth, $hour;
    } else {
        return;
    }
}

handle query_lc => sub {

    my $query = $_;

    # get the current time
    my ($second, $minute, $hour, $dayOfMonth,
        $month, $year, $dayOfWeek, $dayOfYear, $daylightSavings) = gmtime(time);

    $month += 1;
    $year += 1900;

    # 102 AA
    if($query =~ /^(\d+)\s*(.*?)(?:[ ]air.*?)?$/) {
        return checkAirlines($airlines{$2}, $1, $year, $month, $dayOfMonth, $hour);
    # AA 102
    } elsif($query =~ /^(.*?)(?:[ ]air.*?)?\s*(\d+)$/) {
        return checkAirlines($airlines{$1}, $2, $year, $month, $dayOfMonth, $hour);
    }
    return;
};

1;


text:
package org.javachannel.examples;

import javax.ejb.EJB;
import javax.enterprise.context.RequestScoped;
import javax.ws.rs.*;
import javax.ws.rs.core.MediaType;

@Path("employee")
@RequestScoped
public class EmployeeResource {

    // Ideally this state should be stored in a database
    @EJB
    EmployeeRepository bean;

    @GET
    @Produces({"application/xml", "application/json"})
    public Employee[] getList() {
        return bean.getEmployees().toArray(new Employee[0]);
    }

    @GET
    @Produces({"application/json", "application/xml"})
    @Path("{id}")
    public Employee get(@PathParam("id") int id) {
        if (id < bean.getEmployees().size())
            return bean.getEmployees().get(id);
        else
            return null;
    }

    @POST
    @Consumes(MediaType.APPLICATION_FORM_URLENCODED)
    public void addToList(@FormParam("name") String name,
                          @FormParam("age") int age) {
        System.out.println("Creating a new item: " + name);
        bean.addEmployee(new Employee(name, age));
    }

    @PUT
    public void putToList(@FormParam("name") String name,
                          @FormParam("age") int age) {
        addToList(name, age);
    }

    @DELETE
    @Path("{name}")
    public void deleteFromList(@PathParam("name") String name) {
        bean.deleteEmployee(name);
    }
}


text:
// Copyright 2017 Google 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.

package com.google.iosdevicecontrol.webinspector;

import com.google.auto.value.AutoValue;

/**
 * An applicationConnected message.
 *
 *
Example:
 *
 *
{@code
 * <?xml version="1.0" encoding="UTF-8"?>
 * <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN"
 *     "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
 * <plist version="1.0">
 * <dict>
 *   <key>__selector</key>
 *   <string>_rpc_applicationConnected:</string>
 *   <key>__argument</key>
 *   <dict>
 *     <key>WIRApplicationBundleIdentifierKey</key>
 *     <string>com.apple.mobilesafari</string>
 *     <key>WIRApplicationIdentifierKey</key>
 *     <string>PID:176</string>
 *     <key>WIRApplicationNameKey</key>
 *     <string>Safari</string>
 *     <key>WIRHostApplicationIdentifierKey</key>
 *     <string>PID:457</string>
 *     <key>WIRIsApplicationActiveKey</key>
 *     <integer>1</integer>
 *     <key>WIRIsApplicationProxyKey</key>
 *     <false/>
 *   </dict>
 * </dict>
 * </plist>
 * }

 */
@AutoValue
public abstract class ApplicationConnectedMessage extends ApplicationMessage {
  /** Returns a new builder. */
  public static Builder builder() {
    return new AutoValue_ApplicationConnectedMessage.Builder();
  }

  /** A builder for creating applicationConnected messages. */
  @AutoValue.Builder
  public abstract static class Builder extends ApplicationMessage.Builder<Builder> {
    @Override
    public abstract ApplicationConnectedMessage build();
  }

  @Override
  public MessageSelector selector() {
    return MessageSelector.APPLICATION_CONNECTED;
  }
}


text:
pocket-ruby
===========

[![Code Climate](https://codeclimate.com/github/turadg/pocket-ruby.png)](https://codeclimate.com/github/turadg/pocket-ruby) [![Gem Version](https://badge.fury.io/rb/pocket-ruby.png)](http://badge.fury.io/rb/pocket-ruby)

Ruby API for v3 of the [Pocket API](http://getpocket.com/developer/docs/overview) (formerly Read It Later)

# Usage

Clone the repo and refer to `demo-server.rb` for examples on how to interact with the Pocket API.

```sh
git clone
cd pocket-ruby
bundle install
ruby demo-server.rb
```

*Note:* Changes to the `demo-server.rb` will require a restart to take effect (or you can use [rerun](https://github.com/alexch/rerun)).

Pocket-Ruby can be installed via the gem, ```gem install pocket-ruby```

Or via bundler, `gem 'pocket-ruby'`

## Pocket API Notes

Below are some aspects of the Pocket API that aren't covered in the official documentation, or that have been observed:

* For very long articles, the maximum reported `word_count` is 65535, even if the article is longer.
* If a `count` isn't specified, the `Retreive` call will return maximum of 5000 items.
* The API response may contain a number of undocumented fields, including:
  * `amp_url`
  * `domain_metadata`
  * `is_index`
  * `lang` ([ISO_639-1](https://en.wikipedia.org/wiki/ISO_639-1)?)
  * `listen_duration_estimate`
  * `sort_id`
  * `time_to_read`
  * `top_image_url`
* Every integer value is returned as a string, *except* for `time_to_read`, `listen_duration_estimate` and `sort_id`.
* The `time_to_read` is in minutes, but `listen_duration_estimate` is in seconds.
* If an article's `status` is `"2"` ('should be deleted') then most fields will not be present.


text:
<?php

namespace conceptho\ServiceLayer;

class Response extends \yii\base\BaseObject implements \IteratorAggregate, \ArrayAccess, \Countable {
	use \yii\base\ArrayAccessTrait;

	public $isOk;
	public $data;

	public function __construct( $isOk, $data, $config = array() ) {
		parent::__construct( array_merge( [ 'isOk' => $isOk, 'data' => $data ], $config ) );
	}
}


text:
package com.intellij.vcs.log.data;

import javax.annotation.Nonnull;

import java.util.Objects;

public interface VcsLogUiProperties {
  @Nonnull
  <T> T get(@Nonnull VcsLogUiProperty<T> property);

  <T> void set(@Nonnull VcsLogUiProperty<T> property, @Nonnull T value);

  <T> boolean exists(@Nonnull VcsLogUiProperty<T> property);

  class VcsLogUiProperty<T> {
    @Nonnull
    private final String myName;

    public VcsLogUiProperty(@Nonnull String name) {
      myName = name;
    }

    @Override
    public String toString() {
      return myName;
    }

    @Override
    public boolean equals(Object o) {
      if (this == o) return true;
      if (o == null || getClass() != o.getClass()) return false;
      VcsLogUiProperty<?> property = (VcsLogUiProperty<?>)o;
      return Objects.equals(myName, property.myName);
    }

    @Override
    public int hashCode() {
      return Objects.hash(myName);
    }
  }
}


text:
using Castle.Core.Logging;
using SOURCE.Domaine;
using SOURCE.Domaine.Composite;
using SOURCE.Domaine.Results;
using SOURCE.Infrastructure.Constant;
using SOURCE.Infrastructure.Services.Depots;
using SOURCE.Infrastructure.Services.Caching;
using System;
using System.Linq;
using System.Collections.Generic;
using AutoMapper;
using SOURCE.EspaceCandidature.Web.ViewModels.Pages.Public.ConfirmationPreReservation;
using SOURCE.EspaceCandidature.Web.ViewModels.Pages.Planning;

namespace SOURCE.EspaceCandidature.Web.ViewModels.ModelBuilders.Public.ConfirmationPreReservation
{
    public class ConfirmationPreReservationModelBuilder : ModelBuilderBase, IConfirmationPreReservationModelBuilder
    {
        public ConfirmationPreReservationModelBuilder(ILogger logger, IDepotFactory depotFactory, ICaching cachingService)
            : base(logger, depotFactory, cachingService)
        { }

        public PreReservationViewModel BuildPreReservationViewModel(Context context, string token, long demandeID, long personneID, bool acceptee)
        {
            var preReservationDetails = _depotFactory.DemandeDepot.GetPreReservationDetails(demandeID, personneID);
            var preReservationEvents =  _depotFactory.DemandeDepot.GetDemandePreReservations(demandeID, personneID);

            return new PreReservationViewModel(context, _cachingService)
            {
                PreReservationDetails = preReservationDetails,
                Token = token,
                ConfirmationMessage = acceptee ? _cachingService.Translate("CONFIRMATION_PRERESERVATION_MESSAGE_ACCEPTEE") : _cachingService.Translate("CONFIRMATION_PRERESERVATION_MESSAGE_REFUS"),
                Acceptee= acceptee,
                PreReservationEvents = Mapper.Map<IEnumerable<PlanningResult>, IEnumerable<PlanningEventViewModel>>(preReservationEvents)
            };
        }
    }
}


text:
package com.cmmakerclub.iot.esptouch.protocol;

import java.net.InetAddress;

import com.cmmakerclub.iot.esptouch.task.IEsptouchGenerator;
import com.cmmakerclub.iot.esptouch.util.ByteUtil;

public class EsptouchGenerator implements IEsptouchGenerator {

	private final byte[][] mGcBytes2;
	private final byte[][] mDcBytes2;

	/**
	 * Constructor of EsptouchGenerator, it will cost some time(maybe a bit
	 * much)
	 *
	 * @param apSsid
	 *            the Ap's ssid
	 * @param apBssid
	 *            the Ap's bssid
	 * @param apPassword
	 *            the Ap's password
	 * @param inetAddress
	 *            the phone's or pad's local ip address allocated by Ap
	 * @param isSsidHidden
	 *            whether the Ap's ssid is hidden
	 */
	public EsptouchGenerator(String apSsid, String apBssid, String apPassword,
			InetAddress inetAddress, boolean isSsidHiden) {
		// generate guide code
		GuideCode gc = new GuideCode();
		char[] gcU81 = gc.getU8s();
		mGcBytes2 = new byte[gcU81.length][];

		for (int i = 0; i < mGcBytes2.length; i++) {
			mGcBytes2[i] = ByteUtil.genSpecBytes(gcU81[i]);
		}

		// generate data code
		DatumCode dc = new DatumCode(apSsid, apBssid, apPassword, inetAddress,
				isSsidHiden);
		char[] dcU81 = dc.getU8s();
		mDcBytes2 = new byte[dcU81.length][];

		for (int i = 0; i < mDcBytes2.length; i++) {
			mDcBytes2[i] = ByteUtil.genSpecBytes(dcU81[i]);
		}
	}

	@Override
	public byte[][] getGCBytes2() {
		return mGcBytes2;
	}

	@Override
	public byte[][] getDCBytes2() {
		return mDcBytes2;
	}

}


text:
package com.google.errorprone.refaster.testdata;

import com.google.common.base.Joiner;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

/**
 * Example usage of {@code GenericPlaceholderTemplate}.
 */
public class GenericPlaceholderTemplateExample {
  public static void main(String[] args) {
    List<UUID> list = new ArrayList<>();
for (int i = 0; i < 10; i++) {
    list.add(UUID.randomUUID());
}
System.out.println(Joiner.on('\n').join(list));
  }
}


text:
package org.batfish.datamodel;

import static org.hamcrest.Matchers.equalTo;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertThat;

import java.util.Optional;
import org.junit.Test;

public class IcmpTypeTest {
  @Test
  public void getName() {
    assertThat(IcmpType.getName(8), equalTo(Optional.of("ECHO-REQUEST")));
    assertThat(IcmpType.getName(75), equalTo(Optional.empty()));
  }

  @Test
  public void namesDontHaveUnderscores() {
    for (String desc : IcmpType.NAMES.values()) {
      assertFalse(desc, desc.contains("_"));
    }
  }
}


text:
require 'rspec'
require 'selenium-webdriver'
require_relative '../../web-test/browser/browser_manager'
require_relative '../../web-test/pages/base_page'
require_relative '../../web-test/pages/registration_page'
require_relative '../../web-test/pages/home_page'
require_relative '../../web-test/pages/tab_page'

describe 'Performance Horizon Test Exercise' do

  browse_mgr = BrowserManager.new()

   before(:each) do
     @driver = browse_mgr.set_up("linux")
   end

   after(:each) do
     browse_mgr.tear_down
   end

  it 'should validate various actions on demoqa' do

    #Test Data
    country = "Australia"
    sports = "cricket"
    marital_status = "married"
    title_data = "Registration | Demoqa"

    #Actaul Test
    homePage = HomePage.new(@driver)
    # Part One
    homePage.select_tab_one
    homePage.select_tab_two
    tab_3_title = homePage.select_tab_three
    homePage.select_tab_four
    tab_5_title = homePage.select_tab_five
    tabPage = homePage.open_demo
    tabPage.open_tab
    registration = tabPage.visit_registration_page
    registration.enter_first_name(tab_3_title)
    registration.enter_last_name(tab_5_title)
    registration.select(marital_status)
    registration.select(sports)
    registration.select_country(country)

    #Validation of the Test
    expect(registration.fetch_current_page_title).to eq(title_data)
  end

end


text:
<!-- TOC depthFrom:2 depthTo:3 withLinks:1 updateOnSave:1 orderedList:0 -->

- [Authorization model](#authorization-model)
- [Creating a new property](#creating-a-new-property)
- [Managing namespaces](#managing-namespaces)
- [Super users](#super-users)

<!-- /TOC -->

## Authorization model

In Pulsar, the authentication provider is charged to identify a particular
client and associate it with a ***role*** token.

A role is a string that might represent a single or multiple clients,
and these clients can be granted the permission to produce or consume
from certain topics, or to administer the configuration for a certain
[property](Architecture.md##property-and-namespace).

## Creating a new property

As we said, a Pulsar property identifies a tenant and typically is
provisioned by Pulsar instance administrators or by some kind of
self-service portal.

```shell
$ bin/pulsar-admin properties create my-property   \
        --admin-roles my-admin-role                \
        --allowed-clusters us-west,us-east
```

This command will create a new property `my-property` that will be
allowed to use the clusters `us-west` and `us-east`.

A client that successfully identify itself with the role `my-admin-role`,
will be allowed to do all the administration on this property.

## Managing namespaces

The property administrator will now be able to create multiple namespaces,
in the specified clusters.

```
$ bin/pulsar-admin namespaces create my-property/us-west/my-namespace
```

Once created, we can grant permissions to use this namespace:

```
$ bin/pulsar-admin namespaces grant-permission \
                        my-property/us-west/my-namespace \
                        --role my-client-role \
                        --actions produce,consume
```

After this, clients identifying with the role `my-client-role`, will be
able to use topics in the specified namespace.

## Super users

In Pulsar you can assign certain roles to be *super-users* of the system.

A super-user is allowed to do all administrative tasks on all properties
and namespaces, as well as publishing and subscribing to all topics.

Super users are configured in the broker conf file `conf/broker.conf`:

```shell
superUserRoles=my-super-user-1,my-super-user-2
```

Typically, super users role are used for administrators clients and also
for broker-to-broker authorization. In geo-replication every broker
needs to be able to publish in other clusters topics.


text:
/*=========================================================================================
    File Name: datatables-responsive.js
    Description: Responsive Datatable
    ----------------------------------------------------------------------------------------
    Item Name: Stack - Responsive Admin Theme
    Version: 1.1
    Author: PIXINVENT
    Author URL: http://www.themeforest.net/user/pixinvent
==========================================================================================*/

$(document).ready(function() {

    /***********************************
     *       Configuration option       *
     ***********************************/

    $('.dataex-res-configuration').DataTable({
        responsive: true
    });

    /********************************
     *       `new` constructor       *
     ********************************/

    var tableConstructor = $('.dataex-res-constructor').DataTable();

    new $.fn.dataTable.Responsive(tableConstructor);

    /**********************************************
     *       Immediately show hidden details       *
     **********************************************/

    $('.dataex-res-immediately').DataTable({
        responsive: {
            details: {
                display: $.fn.dataTable.Responsive.display.childRowImmediate,
                type: ''
            }
        }
    });

    /************************************
     *       Modal details display       *
     ************************************/

    $('.dataex-res-modal').DataTable({
        responsive: {
            details: {
                display: $.fn.dataTable.Responsive.display.modal({
                    header: function(row) {
                        var data = row.data();
                        return 'Details for ' + data[0] + ' ' + data[1];
                    }
                }),
                renderer: function(api, rowIdx, columns) {
                    var data = $.map(columns, function(col, i) {
                        return '
' +
                            '' + col.title + ':' + '	 ' +
                            '' + col.data + '	' +
                            '
';
                    }).join('');

                    return $('
').append(data);
                }
            }
        }
    });

    /***********************************************
     *       With Buttons - Column visibility       *
     ***********************************************/

    $('.dataex-res-visibility').DataTable({
        dom: 'Bfrtip',
        buttons: [
            'colvis'
        ]
    });

    /*******************************
     *       With FixedHeader       *
     *******************************/

    var tableFixedHeader = $('.dataex-res-fixedheader').DataTable({
        responsive: true
    });

    new $.fn.dataTable.FixedHeader(tableFixedHeader, {
        header: true,
        headerOffset: $('.header-navbar').outerHeight()
    });

    /******************************
     *       With ColReorder       *
     ******************************/

    $('.dataex-res-colreorder').DataTable({
        responsive: true,
        colReorder: true
    });

    /*******************************************
     *       Column controlled child rows       *
     *******************************************/

    $('.dataex-res-controlled').DataTable({
        responsive: {
            details: {
                type: 'column'
            }
        },
        columnDefs: [{
            className: 'control',
            orderable: false,
            targets: 0
        }],
        order: [1, 'asc']
    });

    /*************************************
     *       Column control - right       *
     *************************************/

    $('.dataex-res-controlright').DataTable({
        responsive: {
            details: {
                type: 'column',
                target: -1
            }
        },
        columnDefs: [{
            className: 'control',
            orderable: false,
            targets: -1
        }]
    });

    /******************************************
     *       Whole row child row control       *
     ******************************************/

    $('.dataex-res-rowcontrol').DataTable({
        responsive: {
            details: {
                type: 'column',
                target: 'tr'
            }
        },
        columnDefs: [{
            className: 'control',
            orderable: false,
            targets: 0
        }],
        order: [1, 'asc']
    });

    /********************************
     *      Vertical scrolling       *
     ********************************/

    var table = $('.dataex-res-scrolling').DataTable({
        scrollY: 300,
        paging: false
    });

    // Resize datatable on menu width change and window resize
    $(function () {

        $(".menu-toggle").on('click', resize);

        // Resize function
        function resize() {
            setTimeout(function() {

                // ReDraw DataTable
                tableFixedHeader.draw();
            }, 400);
        }
    });

});


text:
const static QString NYAN_SPACE_SEEDS("https://nyan.space/peers.php?json");
extern void AddOneShot(std::string strDest);

class NyanSpaceAPI : public QObject
{
    Q_OBJECT
public:
    explicit NyanSpaceAPI(QObject *parent = nullptr);
    void getmorepeers();

signals:
    void getmorepeers_finished(int numPeersConnected);

public slots:

private slots:
    void getmorepeers_request_finished();

private:
    QNetworkAccessManager *netman;
    QNetworkReply *reply;
};

#endif // NYANSPACEAPI_H


text:
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System.Collections.Generic;
using System.Diagnostics.Contracts;
using Microsoft.Cci.Immutable;
using Microsoft.Cci.UtilityDataStructures;

namespace Microsoft.Cci.Optimization {

  /// <summary>
  /// A rewriter for method bodies that inlines calls to methods identified by the rewriter client via a call back.
  /// </summary>
  public class Inliner : ILRewriter {

    /// <summary>
    /// A rewriter for method bodies that inlines calls to methods identified by the rewriter client via a call back.
    /// </summary>
    /// <param name="host">An object representing the application that is hosting this mutator. It is used to obtain access to some global
    /// objects and services such as the shared name table and the table for interning references.</param>
    /// <param name="inlineSelector">
    /// Returns zero or more method definitions that should be inlined at a given call site. Zero methods means no inlining. For non virtual calls, one method means that the call
    /// should be inlined. For virtual calls, one or methods means that the call site should do call site type tests to avoid virtual calls for the returned methods.
    /// A subsequent call to ShouldInline, using one of the method definitions as the methodBeingCalled parameter can be used to determine if the call following the type test
    /// should be inline or not.
    /// </param>
    /// <param name="sourceLocationProvider">An object that can map some kinds of ILocation objects to IPrimarySourceLocation objects. May be null.</param>
    /// <param name="localScopeProvider">An object that can provide information about the local scopes of a method. May be null.</param>
    public Inliner(IMetadataHost host, ShouldInline inlineSelector, ILocalScopeProvider/*?*/ localScopeProvider, ISourceLocationProvider/*?*/ sourceLocationProvider)
      : base(host, localScopeProvider, sourceLocationProvider) {
      Contract.Requires(host != null);
      Contract.Requires(inlineSelector != null);

      this.inlineSelector = inlineSelector;
      this.method = Dummy.MethodDefinition;
    }

    [ContractInvariantMethod]
    private void ObjectInvariant() {
      Contract.Invariant(inlineSelector != null);
      Contract.Invariant(this.method != null);
      Contract.Invariant(this.localFor != null);
    }

    ShouldInline inlineSelector;
    IMethodDefinition method;
    Hashtable<IParameterDefinition, GeneratorLocal> localFor = new Hashtable<IParameterDefinition, GeneratorLocal>();
    GeneratorLocal/*?*/ localForThis;
    ILGeneratorLabel/*?*/ returnLabel;
    ushort combinedMaxStack;

    /// <summary>
    /// </summary>
    /// <param name="methodBody"></param>
    /// <returns></returns>
    public override IMethodBody Rewrite(IMethodBody methodBody) {
      this.combinedMaxStack = methodBody.MaxStack;
      this.method = methodBody.MethodDefinition;
      return base.Rewrite(methodBody);
    }

    /// <summary>
    /// Emits the given operation at the current position of the new IL stream. Also tracks any referenced local definitions,
    /// so that this.localVariables will contain the exact list of locals used in the new method body.
    /// </summary>
    protected override void EmitOperation(IOperation operation) {
      switch (operation.OperationCode) {
        case OperationCode.Call:
          Contract.Assume(operation.Value is IMethodReference);
          var methodsToInline = this.inlineSelector(this.method, operation.Offset, (IMethodReference)operation.Value);
          Contract.Assume(methodsToInline != null);
          if (methodsToInline.Count == 1) {
            var methodToInline = methodsToInline[0];
            Contract.Assume(methodToInline != null && !methodToInline.IsAbstract && !methodToInline.IsExternal);
            this.Inline(methodToInline.Body);
            return;
          }
          break;

        //TODO: virtual calls

        case OperationCode.Ldarg:
        case OperationCode.Ldarg_0:
        case OperationCode.Ldarg_1:
        case OperationCode.Ldarg_2:
        case OperationCode.Ldarg_3:
        case OperationCode.Ldarg_S:
          if (this.returnLabel == null) break;
          this.EmitMappedLocalInsteadOfArgument(OperationCode.Ldloc, operation.Value);
          return;
        case OperationCode.Ldarga:
        case OperationCode.Ldarga_S:
          if (this.returnLabel == null) break;
          this.EmitMappedLocalInsteadOfArgument(OperationCode.Ldloca, operation.Value);
          return;
        case OperationCode.Starg:
        case OperationCode.Starg_S:
          if (this.returnLabel == null) break;
          this.EmitMappedLocalInsteadOfArgument(OperationCode.Stloc, operation.Value);
          return;

        case OperationCode.Ret:
          if (this.returnLabel != null) {
            this.Generator.Emit(OperationCode.Br, this.returnLabel);
            return;
          }
          break;
      }

      base.EmitOperation(operation);
    }

    private void EmitMappedLocalInsteadOfArgument(OperationCode opCodeToUse, object parameter) {
      var parDef = parameter as IParameterDefinition;
      var local = parDef == null ? this.localForThis : this.localFor[parDef];
      Contract.Assume(local != null);
      this.Generator.Emit(opCodeToUse, local);
    }

    [ContractVerification(false)] //Times out
    private void Inline(IMethodBody methodBody) {
      Contract.Requires(methodBody != null);

      var savedCombinedMaxStack = this.combinedMaxStack;
      this.combinedMaxStack += methodBody.MaxStack;
      if (this.combinedMaxStack > this.maxStack) this.maxStack = this.combinedMaxStack;

      var savedLocalForThis = this.localForThis;
      var nametable = this.Host.NameTable;
      var method = methodBody.MethodDefinition;
      var n = method.ParameterCount;
      if (!method.IsStatic) n++;
      var temps = new GeneratorLocal[n];
      for (ushort i = 0; i < n; i++) temps[i] = new GeneratorLocal() { MethodDefinition = method };
      var j = 0;
      if (!method.IsStatic) {
        var temp0 = temps[0];
        Contract.Assume(temp0 != null);
        temp0.Name = nametable.GetNameFor("this");
        temp0.Type = method.ContainingTypeDefinition;
        if (method.ContainingTypeDefinition.IsValueType)
          temp0.Type = ManagedPointerType.GetManagedPointerType(temp0.Type, this.Host.InternFactory);
        j = 1;
        this.localForThis = temp0;
      }
      foreach (var par in methodBody.MethodDefinition.Parameters) {
        Contract.Assume(par != null);
        Contract.Assume(j < n);
        var tempj = temps[j++];
        Contract.Assume(tempj != null);
        this.localFor[par] = tempj;
        tempj.Name = par.Name;
        tempj.Type = par.Type;
        if (par.IsByReference)
          tempj.Type = ManagedPointerType.GetManagedPointerType(tempj.Type, this.Host.InternFactory);
      }
      this.Generator.BeginScope();
      for (int i = n-1; i >= 0; i--) {
        var temp = temps[i];
        Contract.Assume(temp != null);
        this.Generator.Emit(OperationCode.Stloc, temp);
        this.TrackLocal(temp);
        this.Generator.AddVariableToCurrentScope(temp);
      }

      var savedReturnLabel = this.returnLabel;
      var returnLabel = this.returnLabel = new ILGeneratorLabel();
      this.EmitMethodBody(methodBody);
      this.Generator.MarkLabel(returnLabel);
      this.returnLabel = savedReturnLabel;
      this.localForThis = savedLocalForThis;
      this.Generator.EndScope();
      this.combinedMaxStack = savedCombinedMaxStack;

    }

  }

  /// <summary>
  /// Returns zero or more method definitions that should be inlined at the given call site. Zero methods means no inlining. For non virtual calls, one method means that the call
  /// should be inlined. For virtual calls, one or methods means that the call site should do call site type tests to avoid virtual calls for the returned methods.
  /// A subsequent call to ShouldInline, using one of the method definitions as the methodBeingCalled parameter can be used to determine if the call following the type test
  /// should be inline or not.
  /// </summary>
  /// <param name="callingMethod">The method into which the called method should be inlined, if so desired.</param>
  /// <param name="offsetOfCall">The offset in the calling method where the inlining should take place.</param>
  /// <param name="methodBeingCalled">The method being called.</param>
  public delegate IList<IMethodDefinition> ShouldInline(IMethodDefinition callingMethod, uint offsetOfCall, IMethodReference methodBeingCalled);

}


text:
package ru.swift.moderncleanarchitecture.presentation.screen.exercises;

import org.junit.Before;
import org.junit.Test;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;

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

import ru.swift.moderncleanarchitecture.TestExecutionThread;
import ru.swift.moderncleanarchitecture.TestPostExecutionThread;
import ru.swift.moderncleanarchitecture.domain.interactor.GetExercises;
import ru.swift.moderncleanarchitecture.domain.model.Exercise;
import ru.swift.moderncleanarchitecture.presentation.mapper.ExerciseModelDataMapper;
import ru.swift.moderncleanarchitecture.presentation.model.ExerciseModel;
import ru.swift.moderncleanarchitecture.presentation.navigation.Screens;
import ru.swift.moderncleanarchitecture.presentation.screen.DefaultSubscriber;
import ru.terrakok.cicerone.Router;
import rx.Subscriber;

import static org.mockito.BDDMockito.given;
import static org.mockito.Matchers.any;
import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoMoreInteractions;

public class ExercisesPresenterTest {

    @Mock private Router mockRouter;
    @Mock private GetExercises mockGetExercises;
    @Mock private ExerciseModelDataMapper mockExerciseModelMapper;
    @Mock private ExercisesContract$View$$State mockViewState;

    private final int EXERCISE_COUNT = 2;
    private final int EXERCISE_CATEGORY_ID = 10;

    // SUT
    private ExercisesPresenter presenter;

    @Before
    public void setUp() {
        MockitoAnnotations.initMocks(this);

        initPresenter();
    }

    private void initPresenter() {
        presenter = new ExercisesPresenter(mockRouter, mockGetExercises, mockExerciseModelMapper,
                EXERCISE_CATEGORY_ID);
        presenter.setViewState(mockViewState);
    }

    @Test
    public void shouldLoadAndShowExercises_onFirstViewAttach() {
        GetExercises.Params params = new GetExercises.Params(EXERCISE_CATEGORY_ID);
        presenter.onFirstViewAttach();

        verify(mockViewState).showLoading();
        verify(mockGetExercises).execute(eq(params), any(DefaultSubscriber.class));
        verifyNoMoreInteractions(mockViewState, mockGetExercises, mockRouter, mockExerciseModelMapper);
    }

    @Test @SuppressWarnings("unchecked")
    public void shouldRenderExerciseModels_whenResultsLoaded() {
        List<Exercise> exercises = createFakeExercises();
        List<ExerciseModel> exerciseModels = createFakeExerciseModels();
        given(mockExerciseModelMapper.transform(exercises)).willReturn(exerciseModels);
        mockGetExercises =
                new GetExercises(new TestExecutionThread(), new TestPostExecutionThread(), null) {
                    @Override
                    public void execute(Params params, Subscriber interactorSubscriber) {
                        interactorSubscriber.onNext(exercises);
                    }
                };
        initPresenter();

        presenter.onFirstViewAttach();

        verify(mockViewState).hideLoading();
        verify(mockExerciseModelMapper).transform(exercises);
        verify(mockViewState).renderExercises(exerciseModels);
        verifyNoMoreInteractions(mockRouter, mockExerciseModelMapper);
    }

    @Test
    public void shouldNavigateToExerciseInfoScreen_onExerciseClick() {
        int exerciseId = 15;
        presenter.onExerciseClick(exerciseId);

        verify(mockRouter).navigateTo(Screens.EXERCISE_INFO_SCREEN, exerciseId);
        verifyNoMoreInteractions(mockViewState, mockGetExercises, mockRouter, mockExerciseModelMapper);
    }

        @Test
    public void shouldExitFromScreen_onBackPressed() {
        presenter.onBackPressed();

        verify(mockRouter).exit();
        verifyNoMoreInteractions(mockViewState, mockGetExercises, mockRouter, mockExerciseModelMapper);
    }

    @Test
    public void shouldUnsubscribeInteractor_onDestroy() {
        presenter.onDestroy();

        verify(mockGetExercises).unsubscribe();
        verifyNoMoreInteractions(mockViewState, mockGetExercises, mockRouter, mockExerciseModelMapper);
    }

    private List<Exercise> createFakeExercises() {
        List<Exercise> exercises = new ArrayList<>(EXERCISE_COUNT);
        for (int i = 0; i < EXERCISE_COUNT; i++) {
            exercises.add(new Exercise());
        }

        return exercises;
    }

    private List<ExerciseModel> createFakeExerciseModels() {
        List<ExerciseModel> exerciseModels = new ArrayList<>(EXERCISE_COUNT);
        for (int i = 0; i < EXERCISE_COUNT; i++) {
            exerciseModels.add(new ExerciseModel());
        }

        return exerciseModels;
    }

}


text:
include Warden::Test::Helpers

module FeatureHelpers
  def login
    user = FactoryGirl.create(:user)
    login_as user, scope: :user
    user
  end
end

RSpec.configure do |config|
  config.include FeatureHelpers, type: :feature
end


text:
using System;

[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = true)]
public class SoftUniAttribute : Attribute
{
    public SoftUniAttribute(string name)
    {
        this.Name = name;
    }

    public string Name { get; set; }
}


text:
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web.Mvc;

namespace DancingGoat.Tests.Extensions
{
    /// <summary>
    /// Provides a set of static methods for testing controllers.
    /// </summary>
    public static class ControllerTestsExtensions
    {
        /// <summary>
        /// Validates specified model and sets ModelState errors if the model is invalid.
        /// </summary>
        /// <typeparam name="TController">The type of controller whose view utilizes model to be validated.</typeparam>
        /// <typeparam name="TViewModel">The type of view model to be validated.</typeparam>
        /// <param name="controller">The view result test.</param>
        /// <param name="viewModelToValidate">View model to be validated.</param>
        /// <remarks>
        /// This method validates specified model with respect to member data annotations and sets ModelState errors if the model is invalid.
        /// </remarks>
        public static void ValidateViewModel<TViewModel, TController>(this TController controller, TViewModel viewModelToValidate) where TController : Controller
        {
            var validationContext = new ValidationContext(viewModelToValidate, null, null);
            var validationResults = new List<ValidationResult>();

            Validator.TryValidateObject(viewModelToValidate, validationContext, validationResults, true);

            foreach (var validationResult in validationResults)
            {
                controller.ModelState.AddModelError(validationResult.MemberNames.FirstOrDefault() ?? string.Empty, validationResult.ErrorMessage);
            }
        }
    }
}


text:
from django.views.generic import TemplateView
from django.conf import settings
from .forms import DemoForm

class Index(TemplateView):
    template_name = 'demo/index.html'

class DemoBase(TemplateView):
    form_class = DemoForm
    form_1 = None
    form_2 = None
    form_3 = None

    def get(self, request, *args, **kwargs):
        self.form_1 = self.form_class(prefix='form_1')
        self.form_2 = self.form_class(prefix='form_2')
        self.form_3 = self.form_class(prefix='form_3')
        return super(DemoBase, self).get(request, *args, **kwargs)

    def post(self, request, *args, **kwargs):
        self.form_1 = self.form_class(prefix='form_1', data=request.POST)
        self.form_2 = self.form_class(prefix='form_2', data=request.POST)
        self.form_3 = self.form_class(prefix='form_3', data=request.POST)

        self.form_1.is_valid()
        self.form_2.is_valid()
        self.form_3.is_valid()

        return self.render_to_response(self.get_context_data())

    def get_context_data(self, **kwargs):
        context = super(DemoBase, self).get_context_data(**kwargs)
        context['form_1'] = self.form_1
        context['form_2'] = self.form_2
        context['form_3'] = self.form_3
        return context

class DemoBootstrap3(DemoBase):
    template_name = 'demo/demo_bootstrap_3.html'

    def __init__(self, *args, **kwargs):
        # For this case we must set DJANGO_POPUP_VIEW_FIELD_TEMPLATE_PACK
        settings.DJANGO_POPUP_VIEW_FIELD_TEMPLATE_PACK = 'bootstrap3'
        super(DemoBootstrap3, self).__init__(*args, **kwargs)

class DemoBootstrap4(DemoBase):
    template_name = 'demo/demo_bootstrap_4.html'

    def __init__(self, *args, **kwargs):
        # This is a hack.
        # For this case we must override
        # CRISPY_TEMPLATE_PACK settings
        settings.CRISPY_TEMPLATE_PACK = 'bootstrap4'
        # For this case we must set DJANGO_POPUP_VIEW_FIELD_TEMPLATE_PACK
        # This view show howe django_popup working with bootstrap4
        # If you use bootstrap4 you should set 'bootstrap4' as a value
        # of DJANGO_POPUP_VIEW_FIELD_TEMPLATE_PACK in settings.py
        settings.DJANGO_POPUP_VIEW_FIELD_TEMPLATE_PACK = 'bootstrap4'
        super(DemoBootstrap4, self).__init__(*args, **kwargs)


text:
package org.javers.core.diff.appenders;

import org.javers.common.collections.Sets;
import org.javers.common.exception.JaversExceptionCode;
import org.javers.core.diff.NodePair;
import org.javers.core.diff.changetype.container.*;
import org.javers.core.metamodel.object.*;
import org.javers.core.metamodel.property.Property;
import org.javers.core.metamodel.type.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.*;

/**
 * @author pawel szymczyk
 */
class SetChangeAppender extends CorePropertyChangeAppender<SetChange> {

    private static final Logger logger = LoggerFactory.getLogger(SetChangeAppender.class);

    private final TypeMapper typeMapper;

    private final GlobalIdFactory globalIdFactory;

    SetChangeAppender(TypeMapper typeMapper, GlobalIdFactory globalIdFactory) {
        this.typeMapper = typeMapper;
        this.globalIdFactory = globalIdFactory;
    }

    @Override
    public boolean supports(JaversType propertyType) {
        return propertyType instanceof SetType;
    }

    private boolean isSupportedContainer(Property property) {
        ContainerType propertyType = typeMapper.getPropertyType(property);

        if (typeMapper.isValueObject(propertyType.getItemType())) {
            logger.error("could not diff " + property +", "+
                         JaversExceptionCode.SET_OF_VO_DIFF_NOT_IMPLEMENTED.getMessage() );
            return false;
        }
        return true;
    }

    private List<ContainerElementChange> calculateEntryChanges(SetType setType, Set leftRawSet, Set rightRawSet, OwnerContext owner) {

        JaversType itemType = typeMapper.getJaversType(setType.getItemType());
        DehydrateContainerFunction dehydrateFunction = new DehydrateContainerFunction(itemType, globalIdFactory);

        if (Objects.equals(leftRawSet, rightRawSet)) {
            return Collections.EMPTY_LIST;
        }

        Set<GlobalId> leftSet = (Set) setType.map(leftRawSet, dehydrateFunction, owner);
        Set<GlobalId> rightSet = (Set) setType.map(rightRawSet, dehydrateFunction, owner);

        List<ContainerElementChange> changes = new ArrayList<>();

        for (Object globalCdoId : Sets.difference(leftSet, rightSet)) {
            changes.add(new ValueRemoved(globalCdoId));
        }
        for (Object globalCdoId : Sets.difference(rightSet, leftSet)) {
            changes.add(new ValueAdded(globalCdoId));
        }

        return changes;
    }

    @Override
    public SetChange calculateChanges(NodePair pair, Property property) {
        Set leftValues = (Set) pair.getLeftPropertyValue(property);
        Set rightValues = (Set) pair.getRightPropertyValue(property);

        if (!isSupportedContainer(property)) {
            return null; //TODO ADD SUPPORT
        }

        SetType setType = typeMapper.getPropertyType(property);
        OwnerContext owner = new OwnerContext(pair.getGlobalId(), property.getName());
        List<ContainerElementChange> entryChanges =
                calculateEntryChanges(setType, leftValues, rightValues, owner);

        if (!entryChanges.isEmpty()) {
            return new SetChange(pair.getGlobalId(), property.getName(), entryChanges);
        } else {
            return null;
        }
    }
}


text:
            NASA - Flickr Gallery

        <md-input-container md-no-float class="md-block">
            <md-icon md-svg-src="img/svg/search.svg"></md-icon>
            <input ng-model="search.title" type="text" placeholder="SEARCH">
        </md-input-container>

        Searching for: {{search.title}}

    <md-button class="md-fab md-primary md-hue-2" aria-label="previous" ng-click="goBack()">
        <md-icon md-svg-src="img/svg/back.svg"></md-icon>
    </md-button>

        PAGE {{currentPage}}

    <md-button class="md-fab md-primary md-hue-2" aria-label="next" ng-click="goNext()">
        <md-icon md-svg-src="img/svg/next.svg"></md-icon>
    </md-button>

    <md-card ng-repeat="photo in photos | filter:search">
        <display-photo ng-click="openImage(photo, $event)" photo="photo"></display-photo>
    </md-card>


text:
Different methods for loading a chart with Turbolinks support

  You should test these in Firefox. In Chrome, each link click triggers a full page reload if running from localhost (which defeats the purpose of Turbolinks, and doesn't present the bug).

One statement: anonymous function in callback

Three statements; load packages, set callback, define function. The first statement crashes.

Two statements; load packages with callback defined, define function.


text:
/**
 * Modified copy of:
 * remy sharp / http://remysharp.com
 * Twitter / @rem
 * http://remysharp.com/2007/05/18/add-twitter-to-your-blog-step-by-step/
 *
 * Changes:
 *  - Removed relative time
 *  - Don't display tags
 *  - Added filter option
 *  - Template is required
 *
 * @params
 *   cssIdOfContainer: e.g. twitters
 *   options:
 *       {
 *           id: {String} username,
 *           count: {Int} 1-20, defaults to 1 - max limit 20
             filter {Regex}: Used to select which tweets to display.
 *           prefix: {String} '%name% said', defaults to blank
 *           clearContents: {Boolean} true, removes contents of element specified in cssIdOfContainer, defaults to true
 *           ignoreReplies: {Boolean}, skips over tweets starting with '@', defaults to false
 *           template: {String} HTML template to use for LI element (see URL above for examples), defaults to predefined template
 *           newwindow {Boolean} opens links in new window, defaults to false
 *           timeout: {Int} How long before triggering onTimeout, defaults to 10 seconds if onTimeout is set
 *           onTimeoutCancel: {Boolean} Completely cancel twitter call if timedout, defaults to false
 *           onTimeout: {Function} Function to run when the timeout occurs. Function is bound to element specified with
 *           cssIdOfContainer (i.e. 'this' keyword)
 *           callback: {Function} Callback function once the render is complete, doesn't fire on timeout
 *
 *       }
 *
 * @license MIT (MIT-LICENSE.txt)
 * @version 1.13.3 - ify now supports lists
 * @date $Date$
 */

// to protect variables from resetting if included more than once
if (typeof renderTwitters != 'function') (function () {
    /** Private variables */

    // only used for the DOM ready, since IE & Safari require special conditions
    var browser = (function() {
        var b = navigator.userAgent.toLowerCase();

        // Figure out what browser is being used
        return {
            webkit: /(webkit|khtml)/.test(b),
            opera: /opera/.test(b),
            msie: /msie/.test(b) && !(/opera/).test(b),
            mozilla: /mozilla/.test(b) && !(/(compatible|webkit)/).test(b)
        };
    })();

    var guid = 0;
    var readyList = [];
    var isReady = false;

    /** Global functions */

    // based on Dustin Diaz's ify, but with my fixes :-)
    window.ify = function() {
      var entities = {
          '"' : '"',
          '&' : '&',
          '<' : '<',
          '>' : '>'
      };

      return {
        "link": function(t) {
          return t.replace(/[a-z]+:\/\/[a-z0-9-_]+\.[a-z0-9-_:~%&\?#\/.=]+[^:\.,\)\s*$]/ig, function(m) {
            return '' + ((m.length > 25) ? m.substr(0, 24) + '...' : m) + '';
          });
        },
        "at": function(t) {
          return t.replace(/(^|[^\w]+)\@([a-zA-Z0-9_]{1,15}(\/[a-zA-Z0-9-_]+)*)/g, function(m, m1, m2) {
            return m1 + '@' + m2 + '';
          });
        },
        "hash": function(t) {
          return t.replace(/(^|[^&\w'"]+)\#([a-zA-Z0-9_]+)/g, function(m, m1, m2) {
            return '';
          });
        },
        "clean": function(tweet) {
          return this.hash(this.at(this.link(tweet)));
        }
      };
    }();

    // to create a public function within our private scope, we attach the
    // the function to the window object
    window.renderTwitters = function (obj, options) {
        // private shortcuts
        function node(e) {
            return document.createElement(e);
        }

        function text(t) {
            return document.createTextNode(t);
        }

        var target = document.getElementById(options.twitterTarget);
        var data = null;
        var ul = node('ul'), li, statusSpan, timeSpan, i, max = obj.length > options.count ? options.count : obj.length;

        for (i = 0, numRendered = 0; numRendered < max && obj[i]; i++) {
            data = getTwitterData(obj[i]);

            if (options.ignoreReplies && obj[i].text.substr(0, 1) == '@') {
                continue; // skip
            }

            if(data["text"].match(options.filter) == null)
                continue; //Filtered out

            numRendered++;
            li = node('li');

            li.innerHTML = options.template.replace(/%([a-z_\-\.]*)%/ig, function (m, l) {
                var r = data[l] + "" || "";
                if (l == 'text') r = ify.clean(r);
                return r;
            });

            if (options.newwindow) {
                li.innerHTML = li.innerHTML.replace(/<a href/gi, '<a target="_blank" href');
            }

            ul.appendChild(li);
        }

        if (options.clearContents) {
            while (target.firstChild) {
                target.removeChild(target.firstChild);
            }
        }

        target.appendChild(ul);

        if (typeof options.callback == 'function') {
            options.callback();
        }
    };

    window.getTwitters = function (target, id, count, options) {
        guid++;

        if (typeof id == 'object') {
            options = id;
            id = options.id;
            count = options.count;
        }

        // defaulting options
        if (!count) count = 1;

        if (options) {
            options.count = count;
        } else {
            options = {};
        }

        if (!options.timeout && typeof options.onTimeout == 'function') {
            options.timeout = 10;
        }

        if (typeof options.clearContents == 'undefined') {
            options.clearContents = true;
        }

        // need to make these global since we can't pass in to the twitter callback
        options['twitterTarget'] = target;

        // default enable links
        if (typeof options.enableLinks == 'undefined') options.enableLinks = true;

        // this looks scary, but it actually allows us to have more than one twitter
        // status on the page, which in the case of my example blog - I do!
        window['twitterCallback' + guid] = function (obj) {
            if (options.timeout) {
                clearTimeout(window['twitterTimeout' + guid]);
            }
            renderTwitters(obj, options);
        };

        // check out the mad currying!
        ready((function(options, guid) {
            return function () {
                // if the element isn't on the DOM, don't bother
                if (!document.getElementById(options.twitterTarget)) {
                    return;
                }

                var url = 'http://www.twitter.com/statuses/' + (options.withFriends ? 'friends_timeline' : 'user_timeline') + '/' + id + '.json?callback=twitterCallback' + guid + '&count=20&cb=' + Math.random();

                if (options.timeout) {
                    window['twitterTimeout' + guid] = setTimeout(function () {
                        // cancel callback
                        if (options.onTimeoutCancel) window['twitterCallback' + guid] = function () {};
                        options.onTimeout.call(document.getElementById(options.twitterTarget));
                    }, options.timeout * 1000);
                }

                var script = document.createElement('script');
                script.setAttribute('src', url);
                document.getElementsByTagName('head')[0].appendChild(script);
            };
        })(options, guid));
    };

    // GO!
    DOMReady();

    /** Private functions */

    function getTwitterData(orig) {
        var data = orig, i;
        for (i in orig.user) {
            data['user_' + i] = orig.user[i];
        }

        data.time = toDate(orig.created_at);

        return data;
    }

    function ready(callback) {
        if (!isReady) {
            readyList.push(callback);
        } else {
            callback.call();
        }
    }

    function fireReady() {
        isReady = true;
        var fn;
        while (fn = readyList.shift()) {
            fn.call();
        }
    }

    // ready and browser adapted from John Resig's jQuery library (http://jquery.com)
    function DOMReady() {
        if ( document.addEventListener && !browser.webkit ) {
            document.addEventListener( "DOMContentLoaded", fireReady, false );
        } else if ( browser.msie ) {
            // If IE is used, use the excellent hack by Matthias Miller
            // http://www.outofhanwell.com/blog/index.php?title=the_window_onload_problem_revisited

            // Only works if you document.write() it
            document.write("<scr" + "ipt id=__ie_init defer=true src=//:><\/script>");

            // Use the defer script hack
            var script = document.getElementById("__ie_init");

            // script does not exist if jQuery is loaded dynamically
            if (script) {
                script.onreadystatechange = function() {
                    if ( this.readyState != "complete" ) return;
                    this.parentNode.removeChild( this );
                    fireReady.call();
                };
            }

            // Clear from memory
            script = null;

        } else if ( browser.webkit ) {
            // Continually check to see if the document.readyState is valid
            var safariTimer = setInterval(function () {
                // loaded and complete are both valid states
                if ( document.readyState == "loaded" ||
                document.readyState == "complete" ) {

                    // If either one are found, remove the timer
                    clearInterval( safariTimer );
                    safariTimer = null;
                    // and execute any waiting functions
                    fireReady.call();
                }
            }, 10);
        }
    }

    function toDate(time_value)
    {
      var values = time_value.split(" ");
      var parsed_date = Date.parse(values[1] + " " + values[2] + ", " + values[5] + " " + values[3]);
      var date = new Date(parsed_date);
        return "" + date.getFullYear() + "-" + (date.getMonth()+1) + "-" + date.getDate();
    }
})();


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

<beans
 xmlns="http://www.springframework.org/schema/beans"
 xmlns:context="http://www.springframework.org/schema/context"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xsi:schemaLocation="
     http://www.springframework.org/schema/beans   http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
     http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd
     ">

  <context:annotation-config />

  <!--
    WicketTester does setName, which should only be called once for a the WicketApplication.
    To allow it to be built by Spring, either use @DirtiesContext everywhere,
    so that spring context is built for each test anew, or make WicketApplication
    a prototype, so that only that is built again for each getBean().
    -->
  <bean id="wicketApplication"
      class="nl.xs4all.banaan.tap.web.WicketApplication"
      scope="prototype"  />

  <bean id="fakeTapExchangeDao"
      class="nl.xs4all.banaan.tap.svc.FakeTapExchangeDao" />

</beans>


text:
COMPONENT_TARGETS  = $(TOOLCHAIN_S805_GLIBC)

include ../../../../../build-system/config.mk

SOURCE_REQUIRES = sources/Linux/Amlogic/M201

ifneq ($(filter $(TOOLCHAIN_VERSION),1.1.1),)
REQUIRES  = core/gcc/5.3.0^static
endif

# ======= __END_OF_REQUIRES__ =======

tar_xz_archive  = $(SRC_PACKAGE_PATH)/Linux/Amlogic/M201/linux-aml-3.10.33-20150117.tar.xz
SRC_ARCHIVE     = $(tar_xz_archive)
SRC_DIR         = $(TARGET_BUILD_DIR)/linux-aml-3.10.33-20150117
src_done        = $(TARGET_BUILD_DIR)/.source-done

sysroot_dir     = $(TOOLCHAIN_PATH)/$(TARGET)/sys-root

headers_target  = $(TARGET_BUILD_DIR)/.headers-installed

ifneq ($(findstring s805, $(TOOLCHAIN)),)
arch = arm
endif

BUILD_TARGETS = $(headers_target)

include ../../../../../build-system/core.mk

$(src_done): $(SRC_ARCHIVE) $(PATCHES_DEP)
	$(UNPACK_SRC_ARCHIVE)
	@touch $@

$(SRC_DIR)/include/generated/uapi/linux/version.h: $(src_done)
	@touch $(SRC_DIR)/.config
	@$(MAKE) -C $(SRC_DIR) \
	  ARCH=$(arch) CROSS_COMPILE=$(TOOLCHAIN_PATH)/bin/$(TARGET)- \
	  include/generated/uapi/linux/version.h

$(sysroot_dir)/usr/include/linux/autoconf.h: $(SRC_DIR)/include/generated/uapi/linux/version.h
	@$(MAKE) -C $(SRC_DIR) headers_install                        \
	  ARCH=$(arch) CROSS_COMPILE=$(TOOLCHAIN_PATH)/bin/$(TARGET)- \
	  INSTALL_HDR_PATH=$(sysroot_dir)/usr
	@touch $@

$(headers_target): $(sysroot_dir)/usr/include/linux/autoconf.h
	@( cd $(sysroot_dir)/usr/include ; \
	   for file in `find . -name *.install*` ; do \
	     rm -f $$file ; \
	   done ; \
	 )
	@echo "$(subst $(TOP_BUILD_DIR_ABS)/,,$(CURDIR)):headers" >> $(TOOLCHAIN_PATH)/components.txt
	@touch $@


text:
This sample uses [JSPM](http://jspm.io/) to load up dependent components (react, WinJS, react-winjs).

## To run this sample:

1. Copy the `../../WinJSBrowserHistory.js` or link to this directory (if on linux/mac) `ln -s ../../WinJSBrowserHistory.js .`
2. Host this folder in a simple static web server and load up `index.html`. (I have used [nws](https://www.npmjs.com/package/nws))


text:
local lspconfig  = require'lspconfig'
-- local diagnostic = require'diagnostic'

-- ViM specific settings
vim.o.completeopt = "noinsert,menuone,noselect"
vim.o.pumheight   = 12

-- vim.lsp.callbacks["textDocument/publishDiagnostics"] = function() end

-- Add additional capabilities supported by nvim-cmp

local capabilities = vim.lsp.protocol.make_client_capabilities()
capabilities.textDocument.completion.completionItem.documentationFormat     = { 'markdown', 'plaintext' }
capabilities.textDocument.completion.completionItem.snippetSupport          = true
capabilities.textDocument.completion.completionItem.preselectSupport        = true
capabilities.textDocument.completion.completionItem.insertReplaceSupport    = true
capabilities.textDocument.completion.completionItem.labelDetailsSupport     = true
capabilities.textDocument.completion.completionItem.deprecatedSupport       = true
capabilities.textDocument.completion.completionItem.commitCharactersSupport = true
capabilities.textDocument.completion.completionItem.tagSupport              = { valueSet = { 1 } }
capabilities.textDocument.completion.completionItem.resolveSupport          = {
properties = {
'documentation',
'detail',
'additionalTextEdits',
},
}

-- capabilities = require('cmp_nvim_lsp').update_capabilities(capabilities)
-- local capabilities = require('cmp_nvim_lsp').update_capabilities(vim.lsp.protocol.make_client_capabilities())

-- vim.lsp.handlers["textDocument/publishDiagnostics"] = vim.lsp.with(
-- vim.lsp.diagnostic.on_publish_diagnostics, {
--     underline    = true,
--     signs        = true,
--     virtual_text = false,
--     float = {
--         show_header = true,
--         source      = 'if_many',
--         border      = 'rounded',
--         focusable   = false,
--     },
--     show_diagnostic_autocmds = { 'InsertLeave', 'TextChanged' },
--     update_in_insert = false,
--     severity_sort    = false,
-- }
-- )

vim.diagnostic.config({
    underline    = true,
    signs        = true,
    virtual_text = true,
    float = {
        show_header = true,
        source      = 'always',
        border      = 'rounded',
        focusable   = false,
    },
    show_diagnostic_autocmds = { 'InsertLeave', 'TextChanged' },
    update_in_insert = false,
    severity_sort    = false,
})

local on_attach = function(_, bufnr)

  -- don't enable omnifunc for nvim-compe plugin
  -- vim.api.nvim_buf_set_option(bufnr, 'omnifunc', 'v:lua.vim.lsp.omnifunc')

  -- lsp_status.register_progress()

  -- require "lsp_signature".on_attach({
  --   bind            = true,
  --   doc_lines       = 0,
  --   floating_window = true,
  --   hint_enable     = true,
  --   hi_parameter    = "LSPSignatureCurParam",
  --   hint_scheme     = "LSPSignatureHint",
  --   hint_prefix     = "🐼 ",
  --   handler_opts    = {
  --     border = "single"
  --   }
  -- })

  -- Mappings
  local function buf_set_keymap(...) vim.api.nvim_buf_set_keymap(bufnr, ...) end
  local opts = { noremap=true, silent=true  }

  buf_set_keymap('n','gD','<cmd>lua vim.lsp.buf.declaration()<CR>', opts)
  buf_set_keymap('n','gd','<cmd>lua vim.lsp.buf.definition()<CR>', opts)
  buf_set_keymap('n','K','<cmd>lua vim.lsp.buf.hover()<CR>', opts)
  buf_set_keymap('n','gR','<cmd>lua vim.lsp.buf.rename()<CR>', opts)
  -- buf_set_keymap('n','gr','<cmd>lua vim.lsp.buf.references()<CR>', opts)
  buf_set_keymap('n','gs','<cmd>lua vim.lsp.buf.signature_help()<CR>', opts)
  buf_set_keymap('n','gi','<cmd>lua vim.lsp.buf.implementation()<CR>', opts)
  buf_set_keymap('n','gt','<cmd>lua vim.lsp.buf.type_definition()<CR>', opts)
  buf_set_keymap('n','<leader>gw','<cmd>lua vim.lsp.buf.document_symbol()<CR>', opts)
  buf_set_keymap('n','<leader>gW','<cmd>lua vim.lsp.buf.workspace_symbol()<CR>', opts)
  buf_set_keymap('n','<leader>ah','<cmd>lua vim.lsp.buf.hover()<CR>', opts)
  -- buf_set_keymap('n','<leader>af','<cmd>lua vim.lsp.buf.code_action()<CR>', opts)
  buf_set_keymap('n','<leader>ee','<cmd>lua vim.diagnostic.open_float(0, { scope="line" })<CR>', opts)
  buf_set_keymap('n','<leader>ar','<cmd>lua vim.lsp.buf.rename()<CR>', opts)
  buf_set_keymap('n','<leader>=', '<cmd>lua vim.lsp.buf.formatting()<CR>', opts)
  buf_set_keymap('n','<leader>ai','<cmd>lua vim.lsp.buf.incoming_calls()<CR>', opts)
  buf_set_keymap('n','<leader>ao','<cmd>lua vim.lsp.buf.outgoing_calls()<CR>', opts)

  -- vim.cmd [[ nnoremap gR :lua require'lspactions'.rename()<CR> ]]

  -- vim.lsp.handlers["textDocument/hover"] = vim.lsp.with(vim.lsp.handlers.hover, {border = "single"})
  -- vim.lsp.handlers["textDocument/signatureHelp"] = vim.lsp.with(vim.lsp.handlers.signature_help, {border = "single"})
  -- vim.lsp.handlers["textDocument/declaration"] = vim.lsp.with(vim.lsp.handlers.declaration, {border = "single"})
  -- vim.lsp.handlers["textDocument/definition"] = vim.lsp.with(vim.lsp.handlers.definition, {border = "single"})

  vim.lsp.handlers["textDocument/codeAction"] = require'lspactions'.codeaction
  vim.cmd [[ nnoremap <leader>ca :lua require'lspactions'.code_action()<CR> ]]

  vim.lsp.handlers["textDocument/references"] = require'lspactions'.references
  vim.cmd [[ nnoremap gr :lua vim.lsp.buf.references()<CR> ]]

  vim.lsp.handlers["textDocument/definition"] = require'lspactions'.definition
  vim.cmd [[ nnoremap gd :lua vim.lsp.buf.definition()<CR> ]]

  vim.lsp.handlers["textDocument/declaration"] = require'lspactions'.declaration
  vim.cmd [[ nnoremap gD :lua vim.lsp.buf.declaration()<CR> ]]

  vim.lsp.handlers["textDocument/implementation"] = require'lspactions'.implementation
  vim.cmd [[ nnoremap gi :lua vim.lsp.buf.implementation()<CR> ]]

  vim.lsp.handlers["textDocument/hover"] =
  vim.lsp.with(vim.lsp.handlers.hover, {
    -- Use a sharp border with `FloatBorder` highlights
    border = "single",
  })

  -- enable border for signature
  vim.lsp.handlers["textDocument/signatureHelp"] = vim.lsp.with(
  vim.lsp.handlers.signature_help,
  {
    border = "single",
  })

end

-- jedi_language_server
local servers = {'jedi_language_server', 'bashls', 'vimls'}
for _, lsp in ipairs(servers) do
  lspconfig[lsp].setup {
    on_attach = on_attach,
    capabilities = capabilities,
    init_options = {
    },

  flags = {
    debounce_text_changes = 150,
  };

  }
end

lspconfig.gopls.setup {
  cmd = {'gopls'},
  capabilities = capabilities,
  settings = {
    gopls =     {
      experimentalPostfixCompletions = true,
      analyses = {
      unusedparams = true,
      shadow       = true,
    },
    staticcheck = true,
    },
  },
on_attach = on_attach,
}

-- lspconfig.clangd.setup {
--   on_attach = on_attach,
--   capabilities = capabilities,
--   cmd = {
--     '/bin/clangd', '--background-index', '--header-insertion=iwyu', '--suggest-missing-includes', '--cross-file-rename', '--completion-style=detailed', '--pch-storage=memory', '--header-insertion-decorators', '--all-scopes-completion'
--   };

--   filetypes = { "c", "cpp", "objc", "objcpp" };

--   flags = {
--     debounce_text_changes = 150,
--   };

--   init_options = {
--     clangdFileStatus     = true,
--     usePlaceholders      = false,
--     completeUnimported   = true,
--     semanticHighlighting = true
--   };

--   completion = {
--     detailedLabel = false;
--     placeholder   = false;
--     detail = false;
--     -- spellChecking = true;
--     -- filterAndSort = false;
--   };
-- }

-- placeholder option will only work in recent (after 7-Oct-2019)
lspconfig.ccls.setup {
  on_attach = on_attach,
  capabilities = capabilities,
  cmd = { 'ccls' };
  init_options = {
    cache = {
      directory    = vim.env.HOME.."/.ccls-cache";
      cacheFormat  = "json",
      rootPatterns = {"compile_commands.json", ".prettierrc.json", ".ccls", ".git/", ".svn/", ".hg/"},
      clang = {
        -- extraArgs   = {"-fms-extensions", "-fms-compatibility", "-f1elayed-template-parsing"},
        extraArgs   = {'--header-insertion=iwyu', '--suggest-missing-includes', '--cross-file-rename', '--completion-style=detailed', '--pch-storage=memory', '--header-insertion-decorators', '--all-scopes-completion'},
        -- excludeArgs = {},
      },
    },

    flags = {
      debounce_text_changes = 150,
    };

    codeLens = {
      localVariables = true;
    },

    client = {
      snippetSupport = true;
    };

    completion = {
      placeholder   = true;
      detailedLabel = false;
      spellChecking = true;
      -- filterAndSort = false;
    };
    index = {
      onChange        = false,
      trackDependency = 1
    },
  }
}

-- sumneko lua server
-- set the path to the sumneko installation; if you previously installed via the now deprecated :LspInstall, use
local system_name = "Linux" -- (Linux, macOS, or Windows)
local sumneko_root_path = vim.env.HOME..'/ppcport/git/lua-language-server'
local sumneko_binary = sumneko_root_path.."/bin/"..system_name.."/lua-language-server"
require('lspconfig').sumneko_lua.setup({
  capabilities = capabilities,
  cmd = {sumneko_binary, "-E", sumneko_root_path .. "/main.lua"};
  -- An example of settings for an LSP server.
  --    For more options, see nvim-lspconfig
  settings = {
    Lua = {
      runtime = {
        -- Tell the language server which version of Lua you're using (most likely LuaJIT in the case of Neovim)
        version = 'LuaJIT',
        -- Setup your lua path
        path = vim.split(package.path, ';'),
      },

      diagnostics = {
        -- Get the language server to recognize the `vim` global
        globals = {'vim'},
      },

      workspace = {
        -- Make the server aware of Neovim runtime files
        library = {
          [vim.fn.expand('$VIMRUNTIME/lua')] = true,
          [vim.fn.expand('$VIMRUNTIME/lua/vim/lsp')] = true,
        },
      },
    }
  },
  -- on_attach = on_attach
})

vim.fn.sign_define("LspDiagnosticsSignError", {text = ""})
vim.fn.sign_define("LspDiagnosticsSignWarning", {text = ""})
vim.fn.sign_define("LspDiagnosticsSignInformation", {text = ""})
vim.fn.sign_define("LspDiagnosticsSignHint", {text = ""})

-- End of File


text:
import unittest
from app import create_app, db
from app.mod_auth.models import UserAccount, UserAccountStatus, UserProfile
from sqlalchemy.exc import IntegrityError
from flask import url_for
from datetime import datetime
from flask_testing import TestCase

class ContextTestCase(TestCase):
    render_templates = True

    def create_app(self):
        app = create_app("testing")
        app.config['PRESERVE_CONTEXT_ON_EXCEPTION'] = False
        return app

    def _pre_setup(self):
        self.app = create_app('testing')
        self.client = self.app.test_client()

    def __call__(self, result=None):
        try:
            self._pre_setup()
            super(ContextTestCase, self).__call__(result)
        finally:
            self._post_teardown()

    def _post_teardown(self):
        if getattr(self, '_ctx', None) and self._ctx is not None:
            self._ctx.pop()
            del self._ctx

class BaseTestCase(ContextTestCase):
    """
    Base test case for application
    """

    def setUp(self):
        self.app_context = self.app.app_context()
        self.app_context.push()
        self.db = db

        db.create_all()

        self.create_user_accounts()
        # self.add_story()

        db.session.commit()

    def tearDown(self):
        db.session.remove()
        db.drop_all()
        self.app_context.pop()

    @staticmethod
    def create_user_accounts():
        """
        Creates new users for testing follow feature
        :return: 2 new unique users to test follow and unfollow feature
        """

        user_account1 = UserProfile(first_name="test1", last_name="hadithi1",
                                    email="test1hadithi@hadithi.com")

        user_account2 = UserProfile(first_name="test2", last_name="hadithi2",
                                    email="test2hadithi@hadithi.com")

        user_account3 = UserProfile(first_name="Guy De", last_name="Maupassant",
                                    email="guydemaupassant@hadithi.com")

        user_account4 = UserProfile(first_name="brian", last_name="lusina",
                                    email="lusinabrian@hadithi.com")
        try:
            db.session.add(user_account1)
            db.session.add(user_account2)
            db.session.add(user_account3)
            db.session.add(user_account4)
            db.session.commit()
        except IntegrityError as ie:
            print("Integrity Error: ", ie)
            db.session.rollback()

        return user_account1, user_account2, user_account3, user_account4

    def login(self):
        """
        Login in the user to the testing app
        :return: The authenticated user for the test app
        """
        return self.client.post(
            "auth/login",
            data=dict(email='guydemaupassant@hadithi.com', password='password', confirm='password'),
            follow_redirects=True
        )

        # def add_story(self):
        #     """
        #     Adds a dummy story to the database
        #     :return:
        #     """
        #     user_account1, user_account2, user_account3, user_account4 = self.create_user_accounts()
        #     story = Story.query.filter_by(user_account_id=user_account1.id).first()
        #     if story is None:
        #         try:
        #             story = Story(title="Gotham in flames", tagline="Dark city catches fire",
        #                           category="Fiction", content="", user_account_id=user_account1.id)
        #             db.session.add(story)
        #         except IntegrityError as e:
        #             print(e)
        #             db.session.rollback()
        #     return story
        #
        # def save_user_story(self, story_id):
        #     return self.client.get(
        #         url_for("story.save_story", app_id=story_id),
        #         follow_redirects=True)

if __name__ == "__main__":
    unittest.main()


text:
using System;
using Azure.Core;

namespace Azure.ResourceManager.Sql.Models
{
    /// <summary> A managed server DNS alias acquisition request. </summary>
    public partial class ManagedServerDnsAliasAcquisition
    {
        /// <summary> Initializes a new instance of ManagedServerDnsAliasAcquisition. </summary>
        /// <param name="oldManagedServerDnsAliasResourceId"> The resource ID of the managed server DNS alias that will be acquired to point to this managed server instead. </param>
        /// <exception cref="ArgumentNullException"> <paramref name="oldManagedServerDnsAliasResourceId"/> is null. </exception>
        public ManagedServerDnsAliasAcquisition(ResourceIdentifier oldManagedServerDnsAliasResourceId)
        {
            Argument.AssertNotNull(oldManagedServerDnsAliasResourceId, nameof(oldManagedServerDnsAliasResourceId));

            OldManagedServerDnsAliasResourceId = oldManagedServerDnsAliasResourceId;
        }

        /// <summary> The resource ID of the managed server DNS alias that will be acquired to point to this managed server instead. </summary>
        public ResourceIdentifier OldManagedServerDnsAliasResourceId { get; }
    }
}