file_name large_stringlengths 4 140 | prefix large_stringlengths 0 12.1k | suffix large_stringlengths 0 12k | middle large_stringlengths 0 7.51k | fim_type large_stringclasses 4
values |
|---|---|---|---|---|
momentum_sgd_test.py | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
from caffe2.python import core
import caffe2.python.hypothesis_test_util as hu
import hypothesis
from hypothesis import given
import hypothesis.strategies as st
import n... | (
self, inputs, momentum, nesterov, lr, data_strategy, gc, dc):
w, grad, m = inputs
# Create an indexing array containing values which index into grad
indices = data_strategy.draw(
hu.tensor(dtype=np.int64,
elements=st.sampled_from(np.arange(grad.sh... | test_sparse_momentum_sgd | identifier_name |
momentum_sgd_test.py | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
from caffe2.python import core
import caffe2.python.hypothesis_test_util as hu
import hypothesis
from hypothesis import given
import hypothesis.strategies as st
import n... |
def sparse(grad, m, lr, param, i):
grad_new, m_new = momentum_sgd(grad, m[i], lr)
m[i] = m_new
param[i] -= grad_new
return (grad_new, m, param)
self.assertReferenceChecks(gc, op, [grad, m, lr, w, indices], sparse)
if __name__ == "__main__":
unitte... | lr = lr[0]
if not nesterov:
adjusted_gradient = lr * grad + momentum * m
return (adjusted_gradient, adjusted_gradient)
else:
m_new = momentum * m + lr * grad
return ((1 + momentum) * m_new - momentum * m, m_new) | identifier_body |
SVR_nuclear.py | def read_data(file_name):
return pd.read_csv(file_name)
def preprocess(data):
# Data Preprocessing
data['GDP_scaled']=preprocessing.scale(data['GDP'])
data['CLPRB_scaled']=preprocessing.scale(data['CLPRB'])
data['EMFDB_scaled']=preprocessing.scale(data['EMFDB'])
data['ENPRP_scaled']=preproces... | clf = SVR(kernel='sigmoid', C=90.0, epsilon=0.3).fit(X_train, y_train)
print(clf.score(X_test, y_test))
future_x = data[['GDP_scaled','CLPRB_scaled','EMFDB_scaled','ENPRP_scaled','NGMPB_scaled','PAPRB_scaled','PCP_scaled','ZNDX_scaled','OP_scaled','OP2_scaled']][-6:]
pred = pd.DataFrame(clf.predict(future_... | identifier_body | |
SVR_nuclear.py | def read_data(file_name):
return pd.read_csv(file_name) | def preprocess(data):
# Data Preprocessing
data['GDP_scaled']=preprocessing.scale(data['GDP'])
data['CLPRB_scaled']=preprocessing.scale(data['CLPRB'])
data['EMFDB_scaled']=preprocessing.scale(data['EMFDB'])
data['ENPRP_scaled']=preprocessing.scale(data['ENPRP'])
data['NGMPB_scaled']=preprocessi... | random_line_split | |
SVR_nuclear.py | def read_data(file_name):
return pd.read_csv(file_name)
def preprocess(data):
# Data Preprocessing
data['GDP_scaled']=preprocessing.scale(data['GDP'])
data['CLPRB_scaled']=preprocessing.scale(data['CLPRB'])
data['EMFDB_scaled']=preprocessing.scale(data['EMFDB'])
data['ENPRP_scaled']=preproces... | (data):
# Split data for train and test
all_x = data[['GDP_scaled','CLPRB_scaled','EMFDB_scaled','ENPRP_scaled','NGMPB_scaled','PAPRB_scaled','PCP_scaled','ZNDX_scaled','OP_scaled', 'OP2_scaled']][:55]
all_y = data[['NUETP']][:55]
return cross_validation.train_test_split(all_x, all_y, test_size=0.2, ran... | split_data | identifier_name |
parserTest.py | import unittest
from rmgpy.molecule.molecule import Molecule
from .parser import *
class ParserTest(unittest.TestCase):
def test_fromAugmentedInChI(self):
aug_inchi = 'InChI=1S/CH4/h1H4'
mol = fromAugmentedInChI(Molecule(), aug_inchi)
self.assertTrue(not mol.InChI == '')
aug_inc... |
def test_SingletMethylene(self):
adjlist = """
multiplicity 1
1 C u0 p1 c0 {2,S} {3,S}
2 H u0 p0 c0 {1,S}
3 H u0 p0 c0 {1,S}
"""
mol = Molecule().fromAdjacencyList(adjlist)
p_indices = [1]
reset_lone_pairs(mol, p_indices)
for at in mol.atoms:
if at.symbol == '... | smi = 'C'
mol = Molecule().fromSMILES(smi)
p_indices = []
reset_lone_pairs(mol, p_indices)
for at in mol.atoms:
self.assertEquals(at.lonePairs, 0) | identifier_body |
parserTest.py | import unittest
from rmgpy.molecule.molecule import Molecule
from .parser import *
class ParserTest(unittest.TestCase):
def test_fromAugmentedInChI(self):
aug_inchi = 'InChI=1S/CH4/h1H4'
mol = fromAugmentedInChI(Molecule(), aug_inchi)
self.assertTrue(not mol.InChI == '')
aug_inc... | (unittest.TestCase):
def test_Methane(self):
smi = 'C'
mol = Molecule().fromSMILES(smi)
p_indices = []
reset_lone_pairs(mol, p_indices)
for at in mol.atoms:
self.assertEquals(at.lonePairs, 0)
def test_SingletMethylene(self):
adjlist = """
multiplic... | ResetLonePairsTest | identifier_name |
parserTest.py | import unittest
from rmgpy.molecule.molecule import Molecule
from .parser import *
class ParserTest(unittest.TestCase):
def test_fromAugmentedInChI(self):
aug_inchi = 'InChI=1S/CH4/h1H4'
mol = fromAugmentedInChI(Molecule(), aug_inchi)
self.assertTrue(not mol.InChI == '')
aug_inc... | if connectedAtom.symbol != 'H':
bondType = str(rdkitmol.GetBondBetweenAtoms(rdAtomIndices[atom],rdAtomIndices[connectedAtom]).GetBondType())
rdkitBondOrder = bondOrderDict[bondType]
self.assertEqual(bond.order, rdkitBondOrder) ... | for connectedAtom, bond in atom.bonds.iteritems(): | random_line_split |
parserTest.py | import unittest
from rmgpy.molecule.molecule import Molecule
from .parser import *
class ParserTest(unittest.TestCase):
def test_fromAugmentedInChI(self):
aug_inchi = 'InChI=1S/CH4/h1H4'
mol = fromAugmentedInChI(Molecule(), aug_inchi)
self.assertTrue(not mol.InChI == '')
aug_inc... |
class ResetLonePairsTest(unittest.TestCase):
def test_Methane(self):
smi = 'C'
mol = Molecule().fromSMILES(smi)
p_indices = []
reset_lone_pairs(mol, p_indices)
for at in mol.atoms:
self.assertEquals(at.lonePairs, 0)
def test_SingletMethylene(self):
... | bondType = str(rdkitmol.GetBondBetweenAtoms(rdAtomIndices[atom],rdAtomIndices[connectedAtom]).GetBondType())
rdkitBondOrder = bondOrderDict[bondType]
self.assertEqual(bond.order, rdkitBondOrder) | conditional_block |
memcache.rs | use std::collections::hash_map::Entry;
use std::collections::HashMap;
use std::hash::Hash;
use std::sync::{Arc, Mutex};
pub struct MemCache<K, V>
where
K: Eq + Hash + Clone,
V: Clone + Send,
{
map: Mutex<HashMap<K, Arc<Mutex<Option<V>>>>>,
}
impl<K, V> Default for MemCache<K, V>
where
K: Eq + Hash + C... | () -> Self {
MemCache {
map: Mutex::new(HashMap::new()),
}
}
}
impl<K, V> MemCache<K, V>
where
K: Eq + Hash + Clone,
V: Clone + Send,
{
pub fn run_cached<F>(&self, key: K, worker: F) -> V
where
F: Fn(Option<V>) -> V,
{
// Get/create lock for cache ent... | default | identifier_name |
memcache.rs | use std::collections::hash_map::Entry;
use std::collections::HashMap;
use std::hash::Hash;
use std::sync::{Arc, Mutex};
pub struct MemCache<K, V>
where
K: Eq + Hash + Clone,
V: Clone + Send,
{
map: Mutex<HashMap<K, Arc<Mutex<Option<V>>>>>,
}
impl<K, V> Default for MemCache<K, V>
where
K: Eq + Hash + C... | let value = worker(entry.take());
*entry = Some(value.clone());
value
}
Err(e) => panic!("Mutex error: {}", e),
}
}
} | Ok(mut entry) => { | random_line_split |
version.rs | use std::str::CharIndices;
use std::iter::Peekable;
use std::cmp::Ordering;
use std::default::Default;
use quire::validate as V;
use quire::ast::{Ast, NullKind, Tag};
use quire::{Error as QuireError, ErrorCollector};
pub struct Version<'a>(pub &'a str);
pub struct Components<'a>(&'a str, Peekable<CharIndices<'a>>);
... | while let Some(&(_, x)) = self.1.peek() {
if x.is_alphanumeric() { break; }
self.1.next();
}
if let Some(&(start, x)) = self.1.peek() {
if x.is_numeric() {
while let Some(&(_, x)) = self.1.peek() {
if !x.is_numeric() { break... | type Item = Component<'a>;
fn next(&mut self) -> Option<Component<'a>> {
use self::Component::*; | random_line_split |
version.rs | use std::str::CharIndices;
use std::iter::Peekable;
use std::cmp::Ordering;
use std::default::Default;
use quire::validate as V;
use quire::ast::{Ast, NullKind, Tag};
use quire::{Error as QuireError, ErrorCollector};
pub struct Version<'a>(pub &'a str);
pub struct Components<'a>(&'a str, Peekable<CharIndices<'a>>);
... | () {
assert!(Version("v0.4.1-28-gfba00d7") > Version("v0.4.1"));
assert!(Version("v0.4.1-28-gfba00d7") > Version("v0.4.1-27-gtest"));
assert!(Version("v0.4.1-28-gfba00d7") < Version("v0.4.2"));
}
#[test]
fn test_version_cmp2() {
assert!(!(Version("v0.4.1-172-ge011471")
... | test_version_cmp | identifier_name |
version.rs | use std::str::CharIndices;
use std::iter::Peekable;
use std::cmp::Ordering;
use std::default::Default;
use quire::validate as V;
use quire::ast::{Ast, NullKind, Tag};
use quire::{Error as QuireError, ErrorCollector};
pub struct Version<'a>(pub &'a str);
pub struct Components<'a>(&'a str, Peekable<CharIndices<'a>>);
... |
pub fn current_version(mut self, version: String) -> MinimumVagga {
self.current_version = Some(version);
self
}
}
impl V::Validator for MinimumVagga {
fn default(&self, pos: V::Pos) -> Option<Ast> {
if self.optional {
Some(Ast::Null(pos.clone(), Tag::NonSpecific, NullK... | {
self.optional = true;
self
} | identifier_body |
add_to_a_path.py | """Script to display a collection of paths after inserting one new path
Usage:
add_to_a_path.py [-U] PATHS PATH
add_to_a_path.py [-U] (-s | -i INDEX ) PATHS PATH
Options:
-h, --help Show this help and exit
-v, --version Show version number and exit
-s, --start ... | def main():
"""Run the script"""
try:
args = parse_args()
return os.EX_OK if script(args) else not os.EX_OK
except (SystemExit, BdbQuit):
pass
return os.EX_OK
if __name__ == '__main__':
sys.exit(main()) | return True
| random_line_split |
add_to_a_path.py | """Script to display a collection of paths after inserting one new path
Usage:
add_to_a_path.py [-U] PATHS PATH
add_to_a_path.py [-U] (-s | -i INDEX ) PATHS PATH
Options:
-h, --help Show this help and exit
-v, --version Show version number and exit
-s, --start ... |
j = result.index(symbol)
if i != j:
del result[j]
result.insert(i, symbol)
return result
def get_arg_path(args):
path = args.path
if not path:
return ''
user_path = os.path.expanduser(path)
real_path = os.path.realpath(user_path)
if not os.path.isdir(real_path)... | result.insert(i, symbol)
return result | conditional_block |
add_to_a_path.py | """Script to display a collection of paths after inserting one new path
Usage:
add_to_a_path.py [-U] PATHS PATH
add_to_a_path.py [-U] (-s | -i INDEX ) PATHS PATH
Options:
-h, --help Show this help and exit
-v, --version Show version number and exit
-s, --start ... |
def get_paths(args):
symbol = args.symbol
paths_string = ''
if symbol in os.environ:
paths_string = os.environ[symbol]
elif os.path.pathsep in symbol:
paths_string = symbol
return split_paths(paths_string)
def script(args):
arg_path = get_arg_path(args)
paths = get_paths... | if not string:
return []
return [p for p in string.split(os.path.pathsep) if p] | identifier_body |
add_to_a_path.py | """Script to display a collection of paths after inserting one new path
Usage:
add_to_a_path.py [-U] PATHS PATH
add_to_a_path.py [-U] (-s | -i INDEX ) PATHS PATH
Options:
-h, --help Show this help and exit
-v, --version Show version number and exit
-s, --start ... | (args):
symbol = args.symbol
paths_string = ''
if symbol in os.environ:
paths_string = os.environ[symbol]
elif os.path.pathsep in symbol:
paths_string = symbol
return split_paths(paths_string)
def script(args):
arg_path = get_arg_path(args)
paths = get_paths(args)
if no... | get_paths | identifier_name |
print-tickets.js | $(document).ready(function(){
// removing some column headers when there is at least one product
if ( $('#lines tbody tr.product').length > 0 )
{
$('#lines').addClass('with-product');
$('body').addClass('with-product');
}
if ( $('#lines tbody tr.ticket').length > 0 )
{
$('#lines').addClass('with... | window.print();
// update the parent window's content
if ( window.opener != undefined && typeof window.opener.li === 'object' )
window.opener.li.initContent();
// print again
if ( $('#options #print-again').length > 0 )
window.location = $('#options #print-again a').prop('href');
// close
... | random_line_split | |
generate_usage.py | import simpy
import datetime
import random
from datetime import timedelta
end_of_time = 60*60*24*365
def working_hours(current_time):
return current_time.hour < 17 and current_time.hour > 8
def linear_increase(now, min_duration, max_duration):
time_left = end_of_time - now
return min_duration + max_duration * ... |
random_duration = lambda x,min_duration,max_duration : random.gauss((max_duration-min_duration)/2, (max_duration-min_duration)/(6))
increasing_duration = lambda x,min_duration,max_duration : linear_increase(x,min_duration,max_duration)
decreasing_duration = lambda x,min_duration,max_duration : linear_decrease(x,min_d... | return min_duration + max_duration * now / end_of_time | identifier_body |
generate_usage.py | import simpy
import datetime
import random
from datetime import timedelta
end_of_time = 60*60*24*365
def working_hours(current_time):
return current_time.hour < 17 and current_time.hour > 8
def linear_increase(now, min_duration, max_duration):
time_left = end_of_time - now
return min_duration + max_duration * ... | fields.append(row['at'].strftime("%Y-%m-%dT%H:%M:%S"))
f.write(str.join(fields) + "\n")
print("Data has been written to: data.csv") | f.write(str.join(fieldNames) + "\n")
for row in events:
fields = []
fields.append(row['name'])
fields.append(row['type']) | random_line_split |
generate_usage.py | import simpy
import datetime
import random
from datetime import timedelta
end_of_time = 60*60*24*365
def | (current_time):
return current_time.hour < 17 and current_time.hour > 8
def linear_increase(now, min_duration, max_duration):
time_left = end_of_time - now
return min_duration + max_duration * time_left / end_of_time
def linear_decrease(now, min_duration, max_duration):
return min_duration + max_duration * n... | working_hours | identifier_name |
generate_usage.py | import simpy
import datetime
import random
from datetime import timedelta
end_of_time = 60*60*24*365
def working_hours(current_time):
return current_time.hour < 17 and current_time.hour > 8
def linear_increase(now, min_duration, max_duration):
time_left = end_of_time - now
return min_duration + max_duration * ... |
env = simpy.Environment()
env.process(user(env, 'rhino', decreasing_duration, 60*10, 60*60*2))
env.process(user(env, 'cheetah', increasing_duration, 60*2, 60*45))
env.process(user(env, 'moose', random_duration, 50, 6000))
env.process(user(env, 'lion', increasing_duration, 60*5, 60*60*1))
env.process(user(env, 'mouse'... | current_time = start + timedelta(seconds=env.now)
if(working_hours(current_time)):
events.append({'name':name,'at':current_time, 'type':'tick'})
duration_in_s = duration(env.now, min_duration, max_duration)
while(duration_in_s < 0):
duration_in_s = duration(env.now, min_duration, max_duration)
yiel... | conditional_block |
graphics.spec.ts | import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { Component, OnChanges, DoCheck, OnInit, ViewChild, ElementRef, Input } from '@angular/core';
import { By } from '@angular/platform-browser';
import { DebugElement } from '@angular/core';
import { HImage } from './image';
import { Callba... | template: '<div><canvas [attr.id]="uuid" #renderCanvas class="canvas" [(attr.width)]="width" [(style.width.px)]="stwidth" [(attr.height)]="height" [(style.height.px)]="stheight" ></canvas></div>',
styleUrls: []
})
export class SurfaceComponent {
width: number;
height: number;
stwidth: number;
stheight: nu... | random_line_split | |
graphics.spec.ts | import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { Component, OnChanges, DoCheck, OnInit, ViewChild, ElementRef, Input } from '@angular/core';
import { By } from '@angular/platform-browser';
import { DebugElement } from '@angular/core';
import { HImage } from './image';
import { Callba... | () {
this.width = width;
this.height = height;
}
}
describe('graphics', () => {
let comp: SurfaceComponent;
let fixture: ComponentFixture<SurfaceComponent>;
let canvas: HTMLCanvasElement;
let img: HImage;
let context: CanvasRenderingContext2D;
beforeEach(() => {
TestBed.configureTestingModu... | constructor | identifier_name |
tokenization.ts | /*
* Copyright (C) 2017 TypeFox and others.
*
* 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
*/
/*------------------------------------------------... | tsTokenTypeTable[ts.TokenClass.Keyword] = 'keyword.ts';
tsTokenTypeTable[ts.TokenClass.Operator] = 'delimiter.ts';
tsTokenTypeTable[ts.TokenClass.Punctuation] = 'delimiter.ts';
tsTokenTypeTable[ts.TokenClass.NumberLiteral] = 'number.ts';
tsTokenTypeTable[ts.TokenClass.RegExpLiteral] = 'regexp.ts';
tsTokenTypeTable[ts.T... | tsBracketTypeTable[']'.charCodeAt(0)] = 'delimiter.array.ts';
var tsTokenTypeTable: INumberStringDictionary = Object.create(null);
tsTokenTypeTable[ts.TokenClass.Identifier] = 'identifier.ts'; | random_line_split |
tokenization.ts | /*
* Copyright (C) 2017 TypeFox and others.
*
* 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
*/
/*------------------------------------------------... | (deltaOffset: number, line: string, appendFn: (startIndex: number, type: string) => void): boolean {
if (line.indexOf('#!') === 0) {
appendFn(deltaOffset, 'comment.shebang');
return true;
}
return false;
}
| checkSheBang | identifier_name |
tokenization.ts | /*
* Copyright (C) 2017 TypeFox and others.
*
* 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
*/
/*------------------------------------------------... | if (!isTypeScript && checkSheBang(0, text, appendFn)) {
return ret;
}
var result = classifier.getClassificationsForLine(text, state.eolState, true),
offset = 0;
ret.endState.eolState = result.finalLexState;
ret.endState.inJsDocComment = result.finalLexState === ts.EndOfLineState.InMultiLineCommentTrivia && (... | {
// Create result early and fill in tokens
var ret = {
tokens: <monaco.languages.IToken[]>[],
endState: new State(state.language, ts.EndOfLineState.None, false)
};
function appendFn(startIndex: number, type: string): void {
if (ret.tokens.length === 0 || ret.tokens[ret.tokens.length - 1].scopes !== type) {... | identifier_body |
tokenization.ts | /*
* Copyright (C) 2017 TypeFox and others.
*
* 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
*/
/*------------------------------------------------... |
if (this.eolState !== (<State>other).eolState) {
return false;
}
if (this.inJsDocComment !== (<State>other).inJsDocComment) {
return false;
}
return true;
}
}
function tokenize(bracketTypeTable: { [i: number]: string }, tokenTypeTable: { [i: number]: string },
classifier: /*ts.Classifier*/ any, stat... | {
return false;
} | conditional_block |
workspace.routes.ts | import {WorkspaceComponent} from './workspace.component';
import {PageNotFoundComponent} from '../not-found.component';
export const workspaceRoutes = [
{
path: '',
component: WorkspaceComponent,
children: [
{
path: '', redirectTo: 'data-table', pathMatch: 'full' | {
path: 'data-table',
loadChildren: '../data-table/data-table.module#MyDataTableModule',
data: {preload: true}
},
{
path: 'editor',
loadChildren: '../editor/editor.module#EditorModule',
data: {preload: true}
},
{
path: 'collection',
... | }, | random_line_split |
sqs_transport.py | # -*- coding: utf-8 -*-
import boto.sqs
import uuid
from beaver.transports.base_transport import BaseTransport
from beaver.transports.exception import TransportException
class SqsTransport(BaseTransport):
def __init__(self, beaver_config, logger=None):
super(SqsTransport, self).__init__(beaver_config, l... | if len(message_batch) > 0:
self._logger.debug('Flushing last {0} messages to SQS queue'.format(len(message_batch)))
self._send_message_batch(message_batch)
return True
def _send_message_batch(self, message_batch):
try:
result = self._queue.write_batch(mes... | if len(message_batch) == 10: # SQS can only handle up to 10 messages in batch send
self._logger.debug('Flushing 10 messages to SQS queue')
self._send_message_batch(message_batch)
message_batch = []
| random_line_split |
sqs_transport.py | # -*- coding: utf-8 -*-
import boto.sqs
import uuid
from beaver.transports.base_transport import BaseTransport
from beaver.transports.exception import TransportException
class SqsTransport(BaseTransport):
def __init__(self, beaver_config, logger=None):
super(SqsTransport, self).__init__(beaver_config, l... |
except Exception, e:
self._logger.exception('Exception occurred sending batch to SQS queue')
raise TransportException(e.message)
def interrupt(self):
return True
def unhandled(self):
return True
| self._logger.error('Error occurred sending messages to SQS queue {0}. result: {1}'.format(
self._queue_name, result))
raise TransportException('Error occurred sending message to queue {0}'.format(self._queue_name)) | conditional_block |
sqs_transport.py | # -*- coding: utf-8 -*-
import boto.sqs
import uuid
from beaver.transports.base_transport import BaseTransport
from beaver.transports.exception import TransportException
class SqsTransport(BaseTransport):
def __init__(self, beaver_config, logger=None):
super(SqsTransport, self).__init__(beaver_config, l... |
def _send_message_batch(self, message_batch):
try:
result = self._queue.write_batch(message_batch)
if not result:
self._logger.error('Error occurred sending messages to SQS queue {0}. result: {1}'.format(
self._queue_name, result))
... | timestamp = self.get_timestamp(**kwargs)
if kwargs.get('timestamp', False):
del kwargs['timestamp']
message_batch = []
for line in lines:
message_batch.append((uuid.uuid4(), self.format(filename, line, timestamp, **kwargs), 0))
if len(message_batch) == 10: #... | identifier_body |
sqs_transport.py | # -*- coding: utf-8 -*-
import boto.sqs
import uuid
from beaver.transports.base_transport import BaseTransport
from beaver.transports.exception import TransportException
class | (BaseTransport):
def __init__(self, beaver_config, logger=None):
super(SqsTransport, self).__init__(beaver_config, logger=logger)
self._access_key = beaver_config.get('sqs_aws_access_key')
self._secret_key = beaver_config.get('sqs_aws_secret_key')
self._region = beaver_config.get('... | SqsTransport | identifier_name |
dispatcher.rs | ::{authority_addr, host_addr},
};
pub struct HttpDispatcher {
context: Arc<ServiceContext>,
req: Request<Body>,
balancer: PingBalancer,
client_addr: SocketAddr,
bypass_client: BypassHttpClient,
proxy_client_cache: Arc<ProxyClientCache>,
}
impl HttpDispatcher {
pub fn new(
context: ... | (mut self) -> io::Result<Response<Body>> {
trace!("request {} {:?}", self.client_addr, self.req);
// Parse URI
//
// Proxy request URI must contains a host
let host = match host_addr(self.req.uri()) {
None => {
if self.req.uri().authority().is_some() ... | dispatch | identifier_name |
dispatcher.rs |
use crate::local::{
context::ServiceContext,
loadbalancing::PingBalancer,
net::AutoProxyClientStream,
utils::establish_tcp_tunnel,
};
use super::{
client_cache::ProxyClientCache,
http_client::{BypassHttpClient, HttpClientEnum},
utils::{authority_addr, host_addr},
};
pub struct HttpDispatc... |
use shadowsocks::relay::socks5::Address; | random_line_split | |
dispatcher.rs | ::{authority_addr, host_addr},
};
pub struct HttpDispatcher {
context: Arc<ServiceContext>,
req: Request<Body>,
balancer: PingBalancer,
client_addr: SocketAddr,
bypass_client: BypassHttpClient,
proxy_client_cache: Arc<ProxyClientCache>,
}
impl HttpDispatcher {
pub fn new(
context: ... | else {
trace!("proxied {} -> {} {:?}", self.client_addr, host, self.req);
// Keep connections for clients in ServerScore::client
// client instance is kept for Keep-Alive connections
let server = self.balancer.best_tcp_server();
HttpClien... | {
trace!("bypassed {} -> {} {:?}", self.client_addr, host, self.req);
HttpClientEnum::Bypass(self.bypass_client)
} | conditional_block |
dispatcher.rs | ::{authority_addr, host_addr},
};
pub struct HttpDispatcher {
context: Arc<ServiceContext>,
req: Request<Body>,
balancer: PingBalancer,
client_addr: SocketAddr,
bypass_client: BypassHttpClient,
proxy_client_cache: Arc<ProxyClientCache>,
}
impl HttpDispatcher {
pub fn new(
context: ... |
pub async fn dispatch(mut self) -> io::Result<Response<Body>> {
trace!("request {} {:?}", self.client_addr, self.req);
// Parse URI
//
// Proxy request URI must contains a host
let host = match host_addr(self.req.uri()) {
None => {
if self.req.u... | {
HttpDispatcher {
context,
req,
balancer,
client_addr,
bypass_client,
proxy_client_cache,
}
} | identifier_body |
WebpackRunner.ts | import MultiStats = webpack.compilation.MultiStats;
const fs = require("fs-extra");
import {bgCyan, black, yellow, cyan} from "kleur";
import * as webpack from "webpack";
import {kaba} from "../@types/kaba";
import {Logger} from "../Logger";
const path = require("path");
export class WebpackRunner
{
private build... | if (this.buildConfig.js.watch)
{
this.resolveCallback = resolve;
}
let compiler = webpack(this.buildConfig.js.configs) as webpack.MultiCompiler;
if (this.buildConfig.js.watch)
{
this... |
this.logger.log("Launching webpack...");
const start = process.hrtime();
| random_line_split |
WebpackRunner.ts | import MultiStats = webpack.compilation.MultiStats;
const fs = require("fs-extra");
import {bgCyan, black, yellow, cyan} from "kleur";
import * as webpack from "webpack";
import {kaba} from "../@types/kaba";
import {Logger} from "../Logger";
const path = require("path");
export class WebpackRunner
{
private build... | (error: Error|null, stats: MultiStats, start?: [number, number]) : boolean
{
if (error)
{
this.logger.logError("webpack error", error);
this.logger.logWithDuration("webpack finished", process.hrtime(start));
return false;
}
// log webpack output
... | onCompilationFinished | identifier_name |
WebpackRunner.ts | import MultiStats = webpack.compilation.MultiStats;
const fs = require("fs-extra");
import {bgCyan, black, yellow, cyan} from "kleur";
import * as webpack from "webpack";
import {kaba} from "../@types/kaba";
import {Logger} from "../Logger";
const path = require("path");
export class WebpackRunner
{
private build... |
let baseDir = this.buildConfig.js.basePath;
const dependenciesFileName = `${this.buildConfig.js.javaScriptDependenciesFileName}.json`;
const dependenciesFilePath = path.join(baseDir, dependenciesFileName);
let entrypoints;
try
{
entrypoints = require(depen... | {
return;
} | conditional_block |
WebpackRunner.ts | import MultiStats = webpack.compilation.MultiStats;
const fs = require("fs-extra");
import {bgCyan, black, yellow, cyan} from "kleur";
import * as webpack from "webpack";
import {kaba} from "../@types/kaba";
import {Logger} from "../Logger";
const path = require("path");
export class WebpackRunner
{
private build... | stats.stats.forEach(
singleStats =>
{
for (const mapEntry of singleStats.compilation.entrypoints.entries())
{
let outputPath = path.relative(
baseDir,
singleStats.compilation.outputOptions... | {
if (!this.buildConfig.js)
{
return;
}
let baseDir = this.buildConfig.js.basePath;
const dependenciesFileName = `${this.buildConfig.js.javaScriptDependenciesFileName}.json`;
const dependenciesFilePath = path.join(baseDir, dependenciesFileName);
let ... | identifier_body |
m6809make.py | #!/usr/bin/python
# license:BSD-3-Clause
# copyright-holders:Olivier Galibert
import io
import re
import sys
# Initial state
state = 1
text = ""
dispatch_to_states = { "MAIN" : 0 }
states_to_dispatch = { 0 : "MAIN" }
def load_file(fname, lines):
path = fname.rpartition('/')[0]
if path != "":
path += '/'
try:
... |
elif next_line_is_dispatch_and_return:
# We are followed by a dispatch/return combo; identify the next dispatch
percent_pos = lines[count+1].find("%")
next_dispatch = lines[count+1][percent_pos+1:].strip("\t\n; ")
# If there is no state number associated with the next dispatch, make one
if next_dispa... | text += whitespace + goto_command
count += 1 # Skip the return | conditional_block |
m6809make.py | #!/usr/bin/python
# license:BSD-3-Clause
# copyright-holders:Olivier Galibert
import io
import re
import sys
# Initial state
state = 1
text = ""
dispatch_to_states = { "MAIN" : 0 }
states_to_dispatch = { 0 : "MAIN" }
def load_file(fname, lines):
path = fname.rpartition('/')[0]
if path != "":
path += '/'
try:
... | next_line_is_return = (count + 1 == len(lines)) or lines[count+1].strip() == "return;"
# Check to see if the next line is a dispatch followed by return
next_line_is_dispatch_and_return = (count + 1 < len(lines)) and re.match('([A-Za-z0-9\t ]+\:)*\s*\%', lines[count+1]) and lines[count+2].strip() == "return;"
if r... |
# Retrieve the whitespace
whitespace = line[:len(line) - len(line.lstrip())]
# Check to see if the next line is a return | random_line_split |
m6809make.py | #!/usr/bin/python
# license:BSD-3-Clause
# copyright-holders:Olivier Galibert
import io
import re
import sys
# Initial state
state = 1
text = ""
dispatch_to_states = { "MAIN" : 0 }
states_to_dispatch = { 0 : "MAIN" }
def | (fname, lines):
path = fname.rpartition('/')[0]
if path != "":
path += '/'
try:
f = io.open(fname, "r")
except Exception:
err = sys.exc_info()[1]
sys.stderr.write("Cannot read opcodes file %s [%s]\n" % (fname, err))
sys.exit(1)
rawlines = re.split('(\n|; *\n?)', f.read())
count = 0
while count < len(... | load_file | identifier_name |
m6809make.py | #!/usr/bin/python
# license:BSD-3-Clause
# copyright-holders:Olivier Galibert
import io
import re
import sys
# Initial state
state = 1
text = ""
dispatch_to_states = { "MAIN" : 0 }
states_to_dispatch = { 0 : "MAIN" }
def load_file(fname, lines):
| f.close()
# Get lines
lines = []
load_file(sys.argv[1], lines)
count = 0
while count < len(lines):
# Retrieve this line
line = lines[count]
# Retrieve the whitespace
whitespace = line[:len(line) - len(line.lstrip())]
# Check to see if the next line is a return
next_line_is_return = (count + 1 == len(lines))... | path = fname.rpartition('/')[0]
if path != "":
path += '/'
try:
f = io.open(fname, "r")
except Exception:
err = sys.exc_info()[1]
sys.stderr.write("Cannot read opcodes file %s [%s]\n" % (fname, err))
sys.exit(1)
rawlines = re.split('(\n|; *\n?)', f.read())
count = 0
while count < len(rawlines)-1:
li... | identifier_body |
transform.py | import math
from autoprotocol import UserError
from modules.utils import *
def transform(protocol, params):
# general parameters
constructs = params['constructs']
num_constructs = len(constructs)
plates = list(set([construct.container for construct in constructs]))
if len(plates) != 1:
|
# **** need to be able to check if plate is sealed to add run-chaining ****
mm_mult = 1.3
transformation_plate = protocol.ref("transformation_plate", None, "96-pcr", discard=True)
protocol.incubate(transformation_plate, "cold_20", "10:minute")
transformation_wells = transformation_plate.wells_fr... | raise UserError('You can only transform aliquots from one common container.') | conditional_block |
transform.py | import math
from autoprotocol import UserError
from modules.utils import *
def transform(protocol, params):
# general parameters
| new_group=det_new_group(i))
if well.name:
transformation_wells[i].set_name(well.name)
else:
transformation_wells[i].set_name('construct_%s' % (i+1))
# NEED to confirm second de-seal is working OR move to cover/uncover 96-flat
protocol.seal(trans... | constructs = params['constructs']
num_constructs = len(constructs)
plates = list(set([construct.container for construct in constructs]))
if len(plates) != 1:
raise UserError('You can only transform aliquots from one common container.')
# **** need to be able to check if plate is sealed to add r... | identifier_body |
transform.py | import math
from autoprotocol import UserError
from modules.utils import *
def transform(protocol, params):
# general parameters
constructs = params['constructs'] | num_constructs = len(constructs)
plates = list(set([construct.container for construct in constructs]))
if len(plates) != 1:
raise UserError('You can only transform aliquots from one common container.')
# **** need to be able to check if plate is sealed to add run-chaining ****
mm_mult = 1.3... | random_line_split | |
transform.py | import math
from autoprotocol import UserError
from modules.utils import *
def | (protocol, params):
# general parameters
constructs = params['constructs']
num_constructs = len(constructs)
plates = list(set([construct.container for construct in constructs]))
if len(plates) != 1:
raise UserError('You can only transform aliquots from one common container.')
# **** ne... | transform | identifier_name |
sumton.py | #!/usr/bin/env python3
"""
sumton.py : compute the sum of 0 through N
Copyright (C) Simon D. Levy 2016
This file is part of ISCPP.
ISCPP 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... | """
Example
"""
print(sumToN(5)) | conditional_block | |
sumton.py | #!/usr/bin/env python3
"""
sumton.py : compute the sum of 0 through N
Copyright (C) Simon D. Levy 2016
This file is part of ISCPP.
ISCPP 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... | 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 Lesser General Public License
along with this code. If not, see <http:#www.gnu.org/licenses/>.
"""
def su... | random_line_split | |
sumton.py | #!/usr/bin/env python3
"""
sumton.py : compute the sum of 0 through N
Copyright (C) Simon D. Levy 2016
This file is part of ISCPP.
ISCPP 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... |
if __name__ == "__main__":
"""
Example
"""
print(sumToN(5))
| res = 0
for k in range(0,n+1):
res = res + k
return res | identifier_body |
sumton.py | #!/usr/bin/env python3
"""
sumton.py : compute the sum of 0 through N
Copyright (C) Simon D. Levy 2016
This file is part of ISCPP.
ISCPP 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... | (n):
res = 0
for k in range(0,n+1):
res = res + k
return res
if __name__ == "__main__":
"""
Example
"""
print(sumToN(5))
| sumToN | identifier_name |
presence.service.ts | import {Injectable, EventEmitter} from "@angular/core";
import {of} from "rxjs/observable/of";
import {SSEService} from "../sse-module/see.service";
import {HttpClient} from "../http-module/http-client";
import {Observable} from "rxjs/Observable";
@Injectable()
export class PresenceService {
private cache = {};
pr... | this.changeUserStatus(userId, status);
}
return of(this.cache[userId]);
}
private randomStatusChange() {
// Random Key
let id = Object.keys(this.cache)[Math.floor(Math.random() * Object.keys(this.cache).length)];
if (id) {
let status = Math.random() >= 0.5;
this.changeUserSt... | if (!(userId in this.cache)) {
let status = Math.random() >= 0.5; | random_line_split |
presence.service.ts | import {Injectable, EventEmitter} from "@angular/core";
import {of} from "rxjs/observable/of";
import {SSEService} from "../sse-module/see.service";
import {HttpClient} from "../http-module/http-client";
import {Observable} from "rxjs/Observable";
@Injectable()
export class PresenceService {
private cache = {};
pr... |
setTimeout(() => this.randomStatusChange(), 2000);
}
private changeUserStatus(id, status) {
this.cache[id] = status;
this.userStatusChangeEE.emit({
id, status
});
}
}
| {
let status = Math.random() >= 0.5;
this.changeUserStatus(id, status);
console.info('changed online status for id=', id);
} | conditional_block |
presence.service.ts | import {Injectable, EventEmitter} from "@angular/core";
import {of} from "rxjs/observable/of";
import {SSEService} from "../sse-module/see.service";
import {HttpClient} from "../http-module/http-client";
import {Observable} from "rxjs/Observable";
@Injectable()
export class PresenceService {
private cache = {};
pr... | (id, status) {
this.cache[id] = status;
this.userStatusChangeEE.emit({
id, status
});
}
private getUserStatusInternal(userId): any {
if (userId in this.cache) {
return of(this.cache[userId]);
}
return this.http.post('/status/subscribe', {_id: userId})
.map(res => res.onli... | changeUserStatus | identifier_name |
presence.service.ts | import {Injectable, EventEmitter} from "@angular/core";
import {of} from "rxjs/observable/of";
import {SSEService} from "../sse-module/see.service";
import {HttpClient} from "../http-module/http-client";
import {Observable} from "rxjs/Observable";
@Injectable()
export class PresenceService {
private cache = {};
pr... |
private changeUserStatus(id, status) {
this.cache[id] = status;
this.userStatusChangeEE.emit({
id, status
});
}
private getUserStatusInternal(userId): any {
if (userId in this.cache) {
return of(this.cache[userId]);
}
return this.http.post('/status/subscribe', {_id: userId... | {
return this.getUserStatusInternal(userId);
} | identifier_body |
user.js | var mongoose = require('mongoose');
var bcrypt = require('bcrypt');
var validator = require('validator');
var SALT_WORK_FACTOR = 10;
var MAX_LOGIN_ATTEMPTS = 5;
var LOCK_TIME = 2 * 60 * 60 * 1000;
var UserSchema = mongoose.Schema({
email: { type: String, required: true, index: { unique: true } },
password: { type... | ;
// test for a matching password
user.comparePassword(password, function (err, isMatch) {
if (err) return callback(err);
// check if the password was a match
if (isMatch) {
// if there's no lock or failed attempts, just return the user
if (!user.loginAttempts && !user.lockUn... | {
// just increment login attempts if account is already locked
return user.incLoginAttempts(function (err) {
if (err) return callback(err);
return callback(null, null, reasons.MAX_ATTEMPTS);
});
} | conditional_block |
user.js | var mongoose = require('mongoose');
var bcrypt = require('bcrypt');
var validator = require('validator');
var SALT_WORK_FACTOR = 10;
var MAX_LOGIN_ATTEMPTS = 5;
var LOCK_TIME = 2 * 60 * 60 * 1000;
var UserSchema = mongoose.Schema({
email: { type: String, required: true, index: { unique: true } },
password: { type... | // lock the account if we've reached max attempts and it's not locked already
if (this.loginAttempts + 1 >= MAX_LOGIN_ATTEMPTS && !this.isLocked) {
updates.$set = { lockUntil: Date.now() + LOCK_TIME };
};
return this.update(updates, callback);
};
UserSchema.statics.getAuthenticated = function (email, passw... |
// otherwise increment
var updates = { $inc: { loginAttempts: 1 } }; | random_line_split |
text_run.rs | one at http://mozilla.org/MPL/2.0/. */
use font::{Font, RunMetrics, FontMetrics};
use servo_util::geometry::Au;
use servo_util::range::Range;
use servo_util::vec::{Comparator, FullBinarySearchMethods};
use std::slice::Items;
use sync::Arc;
use text::glyph::{CharIndex, GlyphStore};
use font::FontHandleMethods;
use pla... | };
// Create a glyph store for this slice if it's nonempty.
if can_break_before && byte_i > byte_last_boundary {
let slice = text.slice(byte_last_boundary, byte_i).to_string();
debug!("creating glyph store for slice {} (ws? {}), {} - {} in run {}",
... | _ => false
} | random_line_split |
text_run.rs | one at http://mozilla.org/MPL/2.0/. */
use font::{Font, RunMetrics, FontMetrics};
use servo_util::geometry::Au;
use servo_util::range::Range;
use servo_util::vec::{Comparator, FullBinarySearchMethods};
use std::slice::Items;
use sync::Arc;
use text::glyph::{CharIndex, GlyphStore};
use font::FontHandleMethods;
use pla... | (&self, range: &Range<CharIndex>) -> Au {
// TODO(Issue #199): alter advance direction for RTL
// TODO(Issue #98): using inter-char and inter-word spacing settings when measuring text
self.iter_slices_for_range(range)
.fold(Au(0), |advance, (glyphs, _, slice_range)| {
... | advance_for_range | identifier_name |
text_run.rs | at http://mozilla.org/MPL/2.0/. */
use font::{Font, RunMetrics, FontMetrics};
use servo_util::geometry::Au;
use servo_util::range::Range;
use servo_util::vec::{Comparator, FullBinarySearchMethods};
use std::slice::Items;
use sync::Arc;
use text::glyph::{CharIndex, GlyphStore};
use font::FontHandleMethods;
use platfor... |
}
} else {
match ch {
' ' | '\t' | '\n' => {
cur_slice_is_whitespace = true;
true
},
_ => false
}
};
// Create a glyph store f... | {
cur_slice_is_whitespace = false;
true
} | conditional_block |
pausemenu.rs | use std::fmt::{self, Debug, Formatter};
use std::path::Path;
use conrod::{self, Labelable, Positionable, Sizeable, Widget};
use piston;
use piston::window::Window;
use piston_window::{self, Context, G2d, G2dTexture};
use piston_window::texture::UpdateTexture;
use ::{GameState, Resources, StateTransition};
widget_ids... | (&mut self, event: &piston::input::Event,
resources: &mut Resources) -> StateTransition
{
// Convert the piston event to a conrod event.
let window_size = resources.window.size();
if let Some(ce) = conrod::backend::piston::event::convert(
event.clone(), window... | handle_event | identifier_name |
pausemenu.rs | use std::fmt::{self, Debug, Formatter};
use std::path::Path;
use conrod::{self, Labelable, Positionable, Sizeable, Widget};
use piston;
use piston::window::Window;
use piston_window::{self, Context, G2d, G2dTexture};
use piston_window::texture::UpdateTexture;
use ::{GameState, Resources, StateTransition};
widget_ids... |
}
impl PauseMenu {
pub fn new(resources: &mut Resources) -> PauseMenu {
let window_size = resources.window.size();
// Construct our `Ui`.
let mut ui = conrod::UiBuilder::new([window_size.width as f64,
window_size.height as f64])
.bu... | {
write!(f, "PauseMenu")
} | identifier_body |
pausemenu.rs | use std::fmt::{self, Debug, Formatter};
use std::path::Path;
use conrod::{self, Labelable, Positionable, Sizeable, Widget};
use piston;
use piston::window::Window;
use piston_window::{self, Context, G2d, G2dTexture};
use piston_window::texture::UpdateTexture;
use ::{GameState, Resources, StateTransition};
widget_ids... | else if conrod::widget::Button::new()
.down(15.0)
.w_h(80.0, 25.0)
.label("Quit")
.set(self.widget_ids.quit, ui)
.was_clicked()
{
StateTransition::Quit
} else {
StateTransition::Continue
}
}
fn update(&... | {
StateTransition::End
} | conditional_block |
pausemenu.rs | use std::fmt::{self, Debug, Formatter};
use std::path::Path;
use conrod::{self, Labelable, Positionable, Sizeable, Widget};
use piston;
use piston::window::Window;
use piston_window::{self, Context, G2d, G2dTexture};
use piston_window::texture::UpdateTexture;
use ::{GameState, Resources, StateTransition};
widget_ids... | {
StateTransition::End
} else if conrod::widget::Button::new()
.down(15.0)
.w_h(80.0, 25.0)
.label("Quit")
.set(self.widget_ids.quit, ui)
.was_clicked()
{
StateTransition::Quit
} else {
StateT... | .mid_top_of(self.widget_ids.canvas)
.w_h(80.0, 25.0)
.label("Resume")
.set(self.widget_ids.resume, ui)
.was_clicked() | random_line_split |
permissions_test.py | #!/usr/bin/env vpython
# Copyright 2020 The LUCI Authors. All rights reserved.
# Use of this source code is governed under the Apache License, Version 2.0
# that can be found in the LICENSE file.
import logging
import sys
import unittest
import test_env
test_env.setup_test_env()
from proto import realms_config_pb2
f... |
def test_permissions_only(self):
self.permission('luci.dev.p1')
self.permission('luci.dev.p2')
self.permission('luci.dev.p1') # redeclaration is ok
self.check(perms=['luci.dev.p1', 'luci.dev.p2'])
def test_bad_permission_name(self):
with self.assertRaises(ValueError):
self.permission('... | self.check([], {}) | identifier_body |
permissions_test.py | #!/usr/bin/env vpython
# Copyright 2020 The LUCI Authors. All rights reserved.
# Use of this source code is governed under the Apache License, Version 2.0
# that can be found in the LICENSE file.
import logging
import sys
import unittest
import test_env
test_env.setup_test_env()
from proto import realms_config_pb2
f... | (self):
self.check([], {})
def test_permissions_only(self):
self.permission('luci.dev.p1')
self.permission('luci.dev.p2')
self.permission('luci.dev.p1') # redeclaration is ok
self.check(perms=['luci.dev.p1', 'luci.dev.p2'])
def test_bad_permission_name(self):
with self.assertRaises(ValueE... | test_empty | identifier_name |
permissions_test.py | #!/usr/bin/env vpython
# Copyright 2020 The LUCI Authors. All rights reserved.
# Use of this source code is governed under the Apache License, Version 2.0
# that can be found in the LICENSE file.
import logging
import sys
import unittest
import test_env
test_env.setup_test_env()
from proto import realms_config_pb2
f... |
if __name__ == '__main__':
if '-v' in sys.argv:
unittest.TestCase.maxDiff = None
logging.basicConfig(level=logging.DEBUG)
else:
logging.basicConfig(level=logging.FATAL)
unittest.main()
| self.assertIsInstance(b, realms_config_pb2.Binding) | conditional_block |
permissions_test.py | #!/usr/bin/env vpython
# Copyright 2020 The LUCI Authors. All rights reserved.
# Use of this source code is governed under the Apache License, Version 2.0
# that can be found in the LICENSE file.
import logging
import sys
import unittest
import test_env
test_env.setup_test_env()
from proto import realms_config_pb2
f... | with self.assertRaises(ValueError):
self.permission('luci.dev.something.something')
def test_simple_role(self):
self.role('role/dev.a', [
self.permission('luci.dev.p1'),
self.permission('luci.dev.p2'),
])
self.check(
perms=['luci.dev.p1', 'luci.dev.p2'],
roles={'... |
def test_bad_permission_name(self):
with self.assertRaises(ValueError):
self.permission('luci.dev') | random_line_split |
karma.conf.js | module.exports = function(config) {
config.set({
basePath: '../../',
frameworks: ['jasmine', 'requirejs'],
files: [
{pattern: 'test/unit/require.conf.js', included: true},
{pattern: 'test/unit/tests/global.js', included: true},
{pattern: 'src/client/**/... | 'karma-ie-launcher'
],
reporters: ['coverage', 'html', 'progress'],
preprocessors: {
'src/client/component/**/*.js': ['coverage'],
'src/client/service/**/*.js': ['coverage']
},
coverageReporter: {
type: 'html',
dir: '... | 'karma-safari-launcher', | random_line_split |
emailform.js | emailForm = function() {
var remite = prompt("Introduzca correo de contacto: ");
document.getElementById("remite").value;
if (remite != '' && remite != null && nombre != '' && nombre != null && telefono != '' && telefono != null) {
itemsString = "";
esubtotal = 0;
egastos = 0;
etotal = 0;
for(... | document.body.appendChild(form);
me.empty();
form.submit();
document.body.removeChild(form);
if (p == null || p=='');
}
return;
}; | random_line_split | |
emailform.js | emailForm = function() {
var remite = prompt("Introduzca correo de contacto: ");
document.getElementById("remite").value;
if (remite != '' && remite != null && nombre != '' && nombre != null && telefono != '' && telefono != null) {
itemsString = "";
esubtotal = 0;
egastos = 0;
etotal = 0;
for(... | else {itemsString += "Gastos de envio = GRATIS\n";}
itemsString +="\nTOTAL: " + String(etotal) + me.currency + "\n\n" + "Remitente: " + remite;
itemsString +="\n\nNOMBRE: " + nombre + "\nTelefono: " + telefono;
itemsString +="\nDIRECCION: " + direccion;
itemsString +="\nCIUDAD/PAIS: " + codigo + " " + ciudad + " - " +... | {
itemsString += "Gastos de envio = " + gastos + " " + me.currency +"\n";
etotal += me.shippingCost;
} | conditional_block |
annotation_helper.js | cindent expandtab: */
/* Copyright 2014 Mozilla Foundation
*
* 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 a... | (item) {
var container = document.createElement('section');
var cstyle = container.style;
var width = item.rect[2] - item.rect[0];
var height = item.rect[3] - item.rect[1];
// Border
if (item.borderStyle.width > 0) {
// Border width
container.style.borderWidth = item.borderStyle.wid... | initContainer | identifier_name |
annotation_helper.js | cindent expandtab: */
/* Copyright 2014 Mozilla Foundation
*
* 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 a... |
var title = document.createElement('h1');
var text = document.createElement('p');
title.textContent = item.title;
if (!item.content && !item.title) {
content.setAttribute('hidden', true);
} else {
var e = document.createElement('span');
var lines = item.content.split(/(?:\r\n?|\... | {
var color = item.color;
// Enlighten the color (70%)
var BACKGROUND_ENLIGHT = 0.7;
var r = BACKGROUND_ENLIGHT * (255 - color[0]) + color[0];
var g = BACKGROUND_ENLIGHT * (255 - color[1]) + color[1];
var b = BACKGROUND_ENLIGHT * (255 - color[2]) + color[2];
content.style.back... | conditional_block |
annotation_helper.js | cindent expandtab: */
/* Copyright 2014 Mozilla Foundation
*
* 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 a... | return container;
}
function getHtmlElementForTextWidgetAnnotation(item, commonObjs) {
var element = document.createElement('div');
var width = item.rect[2] - item.rect[0];
var height = item.rect[3] - item.rect[1];
element.style.width = width + 'px';
element.style.height = height + 'px';
... | cstyle.height = height + 'px'; | random_line_split |
annotation_helper.js | cindent expandtab: */
/* Copyright 2014 Mozilla Foundation
*
* 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 a... |
return element;
}
function getHtmlElementForTextAnnotation(item) {
var rect = item.rect;
// sanity check because of OOo-generated PDFs
if ((rect[3] - rect[1]) < ANNOT_MIN_SIZE) {
rect[3] = rect[1] + ANNOT_MIN_SIZE;
}
if ((rect[2] - rect[0]) < ANNOT_MIN_SIZE) {
rect[2] = rect[... | {
var element = document.createElement('div');
var width = item.rect[2] - item.rect[0];
var height = item.rect[3] - item.rect[1];
element.style.width = width + 'px';
element.style.height = height + 'px';
element.style.display = 'table';
var content = document.createElement('div');
conte... | identifier_body |
parallel.rs | (n_workers);
pool.scoped(|pool_scope| {
let work = &work;
loop {
// recycle an old RecordSet sent back after use
let (mut data, mut out) = if let Ok(r) = empty_recv.recv() {
r
} else {
... | read_process_records_init | identifier_name | |
parallel.rs | where
D: Send,
E: Send,
O: Send,
{
empty_send: mpsc::SyncSender<(D, O)>,
done_recv: mpsc::Receiver<Option<Result<(D, O), E>>>,
current_recordset: (D, O),
}
impl<D, E, O> ParallelDataSets<D, E, O>
where
D: Send,
E: Send,
O: Send,
{
/// Returns a tuple of the next processed record... | {
read_process_recordsets_init(
reader_init,
n_workers,
queue_len,
|rset, out: &mut Vec<O>| {
let mut record_iter = rset.into_iter();
for mut d in (&mut record_iter).zip(out.iter_mut()) {
work(d.0, &mut d.1);
}
for recor... | identifier_body | |
parallel.rs | In real-world programs, this may be less of an issue because the
//! // returned result type is often known.
//! Ok::<_, fastq::Error>(())
//! }
//! ).expect("FASTQ reading error");
//! ```
use crate::core::{QualRecordPosition, SeqRecordPosition};
use crate::{fasta, fastq, fastx};
use std::sync::m... | W: Send + Sync + Fn($Record, &mut O),
F: FnMut($Record, &mut O) -> Option<Out>,
{
let out: Result<_, $Error> = $name_init( | random_line_split | |
test_address.py | """Address model tests."""
from core.models import Address
from core.factory import AddressFactory
from tests.utils import ModelTestCase
class AddressTest(ModelTestCase):
"""Test the Address model."""
model = Address
field_tests = {
'line1': {
'verbose_name': 'ligne 1',
'... |
def test_str(self):
expected = '3 Rue Joliot Curie, 91190 Gif-sur-Yvette, France'
self.assertEqual(expected, str(self.obj))
| cls.obj = AddressFactory.create(
line1='3 Rue Joliot Curie',
post_code='91190',
city='Gif-sur-Yvette',
) | identifier_body |
test_address.py | """Address model tests."""
from core.models import Address
from core.factory import AddressFactory
from tests.utils import ModelTestCase
class AddressTest(ModelTestCase):
"""Test the Address model."""
model = Address
field_tests = {
'line1': {
'verbose_name': 'ligne 1',
'... | (self):
expected = '3 Rue Joliot Curie, 91190 Gif-sur-Yvette, France'
self.assertEqual(expected, str(self.obj))
| test_str | identifier_name |
test_address.py | """Address model tests."""
from core.models import Address
from core.factory import AddressFactory
from tests.utils import ModelTestCase
class AddressTest(ModelTestCase):
"""Test the Address model."""
model = Address
field_tests = {
'line1': {
'verbose_name': 'ligne 1',
'... | }
@classmethod
def setUpTestData(cls):
cls.obj = AddressFactory.create(
line1='3 Rue Joliot Curie',
post_code='91190',
city='Gif-sur-Yvette',
)
def test_str(self):
expected = '3 Rue Joliot Curie, 91190 Gif-sur-Yvette, France'
self.ass... | random_line_split | |
hash.rs | //! Trait for hash functions.
use std::mem;
use std::num::Wrapping;
/// Hash function.
pub trait HashFun<K> {
/// Hash function.
fn hash(&self, &K) -> usize;
}
/// Hash function for pairs of `usize`, using the Tomas Wang hash.
#[derive(Clone, RustcEncodable, RustcDecodable)]
pub struct UintPairTWHash { unuse... |
tomas_wang_hash(key_from_pair(ia, ib))
}
}
/// Hash function for `usize`.
#[derive(Clone, RustcEncodable, RustcDecodable)]
pub struct UintTWHash { unused: usize } // FIXME: ICE if the struct is zero-sized
impl UintTWHash {
/// Creates a new UintTWHash.
pub fn new() -> UintTWHash {
UintTW... | {
mem::swap(&mut ia, &mut ib)
} | conditional_block |
hash.rs | //! Trait for hash functions.
use std::mem;
use std::num::Wrapping;
/// Hash function.
pub trait HashFun<K> {
/// Hash function.
fn hash(&self, &K) -> usize;
}
/// Hash function for pairs of `usize`, using the Tomas Wang hash.
#[derive(Clone, RustcEncodable, RustcDecodable)]
pub struct UintPairTWHash { unuse... | let mut ib = b;
if ia > ib {
mem::swap(&mut ia, &mut ib)
}
tomas_wang_hash(key_from_pair(ia, ib))
}
}
/// Hash function for `usize`.
#[derive(Clone, RustcEncodable, RustcDecodable)]
pub struct UintTWHash { unused: usize } // FIXME: ICE if the struct is zero-sized
impl... | random_line_split | |
hash.rs | //! Trait for hash functions.
use std::mem;
use std::num::Wrapping;
/// Hash function.
pub trait HashFun<K> {
/// Hash function.
fn hash(&self, &K) -> usize;
}
/// Hash function for pairs of `usize`, using the Tomas Wang hash.
#[derive(Clone, RustcEncodable, RustcDecodable)]
pub struct UintPairTWHash { unuse... |
}
/// Hash function for `usize`.
#[derive(Clone, RustcEncodable, RustcDecodable)]
pub struct UintTWHash { unused: usize } // FIXME: ICE if the struct is zero-sized
impl UintTWHash {
/// Creates a new UintTWHash.
pub fn new() -> UintTWHash {
UintTWHash { unused: 0 }
}
}
impl HashFun<usize> for Ui... | {
let mut ia = a;
let mut ib = b;
if ia > ib {
mem::swap(&mut ia, &mut ib)
}
tomas_wang_hash(key_from_pair(ia, ib))
} | identifier_body |
hash.rs | //! Trait for hash functions.
use std::mem;
use std::num::Wrapping;
/// Hash function.
pub trait HashFun<K> {
/// Hash function.
fn hash(&self, &K) -> usize;
}
/// Hash function for pairs of `usize`, using the Tomas Wang hash.
#[derive(Clone, RustcEncodable, RustcDecodable)]
pub struct UintPairTWHash { unuse... | (a: usize, b: usize) -> usize {
(a & 0xffffffff) | (b << 32)
}
// http://www.concentric.net/~Ttwang/tech/inthash.htm -- dead link!
// (this one works: http://naml.us/blog/tag/thomas-wang)
/// Tomas Wang integer hash function.
#[cfg(target_pointer_width = "64")] #[inline]
pub fn tomas_wang_hash(k: usize) -> usize {... | key_from_pair | identifier_name |
apple_ios_base.rs | // Copyright 2014 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 ... | &Armv7 => "armv7",
&Armv7s => "armv7s",
&Arm64 => "arm64",
&I386 => "i386",
&X86_64 => "x86_64"
}
}
}
pub fn get_sdk_root(sdk_name: &str) -> String {
let res = Command::new("xcrun")
.arg("--show-sdk-path")
... | impl Arch {
pub fn to_string(&self) -> &'static str {
match self { | random_line_split |
apple_ios_base.rs | // Copyright 2014 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 ... | {
TargetOptions {
cpu: target_cpu(arch),
dynamic_linking: false,
executables: true,
// Although there is an experimental implementation of LLVM which
// supports SS on armv7 it wasn't approved by Apple, see:
// http://lists.cs.uiuc.edu/pipermail/llvm-commits/Week-of-M... | identifier_body | |
apple_ios_base.rs | // Copyright 2014 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 ... | (arch: Arch) -> String {
match arch {
Armv7 => "cortex-a8", // iOS7 is supported on iPhone 4 and higher
Armv7s => "cortex-a9",
Arm64 => "cyclone",
I386 => "generic",
X86_64 => "x86-64",
}.to_string()
}
pub fn opts(arch: Arch) -> TargetOptions {
TargetOptions {
... | target_cpu | identifier_name |
app.js | import http from 'http' // HTTP Server
import express from 'express' // HTTP improvements
import bodyParser from 'body-parser' // Parse JSON
import cors from 'cors' // Cross-origin resource sharing
import blocked from 'blocked' // detect if a node event loop is blocked
import api from '~/api'
import config from '~/con... | })
requiredPgProviderInfo.forEach(info => {
if (config.providers[provider][info] === undefined && config.providers[provider].type === 'pg') {
throw new Error(`Provider ${provider} is missing ${info} information`)
}
})
})
export default app | random_line_split | |
app.js | import http from 'http' // HTTP Server
import express from 'express' // HTTP improvements
import bodyParser from 'body-parser' // Parse JSON
import cors from 'cors' // Cross-origin resource sharing
import blocked from 'blocked' // detect if a node event loop is blocked
import api from '~/api'
import config from '~/con... |
})
if (toBoolean(config.cors)) {
app.use(cors()) // https://github.com/expressjs/cors#simple-usage-enable-all-cors-requests
app.options('*', cors()) // https://github.com/expressjs/cors#enabling-cors-pre-flight
}
// logging middleware
app.use((req, res, next) => {
logger.verbose(`${new Date().toISOString()} ${r... | {
next(err)
} | conditional_block |
spinner.js | /* global PIXI */
import 'pixi.js'
class Spinner {
constructor (position, color, beat = 4, offset = 0, spinSpeed = 10, initialAngle = 0, width = 10, blur = 10) {
beat = beat * 7 / 4
this.blur = blur
this.beat = beat
this.offset = offset
this.spinSpeed = spinSpeed
this.gfx = new PIXI.Graphics(... |
}
export { Spinner }
| {
let time = (game.gametime + this.offset)
this.gfx.transform.rotation = time / this.spinSpeed
let amp = Math.sin(time * this.beat)
this.gfx.filters[0].blur = amp * this.blur + this.blur * 2
} | identifier_body |
spinner.js | /* global PIXI */
import 'pixi.js'
class Spinner {
| (position, color, beat = 4, offset = 0, spinSpeed = 10, initialAngle = 0, width = 10, blur = 10) {
beat = beat * 7 / 4
this.blur = blur
this.beat = beat
this.offset = offset
this.spinSpeed = spinSpeed
this.gfx = new PIXI.Graphics()
this.gfx.position.x = position[0]
this.gfx.position.y =... | constructor | identifier_name |
spinner.js | /* global PIXI */
import 'pixi.js'
class Spinner {
constructor (position, color, beat = 4, offset = 0, spinSpeed = 10, initialAngle = 0, width = 10, blur = 10) {
beat = beat * 7 / 4
this.blur = blur
this.beat = beat
this.offset = offset
this.spinSpeed = spinSpeed
this.gfx = new PIXI.Graphics(... | this.gfx.filters = [blurFilter]
this.gfx.blendMode = PIXI.BLEND_MODES.SCREEN
this.gfx.transform.rotation = initialAngle
}
pushGame (game) {
game.viewport.addChild(this.gfx)
}
popGame (game) {
game.viewport.removeChild(this.gfx)
}
update (game) {
let time = (game.gametime + this.of... | var blurFilter = new PIXI.filters.BlurFilter()
blurFilter.blur = 10 | random_line_split |
cache.module.spec.ts | import {} from 'jasmine';
import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { By } from '@angular/platform-browser';
import { DebugElement } from '@angular/core';
import { CacheComponent } from './cache.component';
import { CacheService } from './cache.service';
import { IonicStorageModu... |
describe('Cache read/write test', () => {
let comp: CacheComponent;
let fixture: ComponentFixture<CacheComponent>;
beforeEach(() => {
TestBed.configureTestingModule({
declarations: [
CacheComponent
],
providers: [
{ provide: CacheService, useClass: CacheService }
],
... | random_line_split | |
ocr.py | configData['purgeLog']
#Initialization...
print ("\n-----------------------= AMS Py =----------------------")
print ("Azure Media Analytics -OCR v1 Sample")
print ("for details see: https://azure.microsoft.com/en-us/documentation/articles/media-services-video-optical-character-recognition/")
print ("-----------------... | (message):
time_stamp = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
print (str(time_stamp) + ": " + message)
### get ams redirected url
response = azurerm.get_url(access_token)
if (response.status_code == 200):
ams_redirected_rest_endpoint = str(response.url)
else:
print_phas... | print_phase_message | identifier_name |
ocr.py | configData['purgeLog']
#Initialization...
print ("\n-----------------------= AMS Py =----------------------")
print ("Azure Media Analytics -OCR v1 Sample")
print ("for details see: https://azure.microsoft.com/en-us/documentation/articles/media-services-video-optical-character-recognition/")
print ("-----------------... |
### get ams redirected url
response = azurerm.get_url(access_token)
if (response.status_code == 200):
ams_redirected_rest_endpoint = str(response.url)
else:
print_phase_message("GET Status: " + str(response.status_code) + " - Getting Redirected URL ERROR." + str(response.content))
exit(1)
##... | time_stamp = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
print (str(time_stamp) + ": " + message) | identifier_body |
ocr.py | configData['purgeLog']
#Initialization...
print ("\n-----------------------= AMS Py =----------------------")
print ("Azure Media Analytics -OCR v1 Sample")
print ("for details see: https://azure.microsoft.com/en-us/documentation/articles/media-services-video-optical-character-recognition/")
print ("-----------------... |
#Basic Logging...
logging.basicConfig(format='%(asctime)s - %(levelname)s:%(message)s', level=log_level, filename=log_name)
# Get the access token...
response = azurerm.get_ams_access_token(account_name, account_key)
resjson = response.json()
access_token = resjson["access_token"]
#Some global vars...
NAME = "movie... | os.remove(log_name) | conditional_block |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.