file_name large_stringlengths 4 140 | prefix large_stringlengths 0 39k | suffix large_stringlengths 0 36.1k | middle large_stringlengths 0 29.4k | fim_type large_stringclasses 4
values |
|---|---|---|---|---|
exceptions.js | import { ListWrapper } from 'angular2/src/facade/collection';
import { stringify, isBlank } from 'angular2/src/facade/lang';
import { BaseException, WrappedException } from 'angular2/src/facade/exceptions';
function findFirstClosedCycle(keys) {
var res = [];
for (var i = 0; i < keys.length; ++i) {
if (ListWrapper.contains(res, keys[i])) {
res.push(keys[i]);
return res;
}
else {
res.push(keys[i]);
}
}
return res;
}
function constructResolvingPath(keys) {
if (keys.length > 1) {
var reversed = findFirstClosedCycle(ListWrapper.reversed(keys));
var tokenStrs = reversed.map(k => stringify(k.token));
return " (" + tokenStrs.join(' -> ') + ")"; | else {
return "";
}
}
/**
* Base class for all errors arising from misconfigured providers.
*/
export class AbstractProviderError extends BaseException {
constructor(injector, key, constructResolvingMessage) {
super("DI Exception");
this.keys = [key];
this.injectors = [injector];
this.constructResolvingMessage = constructResolvingMessage;
this.message = this.constructResolvingMessage(this.keys);
}
addKey(injector, key) {
this.injectors.push(injector);
this.keys.push(key);
this.message = this.constructResolvingMessage(this.keys);
}
get context() { return this.injectors[this.injectors.length - 1].debugContext(); }
}
/**
* Thrown when trying to retrieve a dependency by `Key` from {@link Injector}, but the
* {@link Injector} does not have a {@link Provider} for {@link Key}.
*
* ### Example ([live demo](http://plnkr.co/edit/vq8D3FRB9aGbnWJqtEPE?p=preview))
*
* ```typescript
* class A {
* constructor(b:B) {}
* }
*
* expect(() => Injector.resolveAndCreate([A])).toThrowError();
* ```
*/
export class NoProviderError extends AbstractProviderError {
constructor(injector, key) {
super(injector, key, function (keys) {
var first = stringify(ListWrapper.first(keys).token);
return `No provider for ${first}!${constructResolvingPath(keys)}`;
});
}
}
/**
* Thrown when dependencies form a cycle.
*
* ### Example ([live demo](http://plnkr.co/edit/wYQdNos0Tzql3ei1EV9j?p=info))
*
* ```typescript
* var injector = Injector.resolveAndCreate([
* provide("one", {useFactory: (two) => "two", deps: [[new Inject("two")]]}),
* provide("two", {useFactory: (one) => "one", deps: [[new Inject("one")]]})
* ]);
*
* expect(() => injector.get("one")).toThrowError();
* ```
*
* Retrieving `A` or `B` throws a `CyclicDependencyError` as the graph above cannot be constructed.
*/
export class CyclicDependencyError extends AbstractProviderError {
constructor(injector, key) {
super(injector, key, function (keys) {
return `Cannot instantiate cyclic dependency!${constructResolvingPath(keys)}`;
});
}
}
/**
* Thrown when a constructing type returns with an Error.
*
* The `InstantiationError` class contains the original error plus the dependency graph which caused
* this object to be instantiated.
*
* ### Example ([live demo](http://plnkr.co/edit/7aWYdcqTQsP0eNqEdUAf?p=preview))
*
* ```typescript
* class A {
* constructor() {
* throw new Error('message');
* }
* }
*
* var injector = Injector.resolveAndCreate([A]);
* try {
* injector.get(A);
* } catch (e) {
* expect(e instanceof InstantiationError).toBe(true);
* expect(e.originalException.message).toEqual("message");
* expect(e.originalStack).toBeDefined();
* }
* ```
*/
export class InstantiationError extends WrappedException {
constructor(injector, originalException, originalStack, key) {
super("DI Exception", originalException, originalStack, null);
this.keys = [key];
this.injectors = [injector];
}
addKey(injector, key) {
this.injectors.push(injector);
this.keys.push(key);
}
get wrapperMessage() {
var first = stringify(ListWrapper.first(this.keys).token);
return `Error during instantiation of ${first}!${constructResolvingPath(this.keys)}.`;
}
get causeKey() { return this.keys[0]; }
get context() { return this.injectors[this.injectors.length - 1].debugContext(); }
}
/**
* Thrown when an object other then {@link Provider} (or `Type`) is passed to {@link Injector}
* creation.
*
* ### Example ([live demo](http://plnkr.co/edit/YatCFbPAMCL0JSSQ4mvH?p=preview))
*
* ```typescript
* expect(() => Injector.resolveAndCreate(["not a type"])).toThrowError();
* ```
*/
export class InvalidProviderError extends BaseException {
constructor(provider) {
super("Invalid provider - only instances of Provider and Type are allowed, got: " +
provider.toString());
}
}
/**
* Thrown when the class has no annotation information.
*
* Lack of annotation information prevents the {@link Injector} from determining which dependencies
* need to be injected into the constructor.
*
* ### Example ([live demo](http://plnkr.co/edit/rHnZtlNS7vJOPQ6pcVkm?p=preview))
*
* ```typescript
* class A {
* constructor(b) {}
* }
*
* expect(() => Injector.resolveAndCreate([A])).toThrowError();
* ```
*
* This error is also thrown when the class not marked with {@link Injectable} has parameter types.
*
* ```typescript
* class B {}
*
* class A {
* constructor(b:B) {} // no information about the parameter types of A is available at runtime.
* }
*
* expect(() => Injector.resolveAndCreate([A,B])).toThrowError();
* ```
*/
export class NoAnnotationError extends BaseException {
constructor(typeOrFunc, params) {
super(NoAnnotationError._genMessage(typeOrFunc, params));
}
static _genMessage(typeOrFunc, params) {
var signature = [];
for (var i = 0, ii = params.length; i < ii; i++) {
var parameter = params[i];
if (isBlank(parameter) || parameter.length == 0) {
signature.push('?');
}
else {
signature.push(parameter.map(stringify).join(' '));
}
}
return "Cannot resolve all parameters for " + stringify(typeOrFunc) + "(" +
signature.join(', ') + "). " + 'Make sure they all have valid type or annotations.';
}
}
/**
* Thrown when getting an object by index.
*
* ### Example ([live demo](http://plnkr.co/edit/bRs0SX2OTQiJzqvjgl8P?p=preview))
*
* ```typescript
* class A {}
*
* var injector = Injector.resolveAndCreate([A]);
*
* expect(() => injector.getAt(100)).toThrowError();
* ```
*/
export class OutOfBoundsError extends BaseException {
constructor(index) {
super(`Index ${index} is out-of-bounds.`);
}
}
// TODO: add a working example after alpha38 is released
/**
* Thrown when a multi provider and a regular provider are bound to the same token.
*
* ### Example
*
* ```typescript
* expect(() => Injector.resolveAndCreate([
* new Provider("Strings", {useValue: "string1", multi: true}),
* new Provider("Strings", {useValue: "string2", multi: false})
* ])).toThrowError();
* ```
*/
export class MixingMultiProvidersWithRegularProvidersError extends BaseException {
constructor(provider1, provider2) {
super("Cannot mix multi providers and regular providers, got: " + provider1.toString() + " " +
provider2.toString());
}
}
//# sourceMappingURL=exceptions.js.map | } | random_line_split |
exceptions.js | import { ListWrapper } from 'angular2/src/facade/collection';
import { stringify, isBlank } from 'angular2/src/facade/lang';
import { BaseException, WrappedException } from 'angular2/src/facade/exceptions';
function findFirstClosedCycle(keys) {
var res = [];
for (var i = 0; i < keys.length; ++i) {
if (ListWrapper.contains(res, keys[i])) {
res.push(keys[i]);
return res;
}
else {
res.push(keys[i]);
}
}
return res;
}
function constructResolvingPath(keys) {
if (keys.length > 1) {
var reversed = findFirstClosedCycle(ListWrapper.reversed(keys));
var tokenStrs = reversed.map(k => stringify(k.token));
return " (" + tokenStrs.join(' -> ') + ")";
}
else {
return "";
}
}
/**
* Base class for all errors arising from misconfigured providers.
*/
export class AbstractProviderError extends BaseException {
constructor(injector, key, constructResolvingMessage) {
super("DI Exception");
this.keys = [key];
this.injectors = [injector];
this.constructResolvingMessage = constructResolvingMessage;
this.message = this.constructResolvingMessage(this.keys);
}
addKey(injector, key) {
this.injectors.push(injector);
this.keys.push(key);
this.message = this.constructResolvingMessage(this.keys);
}
get context() { return this.injectors[this.injectors.length - 1].debugContext(); }
}
/**
* Thrown when trying to retrieve a dependency by `Key` from {@link Injector}, but the
* {@link Injector} does not have a {@link Provider} for {@link Key}.
*
* ### Example ([live demo](http://plnkr.co/edit/vq8D3FRB9aGbnWJqtEPE?p=preview))
*
* ```typescript
* class A {
* constructor(b:B) {}
* }
*
* expect(() => Injector.resolveAndCreate([A])).toThrowError();
* ```
*/
export class NoProviderError extends AbstractProviderError {
constructor(injector, key) {
super(injector, key, function (keys) {
var first = stringify(ListWrapper.first(keys).token);
return `No provider for ${first}!${constructResolvingPath(keys)}`;
});
}
}
/**
* Thrown when dependencies form a cycle.
*
* ### Example ([live demo](http://plnkr.co/edit/wYQdNos0Tzql3ei1EV9j?p=info))
*
* ```typescript
* var injector = Injector.resolveAndCreate([
* provide("one", {useFactory: (two) => "two", deps: [[new Inject("two")]]}),
* provide("two", {useFactory: (one) => "one", deps: [[new Inject("one")]]})
* ]);
*
* expect(() => injector.get("one")).toThrowError();
* ```
*
* Retrieving `A` or `B` throws a `CyclicDependencyError` as the graph above cannot be constructed.
*/
export class CyclicDependencyError extends AbstractProviderError {
constructor(injector, key) {
super(injector, key, function (keys) {
return `Cannot instantiate cyclic dependency!${constructResolvingPath(keys)}`;
});
}
}
/**
* Thrown when a constructing type returns with an Error.
*
* The `InstantiationError` class contains the original error plus the dependency graph which caused
* this object to be instantiated.
*
* ### Example ([live demo](http://plnkr.co/edit/7aWYdcqTQsP0eNqEdUAf?p=preview))
*
* ```typescript
* class A {
* constructor() {
* throw new Error('message');
* }
* }
*
* var injector = Injector.resolveAndCreate([A]);
* try {
* injector.get(A);
* } catch (e) {
* expect(e instanceof InstantiationError).toBe(true);
* expect(e.originalException.message).toEqual("message");
* expect(e.originalStack).toBeDefined();
* }
* ```
*/
export class InstantiationError extends WrappedException {
constructor(injector, originalException, originalStack, key) {
super("DI Exception", originalException, originalStack, null);
this.keys = [key];
this.injectors = [injector];
}
addKey(injector, key) {
this.injectors.push(injector);
this.keys.push(key);
}
get wrapperMessage() {
var first = stringify(ListWrapper.first(this.keys).token);
return `Error during instantiation of ${first}!${constructResolvingPath(this.keys)}.`;
}
get causeKey() { return this.keys[0]; }
get context() { return this.injectors[this.injectors.length - 1].debugContext(); }
}
/**
* Thrown when an object other then {@link Provider} (or `Type`) is passed to {@link Injector}
* creation.
*
* ### Example ([live demo](http://plnkr.co/edit/YatCFbPAMCL0JSSQ4mvH?p=preview))
*
* ```typescript
* expect(() => Injector.resolveAndCreate(["not a type"])).toThrowError();
* ```
*/
export class InvalidProviderError extends BaseException {
constructor(provider) {
super("Invalid provider - only instances of Provider and Type are allowed, got: " +
provider.toString());
}
}
/**
* Thrown when the class has no annotation information.
*
* Lack of annotation information prevents the {@link Injector} from determining which dependencies
* need to be injected into the constructor.
*
* ### Example ([live demo](http://plnkr.co/edit/rHnZtlNS7vJOPQ6pcVkm?p=preview))
*
* ```typescript
* class A {
* constructor(b) {}
* }
*
* expect(() => Injector.resolveAndCreate([A])).toThrowError();
* ```
*
* This error is also thrown when the class not marked with {@link Injectable} has parameter types.
*
* ```typescript
* class B {}
*
* class A {
* constructor(b:B) {} // no information about the parameter types of A is available at runtime.
* }
*
* expect(() => Injector.resolveAndCreate([A,B])).toThrowError();
* ```
*/
export class NoAnnotationError extends BaseException {
constructor(typeOrFunc, params) {
super(NoAnnotationError._genMessage(typeOrFunc, params));
}
static _genMessage(typeOrFunc, params) {
var signature = [];
for (var i = 0, ii = params.length; i < ii; i++) |
return "Cannot resolve all parameters for " + stringify(typeOrFunc) + "(" +
signature.join(', ') + "). " + 'Make sure they all have valid type or annotations.';
}
}
/**
* Thrown when getting an object by index.
*
* ### Example ([live demo](http://plnkr.co/edit/bRs0SX2OTQiJzqvjgl8P?p=preview))
*
* ```typescript
* class A {}
*
* var injector = Injector.resolveAndCreate([A]);
*
* expect(() => injector.getAt(100)).toThrowError();
* ```
*/
export class OutOfBoundsError extends BaseException {
constructor(index) {
super(`Index ${index} is out-of-bounds.`);
}
}
// TODO: add a working example after alpha38 is released
/**
* Thrown when a multi provider and a regular provider are bound to the same token.
*
* ### Example
*
* ```typescript
* expect(() => Injector.resolveAndCreate([
* new Provider("Strings", {useValue: "string1", multi: true}),
* new Provider("Strings", {useValue: "string2", multi: false})
* ])).toThrowError();
* ```
*/
export class MixingMultiProvidersWithRegularProvidersError extends BaseException {
constructor(provider1, provider2) {
super("Cannot mix multi providers and regular providers, got: " + provider1.toString() + " " +
provider2.toString());
}
}
//# sourceMappingURL=exceptions.js.map | {
var parameter = params[i];
if (isBlank(parameter) || parameter.length == 0) {
signature.push('?');
}
else {
signature.push(parameter.map(stringify).join(' '));
}
} | conditional_block |
main.rs | /*
License stuff
----------------------------------------------------------
Copyright 2013 Joris Rehm
Licensed under the Apache License, Version 2.0.
Licensed under The MIT License.
See joined files "LICENSE-APACHE" and "LICENSE-MIT".
----------------------------------------------------------
*/
extern mod sdl;
use ecs::FunctionalTable;
use ecs::Entity;
use vec::Vec;
use vec::MyFloat;
mod ecs;
mod vec;
/* Let's defining a data structure for managing our ECS. */
struct Manager {
/* There is a data to remember the numbers of created entities. */
priv entities_numbers : uint,
// tables
table_position : FunctionalTable<Vec>,
table_velocity : FunctionalTable<Vec>,
table_acceleration : FunctionalTable<Vec>,
table_mass : FunctionalTable<MyFloat>
}
impl Manager {
/* Inializing an empty ECS */
fn new() -> ~Manager {
~Manager {
entities_numbers : 0,
table_position : FunctionalTable::new(~"position"),
table_velocity : FunctionalTable::new(~"velocity"),
table_acceleration : FunctionalTable::new(~"acceleration"),
table_mass : FunctionalTable::new(~"mass")
}
}
/* Creating an new entity is just taking a unused id. */
fn new_entity(&mut self) -> Entity {
let res = self.entities_numbers;
self.entities_numbers = self.entities_numbers + 1;
info!("create_entity id={}", res);
res
}
/* TODO: how to manage the deletion of entities ?
It depend if we iterate on entity id or on component tables.
Maybe it's enought to delete the associated components.
We may use a pool of unused id for recycling (probably not
very needed) or just search for not associated id.*/
} /* impl Manager */
#[test]
fn test_entity_management() {
let mut mng = Manager::new();
let e1 = mng.new_entity();
assert!( e1 == 0 );
let e2 = mng.new_entity();
assert!( e2 == 1 );
}
/* ----------------------------------------------------------- */
// TODO define an integration function and refactor
// compute_velocity and compute_position.
// TODO it's not really usefull to record acceleration
/* ----------------------------------------------------------- */
fn init_system() -> ~Manager {
println("use RUST_LOG=3 to see log");
let mut mng = Manager::new();
let zero = Vec(0., 0., 0.);
//
for i in range(0,10) {
let entity2 = mng.new_entity();
mng.table_position.set(entity2, Vec::rand_around_origin(5., 25.) );
mng.table_velocity.set(entity2, Vec::rand_around_origin(0.2, 0.5) );
mng.table_acceleration.set(entity2, zero);
mng.table_mass.set(entity2, 1.);
}
//
return mng;
}
fn system_loop(mng : &mut Manager, cycle : uint, screen: &sdl::video::Surface){
let delta_time = 1./24. as MyFloat; // TODO compute real delay
info!("start_cycle {}",cycle);
compute_acceleration(mng);
compute_velocity(mng, delta_time);
compute_position(mng, delta_time);
draw(mng,screen)
}
fn draw(mng: &Manager, screen: &sdl::video::Surface){
screen.clear();
for x in mng.table_position.iter() {
let (&e,pos) : (&Entity,&Vec) = x;
let Vec(pos_x,pos_y,_) = *pos;
let mut x = 0;
let mut y = 0;
let scale = 5.;
x = (pos_x*scale + 400.) as i16;
y = (pos_y*scale + 300.) as i16 ;
draw_circle(screen, x, y);
}
}
// Having an acceleration imply having a velocity!
// Having an acceleration imply having a mass!
fn compute_acceleration(mng: &mut Manager) {
let comp = |e: uint, accel: &Vec| {
// note: accel not used
let pos = mng.table_position.get(e);
let force = gravity_force_at(*pos);
let mass = *mng.table_mass.get(e);
force.scale(1./mass)
};
mng.table_acceleration.apply(comp);
}
fn gravity_force_at(pos: Vec) -> Vec {
let earth_gravity = 9.80665; // in m/s²
let planet_center = Vec(0.,0.,0.);
// the vector from planet center to the pos
let pos_from_planet = pos - planet_center;
// TODO and yes it's useless :)
let dist = pos_from_planet.length();
let gravity_force =
pos_from_planet.normalize(
).scale(- earth_gravity
).scale(1./(dist*dist));
if gravity_force.is_nan() {
Vec(0.,0.,0.)
} else {
gravity_force
}
}
// integration of acceleration
// having a acceleration imply having a velocity
fn compute_velocity (mng: &mut Manager, dt: MyFloat) {
for x in mng.table_acceleration.iter() {
let (&e,accel) : (&Entity,&Vec) = x;
let vel : Vec = *mng.table_velocity.get(e);
let new_vel = vel + accel.scale(dt);
mng.table_velocity.set(e, new_vel);
}
}
// Move all the entities with the velocity applied during dt time.
// Having a velocity imply having a position!
fn compute_position(mng: &mut Manager, dt:MyFloat) {
for x in mng.table_velocity.iter() {
let (&e,vel) : (&Entity,&Vec) = x;
let pos = *mng.table_position.get(e);
let new_pos = pos + vel.scale(dt);
mng.table_position.set(e, new_pos);
}
}
fn draw_circle(screen : &sdl::video::Surface, px : i16, py : i16){
// this algorithm is dumb
// TODO use a proper algorithm for circle drawing
let r = 10;
let mut x = -r;
let mut y = -r;
while(y <= r){
if x*x + y*y <= r*r {
draw_plot(screen, px+x, py+y);
}
x += 1;
if r < x {
x = -r;
y += 1;
}
}
}
fn draw_plot(screen : &sdl::video::Surface, px : i16, py : i16){
let rect = Some(sdl::Rect {
x: px,
y: py,
w: 1,
h: 1
});
let color= sdl::video::RGB(255,255,255);
screen.fill_rect(rect,color);
}
fn main() {
sdl::init([sdl::InitVideo]);
sdl::wm::set_caption("Bouncing Balls On a Big Ball", "Bobobib");
let screen = match sdl::video::set_video_mode
(800, 600, 32, [sdl::video::HWSurface],[sdl::video::DoubleBuf]) {
Ok(screen) => screen,
Err(err) => fail!("Impossible to open screen: {}", err)
};
let mut mng = init_system();
let mut cycle = 1; | 'event : loop {
match sdl::event::poll_event() {
sdl::event::QuitEvent => break 'main,
sdl::event::NoEvent => break 'event,
sdl::event::KeyEvent(k, _, _, _)
if k == sdl::event::EscapeKey
=> break 'main,
_ => {}
}
}
system_loop(mng, cycle, screen);
cycle += 1;
screen.flip();
// if cycle == 100 {
// break 'main;
// }
}
sdl::quit();
} |
'main : loop { | random_line_split |
main.rs | /*
License stuff
----------------------------------------------------------
Copyright 2013 Joris Rehm
Licensed under the Apache License, Version 2.0.
Licensed under The MIT License.
See joined files "LICENSE-APACHE" and "LICENSE-MIT".
----------------------------------------------------------
*/
extern mod sdl;
use ecs::FunctionalTable;
use ecs::Entity;
use vec::Vec;
use vec::MyFloat;
mod ecs;
mod vec;
/* Let's defining a data structure for managing our ECS. */
struct Manager {
/* There is a data to remember the numbers of created entities. */
priv entities_numbers : uint,
// tables
table_position : FunctionalTable<Vec>,
table_velocity : FunctionalTable<Vec>,
table_acceleration : FunctionalTable<Vec>,
table_mass : FunctionalTable<MyFloat>
}
impl Manager {
/* Inializing an empty ECS */
fn new() -> ~Manager {
~Manager {
entities_numbers : 0,
table_position : FunctionalTable::new(~"position"),
table_velocity : FunctionalTable::new(~"velocity"),
table_acceleration : FunctionalTable::new(~"acceleration"),
table_mass : FunctionalTable::new(~"mass")
}
}
/* Creating an new entity is just taking a unused id. */
fn new_entity(&mut self) -> Entity {
let res = self.entities_numbers;
self.entities_numbers = self.entities_numbers + 1;
info!("create_entity id={}", res);
res
}
/* TODO: how to manage the deletion of entities ?
It depend if we iterate on entity id or on component tables.
Maybe it's enought to delete the associated components.
We may use a pool of unused id for recycling (probably not
very needed) or just search for not associated id.*/
} /* impl Manager */
#[test]
fn test_entity_management() |
/* ----------------------------------------------------------- */
// TODO define an integration function and refactor
// compute_velocity and compute_position.
// TODO it's not really usefull to record acceleration
/* ----------------------------------------------------------- */
fn init_system() -> ~Manager {
println("use RUST_LOG=3 to see log");
let mut mng = Manager::new();
let zero = Vec(0., 0., 0.);
//
for i in range(0,10) {
let entity2 = mng.new_entity();
mng.table_position.set(entity2, Vec::rand_around_origin(5., 25.) );
mng.table_velocity.set(entity2, Vec::rand_around_origin(0.2, 0.5) );
mng.table_acceleration.set(entity2, zero);
mng.table_mass.set(entity2, 1.);
}
//
return mng;
}
fn system_loop(mng : &mut Manager, cycle : uint, screen: &sdl::video::Surface){
let delta_time = 1./24. as MyFloat; // TODO compute real delay
info!("start_cycle {}",cycle);
compute_acceleration(mng);
compute_velocity(mng, delta_time);
compute_position(mng, delta_time);
draw(mng,screen)
}
fn draw(mng: &Manager, screen: &sdl::video::Surface){
screen.clear();
for x in mng.table_position.iter() {
let (&e,pos) : (&Entity,&Vec) = x;
let Vec(pos_x,pos_y,_) = *pos;
let mut x = 0;
let mut y = 0;
let scale = 5.;
x = (pos_x*scale + 400.) as i16;
y = (pos_y*scale + 300.) as i16 ;
draw_circle(screen, x, y);
}
}
// Having an acceleration imply having a velocity!
// Having an acceleration imply having a mass!
fn compute_acceleration(mng: &mut Manager) {
let comp = |e: uint, accel: &Vec| {
// note: accel not used
let pos = mng.table_position.get(e);
let force = gravity_force_at(*pos);
let mass = *mng.table_mass.get(e);
force.scale(1./mass)
};
mng.table_acceleration.apply(comp);
}
fn gravity_force_at(pos: Vec) -> Vec {
let earth_gravity = 9.80665; // in m/s²
let planet_center = Vec(0.,0.,0.);
// the vector from planet center to the pos
let pos_from_planet = pos - planet_center;
// TODO and yes it's useless :)
let dist = pos_from_planet.length();
let gravity_force =
pos_from_planet.normalize(
).scale(- earth_gravity
).scale(1./(dist*dist));
if gravity_force.is_nan() {
Vec(0.,0.,0.)
} else {
gravity_force
}
}
// integration of acceleration
// having a acceleration imply having a velocity
fn compute_velocity (mng: &mut Manager, dt: MyFloat) {
for x in mng.table_acceleration.iter() {
let (&e,accel) : (&Entity,&Vec) = x;
let vel : Vec = *mng.table_velocity.get(e);
let new_vel = vel + accel.scale(dt);
mng.table_velocity.set(e, new_vel);
}
}
// Move all the entities with the velocity applied during dt time.
// Having a velocity imply having a position!
fn compute_position(mng: &mut Manager, dt:MyFloat) {
for x in mng.table_velocity.iter() {
let (&e,vel) : (&Entity,&Vec) = x;
let pos = *mng.table_position.get(e);
let new_pos = pos + vel.scale(dt);
mng.table_position.set(e, new_pos);
}
}
fn draw_circle(screen : &sdl::video::Surface, px : i16, py : i16){
// this algorithm is dumb
// TODO use a proper algorithm for circle drawing
let r = 10;
let mut x = -r;
let mut y = -r;
while(y <= r){
if x*x + y*y <= r*r {
draw_plot(screen, px+x, py+y);
}
x += 1;
if r < x {
x = -r;
y += 1;
}
}
}
fn draw_plot(screen : &sdl::video::Surface, px : i16, py : i16){
let rect = Some(sdl::Rect {
x: px,
y: py,
w: 1,
h: 1
});
let color= sdl::video::RGB(255,255,255);
screen.fill_rect(rect,color);
}
fn main() {
sdl::init([sdl::InitVideo]);
sdl::wm::set_caption("Bouncing Balls On a Big Ball", "Bobobib");
let screen = match sdl::video::set_video_mode
(800, 600, 32, [sdl::video::HWSurface],[sdl::video::DoubleBuf]) {
Ok(screen) => screen,
Err(err) => fail!("Impossible to open screen: {}", err)
};
let mut mng = init_system();
let mut cycle = 1;
'main : loop {
'event : loop {
match sdl::event::poll_event() {
sdl::event::QuitEvent => break 'main,
sdl::event::NoEvent => break 'event,
sdl::event::KeyEvent(k, _, _, _)
if k == sdl::event::EscapeKey
=> break 'main,
_ => {}
}
}
system_loop(mng, cycle, screen);
cycle += 1;
screen.flip();
// if cycle == 100 {
// break 'main;
// }
}
sdl::quit();
}
| {
let mut mng = Manager::new();
let e1 = mng.new_entity();
assert!( e1 == 0 );
let e2 = mng.new_entity();
assert!( e2 == 1 );
} | identifier_body |
main.rs | /*
License stuff
----------------------------------------------------------
Copyright 2013 Joris Rehm
Licensed under the Apache License, Version 2.0.
Licensed under The MIT License.
See joined files "LICENSE-APACHE" and "LICENSE-MIT".
----------------------------------------------------------
*/
extern mod sdl;
use ecs::FunctionalTable;
use ecs::Entity;
use vec::Vec;
use vec::MyFloat;
mod ecs;
mod vec;
/* Let's defining a data structure for managing our ECS. */
struct Manager {
/* There is a data to remember the numbers of created entities. */
priv entities_numbers : uint,
// tables
table_position : FunctionalTable<Vec>,
table_velocity : FunctionalTable<Vec>,
table_acceleration : FunctionalTable<Vec>,
table_mass : FunctionalTable<MyFloat>
}
impl Manager {
/* Inializing an empty ECS */
fn new() -> ~Manager {
~Manager {
entities_numbers : 0,
table_position : FunctionalTable::new(~"position"),
table_velocity : FunctionalTable::new(~"velocity"),
table_acceleration : FunctionalTable::new(~"acceleration"),
table_mass : FunctionalTable::new(~"mass")
}
}
/* Creating an new entity is just taking a unused id. */
fn new_entity(&mut self) -> Entity {
let res = self.entities_numbers;
self.entities_numbers = self.entities_numbers + 1;
info!("create_entity id={}", res);
res
}
/* TODO: how to manage the deletion of entities ?
It depend if we iterate on entity id or on component tables.
Maybe it's enought to delete the associated components.
We may use a pool of unused id for recycling (probably not
very needed) or just search for not associated id.*/
} /* impl Manager */
#[test]
fn test_entity_management() {
let mut mng = Manager::new();
let e1 = mng.new_entity();
assert!( e1 == 0 );
let e2 = mng.new_entity();
assert!( e2 == 1 );
}
/* ----------------------------------------------------------- */
// TODO define an integration function and refactor
// compute_velocity and compute_position.
// TODO it's not really usefull to record acceleration
/* ----------------------------------------------------------- */
fn | () -> ~Manager {
println("use RUST_LOG=3 to see log");
let mut mng = Manager::new();
let zero = Vec(0., 0., 0.);
//
for i in range(0,10) {
let entity2 = mng.new_entity();
mng.table_position.set(entity2, Vec::rand_around_origin(5., 25.) );
mng.table_velocity.set(entity2, Vec::rand_around_origin(0.2, 0.5) );
mng.table_acceleration.set(entity2, zero);
mng.table_mass.set(entity2, 1.);
}
//
return mng;
}
fn system_loop(mng : &mut Manager, cycle : uint, screen: &sdl::video::Surface){
let delta_time = 1./24. as MyFloat; // TODO compute real delay
info!("start_cycle {}",cycle);
compute_acceleration(mng);
compute_velocity(mng, delta_time);
compute_position(mng, delta_time);
draw(mng,screen)
}
fn draw(mng: &Manager, screen: &sdl::video::Surface){
screen.clear();
for x in mng.table_position.iter() {
let (&e,pos) : (&Entity,&Vec) = x;
let Vec(pos_x,pos_y,_) = *pos;
let mut x = 0;
let mut y = 0;
let scale = 5.;
x = (pos_x*scale + 400.) as i16;
y = (pos_y*scale + 300.) as i16 ;
draw_circle(screen, x, y);
}
}
// Having an acceleration imply having a velocity!
// Having an acceleration imply having a mass!
fn compute_acceleration(mng: &mut Manager) {
let comp = |e: uint, accel: &Vec| {
// note: accel not used
let pos = mng.table_position.get(e);
let force = gravity_force_at(*pos);
let mass = *mng.table_mass.get(e);
force.scale(1./mass)
};
mng.table_acceleration.apply(comp);
}
fn gravity_force_at(pos: Vec) -> Vec {
let earth_gravity = 9.80665; // in m/s²
let planet_center = Vec(0.,0.,0.);
// the vector from planet center to the pos
let pos_from_planet = pos - planet_center;
// TODO and yes it's useless :)
let dist = pos_from_planet.length();
let gravity_force =
pos_from_planet.normalize(
).scale(- earth_gravity
).scale(1./(dist*dist));
if gravity_force.is_nan() {
Vec(0.,0.,0.)
} else {
gravity_force
}
}
// integration of acceleration
// having a acceleration imply having a velocity
fn compute_velocity (mng: &mut Manager, dt: MyFloat) {
for x in mng.table_acceleration.iter() {
let (&e,accel) : (&Entity,&Vec) = x;
let vel : Vec = *mng.table_velocity.get(e);
let new_vel = vel + accel.scale(dt);
mng.table_velocity.set(e, new_vel);
}
}
// Move all the entities with the velocity applied during dt time.
// Having a velocity imply having a position!
fn compute_position(mng: &mut Manager, dt:MyFloat) {
for x in mng.table_velocity.iter() {
let (&e,vel) : (&Entity,&Vec) = x;
let pos = *mng.table_position.get(e);
let new_pos = pos + vel.scale(dt);
mng.table_position.set(e, new_pos);
}
}
fn draw_circle(screen : &sdl::video::Surface, px : i16, py : i16){
// this algorithm is dumb
// TODO use a proper algorithm for circle drawing
let r = 10;
let mut x = -r;
let mut y = -r;
while(y <= r){
if x*x + y*y <= r*r {
draw_plot(screen, px+x, py+y);
}
x += 1;
if r < x {
x = -r;
y += 1;
}
}
}
fn draw_plot(screen : &sdl::video::Surface, px : i16, py : i16){
let rect = Some(sdl::Rect {
x: px,
y: py,
w: 1,
h: 1
});
let color= sdl::video::RGB(255,255,255);
screen.fill_rect(rect,color);
}
fn main() {
sdl::init([sdl::InitVideo]);
sdl::wm::set_caption("Bouncing Balls On a Big Ball", "Bobobib");
let screen = match sdl::video::set_video_mode
(800, 600, 32, [sdl::video::HWSurface],[sdl::video::DoubleBuf]) {
Ok(screen) => screen,
Err(err) => fail!("Impossible to open screen: {}", err)
};
let mut mng = init_system();
let mut cycle = 1;
'main : loop {
'event : loop {
match sdl::event::poll_event() {
sdl::event::QuitEvent => break 'main,
sdl::event::NoEvent => break 'event,
sdl::event::KeyEvent(k, _, _, _)
if k == sdl::event::EscapeKey
=> break 'main,
_ => {}
}
}
system_loop(mng, cycle, screen);
cycle += 1;
screen.flip();
// if cycle == 100 {
// break 'main;
// }
}
sdl::quit();
}
| init_system | identifier_name |
gulpfile.js | var gulp = require('gulp');
var gutil = require('gulp-util');
var bower = require('bower');
var concat = require('gulp-concat');
var sass = require('gulp-sass');
var minifyCss = require('gulp-minify');
var rename = require('gulp-rename');
var sh = require('shelljs');
var minify = require('gulp-minify');
var argv = require('yargs').argv;
var mid = 0;
for (arg in argv){
if (argv[arg] === true){
mid = parseInt(arg,16); // yeah, counting to f ;)
}
}
var libs= [
"./www/lib/ionic/release/js/ionic.bundle.js",
"./www/lib/moment/min/moment.min.js","./www/lib/angular-moment/angular-moment.min.js","./www/lib/moment/locale/fr.js","./www/lib/moment-timezone/builds/moment-timezone-with-data-2010-2020.min.js","./www/lib/openfb/openfb.js",
"./www/lib/ngstorage/ngStorage.min.js","./www/lib/leaflet/dist/leaflet.js","./www/lib/angular-simple-logger/dist/angular-simple-logger.js","./www/lib/angular-leaflet-directive/dist/angular-leaflet-directive.min.js","./www/lib/ngCordova/dist/ng-cordova.min.js","./www/cordova.js"
//, /* BUGGY */ "./www/lib/ng-walkthrough/ng-walkthrough.js"
]
var paths = {
sass: ['./scss/**/*.scss'],
js: [
'./www/js/*.js','./www/WhatTheFood/shared/*.js','./www/WhatTheFood/shared/**/*.js','./www/WhatTheFood/components/**/*.js'
],
lib: libs,
lib1: libs.slice(0,mid),
mid : libs[mid],
lib2: libs.slice(mid + 1)
};
/*
gulp.task('watch', function() {
gulp.watch(paths.js, ['concat']);
});
*/
gulp.task('dbg', ['concat-lib1','concat-lib2','concat-mid']);
gulp.task('concat-lib1',function(){
return gulp.src(paths.lib1)
.pipe(concat('lib1-bundle.js'))
.pipe(gulp.dest('./www/dist/'));
})
gulp.task('concat-lib2',function(){
return gulp.src(paths.lib2)
.pipe(concat('lib2-bundle.js'))
.pipe(gulp.dest('./www/dist/'));
})
gulp.task('concat-mid',function(){
return gulp.src(paths.mid)
.pipe(concat('mid-bundle.js'))
.pipe(gulp.dest('./www/dist/'));
})
gulp.task('concat', ['concat-src','concat-lib']); | })
gulp.task('concat-src', function() {
return gulp.src(paths.js)
.pipe(concat('app-bundle.js'))
.pipe(gulp.dest('./www/dist/'));
});
gulp.task('concat-lib', function() {
return gulp.src(paths.lib)
.pipe(concat('lib-bundle.js'))
.pipe(gulp.dest('./www/dist/'));
});
gulp.task('minify', ['concat'],function() {
return gulp.src(['./www/dist/app-bundle.js','./www/dist/lib-bundle.js'])
.pipe(minify({mangle:false}))
.pipe(gulp.dest('./www/dist'));
});
gulp.task('sass', function(done) {
gulp.src('./scss/ionic.app.scss')
.pipe(sass())
.pipe(gulp.dest('./www/css/'))
.pipe(minifyCss({
keepSpecialComments: 0
}))
.pipe(rename({ extname: '.min.css' }))
.pipe(gulp.dest('./www/css/'))
.on('end', done);
});
gulp.task('watch', function() {
gulp.watch(paths.sass, ['sass']);
});
gulp.task('install', ['git-check'], function() {
return bower.commands.install()
.on('log', function(data) {
gutil.log('bower', gutil.colors.cyan(data.id), data.message);
});
});
gulp.task('git-check', function(done) {
if (!sh.which('git')) {
console.log(
' ' + gutil.colors.red('Git is not installed.'),
'\n Git, the version control system, is required to download Ionic.',
'\n Download git here:', gutil.colors.cyan('http://git-scm.com/downloads') + '.',
'\n Once git is installed, run \'' + gutil.colors.cyan('gulp install') + '\' again.'
);
process.exit(1);
}
done();
});
gulp.task('concat-and-minify', ['concat','minify']);
gulp.task('default', ['concat-and-minify']); |
gulp.task('concat-all', ['minify'],function(){
return gulp.src(['./www/dist/lib-bundle-min.js','./www/dist/app-bundle-min.js'])
.pipe(concat('bundle-min.js'))
.pipe(gulp.dest('./www/dist/')); | random_line_split |
gulpfile.js | var gulp = require('gulp');
var gutil = require('gulp-util');
var bower = require('bower');
var concat = require('gulp-concat');
var sass = require('gulp-sass');
var minifyCss = require('gulp-minify');
var rename = require('gulp-rename');
var sh = require('shelljs');
var minify = require('gulp-minify');
var argv = require('yargs').argv;
var mid = 0;
for (arg in argv){
if (argv[arg] === true){
mid = parseInt(arg,16); // yeah, counting to f ;)
}
}
var libs= [
"./www/lib/ionic/release/js/ionic.bundle.js",
"./www/lib/moment/min/moment.min.js","./www/lib/angular-moment/angular-moment.min.js","./www/lib/moment/locale/fr.js","./www/lib/moment-timezone/builds/moment-timezone-with-data-2010-2020.min.js","./www/lib/openfb/openfb.js",
"./www/lib/ngstorage/ngStorage.min.js","./www/lib/leaflet/dist/leaflet.js","./www/lib/angular-simple-logger/dist/angular-simple-logger.js","./www/lib/angular-leaflet-directive/dist/angular-leaflet-directive.min.js","./www/lib/ngCordova/dist/ng-cordova.min.js","./www/cordova.js"
//, /* BUGGY */ "./www/lib/ng-walkthrough/ng-walkthrough.js"
]
var paths = {
sass: ['./scss/**/*.scss'],
js: [
'./www/js/*.js','./www/WhatTheFood/shared/*.js','./www/WhatTheFood/shared/**/*.js','./www/WhatTheFood/components/**/*.js'
],
lib: libs,
lib1: libs.slice(0,mid),
mid : libs[mid],
lib2: libs.slice(mid + 1)
};
/*
gulp.task('watch', function() {
gulp.watch(paths.js, ['concat']);
});
*/
gulp.task('dbg', ['concat-lib1','concat-lib2','concat-mid']);
gulp.task('concat-lib1',function(){
return gulp.src(paths.lib1)
.pipe(concat('lib1-bundle.js'))
.pipe(gulp.dest('./www/dist/'));
})
gulp.task('concat-lib2',function(){
return gulp.src(paths.lib2)
.pipe(concat('lib2-bundle.js'))
.pipe(gulp.dest('./www/dist/'));
})
gulp.task('concat-mid',function(){
return gulp.src(paths.mid)
.pipe(concat('mid-bundle.js'))
.pipe(gulp.dest('./www/dist/'));
})
gulp.task('concat', ['concat-src','concat-lib']);
gulp.task('concat-all', ['minify'],function(){
return gulp.src(['./www/dist/lib-bundle-min.js','./www/dist/app-bundle-min.js'])
.pipe(concat('bundle-min.js'))
.pipe(gulp.dest('./www/dist/'));
})
gulp.task('concat-src', function() {
return gulp.src(paths.js)
.pipe(concat('app-bundle.js'))
.pipe(gulp.dest('./www/dist/'));
});
gulp.task('concat-lib', function() {
return gulp.src(paths.lib)
.pipe(concat('lib-bundle.js'))
.pipe(gulp.dest('./www/dist/'));
});
gulp.task('minify', ['concat'],function() {
return gulp.src(['./www/dist/app-bundle.js','./www/dist/lib-bundle.js'])
.pipe(minify({mangle:false}))
.pipe(gulp.dest('./www/dist'));
});
gulp.task('sass', function(done) {
gulp.src('./scss/ionic.app.scss')
.pipe(sass())
.pipe(gulp.dest('./www/css/'))
.pipe(minifyCss({
keepSpecialComments: 0
}))
.pipe(rename({ extname: '.min.css' }))
.pipe(gulp.dest('./www/css/'))
.on('end', done);
});
gulp.task('watch', function() {
gulp.watch(paths.sass, ['sass']);
});
gulp.task('install', ['git-check'], function() {
return bower.commands.install()
.on('log', function(data) {
gutil.log('bower', gutil.colors.cyan(data.id), data.message);
});
});
gulp.task('git-check', function(done) {
if (!sh.which('git')) |
done();
});
gulp.task('concat-and-minify', ['concat','minify']);
gulp.task('default', ['concat-and-minify']);
| {
console.log(
' ' + gutil.colors.red('Git is not installed.'),
'\n Git, the version control system, is required to download Ionic.',
'\n Download git here:', gutil.colors.cyan('http://git-scm.com/downloads') + '.',
'\n Once git is installed, run \'' + gutil.colors.cyan('gulp install') + '\' again.'
);
process.exit(1);
} | conditional_block |
lib.rs | // =================================================================
//
// * WARNING *
//
// This file is generated!
//
// Changes made to this file will be overwritten. If changes are
// required to the generated code, the service_crategen project
// must be updated to generate the changes.
//
// =================================================================
#![doc(html_logo_url = "https://raw.githubusercontent.com/rusoto/rusoto/master/assets/logo-square.png")]
//! <p><fullname>Amazon DynamoDB</fullname> <p>Amazon DynamoDB Streams provides API actions for accessing streams and processing stream records. To learn more about application development with Streams, see <a href="http://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Streams.html">Capturing Table Activity with DynamoDB Streams</a> in the Amazon DynamoDB Developer Guide.</p></p>
//!
//! If you're using the service, you're probably looking for [DynamoDbStreamsClient](struct.DynamoDbStreamsClient.html) and [DynamoDbStreams](trait.DynamoDbStreams.html).
extern crate futures;
extern crate rusoto_core;
extern crate serde;
#[macro_use] | extern crate serde_derive;
extern crate serde_json;
mod generated;
mod custom;
pub use generated::*;
pub use custom::*; | random_line_split | |
disallow_id_as_alias.rs | /*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
use common::WithLocation;
use errors::try2;
use graphql_ir::{
LinkedField, Program, ScalarField, ValidationError, ValidationMessage, Validator,
};
use interner::{Intern, StringKey};
use schema::{FieldID, Schema};
pub fn disallow_id_as_alias<'s>(program: &'s Program<'s>) -> Vec<ValidationError> {
let mut validator = DisallowIdAsAlias::new(program);
match validator.validate_program(program) {
Err(e) => e,
Ok(_) => Default::default(),
}
}
struct DisallowIdAsAlias<'s> {
program: &'s Program<'s>,
id_key: StringKey,
}
impl<'s> DisallowIdAsAlias<'s> {
fn new(program: &'s Program<'s>) -> Self { | }
}
}
impl<'s> Validator for DisallowIdAsAlias<'s> {
const NAME: &'static str = "DisallowIdAsAlias";
const VALIDATE_ARGUMENTS: bool = false;
const VALIDATE_DIRECTIVES: bool = false;
fn validate_linked_field(&mut self, field: &LinkedField) -> Result<(), Vec<ValidationError>> {
if let Some(alias) = field.alias {
try2(
validate_field_alias(
self.program.schema(),
self.id_key,
&alias,
field.definition.item,
),
self.validate_selections(&field.selections),
)?;
Ok(())
} else {
self.validate_selections(&field.selections)
}
}
fn validate_scalar_field(&mut self, field: &ScalarField) -> Result<(), Vec<ValidationError>> {
if let Some(alias) = field.alias {
validate_field_alias(
self.program.schema(),
self.id_key,
&alias,
field.definition.item,
)
} else {
Ok(())
}
}
}
fn validate_field_alias<'s>(
schema: &'s Schema,
id_key: StringKey,
alias: &WithLocation<StringKey>,
field: FieldID,
) -> Result<(), Vec<ValidationError>> {
if alias.item == id_key && schema.field(field).name != id_key {
Err(vec![ValidationError::new(
ValidationMessage::DisallowIdAsAliasError(),
vec![alias.location],
)])
} else {
Ok(())
}
} | Self {
program,
id_key: "id".intern(), | random_line_split |
disallow_id_as_alias.rs | /*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
use common::WithLocation;
use errors::try2;
use graphql_ir::{
LinkedField, Program, ScalarField, ValidationError, ValidationMessage, Validator,
};
use interner::{Intern, StringKey};
use schema::{FieldID, Schema};
pub fn disallow_id_as_alias<'s>(program: &'s Program<'s>) -> Vec<ValidationError> {
let mut validator = DisallowIdAsAlias::new(program);
match validator.validate_program(program) {
Err(e) => e,
Ok(_) => Default::default(),
}
}
struct DisallowIdAsAlias<'s> {
program: &'s Program<'s>,
id_key: StringKey,
}
impl<'s> DisallowIdAsAlias<'s> {
fn new(program: &'s Program<'s>) -> Self {
Self {
program,
id_key: "id".intern(),
}
}
}
impl<'s> Validator for DisallowIdAsAlias<'s> {
const NAME: &'static str = "DisallowIdAsAlias";
const VALIDATE_ARGUMENTS: bool = false;
const VALIDATE_DIRECTIVES: bool = false;
fn validate_linked_field(&mut self, field: &LinkedField) -> Result<(), Vec<ValidationError>> {
if let Some(alias) = field.alias {
try2(
validate_field_alias(
self.program.schema(),
self.id_key,
&alias,
field.definition.item,
),
self.validate_selections(&field.selections),
)?;
Ok(())
} else {
self.validate_selections(&field.selections)
}
}
fn validate_scalar_field(&mut self, field: &ScalarField) -> Result<(), Vec<ValidationError>> {
if let Some(alias) = field.alias {
validate_field_alias(
self.program.schema(),
self.id_key,
&alias,
field.definition.item,
)
} else {
Ok(())
}
}
}
fn validate_field_alias<'s>(
schema: &'s Schema,
id_key: StringKey,
alias: &WithLocation<StringKey>,
field: FieldID,
) -> Result<(), Vec<ValidationError>> {
if alias.item == id_key && schema.field(field).name != id_key | else {
Ok(())
}
}
| {
Err(vec![ValidationError::new(
ValidationMessage::DisallowIdAsAliasError(),
vec![alias.location],
)])
} | conditional_block |
disallow_id_as_alias.rs | /*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
use common::WithLocation;
use errors::try2;
use graphql_ir::{
LinkedField, Program, ScalarField, ValidationError, ValidationMessage, Validator,
};
use interner::{Intern, StringKey};
use schema::{FieldID, Schema};
pub fn disallow_id_as_alias<'s>(program: &'s Program<'s>) -> Vec<ValidationError> {
let mut validator = DisallowIdAsAlias::new(program);
match validator.validate_program(program) {
Err(e) => e,
Ok(_) => Default::default(),
}
}
struct DisallowIdAsAlias<'s> {
program: &'s Program<'s>,
id_key: StringKey,
}
impl<'s> DisallowIdAsAlias<'s> {
fn new(program: &'s Program<'s>) -> Self {
Self {
program,
id_key: "id".intern(),
}
}
}
impl<'s> Validator for DisallowIdAsAlias<'s> {
const NAME: &'static str = "DisallowIdAsAlias";
const VALIDATE_ARGUMENTS: bool = false;
const VALIDATE_DIRECTIVES: bool = false;
fn validate_linked_field(&mut self, field: &LinkedField) -> Result<(), Vec<ValidationError>> {
if let Some(alias) = field.alias {
try2(
validate_field_alias(
self.program.schema(),
self.id_key,
&alias,
field.definition.item,
),
self.validate_selections(&field.selections),
)?;
Ok(())
} else {
self.validate_selections(&field.selections)
}
}
fn validate_scalar_field(&mut self, field: &ScalarField) -> Result<(), Vec<ValidationError>> {
if let Some(alias) = field.alias {
validate_field_alias(
self.program.schema(),
self.id_key,
&alias,
field.definition.item,
)
} else {
Ok(())
}
}
}
fn validate_field_alias<'s>(
schema: &'s Schema,
id_key: StringKey,
alias: &WithLocation<StringKey>,
field: FieldID,
) -> Result<(), Vec<ValidationError>> | {
if alias.item == id_key && schema.field(field).name != id_key {
Err(vec![ValidationError::new(
ValidationMessage::DisallowIdAsAliasError(),
vec![alias.location],
)])
} else {
Ok(())
}
} | identifier_body | |
disallow_id_as_alias.rs | /*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
use common::WithLocation;
use errors::try2;
use graphql_ir::{
LinkedField, Program, ScalarField, ValidationError, ValidationMessage, Validator,
};
use interner::{Intern, StringKey};
use schema::{FieldID, Schema};
pub fn | <'s>(program: &'s Program<'s>) -> Vec<ValidationError> {
let mut validator = DisallowIdAsAlias::new(program);
match validator.validate_program(program) {
Err(e) => e,
Ok(_) => Default::default(),
}
}
struct DisallowIdAsAlias<'s> {
program: &'s Program<'s>,
id_key: StringKey,
}
impl<'s> DisallowIdAsAlias<'s> {
fn new(program: &'s Program<'s>) -> Self {
Self {
program,
id_key: "id".intern(),
}
}
}
impl<'s> Validator for DisallowIdAsAlias<'s> {
const NAME: &'static str = "DisallowIdAsAlias";
const VALIDATE_ARGUMENTS: bool = false;
const VALIDATE_DIRECTIVES: bool = false;
fn validate_linked_field(&mut self, field: &LinkedField) -> Result<(), Vec<ValidationError>> {
if let Some(alias) = field.alias {
try2(
validate_field_alias(
self.program.schema(),
self.id_key,
&alias,
field.definition.item,
),
self.validate_selections(&field.selections),
)?;
Ok(())
} else {
self.validate_selections(&field.selections)
}
}
fn validate_scalar_field(&mut self, field: &ScalarField) -> Result<(), Vec<ValidationError>> {
if let Some(alias) = field.alias {
validate_field_alias(
self.program.schema(),
self.id_key,
&alias,
field.definition.item,
)
} else {
Ok(())
}
}
}
fn validate_field_alias<'s>(
schema: &'s Schema,
id_key: StringKey,
alias: &WithLocation<StringKey>,
field: FieldID,
) -> Result<(), Vec<ValidationError>> {
if alias.item == id_key && schema.field(field).name != id_key {
Err(vec![ValidationError::new(
ValidationMessage::DisallowIdAsAliasError(),
vec![alias.location],
)])
} else {
Ok(())
}
}
| disallow_id_as_alias | identifier_name |
backend.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
import re
import string
from urlparse import urlparse, parse_qs
from mopidy import backend
from mopidy.models import SearchResult, Track, Album, Artist
import pykka
import pafy
import requests
import unicodedata
from mopidy_youtube import logger
yt_api_endpoint = 'https://www.googleapis.com/youtube/v3/'
yt_key = 'AIzaSyAl1Xq9DwdE_KD4AtPaE4EJl3WZe2zCqg4'
def resolve_track(track, stream=False):
logger.debug("Resolving Youtube for track '%s'", track)
if hasattr(track, 'uri'):
return resolve_url(track.comment, stream)
else:
return resolve_url(track.split('.')[-1], stream)
def safe_url(uri):
valid_chars = "-_.() %s%s" % (string.ascii_letters, string.digits)
safe_uri = unicodedata.normalize(
'NFKD',
unicode(uri)
).encode('ASCII', 'ignore')
return re.sub(
'\s+',
' ',
''.join(c for c in safe_uri if c in valid_chars)
).strip()
def resolve_url(url, stream=False):
video = pafy.new(url)
if not stream:
uri = 'youtube:video/%s.%s' % (
safe_url(video.title), video.videoid
)
else:
uri = video.getbestaudio()
if not uri: # get video url
uri = video.getbest()
logger.debug('%s - %s %s %s' % (
video.title, uri.bitrate, uri.mediatype, uri.extension))
uri = uri.url
if not uri:
return
if '-' in video.title:
title = video.title.split('-')
track = Track(
name=title[1].strip(),
comment=video.videoid,
length=video.length*1000,
artists=[Artist(name=title[0].strip())],
album=Album(
name='Youtube',
images=[video.bigthumb, video.bigthumbhd]
),
uri=uri
)
else:
track = Track(
name=video.title,
comment=video.videoid,
length=video.length*1000,
album=Album(
name='Youtube',
images=[video.bigthumb, video.bigthumbhd]
),
uri=uri
)
return track
def search_youtube(q):
|
def resolve_playlist(url):
logger.info("Resolving Youtube for playlist '%s'", url)
query = {
'part': 'snippet',
'maxResults': 50,
'playlistId': url,
'fields': 'items/snippet/resourceId',
'key': yt_key
}
pl = requests.get(yt_api_endpoint+'playlistItem', params=query)
playlist = []
for yt_id in pl.json().get('items'):
try:
yt_id = yt_id.get('snippet').get('resourceId').get('videoId')
playlist.append(resolve_url(yt_id))
except Exception as e:
logger.info(e.message)
return playlist
class YoutubeBackend(pykka.ThreadingActor, backend.Backend):
def __init__(self, config, audio):
super(YoutubeBackend, self).__init__()
self.config = config
self.library = YoutubeLibraryProvider(backend=self)
self.playback = YoutubePlaybackProvider(audio=audio, backend=self)
self.uri_schemes = ['youtube', 'yt']
class YoutubeLibraryProvider(backend.LibraryProvider):
def lookup(self, track):
if 'yt:' in track:
track = track.replace('yt:', '')
if 'youtube.com' in track:
url = urlparse(track)
req = parse_qs(url.query)
if 'list' in req:
return resolve_playlist(req.get('list')[0])
else:
return [resolve_url(track)]
else:
return [resolve_url(track)]
def search(self, query=None, uris=None):
if not query:
return
if 'uri' in query:
search_query = ''.join(query['uri'])
url = urlparse(search_query)
if 'youtube.com' in url.netloc:
req = parse_qs(url.query)
if 'list' in req:
return SearchResult(
uri='youtube:search',
tracks=resolve_playlist(req.get('list')[0])
)
else:
logger.info(
"Resolving Youtube for track '%s'", search_query)
return SearchResult(
uri='youtube:search',
tracks=[resolve_url(search_query)]
)
else:
search_query = '|'.join(query.values()[0])
logger.info("Searching Youtube for query '%s'", search_query)
return SearchResult(
uri='youtube:search',
tracks=search_youtube(search_query)
)
class YoutubePlaybackProvider(backend.PlaybackProvider):
def play(self, track):
track = resolve_track(track, True)
return super(YoutubePlaybackProvider, self).play(track)
| query = {
'part': 'id',
'maxResults': 15,
'type': 'video',
'q': q,
'key': yt_key
}
pl = requests.get(yt_api_endpoint+'search', params=query)
playlist = []
for yt_id in pl.json().get('items'):
try:
track = resolve_url(yt_id.get('id').get('videoId'))
playlist.append(track)
except Exception as e:
logger.info(e.message)
return playlist | identifier_body |
backend.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
import re
import string
from urlparse import urlparse, parse_qs
from mopidy import backend
from mopidy.models import SearchResult, Track, Album, Artist
import pykka
import pafy
import requests
import unicodedata
from mopidy_youtube import logger
yt_api_endpoint = 'https://www.googleapis.com/youtube/v3/'
yt_key = 'AIzaSyAl1Xq9DwdE_KD4AtPaE4EJl3WZe2zCqg4'
def resolve_track(track, stream=False):
logger.debug("Resolving Youtube for track '%s'", track)
if hasattr(track, 'uri'):
return resolve_url(track.comment, stream)
else:
return resolve_url(track.split('.')[-1], stream)
def safe_url(uri):
valid_chars = "-_.() %s%s" % (string.ascii_letters, string.digits)
safe_uri = unicodedata.normalize(
'NFKD',
unicode(uri)
).encode('ASCII', 'ignore')
return re.sub(
'\s+',
' ',
''.join(c for c in safe_uri if c in valid_chars)
).strip()
def resolve_url(url, stream=False):
video = pafy.new(url)
if not stream:
uri = 'youtube:video/%s.%s' % (
safe_url(video.title), video.videoid
)
else:
uri = video.getbestaudio()
if not uri: # get video url
uri = video.getbest()
logger.debug('%s - %s %s %s' % (
video.title, uri.bitrate, uri.mediatype, uri.extension))
uri = uri.url
if not uri:
return
if '-' in video.title:
title = video.title.split('-')
track = Track(
name=title[1].strip(),
comment=video.videoid,
length=video.length*1000,
artists=[Artist(name=title[0].strip())],
album=Album(
name='Youtube',
images=[video.bigthumb, video.bigthumbhd]
),
uri=uri
)
else:
track = Track(
name=video.title, | comment=video.videoid,
length=video.length*1000,
album=Album(
name='Youtube',
images=[video.bigthumb, video.bigthumbhd]
),
uri=uri
)
return track
def search_youtube(q):
query = {
'part': 'id',
'maxResults': 15,
'type': 'video',
'q': q,
'key': yt_key
}
pl = requests.get(yt_api_endpoint+'search', params=query)
playlist = []
for yt_id in pl.json().get('items'):
try:
track = resolve_url(yt_id.get('id').get('videoId'))
playlist.append(track)
except Exception as e:
logger.info(e.message)
return playlist
def resolve_playlist(url):
logger.info("Resolving Youtube for playlist '%s'", url)
query = {
'part': 'snippet',
'maxResults': 50,
'playlistId': url,
'fields': 'items/snippet/resourceId',
'key': yt_key
}
pl = requests.get(yt_api_endpoint+'playlistItem', params=query)
playlist = []
for yt_id in pl.json().get('items'):
try:
yt_id = yt_id.get('snippet').get('resourceId').get('videoId')
playlist.append(resolve_url(yt_id))
except Exception as e:
logger.info(e.message)
return playlist
class YoutubeBackend(pykka.ThreadingActor, backend.Backend):
def __init__(self, config, audio):
super(YoutubeBackend, self).__init__()
self.config = config
self.library = YoutubeLibraryProvider(backend=self)
self.playback = YoutubePlaybackProvider(audio=audio, backend=self)
self.uri_schemes = ['youtube', 'yt']
class YoutubeLibraryProvider(backend.LibraryProvider):
def lookup(self, track):
if 'yt:' in track:
track = track.replace('yt:', '')
if 'youtube.com' in track:
url = urlparse(track)
req = parse_qs(url.query)
if 'list' in req:
return resolve_playlist(req.get('list')[0])
else:
return [resolve_url(track)]
else:
return [resolve_url(track)]
def search(self, query=None, uris=None):
if not query:
return
if 'uri' in query:
search_query = ''.join(query['uri'])
url = urlparse(search_query)
if 'youtube.com' in url.netloc:
req = parse_qs(url.query)
if 'list' in req:
return SearchResult(
uri='youtube:search',
tracks=resolve_playlist(req.get('list')[0])
)
else:
logger.info(
"Resolving Youtube for track '%s'", search_query)
return SearchResult(
uri='youtube:search',
tracks=[resolve_url(search_query)]
)
else:
search_query = '|'.join(query.values()[0])
logger.info("Searching Youtube for query '%s'", search_query)
return SearchResult(
uri='youtube:search',
tracks=search_youtube(search_query)
)
class YoutubePlaybackProvider(backend.PlaybackProvider):
def play(self, track):
track = resolve_track(track, True)
return super(YoutubePlaybackProvider, self).play(track) | random_line_split | |
backend.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
import re
import string
from urlparse import urlparse, parse_qs
from mopidy import backend
from mopidy.models import SearchResult, Track, Album, Artist
import pykka
import pafy
import requests
import unicodedata
from mopidy_youtube import logger
yt_api_endpoint = 'https://www.googleapis.com/youtube/v3/'
yt_key = 'AIzaSyAl1Xq9DwdE_KD4AtPaE4EJl3WZe2zCqg4'
def resolve_track(track, stream=False):
logger.debug("Resolving Youtube for track '%s'", track)
if hasattr(track, 'uri'):
return resolve_url(track.comment, stream)
else:
return resolve_url(track.split('.')[-1], stream)
def | (uri):
valid_chars = "-_.() %s%s" % (string.ascii_letters, string.digits)
safe_uri = unicodedata.normalize(
'NFKD',
unicode(uri)
).encode('ASCII', 'ignore')
return re.sub(
'\s+',
' ',
''.join(c for c in safe_uri if c in valid_chars)
).strip()
def resolve_url(url, stream=False):
video = pafy.new(url)
if not stream:
uri = 'youtube:video/%s.%s' % (
safe_url(video.title), video.videoid
)
else:
uri = video.getbestaudio()
if not uri: # get video url
uri = video.getbest()
logger.debug('%s - %s %s %s' % (
video.title, uri.bitrate, uri.mediatype, uri.extension))
uri = uri.url
if not uri:
return
if '-' in video.title:
title = video.title.split('-')
track = Track(
name=title[1].strip(),
comment=video.videoid,
length=video.length*1000,
artists=[Artist(name=title[0].strip())],
album=Album(
name='Youtube',
images=[video.bigthumb, video.bigthumbhd]
),
uri=uri
)
else:
track = Track(
name=video.title,
comment=video.videoid,
length=video.length*1000,
album=Album(
name='Youtube',
images=[video.bigthumb, video.bigthumbhd]
),
uri=uri
)
return track
def search_youtube(q):
query = {
'part': 'id',
'maxResults': 15,
'type': 'video',
'q': q,
'key': yt_key
}
pl = requests.get(yt_api_endpoint+'search', params=query)
playlist = []
for yt_id in pl.json().get('items'):
try:
track = resolve_url(yt_id.get('id').get('videoId'))
playlist.append(track)
except Exception as e:
logger.info(e.message)
return playlist
def resolve_playlist(url):
logger.info("Resolving Youtube for playlist '%s'", url)
query = {
'part': 'snippet',
'maxResults': 50,
'playlistId': url,
'fields': 'items/snippet/resourceId',
'key': yt_key
}
pl = requests.get(yt_api_endpoint+'playlistItem', params=query)
playlist = []
for yt_id in pl.json().get('items'):
try:
yt_id = yt_id.get('snippet').get('resourceId').get('videoId')
playlist.append(resolve_url(yt_id))
except Exception as e:
logger.info(e.message)
return playlist
class YoutubeBackend(pykka.ThreadingActor, backend.Backend):
def __init__(self, config, audio):
super(YoutubeBackend, self).__init__()
self.config = config
self.library = YoutubeLibraryProvider(backend=self)
self.playback = YoutubePlaybackProvider(audio=audio, backend=self)
self.uri_schemes = ['youtube', 'yt']
class YoutubeLibraryProvider(backend.LibraryProvider):
def lookup(self, track):
if 'yt:' in track:
track = track.replace('yt:', '')
if 'youtube.com' in track:
url = urlparse(track)
req = parse_qs(url.query)
if 'list' in req:
return resolve_playlist(req.get('list')[0])
else:
return [resolve_url(track)]
else:
return [resolve_url(track)]
def search(self, query=None, uris=None):
if not query:
return
if 'uri' in query:
search_query = ''.join(query['uri'])
url = urlparse(search_query)
if 'youtube.com' in url.netloc:
req = parse_qs(url.query)
if 'list' in req:
return SearchResult(
uri='youtube:search',
tracks=resolve_playlist(req.get('list')[0])
)
else:
logger.info(
"Resolving Youtube for track '%s'", search_query)
return SearchResult(
uri='youtube:search',
tracks=[resolve_url(search_query)]
)
else:
search_query = '|'.join(query.values()[0])
logger.info("Searching Youtube for query '%s'", search_query)
return SearchResult(
uri='youtube:search',
tracks=search_youtube(search_query)
)
class YoutubePlaybackProvider(backend.PlaybackProvider):
def play(self, track):
track = resolve_track(track, True)
return super(YoutubePlaybackProvider, self).play(track)
| safe_url | identifier_name |
backend.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
import re
import string
from urlparse import urlparse, parse_qs
from mopidy import backend
from mopidy.models import SearchResult, Track, Album, Artist
import pykka
import pafy
import requests
import unicodedata
from mopidy_youtube import logger
yt_api_endpoint = 'https://www.googleapis.com/youtube/v3/'
yt_key = 'AIzaSyAl1Xq9DwdE_KD4AtPaE4EJl3WZe2zCqg4'
def resolve_track(track, stream=False):
logger.debug("Resolving Youtube for track '%s'", track)
if hasattr(track, 'uri'):
return resolve_url(track.comment, stream)
else:
return resolve_url(track.split('.')[-1], stream)
def safe_url(uri):
valid_chars = "-_.() %s%s" % (string.ascii_letters, string.digits)
safe_uri = unicodedata.normalize(
'NFKD',
unicode(uri)
).encode('ASCII', 'ignore')
return re.sub(
'\s+',
' ',
''.join(c for c in safe_uri if c in valid_chars)
).strip()
def resolve_url(url, stream=False):
video = pafy.new(url)
if not stream:
uri = 'youtube:video/%s.%s' % (
safe_url(video.title), video.videoid
)
else:
uri = video.getbestaudio()
if not uri: # get video url
|
logger.debug('%s - %s %s %s' % (
video.title, uri.bitrate, uri.mediatype, uri.extension))
uri = uri.url
if not uri:
return
if '-' in video.title:
title = video.title.split('-')
track = Track(
name=title[1].strip(),
comment=video.videoid,
length=video.length*1000,
artists=[Artist(name=title[0].strip())],
album=Album(
name='Youtube',
images=[video.bigthumb, video.bigthumbhd]
),
uri=uri
)
else:
track = Track(
name=video.title,
comment=video.videoid,
length=video.length*1000,
album=Album(
name='Youtube',
images=[video.bigthumb, video.bigthumbhd]
),
uri=uri
)
return track
def search_youtube(q):
query = {
'part': 'id',
'maxResults': 15,
'type': 'video',
'q': q,
'key': yt_key
}
pl = requests.get(yt_api_endpoint+'search', params=query)
playlist = []
for yt_id in pl.json().get('items'):
try:
track = resolve_url(yt_id.get('id').get('videoId'))
playlist.append(track)
except Exception as e:
logger.info(e.message)
return playlist
def resolve_playlist(url):
logger.info("Resolving Youtube for playlist '%s'", url)
query = {
'part': 'snippet',
'maxResults': 50,
'playlistId': url,
'fields': 'items/snippet/resourceId',
'key': yt_key
}
pl = requests.get(yt_api_endpoint+'playlistItem', params=query)
playlist = []
for yt_id in pl.json().get('items'):
try:
yt_id = yt_id.get('snippet').get('resourceId').get('videoId')
playlist.append(resolve_url(yt_id))
except Exception as e:
logger.info(e.message)
return playlist
class YoutubeBackend(pykka.ThreadingActor, backend.Backend):
def __init__(self, config, audio):
super(YoutubeBackend, self).__init__()
self.config = config
self.library = YoutubeLibraryProvider(backend=self)
self.playback = YoutubePlaybackProvider(audio=audio, backend=self)
self.uri_schemes = ['youtube', 'yt']
class YoutubeLibraryProvider(backend.LibraryProvider):
def lookup(self, track):
if 'yt:' in track:
track = track.replace('yt:', '')
if 'youtube.com' in track:
url = urlparse(track)
req = parse_qs(url.query)
if 'list' in req:
return resolve_playlist(req.get('list')[0])
else:
return [resolve_url(track)]
else:
return [resolve_url(track)]
def search(self, query=None, uris=None):
if not query:
return
if 'uri' in query:
search_query = ''.join(query['uri'])
url = urlparse(search_query)
if 'youtube.com' in url.netloc:
req = parse_qs(url.query)
if 'list' in req:
return SearchResult(
uri='youtube:search',
tracks=resolve_playlist(req.get('list')[0])
)
else:
logger.info(
"Resolving Youtube for track '%s'", search_query)
return SearchResult(
uri='youtube:search',
tracks=[resolve_url(search_query)]
)
else:
search_query = '|'.join(query.values()[0])
logger.info("Searching Youtube for query '%s'", search_query)
return SearchResult(
uri='youtube:search',
tracks=search_youtube(search_query)
)
class YoutubePlaybackProvider(backend.PlaybackProvider):
def play(self, track):
track = resolve_track(track, True)
return super(YoutubePlaybackProvider, self).play(track)
| uri = video.getbest() | conditional_block |
tinyurl.py | from ..base import BaseShortener
from ..exceptions import ShorteningErrorException
class Shortener(BaseShortener):
"""
TinyURL.com shortener implementation
Example:
>>> import pyshorteners
>>> s = pyshorteners.Shortener()
>>> s.tinyurl.short('http://www.google.com')
'http://tinyurl.com/TEST'
>>> s.tinyurl.expand('http://tinyurl.com/test')
'http://www.google.com'
"""
api_url = "http://tinyurl.com/api-create.php"
def short(self, url):
"""Short implementation for TinyURL.com
Args:
url: the URL you want to shorten
Returns:
A string containing the shortened URL
Raises:
ShorteningErrorException: If the API returns an error as response
"""
url = self.clean_url(url)
response = self._get(self.api_url, params=dict(url=url))
if response.ok:
|
raise ShorteningErrorException(response.content)
| return response.text.strip() | conditional_block |
tinyurl.py | from ..base import BaseShortener
from ..exceptions import ShorteningErrorException
class | (BaseShortener):
"""
TinyURL.com shortener implementation
Example:
>>> import pyshorteners
>>> s = pyshorteners.Shortener()
>>> s.tinyurl.short('http://www.google.com')
'http://tinyurl.com/TEST'
>>> s.tinyurl.expand('http://tinyurl.com/test')
'http://www.google.com'
"""
api_url = "http://tinyurl.com/api-create.php"
def short(self, url):
"""Short implementation for TinyURL.com
Args:
url: the URL you want to shorten
Returns:
A string containing the shortened URL
Raises:
ShorteningErrorException: If the API returns an error as response
"""
url = self.clean_url(url)
response = self._get(self.api_url, params=dict(url=url))
if response.ok:
return response.text.strip()
raise ShorteningErrorException(response.content)
| Shortener | identifier_name |
tinyurl.py | from ..base import BaseShortener
from ..exceptions import ShorteningErrorException
class Shortener(BaseShortener):
"""
TinyURL.com shortener implementation
Example:
>>> import pyshorteners
>>> s = pyshorteners.Shortener()
>>> s.tinyurl.short('http://www.google.com')
'http://tinyurl.com/TEST'
>>> s.tinyurl.expand('http://tinyurl.com/test')
'http://www.google.com'
"""
api_url = "http://tinyurl.com/api-create.php"
def short(self, url):
"""Short implementation for TinyURL.com
Args:
url: the URL you want to shorten
Returns:
A string containing the shortened URL
Raises:
ShorteningErrorException: If the API returns an error as response
"""
url = self.clean_url(url)
response = self._get(self.api_url, params=dict(url=url))
if response.ok: | return response.text.strip()
raise ShorteningErrorException(response.content) | random_line_split | |
tinyurl.py | from ..base import BaseShortener
from ..exceptions import ShorteningErrorException
class Shortener(BaseShortener):
"""
TinyURL.com shortener implementation
Example:
>>> import pyshorteners
>>> s = pyshorteners.Shortener()
>>> s.tinyurl.short('http://www.google.com')
'http://tinyurl.com/TEST'
>>> s.tinyurl.expand('http://tinyurl.com/test')
'http://www.google.com'
"""
api_url = "http://tinyurl.com/api-create.php"
def short(self, url):
| """Short implementation for TinyURL.com
Args:
url: the URL you want to shorten
Returns:
A string containing the shortened URL
Raises:
ShorteningErrorException: If the API returns an error as response
"""
url = self.clean_url(url)
response = self._get(self.api_url, params=dict(url=url))
if response.ok:
return response.text.strip()
raise ShorteningErrorException(response.content) | identifier_body | |
HorizontalRule.js | dojo.provide("dijit.form.HorizontalRule");
dojo.require("dijit._Widget");
dojo.require("dijit._Templated");
dojo.declare("dijit.form.HorizontalRule", [dijit._Widget, dijit._Templated],
{
// summary:
// Hash marks for `dijit.form.HorizontalSlider`
templateString: '<div class="dijitRuleContainer dijitRuleContainerH"></div>',
// count: Integer
// Number of hash marks to generate
count: 3,
// container: String
// For HorizontalSlider, this is either "topDecoration" or "bottomDecoration",
// and indicates whether this rule goes above or below the slider.
container: "containerNode",
// ruleStyle: String
// CSS style to apply to individual hash marks
ruleStyle: "",
_positionPrefix: '<div class="dijitRuleMark dijitRuleMarkH" style="left:',
_positionSuffix: '%;',
_suffix: '"></div>',
_genHTML: function(pos, ndx){
return this._positionPrefix + pos + this._positionSuffix + this.ruleStyle + this._suffix;
},
// _isHorizontal: [protected extension] Boolean
// VerticalRule will override this...
_isHorizontal: true,
postCreate: function(){
var innerHTML;
if(this.count==1) | else{
var i;
var interval = 100 / (this.count-1);
if(!this._isHorizontal || this.isLeftToRight()){
innerHTML = this._genHTML(0, 0);
for(i=1; i < this.count-1; i++){
innerHTML += this._genHTML(interval*i, i);
}
innerHTML += this._genHTML(100, this.count-1);
}else{
innerHTML = this._genHTML(100, 0);
for(i=1; i < this.count-1; i++){
innerHTML += this._genHTML(100-interval*i, i);
}
innerHTML += this._genHTML(0, this.count-1);
}
}
this.domNode.innerHTML = innerHTML;
}
});
| {
innerHTML = this._genHTML(50, 0);
} | conditional_block |
HorizontalRule.js | dojo.provide("dijit.form.HorizontalRule");
dojo.require("dijit._Widget");
dojo.require("dijit._Templated");
dojo.declare("dijit.form.HorizontalRule", [dijit._Widget, dijit._Templated],
{
// summary:
// Hash marks for `dijit.form.HorizontalSlider`
templateString: '<div class="dijitRuleContainer dijitRuleContainerH"></div>',
// count: Integer
// Number of hash marks to generate
count: 3,
// container: String
// For HorizontalSlider, this is either "topDecoration" or "bottomDecoration",
// and indicates whether this rule goes above or below the slider.
container: "containerNode",
// ruleStyle: String
// CSS style to apply to individual hash marks
ruleStyle: "",
_positionPrefix: '<div class="dijitRuleMark dijitRuleMarkH" style="left:',
_positionSuffix: '%;',
_suffix: '"></div>',
_genHTML: function(pos, ndx){
return this._positionPrefix + pos + this._positionSuffix + this.ruleStyle + this._suffix;
},
// _isHorizontal: [protected extension] Boolean
// VerticalRule will override this...
_isHorizontal: true, |
postCreate: function(){
var innerHTML;
if(this.count==1){
innerHTML = this._genHTML(50, 0);
}else{
var i;
var interval = 100 / (this.count-1);
if(!this._isHorizontal || this.isLeftToRight()){
innerHTML = this._genHTML(0, 0);
for(i=1; i < this.count-1; i++){
innerHTML += this._genHTML(interval*i, i);
}
innerHTML += this._genHTML(100, this.count-1);
}else{
innerHTML = this._genHTML(100, 0);
for(i=1; i < this.count-1; i++){
innerHTML += this._genHTML(100-interval*i, i);
}
innerHTML += this._genHTML(0, this.count-1);
}
}
this.domNode.innerHTML = innerHTML;
}
}); | random_line_split | |
borrowck-loan-in-overloaded-op.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
struct foo(~uint);
impl Add<foo, foo> for foo {
fn add(&self, f: &foo) -> foo {
let foo(~i) = *self;
let foo(~j) = *f;
foo(~(i + j))
}
}
fn | () {
let x = foo(~3);
let _y = x + {x}; // the `{x}` forces a move to occur
//~^ ERROR cannot move out of `x`
}
| main | identifier_name |
borrowck-loan-in-overloaded-op.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
struct foo(~uint);
impl Add<foo, foo> for foo {
fn add(&self, f: &foo) -> foo |
}
fn main() {
let x = foo(~3);
let _y = x + {x}; // the `{x}` forces a move to occur
//~^ ERROR cannot move out of `x`
}
| {
let foo(~i) = *self;
let foo(~j) = *f;
foo(~(i + j))
} | identifier_body |
borrowck-loan-in-overloaded-op.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms. |
impl Add<foo, foo> for foo {
fn add(&self, f: &foo) -> foo {
let foo(~i) = *self;
let foo(~j) = *f;
foo(~(i + j))
}
}
fn main() {
let x = foo(~3);
let _y = x + {x}; // the `{x}` forces a move to occur
//~^ ERROR cannot move out of `x`
} |
struct foo(~uint); | random_line_split |
templates.js | "use strict";
var __extends = (this && this.__extends) || function (d, b) {
for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
var Handlebars = require("handlebars");
var fs_1 = require("../../../utils/fs");
var stack_1 = require("./stack");
var Template = (function (_super) {
__extends(Template, _super);
function Template() {
return _super.apply(this, arguments) || this;
}
Template.prototype.getTemplate = function () {
if (!this.template) {
var raw = fs_1.readFile(this.fileName);
this.template = Handlebars.compile(raw, {
preventIndent: true
});
}
return this.template;
};
Template.prototype.render = function (context, options) {
var template = this.getTemplate();
return template(context, options);
};
return Template;
}(stack_1.Resource));
exports.Template = Template; | __extends(TemplateStack, _super);
function TemplateStack() {
return _super.call(this, Template, /\.hbs$/) || this;
}
return TemplateStack;
}(stack_1.ResourceStack));
exports.TemplateStack = TemplateStack;
var PartialStack = (function (_super) {
__extends(PartialStack, _super);
function PartialStack() {
var _this = _super.apply(this, arguments) || this;
_this.registeredNames = [];
return _this;
}
PartialStack.prototype.activate = function () {
if (!_super.prototype.activate.call(this))
return false;
var resources = this.getAllResources();
for (var name in resources) {
if (this.registeredNames.indexOf(name) !== -1)
continue;
this.registeredNames.push(name);
var partial = resources[name];
var template = partial.getTemplate();
Handlebars.registerPartial(name, template);
}
return true;
};
PartialStack.prototype.deactivate = function () {
if (!_super.prototype.deactivate.call(this))
return false;
for (var _i = 0, _a = this.registeredNames; _i < _a.length; _i++) {
var name = _a[_i];
Handlebars.unregisterPartial(name);
}
this.registeredNames = [];
return true;
};
return PartialStack;
}(TemplateStack));
exports.PartialStack = PartialStack;
//# sourceMappingURL=templates.js.map | var TemplateStack = (function (_super) { | random_line_split |
templates.js | "use strict";
var __extends = (this && this.__extends) || function (d, b) {
for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
function | () { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
var Handlebars = require("handlebars");
var fs_1 = require("../../../utils/fs");
var stack_1 = require("./stack");
var Template = (function (_super) {
__extends(Template, _super);
function Template() {
return _super.apply(this, arguments) || this;
}
Template.prototype.getTemplate = function () {
if (!this.template) {
var raw = fs_1.readFile(this.fileName);
this.template = Handlebars.compile(raw, {
preventIndent: true
});
}
return this.template;
};
Template.prototype.render = function (context, options) {
var template = this.getTemplate();
return template(context, options);
};
return Template;
}(stack_1.Resource));
exports.Template = Template;
var TemplateStack = (function (_super) {
__extends(TemplateStack, _super);
function TemplateStack() {
return _super.call(this, Template, /\.hbs$/) || this;
}
return TemplateStack;
}(stack_1.ResourceStack));
exports.TemplateStack = TemplateStack;
var PartialStack = (function (_super) {
__extends(PartialStack, _super);
function PartialStack() {
var _this = _super.apply(this, arguments) || this;
_this.registeredNames = [];
return _this;
}
PartialStack.prototype.activate = function () {
if (!_super.prototype.activate.call(this))
return false;
var resources = this.getAllResources();
for (var name in resources) {
if (this.registeredNames.indexOf(name) !== -1)
continue;
this.registeredNames.push(name);
var partial = resources[name];
var template = partial.getTemplate();
Handlebars.registerPartial(name, template);
}
return true;
};
PartialStack.prototype.deactivate = function () {
if (!_super.prototype.deactivate.call(this))
return false;
for (var _i = 0, _a = this.registeredNames; _i < _a.length; _i++) {
var name = _a[_i];
Handlebars.unregisterPartial(name);
}
this.registeredNames = [];
return true;
};
return PartialStack;
}(TemplateStack));
exports.PartialStack = PartialStack;
//# sourceMappingURL=templates.js.map | __ | identifier_name |
templates.js | "use strict";
var __extends = (this && this.__extends) || function (d, b) {
for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
var Handlebars = require("handlebars");
var fs_1 = require("../../../utils/fs");
var stack_1 = require("./stack");
var Template = (function (_super) {
__extends(Template, _super);
function Template() {
return _super.apply(this, arguments) || this;
}
Template.prototype.getTemplate = function () {
if (!this.template) {
var raw = fs_1.readFile(this.fileName);
this.template = Handlebars.compile(raw, {
preventIndent: true
});
}
return this.template;
};
Template.prototype.render = function (context, options) {
var template = this.getTemplate();
return template(context, options);
};
return Template;
}(stack_1.Resource));
exports.Template = Template;
var TemplateStack = (function (_super) {
__extends(TemplateStack, _super);
function TemplateStack() {
return _super.call(this, Template, /\.hbs$/) || this;
}
return TemplateStack;
}(stack_1.ResourceStack));
exports.TemplateStack = TemplateStack;
var PartialStack = (function (_super) {
__extends(PartialStack, _super);
function PartialStack() {
var _this = _super.apply(this, arguments) || this;
_this.registeredNames = [];
return _this;
}
PartialStack.prototype.activate = function () {
if (!_super.prototype.activate.call(this))
return false;
var resources = this.getAllResources();
for (var name in resources) {
if (this.registeredNames.indexOf(name) !== -1)
continue;
this.registeredNames.push(name);
var partial = resources[name];
var template = partial.getTemplate();
Handlebars.registerPartial(name, template);
}
return true;
};
PartialStack.prototype.deactivate = function () {
if (!_super.prototype.deactivate.call(this))
return false;
for (var _i = 0, _a = this.registeredNames; _i < _a.length; _i++) |
this.registeredNames = [];
return true;
};
return PartialStack;
}(TemplateStack));
exports.PartialStack = PartialStack;
//# sourceMappingURL=templates.js.map | {
var name = _a[_i];
Handlebars.unregisterPartial(name);
} | conditional_block |
templates.js | "use strict";
var __extends = (this && this.__extends) || function (d, b) {
for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
var Handlebars = require("handlebars");
var fs_1 = require("../../../utils/fs");
var stack_1 = require("./stack");
var Template = (function (_super) {
__extends(Template, _super);
function Template() {
return _super.apply(this, arguments) || this;
}
Template.prototype.getTemplate = function () {
if (!this.template) {
var raw = fs_1.readFile(this.fileName);
this.template = Handlebars.compile(raw, {
preventIndent: true
});
}
return this.template;
};
Template.prototype.render = function (context, options) {
var template = this.getTemplate();
return template(context, options);
};
return Template;
}(stack_1.Resource));
exports.Template = Template;
var TemplateStack = (function (_super) {
__extends(TemplateStack, _super);
function TemplateStack() {
return _super.call(this, Template, /\.hbs$/) || this;
}
return TemplateStack;
}(stack_1.ResourceStack));
exports.TemplateStack = TemplateStack;
var PartialStack = (function (_super) {
__extends(PartialStack, _super);
function PartialStack() |
PartialStack.prototype.activate = function () {
if (!_super.prototype.activate.call(this))
return false;
var resources = this.getAllResources();
for (var name in resources) {
if (this.registeredNames.indexOf(name) !== -1)
continue;
this.registeredNames.push(name);
var partial = resources[name];
var template = partial.getTemplate();
Handlebars.registerPartial(name, template);
}
return true;
};
PartialStack.prototype.deactivate = function () {
if (!_super.prototype.deactivate.call(this))
return false;
for (var _i = 0, _a = this.registeredNames; _i < _a.length; _i++) {
var name = _a[_i];
Handlebars.unregisterPartial(name);
}
this.registeredNames = [];
return true;
};
return PartialStack;
}(TemplateStack));
exports.PartialStack = PartialStack;
//# sourceMappingURL=templates.js.map | {
var _this = _super.apply(this, arguments) || this;
_this.registeredNames = [];
return _this;
} | identifier_body |
main.rs | extern crate rand;
use std::fmt;
use std::{thread, time};
use std::process;
use rand::{thread_rng, Rng};
trait State : fmt::Display {
fn do_clock(&self, hour: u32) -> Box<State>;
fn do_use(&self, context: Box<&Context>);
fn do_alarm(&self, context: Box<&Context>);
fn do_phone(&self, context: Box<&Context>);
fn value(&self) -> String;
}
impl PartialEq<State> for State {
fn eq(&self, other: &State) -> bool {
self.value() == other.value()
}
}
trait Context {
fn set_clock(&mut self, hour: u32);
fn change_state(&mut self, state: Box<State>);
fn call_security_center(&self, msg: String);
fn record_log(&self, msg: String);
}
#[derive(PartialEq)]
struct DayState {}
impl DayState {
fn new() -> DayState {
DayState {}
}
}
impl State for DayState {
fn do_clock(&self, hour: u32) -> Box<State> {
if hour < 9 || 17 <= hour {
Box::new(NightState::new())
} else {
Box::new(DayState::new())
}
}
fn do_use(&self, context: Box<&Context>) {
context.record_log("金庫使用(昼間)".to_string());
}
fn do_alarm(&self, context: Box<&Context>) {
context.call_security_center("非常ベル(昼間)".to_string());
}
fn do_phone(&self, context: Box<&Context>) {
context.call_security_center("通常の通話(昼間)".to_string());
}
fn value(&self) -> String {
"昼間".to_string()
}
}
impl fmt::Display for DayState {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "[昼間]")
}
}
#[derive(PartialEq)]
struct NightState {}
impl NightState {
fn new() -> NightState {
NightState {}
}
}
impl State for NightState {
fn do_clock(&self, hour: u32) -> Box<State> {
if 9 <= hour && hour < 17 {
Box::new(DayState::new())
} else {
Box::new(NightState::new())
}
}
fn do_use(&self, context: Box<&Context>) {
context.call_security_center("非常:夜間の金庫使用!".to_string());
}
fn do_alarm(&self, context: Box<&Context>) {
context.call_security_center("非常ベル(夜間)".to_string());
}
fn do_phone(&self, context: Box<&Context>) {
context.record_log("夜間の通話録音".to_string());
}
fn value(&self) -> String {
"夜間".to_string()
}
}
impl fmt::Display for NightState {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "[夜間]")
}
}
struct SafeFrame {
title: String,
state: Box<State>,
}
impl SafeFrame {
fn new(title: String, state: Box<State>) -> SafeFrame {
SafeFrame {
title: title,
state: state,
}
}
fn click_use(&self) {
self.state.do_use(Box::new(self));
}
fn click_alarm(&self) {
self.state.do_alarm(Box::new(self));
}
fn click_phone(&self) {
self.state.do_phone(Box::new(self));
} | fn click_exit(&self) {
process::exit(0);
}
}
impl Context for SafeFrame {
fn set_clock(&mut self, hour: u32) {
println!("現在時刻は{0: >02}:00", hour);
let state = self.state.do_clock(hour);
if &self.state != &state {
self.change_state(state);
}
}
fn change_state(&mut self, state: Box<State>) {
println!("{}から{}へ状態が変化しました。", self.state, state);
self.state = state;
}
fn call_security_center(&self, msg: String) {
println!("call! {}", msg);
}
fn record_log(&self, msg: String) {
println!("record ... {}", msg);
}
}
fn main() {
let mut frame = SafeFrame::new("State Sample".to_string(), Box::new(NightState::new()));
let mut rng = thread_rng();
println!("------------");
println!("{}", frame.title);
println!("------------\n");
loop {
for hour in 0..24 {
frame.set_clock(hour);
match rng.gen_range(0, 3) {
0 => frame.click_use(),
1 => frame.click_alarm(),
2 => frame.click_phone(),
_ => frame.click_exit(),
}
thread::sleep(time::Duration::from_millis(1000));
}
}
} | random_line_split | |
main.rs | extern crate rand;
use std::fmt;
use std::{thread, time};
use std::process;
use rand::{thread_rng, Rng};
trait State : fmt::Display {
fn do_clock(&self, hour: u32) -> Box<State>;
fn do_use(&self, context: Box<&Context>);
fn do_alarm(&self, context: Box<&Context>);
fn do_phone(&self, context: Box<&Context>);
fn value(&self) -> String;
}
impl PartialEq<State> for State {
fn eq(&self, other: &State) -> bool {
self.value() == other.value()
}
}
trait Context {
fn set_clock(&mut self, hour: u32);
fn change_state(&mut self, state: Box<State>);
fn call_security_center(&self, msg: String);
fn record_log(&self, msg: String);
}
#[derive(PartialEq)]
struct DayState {}
impl DayState {
fn new() -> DayState {
DayState {}
}
}
impl State for DayState {
fn do_clock(&self, hour: u32) -> Box<State> {
if hour < 9 || 17 <= hour {
Box::new(NightState::new())
} else {
Box::new(DayState::new())
}
}
fn do_use(&self, context: Box<&Context>) {
context.record_log("金庫使用(昼間)".to_string());
}
fn do_alarm(&self, context: Box<&Context>) {
context.call_security_center("非常ベル(昼間)".to_string());
}
fn do_phone(&self, context: Box<&Context>) {
context.call_security_center("通常の通話(昼間)".to_string());
}
fn value(&self) -> String {
"昼間".to_string()
}
}
impl fmt::Display for DayState {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "[昼間]")
}
}
#[derive(PartialEq)]
struct NightState {}
impl NightState {
fn new() -> NightState {
NightState {}
}
}
impl State for NightState {
fn do_clock(&self, hour: u32) -> Box<State> {
if 9 <= hour && hour < 17 {
Box::new(DayState::new())
} else {
Box::new(NightState::new())
}
}
fn do_use(&self, context: Box<&Context>) {
context.call_security_center("非常:夜間の金庫使用!".to_string());
}
fn do_alarm(&self, context: Box<&Context>) {
context.call_security_center("非常ベル(夜間)".to_string());
}
fn do_phone(&self, context: Box<&Context>) {
context.record_log("夜間の通話録音".to_string());
}
fn value(&self) -> String {
"夜間".to_string()
}
}
impl fmt::Display for NightState {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "[夜間]")
}
}
struct SafeFrame {
title: String,
state: Box<State>,
}
impl SafeFrame {
fn new(title: String, state: Box<State>) -> SafeFrame {
SafeFrame {
title: title,
state: state,
}
}
fn click_use(&self) {
self.state.do_use(Box::new(self));
}
fn click_alarm(&self) {
self.state.do_alarm(Box::new(self));
}
fn click_phone(&self) {
self.state.do_phone(Box::new(self));
}
fn click_exit(&self) {
process::exit(0);
}
}
impl Context for SafeFrame {
fn set_clock(&mut self, hour: u32) {
println!("現在時刻は{0: >02}:00", hour);
let state = self.state.do_clock(hour);
if &self.state != &state {
self.change_state(state);
}
}
fn change_state(&mut self, state: Box<State>) {
println!("{}から{}へ状態が変化しました。", self.state, state);
self.state = state;
}
fn call_security_center(&self, msg: String) {
println!("call! {}", msg);
}
fn record_log(&self, msg: String) {
println!("record ... {}", msg);
}
}
f | new("State Sample".to_string(), Box::new(NightState::new()));
let mut rng = thread_rng();
println!("------------");
println!("{}", frame.title);
println!("------------\n");
loop {
for hour in 0..24 {
frame.set_clock(hour);
match rng.gen_range(0, 3) {
0 => frame.click_use(),
1 => frame.click_alarm(),
2 => frame.click_phone(),
_ => frame.click_exit(),
}
thread::sleep(time::Duration::from_millis(1000));
}
}
}
| n main() {
let mut frame = SafeFrame:: | identifier_body |
main.rs | extern crate rand;
use std::fmt;
use std::{thread, time};
use std::process;
use rand::{thread_rng, Rng};
trait State : fmt::Display {
fn do_clock(&self, hour: u32) -> Box<State>;
fn do_use(&self, context: Box<&Context>);
fn do_alarm(&self, context: Box<&Context>);
fn do_phone(&self, context: Box<&Context>);
fn value(&self) -> String;
}
impl PartialEq<State> for State {
fn eq(&self, other: &State) -> bool {
self.value() == other.value()
}
}
trait Context {
fn set_clock(&mut self, hour: u32);
fn change_state(&mut self, state: Box<State>);
fn call_security_center(&self, msg: String);
fn record_log(&self, msg: String);
}
#[derive(PartialEq)]
struct DayState {}
impl DayState {
fn new() -> DayState {
DayState {}
}
}
impl State for DayState {
fn do_clock(&self, hour: u32) -> Box<State> {
if hour < 9 || 17 <= hour {
Box::new(NightState::new())
} else {
Box::new(DayState::new())
}
}
fn do_use(&self, context: Box<&Context>) {
context.record_log("金庫使用(昼間)".to_string());
}
fn do_alarm(&self, context: Box<&Context>) {
context.call_security_center("非常ベル(昼間)".to_string());
}
fn do_phone(&self, context: Box<&Context>) {
context.call_security_center("通常の通話(昼間)".to_string());
}
fn value(&self) -> String {
"昼間".to_string()
}
}
impl fmt::Display for DayState {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "[昼間]")
}
}
#[derive(PartialEq)]
struct NightState {}
impl NightState {
fn new() -> NightState {
NightState {}
}
}
impl State for NightState {
fn do_clock(&self, hour: u32) -> Box<State> {
| 9 <= hour && hour < 17 {
Box::new(DayState::new())
} else {
Box::new(NightState::new())
}
}
fn do_use(&self, context: Box<&Context>) {
context.call_security_center("非常:夜間の金庫使用!".to_string());
}
fn do_alarm(&self, context: Box<&Context>) {
context.call_security_center("非常ベル(夜間)".to_string());
}
fn do_phone(&self, context: Box<&Context>) {
context.record_log("夜間の通話録音".to_string());
}
fn value(&self) -> String {
"夜間".to_string()
}
}
impl fmt::Display for NightState {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "[夜間]")
}
}
struct SafeFrame {
title: String,
state: Box<State>,
}
impl SafeFrame {
fn new(title: String, state: Box<State>) -> SafeFrame {
SafeFrame {
title: title,
state: state,
}
}
fn click_use(&self) {
self.state.do_use(Box::new(self));
}
fn click_alarm(&self) {
self.state.do_alarm(Box::new(self));
}
fn click_phone(&self) {
self.state.do_phone(Box::new(self));
}
fn click_exit(&self) {
process::exit(0);
}
}
impl Context for SafeFrame {
fn set_clock(&mut self, hour: u32) {
println!("現在時刻は{0: >02}:00", hour);
let state = self.state.do_clock(hour);
if &self.state != &state {
self.change_state(state);
}
}
fn change_state(&mut self, state: Box<State>) {
println!("{}から{}へ状態が変化しました。", self.state, state);
self.state = state;
}
fn call_security_center(&self, msg: String) {
println!("call! {}", msg);
}
fn record_log(&self, msg: String) {
println!("record ... {}", msg);
}
}
fn main() {
let mut frame = SafeFrame::new("State Sample".to_string(), Box::new(NightState::new()));
let mut rng = thread_rng();
println!("------------");
println!("{}", frame.title);
println!("------------\n");
loop {
for hour in 0..24 {
frame.set_clock(hour);
match rng.gen_range(0, 3) {
0 => frame.click_use(),
1 => frame.click_alarm(),
2 => frame.click_phone(),
_ => frame.click_exit(),
}
thread::sleep(time::Duration::from_millis(1000));
}
}
}
| if | identifier_name |
dynamic_tests.rs | use crate::cell::RefCell;
use crate::collections::HashMap;
use crate::thread_local;
#[test]
fn smoke() {
fn square(i: i32) -> i32 {
i * i
}
thread_local!(static FOO: i32 = square(3));
FOO.with(|f| {
assert_eq!(*f, 9);
});
}
#[test]
fn hashmap() |
#[test]
fn refcell_vec() {
thread_local!(static FOO: RefCell<Vec<u32>> = RefCell::new(vec![1, 2, 3]));
FOO.with(|vec| {
assert_eq!(vec.borrow().len(), 3);
vec.borrow_mut().push(4);
assert_eq!(vec.borrow()[3], 4);
});
}
| {
fn map() -> RefCell<HashMap<i32, i32>> {
let mut m = HashMap::new();
m.insert(1, 2);
RefCell::new(m)
}
thread_local!(static FOO: RefCell<HashMap<i32, i32>> = map());
FOO.with(|map| {
assert_eq!(map.borrow()[&1], 2);
});
} | identifier_body |
dynamic_tests.rs | use crate::cell::RefCell;
use crate::collections::HashMap;
use crate::thread_local;
#[test]
fn smoke() {
fn square(i: i32) -> i32 {
i * i
}
thread_local!(static FOO: i32 = square(3));
FOO.with(|f| {
assert_eq!(*f, 9);
});
}
#[test]
fn hashmap() {
fn map() -> RefCell<HashMap<i32, i32>> {
let mut m = HashMap::new();
m.insert(1, 2);
RefCell::new(m) |
FOO.with(|map| {
assert_eq!(map.borrow()[&1], 2);
});
}
#[test]
fn refcell_vec() {
thread_local!(static FOO: RefCell<Vec<u32>> = RefCell::new(vec![1, 2, 3]));
FOO.with(|vec| {
assert_eq!(vec.borrow().len(), 3);
vec.borrow_mut().push(4);
assert_eq!(vec.borrow()[3], 4);
});
} | }
thread_local!(static FOO: RefCell<HashMap<i32, i32>> = map()); | random_line_split |
dynamic_tests.rs | use crate::cell::RefCell;
use crate::collections::HashMap;
use crate::thread_local;
#[test]
fn smoke() {
fn | (i: i32) -> i32 {
i * i
}
thread_local!(static FOO: i32 = square(3));
FOO.with(|f| {
assert_eq!(*f, 9);
});
}
#[test]
fn hashmap() {
fn map() -> RefCell<HashMap<i32, i32>> {
let mut m = HashMap::new();
m.insert(1, 2);
RefCell::new(m)
}
thread_local!(static FOO: RefCell<HashMap<i32, i32>> = map());
FOO.with(|map| {
assert_eq!(map.borrow()[&1], 2);
});
}
#[test]
fn refcell_vec() {
thread_local!(static FOO: RefCell<Vec<u32>> = RefCell::new(vec![1, 2, 3]));
FOO.with(|vec| {
assert_eq!(vec.borrow().len(), 3);
vec.borrow_mut().push(4);
assert_eq!(vec.borrow()[3], 4);
});
}
| square | identifier_name |
register.js | const AuthUtil = require('../thulib/auth')
const User = require('../models/user')
const updateCourseInfo = require('./update_course_info')
const updateCurriculumInfo = require('./update_curriculum_info')
const updateScheduleInfo = require('./update_schedule_info')
const taskScheduler = require('./task_scheduler')
const register = async(username, password) => { | const existed = !!user
if (!existed) {
const info = await AuthUtil.getUserInfo(username, password)
user = new User({
username: username,
password: password,
info: info
})
await user.save()
taskScheduler.add(updateCourseInfo, user, 3600000)
taskScheduler.add(updateCurriculumInfo, user, 3600000)
taskScheduler.add(updateScheduleInfo, user, 3600000)
} else if (existed && user.getPassword() !== password) {
user.password = password
user.save()
}
return [user, existed]
} else {
return [null, false]
}
}
module.exports = register | const authResult = await AuthUtil.auth(username, password)
if (authResult) {
let user = await User.findOne({username: username}) | random_line_split |
env.js | /*
* Meccano IOT WebConsole
*
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
'use strict';
module.exports = {
api: {
security: process.env.API_SECURITY
},
seedDB: process.env.SEED_DB,
showConfig: process.env.SHOW_CONFIG,
secrets: {
session: process.env.SECRETS_SESSION,
sessionTime: process.env.SECRETS_SESSION_TIME,
},
port: process.env.PORT,
address: process.env.ADDRESS,
mysql: {
uri: process.env.MYSQL_URI,
username: process.env.MYSQL_USER,
password: process.env.MYSQL_PASSWORD,
database: process.env.MYSQL_DATABASE,
options: {
logging: process.env.MYSQL_OPTIONS_LOGGING, | port: process.env.MYSQL_PORT
}
},
servicemaneger: {
url: process.env.SERVICEMANAGER_URL
}
}; | pool: {
maxConnections: process.env.MYSQL_OPTIONS_POOL_MAXCONNECTIONS,
minConnections: process.env.MYSQL_OPTIONS_POOL_MINCONNECTIONS
},
host: process.env.MYSQL_HOST, | random_line_split |
test_hb.py | from __future__ import division, print_function, absolute_import
from io import StringIO
import tempfile
import numpy as np
from numpy.testing import assert_equal, \
assert_array_almost_equal_nulp
from scipy.sparse import coo_matrix, csc_matrix, rand
from scipy.io import hb_read, hb_write
SIMPLE = """\
No Title |No Key
9 4 1 4
RUA 100 100 10 0
(26I3) (26I3) (3E23.15)
1 2 2 2 2 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3
3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3
3 3 3 3 3 3 3 4 4 4 6 6 6 6 6 6 6 6 6 6 6 8 9 9 9 9
9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 11
37 71 89 18 30 45 70 19 25 52
2.971243799687726e-01 3.662366682877375e-01 4.786962174699534e-01
6.490068647991184e-01 6.617490424831662e-02 8.870370343191623e-01
4.196478590163001e-01 5.649603072111251e-01 9.934423887087086e-01
6.912334991524289e-01
"""
SIMPLE_MATRIX = coo_matrix(
((0.297124379969, 0.366236668288, 0.47869621747, 0.649006864799,
0.0661749042483, 0.887037034319, 0.419647859016,
0.564960307211, 0.993442388709, 0.691233499152,),
(np.array([[36, 70, 88, 17, 29, 44, 69, 18, 24, 51],
[0, 4, 58, 61, 61, 72, 72, 73, 99, 99]]))))
def assert_csc_almost_equal(r, l):
r = csc_matrix(r)
l = csc_matrix(l)
assert_equal(r.indptr, l.indptr)
assert_equal(r.indices, l.indices)
assert_array_almost_equal_nulp(r.data, l.data, 10000)
class TestHBReader(object):
def test_simple(self):
|
class TestHBReadWrite(object):
def check_save_load(self, value):
with tempfile.NamedTemporaryFile(mode='w+t') as file:
hb_write(file, value)
file.file.seek(0)
value_loaded = hb_read(file)
assert_csc_almost_equal(value, value_loaded)
def test_simple(self):
random_matrix = rand(10, 100, 0.1)
for matrix_format in ('coo', 'csc', 'csr', 'bsr', 'dia', 'dok', 'lil'):
matrix = random_matrix.asformat(matrix_format, copy=False)
self.check_save_load(matrix)
| m = hb_read(StringIO(SIMPLE))
assert_csc_almost_equal(m, SIMPLE_MATRIX) | identifier_body |
test_hb.py | from __future__ import division, print_function, absolute_import
from io import StringIO
import tempfile
import numpy as np
from numpy.testing import assert_equal, \
assert_array_almost_equal_nulp
from scipy.sparse import coo_matrix, csc_matrix, rand
from scipy.io import hb_read, hb_write
SIMPLE = """\
No Title |No Key
9 4 1 4
RUA 100 100 10 0
(26I3) (26I3) (3E23.15)
1 2 2 2 2 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3
3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3
3 3 3 3 3 3 3 4 4 4 6 6 6 6 6 6 6 6 6 6 6 8 9 9 9 9
9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 11
37 71 89 18 30 45 70 19 25 52
2.971243799687726e-01 3.662366682877375e-01 4.786962174699534e-01
6.490068647991184e-01 6.617490424831662e-02 8.870370343191623e-01
4.196478590163001e-01 5.649603072111251e-01 9.934423887087086e-01
6.912334991524289e-01
"""
SIMPLE_MATRIX = coo_matrix(
((0.297124379969, 0.366236668288, 0.47869621747, 0.649006864799,
0.0661749042483, 0.887037034319, 0.419647859016,
0.564960307211, 0.993442388709, 0.691233499152,),
(np.array([[36, 70, 88, 17, 29, 44, 69, 18, 24, 51],
[0, 4, 58, 61, 61, 72, 72, 73, 99, 99]]))))
def assert_csc_almost_equal(r, l):
r = csc_matrix(r)
l = csc_matrix(l)
assert_equal(r.indptr, l.indptr)
assert_equal(r.indices, l.indices)
assert_array_almost_equal_nulp(r.data, l.data, 10000)
class TestHBReader(object):
def test_simple(self):
m = hb_read(StringIO(SIMPLE))
assert_csc_almost_equal(m, SIMPLE_MATRIX)
class TestHBReadWrite(object):
def check_save_load(self, value):
with tempfile.NamedTemporaryFile(mode='w+t') as file:
hb_write(file, value)
file.file.seek(0)
value_loaded = hb_read(file)
assert_csc_almost_equal(value, value_loaded)
def test_simple(self):
random_matrix = rand(10, 100, 0.1)
for matrix_format in ('coo', 'csc', 'csr', 'bsr', 'dia', 'dok', 'lil'):
| matrix = random_matrix.asformat(matrix_format, copy=False)
self.check_save_load(matrix) | conditional_block | |
test_hb.py | from __future__ import division, print_function, absolute_import
from io import StringIO
import tempfile
import numpy as np
from numpy.testing import assert_equal, \
assert_array_almost_equal_nulp
from scipy.sparse import coo_matrix, csc_matrix, rand
from scipy.io import hb_read, hb_write
SIMPLE = """\
No Title |No Key
9 4 1 4
RUA 100 100 10 0 | 3 3 3 3 3 3 3 4 4 4 6 6 6 6 6 6 6 6 6 6 6 8 9 9 9 9
9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 11
37 71 89 18 30 45 70 19 25 52
2.971243799687726e-01 3.662366682877375e-01 4.786962174699534e-01
6.490068647991184e-01 6.617490424831662e-02 8.870370343191623e-01
4.196478590163001e-01 5.649603072111251e-01 9.934423887087086e-01
6.912334991524289e-01
"""
SIMPLE_MATRIX = coo_matrix(
((0.297124379969, 0.366236668288, 0.47869621747, 0.649006864799,
0.0661749042483, 0.887037034319, 0.419647859016,
0.564960307211, 0.993442388709, 0.691233499152,),
(np.array([[36, 70, 88, 17, 29, 44, 69, 18, 24, 51],
[0, 4, 58, 61, 61, 72, 72, 73, 99, 99]]))))
def assert_csc_almost_equal(r, l):
r = csc_matrix(r)
l = csc_matrix(l)
assert_equal(r.indptr, l.indptr)
assert_equal(r.indices, l.indices)
assert_array_almost_equal_nulp(r.data, l.data, 10000)
class TestHBReader(object):
def test_simple(self):
m = hb_read(StringIO(SIMPLE))
assert_csc_almost_equal(m, SIMPLE_MATRIX)
class TestHBReadWrite(object):
def check_save_load(self, value):
with tempfile.NamedTemporaryFile(mode='w+t') as file:
hb_write(file, value)
file.file.seek(0)
value_loaded = hb_read(file)
assert_csc_almost_equal(value, value_loaded)
def test_simple(self):
random_matrix = rand(10, 100, 0.1)
for matrix_format in ('coo', 'csc', 'csr', 'bsr', 'dia', 'dok', 'lil'):
matrix = random_matrix.asformat(matrix_format, copy=False)
self.check_save_load(matrix) | (26I3) (26I3) (3E23.15)
1 2 2 2 2 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3
3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 | random_line_split |
test_hb.py | from __future__ import division, print_function, absolute_import
from io import StringIO
import tempfile
import numpy as np
from numpy.testing import assert_equal, \
assert_array_almost_equal_nulp
from scipy.sparse import coo_matrix, csc_matrix, rand
from scipy.io import hb_read, hb_write
SIMPLE = """\
No Title |No Key
9 4 1 4
RUA 100 100 10 0
(26I3) (26I3) (3E23.15)
1 2 2 2 2 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3
3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3
3 3 3 3 3 3 3 4 4 4 6 6 6 6 6 6 6 6 6 6 6 8 9 9 9 9
9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 11
37 71 89 18 30 45 70 19 25 52
2.971243799687726e-01 3.662366682877375e-01 4.786962174699534e-01
6.490068647991184e-01 6.617490424831662e-02 8.870370343191623e-01
4.196478590163001e-01 5.649603072111251e-01 9.934423887087086e-01
6.912334991524289e-01
"""
SIMPLE_MATRIX = coo_matrix(
((0.297124379969, 0.366236668288, 0.47869621747, 0.649006864799,
0.0661749042483, 0.887037034319, 0.419647859016,
0.564960307211, 0.993442388709, 0.691233499152,),
(np.array([[36, 70, 88, 17, 29, 44, 69, 18, 24, 51],
[0, 4, 58, 61, 61, 72, 72, 73, 99, 99]]))))
def assert_csc_almost_equal(r, l):
r = csc_matrix(r)
l = csc_matrix(l)
assert_equal(r.indptr, l.indptr)
assert_equal(r.indices, l.indices)
assert_array_almost_equal_nulp(r.data, l.data, 10000)
class TestHBReader(object):
def | (self):
m = hb_read(StringIO(SIMPLE))
assert_csc_almost_equal(m, SIMPLE_MATRIX)
class TestHBReadWrite(object):
def check_save_load(self, value):
with tempfile.NamedTemporaryFile(mode='w+t') as file:
hb_write(file, value)
file.file.seek(0)
value_loaded = hb_read(file)
assert_csc_almost_equal(value, value_loaded)
def test_simple(self):
random_matrix = rand(10, 100, 0.1)
for matrix_format in ('coo', 'csc', 'csr', 'bsr', 'dia', 'dok', 'lil'):
matrix = random_matrix.asformat(matrix_format, copy=False)
self.check_save_load(matrix)
| test_simple | identifier_name |
drop-container.js | /**
* Copyright IBM Corp. 2016, 2018
*
* This source code is licensed under the Apache-2.0 license found in the
* LICENSE file in the root directory of this source tree.
*/
import React, { useState, useCallback, useEffect } from 'react';
import classnames from 'classnames';
import { settings } from 'carbon-components';
import FileUploaderItem from '../FileUploaderItem';
import FileUploaderDropContainer from '../FileUploaderDropContainer';
import FormItem from '../../FormItem';
import uid from '../../../tools/uniqueId';
import '../FileUploader-story.scss';
const { prefix } = settings;
const ExampleDropContainerApp = (props) => {
const [files, setFiles] = useState([]);
const handleDrop = (e) => {
e.preventDefault();
};
const handleDragover = (e) => {
e.preventDefault();
};
useEffect(() => {
document.addEventListener('drop', handleDrop);
document.addEventListener('dragover', handleDragover);
return () => {
document.removeEventListener('drop', handleDrop);
document.removeEventListener('dragover', handleDragover);
};
}, []);
const uploadFile = async (fileToUpload) => {
// file size validation
if (fileToUpload.filesize > 512000) |
// file type validation
if (fileToUpload.invalidFileType) {
const updatedFile = {
...fileToUpload,
status: 'edit',
iconDescription: 'Delete file',
invalid: true,
errorSubject: 'Invalid file type',
errorBody: `"${fileToUpload.name}" does not have a valid file type.`,
};
setFiles((files) =>
files.map((file) =>
file.uuid === fileToUpload.uuid ? updatedFile : file
)
);
return;
}
// simulate network request time
const rand = Math.random() * 1000;
setTimeout(() => {
const updatedFile = {
...fileToUpload,
status: 'complete',
iconDescription: 'Upload complete',
};
setFiles((files) =>
files.map((file) =>
file.uuid === fileToUpload.uuid ? updatedFile : file
)
);
}, rand);
// show x icon after 1 second
setTimeout(() => {
const updatedFile = {
...fileToUpload,
status: 'edit',
iconDescription: 'Delete file',
};
setFiles((files) =>
files.map((file) =>
file.uuid === fileToUpload.uuid ? updatedFile : file
)
);
}, rand + 1000);
};
const onAddFiles = useCallback(
(evt, { addedFiles }) => {
evt.stopPropagation();
const newFiles = addedFiles.map((file) => ({
uuid: uid(),
name: file.name,
filesize: file.size,
status: 'uploading',
iconDescription: 'Uploading',
invalidFileType: file.invalidFileType,
}));
// eslint-disable-next-line react/prop-types
if (props.multiple) {
setFiles([...files, ...newFiles]);
newFiles.forEach(uploadFile);
} else if (newFiles[0]) {
setFiles([newFiles[0]]);
uploadFile(newFiles[0]);
}
},
// eslint-disable-next-line react/prop-types
[files, props.multiple]
);
const handleFileUploaderItemClick = useCallback(
(_, { uuid: clickedUuid }) =>
setFiles(files.filter(({ uuid }) => clickedUuid !== uuid)),
[files]
);
const labelClasses = classnames(`${prefix}--file--label`, {
// eslint-disable-next-line react/prop-types
[`${prefix}--file--label--disabled`]: props.disabled,
});
const helperTextClasses = classnames(`${prefix}--label-description`, {
// eslint-disable-next-line react/prop-types
[`${prefix}--label-description--disabled`]: props.disabled,
});
return (
<FormItem>
<p className={labelClasses}>Upload files</p>
<p className={helperTextClasses}>
Max file size is 500kb. Supported file types are .jpg and .png.
</p>
<FileUploaderDropContainer {...props} onAddFiles={onAddFiles} />
<div className={`${prefix}--file-container`} style={{ width: '100%' }}>
{files.map(
({
uuid,
name,
filesize,
status,
iconDescription,
invalid,
...rest
}) => (
<FileUploaderItem
key={uid()}
uuid={uuid}
name={name}
filesize={filesize}
// eslint-disable-next-line react/prop-types
size={props.size}
status={status}
iconDescription={iconDescription}
invalid={invalid}
onDelete={handleFileUploaderItemClick}
{...rest}
/>
)
)}
</div>
</FormItem>
);
};
export default ExampleDropContainerApp;
| {
const updatedFile = {
...fileToUpload,
status: 'edit',
iconDescription: 'Delete file',
invalid: true,
errorSubject: 'File size exceeds limit',
errorBody: '500kb max file size. Select a new file and try again.',
};
setFiles((files) =>
files.map((file) =>
file.uuid === fileToUpload.uuid ? updatedFile : file
)
);
return;
} | conditional_block |
drop-container.js | /**
* Copyright IBM Corp. 2016, 2018
*
* This source code is licensed under the Apache-2.0 license found in the
* LICENSE file in the root directory of this source tree.
*/
import React, { useState, useCallback, useEffect } from 'react';
import classnames from 'classnames';
import { settings } from 'carbon-components';
import FileUploaderItem from '../FileUploaderItem';
import FileUploaderDropContainer from '../FileUploaderDropContainer';
import FormItem from '../../FormItem';
import uid from '../../../tools/uniqueId';
import '../FileUploader-story.scss';
const { prefix } = settings;
const ExampleDropContainerApp = (props) => {
const [files, setFiles] = useState([]);
const handleDrop = (e) => {
e.preventDefault();
};
const handleDragover = (e) => {
e.preventDefault();
};
useEffect(() => {
document.addEventListener('drop', handleDrop);
document.addEventListener('dragover', handleDragover);
return () => {
document.removeEventListener('drop', handleDrop);
document.removeEventListener('dragover', handleDragover);
};
}, []);
const uploadFile = async (fileToUpload) => {
// file size validation
if (fileToUpload.filesize > 512000) {
const updatedFile = {
...fileToUpload,
status: 'edit',
iconDescription: 'Delete file',
invalid: true,
errorSubject: 'File size exceeds limit',
errorBody: '500kb max file size. Select a new file and try again.',
};
setFiles((files) =>
files.map((file) =>
file.uuid === fileToUpload.uuid ? updatedFile : file
)
);
return;
}
// file type validation
if (fileToUpload.invalidFileType) {
const updatedFile = {
...fileToUpload,
status: 'edit',
iconDescription: 'Delete file',
invalid: true,
errorSubject: 'Invalid file type',
errorBody: `"${fileToUpload.name}" does not have a valid file type.`,
};
setFiles((files) =>
files.map((file) =>
file.uuid === fileToUpload.uuid ? updatedFile : file
)
);
return;
}
// simulate network request time
const rand = Math.random() * 1000;
setTimeout(() => {
const updatedFile = {
...fileToUpload,
status: 'complete',
iconDescription: 'Upload complete',
};
setFiles((files) =>
files.map((file) =>
file.uuid === fileToUpload.uuid ? updatedFile : file
)
);
}, rand);
// show x icon after 1 second
setTimeout(() => {
const updatedFile = {
...fileToUpload,
status: 'edit',
iconDescription: 'Delete file',
};
setFiles((files) =>
files.map((file) =>
file.uuid === fileToUpload.uuid ? updatedFile : file
)
);
}, rand + 1000);
};
const onAddFiles = useCallback(
(evt, { addedFiles }) => { | name: file.name,
filesize: file.size,
status: 'uploading',
iconDescription: 'Uploading',
invalidFileType: file.invalidFileType,
}));
// eslint-disable-next-line react/prop-types
if (props.multiple) {
setFiles([...files, ...newFiles]);
newFiles.forEach(uploadFile);
} else if (newFiles[0]) {
setFiles([newFiles[0]]);
uploadFile(newFiles[0]);
}
},
// eslint-disable-next-line react/prop-types
[files, props.multiple]
);
const handleFileUploaderItemClick = useCallback(
(_, { uuid: clickedUuid }) =>
setFiles(files.filter(({ uuid }) => clickedUuid !== uuid)),
[files]
);
const labelClasses = classnames(`${prefix}--file--label`, {
// eslint-disable-next-line react/prop-types
[`${prefix}--file--label--disabled`]: props.disabled,
});
const helperTextClasses = classnames(`${prefix}--label-description`, {
// eslint-disable-next-line react/prop-types
[`${prefix}--label-description--disabled`]: props.disabled,
});
return (
<FormItem>
<p className={labelClasses}>Upload files</p>
<p className={helperTextClasses}>
Max file size is 500kb. Supported file types are .jpg and .png.
</p>
<FileUploaderDropContainer {...props} onAddFiles={onAddFiles} />
<div className={`${prefix}--file-container`} style={{ width: '100%' }}>
{files.map(
({
uuid,
name,
filesize,
status,
iconDescription,
invalid,
...rest
}) => (
<FileUploaderItem
key={uid()}
uuid={uuid}
name={name}
filesize={filesize}
// eslint-disable-next-line react/prop-types
size={props.size}
status={status}
iconDescription={iconDescription}
invalid={invalid}
onDelete={handleFileUploaderItemClick}
{...rest}
/>
)
)}
</div>
</FormItem>
);
};
export default ExampleDropContainerApp; | evt.stopPropagation();
const newFiles = addedFiles.map((file) => ({
uuid: uid(), | random_line_split |
toNumber.test.ts | import * as test from 'tape';
import { toNumber } from '../../src/to';
test('toNumber:numbers', (t) => {
t.equal(toNumber(0), 0);
t.equal(toNumber(-0), 0);
t.equal(toNumber(1), 1);
t.equal(toNumber(-1), -1); | });
test('toNumber:strings', (t) => {
t.equal(toNumber(''), 0);
t.equal(toNumber('0'), 0);
t.equal(toNumber('-0'), 0);
t.equal(toNumber('1'), 1);
t.equal(toNumber('-1'), -1);
t.equal(toNumber('1.5'), 1.5);
t.equal(toNumber('-1.5'), -1.5);
t.end();
});
test('toNumber:Infinity', (t) => {
t.equal(toNumber(Infinity), 0);
t.equal(toNumber(Infinity, false), Infinity);
t.equal(toNumber(-Infinity), 0);
t.equal(toNumber(-Infinity, false), -Infinity);
t.end();
});
test('toNumber:other', (t) => {
t.equal(toNumber([]), 0);
t.equal(toNumber({}), 0);
t.equal(toNumber(null), 0);
t.equal(toNumber(undefined), 0);
t.equal(toNumber(new Error('error')), 0);
t.end();
}); | t.equal(toNumber(1), 1);
t.equal(toNumber(1.5), 1.5);
t.equal(toNumber(-1.5), -1.5);
t.end(); | random_line_split |
SacrificedSouls.js | import React from 'react';
import Analyzer, { SELECTED_PLAYER } from 'parser/core/Analyzer';
import Events from 'parser/core/Events';
import calculateEffectiveDamage from 'parser/core/calculateEffectiveDamage';
import SPELLS from 'common/SPELLS';
import { formatThousands } from 'common/format';
import STATISTIC_CATEGORY from 'parser/ui/STATISTIC_CATEGORY';
import Statistic from 'parser/ui/Statistic';
import BoringSpellValueText from 'parser/ui/BoringSpellValueText';
import ItemDamageDone from 'parser/ui/ItemDamageDone';
import DemoPets from '../pets/DemoPets';
const BONUS_DAMAGE_PER_PET = 0.04;
const MAX_TRAVEL_TIME = 3000; // Shadow Bolt is the slowest, takes around 2 seconds to land from max distance, add a little more to account for target movement
const debug = false;
/*
Sacrificed Souls:
Shadow Bolt and Demonbolt deal 5% additional damage per demon you have summoned.
*/
class SacrificedSouls extends Analyzer {
get totalBonusDamage() {
return this._shadowBoltDamage + this._demonboltDamage;
}
static dependencies = {
demoPets: DemoPets,
};
_shadowBoltDamage = 0;
_demonboltDamage = 0;
_queue = [];
constructor(...args) {
super(...args);
this.active = this.selectedCombatant.hasTalent(SPELLS.SACRIFICED_SOULS_TALENT.id);
this.addEventListener(Events.cast.by(SELECTED_PLAYER).spell([SPELLS.SHADOW_BOLT_DEMO, SPELLS.DEMONBOLT]), this.handleCast);
this.addEventListener(Events.damage.by(SELECTED_PLAYER).spell([SPELLS.SHADOW_BOLT_DEMO, SPELLS.DEMONBOLT]), this.handleDamage);
}
// essentially same snapshotting mechanic as in Destruction's Eradication
handleCast(event) {
const bonus = this.demoPets.getPetCount() * BONUS_DAMAGE_PER_PET;
this._queue.push({
timestamp: event.timestamp,
spellId: event.ability.guid,
targetID: event.targetID,
targetInstance: event.targetInstance,
bonus,
});
debug && this.log('Pushed a cast into queue', JSON.parse(JSON.stringify(this._queue)));
}
handleDamage(event) {
// filter out old casts if there are any
this._queue = this._queue.filter(cast => cast.timestamp > (event.timestamp - MAX_TRAVEL_TIME));
const castIndex = this._queue
.findIndex(cast => cast.targetID === event.targetID
&& cast.targetInstance === event.targetInstance
&& cast.spellId === event.ability.guid);
if (castIndex === -1) |
debug && this.log('Paired damage event', event, 'with queued cast', JSON.parse(JSON.stringify(this._queue[castIndex])));
const bonusDamage = calculateEffectiveDamage(event, this._queue[castIndex].bonus);
this._queue.splice(castIndex, 1);
if (event.ability.guid === SPELLS.SHADOW_BOLT_DEMO.id) {
this._shadowBoltDamage += bonusDamage;
} else {
this._demonboltDamage += bonusDamage;
}
}
statistic() {
const hasPS = this.selectedCombatant.hasTalent(SPELLS.POWER_SIPHON_TALENT.id);
return (
<Statistic
category={STATISTIC_CATEGORY.TALENTS}
size="flexible"
tooltip={(
<>
{formatThousands(this.totalBonusDamage)} bonus damage<br />
Bonus Shadow Bolt damage: {formatThousands(this._shadowBoltDamage)} ({this.owner.formatItemDamageDone(this._shadowBoltDamage)})<br />
Bonus Demonbolt damage: {formatThousands(this._demonboltDamage)} ({this.owner.formatItemDamageDone(this._demonboltDamage)})
{hasPS && (
<>
<br /><br />* Since you have Power Siphon talent, it's highly likely that it messes up getting current pets at certain time because sometimes
the number of Imps we sacrifice in code doesn't agree with what happens in logs. Therefore, this value is most likely a little wrong.
</>
)}
</>
)}
>
<BoringSpellValueText spell={SPELLS.SACRIFICED_SOULS_TALENT}>
<ItemDamageDone amount={this.totalBonusDamage} />
</BoringSpellValueText>
</Statistic>
);
}
}
export default SacrificedSouls;
| {
debug && this.error('Encountered damage event with no cast associated. Queue', JSON.parse(JSON.stringify(this._queue)), 'event', event);
return;
} | conditional_block |
SacrificedSouls.js | import React from 'react';
import Analyzer, { SELECTED_PLAYER } from 'parser/core/Analyzer';
import Events from 'parser/core/Events';
import calculateEffectiveDamage from 'parser/core/calculateEffectiveDamage';
import SPELLS from 'common/SPELLS';
import { formatThousands } from 'common/format';
import STATISTIC_CATEGORY from 'parser/ui/STATISTIC_CATEGORY';
import Statistic from 'parser/ui/Statistic';
import BoringSpellValueText from 'parser/ui/BoringSpellValueText';
import ItemDamageDone from 'parser/ui/ItemDamageDone';
import DemoPets from '../pets/DemoPets';
const BONUS_DAMAGE_PER_PET = 0.04;
const MAX_TRAVEL_TIME = 3000; // Shadow Bolt is the slowest, takes around 2 seconds to land from max distance, add a little more to account for target movement
const debug = false;
/*
Sacrificed Souls:
Shadow Bolt and Demonbolt deal 5% additional damage per demon you have summoned.
*/
class | extends Analyzer {
get totalBonusDamage() {
return this._shadowBoltDamage + this._demonboltDamage;
}
static dependencies = {
demoPets: DemoPets,
};
_shadowBoltDamage = 0;
_demonboltDamage = 0;
_queue = [];
constructor(...args) {
super(...args);
this.active = this.selectedCombatant.hasTalent(SPELLS.SACRIFICED_SOULS_TALENT.id);
this.addEventListener(Events.cast.by(SELECTED_PLAYER).spell([SPELLS.SHADOW_BOLT_DEMO, SPELLS.DEMONBOLT]), this.handleCast);
this.addEventListener(Events.damage.by(SELECTED_PLAYER).spell([SPELLS.SHADOW_BOLT_DEMO, SPELLS.DEMONBOLT]), this.handleDamage);
}
// essentially same snapshotting mechanic as in Destruction's Eradication
handleCast(event) {
const bonus = this.demoPets.getPetCount() * BONUS_DAMAGE_PER_PET;
this._queue.push({
timestamp: event.timestamp,
spellId: event.ability.guid,
targetID: event.targetID,
targetInstance: event.targetInstance,
bonus,
});
debug && this.log('Pushed a cast into queue', JSON.parse(JSON.stringify(this._queue)));
}
handleDamage(event) {
// filter out old casts if there are any
this._queue = this._queue.filter(cast => cast.timestamp > (event.timestamp - MAX_TRAVEL_TIME));
const castIndex = this._queue
.findIndex(cast => cast.targetID === event.targetID
&& cast.targetInstance === event.targetInstance
&& cast.spellId === event.ability.guid);
if (castIndex === -1) {
debug && this.error('Encountered damage event with no cast associated. Queue', JSON.parse(JSON.stringify(this._queue)), 'event', event);
return;
}
debug && this.log('Paired damage event', event, 'with queued cast', JSON.parse(JSON.stringify(this._queue[castIndex])));
const bonusDamage = calculateEffectiveDamage(event, this._queue[castIndex].bonus);
this._queue.splice(castIndex, 1);
if (event.ability.guid === SPELLS.SHADOW_BOLT_DEMO.id) {
this._shadowBoltDamage += bonusDamage;
} else {
this._demonboltDamage += bonusDamage;
}
}
statistic() {
const hasPS = this.selectedCombatant.hasTalent(SPELLS.POWER_SIPHON_TALENT.id);
return (
<Statistic
category={STATISTIC_CATEGORY.TALENTS}
size="flexible"
tooltip={(
<>
{formatThousands(this.totalBonusDamage)} bonus damage<br />
Bonus Shadow Bolt damage: {formatThousands(this._shadowBoltDamage)} ({this.owner.formatItemDamageDone(this._shadowBoltDamage)})<br />
Bonus Demonbolt damage: {formatThousands(this._demonboltDamage)} ({this.owner.formatItemDamageDone(this._demonboltDamage)})
{hasPS && (
<>
<br /><br />* Since you have Power Siphon talent, it's highly likely that it messes up getting current pets at certain time because sometimes
the number of Imps we sacrifice in code doesn't agree with what happens in logs. Therefore, this value is most likely a little wrong.
</>
)}
</>
)}
>
<BoringSpellValueText spell={SPELLS.SACRIFICED_SOULS_TALENT}>
<ItemDamageDone amount={this.totalBonusDamage} />
</BoringSpellValueText>
</Statistic>
);
}
}
export default SacrificedSouls;
| SacrificedSouls | identifier_name |
SacrificedSouls.js | import React from 'react';
import Analyzer, { SELECTED_PLAYER } from 'parser/core/Analyzer';
import Events from 'parser/core/Events';
import calculateEffectiveDamage from 'parser/core/calculateEffectiveDamage';
import SPELLS from 'common/SPELLS';
import { formatThousands } from 'common/format';
import STATISTIC_CATEGORY from 'parser/ui/STATISTIC_CATEGORY';
import Statistic from 'parser/ui/Statistic';
import BoringSpellValueText from 'parser/ui/BoringSpellValueText';
import ItemDamageDone from 'parser/ui/ItemDamageDone';
import DemoPets from '../pets/DemoPets';
const BONUS_DAMAGE_PER_PET = 0.04;
const MAX_TRAVEL_TIME = 3000; // Shadow Bolt is the slowest, takes around 2 seconds to land from max distance, add a little more to account for target movement
const debug = false;
/*
Sacrificed Souls:
Shadow Bolt and Demonbolt deal 5% additional damage per demon you have summoned.
*/
class SacrificedSouls extends Analyzer {
get totalBonusDamage() {
return this._shadowBoltDamage + this._demonboltDamage;
}
static dependencies = {
demoPets: DemoPets,
};
_shadowBoltDamage = 0;
_demonboltDamage = 0;
_queue = [];
constructor(...args) {
super(...args);
this.active = this.selectedCombatant.hasTalent(SPELLS.SACRIFICED_SOULS_TALENT.id);
this.addEventListener(Events.cast.by(SELECTED_PLAYER).spell([SPELLS.SHADOW_BOLT_DEMO, SPELLS.DEMONBOLT]), this.handleCast);
this.addEventListener(Events.damage.by(SELECTED_PLAYER).spell([SPELLS.SHADOW_BOLT_DEMO, SPELLS.DEMONBOLT]), this.handleDamage);
}
// essentially same snapshotting mechanic as in Destruction's Eradication
handleCast(event) {
const bonus = this.demoPets.getPetCount() * BONUS_DAMAGE_PER_PET;
this._queue.push({
timestamp: event.timestamp,
spellId: event.ability.guid,
targetID: event.targetID,
targetInstance: event.targetInstance,
bonus,
});
debug && this.log('Pushed a cast into queue', JSON.parse(JSON.stringify(this._queue)));
}
handleDamage(event) {
// filter out old casts if there are any
this._queue = this._queue.filter(cast => cast.timestamp > (event.timestamp - MAX_TRAVEL_TIME));
const castIndex = this._queue
.findIndex(cast => cast.targetID === event.targetID
&& cast.targetInstance === event.targetInstance
&& cast.spellId === event.ability.guid);
if (castIndex === -1) {
debug && this.error('Encountered damage event with no cast associated. Queue', JSON.parse(JSON.stringify(this._queue)), 'event', event);
return;
}
debug && this.log('Paired damage event', event, 'with queued cast', JSON.parse(JSON.stringify(this._queue[castIndex])));
const bonusDamage = calculateEffectiveDamage(event, this._queue[castIndex].bonus);
this._queue.splice(castIndex, 1);
if (event.ability.guid === SPELLS.SHADOW_BOLT_DEMO.id) {
this._shadowBoltDamage += bonusDamage;
} else {
this._demonboltDamage += bonusDamage;
}
}
statistic() {
const hasPS = this.selectedCombatant.hasTalent(SPELLS.POWER_SIPHON_TALENT.id);
return (
<Statistic
category={STATISTIC_CATEGORY.TALENTS}
size="flexible"
tooltip={(
<>
{formatThousands(this.totalBonusDamage)} bonus damage<br />
Bonus Shadow Bolt damage: {formatThousands(this._shadowBoltDamage)} ({this.owner.formatItemDamageDone(this._shadowBoltDamage)})<br />
Bonus Demonbolt damage: {formatThousands(this._demonboltDamage)} ({this.owner.formatItemDamageDone(this._demonboltDamage)}) | </>
)}
</>
)}
>
<BoringSpellValueText spell={SPELLS.SACRIFICED_SOULS_TALENT}>
<ItemDamageDone amount={this.totalBonusDamage} />
</BoringSpellValueText>
</Statistic>
);
}
}
export default SacrificedSouls; | {hasPS && (
<>
<br /><br />* Since you have Power Siphon talent, it's highly likely that it messes up getting current pets at certain time because sometimes
the number of Imps we sacrifice in code doesn't agree with what happens in logs. Therefore, this value is most likely a little wrong. | random_line_split |
SacrificedSouls.js | import React from 'react';
import Analyzer, { SELECTED_PLAYER } from 'parser/core/Analyzer';
import Events from 'parser/core/Events';
import calculateEffectiveDamage from 'parser/core/calculateEffectiveDamage';
import SPELLS from 'common/SPELLS';
import { formatThousands } from 'common/format';
import STATISTIC_CATEGORY from 'parser/ui/STATISTIC_CATEGORY';
import Statistic from 'parser/ui/Statistic';
import BoringSpellValueText from 'parser/ui/BoringSpellValueText';
import ItemDamageDone from 'parser/ui/ItemDamageDone';
import DemoPets from '../pets/DemoPets';
const BONUS_DAMAGE_PER_PET = 0.04;
const MAX_TRAVEL_TIME = 3000; // Shadow Bolt is the slowest, takes around 2 seconds to land from max distance, add a little more to account for target movement
const debug = false;
/*
Sacrificed Souls:
Shadow Bolt and Demonbolt deal 5% additional damage per demon you have summoned.
*/
class SacrificedSouls extends Analyzer {
get totalBonusDamage() |
static dependencies = {
demoPets: DemoPets,
};
_shadowBoltDamage = 0;
_demonboltDamage = 0;
_queue = [];
constructor(...args) {
super(...args);
this.active = this.selectedCombatant.hasTalent(SPELLS.SACRIFICED_SOULS_TALENT.id);
this.addEventListener(Events.cast.by(SELECTED_PLAYER).spell([SPELLS.SHADOW_BOLT_DEMO, SPELLS.DEMONBOLT]), this.handleCast);
this.addEventListener(Events.damage.by(SELECTED_PLAYER).spell([SPELLS.SHADOW_BOLT_DEMO, SPELLS.DEMONBOLT]), this.handleDamage);
}
// essentially same snapshotting mechanic as in Destruction's Eradication
handleCast(event) {
const bonus = this.demoPets.getPetCount() * BONUS_DAMAGE_PER_PET;
this._queue.push({
timestamp: event.timestamp,
spellId: event.ability.guid,
targetID: event.targetID,
targetInstance: event.targetInstance,
bonus,
});
debug && this.log('Pushed a cast into queue', JSON.parse(JSON.stringify(this._queue)));
}
handleDamage(event) {
// filter out old casts if there are any
this._queue = this._queue.filter(cast => cast.timestamp > (event.timestamp - MAX_TRAVEL_TIME));
const castIndex = this._queue
.findIndex(cast => cast.targetID === event.targetID
&& cast.targetInstance === event.targetInstance
&& cast.spellId === event.ability.guid);
if (castIndex === -1) {
debug && this.error('Encountered damage event with no cast associated. Queue', JSON.parse(JSON.stringify(this._queue)), 'event', event);
return;
}
debug && this.log('Paired damage event', event, 'with queued cast', JSON.parse(JSON.stringify(this._queue[castIndex])));
const bonusDamage = calculateEffectiveDamage(event, this._queue[castIndex].bonus);
this._queue.splice(castIndex, 1);
if (event.ability.guid === SPELLS.SHADOW_BOLT_DEMO.id) {
this._shadowBoltDamage += bonusDamage;
} else {
this._demonboltDamage += bonusDamage;
}
}
statistic() {
const hasPS = this.selectedCombatant.hasTalent(SPELLS.POWER_SIPHON_TALENT.id);
return (
<Statistic
category={STATISTIC_CATEGORY.TALENTS}
size="flexible"
tooltip={(
<>
{formatThousands(this.totalBonusDamage)} bonus damage<br />
Bonus Shadow Bolt damage: {formatThousands(this._shadowBoltDamage)} ({this.owner.formatItemDamageDone(this._shadowBoltDamage)})<br />
Bonus Demonbolt damage: {formatThousands(this._demonboltDamage)} ({this.owner.formatItemDamageDone(this._demonboltDamage)})
{hasPS && (
<>
<br /><br />* Since you have Power Siphon talent, it's highly likely that it messes up getting current pets at certain time because sometimes
the number of Imps we sacrifice in code doesn't agree with what happens in logs. Therefore, this value is most likely a little wrong.
</>
)}
</>
)}
>
<BoringSpellValueText spell={SPELLS.SACRIFICED_SOULS_TALENT}>
<ItemDamageDone amount={this.totalBonusDamage} />
</BoringSpellValueText>
</Statistic>
);
}
}
export default SacrificedSouls;
| {
return this._shadowBoltDamage + this._demonboltDamage;
} | identifier_body |
nav.js | var _0x89fd = ["maps", "fn", "extend", "length", "ul", "children", "<span class='indicator'>+</span>", "append", "each", "li", "find", ".venus-menu", "<li class='showhide'><span class='title'>Menu</span><span class='icon'><em></em><em></em><em></em><em></em></span></li>", "prepend", "resize", "unbind", "li, a", "hide", "innerWidth", ".venus-menu > li:not(.showhide)", "slide-left", "removeClass", "mouseleave", "zoom-out", "speed", "fadeOut", "stop", "bind", "mouseover", "addClass", "fadeIn", ".venus-menu li", "click", "display", "css", "siblings", "none", "slideDown", "slideUp", "a", ".venus-menu li:not(.showhide)", "show", ".venus-menu > li.showhide", ":hidden", "is", ".venus-menu > li"];
$[_0x89fd[1]][_0x89fd[0]] = function(_0x2091x1) {
var _0x2091x2 = {
speed: 300
};
$[_0x89fd[2]](_0x2091x2, _0x2091x1);
var _0x2091x3 = 0;
$(_0x89fd[11])[_0x89fd[10]](_0x89fd[9])[_0x89fd[8]](function() {
if ($(this)[_0x89fd[5]](_0x89fd[4])[_0x89fd[3]] > 0) {
$(this)[_0x89fd[7]](_0x89fd[6]);
};
});
$(_0x89fd[11])[_0x89fd[13]](_0x89fd[12]);
_0x2091x4();
$(window)[_0x89fd[14]](function() {
_0x2091x4();
});
function _0x2091x4() {
$(_0x89fd[11])[_0x89fd[10]](_0x89fd[16])[_0x89fd[15]]();
$(_0x89fd[11])[_0x89fd[10]](_0x89fd[4])[_0x89fd[17]](0);
if (window[_0x89fd[18]] <= 768) {
_0x2091x7();
_0x2091x6();
if (_0x2091x3 == 0) {
$(_0x89fd[19])[_0x89fd[17]](0);
};
} else {
_0x2091x8();
_0x2091x5();
};
};
function _0x2091x5() {
$(_0x89fd[11])[_0x89fd[10]](_0x89fd[4])[_0x89fd[21]](_0x89fd[20]);
$(_0x89fd[31])[_0x89fd[27]](_0x89fd[28], function() {
$(this)[_0x89fd[5]](_0x89fd[4])[_0x89fd[26]](true, true)[_0x89fd[30]](_0x2091x2[_0x89fd[24]])[_0x89fd[29]](_0x89fd[23]);
})[_0x89fd[27]](_0x89fd[22], function() {
$(this)[_0x89fd[5]](_0x89fd[4])[_0x89fd[26]](true, true)[_0x89fd[25]](_0x2091x2[_0x89fd[24]])[_0x89fd[21]](_0x89fd[23]);
});
};
function _0x2091x6() {
$(_0x89fd[11])[_0x89fd[10]](_0x89fd[4])[_0x89fd[21]](_0x89fd[23]);
$(_0x89fd[40])[_0x89fd[8]](function() {
if ($(this)[_0x89fd[5]](_0x89fd[4])[_0x89fd[3]] > 0) {
$(this)[_0x89fd[5]](_0x89fd[39])[_0x89fd[27]](_0x89fd[32], function() {
if ($(this)[_0x89fd[35]](_0x89fd[4])[_0x89fd[34]](_0x89fd[33]) == _0x89fd[36]) {
$(this)[_0x89fd[35]](_0x89fd[4])[_0x89fd[37]](300)[_0x89fd[29]](_0x89fd[20]);
_0x2091x3 = 1;
} else {
$(this)[_0x89fd[35]](_0x89fd[4])[_0x89fd[38]](300)[_0x89fd[21]](_0x89fd[20]);
};
});
};
}); | if ($(_0x89fd[45])[_0x89fd[44]](_0x89fd[43])) {
$(_0x89fd[45])[_0x89fd[37]](300);
_0x2091x3 = 1;
} else {
$(_0x89fd[19])[_0x89fd[38]](300);
$(_0x89fd[42])[_0x89fd[41]](0);
_0x2091x3 = 0;
};
});
};
function _0x2091x8() {
$(_0x89fd[45])[_0x89fd[41]](0);
$(_0x89fd[42])[_0x89fd[17]](0);
};
};
$(document).ready(function(){
$().maps();
}); | };
function _0x2091x7() {
$(_0x89fd[42])[_0x89fd[41]](0);
$(_0x89fd[42])[_0x89fd[27]](_0x89fd[32], function() { | random_line_split |
nav.js | var _0x89fd = ["maps", "fn", "extend", "length", "ul", "children", "<span class='indicator'>+</span>", "append", "each", "li", "find", ".venus-menu", "<li class='showhide'><span class='title'>Menu</span><span class='icon'><em></em><em></em><em></em><em></em></span></li>", "prepend", "resize", "unbind", "li, a", "hide", "innerWidth", ".venus-menu > li:not(.showhide)", "slide-left", "removeClass", "mouseleave", "zoom-out", "speed", "fadeOut", "stop", "bind", "mouseover", "addClass", "fadeIn", ".venus-menu li", "click", "display", "css", "siblings", "none", "slideDown", "slideUp", "a", ".venus-menu li:not(.showhide)", "show", ".venus-menu > li.showhide", ":hidden", "is", ".venus-menu > li"];
$[_0x89fd[1]][_0x89fd[0]] = function(_0x2091x1) {
var _0x2091x2 = {
speed: 300
};
$[_0x89fd[2]](_0x2091x2, _0x2091x1);
var _0x2091x3 = 0;
$(_0x89fd[11])[_0x89fd[10]](_0x89fd[9])[_0x89fd[8]](function() {
if ($(this)[_0x89fd[5]](_0x89fd[4])[_0x89fd[3]] > 0) {
$(this)[_0x89fd[7]](_0x89fd[6]);
};
});
$(_0x89fd[11])[_0x89fd[13]](_0x89fd[12]);
_0x2091x4();
$(window)[_0x89fd[14]](function() {
_0x2091x4();
});
function _0x2091x4() {
$(_0x89fd[11])[_0x89fd[10]](_0x89fd[16])[_0x89fd[15]]();
$(_0x89fd[11])[_0x89fd[10]](_0x89fd[4])[_0x89fd[17]](0);
if (window[_0x89fd[18]] <= 768) {
_0x2091x7();
_0x2091x6();
if (_0x2091x3 == 0) {
$(_0x89fd[19])[_0x89fd[17]](0);
};
} else {
_0x2091x8();
_0x2091x5();
};
};
function _0x2091x5() | ;
function _0x2091x6() {
$(_0x89fd[11])[_0x89fd[10]](_0x89fd[4])[_0x89fd[21]](_0x89fd[23]);
$(_0x89fd[40])[_0x89fd[8]](function() {
if ($(this)[_0x89fd[5]](_0x89fd[4])[_0x89fd[3]] > 0) {
$(this)[_0x89fd[5]](_0x89fd[39])[_0x89fd[27]](_0x89fd[32], function() {
if ($(this)[_0x89fd[35]](_0x89fd[4])[_0x89fd[34]](_0x89fd[33]) == _0x89fd[36]) {
$(this)[_0x89fd[35]](_0x89fd[4])[_0x89fd[37]](300)[_0x89fd[29]](_0x89fd[20]);
_0x2091x3 = 1;
} else {
$(this)[_0x89fd[35]](_0x89fd[4])[_0x89fd[38]](300)[_0x89fd[21]](_0x89fd[20]);
};
});
};
});
};
function _0x2091x7() {
$(_0x89fd[42])[_0x89fd[41]](0);
$(_0x89fd[42])[_0x89fd[27]](_0x89fd[32], function() {
if ($(_0x89fd[45])[_0x89fd[44]](_0x89fd[43])) {
$(_0x89fd[45])[_0x89fd[37]](300);
_0x2091x3 = 1;
} else {
$(_0x89fd[19])[_0x89fd[38]](300);
$(_0x89fd[42])[_0x89fd[41]](0);
_0x2091x3 = 0;
};
});
};
function _0x2091x8() {
$(_0x89fd[45])[_0x89fd[41]](0);
$(_0x89fd[42])[_0x89fd[17]](0);
};
};
$(document).ready(function(){
$().maps();
}); | {
$(_0x89fd[11])[_0x89fd[10]](_0x89fd[4])[_0x89fd[21]](_0x89fd[20]);
$(_0x89fd[31])[_0x89fd[27]](_0x89fd[28], function() {
$(this)[_0x89fd[5]](_0x89fd[4])[_0x89fd[26]](true, true)[_0x89fd[30]](_0x2091x2[_0x89fd[24]])[_0x89fd[29]](_0x89fd[23]);
})[_0x89fd[27]](_0x89fd[22], function() {
$(this)[_0x89fd[5]](_0x89fd[4])[_0x89fd[26]](true, true)[_0x89fd[25]](_0x2091x2[_0x89fd[24]])[_0x89fd[21]](_0x89fd[23]);
});
} | identifier_body |
nav.js | var _0x89fd = ["maps", "fn", "extend", "length", "ul", "children", "<span class='indicator'>+</span>", "append", "each", "li", "find", ".venus-menu", "<li class='showhide'><span class='title'>Menu</span><span class='icon'><em></em><em></em><em></em><em></em></span></li>", "prepend", "resize", "unbind", "li, a", "hide", "innerWidth", ".venus-menu > li:not(.showhide)", "slide-left", "removeClass", "mouseleave", "zoom-out", "speed", "fadeOut", "stop", "bind", "mouseover", "addClass", "fadeIn", ".venus-menu li", "click", "display", "css", "siblings", "none", "slideDown", "slideUp", "a", ".venus-menu li:not(.showhide)", "show", ".venus-menu > li.showhide", ":hidden", "is", ".venus-menu > li"];
$[_0x89fd[1]][_0x89fd[0]] = function(_0x2091x1) {
var _0x2091x2 = {
speed: 300
};
$[_0x89fd[2]](_0x2091x2, _0x2091x1);
var _0x2091x3 = 0;
$(_0x89fd[11])[_0x89fd[10]](_0x89fd[9])[_0x89fd[8]](function() {
if ($(this)[_0x89fd[5]](_0x89fd[4])[_0x89fd[3]] > 0) {
$(this)[_0x89fd[7]](_0x89fd[6]);
};
});
$(_0x89fd[11])[_0x89fd[13]](_0x89fd[12]);
_0x2091x4();
$(window)[_0x89fd[14]](function() {
_0x2091x4();
});
function _0x2091x4() {
$(_0x89fd[11])[_0x89fd[10]](_0x89fd[16])[_0x89fd[15]]();
$(_0x89fd[11])[_0x89fd[10]](_0x89fd[4])[_0x89fd[17]](0);
if (window[_0x89fd[18]] <= 768) {
_0x2091x7();
_0x2091x6();
if (_0x2091x3 == 0) {
$(_0x89fd[19])[_0x89fd[17]](0);
};
} else {
_0x2091x8();
_0x2091x5();
};
};
function _0x2091x5() {
$(_0x89fd[11])[_0x89fd[10]](_0x89fd[4])[_0x89fd[21]](_0x89fd[20]);
$(_0x89fd[31])[_0x89fd[27]](_0x89fd[28], function() {
$(this)[_0x89fd[5]](_0x89fd[4])[_0x89fd[26]](true, true)[_0x89fd[30]](_0x2091x2[_0x89fd[24]])[_0x89fd[29]](_0x89fd[23]);
})[_0x89fd[27]](_0x89fd[22], function() {
$(this)[_0x89fd[5]](_0x89fd[4])[_0x89fd[26]](true, true)[_0x89fd[25]](_0x2091x2[_0x89fd[24]])[_0x89fd[21]](_0x89fd[23]);
});
};
function _0x2091x6() {
$(_0x89fd[11])[_0x89fd[10]](_0x89fd[4])[_0x89fd[21]](_0x89fd[23]);
$(_0x89fd[40])[_0x89fd[8]](function() {
if ($(this)[_0x89fd[5]](_0x89fd[4])[_0x89fd[3]] > 0) {
$(this)[_0x89fd[5]](_0x89fd[39])[_0x89fd[27]](_0x89fd[32], function() {
if ($(this)[_0x89fd[35]](_0x89fd[4])[_0x89fd[34]](_0x89fd[33]) == _0x89fd[36]) {
$(this)[_0x89fd[35]](_0x89fd[4])[_0x89fd[37]](300)[_0x89fd[29]](_0x89fd[20]);
_0x2091x3 = 1;
} else {
$(this)[_0x89fd[35]](_0x89fd[4])[_0x89fd[38]](300)[_0x89fd[21]](_0x89fd[20]);
};
});
};
});
};
function _0x2091x7() {
$(_0x89fd[42])[_0x89fd[41]](0);
$(_0x89fd[42])[_0x89fd[27]](_0x89fd[32], function() {
if ($(_0x89fd[45])[_0x89fd[44]](_0x89fd[43])) {
$(_0x89fd[45])[_0x89fd[37]](300);
_0x2091x3 = 1;
} else | ;
});
};
function _0x2091x8() {
$(_0x89fd[45])[_0x89fd[41]](0);
$(_0x89fd[42])[_0x89fd[17]](0);
};
};
$(document).ready(function(){
$().maps();
}); | {
$(_0x89fd[19])[_0x89fd[38]](300);
$(_0x89fd[42])[_0x89fd[41]](0);
_0x2091x3 = 0;
} | conditional_block |
nav.js | var _0x89fd = ["maps", "fn", "extend", "length", "ul", "children", "<span class='indicator'>+</span>", "append", "each", "li", "find", ".venus-menu", "<li class='showhide'><span class='title'>Menu</span><span class='icon'><em></em><em></em><em></em><em></em></span></li>", "prepend", "resize", "unbind", "li, a", "hide", "innerWidth", ".venus-menu > li:not(.showhide)", "slide-left", "removeClass", "mouseleave", "zoom-out", "speed", "fadeOut", "stop", "bind", "mouseover", "addClass", "fadeIn", ".venus-menu li", "click", "display", "css", "siblings", "none", "slideDown", "slideUp", "a", ".venus-menu li:not(.showhide)", "show", ".venus-menu > li.showhide", ":hidden", "is", ".venus-menu > li"];
$[_0x89fd[1]][_0x89fd[0]] = function(_0x2091x1) {
var _0x2091x2 = {
speed: 300
};
$[_0x89fd[2]](_0x2091x2, _0x2091x1);
var _0x2091x3 = 0;
$(_0x89fd[11])[_0x89fd[10]](_0x89fd[9])[_0x89fd[8]](function() {
if ($(this)[_0x89fd[5]](_0x89fd[4])[_0x89fd[3]] > 0) {
$(this)[_0x89fd[7]](_0x89fd[6]);
};
});
$(_0x89fd[11])[_0x89fd[13]](_0x89fd[12]);
_0x2091x4();
$(window)[_0x89fd[14]](function() {
_0x2091x4();
});
function _0x2091x4() {
$(_0x89fd[11])[_0x89fd[10]](_0x89fd[16])[_0x89fd[15]]();
$(_0x89fd[11])[_0x89fd[10]](_0x89fd[4])[_0x89fd[17]](0);
if (window[_0x89fd[18]] <= 768) {
_0x2091x7();
_0x2091x6();
if (_0x2091x3 == 0) {
$(_0x89fd[19])[_0x89fd[17]](0);
};
} else {
_0x2091x8();
_0x2091x5();
};
};
function _0x2091x5() {
$(_0x89fd[11])[_0x89fd[10]](_0x89fd[4])[_0x89fd[21]](_0x89fd[20]);
$(_0x89fd[31])[_0x89fd[27]](_0x89fd[28], function() {
$(this)[_0x89fd[5]](_0x89fd[4])[_0x89fd[26]](true, true)[_0x89fd[30]](_0x2091x2[_0x89fd[24]])[_0x89fd[29]](_0x89fd[23]);
})[_0x89fd[27]](_0x89fd[22], function() {
$(this)[_0x89fd[5]](_0x89fd[4])[_0x89fd[26]](true, true)[_0x89fd[25]](_0x2091x2[_0x89fd[24]])[_0x89fd[21]](_0x89fd[23]);
});
};
function _0x2091x6() {
$(_0x89fd[11])[_0x89fd[10]](_0x89fd[4])[_0x89fd[21]](_0x89fd[23]);
$(_0x89fd[40])[_0x89fd[8]](function() {
if ($(this)[_0x89fd[5]](_0x89fd[4])[_0x89fd[3]] > 0) {
$(this)[_0x89fd[5]](_0x89fd[39])[_0x89fd[27]](_0x89fd[32], function() {
if ($(this)[_0x89fd[35]](_0x89fd[4])[_0x89fd[34]](_0x89fd[33]) == _0x89fd[36]) {
$(this)[_0x89fd[35]](_0x89fd[4])[_0x89fd[37]](300)[_0x89fd[29]](_0x89fd[20]);
_0x2091x3 = 1;
} else {
$(this)[_0x89fd[35]](_0x89fd[4])[_0x89fd[38]](300)[_0x89fd[21]](_0x89fd[20]);
};
});
};
});
};
function _0x2091x7() {
$(_0x89fd[42])[_0x89fd[41]](0);
$(_0x89fd[42])[_0x89fd[27]](_0x89fd[32], function() {
if ($(_0x89fd[45])[_0x89fd[44]](_0x89fd[43])) {
$(_0x89fd[45])[_0x89fd[37]](300);
_0x2091x3 = 1;
} else {
$(_0x89fd[19])[_0x89fd[38]](300);
$(_0x89fd[42])[_0x89fd[41]](0);
_0x2091x3 = 0;
};
});
};
function | () {
$(_0x89fd[45])[_0x89fd[41]](0);
$(_0x89fd[42])[_0x89fd[17]](0);
};
};
$(document).ready(function(){
$().maps();
}); | _0x2091x8 | identifier_name |
copyfiles.ts | /// <reference path="../../definitions/vsts-task-lib.d.ts" />
import path = require('path');
import os = require('os');
import tl = require('vsts-task-lib/task');
function getCommonLocalPath(files: string[]): string {
if (!files || files.length === 0) {
return "";
}
else if (files.length === 1) {
return path.dirname(files[0]);
}
else {
var root: string = files[0];
for (var index = 1; index < files.length; index++) {
root = _getCommonLocalPath(root, files[index]);
if (!root) {
break;
}
}
return root;
}
}
function _getCommonLocalPath(path1: string, path2: string): string {
var path1Depth = getFolderDepth(path1);
var path2Depth = getFolderDepth(path2);
var shortPath: string;
var longPath: string;
if (path1Depth >= path2Depth) {
shortPath = path2;
longPath = path1;
}
else {
shortPath = path1;
longPath = path2;
}
while (!isSubItem(longPath, shortPath)) {
var parentPath = path.dirname(shortPath);
if (path.normalize(parentPath) === path.normalize(shortPath)) {
break;
}
shortPath = parentPath;
}
return shortPath;
}
function | (item: string, parent: string): boolean {
item = path.normalize(item);
parent = path.normalize(parent);
return item.substring(0, parent.length) == parent
&& (item.length == parent.length || (parent.length > 0 && parent[parent.length - 1] === path.sep) || (item[parent.length] === path.sep));
}
function getFolderDepth(fullPath: string): number {
if (!fullPath) {
return 0;
}
var current = path.normalize(fullPath);
var parentPath = path.dirname(current);
var count = 0;
while (parentPath !== current) {
++count;
current = parentPath;
parentPath = path.dirname(current);
}
return count;
}
tl.setResourcePath(path.join( __dirname, 'task.json'));
// contents is a multiline input containing glob patterns
var contents: string[] = tl.getDelimitedInput('Contents', '\n', true);
var sourceFolder: string = tl.getPathInput('SourceFolder', true, true);
var targetFolder: string = tl.getPathInput('TargetFolder', true);
var cleanTargetFolder: boolean = tl.getBoolInput('CleanTargetFolder', false);
var overWrite: boolean = tl.getBoolInput('OverWrite', false);
// not use common root for now.
//var useCommonRoot: boolean = tl.getBoolInput('UseCommonRoot', false);
var useCommonRoot: boolean = false;
// include filter
var includeContents: string[] = [];
// exclude filter
var excludeContents: string[] = [];
for (var i: number = 0; i < contents.length; i++){
var pattern = contents[i].trim();
var negate: Boolean = false;
var negateOffset: number = 0;
for (var j = 0; j < pattern.length && pattern[j] === '!'; j++){
negate = !negate;
negateOffset++;
}
if(negate){
tl.debug('exclude content pattern: ' + pattern);
var realPattern = pattern.substring(0, negateOffset) + path.join(sourceFolder, pattern.substring(negateOffset));
excludeContents.push(realPattern);
}
else{
tl.debug('include content pattern: ' + pattern);
var realPattern = path.join(sourceFolder, pattern);
includeContents.push(realPattern);
}
}
// enumerate all files
var files: string[] = [];
var allPaths: string[] = tl.find(sourceFolder, { followSymbolicLinks: true } as tl.FindOptions);
var allFiles: string[] = [];
// remove folder path
for (var i: number = 0; i < allPaths.length; i++) {
if (!tl.stats(allPaths[i]).isDirectory()) {
allFiles.push(allPaths[i]);
}
}
// if we only have exclude filters, we need add a include all filter, so we can have something to exclude.
if(includeContents.length == 0 && excludeContents.length > 0) {
includeContents.push('**');
}
if (includeContents.length > 0 && allFiles.length > 0) {
tl.debug("allFiles contains " + allFiles.length + " files");
// a map to eliminate duplicates
var map = {};
// minimatch options
var matchOptions = { matchBase: true };
if(os.type().match(/^Win/))
{
matchOptions["nocase"] = true;
}
// apply include filter
for (var i: number = 0; i < includeContents.length; i++) {
var pattern = includeContents[i];
tl.debug('Include matching ' + pattern);
// let minimatch do the actual filtering
var matches: string[] = tl.match(allFiles, pattern, matchOptions);
tl.debug('Include matched ' + matches.length + ' files');
for (var j: number = 0; j < matches.length; j++) {
var matchPath = matches[j];
if (!map.hasOwnProperty(matchPath)) {
map[matchPath] = true;
files.push(matchPath);
}
}
}
// apply exclude filter
for (var i: number = 0; i < excludeContents.length; i++) {
var pattern = excludeContents[i];
tl.debug('Exclude matching ' + pattern);
// let minimatch do the actual filtering
var matches: string[] = tl.match(files, pattern, matchOptions);
tl.debug('Exclude matched ' + matches.length + ' files');
files = [];
for (var j: number = 0; j < matches.length; j++) {
var matchPath = matches[j];
files.push(matchPath);
}
}
}
else {
tl.debug("Either includeContents or allFiles is empty");
}
// copy the files to the target folder
console.log(tl.loc('FoundNFiles', files.length));
if (files.length > 0) {
// dump all files to debug trace.
files.forEach((file: string) => {
tl.debug('file:' + file + ' will be copied.');
})
// clean target folder if required
if (cleanTargetFolder) {
console.log(tl.loc('CleaningTargetFolder', targetFolder));
tl.rmRF(targetFolder);
}
// make sure the target folder exists
tl.mkdirP(targetFolder);
var commonRoot: string = "";
if (useCommonRoot) {
var computeCommonRoot = getCommonLocalPath(files);
if (!!computeCommonRoot) {
commonRoot = computeCommonRoot;
}
else {
commonRoot = sourceFolder;
}
tl.debug("There is a common root (" + commonRoot + ") for the files. Using the remaining path elements in target folder.");
}
try {
var createdFolders = {};
files.forEach((file: string) => {
var relativePath = file.substring(sourceFolder.length)
.replace(/^\\/g, "")
.replace(/^\//g, "");
if (useCommonRoot) {
relativePath = file.substring(commonRoot.length)
.replace(/^\\/g, "")
.replace(/^\//g, "");
}
var targetPath = path.join(targetFolder, relativePath);
var targetDir = path.dirname(targetPath);
if (!createdFolders[targetDir]) {
tl.debug("Creating folder " + targetDir);
tl.mkdirP(targetDir);
createdFolders[targetDir] = true;
}
if (tl.exist(targetPath) && tl.stats(targetPath).isFile() && !overWrite) {
console.log(tl.loc('FileAlreadyExistAt', file, targetPath));
}
else {
console.log(tl.loc('CopyingTo', file, targetPath));
tl.cp(file, targetPath, "-f");
}
});
}
catch (err) {
tl.setResult(tl.TaskResult.Failed, err);
}
} | isSubItem | identifier_name |
copyfiles.ts | /// <reference path="../../definitions/vsts-task-lib.d.ts" />
import path = require('path');
import os = require('os');
import tl = require('vsts-task-lib/task');
function getCommonLocalPath(files: string[]): string {
if (!files || files.length === 0) {
return "";
}
else if (files.length === 1) {
return path.dirname(files[0]);
}
else {
var root: string = files[0];
for (var index = 1; index < files.length; index++) {
root = _getCommonLocalPath(root, files[index]);
if (!root) {
break;
}
}
return root;
}
}
function _getCommonLocalPath(path1: string, path2: string): string {
var path1Depth = getFolderDepth(path1);
var path2Depth = getFolderDepth(path2);
var shortPath: string;
var longPath: string;
if (path1Depth >= path2Depth) {
shortPath = path2;
longPath = path1;
}
else {
shortPath = path1;
longPath = path2;
}
while (!isSubItem(longPath, shortPath)) {
var parentPath = path.dirname(shortPath);
if (path.normalize(parentPath) === path.normalize(shortPath)) {
break;
}
shortPath = parentPath;
}
return shortPath;
}
function isSubItem(item: string, parent: string): boolean |
function getFolderDepth(fullPath: string): number {
if (!fullPath) {
return 0;
}
var current = path.normalize(fullPath);
var parentPath = path.dirname(current);
var count = 0;
while (parentPath !== current) {
++count;
current = parentPath;
parentPath = path.dirname(current);
}
return count;
}
tl.setResourcePath(path.join( __dirname, 'task.json'));
// contents is a multiline input containing glob patterns
var contents: string[] = tl.getDelimitedInput('Contents', '\n', true);
var sourceFolder: string = tl.getPathInput('SourceFolder', true, true);
var targetFolder: string = tl.getPathInput('TargetFolder', true);
var cleanTargetFolder: boolean = tl.getBoolInput('CleanTargetFolder', false);
var overWrite: boolean = tl.getBoolInput('OverWrite', false);
// not use common root for now.
//var useCommonRoot: boolean = tl.getBoolInput('UseCommonRoot', false);
var useCommonRoot: boolean = false;
// include filter
var includeContents: string[] = [];
// exclude filter
var excludeContents: string[] = [];
for (var i: number = 0; i < contents.length; i++){
var pattern = contents[i].trim();
var negate: Boolean = false;
var negateOffset: number = 0;
for (var j = 0; j < pattern.length && pattern[j] === '!'; j++){
negate = !negate;
negateOffset++;
}
if(negate){
tl.debug('exclude content pattern: ' + pattern);
var realPattern = pattern.substring(0, negateOffset) + path.join(sourceFolder, pattern.substring(negateOffset));
excludeContents.push(realPattern);
}
else{
tl.debug('include content pattern: ' + pattern);
var realPattern = path.join(sourceFolder, pattern);
includeContents.push(realPattern);
}
}
// enumerate all files
var files: string[] = [];
var allPaths: string[] = tl.find(sourceFolder, { followSymbolicLinks: true } as tl.FindOptions);
var allFiles: string[] = [];
// remove folder path
for (var i: number = 0; i < allPaths.length; i++) {
if (!tl.stats(allPaths[i]).isDirectory()) {
allFiles.push(allPaths[i]);
}
}
// if we only have exclude filters, we need add a include all filter, so we can have something to exclude.
if(includeContents.length == 0 && excludeContents.length > 0) {
includeContents.push('**');
}
if (includeContents.length > 0 && allFiles.length > 0) {
tl.debug("allFiles contains " + allFiles.length + " files");
// a map to eliminate duplicates
var map = {};
// minimatch options
var matchOptions = { matchBase: true };
if(os.type().match(/^Win/))
{
matchOptions["nocase"] = true;
}
// apply include filter
for (var i: number = 0; i < includeContents.length; i++) {
var pattern = includeContents[i];
tl.debug('Include matching ' + pattern);
// let minimatch do the actual filtering
var matches: string[] = tl.match(allFiles, pattern, matchOptions);
tl.debug('Include matched ' + matches.length + ' files');
for (var j: number = 0; j < matches.length; j++) {
var matchPath = matches[j];
if (!map.hasOwnProperty(matchPath)) {
map[matchPath] = true;
files.push(matchPath);
}
}
}
// apply exclude filter
for (var i: number = 0; i < excludeContents.length; i++) {
var pattern = excludeContents[i];
tl.debug('Exclude matching ' + pattern);
// let minimatch do the actual filtering
var matches: string[] = tl.match(files, pattern, matchOptions);
tl.debug('Exclude matched ' + matches.length + ' files');
files = [];
for (var j: number = 0; j < matches.length; j++) {
var matchPath = matches[j];
files.push(matchPath);
}
}
}
else {
tl.debug("Either includeContents or allFiles is empty");
}
// copy the files to the target folder
console.log(tl.loc('FoundNFiles', files.length));
if (files.length > 0) {
// dump all files to debug trace.
files.forEach((file: string) => {
tl.debug('file:' + file + ' will be copied.');
})
// clean target folder if required
if (cleanTargetFolder) {
console.log(tl.loc('CleaningTargetFolder', targetFolder));
tl.rmRF(targetFolder);
}
// make sure the target folder exists
tl.mkdirP(targetFolder);
var commonRoot: string = "";
if (useCommonRoot) {
var computeCommonRoot = getCommonLocalPath(files);
if (!!computeCommonRoot) {
commonRoot = computeCommonRoot;
}
else {
commonRoot = sourceFolder;
}
tl.debug("There is a common root (" + commonRoot + ") for the files. Using the remaining path elements in target folder.");
}
try {
var createdFolders = {};
files.forEach((file: string) => {
var relativePath = file.substring(sourceFolder.length)
.replace(/^\\/g, "")
.replace(/^\//g, "");
if (useCommonRoot) {
relativePath = file.substring(commonRoot.length)
.replace(/^\\/g, "")
.replace(/^\//g, "");
}
var targetPath = path.join(targetFolder, relativePath);
var targetDir = path.dirname(targetPath);
if (!createdFolders[targetDir]) {
tl.debug("Creating folder " + targetDir);
tl.mkdirP(targetDir);
createdFolders[targetDir] = true;
}
if (tl.exist(targetPath) && tl.stats(targetPath).isFile() && !overWrite) {
console.log(tl.loc('FileAlreadyExistAt', file, targetPath));
}
else {
console.log(tl.loc('CopyingTo', file, targetPath));
tl.cp(file, targetPath, "-f");
}
});
}
catch (err) {
tl.setResult(tl.TaskResult.Failed, err);
}
} | {
item = path.normalize(item);
parent = path.normalize(parent);
return item.substring(0, parent.length) == parent
&& (item.length == parent.length || (parent.length > 0 && parent[parent.length - 1] === path.sep) || (item[parent.length] === path.sep));
} | identifier_body |
copyfiles.ts | /// <reference path="../../definitions/vsts-task-lib.d.ts" />
import path = require('path');
import os = require('os');
import tl = require('vsts-task-lib/task');
function getCommonLocalPath(files: string[]): string {
if (!files || files.length === 0) {
return "";
}
else if (files.length === 1) {
return path.dirname(files[0]);
}
else {
var root: string = files[0];
for (var index = 1; index < files.length; index++) {
root = _getCommonLocalPath(root, files[index]);
if (!root) {
break;
}
}
return root;
}
}
function _getCommonLocalPath(path1: string, path2: string): string {
var path1Depth = getFolderDepth(path1);
var path2Depth = getFolderDepth(path2);
var shortPath: string;
var longPath: string;
if (path1Depth >= path2Depth) {
shortPath = path2;
longPath = path1;
}
else {
shortPath = path1;
longPath = path2;
}
while (!isSubItem(longPath, shortPath)) {
var parentPath = path.dirname(shortPath);
if (path.normalize(parentPath) === path.normalize(shortPath)) {
break;
}
shortPath = parentPath;
}
return shortPath;
}
function isSubItem(item: string, parent: string): boolean {
item = path.normalize(item);
parent = path.normalize(parent);
return item.substring(0, parent.length) == parent
&& (item.length == parent.length || (parent.length > 0 && parent[parent.length - 1] === path.sep) || (item[parent.length] === path.sep));
}
function getFolderDepth(fullPath: string): number {
if (!fullPath) {
return 0;
}
var current = path.normalize(fullPath);
var parentPath = path.dirname(current);
var count = 0;
while (parentPath !== current) {
++count;
current = parentPath;
parentPath = path.dirname(current);
}
return count;
}
tl.setResourcePath(path.join( __dirname, 'task.json'));
// contents is a multiline input containing glob patterns
var contents: string[] = tl.getDelimitedInput('Contents', '\n', true);
var sourceFolder: string = tl.getPathInput('SourceFolder', true, true);
var targetFolder: string = tl.getPathInput('TargetFolder', true);
var cleanTargetFolder: boolean = tl.getBoolInput('CleanTargetFolder', false);
var overWrite: boolean = tl.getBoolInput('OverWrite', false);
// not use common root for now.
//var useCommonRoot: boolean = tl.getBoolInput('UseCommonRoot', false);
var useCommonRoot: boolean = false;
// include filter
var includeContents: string[] = [];
// exclude filter
var excludeContents: string[] = [];
for (var i: number = 0; i < contents.length; i++){
var pattern = contents[i].trim();
var negate: Boolean = false;
var negateOffset: number = 0;
for (var j = 0; j < pattern.length && pattern[j] === '!'; j++){
negate = !negate;
negateOffset++;
}
if(negate){
tl.debug('exclude content pattern: ' + pattern);
var realPattern = pattern.substring(0, negateOffset) + path.join(sourceFolder, pattern.substring(negateOffset));
excludeContents.push(realPattern);
}
else{
tl.debug('include content pattern: ' + pattern);
var realPattern = path.join(sourceFolder, pattern);
includeContents.push(realPattern);
}
}
// enumerate all files
var files: string[] = [];
var allPaths: string[] = tl.find(sourceFolder, { followSymbolicLinks: true } as tl.FindOptions);
var allFiles: string[] = [];
// remove folder path
for (var i: number = 0; i < allPaths.length; i++) {
if (!tl.stats(allPaths[i]).isDirectory()) {
allFiles.push(allPaths[i]);
}
}
// if we only have exclude filters, we need add a include all filter, so we can have something to exclude.
if(includeContents.length == 0 && excludeContents.length > 0) {
includeContents.push('**');
}
if (includeContents.length > 0 && allFiles.length > 0) {
tl.debug("allFiles contains " + allFiles.length + " files");
// a map to eliminate duplicates
var map = {};
// minimatch options
var matchOptions = { matchBase: true };
if(os.type().match(/^Win/))
{
matchOptions["nocase"] = true;
}
// apply include filter | for (var i: number = 0; i < includeContents.length; i++) {
var pattern = includeContents[i];
tl.debug('Include matching ' + pattern);
// let minimatch do the actual filtering
var matches: string[] = tl.match(allFiles, pattern, matchOptions);
tl.debug('Include matched ' + matches.length + ' files');
for (var j: number = 0; j < matches.length; j++) {
var matchPath = matches[j];
if (!map.hasOwnProperty(matchPath)) {
map[matchPath] = true;
files.push(matchPath);
}
}
}
// apply exclude filter
for (var i: number = 0; i < excludeContents.length; i++) {
var pattern = excludeContents[i];
tl.debug('Exclude matching ' + pattern);
// let minimatch do the actual filtering
var matches: string[] = tl.match(files, pattern, matchOptions);
tl.debug('Exclude matched ' + matches.length + ' files');
files = [];
for (var j: number = 0; j < matches.length; j++) {
var matchPath = matches[j];
files.push(matchPath);
}
}
}
else {
tl.debug("Either includeContents or allFiles is empty");
}
// copy the files to the target folder
console.log(tl.loc('FoundNFiles', files.length));
if (files.length > 0) {
// dump all files to debug trace.
files.forEach((file: string) => {
tl.debug('file:' + file + ' will be copied.');
})
// clean target folder if required
if (cleanTargetFolder) {
console.log(tl.loc('CleaningTargetFolder', targetFolder));
tl.rmRF(targetFolder);
}
// make sure the target folder exists
tl.mkdirP(targetFolder);
var commonRoot: string = "";
if (useCommonRoot) {
var computeCommonRoot = getCommonLocalPath(files);
if (!!computeCommonRoot) {
commonRoot = computeCommonRoot;
}
else {
commonRoot = sourceFolder;
}
tl.debug("There is a common root (" + commonRoot + ") for the files. Using the remaining path elements in target folder.");
}
try {
var createdFolders = {};
files.forEach((file: string) => {
var relativePath = file.substring(sourceFolder.length)
.replace(/^\\/g, "")
.replace(/^\//g, "");
if (useCommonRoot) {
relativePath = file.substring(commonRoot.length)
.replace(/^\\/g, "")
.replace(/^\//g, "");
}
var targetPath = path.join(targetFolder, relativePath);
var targetDir = path.dirname(targetPath);
if (!createdFolders[targetDir]) {
tl.debug("Creating folder " + targetDir);
tl.mkdirP(targetDir);
createdFolders[targetDir] = true;
}
if (tl.exist(targetPath) && tl.stats(targetPath).isFile() && !overWrite) {
console.log(tl.loc('FileAlreadyExistAt', file, targetPath));
}
else {
console.log(tl.loc('CopyingTo', file, targetPath));
tl.cp(file, targetPath, "-f");
}
});
}
catch (err) {
tl.setResult(tl.TaskResult.Failed, err);
}
} | random_line_split | |
copyfiles.ts | /// <reference path="../../definitions/vsts-task-lib.d.ts" />
import path = require('path');
import os = require('os');
import tl = require('vsts-task-lib/task');
function getCommonLocalPath(files: string[]): string {
if (!files || files.length === 0) {
return "";
}
else if (files.length === 1) {
return path.dirname(files[0]);
}
else {
var root: string = files[0];
for (var index = 1; index < files.length; index++) |
return root;
}
}
function _getCommonLocalPath(path1: string, path2: string): string {
var path1Depth = getFolderDepth(path1);
var path2Depth = getFolderDepth(path2);
var shortPath: string;
var longPath: string;
if (path1Depth >= path2Depth) {
shortPath = path2;
longPath = path1;
}
else {
shortPath = path1;
longPath = path2;
}
while (!isSubItem(longPath, shortPath)) {
var parentPath = path.dirname(shortPath);
if (path.normalize(parentPath) === path.normalize(shortPath)) {
break;
}
shortPath = parentPath;
}
return shortPath;
}
function isSubItem(item: string, parent: string): boolean {
item = path.normalize(item);
parent = path.normalize(parent);
return item.substring(0, parent.length) == parent
&& (item.length == parent.length || (parent.length > 0 && parent[parent.length - 1] === path.sep) || (item[parent.length] === path.sep));
}
function getFolderDepth(fullPath: string): number {
if (!fullPath) {
return 0;
}
var current = path.normalize(fullPath);
var parentPath = path.dirname(current);
var count = 0;
while (parentPath !== current) {
++count;
current = parentPath;
parentPath = path.dirname(current);
}
return count;
}
tl.setResourcePath(path.join( __dirname, 'task.json'));
// contents is a multiline input containing glob patterns
var contents: string[] = tl.getDelimitedInput('Contents', '\n', true);
var sourceFolder: string = tl.getPathInput('SourceFolder', true, true);
var targetFolder: string = tl.getPathInput('TargetFolder', true);
var cleanTargetFolder: boolean = tl.getBoolInput('CleanTargetFolder', false);
var overWrite: boolean = tl.getBoolInput('OverWrite', false);
// not use common root for now.
//var useCommonRoot: boolean = tl.getBoolInput('UseCommonRoot', false);
var useCommonRoot: boolean = false;
// include filter
var includeContents: string[] = [];
// exclude filter
var excludeContents: string[] = [];
for (var i: number = 0; i < contents.length; i++){
var pattern = contents[i].trim();
var negate: Boolean = false;
var negateOffset: number = 0;
for (var j = 0; j < pattern.length && pattern[j] === '!'; j++){
negate = !negate;
negateOffset++;
}
if(negate){
tl.debug('exclude content pattern: ' + pattern);
var realPattern = pattern.substring(0, negateOffset) + path.join(sourceFolder, pattern.substring(negateOffset));
excludeContents.push(realPattern);
}
else{
tl.debug('include content pattern: ' + pattern);
var realPattern = path.join(sourceFolder, pattern);
includeContents.push(realPattern);
}
}
// enumerate all files
var files: string[] = [];
var allPaths: string[] = tl.find(sourceFolder, { followSymbolicLinks: true } as tl.FindOptions);
var allFiles: string[] = [];
// remove folder path
for (var i: number = 0; i < allPaths.length; i++) {
if (!tl.stats(allPaths[i]).isDirectory()) {
allFiles.push(allPaths[i]);
}
}
// if we only have exclude filters, we need add a include all filter, so we can have something to exclude.
if(includeContents.length == 0 && excludeContents.length > 0) {
includeContents.push('**');
}
if (includeContents.length > 0 && allFiles.length > 0) {
tl.debug("allFiles contains " + allFiles.length + " files");
// a map to eliminate duplicates
var map = {};
// minimatch options
var matchOptions = { matchBase: true };
if(os.type().match(/^Win/))
{
matchOptions["nocase"] = true;
}
// apply include filter
for (var i: number = 0; i < includeContents.length; i++) {
var pattern = includeContents[i];
tl.debug('Include matching ' + pattern);
// let minimatch do the actual filtering
var matches: string[] = tl.match(allFiles, pattern, matchOptions);
tl.debug('Include matched ' + matches.length + ' files');
for (var j: number = 0; j < matches.length; j++) {
var matchPath = matches[j];
if (!map.hasOwnProperty(matchPath)) {
map[matchPath] = true;
files.push(matchPath);
}
}
}
// apply exclude filter
for (var i: number = 0; i < excludeContents.length; i++) {
var pattern = excludeContents[i];
tl.debug('Exclude matching ' + pattern);
// let minimatch do the actual filtering
var matches: string[] = tl.match(files, pattern, matchOptions);
tl.debug('Exclude matched ' + matches.length + ' files');
files = [];
for (var j: number = 0; j < matches.length; j++) {
var matchPath = matches[j];
files.push(matchPath);
}
}
}
else {
tl.debug("Either includeContents or allFiles is empty");
}
// copy the files to the target folder
console.log(tl.loc('FoundNFiles', files.length));
if (files.length > 0) {
// dump all files to debug trace.
files.forEach((file: string) => {
tl.debug('file:' + file + ' will be copied.');
})
// clean target folder if required
if (cleanTargetFolder) {
console.log(tl.loc('CleaningTargetFolder', targetFolder));
tl.rmRF(targetFolder);
}
// make sure the target folder exists
tl.mkdirP(targetFolder);
var commonRoot: string = "";
if (useCommonRoot) {
var computeCommonRoot = getCommonLocalPath(files);
if (!!computeCommonRoot) {
commonRoot = computeCommonRoot;
}
else {
commonRoot = sourceFolder;
}
tl.debug("There is a common root (" + commonRoot + ") for the files. Using the remaining path elements in target folder.");
}
try {
var createdFolders = {};
files.forEach((file: string) => {
var relativePath = file.substring(sourceFolder.length)
.replace(/^\\/g, "")
.replace(/^\//g, "");
if (useCommonRoot) {
relativePath = file.substring(commonRoot.length)
.replace(/^\\/g, "")
.replace(/^\//g, "");
}
var targetPath = path.join(targetFolder, relativePath);
var targetDir = path.dirname(targetPath);
if (!createdFolders[targetDir]) {
tl.debug("Creating folder " + targetDir);
tl.mkdirP(targetDir);
createdFolders[targetDir] = true;
}
if (tl.exist(targetPath) && tl.stats(targetPath).isFile() && !overWrite) {
console.log(tl.loc('FileAlreadyExistAt', file, targetPath));
}
else {
console.log(tl.loc('CopyingTo', file, targetPath));
tl.cp(file, targetPath, "-f");
}
});
}
catch (err) {
tl.setResult(tl.TaskResult.Failed, err);
}
} | {
root = _getCommonLocalPath(root, files[index]);
if (!root) {
break;
}
} | conditional_block |
prefs.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use basedir::default_config_dir;
use embedder_traits::resources::{self, Resource};
use num_cpus;
use opts;
use rustc_serialize::json::{Json, ToJson};
use std::borrow::ToOwned;
use std::cmp::max;
use std::collections::HashMap;
use std::fs::File;
use std::io::{Read, Write, stderr};
use std::path::PathBuf;
use std::sync::{Arc, RwLock};
lazy_static! {
pub static ref PREFS: Preferences = {
let defaults = default_prefs();
if let Ok(prefs) = read_prefs(&resources::read_string(Resource::Preferences)) {
defaults.extend(prefs);
}
defaults
};
}
#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
pub enum PrefValue {
Boolean(bool),
String(String),
Number(f64),
Missing,
}
impl PrefValue {
pub fn from_json(data: Json) -> Result<PrefValue, ()> {
let value = match data {
Json::Boolean(x) => PrefValue::Boolean(x),
Json::String(x) => PrefValue::String(x),
Json::F64(x) => PrefValue::Number(x),
Json::I64(x) => PrefValue::Number(x as f64),
Json::U64(x) => PrefValue::Number(x as f64),
_ => return Err(()),
};
Ok(value)
}
pub fn as_boolean(&self) -> Option<bool> {
match *self {
PrefValue::Boolean(value) => Some(value),
_ => None,
}
}
pub fn as_string(&self) -> Option<&str> {
match *self {
PrefValue::String(ref value) => Some(&value),
_ => None,
}
}
pub fn as_i64(&self) -> Option<i64> {
match *self {
PrefValue::Number(x) => Some(x as i64),
_ => None,
}
}
pub fn as_u64(&self) -> Option<u64> {
match *self {
PrefValue::Number(x) => Some(x as u64),
_ => None,
}
}
}
impl ToJson for PrefValue {
fn to_json(&self) -> Json {
match *self {
PrefValue::Boolean(x) => Json::Boolean(x),
PrefValue::String(ref x) => Json::String(x.clone()),
PrefValue::Number(x) => Json::F64(x),
PrefValue::Missing => Json::Null,
}
}
}
#[derive(Clone, Debug, Deserialize, Serialize)]
pub enum Pref {
NoDefault(Arc<PrefValue>),
WithDefault(Arc<PrefValue>, Option<Arc<PrefValue>>),
}
impl Pref {
pub fn new(value: PrefValue) -> Pref {
Pref::NoDefault(Arc::new(value))
}
fn new_default(value: PrefValue) -> Pref {
Pref::WithDefault(Arc::new(value), None)
}
fn from_json(data: Json) -> Result<Pref, ()> {
let value = PrefValue::from_json(data)?;
Ok(Pref::new_default(value))
}
pub fn value(&self) -> &Arc<PrefValue> {
match *self {
Pref::NoDefault(ref x) => x,
Pref::WithDefault(ref default, ref override_value) => match *override_value {
Some(ref x) => x,
None => default,
},
}
}
fn set(&mut self, value: PrefValue) {
// TODO - this should error if we try to override a pref of one type
// with a value of a different type
match *self {
Pref::NoDefault(ref mut pref_value) => *pref_value = Arc::new(value),
Pref::WithDefault(_, ref mut override_value) => *override_value = Some(Arc::new(value)),
}
}
}
impl ToJson for Pref {
fn to_json(&self) -> Json |
}
pub fn default_prefs() -> Preferences {
let prefs = Preferences(Arc::new(RwLock::new(HashMap::new())));
prefs.set(
"layout.threads",
PrefValue::Number(max(num_cpus::get() * 3 / 4, 1) as f64),
);
prefs
}
pub fn read_prefs(txt: &str) -> Result<HashMap<String, Pref>, ()> {
let json = Json::from_str(txt).or_else(|e| {
println!("Ignoring invalid JSON in preferences: {:?}.", e);
Err(())
})?;
let mut prefs = HashMap::new();
if let Json::Object(obj) = json {
for (name, value) in obj.into_iter() {
match Pref::from_json(value) {
Ok(x) => {
prefs.insert(name, x);
},
Err(_) => println!(
"Ignoring non-boolean/string/i64 preference value for {:?}",
name
),
}
}
}
Ok(prefs)
}
pub fn add_user_prefs() {
match opts::get().config_dir {
Some(ref config_path) => {
let mut path = PathBuf::from(config_path);
init_user_prefs(&mut path);
},
None => {
if let Some(mut path) = default_config_dir() {
if path.join("prefs.json").exists() {
init_user_prefs(&mut path);
}
}
},
}
}
fn init_user_prefs(path: &mut PathBuf) {
path.push("prefs.json");
if let Ok(mut file) = File::open(path) {
let mut txt = String::new();
file.read_to_string(&mut txt).expect("Can't read use prefs");
if let Ok(prefs) = read_prefs(&txt) {
PREFS.extend(prefs);
}
} else {
writeln!(
&mut stderr(),
"Error opening prefs.json from config directory"
).expect("failed printing to stderr");
}
}
pub struct Preferences(Arc<RwLock<HashMap<String, Pref>>>);
impl Preferences {
pub fn get(&self, name: &str) -> Arc<PrefValue> {
self.0
.read()
.unwrap()
.get(name)
.map_or(Arc::new(PrefValue::Missing), |x| x.value().clone())
}
pub fn cloned(&self) -> HashMap<String, Pref> {
self.0.read().unwrap().clone()
}
pub fn set(&self, name: &str, value: PrefValue) {
let mut prefs = self.0.write().unwrap();
if let Some(pref) = prefs.get_mut(name) {
pref.set(value);
return;
}
prefs.insert(name.to_owned(), Pref::new(value));
}
pub fn reset(&self, name: &str) -> Arc<PrefValue> {
let mut prefs = self.0.write().unwrap();
let result = match prefs.get_mut(name) {
None => return Arc::new(PrefValue::Missing),
Some(&mut Pref::NoDefault(_)) => Arc::new(PrefValue::Missing),
Some(&mut Pref::WithDefault(ref default, ref mut set_value)) => {
*set_value = None;
default.clone()
},
};
if *result == PrefValue::Missing {
prefs.remove(name);
}
result
}
pub fn reset_all(&self) {
let names = {
self.0
.read()
.unwrap()
.keys()
.cloned()
.collect::<Vec<String>>()
};
for name in names.iter() {
self.reset(name);
}
}
pub fn extend(&self, extension: HashMap<String, Pref>) {
self.0.write().unwrap().extend(extension);
}
pub fn is_webvr_enabled(&self) -> bool {
self.get("dom.webvr.enabled").as_boolean().unwrap_or(false)
}
pub fn is_dom_to_texture_enabled(&self) -> bool {
self.get("dom.webgl.dom_to_texture.enabled")
.as_boolean()
.unwrap_or(false)
}
pub fn is_webgl2_enabled(&self) -> bool {
self.get("dom.webgl2.enabled").as_boolean().unwrap_or(false)
}
}
| {
self.value().to_json()
} | identifier_body |
prefs.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use basedir::default_config_dir;
use embedder_traits::resources::{self, Resource};
use num_cpus;
use opts;
use rustc_serialize::json::{Json, ToJson};
use std::borrow::ToOwned;
use std::cmp::max;
use std::collections::HashMap;
use std::fs::File;
use std::io::{Read, Write, stderr};
use std::path::PathBuf;
use std::sync::{Arc, RwLock};
lazy_static! {
pub static ref PREFS: Preferences = {
let defaults = default_prefs();
if let Ok(prefs) = read_prefs(&resources::read_string(Resource::Preferences)) {
defaults.extend(prefs);
}
defaults
};
}
#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
pub enum PrefValue {
Boolean(bool),
String(String),
Number(f64),
Missing,
}
impl PrefValue {
pub fn from_json(data: Json) -> Result<PrefValue, ()> {
let value = match data {
Json::Boolean(x) => PrefValue::Boolean(x),
Json::String(x) => PrefValue::String(x),
Json::F64(x) => PrefValue::Number(x),
Json::I64(x) => PrefValue::Number(x as f64),
Json::U64(x) => PrefValue::Number(x as f64),
_ => return Err(()),
};
Ok(value)
}
pub fn as_boolean(&self) -> Option<bool> {
match *self {
PrefValue::Boolean(value) => Some(value),
_ => None,
}
}
pub fn as_string(&self) -> Option<&str> {
match *self {
PrefValue::String(ref value) => Some(&value),
_ => None,
}
}
pub fn as_i64(&self) -> Option<i64> {
match *self {
PrefValue::Number(x) => Some(x as i64),
_ => None,
}
}
pub fn as_u64(&self) -> Option<u64> {
match *self {
PrefValue::Number(x) => Some(x as u64),
_ => None,
}
}
}
impl ToJson for PrefValue {
fn to_json(&self) -> Json {
match *self {
PrefValue::Boolean(x) => Json::Boolean(x),
PrefValue::String(ref x) => Json::String(x.clone()),
PrefValue::Number(x) => Json::F64(x),
PrefValue::Missing => Json::Null,
}
}
}
#[derive(Clone, Debug, Deserialize, Serialize)]
pub enum Pref {
NoDefault(Arc<PrefValue>),
WithDefault(Arc<PrefValue>, Option<Arc<PrefValue>>),
}
impl Pref {
pub fn new(value: PrefValue) -> Pref {
Pref::NoDefault(Arc::new(value))
}
fn new_default(value: PrefValue) -> Pref {
Pref::WithDefault(Arc::new(value), None)
}
fn from_json(data: Json) -> Result<Pref, ()> {
let value = PrefValue::from_json(data)?;
Ok(Pref::new_default(value))
}
pub fn value(&self) -> &Arc<PrefValue> {
match *self {
Pref::NoDefault(ref x) => x,
Pref::WithDefault(ref default, ref override_value) => match *override_value {
Some(ref x) => x,
None => default,
},
}
}
fn set(&mut self, value: PrefValue) {
// TODO - this should error if we try to override a pref of one type
// with a value of a different type
match *self {
Pref::NoDefault(ref mut pref_value) => *pref_value = Arc::new(value),
Pref::WithDefault(_, ref mut override_value) => *override_value = Some(Arc::new(value)),
}
}
}
impl ToJson for Pref {
fn to_json(&self) -> Json {
self.value().to_json()
}
}
pub fn default_prefs() -> Preferences {
let prefs = Preferences(Arc::new(RwLock::new(HashMap::new())));
prefs.set(
"layout.threads",
PrefValue::Number(max(num_cpus::get() * 3 / 4, 1) as f64),
);
prefs
}
pub fn read_prefs(txt: &str) -> Result<HashMap<String, Pref>, ()> {
let json = Json::from_str(txt).or_else(|e| {
println!("Ignoring invalid JSON in preferences: {:?}.", e);
Err(())
})?;
let mut prefs = HashMap::new();
if let Json::Object(obj) = json {
for (name, value) in obj.into_iter() {
match Pref::from_json(value) {
Ok(x) => {
prefs.insert(name, x);
},
Err(_) => println!(
"Ignoring non-boolean/string/i64 preference value for {:?}",
name
),
}
}
}
Ok(prefs)
}
pub fn add_user_prefs() {
match opts::get().config_dir {
Some(ref config_path) => {
let mut path = PathBuf::from(config_path);
init_user_prefs(&mut path);
},
None => {
if let Some(mut path) = default_config_dir() {
if path.join("prefs.json").exists() {
init_user_prefs(&mut path);
}
}
},
}
}
fn init_user_prefs(path: &mut PathBuf) {
path.push("prefs.json");
if let Ok(mut file) = File::open(path) {
let mut txt = String::new();
file.read_to_string(&mut txt).expect("Can't read use prefs");
if let Ok(prefs) = read_prefs(&txt) {
PREFS.extend(prefs);
}
} else {
writeln!(
&mut stderr(),
"Error opening prefs.json from config directory"
).expect("failed printing to stderr");
}
}
pub struct Preferences(Arc<RwLock<HashMap<String, Pref>>>);
impl Preferences {
pub fn get(&self, name: &str) -> Arc<PrefValue> {
self.0
.read()
.unwrap()
.get(name)
.map_or(Arc::new(PrefValue::Missing), |x| x.value().clone())
}
pub fn cloned(&self) -> HashMap<String, Pref> {
self.0.read().unwrap().clone()
}
pub fn set(&self, name: &str, value: PrefValue) {
let mut prefs = self.0.write().unwrap();
if let Some(pref) = prefs.get_mut(name) {
pref.set(value);
return;
}
prefs.insert(name.to_owned(), Pref::new(value));
}
pub fn reset(&self, name: &str) -> Arc<PrefValue> {
let mut prefs = self.0.write().unwrap();
let result = match prefs.get_mut(name) {
None => return Arc::new(PrefValue::Missing),
Some(&mut Pref::NoDefault(_)) => Arc::new(PrefValue::Missing),
Some(&mut Pref::WithDefault(ref default, ref mut set_value)) => {
*set_value = None;
default.clone()
},
};
if *result == PrefValue::Missing {
prefs.remove(name);
}
result
}
pub fn reset_all(&self) {
let names = {
self.0
.read()
.unwrap()
.keys()
.cloned()
.collect::<Vec<String>>()
};
for name in names.iter() {
self.reset(name);
}
}
pub fn extend(&self, extension: HashMap<String, Pref>) {
self.0.write().unwrap().extend(extension);
}
pub fn is_webvr_enabled(&self) -> bool {
self.get("dom.webvr.enabled").as_boolean().unwrap_or(false)
}
pub fn is_dom_to_texture_enabled(&self) -> bool {
self.get("dom.webgl.dom_to_texture.enabled")
.as_boolean()
.unwrap_or(false)
}
pub fn | (&self) -> bool {
self.get("dom.webgl2.enabled").as_boolean().unwrap_or(false)
}
}
| is_webgl2_enabled | identifier_name |
prefs.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use basedir::default_config_dir;
use embedder_traits::resources::{self, Resource};
use num_cpus;
use opts;
use rustc_serialize::json::{Json, ToJson};
use std::borrow::ToOwned;
use std::cmp::max;
use std::collections::HashMap;
use std::fs::File;
use std::io::{Read, Write, stderr};
use std::path::PathBuf;
use std::sync::{Arc, RwLock};
lazy_static! {
pub static ref PREFS: Preferences = {
let defaults = default_prefs();
if let Ok(prefs) = read_prefs(&resources::read_string(Resource::Preferences)) {
defaults.extend(prefs);
}
defaults
};
}
#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
pub enum PrefValue {
Boolean(bool),
String(String),
Number(f64),
Missing,
}
impl PrefValue {
pub fn from_json(data: Json) -> Result<PrefValue, ()> {
let value = match data {
Json::Boolean(x) => PrefValue::Boolean(x),
Json::String(x) => PrefValue::String(x),
Json::F64(x) => PrefValue::Number(x),
Json::I64(x) => PrefValue::Number(x as f64),
Json::U64(x) => PrefValue::Number(x as f64),
_ => return Err(()),
};
Ok(value)
}
pub fn as_boolean(&self) -> Option<bool> {
match *self {
PrefValue::Boolean(value) => Some(value),
_ => None,
}
}
pub fn as_string(&self) -> Option<&str> {
match *self {
PrefValue::String(ref value) => Some(&value),
_ => None,
}
}
pub fn as_i64(&self) -> Option<i64> {
match *self {
PrefValue::Number(x) => Some(x as i64),
_ => None,
}
}
pub fn as_u64(&self) -> Option<u64> {
match *self {
PrefValue::Number(x) => Some(x as u64),
_ => None,
}
}
}
impl ToJson for PrefValue {
fn to_json(&self) -> Json {
match *self {
PrefValue::Boolean(x) => Json::Boolean(x),
PrefValue::String(ref x) => Json::String(x.clone()),
PrefValue::Number(x) => Json::F64(x),
PrefValue::Missing => Json::Null,
}
} | WithDefault(Arc<PrefValue>, Option<Arc<PrefValue>>),
}
impl Pref {
pub fn new(value: PrefValue) -> Pref {
Pref::NoDefault(Arc::new(value))
}
fn new_default(value: PrefValue) -> Pref {
Pref::WithDefault(Arc::new(value), None)
}
fn from_json(data: Json) -> Result<Pref, ()> {
let value = PrefValue::from_json(data)?;
Ok(Pref::new_default(value))
}
pub fn value(&self) -> &Arc<PrefValue> {
match *self {
Pref::NoDefault(ref x) => x,
Pref::WithDefault(ref default, ref override_value) => match *override_value {
Some(ref x) => x,
None => default,
},
}
}
fn set(&mut self, value: PrefValue) {
// TODO - this should error if we try to override a pref of one type
// with a value of a different type
match *self {
Pref::NoDefault(ref mut pref_value) => *pref_value = Arc::new(value),
Pref::WithDefault(_, ref mut override_value) => *override_value = Some(Arc::new(value)),
}
}
}
impl ToJson for Pref {
fn to_json(&self) -> Json {
self.value().to_json()
}
}
pub fn default_prefs() -> Preferences {
let prefs = Preferences(Arc::new(RwLock::new(HashMap::new())));
prefs.set(
"layout.threads",
PrefValue::Number(max(num_cpus::get() * 3 / 4, 1) as f64),
);
prefs
}
pub fn read_prefs(txt: &str) -> Result<HashMap<String, Pref>, ()> {
let json = Json::from_str(txt).or_else(|e| {
println!("Ignoring invalid JSON in preferences: {:?}.", e);
Err(())
})?;
let mut prefs = HashMap::new();
if let Json::Object(obj) = json {
for (name, value) in obj.into_iter() {
match Pref::from_json(value) {
Ok(x) => {
prefs.insert(name, x);
},
Err(_) => println!(
"Ignoring non-boolean/string/i64 preference value for {:?}",
name
),
}
}
}
Ok(prefs)
}
pub fn add_user_prefs() {
match opts::get().config_dir {
Some(ref config_path) => {
let mut path = PathBuf::from(config_path);
init_user_prefs(&mut path);
},
None => {
if let Some(mut path) = default_config_dir() {
if path.join("prefs.json").exists() {
init_user_prefs(&mut path);
}
}
},
}
}
fn init_user_prefs(path: &mut PathBuf) {
path.push("prefs.json");
if let Ok(mut file) = File::open(path) {
let mut txt = String::new();
file.read_to_string(&mut txt).expect("Can't read use prefs");
if let Ok(prefs) = read_prefs(&txt) {
PREFS.extend(prefs);
}
} else {
writeln!(
&mut stderr(),
"Error opening prefs.json from config directory"
).expect("failed printing to stderr");
}
}
pub struct Preferences(Arc<RwLock<HashMap<String, Pref>>>);
impl Preferences {
pub fn get(&self, name: &str) -> Arc<PrefValue> {
self.0
.read()
.unwrap()
.get(name)
.map_or(Arc::new(PrefValue::Missing), |x| x.value().clone())
}
pub fn cloned(&self) -> HashMap<String, Pref> {
self.0.read().unwrap().clone()
}
pub fn set(&self, name: &str, value: PrefValue) {
let mut prefs = self.0.write().unwrap();
if let Some(pref) = prefs.get_mut(name) {
pref.set(value);
return;
}
prefs.insert(name.to_owned(), Pref::new(value));
}
pub fn reset(&self, name: &str) -> Arc<PrefValue> {
let mut prefs = self.0.write().unwrap();
let result = match prefs.get_mut(name) {
None => return Arc::new(PrefValue::Missing),
Some(&mut Pref::NoDefault(_)) => Arc::new(PrefValue::Missing),
Some(&mut Pref::WithDefault(ref default, ref mut set_value)) => {
*set_value = None;
default.clone()
},
};
if *result == PrefValue::Missing {
prefs.remove(name);
}
result
}
pub fn reset_all(&self) {
let names = {
self.0
.read()
.unwrap()
.keys()
.cloned()
.collect::<Vec<String>>()
};
for name in names.iter() {
self.reset(name);
}
}
pub fn extend(&self, extension: HashMap<String, Pref>) {
self.0.write().unwrap().extend(extension);
}
pub fn is_webvr_enabled(&self) -> bool {
self.get("dom.webvr.enabled").as_boolean().unwrap_or(false)
}
pub fn is_dom_to_texture_enabled(&self) -> bool {
self.get("dom.webgl.dom_to_texture.enabled")
.as_boolean()
.unwrap_or(false)
}
pub fn is_webgl2_enabled(&self) -> bool {
self.get("dom.webgl2.enabled").as_boolean().unwrap_or(false)
}
} | }
#[derive(Clone, Debug, Deserialize, Serialize)]
pub enum Pref {
NoDefault(Arc<PrefValue>), | random_line_split |
main.js | (function(){
// Back to Top - by CodyHouse.co
var backTop = document.getElementsByClassName('js-cd-top')[0],
offset = 300, // browser window scroll (in pixels) after which the "back to top" link is shown
offsetOpacity = 1200, //browser window scroll (in pixels) after which the "back to top" link opacity is reduced
scrollDuration = 700,
scrolling = false;
if( backTop ) {
//update back to top visibility on scrolling
window.addEventListener("scroll", function(event) {
if( !scrolling ) {
scrolling = true;
(!window.requestAnimationFrame) ? setTimeout(checkBackToTop, 250) : window.requestAnimationFrame(checkBackToTop);
}
});
//smooth scroll to top
backTop.addEventListener('click', function(event) {
event.preventDefault();
(!window.requestAnimationFrame) ? window.scrollTo(0, 0) : Util.scrollTo(0, scrollDuration);
});
}
function | () {
var windowTop = window.scrollY || document.documentElement.scrollTop;
( windowTop > offset ) ? Util.addClass(backTop, 'cd-top--is-visible') : Util.removeClass(backTop, 'cd-top--is-visible cd-top--fade-out');
( windowTop > offsetOpacity ) && Util.addClass(backTop, 'cd-top--fade-out');
scrolling = false;
}
})(); | checkBackToTop | identifier_name |
main.js | (function(){
// Back to Top - by CodyHouse.co
var backTop = document.getElementsByClassName('js-cd-top')[0],
offset = 300, // browser window scroll (in pixels) after which the "back to top" link is shown
offsetOpacity = 1200, //browser window scroll (in pixels) after which the "back to top" link opacity is reduced |
if( backTop ) {
//update back to top visibility on scrolling
window.addEventListener("scroll", function(event) {
if( !scrolling ) {
scrolling = true;
(!window.requestAnimationFrame) ? setTimeout(checkBackToTop, 250) : window.requestAnimationFrame(checkBackToTop);
}
});
//smooth scroll to top
backTop.addEventListener('click', function(event) {
event.preventDefault();
(!window.requestAnimationFrame) ? window.scrollTo(0, 0) : Util.scrollTo(0, scrollDuration);
});
}
function checkBackToTop() {
var windowTop = window.scrollY || document.documentElement.scrollTop;
( windowTop > offset ) ? Util.addClass(backTop, 'cd-top--is-visible') : Util.removeClass(backTop, 'cd-top--is-visible cd-top--fade-out');
( windowTop > offsetOpacity ) && Util.addClass(backTop, 'cd-top--fade-out');
scrolling = false;
}
})(); | scrollDuration = 700,
scrolling = false; | random_line_split |
main.js | (function(){
// Back to Top - by CodyHouse.co
var backTop = document.getElementsByClassName('js-cd-top')[0],
offset = 300, // browser window scroll (in pixels) after which the "back to top" link is shown
offsetOpacity = 1200, //browser window scroll (in pixels) after which the "back to top" link opacity is reduced
scrollDuration = 700,
scrolling = false;
if( backTop ) {
//update back to top visibility on scrolling
window.addEventListener("scroll", function(event) {
if( !scrolling ) {
scrolling = true;
(!window.requestAnimationFrame) ? setTimeout(checkBackToTop, 250) : window.requestAnimationFrame(checkBackToTop);
}
});
//smooth scroll to top
backTop.addEventListener('click', function(event) {
event.preventDefault();
(!window.requestAnimationFrame) ? window.scrollTo(0, 0) : Util.scrollTo(0, scrollDuration);
});
}
function checkBackToTop() |
})(); | {
var windowTop = window.scrollY || document.documentElement.scrollTop;
( windowTop > offset ) ? Util.addClass(backTop, 'cd-top--is-visible') : Util.removeClass(backTop, 'cd-top--is-visible cd-top--fade-out');
( windowTop > offsetOpacity ) && Util.addClass(backTop, 'cd-top--fade-out');
scrolling = false;
} | identifier_body |
main.js | (function(){
// Back to Top - by CodyHouse.co
var backTop = document.getElementsByClassName('js-cd-top')[0],
offset = 300, // browser window scroll (in pixels) after which the "back to top" link is shown
offsetOpacity = 1200, //browser window scroll (in pixels) after which the "back to top" link opacity is reduced
scrollDuration = 700,
scrolling = false;
if( backTop ) {
//update back to top visibility on scrolling
window.addEventListener("scroll", function(event) {
if( !scrolling ) |
});
//smooth scroll to top
backTop.addEventListener('click', function(event) {
event.preventDefault();
(!window.requestAnimationFrame) ? window.scrollTo(0, 0) : Util.scrollTo(0, scrollDuration);
});
}
function checkBackToTop() {
var windowTop = window.scrollY || document.documentElement.scrollTop;
( windowTop > offset ) ? Util.addClass(backTop, 'cd-top--is-visible') : Util.removeClass(backTop, 'cd-top--is-visible cd-top--fade-out');
( windowTop > offsetOpacity ) && Util.addClass(backTop, 'cd-top--fade-out');
scrolling = false;
}
})(); | {
scrolling = true;
(!window.requestAnimationFrame) ? setTimeout(checkBackToTop, 250) : window.requestAnimationFrame(checkBackToTop);
} | conditional_block |
_nlp_common.py | import unicodedata
try:
import sentencepiece as spm
except ImportError:
spm = None
#from ..config import ConfigError
#from ..utils import contains_all
SPIECE_UNDERLINE = '\N{LOWER ONE EIGHTH BLOCK}'
SEG_ID_A = 0
SEG_ID_B = 1
SEG_ID_CLS = 2
SEG_ID_SEP = 3
SEG_ID_PAD = 4
special_symbols = {
"<unk>": 0,
"<s>": 1,
"</s>": 2,
"<cls>": 3,
"<sep>": 4,
"<pad>": 5,
"<mask>": 6,
"<eod>": 7,
"<eop>": 8,
}
UNK_ID = special_symbols["<unk>"]
CLS_ID = special_symbols["<cls>"]
SEP_ID = special_symbols["<sep>"]
MASK_ID = special_symbols["<mask>"]
EOD_ID = special_symbols["<eod>"]
WORD_PIECE_PARAMETERS = ['vocab_file']
SENTENCE_PIECE_PARAMETERS = ['sentence_piece_model_file']
def get_tokenizer(lower_case, vocab_file=None, sentence_piece_model_file=None):
tokenizer = None
if vocab_file:
tokenizer = WordPieceTokenizer(vocab_file, lower_case)
elif sentence_piece_model_file:
tokenizer = SentencePieceTokenizer(sentence_piece_model_file, lower_case)
if tokenizer is None:
raise ValueError('tokenization parameters is not found, please provide: \n'
'for WordPiece tokenization - {}\nfor SentencePiece tokenization - {}\n'.format(
', '.join(WORD_PIECE_PARAMETERS), ', '.join(SENTENCE_PIECE_PARAMETERS))
)
return tokenizer
class QuestionAnsweringAnnotation():
def __init__(self, identifier, unique_id, input_ids, input_mask, segment_ids, tokens, orig_answer_text=None):
self.identifier = identifier
self.orig_answer_text = orig_answer_text if orig_answer_text is not None else ''
self.unique_id = unique_id
self.input_ids = input_ids
self.input_mask = input_mask
self.segment_ids = segment_ids
self.tokens = tokens
class WordPieceTokenizer:
def __init__(self, vocab_file, lower_case=True, tokenize_chinese_chars=True):
self.vocab = self.load_vocab(vocab_file)
self.lower_case = lower_case
self.tokenize_chinese_chars = tokenize_chinese_chars
@staticmethod
def _run_strip_accents(text):
text = unicodedata.normalize("NFD", text)
output = []
for char in text:
cat = unicodedata.category(char)
if cat == "Mn":
continue
output.append(char)
return "".join(output)
@staticmethod
def _run_split_on_punc(text):
def _is_punctuation(char):
punct = set('!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~')
if char in punct:
return True
cat = unicodedata.category(char)
if cat.startswith("P"):
return True
return False
chars = list(text)
i = 0
start_new_word = True
output = []
while i < len(chars):
char = chars[i]
if _is_punctuation(char):
output.append([char])
start_new_word = True
else:
if start_new_word:
output.append([])
start_new_word = False
output[-1].append(char)
i += 1
return ["".join(x) for x in output]
def basic_tokenizer(self, text):
if isinstance(text, bytes):
text = text.decode("utf-8", "ignore")
if self.tokenize_chinese_chars:
text = self._tokenize_chinese_chars(text)
text = text.strip()
tokens = text.split() if text else []
split_tokens = []
for token in tokens:
if self.lower_case:
token = token.lower()
token = self._run_strip_accents(token)
split_tokens.extend(self._run_split_on_punc(token))
output_tokens = " ".join(split_tokens)
output_tokens = output_tokens.strip()
output_tokens = output_tokens.split() if output_tokens else []
return output_tokens
def _tokenize_chinese_chars(self, text):
"""Adds whitespace around any CJK character."""
output = []
for char in text:
cp = ord(char)
if self._is_chinese_char(cp):
output.append(" ")
output.append(char)
output.append(" ")
else:
output.append(char)
return "".join(output)
@staticmethod
def _is_chinese_char(cp):
"""Checks whether CP is the codepoint of a CJK character."""
# This defines a "chinese character" as anything in the CJK Unicode block:
# https://en.wikipedia.org/wiki/CJK_Unified_Ideographs_(Unicode_block)
#
# Note that the CJK Unicode block is NOT all Japanese and Korean characters,
# despite its name. The modern Korean Hangul alphabet is a different block,
# as is Japanese Hiragana and Katakana. Those alphabets are used to write
# space-separated words, so they are not treated specially and handled
# like the all of the other languages.
#pylint:disable=chained-comparison
#pylint:disable=too-many-boolean-expressions
if ((cp >= 0x4E00 and cp <= 0x9FFF) or #
(cp >= 0x3400 and cp <= 0x4DBF) or #
(cp >= 0x20000 and cp <= 0x2A6DF) or #
(cp >= 0x2A700 and cp <= 0x2B73F) or #
(cp >= 0x2B740 and cp <= 0x2B81F) or #
(cp >= 0x2B820 and cp <= 0x2CEAF) or
(cp >= 0xF900 and cp <= 0xFAFF) or #
(cp >= 0x2F800 and cp <= 0x2FA1F)): #
return True
return False
def wordpiece_tokenizer(self, text):
if isinstance(text, bytes):
text = text.decode("utf-8", "ignore")
output_tokens = []
text = text.strip()
tokens = text.split() if text else []
for token in tokens:
chars = list(token)
if len(chars) > 200:
output_tokens.append("[UNK]")
continue
is_bad = False
start = 0
sub_tokens = []
while start < len(chars):
end = len(chars)
cur_substr = None
while start < end:
|
if cur_substr is None:
is_bad = True
break
sub_tokens.append(cur_substr)
start = end
if is_bad:
output_tokens.append("[UNK]")
else:
output_tokens.extend(sub_tokens)
return output_tokens
def tokenize(self, text):
tokens = []
for token in self.basic_tokenizer(text):
for sub_token in self.wordpiece_tokenizer(token):
tokens.append(sub_token)
return tokens
def convert_tokens_to_ids(self, items):
output = []
for item in items:
output.append(self.vocab[item])
return output
@staticmethod
def load_vocab(file):
vocab = {}
index = 0
with open(str(file), 'rb') as reader:
while True:
token = reader.readline()
if isinstance(token, bytes):
token = token.decode("utf-8", "ignore")
if not token:
break
token = token.strip()
vocab[token] = index
index += 1
return vocab
def truncate_seq_pair(tokens_a, tokens_b, max_length):
"""Truncates a sequence pair in place to the maximum length."""
# This is a simple heuristic which will always truncate the longer sequence
# one token at a time. This makes more sense than truncating an equal percent
# of tokens from each, since if one sequence is very short then each token
# that's truncated likely contains more information than a longer sequence.
while True:
total_length = len(tokens_a) + len(tokens_b)
if total_length <= max_length:
break
if len(tokens_a) > len(tokens_b):
tokens_a.pop()
else:
tokens_b.pop()
class SentencePieceTokenizer:
def __init__(self, tokenizer_model, lower_case=True, remove_space=True):
if spm is None:
raise ImportError('Sentence piece tokenizer required sentencepiece, please install it before usage')
self.encoder = spm.SentencePieceProcessor()
self.encoder.Load(str(tokenizer_model))
self.lower_case = lower_case
self.remove_space = remove_space
def preprocess_text(self, inputs):
if self.remove_space:
outputs = ' '.join(inputs.strip().split())
else:
outputs = inputs
outputs = outputs.replace("``", '"').replace("''", '"')
if self.lower_case:
outputs = outputs.lower()
return outputs
def encode_ids(self, text, sample=False):
pieces = self.encode_pieces(text, sample)
ids = [self.encoder.PieceToId(piece) for piece in pieces]
return ids
def encode_pieces(self, text, sample=False):
if not sample:
pieces = self.encoder.EncodeAsPieces(text)
else:
pieces = self.encoder.SampleEncodeAsPieces(text, 64, 0.1)
new_pieces = []
for piece in pieces:
if len(piece) > 1 and piece[-1] == ',' and piece[-2].isdigit():
cur_pieces = self.encoder.EncodeAsPieces(
piece[:-1].replace(SPIECE_UNDERLINE, ''))
if piece[0] != SPIECE_UNDERLINE and cur_pieces[0][0] == SPIECE_UNDERLINE:
if len(cur_pieces[0]) == 1:
cur_pieces = cur_pieces[1:]
else:
cur_pieces[0] = cur_pieces[0][1:]
cur_pieces.append(piece[-1])
new_pieces.extend(cur_pieces)
else:
new_pieces.append(piece)
return new_pieces
def tokenize(self, text):
text = self.preprocess_text(text)
return self.encode_ids(text)
| substr = "".join(chars[start:end])
if start > 0:
substr = "##" + substr
if substr in self.vocab:
cur_substr = substr
break
end -= 1 | conditional_block |
_nlp_common.py | import unicodedata
try:
import sentencepiece as spm
except ImportError:
spm = None
#from ..config import ConfigError
#from ..utils import contains_all
SPIECE_UNDERLINE = '\N{LOWER ONE EIGHTH BLOCK}'
SEG_ID_A = 0
SEG_ID_B = 1
SEG_ID_CLS = 2
SEG_ID_SEP = 3
SEG_ID_PAD = 4
special_symbols = {
"<unk>": 0,
"<s>": 1,
"</s>": 2,
"<cls>": 3,
"<sep>": 4,
"<pad>": 5,
"<mask>": 6,
"<eod>": 7,
"<eop>": 8,
}
UNK_ID = special_symbols["<unk>"]
CLS_ID = special_symbols["<cls>"]
SEP_ID = special_symbols["<sep>"]
MASK_ID = special_symbols["<mask>"]
EOD_ID = special_symbols["<eod>"]
WORD_PIECE_PARAMETERS = ['vocab_file']
SENTENCE_PIECE_PARAMETERS = ['sentence_piece_model_file']
def get_tokenizer(lower_case, vocab_file=None, sentence_piece_model_file=None):
tokenizer = None
if vocab_file:
tokenizer = WordPieceTokenizer(vocab_file, lower_case)
elif sentence_piece_model_file:
tokenizer = SentencePieceTokenizer(sentence_piece_model_file, lower_case)
if tokenizer is None:
raise ValueError('tokenization parameters is not found, please provide: \n'
'for WordPiece tokenization - {}\nfor SentencePiece tokenization - {}\n'.format(
', '.join(WORD_PIECE_PARAMETERS), ', '.join(SENTENCE_PIECE_PARAMETERS))
)
return tokenizer
class QuestionAnsweringAnnotation():
def __init__(self, identifier, unique_id, input_ids, input_mask, segment_ids, tokens, orig_answer_text=None):
self.identifier = identifier
self.orig_answer_text = orig_answer_text if orig_answer_text is not None else ''
self.unique_id = unique_id
self.input_ids = input_ids
self.input_mask = input_mask
self.segment_ids = segment_ids
self.tokens = tokens
class WordPieceTokenizer:
def __init__(self, vocab_file, lower_case=True, tokenize_chinese_chars=True):
self.vocab = self.load_vocab(vocab_file)
self.lower_case = lower_case
self.tokenize_chinese_chars = tokenize_chinese_chars
@staticmethod
def _run_strip_accents(text):
text = unicodedata.normalize("NFD", text)
output = []
for char in text:
cat = unicodedata.category(char)
if cat == "Mn":
continue
output.append(char)
return "".join(output)
@staticmethod
def _run_split_on_punc(text):
def _is_punctuation(char):
punct = set('!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~')
if char in punct:
return True
cat = unicodedata.category(char)
if cat.startswith("P"):
return True
return False
chars = list(text)
i = 0
start_new_word = True
output = []
while i < len(chars):
char = chars[i]
if _is_punctuation(char):
output.append([char])
start_new_word = True
else:
if start_new_word:
output.append([])
start_new_word = False
output[-1].append(char)
i += 1
return ["".join(x) for x in output]
def basic_tokenizer(self, text):
if isinstance(text, bytes):
text = text.decode("utf-8", "ignore")
if self.tokenize_chinese_chars:
text = self._tokenize_chinese_chars(text)
text = text.strip()
tokens = text.split() if text else []
split_tokens = []
for token in tokens:
if self.lower_case:
token = token.lower()
token = self._run_strip_accents(token)
split_tokens.extend(self._run_split_on_punc(token))
output_tokens = " ".join(split_tokens)
output_tokens = output_tokens.strip()
output_tokens = output_tokens.split() if output_tokens else []
return output_tokens
def _tokenize_chinese_chars(self, text):
"""Adds whitespace around any CJK character."""
output = []
for char in text:
cp = ord(char)
if self._is_chinese_char(cp):
output.append(" ")
output.append(char)
output.append(" ")
else:
output.append(char)
return "".join(output)
@staticmethod
def _is_chinese_char(cp):
"""Checks whether CP is the codepoint of a CJK character."""
# This defines a "chinese character" as anything in the CJK Unicode block:
# https://en.wikipedia.org/wiki/CJK_Unified_Ideographs_(Unicode_block)
#
# Note that the CJK Unicode block is NOT all Japanese and Korean characters,
# despite its name. The modern Korean Hangul alphabet is a different block,
# as is Japanese Hiragana and Katakana. Those alphabets are used to write
# space-separated words, so they are not treated specially and handled
# like the all of the other languages.
#pylint:disable=chained-comparison
#pylint:disable=too-many-boolean-expressions
if ((cp >= 0x4E00 and cp <= 0x9FFF) or #
(cp >= 0x3400 and cp <= 0x4DBF) or #
(cp >= 0x20000 and cp <= 0x2A6DF) or #
(cp >= 0x2A700 and cp <= 0x2B73F) or #
(cp >= 0x2B740 and cp <= 0x2B81F) or #
(cp >= 0x2B820 and cp <= 0x2CEAF) or
(cp >= 0xF900 and cp <= 0xFAFF) or #
(cp >= 0x2F800 and cp <= 0x2FA1F)): #
return True
return False
def wordpiece_tokenizer(self, text):
if isinstance(text, bytes):
text = text.decode("utf-8", "ignore")
output_tokens = []
text = text.strip()
tokens = text.split() if text else []
for token in tokens:
chars = list(token)
if len(chars) > 200:
output_tokens.append("[UNK]")
continue
is_bad = False
start = 0
sub_tokens = []
while start < len(chars):
end = len(chars)
cur_substr = None
while start < end:
substr = "".join(chars[start:end])
if start > 0:
substr = "##" + substr
if substr in self.vocab:
cur_substr = substr
break
end -= 1
if cur_substr is None:
is_bad = True
break
sub_tokens.append(cur_substr)
start = end
if is_bad:
output_tokens.append("[UNK]")
else:
output_tokens.extend(sub_tokens)
return output_tokens
def tokenize(self, text):
tokens = []
for token in self.basic_tokenizer(text):
for sub_token in self.wordpiece_tokenizer(token):
tokens.append(sub_token)
return tokens
def convert_tokens_to_ids(self, items):
output = []
for item in items:
output.append(self.vocab[item])
return output
@staticmethod
def load_vocab(file):
vocab = {}
index = 0
with open(str(file), 'rb') as reader:
while True:
token = reader.readline()
if isinstance(token, bytes):
token = token.decode("utf-8", "ignore")
if not token:
break
token = token.strip()
vocab[token] = index
index += 1
return vocab
def truncate_seq_pair(tokens_a, tokens_b, max_length):
"""Truncates a sequence pair in place to the maximum length."""
# This is a simple heuristic which will always truncate the longer sequence
# one token at a time. This makes more sense than truncating an equal percent
# of tokens from each, since if one sequence is very short then each token
# that's truncated likely contains more information than a longer sequence.
while True:
total_length = len(tokens_a) + len(tokens_b)
if total_length <= max_length:
break
if len(tokens_a) > len(tokens_b):
tokens_a.pop()
else:
tokens_b.pop()
class SentencePieceTokenizer:
def __init__(self, tokenizer_model, lower_case=True, remove_space=True):
if spm is None:
raise ImportError('Sentence piece tokenizer required sentencepiece, please install it before usage')
self.encoder = spm.SentencePieceProcessor()
self.encoder.Load(str(tokenizer_model))
self.lower_case = lower_case
self.remove_space = remove_space
def preprocess_text(self, inputs):
if self.remove_space:
outputs = ' '.join(inputs.strip().split())
else:
outputs = inputs
outputs = outputs.replace("``", '"').replace("''", '"')
if self.lower_case:
outputs = outputs.lower()
return outputs
def encode_ids(self, text, sample=False):
pieces = self.encode_pieces(text, sample)
ids = [self.encoder.PieceToId(piece) for piece in pieces]
return ids
def encode_pieces(self, text, sample=False):
|
def tokenize(self, text):
text = self.preprocess_text(text)
return self.encode_ids(text)
| if not sample:
pieces = self.encoder.EncodeAsPieces(text)
else:
pieces = self.encoder.SampleEncodeAsPieces(text, 64, 0.1)
new_pieces = []
for piece in pieces:
if len(piece) > 1 and piece[-1] == ',' and piece[-2].isdigit():
cur_pieces = self.encoder.EncodeAsPieces(
piece[:-1].replace(SPIECE_UNDERLINE, ''))
if piece[0] != SPIECE_UNDERLINE and cur_pieces[0][0] == SPIECE_UNDERLINE:
if len(cur_pieces[0]) == 1:
cur_pieces = cur_pieces[1:]
else:
cur_pieces[0] = cur_pieces[0][1:]
cur_pieces.append(piece[-1])
new_pieces.extend(cur_pieces)
else:
new_pieces.append(piece)
return new_pieces | identifier_body |
_nlp_common.py | import unicodedata
try:
import sentencepiece as spm
except ImportError:
spm = None
#from ..config import ConfigError
#from ..utils import contains_all
SPIECE_UNDERLINE = '\N{LOWER ONE EIGHTH BLOCK}'
SEG_ID_A = 0
SEG_ID_B = 1
SEG_ID_CLS = 2
SEG_ID_SEP = 3
SEG_ID_PAD = 4
special_symbols = {
"<unk>": 0,
"<s>": 1,
"</s>": 2,
"<cls>": 3,
"<sep>": 4,
"<pad>": 5,
"<mask>": 6,
"<eod>": 7,
"<eop>": 8,
}
UNK_ID = special_symbols["<unk>"]
CLS_ID = special_symbols["<cls>"]
SEP_ID = special_symbols["<sep>"]
MASK_ID = special_symbols["<mask>"]
EOD_ID = special_symbols["<eod>"]
WORD_PIECE_PARAMETERS = ['vocab_file'] | def get_tokenizer(lower_case, vocab_file=None, sentence_piece_model_file=None):
tokenizer = None
if vocab_file:
tokenizer = WordPieceTokenizer(vocab_file, lower_case)
elif sentence_piece_model_file:
tokenizer = SentencePieceTokenizer(sentence_piece_model_file, lower_case)
if tokenizer is None:
raise ValueError('tokenization parameters is not found, please provide: \n'
'for WordPiece tokenization - {}\nfor SentencePiece tokenization - {}\n'.format(
', '.join(WORD_PIECE_PARAMETERS), ', '.join(SENTENCE_PIECE_PARAMETERS))
)
return tokenizer
class QuestionAnsweringAnnotation():
def __init__(self, identifier, unique_id, input_ids, input_mask, segment_ids, tokens, orig_answer_text=None):
self.identifier = identifier
self.orig_answer_text = orig_answer_text if orig_answer_text is not None else ''
self.unique_id = unique_id
self.input_ids = input_ids
self.input_mask = input_mask
self.segment_ids = segment_ids
self.tokens = tokens
class WordPieceTokenizer:
def __init__(self, vocab_file, lower_case=True, tokenize_chinese_chars=True):
self.vocab = self.load_vocab(vocab_file)
self.lower_case = lower_case
self.tokenize_chinese_chars = tokenize_chinese_chars
@staticmethod
def _run_strip_accents(text):
text = unicodedata.normalize("NFD", text)
output = []
for char in text:
cat = unicodedata.category(char)
if cat == "Mn":
continue
output.append(char)
return "".join(output)
@staticmethod
def _run_split_on_punc(text):
def _is_punctuation(char):
punct = set('!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~')
if char in punct:
return True
cat = unicodedata.category(char)
if cat.startswith("P"):
return True
return False
chars = list(text)
i = 0
start_new_word = True
output = []
while i < len(chars):
char = chars[i]
if _is_punctuation(char):
output.append([char])
start_new_word = True
else:
if start_new_word:
output.append([])
start_new_word = False
output[-1].append(char)
i += 1
return ["".join(x) for x in output]
def basic_tokenizer(self, text):
if isinstance(text, bytes):
text = text.decode("utf-8", "ignore")
if self.tokenize_chinese_chars:
text = self._tokenize_chinese_chars(text)
text = text.strip()
tokens = text.split() if text else []
split_tokens = []
for token in tokens:
if self.lower_case:
token = token.lower()
token = self._run_strip_accents(token)
split_tokens.extend(self._run_split_on_punc(token))
output_tokens = " ".join(split_tokens)
output_tokens = output_tokens.strip()
output_tokens = output_tokens.split() if output_tokens else []
return output_tokens
def _tokenize_chinese_chars(self, text):
"""Adds whitespace around any CJK character."""
output = []
for char in text:
cp = ord(char)
if self._is_chinese_char(cp):
output.append(" ")
output.append(char)
output.append(" ")
else:
output.append(char)
return "".join(output)
@staticmethod
def _is_chinese_char(cp):
"""Checks whether CP is the codepoint of a CJK character."""
# This defines a "chinese character" as anything in the CJK Unicode block:
# https://en.wikipedia.org/wiki/CJK_Unified_Ideographs_(Unicode_block)
#
# Note that the CJK Unicode block is NOT all Japanese and Korean characters,
# despite its name. The modern Korean Hangul alphabet is a different block,
# as is Japanese Hiragana and Katakana. Those alphabets are used to write
# space-separated words, so they are not treated specially and handled
# like the all of the other languages.
#pylint:disable=chained-comparison
#pylint:disable=too-many-boolean-expressions
if ((cp >= 0x4E00 and cp <= 0x9FFF) or #
(cp >= 0x3400 and cp <= 0x4DBF) or #
(cp >= 0x20000 and cp <= 0x2A6DF) or #
(cp >= 0x2A700 and cp <= 0x2B73F) or #
(cp >= 0x2B740 and cp <= 0x2B81F) or #
(cp >= 0x2B820 and cp <= 0x2CEAF) or
(cp >= 0xF900 and cp <= 0xFAFF) or #
(cp >= 0x2F800 and cp <= 0x2FA1F)): #
return True
return False
def wordpiece_tokenizer(self, text):
if isinstance(text, bytes):
text = text.decode("utf-8", "ignore")
output_tokens = []
text = text.strip()
tokens = text.split() if text else []
for token in tokens:
chars = list(token)
if len(chars) > 200:
output_tokens.append("[UNK]")
continue
is_bad = False
start = 0
sub_tokens = []
while start < len(chars):
end = len(chars)
cur_substr = None
while start < end:
substr = "".join(chars[start:end])
if start > 0:
substr = "##" + substr
if substr in self.vocab:
cur_substr = substr
break
end -= 1
if cur_substr is None:
is_bad = True
break
sub_tokens.append(cur_substr)
start = end
if is_bad:
output_tokens.append("[UNK]")
else:
output_tokens.extend(sub_tokens)
return output_tokens
def tokenize(self, text):
tokens = []
for token in self.basic_tokenizer(text):
for sub_token in self.wordpiece_tokenizer(token):
tokens.append(sub_token)
return tokens
def convert_tokens_to_ids(self, items):
output = []
for item in items:
output.append(self.vocab[item])
return output
@staticmethod
def load_vocab(file):
vocab = {}
index = 0
with open(str(file), 'rb') as reader:
while True:
token = reader.readline()
if isinstance(token, bytes):
token = token.decode("utf-8", "ignore")
if not token:
break
token = token.strip()
vocab[token] = index
index += 1
return vocab
def truncate_seq_pair(tokens_a, tokens_b, max_length):
"""Truncates a sequence pair in place to the maximum length."""
# This is a simple heuristic which will always truncate the longer sequence
# one token at a time. This makes more sense than truncating an equal percent
# of tokens from each, since if one sequence is very short then each token
# that's truncated likely contains more information than a longer sequence.
while True:
total_length = len(tokens_a) + len(tokens_b)
if total_length <= max_length:
break
if len(tokens_a) > len(tokens_b):
tokens_a.pop()
else:
tokens_b.pop()
class SentencePieceTokenizer:
def __init__(self, tokenizer_model, lower_case=True, remove_space=True):
if spm is None:
raise ImportError('Sentence piece tokenizer required sentencepiece, please install it before usage')
self.encoder = spm.SentencePieceProcessor()
self.encoder.Load(str(tokenizer_model))
self.lower_case = lower_case
self.remove_space = remove_space
def preprocess_text(self, inputs):
if self.remove_space:
outputs = ' '.join(inputs.strip().split())
else:
outputs = inputs
outputs = outputs.replace("``", '"').replace("''", '"')
if self.lower_case:
outputs = outputs.lower()
return outputs
def encode_ids(self, text, sample=False):
pieces = self.encode_pieces(text, sample)
ids = [self.encoder.PieceToId(piece) for piece in pieces]
return ids
def encode_pieces(self, text, sample=False):
if not sample:
pieces = self.encoder.EncodeAsPieces(text)
else:
pieces = self.encoder.SampleEncodeAsPieces(text, 64, 0.1)
new_pieces = []
for piece in pieces:
if len(piece) > 1 and piece[-1] == ',' and piece[-2].isdigit():
cur_pieces = self.encoder.EncodeAsPieces(
piece[:-1].replace(SPIECE_UNDERLINE, ''))
if piece[0] != SPIECE_UNDERLINE and cur_pieces[0][0] == SPIECE_UNDERLINE:
if len(cur_pieces[0]) == 1:
cur_pieces = cur_pieces[1:]
else:
cur_pieces[0] = cur_pieces[0][1:]
cur_pieces.append(piece[-1])
new_pieces.extend(cur_pieces)
else:
new_pieces.append(piece)
return new_pieces
def tokenize(self, text):
text = self.preprocess_text(text)
return self.encode_ids(text) | SENTENCE_PIECE_PARAMETERS = ['sentence_piece_model_file']
| random_line_split |
_nlp_common.py | import unicodedata
try:
import sentencepiece as spm
except ImportError:
spm = None
#from ..config import ConfigError
#from ..utils import contains_all
SPIECE_UNDERLINE = '\N{LOWER ONE EIGHTH BLOCK}'
SEG_ID_A = 0
SEG_ID_B = 1
SEG_ID_CLS = 2
SEG_ID_SEP = 3
SEG_ID_PAD = 4
special_symbols = {
"<unk>": 0,
"<s>": 1,
"</s>": 2,
"<cls>": 3,
"<sep>": 4,
"<pad>": 5,
"<mask>": 6,
"<eod>": 7,
"<eop>": 8,
}
UNK_ID = special_symbols["<unk>"]
CLS_ID = special_symbols["<cls>"]
SEP_ID = special_symbols["<sep>"]
MASK_ID = special_symbols["<mask>"]
EOD_ID = special_symbols["<eod>"]
WORD_PIECE_PARAMETERS = ['vocab_file']
SENTENCE_PIECE_PARAMETERS = ['sentence_piece_model_file']
def get_tokenizer(lower_case, vocab_file=None, sentence_piece_model_file=None):
tokenizer = None
if vocab_file:
tokenizer = WordPieceTokenizer(vocab_file, lower_case)
elif sentence_piece_model_file:
tokenizer = SentencePieceTokenizer(sentence_piece_model_file, lower_case)
if tokenizer is None:
raise ValueError('tokenization parameters is not found, please provide: \n'
'for WordPiece tokenization - {}\nfor SentencePiece tokenization - {}\n'.format(
', '.join(WORD_PIECE_PARAMETERS), ', '.join(SENTENCE_PIECE_PARAMETERS))
)
return tokenizer
class QuestionAnsweringAnnotation():
def __init__(self, identifier, unique_id, input_ids, input_mask, segment_ids, tokens, orig_answer_text=None):
self.identifier = identifier
self.orig_answer_text = orig_answer_text if orig_answer_text is not None else ''
self.unique_id = unique_id
self.input_ids = input_ids
self.input_mask = input_mask
self.segment_ids = segment_ids
self.tokens = tokens
class WordPieceTokenizer:
def __init__(self, vocab_file, lower_case=True, tokenize_chinese_chars=True):
self.vocab = self.load_vocab(vocab_file)
self.lower_case = lower_case
self.tokenize_chinese_chars = tokenize_chinese_chars
@staticmethod
def _run_strip_accents(text):
text = unicodedata.normalize("NFD", text)
output = []
for char in text:
cat = unicodedata.category(char)
if cat == "Mn":
continue
output.append(char)
return "".join(output)
@staticmethod
def _run_split_on_punc(text):
def _is_punctuation(char):
punct = set('!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~')
if char in punct:
return True
cat = unicodedata.category(char)
if cat.startswith("P"):
return True
return False
chars = list(text)
i = 0
start_new_word = True
output = []
while i < len(chars):
char = chars[i]
if _is_punctuation(char):
output.append([char])
start_new_word = True
else:
if start_new_word:
output.append([])
start_new_word = False
output[-1].append(char)
i += 1
return ["".join(x) for x in output]
def basic_tokenizer(self, text):
if isinstance(text, bytes):
text = text.decode("utf-8", "ignore")
if self.tokenize_chinese_chars:
text = self._tokenize_chinese_chars(text)
text = text.strip()
tokens = text.split() if text else []
split_tokens = []
for token in tokens:
if self.lower_case:
token = token.lower()
token = self._run_strip_accents(token)
split_tokens.extend(self._run_split_on_punc(token))
output_tokens = " ".join(split_tokens)
output_tokens = output_tokens.strip()
output_tokens = output_tokens.split() if output_tokens else []
return output_tokens
def _tokenize_chinese_chars(self, text):
"""Adds whitespace around any CJK character."""
output = []
for char in text:
cp = ord(char)
if self._is_chinese_char(cp):
output.append(" ")
output.append(char)
output.append(" ")
else:
output.append(char)
return "".join(output)
@staticmethod
def _is_chinese_char(cp):
"""Checks whether CP is the codepoint of a CJK character."""
# This defines a "chinese character" as anything in the CJK Unicode block:
# https://en.wikipedia.org/wiki/CJK_Unified_Ideographs_(Unicode_block)
#
# Note that the CJK Unicode block is NOT all Japanese and Korean characters,
# despite its name. The modern Korean Hangul alphabet is a different block,
# as is Japanese Hiragana and Katakana. Those alphabets are used to write
# space-separated words, so they are not treated specially and handled
# like the all of the other languages.
#pylint:disable=chained-comparison
#pylint:disable=too-many-boolean-expressions
if ((cp >= 0x4E00 and cp <= 0x9FFF) or #
(cp >= 0x3400 and cp <= 0x4DBF) or #
(cp >= 0x20000 and cp <= 0x2A6DF) or #
(cp >= 0x2A700 and cp <= 0x2B73F) or #
(cp >= 0x2B740 and cp <= 0x2B81F) or #
(cp >= 0x2B820 and cp <= 0x2CEAF) or
(cp >= 0xF900 and cp <= 0xFAFF) or #
(cp >= 0x2F800 and cp <= 0x2FA1F)): #
return True
return False
def wordpiece_tokenizer(self, text):
if isinstance(text, bytes):
text = text.decode("utf-8", "ignore")
output_tokens = []
text = text.strip()
tokens = text.split() if text else []
for token in tokens:
chars = list(token)
if len(chars) > 200:
output_tokens.append("[UNK]")
continue
is_bad = False
start = 0
sub_tokens = []
while start < len(chars):
end = len(chars)
cur_substr = None
while start < end:
substr = "".join(chars[start:end])
if start > 0:
substr = "##" + substr
if substr in self.vocab:
cur_substr = substr
break
end -= 1
if cur_substr is None:
is_bad = True
break
sub_tokens.append(cur_substr)
start = end
if is_bad:
output_tokens.append("[UNK]")
else:
output_tokens.extend(sub_tokens)
return output_tokens
def tokenize(self, text):
tokens = []
for token in self.basic_tokenizer(text):
for sub_token in self.wordpiece_tokenizer(token):
tokens.append(sub_token)
return tokens
def convert_tokens_to_ids(self, items):
output = []
for item in items:
output.append(self.vocab[item])
return output
@staticmethod
def load_vocab(file):
vocab = {}
index = 0
with open(str(file), 'rb') as reader:
while True:
token = reader.readline()
if isinstance(token, bytes):
token = token.decode("utf-8", "ignore")
if not token:
break
token = token.strip()
vocab[token] = index
index += 1
return vocab
def | (tokens_a, tokens_b, max_length):
"""Truncates a sequence pair in place to the maximum length."""
# This is a simple heuristic which will always truncate the longer sequence
# one token at a time. This makes more sense than truncating an equal percent
# of tokens from each, since if one sequence is very short then each token
# that's truncated likely contains more information than a longer sequence.
while True:
total_length = len(tokens_a) + len(tokens_b)
if total_length <= max_length:
break
if len(tokens_a) > len(tokens_b):
tokens_a.pop()
else:
tokens_b.pop()
class SentencePieceTokenizer:
def __init__(self, tokenizer_model, lower_case=True, remove_space=True):
if spm is None:
raise ImportError('Sentence piece tokenizer required sentencepiece, please install it before usage')
self.encoder = spm.SentencePieceProcessor()
self.encoder.Load(str(tokenizer_model))
self.lower_case = lower_case
self.remove_space = remove_space
def preprocess_text(self, inputs):
if self.remove_space:
outputs = ' '.join(inputs.strip().split())
else:
outputs = inputs
outputs = outputs.replace("``", '"').replace("''", '"')
if self.lower_case:
outputs = outputs.lower()
return outputs
def encode_ids(self, text, sample=False):
pieces = self.encode_pieces(text, sample)
ids = [self.encoder.PieceToId(piece) for piece in pieces]
return ids
def encode_pieces(self, text, sample=False):
if not sample:
pieces = self.encoder.EncodeAsPieces(text)
else:
pieces = self.encoder.SampleEncodeAsPieces(text, 64, 0.1)
new_pieces = []
for piece in pieces:
if len(piece) > 1 and piece[-1] == ',' and piece[-2].isdigit():
cur_pieces = self.encoder.EncodeAsPieces(
piece[:-1].replace(SPIECE_UNDERLINE, ''))
if piece[0] != SPIECE_UNDERLINE and cur_pieces[0][0] == SPIECE_UNDERLINE:
if len(cur_pieces[0]) == 1:
cur_pieces = cur_pieces[1:]
else:
cur_pieces[0] = cur_pieces[0][1:]
cur_pieces.append(piece[-1])
new_pieces.extend(cur_pieces)
else:
new_pieces.append(piece)
return new_pieces
def tokenize(self, text):
text = self.preprocess_text(text)
return self.encode_ids(text)
| truncate_seq_pair | identifier_name |
AccordionTitle.js | 'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _extends2 = require('babel-runtime/helpers/extends');
var _extends3 = _interopRequireDefault(_extends2);
var _classCallCheck2 = require('babel-runtime/helpers/classCallCheck');
var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);
var _createClass2 = require('babel-runtime/helpers/createClass');
var _createClass3 = _interopRequireDefault(_createClass2);
var _possibleConstructorReturn2 = require('babel-runtime/helpers/possibleConstructorReturn');
var _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2);
var _inherits2 = require('babel-runtime/helpers/inherits');
var _inherits3 = _interopRequireDefault(_inherits2);
var _classnames = require('classnames');
var _classnames2 = _interopRequireDefault(_classnames);
var _react = require('react');
var _react2 = _interopRequireDefault(_react);
var _lib = require('../../lib');
function _interopRequireDefault(obj) |
/**
* A title sub-component for Accordion component
*/
var AccordionTitle = function (_Component) {
(0, _inherits3.default)(AccordionTitle, _Component);
function AccordionTitle() {
var _ref;
var _temp, _this, _ret;
(0, _classCallCheck3.default)(this, AccordionTitle);
for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
return _ret = (_temp = (_this = (0, _possibleConstructorReturn3.default)(this, (_ref = AccordionTitle.__proto__ || Object.getPrototypeOf(AccordionTitle)).call.apply(_ref, [this].concat(args))), _this), _this.handleClick = function (e) {
var onClick = _this.props.onClick;
if (onClick) onClick(e, _this.props);
}, _temp), (0, _possibleConstructorReturn3.default)(_this, _ret);
}
(0, _createClass3.default)(AccordionTitle, [{
key: 'render',
value: function render() {
var _props = this.props,
active = _props.active,
children = _props.children,
className = _props.className;
var classes = (0, _classnames2.default)((0, _lib.useKeyOnly)(active, 'active'), 'title', className);
var rest = (0, _lib.getUnhandledProps)(AccordionTitle, this.props);
var ElementType = (0, _lib.getElementType)(AccordionTitle, this.props);
return _react2.default.createElement(
ElementType,
(0, _extends3.default)({}, rest, { className: classes, onClick: this.handleClick }),
children
);
}
}]);
return AccordionTitle;
}(_react.Component);
AccordionTitle.displayName = 'AccordionTitle';
AccordionTitle._meta = {
name: 'AccordionTitle',
type: _lib.META.TYPES.MODULE,
parent: 'Accordion'
};
exports.default = AccordionTitle;
process.env.NODE_ENV !== "production" ? AccordionTitle.propTypes = {
/** An element type to render as (string or function). */
as: _lib.customPropTypes.as,
/** Whether or not the title is in the open state. */
active: _react.PropTypes.bool,
/** Primary content. */
children: _react.PropTypes.node,
/** Additional classes. */
className: _react.PropTypes.string,
/**
* Called on blur.
*
* @param {SyntheticEvent} event - React's original SyntheticEvent.
* @param {object} data - All props.
*/
onClick: _react.PropTypes.func
} : void 0;
AccordionTitle.handledProps = ['active', 'as', 'children', 'className', 'onClick']; | { return obj && obj.__esModule ? obj : { default: obj }; } | identifier_body |
AccordionTitle.js | 'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _extends2 = require('babel-runtime/helpers/extends');
var _extends3 = _interopRequireDefault(_extends2);
var _classCallCheck2 = require('babel-runtime/helpers/classCallCheck');
var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);
var _createClass2 = require('babel-runtime/helpers/createClass');
var _createClass3 = _interopRequireDefault(_createClass2);
var _possibleConstructorReturn2 = require('babel-runtime/helpers/possibleConstructorReturn');
var _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2);
var _inherits2 = require('babel-runtime/helpers/inherits');
var _inherits3 = _interopRequireDefault(_inherits2);
var _classnames = require('classnames');
var _classnames2 = _interopRequireDefault(_classnames);
var _react = require('react');
var _react2 = _interopRequireDefault(_react);
var _lib = require('../../lib');
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/**
* A title sub-component for Accordion component
*/
var AccordionTitle = function (_Component) {
(0, _inherits3.default)(AccordionTitle, _Component);
function AccordionTitle() {
var _ref;
var _temp, _this, _ret;
(0, _classCallCheck3.default)(this, AccordionTitle);
for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) |
return _ret = (_temp = (_this = (0, _possibleConstructorReturn3.default)(this, (_ref = AccordionTitle.__proto__ || Object.getPrototypeOf(AccordionTitle)).call.apply(_ref, [this].concat(args))), _this), _this.handleClick = function (e) {
var onClick = _this.props.onClick;
if (onClick) onClick(e, _this.props);
}, _temp), (0, _possibleConstructorReturn3.default)(_this, _ret);
}
(0, _createClass3.default)(AccordionTitle, [{
key: 'render',
value: function render() {
var _props = this.props,
active = _props.active,
children = _props.children,
className = _props.className;
var classes = (0, _classnames2.default)((0, _lib.useKeyOnly)(active, 'active'), 'title', className);
var rest = (0, _lib.getUnhandledProps)(AccordionTitle, this.props);
var ElementType = (0, _lib.getElementType)(AccordionTitle, this.props);
return _react2.default.createElement(
ElementType,
(0, _extends3.default)({}, rest, { className: classes, onClick: this.handleClick }),
children
);
}
}]);
return AccordionTitle;
}(_react.Component);
AccordionTitle.displayName = 'AccordionTitle';
AccordionTitle._meta = {
name: 'AccordionTitle',
type: _lib.META.TYPES.MODULE,
parent: 'Accordion'
};
exports.default = AccordionTitle;
process.env.NODE_ENV !== "production" ? AccordionTitle.propTypes = {
/** An element type to render as (string or function). */
as: _lib.customPropTypes.as,
/** Whether or not the title is in the open state. */
active: _react.PropTypes.bool,
/** Primary content. */
children: _react.PropTypes.node,
/** Additional classes. */
className: _react.PropTypes.string,
/**
* Called on blur.
*
* @param {SyntheticEvent} event - React's original SyntheticEvent.
* @param {object} data - All props.
*/
onClick: _react.PropTypes.func
} : void 0;
AccordionTitle.handledProps = ['active', 'as', 'children', 'className', 'onClick']; | {
args[_key] = arguments[_key];
} | conditional_block |
AccordionTitle.js | 'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _extends2 = require('babel-runtime/helpers/extends');
var _extends3 = _interopRequireDefault(_extends2);
var _classCallCheck2 = require('babel-runtime/helpers/classCallCheck');
var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);
var _createClass2 = require('babel-runtime/helpers/createClass');
var _createClass3 = _interopRequireDefault(_createClass2);
var _possibleConstructorReturn2 = require('babel-runtime/helpers/possibleConstructorReturn');
var _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2);
var _inherits2 = require('babel-runtime/helpers/inherits');
var _inherits3 = _interopRequireDefault(_inherits2);
var _classnames = require('classnames');
var _classnames2 = _interopRequireDefault(_classnames);
var _react = require('react');
var _react2 = _interopRequireDefault(_react);
var _lib = require('../../lib');
function | (obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/**
* A title sub-component for Accordion component
*/
var AccordionTitle = function (_Component) {
(0, _inherits3.default)(AccordionTitle, _Component);
function AccordionTitle() {
var _ref;
var _temp, _this, _ret;
(0, _classCallCheck3.default)(this, AccordionTitle);
for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
return _ret = (_temp = (_this = (0, _possibleConstructorReturn3.default)(this, (_ref = AccordionTitle.__proto__ || Object.getPrototypeOf(AccordionTitle)).call.apply(_ref, [this].concat(args))), _this), _this.handleClick = function (e) {
var onClick = _this.props.onClick;
if (onClick) onClick(e, _this.props);
}, _temp), (0, _possibleConstructorReturn3.default)(_this, _ret);
}
(0, _createClass3.default)(AccordionTitle, [{
key: 'render',
value: function render() {
var _props = this.props,
active = _props.active,
children = _props.children,
className = _props.className;
var classes = (0, _classnames2.default)((0, _lib.useKeyOnly)(active, 'active'), 'title', className);
var rest = (0, _lib.getUnhandledProps)(AccordionTitle, this.props);
var ElementType = (0, _lib.getElementType)(AccordionTitle, this.props);
return _react2.default.createElement(
ElementType,
(0, _extends3.default)({}, rest, { className: classes, onClick: this.handleClick }),
children
);
}
}]);
return AccordionTitle;
}(_react.Component);
AccordionTitle.displayName = 'AccordionTitle';
AccordionTitle._meta = {
name: 'AccordionTitle',
type: _lib.META.TYPES.MODULE,
parent: 'Accordion'
};
exports.default = AccordionTitle;
process.env.NODE_ENV !== "production" ? AccordionTitle.propTypes = {
/** An element type to render as (string or function). */
as: _lib.customPropTypes.as,
/** Whether or not the title is in the open state. */
active: _react.PropTypes.bool,
/** Primary content. */
children: _react.PropTypes.node,
/** Additional classes. */
className: _react.PropTypes.string,
/**
* Called on blur.
*
* @param {SyntheticEvent} event - React's original SyntheticEvent.
* @param {object} data - All props.
*/
onClick: _react.PropTypes.func
} : void 0;
AccordionTitle.handledProps = ['active', 'as', 'children', 'className', 'onClick']; | _interopRequireDefault | identifier_name |
AccordionTitle.js | 'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _extends2 = require('babel-runtime/helpers/extends');
var _extends3 = _interopRequireDefault(_extends2);
var _classCallCheck2 = require('babel-runtime/helpers/classCallCheck');
var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);
var _createClass2 = require('babel-runtime/helpers/createClass');
var _createClass3 = _interopRequireDefault(_createClass2);
var _possibleConstructorReturn2 = require('babel-runtime/helpers/possibleConstructorReturn');
var _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2);
var _inherits2 = require('babel-runtime/helpers/inherits');
var _inherits3 = _interopRequireDefault(_inherits2);
var _classnames = require('classnames');
var _classnames2 = _interopRequireDefault(_classnames);
var _react = require('react');
var _react2 = _interopRequireDefault(_react);
| function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/**
* A title sub-component for Accordion component
*/
var AccordionTitle = function (_Component) {
(0, _inherits3.default)(AccordionTitle, _Component);
function AccordionTitle() {
var _ref;
var _temp, _this, _ret;
(0, _classCallCheck3.default)(this, AccordionTitle);
for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
return _ret = (_temp = (_this = (0, _possibleConstructorReturn3.default)(this, (_ref = AccordionTitle.__proto__ || Object.getPrototypeOf(AccordionTitle)).call.apply(_ref, [this].concat(args))), _this), _this.handleClick = function (e) {
var onClick = _this.props.onClick;
if (onClick) onClick(e, _this.props);
}, _temp), (0, _possibleConstructorReturn3.default)(_this, _ret);
}
(0, _createClass3.default)(AccordionTitle, [{
key: 'render',
value: function render() {
var _props = this.props,
active = _props.active,
children = _props.children,
className = _props.className;
var classes = (0, _classnames2.default)((0, _lib.useKeyOnly)(active, 'active'), 'title', className);
var rest = (0, _lib.getUnhandledProps)(AccordionTitle, this.props);
var ElementType = (0, _lib.getElementType)(AccordionTitle, this.props);
return _react2.default.createElement(
ElementType,
(0, _extends3.default)({}, rest, { className: classes, onClick: this.handleClick }),
children
);
}
}]);
return AccordionTitle;
}(_react.Component);
AccordionTitle.displayName = 'AccordionTitle';
AccordionTitle._meta = {
name: 'AccordionTitle',
type: _lib.META.TYPES.MODULE,
parent: 'Accordion'
};
exports.default = AccordionTitle;
process.env.NODE_ENV !== "production" ? AccordionTitle.propTypes = {
/** An element type to render as (string or function). */
as: _lib.customPropTypes.as,
/** Whether or not the title is in the open state. */
active: _react.PropTypes.bool,
/** Primary content. */
children: _react.PropTypes.node,
/** Additional classes. */
className: _react.PropTypes.string,
/**
* Called on blur.
*
* @param {SyntheticEvent} event - React's original SyntheticEvent.
* @param {object} data - All props.
*/
onClick: _react.PropTypes.func
} : void 0;
AccordionTitle.handledProps = ['active', 'as', 'children', 'className', 'onClick']; | var _lib = require('../../lib');
| random_line_split |
preprocessor_tests.rs | // Copyright (c) The Diem Core Contributors
// SPDX-License-Identifier: Apache-2.0
use crate::{
errors::*,
preprocessor::{build_transactions, extract_global_config, split_input},
};
fn parse_input(input: &str) -> Result<()> {
let config = extract_global_config("".lines(), false)?;
let (_, transactions) = split_input(input.lines(), &config)?;
build_transactions(&config, &transactions)?;
Ok(())
}
#[test]
fn parse_input_no_transactions() {
parse_input("").unwrap_err();
}
#[test]
fn parse_input_no_transactions_with_config() {
parse_input("//! no-run: verifier").unwrap_err();
}
#[rustfmt::skip]
#[test]
fn parse_input_nothing_before_first_empty_transaction() {
parse_input(r"
//! new-transaction
main() {}
").unwrap();
}
#[rustfmt::skip]
#[test]
fn parse_input_config_before_first_empty_transaction() {
parse_input(r"
//! no-run: runtime
//! new-transaction
main() {}
").unwrap_err();
}
#[rustfmt::skip]
#[test]
fn | () {
parse_input(r"
main() {}
//! new-transaction
//! new-transaction
main() {}
").unwrap_err();
}
#[rustfmt::skip]
#[test]
fn parse_input_empty_transaction_with_config() {
parse_input(r"
main() {}
//! new-transaction
//! sender: default
//! new-transaction
main() {}
").unwrap_err();
}
| parse_input_empty_transaction | identifier_name |
preprocessor_tests.rs | // Copyright (c) The Diem Core Contributors
// SPDX-License-Identifier: Apache-2.0
use crate::{
errors::*,
preprocessor::{build_transactions, extract_global_config, split_input},
};
fn parse_input(input: &str) -> Result<()> {
let config = extract_global_config("".lines(), false)?;
let (_, transactions) = split_input(input.lines(), &config)?;
build_transactions(&config, &transactions)?;
Ok(())
}
#[test]
fn parse_input_no_transactions() |
#[test]
fn parse_input_no_transactions_with_config() {
parse_input("//! no-run: verifier").unwrap_err();
}
#[rustfmt::skip]
#[test]
fn parse_input_nothing_before_first_empty_transaction() {
parse_input(r"
//! new-transaction
main() {}
").unwrap();
}
#[rustfmt::skip]
#[test]
fn parse_input_config_before_first_empty_transaction() {
parse_input(r"
//! no-run: runtime
//! new-transaction
main() {}
").unwrap_err();
}
#[rustfmt::skip]
#[test]
fn parse_input_empty_transaction() {
parse_input(r"
main() {}
//! new-transaction
//! new-transaction
main() {}
").unwrap_err();
}
#[rustfmt::skip]
#[test]
fn parse_input_empty_transaction_with_config() {
parse_input(r"
main() {}
//! new-transaction
//! sender: default
//! new-transaction
main() {}
").unwrap_err();
}
| {
parse_input("").unwrap_err();
} | identifier_body |
preprocessor_tests.rs | // Copyright (c) The Diem Core Contributors
// SPDX-License-Identifier: Apache-2.0
use crate::{
errors::*,
preprocessor::{build_transactions, extract_global_config, split_input},
};
| build_transactions(&config, &transactions)?;
Ok(())
}
#[test]
fn parse_input_no_transactions() {
parse_input("").unwrap_err();
}
#[test]
fn parse_input_no_transactions_with_config() {
parse_input("//! no-run: verifier").unwrap_err();
}
#[rustfmt::skip]
#[test]
fn parse_input_nothing_before_first_empty_transaction() {
parse_input(r"
//! new-transaction
main() {}
").unwrap();
}
#[rustfmt::skip]
#[test]
fn parse_input_config_before_first_empty_transaction() {
parse_input(r"
//! no-run: runtime
//! new-transaction
main() {}
").unwrap_err();
}
#[rustfmt::skip]
#[test]
fn parse_input_empty_transaction() {
parse_input(r"
main() {}
//! new-transaction
//! new-transaction
main() {}
").unwrap_err();
}
#[rustfmt::skip]
#[test]
fn parse_input_empty_transaction_with_config() {
parse_input(r"
main() {}
//! new-transaction
//! sender: default
//! new-transaction
main() {}
").unwrap_err();
} | fn parse_input(input: &str) -> Result<()> {
let config = extract_global_config("".lines(), false)?;
let (_, transactions) = split_input(input.lines(), &config)?; | random_line_split |
boxes.rs | // This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at https://mozilla.org/MPL/2.0/.
use std::fmt;
macro_rules! box_database {
($($boxenum:ident $boxtype:expr),*,) => {
#[derive(Clone, Copy, PartialEq)]
pub enum BoxType {
$($boxenum),*,
UnknownBox(u32),
}
| impl From<u32> for BoxType {
fn from(t: u32) -> BoxType {
use self::BoxType::*;
match t {
$($boxtype => $boxenum),*,
_ => UnknownBox(t),
}
}
}
impl Into<u32> for BoxType {
fn into(self) -> u32 {
use self::BoxType::*;
match self {
$($boxenum => $boxtype),*,
UnknownBox(t) => t,
}
}
}
impl fmt::Debug for BoxType {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let fourcc: FourCC = From::from(self.clone());
write!(f, "{}", fourcc)
}
}
}
}
#[derive(Default, PartialEq, Clone)]
pub struct FourCC {
pub value: String
}
impl From<u32> for FourCC {
fn from(number: u32) -> FourCC {
let mut box_chars = Vec::new();
for x in 0..4 {
let c = (number >> (x * 8) & 0x0000_00FF) as u8;
box_chars.push(c);
}
box_chars.reverse();
let box_string = match String::from_utf8(box_chars) {
Ok(t) => t,
_ => String::from("null"), // error to retrieve fourcc
};
FourCC {
value: box_string
}
}
}
impl From<BoxType> for FourCC {
fn from(t: BoxType) -> FourCC {
let box_num: u32 = Into::into(t);
From::from(box_num)
}
}
impl<'a> From<&'a str> for FourCC {
fn from(v: &'a str) -> FourCC {
FourCC {
value: v.to_owned()
}
}
}
impl fmt::Debug for FourCC {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}", self.value)
}
}
impl fmt::Display for FourCC {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}", self.value)
}
}
box_database!(
FileTypeBox 0x6674_7970, // "ftyp"
MovieBox 0x6d6f_6f76, // "moov"
MovieHeaderBox 0x6d76_6864, // "mvhd"
TrackBox 0x7472_616b, // "trak"
TrackHeaderBox 0x746b_6864, // "tkhd"
EditBox 0x6564_7473, // "edts"
MediaBox 0x6d64_6961, // "mdia"
EditListBox 0x656c_7374, // "elst"
MediaHeaderBox 0x6d64_6864, // "mdhd"
HandlerBox 0x6864_6c72, // "hdlr"
MediaInformationBox 0x6d69_6e66, // "minf"
SampleTableBox 0x7374_626c, // "stbl"
SampleDescriptionBox 0x7374_7364, // "stsd"
TimeToSampleBox 0x7374_7473, // "stts"
SampleToChunkBox 0x7374_7363, // "stsc"
SampleSizeBox 0x7374_737a, // "stsz"
ChunkOffsetBox 0x7374_636f, // "stco"
ChunkLargeOffsetBox 0x636f_3634, // "co64"
SyncSampleBox 0x7374_7373, // "stss"
AVCSampleEntry 0x6176_6331, // "avc1"
AVC3SampleEntry 0x6176_6333, // "avc3" - Need to check official name in spec.
AVCConfigurationBox 0x6176_6343, // "avcC"
MP4AudioSampleEntry 0x6d70_3461, // "mp4a"
MP4VideoSampleEntry 0x6d70_3476, // "mp4v"
ESDBox 0x6573_6473, // "esds"
VP8SampleEntry 0x7670_3038, // "vp08"
VP9SampleEntry 0x7670_3039, // "vp09"
VPCodecConfigurationBox 0x7670_6343, // "vpcC"
AV1SampleEntry 0x6176_3031, // "av01"
AV1CodecConfigurationBox 0x6176_3143, // "av1C"
FLACSampleEntry 0x664c_6143, // "fLaC"
FLACSpecificBox 0x6466_4c61, // "dfLa"
OpusSampleEntry 0x4f70_7573, // "Opus"
OpusSpecificBox 0x644f_7073, // "dOps"
ProtectedVisualSampleEntry 0x656e_6376, // "encv" - Need to check official name in spec.
ProtectedAudioSampleEntry 0x656e_6361, // "enca" - Need to check official name in spec.
MovieExtendsBox 0x6d76_6578, // "mvex"
MovieExtendsHeaderBox 0x6d65_6864, // "mehd"
QTWaveAtom 0x7761_7665, // "wave" - quicktime atom
ProtectionSystemSpecificHeaderBox 0x7073_7368, // "pssh"
SchemeInformationBox 0x7363_6869, // "schi"
TrackEncryptionBox 0x7465_6e63, // "tenc"
ProtectionSchemeInformationBox 0x7369_6e66, // "sinf"
OriginalFormatBox 0x6672_6d61, // "frma"
SchemeTypeBox 0x7363_686d, // "schm"
MP3AudioSampleEntry 0x2e6d_7033, // ".mp3" - from F4V.
CompositionOffsetBox 0x6374_7473, // "ctts"
LPCMAudioSampleEntry 0x6C70_636D, // "lpcm" - quicktime atom
ALACSpecificBox 0x616C_6163, // "alac" - Also used by ALACSampleEntry
UuidBox 0x7575_6964, // "uuid"
MetadataBox 0x6d65_7461, // "meta"
MetadataHeaderBox 0x6d68_6472, // "mhdr"
MetadataItemKeysBox 0x6b65_7973, // "keys"
MetadataItemListEntry 0x696c_7374, // "ilst"
MetadataItemDataEntry 0x6461_7461, // "data"
MetadataItemNameBox 0x6e61_6d65, // "name"
MetadataItemInformationBox 0x6974_6966, // "itif"
UserdataBox 0x7564_7461, // "udta"
AlbumEntry 0xa961_6c62, // "©alb"
ArtistEntry 0xa941_5254, // "©ART"
ArtistLowercaseEntry 0xa961_7274, // "©art"
AlbumArtistEntry 0x6141_5254, // "aART"
CommentEntry 0xa963_6d74, // "©cmt"
DateEntry 0xa964_6179, // "©day"
TitleEntry 0xa96e_616d, // "©nam"
CustomGenreEntry 0xa967_656e, // "©gen"
StandardGenreEntry 0x676e_7265, // "gnre"
TrackNumberEntry 0x7472_6b6e, // "trkn"
DiskNumberEntry 0x6469_736b, // "disk"
ComposerEntry 0xa977_7274, // "©wrt"
EncoderEntry 0xa974_6f6f, // "©too"
EncodedByEntry 0xa965_6e63, // "©enc"
TempoEntry 0x746d_706f, // "tmpo"
CopyrightEntry 0x6370_7274, // "cprt"
CompilationEntry 0x6370_696c, // "cpil"
CoverArtEntry 0x636f_7672, // "covr"
AdvisoryEntry 0x7274_6e67, // "rtng"
RatingEntry 0x7261_7465, // "rate"
GroupingEntry 0xa967_7270, // "©grp"
MediaTypeEntry 0x7374_696b, // "stik"
PodcastEntry 0x7063_7374, // "pcst"
CategoryEntry 0x6361_7467, // "catg"
KeywordEntry 0x6b65_7977, // "keyw"
PodcastUrlEntry 0x7075_726c, // "purl"
PodcastGuidEntry 0x6567_6964, // "egid"
DescriptionEntry 0x6465_7363, // "desc"
LongDescriptionEntry 0x6c64_6573, // "ldes"
LyricsEntry 0xa96c_7972, // "©lyr"
TVNetworkNameEntry 0x7476_6e6e, // "tvnn"
TVShowNameEntry 0x7476_7368, // "tvsh"
TVEpisodeNameEntry 0x7476_656e, // "tven"
TVSeasonNumberEntry 0x7476_736e, // "tvsn"
TVEpisodeNumberEntry 0x7476_6573, // "tves"
PurchaseDateEntry 0x7075_7264, // "purd"
GaplessPlaybackEntry 0x7067_6170, // "pgap"
OwnerEntry 0x6f77_6e72, // "ownr"
HDVideoEntry 0x6864_7664, // "hdvd"
SortNameEntry 0x736f_6e6d, // "sonm"
SortAlbumEntry 0x736f_616c, // "soal"
SortArtistEntry 0x736f_6172, // "soar"
SortAlbumArtistEntry 0x736f_6161, // "soaa"
SortComposerEntry 0x736f_636f, // "soco"
); | random_line_split | |
boxes.rs | // This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at https://mozilla.org/MPL/2.0/.
use std::fmt;
macro_rules! box_database {
($($boxenum:ident $boxtype:expr),*,) => {
#[derive(Clone, Copy, PartialEq)]
pub enum BoxType {
$($boxenum),*,
UnknownBox(u32),
}
impl From<u32> for BoxType {
fn from(t: u32) -> BoxType {
use self::BoxType::*;
match t {
$($boxtype => $boxenum),*,
_ => UnknownBox(t),
}
}
}
impl Into<u32> for BoxType {
fn into(self) -> u32 {
use self::BoxType::*;
match self {
$($boxenum => $boxtype),*,
UnknownBox(t) => t,
}
}
}
impl fmt::Debug for BoxType {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let fourcc: FourCC = From::from(self.clone());
write!(f, "{}", fourcc)
}
}
}
}
#[derive(Default, PartialEq, Clone)]
pub struct FourCC {
pub value: String
}
impl From<u32> for FourCC {
fn from(number: u32) -> FourCC {
let mut box_chars = Vec::new();
for x in 0..4 {
let c = (number >> (x * 8) & 0x0000_00FF) as u8;
box_chars.push(c);
}
box_chars.reverse();
let box_string = match String::from_utf8(box_chars) {
Ok(t) => t,
_ => String::from("null"), // error to retrieve fourcc
};
FourCC {
value: box_string
}
}
}
impl From<BoxType> for FourCC {
fn | (t: BoxType) -> FourCC {
let box_num: u32 = Into::into(t);
From::from(box_num)
}
}
impl<'a> From<&'a str> for FourCC {
fn from(v: &'a str) -> FourCC {
FourCC {
value: v.to_owned()
}
}
}
impl fmt::Debug for FourCC {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}", self.value)
}
}
impl fmt::Display for FourCC {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}", self.value)
}
}
box_database!(
FileTypeBox 0x6674_7970, // "ftyp"
MovieBox 0x6d6f_6f76, // "moov"
MovieHeaderBox 0x6d76_6864, // "mvhd"
TrackBox 0x7472_616b, // "trak"
TrackHeaderBox 0x746b_6864, // "tkhd"
EditBox 0x6564_7473, // "edts"
MediaBox 0x6d64_6961, // "mdia"
EditListBox 0x656c_7374, // "elst"
MediaHeaderBox 0x6d64_6864, // "mdhd"
HandlerBox 0x6864_6c72, // "hdlr"
MediaInformationBox 0x6d69_6e66, // "minf"
SampleTableBox 0x7374_626c, // "stbl"
SampleDescriptionBox 0x7374_7364, // "stsd"
TimeToSampleBox 0x7374_7473, // "stts"
SampleToChunkBox 0x7374_7363, // "stsc"
SampleSizeBox 0x7374_737a, // "stsz"
ChunkOffsetBox 0x7374_636f, // "stco"
ChunkLargeOffsetBox 0x636f_3634, // "co64"
SyncSampleBox 0x7374_7373, // "stss"
AVCSampleEntry 0x6176_6331, // "avc1"
AVC3SampleEntry 0x6176_6333, // "avc3" - Need to check official name in spec.
AVCConfigurationBox 0x6176_6343, // "avcC"
MP4AudioSampleEntry 0x6d70_3461, // "mp4a"
MP4VideoSampleEntry 0x6d70_3476, // "mp4v"
ESDBox 0x6573_6473, // "esds"
VP8SampleEntry 0x7670_3038, // "vp08"
VP9SampleEntry 0x7670_3039, // "vp09"
VPCodecConfigurationBox 0x7670_6343, // "vpcC"
AV1SampleEntry 0x6176_3031, // "av01"
AV1CodecConfigurationBox 0x6176_3143, // "av1C"
FLACSampleEntry 0x664c_6143, // "fLaC"
FLACSpecificBox 0x6466_4c61, // "dfLa"
OpusSampleEntry 0x4f70_7573, // "Opus"
OpusSpecificBox 0x644f_7073, // "dOps"
ProtectedVisualSampleEntry 0x656e_6376, // "encv" - Need to check official name in spec.
ProtectedAudioSampleEntry 0x656e_6361, // "enca" - Need to check official name in spec.
MovieExtendsBox 0x6d76_6578, // "mvex"
MovieExtendsHeaderBox 0x6d65_6864, // "mehd"
QTWaveAtom 0x7761_7665, // "wave" - quicktime atom
ProtectionSystemSpecificHeaderBox 0x7073_7368, // "pssh"
SchemeInformationBox 0x7363_6869, // "schi"
TrackEncryptionBox 0x7465_6e63, // "tenc"
ProtectionSchemeInformationBox 0x7369_6e66, // "sinf"
OriginalFormatBox 0x6672_6d61, // "frma"
SchemeTypeBox 0x7363_686d, // "schm"
MP3AudioSampleEntry 0x2e6d_7033, // ".mp3" - from F4V.
CompositionOffsetBox 0x6374_7473, // "ctts"
LPCMAudioSampleEntry 0x6C70_636D, // "lpcm" - quicktime atom
ALACSpecificBox 0x616C_6163, // "alac" - Also used by ALACSampleEntry
UuidBox 0x7575_6964, // "uuid"
MetadataBox 0x6d65_7461, // "meta"
MetadataHeaderBox 0x6d68_6472, // "mhdr"
MetadataItemKeysBox 0x6b65_7973, // "keys"
MetadataItemListEntry 0x696c_7374, // "ilst"
MetadataItemDataEntry 0x6461_7461, // "data"
MetadataItemNameBox 0x6e61_6d65, // "name"
MetadataItemInformationBox 0x6974_6966, // "itif"
UserdataBox 0x7564_7461, // "udta"
AlbumEntry 0xa961_6c62, // "©alb"
ArtistEntry 0xa941_5254, // "©ART"
ArtistLowercaseEntry 0xa961_7274, // "©art"
AlbumArtistEntry 0x6141_5254, // "aART"
CommentEntry 0xa963_6d74, // "©cmt"
DateEntry 0xa964_6179, // "©day"
TitleEntry 0xa96e_616d, // "©nam"
CustomGenreEntry 0xa967_656e, // "©gen"
StandardGenreEntry 0x676e_7265, // "gnre"
TrackNumberEntry 0x7472_6b6e, // "trkn"
DiskNumberEntry 0x6469_736b, // "disk"
ComposerEntry 0xa977_7274, // "©wrt"
EncoderEntry 0xa974_6f6f, // "©too"
EncodedByEntry 0xa965_6e63, // "©enc"
TempoEntry 0x746d_706f, // "tmpo"
CopyrightEntry 0x6370_7274, // "cprt"
CompilationEntry 0x6370_696c, // "cpil"
CoverArtEntry 0x636f_7672, // "covr"
AdvisoryEntry 0x7274_6e67, // "rtng"
RatingEntry 0x7261_7465, // "rate"
GroupingEntry 0xa967_7270, // "©grp"
MediaTypeEntry 0x7374_696b, // "stik"
PodcastEntry 0x7063_7374, // "pcst"
CategoryEntry 0x6361_7467, // "catg"
KeywordEntry 0x6b65_7977, // "keyw"
PodcastUrlEntry 0x7075_726c, // "purl"
PodcastGuidEntry 0x6567_6964, // "egid"
DescriptionEntry 0x6465_7363, // "desc"
LongDescriptionEntry 0x6c64_6573, // "ldes"
LyricsEntry 0xa96c_7972, // "©lyr"
TVNetworkNameEntry 0x7476_6e6e, // "tvnn"
TVShowNameEntry 0x7476_7368, // "tvsh"
TVEpisodeNameEntry 0x7476_656e, // "tven"
TVSeasonNumberEntry 0x7476_736e, // "tvsn"
TVEpisodeNumberEntry 0x7476_6573, // "tves"
PurchaseDateEntry 0x7075_7264, // "purd"
GaplessPlaybackEntry 0x7067_6170, // "pgap"
OwnerEntry 0x6f77_6e72, // "ownr"
HDVideoEntry 0x6864_7664, // "hdvd"
SortNameEntry 0x736f_6e6d, // "sonm"
SortAlbumEntry 0x736f_616c, // "soal"
SortArtistEntry 0x736f_6172, // "soar"
SortAlbumArtistEntry 0x736f_6161, // "soaa"
SortComposerEntry 0x736f_636f, // "soco"
);
| from | identifier_name |
boxes.rs | // This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at https://mozilla.org/MPL/2.0/.
use std::fmt;
macro_rules! box_database {
($($boxenum:ident $boxtype:expr),*,) => {
#[derive(Clone, Copy, PartialEq)]
pub enum BoxType {
$($boxenum),*,
UnknownBox(u32),
}
impl From<u32> for BoxType {
fn from(t: u32) -> BoxType {
use self::BoxType::*;
match t {
$($boxtype => $boxenum),*,
_ => UnknownBox(t),
}
}
}
impl Into<u32> for BoxType {
fn into(self) -> u32 {
use self::BoxType::*;
match self {
$($boxenum => $boxtype),*,
UnknownBox(t) => t,
}
}
}
impl fmt::Debug for BoxType {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let fourcc: FourCC = From::from(self.clone());
write!(f, "{}", fourcc)
}
}
}
}
#[derive(Default, PartialEq, Clone)]
pub struct FourCC {
pub value: String
}
impl From<u32> for FourCC {
fn from(number: u32) -> FourCC |
}
impl From<BoxType> for FourCC {
fn from(t: BoxType) -> FourCC {
let box_num: u32 = Into::into(t);
From::from(box_num)
}
}
impl<'a> From<&'a str> for FourCC {
fn from(v: &'a str) -> FourCC {
FourCC {
value: v.to_owned()
}
}
}
impl fmt::Debug for FourCC {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}", self.value)
}
}
impl fmt::Display for FourCC {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}", self.value)
}
}
box_database!(
FileTypeBox 0x6674_7970, // "ftyp"
MovieBox 0x6d6f_6f76, // "moov"
MovieHeaderBox 0x6d76_6864, // "mvhd"
TrackBox 0x7472_616b, // "trak"
TrackHeaderBox 0x746b_6864, // "tkhd"
EditBox 0x6564_7473, // "edts"
MediaBox 0x6d64_6961, // "mdia"
EditListBox 0x656c_7374, // "elst"
MediaHeaderBox 0x6d64_6864, // "mdhd"
HandlerBox 0x6864_6c72, // "hdlr"
MediaInformationBox 0x6d69_6e66, // "minf"
SampleTableBox 0x7374_626c, // "stbl"
SampleDescriptionBox 0x7374_7364, // "stsd"
TimeToSampleBox 0x7374_7473, // "stts"
SampleToChunkBox 0x7374_7363, // "stsc"
SampleSizeBox 0x7374_737a, // "stsz"
ChunkOffsetBox 0x7374_636f, // "stco"
ChunkLargeOffsetBox 0x636f_3634, // "co64"
SyncSampleBox 0x7374_7373, // "stss"
AVCSampleEntry 0x6176_6331, // "avc1"
AVC3SampleEntry 0x6176_6333, // "avc3" - Need to check official name in spec.
AVCConfigurationBox 0x6176_6343, // "avcC"
MP4AudioSampleEntry 0x6d70_3461, // "mp4a"
MP4VideoSampleEntry 0x6d70_3476, // "mp4v"
ESDBox 0x6573_6473, // "esds"
VP8SampleEntry 0x7670_3038, // "vp08"
VP9SampleEntry 0x7670_3039, // "vp09"
VPCodecConfigurationBox 0x7670_6343, // "vpcC"
AV1SampleEntry 0x6176_3031, // "av01"
AV1CodecConfigurationBox 0x6176_3143, // "av1C"
FLACSampleEntry 0x664c_6143, // "fLaC"
FLACSpecificBox 0x6466_4c61, // "dfLa"
OpusSampleEntry 0x4f70_7573, // "Opus"
OpusSpecificBox 0x644f_7073, // "dOps"
ProtectedVisualSampleEntry 0x656e_6376, // "encv" - Need to check official name in spec.
ProtectedAudioSampleEntry 0x656e_6361, // "enca" - Need to check official name in spec.
MovieExtendsBox 0x6d76_6578, // "mvex"
MovieExtendsHeaderBox 0x6d65_6864, // "mehd"
QTWaveAtom 0x7761_7665, // "wave" - quicktime atom
ProtectionSystemSpecificHeaderBox 0x7073_7368, // "pssh"
SchemeInformationBox 0x7363_6869, // "schi"
TrackEncryptionBox 0x7465_6e63, // "tenc"
ProtectionSchemeInformationBox 0x7369_6e66, // "sinf"
OriginalFormatBox 0x6672_6d61, // "frma"
SchemeTypeBox 0x7363_686d, // "schm"
MP3AudioSampleEntry 0x2e6d_7033, // ".mp3" - from F4V.
CompositionOffsetBox 0x6374_7473, // "ctts"
LPCMAudioSampleEntry 0x6C70_636D, // "lpcm" - quicktime atom
ALACSpecificBox 0x616C_6163, // "alac" - Also used by ALACSampleEntry
UuidBox 0x7575_6964, // "uuid"
MetadataBox 0x6d65_7461, // "meta"
MetadataHeaderBox 0x6d68_6472, // "mhdr"
MetadataItemKeysBox 0x6b65_7973, // "keys"
MetadataItemListEntry 0x696c_7374, // "ilst"
MetadataItemDataEntry 0x6461_7461, // "data"
MetadataItemNameBox 0x6e61_6d65, // "name"
MetadataItemInformationBox 0x6974_6966, // "itif"
UserdataBox 0x7564_7461, // "udta"
AlbumEntry 0xa961_6c62, // "©alb"
ArtistEntry 0xa941_5254, // "©ART"
ArtistLowercaseEntry 0xa961_7274, // "©art"
AlbumArtistEntry 0x6141_5254, // "aART"
CommentEntry 0xa963_6d74, // "©cmt"
DateEntry 0xa964_6179, // "©day"
TitleEntry 0xa96e_616d, // "©nam"
CustomGenreEntry 0xa967_656e, // "©gen"
StandardGenreEntry 0x676e_7265, // "gnre"
TrackNumberEntry 0x7472_6b6e, // "trkn"
DiskNumberEntry 0x6469_736b, // "disk"
ComposerEntry 0xa977_7274, // "©wrt"
EncoderEntry 0xa974_6f6f, // "©too"
EncodedByEntry 0xa965_6e63, // "©enc"
TempoEntry 0x746d_706f, // "tmpo"
CopyrightEntry 0x6370_7274, // "cprt"
CompilationEntry 0x6370_696c, // "cpil"
CoverArtEntry 0x636f_7672, // "covr"
AdvisoryEntry 0x7274_6e67, // "rtng"
RatingEntry 0x7261_7465, // "rate"
GroupingEntry 0xa967_7270, // "©grp"
MediaTypeEntry 0x7374_696b, // "stik"
PodcastEntry 0x7063_7374, // "pcst"
CategoryEntry 0x6361_7467, // "catg"
KeywordEntry 0x6b65_7977, // "keyw"
PodcastUrlEntry 0x7075_726c, // "purl"
PodcastGuidEntry 0x6567_6964, // "egid"
DescriptionEntry 0x6465_7363, // "desc"
LongDescriptionEntry 0x6c64_6573, // "ldes"
LyricsEntry 0xa96c_7972, // "©lyr"
TVNetworkNameEntry 0x7476_6e6e, // "tvnn"
TVShowNameEntry 0x7476_7368, // "tvsh"
TVEpisodeNameEntry 0x7476_656e, // "tven"
TVSeasonNumberEntry 0x7476_736e, // "tvsn"
TVEpisodeNumberEntry 0x7476_6573, // "tves"
PurchaseDateEntry 0x7075_7264, // "purd"
GaplessPlaybackEntry 0x7067_6170, // "pgap"
OwnerEntry 0x6f77_6e72, // "ownr"
HDVideoEntry 0x6864_7664, // "hdvd"
SortNameEntry 0x736f_6e6d, // "sonm"
SortAlbumEntry 0x736f_616c, // "soal"
SortArtistEntry 0x736f_6172, // "soar"
SortAlbumArtistEntry 0x736f_6161, // "soaa"
SortComposerEntry 0x736f_636f, // "soco"
);
| {
let mut box_chars = Vec::new();
for x in 0..4 {
let c = (number >> (x * 8) & 0x0000_00FF) as u8;
box_chars.push(c);
}
box_chars.reverse();
let box_string = match String::from_utf8(box_chars) {
Ok(t) => t,
_ => String::from("null"), // error to retrieve fourcc
};
FourCC {
value: box_string
}
} | identifier_body |
VideoWizard.py | from boxbranding import getBoxType, getMachineName, getMachineBuild, getBrandOEM, getMachineBrand
from Screens.Wizard import WizardSummary
from Screens.WizardLanguage import WizardLanguage
from Screens.Rc import Rc
from Components.AVSwitch import iAVSwitch
from Screens.Screen import Screen
from Components.Pixmap import Pixmap
from Components.config import config, ConfigBoolean, configfile
from Tools.Directories import resolveFilename, SCOPE_SKIN, SCOPE_ACTIVE_SKIN
from Tools.HardwareInfo import HardwareInfo
config.misc.showtestcard = ConfigBoolean(default = False)
boxtype = getBoxType()
has_rca = False
has_dvi = False
if boxtype in ('formuler3', 'enibox', 'mago', 'x2plus', 'sf3038', 'sf108', 'twinboxlcd', 'atemio6000', 'atemio6100', 'atemio6200', 'mbminiplus', 'vp7358ci', 'enibox', 'gbquad', 'gbquadplus', 'et5x00', 'et6000', 'et7000', 'et7500', 'et8500', 'classm', 'axodin', 'axodinc', 'genius', 'evo', 'galaxym6', 'geniuse3hd', 'evoe3hd', 'axase3', 'axase3c', 'starsatlx', 'mixosf7', 'mixoslumi', 'tmnano', 'azboxme', 'azboxminime', 'optimussos1', 'optimussos2', 'gb800seplus', 'gb800ueplus', 'gbultrase', 'gbultraue', 'sezam1000hd', 'ixussone', 'ixusszero', 'enfinity', 'marvel1', 'bre2ze', 'force1', 'force1plus', 'worldvisionf1', 'optimussos1plus', 'optimussos2plus', 'optimussos3plus', 'formuler1', 'tmnano2super', 'vusolose', 'vuzero', 'tyrant') or getMachineBrand() == 'Zgemma':
has_rca = True
if boxtype == 'dm8000' or boxtype == 'dm800':
has_dvi = True
class VideoWizardSummary(WizardSummary):
skin = (
"""<screen name="VideoWizardSummary" position="0,0" size="132,64" id="1">
<widget name="text" position="6,4" size="120,40" font="Regular;12" transparent="1" />
<widget source="parent.list" render="Label" position="6,40" size="120,21" font="Regular;14">
<convert type="StringListSelection" />
</widget>
<!--widget name="pic" pixmap="%s" position="6,22" zPosition="10" size="64,64" transparent="1" alphatest="on"/-->
</screen>""",
"""<screen name="VideoWizardSummary" position="0,0" size="96,64" id="2">
<widget name="text" position="0,4" size="96,40" font="Regular;12" transparent="1" />
<widget source="parent.list" render="Label" position="0,40" size="96,21" font="Regular;14">
<convert type="StringListSelection" />
</widget>
<!--widget name="pic" pixmap="%s" position="0,22" zPosition="10" size="64,64" transparent="1" alphatest="on"/-->
</screen>""")
#% (resolveFilename(SCOPE_PLUGINS, "SystemPlugins/Videomode/lcd_Scart.png"))
def __init__(self, session, parent):
WizardSummary.__init__(self, session, parent)
#self["pic"] = Pixmap()
def setLCDPicCallback(self):
self.parent.setLCDTextCallback(self.setText)
def setLCDPic(self, file):
self["pic"].instance.setPixmapFromFile(file)
class VideoWizard(WizardLanguage, Rc):
skin = """
<screen position="fill" title="Welcome..." flags="wfNoBorder" >
<panel name="WizardMarginsTemplate"/>
<panel name="WizardPictureLangTemplate"/>
<panel name="RemoteControlTemplate"/>
<panel position="left" size="10,*" />
<panel position="right" size="10,*" />
<panel position="fill">
<widget name="text" position="top" size="*,270" font="Regular;23" valign="center" />
<panel position="fill">
<panel position="left" size="150,*">
<widget name="portpic" position="top" zPosition="10" size="150,150" transparent="1" alphatest="on"/>
</panel>
<panel position="fill" layout="stack">
<widget source="list" render="Listbox" position="fill" scrollbarMode="showOnDemand" >
<convert type="StringList" />
</widget>
<!--<widget name="config" position="fill" zPosition="1" scrollbarMode="showOnDemand" />-->
</panel>
</panel>
</panel>
</screen>"""
def __init__(self, session):
# FIXME anyone knows how to use relative paths from the plugin's directory?
self.xmlfile = resolveFilename(SCOPE_SKIN, "videowizard.xml")
self.hw = iAVSwitch
WizardLanguage.__init__(self, session, showSteps = False, showStepSlider = False)
Rc.__init__(self)
self["wizard"] = Pixmap()
self["portpic"] = Pixmap()
Screen.setTitle(self, _("Welcome..."))
self.port = None
self.mode = None
self.rate = None
def createSummary(self):
return VideoWizardSummary
def markDone(self):
self.hw.saveMode(self.port, self.mode, self.rate)
config.misc.videowizardenabled.value = 0
config.misc.videowizardenabled.save()
configfile.save()
def listInputChannels(self):
hw_type = HardwareInfo().get_device_name()
has_hdmi = HardwareInfo().has_hdmi()
list = []
for port in self.hw.getPortList():
if self.hw.isPortUsed(port):
descr = port
if descr == 'HDMI' and has_dvi:
descr = 'DVI'
if descr == 'Scart' and has_rca:
descr = 'RCA'
if port != "DVI-PC":
list.append((descr,port))
list.sort(key = lambda x: x[0])
print "listInputChannels:", list
return list
def inputSelectionMade(self, index):
print "inputSelectionMade:", index
self.port = index
self.inputSelect(index)
def inputSelectionMoved(self):
hw_type = HardwareInfo().get_device_name()
has_hdmi = HardwareInfo().has_hdmi()
print "input selection moved:", self.selection
self.inputSelect(self.selection)
if self["portpic"].instance is not None:
picname = self.selection
if picname == 'HDMI' and has_dvi:
picname = "DVI"
if picname == 'Scart' and has_rca:
picname = "RCA"
self["portpic"].instance.setPixmapFromFile(resolveFilename(SCOPE_ACTIVE_SKIN, "icons/" + picname + ".png"))
def inputSelect(self, port):
print "inputSelect:", port
modeList = self.hw.getModeList(self.selection)
print "modeList:", modeList
self.port = port
if len(modeList) > 0:
ratesList = self.listRates(modeList[0][0])
self.hw.setMode(port = port, mode = modeList[0][0], rate = ratesList[0][0])
def listModes(self):
list = []
print "modes for port", self.port
for mode in self.hw.getModeList(self.port):
#if mode[0] != "PC":
list.append((mode[0], mode[0]))
print "modeslist:", list
list.sort()
return list
def modeSelectionMade(self, index):
|
def modeSelectionMoved(self):
print "mode selection moved:", self.selection
self.modeSelect(self.selection)
def modeSelect(self, mode):
ratesList = self.listRates(mode)
print "ratesList:", ratesList
if self.port == "HDMI" and mode in ("720p", "1080i", "1080p"):
self.rate = "multi"
self.hw.setMode(port = self.port, mode = mode, rate = "multi")
else:
self.hw.setMode(port = self.port, mode = mode, rate = ratesList[0][0])
def listRates(self, querymode = None):
if querymode is None:
querymode = self.mode
list = []
print "modes for port", self.port, "and mode", querymode
for mode in self.hw.getModeList(self.port):
print mode
if mode[0] == querymode:
for rate in mode[1]:
if self.port == "DVI-PC":
print "rate:", rate
if rate == "640x480":
list.insert(0, (rate, rate))
continue
list.append((rate, rate))
return list
def rateSelectionMade(self, index):
print "rateSelectionMade:", index
self.rate = index
self.rateSelect(index)
def rateSelectionMoved(self):
print "rate selection moved:", self.selection
self.rateSelect(self.selection)
def rateSelect(self, rate):
self.hw.setMode(port = self.port, mode = self.mode, rate = rate)
def showTestCard(self, selection = None):
if selection is None:
selection = self.selection
print "set config.misc.showtestcard to", {'yes': True, 'no': False}[selection]
if selection == "yes":
config.misc.showtestcard.value = True
else:
config.misc.showtestcard.value = False
def keyNumberGlobal(self, number):
if number in (1,2,3):
if number == 1:
self.hw.saveMode("HDMI", "720p", "multi")
elif number == 2:
self.hw.saveMode("HDMI", "1080i", "multi")
elif number == 3:
self.hw.saveMode("Scart", "Multi", "multi")
self.hw.setConfiguredMode()
self.close()
WizardLanguage.keyNumberGlobal(self, number)
| print "modeSelectionMade:", index
self.mode = index
self.modeSelect(index) | identifier_body |
VideoWizard.py | from boxbranding import getBoxType, getMachineName, getMachineBuild, getBrandOEM, getMachineBrand
from Screens.Wizard import WizardSummary
from Screens.WizardLanguage import WizardLanguage
from Screens.Rc import Rc
from Components.AVSwitch import iAVSwitch
from Screens.Screen import Screen
from Components.Pixmap import Pixmap
from Components.config import config, ConfigBoolean, configfile
from Tools.Directories import resolveFilename, SCOPE_SKIN, SCOPE_ACTIVE_SKIN
from Tools.HardwareInfo import HardwareInfo
config.misc.showtestcard = ConfigBoolean(default = False)
boxtype = getBoxType()
has_rca = False
has_dvi = False
if boxtype in ('formuler3', 'enibox', 'mago', 'x2plus', 'sf3038', 'sf108', 'twinboxlcd', 'atemio6000', 'atemio6100', 'atemio6200', 'mbminiplus', 'vp7358ci', 'enibox', 'gbquad', 'gbquadplus', 'et5x00', 'et6000', 'et7000', 'et7500', 'et8500', 'classm', 'axodin', 'axodinc', 'genius', 'evo', 'galaxym6', 'geniuse3hd', 'evoe3hd', 'axase3', 'axase3c', 'starsatlx', 'mixosf7', 'mixoslumi', 'tmnano', 'azboxme', 'azboxminime', 'optimussos1', 'optimussos2', 'gb800seplus', 'gb800ueplus', 'gbultrase', 'gbultraue', 'sezam1000hd', 'ixussone', 'ixusszero', 'enfinity', 'marvel1', 'bre2ze', 'force1', 'force1plus', 'worldvisionf1', 'optimussos1plus', 'optimussos2plus', 'optimussos3plus', 'formuler1', 'tmnano2super', 'vusolose', 'vuzero', 'tyrant') or getMachineBrand() == 'Zgemma':
has_rca = True
if boxtype == 'dm8000' or boxtype == 'dm800':
has_dvi = True
class VideoWizardSummary(WizardSummary):
skin = (
"""<screen name="VideoWizardSummary" position="0,0" size="132,64" id="1">
<widget name="text" position="6,4" size="120,40" font="Regular;12" transparent="1" />
<widget source="parent.list" render="Label" position="6,40" size="120,21" font="Regular;14">
<convert type="StringListSelection" />
</widget>
<!--widget name="pic" pixmap="%s" position="6,22" zPosition="10" size="64,64" transparent="1" alphatest="on"/-->
</screen>""",
"""<screen name="VideoWizardSummary" position="0,0" size="96,64" id="2">
<widget name="text" position="0,4" size="96,40" font="Regular;12" transparent="1" />
<widget source="parent.list" render="Label" position="0,40" size="96,21" font="Regular;14">
<convert type="StringListSelection" />
</widget>
<!--widget name="pic" pixmap="%s" position="0,22" zPosition="10" size="64,64" transparent="1" alphatest="on"/-->
</screen>""")
#% (resolveFilename(SCOPE_PLUGINS, "SystemPlugins/Videomode/lcd_Scart.png"))
def __init__(self, session, parent):
WizardSummary.__init__(self, session, parent)
#self["pic"] = Pixmap()
def setLCDPicCallback(self):
self.parent.setLCDTextCallback(self.setText)
def setLCDPic(self, file):
self["pic"].instance.setPixmapFromFile(file)
class VideoWizard(WizardLanguage, Rc):
skin = """
<screen position="fill" title="Welcome..." flags="wfNoBorder" >
<panel name="WizardMarginsTemplate"/>
<panel name="WizardPictureLangTemplate"/>
<panel name="RemoteControlTemplate"/>
<panel position="left" size="10,*" />
<panel position="right" size="10,*" />
<panel position="fill">
<widget name="text" position="top" size="*,270" font="Regular;23" valign="center" />
<panel position="fill">
<panel position="left" size="150,*">
<widget name="portpic" position="top" zPosition="10" size="150,150" transparent="1" alphatest="on"/>
</panel>
<panel position="fill" layout="stack">
<widget source="list" render="Listbox" position="fill" scrollbarMode="showOnDemand" >
<convert type="StringList" />
</widget>
<!--<widget name="config" position="fill" zPosition="1" scrollbarMode="showOnDemand" />-->
</panel>
</panel>
</panel>
</screen>"""
def __init__(self, session):
# FIXME anyone knows how to use relative paths from the plugin's directory?
self.xmlfile = resolveFilename(SCOPE_SKIN, "videowizard.xml")
self.hw = iAVSwitch
WizardLanguage.__init__(self, session, showSteps = False, showStepSlider = False)
Rc.__init__(self)
self["wizard"] = Pixmap()
self["portpic"] = Pixmap()
Screen.setTitle(self, _("Welcome..."))
self.port = None
self.mode = None
self.rate = None
def createSummary(self):
return VideoWizardSummary
def markDone(self):
self.hw.saveMode(self.port, self.mode, self.rate)
config.misc.videowizardenabled.value = 0
config.misc.videowizardenabled.save()
configfile.save()
def listInputChannels(self):
hw_type = HardwareInfo().get_device_name()
has_hdmi = HardwareInfo().has_hdmi()
list = []
for port in self.hw.getPortList():
if self.hw.isPortUsed(port):
descr = port
if descr == 'HDMI' and has_dvi:
descr = 'DVI'
if descr == 'Scart' and has_rca:
descr = 'RCA'
if port != "DVI-PC":
list.append((descr,port))
list.sort(key = lambda x: x[0])
print "listInputChannels:", list
return list
def inputSelectionMade(self, index):
print "inputSelectionMade:", index
self.port = index
self.inputSelect(index)
def inputSelectionMoved(self):
hw_type = HardwareInfo().get_device_name()
has_hdmi = HardwareInfo().has_hdmi()
print "input selection moved:", self.selection
self.inputSelect(self.selection)
if self["portpic"].instance is not None:
picname = self.selection
if picname == 'HDMI' and has_dvi:
picname = "DVI"
if picname == 'Scart' and has_rca:
picname = "RCA"
self["portpic"].instance.setPixmapFromFile(resolveFilename(SCOPE_ACTIVE_SKIN, "icons/" + picname + ".png"))
def inputSelect(self, port):
print "inputSelect:", port
modeList = self.hw.getModeList(self.selection)
print "modeList:", modeList
self.port = port
if len(modeList) > 0:
ratesList = self.listRates(modeList[0][0])
self.hw.setMode(port = port, mode = modeList[0][0], rate = ratesList[0][0])
def listModes(self):
list = []
print "modes for port", self.port
for mode in self.hw.getModeList(self.port):
#if mode[0] != "PC":
list.append((mode[0], mode[0]))
print "modeslist:", list
list.sort()
return list
def modeSelectionMade(self, index):
print "modeSelectionMade:", index
self.mode = index
self.modeSelect(index)
def modeSelectionMoved(self):
print "mode selection moved:", self.selection
self.modeSelect(self.selection)
def modeSelect(self, mode):
ratesList = self.listRates(mode)
print "ratesList:", ratesList
if self.port == "HDMI" and mode in ("720p", "1080i", "1080p"):
self.rate = "multi"
self.hw.setMode(port = self.port, mode = mode, rate = "multi")
else:
self.hw.setMode(port = self.port, mode = mode, rate = ratesList[0][0])
def listRates(self, querymode = None):
if querymode is None:
querymode = self.mode
list = []
print "modes for port", self.port, "and mode", querymode
for mode in self.hw.getModeList(self.port):
print mode
if mode[0] == querymode:
|
return list
def rateSelectionMade(self, index):
print "rateSelectionMade:", index
self.rate = index
self.rateSelect(index)
def rateSelectionMoved(self):
print "rate selection moved:", self.selection
self.rateSelect(self.selection)
def rateSelect(self, rate):
self.hw.setMode(port = self.port, mode = self.mode, rate = rate)
def showTestCard(self, selection = None):
if selection is None:
selection = self.selection
print "set config.misc.showtestcard to", {'yes': True, 'no': False}[selection]
if selection == "yes":
config.misc.showtestcard.value = True
else:
config.misc.showtestcard.value = False
def keyNumberGlobal(self, number):
if number in (1,2,3):
if number == 1:
self.hw.saveMode("HDMI", "720p", "multi")
elif number == 2:
self.hw.saveMode("HDMI", "1080i", "multi")
elif number == 3:
self.hw.saveMode("Scart", "Multi", "multi")
self.hw.setConfiguredMode()
self.close()
WizardLanguage.keyNumberGlobal(self, number)
| for rate in mode[1]:
if self.port == "DVI-PC":
print "rate:", rate
if rate == "640x480":
list.insert(0, (rate, rate))
continue
list.append((rate, rate)) | conditional_block |
VideoWizard.py | from boxbranding import getBoxType, getMachineName, getMachineBuild, getBrandOEM, getMachineBrand
from Screens.Wizard import WizardSummary
from Screens.WizardLanguage import WizardLanguage
from Screens.Rc import Rc
from Components.AVSwitch import iAVSwitch
from Screens.Screen import Screen
from Components.Pixmap import Pixmap
from Components.config import config, ConfigBoolean, configfile
from Tools.Directories import resolveFilename, SCOPE_SKIN, SCOPE_ACTIVE_SKIN
from Tools.HardwareInfo import HardwareInfo
config.misc.showtestcard = ConfigBoolean(default = False)
boxtype = getBoxType()
has_rca = False
has_dvi = False
if boxtype in ('formuler3', 'enibox', 'mago', 'x2plus', 'sf3038', 'sf108', 'twinboxlcd', 'atemio6000', 'atemio6100', 'atemio6200', 'mbminiplus', 'vp7358ci', 'enibox', 'gbquad', 'gbquadplus', 'et5x00', 'et6000', 'et7000', 'et7500', 'et8500', 'classm', 'axodin', 'axodinc', 'genius', 'evo', 'galaxym6', 'geniuse3hd', 'evoe3hd', 'axase3', 'axase3c', 'starsatlx', 'mixosf7', 'mixoslumi', 'tmnano', 'azboxme', 'azboxminime', 'optimussos1', 'optimussos2', 'gb800seplus', 'gb800ueplus', 'gbultrase', 'gbultraue', 'sezam1000hd', 'ixussone', 'ixusszero', 'enfinity', 'marvel1', 'bre2ze', 'force1', 'force1plus', 'worldvisionf1', 'optimussos1plus', 'optimussos2plus', 'optimussos3plus', 'formuler1', 'tmnano2super', 'vusolose', 'vuzero', 'tyrant') or getMachineBrand() == 'Zgemma':
has_rca = True
if boxtype == 'dm8000' or boxtype == 'dm800':
has_dvi = True
class VideoWizardSummary(WizardSummary):
skin = (
"""<screen name="VideoWizardSummary" position="0,0" size="132,64" id="1">
<widget name="text" position="6,4" size="120,40" font="Regular;12" transparent="1" />
<widget source="parent.list" render="Label" position="6,40" size="120,21" font="Regular;14">
<convert type="StringListSelection" />
</widget>
<!--widget name="pic" pixmap="%s" position="6,22" zPosition="10" size="64,64" transparent="1" alphatest="on"/-->
</screen>""",
"""<screen name="VideoWizardSummary" position="0,0" size="96,64" id="2">
<widget name="text" position="0,4" size="96,40" font="Regular;12" transparent="1" />
<widget source="parent.list" render="Label" position="0,40" size="96,21" font="Regular;14">
<convert type="StringListSelection" />
</widget>
<!--widget name="pic" pixmap="%s" position="0,22" zPosition="10" size="64,64" transparent="1" alphatest="on"/-->
</screen>""")
#% (resolveFilename(SCOPE_PLUGINS, "SystemPlugins/Videomode/lcd_Scart.png"))
def __init__(self, session, parent):
WizardSummary.__init__(self, session, parent)
#self["pic"] = Pixmap()
def setLCDPicCallback(self):
self.parent.setLCDTextCallback(self.setText)
def setLCDPic(self, file):
self["pic"].instance.setPixmapFromFile(file)
class VideoWizard(WizardLanguage, Rc):
skin = """
<screen position="fill" title="Welcome..." flags="wfNoBorder" >
<panel name="WizardMarginsTemplate"/>
<panel name="WizardPictureLangTemplate"/>
<panel name="RemoteControlTemplate"/>
<panel position="left" size="10,*" />
<panel position="right" size="10,*" />
<panel position="fill">
<widget name="text" position="top" size="*,270" font="Regular;23" valign="center" />
<panel position="fill">
<panel position="left" size="150,*">
<widget name="portpic" position="top" zPosition="10" size="150,150" transparent="1" alphatest="on"/>
</panel>
<panel position="fill" layout="stack">
<widget source="list" render="Listbox" position="fill" scrollbarMode="showOnDemand" >
<convert type="StringList" />
</widget>
<!--<widget name="config" position="fill" zPosition="1" scrollbarMode="showOnDemand" />-->
</panel>
</panel>
</panel>
</screen>"""
def __init__(self, session):
# FIXME anyone knows how to use relative paths from the plugin's directory?
self.xmlfile = resolveFilename(SCOPE_SKIN, "videowizard.xml")
self.hw = iAVSwitch
WizardLanguage.__init__(self, session, showSteps = False, showStepSlider = False)
Rc.__init__(self)
self["wizard"] = Pixmap()
self["portpic"] = Pixmap()
Screen.setTitle(self, _("Welcome..."))
self.port = None
self.mode = None
self.rate = None
def createSummary(self):
return VideoWizardSummary
def markDone(self):
self.hw.saveMode(self.port, self.mode, self.rate)
config.misc.videowizardenabled.value = 0
config.misc.videowizardenabled.save()
configfile.save()
def listInputChannels(self):
hw_type = HardwareInfo().get_device_name()
has_hdmi = HardwareInfo().has_hdmi()
list = []
for port in self.hw.getPortList():
if self.hw.isPortUsed(port):
descr = port
if descr == 'HDMI' and has_dvi:
descr = 'DVI'
if descr == 'Scart' and has_rca:
descr = 'RCA'
if port != "DVI-PC":
list.append((descr,port))
list.sort(key = lambda x: x[0])
print "listInputChannels:", list
return list
def inputSelectionMade(self, index):
print "inputSelectionMade:", index
self.port = index
self.inputSelect(index)
def inputSelectionMoved(self):
hw_type = HardwareInfo().get_device_name()
has_hdmi = HardwareInfo().has_hdmi()
print "input selection moved:", self.selection
self.inputSelect(self.selection)
if self["portpic"].instance is not None:
picname = self.selection
if picname == 'HDMI' and has_dvi:
picname = "DVI"
if picname == 'Scart' and has_rca:
picname = "RCA"
self["portpic"].instance.setPixmapFromFile(resolveFilename(SCOPE_ACTIVE_SKIN, "icons/" + picname + ".png"))
def inputSelect(self, port):
print "inputSelect:", port
modeList = self.hw.getModeList(self.selection)
print "modeList:", modeList
self.port = port | if len(modeList) > 0:
ratesList = self.listRates(modeList[0][0])
self.hw.setMode(port = port, mode = modeList[0][0], rate = ratesList[0][0])
def listModes(self):
list = []
print "modes for port", self.port
for mode in self.hw.getModeList(self.port):
#if mode[0] != "PC":
list.append((mode[0], mode[0]))
print "modeslist:", list
list.sort()
return list
def modeSelectionMade(self, index):
print "modeSelectionMade:", index
self.mode = index
self.modeSelect(index)
def modeSelectionMoved(self):
print "mode selection moved:", self.selection
self.modeSelect(self.selection)
def modeSelect(self, mode):
ratesList = self.listRates(mode)
print "ratesList:", ratesList
if self.port == "HDMI" and mode in ("720p", "1080i", "1080p"):
self.rate = "multi"
self.hw.setMode(port = self.port, mode = mode, rate = "multi")
else:
self.hw.setMode(port = self.port, mode = mode, rate = ratesList[0][0])
def listRates(self, querymode = None):
if querymode is None:
querymode = self.mode
list = []
print "modes for port", self.port, "and mode", querymode
for mode in self.hw.getModeList(self.port):
print mode
if mode[0] == querymode:
for rate in mode[1]:
if self.port == "DVI-PC":
print "rate:", rate
if rate == "640x480":
list.insert(0, (rate, rate))
continue
list.append((rate, rate))
return list
def rateSelectionMade(self, index):
print "rateSelectionMade:", index
self.rate = index
self.rateSelect(index)
def rateSelectionMoved(self):
print "rate selection moved:", self.selection
self.rateSelect(self.selection)
def rateSelect(self, rate):
self.hw.setMode(port = self.port, mode = self.mode, rate = rate)
def showTestCard(self, selection = None):
if selection is None:
selection = self.selection
print "set config.misc.showtestcard to", {'yes': True, 'no': False}[selection]
if selection == "yes":
config.misc.showtestcard.value = True
else:
config.misc.showtestcard.value = False
def keyNumberGlobal(self, number):
if number in (1,2,3):
if number == 1:
self.hw.saveMode("HDMI", "720p", "multi")
elif number == 2:
self.hw.saveMode("HDMI", "1080i", "multi")
elif number == 3:
self.hw.saveMode("Scart", "Multi", "multi")
self.hw.setConfiguredMode()
self.close()
WizardLanguage.keyNumberGlobal(self, number) | random_line_split | |
VideoWizard.py | from boxbranding import getBoxType, getMachineName, getMachineBuild, getBrandOEM, getMachineBrand
from Screens.Wizard import WizardSummary
from Screens.WizardLanguage import WizardLanguage
from Screens.Rc import Rc
from Components.AVSwitch import iAVSwitch
from Screens.Screen import Screen
from Components.Pixmap import Pixmap
from Components.config import config, ConfigBoolean, configfile
from Tools.Directories import resolveFilename, SCOPE_SKIN, SCOPE_ACTIVE_SKIN
from Tools.HardwareInfo import HardwareInfo
config.misc.showtestcard = ConfigBoolean(default = False)
boxtype = getBoxType()
has_rca = False
has_dvi = False
if boxtype in ('formuler3', 'enibox', 'mago', 'x2plus', 'sf3038', 'sf108', 'twinboxlcd', 'atemio6000', 'atemio6100', 'atemio6200', 'mbminiplus', 'vp7358ci', 'enibox', 'gbquad', 'gbquadplus', 'et5x00', 'et6000', 'et7000', 'et7500', 'et8500', 'classm', 'axodin', 'axodinc', 'genius', 'evo', 'galaxym6', 'geniuse3hd', 'evoe3hd', 'axase3', 'axase3c', 'starsatlx', 'mixosf7', 'mixoslumi', 'tmnano', 'azboxme', 'azboxminime', 'optimussos1', 'optimussos2', 'gb800seplus', 'gb800ueplus', 'gbultrase', 'gbultraue', 'sezam1000hd', 'ixussone', 'ixusszero', 'enfinity', 'marvel1', 'bre2ze', 'force1', 'force1plus', 'worldvisionf1', 'optimussos1plus', 'optimussos2plus', 'optimussos3plus', 'formuler1', 'tmnano2super', 'vusolose', 'vuzero', 'tyrant') or getMachineBrand() == 'Zgemma':
has_rca = True
if boxtype == 'dm8000' or boxtype == 'dm800':
has_dvi = True
class VideoWizardSummary(WizardSummary):
skin = (
"""<screen name="VideoWizardSummary" position="0,0" size="132,64" id="1">
<widget name="text" position="6,4" size="120,40" font="Regular;12" transparent="1" />
<widget source="parent.list" render="Label" position="6,40" size="120,21" font="Regular;14">
<convert type="StringListSelection" />
</widget>
<!--widget name="pic" pixmap="%s" position="6,22" zPosition="10" size="64,64" transparent="1" alphatest="on"/-->
</screen>""",
"""<screen name="VideoWizardSummary" position="0,0" size="96,64" id="2">
<widget name="text" position="0,4" size="96,40" font="Regular;12" transparent="1" />
<widget source="parent.list" render="Label" position="0,40" size="96,21" font="Regular;14">
<convert type="StringListSelection" />
</widget>
<!--widget name="pic" pixmap="%s" position="0,22" zPosition="10" size="64,64" transparent="1" alphatest="on"/-->
</screen>""")
#% (resolveFilename(SCOPE_PLUGINS, "SystemPlugins/Videomode/lcd_Scart.png"))
def __init__(self, session, parent):
WizardSummary.__init__(self, session, parent)
#self["pic"] = Pixmap()
def | (self):
self.parent.setLCDTextCallback(self.setText)
def setLCDPic(self, file):
self["pic"].instance.setPixmapFromFile(file)
class VideoWizard(WizardLanguage, Rc):
skin = """
<screen position="fill" title="Welcome..." flags="wfNoBorder" >
<panel name="WizardMarginsTemplate"/>
<panel name="WizardPictureLangTemplate"/>
<panel name="RemoteControlTemplate"/>
<panel position="left" size="10,*" />
<panel position="right" size="10,*" />
<panel position="fill">
<widget name="text" position="top" size="*,270" font="Regular;23" valign="center" />
<panel position="fill">
<panel position="left" size="150,*">
<widget name="portpic" position="top" zPosition="10" size="150,150" transparent="1" alphatest="on"/>
</panel>
<panel position="fill" layout="stack">
<widget source="list" render="Listbox" position="fill" scrollbarMode="showOnDemand" >
<convert type="StringList" />
</widget>
<!--<widget name="config" position="fill" zPosition="1" scrollbarMode="showOnDemand" />-->
</panel>
</panel>
</panel>
</screen>"""
def __init__(self, session):
# FIXME anyone knows how to use relative paths from the plugin's directory?
self.xmlfile = resolveFilename(SCOPE_SKIN, "videowizard.xml")
self.hw = iAVSwitch
WizardLanguage.__init__(self, session, showSteps = False, showStepSlider = False)
Rc.__init__(self)
self["wizard"] = Pixmap()
self["portpic"] = Pixmap()
Screen.setTitle(self, _("Welcome..."))
self.port = None
self.mode = None
self.rate = None
def createSummary(self):
return VideoWizardSummary
def markDone(self):
self.hw.saveMode(self.port, self.mode, self.rate)
config.misc.videowizardenabled.value = 0
config.misc.videowizardenabled.save()
configfile.save()
def listInputChannels(self):
hw_type = HardwareInfo().get_device_name()
has_hdmi = HardwareInfo().has_hdmi()
list = []
for port in self.hw.getPortList():
if self.hw.isPortUsed(port):
descr = port
if descr == 'HDMI' and has_dvi:
descr = 'DVI'
if descr == 'Scart' and has_rca:
descr = 'RCA'
if port != "DVI-PC":
list.append((descr,port))
list.sort(key = lambda x: x[0])
print "listInputChannels:", list
return list
def inputSelectionMade(self, index):
print "inputSelectionMade:", index
self.port = index
self.inputSelect(index)
def inputSelectionMoved(self):
hw_type = HardwareInfo().get_device_name()
has_hdmi = HardwareInfo().has_hdmi()
print "input selection moved:", self.selection
self.inputSelect(self.selection)
if self["portpic"].instance is not None:
picname = self.selection
if picname == 'HDMI' and has_dvi:
picname = "DVI"
if picname == 'Scart' and has_rca:
picname = "RCA"
self["portpic"].instance.setPixmapFromFile(resolveFilename(SCOPE_ACTIVE_SKIN, "icons/" + picname + ".png"))
def inputSelect(self, port):
print "inputSelect:", port
modeList = self.hw.getModeList(self.selection)
print "modeList:", modeList
self.port = port
if len(modeList) > 0:
ratesList = self.listRates(modeList[0][0])
self.hw.setMode(port = port, mode = modeList[0][0], rate = ratesList[0][0])
def listModes(self):
list = []
print "modes for port", self.port
for mode in self.hw.getModeList(self.port):
#if mode[0] != "PC":
list.append((mode[0], mode[0]))
print "modeslist:", list
list.sort()
return list
def modeSelectionMade(self, index):
print "modeSelectionMade:", index
self.mode = index
self.modeSelect(index)
def modeSelectionMoved(self):
print "mode selection moved:", self.selection
self.modeSelect(self.selection)
def modeSelect(self, mode):
ratesList = self.listRates(mode)
print "ratesList:", ratesList
if self.port == "HDMI" and mode in ("720p", "1080i", "1080p"):
self.rate = "multi"
self.hw.setMode(port = self.port, mode = mode, rate = "multi")
else:
self.hw.setMode(port = self.port, mode = mode, rate = ratesList[0][0])
def listRates(self, querymode = None):
if querymode is None:
querymode = self.mode
list = []
print "modes for port", self.port, "and mode", querymode
for mode in self.hw.getModeList(self.port):
print mode
if mode[0] == querymode:
for rate in mode[1]:
if self.port == "DVI-PC":
print "rate:", rate
if rate == "640x480":
list.insert(0, (rate, rate))
continue
list.append((rate, rate))
return list
def rateSelectionMade(self, index):
print "rateSelectionMade:", index
self.rate = index
self.rateSelect(index)
def rateSelectionMoved(self):
print "rate selection moved:", self.selection
self.rateSelect(self.selection)
def rateSelect(self, rate):
self.hw.setMode(port = self.port, mode = self.mode, rate = rate)
def showTestCard(self, selection = None):
if selection is None:
selection = self.selection
print "set config.misc.showtestcard to", {'yes': True, 'no': False}[selection]
if selection == "yes":
config.misc.showtestcard.value = True
else:
config.misc.showtestcard.value = False
def keyNumberGlobal(self, number):
if number in (1,2,3):
if number == 1:
self.hw.saveMode("HDMI", "720p", "multi")
elif number == 2:
self.hw.saveMode("HDMI", "1080i", "multi")
elif number == 3:
self.hw.saveMode("Scart", "Multi", "multi")
self.hw.setConfiguredMode()
self.close()
WizardLanguage.keyNumberGlobal(self, number)
| setLCDPicCallback | identifier_name |
Scene.ts | //missing
import {ISprite} from "browser/graphics/ISprite";
//convert-files
import {View} from "./View";
///<module="framework/ghost/events"/>
//convert-files
import {Sprite} from "./Sprite";
export class Scene extends Sprite
{
public static EVENT_CHANGE:string = "change";
public static EVENT_END: string = "end";
protected static STATE_PLAY: string = "play";
protected static STATE_STOP: string = "stop";
public views: View[];
protected viewsLength: number;
public children: ISprite[];
protected state_running: string;
public constructor()
|
public addView(view:View)
{
this.views.push(view);
this.viewsLength++;
view.on(View.EVENT_SIZE_CHANGE, this.viewChanged, this, view);
view.on(View.EVENT_CHANGE, this.viewChanged, this, view);
}
public play():void
{
if(this.state_running !== Scene.STATE_PLAY)
{
this.state_running = Scene.STATE_PLAY;
this.render();
}
}
protected viewChanged(view:View)
{
view.draw(this);
this.trigger(Scene.EVENT_CHANGE);
}
public draw(view: View): void {
var len: number = this.children.length;
for (var i: number = 0; i < len; i++) {
this.children[i].draw(view);
}
}
public pause():void
{
this.state_running = Scene.STATE_STOP;
}
protected render():void
{
for (var i: number = 0; i < this.viewsLength; i++)
{
this.views[i].draw(this);
}
if (this.state_running == Scene.STATE_PLAY)
{
requestAnimationFrame(this.render.bind(this));
}
}
}
| {
super();
this.views = [];
this.viewsLength = 0;
this.state_running = Scene.STATE_STOP;
} | identifier_body |
Scene.ts | //missing
import {ISprite} from "browser/graphics/ISprite";
//convert-files
import {View} from "./View";
///<module="framework/ghost/events"/>
//convert-files
import {Sprite} from "./Sprite";
export class Scene extends Sprite
{
public static EVENT_CHANGE:string = "change";
public static EVENT_END: string = "end";
protected static STATE_PLAY: string = "play";
protected static STATE_STOP: string = "stop";
public views: View[];
protected viewsLength: number;
public children: ISprite[];
protected state_running: string;
public constructor()
{
super();
this.views = [];
this.viewsLength = 0;
this.state_running = Scene.STATE_STOP;
}
public addView(view:View)
{
this.views.push(view);
this.viewsLength++;
view.on(View.EVENT_SIZE_CHANGE, this.viewChanged, this, view);
view.on(View.EVENT_CHANGE, this.viewChanged, this, view);
}
public play():void
{
if(this.state_running !== Scene.STATE_PLAY)
{
this.state_running = Scene.STATE_PLAY;
this.render();
}
}
protected viewChanged(view:View)
{
view.draw(this);
this.trigger(Scene.EVENT_CHANGE);
}
public draw(view: View): void {
var len: number = this.children.length;
for (var i: number = 0; i < len; i++) {
this.children[i].draw(view);
}
}
public pause():void
{
this.state_running = Scene.STATE_STOP;
}
protected render():void
{
for (var i: number = 0; i < this.viewsLength; i++)
{
this.views[i].draw(this);
}
if (this.state_running == Scene.STATE_PLAY)
|
}
}
| {
requestAnimationFrame(this.render.bind(this));
} | conditional_block |
Scene.ts | //missing
import {ISprite} from "browser/graphics/ISprite";
//convert-files
import {View} from "./View";
///<module="framework/ghost/events"/>
//convert-files
import {Sprite} from "./Sprite";
export class Scene extends Sprite
{
public static EVENT_CHANGE:string = "change";
public static EVENT_END: string = "end";
protected static STATE_PLAY: string = "play";
protected static STATE_STOP: string = "stop";
public views: View[];
protected viewsLength: number;
public children: ISprite[];
protected state_running: string;
public constructor() | this.viewsLength = 0;
this.state_running = Scene.STATE_STOP;
}
public addView(view:View)
{
this.views.push(view);
this.viewsLength++;
view.on(View.EVENT_SIZE_CHANGE, this.viewChanged, this, view);
view.on(View.EVENT_CHANGE, this.viewChanged, this, view);
}
public play():void
{
if(this.state_running !== Scene.STATE_PLAY)
{
this.state_running = Scene.STATE_PLAY;
this.render();
}
}
protected viewChanged(view:View)
{
view.draw(this);
this.trigger(Scene.EVENT_CHANGE);
}
public draw(view: View): void {
var len: number = this.children.length;
for (var i: number = 0; i < len; i++) {
this.children[i].draw(view);
}
}
public pause():void
{
this.state_running = Scene.STATE_STOP;
}
protected render():void
{
for (var i: number = 0; i < this.viewsLength; i++)
{
this.views[i].draw(this);
}
if (this.state_running == Scene.STATE_PLAY)
{
requestAnimationFrame(this.render.bind(this));
}
}
} | {
super();
this.views = []; | random_line_split |
Scene.ts | //missing
import {ISprite} from "browser/graphics/ISprite";
//convert-files
import {View} from "./View";
///<module="framework/ghost/events"/>
//convert-files
import {Sprite} from "./Sprite";
export class Scene extends Sprite
{
public static EVENT_CHANGE:string = "change";
public static EVENT_END: string = "end";
protected static STATE_PLAY: string = "play";
protected static STATE_STOP: string = "stop";
public views: View[];
protected viewsLength: number;
public children: ISprite[];
protected state_running: string;
public constructor()
{
super();
this.views = [];
this.viewsLength = 0;
this.state_running = Scene.STATE_STOP;
}
public addView(view:View)
{
this.views.push(view);
this.viewsLength++;
view.on(View.EVENT_SIZE_CHANGE, this.viewChanged, this, view);
view.on(View.EVENT_CHANGE, this.viewChanged, this, view);
}
public play():void
{
if(this.state_running !== Scene.STATE_PLAY)
{
this.state_running = Scene.STATE_PLAY;
this.render();
}
}
protected viewChanged(view:View)
{
view.draw(this);
this.trigger(Scene.EVENT_CHANGE);
}
public draw(view: View): void {
var len: number = this.children.length;
for (var i: number = 0; i < len; i++) {
this.children[i].draw(view);
}
}
public | ():void
{
this.state_running = Scene.STATE_STOP;
}
protected render():void
{
for (var i: number = 0; i < this.viewsLength; i++)
{
this.views[i].draw(this);
}
if (this.state_running == Scene.STATE_PLAY)
{
requestAnimationFrame(this.render.bind(this));
}
}
}
| pause | identifier_name |
ListProvider.ts | import {Model} from '../../models/base/Model';
import {Subject} from 'rxjs/Subject';
import {BaseService} from '../BaseService';
import {ActivatedRoute, Router} from '@angular/router';
import {UserRights, UserService} from '../../services/UserService';
import {ListTableColumn} from './ListTableColumn';
import {BehaviorSubject} from 'rxjs/BehaviorSubject';
import {SortDirection} from '../SortDirection';
import {ListTableColumnActionType, ListTableColumnType} from './ListEnums';
export class ListProvider<T extends Model> {
public currentPage = 1;
public itemsPerPage = 10;
public totalItems = 0;
public dataLoaded = false;
public items: Subject<T[]>;
public cardTitle = '';
public cardIcon = '';
public columns: ListTableColumn<T>[];
public sortDirection = SortDirection;
public columnTypes = ListTableColumnType;
public actionTypes = ListTableColumnActionType;
protected title = 'Список';
private sort = '-id';
public getRowClass: (model: T) => { [key: string]: boolean };
private static getSortKey(column: string, desc: boolean = false): string {
let sortKey = column;
if (desc) {
sortKey = '-' + sortKey;
}
return sortKey;
}
constructor(private service: BaseService<T>, private router: Router,
private route: ActivatedRoute, private _userService: UserService) {
}
| blic init() {
this.items = new BehaviorSubject<T[]>([]);
this.route.queryParamMap.subscribe(params => {
const pageNumber = parseInt(params.get('page'), 10);
if (pageNumber >= 1) {
this.currentPage = pageNumber;
}
const sort = params.get('sort');
if (sort != null) {
this.sort = sort;
const key = this.sort.replace('-', '');
const sortDirection = this.sort.indexOf('-') > -1 ? SortDirection.Desc : SortDirection.Asc;
this.columns.forEach(col => {
col.setSorted(col.Key === key ? sortDirection : null);
});
}
this.load(this.currentPage);
});
}
public applySort(column: string) {
let sortKey;
if (this.sort === column) {
sortKey = ListProvider.getSortKey(column, true);
} else {
sortKey = ListProvider.getSortKey(column);
}
this.sort = sortKey;
this.reload();
}
public changePage(page: number) {
this.currentPage = page;
this.reload();
}
public load(page?: number) {
page = page ? page : this.currentPage;
this.service.getList(page, this.itemsPerPage, this.sort).subscribe((res) => {
this.items.next(res.data);
this.totalItems = res.totalItems;
this.currentPage = page;
this.dataLoaded = true;
});
}
private reload() {
this.router.navigate([], {queryParams: {page: this.currentPage, sort: this.sort}, relativeTo: this.route});
}
public can(right: UserRights): boolean {
return this._userService.hasRight(right);
}
}
|
pu | identifier_body |
ListProvider.ts | import {Model} from '../../models/base/Model';
import {Subject} from 'rxjs/Subject';
import {BaseService} from '../BaseService';
import {ActivatedRoute, Router} from '@angular/router';
import {UserRights, UserService} from '../../services/UserService';
import {ListTableColumn} from './ListTableColumn';
import {BehaviorSubject} from 'rxjs/BehaviorSubject';
import {SortDirection} from '../SortDirection';
import {ListTableColumnActionType, ListTableColumnType} from './ListEnums';
export class ListProvider<T extends Model> {
public currentPage = 1;
public itemsPerPage = 10;
public totalItems = 0;
public dataLoaded = false;
public items: Subject<T[]>;
public cardTitle = '';
public cardIcon = '';
public columns: ListTableColumn<T>[];
public sortDirection = SortDirection;
public columnTypes = ListTableColumnType;
public actionTypes = ListTableColumnActionType;
protected title = 'Список';
private sort = '-id';
public getRowClass: (model: T) => { [key: string]: boolean };
private static getSortKey(column: string, desc: boolean = false): string {
let sortKey = column;
if (desc) {
| eturn sortKey;
}
constructor(private service: BaseService<T>, private router: Router,
private route: ActivatedRoute, private _userService: UserService) {
}
public init() {
this.items = new BehaviorSubject<T[]>([]);
this.route.queryParamMap.subscribe(params => {
const pageNumber = parseInt(params.get('page'), 10);
if (pageNumber >= 1) {
this.currentPage = pageNumber;
}
const sort = params.get('sort');
if (sort != null) {
this.sort = sort;
const key = this.sort.replace('-', '');
const sortDirection = this.sort.indexOf('-') > -1 ? SortDirection.Desc : SortDirection.Asc;
this.columns.forEach(col => {
col.setSorted(col.Key === key ? sortDirection : null);
});
}
this.load(this.currentPage);
});
}
public applySort(column: string) {
let sortKey;
if (this.sort === column) {
sortKey = ListProvider.getSortKey(column, true);
} else {
sortKey = ListProvider.getSortKey(column);
}
this.sort = sortKey;
this.reload();
}
public changePage(page: number) {
this.currentPage = page;
this.reload();
}
public load(page?: number) {
page = page ? page : this.currentPage;
this.service.getList(page, this.itemsPerPage, this.sort).subscribe((res) => {
this.items.next(res.data);
this.totalItems = res.totalItems;
this.currentPage = page;
this.dataLoaded = true;
});
}
private reload() {
this.router.navigate([], {queryParams: {page: this.currentPage, sort: this.sort}, relativeTo: this.route});
}
public can(right: UserRights): boolean {
return this._userService.hasRight(right);
}
}
| sortKey = '-' + sortKey;
}
r | conditional_block |
ListProvider.ts | import {Model} from '../../models/base/Model';
import {Subject} from 'rxjs/Subject';
import {BaseService} from '../BaseService';
import {ActivatedRoute, Router} from '@angular/router';
import {UserRights, UserService} from '../../services/UserService';
import {ListTableColumn} from './ListTableColumn';
import {BehaviorSubject} from 'rxjs/BehaviorSubject';
import {SortDirection} from '../SortDirection';
import {ListTableColumnActionType, ListTableColumnType} from './ListEnums';
export class ListProvider<T extends Model> {
public currentPage = 1;
public itemsPerPage = 10;
public totalItems = 0;
public dataLoaded = false;
public items: Subject<T[]>;
public cardTitle = '';
public cardIcon = '';
public columns: ListTableColumn<T>[];
public sortDirection = SortDirection;
public columnTypes = ListTableColumnType;
public actionTypes = ListTableColumnActionType;
protected title = 'Список';
private sort = '-id';
public getRowClass: (model: T) => { [key: string]: boolean };
private static getSortKey(column: string, desc: boolean = false): string {
let sortKey = column;
if (desc) {
sortKey = '-' + sortKey;
}
return sortKey;
}
constr | te service: BaseService<T>, private router: Router,
private route: ActivatedRoute, private _userService: UserService) {
}
public init() {
this.items = new BehaviorSubject<T[]>([]);
this.route.queryParamMap.subscribe(params => {
const pageNumber = parseInt(params.get('page'), 10);
if (pageNumber >= 1) {
this.currentPage = pageNumber;
}
const sort = params.get('sort');
if (sort != null) {
this.sort = sort;
const key = this.sort.replace('-', '');
const sortDirection = this.sort.indexOf('-') > -1 ? SortDirection.Desc : SortDirection.Asc;
this.columns.forEach(col => {
col.setSorted(col.Key === key ? sortDirection : null);
});
}
this.load(this.currentPage);
});
}
public applySort(column: string) {
let sortKey;
if (this.sort === column) {
sortKey = ListProvider.getSortKey(column, true);
} else {
sortKey = ListProvider.getSortKey(column);
}
this.sort = sortKey;
this.reload();
}
public changePage(page: number) {
this.currentPage = page;
this.reload();
}
public load(page?: number) {
page = page ? page : this.currentPage;
this.service.getList(page, this.itemsPerPage, this.sort).subscribe((res) => {
this.items.next(res.data);
this.totalItems = res.totalItems;
this.currentPage = page;
this.dataLoaded = true;
});
}
private reload() {
this.router.navigate([], {queryParams: {page: this.currentPage, sort: this.sort}, relativeTo: this.route});
}
public can(right: UserRights): boolean {
return this._userService.hasRight(right);
}
}
| uctor(priva | identifier_name |
ListProvider.ts | import {Model} from '../../models/base/Model';
import {Subject} from 'rxjs/Subject';
import {BaseService} from '../BaseService';
import {ActivatedRoute, Router} from '@angular/router';
import {UserRights, UserService} from '../../services/UserService';
import {ListTableColumn} from './ListTableColumn'; |
export class ListProvider<T extends Model> {
public currentPage = 1;
public itemsPerPage = 10;
public totalItems = 0;
public dataLoaded = false;
public items: Subject<T[]>;
public cardTitle = '';
public cardIcon = '';
public columns: ListTableColumn<T>[];
public sortDirection = SortDirection;
public columnTypes = ListTableColumnType;
public actionTypes = ListTableColumnActionType;
protected title = 'Список';
private sort = '-id';
public getRowClass: (model: T) => { [key: string]: boolean };
private static getSortKey(column: string, desc: boolean = false): string {
let sortKey = column;
if (desc) {
sortKey = '-' + sortKey;
}
return sortKey;
}
constructor(private service: BaseService<T>, private router: Router,
private route: ActivatedRoute, private _userService: UserService) {
}
public init() {
this.items = new BehaviorSubject<T[]>([]);
this.route.queryParamMap.subscribe(params => {
const pageNumber = parseInt(params.get('page'), 10);
if (pageNumber >= 1) {
this.currentPage = pageNumber;
}
const sort = params.get('sort');
if (sort != null) {
this.sort = sort;
const key = this.sort.replace('-', '');
const sortDirection = this.sort.indexOf('-') > -1 ? SortDirection.Desc : SortDirection.Asc;
this.columns.forEach(col => {
col.setSorted(col.Key === key ? sortDirection : null);
});
}
this.load(this.currentPage);
});
}
public applySort(column: string) {
let sortKey;
if (this.sort === column) {
sortKey = ListProvider.getSortKey(column, true);
} else {
sortKey = ListProvider.getSortKey(column);
}
this.sort = sortKey;
this.reload();
}
public changePage(page: number) {
this.currentPage = page;
this.reload();
}
public load(page?: number) {
page = page ? page : this.currentPage;
this.service.getList(page, this.itemsPerPage, this.sort).subscribe((res) => {
this.items.next(res.data);
this.totalItems = res.totalItems;
this.currentPage = page;
this.dataLoaded = true;
});
}
private reload() {
this.router.navigate([], {queryParams: {page: this.currentPage, sort: this.sort}, relativeTo: this.route});
}
public can(right: UserRights): boolean {
return this._userService.hasRight(right);
}
} | import {BehaviorSubject} from 'rxjs/BehaviorSubject';
import {SortDirection} from '../SortDirection';
import {ListTableColumnActionType, ListTableColumnType} from './ListEnums'; | random_line_split |
generator.py | def is_tl(data):
return isinstance(data, tuple) or isinstance(data, list)
def get_depth(data):
'''
:type data: list or tuple
get the depth of nested list
'x' is 0
['x', 'y'] is 1
['x', ['y', 'z'] is 2
'''
if is_tl(data):
depths = []
for i in data:
depths.append(1+get_depth(i))
return max(depths)
else:
return 0
def reduce_d2(a, b):
'''
generate all combination from a, b
'''
if not is_tl(a):
|
if not is_tl(b):
b = [b]
result = []
for i in a:
for j in b:
result.append('%s%s' % (i, j))
return result
def _generate_d2(data):
return reduce(reduce_d2, data)
def _generate(data):
'''
recursively generate the list
'''
depth = get_depth(data)
if depth > 2:
temp = []
for i in data:
temp.append(_generate(i))
return _generate(temp)
elif depth == 2:
return _generate_d2(data)
elif depth == 1:
return data
else:
return [str(data)]
def generate(data):
'''
:rtype: list of str
:type data: list or tuple
generate the final result
'''
result = _generate(data)
# fix if initial data's depth == 1
if result == data:
result = _generate_d2(data)
return result
if __name__ == '__main__':
nested = [range(2), [range(3), range(4)]]
print(generate(nested))
print(generate([1, [2, 3]]))
print(generate([1, 2]))
print(generate(1))
| a = [a] | conditional_block |
generator.py | def is_tl(data):
|
def get_depth(data):
'''
:type data: list or tuple
get the depth of nested list
'x' is 0
['x', 'y'] is 1
['x', ['y', 'z'] is 2
'''
if is_tl(data):
depths = []
for i in data:
depths.append(1+get_depth(i))
return max(depths)
else:
return 0
def reduce_d2(a, b):
'''
generate all combination from a, b
'''
if not is_tl(a):
a = [a]
if not is_tl(b):
b = [b]
result = []
for i in a:
for j in b:
result.append('%s%s' % (i, j))
return result
def _generate_d2(data):
return reduce(reduce_d2, data)
def _generate(data):
'''
recursively generate the list
'''
depth = get_depth(data)
if depth > 2:
temp = []
for i in data:
temp.append(_generate(i))
return _generate(temp)
elif depth == 2:
return _generate_d2(data)
elif depth == 1:
return data
else:
return [str(data)]
def generate(data):
'''
:rtype: list of str
:type data: list or tuple
generate the final result
'''
result = _generate(data)
# fix if initial data's depth == 1
if result == data:
result = _generate_d2(data)
return result
if __name__ == '__main__':
nested = [range(2), [range(3), range(4)]]
print(generate(nested))
print(generate([1, [2, 3]]))
print(generate([1, 2]))
print(generate(1))
| return isinstance(data, tuple) or isinstance(data, list) | identifier_body |
generator.py | def is_tl(data):
return isinstance(data, tuple) or isinstance(data, list)
def get_depth(data):
'''
:type data: list or tuple
get the depth of nested list
'x' is 0
['x', 'y'] is 1
['x', ['y', 'z'] is 2
'''
if is_tl(data):
depths = []
for i in data:
depths.append(1+get_depth(i))
return max(depths) |
def reduce_d2(a, b):
'''
generate all combination from a, b
'''
if not is_tl(a):
a = [a]
if not is_tl(b):
b = [b]
result = []
for i in a:
for j in b:
result.append('%s%s' % (i, j))
return result
def _generate_d2(data):
return reduce(reduce_d2, data)
def _generate(data):
'''
recursively generate the list
'''
depth = get_depth(data)
if depth > 2:
temp = []
for i in data:
temp.append(_generate(i))
return _generate(temp)
elif depth == 2:
return _generate_d2(data)
elif depth == 1:
return data
else:
return [str(data)]
def generate(data):
'''
:rtype: list of str
:type data: list or tuple
generate the final result
'''
result = _generate(data)
# fix if initial data's depth == 1
if result == data:
result = _generate_d2(data)
return result
if __name__ == '__main__':
nested = [range(2), [range(3), range(4)]]
print(generate(nested))
print(generate([1, [2, 3]]))
print(generate([1, 2]))
print(generate(1)) | else:
return 0
| random_line_split |
generator.py | def is_tl(data):
return isinstance(data, tuple) or isinstance(data, list)
def get_depth(data):
'''
:type data: list or tuple
get the depth of nested list
'x' is 0
['x', 'y'] is 1
['x', ['y', 'z'] is 2
'''
if is_tl(data):
depths = []
for i in data:
depths.append(1+get_depth(i))
return max(depths)
else:
return 0
def | (a, b):
'''
generate all combination from a, b
'''
if not is_tl(a):
a = [a]
if not is_tl(b):
b = [b]
result = []
for i in a:
for j in b:
result.append('%s%s' % (i, j))
return result
def _generate_d2(data):
return reduce(reduce_d2, data)
def _generate(data):
'''
recursively generate the list
'''
depth = get_depth(data)
if depth > 2:
temp = []
for i in data:
temp.append(_generate(i))
return _generate(temp)
elif depth == 2:
return _generate_d2(data)
elif depth == 1:
return data
else:
return [str(data)]
def generate(data):
'''
:rtype: list of str
:type data: list or tuple
generate the final result
'''
result = _generate(data)
# fix if initial data's depth == 1
if result == data:
result = _generate_d2(data)
return result
if __name__ == '__main__':
nested = [range(2), [range(3), range(4)]]
print(generate(nested))
print(generate([1, [2, 3]]))
print(generate([1, 2]))
print(generate(1))
| reduce_d2 | identifier_name |
index.tsx | import * as React from 'react';
import { Route, Switch } from 'react-router-dom';
import Header from '../Header/index';
import Home from '../Home/index';
import Login from '../Login/index';
import SignUp from '../SignUp/index';
import Dashboard from '../Dashboard/index';
import Settings from '../Settings/index';
import NotFoundPage from '../NotFound/index';
import Encounter from '../Encounter/index';
const routes: Array<any> = [
{
path: '/',
exact: true,
protectedPath: false,
header: () => <Header/>,
main: () => <Home/>,
},
{
path: '/login',
protectedPath: false,
header: () => <Header title="Login"/>,
main: () => <Login title="Login"/>,
},
{
path: '/signup',
protectedPath: false,
header: () => <Header title="Registration"/>,
main: () => <SignUp title="Registration"/>,
},
{
path: '/dashboard',
protectedPath: true,
header: () => <Header title="Dashboard"/>,
main: () => <Dashboard title="Dashboard"/>,
},
{
path: '/settings',
protectedPath: true,
header: () => <Header title="Settings"/>,
main: () => <Settings title="Settings"/>,
},
{
path: '/encounter',
protectedPath: true,
header: () => <Header title="Encounter"/>,
main: () => <Encounter title="Encounter"/>,
},
{
protectedPath: false,
header: () => <Header title="Page not found"/>,
main: () => <NotFoundPage title="Page not found"/>,
},
];
class | extends React.PureComponent<any, any> {
constructor(props: any, context: any) {
super(props, context);
}
render() {
const { auth, component: Component, ...rest } = this.props;
return (
<Route {...rest} render={props => {
if (!auth || !!localStorage.getItem('token')) {
return <Component {...props}/>;
} else {
const Redirect = require('react-router').Redirect;
return <Redirect to={{ pathname: '/login', state: { from: props.location } }}/>;
}
}}/>
)
}
}
const Routing = ({ component }: any) => (
<Switch>
{routes.map(
(route: any, index: number) => (
<PrivateRoute auth={route.protectedPath} key={index} path={route.path} exact={route.exact}
component={route[component]}/> ))}
</Switch>
);
export default Routing; | PrivateRoute | identifier_name |
index.tsx | import * as React from 'react';
import { Route, Switch } from 'react-router-dom';
import Header from '../Header/index';
import Home from '../Home/index';
import Login from '../Login/index';
import SignUp from '../SignUp/index';
import Dashboard from '../Dashboard/index';
import Settings from '../Settings/index';
import NotFoundPage from '../NotFound/index';
import Encounter from '../Encounter/index';
const routes: Array<any> = [
{
path: '/',
exact: true,
protectedPath: false,
header: () => <Header/>,
main: () => <Home/>,
},
{
path: '/login',
protectedPath: false,
header: () => <Header title="Login"/>,
main: () => <Login title="Login"/>,
},
{
path: '/signup',
protectedPath: false,
header: () => <Header title="Registration"/>,
main: () => <SignUp title="Registration"/>,
},
{
path: '/dashboard',
protectedPath: true,
header: () => <Header title="Dashboard"/>,
main: () => <Dashboard title="Dashboard"/>,
},
{
path: '/settings',
protectedPath: true,
header: () => <Header title="Settings"/>,
main: () => <Settings title="Settings"/>,
},
{ | main: () => <Encounter title="Encounter"/>,
},
{
protectedPath: false,
header: () => <Header title="Page not found"/>,
main: () => <NotFoundPage title="Page not found"/>,
},
];
class PrivateRoute extends React.PureComponent<any, any> {
constructor(props: any, context: any) {
super(props, context);
}
render() {
const { auth, component: Component, ...rest } = this.props;
return (
<Route {...rest} render={props => {
if (!auth || !!localStorage.getItem('token')) {
return <Component {...props}/>;
} else {
const Redirect = require('react-router').Redirect;
return <Redirect to={{ pathname: '/login', state: { from: props.location } }}/>;
}
}}/>
)
}
}
const Routing = ({ component }: any) => (
<Switch>
{routes.map(
(route: any, index: number) => (
<PrivateRoute auth={route.protectedPath} key={index} path={route.path} exact={route.exact}
component={route[component]}/> ))}
</Switch>
);
export default Routing; | path: '/encounter',
protectedPath: true,
header: () => <Header title="Encounter"/>, | random_line_split |
index.tsx | import * as React from 'react';
import { Route, Switch } from 'react-router-dom';
import Header from '../Header/index';
import Home from '../Home/index';
import Login from '../Login/index';
import SignUp from '../SignUp/index';
import Dashboard from '../Dashboard/index';
import Settings from '../Settings/index';
import NotFoundPage from '../NotFound/index';
import Encounter from '../Encounter/index';
const routes: Array<any> = [
{
path: '/',
exact: true,
protectedPath: false,
header: () => <Header/>,
main: () => <Home/>,
},
{
path: '/login',
protectedPath: false,
header: () => <Header title="Login"/>,
main: () => <Login title="Login"/>,
},
{
path: '/signup',
protectedPath: false,
header: () => <Header title="Registration"/>,
main: () => <SignUp title="Registration"/>,
},
{
path: '/dashboard',
protectedPath: true,
header: () => <Header title="Dashboard"/>,
main: () => <Dashboard title="Dashboard"/>,
},
{
path: '/settings',
protectedPath: true,
header: () => <Header title="Settings"/>,
main: () => <Settings title="Settings"/>,
},
{
path: '/encounter',
protectedPath: true,
header: () => <Header title="Encounter"/>,
main: () => <Encounter title="Encounter"/>,
},
{
protectedPath: false,
header: () => <Header title="Page not found"/>,
main: () => <NotFoundPage title="Page not found"/>,
},
];
class PrivateRoute extends React.PureComponent<any, any> {
constructor(props: any, context: any) |
render() {
const { auth, component: Component, ...rest } = this.props;
return (
<Route {...rest} render={props => {
if (!auth || !!localStorage.getItem('token')) {
return <Component {...props}/>;
} else {
const Redirect = require('react-router').Redirect;
return <Redirect to={{ pathname: '/login', state: { from: props.location } }}/>;
}
}}/>
)
}
}
const Routing = ({ component }: any) => (
<Switch>
{routes.map(
(route: any, index: number) => (
<PrivateRoute auth={route.protectedPath} key={index} path={route.path} exact={route.exact}
component={route[component]}/> ))}
</Switch>
);
export default Routing; | {
super(props, context);
} | identifier_body |
main.ng.rs | //! Multivariate linear regression using gradient descent
//!
//! Model:
//!
//! ```
//! y = x * theta + e
//!
//! y Dependent variable (scalar)
//! x Independent variables (1-by-n matrix)
//! theta Parameters to estimate (n-by-1 matrix)
//! e Error (scalar)
//! ```
//!
//! Cost function: Half of the mean squared error (MSE)
//!
//! ```
//! E = X * theta - Y
//! J = E' * E / 2 / m
//!
//! E Error per observation (m-by-1 matrix)
//! X Observed independent variables (m-by-n matrix)
//! Y Observed dependent variables (m-by-1 matrix)
//! m Number of observations (integer)
//! theta Parameters to estimate (n-by-1 matrix)
//! ```
//!
//! Estimator: Gradient descent
//!
//! ```
//! loop
//! E = X * theta - Y
//! theta = theta - alpha / m * X' * E
//! until stop_condition
//!
//! E (m-by-1 matrix)
//! X (m-by-n matrix)
//! Y (m-by-1 matrix)
//! alpha Step size (scalar)
//! theta (n-by-1 matrix)
//! ```
#![allow(non_snake_case)]
#![deny(warnings)]
#![feature(plugin)]
#![plugin(linalg_macros)]
extern crate cast;
extern crate env_logger;
extern crate linalg;
extern crate lines;
extern crate stats;
extern crate time;
#[macro_use]
extern crate log;
use std::fs::File;
use std::io::{BufReader, self};
use std::path::Path;
use cast::From as _0;
use linalg::prelude::*;
use linalg::{Col, ColMut, SubMat, SubMatMut, Transposed};
use lines::Lines;
use stats::univariate::Sample;
macro_rules! timeit {
($msg:expr, $e:expr) => {{
let now = time::precise_time_ns();
let out = $e;
let elapsed = time::precise_time_ns() - now;
println!(concat!($msg, " took {} ms"), f64::from_(elapsed) / 1_000_000.);
out
}}
}
fn main() {
env_logger::init().unwrap();
// Some dummy operation to force the initialization of OpenBLAS' runtime (~90 ms) here rather
// than during the measurements below
(&mat![1., 2.; 3., 4.].inv() * &mat![1., 2.; 3., 4.]).eval();
let data = timeit!("Loading data", {
load("mpg.tsv").unwrap()
});
// Number of observations
let m = data.nrows();
println!("{} observations", m);
// Number of independent variables
let n = data.ncols() - 1;
println!("{} independent variables\n", n);
let mut X = Mat::ones((m, n + 1));
X[.., 1..] = data[.., 1..];
let y = data.col(0);
let (mu, sigma) = timeit!("Normalization", {
normalize(&mut X[.., 1..])
});
println!("mean: {:?}", mu);
println!("std deviation: {:?}\n", sigma);
let ref mut theta = ColVec::zeros(n + 1);
let alpha = 0.01;
let max_niters = 100_000;
let niters = timeit!("Gradient descent", {
descent(&X, y, theta, alpha, max_niters)
});
println!("Estimated parameters: {:?}", theta);
println!("Iterations required: {}", niters);
}
/// Evaluates the cost function for `theta`
///
/// X (m, n)
/// y (m, 1)
/// theta (n, 1)
/// z (m, 1) Auxiliary buffer to avoid allocating
fn cost(X: &SubMat<f64>, y: &Col<f64>, theta: &Col<f64>, mut z: &mut Col<f64>) -> f64 {
let m = f64::from_(X.nrows());
z[..] = y - X * theta;
let e = &*z;
e.t() * e / 2. / m
}
/// Normalizes the independent variables
///
/// X (m, n)
///
/// -> Returns a vector of means and a vector of standard deviations
fn normalize(X: &mut SubMat<f64>) -> (Vec<f64>, Vec<f64>) {
let n = usize::from_(X.ncols());
let mut mu = Vec::with_capacity(n);
let mut sigma = Vec::with_capacity(n);
for col in X.cols_mut() {
let (mean, sd) = {
let sample = Sample::new(col.as_slice().unwrap());
let mean = sample.mean();
(mean, sample.std_dev(Some(mean)))
};
mu.push(mean);
sigma.push(sd);
*col -= mean;
*col /= sd;
}
(mu, sigma)
}
/// Performs the gradient descent algorithm to find the value of `theta` that minimizes the cost
/// function.
///
/// X (m, n)
/// y (m, 1)
/// theta (n, 1)
/// alpha scalar Step size
/// max_niters integer Maximum number of iterations
///
/// -> Returns the number of iterations required to converge to a solution
fn descent(
X: &SubMat<f64>,
y: &Col<f64>,
theta: &mut Col<f64>,
alpha: f64,
max_niters: u32,
) -> u32 {
const TOL: f64 = 1e-5;
let m = f64::from_(X.nrows());
// Pre-allocate a column vector to avoid allocations in the loop
let ref mut z = ColVec::zeros(X.nrows());
let mut last_J = cost(X, y, theta, z);
for i in 0..max_niters {
// z = e = y - X * theta
z[..] = y - X * theta;
// theta = theta + alpha / m * x' * e
*theta += alpha * X.t() * &*z / m;
let J = cost(X, y, theta, z);
debug!("i: {}, J: {}, theta: {:?}", i, J, theta);
// Stop condition: `cost` reduced by less than `TOL`% in last iteration
if (J - last_J).abs() / J.max(last_J) < TOL {
return i
}
last_J = J;
}
max_niters
}
/// Loads data from a TSV file
fn load<P>(path: P) -> io::Result<Transposed<Mat<f64>>> where P: AsRef<Path> {
fn | (path: &Path) -> io::Result<Transposed<Mat<f64>>> {
let mut lines = Lines::from(BufReader::new(try!(File::open(path))));
let mut v = vec![];
let ncols = {
let mut ncols = 0;
for number in try!(lines.next().unwrap()).split_whitespace() {
ncols += 1;
v.push(number.parse().unwrap());
}
ncols
};
let mut nrows = 1;
while let Some(line) = lines.next() {
let line = try!(line);
for number in line.split_whitespace() {
v.push(number.parse().unwrap());
}
nrows += 1;
}
unsafe {
Ok(Mat::from_raw_parts(v.into_boxed_slice(), (ncols, nrows)).t())
}
}
load(path.as_ref())
}
| load | identifier_name |
main.ng.rs | //! Multivariate linear regression using gradient descent
//!
//! Model:
//!
//! ```
//! y = x * theta + e
//!
//! y Dependent variable (scalar)
//! x Independent variables (1-by-n matrix)
//! theta Parameters to estimate (n-by-1 matrix)
//! e Error (scalar)
//! ```
//!
//! Cost function: Half of the mean squared error (MSE)
//!
//! ```
//! E = X * theta - Y
//! J = E' * E / 2 / m
//!
//! E Error per observation (m-by-1 matrix)
//! X Observed independent variables (m-by-n matrix)
//! Y Observed dependent variables (m-by-1 matrix)
//! m Number of observations (integer)
//! theta Parameters to estimate (n-by-1 matrix)
//! ```
//!
//! Estimator: Gradient descent
//!
//! ```
//! loop
//! E = X * theta - Y
//! theta = theta - alpha / m * X' * E
//! until stop_condition
//!
//! E (m-by-1 matrix)
//! X (m-by-n matrix)
//! Y (m-by-1 matrix)
//! alpha Step size (scalar)
//! theta (n-by-1 matrix)
//! ```
#![allow(non_snake_case)]
#![deny(warnings)]
#![feature(plugin)]
#![plugin(linalg_macros)]
extern crate cast;
extern crate env_logger;
extern crate linalg;
extern crate lines;
extern crate stats;
extern crate time;
#[macro_use]
extern crate log;
use std::fs::File;
use std::io::{BufReader, self};
use std::path::Path;
use cast::From as _0;
use linalg::prelude::*;
use linalg::{Col, ColMut, SubMat, SubMatMut, Transposed};
use lines::Lines;
use stats::univariate::Sample;
macro_rules! timeit {
($msg:expr, $e:expr) => {{
let now = time::precise_time_ns();
let out = $e;
let elapsed = time::precise_time_ns() - now;
println!(concat!($msg, " took {} ms"), f64::from_(elapsed) / 1_000_000.);
out
}}
}
fn main() {
env_logger::init().unwrap();
// Some dummy operation to force the initialization of OpenBLAS' runtime (~90 ms) here rather
// than during the measurements below
(&mat![1., 2.; 3., 4.].inv() * &mat![1., 2.; 3., 4.]).eval();
let data = timeit!("Loading data", {
load("mpg.tsv").unwrap()
});
// Number of observations
let m = data.nrows();
println!("{} observations", m);
// Number of independent variables
let n = data.ncols() - 1;
println!("{} independent variables\n", n);
let mut X = Mat::ones((m, n + 1));
X[.., 1..] = data[.., 1..];
let y = data.col(0);
let (mu, sigma) = timeit!("Normalization", {
normalize(&mut X[.., 1..])
});
println!("mean: {:?}", mu);
println!("std deviation: {:?}\n", sigma);
let ref mut theta = ColVec::zeros(n + 1);
let alpha = 0.01;
let max_niters = 100_000;
let niters = timeit!("Gradient descent", {
descent(&X, y, theta, alpha, max_niters)
});
println!("Estimated parameters: {:?}", theta);
println!("Iterations required: {}", niters);
}
/// Evaluates the cost function for `theta`
///
/// X (m, n)
/// y (m, 1)
/// theta (n, 1)
/// z (m, 1) Auxiliary buffer to avoid allocating
fn cost(X: &SubMat<f64>, y: &Col<f64>, theta: &Col<f64>, mut z: &mut Col<f64>) -> f64 {
let m = f64::from_(X.nrows());
z[..] = y - X * theta;
let e = &*z;
e.t() * e / 2. / m
}
/// Normalizes the independent variables
///
/// X (m, n)
///
/// -> Returns a vector of means and a vector of standard deviations
fn normalize(X: &mut SubMat<f64>) -> (Vec<f64>, Vec<f64>) {
let n = usize::from_(X.ncols());
let mut mu = Vec::with_capacity(n);
let mut sigma = Vec::with_capacity(n);
for col in X.cols_mut() {
let (mean, sd) = {
let sample = Sample::new(col.as_slice().unwrap());
let mean = sample.mean();
(mean, sample.std_dev(Some(mean)))
};
mu.push(mean);
sigma.push(sd);
*col -= mean;
*col /= sd;
}
(mu, sigma)
}
/// Performs the gradient descent algorithm to find the value of `theta` that minimizes the cost
/// function.
///
/// X (m, n)
/// y (m, 1)
/// theta (n, 1)
/// alpha scalar Step size
/// max_niters integer Maximum number of iterations
///
/// -> Returns the number of iterations required to converge to a solution
fn descent(
X: &SubMat<f64>,
y: &Col<f64>,
theta: &mut Col<f64>,
alpha: f64,
max_niters: u32,
) -> u32 {
const TOL: f64 = 1e-5;
let m = f64::from_(X.nrows());
// Pre-allocate a column vector to avoid allocations in the loop
let ref mut z = ColVec::zeros(X.nrows());
let mut last_J = cost(X, y, theta, z);
for i in 0..max_niters {
// z = e = y - X * theta
z[..] = y - X * theta;
// theta = theta + alpha / m * x' * e
*theta += alpha * X.t() * &*z / m;
let J = cost(X, y, theta, z);
debug!("i: {}, J: {}, theta: {:?}", i, J, theta);
// Stop condition: `cost` reduced by less than `TOL`% in last iteration
if (J - last_J).abs() / J.max(last_J) < TOL |
last_J = J;
}
max_niters
}
/// Loads data from a TSV file
fn load<P>(path: P) -> io::Result<Transposed<Mat<f64>>> where P: AsRef<Path> {
fn load(path: &Path) -> io::Result<Transposed<Mat<f64>>> {
let mut lines = Lines::from(BufReader::new(try!(File::open(path))));
let mut v = vec![];
let ncols = {
let mut ncols = 0;
for number in try!(lines.next().unwrap()).split_whitespace() {
ncols += 1;
v.push(number.parse().unwrap());
}
ncols
};
let mut nrows = 1;
while let Some(line) = lines.next() {
let line = try!(line);
for number in line.split_whitespace() {
v.push(number.parse().unwrap());
}
nrows += 1;
}
unsafe {
Ok(Mat::from_raw_parts(v.into_boxed_slice(), (ncols, nrows)).t())
}
}
load(path.as_ref())
}
| {
return i
} | conditional_block |
main.ng.rs | //! Multivariate linear regression using gradient descent
//!
//! Model:
//!
//! ```
//! y = x * theta + e
//!
//! y Dependent variable (scalar)
//! x Independent variables (1-by-n matrix)
//! theta Parameters to estimate (n-by-1 matrix)
//! e Error (scalar)
//! ```
//!
//! Cost function: Half of the mean squared error (MSE)
//!
//! ```
//! E = X * theta - Y
//! J = E' * E / 2 / m
//!
//! E Error per observation (m-by-1 matrix)
//! X Observed independent variables (m-by-n matrix)
//! Y Observed dependent variables (m-by-1 matrix)
//! m Number of observations (integer)
//! theta Parameters to estimate (n-by-1 matrix)
//! ```
//!
//! Estimator: Gradient descent
//!
//! ```
//! loop
//! E = X * theta - Y
//! theta = theta - alpha / m * X' * E
//! until stop_condition
//!
//! E (m-by-1 matrix)
//! X (m-by-n matrix)
//! Y (m-by-1 matrix)
//! alpha Step size (scalar)
//! theta (n-by-1 matrix)
//! ```
#![allow(non_snake_case)]
#![deny(warnings)]
#![feature(plugin)]
#![plugin(linalg_macros)]
extern crate cast;
extern crate env_logger;
extern crate linalg;
extern crate lines;
extern crate stats;
extern crate time;
#[macro_use]
extern crate log;
use std::fs::File;
use std::io::{BufReader, self};
use std::path::Path;
use cast::From as _0;
use linalg::prelude::*;
use linalg::{Col, ColMut, SubMat, SubMatMut, Transposed};
use lines::Lines;
use stats::univariate::Sample;
macro_rules! timeit {
($msg:expr, $e:expr) => {{
let now = time::precise_time_ns();
let out = $e;
let elapsed = time::precise_time_ns() - now;
println!(concat!($msg, " took {} ms"), f64::from_(elapsed) / 1_000_000.);
out
}}
}
fn main() |
/// Evaluates the cost function for `theta`
///
/// X (m, n)
/// y (m, 1)
/// theta (n, 1)
/// z (m, 1) Auxiliary buffer to avoid allocating
fn cost(X: &SubMat<f64>, y: &Col<f64>, theta: &Col<f64>, mut z: &mut Col<f64>) -> f64 {
let m = f64::from_(X.nrows());
z[..] = y - X * theta;
let e = &*z;
e.t() * e / 2. / m
}
/// Normalizes the independent variables
///
/// X (m, n)
///
/// -> Returns a vector of means and a vector of standard deviations
fn normalize(X: &mut SubMat<f64>) -> (Vec<f64>, Vec<f64>) {
let n = usize::from_(X.ncols());
let mut mu = Vec::with_capacity(n);
let mut sigma = Vec::with_capacity(n);
for col in X.cols_mut() {
let (mean, sd) = {
let sample = Sample::new(col.as_slice().unwrap());
let mean = sample.mean();
(mean, sample.std_dev(Some(mean)))
};
mu.push(mean);
sigma.push(sd);
*col -= mean;
*col /= sd;
}
(mu, sigma)
}
/// Performs the gradient descent algorithm to find the value of `theta` that minimizes the cost
/// function.
///
/// X (m, n)
/// y (m, 1)
/// theta (n, 1)
/// alpha scalar Step size
/// max_niters integer Maximum number of iterations
///
/// -> Returns the number of iterations required to converge to a solution
fn descent(
X: &SubMat<f64>,
y: &Col<f64>,
theta: &mut Col<f64>,
alpha: f64,
max_niters: u32,
) -> u32 {
const TOL: f64 = 1e-5;
let m = f64::from_(X.nrows());
// Pre-allocate a column vector to avoid allocations in the loop
let ref mut z = ColVec::zeros(X.nrows());
let mut last_J = cost(X, y, theta, z);
for i in 0..max_niters {
// z = e = y - X * theta
z[..] = y - X * theta;
// theta = theta + alpha / m * x' * e
*theta += alpha * X.t() * &*z / m;
let J = cost(X, y, theta, z);
debug!("i: {}, J: {}, theta: {:?}", i, J, theta);
// Stop condition: `cost` reduced by less than `TOL`% in last iteration
if (J - last_J).abs() / J.max(last_J) < TOL {
return i
}
last_J = J;
}
max_niters
}
/// Loads data from a TSV file
fn load<P>(path: P) -> io::Result<Transposed<Mat<f64>>> where P: AsRef<Path> {
fn load(path: &Path) -> io::Result<Transposed<Mat<f64>>> {
let mut lines = Lines::from(BufReader::new(try!(File::open(path))));
let mut v = vec![];
let ncols = {
let mut ncols = 0;
for number in try!(lines.next().unwrap()).split_whitespace() {
ncols += 1;
v.push(number.parse().unwrap());
}
ncols
};
let mut nrows = 1;
while let Some(line) = lines.next() {
let line = try!(line);
for number in line.split_whitespace() {
v.push(number.parse().unwrap());
}
nrows += 1;
}
unsafe {
Ok(Mat::from_raw_parts(v.into_boxed_slice(), (ncols, nrows)).t())
}
}
load(path.as_ref())
}
| {
env_logger::init().unwrap();
// Some dummy operation to force the initialization of OpenBLAS' runtime (~90 ms) here rather
// than during the measurements below
(&mat![1., 2.; 3., 4.].inv() * &mat![1., 2.; 3., 4.]).eval();
let data = timeit!("Loading data", {
load("mpg.tsv").unwrap()
});
// Number of observations
let m = data.nrows();
println!("{} observations", m);
// Number of independent variables
let n = data.ncols() - 1;
println!("{} independent variables\n", n);
let mut X = Mat::ones((m, n + 1));
X[.., 1..] = data[.., 1..];
let y = data.col(0);
let (mu, sigma) = timeit!("Normalization", {
normalize(&mut X[.., 1..])
});
println!("mean: {:?}", mu);
println!("std deviation: {:?}\n", sigma);
let ref mut theta = ColVec::zeros(n + 1);
let alpha = 0.01;
let max_niters = 100_000;
let niters = timeit!("Gradient descent", {
descent(&X, y, theta, alpha, max_niters)
});
println!("Estimated parameters: {:?}", theta);
println!("Iterations required: {}", niters);
} | identifier_body |
main.ng.rs | //! Multivariate linear regression using gradient descent
//!
//! Model:
//!
//! ```
//! y = x * theta + e
//!
//! y Dependent variable (scalar)
//! x Independent variables (1-by-n matrix)
//! theta Parameters to estimate (n-by-1 matrix)
//! e Error (scalar)
//! ```
//!
//! Cost function: Half of the mean squared error (MSE)
//!
//! ```
//! E = X * theta - Y
//! J = E' * E / 2 / m
//!
//! E Error per observation (m-by-1 matrix)
//! X Observed independent variables (m-by-n matrix)
//! Y Observed dependent variables (m-by-1 matrix)
//! m Number of observations (integer)
//! theta Parameters to estimate (n-by-1 matrix)
//! ```
//!
//! Estimator: Gradient descent
//!
//! ```
//! loop
//! E = X * theta - Y
//! theta = theta - alpha / m * X' * E
//! until stop_condition
//!
//! E (m-by-1 matrix)
//! X (m-by-n matrix)
//! Y (m-by-1 matrix)
//! alpha Step size (scalar)
//! theta (n-by-1 matrix)
//! ```
#![allow(non_snake_case)]
#![deny(warnings)]
#![feature(plugin)]
#![plugin(linalg_macros)]
extern crate cast;
extern crate env_logger;
extern crate linalg;
extern crate lines;
extern crate stats;
extern crate time;
#[macro_use]
extern crate log;
use std::fs::File;
use std::io::{BufReader, self};
use std::path::Path;
use cast::From as _0;
use linalg::prelude::*;
use linalg::{Col, ColMut, SubMat, SubMatMut, Transposed};
use lines::Lines;
use stats::univariate::Sample;
macro_rules! timeit {
($msg:expr, $e:expr) => {{
let now = time::precise_time_ns();
let out = $e;
let elapsed = time::precise_time_ns() - now;
println!(concat!($msg, " took {} ms"), f64::from_(elapsed) / 1_000_000.);
out
}}
}
fn main() {
env_logger::init().unwrap();
// Some dummy operation to force the initialization of OpenBLAS' runtime (~90 ms) here rather
// than during the measurements below
(&mat![1., 2.; 3., 4.].inv() * &mat![1., 2.; 3., 4.]).eval();
let data = timeit!("Loading data", {
load("mpg.tsv").unwrap()
});
// Number of observations
let m = data.nrows();
println!("{} observations", m);
// Number of independent variables
let n = data.ncols() - 1;
println!("{} independent variables\n", n);
let mut X = Mat::ones((m, n + 1));
X[.., 1..] = data[.., 1..];
let y = data.col(0);
let (mu, sigma) = timeit!("Normalization", {
normalize(&mut X[.., 1..])
});
println!("mean: {:?}", mu);
println!("std deviation: {:?}\n", sigma);
let ref mut theta = ColVec::zeros(n + 1);
let alpha = 0.01;
let max_niters = 100_000;
let niters = timeit!("Gradient descent", {
descent(&X, y, theta, alpha, max_niters)
});
println!("Estimated parameters: {:?}", theta);
println!("Iterations required: {}", niters);
}
/// Evaluates the cost function for `theta`
///
/// X (m, n)
/// y (m, 1)
/// theta (n, 1)
/// z (m, 1) Auxiliary buffer to avoid allocating
fn cost(X: &SubMat<f64>, y: &Col<f64>, theta: &Col<f64>, mut z: &mut Col<f64>) -> f64 {
let m = f64::from_(X.nrows());
z[..] = y - X * theta;
let e = &*z;
e.t() * e / 2. / m
}
/// Normalizes the independent variables
///
/// X (m, n)
///
/// -> Returns a vector of means and a vector of standard deviations
fn normalize(X: &mut SubMat<f64>) -> (Vec<f64>, Vec<f64>) {
let n = usize::from_(X.ncols());
let mut mu = Vec::with_capacity(n);
let mut sigma = Vec::with_capacity(n);
for col in X.cols_mut() {
let (mean, sd) = {
let sample = Sample::new(col.as_slice().unwrap());
let mean = sample.mean();
(mean, sample.std_dev(Some(mean)))
}; |
*col -= mean;
*col /= sd;
}
(mu, sigma)
}
/// Performs the gradient descent algorithm to find the value of `theta` that minimizes the cost
/// function.
///
/// X (m, n)
/// y (m, 1)
/// theta (n, 1)
/// alpha scalar Step size
/// max_niters integer Maximum number of iterations
///
/// -> Returns the number of iterations required to converge to a solution
fn descent(
X: &SubMat<f64>,
y: &Col<f64>,
theta: &mut Col<f64>,
alpha: f64,
max_niters: u32,
) -> u32 {
const TOL: f64 = 1e-5;
let m = f64::from_(X.nrows());
// Pre-allocate a column vector to avoid allocations in the loop
let ref mut z = ColVec::zeros(X.nrows());
let mut last_J = cost(X, y, theta, z);
for i in 0..max_niters {
// z = e = y - X * theta
z[..] = y - X * theta;
// theta = theta + alpha / m * x' * e
*theta += alpha * X.t() * &*z / m;
let J = cost(X, y, theta, z);
debug!("i: {}, J: {}, theta: {:?}", i, J, theta);
// Stop condition: `cost` reduced by less than `TOL`% in last iteration
if (J - last_J).abs() / J.max(last_J) < TOL {
return i
}
last_J = J;
}
max_niters
}
/// Loads data from a TSV file
fn load<P>(path: P) -> io::Result<Transposed<Mat<f64>>> where P: AsRef<Path> {
fn load(path: &Path) -> io::Result<Transposed<Mat<f64>>> {
let mut lines = Lines::from(BufReader::new(try!(File::open(path))));
let mut v = vec![];
let ncols = {
let mut ncols = 0;
for number in try!(lines.next().unwrap()).split_whitespace() {
ncols += 1;
v.push(number.parse().unwrap());
}
ncols
};
let mut nrows = 1;
while let Some(line) = lines.next() {
let line = try!(line);
for number in line.split_whitespace() {
v.push(number.parse().unwrap());
}
nrows += 1;
}
unsafe {
Ok(Mat::from_raw_parts(v.into_boxed_slice(), (ncols, nrows)).t())
}
}
load(path.as_ref())
} |
mu.push(mean);
sigma.push(sd); | random_line_split |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.