file_name
large_stringlengths
4
140
prefix
large_stringlengths
0
39k
suffix
large_stringlengths
0
36.1k
middle
large_stringlengths
0
29.4k
fim_type
large_stringclasses
4 values
unittest_cst.py
""" @file @brief Helpers to compress constant used in unit tests. """ import base64 import json import lzma import pprint def compress_cst(data, length=70, as_text=False): """ Transforms a huge constant into a sequence of compressed binary strings. :param data: data :param length: line length :pa...
""" Transforms a huge constant produced by function @see fn compress_cst into the original value. :param data: data :param length: line length :param as_text: returns the results as text :return: results .. runpython:: :showcode: from pyquickhelper.pycode.unittest_cst impo...
identifier_body
listener.py
from typing import Callable, Any from ..model import MetaEvent, Event from ..exceptions import PropertyStatechartError __all__ = ['InternalEventListener', 'PropertyStatechartListener']
""" def __init__(self, callable: Callable[[Event], Any]) -> None: self._callable = callable def __call__(self, event: MetaEvent) -> None: if event.name == 'event sent': self._callable(Event(event.event.name, **event.event.data)) class PropertyStatechartListener: """ L...
class InternalEventListener: """ Listener that filters and propagates internal events as external events.
random_line_split
listener.py
from typing import Callable, Any from ..model import MetaEvent, Event from ..exceptions import PropertyStatechartError __all__ = ['InternalEventListener', 'PropertyStatechartListener'] class InternalEventListener: """ Listener that filters and propagates internal events as external events. """ de...
raise PropertyStatechartError(self._interpreter)
conditional_block
listener.py
from typing import Callable, Any from ..model import MetaEvent, Event from ..exceptions import PropertyStatechartError __all__ = ['InternalEventListener', 'PropertyStatechartListener'] class InternalEventListener: """ Listener that filters and propagates internal events as external events. """ de...
: """ Listener that propagates meta-events to given property statechart, executes the property statechart, and checks it. """ def __init__(self, interpreter) -> None: self._interpreter = interpreter def __call__(self, event: MetaEvent) -> None: self._interpreter.queue(event) ...
PropertyStatechartListener
identifier_name
listener.py
from typing import Callable, Any from ..model import MetaEvent, Event from ..exceptions import PropertyStatechartError __all__ = ['InternalEventListener', 'PropertyStatechartListener'] class InternalEventListener: """ Listener that filters and propagates internal events as external events. """ de...
def __call__(self, event: MetaEvent) -> None: if event.name == 'event sent': self._callable(Event(event.event.name, **event.event.data)) class PropertyStatechartListener: """ Listener that propagates meta-events to given property statechart, executes the property statechart, and ...
self._callable = callable
identifier_body
complex.rs
// Copyright 2013 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
(re: T, im: T) -> Complex<T> { Complex { re: re, im: im } } /** Returns the square of the norm (since `T` doesn't necessarily have a sqrt function), i.e. `re^2 + im^2`. */ #[inline] pub fn norm_sqr(&self) -> T { self.re * self.re + self.im * self.im } /// Returns t...
new
identifier_name
complex.rs
// Copyright 2013 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
for &c in all_consts.iter() { assert_eq!(_0_0i + c, c); assert_eq!(c + _0_0i, c); } } #[test] fn test_sub() { assert_eq!(_05_05i - _05_05i, _0_0i); assert_eq!(_0_1i - _1_0i, _neg1_1i); assert_eq!(_0_1i -...
assert_eq!(_0_1i + _1_0i, _1_1i); assert_eq!(_1_0i + _neg1_1i, _0_1i);
random_line_split
complex.rs
// Copyright 2013 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
} } #[cfg(test)] mod test { #![allow(non_uppercase_statics)] use super::{Complex64, Complex}; use std::num::{Zero,One,Float}; pub static _0_0i : Complex64 = Complex { re: 0.0, im: 0.0 }; pub static _1_0i : Complex64 = Complex { re: 1.0, im: 0.0 }; pub static _1_1i : Complex64 = Complex {...
{ format!("{}+{}i", self.re.to_str_radix(radix), self.im.to_str_radix(radix)) }
conditional_block
complex.rs
// Copyright 2013 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
/// Convert a polar representation into a complex number. #[inline] pub fn from_polar(r: &T, theta: &T) -> Complex<T> { Complex::new(*r * theta.cos(), *r * theta.sin()) } } /* arithmetic */ // (a + i b) + (c + i d) == (a + c) + i (b + d) impl<T: Clone + Num> Add<Complex<T>, Complex<T>> for Com...
{ (self.norm(), self.arg()) }
identifier_body
getAttribute.js
describe('getAttribute', function () { var chai = require('chai'), assert = chai.assert; var DomParser = require('../index.js'), parser = new DomParser(); it('attr value with "="', function(){ var html = '<div id="outer" data-a ttt = "asd\'">\n' + ' <a id="inner" href="/search...
assert.strictEqual(outer.getAttribute('not-exists'), null); assert.equal(inner.getAttribute('href'), '/search?field=123'); }); });
assert.equal(outer.attributes.length, 3); assert.equal(outer.getAttribute('id'), 'outer'); assert.equal(outer.getAttribute('data-a'), ''); assert.equal(outer.getAttribute('ttt'), 'asd\'');
random_line_split
asteroids.js
//asteroid clone (core mechanics only) //arrow keys to move + x to shoot var bullets; var asteroids; var ship; var shipImage, bulletImage, particleImage; var MARGIN = 40; function setup() { createCanvas(800, 600); bulletImage = loadImage('assets/asteroids_bullet.png'); shipImage = loadImage('assets/asteroids_s...
(type, x, y) { var a = createSprite(x, y); var img = loadImage('assets/asteroid'+floor(random(0, 3))+'.png'); a.addImage(img); a.setSpeed(2.5-(type/2), random(360)); a.rotationSpeed = 0.5; //a.debug = true; a.type = type; if(type == 2) a.scale = 0.6; if(type == 1) a.scale = 0.3; a.mass = 2...
createAsteroid
identifier_name
asteroids.js
//asteroid clone (core mechanics only) //arrow keys to move + x to shoot var bullets; var asteroids; var ship; var shipImage, bulletImage, particleImage; var MARGIN = 40; function setup() { createCanvas(800, 600); bulletImage = loadImage('assets/asteroids_bullet.png'); shipImage = loadImage('assets/asteroids_s...
createAsteroid(3, px, py); } } function draw() { background(0); fill(255); textAlign(CENTER); text('Controls: Arrow Keys + X', width/2, 20); for(var i=0; i<allSprites.length; i++) { var s = allSprites[i]; if(s.position.x<-MARGIN) s.position.x = width+MARGIN; if(s.position.x>width+MARGIN) ...
for(var i = 0; i<8; i++) { var ang = random(360); var px = width/2 + 1000 * cos(radians(ang)); var py = height/2+ 1000 * sin(radians(ang));
random_line_split
asteroids.js
//asteroid clone (core mechanics only) //arrow keys to move + x to shoot var bullets; var asteroids; var ship; var shipImage, bulletImage, particleImage; var MARGIN = 40; function setup() { createCanvas(800, 600); bulletImage = loadImage('assets/asteroids_bullet.png'); shipImage = loadImage('assets/asteroids_s...
function createAsteroid(type, x, y) { var a = createSprite(x, y); var img = loadImage('assets/asteroid'+floor(random(0, 3))+'.png'); a.addImage(img); a.setSpeed(2.5-(type/2), random(360)); a.rotationSpeed = 0.5; //a.debug = true; a.type = type; if(type == 2) a.scale = 0.6; if(type == 1) a.s...
{ background(0); fill(255); textAlign(CENTER); text('Controls: Arrow Keys + X', width/2, 20); for(var i=0; i<allSprites.length; i++) { var s = allSprites[i]; if(s.position.x<-MARGIN) s.position.x = width+MARGIN; if(s.position.x>width+MARGIN) s.position.x = -MARGIN; if(s.position.y<-MARGIN) s...
identifier_body
sap.ui.core.message.d.ts
declare namespace sap.ui.core.message { class Message extends sap.ui.base.Object { /** * * @param mParameters a map which contains the following parameter properties: * {string} [mParameters.id] The message id: will be defaulted if no id is set * {string} [mParameters.me...
/** * Returns the ID of the MessageProcessor instance */ getId(); /** * Implement in inheriting classes */ setMessages(vMessages); } }
random_line_split
sap.ui.core.message.d.ts
declare namespace sap.ui.core.message { class Message extends sap.ui.base.Object { /** * * @param mParameters a map which contains the following parameter properties: * {string} [mParameters.id] The message id: will be defaulted if no id is set * {string} [mParameters.me...
extends sap.ui.base.EventProvider { /** * Add messages to MessageManager */ addMessages(vMessages: Message|Message[]); /** * Get the MessageModel */ getMessageModel(); /** * Register MessageProcessor */ registerMess...
MessageManager
identifier_name
device.d.ts
export interface Device { /** Get the version of Cordova running on the device. */ cordova: string; /** * The device.model returns the name of the device's model or product. The value is set * by the device manufacturer and may be different across versions of the same product. */ model: s...
{ /** * Returns the whole device object. * * @returns {Object} The device object. */ static readonly device: Device; }
Device
identifier_name
device.d.ts
export interface Device { /** Get the version of Cordova running on the device. */ cordova: string; /** * The device.model returns the name of the device's model or product. The value is set * by the device manufacturer and may be different across versions of the same product. */ model: s...
manufacturer: string; /** Whether the device is running on a simulator. */ isVirtual: boolean; /** Get the device hardware serial number. */ serial: string; } /** * @name Device * @description * Access information about the underlying device and platform. * * @usage * ```typescript * import {...
random_line_split
quota_manager.rs
// CopyrightTechnologies LLC. // // 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 writ...
pub fn default_quota() -> Vec<u64> { info!("Use default quota."); Vec::new() } /// Account array pub fn users(&self, block_tag: BlockTag) -> Option<Vec<Address>> { self.executor .call_method( &*CONTRACT_ADDRESS, &*ACCOUNTS_HASH.as_slic...
.and_then(|output| decode_tools::to_u64_vec(&output)) }
random_line_split
quota_manager.rs
// CopyrightTechnologies LLC. // // 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 writ...
(self) -> ProtoAccountQuotaLimit { let mut r = ProtoAccountQuotaLimit::new(); r.common_quota_limit = self.common_quota_limit; let specific_quota_limit: HashMap<String, u64> = self .get_specific_quota_limit() .iter() .map(|(k, v)| (k.lower_hex(), *v)) ...
into
identifier_name
quota_manager.rs
// CopyrightTechnologies LLC. // // 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 writ...
/// Quota array pub fn quota(&self, block_tag: BlockTag) -> Option<Vec<u64>> { self.executor .call_method( &*CONTRACT_ADDRESS, &*QUOTAS_HASH.as_slice(), None, block_tag, ) .ok() .and_then(|o...
{ let users = self.users(block_tag).unwrap_or_else(Self::default_users); let quota = self.quota(block_tag).unwrap_or_else(Self::default_quota); let mut specific = HashMap::new(); for (k, v) in users.iter().zip(quota.iter()) { specific.insert(*k, *v); } specifi...
identifier_body
crx.js
/* global require, process, Buffer, module */ 'use strict'; var fs = require("fs"); var path = require("path"); var join = path.join; var crypto = require("crypto"); var RSA = require('node-rsa'); var wrench = require("wrench"); var archiver = require("archiver"); var Promise = require('es6-promise').Promise; var temp...
selfie.manifest = require(join(selfie.path, "manifest.json")); selfie.loaded = true; resolve(selfie); }); }); }, /** * Writes data into the extension workable directory. * * @param {string} path * @param {*} data * @returns {Promise} */ writeFile: function (...
{ return reject(err); }
conditional_block
crx.js
/* global require, process, Buffer, module */ 'use strict'; var fs = require("fs"); var path = require("path"); var join = path.join; var crypto = require("crypto"); var RSA = require('node-rsa'); var wrench = require("wrench"); var archiver = require("archiver"); var Promise = require('es6-promise').Promise; var temp...
(attrs) { if ((this instanceof ChromeExtension) !== true) { return new ChromeExtension(attrs); } /* Defaults */ this.appId = null; this.manifest = ''; this.loaded = false; this.rootDirectory = ''; this.publicKey = null; this.privateKey = null; this.codebase = null; /* Copying a...
ChromeExtension
identifier_name
crx.js
/* global require, process, Buffer, module */ 'use strict'; var fs = require("fs"); var path = require("path"); var join = path.join; var crypto = require("crypto"); var RSA = require('node-rsa'); var wrench = require("wrench"); var archiver = require("archiver"); var Promise = require('es6-promise').Promise; var temp...
this.codebase = null; /* Copying attributes */ for (var name in attrs) { this[name] = attrs[name]; } temp.track(); this.path = temp.mkdirSync('crx'); } ChromeExtension.prototype = { /** * Packs the content of the extension in a crx file. * * @param {Buffer=} contentsBuffer * @ret...
random_line_split
crx.js
/* global require, process, Buffer, module */ 'use strict'; var fs = require("fs"); var path = require("path"); var join = path.join; var crypto = require("crypto"); var RSA = require('node-rsa'); var wrench = require("wrench"); var archiver = require("archiver"); var Promise = require('es6-promise').Promise; var temp...
ChromeExtension.prototype = { /** * Packs the content of the extension in a crx file. * * @param {Buffer=} contentsBuffer * @returns {Promise} * @example * * crx.pack().then(function(crxContent){ * // do something with the crxContent binary data * }); * */ pack: function (conten...
{ if ((this instanceof ChromeExtension) !== true) { return new ChromeExtension(attrs); } /* Defaults */ this.appId = null; this.manifest = ''; this.loaded = false; this.rootDirectory = ''; this.publicKey = null; this.privateKey = null; this.codebase = null; /* Copying attribute...
identifier_body
create-test-list.py
#!/usr/bin/env python """ Rules for *.py files * if the changed file is __init__.py, and there is a side-band test/ dir, then test the entire test/functional directory the reason for this is that the init files are usually organizing collections and those can affect many different apis if they break * if ...
(files): lines = sorted(files) for idx, item in enumerate(lines): file, ext = os.path.splitext(item) if not ext and not file.endswith('/'): item += '/' tmp = [x for x in lines if item in x and item != x] for _ in tmp: lines.remove(_) return lines if...
compress_testable_files
identifier_name
create-test-list.py
#!/usr/bin/env python """ Rules for *.py files * if the changed file is __init__.py, and there is a side-band test/ dir, then test the entire test/functional directory the reason for this is that the init files are usually organizing collections and those can affect many different apis if they break * if ...
for product in ['iworkflow', 'bigip', 'bigiq']: determine_files_to_test(product, args.commit)
random_line_split
create-test-list.py
#!/usr/bin/env python """ Rules for *.py files * if the changed file is __init__.py, and there is a side-band test/ dir, then test the entire test/functional directory the reason for this is that the init files are usually organizing collections and those can affect many different apis if they break * if ...
if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument('-c','--commit', help='Git commit to check', required=True) args = parser.parse_args() for product in ['iworkflow', 'bigip', 'bigiq']: determine_files_to_test(product, args.commit)
lines = sorted(files) for idx, item in enumerate(lines): file, ext = os.path.splitext(item) if not ext and not file.endswith('/'): item += '/' tmp = [x for x in lines if item in x and item != x] for _ in tmp: lines.remove(_) return lines
identifier_body
create-test-list.py
#!/usr/bin/env python """ Rules for *.py files * if the changed file is __init__.py, and there is a side-band test/ dir, then test the entire test/functional directory the reason for this is that the init files are usually organizing collections and those can affect many different apis if they break * if ...
if results: results = set(results) results = compress_testable_files(results) fh = open(output_file, 'w') fh.writelines("%s\n" % l for l in results) fh.close() def compress_testable_files(files): lines = sorted(files) for idx, item in enumerate(lines): fil...
results.append(result)
conditional_block
traceback.rs
use std::default::Default; use std::iter; use std::marker::PhantomData; use std::ops::Range; use crate::alignment::AlignmentOperation; use crate::pattern_matching::myers::{word_size, BitVec, DistType, State}; /// Objects implementing this trait handle the addition of calculated blocks (State<T, D>) /// to a containe...
/// m (pattern length). /// Returns the expected size of the vector storing the calculated blocks given this /// information. The vector will then be initialized with the given number of 'empty' /// State<T, D> objects and supplied to the other methods as slice. fn init(&mut self, n: usize, m: D) ->...
/// Prepare for a new search given n (maximum expected number of traceback columns) and
random_line_split
traceback.rs
use std::default::Default; use std::iter; use std::marker::PhantomData; use std::ops::Range; use crate::alignment::AlignmentOperation; use crate::pattern_matching::myers::{word_size, BitVec, DistType, State}; /// Objects implementing this trait handle the addition of calculated blocks (State<T, D>) /// to a containe...
( states: &mut Vec<State<T, D>>, initial_state: &H::TracebackColumn, num_cols: usize, m: D, mut handler: H, ) -> Self { // Correct traceback needs two additional columns at the left of the matrix (see below). // Therefore reserving additional space. le...
new
identifier_name
traceback.rs
use std::default::Default; use std::iter; use std::marker::PhantomData; use std::ops::Range; use crate::alignment::AlignmentOperation; use crate::pattern_matching::myers::{word_size, BitVec, DistType, State}; /// Objects implementing this trait handle the addition of calculated blocks (State<T, D>) /// to a containe...
else { print!(" -"); } } println!(); } } }
{ if *d >= (D::max_value() >> 1) { // missing value print!(" "); } else { print!("{:>4?}", d); } }
conditional_block
traceback.rs
use std::default::Default; use std::iter; use std::marker::PhantomData; use std::ops::Range; use crate::alignment::AlignmentOperation; use crate::pattern_matching::myers::{word_size, BitVec, DistType, State}; /// Objects implementing this trait handle the addition of calculated blocks (State<T, D>) /// to a containe...
} pub(super) struct Traceback<'a, T, D, H> where T: BitVec + 'a, D: DistType, H: StatesHandler<'a, T, D>, { m: D, positions: iter::Cycle<Range<usize>>, handler: H, pos: usize, _t: PhantomData<&'a T>, } impl<'a, T, D, H> Traceback<'a, T, D, H> where T: BitVec, D: DistType, ...
{ println!( "--- TB dist ({:?} <-> {:?})", self.left_block().dist, self.block().dist ); println!( "{:064b} m\n{:064b} + ({:?}) (left) d={:?}\n{:064b} - ({:?})\n \ {:064b} + ({:?}) (current) d={:?}\n{:064b} - ({:?})\n", self...
identifier_body
copy-entrypoints.ts
import * as fs from "fs"; import * as path from "path"; import { examples } from "./examples"; copyEntryPoints(); function assertHasProp<T extends string>( value: unknown, prop: T ): asserts value is Record<T, unknown> { if (!value || typeof value !== "object" || !(prop in value)) { throw new Error( ...
function copyEntryPoints() { const angularOptions: unknown = JSON.parse( fs.readFileSync(path.join(__dirname, "../../../angular.json"), { encoding: "utf-8", }) ); const angularDistDirSetting = readOutputPath(angularOptions); const angularDistDir = path.join( __dirname, "../../..", ang...
return outputPath; }
random_line_split
copy-entrypoints.ts
import * as fs from "fs"; import * as path from "path"; import { examples } from "./examples"; copyEntryPoints(); function assertHasProp<T extends string>( value: unknown, prop: T ): asserts value is Record<T, unknown> { if (!value || typeof value !== "object" || !(prop in value))
} function getProp<T extends string[]>(value: unknown, ...propPath: T): unknown { let current = value; for (const prop of propPath) { assertHasProp(current, prop); current = current[prop]; } return current; } function readOutputPath(angularConfiguration: unknown): string { const outputPath = getPr...
{ throw new Error( `Expected value to be an object containing property "${prop}", but it did not.` ); }
conditional_block
copy-entrypoints.ts
import * as fs from "fs"; import * as path from "path"; import { examples } from "./examples"; copyEntryPoints(); function assertHasProp<T extends string>( value: unknown, prop: T ): asserts value is Record<T, unknown> { if (!value || typeof value !== "object" || !(prop in value)) { throw new Error( ...
<T extends string[]>(value: unknown, ...propPath: T): unknown { let current = value; for (const prop of propPath) { assertHasProp(current, prop); current = current[prop]; } return current; } function readOutputPath(angularConfiguration: unknown): string { const outputPath = getProp( angularConfi...
getProp
identifier_name
copy-entrypoints.ts
import * as fs from "fs"; import * as path from "path"; import { examples } from "./examples"; copyEntryPoints(); function assertHasProp<T extends string>( value: unknown, prop: T ): asserts value is Record<T, unknown> { if (!value || typeof value !== "object" || !(prop in value)) { throw new Error( ...
{ const angularOptions: unknown = JSON.parse( fs.readFileSync(path.join(__dirname, "../../../angular.json"), { encoding: "utf-8", }) ); const angularDistDirSetting = readOutputPath(angularOptions); const angularDistDir = path.join( __dirname, "../../..", angularDistDirSetting ); c...
identifier_body
observe.py
from __future__ import absolute_import from abc import ABCMeta, abstractmethod import weakref import functools # Decorator to target specific messages. def targets(target_messages, no_first=False): if isinstance(target_messages, str): target_messages = [target_messages] def wrapper(f): @funct...
f(self, *args, **kwargs) return _ return wrapper class Observer(object): __metaclass__ = ABCMeta @abstractmethod def update(self, *args, **kwargs): pass class Observable(object): def __init__(self): self.observers = weakref.WeakSet() def register(...
return
conditional_block
observe.py
from __future__ import absolute_import from abc import ABCMeta, abstractmethod import weakref import functools # Decorator to target specific messages. def targets(target_messages, no_first=False): if isinstance(target_messages, str): target_messages = [target_messages] def wrapper(f): @funct...
@abstractmethod def update(self, *args, **kwargs): pass class Observable(object): def __init__(self): self.observers = weakref.WeakSet() def register(self, observer): self.observers.add(observer) def unregister(self, observer): self.observers.discard(observer) ...
class Observer(object): __metaclass__ = ABCMeta
random_line_split
observe.py
from __future__ import absolute_import from abc import ABCMeta, abstractmethod import weakref import functools # Decorator to target specific messages. def targets(target_messages, no_first=False): if isinstance(target_messages, str): target_messages = [target_messages] def wrapper(f): @funct...
def update_observers(self, *args, **kwargs): for observer in self.observers: observer.update(*args, **kwargs) def __getstate__(self): state = self.__dict__.copy() # Do not try to pickle observers. del state["observers"] return state
self.observers.clear()
identifier_body
observe.py
from __future__ import absolute_import from abc import ABCMeta, abstractmethod import weakref import functools # Decorator to target specific messages. def targets(target_messages, no_first=False): if isinstance(target_messages, str): target_messages = [target_messages] def wrapper(f): @funct...
(self): state = self.__dict__.copy() # Do not try to pickle observers. del state["observers"] return state
__getstate__
identifier_name
wrapper.rs
//! This module holds the Wrapper newtype; used to write //! instances of typeclasses that we don't define for types we don't //! own use frunk::monoid::*; use frunk::semigroup::*; use quickcheck::*; /// The Wrapper NewType. Used for writing implementations of traits /// that we don't own for type we don't own. /// /...
<G: Gen>(g: &mut G) -> Self { Wrapper(Min(Arbitrary::arbitrary(g))) } } impl<A: Arbitrary> Arbitrary for Wrapper<All<A>> { fn arbitrary<G: Gen>(g: &mut G) -> Self { Wrapper(All(Arbitrary::arbitrary(g))) } } impl<A: Arbitrary> Arbitrary for Wrapper<Any<A>> { fn arbitrary<G: Gen>(g: &mut...
arbitrary
identifier_name
wrapper.rs
//! This module holds the Wrapper newtype; used to write //! instances of typeclasses that we don't define for types we don't //! own use frunk::monoid::*; use frunk::semigroup::*; use quickcheck::*; /// The Wrapper NewType. Used for writing implementations of traits /// that we don't own for type we don't own. /// /...
}
{ Wrapper(<A as Monoid>::empty()) }
identifier_body
wrapper.rs
//! This module holds the Wrapper newtype; used to write //! instances of typeclasses that we don't define for types we don't //! own use frunk::monoid::*; use frunk::semigroup::*; use quickcheck::*; /// The Wrapper NewType. Used for writing implementations of traits /// that we don't own for type we don't own. /// /...
impl<A: Monoid> Monoid for Wrapper<A> { fn empty() -> Self { Wrapper(<A as Monoid>::empty()) } }
fn combine(&self, other: &Self) -> Self { Wrapper(self.0.combine(&other.0)) } }
random_line_split
manage_languages_page.js
// Copyright 2015 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. /** * @fileoverview 'settings-manage-languages-page' is a sub-page for enabling * and disabling languages. * * @group Chrome Settings Elements * @ele...
assert(this.languages.enabledLanguages.length > 1); return true; }, /** * Updates the available languages that are bound to the iron-list. * @private */ enabledLanguagesChanged_: function() { if (!this.availableLanguages_) { var availableLanguages = []; for (var i = 0; i < this....
{ return false; }
conditional_block
manage_languages_page.js
// Copyright 2015 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. /** * @fileoverview 'settings-manage-languages-page' is a sub-page for enabling * and disabling languages. * * @group Chrome Settings Elements * @ele...
for (var i = 0; i < this.availableLanguages_.length; i++) { this.set('availableLanguages_.' + i + '.enabled', this.languageHelper_.isLanguageEnabled( this.availableLanguages_[i].code)); } } }, });
// Update the available languages in place.
random_line_split
QtVariant.py
import sys import os default_variant = 'PySide' env_api = os.environ.get('QT_API', 'pyqt') if '--pyside' in sys.argv: variant = 'PySide' elif '--pyqt4' in sys.argv: variant = 'PyQt4' elif env_api == 'pyside': variant = 'PySide' elif env_api == 'pyqt': variant = 'PyQt4' else: variant = default_vari...
else: raise ImportError("Python Variant not specified") __all__ = [QtGui, QtCore, QtLoadUI, variant]
random_line_split
QtVariant.py
import sys import os default_variant = 'PySide' env_api = os.environ.get('QT_API', 'pyqt') if '--pyside' in sys.argv: variant = 'PySide' elif '--pyqt4' in sys.argv: variant = 'PyQt4' elif env_api == 'pyside': variant = 'PySide' elif env_api == 'pyqt': variant = 'PyQt4' else: variant = default_vari...
else: raise ImportError("Python Variant not specified") __all__ = [QtGui, QtCore, QtLoadUI, variant]
from PyQt4 import uic return uic.loadUi(uifile)
identifier_body
QtVariant.py
import sys import os default_variant = 'PySide' env_api = os.environ.get('QT_API', 'pyqt') if '--pyside' in sys.argv: variant = 'PySide' elif '--pyqt4' in sys.argv: variant = 'PyQt4' elif env_api == 'pyside': variant = 'PySide' elif env_api == 'pyqt': variant = 'PyQt4' else: variant = default_vari...
(uifile): from PySide import QtUiTools loader = QtUiTools.QUiLoader() uif = QtCore.QFile(uifile) uif.open(QtCore.QFile.ReadOnly) result = loader.load(uif) uif.close() return result elif variant == 'PyQt4': import sip api2_classes = [ 'QData', '...
QtLoadUI
identifier_name
QtVariant.py
import sys import os default_variant = 'PySide' env_api = os.environ.get('QT_API', 'pyqt') if '--pyside' in sys.argv: variant = 'PySide' elif '--pyqt4' in sys.argv: variant = 'PyQt4' elif env_api == 'pyside': variant = 'PySide' elif env_api == 'pyqt': variant = 'PyQt4' else:
if variant == 'PySide': from PySide import QtGui, QtCore # This will be passed on to new versions of matplotlib os.environ['QT_API'] = 'pyside' def QtLoadUI(uifile): from PySide import QtUiTools loader = QtUiTools.QUiLoader() uif = QtCore.QFile(uifile) uif.open(QtCore.Q...
variant = default_variant
conditional_block
indexes.py
# Copyright 2013 Donald Stufft # # 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, so...
class BaseMapping(object): SEARCH_LIMIT = 25 def __init__(self, index): self.index = index def get_mapping(self): raise NotImplementedError def get_indexable(self): raise NotImplementedError def extract_id(self, item): raise NotImplementedError def extrac...
_index = "warehouse" def __init__(self, models, config): self.models = models self.config = config self.es = Elasticsearch( hosts=self.config.hosts, **self.config.get("client_options", {}) ) self.types = AttributeDict() def register(self, type_)...
identifier_body
indexes.py
# Copyright 2013 Donald Stufft # # 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, so...
def update_alias(self, alias, index, keep_old=False): # Get the old index from ElasticSearch try: old_index = self.es.indices.get_alias(self._index).keys()[0] except TransportError as exc: if not exc.status_code == 404: raise old_index = ...
self.update_alias(self._index, index, keep_old=keep_old)
conditional_block
indexes.py
# Copyright 2013 Donald Stufft # # 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, so...
) def search(self, query): raise NotImplementedError
random_line_split
indexes.py
# Copyright 2013 Donald Stufft # # 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, so...
(self, query): raise NotImplementedError
search
identifier_name
__init__.py
# Copyright (c) 2014, Guillermo López-Anglada. Please see the AUTHORS file for details. # All rights reserved. Use of this source code is governed by a BSD-style # license that can be found in the LICENSE file.) from logging.handlers import RotatingFileHandler from os import path import logging import logging.config ...
file_name = self._file_name() if file_name: # FIXME: RotatingFileHandler does not rollover ever. if os.path.exists(file_name): try: os.uznlink(file_name) except: pass fileHandler = RotatingFileHan...
random_line_split
__init__.py
# Copyright (c) 2014, Guillermo López-Anglada. Please see the AUTHORS file for details. # All rights reserved. Use of this source code is governed by a BSD-style # license that can be found in the LICENSE file.) from logging.handlers import RotatingFileHandler from os import path import logging import logging.config ...
elif result == 'sublime-package': parent = path.dirname(start) if path.exists(path.join(path.dirname(parent), 'Packages')): return path.join(path.dirname(parent), 'Packages', '.logs') if path.dirname(start) == start: return ...
f os.path.exists(path.join(path.dirname(start), 'User')): return path.join(path.dirname(start), '.logs')
conditional_block
__init__.py
# Copyright (c) 2014, Guillermo López-Anglada. Please see the AUTHORS file for details. # All rights reserved. Use of this source code is governed by a BSD-style # license that can be found in the LICENSE file.) from logging.handlers import RotatingFileHandler from os import path import logging import logging.config ...
def debug(self, message, *args, **kwargs): pass def info(self, message, *args, **kwargs): pass def warn(self, message, *args, **kwargs): pass def warning(self, message, *args, **kwargs): pass def error(self, message, *args, **kwargs): pass def critic...
ass
identifier_body
__init__.py
# Copyright (c) 2014, Guillermo López-Anglada. Please see the AUTHORS file for details. # All rights reserved. Use of this source code is governed by a BSD-style # license that can be found in the LICENSE file.) from logging.handlers import RotatingFileHandler from os import path import logging import logging.config ...
self, message, *args, **kwargs): self.logger.info(message, *args, **kwargs) def warn(self, message, *args, **kwargs): self.logger.warning(message, *args, **kwargs) def warning(self, message, *args, **kwargs): self.logger.warning(message, *args, **kwargs) def error(self, message, *...
nfo(
identifier_name
text-list-control.component.ts
import { Component, OnInit, forwardRef } from '@angular/core'; import { ControlValueAccessor, NG_VALUE_ACCESSOR } from '@angular/forms'; @Component({ selector: 'app-text-list-control', templateUrl: './text-list-control.component.html', styleUrls: ['./text-list-control.component.scss'], providers: [{ provide: NG_...
} get textList(): string[] { return this.actuallTextList; } onChangeCallback: Function; constructor() { } ngOnInit() { } writeValue(val: string[]) { this.actuallTextList = val; } registerOnChange(fn: Function) { this.onChangeCallback = fn; } registerOnTouched() {} }
{ this.actuallTextList = list; }
conditional_block
text-list-control.component.ts
import { Component, OnInit, forwardRef } from '@angular/core'; import { ControlValueAccessor, NG_VALUE_ACCESSOR } from '@angular/forms'; @Component({ selector: 'app-text-list-control', templateUrl: './text-list-control.component.html', styleUrls: ['./text-list-control.component.scss'], providers: [{ provide: NG_...
registerOnChange(fn: Function) { this.onChangeCallback = fn; } registerOnTouched() {} }
{ this.actuallTextList = val; }
identifier_body
text-list-control.component.ts
import { Component, OnInit, forwardRef } from '@angular/core'; import { ControlValueAccessor, NG_VALUE_ACCESSOR } from '@angular/forms'; @Component({ selector: 'app-text-list-control', templateUrl: './text-list-control.component.html', styleUrls: ['./text-list-control.component.scss'], providers: [{ provide: NG_...
constructor() { } ngOnInit() { } writeValue(val: string[]) { this.actuallTextList = val; } registerOnChange(fn: Function) { this.onChangeCallback = fn; } registerOnTouched() {} }
return this.actuallTextList; } onChangeCallback: Function;
random_line_split
text-list-control.component.ts
import { Component, OnInit, forwardRef } from '@angular/core'; import { ControlValueAccessor, NG_VALUE_ACCESSOR } from '@angular/forms'; @Component({ selector: 'app-text-list-control', templateUrl: './text-list-control.component.html', styleUrls: ['./text-list-control.component.scss'], providers: [{ provide: NG_...
(fn: Function) { this.onChangeCallback = fn; } registerOnTouched() {} }
registerOnChange
identifier_name
zwave.py
"""Mock helpers for Z-Wave component.""" from pydispatch import dispatcher from tests.async_mock import MagicMock def value_changed(value): """Fire a value changed.""" dispatcher.send( MockNetwork.SIGNAL_VALUE_CHANGED, value=value, node=value.node, network=value.node._network,...
(node): """Fire a node changed.""" dispatcher.send(MockNetwork.SIGNAL_NODE, node=node, network=node._network) def notification(node_id, network=None): """Fire a notification.""" dispatcher.send( MockNetwork.SIGNAL_NOTIFICATION, args={"nodeId": node_id}, network=network ) class MockOption...
node_changed
identifier_name
zwave.py
"""Mock helpers for Z-Wave component.""" from pydispatch import dispatcher from tests.async_mock import MagicMock def value_changed(value): """Fire a value changed.""" dispatcher.send( MockNetwork.SIGNAL_VALUE_CHANGED, value=value, node=value.node, network=value.node._network,...
def __init__(self, options=None, *args, **kwargs): """Initialize a Z-Wave mock network.""" super().__init__() self.options = options self.state = MockNetwork.STATE_STOPPED class MockNode(MagicMock): """Mock Z-Wave node.""" def __init__( self, *, no...
STATE_READY = 10
random_line_split
zwave.py
"""Mock helpers for Z-Wave component.""" from pydispatch import dispatcher from tests.async_mock import MagicMock def value_changed(value): """Fire a value changed.""" dispatcher.send( MockNetwork.SIGNAL_VALUE_CHANGED, value=value, node=value.node, network=value.node._network,...
class MockValue(MagicMock): """Mock Z-Wave value.""" _mock_value_id = 1234 def __init__( self, *, label="Mock Value", node=None, instance=0, index=0, value_id=None, **kwargs, ): """Initialize a Z-Wave mock value.""" sup...
"""Mock Z-Wave node.""" def __init__( self, *, node_id=567, name="Mock Node", manufacturer_id="ABCD", product_id="123", product_type="678", command_classes=None, can_wake_up_value=True, manufacturer_name="Test Manufacturer", pr...
identifier_body
zwave.py
"""Mock helpers for Z-Wave component.""" from pydispatch import dispatcher from tests.async_mock import MagicMock def value_changed(value): """Fire a value changed.""" dispatcher.send( MockNetwork.SIGNAL_VALUE_CHANGED, value=value, node=value.node, network=value.node._network,...
def has_command_class(self, command_class): """Test if mock has a command class.""" return command_class in self._command_classes def get_battery_level(self): """Return mock battery level.""" return 42 def can_wake_up(self): """Return whether the node can wake up....
setattr(self, attr_name, kwargs[attr_name])
conditional_block
client.py
import json from autobahn.twisted.websocket import WebSocketClientProtocol, WebSocketClientFactory class SocketClientProtocol(WebSocketClientProtocol): def emit(self, event_name, **kwargs): payload = self._format_outbound_data(event_name, **kwargs) self.sendMessage(payload) def _format_out...
(WebSocketClientFactory): protocol = SocketClientProtocol def __init__(self, *args, **kwargs): WebSocketClientFactory.__init__(self, *args, **kwargs) self.callbacks = {} self.register_callbacks() def register_callbacks(self): pass def on(self, event_name, callback): ...
BaseSocketClientFactory
identifier_name
client.py
import json from autobahn.twisted.websocket import WebSocketClientProtocol, WebSocketClientFactory class SocketClientProtocol(WebSocketClientProtocol): def emit(self, event_name, **kwargs): payload = self._format_outbound_data(event_name, **kwargs) self.sendMessage(payload) def _format_out...
def parse_message(self, message): payload = json.loads(message) if 'event' in payload: output = payload return output
event = payload.pop('event') self.fire_callback(client, event, **payload)
conditional_block
client.py
import json from autobahn.twisted.websocket import WebSocketClientProtocol, WebSocketClientFactory class SocketClientProtocol(WebSocketClientProtocol): def emit(self, event_name, **kwargs): payload = self._format_outbound_data(event_name, **kwargs) self.sendMessage(payload) def _format_out...
protocol = SocketClientProtocol def __init__(self, *args, **kwargs): WebSocketClientFactory.__init__(self, *args, **kwargs) self.callbacks = {} self.register_callbacks() def register_callbacks(self): pass def on(self, event_name, callback): self.callbacks[event_na...
identifier_body
client.py
import json from autobahn.twisted.websocket import WebSocketClientProtocol, WebSocketClientFactory
class SocketClientProtocol(WebSocketClientProtocol): def emit(self, event_name, **kwargs): payload = self._format_outbound_data(event_name, **kwargs) self.sendMessage(payload) def _format_outbound_data(self, event, **kwargs): """ Format outbound message as JSON """ message =...
random_line_split
oop_utils.rs
use super::Universe; use super::oop::*; use ast::sexpr::SExpr; use std::fmt::{self, Formatter, Display}; // Format impl unsafe fn fmt_oop(oop: Oop, u: &Universe, fmt: &mut Formatter) -> fmt::Result { if oop == NULL_OOP { write!(fmt, "<null>")?; } else if Singleton::is_singleton(oop) { write!(...
else if u.oop_is_closure(oop) { let mb = MutBox::from_raw(oop); write!(fmt, "<Box {} @{:#x}>", FmtOop(mb.value(), u), oop)?; } else if u.oop_is_ooparray(oop) { let arr = OopArray::from_raw(oop); write!(fmt, "[")?; for (i, oop) in arr.content().iter().enumerate() { ...
{ let clo = Closure::from_raw(oop); write!(fmt, "<Closure {} @{:#x}>", clo.info().name(), oop)?; }
conditional_block
oop_utils.rs
use super::Universe; use super::oop::*; use ast::sexpr::SExpr; use std::fmt::{self, Formatter, Display}; // Format impl unsafe fn fmt_oop(oop: Oop, u: &Universe, fmt: &mut Formatter) -> fmt::Result { if oop == NULL_OOP { write!(fmt, "<null>")?; } else if Singleton::is_singleton(oop) { write!(...
(_oop: Handle<Closure>, _u: &Universe) -> SExpr { panic!("oop_to_sexpr: not implemenetd") }
oop_to_sexpr
identifier_name
oop_utils.rs
use super::Universe; use super::oop::*; use ast::sexpr::SExpr; use std::fmt::{self, Formatter, Display}; // Format impl unsafe fn fmt_oop(oop: Oop, u: &Universe, fmt: &mut Formatter) -> fmt::Result { if oop == NULL_OOP { write!(fmt, "<null>")?; } else if Singleton::is_singleton(oop) { write!(...
panic!("oop_to_sexpr: not implemenetd") }
} pub fn oop_to_sexpr(_oop: Handle<Closure>, _u: &Universe) -> SExpr {
random_line_split
i2c_lcd.py
#!/usr/bin/env python import time import smbus BUS = smbus.SMBus(1) def write_word(addr, data): global BLEN temp = data if BLEN == 1: temp |= 0x08 else: temp &= 0xF7 BUS.write_byte(addr ,temp) def send_command(comm): # Send bit7-4 firstly buf = comm & 0xF0 buf |= 0x04 # RS = 0, RW = 0, EN ...
def init(addr, bl): # global BUS # BUS = smbus.SMBus(1) global LCD_ADDR global BLEN LCD_ADDR = addr BLEN = bl try: send_command(0x33) # Must initialize to 8-line mode at first time.sleep(0.005) send_command(0x32) # Then initialize to 4-line mode time.sleep(0.005) send_command(0x28) # 2 Lines & 5*7 dots...
buf = data & 0xF0 buf |= 0x05 # RS = 1, RW = 0, EN = 1 write_word(LCD_ADDR ,buf) time.sleep(0.002) buf &= 0xFB # Make EN = 0 write_word(LCD_ADDR ,buf) # Send bit3-0 secondly buf = (data & 0x0F) << 4 buf |= 0x05 # RS = 1, RW = 0, EN = 1 write_word(LCD_ADDR ,buf) time....
identifier_body
i2c_lcd.py
#!/usr/bin/env python import time import smbus BUS = smbus.SMBus(1) def write_word(addr, data): global BLEN temp = data if BLEN == 1: temp |= 0x08 else: temp &= 0xF7 BUS.write_byte(addr ,temp) def send_command(comm): # Send bit7-4 firstly buf = comm & 0xF0 buf |= 0x04 # RS = 0, RW = 0, EN ...
(data): # Send bit7-4 firstly buf = data & 0xF0 buf |= 0x05 # RS = 1, RW = 0, EN = 1 write_word(LCD_ADDR ,buf) time.sleep(0.002) buf &= 0xFB # Make EN = 0 write_word(LCD_ADDR ,buf) # Send bit3-0 secondly buf = (data & 0x0F) << 4 buf |= 0x05 # RS = 1, RW = 0, EN = 1 ...
send_data
identifier_name
i2c_lcd.py
#!/usr/bin/env python import time import smbus BUS = smbus.SMBus(1) def write_word(addr, data): global BLEN temp = data if BLEN == 1: temp |= 0x08 else: temp &= 0xF7 BUS.write_byte(addr ,temp) def send_command(comm): # Send bit7-4 firstly buf = comm & 0xF0 buf |= 0x04 # RS = 0, RW = 0, EN ...
write_word(LCD_ADDR ,buf) time.sleep(0.002) buf &= 0xFB # Make EN = 0 write_word(LCD_ADDR ,buf) def send_data(data): # Send bit7-4 firstly buf = data & 0xF0 buf |= 0x05 # RS = 1, RW = 0, EN = 1 write_word(LCD_ADDR ,buf) time.sleep(0.002) buf &= 0xFB # Make EN = 0 wr...
write_word(LCD_ADDR ,buf) # Send bit3-0 secondly buf = (comm & 0x0F) << 4 buf |= 0x04 # RS = 0, RW = 0, EN = 1
random_line_split
i2c_lcd.py
#!/usr/bin/env python import time import smbus BUS = smbus.SMBus(1) def write_word(addr, data): global BLEN temp = data if BLEN == 1: temp |= 0x08 else: temp &= 0xF7 BUS.write_byte(addr ,temp) def send_command(comm): # Send bit7-4 firstly buf = comm & 0xF0 buf |= 0x04 # RS = 0, RW = 0, EN ...
def clear(): send_command(0x01) # Clear Screen def openlight(): # Enable the backlight BUS.write_byte(0x27,0x08) BUS.close() def write(x, y, str): if x < 0: x = 0 if x > 15: x = 15 if y <0: y = 0 if y > 1: y = 1 # Move cursor addr = 0x80 + 0x40 * y + x send_command(addr) for chr in str: send...
return True
conditional_block
makepot.js
/* * grunt-wp-i18n * https://github.com/cedaro/grunt-wp-i18n * * Copyright (c) 2014 Cedaro, LLC * Licensed under the MIT license. */ 'use strict'; module.exports = function( grunt ) { var _ = require( 'underscore' ), gettext = require( 'gettext-parser' ), path = require( 'path' ), pkg = r...
// Use the Text Domain header or project folder name // for the pot file if it hasn't been set. if ( '' === o.potFilename ) { o.potFilename = wp.getHeader( 'Text Domain', o.mainFile ) + '.pot' || wp.slugify() + '.pot'; } o.domainPath = _.ltrim( o.domainPath, [ '/', '\\' ] ); o.i18nToolsPath =...
{ o.domainPath = wp.getHeader( 'Domain Path', o.mainFile ); }
conditional_block
makepot.js
/* * grunt-wp-i18n * https://github.com/cedaro/grunt-wp-i18n * * Copyright (c) 2014 Cedaro, LLC * Licensed under the MIT license. */ 'use strict'; module.exports = function( grunt ) { var _ = require( 'underscore' ), gettext = require( 'gettext-parser' ), path = require( 'path' ), pkg = r...
pattern = /# <!=([\s\S]+?)=!>/; if ( '' === o.potComments && ( matches = pot.match( pattern ) ) ) { o.potComments = matches[1]; } o.potComments = '# ' + o.potComments.replace( /\n(# )?/g, '\n# ' ).replace( '{year}', new Date().getFullYear() ); pot = pot.replace( pattern, o.potComments ); ...
// Update the comments header.
random_line_split
resource.js
/* global phantom, exports, require, console */ (function () { 'use strict'; exports.resolveUrl = function (url, verbose) { var fs = require('fs'); // assume http if no protocol is specified // and we're not looking at a local file if (!url.match(/:\/\//)) { if (!fs.exists(url)) { u...
(testFx, onReady, timeOutMillis) { var maxtimeOutMillis = timeOutMillis ? timeOutMillis : 3000, //< Default Max Timout is 3s start = new Date().getTime(), condition = false, interval = setInterval(function() { if ( (new Date().getTime() - start < maxtimeOutMillis) && !condition ) { ...
politelyWait
identifier_name
resource.js
/* global phantom, exports, require, console */ (function () { 'use strict'; exports.resolveUrl = function (url, verbose) { var fs = require('fs'); // assume http if no protocol is specified // and we're not looking at a local file if (!url.match(/:\/\//)) { if (!fs.exists(url)) { u...
page.injectJs('lib/obj.js'); page.injectJs('lib/css.js'); page.onConsoleMessage = function (msg) { console.log(msg); }; page.evaluate(function () { /* global $ */ if(window.fullyLoaded !== true) { // do not check twice window.fullyLoade...
{ page.injectJs('vendor/underscore-1.4.2.js'); }
conditional_block
resource.js
/* global phantom, exports, require, console */ (function () { 'use strict'; exports.resolveUrl = function (url, verbose) { var fs = require('fs'); // assume http if no protocol is specified // and we're not looking at a local file if (!url.match(/:\/\//)) { if (!fs.exists(url)) { u...
// If not time-out yet and condition not yet fulfilled condition = testFx(); //< defensive code } else { if(!condition) { // If condition still not fulfilled (timeout but condition is 'false') // then just go ahead, we gave it some time onReady()...
if ( (new Date().getTime() - start < maxtimeOutMillis) && !condition ) {
random_line_split
resource.js
/* global phantom, exports, require, console */ (function () { 'use strict'; exports.resolveUrl = function (url, verbose) { var fs = require('fs'); // assume http if no protocol is specified // and we're not looking at a local file if (!url.match(/:\/\//)) { if (!fs.exists(url)) { u...
}());
{ var maxtimeOutMillis = timeOutMillis ? timeOutMillis : 3000, //< Default Max Timout is 3s start = new Date().getTime(), condition = false, interval = setInterval(function() { if ( (new Date().getTime() - start < maxtimeOutMillis) && !condition ) { // If not time-out yet and con...
identifier_body
main.rs
extern crate crypto; extern crate hyper; extern crate rustc_serialize; extern crate rand; mod hmac_sha1; use hyper::server::{Server, Request, Response}; use hyper::status::StatusCode; use hyper::net::Fresh; use hyper::uri::RequestUri::AbsolutePath; const HOST: &'static str = "localhost:9000"; const DELAY: u32 = 1; ...
#[cfg(test)] mod tests { #[test] #[ignore] fn insecure_compare() { assert!(super::insecure_compare(b"yellow submarine", b"yellow submarine"), "should have been equal"); assert!(!super::insecure_compare(b"yellow submarine", b"yellow_submarine"), "should have been unequal"...
} true }
random_line_split
main.rs
extern crate crypto; extern crate hyper; extern crate rustc_serialize; extern crate rand; mod hmac_sha1; use hyper::server::{Server, Request, Response}; use hyper::status::StatusCode; use hyper::net::Fresh; use hyper::uri::RequestUri::AbsolutePath; const HOST: &'static str = "localhost:9000"; const DELAY: u32 = 1; ...
, } } fn check_signature(key: &[u8], filename: &str, signature: &str) -> StatusCode { use rustc_serialize::hex::FromHex; let parsed_signature = match signature.from_hex() { Ok(sig) => sig, _ => return StatusCode::BadRequest, }; let file_hash = match file_hmac(key, filename) { ...
{}
conditional_block
main.rs
extern crate crypto; extern crate hyper; extern crate rustc_serialize; extern crate rand; mod hmac_sha1; use hyper::server::{Server, Request, Response}; use hyper::status::StatusCode; use hyper::net::Fresh; use hyper::uri::RequestUri::AbsolutePath; const HOST: &'static str = "localhost:9000"; const DELAY: u32 = 1; ...
fn insecure_compare(first: &[u8], second: &[u8]) -> bool { for (x, y) in first.iter().zip(second.iter()) { if { x != y } { return false; } std::thread::sleep_ms(DELAY); } if first.len() != second.len() { //do this after step-by-step to preserve return false; //elemen...
{ use std::io::prelude::*; use std::fs::File; let mut file = try!(File::open(filename)); let mut s = String::new(); try!(file.read_to_string(&mut s)); Ok(hmac_sha1::hmac_sha1(key, &s.into_bytes()[..])) }
identifier_body
main.rs
extern crate crypto; extern crate hyper; extern crate rustc_serialize; extern crate rand; mod hmac_sha1; use hyper::server::{Server, Request, Response}; use hyper::status::StatusCode; use hyper::net::Fresh; use hyper::uri::RequestUri::AbsolutePath; const HOST: &'static str = "localhost:9000"; const DELAY: u32 = 1; ...
(first: &[u8], second: &[u8]) -> bool { for (x, y) in first.iter().zip(second.iter()) { if { x != y } { return false; } std::thread::sleep_ms(DELAY); } if first.len() != second.len() { //do this after step-by-step to preserve return false; //element-by-element comparis...
insecure_compare
identifier_name
math.rs
// Copyright 2021 TiKV Project Authors. Licensed under Apache-2.0. use std::sync::{ atomic::{AtomicU32, Ordering}, Mutex, }; struct MovingAvgU32Inner { buffer: Vec<u32>, current_index: usize, sum: u32, } pub struct MovingAvgU32 { protected: Mutex<MovingAvgU32Inner>, cached_avg: AtomicU32,...
() { use rand::Rng; let mut rng = rand::thread_rng(); let avg = MovingAvgU32::new(105); let mut external_sum = 0; for _ in 0..100 { let n: u32 = rng.gen_range(0..u32::MAX / 100); external_sum += n; avg.add(n); assert_eq!(avg.fetch(...
test_random_sequence
identifier_name
math.rs
// Copyright 2021 TiKV Project Authors. Licensed under Apache-2.0. use std::sync::{ atomic::{AtomicU32, Ordering}, Mutex, }; struct MovingAvgU32Inner { buffer: Vec<u32>, current_index: usize, sum: u32, } pub struct MovingAvgU32 { protected: Mutex<MovingAvgU32Inner>, cached_avg: AtomicU32,...
cached_avg: AtomicU32::new(0), } } pub fn add(&self, sample: u32) -> (u32, u32) { let mut inner = self.protected.lock().unwrap(); let current_index = (inner.current_index + 1) % inner.buffer.len(); inner.current_index = current_index; let old_avg = inner.sum ...
current_index: 0, sum: 0, }),
random_line_split
math.rs
// Copyright 2021 TiKV Project Authors. Licensed under Apache-2.0. use std::sync::{ atomic::{AtomicU32, Ordering}, Mutex, }; struct MovingAvgU32Inner { buffer: Vec<u32>, current_index: usize, sum: u32, } pub struct MovingAvgU32 { protected: Mutex<MovingAvgU32Inner>, cached_avg: AtomicU32,...
} } #[test] fn test_random_sequence() { use rand::Rng; let mut rng = rand::thread_rng(); let avg = MovingAvgU32::new(105); let mut external_sum = 0; for _ in 0..100 { let n: u32 = rng.gen_range(0..u32::MAX / 100); external_sum += n; ...
{ assert_eq!(avg.fetch(), (i * (i + 1) / 10)); }
conditional_block
math.rs
// Copyright 2021 TiKV Project Authors. Licensed under Apache-2.0. use std::sync::{ atomic::{AtomicU32, Ordering}, Mutex, }; struct MovingAvgU32Inner { buffer: Vec<u32>, current_index: usize, sum: u32, } pub struct MovingAvgU32 { protected: Mutex<MovingAvgU32Inner>, cached_avg: AtomicU32,...
}
{ use rand::Rng; let mut rng = rand::thread_rng(); let avg = MovingAvgU32::new(105); let mut external_sum = 0; for _ in 0..100 { let n: u32 = rng.gen_range(0..u32::MAX / 100); external_sum += n; avg.add(n); assert_eq!(avg.fetch(), ...
identifier_body
django.py
""" Django support. """ from __future__ import absolute_import import datetime from os import path from types import GeneratorType import decimal from django import VERSION if VERSION < (1, 8): from django.contrib.contenttypes.generic import ( GenericForeignKey, GenericRelation) else: from django.cont...
(self, field, fname=None, fake=False, kwargs=None): # noqa """ Make a fabric for field. :param field: A mixer field :param fname: Field name :param fake: Force fake data :return function: """ kwargs = {} if kwargs is None else kwargs fcls = type(field)...
make_fabric
identifier_name
django.py
""" Django support. """ from __future__ import absolute_import import datetime from os import path from types import GeneratorType import decimal from django import VERSION if VERSION < (1, 8): from django.contrib.contenttypes.generic import ( GenericForeignKey, GenericRelation) else: from django.cont...
else: from django.apps import apps for app in apps.all_models: for name, model in apps.all_models[app].items(): cls.models_cache[name] = model class TypeMixer(_.with_metaclass(TypeMixerMeta, BaseTypeMixer)): """ TypeMixer for Django. """ _...
for app_models in models.loading.cache.app_models.values(): for name, model in app_models.items(): cls.models_cache[name] = model
conditional_block
django.py
""" Django support. """ from __future__ import absolute_import import datetime from os import path from types import GeneratorType import decimal from django import VERSION if VERSION < (1, 8): from django.contrib.contenttypes.generic import ( GenericForeignKey, GenericRelation) else: from django.cont...
""" Associate Scheme with Django models. Cache Django models. :return mixer.backend.django.TypeMixer: A generated class. """ params['models_cache'] = dict() cls = super(TypeMixerMeta, mcs).__new__(mcs, name, bases, params) return cls def __load_cls(cls, cl...
def __new__(mcs, name, bases, params):
random_line_split
django.py
""" Django support. """ from __future__ import absolute_import import datetime from os import path from types import GeneratorType import decimal from django import VERSION if VERSION < (1, 8): from django.contrib.contenttypes.generic import ( GenericForeignKey, GenericRelation) else: from django.cont...
class TypeMixer(_.with_metaclass(TypeMixerMeta, BaseTypeMixer)): """ TypeMixer for Django. """ __metaclass__ = TypeMixerMeta factory = GenFactory def postprocess(self, target, postprocess_values): """ Fill postprocess_values. """ for name, deffered in postprocess_values: ...
""" Load django models from strings. """ def __new__(mcs, name, bases, params): """ Associate Scheme with Django models. Cache Django models. :return mixer.backend.django.TypeMixer: A generated class. """ params['models_cache'] = dict() cls = super(TypeMixerMeta, ...
identifier_body
form.component.ts
/** * Copyright 2017 The Mifos Initiative. * * 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 agr...
ngOnInit(): void { this.detailsStep.open(); } ngOnChanges(changes: SimpleChanges): void { if (changes.distribution) { this.form.reset({ mainAccountNumber: this.distribution.mainAccountNumber }); this.distribution.payrollAllocations.forEach(allocation => this.addAllocation(allo...
this.form = this.formBuilder.group({ mainAccountNumber: ['', [Validators.required]], payrollAllocations: this.initAllocations([]) }, { validator: accountUnique }); }
random_line_split
form.component.ts
/** * Copyright 2017 The Mifos Initiative. * * 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 agr...
(): AbstractControl[] { const allocations: FormArray = this.form.get('payrollAllocations') as FormArray; return allocations.controls; } }
allocations
identifier_name
form.component.ts
/** * Copyright 2017 The Mifos Initiative. * * 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 agr...
ngOnInit(): void { this.detailsStep.open(); } ngOnChanges(changes: SimpleChanges): void { if (changes.distribution) { this.form.reset({ mainAccountNumber: this.distribution.mainAccountNumber }); this.distribution.payrollAllocations.forEach(allocation => this.addAllocation(all...
{ this.form = this.formBuilder.group({ mainAccountNumber: ['', [Validators.required]], payrollAllocations: this.initAllocations([]) }, { validator: accountUnique }); }
identifier_body
form.component.ts
/** * Copyright 2017 The Mifos Initiative. * * 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 agr...
} save(): void { const distribution = Object.assign({}, this.distribution, { mainAccountNumber: this.form.get('mainAccountNumber').value, payrollAllocations: this.form.get('payrollAllocations').value }); this.onSave.emit(distribution); } cancel(): void { this.onCancel.emit(); }...
{ this.form.reset({ mainAccountNumber: this.distribution.mainAccountNumber }); this.distribution.payrollAllocations.forEach(allocation => this.addAllocation(allocation)); }
conditional_block
generator.py
# Copyright 2012 SINA Corporation # Copyright 2014 Cisco Systems, Inc. # 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/licens...
def main(): generate(sys.argv[1:]) if __name__ == '__main__': main()
opt_name, opt_default, opt_help = opt.dest, opt.default, opt.help if not opt_help: sys.stderr.write('WARNING: "%s" is missing help string.\n' % opt_name) opt_help = "" opt_type = None try: opt_type = OPTION_REGEX.search(str(type(opt))).group(0) except (ValueError, AttributeError)...
identifier_body
generator.py
# Copyright 2012 SINA Corporation # Copyright 2014 Cisco Systems, Inc. # 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/licens...
def generate(argv): parser = argparse.ArgumentParser( description='generate sample configuration file', ) parser.add_argument('-m', dest='modules', action='append') parser.add_argument('-l', dest='libraries', action='append') parser.add_argument('srcfiles', nargs='*') parsed_args = parse...
random_line_split