text:
"""Image Processing SciKit (Toolbox for SciPy)"""

import os.path as _osp

data_dir = _osp.abspath(_osp.join(_osp.dirname(__file__), 'data'))

from version import version as __version__

def _setup_test():
    import functools

    basedir = _osp.dirname(_osp.join(__file__, '../'))
    args = ['', '--exe', '-w', '%s' % basedir]

    try:
        import nose as _nose
    except ImportError:
        print("Could not load nose.  Unit tests not available.")
        return None
    else:
        return functools.partial(_nose.run, 'scikits.image', argv=args)

test = _setup_test()
if test is None:
    del test

def get_log(name):
    """Return a console logger.

    Output may be sent to the logger using the `debug`, `info`, `warning`,
    `error` and `critical` methods.

    Parameters
    ----------
    name : str
        Name of the log.

    References
    ----------
    .. [1] Logging facility for Python,
           http://docs.python.org/library/logging.html

    """
    import logging, sys
    logging.basicConfig(stream=sys.stdout, level=logging.DEBUG)
    return logging.getLogger(name)


text:
package lab.s2jh.auth.entity;

import java.util.List;

import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import javax.persistence.Transient;

import lab.s2jh.core.annotation.MetaData;
import lab.s2jh.core.entity.BaseEntity;
import lab.s2jh.core.entity.annotation.EntityAutoCode;

import org.hibernate.annotations.Cache;
import org.hibernate.annotations.CacheConcurrencyStrategy;
import org.hibernate.annotations.GenericGenerator;

import com.fasterxml.jackson.annotation.JsonIgnore;
import com.google.common.collect.Lists;

/**
 * 权限控制资源,指对菜单、按钮、URL等访问控制点
 *
 */
@Entity
@Table(name = "T_AUTH_PRIVILEGE")
@MetaData(title = "权限")
@Cache(usage = CacheConcurrencyStrategy.READ_WRITE)
public class Privilege extends BaseEntity<String> {

    @MetaData(title = "分类")
    @EntityAutoCode(order = 5, search = true)
    private String category;

    @MetaData(title = "代码")
    @EntityAutoCode(order = 10, search = true)
    private String code;

    @MetaData(title = "名称")
    @EntityAutoCode(order = 20, search = true)
    private String title;

    @MetaData(title = "URL")
    @EntityAutoCode(order = 30, search = true)
    private String url;

    @MetaData(title = "描述")
    @EntityAutoCode(listShow = false)
    private String description;

    @MetaData(title = "禁用标识", description = "禁用不参与权限控制逻辑")
    @EntityAutoCode(order = 40, search = true)
    private Boolean disabled = Boolean.FALSE;

    /**
     * 权限控制的优先级,数字越大匹配优先级越高,大部分情况无需要考虑此属性,直接默认值即可;
     * 如果权限URL部分由包含关系需要用到此属性,具体请查看Spring Security对于URL匹配规则说明
     */
    @MetaData(title = "排序号", description = "权限控制的优先级,数字越大匹配优先级越高")
    @EntityAutoCode(order = 50)
    private Integer orderRank = 100;

    @MetaData(title = "角色权限关联")
    private List<RoleR2Privilege> roleR2Privileges = Lists.newArrayList();

    private String id;

    @Id
    @Column(length = 40)
    @GeneratedValue(generator = "hibernate-uuid")
    @GenericGenerator(name = "hibernate-uuid", strategy = "uuid")
    public String getId() {
        return id;
    }

    public void setId(final String id) {
        this.id = id;
    }

    @Column(nullable = false, length = 256)
    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    @Column(nullable = true, length = 2000)
    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }

    @Column(nullable = false, unique = true, length = 64)
    public String getCode() {
        return code;
    }

    public void setCode(String code) {
        this.code = code;
    }

    public Boolean getDisabled() {
        return disabled;
    }

    public void setDisabled(Boolean disabled) {
        this.disabled = disabled;
    }

    public Integer getOrderRank() {
        return orderRank;
    }

    public void setOrderRank(Integer orderRank) {
        this.orderRank = orderRank;
    }

    @Column(nullable = true, length = 512)
    public String getUrl() {
        return url;
    }

    public void setUrl(String url) {
        this.url = url;
    }

    @Column(nullable = false, length = 128)
    public String getCategory() {
        return category;
    }

    public void setCategory(String category) {
        this.category = category;
    }

    @Override
    @Transient
    public String getDisplayLabel() {
        return title;
    }

    @OneToMany(mappedBy = "privilege", cascade = CascadeType.ALL, orphanRemoval = true)
    @JsonIgnore
    public List<RoleR2Privilege> getRoleR2Privileges() {
        return roleR2Privileges;
    }

    public void setRoleR2Privileges(List<RoleR2Privilege> roleR2Privileges) {
        this.roleR2Privileges = roleR2Privileges;
    }
}

redpajama_set_name: RedPajamaGithub


text:
include_recipe "tomcat7::set_catalina_home"
include_recipe "tomcat7::set_catalina_base"

directory "#{node[:tomcat7][:artifact_dir]}" do
  mode "0755"
  action :create
  not_if { File.directory?("#{node[:tomcat7][:artifact_dir]}") }
end

directory "#{node[:tomcat7][:InstallLocation]}" do
  mode "0755"
  owner node[:tomcat7][:user]
  group node[:tomcat7][:group]
  action :create
end

remote_file "download_tomcat7" do
  path "#{node[:tomcat7][:artifact_dir]}/#{node[:tomcat7][:FileName]}"
  source "#{node[:tomcat7][:url]}/#{node[:tomcat7][:FileName]}"
  backup false
  mode "0644"
  checksum node[:tomcat7][:checksum]
  action :create
end

tar_opts = (node[:tomcat7][:InstallName] ? "--strip-components=1 -C #{node[:tomcat7][:InstallLocation]}/#{node[:tomcat7][:InstallName]}" : "-C #{node[:tomcat7][:InstallLocation]}")

bash "install_tomcat7" do
  code <<-EOF
      cd #{node[:tomcat7][:artifact_dir]}
      tar xvfz #{node[:tomcat7][:artifact_dir]}/#{node[:tomcat7][:FileName]} #{tar_opts}
  EOF
  action :run
  user node[:tomcat7][:user]
  group node[:tomcat7][:group]
end

template '/etc/init.d/tomcat7' do
  source 'tomcat.init.erb'
  mode "0755"
end


text:
KISSY.add(function (S, UA, Node, Overlay) {
    describe("view", function () {
        it("should reflect after create", function () {
            var overlay = new Overlay({
                content:"haha"
            });
            overlay.create();
            overlay.set("visible", false);
            overlay.render();
            expect(overlay.get("visible")).toBe(false);
            expect(overlay.get("el").css('visibility')).toBe("hidden");
            overlay.destroy();
        });

        it("should show after call hide after create", function () {
            var overlay = new Overlay({
                content:"haha"
            });
            overlay.create();
            overlay.hide();
            overlay.show();
            expect(overlay.get("visible")).toBe(true);
            expect(overlay.get("el").css('visibility')).not.toBe('hidden');
            overlay.destroy();
        });
    });
},{
    requires:"ua,node,overlay".split(',')
});


text:
@interface VSNetworkTableViewController : VSBaseTableViewController
<VSNetworkDataConstructorDelegate>

@end


text:
import { ChangeDetectionStrategy, Component } from '@angular/core';
import { select, Store } from '@ngrx/store';
import { FormGroupState, ResetAction, SetValueAction } from 'ngrx-forms';
import { Observable } from 'rxjs';
import { filter, map, take } from 'rxjs/operators';

import { FormValue, INITIAL_STATE, SetSubmittedValueAction, State } from './sync-validation.reducer';

@Component({
  selector: 'ngf-sync-validation',
  templateUrl: './sync-validation.component.html',
  styleUrls: ['./sync-validation.component.scss'],
  changeDetection: ChangeDetectionStrategy.OnPush,
})
export class SyncValidationPageComponent {
  formState$: Observable<FormGroupState<FormValue>>;
  submittedValue$: Observable<FormValue | undefined>;

  days = Array.from(Array(31).keys());
  months = [
    'January',
    'Febuary',
    'March',
    'April',
    'May',
    'June',
    'July',
    'August',
    'September',
    'October',
    'November',
    'December',
  ];
  years = Array.from(Array(115).keys()).map(i => i + 1910);

  constructor(private store: Store<State>) {
    this.formState$ = store.pipe(select(s => s.syncValidation.formState));
    this.submittedValue$ = store.pipe(select(s => s.syncValidation.submittedValue));
  }

  reset() {
    this.store.dispatch(new SetValueAction(INITIAL_STATE.id, INITIAL_STATE.value));
    this.store.dispatch(new ResetAction(INITIAL_STATE.id));
  }

  submit() {
    this.formState$.pipe(
      take(1),
      filter(s => s.isValid),
      map(fs => new SetSubmittedValueAction(fs.value)),
    ).subscribe(this.store);
  }
}


text:
/**
 * @author sabidib http://github.com/sabidib
 */
/**
 * Creates a 2D Monomer
 * @constructor
 * @param {[Float]} radius     [The radius of the Monomer]
 * @param {[Float]} charge     [The charge of the Monomer, default 0]
 * @param {[Float]} mass       [The mass of the Monomer, default 0]
 * @param {[Object]} [kinematics] [An object with propeties : position , velocity, acceleration, force]
 * @param  {String} [name]        [The name of the entity]
 * @param   {Object} [renderableSettings] [An object containing any of the following keys 'segments'(float),
 * 'color'(hex) or 'material'(THREE.mesh). This is completely optional]
 */
/*global Flory,THREE*/
/*jslint white*/

'use strict';
Flory.Monomer2D = function (options) {
    var name = options.name;
    Flory.Particle.call(this, name);
    var radius = options.radius;
    var charge = options.charge;
    var mass = options.mass;
    var kinematics = options.kinematics;
    var renderableSettings = options.renderableSettings;
    var position = options.position;
    var velocity = options.velocity;
    var acceleration = options.acceleration;
    var force = options.force;
    this.dimension = 2;
    if (kinematics !== undefined) {
        position = position === undefined ? kinematics.position : position;
        velocity = velocity === undefined ? kinematics.velocity : velocity;
        acceleration = acceleration === undefined ? kinematics.acceleration : acceleration;
        force = force === undefined ? kinematics.force : force;
    }
    this.radius = radius !== undefined ? radius : Flory.Monomer2D.defaultRadius;
    this.charge = charge !== undefined ? charge : 0;
    this.mass = mass !== undefined ? mass : 0;
    if (position === undefined) {
        this.position = new Flory.Vector2(0, 0);
    } else if (position instanceof Array) {
        this.position = new Flory.Vector2(position[0], position[1]);
    } else if (position.x !== undefined || position.y !== undefined) {
        this.position = new Flory.Vector2(position.x, position.y);
    } else {
        if (!(position instanceof Flory.baseVector)) {
            console.log('Flory: position is not a valid Flory.baseVector .');
            return undefined;
        }
        if (position instanceof Flory.Vector3) {
            this.position = new Flory.Vector2(position.x, position.y);
        } else if (position instanceof Flory.Vector) {
            this.position = new Flory.Vector2(position.components[0], position.components[1]);
        } else {
            this.position = position.clone();
        }
    }
    if (velocity === undefined) {
        this.velocity = new Flory.Vector2(0, 0);
    } else if (velocity instanceof Array) {
        this.velocity = new Flory.Vector2(velocity[0], velocity[1]);
    } else if (velocity.x !== undefined || velocity.y !== undefined) {
        this.velocity = new Flory.Vector2(velocity.x, velocity.y);
    } else {
        if (!(velocity instanceof Flory.baseVector)) {
            console.log('Flory: velocity is not a valid Flory.baseVector .');
            return undefined;
        }
        if (velocity instanceof Flory.Vector3) {
            this.velocity = new Flory.Vector2(velocity.x, velocity.y);
        } else if (velocity instanceof Flory.Vector) {
            this.velocity = new Flory.Vector2(velocity.components[0], velocity.components[1]);
        } else {
            this.velocity = velocity.clone();
        }
    }
    if (acceleration === undefined) {
        this.acceleration = new Flory.Vector2(0, 0);
    } else if (acceleration instanceof Array) {
        this.acceleration = new Flory.Vector2(acceleration[0], acceleration[1]);
    } else if (acceleration.x !== undefined || acceleration.y !== undefined) {
        this.acceleration = new Flory.Vector2(acceleration.x, acceleration.y);
    } else {
        if (!(acceleration instanceof Flory.baseVector)) {
            console.log('Flory: acceleration is not a valid Flory.baseVector .');
            return undefined;
        }
        if (acceleration instanceof Flory.Vector3) {
            this.acceleration = new Flory.Vector2(acceleration.x, acceleration.y);
        } else if (acceleration instanceof Flory.Vector) {
            this.acceleration = new Flory.Vector2(acceleration.components[0], acceleration.components[1]);
        } else {
            this.acceleration = acceleration.clone();
        }
    }
    if (force === undefined) {
        this.force = new Flory.Vector2(0, 0);
    } else if (force instanceof Array) {
        this.force = new Flory.Vector2(force[0], force[1]);
    } else if (force.x !== undefined || force.y !== undefined) {
        this.force = new Flory.Vector2(force.x, force.y);
    } else {
        if (!(force instanceof Flory.baseVector)) {
            console.log('Flory: force is not a valid Flory.baseVector .');
            return undefined;
        }
        if (force instanceof Flory.Vector3) {
            this.force = new Flory.Vector2(force.x, force.y);
        } else if (force instanceof Flory.Vector) {
            this.force = new Flory.Vector2(force.components[0], force.components[1]);
        } else {
            this.force = force.clone();
        }
    }
    this.setDefaultMesh(renderableSettings);
    return this
};
Flory.Monomer2D.prototype = Object.create(Flory.Particle.prototype);
Flory.Monomer2D.prototype.setDefaultMesh = function (settings) {
    var material = {};
    var geometry = {};
    var segments = settings !== undefined && typeof settings.segments === 'number' ? settings.segments : 20;
    var dim = this.position.dimension();
    geometry = new THREE.SphereGeometry(this.radius, segments, segments);
    var color_of_mesh = settings !== undefined && typeof settings.color === 'number' ? settings.color : 16711680;
    if (settings === undefined) {
        material = new THREE.MeshBasicMaterial({ color: color_of_mesh });
    } else if (settings.material !== undefined && settings.material instanceof THREE.Material) {
        material = settings.material;
    } else {
        material = new THREE.MeshBasicMaterial({ color: color_of_mesh });
    }
    this.geometry = geometry;
    this.material = material;
    this.mesh = new THREE.Mesh(geometry, material);
    return this;
};
Flory.Monomer2D.prototype.incrementX = function (amount) {
    this.position.x += amount;
    return this;
};
Flory.Monomer2D.prototype.incrementY = function (amount) {
    this.position.y += amount;
    return this;
};
Flory.Monomer2D.prototype.distanceTo = function (a) {
    return this.position.distanceTo(a.position);
};
Flory.Monomer2D.prototype.distanceToSq = function (a) {
    return this.position.distanceToSq(a.position);
};
Flory.Monomer2D.prototype.clone = function () {
    return new Flory.Monomer2D(this.radius, this.position);
};
Flory.Monomer2D.defaultRadius = 1;


text:
package backend.analysis;

import backend.type.Type;
import backend.value.Loop;
import tools.Pair;
import tools.Util;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.HashMap;

/**
 * @author Jianping Zeng
 * @version 0.4
 */
public abstract class SCEVCommutativeExpr extends SCEV {
  /**
   * A cache for keeping only SCEVMulExpr instance of a pair of two SCEV value.
   */
  protected static final HashMap<Pair<SCEVType, ArrayList<SCEV>>, SCEVCommutativeExpr>
      scevCommExprsMap = new HashMap<>();

  protected ArrayList<SCEV> operands;

  protected SCEVCommutativeExpr(SCEVType scevType, ArrayList<SCEV> ops) {
    super(scevType);
    operands = new ArrayList<>(ops.size());
    operands.addAll(ops);
  }

  public final int getNumOperands() {
    return operands.size();
  }

  public final SCEV getOperand(int index) {
    Util.assertion(index >= 0 && index < operands.size());
    return operands.get(index);
  }

  public final ArrayList<SCEV> getOperands() {
    return operands;
  }

  @Override
  public final boolean isLoopInvariant(Loop loop) {
    for (SCEV val : operands)
      if (!val.isLoopInvariant(loop)) return false;

    return true;
  }

  @Override
  public final boolean hasComputableLoopEvolution(Loop loop) {
    boolean hasVaring = false;
    for (SCEV val : operands)
      if (!val.isLoopInvariant(loop)) {
        if (val.hasComputableLoopEvolution(loop))
          hasVaring = true;
        else
          return false;
      }
    return hasVaring;
  }

  @Override
  public final SCEV replaceSymbolicValuesWithConcrete(SCEV sym, SCEV concrete) {
    for (int i = 0, e = operands.size(); i < e; i++) {
      SCEV midd = operands.get(i).replaceSymbolicValuesWithConcrete(sym, concrete);
      if (!midd.equals(operands.get(i))) {
        ArrayList<SCEV> res = new ArrayList<>(getNumOperands());
        for (int j = 0; j < i; j++)
          res.add(getOperand(j));

        res.add(midd);
        for (int j = i + 1; j < e; j++)
          res.add(operands.get(j));

        if (this instanceof SCEVAddExpr)
          return SCEVAddExpr.get(res);
        if (this instanceof SCEVMulExpr)
          return SCEVMulExpr.get(res);

        Util.assertion(false, "Invalid comutative opr!");
      }
    }
    return this;
  }

  public abstract String getOperationString();

  public Type getType() {
    return getOperand(0).getType();
  }

  /**
   * Return true if the complexity of the lhs is less than the complexity of
   * rhs. This comparator is used for canonical expression.
   */
  public static Comparator<SCEV> SCEVComplexityCompare = new Comparator<SCEV>() {
    @Override
    public int compare(SCEV o1, SCEV o2) {
      return o1.getSCEVType().ordinal() - o2.getSCEVType().ordinal();
    }
  };

  public static void groupByComplexity(ArrayList<SCEV> ops) {
    if (ops.size() < 2) return;

    if (ops.size() == 2) {
      if (ops.get(0).getSCEVType().ordinal() > ops.get(1).getSCEVType().ordinal()) {
        SCEV temp = ops.get(0);
        ops.set(0, ops.get(1));
        ops.set(1, temp);
      }
      return;
    }
    // do the rough sort by complexity.
    ops.sort(SCEVComplexityCompare);

    // Now that we are sorted by complexity, group elements of the same
    // complexity.  Note that this is, at worst, N^2, but the vector is likely to
    // be extremely short in practice.  Note that we take this approach because we
    // do not want to depend on the addresses of the objects we are grouping.
    for (int i = 0, e = ops.size(); i < e - 2; i++) {
      SCEV val = ops.get(i);
      int complexity = val.getSCEVType().ordinal();

      for (int j = i + 1; j < e && ops.get(j).getSCEVType().ordinal() == complexity; j++) {
        if (ops.get(j).equals(val)) {
          // Move the j'th element to immediately after i'th element.
          SCEV temp = ops.get(i + 1);
          ops.set(i + 1, ops.get(j));
          ops.set(j, temp);
          // avoids rescan.
          i++;
          if (i == e - 2) return;
        }
      }
    }
  }
}


text:
<!DOCTYPE frameset SYSTEM "frameset.dtd">
<frameset>
    <predicate lemma="halt">

        <roleset framnet="Halt  Activity_stop" id="halt.01" name="stop" vncls="45.4  55.4">
            <roles>
                <role descr="causer of stopping" f="" n="0">
                    <vnrole vncls="55.4" vntheta="agent"/>
                    <vnrole vncls="45.4" vntheta="agent"/>
                </role>
                <role descr="Theme (action or object being stopped)" f="" n="1">
                    <vnrole vncls="55.4" vntheta="theme"/>
                    <vnrole vncls="45.4" vntheta="patient"/>
                </role>
                <role descr="Instrument, if separate from arg0" f="" n="2">
                    <vnrole vncls="45.4" vntheta="instrument"/>
                    <vnrole vncls="55.4" vntheta="instrument"/>
                </role>

                <note>Higher numbered args might or might not occur; refer to 'stop' for
                    usage of them.
                </note>
            </roles>

            <example name="transitive active" src="" type="">
                <text>While program trades swiftly kicked in, a ``circuit breaker'' that-1
                    *trace*-1 halted trading in stock futures in Chicago made some
                    program trading impossible.
                </text>
                <arg f="" n="0">*trace*-1     (= that)</arg>
                <arg f="slc" n="m">that -> a ``circuit breaker''</arg>
                <rel f="">halted</rel>
                <arg f="" n="1">trading in stock futures in Chicago</arg>

                <note/>
            </example>

            <example name="passivized" src="" type="">
                <text>Cineplex traded on the New York Stock Exchange at $11.25 a share,
                    up $1.125, before trading-1 was halted *trace*-1.
                </text>
                <rel f="">halted</rel>
                <arg f="" n="1">*trace*</arg>

                <note/>
            </example>

            <note>Verbnet class other_cos-45.4, stop-55.4. Comparison with 'stop'.VN, FN updated by Julia.</note>
        </roleset>

        <roleset framnet="-" id="halt.02" name="halt from" vncls="-">
            <roles>
                <role descr="primary agent, preventer" f="" n="0"/>

                <role descr="secondary agent, entity coming to to a halt" f="" n="1"/>
                <role descr="action secondary agent is kept from" f="" n="2"/>

                <note/>
            </roles>

            <example name="All args" src="WSJ" type="-">
                <inflection aspect="ns" form="infinitive" person="third" tense="ns" voice="active"/>
                <text>Gold and silver broker Preston Semel asked [a federal court]-1 *PRO*-1 to halt the Commodity Exchange from imposing a record $ 550,000 fine on his firm .</text>

                <arg f="" n="0">*PRO*-1</arg>
                <rel f="">halt</rel>
                <arg f="" n="1">the Commodity Exchange</arg>
                <arg f="" n="2">from imposing a record $ 550,000 fine on his firm</arg>

                <note/>
            </example>

            <note>Added by Julia based on WSJ. Comparison to stop.03-- note the syntactic difference between stop.01 and stop.03. No. Vncls.</note>
        </roleset>

        <note>Frames file for 'halt' based on sentences in financial subcorpus.</note>
    </predicate>

    <note/>
</frameset>


text:
.debugger {

}

.debugger-menu {
  position: absolute;
  top: 20;
  right: 0;
}

.debugger input[type="button"] {
  background: white;
  border: 1px solid lightgray;
  border-radius: 2px;
  box-shadow: 0 0 4px 2px #f5f5f5;
  padding: 5px 10px;
  margin: 5px;
}

.debugger input[type="button"]:hover {
  background: #f1f1f1;
}

.debugger input[type="button"]:disabled {
  background: lightgray;
}


text:
import { PitchShift } from "./PitchShift";
import { BasicTests } from "test/helper/Basic";
import { EffectTests } from "test/helper/EffectTests";
import { expect } from "chai";
import { Oscillator } from "Tone/source/oscillator/Oscillator";
import { CompareToFile } from "test/helper/CompareToFile";

describe("PitchShift", () => {

	BasicTests(PitchShift);
	EffectTests(PitchShift);

	it("matches a file", () => {
		return CompareToFile(() => {
			const pitchShift = new PitchShift(4).toDestination();
			const osc = new Oscillator().toDestination().connect(pitchShift);
			osc.start(0);
		}, "pitchShift.wav", 0.3);
	});

	context("API", () => {

		it("can pass in options in the constructor", () => {
			const pitchShift = new PitchShift({
				windowSize: 0.2,
				pitch: 2
			});
			expect(pitchShift.windowSize).to.be.closeTo(0.2, 0.01);
			expect(pitchShift.pitch).to.be.closeTo(2, 0.01);
			pitchShift.dispose();
		});

		it("can set positive and negative pitches", () => {
			const pitchShift = new PitchShift();
			pitchShift.pitch = 2;
			expect(pitchShift.pitch).to.be.equal(2);
			pitchShift.pitch = -2;
			expect(pitchShift.pitch).to.be.equal(-2);
			pitchShift.pitch = -4.5;
			expect(pitchShift.pitch).to.be.equal(-4.5);
			pitchShift.dispose();
		});

		it("can get/set the options", () => {
			const pitchShift = new PitchShift();
			pitchShift.set({
				windowSize: 0.4,
			});
			expect(pitchShift.get().windowSize).to.be.closeTo(0.4, 0.01);
			pitchShift.dispose();
		});

		it("can set set the feedback and delay times", () => {
			const pitchShift = new PitchShift({
				delayTime: "4n",
				feedback: 0.3
			});
			expect(pitchShift.delayTime.value).to.be.closeTo(pitchShift.toSeconds("4n"), 0.01);
			expect(pitchShift.feedback.value).to.be.closeTo(0.3, 0.01);
			pitchShift.delayTime.value = 0.2;
			expect(pitchShift.delayTime.value).to.be.closeTo(0.2, 0.01);
			pitchShift.dispose();
		});
	});
});


text:
class Admin::UsersController < Admin::BaseController

  def index
    @users = User.asc(:nickname)
  end
end


text:
package com.algorithm.sorting;

import org.junit.AfterClass;
import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit.Test;

import java.util.*;

/**
 * @author Chris, Z
 * @date Aug 23, 2012 3:29:43 PM
 */
public class SortingJUnit {

    private static Integer[] srcArr;
    private static boolean ascending = true;
    private static Map<String, Long> map = new HashMap<>();

    @BeforeClass
    public static void beforeStart() {
        int size = 50000;
		System.out.printf("Size  : %d\n", size);
        srcArr = generateArray(size);
//		srcArr = new Integer[] {3, 1, 5, 8, 1, 2};
        map = new HashMap<>();
    }

    @AfterClass
    public static void afterFinish() {
        List<Map.Entry<String, Long>> list = new LinkedList<Map.Entry<String, Long>>(map.entrySet());
        Collections.sort(list, Comparator.comparingLong(Map.Entry::getValue));
        Iterator<Map.Entry<String, Long>> it = list.iterator();
        while (it.hasNext()) {
            Map.Entry<String, Long> next = it.next();
            System.out.printf("%-6s: [%-3sms]\n", next.getKey(), next.getValue());
        }
    }

    private void sort(SortingType type) {
        Integer[] myArr = srcArr.clone();
        Assert.assertFalse(isOrdered(myArr, ascending));
        long start = Calendar.getInstance().getTimeInMillis();
        type.sort(myArr, ascending);
        map.put(type.name(), Calendar.getInstance().getTimeInMillis() - start);
        Assert.assertTrue(isOrdered(myArr, ascending));
    }

    private static Integer[] generateArray(int length) {
        Integer[] arr = new Integer[length];
        Random random = new Random();
        for (int i = 0; i < arr.length; i++) {
            arr[i] = random.nextInt(arr.length * 10);
        }
        return arr;
    }

    private static boolean isOrdered(Comparable[] arr, boolean ascending) {
        boolean isOrdered = true;
        for (int i = 1; i < arr.length; i++) {
            int res = arr[i - 1].compareTo(arr[i]);
            if (res != 0 && res > 0 == ascending) {
                isOrdered = false;
                break;
            }
        }
        return isOrdered;
    }

	@Test
    public void bubble() {
        sort(SortingType.BUBBLE);
    }

	@Test
    public void insert() {
        sort(SortingType.INSERT);
    }

    @Test
    public void select() {
        sort(SortingType.SELECT);
    }

//	@Test
    public void shell() {
        sort(SortingType.SHELL);
    }

//    @Test
    public void heap() {
        sort(SortingType.HEAP);
    }

//    @Test
    public void merge() {
        sort(SortingType.MERGE);
    }

//    @Test
    public void java() {
        sort(SortingType.JAVA);
    }

//    @Test
    public void quick() {
        sort(SortingType.QUICK);
    }

}


text:
define('type/config/Boolean',['util/is'],
function(is){

	return {
		//the name associated with this type...
		name:'Boolean',

		//the accessor is what is used to identify a type
		//custom types expose some kind of accessor, and
		//expose these under types like datapath.types.ObjectId
		accessorAlias:Boolean,

		//the options that this type accepts
		options:['range'],

		//this is required for validation.
		//the datum to be validated is passed in as the first argument
		//and the options specified for the schema primitive are passed in
		//so that decisions can be made dynamically...
		isValid:function(datum, options){
			return is.Boolean(datum);
		}

	};

});


text:
package org.springframework.cloud.context.properties;

import static org.junit.Assert.assertEquals;

import java.util.List;
import java.util.Map;

import javax.annotation.PostConstruct;

import org.junit.Ignore;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.PropertyPlaceholderAutoConfiguration;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.boot.test.EnvironmentTestUtils;
import org.springframework.boot.test.IntegrationTest;
import org.springframework.boot.test.SpringApplicationConfiguration;
import org.springframework.cloud.autoconfigure.ConfigurationPropertiesRebinderAutoConfiguration;
import org.springframework.cloud.autoconfigure.RefreshAutoConfiguration;
import org.springframework.cloud.context.properties.ConfigurationPropertiesRebinderListIntegrationTests.TestConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.test.annotation.DirtiesContext;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

@SpringApplicationConfiguration(classes=TestConfiguration.class)
@RunWith(SpringJUnit4ClassRunner.class)
@IntegrationTest("messages=one,two")
public class ConfigurationPropertiesRebinderListIntegrationTests {

	@Autowired
	private TestProperties properties;

	@Autowired
	private ConfigurationPropertiesRebinder rebinder;

	@Autowired
	private ConfigurableEnvironment environment;

	@Test
	@DirtiesContext
	public void testAppendProperties() throws Exception {
		assertEquals("[one, two]", this.properties.getMessages().toString());
		EnvironmentTestUtils.addEnvironment(this.environment, "messages[0]:foo");
		this.rebinder.rebind();
		assertEquals("[foo, two]", this.properties.getMessages().toString());
	}

	@Test
	@DirtiesContext
	@Ignore("Can't rebind to list and re-initialize it (need refresh scope for this to work)")
	public void testReplaceProperties() throws Exception {
		assertEquals("[one, two]", this.properties.getMessages().toString());
		@SuppressWarnings("unchecked")
		Map<String,Object> map = (Map<String, Object>) this.environment.getPropertySources().get("integrationTest").getSource();
		map.clear();
		EnvironmentTestUtils.addEnvironment(this.environment, "messages[0]:foo");
		this.rebinder.rebind();
		assertEquals("[foo]", this.properties.getMessages().toString());
	}

	@Test
	@DirtiesContext
	public void testReplacePropertiesWithCommaSeparated() throws Exception {
		assertEquals("[one, two]", this.properties.getMessages().toString());
		@SuppressWarnings("unchecked")
		Map<String,Object> map = (Map<String, Object>) this.environment.getPropertySources().get("integrationTest").getSource();
		map.clear();
		EnvironmentTestUtils.addEnvironment(this.environment, "messages:foo");
		this.rebinder.rebind();
		assertEquals("[foo]", this.properties.getMessages().toString());
	}

	@Configuration
	@EnableConfigurationProperties
	@Import({RefreshConfiguration.RebinderConfiguration.class, PropertyPlaceholderAutoConfiguration.class})
	protected static class TestConfiguration {

		@Bean
		protected TestProperties properties() {
			return new TestProperties();
		}

	}

	// Hack out a protected inner class for testing
	protected static class RefreshConfiguration extends RefreshAutoConfiguration {
		@Configuration
		protected static class RebinderConfiguration extends ConfigurationPropertiesRebinderAutoConfiguration {

		}
	}

	@ConfigurationProperties
	protected static class TestProperties {
		private List<String> messages;
		private int count;
		public List<String> getMessages() {
			return this.messages;
		}
		public void setMessages(List<String> messages) {
			this.messages = messages;
		}
		public int getCount() {
			return this.count;
		}
		@PostConstruct
		public void init() {
			this.count ++;
		}
	}

}


text:
from __future__ import unicode_literals

import datetime
from django.db import migrations, models
import django.db.models.deletion
import django.utils.timezone

class Migration(migrations.Migration):

    initial = True

    dependencies = [
    ]

    operations = [
        migrations.CreateModel(
            name='DateInline',
            fields=[
                ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
                ('date_time', models.DateTimeField(default=django.utils.timezone.now)),
                ('date', models.DateField(default=datetime.date.today)),
                ('time', models.TimeField(default=django.utils.timezone.now)),
                ('add_inline', models.BooleanField(default=False, help_text='Tick this!')),
            ],
        ),
        migrations.CreateModel(
            name='Demo',
            fields=[
                ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
                ('title', models.CharField(max_length=100)),
                ('slug', models.SlugField(max_length=100, unique=True)),
            ],
        ),
        migrations.CreateModel(
            name='FileInline',
            fields=[
                ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
                ('file_upload', models.FileField(upload_to='uploads')),
                ('clearable_file_upload', models.FileField(blank=True, upload_to='uploads')),
                ('demo', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='demo_models.Demo')),
            ],
        ),
        migrations.CreateModel(
            name='ManySource',
            fields=[
                ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
                ('title', models.SlugField(max_length=100, unique=True)),
            ],
        ),
        migrations.AddField(
            model_name='demo',
            name='filter_horizontal',
            field=models.ManyToManyField(blank=True, related_name='_demo_filter_horizontal_+', to='demo_models.ManySource'),
        ),
        migrations.AddField(
            model_name='demo',
            name='filter_vertical',
            field=models.ManyToManyField(blank=True, related_name='_demo_filter_vertical_+', to='demo_models.ManySource'),
        ),
        migrations.AddField(
            model_name='demo',
            name='foreign_key',
            field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='+', to='demo_models.ManySource'),
        ),
        migrations.AddField(
            model_name='demo',
            name='many_to_many',
            field=models.ManyToManyField(blank=True, related_name='_demo_many_to_many_+', to='demo_models.ManySource'),
        ),
        migrations.AddField(
            model_name='demo',
            name='radio_fields_horizontal',
            field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='+', to='demo_models.ManySource'),
        ),
        migrations.AddField(
            model_name='demo',
            name='radio_fields_vertical',
            field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='+', to='demo_models.ManySource'),
        ),
        migrations.AddField(
            model_name='demo',
            name='raw_foreign_key',
            field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='+', to='demo_models.ManySource'),
        ),
        migrations.AddField(
            model_name='demo',
            name='raw_many_to_many',
            field=models.ManyToManyField(blank=True, related_name='_demo_raw_many_to_many_+', to='demo_models.ManySource'),
        ),
        migrations.AddField(
            model_name='dateinline',
            name='demo',
            field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='demo_models.Demo'),
        ),
    ]


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="description" content="">
    <meta name="author" content="">

    <title>Motion Box</title>

    <link href="css/bootstrap.min.css" rel="stylesheet">

    <link href="css/modern-business.css" rel="stylesheet">

    <link href="font-awesome/css/font-awesome.min.css" rel="stylesheet" type="text/css">

                <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1">
                    Toggle navigation

                </button>

Phillips Exeter Academy

 Student Council

                        Home

                        Updates

                                News

                                Events

                                Legislation

                        About

                        Committees

                        Constitution

                                Motion Box

                                Student Information

                                Feedback Center

                                Stuco Documents

                                Sign Out

Motion Box

Home

Login

Motion Box

What is the Motion Box

                    A motion will be the first step to any proposal or legislation of the Student Council.
If a student at Phillips Exeter Academy wishes the Council to act upon a certain issue, a motion is required. All motions must be submitted to the Vice-President in writing.

How to use the Motion Box

                A motion can be formed and written by any member of the Phillips Exeter Academy student body; however, they must satisfy these rules for consideration:

 Sponsored by a Class Representative or a Dorm Representative

 Signed by two Members of Student Council: Executive officers, Class Representatives, Dorm Representatives, and Committee Chairs

                 A motion calling for a proposal to be presented and voted upon on the floor must have a written proposal attached. A specific header for proposals is available below.

                 Anything a student wishes the Student Body to assemble upon may be grounds for a motion for Student Council proceedings. All committee chairs wishing to use Student Council funds for duties/activities must submit a motion; there are no exceptions.

                 To submit a motion, please print out the template below, complete with legible handwriting—illegible handwriting will be sent back for re-completion—and submit it directly to the Student Council PO box (ask PO attendant). Motions that do not use this template will be rejected for procedural matters.

                 Motions can be

 Accepted, presented to the Executive Board and the relevant Committee, if applicable, and brought to the Council Floor

 Put on hold. Sponsor and co-sponsors will be summoned, by email, to a markup meeting with the Vice-President and Secretary to revise language and content of a  proposal; following a markup meeting, the revised motion will be sent back to the sponsor and may be edited and resubmitted at any time. Sponsors of motions without an attached proposal will not be subjected to summons. Failure to show up to a markup meeting will result in automatic rejection of the motion and proposal, subject to appeal.

 Rejected, at the discretion of the Vice-President.

                 A motion may request the use of Student Council funds for any purposes that affirm the E-book. If it is for a club or extracurricular student activities, complete the Request for Funds form  located under the student council documents tab. If not, a direct motion to the Vice-President shall be entertained.

 A motion can be any of these following, but not limited to:

 A proposal for a school-wide policy change

 A specific recognition of a certain student/team

 An issue with a departmental curriculum

 An official statement to the Administration

                 Please email the Vice-President if you have any questions, at hkim3@exeter.edu.

                Download Motion Template

Copyright © Jackson Parell 2016, Photography by Rachel Luo


text:
USER_HOME=/home/vagrant

echo -e "\n\n"
echo "######################################"
echo "## Create dependencies download dir ##"
echo "## for the external services needed ##"
echo "######################################"

mkdir $USER_HOME/get_a_room/dependencies

echo -e "\n\n"
echo "####################"
echo "## Installing Git ##"
echo "####################"

apt-get install -y git-core

echo -e "\n\n"
echo "###########################"
echo "## Install PostgreSQL    ##"
echo "## Versiоn 9.4 (bit old) ##"
echo "###########################"

cd $USER_HOME/get_a_room/dependencies
# install dependencies for PostgreSQL to work with Django
apt-get install -y libpq-dev python-dev
# download ultra cool .sh script that will enable PostgreSQL APT
wget https://gist.githubusercontent.com/hhursev/4fbe4643e2304b0b315c/raw/574146ce201e18d1c9ecb0bf9932d4707410a104/postgresql.apt.sh
chmod +x postgresql.apt.sh
./postgresql.apt.sh

apt-get install -y postgresql-9.4
apt-get install -y postgresql-server-dev-9.4

# Remove password from default postgres user
sudo -u postgres psql template1 -x -c "ALTER ROLE postgres PASSWORD ''"

# Set configuration
cp $USER_HOME/get_a_room/vagrant_data/pg_hba.conf /etc/postgresql/9.4/main/pg_hba.conf
cp $USER_HOME/get_a_room/vagrant_data/postgresql.conf /etc/postgresql/9.4/main/postgresql.conf

# Restart postgres
service postgresql restart

# Create get_a_room database
sudo -u postgres psql -d postgres -c "CREATE DATABASE get_a_room;"

echo -e "\n\n"
echo "##########################"
echo "## Install Python 3.5.1 ##"
echo "##########################"

# to be able to compile Python from source, we will need few packages
apt-get install -y build-essential libncursesw5-dev libreadline6-dev
apt-get install -y libssl-dev libgdbm-dev libc6-dev libsqlite3-dev tk-dev

# download and build Python 3.5.1
cd $USER_HOME/get_a_room/dependencies
wget -O Python-3.5.1.tgz https://www.python.org/ftp/python/3.5.1/Python-3.5.1.tgz
tar xvzf Python-3.5.1.tgz
cd $USER_HOME/get_a_room/dependencies/Python-3.5.1
# Python 3.5.1 will be installed in /opt/python3
./configure --prefix=/opt/python3
make
make install

echo -e "\n\n"
echo "#################################"
echo "## Create project's virtualenv ##"
echo "#################################"

apt-get install -y python-pip
pip install virtualenv
pip install virtualenvwrapper

echo "source /usr/local/bin/virtualenvwrapper.sh" >> $USER_HOME/.bashrc
mkdir $USER_HOME/.virtualenvs
WORKON_HOME=$USER_HOME/.virtualenvs
source /usr/local/bin/virtualenvwrapper.sh

cd $USER_HOME/get_a_room
mkvirtualenv -a `pwd` -p /opt/python3/bin/python3.5 get_a_room
# Set vagrant as owner for virtualenvs
chown -R vagrant:vagrant $USER_HOME/.virtualenvs

workon get_a_room
pip install -r requirements.txt

killall -9 python

echo -e "\n\n"
echo "#############################"
echo "## Successful installation ##"
echo "#############################"

echo -e "\nInstalled versions:"
(
git --version
$USER_HOME/.virtualenvs/local/bin/python3 --version
psql --version
virtualenv --version
) | sed -u "s/^/  /"

exit 0


text:
class AddUsersSpotsToReviews < ActiveRecord::Migration
	def change
	    add_reference :reviews, :author, index:true
	    add_reference :reviews, :spot, index:true
	end
end


text:
using System;
using System.Threading;

namespace GitHub.Extensions
{
    public static class ExceptionExtensions
    {
        /// <summary>
        /// Represents exceptions we should never attempt to catch and ignore.
        /// </summary>
        /// <param name="exception">The exception being thrown.</param>
        /// <returns></returns>
        public static bool IsCriticalException(this Exception exception)
        {
            if (exception == null)
            {
                throw new ArgumentNullException("exception");
            }

            return exception.IsFatalException()
                || exception is AppDomainUnloadedException
                || exception is BadImageFormatException
                || exception is CannotUnloadAppDomainException
                || exception is InvalidProgramException
                || exception is NullReferenceException
                || exception is ArgumentException;
        }

        /// <summary>
        /// Represents exceptions we should never attempt to catch and ignore when executing third party plugin code.
        /// This is not as extensive as a proposed IsCriticalException method that I want to write for our own code.
        /// </summary>
        /// <param name="exception">The exception being thrown.</param>
        /// <returns></returns>
        public static bool IsFatalException(this Exception exception)
        {
            if (exception == null)
            {
                throw new ArgumentNullException("exception");
            }

            return exception is StackOverflowException
                || exception is OutOfMemoryException
                || exception is ThreadAbortException
                || exception is AccessViolationException;
        }

        public static bool CanRetry(this Exception exception)
        {
            return !exception.IsCriticalException()
                && !(exception is ObjectDisposedException);
        }
    }
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace Maticsoft.Web.View.NoticeMng
{
    public partial class NoticeList : BasePage
    {
        protected void Page_Load(object sender, EventArgs e)
        {

        }
    }
}


text:
<?php

use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;

//Request::setTrustedProxies(array('127.0.0.1'));

/*$app->get('/', function () use ($app) {
    return $app['twig']->render('index.html', array());
})->bind('ingres_field_precision(result, index)');
*/

//LOGIN
$app->mount('/', include __DIR__.'/../src/login/login_index.php');

//INICIO
$app->mount('/', include __DIR__.'/../src/inicio/inicio_index.php');

//EMPRESA
$app->mount('/', include __DIR__.'/../src/empresa/empresa_index.php');
//GERENCIA
$app->mount('/', include __DIR__.'/../src/gerencia/gerencia_index.php');
//UBICACIÓN
$app->mount('/', include __DIR__.'/../src/ubicacion/ubicacion_index.php');
//MARCA
$app->mount('/', include __DIR__.'/../src/marca/marca_index.php');
//SISTEMA OPERATIVO
$app->mount('/', include __DIR__.'/../src/sistema_operativo/sistema_operativo_index.php');
//ESTACION
$app->mount('/', include __DIR__.'/../src/estacion/estacion_index.php');

$app->error(function (\Exception $e, $code) use ($app) {
    if ($app['debug']) {
        return;
    }

    // 404.html, or 40x.html, or 4xx.html, or error.html
    $templates = array(
        'errors/'.$code.'.html',
        'errors/'.substr($code, 0, 2).'x.html',
        'errors/'.substr($code, 0, 1).'xx.html',
        'errors/default.html',
    );

    return new Response($app['twig']->resolveTemplate($templates)->render(array('code' => $code)), $code);
});


text: <link rel="prefetch" href="prefetch.js">


text:
<?php
/* SVN FILE: $Id: footer.php 7945 2008-12-19 02:16:01Z gwoo $ */
/**
 * Short description for file.
 *
 * Long description for file
 *
 * PHP versions 4 and 5
 *
 * CakePHP(tm) Tests <https://trac.cakephp.org/wiki/Developement/TestSuite>
 * Copyright 2005-2008, Cake Software Foundation, Inc. (http://www.cakefoundation.org)
 *
 *  Licensed under The Open Group Test Suite License
 *  Redistributions of files must retain the above copyright notice.
 *
 * @filesource
 * @copyright     Copyright 2005-2008, Cake Software Foundation, Inc. (http://www.cakefoundation.org)
 * @link          https://trac.cakephp.org/wiki/Developement/TestSuite CakePHP(tm) Tests
 * @package       cake
 * @subpackage    cake.cake.tests.lib
 * @since         CakePHP(tm) v 1.2.0.4433
 * @version       $Revision: 7945 $
 * @modifiedby    $LastChangedBy: gwoo $
 * @lastmodified  $Date: 2008-12-18 18:16:01 -0800 (Thu, 18 Dec 2008) $
 * @license       http://www.opensource.org/licenses/opengroup.php The Open Group Test Suite License
 */
?>

 				<img src="<?php echo $baseUrl; ?>img/cake.power.gif" alt="CakePHP(tm) :: Rapid Development Framework" />


text: A simple SFML chess game for two players.


text:
angular.module('app.browse', [])

.controller('BrowseController', ['$scope', '$http', '$state', '$timeout', function($scope, $http, $state, $timeout){
  $scope.mapData = [];

  $scope.showSigninMsg = false;

  // this fn should be refactored to a factory -- a variattion is used by dashboard
  $scope.addTotalNodesOfMaps = function (arr){
    arr.forEach(function(map){
      map.totalNodes = map.nodes.length;
    });
  };

  $scope.getMapData = function () {
    $http({
      method: 'GET',
      url:'/api/roadmaps?sort=-created'
    })
      .then(
        //success callback
        function(response){
          console.log('getMaps response.data', response.data);
          $scope.mapData = response.data.data || [];
          $scope.addTotalNodesOfMaps($scope.mapData);
        },
        //failure callback
        function(err){
          console.log('error with getMapData request', err);
        }
      );
  };

  $scope.goToDash = function () {
      $state.go('dashboard');
  }

  $scope.addMapToEmbarked = function (mapID) {
      $http({
        method: 'PUT',
        url: '/api/users/' + localStorage.getItem('user.username'),
        data: {
          'inProgress.roadmaps': mapID
         }
      })
        .then(function(response){
          console.log('status', response.status);
          console.log('response.body', response.body);
        },
        function(response){
          $scope.showSigninMsg = true;
          $timeout(function(){
            $scope.showSigninMsg = false;
          }, 5000)
        });
  }

  $scope.goToMap = function (mapID){  //refactor to factory, dash also uses
    localStorage.setItem('user.currentRoadMap', mapID);
    $state.go('roadmapTemplate');
  }

  $scope.getMapData();

}]);


text:
<head>
  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1">

  <title>{% if page.title %}{{ page.title | escape }}{% else %}{{ site.title | escape }}{% endif %}</title>
  <meta name="description" content="{% if page.excerpt %}{{ page.excerpt | strip_html | strip_newlines | truncate: 160 }}{% else %}{{ site.description }}{% endif %}">

  <link rel="stylesheet" href="{{ "/css/main.css" | prepend: site.baseurl }}">
  <link rel="canonical" href="{{ page.url | replace:'index.html','' | prepend: site.baseurl | prepend: site.url }}">
  <link rel="alternate" type="application/rss+xml" title="{{ site.title }}" href="{{ "/feed.xml" | prepend: site.baseurl | prepend: site.url }}">

  <!-- JQuery CDNs -->
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.2/jquery.min.js"></script>

  <!-- Bootstrap CDNs -->
  <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7" crossorigin="anonymous">
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js" integrity="sha384-0mSbJDEHialfmuBBQP6A4Qrprq5OVfW37PRR3j5ELqxss1yVqOtnepnHVP9aJ7xS" crossorigin="anonymous"></script>

  <!-- CraftyJS Release -->
  <script type="text/javascript" src="https://rawgithub.com/craftyjs/Crafty/release/dist/crafty-min.js"></script>
</head>


text:
#ifndef __FORK_EDITOR_UI_PROPERTY_STRING_H__
#define __FORK_EDITOR_UI_PROPERTY_STRING_H__

#include "UIProperty.h"

namespace Fork
{

namespace Editor
{

//! Abstract component property class for strings.
class UIPropertyString : public Engine::Component::StringProperty, public UIProperty
{

    public:

        UIPropertyString(UIPropertyGrid& propGrid, const wxString& propName);

        void WriteToProperty() override;
        void ReadFromProperty(const PropertyState& state) override;

    private:

        wxStringProperty* prop_ = nullptr;

};

} // /namespace Editor

} // /namespace Fork

#endif

// ========================


text:
platform_is :windows do
  require_relative '../fixtures/classes'
  guard -> { WIN32OLESpecs::SYSTEM_MONITOR_CONTROL_AVAILABLE } do

    describe "WIN32OLE_METHOD#event?" do
      before :each do
        ole_type = WIN32OLE_TYPE.new("System Monitor Control", "SystemMonitor")
        @on_dbl_click_method = WIN32OLE_METHOD.new(ole_type, "OnDblClick")
      end

      it "raises ArgumentError if argument is given" do
        lambda { @on_dbl_click_method.event?(1) }.should raise_error ArgumentError
      end

      it "returns true for System Monitor Control's 'OnDblClick' method" do
        @on_dbl_click_method.event?.should be_true
      end

    end
  end

end


text:
"use strict";

var _ = require('lodash'),
    objectPath = require('object-path');

var ViewModel = function (context, scope, propertiesRegistry, bus, eventsRegistry) {

    //Register properties listeners
    _.forEach(propertiesRegistry.obtain(context), function (command, property) {
        scope.$watch(_.bind(function () {
            return objectPath.get(this, property);
        }, this), function (newValue, oldValue) {
            bus.publish(context, property, {newValue: newValue, oldValue: oldValue});
        }, true);
    }, this);

    //Register events listeners
    _.forEach(eventsRegistry.obtain(context), function (command, type) {
        scope.$on(type, function (event, data) {
            bus.publish(context, type, {
                data: data
            });
        });
    }, this);
};

module.exports = ViewModel;


text: start "" "${CMAKE_RUNTIME_OUTPUT_DIRECTORY}/Release/asset_manager.exe"


text:
using System.Reflection;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http.Metadata;
using Microsoft.AspNetCore.Routing;
using Microsoft.AspNetCore.Routing.Patterns;
using Microsoft.AspNetCore.Testing;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Logging.Abstractions;

namespace Microsoft.AspNetCore.Http.HttpResults;

public partial class CreatedAtRouteResultTests
{
    public static IEnumerable<object[]> CreatedAtRouteData
    {
        get
        {
            yield return new object[] { null };
            yield return
                new object[] {
                        new Dictionary<string, string>() { { "hello", "world" } }
                };
            yield return
                new object[] {
                        new RouteValueDictionary(new Dictionary<string, string>() {
                            { "test", "case" },
                            { "sample", "route" }
                        })
                };
        }
    }

    [Theory]
    [MemberData(nameof(CreatedAtRouteData))]
    public async Task CreatedAtRouteResult_ReturnsStatusCode_SetsLocationHeader(object values)
    {
        // Arrange
        var expectedUrl = "testAction";
        var httpContext = GetHttpContext(expectedUrl);

        // Act
        var result = new CreatedAtRoute(routeName: null, routeValues: values);
        await result.ExecuteAsync(httpContext);

        // Assert
        Assert.Equal(StatusCodes.Status201Created, httpContext.Response.StatusCode);
        Assert.Equal(expectedUrl, httpContext.Response.Headers["Location"]);
    }

    [Fact]
    public async Task CreatedAtRouteResult_ThrowsOnNullUrl()
    {
        // Arrange
        var httpContext = GetHttpContext(expectedUrl: null);

        var result = new CreatedAtRoute(
            routeName: null,
            routeValues: new Dictionary<string, object>());

        // Act & Assert
        await ExceptionAssert.ThrowsAsync<InvalidOperationException>(
            async () => await result.ExecuteAsync(httpContext),
        "No route matches the supplied values.");
    }

    [Fact]
    public void PopulateMetadata_AddsResponseTypeMetadata()
    {
        // Arrange
        CreatedAtRoute MyApi() { throw new NotImplementedException(); }
        var metadata = new List<object>();
        var builder = new RouteEndpointBuilder(requestDelegate: null, RoutePatternFactory.Parse("/"), order: 0);

        // Act
        PopulateMetadata<CreatedAtRoute>(((Delegate)MyApi).GetMethodInfo(), builder);

        // Assert
        var producesResponseTypeMetadata = builder.Metadata.OfType<ProducesResponseTypeMetadata>().Last();
        Assert.Equal(StatusCodes.Status201Created, producesResponseTypeMetadata.StatusCode);
        Assert.Equal(typeof(void), producesResponseTypeMetadata.Type);
    }

    [Fact]
    public void ExecuteAsync_ThrowsArgumentNullException_WhenHttpContextIsNull()
    {
        // Arrange
        var result = new CreatedAtRoute(null);
        HttpContext httpContext = null;

        // Act & Assert
        Assert.ThrowsAsync<ArgumentNullException>("httpContext", () => result.ExecuteAsync(httpContext));
    }

    [Fact]
    public void PopulateMetadata_ThrowsArgumentNullException_WhenMethodOrBuilderAreNull()
    {
        // Act & Assert
        Assert.Throws<ArgumentNullException>("method", () => PopulateMetadata<CreatedAtRoute>(null, new RouteEndpointBuilder(requestDelegate: null, RoutePatternFactory.Parse("/"), order: 0)));
        Assert.Throws<ArgumentNullException>("builder", () => PopulateMetadata<CreatedAtRoute>(((Delegate)PopulateMetadata_ThrowsArgumentNullException_WhenMethodOrBuilderAreNull).GetMethodInfo(), null));
    }

    [Fact]
    public void CreatedAtRouteResult_Implements_IValueHttpResult_Correctly()
    {
        // Arrange & Act
        var rawResult = new CreatedAtRoute(
            routeName: null,
            routeValues: new Dictionary<string, object>());

        // Assert
        var result = Assert.IsAssignableFrom<IStatusCodeHttpResult>(rawResult);
        Assert.Equal(StatusCodes.Status201Created, result.StatusCode);
    }

    private static void PopulateMetadata<TResult>(MethodInfo method, EndpointBuilder builder)
        where TResult : IEndpointMetadataProvider => TResult.PopulateMetadata(method, builder);

    private static HttpContext GetHttpContext(string expectedUrl)
    {
        var httpContext = new DefaultHttpContext();
        httpContext.Request.PathBase = new PathString("");
        httpContext.Response.Body = new MemoryStream();
        httpContext.RequestServices = CreateServices(expectedUrl);
        return httpContext;
    }

    private static IServiceProvider CreateServices(string expectedUrl)
    {
        var services = new ServiceCollection();
        services.AddSingleton<ILoggerFactory, NullLoggerFactory>();
        services.AddSingleton<LinkGenerator>(new TestLinkGenerator
        {
            Url = expectedUrl
        });

        return services.BuildServiceProvider();
    }
}


text:
.some-random {
  font-family: 'Comic Sans';
}


text:
/* global describe, it */
'use strict'

const promisify = require('../')
const assert = require('assert')
const fs = require('fs')
const join = require('path').join
const readFile = promisify(fs.readFile)
const file = join(__dirname, 'sample.txt')

describe('promisify', () => {
	it('readFile', done => {
		readFile(file)
			.then(buffer => {
				assert.deepEqual(buffer.toString('utf8'), 'Thiago, Sabrina e Lucas\n')
				done()
			})
	})

	it('fail', done => {
		readFile('./not-found.txt')
			.catch(err => {
				assert.equal(err.message, `ENOENT: no such file or directory, open './not-found.txt'`)
				done()
			})
	})
})


text:
package com.navercorp.pinpoint.web.applicationmap.appender.server;

import com.navercorp.pinpoint.web.applicationmap.appender.server.datasource.ServerInstanceListDataSource;
import com.navercorp.pinpoint.web.applicationmap.histogram.NodeHistogram;
import com.navercorp.pinpoint.web.applicationmap.nodes.Node;
import com.navercorp.pinpoint.web.applicationmap.nodes.ServerBuilder;
import com.navercorp.pinpoint.web.applicationmap.nodes.ServerInstanceList;
import com.navercorp.pinpoint.web.applicationmap.rawdata.LinkData;
import com.navercorp.pinpoint.web.applicationmap.rawdata.LinkDataDuplexMap;
import com.navercorp.pinpoint.web.vo.AgentInfo;
import com.navercorp.pinpoint.web.vo.Application;

import java.time.Instant;
import java.util.HashSet;
import java.util.Objects;
import java.util.Set;

/**
 * @author jaehong.kim
 */
public class StatisticsServerInstanceListFactory implements ServerInstanceListFactory {
    private final ServerInstanceListDataSource serverInstanceListDataSource;

    public StatisticsServerInstanceListFactory(ServerInstanceListDataSource serverInstanceListDataSource) {
        this.serverInstanceListDataSource = serverInstanceListDataSource;
    }

    @Override
    public ServerInstanceList createWasNodeInstanceList(Node wasNode, Instant timestamp) {
        ServerInstanceList serverInstanceList = createWasNodeInstanceListFromHistogram(wasNode, timestamp);
        if (serverInstanceList.getServerInstanceList().isEmpty()) {
            // When there is no transaction information, agentInfo information is used.
            serverInstanceList = createWasNodeInstanceListFromAgentInfo(wasNode, timestamp);
        }
        return serverInstanceList;
    }

    ServerInstanceList createWasNodeInstanceListFromHistogram(Node wasNode, Instant timestamp) {
        Objects.requireNonNull(wasNode, "wasNode");
        if (timestamp.toEpochMilli() < 0) {
            return new ServerInstanceList();
        }

        final ServerBuilder builder = new ServerBuilder();
        final Set<AgentInfo> agentInfoSet = new HashSet<>();
        final NodeHistogram nodeHistogram = wasNode.getNodeHistogram();
        if (nodeHistogram != null && nodeHistogram.getAgentHistogramMap() != null) {
            for (String agentId : nodeHistogram.getAgentHistogramMap().keySet()) {
                AgentInfo agentInfo = new AgentInfo();
                agentInfo.setAgentId(agentId);
                agentInfo.setHostName(agentId);
                agentInfo.setIp("");
                agentInfo.setServiceTypeCode(wasNode.getServiceType().getCode());
                agentInfoSet.add(agentInfo);
            }
        }
        builder.addAgentInfo(agentInfoSet);
        return builder.build();
    }

    ServerInstanceList createWasNodeInstanceListFromAgentInfo(Node wasNode, Instant timestamp) {
        return serverInstanceListDataSource.createServerInstanceList(wasNode, timestamp);
    }

    @Override
    public ServerInstanceList createTerminalNodeInstanceList(Node terminalNode, LinkDataDuplexMap linkDataDuplexMap) {
        // extract information about the terminal node
        ServerBuilder builder = new ServerBuilder();
        for (LinkData linkData : linkDataDuplexMap.getSourceLinkDataList()) {
            Application toApplication = linkData.getToApplication();
            if (terminalNode.getApplication().equals(toApplication)) {
                builder.addCallHistogramList(linkData.getTargetList());
            }
        }
        return builder.build();
    }

    @Override
    public ServerInstanceList createQueueNodeInstanceList(Node queueNode, LinkDataDuplexMap linkDataDuplexMap) {
        return createEmptyNodeInstanceList();
    }

    @Override
    public ServerInstanceList createUserNodeInstanceList() {
        return createEmptyNodeInstanceList();
    }

    @Override
    public ServerInstanceList createEmptyNodeInstanceList() {
        return new ServerInstanceList();
    }
}


text:
package org.metawatch.manager.widgets;

import java.util.ArrayList;

import org.metawatch.manager.Utils;

public class K9Widget extends SimpleIconWidget {

	@Override
	protected int getCount() {
		return Utils.getUnreadK9Count(context);
	}

	@Override
	protected String idBase() {
		return "unreadK9";
	}

	@Override
	protected String descBase() {
		return "Unread K-9 email";
	}

	@Override
	protected String icon16x16() {
		return "idle_k9mail_10.bmp";
	}

	@Override
	protected String icon24x32() {
		return "idle_k9mail.bmp";
	}

	@Override
	protected String icon46x46() {
		return "idle_k9mail.bmp";
	}

	@Override
	public void refresh(ArrayList<CharSequence> widgetIds) {
	}
}


text:
package com.woodplantation.werwolf.network.server;

import android.os.AsyncTask;
import android.util.Log;

import com.woodplantation.werwolf.network.Server;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.Socket;

/**
 * Created by Sebu on 10.01.2017.
 */

public class CollectingClientsTask extends AsyncTask<Void, Void, Socket> {

    private Server server;

    public CollectingClientsTask(Server server) {
        this.server = server;
    }

    @Override
    protected Socket doInBackground(Void... voids) {
        Log.d("Server","collecting clients task");
        server.getTasks().add(this);
        try {
            return server.getServerSocket().accept();
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }

        @Override
        protected void onPostExecute(Socket result) {
            Log.d("Server","collecting clients task on postexecute");
            server.getTasks().remove(this);
            if (result == null) {
                return;
            }

            //if we started already we dont want new clients
            if (server.isStarted()) {
                try {
                    result.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                return;
            }

            //start new task for collecting clients
            CollectingClientsTask collectingClientsTask = new CollectingClientsTask(server);
            collectingClientsTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);

            //get Input
            InputStream inputStream;
            OutputStream outputStream;
            try {
                inputStream = result.getInputStream();
                outputStream = result.getOutputStream();
            } catch (IOException e) {
                e.printStackTrace();
                return;
            }
            //save client, input and output in list
            BufferedReader in = new BufferedReader(new InputStreamReader(inputStream));
            PrintWriter out = new PrintWriter(outputStream, true);
            ClientInfo clientInfo = new ClientInfo();
            clientInfo.socket = result;
            clientInfo.in = in;
            clientInfo.out = out;
            server.getClients().add(clientInfo);

            //start task for getting displayname from client
            GetDisplaynameAndIdTask getDisplaynameAndIdTask = new GetDisplaynameAndIdTask(server);
            getDisplaynameAndIdTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, server.getClients().indexOf(clientInfo));
        }
}


text:
/* global chai, fixture, sinon */

'use strict';

import { default as $, BEMQuery as BEMQuery } from 'bemquery-core';
import '../src/listeners';

const expect = chai.expect;

describe( 'BEMQuery#on', () => {
	before( () => {
		fixture.setBase( 'tests/support/fixtures' );
	} );

	afterEach( () => {
		fixture.cleanup();
		BEMQuery.converter = {};
	} );

	it( 'is a function', () => {
		expect( BEMQuery.prototype.on ).to.be.a( 'function' );
	} );

	it( 'returns BEMQuery instance', () => {
		const result = $( [] ).on( 'qwerty', () => {} );

		expect( result ).to.be.instanceof( BEMQuery );
	} );

	it( 'expects the first parameter to be a non empty string', () => {
		const bemQuery = $( [] );

		expect( () => {
			bemQuery.on( 1, () => {} );
		} ).to.throw( TypeError, 'Type of event must be a non-empty string.' );

		expect( () => {
			bemQuery.on( '', () => {} );
		} ).to.throw( TypeError, 'Type of event must be a non-empty string.' );
	} );

	it( 'expects the second parameter to be a non empty string or a function', () => {
		const bemQuery = $( [] );

		expect( () => {
			bemQuery.on( 'click', 1 );
		} ).to.throw( TypeError, 'Selector must be a non-empty string or function.' );

		expect( () => {
			bemQuery.on( 'click', '' );
		} ).to.throw( TypeError, 'Selector must be a non-empty string or function.' );
	} );

	it( 'expects the third parameter to be a function', () => {
		const bemQuery = $( [] );

		expect( () => {
			bemQuery.on( 'click', 'selector', 1 );
		} ).to.throw( TypeError, 'Callback must be a function.' );
	} );

	it( 'adds listeners to all elements in collection', () => {
		fixture.load( 'elements.html' );

		const bemQuery = $( [ ...document.querySelectorAll( '.block' ) ] );

		let fired = 0;
		const spy = sinon.spy();

		bemQuery.on( 'click', spy );

		return new Promise( ( resolve ) => {
			bemQuery.elements.forEach( ( element ) => {
				element.addEventListener( 'click', () => {
					if ( ++fired === bemQuery.elements.length ) {
						resolve();
					}
				} );

				const clickEvent = new Event( 'click' );

				element.dispatchEvent( clickEvent );
			} );
		} ).then( () => {
			expect( spy ).to.have.callCount( bemQuery.elements.length );
		} );
	} );

	it( 'fires listener only for delegated element', () => {
		fixture.load( 'elements.html' );
		BEMQuery.converter = {
			BEM: 'block elem',
			CSS: '.block__elem'
		};

		const bemQuery = $( [ document.getElementById( 'delegation' ) ] );

		const spy = sinon.spy();

		bemQuery.on( 'click', 'block elem', spy );

		return new Promise( ( resolve ) => {
			const element = document.querySelector( '#delegation .block__other' );

			element.addEventListener( 'click', () => {
				resolve();
			} );

			const clickEvent = new Event( 'click', {
				bubbles: true
			} );

			element.dispatchEvent( clickEvent );
		} ).then( () => {
			expect( spy ).to.have.not.been.called;

			return new Promise( ( resolve ) => {
				const element = document.querySelector( '#delegation .block__elem' );

				element.addEventListener( 'click', () => {
					resolve();
				} );

				const clickEvent = new Event( 'click', {
					bubbles: true
				} );

				element.dispatchEvent( clickEvent );
			} );
		} ).then( () => {
			expect( spy ).to.have.been.calledOnce;
		} );
	} );

	it( 'fires listener for descendant of delegated element', () => {
		fixture.load( 'elements.html' );
		BEMQuery.converter = {
			BEM: 'block elem',
			CSS: '.block__elem'
		};

		const bemQuery = $( [ document.getElementById( 'delegation' ) ] );

		const spy = sinon.spy();

		bemQuery.on( 'click', 'block elem', spy );

		return new Promise( ( resolve ) => {
			const element = document.querySelector( '#delegation .block__elem span' );

			element.addEventListener( 'click', () => {
				resolve();
			} );

			const clickEvent = new Event( 'click', {
				bubbles: true
			} );

			element.dispatchEvent( clickEvent );
		} ).then( () => {
			expect( spy ).to.have.been.calledOnce;
		} );
	} );
} );

describe( 'BEMQuery#off', () => {
	before( () => {
		fixture.setBase( 'tests/support/fixtures' );
	} );

	afterEach( () => {
		fixture.cleanup();
		BEMQuery.converter = {};
	} );

	it( 'is a function', () => {
		expect( BEMQuery.prototype.off ).to.be.a( 'function' );
	} );

	it( 'returns BEMQuery instance', () => {
		const result = $( [] ).off( 'qwerty', () => {} );

		expect( result ).to.be.instanceof( BEMQuery );
	} );

	it( 'expects the first parameter to be a non empty string', () => {
		const bemQuery = $( [] );

		expect( () => {
			bemQuery.off( 1, () => {} );
		} ).to.throw( TypeError, 'Type of event must be a non-empty string.' );

		expect( () => {
			bemQuery.off( '', () => {} );
		} ).to.throw( TypeError, 'Type of event must be a non-empty string.' );
	} );

	it( 'expects the second parameter to be a non empty string or a function', () => {
		const bemQuery = $( [] );

		expect( () => {
			bemQuery.off( 'click', 1 );
		} ).to.throw( TypeError, 'Selector must be a non-empty string or function.' );

		expect( () => {
			bemQuery.off( 'click', '' );
		} ).to.throw( TypeError, 'Selector must be a non-empty string or function.' );
	} );

	it( 'expects the third parameter to be a function', () => {
		const bemQuery = $( [] );

		expect( () => {
			bemQuery.off( 'click', 'selector', 1 );
		} ).to.throw( TypeError, 'Callback must be a function.' );
	} );

	it( 'removes listeners to all elements in collection', () => {
		fixture.load( 'elements.html' );

		const bemQuery = $( [ ...document.querySelectorAll( '.block' ) ] );

		let fired = 0;
		const spy = sinon.spy();

		bemQuery.on( 'click', spy );
		bemQuery.off( 'click', spy );

		return new Promise( ( resolve ) => {
			bemQuery.elements.forEach( ( element ) => {
				element.addEventListener( 'click', () => {
					if ( ++fired === bemQuery.elements.length ) {
						resolve();
					}
				} );

				const clickEvent = new Event( 'click' );

				element.dispatchEvent( clickEvent );
			} );
		} ).then( () => {
			expect( spy ).to.have.not.been.called;
		} );
	} );

	it( 'removes listener for delegated element', () => {
		fixture.load( 'elements.html' );
		BEMQuery.converter = {
			BEM: 'block elem',
			CSS: '.block__elem'
		};

		const bemQuery = $( [ document.getElementById( 'delegation' ) ] );

		const spy = sinon.spy();

		bemQuery.on( 'click', 'block elem', spy );
		bemQuery.off( 'click', 'block elem', spy );

		return new Promise( ( resolve ) => {
			const element = document.querySelector( '#delegation .block__elem' );

			element.addEventListener( 'click', () => {
				resolve();
			} );

			const clickEvent = new Event( 'click', {
				bubbles: true
			} );

			element.dispatchEvent( clickEvent );
		} ).then( () => {
			expect( spy ).to.have.not.been.called;
		} );
	} );
} );


text:
package org.anarres.cpp;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import javax.annotation.Nonnull;

/**
 * A macro argument.
 *
 * This encapsulates a raw and preprocessed token stream.
 */
/* pp */ class Argument extends ArrayList<Token> {

    private List<Token> expansion;

    public Argument() {
        this.expansion = null;
    }

    public void addToken(@Nonnull Token tok) {
        add(tok);
    }

    /* pp */ void expand(@Nonnull Preprocessor p)
            throws IOException,
            LexerException {
        /* Cache expansion. */
        if (expansion == null) {
            this.expansion = p.expand(this);
            // System.out.println("Expanded arg " + this);
        }
    }

    @Nonnull
    public Iterator<Token> expansion() {
        return expansion.iterator();
    }

    @Override
    public String toString() {
        StringBuilder buf = new StringBuilder();
        buf.append("Argument(");
        // buf.append(super.toString());
        buf.append("raw=[ ");
        for (int i = 0; i < size(); i++)
            buf.append(get(i).getText());
        buf.append(" ];expansion=[ ");
        if (expansion == null)
            buf.append("null");
        else
            for (Token token : expansion)
                buf.append(token.getText());
        buf.append(" ])");
        return buf.toString();
    }

}


text:
// Copyright (c) 2012 Ecma International.  All rights reserved.
// Ecma International makes this code available under the terms and conditions set
// forth on http://hg.ecmascript.org/tests/test262/raw-file/tip/LICENSE (the
// "Use Terms").   Any redistribution of this code must retain the above
// copyright and this notice and otherwise comply with the Use Terms.

/*---
es5id: 15.2.3.7-5-b-264
description: >
    Object.defineProperties - TypeError is thrown if both 'get'
    property and 'writable' property of 'descObj' are present (8.10.5
    step 9.a)
includes: [runTestCase.js]
---*/

function testcase() {

        var getFun = function () {};

        var obj = {};

        try {
            Object.defineProperties(obj, {
                "prop": {
                    writable: true,
                    get: getFun
                }
            });
            return false;
        } catch (e) {
            return (e instanceof TypeError);
        }
    }
runTestCase(testcase);


text:
if (typeof Object.assign !== 'function') {
    Object.assign = function (target, varArgs) {
        'use strict';
        if (target === null) {
            throw new TypeError('Cannot convert undefined or null to object');
        }

        var to = Object(target);

        for (var index = 1; index < arguments.length; index++) {
            var nextSource = arguments[index];

            if (nextSource !== null) {
                for (var nextKey in nextSource) {
                    if (Object.prototype.hasOwnProperty.call(nextSource, nextKey)) {
                        to[nextKey] = nextSource[nextKey];
                    }
                }
            }
        }
        return to;
    };
}


text:
<project xmlns="http://maven.apache.org/POM/4.0.0"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<artifactId>jaxb2-basics-sample-jaxws</artifactId>
	<packaging>pom</packaging>
	<name>JAXB2 Basics - Sample [jaxws]</name>
	<parent>
		<groupId>org.jvnet.jaxb2_commons</groupId>
		<artifactId>jaxb2-basics-samples</artifactId>
		<version>0.11.2-SNAPSHOT</version>
	</parent>
	<dependencies>
		<dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
		</dependency>
		<dependency>
			<groupId>org.jvnet.jaxb2_commons</groupId>
			<artifactId>jaxb2-basics-plugins</artifactId>
		</dependency>
		<dependency>
			<groupId>org.jvnet.jaxb2_commons</groupId>
			<artifactId>jaxb2-basics-testing</artifactId>
		</dependency>
		<dependency>
			<groupId>org.jvnet.jaxb2_commons</groupId>
			<artifactId>jaxb2-basics-ant</artifactId>
		</dependency>
		<dependency>
			<groupId>org.glassfish.jaxb</groupId>
			<artifactId>jaxb-runtime</artifactId>
		</dependency>
		<dependency>
			<groupId>org.glassfish.jaxb</groupId>
			<artifactId>jaxb-xjc</artifactId>
		</dependency>
		<dependency>
			<groupId>org.slf4j</groupId>
			<artifactId>slf4j-simple</artifactId>
		</dependency>
	</dependencies>
	<build>
		<defaultGoal>install</defaultGoal>
		<plugins>
			<plugin>
				<artifactId>maven-assembly-plugin</artifactId>
				<executions>
					<execution>
						<id>maven-assembly</id>
						<phase>package</phase>
					</execution>
					<!--execution>
						<id>ant-assembly</id>
						<phase>package</phase>
					</execution-->
				</executions>
			</plugin>
			<plugin>
				<artifactId>maven-antrun-plugin</artifactId>
				<executions>
					<execution>
						<id>maven-unpack</id>
						<phase>pre-integration-test</phase>
					</execution>
					<!--execution>
						<id>ant-unpack</id>
						<phase>pre-integration-test</phase>
					</execution>
					<execution>
						<id>ant-integration-test</id>
						<phase>integration-test</phase>
					</execution-->
				</executions>
			</plugin>
			<plugin>
				<artifactId>maven-invoker-plugin</artifactId>
				<executions>
					<execution>
						<id>maven-integration-test</id>
						<phase>integration-test</phase>
					</execution>
				</executions>
			</plugin>
		</plugins>
	</build>
</project>


text:
package org.apache.kylin.util;

import java.util.BitSet;

import org.apache.kylin.common.threadlocal.InternalThreadLocal;
import org.objenesis.strategy.StdInstantiatorStrategy;

import com.esotericsoftware.kryo.Kryo;
import com.esotericsoftware.kryo.io.Input;
import com.esotericsoftware.kryo.io.Output;

public class KryoUtils {

    private static InternalThreadLocal<Kryo> _Kryo = new InternalThreadLocal<>();

    private KryoUtils() {
        throw new IllegalStateException("Class KryoUtils is an utility class !");
    }

    public static byte[] serialize(Object obj) {
        Kryo kryo = getKryo();
        Output output = new Output(1024, 8 * 1024 * 1024);
        kryo.writeObject(output, obj);
        return output.toBytes();
    }

    public static <T> T deserialize(byte[] bytes, Class<T> clazz) {
        Kryo kryo = getKryo();
        Input input = new Input(bytes);
        return kryo.readObject(input, clazz);
    }

    public static <T> T copy(T origin, Class<T> clazz) {
        byte[] bytes = serialize(origin);
        return deserialize(bytes, clazz);
    }

    public static Kryo getKryo() {
        if (_Kryo.get() == null) {
            Kryo kryo = new Kryo();
            kryo.setInstantiatorStrategy(new Kryo.DefaultInstantiatorStrategy(new StdInstantiatorStrategy()));
            kryo.register(BitSet.class, new BitSetSerializer());
            _Kryo.set(kryo);
        }

        return _Kryo.get();
    }
}


text:
require File.dirname(__FILE__) + '/../../spec_helper'

describe "Eye::Checker::ChildrenMemory" do
  it "should not restart because all is ok" do
    @process = start_ok_process(C.p1.merge(:checks => C.check_children_memory(:below => 50), :monitor_children => {}))

    3.times { @pids << Eye::System.daemonize("sleep 10")[:pid] }
    stub(Eye::SystemResources).children(@process.pid){ @pids }
    @process.add_children

    stub(Eye::SystemResources).memory(anything) { 1 }

    dont_allow(@process).schedule(:restart, anything)

    sleep 5
  end

  it "should restart with strategy :restart" do
    @process = start_ok_process(C.p1.merge(:checks => C.check_children_memory(:below => 50), :monitor_children => {}))

    10.times { @pids << Eye::System.daemonize("sleep 10")[:pid] }
    stub(Eye::SystemResources).children(@process.pid){ @pids }
    @process.add_children

    stub(Eye::SystemResources).memory(anything) { 11 }
    mock(@process).schedule(:restart, anything)

    sleep 5
  end
end


text:
namespace DSInternals.PowerShell.Commands
{
    using System;
    using System.Management.Automation;
    using DSInternals.DataStore;

    public abstract class ADDBCommandBase : PSCmdletEx, IDisposable
    {
        /// <summary>
        /// Gets or sets the DIT database file path.
        /// </summary>
        /// <value>
        /// Path to the DIT file on the local server.
        /// </value>
        /// <remarks>
        /// The DIT must be in a consistent state, that is, the ESE logs must be replayed.
        /// </remarks>
        [Parameter(Mandatory = true)]
        [ValidateNotNullOrEmpty]
        [Alias("Database", "DBPath", "DatabaseFilePath", "DBFilePath")]
        public string DatabasePath
        {
            get;
            set;
        }

        /// <summary>
        /// Gets or sets the ESE transaction log folder. If not specified, then database folder will be used.
        /// </summary>
        /// <value>
        /// The log path.
        /// </value>
        [Parameter(Mandatory = false)]
        [ValidateNotNullOrEmpty]
        [Alias("Log", "TransactionLogPath")]
        public string LogPath
        {
            get;
            set;
        }

        protected virtual bool ReadOnly
        {
            get
            {
                return true;
            }
        }

        protected DirectoryContext DirectoryContext
        {
            get;
            private set;
        }

        protected override void BeginProcessing()
        {
            // TODO: Debug output
            this.WriteDebug("Opening the Active Directory database.");
            try
            {
                // Resolve possibly relative paths to absolute paths:
                string dbPathResolved = this.ResolveFilePath(this.DatabasePath);
                string logPathResolved = this.ResolveDirectoryPath(this.LogPath);
                this.DirectoryContext = new DirectoryContext(dbPathResolved, this.ReadOnly, logPathResolved);
            }
            catch(SessionStateException ex)
            {
                // This may be DriveNotFoundException, ItemNotFoundException, ProviderNotFoundException, etc.
                // Terminate on this error:
                this.ThrowTerminatingError(new ErrorRecord(ex.ErrorRecord, ex));
            }
            catch (Exception ex)
            {
                ErrorRecord error = new ErrorRecord(ex, "DBContextError", ErrorCategory.OpenError, null);
                // Terminate on this error:
                this.ThrowTerminatingError(error);
            }
        }
        public void Dispose()
        {
            this.Dispose(true);
            GC.SuppressFinalize(this);
        }

        protected virtual void Dispose(bool disposing)
        {
            if (disposing && this.DirectoryContext != null)
            {
                this.DirectoryContext.Dispose();
                this.DirectoryContext = null;
            }
        }
    }
}


text:
from __future__ import absolute_import

"""
Contains functions for traversing a query.
"""
from ..utils.multimethods import getNamespace
try:
    from threading import current_thread
except: #no threading on GAE
    current_thread = lambda: None
mm = getNamespace()
from ..Language.corelanguage import GetV, Node, GetSet, ValueSet, TypeSet, Filter, Compare, RemoveAll, Replace, Remove, Add, LimitFilter, List, Unlist
from ..Language.corelanguage import GT, LT, LTE, GTE, NE, EQ, KINDS, PropertyStatement

class QueryParser(object):

    def __init__(self, typeset, getv, remove_all, replace, remove, add, list, unlist):
        """
        As used below, a set is a func on () -> [values].

        typeset(typename) -> set
        getv(set, typename, property) -> set

        remove_all(value, type, property)
        replace(value, type, property, newvalues)
        remove(value, type, property, value)
        add(value, type, property, value)
        list(value, type)
        unlist(value, type)
        """
        self.typeset = typeset
        self.getv = getv

        self.remove_all = remove_all
        self.replace = replace
        self.remove = remove
        self.add = add
        self.list = list
        self.unlist = unlist
        self.data_dict = {}

    def add_data(self, data_piece):
        self.data_dict[current_thread()].append(data_piece)

    def start_data(self):
        self.data_dict[current_thread()] = []

    def end_data(self):
        del self.data_dict[current_thread()]

    def get_data(self):
        return tuple(self.data_dict[current_thread()])

    def query(self, query):
        return self.querydata(query)[0]

    def querydata(self, query):
        self.start_data()
        try:
            set = self._get_base(query.values)()
            r = self.execute_query(query, set)
            return r, self.get_data()
        finally:
            self.end_data()

    @mm(object, GetSet, object)
    def execute_query(self, command, set):
        return set

    @mm(object, RemoveAll, object)
    def execute_query(self, command, set):
        for v in set:
            self.remove_all(v, command.type, command.property)

    @mm(object, Replace, object)
    def execute_query(self, command, set):
        for v in set:
            self.replace(v, command.type, command.property, command.newvalues)

    @mm(object, Remove, object)
    def execute_query(self, command, set):
        for v in set:
            self.remove(v, command.type, command.property, command.value)

    @mm(object, Add, object)
    def execute_query(self, command, set):
        for v in set:
            self.add(v, command.type, command.property, command.value)

    @mm(object, List, object)
    def execute_query(self, command, set):
        for v in set:
            self.list(v, command.type)

    @mm(object, Unlist, object)
    def execute_query(self, command, set):
        for v in set:
            self.unlist(v, command.type)

    def _get_base(self, querybase):
        """returns a set (a func on () -> values)"""
        if querybase == ():
            raise Exception('query terminated prematurely -- must start with a ValueSet, TypeSet, or similar')
        return self._parse(querybase[-1], querybase[:-1])

    @mm(object, ValueSet, tuple)
    def _parse(self, node, base): #all instances of parse return a set (a func on () -> values)
        if base != ():
            raise Exception('Error: nothing should precede ValueSets')
        def ret():
            v = node.values
            if isinstance(v, list):
                return v
            elif isinstance(v, tuple):
                return list(v)
            else:
                return [v]
        return ret

    @mm(object, TypeSet, tuple)
    def _parse(self, node, base):
        if base != ():
            raise Exception('Error: nothing should precede TypeSets')
        return self.typeset(node.type)

    @mm(object, GetV, tuple)
    def _parse(self, node, base):
        return self.getv(self._get_base(base), node.type, node.property)

    def defaultFilter(self, node, base):
        def getset():
            newvalues = self._get_base(base)()
            for filter in node.filters:
                if isinstance(filter[0], LimitFilter):
                    if len(filter) > 1:
                        raise Exception('LimitFilters must be the only term in a filter sequence')
                    newvalues = newvalues[filter[0].offset : filter[0].offset + filter[0].number]
                else:
                    nv = []
                    for v in newvalues:
                        if self._get_base((ValueSet(v),) + filter):
                            nv.append(v)
                    newvalues = nv
            return newvalues
        return getset

    @mm(object, Filter, tuple)
    def _parse(self, node, base):
        return self.defaultFilter(node, base)

    @mm(object, Compare, tuple)
    def _parse(self, node, base):
        return self.defaultCompare(self._get_base(base)(), node)

    @mm(object, LimitFilter, tuple)
    def _parse(self, node, base):
        raise Exception('LimitFilters can only appear as the first (and only) term in a filter sequence')

    def defaultCompare(self, values, compare_node):
        for v in values: #find at least one value that passes
            if self.docompare(compare_node, v):
                return True
        return False

    @mm(object, GT, object)
    def docompare(self, compare, value):
        return value > compare.value

    @mm(object, LT, object)
    def docompare(self, compare, value):
        return value < compare.value

    @mm(object, LTE, object)
    def docompare(self, compare, value):
        return value <= compare.value

    @mm(object, GTE, object)
    def docompare(self, compare, value):
        return value >= compare.value

    @mm(object, EQ, object)
    def docompare(self, compare, value):
        return value == compare.value

    @mm(object, NE, object)
    def docompare(self, compare, value):
        return value != compare.value


text:
@class APPeer;
@class APTypingTypeEnum;
@class BSBserValues;
@class BSBserWriter;
@class IOSByteArray;

#define APUpdateTyping_HEADER 6

@interface APUpdateTyping : APUpdate

#pragma mark Public

- (instancetype)init;

- (instancetype)initWithAPPeer:(APPeer *)peer
                       withInt:(jint)uid
          withAPTypingTypeEnum:(APTypingTypeEnum *)typingType;

+ (APUpdateTyping *)fromBytesWithByteArray:(IOSByteArray *)data;

- (jint)getHeaderKey;

- (APPeer *)getPeer;

- (APTypingTypeEnum *)getTypingType;

- (jint)getUid;

- (void)parseWithBSBserValues:(BSBserValues *)values;

- (void)serializeWithBSBserWriter:(BSBserWriter *)writer;

- (NSString *)description;

@end

J2OBJC_EMPTY_STATIC_INIT(APUpdateTyping)

J2OBJC_STATIC_FIELD_GETTER(APUpdateTyping, HEADER, jint)

FOUNDATION_EXPORT APUpdateTyping *APUpdateTyping_fromBytesWithByteArray_(IOSByteArray *data);

FOUNDATION_EXPORT void APUpdateTyping_initWithAPPeer_withInt_withAPTypingTypeEnum_(APUpdateTyping *self, APPeer *peer, jint uid, APTypingTypeEnum *typingType);

FOUNDATION_EXPORT APUpdateTyping *new_APUpdateTyping_initWithAPPeer_withInt_withAPTypingTypeEnum_(APPeer *peer, jint uid, APTypingTypeEnum *typingType) NS_RETURNS_RETAINED;

FOUNDATION_EXPORT void APUpdateTyping_init(APUpdateTyping *self);

FOUNDATION_EXPORT APUpdateTyping *new_APUpdateTyping_init() NS_RETURNS_RETAINED;

J2OBJC_TYPE_LITERAL_HEADER(APUpdateTyping)

typedef APUpdateTyping ImActorModelApiUpdatesUpdateTyping;

#endif // _APUpdateTyping_H_


text:
package org.apache.lucene.analysis.ja;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.nio.charset.Charset;
import java.nio.charset.CharsetDecoder;
import java.nio.charset.CodingErrorAction;
import java.util.Locale;
import java.util.Map;

import org.apache.lucene.analysis.Tokenizer;
import org.apache.lucene.analysis.ja.JapaneseTokenizer;
import org.apache.lucene.analysis.ja.JapaneseTokenizer.Mode;
import org.apache.lucene.analysis.ja.dict.UserDictionary;
import org.apache.lucene.analysis.util.TokenizerFactory;
import org.apache.lucene.util.IOUtils;
import org.apache.lucene.analysis.util.ResourceLoader;
import org.apache.lucene.analysis.util.ResourceLoaderAware;

/**
 * Factory for {@link org.apache.lucene.analysis.ja.JapaneseTokenizer}.
 * <pre class="prettyprint">
 * <fieldType name="text_ja" class="solr.TextField">
 *   <analyzer>
 *     <tokenizer class="solr.JapaneseTokenizerFactory"
 *       mode="NORMAL"
 *       userDictionary="user.txt"
 *       userDictionaryEncoding="UTF-8"
 *       discardPunctuation="true"
 *     />
 *     <filter class="solr.JapaneseBaseFormFilterFactory"/>
 *   </analyzer>
 * </fieldType>
 * </pre>
 */
public class JapaneseTokenizerFactory extends TokenizerFactory implements ResourceLoaderAware {
  private static final String MODE = "mode";

  private static final String USER_DICT_PATH = "userDictionary";

  private static final String USER_DICT_ENCODING = "userDictionaryEncoding";

  private static final String DISCARD_PUNCTUATION = "discardPunctuation"; // Expert option

  private UserDictionary userDictionary;

  private Mode mode;

  private boolean discardPunctuation;

  @Override
  public void inform(ResourceLoader loader) throws IOException {
    mode = getMode(args);
    String userDictionaryPath = args.get(USER_DICT_PATH);
    if (userDictionaryPath != null) {
      InputStream stream = loader.openResource(userDictionaryPath);
      String encoding = args.get(USER_DICT_ENCODING);
      if (encoding == null) {
        encoding = IOUtils.UTF_8;
      }
      CharsetDecoder decoder = Charset.forName(encoding).newDecoder()
          .onMalformedInput(CodingErrorAction.REPORT)
          .onUnmappableCharacter(CodingErrorAction.REPORT);
      Reader reader = new InputStreamReader(stream, decoder);
      userDictionary = new UserDictionary(reader);
    } else {
      userDictionary = null;
    }
    discardPunctuation = getBoolean(DISCARD_PUNCTUATION, true);
  }

  @Override
  public Tokenizer create(Reader input) {
    return new JapaneseTokenizer(input, userDictionary, discardPunctuation, mode);
  }

  private Mode getMode(Map<String, String> args) {
    String mode = args.get(MODE);
    if (mode != null) {
      return Mode.valueOf(mode.toUpperCase(Locale.ROOT));
    } else {
      return JapaneseTokenizer.DEFAULT_MODE;
    }
  }
}