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 |
|---|---|---|---|---|
trackTimeOnSite.js | import { bind, unbind } from '@segmentstream/utils/eventListener'
import listenEvents from './listenEvents'
import Storage from '../Storage'
const timeout = 10 // 10 seconds | let hasActive = false
let events = []
const storagePrefix = 'timeOnSite:'
const storage = new Storage({ prefix: storagePrefix })
// Load from storage
let activeTime = storage.get('activeTime') || 0
let time = storage.get('time') || 0
const firedEventsJSON = storage.get('firedEvents')
let firedEvents = firedEventsJSON... | let interval = null | random_line_split |
testidentifysourcefiles.py | import unittest
import sys
import os
import errno
import commands
from xml.dom import minidom
sys.path.append('bin')
from umdinst import wrap
from testsuccessfulcompiledata import getfield, timezonecheck, xmlifystring
from testcapturecompile import programcheck
def createemptyfile(fname):
"""Creates an empty fil... | (self):
os.remove("foo.c")
os.remove("bar.cpp")
os.remove("baz.upc")
os.remove("quux.f77")
if __name__ == '__main__':
unittest.main()
| tearDown | identifier_name |
testidentifysourcefiles.py | import unittest
import sys
import os
import errno
import commands
from xml.dom import minidom
sys.path.append('bin')
from umdinst import wrap
from testsuccessfulcompiledata import getfield, timezonecheck, xmlifystring
from testcapturecompile import programcheck
def createemptyfile(fname):
"""Creates an empty fil... | def setUp(self):
# Create some source files
createemptyfile("foo.c")
createemptyfile("bar.cpp")
createemptyfile("baz.upc")
createemptyfile("quux.f77")
self.args = "foo.c bar.cpp baz.upc quux.f77 others x.o y.exe -Dgoomba".split()
self.argsdasho = "foo.c -o baz... | class TestIdentifySourcefiles(unittest.TestCase): | random_line_split |
testidentifysourcefiles.py | import unittest
import sys
import os
import errno
import commands
from xml.dom import minidom
sys.path.append('bin')
from umdinst import wrap
from testsuccessfulcompiledata import getfield, timezonecheck, xmlifystring
from testcapturecompile import programcheck
def createemptyfile(fname):
"""Creates an empty fil... |
def testBasic(self):
files = wrap.identify_sourcefiles(self.args)
self.assertEquals(files,
['foo.c','bar.cpp','baz.upc','quux.f77'])
def testWithDashO(self):
files = wrap.identify_sourcefiles(self.argsdasho)
self.assertEquals(files,['foo.c','bar.c... | createemptyfile("foo.c")
createemptyfile("bar.cpp")
createemptyfile("baz.upc")
createemptyfile("quux.f77")
self.args = "foo.c bar.cpp baz.upc quux.f77 others x.o y.exe -Dgoomba".split()
self.argsdasho = "foo.c -o baz.upc bar.cpp".split() | identifier_body |
testidentifysourcefiles.py | import unittest
import sys
import os
import errno
import commands
from xml.dom import minidom
sys.path.append('bin')
from umdinst import wrap
from testsuccessfulcompiledata import getfield, timezonecheck, xmlifystring
from testcapturecompile import programcheck
def createemptyfile(fname):
"""Creates an empty fil... |
f = open(fname,'w')
f.close()
class TestIdentifySourcefiles(unittest.TestCase):
def setUp(self):
# Create some source files
createemptyfile("foo.c")
createemptyfile("bar.cpp")
createemptyfile("baz.upc")
createemptyfile("quux.f77")
self.args = "foo.c bar.cpp ... | raise ValueError,"File already exists" | conditional_block |
lib.rs | extern crate rand;
use rand::{thread_rng, RngCore};
#[cfg(test)]
mod tests {
use super::SecretData;
#[test]
fn it_works() {}
#[test]
fn it_generates_coefficients() {
let secret_data = SecretData::with_secret("Hello, world!", 3);
assert_eq!(secret_data.coefficients.len(), 13);
... |
}
static GF256_EXP: [u8; 256] = [
0x01, 0x03, 0x05, 0x0f, 0x11, 0x33, 0x55, 0xff, 0x1a, 0x2e, 0x72, 0x96, 0xa1, 0xf8, 0x13, 0x35,
0x5f, 0xe1, 0x38, 0x48, 0xd8, 0x73, 0x95, 0xa4, 0xf7, 0x02, 0x06, 0x0a, 0x1e, 0x22, 0x66, 0xaa,
0xe5, 0x34, 0x5c, 0xe4, 0x37, 0x59, 0xeb, 0x26, 0x6a, 0xbe, 0xd9, 0x70, 0x90, 0x... | {
let mut a = a.to_owned();
let mut b = b.to_owned();
if a.len() < b.len() {
let mut t = vec![0; b.len() - a.len()];
a.append(&mut t);
} else if a.len() > b.len() {
let mut t = vec![0; a.len() - b.len()];
b.append(&mut t);
}
... | identifier_body |
lib.rs | extern crate rand;
use rand::{thread_rng, RngCore};
#[cfg(test)]
mod tests {
use super::SecretData;
#[test]
fn it_works() {}
#[test]
fn it_generates_coefficients() {
let secret_data = SecretData::with_secret("Hello, world!", 3);
assert_eq!(secret_data.coefficients.len(), 13);
... | }
#[test]
fn it_can_recover_secret() {
let s1 = vec![1, 184, 190, 251, 87, 232, 39, 47, 17, 4, 36, 190, 245];
let s2 = vec![2, 231, 107, 52, 138, 34, 221, 9, 221, 67, 79, 33, 16];
let s3 = vec![3, 23, 176, 163, 177, 165, 218, 113, 163, 53, 7, 251, 196];
let new_secret = Sec... | assert!(secret_data.is_valid_share(&s1));
let s2 = secret_data.get_share(1).unwrap();
assert_eq!(s1, s2); | random_line_split |
lib.rs | extern crate rand;
use rand::{thread_rng, RngCore};
#[cfg(test)]
mod tests {
use super::SecretData;
#[test]
fn it_works() {}
#[test]
fn it_generates_coefficients() {
let secret_data = SecretData::with_secret("Hello, world!", 3);
assert_eq!(secret_data.coefficients.len(), 13);
... | {
/// The number of shares must be between 1 and 255
InvalidShareCount,
}
impl SecretData {
pub fn with_secret(secret: &str, threshold: u8) -> SecretData {
let mut coefficients: Vec<Vec<u8>> = vec![];
let mut rng = thread_rng();
let mut rand_container = vec![0u8; (threshold - 1) as... | ShamirError | identifier_name |
microversion.py | # Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the... | (headers):
"""Extract the microversion from Version.HEADER
There may be multiple headers and some which don't match our
service.
"""
found_version = microversion_parse.get_version(headers,
service_type=SERVICE_TYPE)
version_string = found_vers... | extract_version | identifier_name |
microversion.py | # Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the... | return _find_method(f, version)(req, *args, **kwargs)
# Sort highest min version to beginning of list.
VERSIONED_METHODS[qualified_name].sort(key=lambda x: x[0],
reverse=True)
return decorated_func
return decorator | VERSIONED_METHODS[qualified_name].append(
(min_version, max_version, f))
def decorated_func(req, *args, **kwargs):
version = req.environ[MICROVERSION_ENVIRON] | random_line_split |
microversion.py | # Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the... |
return name
def _find_method(f, version):
"""Look in VERSIONED_METHODS for method with right name matching version.
If no match is found raise a 404.
"""
qualified_name = _fully_qualified_name(f)
# A KeyError shouldn't be possible here, but let's be robust
# just in case.
method_list... | try:
cls = obj.im_class
except AttributeError:
# Python 3 eliminates im_class, substitutes __module__ and
# __qualname__ to provide similar information.
return "%s.%s" % (obj.__module__, obj.__qualname__)
else:
className = _fully_qualified_name... | conditional_block |
microversion.py | # Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the... |
class MicroversionMiddleware(object):
"""WSGI middleware for getting microversion info."""
def __init__(self, application):
self.application = application
@webob.dec.wsgify
def __call__(self, req):
util = nova.api.openstack.placement.util
try:
microversion = extr... | """Utility to raise a http status code if the wanted microversion does not
match.
:param req: The HTTP request for the placement api
:param status_code: HTTP status code (integer value) to be raised
:param min_version: Minimum placement microversion level
:param max_version: Maximum placement mi... | identifier_body |
build.js | (function() {
'use strict';
var getModulesList = function(modules) {
return modules.map(function(moduleName) {
return {name: moduleName};
});
};
| return {
namespace: 'RequireJS',
/**
* List the modules that will be optimized. All their immediate and deep
* dependencies will be included in the module's file when the build is
* done.
*/
modules: getModulesList([
'course_bookmarks/js/course... | var jsOptimize = process.env.REQUIRE_BUILD_PROFILE_OPTIMIZE !== undefined ?
process.env.REQUIRE_BUILD_PROFILE_OPTIMIZE : 'uglify2';
| random_line_split |
sitecustomize.py | import os
import socket
import sys
input_host = '127.0.0.1'
input_port = 65000
batch_enabled = int(os.environ.get('_BACKEND_BATCH_MODE', '0'))
if batch_enabled:
# Since latest Python 2 has `builtins`and `input`,
# we cannot detect Python 2 with the existence of them.
if sys.version_info.major > 2:
... | import __builtin__
builtins = __builtin__
def _raw_input(prompt=''):
sys.stdout.write(prompt)
sys.stdout.flush()
try:
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect((input_host, input_port))
... | else:
# __builtins__ is an alias dict for __builtin__ in modules other than __main__.
# Thus, we have to explicitly import __builtin__ module in Python 2. | random_line_split |
sitecustomize.py | import os
import socket
import sys
input_host = '127.0.0.1'
input_port = 65000
batch_enabled = int(os.environ.get('_BACKEND_BATCH_MODE', '0'))
if batch_enabled:
# Since latest Python 2 has `builtins`and `input`,
# we cannot detect Python 2 with the existence of them.
if sys.version_info.major > 2:
... |
builtins._raw_input = builtins.raw_input # type: ignore
builtins.raw_input = _raw_input # type: ignore
| sys.stdout.write(prompt)
sys.stdout.flush()
try:
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect((input_host, input_port))
userdata = sock.recv(1024)
except socket.error:
userdata = b'<user-input-un... | identifier_body |
sitecustomize.py | import os
import socket
import sys
input_host = '127.0.0.1'
input_port = 65000
batch_enabled = int(os.environ.get('_BACKEND_BATCH_MODE', '0'))
if batch_enabled:
# Since latest Python 2 has `builtins`and `input`,
# we cannot detect Python 2 with the existence of them.
if sys.version_info.major > 2:
... | (prompt=''):
sys.stdout.write(prompt)
sys.stdout.flush()
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:
try:
sock.connect((input_host, input_port))
userdata = sock.recv(1024)
except ConnectionRef... | _input | identifier_name |
sitecustomize.py | import os
import socket
import sys
input_host = '127.0.0.1'
input_port = 65000
batch_enabled = int(os.environ.get('_BACKEND_BATCH_MODE', '0'))
if batch_enabled:
# Since latest Python 2 has `builtins`and `input`,
# we cannot detect Python 2 with the existence of them.
if sys.version_info.major > 2:
... |
else:
# __builtins__ is an alias dict for __builtin__ in modules other than __main__.
# Thus, we have to explicitly import __builtin__ module in Python 2.
import __builtin__
builtins = __builtin__
def _raw_input(prompt=''):
sys.stdout.write(prompt)
s... | import builtins
def _input(prompt=''):
sys.stdout.write(prompt)
sys.stdout.flush()
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:
try:
sock.connect((input_host, input_port))
userdata = sock.recv(1024)
... | conditional_block |
index.d.ts | // Type definitions for karma-jasmine-spec-tags 1.2
// Project: https://github.com/mnasyrov/karma-jasmine-spec-tags#readme
// Definitions by: Piotr Błażejewicz (Peter Blazejewicz) <https://github.com/peterblazejewicz>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 3.2
import ... | tags?: string | string[] | boolean;
/**
* defines a comma-separated list of tag names
* * If `names` is defined then specs which match to tags will be skipped.
* * If `names` is not defined then all specs with a tag will be skipped.
*/
skipTags?: string | stri... | */ | random_line_split |
pagerank.rs | use super::super::{ Network, NodeId };
/// Runs pagerank algorithm on a graph until convergence.
/// Convergence is reached, when the last ranks vector and the new one
/// differ by less than `eps` in their L1-norm.
/// `beta` is the teleport probability. CAUTION: Never use a teleport
/// probability of `beta == 0.0`... |
/// Determines convergence for two vectors with respect to the tolerance.
fn is_converged(old: &Vec<f64>, new: &Vec<f64>, eps: f64) -> bool {
assert!(old.len() == new.len());
let mut sum = 0.0;
for i in 0..old.len() {
sum += (old[i] - new[i]).powi(2);
}
println!("{:e} ({:e})", sum.sqrt(), ... | {
let mut new_ranks = vec![0.0; current.len()];
for source_node in 0..current.len() {
let inv_out_deg = inv_out_degs[source_node];
for target_node in &adj_list[source_node] {
new_ranks[*target_node] += (1.0-beta) * inv_out_deg * current[source_node];
}
}
new_ranks
} | identifier_body |
pagerank.rs | use super::super::{ Network, NodeId };
/// Runs pagerank algorithm on a graph until convergence.
/// Convergence is reached, when the last ranks vector and the new one
/// differ by less than `eps` in their L1-norm.
/// `beta` is the teleport probability. CAUTION: Never use a teleport
/// probability of `beta == 0.0`... | (0,3,0.0,0.0),
(1,2,0.0,0.0),
(1,3,0.0,0.0),
(2,0,0.0,0.0),
(3,0,0.0,0.0),
(3,2,0.0,0.0)];
let compact_star = compact_star_from_edge_vec(4, &mut edges);
assert_eq!(vec![1.0/3.0, 1.0/2.0, 1.0/1.0, 1.0/2.0], inv_out_deg(&compact_star));
}
#[test]
fn test_build_adj_... | random_line_split | |
pagerank.rs | use super::super::{ Network, NodeId };
/// Runs pagerank algorithm on a graph until convergence.
/// Convergence is reached, when the last ranks vector and the new one
/// differ by less than `eps` in their L1-norm.
/// `beta` is the teleport probability. CAUTION: Never use a teleport
/// probability of `beta == 0.0`... | <N: Network>(network: &N) -> Vec<f64> {
let mut inv_out_deg = Vec::with_capacity(network.num_nodes());
for i in 0..network.num_nodes() {
let out_deg = network.adjacent(i as NodeId).len() as f64;
if out_deg > 0.0 {
inv_out_deg.push(1.0 / out_deg);
} else {
inv_out_... | inv_out_deg | identifier_name |
pagerank.rs | use super::super::{ Network, NodeId };
/// Runs pagerank algorithm on a graph until convergence.
/// Convergence is reached, when the last ranks vector and the new one
/// differ by less than `eps` in their L1-norm.
/// `beta` is the teleport probability. CAUTION: Never use a teleport
/// probability of `beta == 0.0`... |
}
inv_out_deg
}
/// Converts the network in a slightly faster traversable adjacency list.
fn build_adj_list<N: Network>(network: &N) -> Vec<Vec<usize>> {
let mut adj_list = Vec::with_capacity(network.num_nodes());
for i in 0..network.num_nodes() {
let adj_nodes = network.adjacent(i as NodeId);... | {
inv_out_deg.push(0.0);
} | conditional_block |
header-test.js | const { expect } = require('chai')
const path = require('path')
const ldnode = require('../../index')
const supertest = require('supertest')
const serverOptions = {
root: path.join(__dirname, '../resources/headers'),
multiuser: false,
webid: true,
sslKey: path.join(__dirname, '../keys/key.pem'),
sslCert: pat... |
})
| {
describe(`a resource that is ${label}`, () => {
let response
before(() => request.get(resource).then(res => { response = res }))
for (const header in headers) {
const value = headers[header]
const name = header.toLowerCase()
if (value instanceof RegExp) {
it(`h... | identifier_body |
header-test.js | const { expect } = require('chai')
const path = require('path')
const ldnode = require('../../index')
const supertest = require('supertest')
const serverOptions = {
root: path.join(__dirname, '../resources/headers'),
multiuser: false,
webid: true,
sslKey: path.join(__dirname, '../keys/key.pem'),
sslCert: pat... | headers: {
'WAC-Allow': 'user="read append",public="read append"',
'Access-Control-Expose-Headers': /(^|,\s*)WAC-Allow(,|$)/
}
})
describeHeaderTest('read/write for the user, read for the public', {
resource: '/user-rw-public-r',
headers: {
'WAC-Allow': 'user="re... | resource: '/public-ra', | random_line_split |
header-test.js | const { expect } = require('chai')
const path = require('path')
const ldnode = require('../../index')
const supertest = require('supertest')
const serverOptions = {
root: path.join(__dirname, '../resources/headers'),
multiuser: false,
webid: true,
sslKey: path.join(__dirname, '../keys/key.pem'),
sslCert: pat... | else {
it(`has a ${header} header of ${value}`, () => {
expect(response.headers).to.have.property(name, value)
})
}
}
})
}
})
| {
it(`has a ${header} header matching ${value}`, () => {
expect(response.headers).to.have.property(name)
expect(response.headers[name]).to.match(value)
})
} | conditional_block |
header-test.js | const { expect } = require('chai')
const path = require('path')
const ldnode = require('../../index')
const supertest = require('supertest')
const serverOptions = {
root: path.join(__dirname, '../resources/headers'),
multiuser: false,
webid: true,
sslKey: path.join(__dirname, '../keys/key.pem'),
sslCert: pat... | (label, { resource, headers }) {
describe(`a resource that is ${label}`, () => {
let response
before(() => request.get(resource).then(res => { response = res }))
for (const header in headers) {
const value = headers[header]
const name = header.toLowerCase()
if (value inst... | describeHeaderTest | identifier_name |
errors.py | # -*- coding: utf-8 -*-
# Copyright 2009-2013 Jaap Karssenberg <jaap.karssenberg@gmail.com>
# The Error class needed to be put in a separate file to avoid recursive
# imports.
'''This module contains the base class for all errors in zim'''
import sys
import logging
logger = logging.getLogger('zim')
use_gtk_error... | error = exc_info[1]
del exc_info # recommended by manual
log_error(error, debug=debug)
if use_gtk_errordialog:
_run_error_dialog(error)
class Error(Exception):
'''Base class for all errors in zim.
This class is intended for application and usage errors, these will
be caught in the user interface and presen... | exc_info = sys.exc_info() | random_line_split |
errors.py | # -*- coding: utf-8 -*-
# Copyright 2009-2013 Jaap Karssenberg <jaap.karssenberg@gmail.com>
# The Error class needed to be put in a separate file to avoid recursive
# imports.
'''This module contains the base class for all errors in zim'''
import sys
import logging
logger = logging.getLogger('zim')
use_gtk_error... | (self, msg, description=None):
self.msg = msg
if description:
self.description = description
# else use class attribute
def __str__(self):
msg = self.__unicode__()
return msg.encode('utf-8')
def __unicode__(self):
msg = u'' + self.msg.strip()
if self.description:
msg += '\n\n' + self.descriptio... | __init__ | identifier_name |
errors.py | # -*- coding: utf-8 -*-
# Copyright 2009-2013 Jaap Karssenberg <jaap.karssenberg@gmail.com>
# The Error class needed to be put in a separate file to avoid recursive
# imports.
'''This module contains the base class for all errors in zim'''
import sys
import logging
logger = logging.getLogger('zim')
use_gtk_error... |
def _run_error_dialog(error):
#~ try:
from zim.gui.widgets import ErrorDialog
ErrorDialog(None, error, do_logging=False).run()
#~ except:
#~ logger.error('Failed to run error dialog')
def show_error(error):
'''Show an error by calling L{log_error()} and when running
interactive also calling L{ErrorDialog}.... | '''Log error and traceback
@param error: error as understood by L{get_error_msg()}
@param debug: optional debug message, defaults to the error itself
'''
msg, show_trace = get_error_msg(error)
if debug is None:
debug = msg
if show_trace:
# unexpected error - will be logged with traceback
logger.exception(d... | identifier_body |
errors.py | # -*- coding: utf-8 -*-
# Copyright 2009-2013 Jaap Karssenberg <jaap.karssenberg@gmail.com>
# The Error class needed to be put in a separate file to avoid recursive
# imports.
'''This module contains the base class for all errors in zim'''
import sys
import logging
logger = logging.getLogger('zim')
use_gtk_error... |
elif isinstance(error, EnvironmentError):
# Normal error, e.g. OSError or IOError
msg = error.strerror
if hasattr(error, 'filename') and error.filename:
msg += ': ' + error.filename
return msg, False
else:
# An unexpected error, all other Exception's
msg = _('Looks like you found a bug') # T: generi... | return error.msg, False | conditional_block |
results_fetcher.py | # Copyright (c) 2009, Google Inc. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the... | (self):
self.web = Web()
self.builders = BuilderList.load_default_builder_list(FileSystem())
def results_url(self, builder_name, build_number=None, step_name=None):
"""Returns a URL for one set of archived web test results.
If a build number is given, this will be results for a par... | __init__ | identifier_name |
results_fetcher.py | # Copyright (c) 2009, Google Inc. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the... | if not data:
_log.debug('Got 404 response from:\n%s', url)
return None
return WebTestResults.results_from_string(data)
def filter_latest_builds(builds):
"""Filters Build objects to include only the latest for each builder.
Args:
builds: A collection of Build ob... | ('name', 'full_results.json')]))
data = self.web.get_binary(url, return_none_on_404=True) | random_line_split |
results_fetcher.py | # Copyright (c) 2009, Google Inc. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the... |
# We were not able to retrieve step name for some builders from
# https://test-results.appspot.com. Read from config file instead
step_name = self.builders.step_name_for_builder(build.builder_name)
if step_name:
return step_name
url = '%s/testfile?%s' % (
... | _log.debug('Builder name or build number is None')
return None | conditional_block |
results_fetcher.py | # Copyright (c) 2009, Google Inc. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the... | """Filters Build objects to include only the latest for each builder.
Args:
builds: A collection of Build objects.
Returns:
A list of Build objects; only one Build object per builder name. If
there are only Builds with no build number, then one is kept; if there
are Builds with... | identifier_body | |
power_measurement_suite_new.py | import SCPI
import time
import numpy
totalSamples = 10
sampleFreq = 100
#freq= SCPI.SCPI("172.17.5.121")
dmm = SCPI.SCPI("172.17.5.131")
#setup freq gen
#freq.setSquare()
#freq.setVoltage(0,3)
#freq.setFrequency(sampleFreq)
#setup voltage meter
#dmm.setVoltageDC("10V", "MAX")
# set external trigger
#dmm.setTriggerS... |
#freq.setOutput(0)
s = 0
for i in range(0, totalSamples):
print float(currentMeasurements[i])
#print "Average Power Consumption: ", s/float(totalSamples), "W avg volt: ", numpy.mean(voltageMeasurements), "V avg current: ", numpy.mean(currentMeasurements), "A"
| if len(currentMeasurements) < totalSamples:
currentMeasurements += dmm.getMeasurements()
if (len(currentMeasurements) >= totalSamples):
break
time.sleep(0.1) | conditional_block |
power_measurement_suite_new.py |
totalSamples = 10
sampleFreq = 100
#freq= SCPI.SCPI("172.17.5.121")
dmm = SCPI.SCPI("172.17.5.131")
#setup freq gen
#freq.setSquare()
#freq.setVoltage(0,3)
#freq.setFrequency(sampleFreq)
#setup voltage meter
#dmm.setVoltageDC("10V", "MAX")
# set external trigger
#dmm.setTriggerSource("INT")
#dmm.setTriggerCount(str... | import SCPI
import time
import numpy | random_line_split | |
api-data.js | import supertest from 'supertest';
import { publicChannelName, privateChannelName } from './channel.js';
import { roleNameUsers, roleNameSubscriptions, roleScopeUsers, roleScopeSubscriptions, roleDescription } from './role.js';
import { username, email, adminUsername, adminPassword } from './user.js';
export const re... |
export function log(res) {
console.log(res.req.path);
console.log({
body: res.body,
headers: res.headers,
});
}
export function getCredentials(done = function() {}) {
request.post(api('login'))
.send(login)
.expect('Content-Type', 'application/json')
.expect(200)
.expect((res) => {
credentials['X-... | {
return api(`method.call/${ methodName }`);
} | identifier_body |
api-data.js | import supertest from 'supertest';
import { publicChannelName, privateChannelName } from './channel.js';
import { roleNameUsers, roleNameSubscriptions, roleScopeUsers, roleScopeSubscriptions, roleDescription } from './role.js';
import { username, email, adminUsername, adminPassword } from './user.js';
export const re... | 'X-User-Id': undefined,
};
export const login = {
user: adminUsername,
password: adminPassword,
};
export function api(path) {
return prefix + path;
}
export function methodCall(methodName) {
return api(`method.call/${ methodName }`);
}
export function log(res) {
console.log(res.req.path);
console.log({
bod... | export const directMessage = {};
export const integration = {};
export const credentials = {
'X-Auth-Token': undefined, | random_line_split |
api-data.js | import supertest from 'supertest';
import { publicChannelName, privateChannelName } from './channel.js';
import { roleNameUsers, roleNameSubscriptions, roleScopeUsers, roleScopeSubscriptions, roleDescription } from './role.js';
import { username, email, adminUsername, adminPassword } from './user.js';
export const re... | (cb, time) {
return () => setTimeout(cb, time);
}
export const apiUsername = `api${ username }`;
export const apiEmail = `api${ email }`;
export const apiPublicChannelName = `api${ publicChannelName }`;
export const apiPrivateChannelName = `api${ privateChannelName }`;
export const apiRoleNameUsers = `api${ roleName... | wait | identifier_name |
activity.py | """
The MIT License (MIT)
Copyright (c) 2015-present Rapptz
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the "Software"),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merg... |
class ActivityButton(TypedDict):
label: str
url: str
class _SendableActivityOptional(TypedDict, total=False):
url: Optional[str]
ActivityType = Literal[0, 1, 2, 4, 5]
class SendableActivity(_SendableActivityOptional):
name: str
type: ActivityType
class _BaseActivity(SendableActivity):
c... | random_line_split | |
activity.py | """
The MIT License (MIT)
Copyright (c) 2015-present Rapptz
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the "Software"),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merg... | (TypedDict):
user: User
guild_id: Snowflake
status: StatusType
activities: List[Activity]
client_status: ClientStatus
class ClientStatus(TypedDict, total=False):
desktop: StatusType
mobile: StatusType
web: StatusType
class ActivityTimestamps(TypedDict, total=False):
start: int
... | PartialPresenceUpdate | identifier_name |
activity.py | """
The MIT License (MIT)
Copyright (c) 2015-present Rapptz
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the "Software"),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merg... |
class ActivityButton(TypedDict):
label: str
url: str
class _SendableActivityOptional(TypedDict, total=False):
url: Optional[str]
ActivityType = Literal[0, 1, 2, 4, 5]
class SendableActivity(_SendableActivityOptional):
name: str
type: ActivityType
class _BaseActivity(SendableActivity):
... | name: str | identifier_body |
FormProps.ts | import * as React from "react";
import * as PropTypes from "prop-types";
import { FormContext } from "./FormContext";
import { ModelInterface, ModelValue } from "../Model";
export type StorageRequiredInterface = Pick<Storage, "setItem" | "getItem">;
export const StorageRequiredInterfaceTypes:
{[P in keyof Storag... | }; | random_line_split | |
acceptance_tests.rs | #![cfg(test)]
#[macro_use]
extern crate lazy_static;
mod acceptance {
use std::process::{Command, Output};
fn run_tests() -> Output {
Command::new("cargo")
.args(&["test", "test_cases"])
.output()
.expect("cargo command failed to start")
}
lazy_static! {
... |
#[test]
fn marks_inconclusive_tests_as_ignored() {
assert!(actual().contains("test test_cases::inconclusive_tests::should_not_take_into_account_keyword_on_argument_position ... ok"));
assert!(actual().contains("test test_cases::inconclusive_tests::this_test_is_inconclusive_and_will_always_be .... | {
assert!(actual().contains("test test_cases::lowercase_test_name::dummy_code ... ok"));
} | identifier_body |
acceptance_tests.rs | #![cfg(test)]
#[macro_use]
extern crate lazy_static;
mod acceptance {
use std::process::{Command, Output};
fn run_tests() -> Output {
Command::new("cargo")
.args(&["test", "test_cases"])
.output()
.expect("cargo command failed to start")
}
lazy_static! {
... | }
#[test]
fn escapes_names_starting_with_digit() {
assert!(actual().contains("test test_cases::basic_test::_1 ... ok"));
}
#[test]
fn removes_repeated_underscores() {
assert!(actual().contains("test test_cases::arg_expressions::_2_4_6_to_string ... ok"));
}
#[test]
... | random_line_split | |
acceptance_tests.rs | #![cfg(test)]
#[macro_use]
extern crate lazy_static;
mod acceptance {
use std::process::{Command, Output};
fn run_tests() -> Output {
Command::new("cargo")
.args(&["test", "test_cases"])
.output()
.expect("cargo command failed to start")
}
lazy_static! {
... | () {
assert!(actual().contains("test test_cases::basic_test::_1 ... ok"));
}
#[test]
fn removes_repeated_underscores() {
assert!(actual().contains("test test_cases::arg_expressions::_2_4_6_to_string ... ok"));
}
#[test]
fn escapes_rust_keywords() {
assert!(actual().cont... | escapes_names_starting_with_digit | identifier_name |
lib.rs | use std::collections::VecDeque;
use std::char;
macro_rules! try_option {
($o:expr) => {
match $o {
Some(s) => s,
None => return None,
}
}
}
// Takes in a string with backslash escapes written out with literal backslash characters and
// converts it to a string with the... | (c: char, queue: &mut VecDeque<char>) -> Option<char> {
match unescape_octal_leading(c, queue) {
Some(ch) => {
let _ = queue.pop_front();
let _ = queue.pop_front();
Some(ch)
}
None => unescape_octal_no_leading(c, queue)
}
}
fn unescape_octal_leading(c... | unescape_octal | identifier_name |
lib.rs | use std::collections::VecDeque;
use std::char;
macro_rules! try_option {
($o:expr) => {
match $o {
Some(s) => s,
None => return None,
}
}
}
// Takes in a string with backslash escapes written out with literal backslash characters and
// converts it to a string with the... | } | char::from_u32(u) | random_line_split |
lib.rs | use std::collections::VecDeque;
use std::char;
macro_rules! try_option {
($o:expr) => {
match $o {
Some(s) => s,
None => return None,
}
}
}
// Takes in a string with backslash escapes written out with literal backslash characters and
// converts it to a string with the... |
fn unescape_octal(c: char, queue: &mut VecDeque<char>) -> Option<char> {
match unescape_octal_leading(c, queue) {
Some(ch) => {
let _ = queue.pop_front();
let _ = queue.pop_front();
Some(ch)
}
None => unescape_octal_no_leading(c, queue)
}
}
fn unesc... | {
let mut s = String::new();
for _ in 0..2 {
s.push(try_option!(queue.pop_front()));
}
let u = try_option!(u32::from_str_radix(&s, 16).ok());
char::from_u32(u)
} | identifier_body |
screen-snippet-handler.ts | import { app, BrowserWindow } from 'electron';
import * as fs from 'fs';
import * as os from 'os';
import * as path from 'path';
import { ChildProcess, ExecException, execFile } from 'child_process';
import * as util from 'util';
import { IScreenSnippet } from '../common/api-interface';
import { isDevEnv, isLinux, isM... | logger.info(`screen-snippet-handler: cleaning up temp snippet file: ${this.outputFileName}!`);
if (removeErr) {
logger.error(`screen-snippet-handler: error removing temp snippet file: ${this.outputFileName}, err: ${removeErr}`);
}
... | this.focusedWindow.moveTop();
}
// remove tmp file (async)
if (this.outputFileName) {
fs.unlink(this.outputFileName, (removeErr) => { | random_line_split |
screen-snippet-handler.ts | import { app, BrowserWindow } from 'electron';
import * as fs from 'fs';
import * as os from 'os';
import * as path from 'path';
import { ChildProcess, ExecException, execFile } from 'child_process';
import * as util from 'util';
import { IScreenSnippet } from '../common/api-interface';
import { isDevEnv, isLinux, isM... |
/**
* Captures a user selected portion of the monitor and returns jpeg image
* encoded in base64 format.
*
* @param webContents {Electron.webContents}
*/
public async capture(webContents: Electron.webContents) {
const mainWindow = windowHandler.getMainWindow();
if (mai... | {
this.tempDir = os.tmpdir();
this.captureUtil = isMac ? '/usr/sbin/screencapture' : isDevEnv
? path.join(__dirname,
'../../../node_modules/screen-snippet/ScreenSnippet.exe')
: path.join(path.dirname(app.getPath('exe')), 'ScreenSnippet.exe');
if (isLinux)... | identifier_body |
screen-snippet-handler.ts | import { app, BrowserWindow } from 'electron';
import * as fs from 'fs';
import * as os from 'os';
import * as path from 'path';
import { ChildProcess, ExecException, execFile } from 'child_process';
import * as util from 'util';
import { IScreenSnippet } from '../common/api-interface';
import { isDevEnv, isLinux, isM... |
logger.info(`screen-snippet-handler: Starting screen capture!`);
this.outputFileName = path.join(this.tempDir, 'symphonyImage-' + Date.now() + '.png');
this.captureUtilArgs = isMac
? [ '-i', '-s', '-t', 'png', this.outputFileName ]
: [ this.outputFileName, i18n.getLocale... | {
this.shouldUpdateAlwaysOnTop = mainWindow.isAlwaysOnTop();
if (this.shouldUpdateAlwaysOnTop) {
await updateAlwaysOnTop(false, false, false);
}
} | conditional_block |
screen-snippet-handler.ts | import { app, BrowserWindow } from 'electron';
import * as fs from 'fs';
import * as os from 'os';
import * as path from 'path';
import { ChildProcess, ExecException, execFile } from 'child_process';
import * as util from 'util';
import { IScreenSnippet } from '../common/api-interface';
import { isDevEnv, isLinux, isM... | (): Promise<void> {
if (this.shouldUpdateAlwaysOnTop) {
await updateAlwaysOnTop(true, false, false);
this.shouldUpdateAlwaysOnTop = false;
}
}
}
const screenSnippet = new ScreenSnippet();
export { screenSnippet };
| verifyAndUpdateAlwaysOnTop | identifier_name |
test_parameters.py | # Licensed under a 3-clause BSD style license - see LICENSE.rst
# STDLIB
from types import MappingProxyType
# THIRD PARTY
import numpy as np
import pytest
# LOCAL
from astropy.cosmology import parameters, realizations
def test_realizations_in_dir():
|
@pytest.mark.parametrize("name", parameters.available)
def test_getting_parameters(name):
"""
Test getting 'parameters' and that it is derived from the corresponding
realization.
"""
params = getattr(parameters, name)
assert isinstance(params, MappingProxyType)
assert params["name"] == n... | """Test the realizations are in ``dir`` of :mod:`astropy.cosmology.parameters`."""
d = dir(parameters)
assert set(d) == set(parameters.__all__)
for n in parameters.available:
assert n in d | identifier_body |
test_parameters.py | # Licensed under a 3-clause BSD style license - see LICENSE.rst
# STDLIB
from types import MappingProxyType
# THIRD PARTY
import numpy as np
import pytest
# LOCAL
from astropy.cosmology import parameters, realizations
def test_realizations_in_dir():
"""Test the realizations are in ``dir`` of :mod:`astropy.cosm... |
# All the metadata is included. Parameter values take precedence, so only
# checking the keys.
assert set(cosmo.meta.keys()).issubset(params.keys())
# Lastly, check the generation process.
m = cosmo.to_format("mapping", cosmology_as_str=True, move_from_meta=True)
assert params == m
| assert np.array_equal(params[n], getattr(cosmo, n)) | conditional_block |
test_parameters.py | # Licensed under a 3-clause BSD style license - see LICENSE.rst
# STDLIB
from types import MappingProxyType
# THIRD PARTY
import numpy as np
import pytest
# LOCAL
from astropy.cosmology import parameters, realizations
def test_realizations_in_dir():
"""Test the realizations are in ``dir`` of :mod:`astropy.cosm... | assert params["name"] == name
# Check parameters have the right keys and values
cosmo = getattr(realizations, name)
assert params["name"] == cosmo.name
assert params["cosmology"] == cosmo.__class__.__qualname__
# All the cosmology parameters are equal
for n in cosmo.__parameters__:
... | assert isinstance(params, MappingProxyType) | random_line_split |
test_parameters.py | # Licensed under a 3-clause BSD style license - see LICENSE.rst
# STDLIB
from types import MappingProxyType
# THIRD PARTY
import numpy as np
import pytest
# LOCAL
from astropy.cosmology import parameters, realizations
def test_realizations_in_dir():
"""Test the realizations are in ``dir`` of :mod:`astropy.cosm... | (name):
"""
Test getting 'parameters' and that it is derived from the corresponding
realization.
"""
params = getattr(parameters, name)
assert isinstance(params, MappingProxyType)
assert params["name"] == name
# Check parameters have the right keys and values
cosmo = getattr(realiz... | test_getting_parameters | identifier_name |
data_manager_view_mixin.py | from django.contrib import messages
from django.views.generic.base import ContextMixin
from edc_constants.constants import OPEN
from ..models import DataActionItem
from ..model_wrappers import DataActionItemModelWrapper
from .user_details_check_view_mixin import UserDetailsCheckViewMixin
class DataActionItemsViewMi... | (self):
"""Returns a wrapped saved or unsaved consent version.
"""
model_obj = DataActionItem(subject_identifier=self.subject_identifier)
return DataActionItemModelWrapper(model_obj=model_obj)
def data_action_items(self):
"""Return a list of action items.
"""
... | data_action_item | identifier_name |
data_manager_view_mixin.py | from django.contrib import messages
from django.views.generic.base import ContextMixin
from edc_constants.constants import OPEN
from ..models import DataActionItem
from ..model_wrappers import DataActionItemModelWrapper
from .user_details_check_view_mixin import UserDetailsCheckViewMixin
class DataActionItemsViewMi... | for data_action_item in data_action_items:
msg = (f'Issue {data_action_item.issue_number}. Pending action'
f' created by {data_action_item.user_created}. '
f'{data_action_item.subject} Assigned to '
f'{data_action_item.assigned}')
... | status__in=status).order_by('issue_number')
msg = '' | random_line_split |
data_manager_view_mixin.py | from django.contrib import messages
from django.views.generic.base import ContextMixin
from edc_constants.constants import OPEN
from ..models import DataActionItem
from ..model_wrappers import DataActionItemModelWrapper
from .user_details_check_view_mixin import UserDetailsCheckViewMixin
class DataActionItemsViewMi... |
context.update(
data_action_item_template=self.data_action_item_template,
data_action_item_add_url=self.data_action_item.href,
data_action_items=self.data_action_items)
return context
| msg = (f'Issue {data_action_item.issue_number}. Pending action'
f' created by {data_action_item.user_created}. '
f'{data_action_item.subject} Assigned to '
f'{data_action_item.assigned}')
messages.add_message(
self.request, messages.ER... | conditional_block |
data_manager_view_mixin.py | from django.contrib import messages
from django.views.generic.base import ContextMixin
from edc_constants.constants import OPEN
from ..models import DataActionItem
from ..model_wrappers import DataActionItemModelWrapper
from .user_details_check_view_mixin import UserDetailsCheckViewMixin
class DataActionItemsViewMi... | context = super().get_context_data(**kwargs)
status = [OPEN, 'stalled', 'resolved']
data_action_items = DataActionItem.objects.filter(
subject_identifier=self.subject_identifier,
status__in=status).order_by('issue_number')
msg = ''
for data_action_item in data_ac... | identifier_body | |
parse.js | var assert = require('assert');
var cookie = require('..');
suite('parse');
test('basic', function() {
assert.deepEqual({ foo: 'bar' }, cookie.parse('foo=bar'));
assert.deepEqual({ foo: '123' }, cookie.parse('foo=123'));
});
test('ignore spaces', function() {
assert.deepEqual({ FOO: 'bar', baz: 'raz' },... | assert.deepEqual({ foo: '%1', bar: 'bar' }, cookie.parse('foo=%1;bar=bar'));
}); | random_line_split | |
event-target-legacy.ts | /**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
export function eventTargetLegacyPatch(_global: any, api: _ZonePrivate) {
const {eventNames, globalSources, zoneSy... | (global: any, api: _ZonePrivate) {
api.patchEventPrototype(global, api);
}
| patchEvent | identifier_name |
event-target-legacy.ts | /**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
export function eventTargetLegacyPatch(_global: any, api: _ZonePrivate) {
const {eventNames, globalSources, zoneSy... | {
api.patchEventPrototype(global, api);
} | identifier_body | |
event-target-legacy.ts | /**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
export function eventTargetLegacyPatch(_global: any, api: _ZonePrivate) {
const {eventNames, globalSources, zoneSy... | const ieOrEdge = api.isIEOrEdge();
const ADD_EVENT_LISTENER_SOURCE = '.addEventListener:';
const FUNCTION_WRAPPER = '[object FunctionWrapper]';
const BROWSER_TOOLS = 'function __BROWSERTOOLS_CONSOLE_SAFEFUNC() { [native code] }';
const pointerEventsMap: {[key: string]: string} = {
'MSPointerCancel': 'po... | random_line_split | |
event-target-legacy.ts | /**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
export function eventTargetLegacyPatch(_global: any, api: _ZonePrivate) {
const {eventNames, globalSources, zoneSy... |
const isDisableIECheck = _global['__Zone_disable_IE_check'] || false;
const isEnableCrossContextCheck = _global['__Zone_enable_cross_context_check'] || false;
const ieOrEdge = api.isIEOrEdge();
const ADD_EVENT_LISTENER_SOURCE = '.addEventListener:';
const FUNCTION_WRAPPER = '[object FunctionWrapper]';
co... | {
// Note: EventTarget is not available in all browsers,
// if it's not available, we instead patch the APIs in the IDL that inherit from EventTarget
apis = NO_EVENT_TARGET;
} | conditional_block |
inject.js | /* Copyright (C) 2016 R&D Solutions Ltd.
*
* 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... | var injectStyles = gulp.src([
path.join(conf.paths.src, '/app/**/*.css')
], {read: false});
var injectScripts = gulp.src([
path.join(conf.paths.src, '/app/**/*.main.js'),
path.join(conf.paths.src, '/app/**/*.js'),
path.join('!' + conf.paths.src, '/app/dataTables/*.js'),
path.join('!' ... | random_line_split | |
filter_library.py | from __future__ import print_function
from future import standard_library
standard_library.install_aliases()
from builtins import object
import pandas as pd
import os
import yaml
import astropy.io.votable as votable
import astropy.units as u
import urllib.request, urllib.error, urllib.parse
import xml.etree.ElementTre... |
return filter_dict
def download_grond(filter_dict):
save_path = os.path.join(get_speclite_filter_path(), "ESO")
if_directory_not_existing_then_make(save_path)
grond_filter_url = "http://www.mpe.mpg.de/~jcg/GROND/GROND_filtercurves.txt"
url_response = urllib.request.urlopen(grond_filter_url)
... | if obs == "2MASS":
obs = "TwoMASS"
url_response = urllib.request.urlopen(
"http://svo2.cab.inta-csic.es/svo/theory/fps/fps.php?Facility=%s" % obs
)
try:
# parse the VO table
v = votable.parse(url_response)
instrument_dict = defaul... | conditional_block |
filter_library.py | from __future__ import print_function
from future import standard_library
standard_library.install_aliases()
from builtins import object
import pandas as pd
import os
import yaml
import astropy.io.votable as votable
import astropy.units as u
import urllib.request, urllib.error, urllib.parse
import xml.etree.ElementTre... |
return False
else:
return True
with warnings.catch_warnings():
warnings.simplefilter("ignore")
lib_exists = build_filter_library()
if lib_exists:
threeML_filter_library = FilterLibrary(
os.path.join(get_speclite_filter_path(), "filter_lib.yml")
)
__all__ = ["... | random_line_split | |
filter_library.py | from __future__ import print_function
from future import standard_library
standard_library.install_aliases()
from builtins import object
import pandas as pd
import os
import yaml
import astropy.io.votable as votable
import astropy.units as u
import urllib.request, urllib.error, urllib.parse
import xml.etree.ElementTre... | (object):
def __init__(self, sub_dict):
self._sub_dict = sub_dict
def __repr__(self):
return yaml.dump(self._sub_dict, default_flow_style=False)
class FilterLibrary(object):
def __init__(self, library_file):
"""
holds all the observatories/instruments/filters
:p... | ObservatoryNode | identifier_name |
filter_library.py | from __future__ import print_function
from future import standard_library
standard_library.install_aliases()
from builtins import object
import pandas as pd
import os
import yaml
import astropy.io.votable as votable
import astropy.units as u
import urllib.request, urllib.error, urllib.parse
import xml.etree.ElementTre... |
@property
def instruments(self):
return self._instruments
def __repr__(self):
return yaml.dump(self._library, default_flow_style=False)
def add_svo_filter_to_speclite(observatory, instrument, ffilter, update=False):
"""
download an SVO filter file and then add it to the user li... | """
holds all the observatories/instruments/filters
:param library_file:
"""
# get the filter file
with open(library_file) as f:
self._library = yaml.load(f, Loader=yaml.SafeLoader)
self._instruments = []
# create attributes which are lib.observ... | identifier_body |
ShardingManager.js | const path = require('path');
const fs = require('fs');
const EventEmitter = require('events').EventEmitter;
const Shard = require('./Shard');
const Collection = require('../util/Collection');
const Util = require('../util/Util');
/**
* This is a utility class that can be used to help you spawn shards of your client.... | (amount, delay) {
return new Promise(resolve => {
if (this.shards.size >= amount) throw new Error(`Already spawned ${this.shards.size} shards.`);
this.totalShards = amount;
this.createShard();
if (this.shards.size >= this.totalShards) {
resolve(this.shards);
return;
}
... | _spawn | identifier_name |
ShardingManager.js | const path = require('path');
const fs = require('fs');
const EventEmitter = require('events').EventEmitter;
const Shard = require('./Shard');
const Collection = require('../util/Collection');
const Util = require('../util/Util');
/**
* This is a utility class that can be used to help you spawn shards of your client.... |
}, delay);
}
});
}
/**
* Send a message to all shards.
* @param {*} message Message to be sent to the shards
* @returns {Promise<Shard[]>}
*/
broadcast(message) {
const promises = [];
for (const shard of this.shards.values()) promises.push(shard.send(message));
return P... | {
clearInterval(interval);
resolve(this.shards);
} | conditional_block |
ShardingManager.js | const path = require('path');
const fs = require('fs');
const EventEmitter = require('events').EventEmitter;
const Shard = require('./Shard');
const Collection = require('../util/Collection');
const Util = require('../util/Util');
/**
* This is a utility class that can be used to help you spawn shards of your client.... | * @type {string}
*/
this.file = file;
if (!file) throw new Error('File must be specified.');
if (!path.isAbsolute(file)) this.file = path.resolve(process.cwd(), file);
const stats = fs.statSync(this.file);
if (!stats.isFile()) throw new Error('File path does not point to a file.');
/*... | /**
* Path to the shard script file | random_line_split |
ShardingManager.js | const path = require('path');
const fs = require('fs');
const EventEmitter = require('events').EventEmitter;
const Shard = require('./Shard');
const Collection = require('../util/Collection');
const Util = require('../util/Util');
/**
* This is a utility class that can be used to help you spawn shards of your client.... |
/**
* Actually spawns shards, unlike that poser above >:(
* @param {number} amount Number of shards to spawn
* @param {number} delay How long to wait in between spawning each shard (in milliseconds)
* @returns {Promise<Collection<number, Shard>>}
* @private
*/
_spawn(amount, delay) {
return ... | {
if (amount === 'auto') {
return Util.fetchRecommendedShards(this.token).then(count => {
this.totalShards = count;
return this._spawn(count, delay);
});
} else {
if (typeof amount !== 'number' || isNaN(amount)) throw new TypeError('Amount of shards must be a number.');
i... | identifier_body |
sha1.js | /**
*
* Secure Hash Algorithm (SHA1)
* http://www.webtoolkit.info/
*
**/
export function SHA1(msg) {
function rotate_left(n, s) {
var t4 = (n << s) | (n >>> (32 - s));
return t4;
};
function lsb_hex(val) {
var str = "";
var i;
var vh;
var vl;
... | (string) {
string = string.replace(/\r\n/g, "\n");
var utftext = "";
for (var n = 0; n < string.length; n++) {
var c = string.charCodeAt(n);
if (c < 128) {
utftext += String.fromCharCode(c);
} else if ((c > 127) && (c < 2048)) {
... | Utf8Encode | identifier_name |
sha1.js | /**
*
* Secure Hash Algorithm (SHA1)
* http://www.webtoolkit.info/
*
**/
export function SHA1(msg) {
function rotate_left(n, s) {
var t4 = (n << s) | (n >>> (32 - s));
return t4;
};
function lsb_hex(val) {
var str = "";
var i;
var vh;
var vl;
... | E = D;
D = C;
C = rotate_left(B, 30);
B = A;
A = temp;
}
for (i = 20; i <= 39; i++) {
temp = (rotate_left(A, 5) + (B ^ C ^ D) + E + W[i] + 0x6ED9EBA1) & 0x0ffffffff;
E = D;
D = C;
C = rotate_left... | for (i = 0; i <= 19; i++) {
temp = (rotate_left(A, 5) + ((B & C) | (~B & D)) + E + W[i] + 0x5A827999) & 0x0ffffffff; | random_line_split |
sha1.js | /**
*
* Secure Hash Algorithm (SHA1)
* http://www.webtoolkit.info/
*
**/
export function SHA1(msg) | ;
| {
function rotate_left(n, s) {
var t4 = (n << s) | (n >>> (32 - s));
return t4;
};
function lsb_hex(val) {
var str = "";
var i;
var vh;
var vl;
for (i = 0; i <= 6; i += 2) {
vh = (val >>> (i * 4 + 4)) & 0x0f;
vl = (val >>> (i... | identifier_body |
gr-keyboard-shortcuts-dialog.ts | /**
* @license
* Copyright (C) 2016 The Android Open Source Project
*
* 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 require... | shortcuts: directory.get(ShortcutSection.ACTIONS),
});
}
if (directory.has(ShortcutSection.REPLY_DIALOG)) {
right.push({
section: ShortcutSection.REPLY_DIALOG,
shortcuts: directory.get(ShortcutSection.REPLY_DIALOG),
});
}
if (directory.has(ShortcutSection.FILE... | if (directory.has(ShortcutSection.ACTIONS)) {
right.push({
section: ShortcutSection.ACTIONS, | random_line_split |
gr-keyboard-shortcuts-dialog.ts | /**
* @license
* Copyright (C) 2016 The Android Open Source Project
*
* 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 require... |
this._right = right;
this._left = left;
}
}
| {
right.push({
section: ShortcutSection.DIFFS,
shortcuts: directory.get(ShortcutSection.DIFFS),
});
} | conditional_block |
gr-keyboard-shortcuts-dialog.ts | /**
* @license
* Copyright (C) 2016 The Android Open Source Project
*
* 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 require... | () {
super.connectedCallback();
this.shortcuts.addListener(this.shortcutListener);
}
override disconnectedCallback() {
this.shortcuts.removeListener(this.shortcutListener);
super.disconnectedCallback();
}
private handleCloseTap(e: MouseEvent) {
e.preventDefault();
e.stopPropagation();
... | connectedCallback | identifier_name |
gr-keyboard-shortcuts-dialog.ts | /**
* @license
* Copyright (C) 2016 The Android Open Source Project
*
* 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 require... |
_onDirectoryUpdated(directory?: Map<ShortcutSection, SectionView>) {
if (!directory) {
return;
}
const left = [] as SectionShortcut[];
const right = [] as SectionShortcut[];
if (directory.has(ShortcutSection.EVERYWHERE)) {
left.push({
section: ShortcutSection.EVERYWHERE,
... | {
e.preventDefault();
e.stopPropagation();
this.dispatchEvent(
new CustomEvent('close', {
composed: true,
bubbles: false,
})
);
} | identifier_body |
menu.js | /*
Author: mg12
Update: 2009/08/07
Author URI: http://www.neoease.com/
*/
(function() {
var Class = {
create: function() {
return function() {
this.initialize.apply(this, arguments);
}
}
}
var GhostlyMenu = Class.create();
GhostlyMenu.prototype = {
initialize: function(target, align, sub) {
this.obj = cl... | var tid = setInterval( function() {
clearInterval(tid);
if (!/current/.test(thismenu.title.className)) {
setStyle(thismenu.body, 'visibility', 'hidden');
}
return false;
}, 400);
}
}
$A = function(iterable) {
if(!iterable) {
return [];
}
if(iterable.toArray) {
return iterable.toArray();
} ... | var thismenu = this; | random_line_split |
menu.js | /*
Author: mg12
Update: 2009/08/07
Author URI: http://www.neoease.com/
*/
(function() {
var Class = {
create: function() {
return function() {
this.initialize.apply(this, arguments);
}
}
}
var GhostlyMenu = Class.create();
GhostlyMenu.prototype = {
initialize: function(target, align, sub) {
this.obj = cl... |
if (document.addEventListener) {
document.addEventListener("DOMContentLoaded", loadMenus, false);
} else if (/MSIE/i.test(navigator.userAgent)) {
document.write('<script id="__ie_onload_for_Julie" defer src="javascript:void(0)"></script>');
var script = document.getElementById('__ie_onload_for_Julie');
script.on... | {
var align = 'left';
for(var i = 0; (a = document.getElementsByTagName('link')[i]); i++) {
if((a.getAttribute('rel') == 'stylesheet') && (a.getAttribute('href').indexOf('rtl.css') != -1)) {
align = 'right';
}
}
var subscribe = document.getElementById('subscribe');
if (subscribe) {
new GhostlyMenu(subscr... | identifier_body |
menu.js | /*
Author: mg12
Update: 2009/08/07
Author URI: http://www.neoease.com/
*/
(function() {
var Class = {
create: function() {
return function() {
this.initialize.apply(this, arguments);
}
}
}
var GhostlyMenu = Class.create();
GhostlyMenu.prototype = {
initialize: function(target, align, sub) {
this.obj = cl... | () {
var align = 'left';
for(var i = 0; (a = document.getElementsByTagName('link')[i]); i++) {
if((a.getAttribute('rel') == 'stylesheet') && (a.getAttribute('href').indexOf('rtl.css') != -1)) {
align = 'right';
}
}
var subscribe = document.getElementById('subscribe');
if (subscribe) {
new GhostlyMenu(sub... | loadMenus | identifier_name |
meus_marcados-service.ts | import { MappingsService } from './_mappings-service';
import { VitrineVO } from './../../model/vitrineVO';
import { FirebaseService } from './../database/firebase-service';
import { Injectable } from '@angular/core';
@Injectable()
export class MeusMarcadosService {
private meusMarcadosRef: any;
constructor(priv... |
public getMeusMarcadosRef() {
return this.meusMarcadosRef;
}
public getMeusMarcadosPorUsuario(uidUsuario: string) {
return this.meusMarcadosRef.child(uidUsuario).orderByKey().once('value');
}
public salvar(uidUsuario: string, vitrine: VitrineVO) {
var newKey = this.meusMarcadosRef.child(uidUsu... | {
this.meusMarcadosRef = this.fbService.getDataBase().ref('minhavitrine');
} | identifier_body |
meus_marcados-service.ts | import { MappingsService } from './_mappings-service';
import { VitrineVO } from './../../model/vitrineVO';
import { FirebaseService } from './../database/firebase-service';
import { Injectable } from '@angular/core';
@Injectable()
export class MeusMarcadosService {
private meusMarcadosRef: any;
constructor(priv... | }
public getMeusMarcadosRef() {
return this.meusMarcadosRef;
}
public getMeusMarcadosPorUsuario(uidUsuario: string) {
return this.meusMarcadosRef.child(uidUsuario).orderByKey().once('value');
}
public salvar(uidUsuario: string, vitrine: VitrineVO) {
var newKey = this.meusMarcadosRef.child(uid... | private mapSrv: MappingsService) {
this.meusMarcadosRef = this.fbService.getDataBase().ref('minhavitrine'); | random_line_split |
meus_marcados-service.ts | import { MappingsService } from './_mappings-service';
import { VitrineVO } from './../../model/vitrineVO';
import { FirebaseService } from './../database/firebase-service';
import { Injectable } from '@angular/core';
@Injectable()
export class MeusMarcadosService {
private meusMarcadosRef: any;
constructor(priv... | () {
return this.meusMarcadosRef;
}
public getMeusMarcadosPorUsuario(uidUsuario: string) {
return this.meusMarcadosRef.child(uidUsuario).orderByKey().once('value');
}
public salvar(uidUsuario: string, vitrine: VitrineVO) {
var newKey = this.meusMarcadosRef.child(uidUsuario).push().key
this.meu... | getMeusMarcadosRef | identifier_name |
base.py | # -*- coding: utf-8 -*-
import re
from math import modf
from datetime import datetime, timedelta
## {{{ http://code.activestate.com/recipes/65215/ (r5)
EMAIL_PATTERN = re.compile('^.+\\@(\\[?)[a-zA-Z0-9\\-\\.]' \
'+\\.([a-zA-Z]{2,3}|[0-9]{1,3})(\\]?)$')
def to_unicode(text):
'''
C... | (data):
'''
Gets the size in bytes of a str.
@return: long
'''
return len(data)
| size_in_bytes | identifier_name |
base.py | # -*- coding: utf-8 -*-
import re
from math import modf
from datetime import datetime, timedelta
## {{{ http://code.activestate.com/recipes/65215/ (r5)
EMAIL_PATTERN = re.compile('^.+\\@(\\[?)[a-zA-Z0-9\\-\\.]' \
'+\\.([a-zA-Z]{2,3}|[0-9]{1,3})(\\]?)$')
def to_unicode(text):
'''
C... |
def extract_id_from_uri(s):
'''
Returns the ID section of an URI.
@param s:str URI
@return: str
'''
return [ item for item in s.split("/") if item ][-1]
def size_in_bytes(data):
'''
Gets the size in bytes of a str.
@return: long
'''
return len(data)
| '''
Converts a datetime instance into a timestamp string.
@param d:datetime Date instance
@return:long
'''
return long(d.strftime("%s") + "%03d" % (d.time().microsecond / 1000)) | identifier_body |
base.py | # -*- coding: utf-8 -*-
import re
from math import modf
from datetime import datetime, timedelta
## {{{ http://code.activestate.com/recipes/65215/ (r5) |
def to_unicode(text):
'''
Converts an input text to a unicode object.
@param text:object Input text
@returns:unicode
'''
return text.decode("UTF-8") if type(text) == str else unicode(text)
def to_byte_string(text):
'''
Converts an input text to a unicode object.
@param text:objec... | EMAIL_PATTERN = re.compile('^.+\\@(\\[?)[a-zA-Z0-9\\-\\.]' \
'+\\.([a-zA-Z]{2,3}|[0-9]{1,3})(\\]?)$') | random_line_split |
wsgi.py | """
WSGI config for influencetx project.
This module contains the WSGI application used by Django's development server
and any production WSGI deployments. It should expose a module-level variable
named ``application``. Django's ``runserver`` and ``runfcgi`` commands discover
this application via the ``WSGI_APPLICATIO... | #if os.environ.get('DJANGO_SETTINGS_MODULE') == 'config.settings.production':
# application = Sentry(application)
# Apply WSGI middleware here.
#from influencetx.wsgi import influencetx
#application = influencetx(application) | # file. This includes Django's development server, if the WSGI_APPLICATION
# setting points here.
application = get_wsgi_application() | random_line_split |
wsgi.py | """
WSGI config for influencetx project.
This module contains the WSGI application used by Django's development server
and any production WSGI deployments. It should expose a module-level variable
named ``application``. Django's ``runserver`` and ``runfcgi`` commands discover
this application via the ``WSGI_APPLICATIO... |
# We defer to a DJANGO_SETTINGS_MODULE already in the environment. This breaks
# if running multiple sites in the same mod_wsgi process. To fix this, use
# mod_wsgi daemon mode with each site in its own daemon process, or use
# os.environ["DJANGO_SETTINGS_MODULE"] = "config.settings.production"
os.environ.setdefault(... | from raven.contrib.django.raven_compat.middleware.wsgi import Sentry | conditional_block |
seg_queue.rs | use std::sync::atomic::Ordering::{Acquire, Release, Relaxed};
use std::sync::atomic::{AtomicBool, AtomicUsize};
use std::{ptr, mem};
use std::cmp;
use std::cell::UnsafeCell;
use mem::epoch::{self, Atomic, Owned};
const SEG_SIZE: usize = 32;
/// A Michael-Scott queue that allocates "segments" (arrays of nodes)
/// fo... |
}
| {
enum LR { Left(i64), Right(i64) }
let q: SegQueue<LR> = SegQueue::new();
scope(|scope| {
for _t in 0..2 {
scope.spawn(|| {
for i in CONC_COUNT-1..CONC_COUNT {
q.push(LR::Left(i))
}
});... | identifier_body |
seg_queue.rs | use std::sync::atomic::Ordering::{Acquire, Release, Relaxed};
use std::sync::atomic::{AtomicBool, AtomicUsize};
use std::{ptr, mem};
use std::cmp;
use std::cell::UnsafeCell;
use mem::epoch::{self, Atomic, Owned};
const SEG_SIZE: usize = 32;
/// A Michael-Scott queue that allocates "segments" (arrays of nodes)
/// fo... |
}
}
let mut vl2 = vl.clone();
let mut vr2 = vr.clone();
vl2.sort();
vr2.sort();
assert_eq!(vl, vl2);
assert_eq!(vr, vr2);
});
... | {} | conditional_block |
seg_queue.rs | use std::sync::atomic::Ordering::{Acquire, Release, Relaxed};
use std::sync::atomic::{AtomicBool, AtomicUsize};
use std::{ptr, mem};
use std::cmp;
use std::cell::UnsafeCell;
use mem::epoch::{self, Atomic, Owned};
const SEG_SIZE: usize = 32;
/// A Michael-Scott queue that allocates "segments" (arrays of nodes)
/// fo... | () {
let q: SegQueue<i64> = SegQueue::new();
q.push(37);
q.push(48);
assert_eq!(q.pop(), Some(37));
assert_eq!(q.pop(), Some(48));
}
#[test]
fn push_pop_many_seq() {
let q: SegQueue<i64> = SegQueue::new();
for i in 0..200 {
q.push(i)
... | push_pop_2 | identifier_name |
seg_queue.rs | use std::sync::atomic::Ordering::{Acquire, Release, Relaxed};
use std::sync::atomic::{AtomicBool, AtomicUsize};
use std::{ptr, mem};
use std::cmp;
use std::cell::UnsafeCell;
use mem::epoch::{self, Atomic, Owned};
const SEG_SIZE: usize = 32;
/// A Michael-Scott queue that allocates "segments" (arrays of nodes)
/// fo... | next: Atomic::null(),
}
}
}
impl<T> SegQueue<T> {
/// Create a enw, emtpy queue.
pub fn new() -> SegQueue<T> {
let q = SegQueue {
head: Atomic::null(),
tail: Atomic::null(),
};
let sentinel = Owned::new(Segment::new());
let guard =... | low: AtomicUsize::new(0),
high: AtomicUsize::new(0), | random_line_split |
commandlineparser.ts | import * as types from "./types";
import * as yargs from "yargs";
export const SECURITIES_DEFAULT = "*";
export const SOURCE_EXTENSION_DEFAULT = "csv";
export interface CommandLineParserResult {
options: types.LeanDataKitConversionOptions;
error: string;
}
class CommandLineParserResultImpl implements Command... | (message: string): any {
parseErrors = message;
console.error(message);
}
let options: any = yargs.alias("output-directory", "o")
.alias("securities", "s")
.alias("securities-file", "f")
.alias("input-directory", "i")
.alias("sourc... | fail | identifier_name |
commandlineparser.ts | import * as types from "./types";
import * as yargs from "yargs";
export const SECURITIES_DEFAULT = "*";
export const SOURCE_EXTENSION_DEFAULT = "csv";
export interface CommandLineParserResult {
options: types.LeanDataKitConversionOptions;
error: string;
}
class CommandLineParserResultImpl implements Command... | let options: any = yargs.alias("output-directory", "o")
.alias("securities", "s")
.alias("securities-file", "f")
.alias("input-directory", "i")
.alias("source-extension", "e")
.alias("data-provider", "p")
.demand("p", "the name of the data ... | random_line_split | |
commandlineparser.ts | import * as types from "./types";
import * as yargs from "yargs";
export const SECURITIES_DEFAULT = "*";
export const SOURCE_EXTENSION_DEFAULT = "csv";
export interface CommandLineParserResult {
options: types.LeanDataKitConversionOptions;
error: string;
}
class CommandLineParserResultImpl implements Command... |
}
export class CommandLineParser {
public parse(args: string[]): CommandLineParserResult {
let parseErrors: string = "";
function fail(message: string): any {
parseErrors = message;
console.error(message);
}
let options: any = yargs.alias("output-directory... | {
this.options = options;
this.error = error;
} | identifier_body |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.