text:
package sproto;

import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.function.Supplier;

public class Decoder {

    private static final Charset UTF8 = Charset.forName("utf-8");
    private int fn;
    private final ByteBuffer data;
    private List<SprotoField> fields;

    public Decoder(ByteBuffer data) {
        this.data = data;
        fields = new LinkedList<>();
        data.order(ByteOrder.LITTLE_ENDIAN);
        readHeader();
    }

    class SprotoField implements Comparable<SprotoField> {
        final int tag;
        final boolean isChunk;
        final long val;

        SprotoField(int tag, boolean isChunk, long val) {
            this.tag = tag;
            this.isChunk = isChunk;
            this.val = val;
        }

        @Override
        public int compareTo(SprotoField o) {
            return Integer.compare(tag, o.tag);
        }
    }

    public List<SprotoField> readHeader() {
        fn = data.getShort() & 0x0000ffff;
        fields = new ArrayList<>(fn);
        int tag = 0;
        for (int i = 0; i < fn; i++) {
            int v = data.getShort() & 0x0000ffff;
            if (v % 2 != 0) {
                tag += (v + 1) / 2;
                continue;
            }
            int val = 0;
            if (v != 0) {
                val = v / 2 - 1;
            }
            fields.add(new SprotoField(tag, v == 0, val));
            tag++;
        }
        fields.sort(SprotoField::compareTo);
        return fields;
    }

    public <T extends SprotoObject> List<T> readList(List<T> list, Supplier<T> factory) {
        int cSize = data.getInt();
        ByteBuffer listBuffer = slice(data, data.position(), cSize);
        data.position(data.position() + cSize);
        while (listBuffer.hasRemaining()) {
            int eleSize = listBuffer.getInt();
            Decoder dec = new Decoder(slice(listBuffer, listBuffer.position(), eleSize));
            listBuffer.position(listBuffer.position()+eleSize);
            T ins = factory.get();
            ins.decode(dec);
            list.add(ins);
        }
        return list;
    }

    public <K, T extends SprotoObject> Map<K, T> readMap(Map<K, T> map, Supplier<T> factory, Function<T, K> mapFunc) {
        int cSize = data.getInt();
        ByteBuffer listBuffer = slice(data, data.position(), cSize);
        data.position(data.position() + cSize);
        while (listBuffer.hasRemaining()) {
            int eleSize = listBuffer.getInt();
            Decoder dec = new Decoder(slice(listBuffer, listBuffer.position(), eleSize));
            T ins = factory.get();
            ins.decode(dec);
            K key = mapFunc.apply(ins);
            map.put(key, ins);
        }
        return map;
    }

    public String readString() {
        int cSize = data.getInt();
        byte[] bytes = new byte[cSize];
        data.get(bytes);
        return new String(bytes, UTF8);
    }

    public long readNumber() {
        int cSize = data.getInt();
        switch (cSize) {
            case 4:
                return data.getInt();
            case 8:
                return data.getLong();
            default:
                throw new IllegalStateException("不能解析数字");
        }
    }

    public boolean readBool(int tag) {
        for (SprotoField field : fields) {
            if (field.tag == tag) {
                return field.val != 0;
            }
        }
        return false;
    }

    public long readNumber(int tag) {
        for (SprotoField field : fields) {
            if (field.tag == tag) {
                if (field.isChunk) {
                    return readNumber();
                }
                return field.val;
            }
        }
        return 0;
    }

    public boolean[] readBooleanArray() {
        int cSize = data.getInt();
        ByteBuffer listBuffer = slice(data, data.position(), cSize);
        data.position(data.position() + cSize);
        int arrSize = listBuffer.remaining();
        boolean[] array = new boolean[arrSize];
        for (int i = 0; i < arrSize; i++) {
            array[i] = listBuffer.get() > 0;
        }
        if (listBuffer.hasRemaining()) {
            throw new IllegalStateException("解码有误");
        }
        return array;
    }
    public String[] readStringArray() {
        int cSize = data.getInt();
        ByteBuffer listBuffer = slice(data, data.position(), cSize);
        data.position(data.position() + cSize);
        List<String> list=new LinkedList<>();
        while(listBuffer.hasRemaining()){
            int strLen=listBuffer.getInt();
            byte[] bytes = new byte[strLen];
            listBuffer.get(bytes);
            list.add(new String(bytes, UTF8));
        }
        return list.toArray(new String[list.size()]);
    }

    public int[] readIntArray() {
        int cSize = data.getInt();
        ByteBuffer listBuffer = slice(data, data.position(), cSize);
        data.position(data.position() + cSize);
        int typeLen = listBuffer.get();
        if (typeLen != 4) {
            throw new IllegalStateException("不能解码");
        }
        int arrSize = listBuffer.remaining() / typeLen;
        int[] array = new int[arrSize];
        for (int i = 0; i < arrSize; i++) {
            array[i] = listBuffer.getInt();
        }
        if (listBuffer.hasRemaining()) {
            throw new IllegalStateException("解码有误");
        }
        return array;
    }

    public long[] readLongArray() {
        int cSize = data.getInt();
        ByteBuffer listBuffer = slice(data, data.position(), cSize);
        data.position(data.position() + cSize);
        int typeLen = listBuffer.get();
        if (typeLen != 8) {
            throw new IllegalStateException("不能解码");
        }
        int arrSize = listBuffer.remaining() / typeLen;
        long[] array = new long[arrSize];
        for (int i = 0; i < arrSize; i++) {
            array[i] = listBuffer.getLong();
        }
        if (listBuffer.hasRemaining()) {
            throw new IllegalStateException("解码有误");
        }
        return array;
    }

    public ByteBuffer readBinary() {
        int cSize = data.getInt();
        ByteBuffer buffer = ByteBuffer.allocate(cSize);
        data.get(buffer.array(), 0, cSize);
        return data;
    }

    public <T extends SprotoObject> T readObject(Supplier<T> factory){
        int cSize = data.getInt();
        ByteBuffer objBuffer = slice(data, data.position(), cSize);
        T obj=factory.get();
        Decoder dec = new Decoder(objBuffer);
        obj.decode(dec);
         return obj;
    }

    private static ByteBuffer slice(ByteBuffer src, int pos, int len) {
        int oldPosition = src.position();
        int oldLimit = src.limit();
        src.position(pos);
        src.limit(pos + len);
        ByteBuffer dst = src.slice();
        dst.order(ByteOrder.LITTLE_ENDIAN);
        src.position(oldPosition);
        src.limit(oldLimit);
        return dst;
    }

    public int[] tags(){
        int[] tags=new int[fields.size()];
        for (int i = 0; i < tags.length; i++) {
            tags[i]=fields.get(i).tag;
        }
        return tags;
    }

}


text:
from .base import *

DEBUG = False

# Media files
DEFAULT_FILE_STORAGE = 'storages.backends.s3boto.S3BotoStorage'
AWS_ACCESS_KEY_ID = os.environ['AWS_ACCESS_KEY_ID']
AWS_SECRET_ACCESS_KEY = os.environ['AWS_SECRET_ACCESS_KEY']
AWS_STORAGE_BUCKET_NAME = os.environ['AWS_STORAGE_BUCKET_NAME']

# Security-related settings
ALLOWED_HOSTS = ["*"]
SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https')
CSRF_COOKIE_HTTPONLY = True
X_FRAME_OPTIONS = 'DENY'

# Static asset configuration
STATIC_URL = '/static/'
STATIC_ROOT = 'staticfiles'
STATICFILES_DIRS = (os.path.join(BASE_DIR, 'static'),)

redpajama_set_name: RedPajamaGithub


text:
package com.njfsoft_utils.artpad.filters;
import android.graphics.Bitmap;

/**
 * ??????,??????????
 * @author ragnarok
 *
 */
public class BitmapFilter {
	/**
	 * ???????id
	 */
	public static final int GRAY_STYLE = 1;
	public static final int RELIEF_STYLE = 2;
	public static final int VAGUE_STYLE = 3;
	public static final int OIL_STYLE = 4;
	public static final int NEON_STYLE = 5;
	public static final int PIXELATE_STYLE = 6;
	public static final int TV_STYLE = 7;
	public static final int INVERT_STYLE = 8;
	public static final int BLOCK_STYLE = 9;
	public static final int OLD_STYLE = 10;
	public static final int SHARPEN_STYLE = 11;
	public static final int LIGHT_STYLE = 12;
	public static final int LOMO_STYLE = 13;
    public static final int WATERMARK_STYLE = 14;
    public static final int REFLECTION_STYLE = 15;
    public static final int ROUNDCORNER_STYLE = 16;
    public static final int SEPIA_STYLE = 17;
    public static final int GAUSSIAN_STYLE = 18;
    public static final int FLIP_VERTICLE_STYLE = 19;
    public static final int FLIP_HORIZONTAL_STYLE = 20;
    public static final int BOOST_STYLE = 21;
    public static final int ROTATE_STYLE = 22;
	/**
	 * ??????,
	 * @param bitmap
	 * @param styleNo
	 */
	public static Bitmap changeStyle(Bitmap bitmap, int styleNo) {
		if (styleNo == GRAY_STYLE) {
			//return changeToGray(bitmap);
			return GrayFilter.changeToGray(bitmap);
		}
		else if (styleNo == RELIEF_STYLE) {
			return ReliefFilter.changeToRelief(bitmap);
		}
		else if (styleNo == VAGUE_STYLE) {
			return VagueFilter.changeToVague(bitmap);
		}
		else if (styleNo == OIL_STYLE) {
			return OilFilter.changeToOil(bitmap);
		}
		else if (styleNo == NEON_STYLE) {
			return NeonFilter.changeToNeon(bitmap);
		}
		else if (styleNo == PIXELATE_STYLE) {
			return PixelateFilter.changeToPixelate(bitmap);
		}

		else if (styleNo == TV_STYLE) {
			return TvFilter.changeToTV(bitmap);
		}
		else if (styleNo == INVERT_STYLE) {
			return InvertFilter.chageToInvert(bitmap);
		}
		else if (styleNo == BLOCK_STYLE) {
			return BlockFilter.changeToBrick(bitmap);
		}
		else if (styleNo == OLD_STYLE) {
			return OldFilter.changeToOld(bitmap);
		}
		else if (styleNo == SHARPEN_STYLE) {
			return SharpenFilter.changeToSharpen(bitmap);
		}
		else if (styleNo == LIGHT_STYLE) {
			return LightFilter.changeToLight(bitmap);
		}
		else if (styleNo == LOMO_STYLE) {
			return LomoFilter.changeToLomo(bitmap);
		}
        else if (styleNo == REFLECTION_STYLE) {
            return ReflectionFilter.applyReflection(bitmap);
        }
        else if (styleNo == ROUNDCORNER_STYLE) {
            return RoundCornerFilter.roundCorner(bitmap, 45);
        }
        else if (styleNo == SEPIA_STYLE) {
            return SepiaFilter.getSepiaEffect(bitmap);
        }
        else if (styleNo == GAUSSIAN_STYLE) {
            return GaussianFilter.applyGaussianBlur(bitmap);
        }
        else if (styleNo == FLIP_VERTICLE_STYLE) {
            return FlipFilter.flip(bitmap, 1);
        }
        else if (styleNo == FLIP_HORIZONTAL_STYLE) {
            return FlipFilter.flip(bitmap, 2);
        }
        else if (styleNo == BOOST_STYLE) {
            return BoostFilter.boost(bitmap, 1, 150);
        }
        else if (styleNo == ROTATE_STYLE) {
            return RotateFilter.getRotatedBmp(bitmap);
        }
			return bitmap;
	}

}


text:
require_relative 'helper'

class TestVertere < Test::Unit::TestCase

  def test_compare
    num_chars = ('0'..'11').map(&:freeze).freeze

    assert_equal(["0", "10"], num_chars.grep(/0/))
    assert_equal((num_chars - ["0", "10"]), num_chars.grep(Vertere.invert(/0/)))
    assert_equal((num_chars - ["0", "10"]), num_chars.grep(/0/.for_!))
    assert_equal(false, (/0/.for_! =~ '0'))
    assert_equal(["0", "10"], num_chars.grep(/0/)) # check not bloken
    assert_equal(num_chars, num_chars.sort_by(&:to_i))
    assert_equal(num_chars.reverse, num_chars.sort_by{|s|s.to_i.for_!})
  end

  def test_methods_minimum_defined
    obj = Object.new
    assert_equal(true, obj.respond_to?(:=~))
    obj.singleton_class.class_eval do
      undef_method :=~
    end
    assert_equal(false, obj.respond_to?(:=~))
    assert_equal(false, obj.for_!.respond_to?(:=~))
  end

  def test_check_methods
    obj = Object.new
    assert_equal(false, obj.comparison_inverted?)
    assert_equal(true, obj.for_!.comparison_inverted?)
  end
end


text:
{% extends "email/base.html" %}

{% load markdown_deux_tags %}

{% block content %}
{{ content | striptags | markdown }}
{% endblock content %}


text:
package org.apache.bcel.generic;

import java.io.DataOutputStream;
import java.io.IOException;

/**
 * GOTO - Branch always (to relative offset, not absolute address)
 *
 * @version $Id$
 * @author  M. Dahm
 */
public class GOTO extends GotoInstruction implements VariableLengthInstruction {

    private static final long serialVersionUID = 6106731367505145625L;

    /**
     * Empty constructor needed for the Class.newInstance() statement in
     * Instruction.readInstruction(). Not to be used otherwise.
     */
    GOTO() {
    }

    public GOTO(InstructionHandle target) {
        super(org.apache.bcel.Constants.GOTO, target);
    }

    /**
     * Dump instruction as byte code to stream out.
     * @param out Output stream
     */
    @Override
    public void dump( DataOutputStream out ) throws IOException {
        index = getTargetOffset();
        if (opcode == org.apache.bcel.Constants.GOTO) {
            super.dump(out);
        } else { // GOTO_W
            index = getTargetOffset();
            out.writeByte(opcode);
            out.writeInt(index);
        }
    }

    /** Called in pass 2 of InstructionList.setPositions() in order to update
     * the branch target, that may shift due to variable length instructions.
     */
    @Override
    protected int updatePosition( int offset, int max_offset ) {
        int i = getTargetOffset(); // Depending on old position value
        position += offset; // Position may be shifted by preceding expansions
        if (Math.abs(i) >= (32767 - max_offset)) { // to large for short (estimate)
            opcode = org.apache.bcel.Constants.GOTO_W;
            short old_length = length;
            length = 5;
            return length - old_length;
        }
        return 0;
    }

    /**
     * Call corresponding visitor method(s). The order is:
     * Call visitor methods of implemented interfaces first, then
     * call methods according to the class hierarchy in descending order,
     * i.e., the most specific visitXXX() call comes last.
     *
     * @param v Visitor object
     */
    @Override
    public void accept( Visitor v ) {
        v.visitVariableLengthInstruction(this);
        v.visitUnconditionalBranch(this);
        v.visitBranchInstruction(this);
        v.visitGotoInstruction(this);
        v.visitGOTO(this);
    }
}


text:
import {bootstrap}    from 'angular2/platform/browser';
import {AppComponent} from './app.component';
import {ROUTER_PROVIDERS} from "angular2/router";
import {PriceService} from "./price/price.service";
import {PortfolioService} from "./portfolio/portfolio.service";

bootstrap(AppComponent, [ROUTER_PROVIDERS, PriceService, PortfolioService]);


text:
<archimate:Gap
    xmlns:archimate="http://www.archimatetool.com/archimate"
    name="Gap"
    id="e6c2f132-e406-4b50-8102-576860996545"
    documentation="A Gap represents a statement of difference between two Plateaus
The Gap element is associated with two Plateaus (e.g., Baseline and Target Architectures, or two subsequent Transition Architectures), and represents the differences between these Plateaus."/>


text:
import $ = require('jquery')
import _ = require('lodash')
import V = require('virtual-dom')
let {h, diff, patch, create} = V
declare var require: (s: string) => any;
let foo = require('jquery-ui')
let _VText = require('virtual-dom/vnode/vtext')
import pie = require('./pie')

function VText(t: string){
    return addTags(new _VText(t))
}

// A pair of Id and distance
type IdDist=[string, number]
interface GroupResult{
    exploit : IdDist[],
    explore : IdDist[],
    prev    : IdDist[],
}

// The response from /similar
interface SimilarResponse {
    a: GroupResult,
    b: GroupResult,
    sample: IdDist[],
    deploy_id: string,
}

function SimilarResponse2State(s: SimilarResponse) : State {
    return {
        samples : s.sample,
        a       : s.a.prev.concat(s.a.exploit),
        b       : s.b.prev.concat(s.b.exploit),
        maybeA  : s.a.explore,
        maybeB  : s.b.explore,
    } as State
}

function sendSimilar(deploy: boolean){
    $("#spinner").show()

    let f = (id: string ) => $(`#${id}  img`).map((idx:number, o: Element) => o.id).get()
    let data = {a: f('panelA'), b: f('panelB')}

    let numRndFeats = $("#numRndFeats").val();
    let numBags = $("#numBags").val();

    let dataset = QueryString['dataset'];
    let prefix = QueryString['prefix'];
    let formData = {
        dataset: dataset,
        prefix: prefix,
        deploy: deploy,
        numBags: numBags,
        numRndFeats: numRndFeats,
        input: JSON.stringify(data)
    };
    let w = deploy ? window.open('rt_prediction.html') : null
    $.ajax({
        "dataType": "json",
        "processData": false,
        "data": JSON.stringify(formData),
        "url": "../similar",
        "method": "POST"
    }).done((ret: SimilarResponse) =>{
        let s = SimilarResponse2State(ret)
        let u = ui(s)
        let cs = document.body.children
        document.body.replaceChild(create(u), $('#main')[0])
        InitSortable()
        $("#spinner").hide()
        $(".startedHidden").show()
        if(deploy){
            w.location.assign(`rt_prediction.html?deploy_id=${ret.deploy_id}`)
        }
    })
}

function onClick(evt: MouseEvent){
    sendSimilar(false)
}

function onDeploy(evt: MouseEvent){
    sendSimilar(true)
}

function addAllToA(evt: MouseEvent){
    $('#panelMaybeA > span').appendTo('#panelA')
}

function addAllToB(evt: MouseEvent){
    $('#panelMaybeB > span').appendTo('#panelB')
}

type Row = [string]

interface State{
    samples : IdDist[]
    a       : IdDist[]
    maybeA  : IdDist[]
    b       : IdDist[]
    maybeB  : IdDist[]
}

const Img = ([imgId, dist]: IdDist) => {
    let dataset = QueryString['dataset'];
    let prefix = QueryString['prefix'];

    let img = h(`img#${imgId}`, {
        src: `${prefix}/${dataset}/${imgId}.jpg`,
        id: imgId,
        style: {
            margin: "4px", borderRadius: "25%", maxWidth: "200px",
        }
    } ,[] )
    let color = HSVtoRGB(dist * 0.333, 1, 1)
    let p = pie(dist, color)
    return h('span', {style:{}}, [img, p])

}

function Panel(id: string, style: any, idDists: IdDist[], title: string, backgroundImg?: string){
    let o1 = idDists.map(Img)
    let o = addTags(o1)

    let style2 = JSON.parse(JSON.stringify(style))
    if(backgroundImg) {
        style2["background"] = "url("+backgroundImg+") center center"
        style2["backgroundRepeat"] = "no-repeat"
    }

    return o.DIVp({id: id, className: 'sortable', style: style2})
}

// Add HTML tag as a function into array, so for an array like a = ['abc', 'def']
// a.TD = TD(a)
// a.mapTD = [TD('abc', TD('def'))]
// a.TDp(prop: dict) = TD(a, prop)
// a.mapTDp(prop: dict) = [TD('abc', prop), TD('def', prop)]
// where TD is h('td', ...) from hyperscript
function addTags(o: any): any{
    if(o.hasOwnProperty('TD')){
        return o
    }
    const add = (tag: string) => {
        let r: any = {}
        r[tag] = { get: function() { return addTags(h(tag, this)) } }
        r[tag + 'p'] = {
            value: function(p: VirtualDOM.createProperties) {
                return addTags(h(tag, p, this))
            }
        }

        r['map' + tag] = {
            get: function() {
                return addTags(this.map(function(e: any) {
                    return h(tag, e)
                }))
            }
        }
        r['map' + tag + 'p'] = {
            value:  function(p: VirtualDOM.createProperties) {
                return addTags(this.map(function(e: any) {
                    return h(tag, p, e)
                }))
            }
        }
        return r
    }

    'TD TR TABLE H1 H2 H3 H4 H5 H6 DIV'.split(' ').forEach((tag: string) =>
        Object.defineProperties(o, add(tag)))
    return o
}

let btnStyle = {float: 'right', margin: '5px 30px'}
const createButton = (f: any) =>
    h('button',
        { "onclick":f
        , className: 'btn btn-info'
        , style: btnStyle
        }
      , "Add All")

// This function creates the whole ui
function ui (s: State){
    let pStyle = {
        minHeight: "300px",
        width: "48vw",
        border: "2px solid #ccc",
        borderRadius: "25px",
        borderCollapse: "separate",
        margin: "0 10px",
        display: "inline-block",
        height: "100%",
        padding: "10px"
    }

    let sampleStyle = _.clone(pStyle)
    sampleStyle['width'] = '96vw'

    //This modify array's prototype.
    addTags(Array.prototype)

    let aStyle = { maxHeight: "500px", overflow: "auto", marginBottom: "15px", minHeight: "100px"}
    let pa = Panel('panelA', pStyle, s.a, 'Target', 'drag_pos.png')
    let pb = Panel('panelB', pStyle, s.b, 'Not Target', 'drag_neg.png')
    let pa1 = Panel('panelMaybeA', pStyle, s.maybeA, 'Maybe Target')
    let pb1 = Panel('panelMaybeB', pStyle, s.maybeB, 'Probably Not Target')

    let ps = Panel('panelSamples', sampleStyle, s.samples, 'Samples')

    let btn       = addTags( h('button', {"onclick": onClick, className: 'btn btn-primary', style: btnStyle }, "Find Similar"))
    let btnDeploy = addTags( h('button', {"onclick": onDeploy, className: 'btn', style: btnStyle }, "Deploy"))
    let btn2 = createButton(addAllToA)
    let btn3 = createButton(addAllToB)
    let h2p = {style: { textAlign: "center", fontSize: "25px"}}
    let hidden = {className: 'startedHidden', style: {display: "none"}}
    let c2 = {colSpan: 2, vAlign: "top"}
    let c3 = {colSpan: 3}
    let c4 = {colSpan: 4}

    return h('table#main',
        [ ([VText('Samples'), [btnDeploy, btn]] as any).mapDIVp(h2p).mapTDp(c2).TR
        , ([ps] as any).mapTDp(c4).TR
        , ([VText('Target').DIVp(h2p), VText(""), VText('Not Target').DIVp(h2p)] as any).mapTD.TR,
        , ([pa, pb] as any).mapTDp(c2).TR
        , ([VText('Maybe Target').DIVp(h2p), btn2, VText('Probably Not Target').DIVp(h2p), btn3] as any).mapDIVp(hidden).mapTD.TR,
        , ([pa1, pb1] as any).mapDIVp(hidden).mapTDp(c2).TR
        ])
}

function rows2State(rows: Row[]): State{
    return {
        samples: rows.map(row => [row[0], 0]),
        a: [],
        b: [],
        maybeA: [],
        maybeB: []
    } as State
}

function handleReceive(event: JQueryEventObject, ui: JQueryUI.SortableUIParams){
    let sid = ui.sender[0].id
    if(this.id == 'panelA' && sid == 'panelB' || this.id == 'panelB' && sid == 'panelA'){
        ui.item.find('svg').hide()
    }
}

function InitSortable(){
        $(".sortable").sortable({
            connectWith: ".sortable",
            helper: "clone",
            cursorAt: {left: 50, top: 50},
            receive: handleReceive
        }).disableSelection()
}

// parse the query string and return a dictionary.
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]] = decodeURIComponent(pair[1]);
        // If second entry with this name
    } else if (typeof query_string[pair[0]] === "string") {
      var arr = [ query_string[pair[0]],decodeURIComponent(pair[1]) ];
      query_string[pair[0]] = arr;
        // If third or later entry with this name
    } else {
      query_string[pair[0]].push(decodeURIComponent(pair[1]));
    }
  }
    return query_string;
}();

export function init(){
    let dataset = QueryString['dataset'];
    $.ajax({
        url: "../../../../../v1/query?q=select count(*) from "+dataset+"&format=table&rowNames=false&headers=false"
    }).done(function (rows) {
        var num_images = rows[0][0];
        var sample_size = Math.min(num_images, 10);
        $.ajax({
            url: "../../../../../v1/query?q=select regex_replace(regex_replace(location, '/.*/', ''), '.jpg', '') from sample(" + dataset + ",{rows:"+sample_size+"})&format=table&rowNames=false&headers=false"
        }).done((rows: Row[]) => {
            let s = rows2State(rows)
            let u = ui(s)
            document.body.appendChild(create(u))
            InitSortable()
        })
    });
}

function HSVtoRGB(h: number, s: number, v: number) {
    let i = Math.floor(h * 6)
    let f = h * 6 - i
    let p = v * (1 - s)
    let q = v * (1 - f * s)
    let t = v * (1 - (1 - f) * s)
    var r: number, g: number, b : number
    switch (i % 6) {
        case 0: r = v, g = t, b = p; break;
        case 1: r = q, g = v, b = p; break;
        case 2: r = p, g = v, b = t; break;
        case 3: r = p, g = q, b = v; break;
        case 4: r = t, g = p, b = v; break;
        case 5: r = v, g = p, b = q; break;
    }
    let he = (x: number) => ('0' + Math.round( x * 255).toString(16)).substr(-2)
    return `#${he(r)}${he(g)}${he(b)}`
}

$(init)


text:
bash 'set git username and email' do
  code <<-EOH
    git config --global user.name #{node['devbox']['name']}
    git config --global user.email #{node['devbox']['email']}
  EOH
end


text:
package ru.job4j.servlets.userstore;
import org.apache.commons.dbcp2.BasicDataSource;

import java.sql.*;
import java.util.Date;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;

public class DbStore implements Store, AutoCloseable {

    private static DbStore instance = new DbStore();

    public static DbStore getInstance() {
        return instance;
    }

    private BasicDataSource source;

    public DbStore() {
        this.source = new BasicDataSource();
        source.setDriverClassName("org.postgresql.Driver");
        source.setUrl("jdbc:postgresql://localhost:5432/postgres");
        source.setUsername("postgres");
        source.setPassword("password");
        source.setMinIdle(5);
        source.setMaxIdle(10);
        source.setMaxOpenPreparedStatements(100);
        createTables();
        if (isEmpty()) {
            addRootUser();
        }
    }

    public void createTables() {
        try (Connection connection = source.getConnection()) {
            PreparedStatement st1 = connection.prepareStatement("create table if not exists public.roles(id serial primary key, name varchar(100))");
            PreparedStatement st2 = connection
                    .prepareStatement("create table if not exists public.users(" +
                            "id serial primary key, name varchar(100), login varchar(100)," +
                            "email varchar (100), password varchar(100)," +
                            "country varchar (100), city varchar(100),"+
                            "roles_id int references roles(id))");
            st1.execute();
            st2.execute();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private boolean isEmpty() {
        int count = 0;
        boolean result = false;
        try (Connection connection = source.getConnection();
             PreparedStatement ps = connection.prepareStatement("Select count(*) from users")) {
            ResultSet rs = ps.executeQuery();
            while (rs.next()) {
                count = rs.getInt(1);
                if (count == 0) {
                    result = true;
                    break;
                }
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return result;
    }

    private void addRootUser() {
        try (Connection connection = source.getConnection()) {
            final PreparedStatement ps = connection.prepareStatement("INSERT INTO roles(name) values ('admin')");
            PreparedStatement st2 = connection.prepareStatement("INSERT INTO roles(name) values ('user')");
            PreparedStatement st3 = connection.prepareStatement("INSERT INTO users(login, password, roles_id) VALUES ('admin', 'admin', 1)");
            ps.execute();
            st2.execute();
            st3.execute();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void close() {
        try {
            source.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    public boolean isCredentional(String login, String password) {
        boolean exists = false;
        try(Connection connection = source.getConnection()) {
            PreparedStatement st = connection.prepareStatement("select * from users where login = ? and password = ?");
            st.setString(1, login);
            st.setString(2, password);
            if (st.executeQuery().next()) {
                exists = true;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return exists;
    }

    @Override
    public boolean contain(User user) {
        try  (Connection connection = source.getConnection()) {
            PreparedStatement st = connection.prepareStatement("select login, email from users where login = ? or email = ?");
            st.setString(1, user.getLogin());
            st.setString(2, user.getEmail());
            ResultSet rs = st.executeQuery();

            User uDb = null;
            if (rs.next()) {
                final String login = rs.getString("login");
                final String email = rs.getString("email");
                uDb = new User(0, "test", login, email, new Date(), "test", "", "", 1);
            }

            if (uDb!=null) {
                if (user.getEmail().equals(uDb.getEmail()) || user.getLogin().equals(uDb.getLogin())) {
                    return true;
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    @Override
    public void add(User user) {
        try (Connection connection = source.getConnection()) {
            PreparedStatement st = connection.prepareStatement("INSERT INTO users(name, login, email, password, roles_id, country, city) values(?,?,?,?,?,?,?)");
            st.setString(1, user.getName());
            st.setString(2, user.getLogin());
            st.setString(3, user.getEmail());
            st.setString(4, user.getPassword());
            st.setInt(5, user.getRole());
            st.setString(6, user.getCountry());
            st.setString(7, user.getCity());
            st.executeUpdate();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void update(int id, User user) {
        try (Connection connection = source.getConnection()) {
            PreparedStatement st = connection.prepareStatement("UPDATE users SET name=?, login=?, email=?, password = ?, roles_id=? WHERE id=?");
            st.setString(1, user.getName());
            st.setString(2, user.getLogin());
            st.setString(3, user.getEmail());
            st.setString(4, user.getPassword());
            st.setInt(5, user.getRole());
            st.setInt(6, id);
            st.executeUpdate();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void delete(int key) {
        try (Connection connection = source.getConnection()) {
            PreparedStatement st = connection.prepareStatement("delete from users where id = ?");
            st.setInt(1, key);
            st.executeUpdate();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public List<User> findAll() {
        List<User> userStore = new CopyOnWriteArrayList<User>();
        try (Connection connection = source.getConnection()) {
            PreparedStatement st = connection.prepareStatement("select * from users");
            ResultSet rs = st.executeQuery();
            while (rs.next()) {
                User user = new User(rs.getInt("id"), rs.getString("name"), rs.getString("login"), rs.getString("email"), new Date(), rs.getString("password"), "", "", rs.getInt("roles_id"));
                userStore.add(user);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return userStore;
    }

    @Override
    public List<Role> findAllRoles() {
        List<Role> roleStore = new CopyOnWriteArrayList<Role>();
        try (Connection connection = source.getConnection()) {
            PreparedStatement st = connection.prepareStatement("select * from roles");
            ResultSet rs = st.executeQuery();
            while (rs.next()) {
                Role role = new Role(rs.getInt("id"), rs.getString("name"));
                roleStore.add(role);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return roleStore;
    }

    @Override
    public User findById(int key) {
        User user = new User();
        try (Connection connection = source.getConnection()) {
            PreparedStatement st = connection.prepareStatement("select * from users where id = ?");
            st.setInt(1, key);
            ResultSet rs = st.executeQuery();
            rs.next();
            user.setId(rs.getInt("id"));
            user.setName(rs.getString("name"));
            user.setLogin(rs.getString("login"));
            user.setEmail(rs.getString("email"));
            user.setPassword(rs.getString("password"));
            user.setRole(rs.getInt("roles_id"));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return user;
    }

    @Override
    public int findByLogin(String login) {
        int id = 0;
        try (Connection connection = source.getConnection()) {
            PreparedStatement st = connection.prepareStatement("select * from users where login = ?");
            st.setString(1, login);
            ResultSet rs = st.executeQuery();
            rs.next();
            id = rs.getInt("roles_id");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return id;
    }
}


text:
import express from 'express';
import http from 'http';
import https from 'https';
import _ from 'lodash';

import { configureExpress, handleErrors, setListeners } from './serverConfig';
import defaultConfig from './defaultConfig';
import { notFound } from '../lib/notFound';
import { Router as router } from '../dependencies/express';
import { ResponseHelper } from '../lib/ResponseHelper';

// Configure http/https before requiring Request module since Request is also using global config
http.globalAgent.maxSockets = 25;
https.globalAgent.options.rejectUnauthorized = false;
https.globalAgent.options.requestCert = true;
https.globalAgent.maxSockets = 25;

/**
 * Orchestrator server. Handles routes and HTTP traffic.
 * @class
 * @param {Config} config - Configuration file for server instance.
 * @param {Object[]} [routes] - The server's endpoints.
 * @param {('DELETE'|'GET'|'POST'|'PUT')} routes[].method - The HTTP method of the route.
 * @param {String} routes[].url - The path from the base url.
 * @param {Function} routes[].fn - the function to be called when route is accessed.
 * @throws {Error} If `config` argument is null.
 */
export default class Orchestrator {
  constructor(config, routes) {
    if (!config) {
      throw new Error('new Orchestrator() - Missing argument `config`');
    }

    this.env = process.env.NODE_ENV || 'development';
    this.app = express();
    this.config = _.merge({}, defaultConfig, config);

    configureExpress(this.app, this.config, this.env);
    this.server = http.createServer(this.app);
    setListeners(this.app, this.server, this.config);

    if (routes) {
      this.setRoutes(routes);
    }
  }

  /**
   * Set Orchestrator endpoints
   * @param {Object[]} routes - The server's endpoints.
   * @param {('DELETE'|'GET'|'POST'|'PUT')} routes[].method - The HTTP method of the route.
   * @param {String} routes[].url - The path from the base url.
   * @param {Function} routes[].fn - the function to be called when route is accessed.
   * @param {Object} [options] - Additional options for route configuration.
   * @param {Boolean} [options.handle404=true] - Whether to handle 404 routes automatically or not.
   * @throws {Error} If routes are already set.
   */
  setRoutes = (routes, options = {}) => {
    if (this.router) {
      throw new Error('You can only set routes once');
    }

    if (options.handle404 !== false) {
      const methods = ['DELETE', 'GET', 'POST', 'PUT'];
      routes.push(...methods.map(method => ({ method, url: '/*', fn: notFound })));
    }

    this.router = router();

    routes.forEach(({ method, url, fn }) => {
      this.router[method.toLowerCase()](url, (req, res) => {
        fn(new ResponseHelper(req, res, this.config), req, res);
      });
    });

    this.app.use(this.router);

    // Must handle errors after settings routes or express throws an error.
    handleErrors(this.app);
  }
}


text:
import { inject as service } from '@ember/service';
import Component from '@glimmer/component';

export default class BackLinkComponent extends Component {
  @service intl;
  back() {
    window.history.back();
  }
}


text:
ACCEPTED

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
<I>Iris</I> 117. 1981

#### Original name
Iris demetrii Achv. & Mirzoeva

### Remarks
null


text:
struct ListNode {
    int val;
    ListNode *next;
    ListNode(int x) : val(x), next(NULL) {}
};

struct TreeNode {
    int val;
    TreeNode *left;
    TreeNode *right;
	TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
};

struct TreeLinkNode {
 int val;
 TreeLinkNode *left, *right, *next;
 TreeLinkNode(int x) : val(x), left(NULL), right(NULL), next(NULL) {}
};


text:
<?php

/**
 * La clase encapsula la logica de acceso a datos asociada a las aseguradoras.
 *
 * @package     pragtico
 * @subpackage  app.models
 */
class Aseguradora extends AppModel {

    var $permissions = array('permissions' => 508, 'group' => 'none', 'role' => 'higher');

	var $validate = array(
        'nombre' => array(
			array(
				'rule'		=> VALID_NOT_EMPTY,
				'message'	=> 'Debe especificar el nombre de la aseguradora.')
        ),
        'codigo' => array(
			array(
				'rule'		=> VALID_NOT_EMPTY,
				'message'	=> 'Debe especificar el codigo de la aseguradora.')
        )
	);

}
?>


text:
<?php

namespace Guzzle\Plugin\Cache;

use Guzzle\Http\Message\RequestInterface;
use Guzzle\Http\Message\Response;
use Guzzle\Http\Exception\BadResponseException;

class DefaultRevalidation implements RevalidationInterface
{

protected $storage;

protected $canCache;

public function __construct(CacheStorageInterface $cache, CanCacheStrategyInterface $canCache = null)
{
$this->storage = $cache;
$this->canCache = $canCache ?: new DefaultCanCacheStrategy();
}

public function revalidate(RequestInterface $request, Response $response)
{
try {
$revalidate = $this->createRevalidationRequest($request, $response);
$validateResponse = $revalidate->send();
if ($validateResponse->getStatusCode() == 200) {
return $this->handle200Response($request, $validateResponse);
} elseif ($validateResponse->getStatusCode() == 304) {
return $this->handle304Response($request, $validateResponse, $response);
}
} catch (BadResponseException $e) {
$this->handleBadResponse($e);
}

return false;
}

public function shouldRevalidate(RequestInterface $request, Response $response)
{
if ($request->getMethod() != RequestInterface::GET) {
return false;
}

$reqCache = $request->getHeader('Cache-Control');
$resCache = $response->getHeader('Cache-Control');

$revalidate = $request->getHeader('Pragma') == 'no-cache' ||
($reqCache && ($reqCache->hasDirective('no-cache') || $reqCache->hasDirective('must-revalidate'))) ||
($resCache && ($resCache->hasDirective('no-cache') || $resCache->hasDirective('must-revalidate')));

if (!$revalidate && !$resCache && $response->hasHeader('ETag')) {
$revalidate = true;
}

return $revalidate;
}

protected function handleBadResponse(BadResponseException $e)
{

if ($e->getResponse()->getStatusCode() == 404) {
$this->storage->delete($e->getRequest());
throw $e;
}
}

protected function createRevalidationRequest(RequestInterface $request, Response $response)
{
$revalidate = clone $request;
$revalidate->removeHeader('Pragma')->removeHeader('Cache-Control');

if ($response->getLastModified()) {
$revalidate->setHeader('If-Modified-Since', $response->getLastModified());
}

if ($response->getEtag()) {
$revalidate->setHeader('If-None-Match', $response->getEtag());
}

$dispatcher = $revalidate->getEventDispatcher();
foreach ($dispatcher->getListeners() as $eventName => $listeners) {
foreach ($listeners as $listener) {
if (is_array($listener) && $listener[0] instanceof CachePlugin) {
$dispatcher->removeListener($eventName, $listener);
}
}
}

return $revalidate;
}

protected function handle200Response(RequestInterface $request, Response $validateResponse)
{
$request->setResponse($validateResponse);
if ($this->canCache->canCacheResponse($validateResponse)) {
$this->storage->cache($request, $validateResponse);
}

return false;
}

protected function handle304Response(RequestInterface $request, Response $validateResponse, Response $response)
{
static $replaceHeaders = array('Date', 'Expires', 'Cache-Control', 'ETag', 'Last-Modified');

if ($validateResponse->getEtag() != $response->getEtag()) {
return false;
}

$modified = false;
foreach ($replaceHeaders as $name) {
if ($validateResponse->hasHeader($name)) {
$modified = true;
$response->setHeader($name, $validateResponse->getHeader($name));
}
}

if ($modified && $this->canCache->canCacheResponse($response)) {
$this->storage->cache($request, $response);
}

return true;
}
}


text:
import ImageProcess
from PIL import Image
import time
import os
import CommonUtil

def generate(input_path, tag, title, desc, output, tag_type):
    im = Image.open(input_path)
    if tag_type is None:
        ttype = 0
    else:
        ttype = int(tag_type)

    image_name = int(time.time())

    web_im = ImageProcess.process(0,
                                  im,
                                  tag,
                                  CommonUtil.restoreNewlineCharacter(title),
                                  CommonUtil.restoreNewlineCharacter(desc),
                                  ttype)
    web_im.save(os.path.join(output, 'Web_' + str(image_name) + '.jpg'),
                quality=ImageProcess.SAVE_IMAGE_QUALITY,
                optimize=True)

    app_im = ImageProcess.process(1,
                                  im,
                                  tag,
                                  CommonUtil.restoreNewlineCharacter(title),
                                  CommonUtil.restoreNewlineCharacter(desc),
                                  ttype)
    app_im.save(os.path.join(output, 'App_' + str(image_name) + '.jpg'),
                quality=ImageProcess.SAVE_IMAGE_QUALITY,
                optimize=True)


text:
require 'chromosome_type'
require 'mutation_methods'
require 'crossover_methods'
require 'selection_methods'
require 'survive_methods'

class GA
    attr_reader :best_log, :avg_log
    include CrossoverMethods
    include SelectionMethods
    include SurviveMethods

    def initialize(&block)
        instance_eval &block
        @population = Population.new @population_size, @chromosome_type, @chromosome_length, @mutation_method, @mutation_probability
        @best_log = []
        @avg_log = []
    end

    def chromosome_type(type)
        @chromosome_type = type
    end

    def chromosome_length(len)
        @chromosome_length = len
    end

    def population_size(size)
        @population_size = size
    end

    def crossover_method(crossover)
        @crossover_method = crossover
    end

    def mutation_method(mutation)
        @mutation_method = mutation
    end

    def mutation_probability(prob)
        @mutation_probability = prob
    end

    def selection_method(selection)
        @selection_method = selection
    end

    def survive_method(survive)
        @survive_method = survive
    end

    def evolve(generations)
        generations.times do |i|
            offspring = Population.new @population_size, @chromosome_type, @chromosome_length, @mutation_method, @mutation_probability
            offspring.clear
            offspring << @population
            offspring.flatten!(1)
            @population.size.times do |i|
                chs1 = @population[select]
                chs2 = @population[select]
                while chs1==chs2
                    chs2 = @population[select]
                end
                new_chs = crossover(chs1,chs2)
                while offspring.include?(new_chs[0]) or offspring.include?(new_chs[1])
                    chs1 = @population[select]
                    chs2 = @population[select]
                    while chs1==chs2
                        chs2 = @population[select]
                    end
                    new_chs = crossover(chs1,chs2)
                end
                offspring << new_chs[0] << new_chs[1]
            end
            survive offspring
            @best_log << best.fitness
            @avg_log << avg
        end

    end

    def select
        send(@selection_method)
    end

    def crossover(chs1, chs2)
        send(@crossover_method, chs1, chs2)
    end

    def set_fitness_eval(&block)
        @fitness = block
    end

    def survive(population)
        population.each { |e| e.fitness = @fitness.call e }
        send(@survive_method, population)
    end

    def best
        best_idx = 0
        best_fit = nil
        @population.each_index do |idx|
            ch = @population[idx]
            ch.fitness = @fitness.call ch
            best_fit = ch.fitness if best_fit==nil
            best_idx = idx if best_fit < ch.fitness
            best_fit = ch.fitness if best_fit < ch.fitness
        end
        return @population[best_idx]
    end

    def avg
        avg_fit = 0
        @population.each do |ch|
            avg_fit += ch.fitness
        end
        return avg_fit/@population.size
    end

end

class Population < Array
    def initialize(size, chs_type, chs_len, chs_mutation, chs_prob)
        return if size==nil
        size.times do |i|
            self << Chromosome.new(chs_type, chs_len, chs_mutation, chs_prob)
        end
    end
end

class Chromosome < Array
    attr_accessor :fitness
    include ChromosomeType
    include MutationMethods

    def initialize(type, size, mutation, probability)
        @size = size
        self.send(type)
        @mutation_method = mutation
        @mutation_probability = probability
    end

    def mutate!
        if rand(100)<=probability
            self.send(:mutation_method)
        end
    end
end


text:
"""
Pickling
--------

This example pickles a function.
"""
from math import sqrt
import pickle

from joblib import Parallel, delayed

assert __name__ == '__main__'
assert '__file__' not in globals()

def function(x):
    return sqrt(x)

pickle.loads(pickle.dumps(function))

# Now with joblib
print(Parallel(n_jobs=2)(delayed(sqrt)(i ** 2) for i in range(10)))
print(Parallel(n_jobs=2)(delayed(function)(i ** 2) for i in range(10)))


text:
Changelog
=========

0.4.1 2016-06-27
----------------
* Default `sidekiq_concurrency` to nil. It now needs explicitly set to
  override concurrency specified in config file

0.4.0 2016-05-16
----------------

* `sidekiq_concurrency`
* sidekiq_timeout is now bigger then 10s
* add task skidekiq:log

0.3.1 2015-01-18
----------------

* fix starting in background

0.2.0 2013-08-18
----------------

Breaking Changes:

* to load the tasks requiring 'mina_sidekiq/tasks' is needed now

Enhancements:

* add sidekiq_processes to allow launching multiple sidekiq instances
* improved checking, if old instances of sidekiq are still running


text:
@interface RLRoomsSceneViewController () <RLScrollPagerDataSource, RLScrollPagerDelegate>

@property (nonatomic, retain) NSMutableArray *rooms;
@property (weak, nonatomic) IBOutlet UIView *roomActionPannel;

@end

@implementation RLRoomsSceneViewController

- (void)viewDidLoad {

    [super viewDidLoad];

    // data initialization

    NSArray *allRooms = [[RLRoomsManager sharedInstance] getAllRooms];

    if ([allRooms count] > 0) {
        _rooms = [NSMutableArray arrayWithArray:allRooms];
    } else {
        _rooms = [NSMutableArray array];
    }

    [self refreshActionPanel];

    // scroll pager
    self.roomScrollPager.dataSource = self;
    self.roomScrollPager.delegate = self;
    [self.roomScrollPager reloadData];

    // notification
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(newRoom:)
                                                 name:kRLNotificationTypeRoomCreated object:nil];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];

    // Dispose of any resources that can be recreated.
}

- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

#pragma mark - utils

- (void)refreshActionPanel {

    _roomActionPannel.hidden = ([_rooms count] > 0) ? NO : YES;
}

- (IBAction)delete:(id)sender {

    RoomModel *room = _roomCanvasVC.room;
    _roomCanvasVC.room = nil;

    if (room) {

        [[RLRoomsManager sharedInstance] deleteRoom:room];

        NSInteger activeIndex = [_rooms indexOfObject:room];
        [_rooms removeObject:room];

        activeIndex = activeIndex < [_rooms count] ? activeIndex : (activeIndex - 1);
        self.roomScrollPager.startFromSecondTab = activeIndex;
        [self.roomScrollPager reloadData];

        if (activeIndex >= 0) {
            _roomCanvasVC.room = _rooms[activeIndex];
        }

        [self refreshActionPanel];
    }
}

#pragma mark - notification

- (void)newRoom:(NSNotification *)note {

    if (note.object != nil) {

        [_rooms addObject:note.object];

        self.roomScrollPager.startFromSecondTab = [_rooms count] - 1;
        [self.roomScrollPager reloadData];

        [self refreshActionPanel];
    }
}

#pragma mark - Navigation

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {

    if ([segue.identifier isEqualToString:@"rl_rc_embed"]) {
        self.roomCanvasVC = segue.destinationViewController;
    }
}

#pragma mark - RLScrollPagerDataSource

- (NSUInteger)numberOfTabsForScrollPager:(RLScrollPagerView *)scrollPager {
    return [self.rooms count];
}

- (UIView *)scrollPager:(RLScrollPagerView *)viewPager viewForTabAtIndex:(NSUInteger)index {

    RoomModel *room = self.rooms[index];

    UILabel *label = [UILabel new];
    label.backgroundColor = [UIColor clearColor];
    label.font = [UIFont boldSystemFontOfSize:16.0];
    label.text = room.name;
    label.textAlignment = NSTextAlignmentCenter;
    label.textColor = [UIColor whiteColor];
    [label sizeToFit];

    return label;
}

#pragma mark - RLScrollPagerDelegate

// delegate object must implement this method if wants to be informed when a tab changes
- (void)scrollPager:(RLScrollPagerView *)viewPager didChangeTabToIndex:(NSUInteger)index {

    [_roomCanvasVC save];

    if ([_rooms count] > 0) {
        _roomCanvasVC.room = _rooms[index];
    }
}

@end


text:
"""Use of \'noargdoc\' function decorator

The :func:`~sphinxcontrib.argdoc.ext.noargdoc` function decorator tells
:obj:`sphinxcontrib.argdoc` to ignore a command-line script, leaving
its ``:automodule:`` output unchanged.

-----------------

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aenean feugiat
tempor diam sed condimentum. Mauris aliquam interdum libero, ut aliquet
erat malesuada sed. Mauris nec venenatis sapien, a feugiat neque. Sed
pulvinar erat sit amet posuere aliquet. Phasellus non quam tincidunt,
semper velit vitae, eleifend ante. Nam finibus vulputate diam. Fusce sit
amet leo aliquam magna gravida fringilla et eu justo. Pellentesque vulputate
elit id dignissim vehicula. Sed tempor interdum lacus, in dapibus magna
interdum eu. Fusce lacinia turpis vel risus porta, eget dapibus nisi
eleifend. Maecenas dictum nec nisi sit amet dignissim. Duis vestibulum
ipsum a vestibulum placerat. Vestibulum ante ipsum primis in faucibus orci
luctus et ultrices posuere cubilia Curae; Nullam consequat nulla quis quam
interdum, eu auctor ante molestie.

Here is a table, to show that we can have rich formatting:

    =============  ======================================================
    **Column 1**   **Column 2**
    -------------  ------------------------------------------------------
     Some item     Some other item.

     Table row 2.  Table row 2 column 2.

     Another row.  Row with a link to `Python <https://www.python.org>`_
    =============  ======================================================

See also
--------
A definition list
    The purpose of this `See also` section is just to show that we can use
    a number of reStructuredText structures, and still have the argument
    descriptions appended below.

Here is another item
    To show that our test works
"""
import argparse
import sys
from sphinxcontrib.argdoc import noargdoc

helptext = {
    "short" : "one-line help text",
    "long"  : "this is very, very long help text which should span multiple lines and thus require special parsing. We'll also add `special` *chars* (default: 513251324)",
}

choices = {
    "single" : ["one_choice"],
    "multi"  : ["one","two","three","four"],
}

@noargdoc
def main(argv=sys.argv[1:]):
    """Command-line program for `simple_parser`"""
    parser = argparse.ArgumentParser(description=__doc__,
                                     formatter_class=argparse.RawDescriptionHelpFormatter)
    # positional arguments
    parser.add_argument("shortpos1")
    parser.add_argument("shortpos2",help=helptext["short"])
    parser.add_argument("shortpos3",help=helptext["long"])
    parser.add_argument("reallyreallyreallyreallyreallyreallyreallyreallylongpositionalargument1")
    parser.add_argument("reallyreallyreallyreallyreallyreallyreallyreallylongpositionalargument2",help=helptext["short"])
    parser.add_argument("reallyreallyreallyreallyreallyreallyreallyreallylongpositionalargument3",help=helptext["long"])

    # optional arguments, one arg
    parser.add_argument("-a",metavar="X")
    parser.add_argument("-b",help=helptext["short"],metavar="X")
    parser.add_argument("-c",help=helptext["long"],metavar="X")
    parser.add_argument("--double1",metavar="X")
    parser.add_argument("--double2",help=helptext["short"],metavar="X")
    parser.add_argument("--double3",help=helptext["long"],metavar="X")
    parser.add_argument("-d","--combo1",metavar="X")
    parser.add_argument("-e","--combo2",help=helptext["short"],metavar="X")
    parser.add_argument("-f","--combo3",help=helptext["long"],metavar="X")
    parser.add_argument("--reallyreallyreallyreallyreallyreallylong_double1",metavar="X")
    parser.add_argument("--reallyreallyreallyreallyreallyreallylong_double2",help=helptext["short"],metavar="X")
    parser.add_argument("--reallyreallyreallyreallyreallyreallylong_double3",help=helptext["long"],metavar="X")
    parser.add_argument("-g","--reallyreallyreallyreallyreallyreallylong_combo1",metavar="X")
    parser.add_argument("-i","--reallyreallyreallyreallyreallyreallylong_combo2",help=helptext["short"],metavar="X")
    parser.add_argument("-j","--reallyreallyreallyreallyreallyreallylong_combo3",help=helptext["long"],metavar="X")

    # optional arguments, 2 args
    parser.add_argument("-k",nargs=2,metavar="X")
    parser.add_argument("-l",help=helptext["short"],nargs=2,metavar="X")
    parser.add_argument("-m",help=helptext["long"],nargs=2,metavar="X")
    parser.add_argument("--double4",nargs=2,metavar="X")
    parser.add_argument("--double5",help=helptext["short"],nargs=2,metavar="X")
    parser.add_argument("--double6",help=helptext["long"],nargs=2,metavar="X")
    parser.add_argument("-n","--combo4",nargs=2,metavar="X")
    parser.add_argument("-o","--combo5",help=helptext["short"],nargs=2,metavar="X")
    parser.add_argument("-p","--combo6",help=helptext["long"],nargs=2,metavar="X")
    parser.add_argument("--reallyreallyreallyreallyreallyreallylong_double4",nargs=2,metavar="X")
    parser.add_argument("--reallyreallyreallyreallyreallyreallylong_double5",help=helptext["short"],nargs=2,metavar="X")
    parser.add_argument("--reallyreallyreallyreallyreallyreallylong_double6",help=helptext["long"],nargs=2,metavar="X")
    parser.add_argument("-q","--reallyreallyreallyreallyreallyreallylong_combo4",nargs=2,metavar="X")
    parser.add_argument("-r","--reallyreallyreallyreallyreallyreallylong_combo5",help=helptext["short"],nargs=2,metavar="X")
    parser.add_argument("-s","--reallyreallyreallyreallyreallyreallylong_combo6",help=helptext["long"],nargs=2,metavar="X")

    # optional arguments, + args
    parser.add_argument("-t",nargs='+',metavar="X")
    parser.add_argument("-u",help=helptext["short"],nargs='+',metavar="X")
    parser.add_argument("-v",help=helptext["long"],nargs='+',metavar="X")
    parser.add_argument("--double7",nargs='+',metavar="X")
    parser.add_argument("--double8",help=helptext["short"],nargs='+',metavar="X")
    parser.add_argument("--double9",help=helptext["long"],nargs='+',metavar="X")
    parser.add_argument("-w","--combo7",nargs='+',metavar="X")
    parser.add_argument("-x","--combo8",help=helptext["short"],nargs='+',metavar="X")
    parser.add_argument("-y","--combo9",help=helptext["long"],nargs='+',metavar="X")
    parser.add_argument("--reallyreallyreallyreallyreallyreallylong_double7",nargs='+',metavar="X")
    parser.add_argument("--reallyreallyreallyreallyreallyreallylong_double8",help=helptext["short"],nargs='+',metavar="X")
    parser.add_argument("--reallyreallyreallyreallyreallyreallylong_double9",help=helptext["long"],nargs='+',metavar="X")
    parser.add_argument("-z","--reallyreallyreallyreallyreallyreallylong_combo7",nargs='+',metavar="X")
    parser.add_argument("-A","--reallyreallyreallyreallyreallyreallylong_combo8",help=helptext["short"],nargs='+',metavar="X")
    parser.add_argument("-B","--reallyreallyreallyreallyreallyreallylong_combo9",help=helptext["long"],nargs='+',metavar="X")

    # optional arguments, ? args
    parser.add_argument("-C",nargs='?',metavar="X")
    parser.add_argument("-D",help=helptext["short"],nargs='?',metavar="X")
    parser.add_argument("-E",help=helptext["long"],nargs='?',metavar="X")
    parser.add_argument("--double10",nargs='?',metavar="X")
    parser.add_argument("--double11",help=helptext["short"],nargs='?',metavar="X")
    parser.add_argument("--double12",help=helptext["long"],nargs='?',metavar="X")
    parser.add_argument("-F","--combo10",nargs='?',metavar="X")
    parser.add_argument("-G","--combo11",help=helptext["short"],nargs='?',metavar="X")
    parser.add_argument("-H","--combo12",help=helptext["long"],nargs='?',metavar="X")
    parser.add_argument("--reallyreallyreallyreallyreallyreallylong_double10",nargs='?',metavar="X")
    parser.add_argument("--reallyreallyreallyreallyreallyreallylong_double11",help=helptext["short"],nargs='?',metavar="X")
    parser.add_argument("--reallyreallyreallyreallyreallyreallylong_double12",help=helptext["long"],nargs='?',metavar="X")
    parser.add_argument("-I","--reallyreallyreallyreallyreallyreallylong_combo10",nargs='?',metavar="X")
    parser.add_argument("-J","--reallyreallyreallyreallyreallyreallylong_combo11",help=helptext["short"],nargs='?',metavar="X")
    parser.add_argument("-K","--reallyreallyreallyreallyreallyreallylong_combo12",help=helptext["long"],nargs='?',metavar="X")

    # optional arguments, * args
    parser.add_argument("-L",nargs='*',metavar="X")
    parser.add_argument("-M",help=helptext["short"],nargs='*',metavar="X")
    parser.add_argument("-N",help=helptext["long"],nargs='*',metavar="X")
    parser.add_argument("--double13",nargs='*',metavar="X")
    parser.add_argument("--double14",help=helptext["short"],nargs='*',metavar="X")
    parser.add_argument("--double15",help=helptext["long"],nargs='*',metavar="X")
    parser.add_argument("-O","--combo13",nargs='*',metavar="X")
    parser.add_argument("-P","--combo14",help=helptext["short"],nargs='*',metavar="X")
    parser.add_argument("-Q","--combo15",help=helptext["long"],nargs='*',metavar="X")
    parser.add_argument("--reallyreallyreallyreallyreallyreallylong_double13",nargs='*',metavar="X")
    parser.add_argument("--reallyreallyreallyreallyreallyreallylong_double14",help=helptext["short"],nargs='*',metavar="X")
    parser.add_argument("--reallyreallyreallyreallyreallyreallylong_double15",help=helptext["long"],nargs='*',metavar="X")
    parser.add_argument("-R","--reallyreallyreallyreallyreallyreallylong_combo13",nargs='*',metavar="X")
    parser.add_argument("-S","--reallyreallyreallyreallyreallyreallylong_combo14",help=helptext["short"],nargs='*',metavar="X")
    parser.add_argument("-T","--reallyreallyreallyreallyreallyreallylong_combo15",help=helptext["long"],nargs='*',metavar="X")

    # optional arguments, single choices
    parser.add_argument("-U",choices=choices["single"],)
    parser.add_argument("-V",help=helptext["short"],choices=choices["single"],)
    parser.add_argument("-W",help=helptext["long"],choices=choices["single"],)
    parser.add_argument("--double16",choices=choices["single"],)
    parser.add_argument("--double17",help=helptext["short"],choices=choices["single"],)
    parser.add_argument("--double18",help=helptext["long"],choices=choices["single"],)
    parser.add_argument("-X","--combo16",choices=choices["single"],)
    parser.add_argument("-Y","--combo17",help=helptext["short"],choices=choices["single"],)
    parser.add_argument("-Z","--combo18",help=helptext["long"],choices=choices["single"],)
    parser.add_argument("--reallyreallyreallyreallyreallyreallylong_double16",choices=choices["single"],)
    parser.add_argument("--reallyreallyreallyreallyreallyreallylong_double17",help=helptext["short"],choices=choices["single"],)
    parser.add_argument("--reallyreallyreallyreallyreallyreallylong_double18",help=helptext["long"],choices=choices["single"],)
    parser.add_argument("-1","--reallyreallyreallyreallyreallyreallylong_combo16",choices=choices["single"],)
    parser.add_argument("-2","--reallyreallyreallyreallyreallyreallylong_combo17",help=helptext["short"],choices=choices["single"],)
    parser.add_argument("-3","--reallyreallyreallyreallyreallyreallylong_combo18",help=helptext["long"],choices=choices["single"],)

    # optional arguments, multi choices
    parser.add_argument("-4",choices=choices["multi"],)
    parser.add_argument("-5",help=helptext["short"],choices=choices["multi"],)
    parser.add_argument("-6",help=helptext["long"],choices=choices["multi"],)
    parser.add_argument("--double19",choices=choices["multi"],)
    parser.add_argument("--double20",help=helptext["short"],choices=choices["multi"],)
    parser.add_argument("--double21",help=helptext["long"],choices=choices["multi"],)
    parser.add_argument("-7","--combo19",choices=choices["multi"],)
    parser.add_argument("-8","--combo20",help=helptext["short"],choices=choices["multi"],)
    parser.add_argument("-9","--combo21",help=helptext["long"],choices=choices["multi"],)
    parser.add_argument("--reallyreallyreallyreallyreallyreallylong_double19",choices=choices["multi"],)
    parser.add_argument("--reallyreallyreallyreallyreallyreallylong_double20",help=helptext["short"],choices=choices["multi"],)
    parser.add_argument("--reallyreallyreallyreallyreallyreallylong_double21",help=helptext["long"],choices=choices["multi"],)
    parser.add_argument("-Â","--reallyreallyreallyreallyreallyreallylong_combo19",choices=choices["multi"],)
    parser.add_argument("-Ã","--reallyreallyreallyreallyreallyreallylong_combo20",help=helptext["short"],choices=choices["multi"],)
    parser.add_argument("-Ä","--reallyreallyreallyreallyreallyreallylong_combo21",help=helptext["long"],choices=choices["multi"],)

    args = parser.parse_args(argv)

if __name__ == "__main__":
    main()


text:
"""Utility for archiving files and directories.

An archive is simply a zip file containing the archived
targets plus an optional log file. The standard used for
the log file is a text file named `__archive_info__.txt`.
The log is always in the root directory of the archive.

By default, the archive filename will be prefixed with
a timestamp of the time created. The default format is the
following: `YYMMDDhhmm-<ARCHIVE_NAME>.zip`. Options are
provided to extend, shorten or remove the timestamp. If a
name for the archive is not explicitly given, the archive
name will be based on the name of the first target.

Usage:
  archiver [options] TARGET...
  archiver -h | --help
  archiver --version

Arguments:
  TARGET   Path to a file or folder to archive.

Options:
  -m LOGMSG         Archive log message.
  --outdir=OUTDIR   Directory to place generated files [default: .].
  --name=NAME       Archive name.
  --no_ts           Do not include timestamp in archive name.
  --short_ts        Only timestamp to the day (hour:min otherwise).
  --long_ts         Timestamp to the second (hour:min otherwise).
  --delete          Delete original targets from file system after archiving.
  --flatten         Flatten directory structure in the zip archive.
  --flatten_ld      Flatten leading directory; only if single directory target.
  -h --help         Show this help message and exit.
  --version         Show version and exit.
"""

##==============================================================#
## DEVELOPED 2012, REVISED 2014, Jeff Rimko.                    #
##==============================================================#

##==============================================================#
## SECTION: Imports                                             #
##==============================================================#

import os
import sys

from docopt import docopt

import arcmgr
from appinfo import ARCHIVER_NAME, ARCHIVER_VER

##==============================================================#
## SECTION: Global Definitions                                  #
##==============================================================#

#: Combined application name and version string.
NAMEVER = "%s %s" % (ARCHIVER_NAME, ARCHIVER_VER)

##==============================================================#
## SECTION: Function Definitions                                #
##==============================================================#

#: Function to print an error message to the console.
print_error = lambda s: sys.stderr.write("ERROR: " + s)

#: Function to print an warning message to the console.
print_warning = lambda s: sys.stderr.write("WARNING: " + s)

def parse_args(args):
    """Parses command line arguments into a UtilData object."""
    arcctr = arcmgr.ArcCreator()
    arcctr.systargets = [os.path.abspath(t) for t in args['TARGET']]
    arcctr.name = args['--name']
    arcctr.logtxt = args['-m']
    if args['--long_ts']:
        arcctr.ts_style = "long"
    elif args['--short_ts']:
        arcctr.ts_style = "short"
    elif args['--no_ts']:
        arcctr.ts_style = "none"
    arcctr.delete = args['--delete']
    arcctr.flatten = args['--flatten']
    arcctr.flatten_ld = args['--flatten_ld']
    arcctr.outdir = args['--outdir']
    return arcctr

def main():
    """The application main logic."""
    args = docopt(__doc__, version=NAMEVER)
    arcctr = parse_args(args)
    if not arcctr.create_archive():
        print_error("Archive could not be created! %s" % arcctr.errmsg)
    if arcctr.warnmsgs:
        for w in arcctr.warnmsgs:
            print_warning(w)

##==============================================================#
## SECTION: Main Body                                           #
##==============================================================#

if __name__ == "__main__":
    main()


text:
function [g1, g2, g3] = sdlfmaXsdlfmvKernGradientBlock(lfmKern1, lfmKern2, ...
    t1, t2, kyy, kyv, kvy, kvv, i, j, generalConst, generalConstGrad, ...
    covGrad)

% SDLFMAXSDLFMVKERNGRADIENTBLOCK Gradients of the parameters in block i,j
% FORMAT
% DESC computes the kernel parameters gradients for the SDLFM kernel
% function in the block specified at indeces i,j. It assumes the
% computation for functions that system 1 describes an acceleration and
% system 2 describes a velocity.
% ARG lfmKern1 : structure containing parameters for the system 1
% ARG lfmKern2 : structure containing parameters for the system 2
% ARG t1 : times at which the system 1 is evaluated
% ARG t2 : times at which the system 2 is evaluated
% ARG kyy : covariance for the initial conditions between position 1 and
% position 2 at block i,j
% ARG kyv : covariance for the initial conditions between position 1 and
% velocity 2 at block i,j
% ARG kvy : covariance for the initial conditions between velocity 1 and
% position 2 at block i,j
% ARG kvv : covariance for the initial conditions between velocity 1 and
% velocity 2 at block i,j
% ARG i : interval to be evaluated for system 1
% ARG j : interval to be evaluated for system 2
% ARG generalConstant : constants evaluated with sdlfmKernComputeConstant.m
% ARG generalConstGrad : derivatives of the constants computed with
% sdlfmKernGradientConstant.m
% ARG covGrad : partial derivatives of the objective function wrt portion
% of the kernel matrix in block i,j
% RETURN g1 : gradients of parameters for the system 1
% RETURN g2 : gradients of parameters for the system 2
% RETURN g3 : gradients of switching points
%
% COPYRIGHT : Mauricio A. Alvarez, 2010.

% KERN

if nargin<11
    j = i;
    generalConst = [];
end

g3 = [];

% Compute derivatives of the mean terms with respect to the parameters

[g1Mean, g2Mean, gsp1Mean, gsp2Mean] = sdlfmKernGradientMean(lfmKern1(1), ...
    lfmKern2(1), t1, t2, kyy, kyv, kvy, kvv, covGrad, {'sdlfma','sdlfmv'}, ...
    {'sdlfmj', 'sdlfma'});

if i==j
    [g1, g2, g3t] = sdlfmaXsdlfmKernGradientBlockIEJ(lfmKern1, lfmKern2, t1, ...
        t2, covGrad, g1Mean, g2Mean, gsp1Mean, gsp2Mean, {'lfma', 'lfmv'}, ...
        {'lfmj', 'lfmv'}, {'lfma', 'lfma'});
    g3(i) = g3t;
else
    if i>j
        [g1, g2, g3] = sdlfmXsdlfmvKernGradientBlockIGJ(lfmKern1, lfmKern2, ...
            t1, t2, i, j, generalConst, generalConstGrad, covGrad, g1Mean, ...
            g2Mean, gsp1Mean, gsp2Mean, 'sdlfma', 'sdlfmj', 'lfmvXlfm', ...
            'lfmvXlfmv', {'lfmvXlfmv', 'lfmaXlfm'}, {'lfmaXlfmv', 'lfmaXlfmv'});
    else
        [g1, g2, g3] = sdlfmaXsdlfmKernGradientBlockILJ(lfmKern1, lfmKern2, ...
            t1, t2, i, j, generalConst, generalConstGrad, covGrad, g1Mean, ...
            g2Mean, gsp1Mean, gsp2Mean, 'sdlfmv', 'sdlfma', 'lfmaXlfm', ...
            'lfmaXlfmv',{'lfmjXlfm', 'lfmaXlfmv'}, {'lfmjXlfmv', 'lfmaXlfma'});
    end
end


text:
module GoogleMapsHelper
end


text:
describe('The helper functions', function () {

  describe('Test helpers', function () {
    beforeEach(function () {
      angular.module('mox').value('x', 1).value('y', 2);
    });

    describe('inject()', function () {
      it('should throw an exception when the injector is not yet ready', function () {
        expect(_.partial(mox.inject, 'x')).toThrow(Error('Sorry, cannot inject x because the injector is not ready yet. Please call mox.run() or inject()'));
      });

      describe('when there is one argument provided', function () {
        it('should return the service that is requested', function () {
          mox.module('mox').run();
          expect(mox.inject('x')).toBe(1);
        });
      });

      describe('when there are multiple arguments provided', function () {
        it('should return an object containing the services that are requested', function () {
          mox.module('mox').run();
          expect(mox.inject('x', 'y')).toEqual({
            x: 1,
            y: 2
          });
        });
      });
    });
  });

  describe('Angular shortcuts', function () {
    describe('createScope()', function () {
      beforeEach(function () {
        mox.module('mox').run();
      });

      it('should return a new non-isolate scope', inject(function ($rootScope) {
        var newScope = createScope();
        expect(newScope.$id).not.toBe($rootScope.$id);
        expect(newScope.$parent).toBe($rootScope);
      }));

      it('should fill the scope with the parameters', function () {
        expect(createScope({ key: 'value', key2: 'value2' })).toEqual(jasmine.objectContaining({ key: 'value', key2: 'value2' }));
      });

      it('should set the created scope on the currentSpec', function () {
        var newScope = createScope();
        var anotherScope = createScope();
        expect(this.$scope).not.toBe(newScope);
        expect(this.$scope).toBe(anotherScope);
      });
    });

    describe('createController()', function () {
      beforeEach(function () {
        angular.module('mox')
          .service('FooService', function () {
            this.foo = 'bar';
          })
          .controller('FooController', function ($scope, FooService) {
            this.$scope = $scope;
            this.FooService = FooService;
          });
        mox.module('mox').run();
      });

      it('should instantiate a controller with the last created scope', function () {
        var newScope = createScope();
        var controller = createController('FooController');
        expect(controller.$scope).toBe(newScope);
        expect(controller.FooService.foo).toBe('bar');
      });

      it('should instantiate a controller with the given scope', inject(function () {
        var newScope = createScope();
        var anotherScope = createScope();
        var controller = createController('FooController', newScope);
        expect(controller.$scope).toBe(newScope);
        expect(controller.$scope).not.toBe(anotherScope);
      }));

      it('should override injections if passed', function () {
        var controller = createController('FooController', createScope(), { FooService: 'mocked service' });
        expect(controller.FooService).toBe('mocked service');
      });
    });
  });

  describe('Compile shortcuts', function () {
    beforeEach(function () {
      mox.module('mox').run();
    });

    describe('compileHtml()', function () {
      it('should compile HTML and link it to the given scope', function () {
        expect(compileHtml('
{{scopeVar}}
', createScope({ scopeVar: 'contents' }))).toHaveText('contents');
      });

      describe('when there is not scope passed as argument', function () {
        it('should link to the last created scope', function () {
          createScope({ scopeVar: 'contents' });
          expect(compileHtml('
{{scopeVar}}
')).toHaveText('contents');
        });
      });

      it('should add the element to the current spec', function () {
        expect(compileHtml('

', createScope())).toBe(this.element);
      });

      describe('when the appendToBody parameter is not given or is truthy', function () {
        it('should append the compiled and linked element directly to the body', function () {
          compileHtml('

', createScope());
          expect(angular.element(document.body).find('#test')).toExist();
          expect(angular.element(document.body).find('#container #test')).not.toExist();
        });

        it('should only append the compile element to the body once', function () {
          compileHtml('

', createScope());
          compileHtml('

', createScope());
          expect(angular.element(document.body).find('#test')).not.toExist();
        });

        describe('when there is testTemplatePath and a testTemplateAppendSelector set', function () {
          beforeEach(function () {
            // See test/mock/html/container.html
            mox.testTemplatePath = 'container.html';
            mox.testTemplateAppendSelector = '#container';
          });

          it('should append the test template to the body and append the compiled element to the element in the test template with the testTemplateAppendSelector', function () {
            compileHtml('

', createScope());
            expect(angular.element(document.body).find('#container #test')).toExist();
          });
        });
      });

      describe('when the appendToBody parameter is falsy', function () {
        it('should not append the compiled and linked element to the body', function () {
          compileHtml('

', createScope(), false);
          var elem = angular.element(document.body).find('#test');
          expect(elem).not.toExist();
        });
      });
    });

    describe('compileTemplate()', function () {
      beforeEach(function () {
        inject(function ($templateCache) {
          $templateCache.put('test.html', '
{{scopeVar}}
');
        });
      });

      it('should retrieve the template, compile its HTML contents and link to the given scope', function () {
        expect(compileTemplate('test.html', createScope({ scopeVar: 'contents' }))).toHaveText('contents');
      });

      it('should wrap the template in a div, in case the template has no root element', function () {
        expect(compileTemplate('test.html', createScope()).find('#test')).toExist();
      });

      it('should pass the scope and appendToBody parameter to the function that compiles the HTML', function () {
        var origCompileHtml = compileHtml;
        compileHtml = jasmine.createSpy('compileHtml');
        compileTemplate('test.html', createScope(), true);
        expect(compileHtml).toHaveBeenCalledWith(jasmine.any(String), this.$scope, true);
        compileHtml = origCompileHtml;
      });

    });

    describe('addSelectors()', function () {
      var element;
      beforeEach(function () {
        element = compileHtml('\
        <root>\
          <element>\
            <child id="1">\
              <child></child>\
            </child>\
            <child id="2"></child>\
          </element>\
        </root>\
        ', createScope());
      });

      it('should add simple selector', function () {
        addSelectors(element, {
          simple: 'element',
          noMatch: 'xyz'
        });
        expect(element.simple()).toExist();
        expect(element.noMatch()).not.toExist();
      });

      it('should support object notation', function () {
        addSelectors(element, {
          full: {
            selector: 'element'
          }
        });
        expect(element.full()).toExist();
      });

      it('should add simple sub selectors', function () {
        addSelectors(element, {
          withSub: {
            selector: 'element',
            sub: {
              id1: '#1',
              id2: '#2',
              id3: '#3'
            }
          }
        });
        expect(element.withSub()).toExist();
        expect(element.withSub().id1()).toExist();
        expect(element.withSub().id2()).toExist();
        expect(element.withSub().id3()).not.toExist();
      });

      it('should add full object sub selector with sub of sub', function () {
        addSelectors(element, {
          withSub: {
            selector: 'element',
            sub: {
              id1: {
                selector: '#1',
                sub: {
                  subChild: 'child',
                  noMatch: 'element'
                }
              },
              noMatch: {
                selector: '#3',
                sub: {
                  noMatch: 'element'
                }
              }

            }
          }
        });
        expect(element.withSub()).toExist();
        expect(element.withSub().id1()).toExist();
        expect(element.withSub().id1().subChild()).toExist();
        expect(element.withSub().id1().noMatch()).not.toExist();
        expect(element.withSub().noMatch().noMatch()).not.toExist();
      });

      it('should add simple child selectors', function () {
        addSelectors(element, {
          withChild: {
            selector: 'element',
            children: ['child1', 'child2', 'child3']
          }
        });
        expect(element.withChild()).toExist();
        expect(element.withChild().child1()).toExist();
        expect(element.withChild().child2()).toExist();
        expect(element.withChild().child3()).not.toExist();
      });

      it('should add full object child selector with sub of sub', function () {
        addSelectors(element, {
          withChild: {
            selector: 'element',
            children: [{
              name: 'child1',
              sub: {
                subChild: 'child',
                noMatch: 'element'
              }
            }]
          }
        });
        expect(element.withChild()).toExist();
        expect(element.withChild().child1()).toExist();
        expect(element.withChild().child1().subChild()).toExist();
        expect(element.withChild().child1().noMatch()).not.toExist();
      });

      it('should replace placeholders in selectors', function () {
        addSelectors(element, {
          placeholder: 'element #{0}'
        });
        expect(element.placeholder()).not.toExist();
        expect(element.placeholder(1)).toExist();
        expect(element.placeholder(2)).toExist();
        expect(element.placeholder(3)).not.toExist();

        addSelectors(element, {
          placeholder2: '{0} {1}'
        });
        expect(element.placeholder2('element', 'child')).toExist();
      });

      it('should allow grouping of selectors without parent selectors', function () {
        addSelectors(element, {
          group1: {
            sub: {
              element: '#1'
            }
          },
          group2: {
            sub: {
              element: '#2'
            }
          }
        });
        expect(element.group1().element()).toHaveAttr('id', '1');
        expect(element.group2().element()).toHaveAttr('id', '2');
      });

      it('should allow overwriting existing selector functions on the element', function () {
        expect(element.root).toBeUndefined();
        addSelectors(element, {
          element: '#1'
        });
        addSelectors(element, {
          element: '#2'
        });
        expect(element.element()).toHaveAttr('id', '1');
      });

      it('should throw an exception when trying to overwrite existing properties on the element', function () {
        expect(function() {
          addSelectors(element, {
            val: 'element'
          });
        }).toThrow();

        element.abc = '1';
        expect(function() {
          addSelectors(element, {
            abc: 'element'
          });
        }).toThrow();
      });

      it('should support repeater definitions', function () {
        addSelectors(element, {
          childElements: {
            repeater: 'element > child',
            sub: {
              kid: 'child'
            }
          }
        });

        expect(element.childElements()).toHaveLength(2);
        expect(element.childElements(0).kid()).toExist();
        expect(element.childElements(1).kid()).not.toExist();
      });

      it('should ignore the children and sub definitions for the repeater itself', function () {
        addSelectors(element, {
          childElements: {
            repeater: 'element > child',
            sub: {
              kid: 'child'
            },
            children: ['kiddo']
          }
        });

        expect(element.childElements().kid).toBeUndefined();
        expect(element.childElements().kiddo).toBeUndefined();
        expect(element.childElements(0).kid).toBeDefined();
        expect(element.childElements(0).kiddo).toBeDefined();

      });
    });
  });
});


text:
/**
 *
 */
package snake;

import java.awt.Graphics2D;
import java.awt.event.KeyEvent;
import java.awt.image.BufferedImage;
import java.io.IOException;

import javax.imageio.ImageIO;

/**
 * @author Aaron
 *
 */
public class MenuState extends GameState {
	private BufferedImage background;

	/**
	 *
	 */
	public MenuState(GameStateManager gameStateManager) {
		this.setGameStateManager(gameStateManager);
		try {
			background = ImageIO.read(this.getClass().getResource("/images/menuBackground.png"));
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	@Override
	public void init() {
	}

	@Override
	public void update() {
	}

	@Override
	public void render(Graphics2D g2d) {
		g2d.drawImage(background, 0, 0, (int) (background.getWidth() * GamePanel.SCALE), (int) (background.getHeight() * GamePanel.SCALE), null);
	}

	@Override
	public void keyPressed(KeyEvent e) {
		if(e.getKeyCode() == KeyEvent.VK_SPACE){
			this.getGameStateManager().setGameState(GameStateManager.LEVELSTATE);
		}
	}

	@Override
	public void keyReleased(KeyEvent e) {
	}

	@Override
	public void keyTyped(KeyEvent e) {
	}

}


text:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<feed><tipo>Rua</tipo><logradouro>Ipê</logradouro><bairro>Carmelo</bairro><cidade>Passos</cidade><uf>MG</uf><cep>37900182</cep></feed>


text:
import {Iresource} from "./resource.interface";
import {Iobjective} from "./objective.interface";
import {ImonitorEffort} from "./monitoreffort.interface";
import {Ikeyword} from "./keyword.interface";
import {Idatahost} from "./datahost.interface";
import {Iorganizationresource} from "./organizationresource.interface";
import {Icontactresource} from "./contactresource.interface";
import {Ipublication} from "./publication.interface";

export interface Ifullproject {
    ProjectId: number;
    ScienceBaseId: string;
    Name: string;
    StartDate: Date;
    EndDate: Date;
    DataManagerId: number;
    status_id: number;
    Status: string;
    duration_id: number;
    Duration: string;
    Description: string;
    AdditionalInfo: string;
    Objectives: Array<Iobjective>;
    MonitoringCoords: Array<ImonitorEffort>;
    Keywords: Array<Ikeyword>;
    ProjectWebsite: string;
    DataHosts: Array<Idatahost>;
    Organizations: Array<Iorganizationresource>;
    Contacts: Array<Icontactresource>;
    Publications: Array<Ipublication>;
    created_stamp: Date;
    last_edited_stamp: Date;
}


text:
import pytest
from pycvs.cli import PyCvs

# Imports for mocking
import os.path
import shutil
import sys

def get_class(mocker):
    init = mocker.patch.object(PyCvs, '__init__')
    init.return_value = None

    return PyCvs()

def test_no_parameter(mocker):
    obj = get_class(mocker)
    mocker.patch.object(sys, 'argv', ['pycvs'])
    pint = mocker.patch('builtins.print')

    obj.process()

    pint.assert_called_once_with("Nothing to do")

def test_checkout_no_parameter(mocker):
    obj = get_class(mocker)
    mocker.patch.object(sys, 'argv', ['pycvs', 'checkout'])
    pint = mocker.patch('builtins.print')

    obj.process()

    pint.assert_called_once_with("Missing arguments for checkout command")

def test_co_no_parameter(mocker):
    obj = get_class(mocker)
    mocker.patch.object(sys, 'argv', ['pycvs', 'co'])
    pint = mocker.patch('builtins.print')

    obj.process()

    pint.assert_called_once_with("Missing arguments for co command")

def test_checkout_parameters(mocker):
    obj = get_class(mocker)
    mocker.patch.object(sys, 'argv', ['pycvs', 'co', 'module/', 'to', 'test'])
    check = mocker.patch.object(PyCvs, '_checkout')

    obj.process()

    check.assert_called_once_with(['module/', 'to', 'test'])


text:
package com.jeecms.core.tpl;

import static com.jeecms.common.web.Constants.UTF8;

import java.io.File;
import java.io.FileFilter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.io.FileUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.multipart.MultipartFile;

import com.jeecms.common.web.springmvc.RealPathResolver;

public class FileTplManagerImpl implements TplManager {
	private static Logger log = LoggerFactory
			.getLogger(FileTplManagerImpl.class);

	public int delete(String[] names) {
		File f;
		int count = 0;
		for (String name : names) {
			f = new File(realPathResolver.get(name));
			if (f.isDirectory()) {
				if (FileUtils.deleteQuietly(f)) {
					count++;
				}
			} else {
				if (f.delete()) {
					count++;
				}
			}
		}
		return count;
	}

	public Tpl get(String name) {
		File f = new File(realPathResolver.get(name));
		if (f.exists()) {
			return new FileTpl(f, root);
		} else {
			return null;
		}
	}

	public List<Tpl> getListByPrefix(String prefix) {
		File f = new File(realPathResolver.get(prefix));
		String name = prefix.substring(prefix.lastIndexOf("/") + 1);
		File parent;
		if (prefix.endsWith("/")) {
			name = "";
			parent = f;
		} else {
			parent = f.getParentFile();
		}
		if (parent.exists()) {
			File[] files = parent.listFiles(new PrefixFilter(name));
			if (files != null) {
				List<Tpl> list = new ArrayList<Tpl>();
				for (File file : files) {
					list.add(new FileTpl(file, root));
				}
				return list;
			} else {
				return new ArrayList<Tpl>(0);
			}
		} else {
			return new ArrayList<Tpl>(0);
		}
	}

	public List<String> getNameListByPrefix(String prefix) {
		List<Tpl> list = getListByPrefix(prefix);
		List<String> result = new ArrayList<String>(list.size());
		for (Tpl tpl : list) {
			result.add(tpl.getName());
		}
		return result;
	}

	public List<Tpl> getChild(String path) {
		File file = new File(realPathResolver.get(path));
		File[] child = file.listFiles();
		if (child != null) {
			List<Tpl> list = new ArrayList<Tpl>(child.length);
			for (File f : child) {
				list.add(new FileTpl(f, root));
			}
			return list;
		} else {
			return new ArrayList<Tpl>(0);
		}
	}

	public void rename(String orig, String dist) {
		String os = realPathResolver.get(orig);
		File of = new File(os);
		String ds = realPathResolver.get(dist);
		File df = new File(ds);
		try {
			if (of.isDirectory()) {
				FileUtils.moveDirectory(of, df);
			} else {
				FileUtils.moveFile(of, df);
			}
		} catch (IOException e) {
			log.error("Move template error: " + orig + " to " + dist, e);
		}
	}

	public void save(String name, String source, boolean isDirectory) {
		String real = realPathResolver.get(name);
		File f = new File(real);
		if (isDirectory) {
			f.mkdirs();
		} else {
			try {
				FileUtils.writeStringToFile(f, source, UTF8);
			} catch (IOException e) {
				log.error("Save template error: " + name, e);
				throw new RuntimeException(e);
			}
		}
	}

	public void save(String path, MultipartFile file) {
		File f = new File(realPathResolver.get(path), file
				.getOriginalFilename());
		try {
			file.transferTo(f);
		} catch (IllegalStateException e) {
			log.error("upload template error!", e);
		} catch (IOException e) {
			log.error("upload template error!", e);
		}
	}

	public void update(String name, String source) {
		String real = realPathResolver.get(name);
		File f = new File(real);
		try {
			FileUtils.writeStringToFile(f, source, UTF8);
		} catch (IOException e) {
			log.error("Save template error: " + name, e);
			throw new RuntimeException(e);
		}
	}

	private String root;

	private RealPathResolver realPathResolver;

	@Autowired
	public void setRealPathResolver(RealPathResolver realPathResolver) {
		this.realPathResolver = realPathResolver;
		root = realPathResolver.get("");
	}

	private static class PrefixFilter implements FileFilter {
		private String prefix;

		public PrefixFilter(String prefix) {
			this.prefix = prefix;
		}

		public boolean accept(File file) {
			String name = file.getName();
			return file.isFile() && name.startsWith(prefix);
		}
	}

}


text:
module Administration
  VERSION = "0.0.1"
end