prompt
large_stringlengths 70
991k
| completion
large_stringlengths 0
1.02k
|
---|---|
<|file_name|>pkcs11factory.go<|end_file_name|><|fim▁begin|>// +build pkcs11
/*
Copyright IBM Corp. All Rights Reserved.
SPDX-License-Identifier: Apache-2.0
*/
package factory
import (
"encoding/hex"
"github.com/hyperledger/fabric/bccsp"
"github.com/hyperledger/fabric/bccsp/pkcs11"
"github.com/hyperledger/fabric/bccsp/sw"
"github.com/pkg/errors"
)
const (
// PKCS11BasedFactoryName is the name of the factory of the hsm-based BCCSP implementation
PKCS11BasedFactoryName = "PKCS11"
)
// PKCS11Factory is the factory of the HSM-based BCCSP.
type PKCS11Factory struct{}
// Name returns the name of this factory
func (f *PKCS11Factory) Name() string {
return PKCS11BasedFactoryName<|fim▁hole|>}
// Get returns an instance of BCCSP using Opts.
func (f *PKCS11Factory) Get(config *FactoryOpts) (bccsp.BCCSP, error) {
// Validate arguments
if config == nil || config.PKCS11 == nil {
return nil, errors.New("Invalid config. It must not be nil.")
}
p11Opts := *config.PKCS11
ks := sw.NewDummyKeyStore()
mapper := skiMapper(p11Opts)
return pkcs11.New(p11Opts, ks, pkcs11.WithKeyMapper(mapper))
}
func skiMapper(p11Opts pkcs11.PKCS11Opts) func([]byte) []byte {
keyMap := map[string]string{}
for _, k := range p11Opts.KeyIDs {
keyMap[k.SKI] = k.ID
}
return func(ski []byte) []byte {
keyID := hex.EncodeToString(ski)
if id, ok := keyMap[keyID]; ok {
return []byte(id)
}
if p11Opts.AltID != "" {
return []byte(p11Opts.AltID)
}
return ski
}
}<|fim▁end|> | |
<|file_name|>init.rs<|end_file_name|><|fim▁begin|>#![feature(core, collections)]
extern crate core;
#[cfg(test)]
mod tests {
use core::slice::SliceExt;
// fn size_from_ptr<T>(_: *const T) -> usize {
// mem::size_of::<T>()
// }
// macro_rules! slice_offset {
// ($ptr:expr, $by:expr) => {{
// let ptr = $ptr;
// if size_from_ptr(ptr) == 0 {
// ::intrinsics::arith_offset(ptr as *mut i8, $by) as *mut _
// } else {
// ptr.offset($by)
// }
// }};
// }
// macro_rules! slice_ref {
// ($ptr:expr) => {{
// let ptr = $ptr;
// if size_from_ptr(ptr) == 0 {
// // Use a non-null pointer value
// &mut *(1 as *mut _)
// } else {
// transmute(ptr)
// }
// }};
// }
// pub unsafe fn from_raw_parts<'a, T>(p: *const T, len: usize) -> &'a [T] {
// transmute(RawSlice { data: p, len: len })
// }
// macro_rules! make_slice {
// ($start: expr, $end: expr) => {{
// let start = $start;
// let diff = ($end as usize).wrapping_sub(start as usize);
// if size_from_ptr(start) == 0 {
// // use a non-null pointer value
// unsafe { from_raw_parts(1 as *const _, diff) }
// } else {
// let len = diff / size_from_ptr(start);
// unsafe { from_raw_parts(start, len) }
// }
// }}
// }
// impl<T> SliceExt for [T] {
// type Item = T;
//
// #[inline]
// fn split_at(&self, mid: usize) -> (&[T], &[T]) {
// (&self[..mid], &self[mid..])
// }
//
// #[inline]
// fn iter<'a>(&'a self) -> Iter<'a, T> {
// unsafe {
// let p = if mem::size_of::<T>() == 0 {
// 1 as *const _
// } else {
// let p = self.as_ptr();
// assume(!p.is_null());
// p
// };
//
// Iter {
// ptr: p,
// end: slice_offset!(p, self.len() as isize),
// _marker: marker::PhantomData
// }
// }
// }
//
// #[inline]
// fn split<'a, P>(&'a self, pred: P) -> Split<'a, T, P> where P: FnMut(&T) -> bool {
// Split {
// v: self,
// pred: pred,
// finished: false
// }
// }
//
// #[inline]
// fn splitn<'a, P>(&'a self, n: usize, pred: P) -> SplitN<'a, T, P> where
// P: FnMut(&T) -> bool,
// {
// SplitN {
// inner: GenericSplitN {
// iter: self.split(pred),
// count: n,
// invert: false
// }
// }
// }
//
// #[inline]
// fn rsplitn<'a, P>(&'a self, n: usize, pred: P) -> RSplitN<'a, T, P> where
// P: FnMut(&T) -> bool,
// {
// RSplitN {
// inner: GenericSplitN {
// iter: self.split(pred),
// count: n,
// invert: true
// }
// }
// }
//
// #[inline]
// fn windows(&self, size: usize) -> Windows<T> {
// assert!(size != 0);
// Windows { v: self, size: size }
// }
//
// #[inline]
// fn chunks(&self, size: usize) -> Chunks<T> {
// assert!(size != 0);
// Chunks { v: self, size: size }
// }
//
// #[inline]
// fn get(&self, index: usize) -> Option<&T> {
// if index < self.len() { Some(&self[index]) } else { None }
// }
//
// #[inline]
// fn first(&self) -> Option<&T> {
// if self.is_empty() { None } else { Some(&self[0]) }
// }
//
// #[inline]
// fn tail(&self) -> &[T] { &self[1..] }
//
// #[inline]
// fn init(&self) -> &[T] {
// &self[..self.len() - 1]
// }
//
// #[inline]
// fn last(&self) -> Option<&T> {
// if self.is_empty() { None } else { Some(&self[self.len() - 1]) }
// }
//
// #[inline]
// unsafe fn get_unchecked(&self, index: usize) -> &T {
// transmute(self.repr().data.offset(index as isize))
// }
//
// #[inline]
// fn as_ptr(&self) -> *const T {
// self.repr().data
// }
//
// #[unstable(feature = "core")]
// fn binary_search_by<F>(&self, mut f: F) -> Result<usize, usize> where
// F: FnMut(&T) -> Ordering
// {
// let mut base : usize = 0;
// let mut lim : usize = self.len();
//
// while lim != 0 {
// let ix = base + (lim >> 1);
// match f(&self[ix]) {
// Equal => return Ok(ix),
// Less => {
// base = ix + 1;
// lim -= 1;
// }
// Greater => ()
// }
// lim >>= 1;
// }
// Err(base)
// }
//
// #[inline]
// fn len(&self) -> usize { self.repr().len }
//
// #[inline]
// fn get_mut(&mut self, index: usize) -> Option<&mut T> {
// if index < self.len() { Some(&mut self[index]) } else { None }
// }
//
// #[inline]
// fn split_at_mut(&mut self, mid: usize) -> (&mut [T], &mut [T]) {
// unsafe {
// let self2: &mut [T] = mem::transmute_copy(&self);
//
// (ops::IndexMut::index_mut(self, ops::RangeTo { end: mid } ),
// ops::IndexMut::index_mut(self2, ops::RangeFrom { start: mid } ))
// }
// }
//
// #[inline]
// fn iter_mut<'a>(&'a mut self) -> IterMut<'a, T> {
// unsafe {
// let p = if mem::size_of::<T>() == 0 {
// 1 as *mut _
// } else {
// let p = self.as_mut_ptr();
// assume(!p.is_null());
// p
// };
//
// IterMut {
// ptr: p,
// end: slice_offset!(p, self.len() as isize),
// _marker: marker::PhantomData
// }
// }
// }
//
// #[inline]
// fn last_mut(&mut self) -> Option<&mut T> {
// let len = self.len();
// if len == 0 { return None; }
// Some(&mut self[len - 1])
// }
//
// #[inline]
// fn first_mut(&mut self) -> Option<&mut T> {
// if self.is_empty() { None } else { Some(&mut self[0]) }
// }
//
// #[inline]
// fn tail_mut(&mut self) -> &mut [T] {
// &mut self[1 ..]
// }
//
// #[inline]
// fn init_mut(&mut self) -> &mut [T] {
// let len = self.len();
// &mut self[.. (len - 1)]
// }
//
// #[inline]
// fn split_mut<'a, P>(&'a mut self, pred: P) -> SplitMut<'a, T, P> where P: FnMut(&T) -> bool {
// SplitMut { v: self, pred: pred, finished: false }
// }
//
// #[inline]
// fn splitn_mut<'a, P>(&'a mut self, n: usize, pred: P) -> SplitNMut<'a, T, P> where
// P: FnMut(&T) -> bool
// {
// SplitNMut {
// inner: GenericSplitN {
// iter: self.split_mut(pred),
// count: n,
// invert: false
// }
// }
// }
//
// #[inline]
// fn rsplitn_mut<'a, P>(&'a mut self, n: usize, pred: P) -> RSplitNMut<'a, T, P> where
// P: FnMut(&T) -> bool,
// {
// RSplitNMut {
// inner: GenericSplitN {
// iter: self.split_mut(pred),
// count: n,
// invert: true
// }
// }
// }
//
// #[inline]
// fn chunks_mut(&mut self, chunk_size: usize) -> ChunksMut<T> {
// assert!(chunk_size > 0);
// ChunksMut { v: self, chunk_size: chunk_size }
// }
//
// #[inline]
// fn swap(&mut self, a: usize, b: usize) {
// unsafe {
// // Can't take two mutable loans from one vector, so instead just cast
// // them to their raw pointers to do the swap
// let pa: *mut T = &mut self[a];
// let pb: *mut T = &mut self[b];
// ptr::swap(pa, pb);
// }
// }
//
// fn reverse(&mut self) {
// let mut i: usize = 0;
// let ln = self.len();
// while i < ln / 2 {
// // Unsafe swap to avoid the bounds check in safe swap.
// unsafe {
// let pa: *mut T = self.get_unchecked_mut(i);
// let pb: *mut T = self.get_unchecked_mut(ln - i - 1);
// ptr::swap(pa, pb);
// }
// i += 1;
// }
// }
//
// #[inline]
// unsafe fn get_unchecked_mut(&mut self, index: usize) -> &mut T {
// transmute((self.repr().data as *mut T).offset(index as isize))
// }
//
// #[inline]
// fn as_mut_ptr(&mut self) -> *mut T {
// self.repr().data as *mut T
// }
//
// #[inline]
// fn position_elem(&self, x: &T) -> Option<usize> where T: PartialEq {
// self.iter().position(|y| *x == *y)
// }
//
// #[inline]
// fn rposition_elem(&self, t: &T) -> Option<usize> where T: PartialEq {
// self.iter().rposition(|x| *x == *t)
// }
//
// #[inline]
// fn contains(&self, x: &T) -> bool where T: PartialEq {
// self.iter().any(|elt| *x == *elt)
// }
//
// #[inline]
// fn starts_with(&self, needle: &[T]) -> bool where T: PartialEq {
// let n = needle.len();
// self.len() >= n && needle == &self[..n]
// }
//
// #[inline]
// fn ends_with(&self, needle: &[T]) -> bool where T: PartialEq {
// let (m, n) = (self.len(), needle.len());
// m >= n && needle == &self[m-n..]
// }
//
// #[unstable(feature = "core")]
// fn binary_search(&self, x: &T) -> Result<usize, usize> where T: Ord {
// self.binary_search_by(|p| p.cmp(x))
// }
//
// #[unstable(feature = "core")]
// fn next_permutation(&mut self) -> bool where T: Ord {
// // These cases only have 1 permutation each, so we can't do anything.
// if self.len() < 2 { return false; }
//
// // Step 1: Identify the longest, rightmost weakly decreasing part of the vector
// let mut i = self.len() - 1;
// while i > 0 && self[i-1] >= self[i] {
// i -= 1;
// }
//
// // If that is the entire vector, this is the last-ordered permutation.
// if i == 0 {
// return false;
// }
//
// // Step 2: Find the rightmost element larger than the pivot (i-1)
// let mut j = self.len() - 1;
// while j >= i && self[j] <= self[i-1] {
// j -= 1;<|fim▁hole|> // // Step 3: Swap that element with the pivot
// self.swap(j, i-1);
//
// // Step 4: Reverse the (previously) weakly decreasing part
// self[i..].reverse();
//
// true
// }
//
// #[unstable(feature = "core")]
// fn prev_permutation(&mut self) -> bool where T: Ord {
// // These cases only have 1 permutation each, so we can't do anything.
// if self.len() < 2 { return false; }
//
// // Step 1: Identify the longest, rightmost weakly increasing part of the vector
// let mut i = self.len() - 1;
// while i > 0 && self[i-1] <= self[i] {
// i -= 1;
// }
//
// // If that is the entire vector, this is the first-ordered permutation.
// if i == 0 {
// return false;
// }
//
// // Step 2: Reverse the weakly increasing part
// self[i..].reverse();
//
// // Step 3: Find the rightmost element equal to or bigger than the pivot (i-1)
// let mut j = self.len() - 1;
// while j >= i && self[j-1] < self[i-1] {
// j -= 1;
// }
//
// // Step 4: Swap that element with the pivot
// self.swap(i-1, j);
//
// true
// }
//
// #[inline]
// fn clone_from_slice(&mut self, src: &[T]) -> usize where T: Clone {
// let min = cmp::min(self.len(), src.len());
// let dst = &mut self[.. min];
// let src = &src[.. min];
// for i in 0..min {
// dst[i].clone_from(&src[i]);
// }
// min
// }
// }
type T = i32;
#[test]
#[should_panic]
fn init_test1() {
let slice: &[T] = &[];
let _: &[T] = slice.init(); // panicked at 'arithmetic operation overflowed'
}
#[test]
fn init_test2() {
let slice: &[T] = &[11, 12, 12, 13, 14, 15, 16];
let init: &[T] = slice.init();
assert_eq!(init, &[11, 12, 12, 13, 14, 15]);
}
}<|fim▁end|> | // }
// |
<|file_name|>babylon.animation.ts<|end_file_name|><|fim▁begin|>module BABYLON {
export class Animation {
private _keys: Array<any>;
private _offsetsCache = {};
private _highLimitsCache = {};
private _stopped = false;
public _target;
private _easingFunction: IEasingFunction;
public targetPropertyPath: string[];
public currentFrame: number;
public static CreateAndStartAnimation(name: string, mesh: AbstractMesh, tartgetProperty: string,
framePerSecond: number, totalFrame: number,
from: any, to: any, loopMode?: number) {
var dataType = undefined;
if (!isNaN(parseFloat(from)) && isFinite(from)) {
dataType = Animation.ANIMATIONTYPE_FLOAT;
} else if (from instanceof Quaternion) {
dataType = Animation.ANIMATIONTYPE_QUATERNION;
} else if (from instanceof Vector3) {
dataType = Animation.ANIMATIONTYPE_VECTOR3;
} else if (from instanceof Vector2) {
dataType = Animation.ANIMATIONTYPE_VECTOR2;
} else if (from instanceof Color3) {
dataType = Animation.ANIMATIONTYPE_COLOR3;
}
if (dataType == undefined) {
return null;
}
var animation = new Animation(name, tartgetProperty, framePerSecond, dataType, loopMode);
var keys = [];
keys.push({ frame: 0, value: from });
keys.push({ frame: totalFrame, value: to });
animation.setKeys(keys);
mesh.animations.push(animation);
return mesh.getScene().beginAnimation(mesh, 0, totalFrame,(animation.loopMode === 1));
}
constructor(public name: string, public targetProperty: string, public framePerSecond: number, public dataType: number, public loopMode?: number) {
this.targetPropertyPath = targetProperty.split(".");
this.dataType = dataType;
this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
}
// Methods
public isStopped(): boolean {
return this._stopped;
}
public getKeys(): any[] {
return this._keys;
}
public getEasingFunction() {
return this._easingFunction;
}
public setEasingFunction(easingFunction: EasingFunction) {
this._easingFunction = easingFunction;
}
public floatInterpolateFunction(startValue: number, endValue: number, gradient: number): number {
return startValue + (endValue - startValue) * gradient;
}
public quaternionInterpolateFunction(startValue: Quaternion, endValue: Quaternion, gradient: number): Quaternion {
return Quaternion.Slerp(startValue, endValue, gradient);
}
public vector3InterpolateFunction(startValue: Vector3, endValue: Vector3, gradient: number): Vector3 {
return Vector3.Lerp(startValue, endValue, gradient);
}
public vector2InterpolateFunction(startValue: Vector2, endValue: Vector2, gradient: number): Vector2 {
return Vector2.Lerp(startValue, endValue, gradient);
}
public color3InterpolateFunction(startValue: Color3, endValue: Color3, gradient: number): Color3 {
return Color3.Lerp(startValue, endValue, gradient);
}
public matrixInterpolateFunction(startValue: Matrix, endValue: Matrix, gradient: number): Matrix {
var startScale = new Vector3(0, 0, 0);
var startRotation = new Quaternion();
var startTranslation = new Vector3(0, 0, 0);
startValue.decompose(startScale, startRotation, startTranslation);
var endScale = new Vector3(0, 0, 0);
var endRotation = new Quaternion();
var endTranslation = new Vector3(0, 0, 0);
endValue.decompose(endScale, endRotation, endTranslation);
var resultScale = this.vector3InterpolateFunction(startScale, endScale, gradient);
var resultRotation = this.quaternionInterpolateFunction(startRotation, endRotation, gradient);
var resultTranslation = this.vector3InterpolateFunction(startTranslation, endTranslation, gradient);
var result = Matrix.Compose(resultScale, resultRotation, resultTranslation);
return result;
}
public clone(): Animation {
var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
clone.setKeys(this._keys);
return clone;
}
public setKeys(values: Array<any>): void {
this._keys = values.slice(0);
this._offsetsCache = {};
this._highLimitsCache = {};
}
private _getKeyValue(value: any): any {
if (typeof value === "function") {
return value();
}
return value;
}
private _interpolate(currentFrame: number, repeatCount: number, loopMode: number, offsetValue?, highLimitValue?) {
if (loopMode === Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
}
this.currentFrame = currentFrame;
// Try to get a hash to find the right key
var startKey = Math.max(0, Math.min(this._keys.length - 1, Math.floor(this._keys.length * (currentFrame - this._keys[0].frame) / (this._keys[this._keys.length - 1].frame - this._keys[0].frame)) - 1));
if (this._keys[startKey].frame >= currentFrame) {
while (startKey - 1 >= 0 && this._keys[startKey].frame >= currentFrame) {
startKey--;
}
}
for (var key = startKey; key < this._keys.length ; key++) {
if (this._keys[key + 1].frame >= currentFrame) {
var startValue = this._getKeyValue(this._keys[key].value);
var endValue = this._getKeyValue(this._keys[key + 1].value);
// gradient : percent of currentFrame between the frame inf and the frame sup
var gradient = (currentFrame - this._keys[key].frame) / (this._keys[key + 1].frame - this._keys[key].frame);
// check for easingFunction and correction of gradient
if (this._easingFunction != null) {
gradient = this._easingFunction.ease(gradient);
}
switch (this.dataType) {
// Float
case Animation.ANIMATIONTYPE_FLOAT:
switch (loopMode) {
case Animation.ANIMATIONLOOPMODE_CYCLE:
case Animation.ANIMATIONLOOPMODE_CONSTANT:
return this.floatInterpolateFunction(startValue, endValue, gradient);
case Animation.ANIMATIONLOOPMODE_RELATIVE:
return offsetValue * repeatCount + this.floatInterpolateFunction(startValue, endValue, gradient);
}
break;
// Quaternion
case Animation.ANIMATIONTYPE_QUATERNION:
var quaternion = null;
switch (loopMode) {
case Animation.ANIMATIONLOOPMODE_CYCLE:
case Animation.ANIMATIONLOOPMODE_CONSTANT:
quaternion = this.quaternionInterpolateFunction(startValue, endValue, gradient);
break;
case Animation.ANIMATIONLOOPMODE_RELATIVE:
quaternion = this.quaternionInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
break;
}
return quaternion;
// Vector3
case Animation.ANIMATIONTYPE_VECTOR3:
switch (loopMode) {
case Animation.ANIMATIONLOOPMODE_CYCLE:
case Animation.ANIMATIONLOOPMODE_CONSTANT:
return this.vector3InterpolateFunction(startValue, endValue, gradient);
case Animation.ANIMATIONLOOPMODE_RELATIVE:
return this.vector3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
}
// Vector2
case Animation.ANIMATIONTYPE_VECTOR2:
switch (loopMode) {
case Animation.ANIMATIONLOOPMODE_CYCLE:
case Animation.ANIMATIONLOOPMODE_CONSTANT:
return this.vector2InterpolateFunction(startValue, endValue, gradient);
case Animation.ANIMATIONLOOPMODE_RELATIVE:
return this.vector2InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
}
// Color3
case Animation.ANIMATIONTYPE_COLOR3:
switch (loopMode) {
case Animation.ANIMATIONLOOPMODE_CYCLE:
case Animation.ANIMATIONLOOPMODE_CONSTANT:
return this.color3InterpolateFunction(startValue, endValue, gradient);
case Animation.ANIMATIONLOOPMODE_RELATIVE:
return this.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
}
// Matrix
case Animation.ANIMATIONTYPE_MATRIX:
switch (loopMode) {
case Animation.ANIMATIONLOOPMODE_CYCLE:
case Animation.ANIMATIONLOOPMODE_CONSTANT:
// return this.matrixInterpolateFunction(startValue, endValue, gradient);
case Animation.ANIMATIONLOOPMODE_RELATIVE:
return startValue;
}
default:
break;
}
break;
}
}
return this._getKeyValue(this._keys[this._keys.length - 1].value);
}
public animate(delay: number, from: number, to: number, loop: boolean, speedRatio: number): boolean {
if (!this.targetPropertyPath || this.targetPropertyPath.length < 1) {
this._stopped = true;
return false;
}
var returnValue = true;
// Adding a start key at frame 0 if missing
if (this._keys[0].frame !== 0) {
var newKey = { frame: 0, value: this._keys[0].value };
this._keys.splice(0, 0, newKey);
}
// Check limits
if (from < this._keys[0].frame || from > this._keys[this._keys.length - 1].frame) {
from = this._keys[0].frame;
}
if (to < this._keys[0].frame || to > this._keys[this._keys.length - 1].frame) {
to = this._keys[this._keys.length - 1].frame;
}
// Compute ratio
var range = to - from;
var offsetValue;
// ratio represents the frame delta between from and to
var ratio = delay * (this.framePerSecond * speedRatio) / 1000.0;
var highLimitValue = 0;
if (ratio > range && !loop) { // If we are out of range and not looping get back to caller
returnValue = false;
highLimitValue = this._getKeyValue(this._keys[this._keys.length - 1].value);
} else {
// Get max value if required
if (this.loopMode !== Animation.ANIMATIONLOOPMODE_CYCLE) {
var keyOffset = to.toString() + from.toString();
if (!this._offsetsCache[keyOffset]) {
var fromValue = this._interpolate(from, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
var toValue = this._interpolate(to, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
switch (this.dataType) {
// Float
case Animation.ANIMATIONTYPE_FLOAT:
this._offsetsCache[keyOffset] = toValue - fromValue;
break;
// Quaternion
case Animation.ANIMATIONTYPE_QUATERNION:
this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
break;
// Vector3
case Animation.ANIMATIONTYPE_VECTOR3:
this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
// Vector2
case Animation.ANIMATIONTYPE_VECTOR2:
this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
// Color3
case Animation.ANIMATIONTYPE_COLOR3:
this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
default:
break;
}
this._highLimitsCache[keyOffset] = toValue;
}
highLimitValue = this._highLimitsCache[keyOffset];
offsetValue = this._offsetsCache[keyOffset];
}
}
if (offsetValue === undefined) {
switch (this.dataType) {
// Float
case Animation.ANIMATIONTYPE_FLOAT:
offsetValue = 0;
break;
// Quaternion
case Animation.ANIMATIONTYPE_QUATERNION:
offsetValue = new Quaternion(0, 0, 0, 0);
break;
// Vector3
case Animation.ANIMATIONTYPE_VECTOR3:
offsetValue = Vector3.Zero();
break;
// Vector2
case Animation.ANIMATIONTYPE_VECTOR2:
offsetValue = Vector2.Zero();
break;
// Color3
case Animation.ANIMATIONTYPE_COLOR3:
offsetValue = Color3.Black();
}
}
// Compute value
var repeatCount = (ratio / range) >> 0;
var currentFrame = returnValue ? from + ratio % range : to;
var currentValue = this._interpolate(currentFrame, repeatCount, this.loopMode, offsetValue, highLimitValue);
// Set value
if (this.targetPropertyPath.length > 1) {
var property = this._target[this.targetPropertyPath[0]];
for (var index = 1; index < this.targetPropertyPath.length - 1; index++) {
property = property[this.targetPropertyPath[index]];
}
property[this.targetPropertyPath[this.targetPropertyPath.length - 1]] = currentValue;
} else {
this._target[this.targetPropertyPath[0]] = currentValue;
}
if (this._target.markAsDirty) {
this._target.markAsDirty(this.targetProperty);
}
if (!returnValue) {
this._stopped = true;
}
return returnValue;
}
// Statics
private static _ANIMATIONTYPE_FLOAT = 0;
private static _ANIMATIONTYPE_VECTOR3 = 1;
private static _ANIMATIONTYPE_QUATERNION = 2;
private static _ANIMATIONTYPE_MATRIX = 3;
private static _ANIMATIONTYPE_COLOR3 = 4;
private static _ANIMATIONTYPE_VECTOR2 = 5;
private static _ANIMATIONLOOPMODE_RELATIVE = 0;
private static _ANIMATIONLOOPMODE_CYCLE = 1;
private static _ANIMATIONLOOPMODE_CONSTANT = 2;
public static get ANIMATIONTYPE_FLOAT(): number {
return Animation._ANIMATIONTYPE_FLOAT;
}
public static get ANIMATIONTYPE_VECTOR3(): number {
return Animation._ANIMATIONTYPE_VECTOR3;
}
public static get ANIMATIONTYPE_VECTOR2(): number {
return Animation._ANIMATIONTYPE_VECTOR2;
}
public static get ANIMATIONTYPE_QUATERNION(): number {
return Animation._ANIMATIONTYPE_QUATERNION;
}<|fim▁hole|>
public static get ANIMATIONTYPE_MATRIX(): number {
return Animation._ANIMATIONTYPE_MATRIX;
}
public static get ANIMATIONTYPE_COLOR3(): number {
return Animation._ANIMATIONTYPE_COLOR3;
}
public static get ANIMATIONLOOPMODE_RELATIVE(): number {
return Animation._ANIMATIONLOOPMODE_RELATIVE;
}
public static get ANIMATIONLOOPMODE_CYCLE(): number {
return Animation._ANIMATIONLOOPMODE_CYCLE;
}
public static get ANIMATIONLOOPMODE_CONSTANT(): number {
return Animation._ANIMATIONLOOPMODE_CONSTANT;
}
}
}<|fim▁end|> | |
<|file_name|>Solution.java<|end_file_name|><|fim▁begin|>package com.mgireesh;
public class Solution extends VersionControl {
public int firstBadVersion(int n) {
int badVersion = 0;<|fim▁hole|> int end = n;
while (start < end) {
int mid = start + (end - start) / 2;
if (isBadVersion(mid)) {
end = mid;
} else {
start = mid + 1;
}
}
return start;
}
}<|fim▁end|> |
int start = 1; |
<|file_name|>tagger.js<|end_file_name|><|fim▁begin|>let BASE_DIR = '/masn01-archive/';
const TAG_OPTIONS = ['meteor', 'cloud', 'bug', 'misc'];
let CURR_DIR = null;
let CURR_FILES = null;
let INIT_CMAP = null;
let CURR_IDX = 0;
let PREV_IDX = null;
$(async function() {
let cameras = JSON.parse(await $.get('cameras.php'));
cameras.forEach((camera) => {
$('#masn-switch').append(`<option value='${camera}/'>${camera}</option>`);
});
BASE_DIR = $('#masn-switch').val();
JS9.ResizeDisplay(750, 750);
TAG_OPTIONS.forEach(tag => $('#tag-select').append(`<option value='${tag}'>${tag}</option>`));
$('#datepicker').prop('disabled', true);
let result = await $.get(BASE_DIR);
let years = getDirectories(result, /\d{4}/);
console.log(years);
new Pikaday({
field: document.getElementById('datepicker'),
format: 'YYYY-MM-DD',
minDate: moment(`${years[0]}-01-01`, 'YYYY-MM-DD').toDate(),
maxDate: moment(`${years[years.length-1]}-12-31`, 'YYYY-MM-DD').toDate(),
defaultDate: moment(`2018-11-20`).toDate(),
onSelect: renderDate,
onDraw: async function(evt) {
let { year, month } = evt.calendars[0];
let { tabs, days } = await $.get(`stats.php?y=${year}&m=${String(month + 1).padStart(2, '0')}`);
let renderedDays = $('.pika-lendar tbody td').filter('[data-day]');
renderedDays.each((_, elem) => {
let dateStr = moment({
day: $(elem).data('day'),
month: month,
year: year
}).format('YYYY-MM-DD');
if (days.indexOf(dateStr) !== -1) {
let dateTab = tabs[days.indexOf(dateStr)];
$(elem).attr('data-tab', dateTab);
if (0 <= dateTab && dateTab < POOR_LIM) $(elem).addClass('day-poor');
else if (POOR_LIM <= dateTab && dateTab < MEDIUM_LIM) $(elem).addClass('day-medium');
else if (MEDIUM_LIM <= dateTab && dateTab < GOOD_LIM) $(elem).addClass('day-good');
}
});
}
});
$('#datepicker').prop('disabled', false);
$('#fileprev').click(function() {
if (CURR_FILES == null) return;
CURR_IDX = CURR_IDX - 1 < 0 ? CURR_FILES.length - 1 : CURR_IDX - 1;
$('#slider').slider('value', CURR_IDX + 1);
renderCurrentFile();
});
$('#filenext').click(function() {
if (CURR_FILES == null) return;
CURR_IDX = CURR_IDX + 1 >= CURR_FILES.length - 1 ? 0 : CURR_IDX + 1;
$('#slider').slider('value', CURR_IDX + 1);
renderCurrentFile();
});
$('#action-tag').click(function() {
let selectedRegions = JS9.GetRegions('selected');
if (selectedRegions.length === 1) {
$('#tag-select')[0].selectedIndex = 0;
$('#tag-modal').show();
} else if (selectedRegions.length > 1) {
alert('Please select only one region.');
} else {
alert('Please select a region.');
}
});
$('#tag-select').change(function(evt) {
let tag = $(this).val();
if (tag.trim() != '') {
JS9.ChangeRegions('selected', { text: tag, data: { tag: tag } });
saveCurrentRegions();
}
$('#tag-modal').hide();
});
$('#action-reset').click(function() {
if (INIT_CMAP == null) return;
JS9.SetColormap(INIT_CMAP.colormap, INIT_CMAP.contrast, INIT_CMAP.bias);
});
$('#action-save').click(function() {
saveCurrentRegions();
alert('All changes saved.');
});
$('#action-info').click(function() {
$('#info-modal').show();
});
$('.modal-close').click(function() {
$('.modal').hide();
});
$(window).keydown(function(evt) {
if (evt.which === 8 && JS9.GetImageData(true)) saveCurrentRegions();
if (evt.which === 27) $('.modal').hide();
});
});
function createSlider() {
let handle = $('#fits-handle');
handle.text(1);
$('#slider').slider({
value: 1,
min: 1,
max: CURR_FILES.length,
change: function(evt, ui) {
handle.text(ui.value);
CURR_IDX = ui.value - 1;
renderCurrentFile();
},
slide: function(evt, ui) {
handle.text(ui.value);
}
});
}
function getDirectories(html, regex) {
let parser = new DOMParser();
let root = parser.parseFromString(html, 'text/html');
let links = [].slice.call(root.getElementsByTagName('a'));
let hrefs = links.map(link => {
let directory = link.href.endsWith('/');
let dest = (directory ? link.href.slice(0, -1) : link.href).split('/').pop();
return dest.match(regex) ? dest : null;
}).filter(e => e != null);
return hrefs;
}
function renderCurrentFile() {
if (PREV_IDX == CURR_IDX) return;
if (CURR_FILES == null) return;
PREV_IDX = CURR_IDX;
let currentFile = CURR_FILES[CURR_IDX];
let currPath = `${CURR_DIR}/${currentFile}`;
JS9.CloseImage();
PREV_ZOOM = null;
PREV_PAN = null;
$('.JS9PluginContainer').each((idx, elem) => {
if($(elem).find('.tag-toggle, #tag-overlay').length === 0) {
$(elem).append(`<div class='tag-toggle'></div>`);
}
});
JS9.globalOpts.menuBar = ['scale'];
JS9.globalOpts.toolBar = ['box', 'circle', 'ellipse', 'zoom+', 'zoom-', 'zoomtofit'];
JS9.SetToolbar('init');
JS9.Load(currPath, {
zoom: 'ToFit',
onload: async function() {
let fileData = JSON.parse(await $.get({
url: 'regions.php',
cache: false<|fim▁hole|> }));
if (Object.keys(fileData).length > 0) {
fileData.params = JSON.parse(fileData.params);
fileData.params.map(region => {
if (region.data.tag) region.text = region.data.tag;
return region;
});
JS9.AddRegions(fileData.params);
}
JS9.SetZoom('ToFit');
if (JS9.GetFlip() === 'none') JS9.SetFlip('x');
CENTER_PAN = JS9.GetPan();
INIT_CMAP = JS9.GetColormap();
console.log(CENTER_PAN);
$('#viewer-container').show();
$('#actions').show();
$('#filename').text(`${currentFile} (${CURR_IDX + 1}/${CURR_FILES.length})`);
$('#filetime').show();
updateSkymap(currentFile);
}
});
}
async function renderDate(date) {
$('#filename').text('Loading...');
let dateStr = moment(date).format('YYYY-MM-DD');
let yearDir = dateStr.substring(0, 4);
let monthDir = dateStr.substring(0, 7);
let parentDir = `${BASE_DIR}${yearDir}/${monthDir}/${dateStr}`
let list;
try {
list = await $.get(parentDir);
} catch (error) {
list = null;
}
let entries = getDirectories(list, /\.fits?/);
console.log(entries);
PREV_IDX = null;
CURR_IDX = 0;
CURR_DIR = parentDir;
CURR_FILES = entries;
if (list) {
$('#skytab').show().attr('src', `${parentDir}/sky.tab.thumb.png`);
createSlider();
renderCurrentFile();
} else {
$('#skytab').hide();
$('#filename').text('No data.');
$('#filetime').hide();
$('#viewer-container').hide();
$('#actions').hide();
}
}
function saveCurrentRegions() {
let regions = JS9.GetRegions('all');
let tags = JS9.GetRegions('all').map(region => region.data ? region.data.tag : null).filter(tag => tag != null);
$.get({
url: 'regions.php',
cache: false
}, {
action: 'update',
path: CURR_FILES[CURR_IDX],
tags: tags.join(','),
params: JSON.stringify(regions)
}).then(response => {
if (response.trim() !== '') {
alert(`Error saving regions: ${response}`);
}
});
}<|fim▁end|> | }, {
action: 'list',
path: currentFile |
<|file_name|>TimezoneModel.js<|end_file_name|><|fim▁begin|>Ext.define('Onlineshopping.onlineshopping.shared.shop.model.location.TimezoneModel', {
"extend": "Ext.data.Model",
"fields": [{
"name": "primaryKey",
"type": "string",
"defaultValue": ""
}, {
"name": "timeZoneId",
"type": "string",
"defaultValue": ""
}, {
"name": "utcdifference",
"type": "int",
"defaultValue": ""
}, {
"name": "gmtLabel",
"type": "string",
"defaultValue": ""
}, {
"name": "timeZoneLabel",
"type": "string",
"defaultValue": ""
}, {
"name": "country",
"type": "string",
"defaultValue": ""
}, {<|fim▁hole|> "name": "versionId",
"type": "int",
"defaultValue": ""
}, {
"name": "entityAudit",
"reference": "EntityAudit"
}, {
"name": "primaryDisplay",
"type": "string",
"defaultValue": ""
}]
});<|fim▁end|> | "name": "cities",
"type": "string",
"defaultValue": ""
}, { |
<|file_name|>test_abstract.py<|end_file_name|><|fim▁begin|>from __future__ import unicode_literals
try:
import unittest2 as unittest
except ImportError:
import unittest
from rpaths import unicode, PY3, AbstractPath, PosixPath, WindowsPath
class TestAbstract(unittest.TestCase):
def test_construct(self):
"""Tests building an AbstractPath."""
with self.assertRaises(RuntimeError):
AbstractPath('path/to/something')
<|fim▁hole|> """Tests building paths."""
self.assertEqual(WindowsPath('C:\\',
WindowsPath('some/dir'),
'with',
'files.txt').path,
'C:\\some\\dir\\with\\files.txt')
with self.assertRaises(TypeError):
WindowsPath(WindowsPath('C:\\somedir'), PosixPath('file.sh'))
self.assertEqual((WindowsPath('Users\\R\xE9mi/Desktop') /
WindowsPath(b'pictures/m\xE9chant.jpg')).path,
'Users\\R\xE9mi\\Desktop\\pictures\\m\xE9chant.jpg')
self.assertEqual((WindowsPath('C:\\dir') /
WindowsPath('D:\\other')).path,
'D:\\other')
def test_plus(self):
"""Tests the plus operator."""
self.assertEqual((WindowsPath('some\\file.txt') + '.bak').path,
'some\\file.txt.bak')
with self.assertRaises(TypeError):
WindowsPath('some\\file.txt') + WindowsPath('.bak')
with self.assertRaises(ValueError):
WindowsPath('some\\file.txt') + '.bak/kidding'
with self.assertRaises(ValueError):
WindowsPath('some\\file.txt') + '/backup'
def test_str(self):
"""Tests getting string representations (repr/bytes/unicode)."""
latin = WindowsPath('C:\\r\xE9mi')
nonlatin = WindowsPath('C:\\you like\u203D.txt')
# repr()
self.assertEqual(repr(latin),
"WindowsPath(u'C:\\\\r\\xe9mi')")
self.assertEqual(repr(nonlatin),
"WindowsPath(u'C:\\\\you like\\u203d.txt')")
# bytes()
self.assertEqual(bytes(latin),
b'C:\\r\xe9mi')
self.assertEqual(bytes(nonlatin),
b'C:\\you like?.txt')
# unicode()
self.assertEqual(unicode(latin),
'C:\\r\xe9mi')
self.assertEqual(unicode(nonlatin),
'C:\\you like\u203d.txt')
def test_parts(self):
"""Tests parent, ancestor, name, stem, ext."""
relative = WindowsPath('directory/users\\r\xE9mi/file.txt')
absolute = WindowsPath('\\some/other\\thing.h\xE9h\xE9')
self.assertEqual(relative.parent.path,
'directory\\users\\r\xE9mi')
self.assertEqual(absolute.parent.path,
'\\some\\other')
self.assertEqual(absolute.ancestor(10).path,
'\\')
self.assertEqual(relative.name, 'file.txt')
self.assertEqual(absolute.name, 'thing.h\xE9h\xE9')
self.assertEqual(absolute.unicodename, 'thing.h\xE9h\xE9')
self.assertEqual(absolute.stem, 'thing')
self.assertEqual(absolute.ext, '.h\xE9h\xE9')
self.assertEqual(relative._components(),
['directory', 'users', 'r\xE9mi', 'file.txt'])
self.assertEqual(absolute._components(),
['\\', 'some', 'other', 'thing.h\xE9h\xE9'])
def test_root(self):
"""Tests roots, drives and UNC shares."""
a = WindowsPath(b'some/relative/path')
b = WindowsPath('alsorelative')
c = WindowsPath(b'/this/is/absolute')
d = WindowsPath('C:\\')
e = WindowsPath(b'C:\\also/absolute')
f = WindowsPath('\\\\SOMEMACHINE\\share\\some\\file')
def split_root(f):
return tuple(p.path for p in f.split_root())
self.assertEqual(split_root(a),
('.', 'some\\relative\\path'))
self.assertEqual(split_root(b),
('.', 'alsorelative'))
self.assertFalse(b.is_absolute)
self.assertEqual(split_root(c),
('\\', 'this\\is\\absolute'))
self.assertTrue(c.is_absolute)
self.assertEqual(split_root(d),
('C:\\', '.'))
self.assertTrue(d.is_absolute)
self.assertEqual(d.root.path, 'C:\\')
self.assertEqual(split_root(e),
('C:\\', 'also\\absolute'))
# FIXME : normpath() doesn't behave consistently: puts \ at the end on
# PY3, not on PY2.
self.assertIn(split_root(f),
[('\\\\SOMEMACHINE\\share', 'some\\file'),
('\\\\SOMEMACHINE\\share\\', 'some\\file')])
def test_rel_path_to(self):
"""Tests the rel_path_to method."""
self.assertEqual(WindowsPath('.').rel_path_to(WindowsPath('')).path,
'.')
self.assertEqual(WindowsPath('\\var\\log\\apache2\\').rel_path_to(
'\\var\\www\\cat.jpg').path,
'..\\..\\www\\cat.jpg')
self.assertEqual(WindowsPath('C:\\var\\log\\apache2\\').rel_path_to(
'C:\\tmp\\access.log').path,
'..\\..\\..\\tmp\\access.log')
self.assertEqual(WindowsPath('var\\log').rel_path_to(
'var\\log\\apache2\\access.log').path,
'apache2\\access.log')
self.assertEqual(WindowsPath('\\var\\log\\apache2').rel_path_to(
'\\var\\log\\apache2').path,
'.')
self.assertEqual(WindowsPath('C:\\').rel_path_to(
'C:\\var\\log\\apache2\\access.log').path,
'var\\log\\apache2\\access.log')
self.assertEqual(WindowsPath('\\tmp\\secretdir\\').rel_path_to(
'\\').path,
'..\\..')
self.assertEqual(WindowsPath('C:\\tmp\\secretdir\\').rel_path_to(
'D:\\other\\file.txt').path,
'D:\\other\\file.txt')
with self.assertRaises(TypeError):
WindowsPath('C:\\mydir\\').rel_path_to(PosixPath('/tmp/file'))
def test_lies_under(self):
"""Tests the lies_under method."""
self.assertTrue(WindowsPath('\\tmp')
.lies_under('\\'))
self.assertFalse(WindowsPath('C:\\tmp')
.lies_under('C:\\var'))
self.assertFalse(WindowsPath('\\tmp')
.lies_under('C:\\tmp'))
self.assertFalse(WindowsPath('C:\\')
.lies_under('D:\\tmp'))
self.assertTrue(WindowsPath('\\tmp\\some\\file\\here')
.lies_under('\\tmp\\some'))
self.assertFalse(WindowsPath('\\tmp\\some\\file\\here')
.lies_under('\\tmp\\no'))
self.assertFalse(WindowsPath('C:\\tmp\\some\\file\\here')
.lies_under('C:\\no\\tmp\\some'))
self.assertFalse(WindowsPath('\\tmp\\some\\file\\here')
.lies_under('\\no\\some'))
self.assertTrue(WindowsPath('C:\\tmp\\some\\file\\here')
.lies_under('C:\\tmp\\some\\file\\here'))
self.assertTrue(WindowsPath('\\')
.lies_under('\\'))
self.assertTrue(WindowsPath('')
.lies_under(''))
self.assertTrue(WindowsPath('test')
.lies_under(''))
self.assertFalse(WindowsPath('')
.lies_under('test'))
self.assertFalse(WindowsPath('test')
.lies_under('\\'))
def test_comparisons(self):
"""Tests the comparison operators."""
self.assertTrue(WindowsPath('\\tmp') == WindowsPath('\\tmp'))
self.assertFalse(WindowsPath('C:\\file') != 'c:\\FILE')
self.assertTrue('c:\\FILE' == WindowsPath('C:\\file'))
self.assertFalse(WindowsPath('C:\\file') == WindowsPath('C:\\dir'))
self.assertFalse(WindowsPath('some/file') == PosixPath('some/file'))
self.assertTrue(WindowsPath('path/to/file1') < 'path/to/file2')
self.assertFalse('path/to/file1' >= WindowsPath('path/to/file2'))
if PY3:
with self.assertRaises(TypeError):
WindowsPath('some/file') < PosixPath('other/file')
class TestPosix(unittest.TestCase):
"""Tests for PosixPath.
"""
def test_construct(self):
"""Tests building paths."""
self.assertEqual(PosixPath('/',
PosixPath(b'r\xE9mis/dir'),
'with',
'files.txt').path,
b'/r\xE9mis/dir/with/files.txt')
with self.assertRaises(TypeError):
PosixPath('/tmp/test', WindowsPath('folder'), 'cat.gif')
self.assertEqual((PosixPath(b'/tmp/dir') /
PosixPath('r\xE9mis/files/')).path,
b'/tmp/dir/r\xC3\xA9mis/files')
if PY3:
self.assertEqual(PosixPath('/tmp/r\uDCE9mi').path,
b'/tmp/r\xE9mi')
self.assertEqual((PosixPath(b'/home/test') /
PosixPath('/var/log')).path,
b'/var/log')
def test_plus(self):
"""Tests the plus operator."""
self.assertEqual((PosixPath('some/file.txt') + '.bak').path,
b'some/file.txt.bak')
with self.assertRaises(TypeError):
PosixPath('some/file.txt') + PosixPath('.bak')
with self.assertRaises(ValueError):
PosixPath('some/file.txt') + '.bak/kidding'
with self.assertRaises(ValueError):
PosixPath('some/file.txt') + '/backup'
def test_str(self):
"""Tests getting string representations (repr/bytes/unicode)."""
utf = PosixPath(b'/tmp/r\xC3\xA9mi')
nonutf = PosixPath(b'/tmp/r\xE9mi')
# repr()
self.assertEqual(repr(utf),
"PosixPath(b'/tmp/r\\xc3\\xa9mi')")
self.assertEqual(repr(nonutf),
"PosixPath(b'/tmp/r\\xe9mi')")
# bytes()
self.assertEqual(bytes(utf),
b'/tmp/r\xC3\xA9mi')
self.assertEqual(bytes(nonutf),
b'/tmp/r\xE9mi')
# unicode()
self.assertEqual(unicode(utf),
'/tmp/r\xE9mi')
self.assertEqual(unicode(nonutf),
'/tmp/r\uDCE9mi' if PY3 else '/tmp/r\uFFFDmi')
def test_parts(self):
"""Tests parent, ancestor, name, stem, ext."""
relative = PosixPath(b'directory/users/r\xE9mi/file.txt')
absolute = PosixPath('/some/other/thing.h\xE9h\xE9')
self.assertEqual(relative.parent.path,
b'directory/users/r\xE9mi')
self.assertEqual(absolute.parent.path,
b'/some/other')
self.assertEqual(absolute.ancestor(10).path,
b'/')
self.assertEqual(relative.name, b'file.txt')
self.assertEqual(absolute.name, b'thing.h\xC3\xA9h\xC3\xA9')
self.assertEqual(absolute.unicodename, 'thing.h\xE9h\xE9')
self.assertEqual(absolute.stem, b'thing')
self.assertEqual(absolute.ext, b'.h\xC3\xA9h\xC3\xA9')
self.assertEqual(relative._components(),
[b'directory', b'users', b'r\xE9mi', b'file.txt'])
self.assertEqual(absolute._components(),
[b'/', b'some',
b'other', b'thing.h\xC3\xA9h\xC3\xA9'])
def test_root(self):
"""Tests roots."""
a = PosixPath(b'some/relative/path')
b = PosixPath('alsorelative')
c = PosixPath(b'/this/is/absolute')
d = PosixPath('/')
def split_root(f):
return tuple(p.path for p in f.split_root())
# FIXME : This behaves weirdly because of normpath(). Do we want this?
self.assertEqual(split_root(a),
(b'.', b'some/relative/path'))
self.assertEqual(split_root(b),
(b'.', b'alsorelative'))
self.assertFalse(b.is_absolute)
self.assertEqual(split_root(c),
(b'/', b'this/is/absolute'))
self.assertTrue(c.is_absolute)
self.assertEqual(split_root(d),
(b'/', b'.'))
self.assertTrue(d.is_absolute)
self.assertEqual(d.root.path, b'/')
def test_rel_path_to(self):
"""Tests the rel_path_to method."""
self.assertEqual(PosixPath('.').rel_path_to(PosixPath('')).path,
b'.')
self.assertEqual(PosixPath(b'/var/log/apache2/').rel_path_to(
b'/var/www/cat.jpg').path,
b'../../www/cat.jpg')
self.assertEqual(PosixPath(b'/var/log/apache2/').rel_path_to(
b'/tmp/access.log').path,
b'../../../tmp/access.log')
self.assertEqual(PosixPath(b'var/log').rel_path_to(
b'var/log/apache2/access.log').path,
b'apache2/access.log')
self.assertEqual(PosixPath(b'/var/log/apache2').rel_path_to(
b'/var/log/apache2').path,
b'.')
self.assertEqual(PosixPath(b'/').rel_path_to(
b'/var/log/apache2/access.log').path,
b'var/log/apache2/access.log')
self.assertEqual(PosixPath(b'/tmp/secretdir/').rel_path_to(
b'/').path,
b'../..')
def test_lies_under(self):
""" Tests the lies_under method."""
self.assertTrue(PosixPath(b'/tmp')
.lies_under(b'/'))
self.assertFalse(PosixPath(b'/tmp')
.lies_under(b'/var'))
self.assertTrue(PosixPath(b'/tmp/some/file/here')
.lies_under(b'/tmp/some'))
self.assertFalse(PosixPath(b'/tmp/some/file/here')
.lies_under(b'/tmp/no'))
self.assertFalse(PosixPath(b'/tmp/some/file/here')
.lies_under(b'/no/tmp/some'))
self.assertFalse(PosixPath(b'/tmp/some/file/here')
.lies_under(b'/no/some'))
self.assertTrue(PosixPath(b'/tmp/some/file/here')
.lies_under(b'/tmp/some/file/here'))
self.assertTrue(PosixPath(b'/')
.lies_under(b'/'))
self.assertTrue(PosixPath(b'')
.lies_under(b''))
self.assertTrue(PosixPath(b'test')
.lies_under(b''))
self.assertFalse(PosixPath(b'')
.lies_under(b'test'))
self.assertFalse(PosixPath(b'test')
.lies_under(b'/'))
def test_comparisons(self):
"""Tests the comparison operators."""
self.assertTrue(PosixPath(b'/tmp/r\xE9mi') == b'/tmp/r\xE9mi')
self.assertTrue(PosixPath(b'/file') != b'/FILE')
self.assertFalse(PosixPath(b'file') == PosixPath(b'dir'))
self.assertFalse(WindowsPath('some/file') == PosixPath('some/file'))
self.assertTrue(PosixPath(b'path/to/file1') < b'path/to/file2')
self.assertFalse(b'path/to/file1' >= PosixPath(b'path/to/file2'))
if PY3:
with self.assertRaises(TypeError):
WindowsPath('some/file') < PosixPath('other/file')<|fim▁end|> | class TestWindows(unittest.TestCase):
"""Tests for WindowsPath.
"""
def test_construct(self): |
<|file_name|>advogato.py<|end_file_name|><|fim▁begin|># Copyright (c) 2001-2004 Twisted Matrix Laboratories.<|fim▁hole|># See LICENSE for details.
#
'''
Usage:
advogato.py <name> <diary entry file>
'''
from twisted.web.xmlrpc import Proxy
from twisted.internet import reactor
from getpass import getpass
import sys
class AddDiary:
def __init__(self, name, password):
self.name = name
self.password = password
self.proxy = Proxy('http://advogato.org/XMLRPC')
def __call__(self, filename):
self.data = open(filename).read()
d = self.proxy.callRemote('authenticate', self.name, self.password)
d.addCallbacks(self.login, self.noLogin)
def noLogin(self, reason):
print "could not login"
reactor.stop()
def login(self, cookie):
d = self.proxy.callRemote('diary.set', cookie, -1, self.data)
d.addCallbacks(self.setDiary, self.errorSetDiary)
def setDiary(self, response):
reactor.stop()
def errorSetDiary(self, error):
print "could not set diary", error
reactor.stop()
diary = AddDiary(sys.argv[1], getpass())
diary(sys.argv[2])
reactor.run()<|fim▁end|> | |
<|file_name|>main.rs<|end_file_name|><|fim▁begin|>use std::net::{TcpStream, TcpListener};
use std::thread;
fn handle_client(stream: TcpStream) {
println!("Someone connected!");
}
fn main() {
println!("Starting Iron IRCd");<|fim▁hole|> match stream {
Ok(stream) => {
thread::spawn(move || {
handle_client(stream)
});
}
Err(e) => { /* Connection Failed */ }
}
}
}<|fim▁end|> |
let listener = TcpListener::bind("127.0.0.1:6667").unwrap();
for stream in listener.incoming() { |
<|file_name|>c_cm1x.py<|end_file_name|><|fim▁begin|># ----------------------------------------------------------------------------
# Copyright (C) 2013-2014 Huynh Vi Lam <[email protected]>
#
# This file is part of pimucha.
#
# 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<|fim▁hole|># ----------------------------------------------------------------------------
import logging,sys
logger = logging.getLogger()
X10Checkers = {
'RF' : 'x10chk(args)' ,
'PL' : 'x10chk(args)' ,
}
X10Encoders = {
'RF' : ('', 'x10rf2hex(args)', '') ,
'PL' : ('', 'x10pl2hex(args)', '') ,
}<|fim▁end|> | # 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/>. |
<|file_name|>Script.ts<|end_file_name|><|fim▁begin|>import { ILogger, getLogger } from './loggers';
import { CancellationToken, ICancellationToken } from '../util/CancellationToken';
import { Step } from './Step';
import { ModuleLoader } from './ModuleLoader';
import * as _ from 'underscore';
import { Guid } from '../util/Guid';
import { InjectorLookup, Module, ModuleRepository } from './Modules';
import { IScope, Scope } from './Scope';
import validateScriptDefinition from './scriptDefinitionValidator';
import * as helpers from '../util/helpers';
import './modules/assert';
import './modules/async';
import './modules/conditional';
import './modules/http';
import './modules/json';
import './modules/loop';
import './modules/math';
import './modules/misc';
import './modules/stats';
import './modules/timer';
import './modules/wait';
const YAML = require('pumlhorse-yamljs');
class ScriptOptions {
logger: ILogger;
}
export interface IScript {
run(context: any, cancellationToken?: ICancellationToken): Promise<any>;
addFunction(name: string, func: Function): void;
addModule(moduleDescriptor: string | Object): void;
id: string;
name: string;
}
export interface IScriptDefinition {
name: string;
description?: string;
modules?: any[];
functions?: Object;
expects?: string[];
steps: any[];
cleanup?: any[];
}
export class Script implements IScript {
id: string;
name: string;
private internalScript: IScriptInternal;
private static readonly DefaultModules = ['assert', 'async', 'conditional', 'json', 'loop', 'math', 'misc', 'timer', 'wait', 'http = http'];
public static readonly StandardModules = Script.DefaultModules.concat(['stats']);
constructor(private scriptDefinition: IScriptDefinition, private scriptOptions?: ScriptOptions) {
validateScriptDefinition(this.scriptDefinition);
this.id = new Guid().value;<|fim▁hole|>
if (this.scriptOptions == null) {
this.scriptOptions = new ScriptOptions();
}
if (this.scriptOptions.logger == null) {
this.scriptOptions.logger = getLogger();
}
this.internalScript = new InternalScript(this.id, this.scriptOptions);
}
static create(scriptText: string, scriptOptions?: ScriptOptions): Script {
const scriptDefinition = YAML.parse(scriptText);
return new Script(scriptDefinition, scriptOptions);
}
async run(context?: any, cancellationToken?: ICancellationToken): Promise<any> {
if (cancellationToken == null) cancellationToken = CancellationToken.None;
this.evaluateExpectations(context);
this.loadModules();
this.loadFunctions();
this.loadCleanupSteps();
const scope = new Scope(this.internalScript, context);
try {
await this.internalScript.runSteps(this.scriptDefinition.steps, scope, cancellationToken);
return scope;
}
finally {
await this.runCleanupTasks(scope, cancellationToken);
}
}
addFunction(name: string, func: Function): void {
this.internalScript.functions[name] = func;
}
addModule(moduleDescriptor: string | Object) {
const moduleLocator = ModuleLoader.getModuleLocator(moduleDescriptor);
const mod = ModuleRepository.lookup[moduleLocator.name];
if (mod == null) throw new Error(`Module "${moduleLocator.name}" does not exist`);
if (moduleLocator.hasNamespace) {
helpers.assignObjectByString(this.internalScript.modules, moduleLocator.namespace, mod.getFunctions());
}
else {
_.extend(this.internalScript.modules, mod.getFunctions());
}
_.extend(this.internalScript.injectors, mod.getInjectors())
}
private evaluateExpectations(context: any) {
if (this.scriptDefinition.expects == null) return;
const missingValues = _.difference(this.scriptDefinition.expects.map(m => m.toString()), _.keys(context));
if (missingValues.length > 0) {
throw new Error(missingValues.length > 1
? `Expected values "${missingValues.join(', ')}", but they were not passed`
: `Expected value "${missingValues[0]}", but it was not passed`)
}
}
private loadModules() {
const modules = Script.DefaultModules.concat(this.scriptDefinition.modules == null
? []
: this.scriptDefinition.modules)
for (let i = 0; i < modules.length; i++) {
this.addModule(modules[i]);
}
}
private loadFunctions() {
this.addFunction('debug', (msg) => this.scriptOptions.logger.debug(msg));
this.addFunction('log', (msg) => this.scriptOptions.logger.log(msg));
this.addFunction('warn', (msg) => this.scriptOptions.logger.warn(msg));
this.addFunction('error', (msg) => this.scriptOptions.logger.error(msg));
const functions = this.scriptDefinition.functions;
if (functions == null) {
return;
}
for(let name in functions) {
this.addFunction(name, this.createFunction(functions[name]));
}
}
private createFunction(val) {
if (_.isString(val)) return new Function(val)
function construct(args) {
function DeclaredFunction(): void {
return Function.apply(this, args);
}
DeclaredFunction.prototype = Function.prototype;
return new DeclaredFunction();
}
return construct(val)
}
private loadCleanupSteps() {
if (this.scriptDefinition.cleanup == null) {
return;
}
for (let i = 0; i < this.scriptDefinition.cleanup.length; i++) {
this.internalScript.cleanup.push(this.scriptDefinition.cleanup[i]);
}
}
private async runCleanupTasks(scope: Scope, cancellationToken: ICancellationToken): Promise<any> {
if (this.internalScript.cleanup == null) {
return;
}
for (let i = 0; i < this.internalScript.cleanup.length; i++) {
const task = this.internalScript.cleanup[i];
try {
await this.internalScript.runSteps([task], scope, cancellationToken);
}
catch (e) {
this.scriptOptions.logger.error(`Error in cleanup task: ${e.message}`);
}
}
}
}
export interface IScriptInternal {
modules: Module[];
functions: {[name: string]: Function};
injectors: InjectorLookup;
steps: any[];
cleanup: any[];
emit(eventName: string, eventInfo: any);
addCleanupTask(task: any, atEnd?: boolean);
getModule(moduleName: string): any;
id: string;
runSteps(steps: any[], scope: IScope, cancellationToken?: ICancellationToken): Promise<any>;
}
class InternalScript implements IScriptInternal {
id: string;
modules: Module[];
injectors: InjectorLookup;
functions: {[name: string]: Function};
steps: any[];
cleanup: any[];
private cancellationToken: ICancellationToken;
private isEnded: boolean = false;
constructor(id: string, private scriptOptions: ScriptOptions) {
this.id = id;
this.modules = [];
this.injectors = {
'$scope': (scope: IScope) => scope,
'$logger': () => this.scriptOptions.logger
};
this.functions = {
'end': () => { this.isEnded = true; }
};
this.steps = [];
this.cleanup = [];
}
emit(): void {
}
addCleanupTask(task: any, atEnd?: boolean): void {
if (atEnd) this.cleanup.push(task);
else this.cleanup.splice(0, 0, task);
}
getModule(moduleName: string): any {
return this.modules[moduleName];
}
async runSteps(steps: any[], scope: IScope, cancellationToken: ICancellationToken): Promise<any> {
if (cancellationToken != null) {
this.cancellationToken = cancellationToken;
}
if (steps == null || steps.length == 0) {
this.scriptOptions.logger.warn('Script does not contain any steps');
return;
}
_.extend(scope, this.modules, this.functions);
for (let i = 0; i < steps.length; i++) {
if (this.cancellationToken.isCancellationRequested || this.isEnded) {
return;
}
await this.runStep(steps[i], scope);
}
}
private async runStep(stepDefinition: any, scope: IScope) {
if (_.isFunction(stepDefinition)) {
// If we programatically added a function as a step, just shortcut and run it
return stepDefinition.call(scope);
}
let step: Step;
const lineNumber = stepDefinition.getLineNumber == null ? null : stepDefinition.getLineNumber();
if (_.isString(stepDefinition)) {
step = new Step(stepDefinition, null, scope, this.injectors, lineNumber);
}
else {
const functionName = _.keys(stepDefinition)[0];
step = new Step(functionName, stepDefinition[functionName], scope, this.injectors, lineNumber);
}
await step.run(this.cancellationToken);
}
}<|fim▁end|> | this.name = scriptDefinition.name; |
<|file_name|>test_parse_rank_score.py<|end_file_name|><|fim▁begin|>from scout.parse.variant.rank_score import parse_rank_score
from scout.parse.variant.variant import parse_variant
def test_parse_rank_score():
## GIVEN a rank score string on genmod format
rank_scores_info = "123:10"
variant_score = 10.0
family_id = "123"
## WHEN parsing the rank score
parsed_rank_score = parse_rank_score(rank_scores_info, family_id)
## THEN assert that the correct rank score is parsed
assert variant_score == parsed_rank_score
def test_parse_rank_score_no_score():
## GIVEN a empty rank score string
rank_scores_info = ""
family_id = "123"
## WHEN parsing the rank score
parsed_rank_score = parse_rank_score(rank_scores_info, family_id)<|fim▁hole|>
def test_parse_rank_score_variant(cyvcf2_variant, case_obj, scout_config):
## GIVEN a variant
rank_score = 15
case_id = case_obj["_id"]
## WHEN adding a rank score string to the INFO field
rank_score_str = f"{case_id}:{rank_score}"
cyvcf2_variant.INFO["RankScore"] = rank_score_str
## WHEN parsing the variant
var_info = parse_variant(cyvcf2_variant, case_obj)
## THEN assert that the correct score is parsed
assert var_info["rank_score"] == rank_score<|fim▁end|> | ## THEN assert that None is returned
assert parsed_rank_score == None
|
<|file_name|>single_thread_calculator.rs<|end_file_name|><|fim▁begin|>use crate::{MonteCarloPiCalculator, gen_random};
use std::sync::Arc;
pub struct SingleThreadCalculator {}
impl SingleThreadCalculator {
#[inline]
fn gen_randoms_static(n: usize) -> (Vec<f64>, Vec<f64>) {
let mut xs = vec![0.0; n];
let mut ys = vec![0.0; n];
for i in 0..n {
let mut t = gen_random(i as f64 / n as f64);
t = gen_random(t);
t = gen_random(t);
xs[i] = t;
for _ in 0..10 {
t = gen_random(t);
}<|fim▁hole|> ys[i] = t;
}
return (xs, ys);
}
#[inline]
#[allow(unused_parens)]
fn cal_static(xs: &Arc<Vec<f64>>, ys: &Arc<Vec<f64>>, n: usize) -> u64 {
let mut cnt = 0;
for i in 0..n {
if (xs[i] * xs[i] + ys[i] * ys[i] < 1.0) {
cnt += 1;
}
}
return cnt;
}
}
impl MonteCarloPiCalculator for SingleThreadCalculator {
#[inline]
fn new(_n: usize) -> SingleThreadCalculator {
return SingleThreadCalculator {};
}
#[inline]
fn gen_randoms(&self, n: usize) -> (Vec<f64>, Vec<f64>) {
return SingleThreadCalculator::gen_randoms_static(n);
}
#[inline]
fn cal(&self, xs: &Arc<Vec<f64>>, ys: &Arc<Vec<f64>>, n: usize) -> u64 {
return SingleThreadCalculator::cal_static(xs, ys, n);
}
}<|fim▁end|> | |
<|file_name|>cog_selector.py<|end_file_name|><|fim▁begin|># #START_LICENSE###########################################################
#
#
# This file is part of the Environment for Tree Exploration program
# (ETE). http://etetoolkit.org
#
# ETE 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.
#
# ETE 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 ETE. If not, see <http://www.gnu.org/licenses/>.
#
#
# ABOUT THE ETE PACKAGE
# =====================
#
# ETE is distributed under the GPL copyleft license (2008-2015).
#
# If you make use of ETE in published work, please cite:
#
# Jaime Huerta-Cepas, Joaquin Dopazo and Toni Gabaldon.
# ETE: a python Environment for Tree Exploration. Jaime BMC
# Bioinformatics 2010,:24doi:10.1186/1471-2105-11-24
#
# Note that extra references to the specific methods implemented in
# the toolkit may be available in the documentation.
#
# More info at http://etetoolkit.org. Contact: [email protected]
#
#
# #END_LICENSE#############################################################
from StringIO import StringIO
import cPickle
from string import strip
from collections import defaultdict
import logging
import os
log = logging.getLogger("main")
from ete2.tools.phylobuild_lib.master_task import CogSelectorTask
from ete2.tools.phylobuild_lib.errors import DataError, TaskError
from ete2.tools.phylobuild_lib.utils import (GLOBALS, print_as_table, generate_node_ids,
encode_seqname, md5, pjoin, _min, _max, _mean, _median, _std)
from ete2.tools.phylobuild_lib import db
__all__ = ["CogSelector"]
class CogSelector(CogSelectorTask):
def __init__(self, target_sp, out_sp, seqtype, conf, confname):
self.missing_factor = float(conf[confname]["_species_missing_factor"])
self.max_missing_factor = float(conf[confname]["_max_species_missing_factor"])
self.cog_hard_limit = int(conf[confname]["_max_cogs"])<|fim▁hole|> CogSelectorTask.__init__(self, node_id, "cog_selector",
"MCL-COGs", None, conf[confname])
# taskid does not depend on jobs, so I set it manually
self.cladeid = clade_id
self.seqtype = seqtype
self.targets = target_sp
self.outgroups = out_sp
self.init()
self.size = len(target_sp | out_sp)
self.cog_analysis = None
self.cogs = None
def finish(self):
def sort_cogs_by_size(c1, c2):
'''
sort cogs by descending size. If two cogs are the same size, sort
them keeping first the one with the less represented
species. Otherwise sort by sequence name sp_seqid.'''
r = -1 * cmp(len(c1), len(c2))
if r == 0:
# finds the cog including the less represented species
c1_repr = _min([sp2cogs[_sp] for _sp, _seq in c1])
c2_repr = _min([sp2cogs[_sp] for _sp, _seq in c2])
r = cmp(c1_repr, c2_repr)
if r == 0:
return cmp(sorted(c1), sorted(c2))
else:
return r
else:
return r
def sort_cogs_by_sp_repr(c1, c2):
c1_repr = _min([sp2cogs[_sp] for _sp, _seq in c1])
c2_repr = _min([sp2cogs[_sp] for _sp, _seq in c2])
r = cmp(c1_repr, c2_repr)
if r == 0:
r = -1 * cmp(len(c1), len(c2))
if r == 0:
return cmp(sorted(c1), sorted(c2))
else:
return r
else:
return r
all_species = self.targets | self.outgroups
# strict threshold
#min_species = len(all_species) - int(round(self.missing_factor * len(all_species)))
# Relax threshold for cog selection to ensure sames genes are always included
min_species = len(all_species) - int(round(self.missing_factor * len(GLOBALS["target_species"])))
min_species = max(min_species, (1-self.max_missing_factor) * len(all_species))
smallest_cog, largest_cog = len(all_species), 0
all_singletons = []
sp2cogs = defaultdict(int)
for cognumber, cog in enumerate(open(GLOBALS["cogs_file"])):
sp2seqs = defaultdict(list)
for sp, seqid in [map(strip, seq.split(GLOBALS["spname_delimiter"], 1)) for seq in cog.split("\t")]:
sp2seqs[sp].append(seqid)
one2one_cog = set()
for sp, seqs in sp2seqs.iteritems():
#if len(seqs) != 1:
# print sp, len(seqs)
if sp in all_species and len(seqs) == 1:
sp2cogs[sp] += 1
one2one_cog.add((sp, seqs[0]))
smallest_cog = min(smallest_cog, len(one2one_cog))
largest_cog = max(largest_cog, len(one2one_cog))
all_singletons.append(one2one_cog)
#if len(one2one_cog) >= min_species:
# valid_cogs.append(one2one_cog)
cognumber += 1 # sets the ammount of cogs in file
for sp, ncogs in sorted(sp2cogs.items(), key=lambda x: x[1], reverse=True):
log.log(28, "% 20s found in single copy in % 6d (%0.1f%%) COGs " %(sp, ncogs, 100 * ncogs/float(cognumber)))
valid_cogs = sorted([sing for sing in all_singletons if len(sing) >= min_species],
sort_cogs_by_size)
log.log(28, "Largest cog size: %s. Smallest cog size: %s" %(
largest_cog, smallest_cog))
self.cog_analysis = ""
# save original cog names hitting the hard limit
if len(valid_cogs) > self.cog_hard_limit:
log.warning("Applying hard limit number of COGs: %d out of %d available" %(self.cog_hard_limit, len(valid_cogs)))
self.raw_cogs = valid_cogs[:self.cog_hard_limit]
self.cogs = []
# Translate sequence names into the internal DB names
sp_repr = defaultdict(int)
sizes = []
for co in self.raw_cogs:
sizes.append(len(co))
for sp, seq in co:
sp_repr[sp] += 1
co_names = ["%s%s%s" %(sp, GLOBALS["spname_delimiter"], seq) for sp, seq in co]
encoded_names = db.translate_names(co_names)
if len(encoded_names) != len(co):
print set(co) - set(encoded_names.keys())
raise DataError("Some sequence ids could not be translated")
self.cogs.append(encoded_names.values())
# ERROR! COGs selected are not the prioritary cogs sorted out before!!!
# Sort Cogs according to the md5 hash of its content. Random
# sorting but kept among runs
#map(lambda x: x.sort(), self.cogs)
#self.cogs.sort(lambda x,y: cmp(md5(','.join(x)), md5(','.join(y))))
log.log(28, "Analysis of current COG selection:")
for sp, ncogs in sorted(sp_repr.items(), key=lambda x:x[1], reverse=True):
log.log(28, " % 30s species present in % 6d COGs (%0.1f%%)" %(sp, ncogs, 100 * ncogs/float(len(self.cogs))))
log.log(28, " %d COGs selected with at least %d species out of %d" %(len(self.cogs), min_species, len(all_species)))
log.log(28, " Average COG size %0.1f/%0.1f +- %0.1f" %(_mean(sizes), _median(sizes), _std(sizes)))
# Some consistency checks
missing_sp = (all_species) - set(sp_repr.keys())
if missing_sp:
log.error("%d missing species or not present in single-copy in any cog:\n%s" %\
(len(missing_sp), '\n'.join(missing_sp)))
open('etebuild.valid_species_names.tmp', 'w').write('\n'.join(sp_repr.keys()) +'\n')
log.error("All %d valid species have been dumped into etebuild.valid_species_names.tmp."
" You can use --spfile to restrict the analysis to those species." %len(sp_repr))
raise TaskError('missing or not single-copy species under current cog selection')
CogSelectorTask.store_data(self, self.cogs, self.cog_analysis)
if __name__ == "__main__":
## TEST CODE
import argparse
parser = argparse.ArgumentParser()
# Input data related flags
parser.add_argument("--cogs_file", dest="cogs_file",
required=True,
help="Cogs file")
parser.add_argument("--spname_delimiter", dest="spname_delimiter",
type=str, default = "_",
help="species name delimiter character")
parser.add_argument("--target_sp", dest="target_sp",
type=str, nargs="+",
help="target species sperated by")
parser.add_argument("-m", dest="missing_factor",
type=float, required=True,
help="missing factor for cog selection")
parser.add_argument("--max_missing", dest="max_missing_factor",
type=float, default = 0.3,
help="max missing factor for cog selection")
parser.add_argument("--total_species", dest="total_species",
type=int, required=True,
help="total number of species in the analysis")
args = parser.parse_args()
GLOBALS["cogs_file"] = args.cogs_file
GLOBALS["spname_delimiter"] = args.spname_delimiter
target_sp = args.target_sp
logging.basicConfig(level=logging.DEBUG)
log = logging
GLOBALS["target_species"] = [1] * args.total_species
conf = { "user": {"_species_missing_factor": args.missing_factor,
"_max_species_missing_factor": args.max_missing_factor,
"_max_cogs": 10000
}}
CogSelectorTask.store_data=lambda a,b,c: True
C = CogSelector(set(target_sp), set(), "aa", conf, "user")
db.translate_names = lambda x: dict([(n,n) for n in x])
C.finish()<|fim▁end|> | node_id, clade_id = generate_node_ids(target_sp, out_sp)
# Initialize task |
<|file_name|>MultiSurfaceType.java<|end_file_name|><|fim▁begin|>/*
* Copyright 2013 Gunnar Kappei.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.opengis.gml;
/**<|fim▁hole|> * An XML MultiSurfaceType(@http://www.opengis.net/gml).
*
* This is a complex type.
*/
public interface MultiSurfaceType extends net.opengis.gml.AbstractGeometricAggregateType
{
public static final org.apache.xmlbeans.SchemaType type = (org.apache.xmlbeans.SchemaType)
org.apache.xmlbeans.XmlBeans.typeSystemForClassLoader(MultiSurfaceType.class.getClassLoader(), "schemaorg_apache_xmlbeans.system.s6E28D279B6C224D74769DB8B98AF1665").resolveHandle("multisurfacetypeb44dtype");
/**
* Gets a List of "surfaceMember" elements
*/
java.util.List<net.opengis.gml.SurfacePropertyType> getSurfaceMemberList();
/**
* Gets array of all "surfaceMember" elements
* @deprecated
*/
@Deprecated
net.opengis.gml.SurfacePropertyType[] getSurfaceMemberArray();
/**
* Gets ith "surfaceMember" element
*/
net.opengis.gml.SurfacePropertyType getSurfaceMemberArray(int i);
/**
* Returns number of "surfaceMember" element
*/
int sizeOfSurfaceMemberArray();
/**
* Sets array of all "surfaceMember" element
*/
void setSurfaceMemberArray(net.opengis.gml.SurfacePropertyType[] surfaceMemberArray);
/**
* Sets ith "surfaceMember" element
*/
void setSurfaceMemberArray(int i, net.opengis.gml.SurfacePropertyType surfaceMember);
/**
* Inserts and returns a new empty value (as xml) as the ith "surfaceMember" element
*/
net.opengis.gml.SurfacePropertyType insertNewSurfaceMember(int i);
/**
* Appends and returns a new empty value (as xml) as the last "surfaceMember" element
*/
net.opengis.gml.SurfacePropertyType addNewSurfaceMember();
/**
* Removes the ith "surfaceMember" element
*/
void removeSurfaceMember(int i);
/**
* Gets the "surfaceMembers" element
*/
net.opengis.gml.SurfaceArrayPropertyType getSurfaceMembers();
/**
* True if has "surfaceMembers" element
*/
boolean isSetSurfaceMembers();
/**
* Sets the "surfaceMembers" element
*/
void setSurfaceMembers(net.opengis.gml.SurfaceArrayPropertyType surfaceMembers);
/**
* Appends and returns a new empty "surfaceMembers" element
*/
net.opengis.gml.SurfaceArrayPropertyType addNewSurfaceMembers();
/**
* Unsets the "surfaceMembers" element
*/
void unsetSurfaceMembers();
/**
* A factory class with static methods for creating instances
* of this type.
*/
public static final class Factory
{
public static net.opengis.gml.MultiSurfaceType newInstance() {
return (net.opengis.gml.MultiSurfaceType) org.apache.xmlbeans.XmlBeans.getContextTypeLoader().newInstance( type, null ); }
public static net.opengis.gml.MultiSurfaceType newInstance(org.apache.xmlbeans.XmlOptions options) {
return (net.opengis.gml.MultiSurfaceType) org.apache.xmlbeans.XmlBeans.getContextTypeLoader().newInstance( type, options ); }
/** @param xmlAsString the string value to parse */
public static net.opengis.gml.MultiSurfaceType parse(java.lang.String xmlAsString) throws org.apache.xmlbeans.XmlException {
return (net.opengis.gml.MultiSurfaceType) org.apache.xmlbeans.XmlBeans.getContextTypeLoader().parse( xmlAsString, type, null ); }
public static net.opengis.gml.MultiSurfaceType parse(java.lang.String xmlAsString, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException {
return (net.opengis.gml.MultiSurfaceType) org.apache.xmlbeans.XmlBeans.getContextTypeLoader().parse( xmlAsString, type, options ); }
/** @param file the file from which to load an xml document */
public static net.opengis.gml.MultiSurfaceType parse(java.io.File file) throws org.apache.xmlbeans.XmlException, java.io.IOException {
return (net.opengis.gml.MultiSurfaceType) org.apache.xmlbeans.XmlBeans.getContextTypeLoader().parse( file, type, null ); }
public static net.opengis.gml.MultiSurfaceType parse(java.io.File file, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException {
return (net.opengis.gml.MultiSurfaceType) org.apache.xmlbeans.XmlBeans.getContextTypeLoader().parse( file, type, options ); }
public static net.opengis.gml.MultiSurfaceType parse(java.net.URL u) throws org.apache.xmlbeans.XmlException, java.io.IOException {
return (net.opengis.gml.MultiSurfaceType) org.apache.xmlbeans.XmlBeans.getContextTypeLoader().parse( u, type, null ); }
public static net.opengis.gml.MultiSurfaceType parse(java.net.URL u, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException {
return (net.opengis.gml.MultiSurfaceType) org.apache.xmlbeans.XmlBeans.getContextTypeLoader().parse( u, type, options ); }
public static net.opengis.gml.MultiSurfaceType parse(java.io.InputStream is) throws org.apache.xmlbeans.XmlException, java.io.IOException {
return (net.opengis.gml.MultiSurfaceType) org.apache.xmlbeans.XmlBeans.getContextTypeLoader().parse( is, type, null ); }
public static net.opengis.gml.MultiSurfaceType parse(java.io.InputStream is, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException {
return (net.opengis.gml.MultiSurfaceType) org.apache.xmlbeans.XmlBeans.getContextTypeLoader().parse( is, type, options ); }
public static net.opengis.gml.MultiSurfaceType parse(java.io.Reader r) throws org.apache.xmlbeans.XmlException, java.io.IOException {
return (net.opengis.gml.MultiSurfaceType) org.apache.xmlbeans.XmlBeans.getContextTypeLoader().parse( r, type, null ); }
public static net.opengis.gml.MultiSurfaceType parse(java.io.Reader r, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException {
return (net.opengis.gml.MultiSurfaceType) org.apache.xmlbeans.XmlBeans.getContextTypeLoader().parse( r, type, options ); }
public static net.opengis.gml.MultiSurfaceType parse(javax.xml.stream.XMLStreamReader sr) throws org.apache.xmlbeans.XmlException {
return (net.opengis.gml.MultiSurfaceType) org.apache.xmlbeans.XmlBeans.getContextTypeLoader().parse( sr, type, null ); }
public static net.opengis.gml.MultiSurfaceType parse(javax.xml.stream.XMLStreamReader sr, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException {
return (net.opengis.gml.MultiSurfaceType) org.apache.xmlbeans.XmlBeans.getContextTypeLoader().parse( sr, type, options ); }
public static net.opengis.gml.MultiSurfaceType parse(org.w3c.dom.Node node) throws org.apache.xmlbeans.XmlException {
return (net.opengis.gml.MultiSurfaceType) org.apache.xmlbeans.XmlBeans.getContextTypeLoader().parse( node, type, null ); }
public static net.opengis.gml.MultiSurfaceType parse(org.w3c.dom.Node node, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException {
return (net.opengis.gml.MultiSurfaceType) org.apache.xmlbeans.XmlBeans.getContextTypeLoader().parse( node, type, options ); }
/** @deprecated {@link org.apache.xmlbeans.xml.stream.XMLInputStream} */
@Deprecated
public static net.opengis.gml.MultiSurfaceType parse(org.apache.xmlbeans.xml.stream.XMLInputStream xis) throws org.apache.xmlbeans.XmlException, org.apache.xmlbeans.xml.stream.XMLStreamException {
return (net.opengis.gml.MultiSurfaceType) org.apache.xmlbeans.XmlBeans.getContextTypeLoader().parse( xis, type, null ); }
/** @deprecated {@link org.apache.xmlbeans.xml.stream.XMLInputStream} */
@Deprecated
public static net.opengis.gml.MultiSurfaceType parse(org.apache.xmlbeans.xml.stream.XMLInputStream xis, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, org.apache.xmlbeans.xml.stream.XMLStreamException {
return (net.opengis.gml.MultiSurfaceType) org.apache.xmlbeans.XmlBeans.getContextTypeLoader().parse( xis, type, options ); }
/** @deprecated {@link org.apache.xmlbeans.xml.stream.XMLInputStream} */
@Deprecated
public static org.apache.xmlbeans.xml.stream.XMLInputStream newValidatingXMLInputStream(org.apache.xmlbeans.xml.stream.XMLInputStream xis) throws org.apache.xmlbeans.XmlException, org.apache.xmlbeans.xml.stream.XMLStreamException {
return org.apache.xmlbeans.XmlBeans.getContextTypeLoader().newValidatingXMLInputStream( xis, type, null ); }
/** @deprecated {@link org.apache.xmlbeans.xml.stream.XMLInputStream} */
@Deprecated
public static org.apache.xmlbeans.xml.stream.XMLInputStream newValidatingXMLInputStream(org.apache.xmlbeans.xml.stream.XMLInputStream xis, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, org.apache.xmlbeans.xml.stream.XMLStreamException {
return org.apache.xmlbeans.XmlBeans.getContextTypeLoader().newValidatingXMLInputStream( xis, type, options ); }
private Factory() { } // No instance of this class allowed
}
}<|fim▁end|> | |
<|file_name|>from_bits.rs<|end_file_name|><|fim▁begin|>use itertools::Itertools;
use malachite_base::num::basic::traits::Zero;
use malachite_base::num::conversion::traits::ExactFrom;
use malachite_base::num::logic::traits::BitAccess;
use malachite_nz::natural::Natural;
pub fn from_bits_asc_naive<I: Iterator<Item = bool>>(bits: I) -> Natural {
let mut n = Natural::ZERO;
for i in bits.enumerate().filter_map(|(index, bit)| {
if bit {
Some(u64::exact_from(index))
} else {
None
}
}) {
n.set_bit(i);
}
n
}
pub fn from_bits_desc_naive<I: Iterator<Item = bool>>(bits: I) -> Natural {
let bits = bits.collect_vec();
let mut n = Natural::ZERO;
for i in bits.iter().rev().enumerate().filter_map(|(index, &bit)| {
if bit {
Some(u64::exact_from(index))
} else {
None
}<|fim▁hole|> n.set_bit(i);
}
n
}<|fim▁end|> | }) { |
<|file_name|>app.js<|end_file_name|><|fim▁begin|>(function() {
function config($stateProvider, $locationProvider) {
$locationProvider
.html5Mode({
enabled: true,
requireBase: false
});
$stateProvider
.state('landing', {
url: '/',<|fim▁hole|> url: '/album',
controller: 'AlbumCtrl as album',
templateUrl: '/templates/album.html'
})
.state('collection', {
url: '/collection',
controller: 'CollectionCtrl as collection',
templateUrl: '/templates/collection.html'
});
}
angular
.module('blocJams', ['ui.router'])
.config(config);
})();<|fim▁end|> | controller: 'LandingCtrl as landing',
templateUrl: '/templates/landing.html'
})
.state('album', { |
<|file_name|>mod.rs<|end_file_name|><|fim▁begin|>pub mod clauses;
pub mod elements;
pub mod expressions;
pub mod func;
pub mod keywords;
pub mod math;
pub mod select_statement;
pub mod values;
use nom::branch::alt;
use nom::combinator::map;
use nom::number::complete::double;
use nom::IResult;
use ordered_float::OrderedFloat;
use crate::parsers::value::PqlValue;
pub use elements::{float_number, string_allowed_in_field, whitespace};<|fim▁hole|>pub use expressions::parse_field;
pub use expressions::parse_path_as_expr;
pub fn parse_value(input: &str) -> IResult<&str, PqlValue> {
alt((
map(elements::string, |s| PqlValue::Str(s.to_string())),
map(double, |f| PqlValue::Float(OrderedFloat(f as f64))),
))(input)
}<|fim▁end|> | pub use expressions::parse_expr; |
<|file_name|>get_outgoing.rs<|end_file_name|><|fim▁begin|>use chrono::{UTC, Date, Datelike};
use std::str::FromStr; // Use of #from_str.
use api::client::{TellerClient, ApiServiceResult, Transaction};
use api::client::parse_utc_date_from_transaction;
use api::inform::Money;
pub trait GetOutgoing {
fn get_outgoing(&self, account_id: &str, for_month: &Date<UTC>) -> ApiServiceResult<Money>;
}
impl<'a> GetOutgoing for TellerClient<'a> {
fn get_outgoing(&self, account_id: &str, for_month: &Date<UTC>) -> ApiServiceResult<Money> {
let account = try!(self.get_account(&account_id));
let currency = account.currency;
let from = for_month.with_day(1).unwrap();
let to = if from.month() < 12 {
from.with_month(from.month() + 1).unwrap()
} else {
from.with_year(from.year() + 1).unwrap().with_month(1).unwrap()
};
let transactions: Vec<Transaction> = self.raw_transactions(&account_id, 250, 1)
.unwrap_or(vec![])
.into_iter()
.filter(|t| {
let transaction_date =
parse_utc_date_from_transaction(&t);
from <= transaction_date && transaction_date <= to
})
.collect();
let from_float_string_to_cent_integer = |t: &Transaction| {
(f64::from_str(&t.amount).unwrap() * 100f64).round() as i64
};
let from_cent_integer_to_float_string = |amount: i64| format!("{:.2}", amount as f64 / 100f64);
let outgoing = transactions.iter()
.map(from_float_string_to_cent_integer)
.filter(|ci| *ci < 0)<|fim▁hole|>
Ok(Money::new(from_cent_integer_to_float_string(outgoing.abs()), currency))
}
}
#[cfg(test)]
mod tests {
use api::client::{TellerClient, generate_utc_date_from_date_str};
use super::GetOutgoing;
use hyper;
mock_connector_in_order!(GetAccountFollowedByGetTransactions {
include_str!("../mocks/get-account.http")
include_str!("../mocks/get-transactions.http")
});
#[test]
fn can_get_outgoing() {
let c = hyper::client::Client::with_connector(GetAccountFollowedByGetTransactions::default());
let teller = TellerClient::new_with_hyper_client("fake-auth-token", c);
let current_month = generate_utc_date_from_date_str("2016-01-01");
let money = teller.get_outgoing("123", ¤t_month).unwrap();
assert_eq!("55.00 GBP", money.get_balance_for_display(&false));
}
}<|fim▁end|> | .fold(0i64, |sum, v| sum + v); |
<|file_name|>current.py<|end_file_name|><|fim▁begin|>"""This *was* the parser for the current HTML format on parl.gc.ca.
But now we have XML. See parl_document.py.
This module is organized like so:
__init__.py - utility functions, simple parse interface
common.py - infrastructure used in the parsers, i.e. regexes<|fim▁hole|>
"""
from parliament.imports.hans_old.common import *
import logging
logger = logging.getLogger(__name__)
class HansardParser2009(HansardParser):
def __init__(self, hansard, html):
for regex in STARTUP_RE_2009:
html = re.sub(regex[0], regex[1], html)
super(HansardParser2009, self).__init__(hansard, html)
for x in self.soup.findAll('a', 'deleteMe'):
x.findParent('div').extract()
def process_related_link(self, tag, string, current_politician=None):
#print "PROCESSING RELATED for %s" % string
resid = re.search(r'ResourceID=(\d+)', tag['href'])
restype = re.search(r'ResourceType=(Document|Affiliation)', tag['href'])
if not resid and restype:
return string
resid, restype = int(resid.group(1)), restype.group(1)
if restype == 'Document':
try:
bill = Bill.objects.get_by_legisinfo_id(resid)
except Bill.DoesNotExist:
match = re.search(r'\b[CS]\-\d+[A-E]?\b', string)
if not match:
logger.error("Invalid bill link %s" % string)
return string
bill = Bill.objects.create_temporary_bill(legisinfo_id=resid,
number=match.group(0), session=self.hansard.session)
except Exception, e:
print "Related bill search failed for callback %s" % resid
print repr(e)
return string
return u'<bill id="%d" name="%s">%s</bill>' % (bill.id, escape(bill.name), string)
elif restype == 'Affiliation':
try:
pol = Politician.objects.getByParlID(resid)
except Politician.DoesNotExist:
print "Related politician search failed for callback %s" % resid
if getattr(settings, 'PARLIAMENT_LABEL_FAILED_CALLBACK', False):
# FIXME migrate away from internalxref?
InternalXref.objects.get_or_create(schema='pol_parlid', int_value=resid, target_id=-1)
return string
if pol == current_politician:
return string # When someone mentions her riding, don't link back to her
return u'<pol id="%d" name="%s">%s</pol>' % (pol.id, escape(pol.name), string)
def get_text(self, cursor):
text = u''
for string in cursor.findAll(text=parsetools.r_hasText):
if string.parent.name == 'a' and string.parent['class'] == 'WebOption':
text += self.process_related_link(string.parent, string, self.t['politician'])
else:
text += unicode(string)
return text
def parse(self):
super(HansardParser2009, self).parse()
# Initialize variables
t = ParseTracker()
self.t = t
member_refs = {}
# Get the date
c = self.soup.find(text='OFFICIAL REPORT (HANSARD)').findNext('h2')
self.date = datetime.datetime.strptime(c.string.strip(), "%A, %B %d, %Y").date()
self.hansard.date = self.date
self.hansard.save()
c = c.findNext(text=r_housemet)
match = re.search(r_housemet, c.string)
t['timestamp'] = self.houseTime(match.group(1), match.group(2))
t.setNext('timestamp', t['timestamp'])
# Move the pointer to the start
c = c.next
# And start the big loop
while c is not None:
# It's a string
if not hasattr(c, 'name'):
pass
# Heading
elif c.name == 'h2':
c = c.next
if not parsetools.isString(c): raise ParseException("Expecting string right after h2")
t.setNext('heading', parsetools.titleIfNecessary(parsetools.tameWhitespace(c.string.strip())))
# Topic
elif c.name == 'h3':
top = c.find(text=r_letter)
#if not parsetools.isString(c):
# check if it's an empty header
# if c.parent.find(text=r_letter):
# raise ParseException("Expecting string right after h3")
if top is not None:
c = top
t['topic_set'] = True
t.setNext('topic', parsetools.titleIfNecessary(parsetools.tameWhitespace(c.string.strip())))
elif c.name == 'h4':
if c.string == 'APPENDIX':
self.saveStatement(t)
print "Appendix reached -- we're done!"
break
# Timestamp
elif c.name == 'a' and c.has_key('name') and c['name'].startswith('T'):
match = re.search(r'^T(\d\d)(\d\d)$', c['name'])
if match:
t.setNext('timestamp', parsetools.time_to_datetime(
hour=int(match.group(1)),
minute=int(match.group(2)),
date=self.date))
else:
raise ParseException("Couldn't match time %s" % c.attrs['name'])
elif c.name == 'b' and c.string:
# Something to do with written answers
match = r_honorific.search(c.string)
if match:
# It's a politician asking or answering a question
# We don't get a proper link here, so this has to be a name match
polname = re.sub(r'\(.+\)', '', match.group(2)).strip()
self.saveStatement(t)
t['member_title'] = c.string.strip()
t['written_question'] = True
try:
pol = Politician.objects.get_by_name(polname, session=self.hansard.session)
t['politician'] = pol
t['member'] = ElectedMember.objects.get_by_pol(politician=pol, date=self.date)
except Politician.DoesNotExist:
print "WARNING: No name match for %s" % polname
except Politician.MultipleObjectsReturned:
print "WARNING: Multiple pols for %s" % polname
else:
if not c.string.startswith('Question'):
print "WARNING: Unexplained boldness: %s" % c.string
# div -- the biggie
elif c.name == 'div':
origdiv = c
if c.find('b'):
# We think it's a new speaker
# Save the current buffer
self.saveStatement(t)
c = c.find('b')
if c.find('a'):
# There's a link...
c = c.find('a')
match = re.search(r'ResourceType=Affiliation&ResourceID=(\d+)', c['href'])
if match and c.find(text=r_letter):
parlwebid = int(match.group(1))
# We have the parl ID. First, see if we already know this ID.
pol = Politician.objects.getByParlID(parlwebid, lookOnline=False)
if pol is None:
# We don't. Try to do a quick name match first (if flags say so)
if not GET_PARLID_ONLINE:
who = c.next.string
match = re.search(r_honorific, who)
if match:
polname = re.sub(r'\(.+\)', '', match.group(2)).strip()
try:
#print "Looking for %s..." % polname,
pol = Politician.objects.get_by_name(polname, session=self.hansard.session)
#print "found."
except Politician.DoesNotExist:
pass
except Politician.MultipleObjectsReturned:
pass
if pol is None:
# Still no match. Go online...
try:
pol = Politician.objects.getByParlID(parlwebid, session=self.hansard.session)
except Politician.DoesNotExist:
print "WARNING: Couldn't find politician for ID %d" % parlwebid
if pol is not None:
t['member'] = ElectedMember.objects.get_by_pol(politician=pol, date=self.date)
t['politician'] = pol
c = c.next
if not parsetools.isString(c): raise Exception("Expecting string in b for member name")
t['member_title'] = c.strip()
#print c
if t['member_title'].endswith(':'): # Remove colon in e.g. Some hon. members:
t['member_title'] = t['member_title'][:-1]
# Sometimes we don't get a link for short statements -- see if we can identify by backreference
if t['member']:
member_refs[t['member_title']] = t['member']
# Also save a backref w/o position/riding
member_refs[re.sub(r'\s*\(.+\)\s*', '', t['member_title'])] = t['member']
elif t['member_title'] in member_refs:
t['member'] = member_refs[t['member_title']]
t['politician'] = t['member'].politician
c.findParent('b').extract() # We've got the title, now get the rest of the paragraph
c = origdiv
t.addText(self.get_text(c))
else:
# There should be text in here
if c.find('div'):
if c.find('div', 'Footer'):
# We're done!
self.saveStatement(t)
print "Footer div reached -- done!"
break
raise Exception("I wasn't expecting another div in here")
txt = self.get_text(c).strip()
if r_proceedings.search(txt):
self.saveStatement(t)
self.saveProceedingsStatement(txt, t)
else:
t.addText(txt, blockquote=bool(c.find('small')))
else:
#print c.name
if c.name == 'b':
print "B: ",
print c
#if c.name == 'p':
# print "P: ",
# print c
c = c.next
return self.statements<|fim▁end|> | current.py - parser for the Hansard format used from 2006 to the present
old.py - (fairly crufty) parser for the format used from 1994 to 2006 |
<|file_name|>problem-0013.rs<|end_file_name|><|fim▁begin|>/// Problem 13
/// Work out the first ten digits of the sum of the following one-hundred 50-digit numbers.
///
/// 37107287533902102798797998220837590246510135740250
/// ...
fn main() {
let raw: String = "\
37107287533902102798797998220837590246510135740250\n\
46376937677490009712648124896970078050417018260538\n\
74324986199524741059474233309513058123726617309629\n\
91942213363574161572522430563301811072406154908250\n\
23067588207539346171171980310421047513778063246676\n\
89261670696623633820136378418383684178734361726757\n\
28112879812849979408065481931592621691275889832738\n\
44274228917432520321923589422876796487670272189318\n\
47451445736001306439091167216856844588711603153276\n\
70386486105843025439939619828917593665686757934951\n\
62176457141856560629502157223196586755079324193331\n\
64906352462741904929101432445813822663347944758178\n\
92575867718337217661963751590579239728245598838407\n\
58203565325359399008402633568948830189458628227828\n\
80181199384826282014278194139940567587151170094390\n\
35398664372827112653829987240784473053190104293586\n\
86515506006295864861532075273371959191420517255829\n\
71693888707715466499115593487603532921714970056938\n\
54370070576826684624621495650076471787294438377604\n\
53282654108756828443191190634694037855217779295145\n\
36123272525000296071075082563815656710885258350721\n\
45876576172410976447339110607218265236877223636045\n\
17423706905851860660448207621209813287860733969412\n\
81142660418086830619328460811191061556940512689692\n\
51934325451728388641918047049293215058642563049483\n\
62467221648435076201727918039944693004732956340691\n\
15732444386908125794514089057706229429197107928209\n\
55037687525678773091862540744969844508330393682126\n\
18336384825330154686196124348767681297534375946515\n\
80386287592878490201521685554828717201219257766954\n\
78182833757993103614740356856449095527097864797581\n\
16726320100436897842553539920931837441497806860984\n\
48403098129077791799088218795327364475675590848030\n\
87086987551392711854517078544161852424320693150332\n\
59959406895756536782107074926966537676326235447210\n\
69793950679652694742597709739166693763042633987085\n\
41052684708299085211399427365734116182760315001271\n\
65378607361501080857009149939512557028198746004375\n\
35829035317434717326932123578154982629742552737307\n\
94953759765105305946966067683156574377167401875275\n\
88902802571733229619176668713819931811048770190271\n\
25267680276078003013678680992525463401061632866526\n\
36270218540497705585629946580636237993140746255962\n\
24074486908231174977792365466257246923322810917141\n\
91430288197103288597806669760892938638285025333403\n\
34413065578016127815921815005561868836468420090470\n\
23053081172816430487623791969842487255036638784583\n\
11487696932154902810424020138335124462181441773470\n\
63783299490636259666498587618221225225512486764533\n\
67720186971698544312419572409913959008952310058822\n\
95548255300263520781532296796249481641953868218774\n\
76085327132285723110424803456124867697064507995236\n\
37774242535411291684276865538926205024910326572967\n\
23701913275725675285653248258265463092207058596522\n\
29798860272258331913126375147341994889534765745501\n\
18495701454879288984856827726077713721403798879715\n\
38298203783031473527721580348144513491373226651381\n\
34829543829199918180278916522431027392251122869539\n\
40957953066405232632538044100059654939159879593635\n\
29746152185502371307642255121183693803580388584903\n\
41698116222072977186158236678424689157993532961922\n\
62467957194401269043877107275048102390895523597457\n\
23189706772547915061505504953922979530901129967519\n\
86188088225875314529584099251203829009407770775672\n\
11306739708304724483816533873502340845647058077308\n\
82959174767140363198008187129011875491310547126581\n\
97623331044818386269515456334926366572897563400500\n\
42846280183517070527831839425882145521227251250327\n\
55121603546981200581762165212827652751691296897789\n\
32238195734329339946437501907836945765883352399886\n\
75506164965184775180738168837861091527357929701337\n\
62177842752192623401942399639168044983993173312731\n\
32924185707147349566916674687634660915035914677504\n\
99518671430235219628894890102423325116913619626622\n\
73267460800591547471830798392868535206946944540724\n\
76841822524674417161514036427982273348055556214818\n\
97142617910342598647204516893989422179826088076852\n\
87783646182799346313767754307809363333018982642090\n\
10848802521674670883215120185883543223812876952786\n\
71329612474782464538636993009049310363619763878039\n\
62184073572399794223406235393808339651327408011116\n\
66627891981488087797941876876144230030984490851411\n\
60661826293682836764744779239180335110989069790714\n\
85786944089552990653640447425576083659976645795096\n\
66024396409905389607120198219976047599490197230297\n\
64913982680032973156037120041377903785566085089252\n\
16730939319872750275468906903707539413042652315011\n\<|fim▁hole|> 94809377245048795150954100921645863754710598436791\n\
78639167021187492431995700641917969777599028300699\n\
15368713711936614952811305876380278410754449733078\n\
40789923115535562561142322423255033685442488917353\n\
44889911501440648020369068063960672322193204149535\n\
41503128880339536053299340368006977710650566631954\n\
81234880673210146739058568557934581403627822703280\n\
82616570773948327592232845941706525094512325230608\n\
22918802058777319719839450180888072429661980811197\n\
77158542502016545090413245809786882778948721859617\n\
72107838435069186155435662884062257473692284509516\n\
20849603980134001723930671666823555245252804609722\n\
53503534226472524250874054075591789781264330331690".to_string();
let first_digits: usize = 10;
let mut sum: Vec<u8> = Vec::new();
let mut nums: Vec<Vec<u8>> = Vec::new();
for line in raw.split('\n') {
// Push reversed vector of u8 digits
nums.push(line.chars().map(|x| x.to_digit(10).unwrap() as u8).rev().collect())
}
let mut rem:u16 = 0;
for i in 0..nums[0].len() { //first_digits {
let mut col_sum:u16 = rem;
for j in 0..nums.len() {
col_sum += nums[j][i] as u16;
}
sum.push((col_sum % 10u16) as u8);
// Do remainder and carry with integer division
rem = col_sum / 10;
}
// Drain remainder digits
while rem > 0 {
sum.push((rem % 10) as u8);
rem /= 10;
}
let mut i: usize = 0;
print!("Answer: ");
for s in sum.iter().rev() {
i += 1;
print!("{}", s);
if i >= first_digits {
break
}
}
println!("");
}<|fim▁end|> | |
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python
"""GRR restful API rendering plugins."""
# pylint: disable=unused-import<|fim▁hole|>from grr.gui.api_plugins import docs
from grr.gui.api_plugins import hunt
from grr.gui.api_plugins import reflection
from grr.gui.api_plugins import stats<|fim▁end|> | from grr.gui.api_plugins import aff4
from grr.gui.api_plugins import artifact
from grr.gui.api_plugins import config |
<|file_name|>mod.rs<|end_file_name|><|fim▁begin|>//! Collision detection algorithms<|fim▁hole|><|fim▁end|> |
pub mod minkowski;
pub mod broad_phase; |
<|file_name|>moment.ts<|end_file_name|><|fim▁begin|>import 'moment';<|fim▁hole|> if (!date) return undefined;
return moment(date).format(format);
}
}<|fim▁end|> |
export class MomentValueConverter {
toView(date: Date, format: string) {
if (!format) format = 'LLL'; |
<|file_name|>twitter.py<|end_file_name|><|fim▁begin|>import urllib
from askbot.deps.django_authopenid.util import OAuthConnection
class Twitter(OAuthConnection):<|fim▁hole|> super(Twitter, self).__init__('twitter')
self.tweet_url = 'https://api.twitter.com/1.1/statuses/update.json'
def tweet(self, text, access_token=None):
client = self.get_client(access_token)
body = urllib.urlencode({'status': text})
return self.send_request(client, self.tweet_url, 'POST', body=body)<|fim▁end|> | def __init__(self): |
<|file_name|>sigecoin_vi.ts<|end_file_name|><|fim▁begin|><TS language="vi" version="2.1">
<context>
<name>AddressBookPage</name>
<message>
<source>Create a new address</source>
<translation>Tạo một địa chỉ mới</translation>
</message>
<message>
<source>&New</source>
<translation>Tạo mới</translation>
</message>
<message>
<source>Copy the currently selected address to the system clipboard</source>
<translation>Sao chép các địa chỉ đã được chọn vào bộ nhớ tạm thời của hệ thống</translation>
</message>
<message>
<source>&Copy</source>
<translation>Sao chép</translation>
</message>
<message>
<source>&Delete</source>
<translation>&Xóa</translation>
</message>
</context>
<context>
<name>AddressTableModel</name>
</context>
<context>
<name>AskPassphraseDialog</name>
</context>
<context>
<name>BanTableModel</name>
</context>
<context>
<name>SigecoinGUI</name>
</context>
<context>
<name>CoinControlDialog</name>
<message>
<source>Amount:</source>
<translation>Số lượng:</translation>
</message>
<message>
<source>Amount</source>
<translation>Số lượng</translation>
</message>
</context>
<context>
<name>EditAddressDialog</name>
<message>
<source>&Label</source>
<translation>Nhãn dữ liệu</translation>
</message>
<message>
<source>&Address</source>
<translation>Địa chỉ</translation>
</message>
</context>
<context>
<name>FreespaceChecker</name>
</context>
<context>
<name>HelpMessageDialog</name>
</context>
<context>
<name>Intro</name>
</context>
<context>
<name>ModalOverlay</name>
</context>
<context>
<name>OpenURIDialog</name>
</context>
<context>
<name>OptionsDialog</name>
</context>
<context>
<name>OverviewPage</name>
</context>
<context>
<name>PaymentServer</name>
</context>
<context>
<name>PeerTableModel</name>
</context>
<context>
<name>QObject</name>
<message>
<source>Amount</source>
<translation>Số lượng</translation>
</message>
</context>
<context>
<name>QObject::QObject</name>
</context>
<context>
<name>QRImageWidget</name>
</context>
<context>
<name>RPCConsole</name>
</context><|fim▁hole|><context>
<name>ReceiveRequestDialog</name>
<message>
<source>Copy &Address</source>
<translation>Sao chép địa chỉ</translation>
</message>
</context>
<context>
<name>RecentRequestsTableModel</name>
</context>
<context>
<name>SendCoinsDialog</name>
<message>
<source>Amount:</source>
<translation>Số lượng:</translation>
</message>
</context>
<context>
<name>SendCoinsEntry</name>
</context>
<context>
<name>SendConfirmationDialog</name>
</context>
<context>
<name>ShutdownWindow</name>
</context>
<context>
<name>SignVerifyMessageDialog</name>
</context>
<context>
<name>SplashScreen</name>
</context>
<context>
<name>TrafficGraphWidget</name>
</context>
<context>
<name>TransactionDesc</name>
</context>
<context>
<name>TransactionDescDialog</name>
</context>
<context>
<name>TransactionTableModel</name>
</context>
<context>
<name>TransactionView</name>
</context>
<context>
<name>UnitDisplayStatusBarControl</name>
</context>
<context>
<name>WalletFrame</name>
</context>
<context>
<name>WalletModel</name>
</context>
<context>
<name>WalletView</name>
</context>
<context>
<name>sigecoin-engine</name>
</context>
</TS><|fim▁end|> | <context>
<name>ReceiveCoinsDialog</name>
</context> |
<|file_name|>testmarkint.cpp<|end_file_name|><|fim▁begin|>/*
* Copyright (C) 2019 Ondrej Starek
*
* This file is part of OTest2.
*
* OTest2 is free software: you can redistribute it and/or modify it under
* the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License,
* or (at your option) any later version.
*
* OTest2 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 Lesser General Public
* License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with OTest2. If not, see <http://www.gnu.org/licenses/>.
*/
#include <testmarkint.h>
#include <assert.h>
#include <iostream>
#include <testmarkhash.h>
#include <testmarkin.h>
#include <testmarkout.h>
namespace OTest2 {
namespace {
const char SERIALIZE_TYPE_MARK[] = "ot2:int";
} /* -- namespace */
TestMarkInt::TestMarkInt(
int64_t value_) :
value(value_) {<|fim▁hole|>}
TestMarkInt::TestMarkInt(
const CtorMark*) :
value(0) {
}
TestMarkInt::~TestMarkInt() {
}
const char* TestMarkInt::typeMark() {
return SERIALIZE_TYPE_MARK;
}
TestMarkHashCode TestMarkInt::doGetHashCode() const noexcept {
return TestMarkHash::hashBasicType(SERIALIZE_TYPE_MARK, value);
}
bool TestMarkInt::doIsEqual(
const TestMark& other_,
long double precision_) const {
return value == static_cast<const TestMarkInt*>(&other_)->value;
}
bool TestMarkInt::doIsEqualValue(
const TestMark& other_,
long double precision_) const {
return doIsEqual(other_, precision_);
}
void TestMarkInt::doDiffArray(
int level_,
std::vector<LinearizedRecord>& array_) const
{
/* -- there are no children */
}
void TestMarkInt::doLinearizedMark(
int level_,
const std::string& label_,
std::vector<LinearizedRecord>& array_) const {
array_.push_back({level_, this, label_});
}
void TestMarkInt::doPrintOpen(
std::ostream& os_,
const std::string& prefix_) const {
os_ << prefix_ << value << '\n';
}
void TestMarkInt::doPrintClose(
std::ostream& os_,
const std::string& prefix_) const {
/* -- nothing to do */
}
void TestMarkInt::doSerializeMark(
TestMarkOut& serializer_) const {
serializer_.writeTypeMark(SERIALIZE_TYPE_MARK);
serializer_.writeInt(value);
}
void TestMarkInt::doDeserializeMark(
TestMarkFactory& factory_,
TestMarkIn& deserializer_) {
value = deserializer_.readInt();
}
} /* namespace OTest2 */<|fim▁end|> | |
<|file_name|>SendMessageUtil.java<|end_file_name|><|fim▁begin|>package com.wjyup.coolq.util;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;<|fim▁hole|>import com.google.common.hash.HashCode;
import com.google.common.hash.HashFunction;
import com.google.common.hash.Hashing;
import com.google.gson.JsonObject;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.util.DigestUtils;
import java.nio.charset.StandardCharsets;
/**
* 发送消息工具类
* @author WJY
*/
public class SendMessageUtil {
private static Logger log = LogManager.getLogger(SendMessageUtil.class);
/**
* 发送json数据并获取返回值
* @param message 消息
* @return 发送消息的结果
*/
public static String sendSocketData(String message){
try {
ConfigCache configCache = SpringContext.getConfigCache();
//判断发送消息方式
if(StaticConf.MSG_SEND_TYPE_HTTP.equalsIgnoreCase(configCache.getMSG_SEND_TYPE())){// http
String url = String.format("http://%s:%s", configCache.getHTTP_HOST(), configCache.getHTTP_PORT());
if(configCache.isUSE_TOKEN()){// 使用token
long authTime = System.currentTimeMillis() / 1000;
String key = configCache.getKEY()+":"+authTime;
String authToken = DigestUtils.md5DigestAsHex(key.getBytes(StandardCharsets.UTF_8));
JSONObject jsonObject = JSON.parseObject(message);
jsonObject.put("authTime", authTime);
jsonObject.put("authToken", authToken);
message = jsonObject.toJSONString();
}
log.debug("发送的json文本:"+message);
try{
String result = WebUtil.post(url, message);
log.debug("返回结果:" + result);
return result;
}catch (Exception e){
log.error(e.getMessage(),e);
}
}
} catch (Exception e) {
log.error(e.getMessage(), e);
}
return null;
}
}<|fim▁end|> | |
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|>from .polarpoint import PolarPoint
__all__ = [
'PolarPoint',<|fim▁hole|>]<|fim▁end|> | |
<|file_name|>testcase_lmd_loader.js<|end_file_name|><|fim▁begin|>(function (require) {
var test = require('test'),
asyncTest = require('asyncTest'),
start = require('start'),
module = require('module'),
ok = require('ok'),
expect = require('expect'),
$ = require('$'),
document = require('document'),
raises = require('raises'),
rnd = '?' + Math.random(),
ENV_NAME = require('worker_some_global_var') ? 'Worker' : require('node_some_global_var') ? 'Node' : 'DOM';
function getComputedStyle(element, rule) {
if(document.defaultView && document.defaultView.getComputedStyle){
return document.defaultView.getComputedStyle(element, "").getPropertyValue(rule);
}
rule = rule.replace(/\-(\w)/g, function (strMatch, p1){
return p1.toUpperCase();
});
return element.currentStyle[rule];
}
module('LMD loader @ ' + ENV_NAME);
asyncTest("require.js()", function () {
expect(6);
require.js('./modules/loader/non_lmd_module.js' + rnd, function (script_tag) {
ok(typeof script_tag === "object" &&
script_tag.nodeName.toUpperCase() === "SCRIPT", "should return script tag on success");
ok(require('some_function')() === true, "we can grab content of the loaded script");
ok(require('./modules/loader/non_lmd_module.js' + rnd) === script_tag, "should cache script tag on success");
// some external
require.js('http://yandex.ru/jquery.js' + rnd, function (script_tag) {
ok(typeof script_tag === "undefined", "should return undefined on error in 3 seconds");
ok(typeof require('http://yandex.ru/jquery.js' + rnd) === "undefined", "should not cache errorous modules");
require.js('module_as_string', function (module_as_string) {
require.async('module_as_string', function (module_as_string_expected) {
ok(module_as_string === module_as_string_expected, 'require.js() acts like require.async() if in-package/declared module passed');
start();
});
});
});
});
});
asyncTest("require.js() JSON callback and chain calls", function () {
expect(2);
var id = require('setTimeout')(function () {
ok(false, 'JSONP call fails');
start();
}, 3000);
require('window').someJsonHandler = function (result) {
ok(result.ok, 'JSON called');
require('window').someJsonHandler = null;
require('clearTimeout')(id);
start();
};
var requireReturned = require.js('./modules/loader/non_lmd_module.jsonp.js' + rnd);
ok(typeof requireReturned === "function", "require.js() must return require");
});
asyncTest("require.js() race calls", function () {
expect(1);
var result;
var check_result = function (scriptTag) {
<|fim▁hole|> } else {
ok(result === scriptTag, "Must perform one call. Results must be the same");
start();
}
};
require.js('./modules/loader_race/non_lmd_module.js' + rnd, check_result);
require.js('./modules/loader_race/non_lmd_module.js' + rnd, check_result);
});
asyncTest("require.js() shortcut", function () {
expect(5);
require.js('sk_js_js', function (script_tag) {
ok(typeof script_tag === "object" &&
script_tag.nodeName.toUpperCase() === "SCRIPT", "should return script tag on success");
ok(require('sk_js_js') === script_tag, "require should return the same result");
require.js('sk_js_js', function (script_tag2) {
ok(script_tag2 === script_tag, 'should load once');
ok(require('sk_js_js') === require('/modules/shortcuts/js.js'), "should be defined using path-to-module");
ok(typeof require('shortcuts_js') === "function", 'Should create a global function shortcuts_js as in module function');
start();
})
});
});
// -- CSS
asyncTest("require.css()", function () {
expect(4);
require.css('./modules/loader/some_css.css' + rnd, function (link_tag) {
ok(typeof link_tag === "object" &&
link_tag.nodeName.toUpperCase() === "LINK", "should return link tag on success");
ok(getComputedStyle(document.getElementById('qunit-fixture'), 'visibility') === "hidden", "css should be applied");
ok(require('./modules/loader/some_css.css' + rnd) === link_tag, "should cache link tag on success");
require.css('module_as_string', function (module_as_string) {
require.async('module_as_string', function (module_as_string_expected) {
ok(module_as_string === module_as_string_expected, 'require.css() acts like require.async() if in-package/declared module passed');
start();
});
});
});
});
asyncTest("require.css() CSS loader without callback", function () {
expect(1);
var requireReturned = require
.css('./modules/loader/some_css_callbackless.css' + rnd)
.css('./modules/loader/some_css_callbackless.css' + rnd + 1);
ok(typeof requireReturned === "function", "require.css() must return require");
start();
});
asyncTest("require.css() race calls", function () {
expect(1);
var result;
var check_result = function (linkTag) {
if (typeof result === "undefined") {
result = linkTag;
} else {
ok(result === linkTag, "Must perform one call. Results must be the same");
start();
}
};
require.css('./modules/loader_race/some_css.css' + rnd, check_result);
require.css('./modules/loader_race/some_css.css' + rnd, check_result);
});
asyncTest("require.css() shortcut", function () {
expect(4);
require.css('sk_css_css', function (link_tag) {
ok(typeof link_tag === "object" &&
link_tag.nodeName.toUpperCase() === "LINK", "should return link tag on success");
ok(require('sk_css_css') === link_tag, "require should return the same result");
require.css('sk_css_css', function (link_tag2) {
ok(link_tag2 === link_tag, 'should load once');
ok(require('sk_css_css') === require('/modules/shortcuts/css.css'), "should be defined using path-to-module");
start();
})
});
});
asyncTest("require.css() cross origin", function () {
expect(2);
require.css('sk_css_xdomain', function (link_tag) {
ok(typeof link_tag === "object" &&
link_tag.nodeName.toUpperCase() === "LINK", "should return link tag on success");
ok(getComputedStyle(document.body, 'min-width') === "960px", "css should be applied");
start();
});
});
// -- image
asyncTest("require.image()", function () {
expect(5);
require.image('./modules/loader/image.gif' + rnd, function (img_tag) {
ok(typeof img_tag === "object" &&
img_tag.nodeName.toUpperCase() === "IMG", "should return img tag on success");
ok(require('./modules/loader/image.gif' + rnd) === img_tag, "should cache img tag on success");
require.image('./modules/loader/image_404.gif' + rnd, function (img_tag) {
ok(typeof img_tag === "undefined", "should return undefined on error in 3 seconds");
ok(typeof require('./modules/loader/image_404.gif' + rnd) === "undefined", "should not cache errorous modules");
require.image('module_as_string', function (module_as_string) {
require.async('module_as_string', function (module_as_string_expected) {
ok(module_as_string === module_as_string_expected, 'require.image() acts like require.async() if in-package/declared module passed');
start();
});
});
});
});
});
asyncTest("require.image() image loader without callback", function () {
expect(1);
var requireReturned = require
.image('./modules/loader/image_callbackless.gif' + rnd)
.image('./modules/loader/image_callbackless.gif' + rnd + 1);
ok(typeof requireReturned === "function", "require.image() must return require");
start();
});
asyncTest("require.image() race calls", function () {
expect(1);
var result;
var check_result = function (linkTag) {
if (typeof result === "undefined") {
result = linkTag;
} else {
ok(result === linkTag, "Must perform one call. Results must be the same");
start();
}
};
require.image('./modules/loader_race/image.gif' + rnd, check_result);
require.image('./modules/loader_race/image.gif' + rnd, check_result);
});
asyncTest("require.image() shortcut", function () {
expect(4);
require.image('sk_image_image', function (img_tag) {
ok(typeof img_tag === "object" &&
img_tag.nodeName.toUpperCase() === "IMG", "should return img tag on success");
ok(require('sk_image_image') === img_tag, "require should return the same result");
require.image('sk_image_image', function (img_tag2) {
ok(img_tag2 === img_tag, 'should load once');
ok(require('sk_image_image') === require('/modules/shortcuts/image.gif'), "should be defined using path-to-module");
start();
})
});
});
})<|fim▁end|> | if (typeof result === "undefined") {
result = scriptTag;
|
<|file_name|>entry.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
# Copyright (C) 2013-2014 Avencall
#
# 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/>
common = {}
execfile_('common.py', common)
MODELS = [
u'7906G',
u'7911G',<|fim▁hole|> u'7961G',
u'7962G',
]
class CiscoSccpPlugin(common['BaseCiscoSccpPlugin']):
IS_PLUGIN = True
pg_associator = common['BaseCiscoPgAssociator'](MODELS)<|fim▁end|> | u'7931G',
u'7941G',
u'7942G', |
<|file_name|>lithos_switch.rs<|end_file_name|><|fim▁begin|>extern crate libc;
extern crate nix;
extern crate env_logger;
extern crate regex;
extern crate argparse;
extern crate quire;
#[macro_use] extern crate log;
extern crate lithos;
use std::env;
use std::io::{stderr, Read, Write};
use std::process::exit;
use std::path::{Path, PathBuf};
use std::str::FromStr;
use std::fs::{File};
use std::fs::{copy, rename};
use std::process::{Command, Stdio};
use argparse::{ArgumentParser, Parse, StoreTrue, Print};
use quire::{parse_config, Options};
use nix::sys::signal::{SIGQUIT, kill};
use nix::unistd::Pid;
use lithos::master_config::MasterConfig;
use lithos::sandbox_config::SandboxConfig;
fn switch_config(master_cfg: &Path, sandbox_name: String, config_file: &Path)
-> Result<(), String>
{
match Command::new(env::current_exe().unwrap()
.parent().unwrap().join("lithos_check"))
.stdin(Stdio::inherit())
.stdout(Stdio::inherit())
.stderr(Stdio::inherit())
.arg("--config")
.arg(&master_cfg)
.arg("--sandbox")
.arg(&sandbox_name)
.arg("--alternate-config")
.arg(&config_file)
.output()
{
Ok(ref po) if po.status.code() == Some(0) => { }
Ok(ref po) => {
return Err(format!(
"Configuration check failed with exit status: {}",
po.status));
}
Err(e) => {
return Err(format!("Can't check configuration: {}", e));
}
}
info!("Checked. Proceeding");
let master: MasterConfig = match parse_config(&master_cfg,
&MasterConfig::validator(), &Options::default())
{
Ok(cfg) => cfg,
Err(e) => {
return Err(format!("Can't parse master config: {}", e));
}
};
let sandbox_fn = master_cfg.parent().unwrap()
.join(&master.sandboxes_dir)
.join(&(sandbox_name.clone() + ".yaml"));
let sandbox: SandboxConfig = match parse_config(&sandbox_fn,
&SandboxConfig::validator(), &Options::default())
{
Ok(cfg) => cfg,
Err(e) => {
return Err(format!("Can't parse sandbox config: {}", e));
}
};
let target_fn = master_cfg.parent().unwrap()
.join(&master.processes_dir)
.join(sandbox.config_file.as_ref().unwrap_or(
&PathBuf::from(&(sandbox_name.clone() + ".yaml"))));
debug!("Target filename {:?}", target_fn);
let tmp_filename = target_fn.with_file_name(
&format!(".tmp.{}", sandbox_name));
try!(copy(&config_file, &tmp_filename)
.map_err(|e| format!("Error copying: {}", e)));
try!(rename(&tmp_filename, &target_fn)
.map_err(|e| format!("Error replacing file: {}", e)));
info!("Done. Sending SIGQUIT to lithos_tree");
let pid_file = master.runtime_dir.join("master.pid");
let mut buf = String::with_capacity(50);
let read_pid = File::open(&pid_file)
.and_then(|mut f| f.read_to_string(&mut buf))
.ok()
.and_then(|_| FromStr::from_str(buf[..].trim()).ok())
.map(Pid::from_raw);
match read_pid {
Some(pid) if kill(pid, None).is_ok() => {
kill(pid, SIGQUIT)
.map_err(|e| error!("Error sending QUIT to master: {:?}", e)).ok();
}
Some(pid) => {
warn!("Process with pid {} is not running...", pid);
}
None => {
warn!("Can't read pid file {}. Probably daemon is not running.",
pid_file.display());
}
};
return Ok(());
}
fn main() {
if env::var("RUST_LOG").is_err() {
env::set_var("RUST_LOG", "warn");
}
env_logger::init();
let mut master_config = PathBuf::from("/etc/lithos/master.yaml");
let mut verbose = false;
let mut config_file = PathBuf::from("");
let mut sandbox_name = "".to_string();
{
let mut ap = ArgumentParser::new();
ap.set_description("Checks if lithos configuration is ok");
ap.refer(&mut master_config)
.add_option(&["--master"], Parse,
"Name of the master configuration file \<|fim▁hole|> .metavar("FILE");
ap.refer(&mut verbose)
.add_option(&["-v", "--verbose"], StoreTrue,
"Verbose configuration");
ap.refer(&mut sandbox_name)
.add_argument("sandbox", Parse,
"Name of the sandbox which configuration will be switched for")
.required()
.metavar("NAME");
ap.refer(&mut config_file)
.add_argument("new_config", Parse, "
Name of the process configuration file for this sandbox to switch
to. The file is copied over current config after configuration is
validated and just before sending a signal to lithos_tree.")
.metavar("FILE")
.required();
ap.add_option(&["--version"],
Print(env!("CARGO_PKG_VERSION").to_string()),
"Show version");
match ap.parse_args() {
Ok(()) => {}
Err(x) => {
exit(x);
}
}
}
match switch_config(&master_config, sandbox_name, &config_file)
{
Ok(()) => {
exit(0);
}
Err(e) => {
write!(&mut stderr(), "Fatal error: {}\n", e).unwrap();
exit(1);
}
}
}<|fim▁end|> | (default /etc/lithos/master.yaml)") |
<|file_name|>test_list_image_filters.py<|end_file_name|><|fim▁begin|># Copyright 2012 OpenStack Foundation
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
import time
from oslo_log import log as logging
import six
import testtools
from tempest.api.compute import base
from tempest.common.utils import data_utils
from tempest.common import waiters
from tempest import config
from tempest import test
CONF = config.CONF
LOG = logging.getLogger(__name__)
class ListImageFiltersTestJSON(base.BaseV2ComputeTest):
@classmethod
def skip_checks(cls):
super(ListImageFiltersTestJSON, cls).skip_checks()
if not CONF.service_available.glance:
skip_msg = ("%s skipped as glance is not available" % cls.__name__)
raise cls.skipException(skip_msg)
@classmethod
def setup_clients(cls):
super(ListImageFiltersTestJSON, cls).setup_clients()
cls.client = cls.images_client
cls.glance_client = cls.os.image_client
@classmethod
def resource_setup(cls):
super(ListImageFiltersTestJSON, cls).resource_setup()
def _create_image():
name = data_utils.rand_name('image')
body = cls.glance_client.create_image(name=name,
container_format='bare',
disk_format='raw',
is_public=False)['image']
image_id = body['id']
cls.images.append(image_id)
# Wait 1 second between creation and upload to ensure a delta
# between created_at and updated_at.
time.sleep(1)
image_file = six.StringIO(('*' * 1024))
cls.glance_client.update_image(image_id, data=image_file)
waiters.wait_for_image_status(cls.client, image_id, 'ACTIVE')
body = cls.client.show_image(image_id)['image']
return body
# Create non-snapshot images via glance
cls.image1 = _create_image()
cls.image1_id = cls.image1['id']
cls.image2 = _create_image()
cls.image2_id = cls.image2['id']
cls.image3 = _create_image()
cls.image3_id = cls.image3['id']
if not CONF.compute_feature_enabled.snapshot:
return
# Create instances and snapshots via nova
cls.server1 = cls.create_test_server()
cls.server2 = cls.create_test_server(wait_until='ACTIVE')
# NOTE(sdague) this is faster than doing the sync wait_util on both
waiters.wait_for_server_status(cls.servers_client,
cls.server1['id'], 'ACTIVE')
# Create images to be used in the filter tests
cls.snapshot1 = cls.create_image_from_server(
cls.server1['id'], wait_until='ACTIVE')
cls.snapshot1_id = cls.snapshot1['id']
# Servers have a hidden property for when they are being imaged
# Performing back-to-back create image calls on a single
# server will sometimes cause failures
cls.snapshot3 = cls.create_image_from_server(
cls.server2['id'], wait_until='ACTIVE')
cls.snapshot3_id = cls.snapshot3['id']
# Wait for the server to be active after the image upload
cls.snapshot2 = cls.create_image_from_server(
cls.server1['id'], wait_until='ACTIVE')
cls.snapshot2_id = cls.snapshot2['id']
@test.idempotent_id('a3f5b513-aeb3-42a9-b18e-f091ef73254d')
def test_list_images_filter_by_status(self):
# The list of images should contain only images with the
# provided status
params = {'status': 'ACTIVE'}
images = self.client.list_images(**params)['images']
self.assertTrue(any([i for i in images if i['id'] == self.image1_id]))
self.assertTrue(any([i for i in images if i['id'] == self.image2_id]))
self.assertTrue(any([i for i in images if i['id'] == self.image3_id]))
@test.idempotent_id('33163b73-79f5-4d07-a7ea-9213bcc468ff')
def test_list_images_filter_by_name(self):
# List of all images should contain the expected images filtered
# by name
params = {'name': self.image1['name']}
images = self.client.list_images(**params)['images']
self.assertTrue(any([i for i in images if i['id'] == self.image1_id]))
self.assertFalse(any([i for i in images if i['id'] == self.image2_id]))
self.assertFalse(any([i for i in images if i['id'] == self.image3_id]))
@test.idempotent_id('9f238683-c763-45aa-b848-232ec3ce3105')
@testtools.skipUnless(CONF.compute_feature_enabled.snapshot,
'Snapshotting is not available.')
def test_list_images_filter_by_server_id(self):
# The images should contain images filtered by server id
params = {'server': self.server1['id']}
images = self.client.list_images(**params)['images']
self.assertTrue(any([i for i in images
if i['id'] == self.snapshot1_id]),
"Failed to find image %s in images. Got images %s" %
(self.image1_id, images))
self.assertTrue(any([i for i in images
if i['id'] == self.snapshot2_id]))
self.assertFalse(any([i for i in images
if i['id'] == self.snapshot3_id]))
@test.idempotent_id('05a377b8-28cf-4734-a1e6-2ab5c38bf606')
@testtools.skipUnless(CONF.compute_feature_enabled.snapshot,
'Snapshotting is not available.')
def test_list_images_filter_by_server_ref(self):
# The list of servers should be filtered by server ref
server_links = self.server2['links']
# Try all server link types
for link in server_links:
params = {'server': link['href']}
images = self.client.list_images(**params)['images']
self.assertFalse(any([i for i in images
if i['id'] == self.snapshot1_id]))
self.assertFalse(any([i for i in images
if i['id'] == self.snapshot2_id]))
self.assertTrue(any([i for i in images
if i['id'] == self.snapshot3_id]))
@test.idempotent_id('e3356918-4d3e-4756-81d5-abc4524ba29f')
@testtools.skipUnless(CONF.compute_feature_enabled.snapshot,
'Snapshotting is not available.')
def test_list_images_filter_by_type(self):
# The list of servers should be filtered by image type
params = {'type': 'snapshot'}
images = self.client.list_images(**params)['images']
self.assertTrue(any([i for i in images
if i['id'] == self.snapshot1_id]))
self.assertTrue(any([i for i in images
if i['id'] == self.snapshot2_id]))
self.assertTrue(any([i for i in images
if i['id'] == self.snapshot3_id]))
self.assertFalse(any([i for i in images
if i['id'] == self.image_ref]))
@test.idempotent_id('3a484ca9-67ba-451e-b494-7fcf28d32d62')
def test_list_images_limit_results(self):
# Verify only the expected number of results are returned
params = {'limit': '1'}
images = self.client.list_images(**params)['images']
self.assertEqual(1, len([x for x in images if 'id' in x]))
@test.idempotent_id('18bac3ae-da27-436c-92a9-b22474d13aab')
def test_list_images_filter_by_changes_since(self):
# Verify only updated images are returned in the detailed list
# Becoming ACTIVE will modify the updated time
# Filter by the image's created time
params = {'changes-since': self.image3['created']}
images = self.client.list_images(**params)['images']
found = any([i for i in images if i['id'] == self.image3_id])
self.assertTrue(found)
@test.idempotent_id('9b0ea018-6185-4f71-948a-a123a107988e')
def test_list_images_with_detail_filter_by_status(self):
# Detailed list of all images should only contain images
# with the provided status
params = {'status': 'ACTIVE'}
images = self.client.list_images(detail=True, **params)['images']
self.assertTrue(any([i for i in images if i['id'] == self.image1_id]))
self.assertTrue(any([i for i in images if i['id'] == self.image2_id]))
self.assertTrue(any([i for i in images if i['id'] == self.image3_id]))
@test.idempotent_id('644ea267-9bd9-4f3b-af9f-dffa02396a17')
def test_list_images_with_detail_filter_by_name(self):
# Detailed list of all images should contain the expected
# images filtered by name
params = {'name': self.image1['name']}
images = self.client.list_images(detail=True, **params)['images']
self.assertTrue(any([i for i in images if i['id'] == self.image1_id]))
self.assertFalse(any([i for i in images if i['id'] == self.image2_id]))
self.assertFalse(any([i for i in images if i['id'] == self.image3_id]))
@test.idempotent_id('ba2fa9a9-b672-47cc-b354-3b4c0600e2cb')
def test_list_images_with_detail_limit_results(self):
# Verify only the expected number of results (with full details)
# are returned
params = {'limit': '1'}
images = self.client.list_images(detail=True, **params)['images']
self.assertEqual(1, len(images))
@test.idempotent_id('8c78f822-203b-4bf6-8bba-56ebd551cf84')
@testtools.skipUnless(CONF.compute_feature_enabled.snapshot,
'Snapshotting is not available.')
def test_list_images_with_detail_filter_by_server_ref(self):
# Detailed list of servers should be filtered by server ref
server_links = self.server2['links']
# Try all server link types
for link in server_links:
params = {'server': link['href']}
images = self.client.list_images(detail=True, **params)['images']
<|fim▁hole|> self.assertTrue(any([i for i in images
if i['id'] == self.snapshot3_id]))
@test.idempotent_id('888c0cc0-7223-43c5-9db0-b125fd0a393b')
@testtools.skipUnless(CONF.compute_feature_enabled.snapshot,
'Snapshotting is not available.')
def test_list_images_with_detail_filter_by_type(self):
# The detailed list of servers should be filtered by image type
params = {'type': 'snapshot'}
images = self.client.list_images(detail=True, **params)['images']
self.client.show_image(self.image_ref)
self.assertTrue(any([i for i in images
if i['id'] == self.snapshot1_id]))
self.assertTrue(any([i for i in images
if i['id'] == self.snapshot2_id]))
self.assertTrue(any([i for i in images
if i['id'] == self.snapshot3_id]))
self.assertFalse(any([i for i in images
if i['id'] == self.image_ref]))
@test.idempotent_id('7d439e18-ac2e-4827-b049-7e18004712c4')
def test_list_images_with_detail_filter_by_changes_since(self):
# Verify an update image is returned
# Becoming ACTIVE will modify the updated time
# Filter by the image's created time
params = {'changes-since': self.image1['created']}
images = self.client.list_images(detail=True, **params)['images']
self.assertTrue(any([i for i in images if i['id'] == self.image1_id]))<|fim▁end|> | self.assertFalse(any([i for i in images
if i['id'] == self.snapshot1_id]))
self.assertFalse(any([i for i in images
if i['id'] == self.snapshot2_id])) |
<|file_name|>lib.rs<|end_file_name|><|fim▁begin|>/* main.rs */
#[crate_id = "main#0.1"];
#[comment = "ironkernel"];
#[license = "MIT"];
#[crate_type = "lib"];
// Forked from pczarn/rustboot
#[no_std];
#[feature(asm, globs, macro_rules)];
extern mod core;
#[cfg(target_arch = "arm")]
pub use support::{memcpy, memmove};
<|fim▁hole|>
#[cfg(target_arch = "arm")]
#[path = "rust-core/support.rs"]
mod support;
#[cfg(target_arch = "arm")]
#[path = "arch/arm/"]
mod platform {
pub mod cpu;
pub mod io;
pub mod drivers;
}<|fim▁end|> | use platform::{cpu, io};
pub mod kernel; |
<|file_name|>urls.py<|end_file_name|><|fim▁begin|>from django.conf.urls import include, url
from sapl.sessao.views import (AdicionarVariasMateriasExpediente,
AdicionarVariasMateriasOrdemDia, BancadaCrud,
CargoBancadaCrud, ExpedienteMateriaCrud,
ExpedienteView, JustificativaAusenciaCrud,
OcorrenciaSessaoView, ConsideracoesFinaisView, MateriaOrdemDiaCrud, OradorOrdemDiaCrud,
MesaView, OradorCrud,
OradorExpedienteCrud, PainelView,
PautaSessaoDetailView, PautaSessaoView,
PesquisarPautaSessaoView,
PesquisarSessaoPlenariaView,
PresencaOrdemDiaView, PresencaView,
ResumoOrdenacaoView, ResumoView, ResumoAtaView, RetiradaPautaCrud, SessaoCrud,
TipoJustificativaCrud, TipoExpedienteCrud, TipoResultadoVotacaoCrud,
TipoExpedienteCrud, TipoResultadoVotacaoCrud, TipoRetiradaPautaCrud,
TipoSessaoCrud, VotacaoEditView,
VotacaoExpedienteEditView,
VotacaoExpedienteView, VotacaoNominalEditView,
VotacaoNominalExpedienteDetailView,
VotacaoNominalExpedienteEditView,
VotacaoNominalExpedienteView,
VotacaoNominalTransparenciaDetailView,
VotacaoSimbolicaTransparenciaDetailView,
VotacaoNominalView, VotacaoView, abrir_votacao,
atualizar_mesa, insere_parlamentar_composicao,
mudar_ordem_materia_sessao, recuperar_materia,
recuperar_numero_sessao_view,
remove_parlamentar_composicao,
reordena_materias,
sessao_legislativa_legislatura_ajax,
VotacaoEmBlocoOrdemDia, VotacaoEmBlocoExpediente,
VotacaoEmBlocoSimbolicaView, VotacaoEmBlocoNominalView,
recuperar_nome_tipo_sessao,
ExpedienteLeituraView,
OrdemDiaLeituraView,
retirar_leitura,
TransferenciaMateriasExpediente, TransferenciaMateriasOrdemDia,
filtra_materias_copia_sessao_ajax, verifica_materia_sessao_plenaria_ajax)
from .apps import AppConfig
app_name = AppConfig.name
urlpatterns = [
url(r'^sessao/', include(SessaoCrud.get_urls() + OradorCrud.get_urls() +
OradorExpedienteCrud.get_urls() +
ExpedienteMateriaCrud.get_urls() +
JustificativaAusenciaCrud.get_urls() +
MateriaOrdemDiaCrud.get_urls() +
OradorOrdemDiaCrud.get_urls() +
RetiradaPautaCrud.get_urls())),
url(r'^sessao/(?P<pk>\d+)/mesa$', MesaView.as_view(), name='mesa'),
url(r'^sessao/mesa/atualizar-mesa/$',
atualizar_mesa,
name='atualizar_mesa'),
url(r'^sessao/mesa/insere-parlamentar/composicao/$',
insere_parlamentar_composicao,
name='insere_parlamentar_composicao'),
url(r'^sessao/mesa/remove-parlamentar-composicao/$',
remove_parlamentar_composicao,
name='remove_parlamentar_composicao'),
url(r'^sessao/recuperar-materia/', recuperar_materia),
url(r'^sessao/recuperar-numero-sessao/',
recuperar_numero_sessao_view,
name='recuperar_numero_sessao_view'
),
url(r'^sessao/recuperar-nome-tipo-sessao/',
recuperar_nome_tipo_sessao,
name='recuperar_nome_tipo_sessao'),
url(r'^sessao/sessao-legislativa-legislatura-ajax/',
sessao_legislativa_legislatura_ajax,
name='sessao_legislativa_legislatura_ajax_view'),
url(r'^sessao/filtra-materias-copia-sessao-ajax/',
filtra_materias_copia_sessao_ajax,
name='filtra_materias_copia_sessao_ajax_view'),
url(r'^sessao/verifica-materia-sessao-plenaria-ajax/',
verifica_materia_sessao_plenaria_ajax,
name='verifica_materia_sessao_plenaria_ajax_view'),
url(r'^sessao/(?P<pk>\d+)/(?P<spk>\d+)/abrir-votacao$',
abrir_votacao,
name="abrir_votacao"),
url(r'^sessao/(?P<pk>\d+)/reordena/(?P<tipo>[\w\-]+)/(?P<ordenacao>\d+)/$', reordena_materias, name="reordena_materias"),
<|fim▁hole|> url(r'^sistema/sessao-plenaria/tipo-expediente/',
include(TipoExpedienteCrud.get_urls())),
url(r'^sistema/sessao-plenaria/tipo-justificativa/',
include(TipoJustificativaCrud.get_urls())),
url(r'^sistema/sessao-plenaria/tipo-retirada-pauta/',
include(TipoRetiradaPautaCrud.get_urls())),
url(r'^sistema/bancada/',
include(BancadaCrud.get_urls())),
url(r'^sistema/cargo-bancada/',
include(CargoBancadaCrud.get_urls())),
url(r'^sistema/resumo-ordenacao/',
ResumoOrdenacaoView.as_view(),
name='resumo_ordenacao'),
url(r'^sessao/(?P<pk>\d+)/adicionar-varias-materias-expediente/',
AdicionarVariasMateriasExpediente.as_view(),
name='adicionar_varias_materias_expediente'),
url(r'^sessao/(?P<pk>\d+)/adicionar-varias-materias-ordem-dia/',
AdicionarVariasMateriasOrdemDia.as_view(),
name='adicionar_varias_materias_ordem_dia'),
# PAUTA SESSÃO
url(r'^sessao/pauta-sessao$',
PautaSessaoView.as_view(), name='pauta_sessao'),
url(r'^sessao/pauta-sessao/pesquisar-pauta$',
PesquisarPautaSessaoView.as_view(), name='pesquisar_pauta'),
url(r'^sessao/pauta-sessao/(?P<pk>\d+)/(?:pdf)?$',
PautaSessaoDetailView.as_view(), name='pauta_sessao_detail'),
# Subnav sessão
url(r'^sessao/(?P<pk>\d+)/expediente$',
ExpedienteView.as_view(), name='expediente'),
url(r'^sessao/(?P<pk>\d+)/ocorrencia_sessao$',
OcorrenciaSessaoView.as_view(), name='ocorrencia_sessao'),
url(r'^sessao/(?P<pk>\d+)/consideracoes_finais$',
ConsideracoesFinaisView.as_view(), name='consideracoes_finais'),
url(r'^sessao/(?P<pk>\d+)/presenca$',
PresencaView.as_view(), name='presenca'),
url(r'^sessao/(?P<pk>\d+)/painel$',
PainelView.as_view(), name='painel'),
url(r'^sessao/(?P<pk>\d+)/presencaordemdia$',
PresencaOrdemDiaView.as_view(),
name='presencaordemdia'),
url(r'^sessao/(?P<pk>\d+)/votacao_bloco_ordemdia$',
VotacaoEmBlocoOrdemDia.as_view(),
name='votacao_bloco_ordemdia'),
url(r'^sessao/(?P<pk>\d+)/votacao_bloco/votnom$',
VotacaoEmBlocoNominalView.as_view(), name='votacaobloconom'),
url(r'^sessao/(?P<pk>\d+)/votacao_bloco/votsimb$',
VotacaoEmBlocoSimbolicaView.as_view(), name='votacaoblocosimb'),
url(r'^sessao/(?P<pk>\d+)/votacao_bloco_expediente$',
VotacaoEmBlocoExpediente.as_view(),
name='votacao_bloco_expediente'),
url(r'^sessao/(?P<pk>\d+)/resumo$',
ResumoView.as_view(), name='resumo'),
url(r'^sessao/(?P<pk>\d+)/resumo_ata$',
ResumoAtaView.as_view(), name='resumo_ata'),
url(r'^sessao/pesquisar-sessao$',
PesquisarSessaoPlenariaView.as_view(), name='pesquisar_sessao'),
url(r'^sessao/(?P<pk>\d+)/matordemdia/votnom/(?P<oid>\d+)/(?P<mid>\d+)$',
VotacaoNominalView.as_view(), name='votacaonominal'),
url(r'^sessao/(?P<pk>\d+)/matordemdia/votnom/edit/(?P<oid>\d+)/(?P<mid>\d+)$',
VotacaoNominalEditView.as_view(), name='votacaonominaledit'),
url(r'^sessao/(?P<pk>\d+)/matordemdia/votsec/(?P<oid>\d+)/(?P<mid>\d+)$',
VotacaoView.as_view(), name='votacaosecreta'),
url(r'^sessao/(?P<pk>\d+)/matordemdia/votsec/view/(?P<oid>\d+)/(?P<mid>\d+)$',
VotacaoEditView.as_view(), name='votacaosecretaedit'),
url(r'^sessao/(?P<pk>\d+)/matordemdia/votsimb/(?P<oid>\d+)/(?P<mid>\d+)$',
VotacaoView.as_view(), name='votacaosimbolica'),
url(r'^sessao/(?P<pk>\d+)/matordemdia/votsimbbloco/$',
VotacaoView.as_view(), name='votacaosimbolicabloco'),
url(r'^sessao/(?P<pk>\d+)/matordemdia/votsimb/view/(?P<oid>\d+)/(?P<mid>\d+)$',
VotacaoEditView.as_view(), name='votacaosimbolicaedit'),
url(r'^sessao/(?P<pk>\d+)/matexp/votnom/(?P<oid>\d+)/(?P<mid>\d+)$',
VotacaoNominalExpedienteView.as_view(), name='votacaonominalexp'),
url(r'^sessao/(?P<pk>\d+)/matexp/votnom/edit/(?P<oid>\d+)/(?P<mid>\d+)$',
VotacaoNominalExpedienteEditView.as_view(),
name='votacaonominalexpedit'),
url(r'^sessao/(?P<pk>\d+)/matexp/votnom/detail/(?P<oid>\d+)/(?P<mid>\d+)$',
VotacaoNominalExpedienteDetailView.as_view(),
name='votacaonominalexpdetail'),
url(r'^sessao/(?P<pk>\d+)/matexp/votsimb/(?P<oid>\d+)/(?P<mid>\d+)$',
VotacaoExpedienteView.as_view(), name='votacaosimbolicaexp'),
url(r'^sessao/(?P<pk>\d+)/matexp/votsimb/view/(?P<oid>\d+)/(?P<mid>\d+)$',
VotacaoExpedienteEditView.as_view(), name='votacaosimbolicaexpedit'),
url(r'^sessao/(?P<pk>\d+)/matexp/votsec/(?P<oid>\d+)/(?P<mid>\d+)$',
VotacaoExpedienteView.as_view(), name='votacaosecretaexp'),
url(r'^sessao/(?P<pk>\d+)/matexp/votsec/view/(?P<oid>\d+)/(?P<mid>\d+)$',
VotacaoExpedienteEditView.as_view(), name='votacaosecretaexpedit'),
url(r'^sessao/(?P<pk>\d+)/votacao-nominal-transparencia/(?P<oid>\d+)/(?P<mid>\d+)$',
VotacaoNominalTransparenciaDetailView.as_view(),
name='votacao_nominal_transparencia'),
url(r'^sessao/(?P<pk>\d+)/votacao-simbolica-transparencia/(?P<oid>\d+)/(?P<mid>\d+)$',
VotacaoSimbolicaTransparenciaDetailView.as_view(),
name='votacao_simbolica_transparencia'),
url(r'^sessao/mudar-ordem-materia-sessao/',
mudar_ordem_materia_sessao,
name='mudar_ordem_materia_sessao'),
url(r'^sessao/(?P<pk>\d+)/matexp/leitura/(?P<oid>\d+)/(?P<mid>\d+)$',
ExpedienteLeituraView.as_view(), name='leituraexp'),
url(r'^sessao/(?P<pk>\d+)/matordemdia/leitura/(?P<oid>\d+)/(?P<mid>\d+)$',
OrdemDiaLeituraView.as_view(), name='leituraod'),
url(r'^sessao/(?P<pk>\d+)/(?P<iso>\d+)/(?P<oid>\d+)/retirar-leitura$',
retirar_leitura, name='retirar_leitura'),
url(r'^sessao/(?P<pk>\d+)/transf-mat-exp$',
TransferenciaMateriasExpediente.as_view(),
name="transf_mat_exp"),
url(r'^sessao/(?P<pk>\d+)/transf-mat-ordemdia$',
TransferenciaMateriasOrdemDia.as_view(),
name="transf_mat_ordemdia"),
]<|fim▁end|> | url(r'^sistema/sessao-plenaria/tipo/',
include(TipoSessaoCrud.get_urls())),
url(r'^sistema/sessao-plenaria/tipo-resultado-votacao/',
include(TipoResultadoVotacaoCrud.get_urls())), |
<|file_name|>conf.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
#
# Configuration file for the Sphinx documentation builder.
#
# This file does only contain a selection of the most common options. For a
# full list see the documentation:
# http://www.sphinx-doc.org/en/master/config
# -- Path setup --------------------------------------------------------------
# If extensions (or modules to document with autodoc) are in another directory,<|fim▁hole|># add these directories to sys.path here. If the directory is relative to the
# documentation root, use os.path.abspath to make it absolute, like shown here.
#
# import os
# import sys
# sys.path.insert(0, os.path.abspath('.'))
# -- Project information -----------------------------------------------------
project = 'msgiver'
copyright = '2018, Tatsunori Nishikori'
author = 'Tatsunori Nishikori'
# The short X.Y version
version = '0.1'
# The full version, including alpha/beta/rc tags
release = '0.1.7.1'
# -- General configuration ---------------------------------------------------
# If your documentation needs a minimal Sphinx version, state it here.
#
# needs_sphinx = '1.0'
# Add any Sphinx extension module names here, as strings. They can be
# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom
# ones.
extensions = [
'sphinx.ext.autodoc',
'sphinx.ext.coverage',
'sphinx.ext.githubpages',
]
# Add any paths that contain templates here, relative to this directory.
templates_path = ['_templates']
# The suffix(es) of source filenames.
# You can specify multiple suffix as a list of string:
#
# source_suffix = ['.rst', '.md']
source_suffix = '.rst'
# The master toctree document.
master_doc = 'index'
# The language for content autogenerated by Sphinx. Refer to documentation
# for a list of supported languages.
#
# This is also used if you do content translation via gettext catalogs.
# Usually you set "language" from the command line for these cases.
language = None
# List of patterns, relative to source directory, that match files and
# directories to ignore when looking for source files.
# This pattern also affects html_static_path and html_extra_path .
exclude_patterns = ['build', 'Thumbs.db', '.DS_Store']
# The name of the Pygments (syntax highlighting) style to use.
pygments_style = 'sphinx'
# -- Options for HTML output -------------------------------------------------
# The theme to use for HTML and HTML Help pages. See the documentation for
# a list of builtin themes.
#
html_theme = 'alabaster'
# Theme options are theme-specific and customize the look and feel of a theme
# further. For a list of options available for each theme, see the
# documentation.
#
# html_theme_options = {}
# Add any paths that contain custom static files (such as style sheets) here,
# relative to this directory. They are copied after the builtin static files,
# so a file named "default.css" will overwrite the builtin "default.css".
html_static_path = ['_static']
# Custom sidebar templates, must be a dictionary that maps document names
# to template names.
#
# The default sidebars (for documents that don't match any pattern) are
# defined by theme itself. Builtin themes are using these templates by
# default: ``['localtoc.html', 'relations.html', 'sourcelink.html',
# 'searchbox.html']``.
#
# html_sidebars = {}
# -- Options for HTMLHelp output ---------------------------------------------
# Output file base name for HTML help builder.
htmlhelp_basename = 'msgiverdoc'
# -- Options for LaTeX output ------------------------------------------------
latex_elements = {
# The paper size ('letterpaper' or 'a4paper').
#
# 'papersize': 'letterpaper',
# The font size ('10pt', '11pt' or '12pt').
#
# 'pointsize': '10pt',
# Additional stuff for the LaTeX preamble.
#
# 'preamble': '',
# Latex figure (float) alignment
#
# 'figure_align': 'htbp',
}
# Grouping the document tree into LaTeX files. List of tuples
# (source start file, target name, title,
# author, documentclass [howto, manual, or own class]).
latex_documents = [
(master_doc, 'msgiver.tex', 'msgiver Documentation',
'Tatsunori Nishikori', 'manual'),
]
# -- Options for manual page output ------------------------------------------
# One entry per manual page. List of tuples
# (source start file, name, description, authors, manual section).
man_pages = [
(master_doc, 'msgiver', 'msgiver Documentation',
[author], 1)
]
# -- Options for Texinfo output ----------------------------------------------
# Grouping the document tree into Texinfo files. List of tuples
# (source start file, target name, title, author,
# dir menu entry, description, category)
texinfo_documents = [
(master_doc, 'msgiver', 'msgiver Documentation',
author, 'msgiver', 'One line description of project.',
'Miscellaneous'),
]<|fim▁end|> | |
<|file_name|>chatsService.js<|end_file_name|><|fim▁begin|>appService.factory('Chats', function() {
// Might use a resource here that returns a JSON array
// Some fake testing data
var chats = [{
id: 0,
<|fim▁hole|> name: 'Ben Sparrow',
lastText: 'You on your way?',
face: 'app/view/common/img/ben.png'
}, {
id: 1,
name: 'Max Lynx',
lastText: 'Hey, it\'s me',
face: 'app/view/common/img/max.png'
}, {
id: 2,
name: 'Adam Bradleyson',
lastText: 'I should buy a boat',
face: 'app/view/common/img/adam.jpg'
}, {
id: 3,
name: 'Perry Governor',
lastText: 'Look at my mukluks!',
face: 'app/view/common/img/perry.png'
}, {
id: 4,
name: 'Mike Harrington',
lastText: 'This is wicked good ice cream.',
face: 'app/view/common/img/mike.png'
}];
return {
all: function() {
return chats;
},
remove: function(chat) {
chats.splice(chats.indexOf(chat), 1);
},
get: function(chatId) {
for (var i = 0; i < chats.length; i++) {
if (chats[i].id === parseInt(chatId)) {
return chats[i];
}
}
return null;
}
};
});<|fim▁end|> | |
<|file_name|>instr_vfmadd132ss.rs<|end_file_name|><|fim▁begin|>use ::{BroadcastMode, Instruction, MaskReg, MergeMode, Mnemonic, OperandSize, Reg, RoundingMode};
use ::RegType::*;
use ::instruction_def::*;
use ::Operand::*;
use ::Reg::*;
use ::RegScale::*;
use ::test::run_test;
#[test]
fn vfmadd132ss_1() {
run_test(&Instruction { mnemonic: Mnemonic::VFMADD132SS, operand1: Some(Direct(XMM6)), operand2: Some(Direct(XMM6)), operand3: Some(Direct(XMM1)), operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[196, 226, 73, 153, 241], OperandSize::Dword)
}
#[test]
fn vfmadd132ss_2() {
run_test(&Instruction { mnemonic: Mnemonic::VFMADD132SS, operand1: Some(Direct(XMM1)), operand2: Some(Direct(XMM2)), operand3: Some(IndirectScaledDisplaced(EDX, Four, 352493850, Some(OperandSize::Dword), None)), operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[196, 226, 105, 153, 12, 149, 26, 161, 2, 21], OperandSize::Dword)
}
#[test]<|fim▁hole|>}
#[test]
fn vfmadd132ss_4() {
run_test(&Instruction { mnemonic: Mnemonic::VFMADD132SS, operand1: Some(Direct(XMM1)), operand2: Some(Direct(XMM6)), operand3: Some(IndirectDisplaced(RCX, 1655863941, Some(OperandSize::Dword), None)), operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[196, 226, 73, 153, 137, 133, 122, 178, 98], OperandSize::Qword)
}
#[test]
fn vfmadd132ss_5() {
run_test(&Instruction { mnemonic: Mnemonic::VFMADD132SS, operand1: Some(Direct(XMM1)), operand2: Some(Direct(XMM6)), operand3: Some(Direct(XMM0)), operand4: None, lock: false, rounding_mode: Some(RoundingMode::Nearest), merge_mode: Some(MergeMode::Zero), sae: false, mask: Some(MaskReg::K4), broadcast: None }, &[98, 242, 77, 156, 153, 200], OperandSize::Dword)
}
#[test]
fn vfmadd132ss_6() {
run_test(&Instruction { mnemonic: Mnemonic::VFMADD132SS, operand1: Some(Direct(XMM7)), operand2: Some(Direct(XMM0)), operand3: Some(IndirectScaledIndexed(ECX, EDI, Four, Some(OperandSize::Dword), None)), operand4: None, lock: false, rounding_mode: None, merge_mode: Some(MergeMode::Zero), sae: false, mask: Some(MaskReg::K2), broadcast: None }, &[98, 242, 125, 138, 153, 60, 185], OperandSize::Dword)
}
#[test]
fn vfmadd132ss_7() {
run_test(&Instruction { mnemonic: Mnemonic::VFMADD132SS, operand1: Some(Direct(XMM6)), operand2: Some(Direct(XMM20)), operand3: Some(Direct(XMM19)), operand4: None, lock: false, rounding_mode: Some(RoundingMode::Zero), merge_mode: Some(MergeMode::Zero), sae: false, mask: Some(MaskReg::K2), broadcast: None }, &[98, 178, 93, 242, 153, 243], OperandSize::Qword)
}
#[test]
fn vfmadd132ss_8() {
run_test(&Instruction { mnemonic: Mnemonic::VFMADD132SS, operand1: Some(Direct(XMM17)), operand2: Some(Direct(XMM4)), operand3: Some(Indirect(RBX, Some(OperandSize::Dword), None)), operand4: None, lock: false, rounding_mode: None, merge_mode: Some(MergeMode::Zero), sae: false, mask: Some(MaskReg::K7), broadcast: None }, &[98, 226, 93, 143, 153, 11], OperandSize::Qword)
}<|fim▁end|> | fn vfmadd132ss_3() {
run_test(&Instruction { mnemonic: Mnemonic::VFMADD132SS, operand1: Some(Direct(XMM0)), operand2: Some(Direct(XMM7)), operand3: Some(Direct(XMM4)), operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[196, 226, 65, 153, 196], OperandSize::Qword) |
End of preview. Expand
in Dataset Viewer.
README.md exists but content is empty.
Use the Edit dataset card button to edit it.
- Downloads last month
- 34