code stringlengths 51 2.34k | sequence stringlengths 186 3.94k | docstring stringlengths 11 171 |
|---|---|---|
def write(self, text):
sys.stdout.write("\r")
self._clear_line()
_text = to_unicode(text)
if PY2:
_text = _text.encode(ENCODING)
assert isinstance(_text, builtin_str)
sys.stdout.write("{0}\n".format(_text)) | module function_definition identifier parameters identifier identifier block expression_statement call attribute attribute identifier identifier identifier argument_list string string_start string_content escape_sequence string_end expression_statement call attribute identifier identifier argument_list expression_statement assignment identifier call identifier argument_list identifier if_statement identifier block expression_statement assignment identifier call attribute identifier identifier argument_list identifier assert_statement call identifier argument_list identifier identifier expression_statement call attribute attribute identifier identifier identifier argument_list call attribute string string_start string_content escape_sequence string_end identifier argument_list identifier | Write text in the terminal without breaking the spinner. |
def normalize(pw):
pw_lower = pw.lower()
return ''.join(helper.L33T.get(c, c) for c in pw_lower) | module function_definition identifier parameters identifier block expression_statement assignment identifier call attribute identifier identifier argument_list return_statement call attribute string string_start string_end identifier generator_expression call attribute attribute identifier identifier identifier argument_list identifier identifier for_in_clause identifier identifier | Lower case, and change the symbols to closest characters |
def missing_count(self):
if self.means:
return self.means.missing_count
return self._cube_dict["result"].get("missing", 0) | module function_definition identifier parameters identifier block if_statement attribute identifier identifier block return_statement attribute attribute identifier identifier identifier return_statement call attribute subscript attribute identifier identifier string string_start string_content string_end identifier argument_list string string_start string_content string_end integer | numeric representing count of missing rows in cube response. |
def scramble_native_password(password, message):
if not password:
return b''
stage1 = sha1_new(password).digest()
stage2 = sha1_new(stage1).digest()
s = sha1_new()
s.update(message[:SCRAMBLE_LENGTH])
s.update(stage2)
result = s.digest()
return _my_crypt(result, stage1) | module function_definition identifier parameters identifier identifier block if_statement not_operator identifier block return_statement string string_start string_end expression_statement assignment identifier call attribute call identifier argument_list identifier identifier argument_list expression_statement assignment identifier call attribute call identifier argument_list identifier identifier argument_list expression_statement assignment identifier call identifier argument_list expression_statement call attribute identifier identifier argument_list subscript identifier slice identifier expression_statement call attribute identifier identifier argument_list identifier expression_statement assignment identifier call attribute identifier identifier argument_list return_statement call identifier argument_list identifier identifier | Scramble used for mysql_native_password |
def update_cache(self, data=None):
if data:
self.cache_data = data
self.cache_updated = timezone.now()
self.save() | module function_definition identifier parameters identifier default_parameter identifier none block if_statement identifier block expression_statement assignment attribute identifier identifier identifier expression_statement assignment attribute identifier identifier call attribute identifier identifier argument_list expression_statement call attribute identifier identifier argument_list | call with new data or set data to self.cache_data and call this |
def _clean_X_y(X, y):
return make_2d(X, verbose=False).astype('float'), y.astype('float') | module function_definition identifier parameters identifier identifier block return_statement expression_list call attribute call identifier argument_list identifier keyword_argument identifier false identifier argument_list string string_start string_content string_end call attribute identifier identifier argument_list string string_start string_content string_end | ensure that X and y data are float and correct shapes |
def diff(self):
self.mmb.complement(self.alphabet)
self.mmb.minimize()
print 'start intersection'
self.mmc = self._intesect()
print 'end intersection'
return self.mmc | module function_definition identifier parameters identifier block expression_statement call attribute attribute identifier identifier identifier argument_list attribute identifier identifier expression_statement call attribute attribute identifier identifier identifier argument_list print_statement string string_start string_content string_end expression_statement assignment attribute identifier identifier call attribute identifier identifier argument_list print_statement string string_start string_content string_end return_statement attribute identifier identifier | The Difference between a PDA and a DFA |
def element(self, inp=None):
if inp is not None:
s = str(inp)[:self.length]
s += ' ' * (self.length - len(s))
return s
else:
return ' ' * self.length | module function_definition identifier parameters identifier default_parameter identifier none block if_statement comparison_operator identifier none block expression_statement assignment identifier subscript call identifier argument_list identifier slice attribute identifier identifier expression_statement augmented_assignment identifier binary_operator string string_start string_content string_end parenthesized_expression binary_operator attribute identifier identifier call identifier argument_list identifier return_statement identifier else_clause block return_statement binary_operator string string_start string_content string_end attribute identifier identifier | Return an element from ``inp`` or from scratch. |
def _GenerateCSRFKey(config):
secret_key = config.Get("AdminUI.csrf_secret_key", None)
if not secret_key:
secret_key = config.Get("AdminUI.django_secret_key", None)
if secret_key:
config.Set("AdminUI.csrf_secret_key", secret_key)
if not secret_key:
key = utils.GeneratePassphrase(length=100)
config.Set("AdminUI.csrf_secret_key", key)
else:
print("Not updating csrf key as it is already set.") | module function_definition identifier parameters identifier block expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end none if_statement not_operator identifier block expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end none if_statement identifier block expression_statement call attribute identifier identifier argument_list string string_start string_content string_end identifier if_statement not_operator identifier block expression_statement assignment identifier call attribute identifier identifier argument_list keyword_argument identifier integer expression_statement call attribute identifier identifier argument_list string string_start string_content string_end identifier else_clause block expression_statement call identifier argument_list string string_start string_content string_end | Update a config with a random csrf key. |
def ruleName(self):
return '%s %s' % (self.rentalRate, self.RateRuleChoices.values.get(self.applyRateRule,self.applyRateRule)) | module function_definition identifier parameters identifier block return_statement binary_operator string string_start string_content string_end tuple attribute identifier identifier call attribute attribute attribute identifier identifier identifier identifier argument_list attribute identifier identifier attribute identifier identifier | This should be overridden for child classes |
def find_file(config_file=None, default_directories=None, default_bases=None):
if config_file:
if path.exists(path.expanduser(config_file)):
return config_file
else:
raise FileNotFoundError('Config file not found: {}'.format(config_file))
dirs = default_directories or CONFIG_DIRS
dirs = [getcwd()] + dirs
bases = default_bases or CONFIG_BASES
for directory, base in product(dirs, bases):
filepath = path.expanduser(path.join(directory, base))
if path.exists(filepath):
return filepath
raise FileNotFoundError('Config file not found in {}'.format(dirs)) | module function_definition identifier parameters default_parameter identifier none default_parameter identifier none default_parameter identifier none block if_statement identifier block if_statement call attribute identifier identifier argument_list call attribute identifier identifier argument_list identifier block return_statement identifier else_clause block raise_statement call identifier argument_list call attribute string string_start string_content string_end identifier argument_list identifier expression_statement assignment identifier boolean_operator identifier identifier expression_statement assignment identifier binary_operator list call identifier argument_list identifier expression_statement assignment identifier boolean_operator identifier identifier for_statement pattern_list identifier identifier call identifier argument_list identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list call attribute identifier identifier argument_list identifier identifier if_statement call attribute identifier identifier argument_list identifier block return_statement identifier raise_statement call identifier argument_list call attribute string string_start string_content string_end identifier argument_list identifier | Search for a config file in a list of files. |
def xywh_from_points(points):
xys = [[int(p) for p in pair.split(',')] for pair in points.split(' ')]
minx = sys.maxsize
miny = sys.maxsize
maxx = 0
maxy = 0
for xy in xys:
if xy[0] < minx:
minx = xy[0]
if xy[0] > maxx:
maxx = xy[0]
if xy[1] < miny:
miny = xy[1]
if xy[1] > maxy:
maxy = xy[1]
return {
'x': minx,
'y': miny,
'w': maxx - minx,
'h': maxy - miny,
} | module function_definition identifier parameters identifier block expression_statement assignment identifier list_comprehension list_comprehension call identifier argument_list identifier for_in_clause identifier call attribute identifier identifier argument_list string string_start string_content string_end for_in_clause identifier call attribute identifier identifier argument_list string string_start string_content string_end expression_statement assignment identifier attribute identifier identifier expression_statement assignment identifier attribute identifier identifier expression_statement assignment identifier integer expression_statement assignment identifier integer for_statement identifier identifier block if_statement comparison_operator subscript identifier integer identifier block expression_statement assignment identifier subscript identifier integer if_statement comparison_operator subscript identifier integer identifier block expression_statement assignment identifier subscript identifier integer if_statement comparison_operator subscript identifier integer identifier block expression_statement assignment identifier subscript identifier integer if_statement comparison_operator subscript identifier integer identifier block expression_statement assignment identifier subscript identifier integer return_statement dictionary pair string string_start string_content string_end identifier pair string string_start string_content string_end identifier pair string string_start string_content string_end binary_operator identifier identifier pair string string_start string_content string_end binary_operator identifier identifier | Constructs an dict representing a rectangle with keys x, y, w, h |
def execute(self):
try:
for key, value in self._watched_keys.items():
if self.mock_redis.redis.get(self.mock_redis._encode(key)) != value:
raise WatchError("Watched variable changed.")
return [command() for command in self.commands]
finally:
self._reset() | module function_definition identifier parameters identifier block try_statement block for_statement pattern_list identifier identifier call attribute attribute identifier identifier identifier argument_list block if_statement comparison_operator call attribute attribute attribute identifier identifier identifier identifier argument_list call attribute attribute identifier identifier identifier argument_list identifier identifier block raise_statement call identifier argument_list string string_start string_content string_end return_statement list_comprehension call identifier argument_list for_in_clause identifier attribute identifier identifier finally_clause block expression_statement call attribute identifier identifier argument_list | Execute all of the saved commands and return results. |
def count(self, eventRegistry):
self.setRequestedResult(RequestEventsInfo())
res = eventRegistry.execQuery(self)
if "error" in res:
print(res["error"])
count = res.get("events", {}).get("totalResults", 0)
return count | module function_definition identifier parameters identifier identifier block expression_statement call attribute identifier identifier argument_list call identifier argument_list expression_statement assignment identifier call attribute identifier identifier argument_list identifier if_statement comparison_operator string string_start string_content string_end identifier block expression_statement call identifier argument_list subscript identifier string string_start string_content string_end expression_statement assignment identifier call attribute call attribute identifier identifier argument_list string string_start string_content string_end dictionary identifier argument_list string string_start string_content string_end integer return_statement identifier | return the number of events that match the criteria |
def _find_usage_spot_instances(self):
logger.debug('Getting spot instance request usage')
try:
res = self.conn.describe_spot_instance_requests()
except botocore.exceptions.ClientError as e:
if e.response['Error']['Code'] == 'UnsupportedOperation':
return
raise
count = 0
for req in res['SpotInstanceRequests']:
if req['State'] in ['open', 'active']:
count += 1
logger.debug('Counting spot instance request %s state=%s',
req['SpotInstanceRequestId'], req['State'])
else:
logger.debug('NOT counting spot instance request %s state=%s',
req['SpotInstanceRequestId'], req['State'])
self.limits['Max spot instance requests per region']._add_current_usage(
count,
aws_type='AWS::EC2::SpotInstanceRequest'
) | module function_definition identifier parameters identifier block expression_statement call attribute identifier identifier argument_list string string_start string_content string_end try_statement block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list except_clause as_pattern attribute attribute identifier identifier identifier as_pattern_target identifier block if_statement comparison_operator subscript subscript attribute identifier identifier string string_start string_content string_end string string_start string_content string_end string string_start string_content string_end block return_statement raise_statement expression_statement assignment identifier integer for_statement identifier subscript identifier string string_start string_content string_end block if_statement comparison_operator subscript identifier string string_start string_content string_end list string string_start string_content string_end string string_start string_content string_end block expression_statement augmented_assignment identifier integer expression_statement call attribute identifier identifier argument_list string string_start string_content string_end subscript identifier string string_start string_content string_end subscript identifier string string_start string_content string_end else_clause block expression_statement call attribute identifier identifier argument_list string string_start string_content string_end subscript identifier string string_start string_content string_end subscript identifier string string_start string_content string_end expression_statement call attribute subscript attribute identifier identifier string string_start string_content string_end identifier argument_list identifier keyword_argument identifier string string_start string_content string_end | calculate spot instance request usage and update Limits |
def predict_y(self, Xnew):
pred_f_mean, pred_f_var = self._build_predict(Xnew)
return self.likelihood.predict_mean_and_var(pred_f_mean, pred_f_var) | module function_definition identifier parameters identifier identifier block expression_statement assignment pattern_list identifier identifier call attribute identifier identifier argument_list identifier return_statement call attribute attribute identifier identifier identifier argument_list identifier identifier | Compute the mean and variance of held-out data at the points Xnew |
def rm_rf(path):
if os.path.isfile(path):
os.unlink(path)
elif os.path.isdir(path):
for root, dirs, files in os.walk(path, topdown=False):
for filename in files:
filepath = os.path.join(root, filename)
logger.info("Deleting file %s" % filepath)
os.unlink(filepath)
for dirname in dirs:
dirpath = os.path.join(root, dirname)
if os.path.islink(dirpath):
logger.info("Deleting link %s" % dirpath)
os.unlink(dirpath)
else:
logger.info("Deleting dir %s" % dirpath)
os.rmdir(dirpath)
logger.info("Deleting dir %s", path)
os.rmdir(path) | module function_definition identifier parameters identifier block if_statement call attribute attribute identifier identifier identifier argument_list identifier block expression_statement call attribute identifier identifier argument_list identifier elif_clause call attribute attribute identifier identifier identifier argument_list identifier block for_statement pattern_list identifier identifier identifier call attribute identifier identifier argument_list identifier keyword_argument identifier false block for_statement identifier identifier block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list identifier identifier expression_statement call attribute identifier identifier argument_list binary_operator string string_start string_content string_end identifier expression_statement call attribute identifier identifier argument_list identifier for_statement identifier identifier block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list identifier identifier if_statement call attribute attribute identifier identifier identifier argument_list identifier block expression_statement call attribute identifier identifier argument_list binary_operator string string_start string_content string_end identifier expression_statement call attribute identifier identifier argument_list identifier else_clause block expression_statement call attribute identifier identifier argument_list binary_operator string string_start string_content string_end identifier expression_statement call attribute identifier identifier argument_list identifier expression_statement call attribute identifier identifier argument_list string string_start string_content string_end identifier expression_statement call attribute identifier identifier argument_list identifier | Act as 'rm -rf' in the shell |
def register(self):
log.info('Installing ssh key, %s' % self.name)
self.consul.create_ssh_pub_key(self.name, self.key) | module function_definition identifier parameters identifier block expression_statement call attribute identifier identifier argument_list binary_operator string string_start string_content string_end attribute identifier identifier expression_statement call attribute attribute identifier identifier identifier argument_list attribute identifier identifier attribute identifier identifier | Registers SSH key with provider. |
def _new_replica(self, instance_id: int, is_master: bool, bls_bft: BlsBft) -> Replica:
return self._replica_class(self._node, instance_id, self._config, is_master, bls_bft, self._metrics) | module function_definition identifier parameters identifier typed_parameter identifier type identifier typed_parameter identifier type identifier typed_parameter identifier type identifier type identifier block return_statement call attribute identifier identifier argument_list attribute identifier identifier identifier attribute identifier identifier identifier identifier attribute identifier identifier | Create a new replica with the specified parameters. |
def load_jupyter_server_extension(nb_server_app):
app = nb_server_app.web_app
host_pattern = '.*$'
app.add_handlers(host_pattern, [
(utils.url_path_join(app.settings['base_url'], '/http_over_websocket'),
handlers.HttpOverWebSocketHandler),
(utils.url_path_join(app.settings['base_url'],
'/http_over_websocket/diagnose'),
handlers.HttpOverWebSocketDiagnosticHandler),
])
print('jupyter_http_over_ws extension initialized. Listening on '
'/http_over_websocket') | module function_definition identifier parameters identifier block expression_statement assignment identifier attribute identifier identifier expression_statement assignment identifier string string_start string_content string_end expression_statement call attribute identifier identifier argument_list identifier list tuple call attribute identifier identifier argument_list subscript attribute identifier identifier string string_start string_content string_end string string_start string_content string_end attribute identifier identifier tuple call attribute identifier identifier argument_list subscript attribute identifier identifier string string_start string_content string_end string string_start string_content string_end attribute identifier identifier expression_statement call identifier argument_list concatenated_string string string_start string_content string_end string string_start string_content string_end | Called by Jupyter when this module is loaded as a server extension. |
def generate(self, request, **kwargs):
self.method_check(request, allowed=['get'])
basic_bundle = self.build_bundle(request=request)
tileset = self.cached_obj_get(
bundle=basic_bundle,
**self.remove_api_resource_names(kwargs))
return self.create_response(request, tileset.generate()) | module function_definition identifier parameters identifier identifier dictionary_splat_pattern identifier block expression_statement call attribute identifier identifier argument_list identifier keyword_argument identifier list string string_start string_content string_end expression_statement assignment identifier call attribute identifier identifier argument_list keyword_argument identifier identifier expression_statement assignment identifier call attribute identifier identifier argument_list keyword_argument identifier identifier dictionary_splat call attribute identifier identifier argument_list identifier return_statement call attribute identifier identifier argument_list identifier call attribute identifier identifier argument_list | proxy for the tileset.generate method |
def data_filler_customer(self, number_of_rows, db):
try:
customer = db
data_list = list()
for i in range(0, number_of_rows):
post_cus_reg = {
"id": rnd_id_generator(self),
"name": self.faker.first_name(),
"lastname": self.faker.last_name(),
"address": self.faker.address(),
"country": self.faker.country(),
"city": self.faker.city(),
"registry_date": self.faker.date(pattern="%d-%m-%Y"),
"birthdate": self.faker.date(pattern="%d-%m-%Y"),
"email": self.faker.safe_email(),
"phone_number": self.faker.phone_number(),
"locale": self.faker.locale()
}
customer.save(post_cus_reg)
logger.warning('customer Commits are successful after write job!',
extra=d)
except Exception as e:
logger.error(e, extra=d) | module function_definition identifier parameters identifier identifier identifier block try_statement block expression_statement assignment identifier identifier expression_statement assignment identifier call identifier argument_list for_statement identifier call identifier argument_list integer identifier block expression_statement assignment identifier dictionary pair string string_start string_content string_end call identifier argument_list identifier pair string string_start string_content string_end call attribute attribute identifier identifier identifier argument_list pair string string_start string_content string_end call attribute attribute identifier identifier identifier argument_list pair string string_start string_content string_end call attribute attribute identifier identifier identifier argument_list pair string string_start string_content string_end call attribute attribute identifier identifier identifier argument_list pair string string_start string_content string_end call attribute attribute identifier identifier identifier argument_list pair string string_start string_content string_end call attribute attribute identifier identifier identifier argument_list keyword_argument identifier string string_start string_content string_end pair string string_start string_content string_end call attribute attribute identifier identifier identifier argument_list keyword_argument identifier string string_start string_content string_end pair string string_start string_content string_end call attribute attribute identifier identifier identifier argument_list pair string string_start string_content string_end call attribute attribute identifier identifier identifier argument_list pair string string_start string_content string_end call attribute attribute identifier identifier identifier argument_list expression_statement call attribute identifier identifier argument_list identifier expression_statement call attribute identifier identifier argument_list string string_start string_content string_end keyword_argument identifier identifier except_clause as_pattern identifier as_pattern_target identifier block expression_statement call attribute identifier identifier argument_list identifier keyword_argument identifier identifier | creates and fills the table with customer data |
def _rd_fld_vals(name, val, set_list_ft=True, qty_min=0, qty_max=None):
if not val and qty_min == 0:
return [] if set_list_ft else set()
vals = val.split('|')
num_vals = len(vals)
assert num_vals >= qty_min, \
"FLD({F}): MIN QUANTITY({Q}) WASN'T MET: {V}".format(
F=name, Q=qty_min, V=vals)
if qty_max is not None:
assert num_vals <= qty_max, \
"FLD({F}): MAX QUANTITY({Q}) EXCEEDED: {V}".format(
F=name, Q=qty_max, V=vals)
return vals if set_list_ft else set(vals) | module function_definition identifier parameters identifier identifier default_parameter identifier true default_parameter identifier integer default_parameter identifier none block if_statement boolean_operator not_operator identifier comparison_operator identifier integer block return_statement conditional_expression list identifier call identifier argument_list expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end expression_statement assignment identifier call identifier argument_list identifier assert_statement comparison_operator identifier identifier call attribute string string_start string_content string_end identifier argument_list keyword_argument identifier identifier keyword_argument identifier identifier keyword_argument identifier identifier if_statement comparison_operator identifier none block assert_statement comparison_operator identifier identifier call attribute string string_start string_content string_end identifier argument_list keyword_argument identifier identifier keyword_argument identifier identifier keyword_argument identifier identifier return_statement conditional_expression identifier identifier call identifier argument_list identifier | Further split a GPAD value within a single field. |
def petl(self, *args, **kwargs):
import petl
t = self.resolved_url.get_resource().get_target()
if t.target_format == 'txt':
return petl.fromtext(str(t.fspath), *args, **kwargs)
elif t.target_format == 'csv':
return petl.fromcsv(str(t.fspath), *args, **kwargs)
else:
raise Exception("Can't handle") | module function_definition identifier parameters identifier list_splat_pattern identifier dictionary_splat_pattern identifier block import_statement dotted_name identifier expression_statement assignment identifier call attribute call attribute attribute identifier identifier identifier argument_list identifier argument_list if_statement comparison_operator attribute identifier identifier string string_start string_content string_end block return_statement call attribute identifier identifier argument_list call identifier argument_list attribute identifier identifier list_splat identifier dictionary_splat identifier elif_clause comparison_operator attribute identifier identifier string string_start string_content string_end block return_statement call attribute identifier identifier argument_list call identifier argument_list attribute identifier identifier list_splat identifier dictionary_splat identifier else_clause block raise_statement call identifier argument_list string string_start string_content string_end | Return a PETL source object |
def extract_imports(script):
if not os.path.isfile(script):
raise ValueError('Not a file: %s' % script)
parse_tree = parse_python(script)
result = find_imports(parse_tree)
result.path = script
return result | module function_definition identifier parameters identifier block if_statement not_operator call attribute attribute identifier identifier identifier argument_list identifier block raise_statement call identifier argument_list binary_operator string string_start string_content string_end identifier expression_statement assignment identifier call identifier argument_list identifier expression_statement assignment identifier call identifier argument_list identifier expression_statement assignment attribute identifier identifier identifier return_statement identifier | Extract all imports from a python script |
def _map_unity_proxy_to_object(value):
vtype = type(value)
if vtype in _proxy_map:
return _proxy_map[vtype](value)
elif vtype == list:
return [_map_unity_proxy_to_object(v) for v in value]
elif vtype == dict:
return {k:_map_unity_proxy_to_object(v) for k,v in value.items()}
else:
return value | module function_definition identifier parameters identifier block expression_statement assignment identifier call identifier argument_list identifier if_statement comparison_operator identifier identifier block return_statement call subscript identifier identifier argument_list identifier elif_clause comparison_operator identifier identifier block return_statement list_comprehension call identifier argument_list identifier for_in_clause identifier identifier elif_clause comparison_operator identifier identifier block return_statement dictionary_comprehension pair identifier call identifier argument_list identifier for_in_clause pattern_list identifier identifier call attribute identifier identifier argument_list else_clause block return_statement identifier | Map returning value, if it is unity SFrame, SArray, map it |
def _build_url(self, shorten=True):
self.url = URL_FORMAT.format(*self._get_url_params(shorten=shorten)) | module function_definition identifier parameters identifier default_parameter identifier true block expression_statement assignment attribute identifier identifier call attribute identifier identifier argument_list list_splat call attribute identifier identifier argument_list keyword_argument identifier identifier | Build the url for a cable ratings page |
def check_py(self, version, name, original, loc, tokens):
internal_assert(len(tokens) == 1, "invalid " + name + " tokens", tokens)
if self.target_info < get_target_info(version):
raise self.make_err(CoconutTargetError, "found Python " + ".".join(version) + " " + name, original, loc, target=version)
else:
return tokens[0] | module function_definition identifier parameters identifier identifier identifier identifier identifier identifier block expression_statement call identifier argument_list comparison_operator call identifier argument_list identifier integer binary_operator binary_operator string string_start string_content string_end identifier string string_start string_content string_end identifier if_statement comparison_operator attribute identifier identifier call identifier argument_list identifier block raise_statement call attribute identifier identifier argument_list identifier binary_operator binary_operator binary_operator string string_start string_content string_end call attribute string string_start string_content string_end identifier argument_list identifier string string_start string_content string_end identifier identifier identifier keyword_argument identifier identifier else_clause block return_statement subscript identifier integer | Check for Python-version-specific syntax. |
def create_cnn_model(base_arch:Callable, nc:int, cut:Union[int,Callable]=None, pretrained:bool=True,
lin_ftrs:Optional[Collection[int]]=None, ps:Floats=0.5, custom_head:Optional[nn.Module]=None,
split_on:Optional[SplitFuncOrIdxList]=None, bn_final:bool=False, concat_pool:bool=True):
"Create custom convnet architecture"
body = create_body(base_arch, pretrained, cut)
if custom_head is None:
nf = num_features_model(nn.Sequential(*body.children())) * (2 if concat_pool else 1)
head = create_head(nf, nc, lin_ftrs, ps=ps, concat_pool=concat_pool, bn_final=bn_final)
else: head = custom_head
return nn.Sequential(body, head) | module function_definition identifier parameters typed_parameter identifier type identifier typed_parameter identifier type identifier typed_default_parameter identifier type generic_type identifier type_parameter type identifier type identifier none typed_default_parameter identifier type identifier true typed_default_parameter identifier type generic_type identifier type_parameter type generic_type identifier type_parameter type identifier none typed_default_parameter identifier type identifier float typed_default_parameter identifier type generic_type identifier type_parameter type attribute identifier identifier none typed_default_parameter identifier type generic_type identifier type_parameter type identifier none typed_default_parameter identifier type identifier false typed_default_parameter identifier type identifier true block expression_statement string string_start string_content string_end expression_statement assignment identifier call identifier argument_list identifier identifier identifier if_statement comparison_operator identifier none block expression_statement assignment identifier binary_operator call identifier argument_list call attribute identifier identifier argument_list list_splat call attribute identifier identifier argument_list parenthesized_expression conditional_expression integer identifier integer expression_statement assignment identifier call identifier argument_list identifier identifier identifier keyword_argument identifier identifier keyword_argument identifier identifier keyword_argument identifier identifier else_clause block expression_statement assignment identifier identifier return_statement call attribute identifier identifier argument_list identifier identifier | Create custom convnet architecture |
def zero_crossing_after(self, n):
n_in_samples = int(n * self.samplerate)
search_end = n_in_samples + self.samplerate
if search_end > self.duration:
search_end = self.duration
frame = zero_crossing_first(
self.range_as_mono(n_in_samples, search_end)) + n_in_samples
return frame / float(self.samplerate) | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call identifier argument_list binary_operator identifier attribute identifier identifier expression_statement assignment identifier binary_operator identifier attribute identifier identifier if_statement comparison_operator identifier attribute identifier identifier block expression_statement assignment identifier attribute identifier identifier expression_statement assignment identifier binary_operator call identifier argument_list call attribute identifier identifier argument_list identifier identifier identifier return_statement binary_operator identifier call identifier argument_list attribute identifier identifier | Find nearest zero crossing in waveform after frame ``n`` |
def getResiduals(self):
X = np.zeros((self.N*self.P,self.n_fixed_effs))
ip = 0
for i in range(self.n_terms):
Ki = self.A[i].shape[0]*self.F[i].shape[1]
X[:,ip:ip+Ki] = np.kron(self.A[i].T,self.F[i])
ip += Ki
y = np.reshape(self.Y,(self.Y.size,1),order='F')
RV = regressOut(y,X)
RV = np.reshape(RV,self.Y.shape,order='F')
return RV | module function_definition identifier parameters identifier block expression_statement assignment identifier call attribute identifier identifier argument_list tuple binary_operator attribute identifier identifier attribute identifier identifier attribute identifier identifier expression_statement assignment identifier integer for_statement identifier call identifier argument_list attribute identifier identifier block expression_statement assignment identifier binary_operator subscript attribute subscript attribute identifier identifier identifier identifier integer subscript attribute subscript attribute identifier identifier identifier identifier integer expression_statement assignment subscript identifier slice slice identifier binary_operator identifier identifier call attribute identifier identifier argument_list attribute subscript attribute identifier identifier identifier identifier subscript attribute identifier identifier identifier expression_statement augmented_assignment identifier identifier expression_statement assignment identifier call attribute identifier identifier argument_list attribute identifier identifier tuple attribute attribute identifier identifier identifier integer keyword_argument identifier string string_start string_content string_end expression_statement assignment identifier call identifier argument_list identifier identifier expression_statement assignment identifier call attribute identifier identifier argument_list identifier attribute attribute identifier identifier identifier keyword_argument identifier string string_start string_content string_end return_statement identifier | regress out fixed effects and results residuals |
def enabled_checker(func):
@wraps(func)
def wrap(self, *args, **kwargs):
if self.allowed_methods and isinstance(self.allowed_methods, list) and func.__name__ not in self.allowed_methods:
raise Exception("Method {} is disabled".format(func.__name__))
return func(self, *args, **kwargs)
return wrap | module function_definition identifier parameters identifier block decorated_definition decorator call identifier argument_list identifier function_definition identifier parameters identifier list_splat_pattern identifier dictionary_splat_pattern identifier block if_statement boolean_operator boolean_operator attribute identifier identifier call identifier argument_list attribute identifier identifier identifier comparison_operator attribute identifier identifier attribute identifier identifier block raise_statement call identifier argument_list call attribute string string_start string_content string_end identifier argument_list attribute identifier identifier return_statement call identifier argument_list identifier list_splat identifier dictionary_splat identifier return_statement identifier | Access decorator which checks if a RPC method is enabled by our configuration |
def token(self, token_address: Address) -> Token:
if not is_binary_address(token_address):
raise ValueError('token_address must be a valid address')
with self._token_creation_lock:
if token_address not in self.address_to_token:
self.address_to_token[token_address] = Token(
jsonrpc_client=self.client,
token_address=token_address,
contract_manager=self.contract_manager,
)
return self.address_to_token[token_address] | module function_definition identifier parameters identifier typed_parameter identifier type identifier type identifier block if_statement not_operator call identifier argument_list identifier block raise_statement call identifier argument_list string string_start string_content string_end with_statement with_clause with_item attribute identifier identifier block if_statement comparison_operator identifier attribute identifier identifier block expression_statement assignment subscript attribute identifier identifier identifier call identifier argument_list keyword_argument identifier attribute identifier identifier keyword_argument identifier identifier keyword_argument identifier attribute identifier identifier return_statement subscript attribute identifier identifier identifier | Return a proxy to interact with a token. |
def getManagers(self):
manager_ids = []
manager_list = []
for department in self.getDepartments():
manager = department.getManager()
if manager is None:
continue
manager_id = manager.getId()
if manager_id not in manager_ids:
manager_ids.append(manager_id)
manager_list.append(manager)
return manager_list | module function_definition identifier parameters identifier block expression_statement assignment identifier list expression_statement assignment identifier list for_statement identifier call attribute identifier identifier argument_list block expression_statement assignment identifier call attribute identifier identifier argument_list if_statement comparison_operator identifier none block continue_statement expression_statement assignment identifier call attribute identifier identifier argument_list if_statement comparison_operator identifier identifier block expression_statement call attribute identifier identifier argument_list identifier expression_statement call attribute identifier identifier argument_list identifier return_statement identifier | Return all managers of responsible departments |
def _parse_preseq_logs(f):
lines = f['f'].splitlines()
header = lines.pop(0)
data_is_bases = False
if header.startswith('TOTAL_READS EXPECTED_DISTINCT'):
pass
elif header.startswith('TOTAL_BASES EXPECTED_DISTINCT'):
data_is_bases = True
elif header.startswith('total_reads distinct_reads'):
pass
else:
log.debug("First line of preseq file {} did not look right".format(f['fn']))
return None, None
data = dict()
for l in lines:
s = l.split()
if float(s[1]) == 0 and float(s[0]) > 0:
continue
data[float(s[0])] = float(s[1])
return data, data_is_bases | module function_definition identifier parameters identifier block expression_statement assignment identifier call attribute subscript identifier string string_start string_content string_end identifier argument_list expression_statement assignment identifier call attribute identifier identifier argument_list integer expression_statement assignment identifier false if_statement call attribute identifier identifier argument_list string string_start string_content string_end block pass_statement elif_clause call attribute identifier identifier argument_list string string_start string_content string_end block expression_statement assignment identifier true elif_clause call attribute identifier identifier argument_list string string_start string_content string_end block pass_statement else_clause block expression_statement call attribute identifier identifier argument_list call attribute string string_start string_content string_end identifier argument_list subscript identifier string string_start string_content string_end return_statement expression_list none none expression_statement assignment identifier call identifier argument_list for_statement identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list if_statement boolean_operator comparison_operator call identifier argument_list subscript identifier integer integer comparison_operator call identifier argument_list subscript identifier integer integer block continue_statement expression_statement assignment subscript identifier call identifier argument_list subscript identifier integer call identifier argument_list subscript identifier integer return_statement expression_list identifier identifier | Go through log file looking for preseq output |
def as_sparse_array(self, kind=None, fill_value=None, copy=False):
if fill_value is None:
fill_value = self.fill_value
if kind is None:
kind = self.kind
return SparseArray(self.values, sparse_index=self.sp_index,
fill_value=fill_value, kind=kind, copy=copy) | module function_definition identifier parameters identifier default_parameter identifier none default_parameter identifier none default_parameter identifier false block if_statement comparison_operator identifier none block expression_statement assignment identifier attribute identifier identifier if_statement comparison_operator identifier none block expression_statement assignment identifier attribute identifier identifier return_statement call identifier argument_list attribute identifier identifier keyword_argument identifier attribute identifier identifier keyword_argument identifier identifier keyword_argument identifier identifier keyword_argument identifier identifier | return my self as a sparse array, do not copy by default |
def make_coord_dict(coord):
return dict(
z=int_if_exact(coord.zoom),
x=int_if_exact(coord.column),
y=int_if_exact(coord.row),
) | module function_definition identifier parameters identifier block return_statement call identifier argument_list keyword_argument identifier call identifier argument_list attribute identifier identifier keyword_argument identifier call identifier argument_list attribute identifier identifier keyword_argument identifier call identifier argument_list attribute identifier identifier | helper function to make a dict from a coordinate for logging |
def _init_taxid2asscs(self):
taxid2asscs = cx.defaultdict(list)
for ntanno in self.associations:
taxid2asscs[ntanno.tax_id].append(ntanno)
assert len(taxid2asscs) != 0, "**FATAL: NO TAXIDS: {F}".format(F=self.filename)
prt = sys.stdout
num_taxids = len(taxid2asscs)
prt.write('{N} taxids stored'.format(N=num_taxids))
if num_taxids < 5:
prt.write(': {Ts}'.format(Ts=' '.join(sorted(str(t) for t in taxid2asscs))))
prt.write('\n')
return dict(taxid2asscs) | module function_definition identifier parameters identifier block expression_statement assignment identifier call attribute identifier identifier argument_list identifier for_statement identifier attribute identifier identifier block expression_statement call attribute subscript identifier attribute identifier identifier identifier argument_list identifier assert_statement comparison_operator call identifier argument_list identifier integer call attribute string string_start string_content string_end identifier argument_list keyword_argument identifier attribute identifier identifier expression_statement assignment identifier attribute identifier identifier expression_statement assignment identifier call identifier argument_list identifier expression_statement call attribute identifier identifier argument_list call attribute string string_start string_content string_end identifier argument_list keyword_argument identifier identifier if_statement comparison_operator identifier integer block expression_statement call attribute identifier identifier argument_list call attribute string string_start string_content string_end identifier argument_list keyword_argument identifier call attribute string string_start string_content string_end identifier argument_list call identifier generator_expression call identifier argument_list identifier for_in_clause identifier identifier expression_statement call attribute identifier identifier argument_list string string_start string_content escape_sequence string_end return_statement call identifier argument_list identifier | Create dict with taxid keys and annotation namedtuple list. |
def _remove_overlaps(in_file, out_dir, data):
out_file = os.path.join(out_dir, "%s-nooverlaps%s" % utils.splitext_plus(os.path.basename(in_file)))
if not utils.file_uptodate(out_file, in_file):
with file_transaction(data, out_file) as tx_out_file:
with open(in_file) as in_handle:
with open(tx_out_file, "w") as out_handle:
prev_line = None
for line in in_handle:
if prev_line:
pchrom, pstart, pend = prev_line.split("\t", 4)[:3]
cchrom, cstart, cend = line.split("\t", 4)[:3]
if pchrom == cchrom and int(pend) > int(cstart):
pass
else:
out_handle.write(prev_line)
prev_line = line
out_handle.write(prev_line)
return out_file | module function_definition identifier parameters identifier identifier identifier block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list identifier binary_operator string string_start string_content string_end call attribute identifier identifier argument_list call attribute attribute identifier identifier identifier argument_list identifier if_statement not_operator call attribute identifier identifier argument_list identifier identifier block with_statement with_clause with_item as_pattern call identifier argument_list identifier identifier as_pattern_target identifier block with_statement with_clause with_item as_pattern call identifier argument_list identifier as_pattern_target identifier block with_statement with_clause with_item as_pattern call identifier argument_list identifier string string_start string_content string_end as_pattern_target identifier block expression_statement assignment identifier none for_statement identifier identifier block if_statement identifier block expression_statement assignment pattern_list identifier identifier identifier subscript call attribute identifier identifier argument_list string string_start string_content escape_sequence string_end integer slice integer expression_statement assignment pattern_list identifier identifier identifier subscript call attribute identifier identifier argument_list string string_start string_content escape_sequence string_end integer slice integer if_statement boolean_operator comparison_operator identifier identifier comparison_operator call identifier argument_list identifier call identifier argument_list identifier block pass_statement else_clause block expression_statement call attribute identifier identifier argument_list identifier expression_statement assignment identifier identifier expression_statement call attribute identifier identifier argument_list identifier return_statement identifier | Remove regions that overlap with next region, these result in issues with PureCN. |
def rsi(series, window=14):
deltas = np.diff(series)
seed = deltas[:window + 1]
ups = seed[seed > 0].sum() / window
downs = -seed[seed < 0].sum() / window
rsival = np.zeros_like(series)
rsival[:window] = 100. - 100. / (1. + ups / downs)
for i in range(window, len(series)):
delta = deltas[i - 1]
if delta > 0:
upval = delta
downval = 0
else:
upval = 0
downval = -delta
ups = (ups * (window - 1) + upval) / window
downs = (downs * (window - 1.) + downval) / window
rsival[i] = 100. - 100. / (1. + ups / downs)
return pd.Series(index=series.index, data=rsival) | module function_definition identifier parameters identifier default_parameter identifier integer block expression_statement assignment identifier call attribute identifier identifier argument_list identifier expression_statement assignment identifier subscript identifier slice binary_operator identifier integer expression_statement assignment identifier binary_operator call attribute subscript identifier comparison_operator identifier integer identifier argument_list identifier expression_statement assignment identifier binary_operator unary_operator call attribute subscript identifier comparison_operator identifier integer identifier argument_list identifier expression_statement assignment identifier call attribute identifier identifier argument_list identifier expression_statement assignment subscript identifier slice identifier binary_operator float binary_operator float parenthesized_expression binary_operator float binary_operator identifier identifier for_statement identifier call identifier argument_list identifier call identifier argument_list identifier block expression_statement assignment identifier subscript identifier binary_operator identifier integer if_statement comparison_operator identifier integer block expression_statement assignment identifier identifier expression_statement assignment identifier integer else_clause block expression_statement assignment identifier integer expression_statement assignment identifier unary_operator identifier expression_statement assignment identifier binary_operator parenthesized_expression binary_operator binary_operator identifier parenthesized_expression binary_operator identifier integer identifier identifier expression_statement assignment identifier binary_operator parenthesized_expression binary_operator binary_operator identifier parenthesized_expression binary_operator identifier float identifier identifier expression_statement assignment subscript identifier identifier binary_operator float binary_operator float parenthesized_expression binary_operator float binary_operator identifier identifier return_statement call attribute identifier identifier argument_list keyword_argument identifier attribute identifier identifier keyword_argument identifier identifier | compute the n period relative strength indicator |
def _list2Rlist(xs):
if isinstance(xs, six.string_types):
xs = [xs]
rlist = ",".join([_quotestring(x) for x in xs])
return "c(" + rlist + ")" | module function_definition identifier parameters identifier block if_statement call identifier argument_list identifier attribute identifier identifier block expression_statement assignment identifier list identifier expression_statement assignment identifier call attribute string string_start string_content string_end identifier argument_list list_comprehension call identifier argument_list identifier for_in_clause identifier identifier return_statement binary_operator binary_operator string string_start string_content string_end identifier string string_start string_content string_end | convert a python list to an R list |
def unindex_model_on_delete(sender, document, **kwargs):
if current_app.config.get('AUTO_INDEX'):
unindex.delay(document) | module function_definition identifier parameters identifier identifier dictionary_splat_pattern identifier block if_statement call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end block expression_statement call attribute identifier identifier argument_list identifier | Unindex Mongo document on post_delete |
def ingress_filter(self, response):
data = self.data_getter(response)
if isinstance(data, dict):
data = m_data.DictResponse(data)
elif isinstance(data, list):
data = m_data.ListResponse(data)
else:
return data
data.meta = self.meta_getter(response)
return data | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list identifier if_statement call identifier argument_list identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list identifier elif_clause call identifier argument_list identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list identifier else_clause block return_statement identifier expression_statement assignment attribute identifier identifier call attribute identifier identifier argument_list identifier return_statement identifier | Flatten a response with meta and data keys into an object. |
def flush():
try:
sys.stdout.flush()
sys.stderr.flush()
except (AttributeError, ValueError, IOError):
pass
try:
libc.fflush(None)
except (AttributeError, ValueError, IOError):
pass | module function_definition identifier parameters block try_statement block expression_statement call attribute attribute identifier identifier identifier argument_list expression_statement call attribute attribute identifier identifier identifier argument_list except_clause tuple identifier identifier identifier block pass_statement try_statement block expression_statement call attribute identifier identifier argument_list none except_clause tuple identifier identifier identifier block pass_statement | Try to flush all stdio buffers, both from python and from C. |
def parse_changes():
with open('CHANGES') as changes:
for match in re.finditer(RE_CHANGES, changes.read(1024), re.M):
if len(match.group(1)) != len(match.group(3)):
error('incorrect underline in CHANGES')
date = datetime.datetime.strptime(match.group(4),
'%Y-%m-%d').date()
if date != datetime.date.today():
error('release date is not today')
return match.group(2)
error('invalid release entry in CHANGES') | module function_definition identifier parameters block with_statement with_clause with_item as_pattern call identifier argument_list string string_start string_content string_end as_pattern_target identifier block for_statement identifier call attribute identifier identifier argument_list identifier call attribute identifier identifier argument_list integer attribute identifier identifier block if_statement comparison_operator call identifier argument_list call attribute identifier identifier argument_list integer call identifier argument_list call attribute identifier identifier argument_list integer block expression_statement call identifier argument_list string string_start string_content string_end expression_statement assignment identifier call attribute call attribute attribute identifier identifier identifier argument_list call attribute identifier identifier argument_list integer string string_start string_content string_end identifier argument_list if_statement comparison_operator identifier call attribute attribute identifier identifier identifier argument_list block expression_statement call identifier argument_list string string_start string_content string_end return_statement call attribute identifier identifier argument_list integer expression_statement call identifier argument_list string string_start string_content string_end | grab version from CHANGES and validate entry |
def doIteration(self, delay=None, fromqt=False):
'This method is called by a Qt timer or by network activity on a file descriptor'
if not self.running and self._blockApp:
self._blockApp.quit()
self._timer.stop()
delay = max(delay, 1)
if not fromqt:
self.qApp.processEvents(QtCore.QEventLoop.AllEvents, delay * 1000)
if self.timeout() is None:
timeout = 0.1
elif self.timeout() == 0:
timeout = 0
else:
timeout = self.timeout()
self._timer.setInterval(timeout * 1000)
self._timer.start() | module function_definition identifier parameters identifier default_parameter identifier none default_parameter identifier false block expression_statement string string_start string_content string_end if_statement boolean_operator not_operator attribute identifier identifier attribute identifier identifier block expression_statement call attribute attribute identifier identifier identifier argument_list expression_statement call attribute attribute identifier identifier identifier argument_list expression_statement assignment identifier call identifier argument_list identifier integer if_statement not_operator identifier block expression_statement call attribute attribute identifier identifier identifier argument_list attribute attribute identifier identifier identifier binary_operator identifier integer if_statement comparison_operator call attribute identifier identifier argument_list none block expression_statement assignment identifier float elif_clause comparison_operator call attribute identifier identifier argument_list integer block expression_statement assignment identifier integer else_clause block expression_statement assignment identifier call attribute identifier identifier argument_list expression_statement call attribute attribute identifier identifier identifier argument_list binary_operator identifier integer expression_statement call attribute attribute identifier identifier identifier argument_list | This method is called by a Qt timer or by network activity on a file descriptor |
def merge_objects(self, mujoco_objects):
self.mujoco_objects = mujoco_objects
self.objects = {}
self.max_horizontal_radius = 0
for obj_name, obj_mjcf in mujoco_objects.items():
self.merge_asset(obj_mjcf)
obj = obj_mjcf.get_collision(name=obj_name, site=True)
obj.append(new_joint(name=obj_name, type="free", damping="0.0005"))
self.objects[obj_name] = obj
self.worldbody.append(obj)
self.max_horizontal_radius = max(
self.max_horizontal_radius, obj_mjcf.get_horizontal_radius()
) | module function_definition identifier parameters identifier identifier block expression_statement assignment attribute identifier identifier identifier expression_statement assignment attribute identifier identifier dictionary expression_statement assignment attribute identifier identifier integer for_statement pattern_list identifier identifier call attribute identifier identifier argument_list block expression_statement call attribute identifier identifier argument_list identifier expression_statement assignment identifier call attribute identifier identifier argument_list keyword_argument identifier identifier keyword_argument identifier true expression_statement call attribute identifier identifier argument_list call identifier argument_list keyword_argument identifier identifier keyword_argument identifier string string_start string_content string_end keyword_argument identifier string string_start string_content string_end expression_statement assignment subscript attribute identifier identifier identifier identifier expression_statement call attribute attribute identifier identifier identifier argument_list identifier expression_statement assignment attribute identifier identifier call identifier argument_list attribute identifier identifier call attribute identifier identifier argument_list | Adds physical objects to the MJCF model. |
def __get_region(conn, vm_):
location = __get_location(conn, vm_)
region = '-'.join(location.name.split('-')[:2])
return conn.ex_get_region(region) | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call identifier argument_list identifier identifier expression_statement assignment identifier call attribute string string_start string_content string_end identifier argument_list subscript call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end slice integer return_statement call attribute identifier identifier argument_list identifier | Return a GCE libcloud region object with matching name. |
def load_contents(self):
with open(METADATA_FILE) as f:
lines = f.readlines()
lines = map(lambda x: x.strip(), lines)
exclude_strings = ['<begin_table>', '<end_table>']
list_of_databases_and_columns = filter(
lambda x: not x[0] in exclude_strings, [
list(value) for key, value in itertools.groupby(
lines,
lambda x: x in exclude_strings
)
]
)
for iterator in list_of_databases_and_columns:
self.create_table_raw(
tablename=iterator[0],
columns=iterator[1:][:],
)
for i in self.tables:
i.load_contents() | module function_definition identifier parameters identifier block with_statement with_clause with_item as_pattern call identifier argument_list identifier as_pattern_target identifier block expression_statement assignment identifier call attribute identifier identifier argument_list expression_statement assignment identifier call identifier argument_list lambda lambda_parameters identifier call attribute identifier identifier argument_list identifier expression_statement assignment identifier list string string_start string_content string_end string string_start string_content string_end expression_statement assignment identifier call identifier argument_list lambda lambda_parameters identifier not_operator comparison_operator subscript identifier integer identifier list_comprehension call identifier argument_list identifier for_in_clause pattern_list identifier identifier call attribute identifier identifier argument_list identifier lambda lambda_parameters identifier comparison_operator identifier identifier for_statement identifier identifier block expression_statement call attribute identifier identifier argument_list keyword_argument identifier subscript identifier integer keyword_argument identifier subscript subscript identifier slice integer slice for_statement identifier attribute identifier identifier block expression_statement call attribute identifier identifier argument_list | Loads contents of the tables into database. |
def _filter_bad_reads(in_bam, ref_file, data):
bam.index(in_bam, data["config"])
out_file = "%s-gatkfilter.bam" % os.path.splitext(in_bam)[0]
if not utils.file_exists(out_file):
with tx_tmpdir(data) as tmp_dir:
with file_transaction(data, out_file) as tx_out_file:
params = [("FixMisencodedBaseQualityReads"
if dd.get_quality_format(data, "").lower() == "illumina"
else "PrintReads"),
"-R", ref_file,
"-I", in_bam,
"-O", tx_out_file,
"-RF", "MatchingBasesAndQualsReadFilter",
"-RF", "SeqIsStoredReadFilter",
"-RF", "CigarContainsNoNOperator"]
jvm_opts = broad.get_gatk_opts(data["config"], tmp_dir)
do.run(broad.gatk_cmd("gatk", jvm_opts, params), "Filter problem reads")
bam.index(out_file, data["config"])
return out_file | module function_definition identifier parameters identifier identifier identifier block expression_statement call attribute identifier identifier argument_list identifier subscript identifier string string_start string_content string_end expression_statement assignment identifier binary_operator string string_start string_content string_end subscript call attribute attribute identifier identifier identifier argument_list identifier integer if_statement not_operator call attribute identifier identifier argument_list identifier block with_statement with_clause with_item as_pattern call identifier argument_list identifier as_pattern_target identifier block with_statement with_clause with_item as_pattern call identifier argument_list identifier identifier as_pattern_target identifier block expression_statement assignment identifier list parenthesized_expression conditional_expression string string_start string_content string_end comparison_operator call attribute call attribute identifier identifier argument_list identifier string string_start string_end identifier argument_list string string_start string_content string_end string string_start string_content string_end string string_start string_content string_end identifier string string_start string_content string_end identifier string string_start string_content string_end identifier string string_start string_content string_end string string_start string_content string_end string string_start string_content string_end string string_start string_content string_end string string_start string_content string_end string string_start string_content string_end expression_statement assignment identifier call attribute identifier identifier argument_list subscript identifier string string_start string_content string_end identifier expression_statement call attribute identifier identifier argument_list call attribute identifier identifier argument_list string string_start string_content string_end identifier identifier string string_start string_content string_end expression_statement call attribute identifier identifier argument_list identifier subscript identifier string string_start string_content string_end return_statement identifier | Use GATK filter to remove problem reads which choke GATK and Picard. |
def segment(self, webvtt, output='', seconds=SECONDS, mpegts=MPEGTS):
if isinstance(webvtt, str):
captions = WebVTT().read(webvtt).captions
elif not self._validate_webvtt(webvtt):
raise InvalidCaptionsError('The captions provided are invalid')
else:
captions = webvtt.captions
self._total_segments = 0 if not captions else int(ceil(captions[-1].end_in_seconds / seconds))
self._output_folder = output
self._seconds = seconds
self._mpegts = mpegts
output_folder = os.path.join(os.getcwd(), output)
if not os.path.exists(output_folder):
os.makedirs(output_folder)
self._slice_segments(captions)
self._write_segments()
self._write_manifest() | module function_definition identifier parameters identifier identifier default_parameter identifier string string_start string_end default_parameter identifier identifier default_parameter identifier identifier block if_statement call identifier argument_list identifier identifier block expression_statement assignment identifier attribute call attribute call identifier argument_list identifier argument_list identifier identifier elif_clause not_operator call attribute identifier identifier argument_list identifier block raise_statement call identifier argument_list string string_start string_content string_end else_clause block expression_statement assignment identifier attribute identifier identifier expression_statement assignment attribute identifier identifier conditional_expression integer not_operator identifier call identifier argument_list call identifier argument_list binary_operator attribute subscript identifier unary_operator integer identifier identifier expression_statement assignment attribute identifier identifier identifier expression_statement assignment attribute identifier identifier identifier expression_statement assignment attribute identifier identifier identifier expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list call attribute identifier identifier argument_list identifier if_statement not_operator call attribute attribute identifier identifier identifier argument_list identifier block expression_statement call attribute identifier identifier argument_list identifier expression_statement call attribute identifier identifier argument_list identifier expression_statement call attribute identifier identifier argument_list expression_statement call attribute identifier identifier argument_list | Segments the captions based on a number of seconds. |
def matches(self, filter_props):
if filter_props is None:
return False
found_one = False
for key, value in filter_props.items():
if key in self.properties and value != self.properties[key]:
return False
elif key in self.properties and value == self.properties[key]:
found_one = True
return found_one | module function_definition identifier parameters identifier identifier block if_statement comparison_operator identifier none block return_statement false expression_statement assignment identifier false for_statement pattern_list identifier identifier call attribute identifier identifier argument_list block if_statement boolean_operator comparison_operator identifier attribute identifier identifier comparison_operator identifier subscript attribute identifier identifier identifier block return_statement false elif_clause boolean_operator comparison_operator identifier attribute identifier identifier comparison_operator identifier subscript attribute identifier identifier identifier block expression_statement assignment identifier true return_statement identifier | Check if the filter matches the supplied properties. |
def list_images(self, repository_name, registry_id=None):
repository = None
found = False
if repository_name in self.repositories:
repository = self.repositories[repository_name]
if registry_id:
if repository.registry_id == registry_id:
found = True
else:
found = True
if not found:
raise RepositoryNotFoundException(repository_name, registry_id or DEFAULT_REGISTRY_ID)
images = []
for image in repository.images:
images.append(image)
return images | module function_definition identifier parameters identifier identifier default_parameter identifier none block expression_statement assignment identifier none expression_statement assignment identifier false if_statement comparison_operator identifier attribute identifier identifier block expression_statement assignment identifier subscript attribute identifier identifier identifier if_statement identifier block if_statement comparison_operator attribute identifier identifier identifier block expression_statement assignment identifier true else_clause block expression_statement assignment identifier true if_statement not_operator identifier block raise_statement call identifier argument_list identifier boolean_operator identifier identifier expression_statement assignment identifier list for_statement identifier attribute identifier identifier block expression_statement call attribute identifier identifier argument_list identifier return_statement identifier | maxResults and filtering not implemented |
def weighted_hamming(b1, b2):
assert(len(b1) == len(b2))
hamming = 0
for i in range(len(b1)):
if b1[i] != b2[i]:
if i > 0:
hamming += 1 + 1.0/i
return hamming | module function_definition identifier parameters identifier identifier block assert_statement parenthesized_expression comparison_operator call identifier argument_list identifier call identifier argument_list identifier expression_statement assignment identifier integer for_statement identifier call identifier argument_list call identifier argument_list identifier block if_statement comparison_operator subscript identifier identifier subscript identifier identifier block if_statement comparison_operator identifier integer block expression_statement augmented_assignment identifier binary_operator integer binary_operator float identifier return_statement identifier | Hamming distance that emphasizes differences earlier in strings. |
def init(self):
url = 'https://finance.yahoo.com/quote/%s/history' % (self.ticker)
r = requests.get(url)
txt = r.content
cookie = r.cookies['B']
pattern = re.compile('.*"CrumbStore":\{"crumb":"(?P<crumb>[^"]+)"\}')
for line in txt.splitlines():
m = pattern.match(line.decode("utf-8"))
if m is not None:
crumb = m.groupdict()['crumb']
crumb = crumb.replace(u'\\u002F', '/')
return cookie, crumb | module function_definition identifier parameters identifier block expression_statement assignment identifier binary_operator string string_start string_content string_end parenthesized_expression attribute identifier identifier expression_statement assignment identifier call attribute identifier identifier argument_list identifier expression_statement assignment identifier attribute identifier identifier expression_statement assignment identifier subscript attribute identifier identifier string string_start string_content string_end expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end for_statement identifier call attribute identifier identifier argument_list block expression_statement assignment identifier call attribute identifier identifier argument_list call attribute identifier identifier argument_list string string_start string_content string_end if_statement comparison_operator identifier none block expression_statement assignment identifier subscript call attribute identifier identifier argument_list string string_start string_content string_end expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content escape_sequence string_end string string_start string_content string_end return_statement expression_list identifier identifier | Returns a tuple pair of cookie and crumb used in the request |
def item_link(self, item):
return reverse_lazy(
'forum_conversation:topic',
kwargs={
'forum_slug': item.forum.slug,
'forum_pk': item.forum.pk,
'slug': item.slug,
'pk': item.id,
},
) | module function_definition identifier parameters identifier identifier block return_statement call identifier argument_list string string_start string_content string_end keyword_argument identifier dictionary pair string string_start string_content string_end attribute attribute identifier identifier identifier pair string string_start string_content string_end attribute attribute identifier identifier identifier pair string string_start string_content string_end attribute identifier identifier pair string string_start string_content string_end attribute identifier identifier | Generates a link for a specific item of the feed. |
def _check_independent_residues(topology):
for res in topology.residues():
atoms_in_residue = set([atom for atom in res.atoms()])
bond_partners_in_residue = [item for sublist in [atom.bond_partners for atom in res.atoms()] for item in sublist]
if not bond_partners_in_residue:
continue
if set(atoms_in_residue) != set(bond_partners_in_residue):
return False
return True | module function_definition identifier parameters identifier block for_statement identifier call attribute identifier identifier argument_list block expression_statement assignment identifier call identifier argument_list list_comprehension identifier for_in_clause identifier call attribute identifier identifier argument_list expression_statement assignment identifier list_comprehension identifier for_in_clause identifier list_comprehension attribute identifier identifier for_in_clause identifier call attribute identifier identifier argument_list for_in_clause identifier identifier if_statement not_operator identifier block continue_statement if_statement comparison_operator call identifier argument_list identifier call identifier argument_list identifier block return_statement false return_statement true | Check to see if residues will constitute independent graphs. |
def apply( self ):
font = self.value('font')
try:
font.setPointSize(self.value('fontSize'))
except TypeError:
pass
palette = self.value('colorSet').palette()
if ( unwrapVariant(QApplication.instance().property('useScheme')) ):
QApplication.instance().setFont(font)
QApplication.instance().setPalette(palette)
for widget in QApplication.topLevelWidgets():
for area in widget.findChildren(QMdiArea):
area.setPalette(palette)
else:
logger.debug('The application doesnt have the useScheme property.') | module function_definition identifier parameters identifier block expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end try_statement block expression_statement call attribute identifier identifier argument_list call attribute identifier identifier argument_list string string_start string_content string_end except_clause identifier block pass_statement expression_statement assignment identifier call attribute call attribute identifier identifier argument_list string string_start string_content string_end identifier argument_list if_statement parenthesized_expression call identifier argument_list call attribute call attribute identifier identifier argument_list identifier argument_list string string_start string_content string_end block expression_statement call attribute call attribute identifier identifier argument_list identifier argument_list identifier expression_statement call attribute call attribute identifier identifier argument_list identifier argument_list identifier for_statement identifier call attribute identifier identifier argument_list block for_statement identifier call attribute identifier identifier argument_list identifier block expression_statement call attribute identifier identifier argument_list identifier else_clause block expression_statement call attribute identifier identifier argument_list string string_start string_content string_end | Applies the scheme to the current application. |
def format(self, password: str = '') -> str:
return MARKER_START + \
self.name + \
self.action + \
self.args + \
password + \
MARKER_END | module function_definition identifier parameters identifier typed_default_parameter identifier type identifier string string_start string_end type identifier block return_statement binary_operator binary_operator binary_operator binary_operator binary_operator identifier line_continuation attribute identifier identifier line_continuation attribute identifier identifier line_continuation attribute identifier identifier line_continuation identifier line_continuation identifier | Format command along with any arguments, ready to be sent. |
def _get_current_tags(name, runas=None):
try:
return list(__salt__['rabbitmq.list_users'](runas=runas)[name])
except CommandExecutionError as err:
log.error('Error: %s', err)
return [] | module function_definition identifier parameters identifier default_parameter identifier none block try_statement block return_statement call identifier argument_list subscript call subscript identifier string string_start string_content string_end argument_list keyword_argument identifier identifier identifier except_clause as_pattern identifier as_pattern_target identifier block expression_statement call attribute identifier identifier argument_list string string_start string_content string_end identifier return_statement list | Whether Rabbitmq user's tags need to be changed |
def _start_vibration_win(self, left_motor, right_motor):
xinput_set_state = self.manager.xinput.XInputSetState
xinput_set_state.argtypes = [
ctypes.c_uint, ctypes.POINTER(XinputVibration)]
xinput_set_state.restype = ctypes.c_uint
vibration = XinputVibration(
int(left_motor * 65535), int(right_motor * 65535))
xinput_set_state(self.__device_number, ctypes.byref(vibration)) | module function_definition identifier parameters identifier identifier identifier block expression_statement assignment identifier attribute attribute attribute identifier identifier identifier identifier expression_statement assignment attribute identifier identifier list attribute identifier identifier call attribute identifier identifier argument_list identifier expression_statement assignment attribute identifier identifier attribute identifier identifier expression_statement assignment identifier call identifier argument_list call identifier argument_list binary_operator identifier integer call identifier argument_list binary_operator identifier integer expression_statement call identifier argument_list attribute identifier identifier call attribute identifier identifier argument_list identifier | Start the vibration, which will run until stopped. |
def fval(self, instance):
try:
val = instance.__dict__[self.instance_field_name]
except KeyError as e:
val = None
return val | module function_definition identifier parameters identifier identifier block try_statement block expression_statement assignment identifier subscript attribute identifier identifier attribute identifier identifier except_clause as_pattern identifier as_pattern_target identifier block expression_statement assignment identifier none return_statement identifier | return the raw value that this property is holding internally for instance |
def next_code_is_indented(lines):
for line in lines:
if _BLANK_LINE.match(line) or _PY_COMMENT.match(line):
continue
return _PY_INDENTED.match(line)
return False | module function_definition identifier parameters identifier block for_statement identifier identifier block if_statement boolean_operator call attribute identifier identifier argument_list identifier call attribute identifier identifier argument_list identifier block continue_statement return_statement call attribute identifier identifier argument_list identifier return_statement false | Is the next unescaped line indented? |
def _domain_differs(self, href):
target = utils.get_domain(href)
if not target:
return False
origin = utils.get_domain(self.url)
return target != origin | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list identifier if_statement not_operator identifier block return_statement false expression_statement assignment identifier call attribute identifier identifier argument_list attribute identifier identifier return_statement comparison_operator identifier identifier | Check that a link is not on the same domain as the source URL |
def generate(env):
try:
bld = env['BUILDERS']['Zip']
except KeyError:
bld = ZipBuilder
env['BUILDERS']['Zip'] = bld
env['ZIP'] = 'zip'
env['ZIPFLAGS'] = SCons.Util.CLVar('')
env['ZIPCOM'] = zipAction
env['ZIPCOMPRESSION'] = zipcompression
env['ZIPSUFFIX'] = '.zip'
env['ZIPROOT'] = SCons.Util.CLVar('') | module function_definition identifier parameters identifier block try_statement block expression_statement assignment identifier subscript subscript identifier string string_start string_content string_end string string_start string_content string_end except_clause identifier block expression_statement assignment identifier identifier expression_statement assignment subscript subscript identifier string string_start string_content string_end string string_start string_content string_end identifier expression_statement assignment subscript identifier string string_start string_content string_end string string_start string_content string_end expression_statement assignment subscript identifier string string_start string_content string_end call attribute attribute identifier identifier identifier argument_list string string_start string_end expression_statement assignment subscript identifier string string_start string_content string_end identifier expression_statement assignment subscript identifier string string_start string_content string_end identifier expression_statement assignment subscript identifier string string_start string_content string_end string string_start string_content string_end expression_statement assignment subscript identifier string string_start string_content string_end call attribute attribute identifier identifier identifier argument_list string string_start string_end | Add Builders and construction variables for zip to an Environment. |
def corr_coeff(x1, x2, t, tau1, tau2):
dt = t[1] - t[0]
tau = np.arange(tau1, tau2+dt, dt)
rho = np.zeros(len(tau))
for n in range(len(tau)):
i = np.abs(int(tau[n]/dt))
if tau[n] >= 0:
seg2 = x2[0:-1-i]
seg1 = x1[i:-1]
elif tau[n] < 0:
seg1 = x1[0:-i-1]
seg2 = x2[i:-1]
seg1 = seg1 - seg1.mean()
seg2 = seg2 - seg2.mean()
rho[n] = np.mean(seg1*seg2)/seg1.std()/seg2.std()
return tau, rho | module function_definition identifier parameters identifier identifier identifier identifier identifier block expression_statement assignment identifier binary_operator subscript identifier integer subscript identifier integer expression_statement assignment identifier call attribute identifier identifier argument_list identifier binary_operator identifier identifier identifier expression_statement assignment identifier call attribute identifier identifier argument_list call identifier argument_list identifier for_statement identifier call identifier argument_list call identifier argument_list identifier block expression_statement assignment identifier call attribute identifier identifier argument_list call identifier argument_list binary_operator subscript identifier identifier identifier if_statement comparison_operator subscript identifier identifier integer block expression_statement assignment identifier subscript identifier slice integer binary_operator unary_operator integer identifier expression_statement assignment identifier subscript identifier slice identifier unary_operator integer elif_clause comparison_operator subscript identifier identifier integer block expression_statement assignment identifier subscript identifier slice integer binary_operator unary_operator identifier integer expression_statement assignment identifier subscript identifier slice identifier unary_operator integer expression_statement assignment identifier binary_operator identifier call attribute identifier identifier argument_list expression_statement assignment identifier binary_operator identifier call attribute identifier identifier argument_list expression_statement assignment subscript identifier identifier binary_operator binary_operator call attribute identifier identifier argument_list binary_operator identifier identifier call attribute identifier identifier argument_list call attribute identifier identifier argument_list return_statement expression_list identifier identifier | Compute lagged correlation coefficient for two time series. |
def delayed_close(self):
self.state = CLOSING
self.server.io_loop.add_callback(self.close) | module function_definition identifier parameters identifier block expression_statement assignment attribute identifier identifier identifier expression_statement call attribute attribute attribute identifier identifier identifier identifier argument_list attribute identifier identifier | Delayed close - won't close immediately, but on next ioloop tick. |
def add_url(self, post_data):
img_desc = post_data['desc']
img_path = post_data['file1']
cur_uid = tools.get_uudd(4)
while MEntity.get_by_uid(cur_uid):
cur_uid = tools.get_uudd(4)
MEntity.create_entity(cur_uid, img_path, img_desc, kind=post_data['kind'] if 'kind' in post_data else '3')
kwd = {
'kind': post_data['kind'] if 'kind' in post_data else '3',
}
self.render('misc/entity/entity_view.html',
filename=img_path,
cfg=config.CMS_CFG,
kwd=kwd,
userinfo=self.userinfo) | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier subscript identifier string string_start string_content string_end expression_statement assignment identifier subscript identifier string string_start string_content string_end expression_statement assignment identifier call attribute identifier identifier argument_list integer while_statement call attribute identifier identifier argument_list identifier block expression_statement assignment identifier call attribute identifier identifier argument_list integer expression_statement call attribute identifier identifier argument_list identifier identifier identifier keyword_argument identifier conditional_expression subscript identifier string string_start string_content string_end comparison_operator string string_start string_content string_end identifier string string_start string_content string_end expression_statement assignment identifier dictionary pair string string_start string_content string_end conditional_expression subscript identifier string string_start string_content string_end comparison_operator string string_start string_content string_end identifier string string_start string_content string_end expression_statement call attribute identifier identifier argument_list string string_start string_content string_end keyword_argument identifier identifier keyword_argument identifier attribute identifier identifier keyword_argument identifier identifier keyword_argument identifier attribute identifier identifier | Adding the URL as entity. |
def cfarray_to_list(cfarray):
count = cf.CFArrayGetCount(cfarray)
return [cftype_to_value(c_void_p(cf.CFArrayGetValueAtIndex(cfarray, i)))
for i in range(count)] | module function_definition identifier parameters identifier block expression_statement assignment identifier call attribute identifier identifier argument_list identifier return_statement list_comprehension call identifier argument_list call identifier argument_list call attribute identifier identifier argument_list identifier identifier for_in_clause identifier call identifier argument_list identifier | Convert CFArray to python list. |
def deployAll(self):
targets = [Target.getTarget(iid) for iid, n, p in self.db.listTargets()]
for target in targets:
target.deploy()
verbose('Deploy all complete') | module function_definition identifier parameters identifier block expression_statement assignment identifier list_comprehension call attribute identifier identifier argument_list identifier for_in_clause pattern_list identifier identifier identifier call attribute attribute identifier identifier identifier argument_list for_statement identifier identifier block expression_statement call attribute identifier identifier argument_list expression_statement call identifier argument_list string string_start string_content string_end | Deploys all the items from the vault. Useful after a format |
def _load_words(self):
with open(self._words_file, 'r') as f:
self._censor_list = [line.strip() for line in f.readlines()] | module function_definition identifier parameters identifier block with_statement with_clause with_item as_pattern call identifier argument_list attribute identifier identifier string string_start string_content string_end as_pattern_target identifier block expression_statement assignment attribute identifier identifier list_comprehension call attribute identifier identifier argument_list for_in_clause identifier call attribute identifier identifier argument_list | Loads the list of profane words from file. |
def update_field(uid, post_id=None, tag_id=None, par_id=None):
if post_id:
entry = TabPost2Tag.update(
post_id=post_id
).where(TabPost2Tag.uid == uid)
entry.execute()
if tag_id:
entry2 = TabPost2Tag.update(
par_id=tag_id[:2] + '00',
tag_id=tag_id,
).where(TabPost2Tag.uid == uid)
entry2.execute()
if par_id:
entry2 = TabPost2Tag.update(
par_id=par_id
).where(TabPost2Tag.uid == uid)
entry2.execute() | module function_definition identifier parameters identifier default_parameter identifier none default_parameter identifier none default_parameter identifier none block if_statement identifier block expression_statement assignment identifier call attribute call attribute identifier identifier argument_list keyword_argument identifier identifier identifier argument_list comparison_operator attribute identifier identifier identifier expression_statement call attribute identifier identifier argument_list if_statement identifier block expression_statement assignment identifier call attribute call attribute identifier identifier argument_list keyword_argument identifier binary_operator subscript identifier slice integer string string_start string_content string_end keyword_argument identifier identifier identifier argument_list comparison_operator attribute identifier identifier identifier expression_statement call attribute identifier identifier argument_list if_statement identifier block expression_statement assignment identifier call attribute call attribute identifier identifier argument_list keyword_argument identifier identifier identifier argument_list comparison_operator attribute identifier identifier identifier expression_statement call attribute identifier identifier argument_list | Update the field of post2tag. |
def _get_sensor_names(self):
if not self.attrs.get('sensor'):
return set([sensor for reader_instance in self.readers.values()
for sensor in reader_instance.sensor_names])
elif not isinstance(self.attrs['sensor'], (set, tuple, list)):
return set([self.attrs['sensor']])
else:
return set(self.attrs['sensor']) | module function_definition identifier parameters identifier block if_statement not_operator call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end block return_statement call identifier argument_list list_comprehension identifier for_in_clause identifier call attribute attribute identifier identifier identifier argument_list for_in_clause identifier attribute identifier identifier elif_clause not_operator call identifier argument_list subscript attribute identifier identifier string string_start string_content string_end tuple identifier identifier identifier block return_statement call identifier argument_list list subscript attribute identifier identifier string string_start string_content string_end else_clause block return_statement call identifier argument_list subscript attribute identifier identifier string string_start string_content string_end | Join the sensors from all loaded readers. |
def _retrieve_revisions(self):
response = self._swimlane.request(
'get',
'history',
params={
'type': 'Records',
'id': self._record.id
}
)
raw_revisions = response.json()
return [Revision(self._record, raw) for raw in raw_revisions] | module function_definition identifier parameters identifier block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end string string_start string_content string_end keyword_argument identifier dictionary pair string string_start string_content string_end string string_start string_content string_end pair string string_start string_content string_end attribute attribute identifier identifier identifier expression_statement assignment identifier call attribute identifier identifier argument_list return_statement list_comprehension call identifier argument_list attribute identifier identifier identifier for_in_clause identifier identifier | Retrieve and populate Revision instances from history API endpoint |
def print_status(raw_status, strip_units=False):
lines = split(raw_status)
if strip_units:
lines = strip_units_from_lines(lines)
for line in lines:
print(line) | module function_definition identifier parameters identifier default_parameter identifier false block expression_statement assignment identifier call identifier argument_list identifier if_statement identifier block expression_statement assignment identifier call identifier argument_list identifier for_statement identifier identifier block expression_statement call identifier argument_list identifier | Print the status to stdout in the same format as the original apcaccess. |
def get(self, request, slug):
matching_datasets = self.generate_matching_datasets(slug)
if matching_datasets is None:
raise Http404("Datasets meeting these criteria do not exist.")
base_context = {
'datasets': matching_datasets,
'num_datasets': matching_datasets.count(),
'page_title': self.generate_page_title(slug),
}
additional_context = self.generate_additional_context(
matching_datasets
)
base_context.update(additional_context)
context = base_context
return render(
request,
self.template_path,
context
) | module function_definition identifier parameters identifier identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list identifier if_statement comparison_operator identifier none block raise_statement call identifier argument_list string string_start string_content string_end expression_statement assignment identifier dictionary pair string string_start string_content string_end identifier pair string string_start string_content string_end call attribute identifier identifier argument_list pair string string_start string_content string_end call attribute identifier identifier argument_list identifier expression_statement assignment identifier call attribute identifier identifier argument_list identifier expression_statement call attribute identifier identifier argument_list identifier expression_statement assignment identifier identifier return_statement call identifier argument_list identifier attribute identifier identifier identifier | Basic functionality for GET request to view. |
def _prepare_sample(data, run_folder):
want = set(["description", "files", "genome_build", "name", "analysis", "upload", "algorithm"])
out = {}
for k, v in data.items():
if k in want:
out[k] = _relative_paths(v, run_folder)
if "algorithm" not in out:
analysis, algorithm = _select_default_algorithm(out.get("analysis"))
out["algorithm"] = algorithm
out["analysis"] = analysis
description = "%s-%s" % (out["name"], clean_name(out["description"]))
out["name"] = [out["name"], description]
out["description"] = description
return out | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call identifier argument_list list string string_start string_content string_end string string_start string_content string_end string string_start string_content string_end string string_start string_content string_end string string_start string_content string_end string string_start string_content string_end string string_start string_content string_end expression_statement assignment identifier dictionary for_statement pattern_list identifier identifier call attribute identifier identifier argument_list block if_statement comparison_operator identifier identifier block expression_statement assignment subscript identifier identifier call identifier argument_list identifier identifier if_statement comparison_operator string string_start string_content string_end identifier block expression_statement assignment pattern_list identifier identifier call identifier argument_list call attribute identifier identifier argument_list string string_start string_content string_end expression_statement assignment subscript identifier string string_start string_content string_end identifier expression_statement assignment subscript identifier string string_start string_content string_end identifier expression_statement assignment identifier binary_operator string string_start string_content string_end tuple subscript identifier string string_start string_content string_end call identifier argument_list subscript identifier string string_start string_content string_end expression_statement assignment subscript identifier string string_start string_content string_end list subscript identifier string string_start string_content string_end identifier expression_statement assignment subscript identifier string string_start string_content string_end identifier return_statement identifier | Extract passed keywords from input LIMS information. |
def send(self):
if self.prepare():
print('sending message')
lg.record_process('comms.py', 'Sending message ' + self.title)
return True
else:
return False | module function_definition identifier parameters identifier block if_statement call attribute identifier identifier argument_list block expression_statement call identifier argument_list string string_start string_content string_end expression_statement call attribute identifier identifier argument_list string string_start string_content string_end binary_operator string string_start string_content string_end attribute identifier identifier return_statement true else_clause block return_statement false | this handles the message transmission |
def read(self, filename):
try:
with open(filename, 'r') as _file:
self._filename = filename
self.readstream(_file)
return True
except IOError:
self._filename = None
return False | module function_definition identifier parameters identifier identifier block try_statement block with_statement with_clause with_item as_pattern call identifier argument_list identifier string string_start string_content string_end as_pattern_target identifier block expression_statement assignment attribute identifier identifier identifier expression_statement call attribute identifier identifier argument_list identifier return_statement true except_clause identifier block expression_statement assignment attribute identifier identifier none return_statement false | Reads the file specified and tokenizes the data for parsing. |
def native(s, encoding='utf-8', fallback='iso-8859-1'):
if isinstance(s, str):
return s
if str is unicode:
return unicodestr(s, encoding, fallback)
return bytestring(s, encoding, fallback) | module function_definition identifier parameters identifier default_parameter identifier string string_start string_content string_end default_parameter identifier string string_start string_content string_end block if_statement call identifier argument_list identifier identifier block return_statement identifier if_statement comparison_operator identifier identifier block return_statement call identifier argument_list identifier identifier identifier return_statement call identifier argument_list identifier identifier identifier | Convert a given string into a native string. |
def load_items():
filename = os.path.join(os.path.dirname(__file__), "data", "items.json")
with open(filename) as f:
items = json.loads(f.read())["result"]["items"]
for item in items:
ITEMS_CACHE[item["id"]] = item | module function_definition identifier parameters block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list call attribute attribute identifier identifier identifier argument_list identifier string string_start string_content string_end string string_start string_content string_end with_statement with_clause with_item as_pattern call identifier argument_list identifier as_pattern_target identifier block expression_statement assignment identifier subscript subscript call attribute identifier identifier argument_list call attribute identifier identifier argument_list string string_start string_content string_end string string_start string_content string_end for_statement identifier identifier block expression_statement assignment subscript identifier subscript identifier string string_start string_content string_end identifier | Load item details fom JSON file into memory |
def generate(self, url, browsers=None, orientation=None, mac_res=None, win_res=None,
quality=None, local=None, wait_time=None, callback_url=None):
if isinstance(browsers, dict):
browsers = [browsers]
if browsers is None:
browsers = [self.default_browser]
data = dict((key, value) for key, value in locals().items() if value is not None and key != 'self')
return self.execute('POST', '/screenshots', json=data) | module function_definition identifier parameters identifier identifier default_parameter identifier none default_parameter identifier none default_parameter identifier none default_parameter identifier none default_parameter identifier none default_parameter identifier none default_parameter identifier none default_parameter identifier none block if_statement call identifier argument_list identifier identifier block expression_statement assignment identifier list identifier if_statement comparison_operator identifier none block expression_statement assignment identifier list attribute identifier identifier expression_statement assignment identifier call identifier generator_expression tuple identifier identifier for_in_clause pattern_list identifier identifier call attribute call identifier argument_list identifier argument_list if_clause boolean_operator comparison_operator identifier none comparison_operator identifier string string_start string_content string_end return_statement call attribute identifier identifier argument_list string string_start string_content string_end string string_start string_content string_end keyword_argument identifier identifier | Generates screenshots for a URL. |
def _create_channel(self, channel):
super()._create_channel(channel)
if 'EXCEPTS' in self._isupport:
self.channels[channel]['exceptlist'] = None
if 'INVEX' in self._isupport:
self.channels[channel]['inviteexceptlist'] = None | module function_definition identifier parameters identifier identifier block expression_statement call attribute call identifier argument_list identifier argument_list identifier if_statement comparison_operator string string_start string_content string_end attribute identifier identifier block expression_statement assignment subscript subscript attribute identifier identifier identifier string string_start string_content string_end none if_statement comparison_operator string string_start string_content string_end attribute identifier identifier block expression_statement assignment subscript subscript attribute identifier identifier identifier string string_start string_content string_end none | Create channel with optional ban and invite exception lists. |
def comment_set(self):
ct = ContentType.objects.get_for_model(self.__class__)
qs = Comment.objects.filter(
content_type=ct,
object_pk=self.pk)
qs = qs.exclude(is_removed=True)
qs = qs.order_by('-submit_date')
return qs | module function_definition identifier parameters identifier block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list attribute identifier identifier expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list keyword_argument identifier identifier keyword_argument identifier attribute identifier identifier expression_statement assignment identifier call attribute identifier identifier argument_list keyword_argument identifier true expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end return_statement identifier | Get the comments that have been submitted for the chat |
def scale_image(self):
new_width = int(self.figcanvas.fwidth *
self._scalestep ** self._scalefactor)
new_height = int(self.figcanvas.fheight *
self._scalestep ** self._scalefactor)
self.figcanvas.setFixedSize(new_width, new_height) | module function_definition identifier parameters identifier block expression_statement assignment identifier call identifier argument_list binary_operator attribute attribute identifier identifier identifier binary_operator attribute identifier identifier attribute identifier identifier expression_statement assignment identifier call identifier argument_list binary_operator attribute attribute identifier identifier identifier binary_operator attribute identifier identifier attribute identifier identifier expression_statement call attribute attribute identifier identifier identifier argument_list identifier identifier | Scale the image size. |
def move_id_ahead(element_id, reference_id, idstr_list):
if element_id == reference_id:
return idstr_list
idstr_list.remove(str(element_id))
reference_index = idstr_list.index(str(reference_id))
idstr_list.insert(reference_index, str(element_id))
return idstr_list | module function_definition identifier parameters identifier identifier identifier block if_statement comparison_operator identifier identifier block return_statement identifier expression_statement call attribute identifier identifier argument_list call identifier argument_list identifier expression_statement assignment identifier call attribute identifier identifier argument_list call identifier argument_list identifier expression_statement call attribute identifier identifier argument_list identifier call identifier argument_list identifier return_statement identifier | Moves element_id ahead of reference_id in the list |
def FetchDiscoveryDoc(discovery_url, retries=5):
discovery_urls = _NormalizeDiscoveryUrls(discovery_url)
discovery_doc = None
last_exception = None
for url in discovery_urls:
for _ in range(retries):
try:
content = _GetURLContent(url)
if isinstance(content, bytes):
content = content.decode('utf8')
discovery_doc = json.loads(content)
break
except (urllib_error.HTTPError, urllib_error.URLError) as e:
logging.info(
'Attempting to fetch discovery doc again after "%s"', e)
last_exception = e
if discovery_doc is None:
raise CommunicationError(
'Could not find discovery doc at any of %s: %s' % (
discovery_urls, last_exception))
return discovery_doc | module function_definition identifier parameters identifier default_parameter identifier integer block expression_statement assignment identifier call identifier argument_list identifier expression_statement assignment identifier none expression_statement assignment identifier none for_statement identifier identifier block for_statement identifier call identifier argument_list identifier block try_statement block expression_statement assignment identifier call identifier argument_list identifier if_statement call identifier argument_list identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end expression_statement assignment identifier call attribute identifier identifier argument_list identifier break_statement except_clause as_pattern tuple attribute identifier identifier attribute identifier identifier as_pattern_target identifier block expression_statement call attribute identifier identifier argument_list string string_start string_content string_end identifier expression_statement assignment identifier identifier if_statement comparison_operator identifier none block raise_statement call identifier argument_list binary_operator string string_start string_content string_end tuple identifier identifier return_statement identifier | Fetch the discovery document at the given url. |
def append_checksum(self, f, checksum):
align_file_position(f, 16)
f.write(struct.pack(b'B', checksum)) | module function_definition identifier parameters identifier identifier identifier block expression_statement call identifier argument_list identifier integer expression_statement call attribute identifier identifier argument_list call attribute identifier identifier argument_list string string_start string_content string_end identifier | Append ESPLoader checksum to the just-written image |
def init_command(default_output_format, default_myproxy_username):
if not default_output_format:
safeprint(
textwrap.fill(
'This must be one of "json" or "text". Other values will be '
"ignored. ENTER to skip."
)
)
default_output_format = (
click.prompt(
"Default CLI output format (cli.output_format)", default="text"
)
.strip()
.lower()
)
if default_output_format not in ("json", "text"):
default_output_format = None
if not default_myproxy_username:
safeprint(textwrap.fill("ENTER to skip."))
default_myproxy_username = click.prompt(
"Default myproxy username (cli.default_myproxy_username)",
default="",
show_default=False,
).strip()
safeprint(
"\n\nWriting updated config to {0}".format(os.path.expanduser("~/.globus.cfg"))
)
write_option(OUTPUT_FORMAT_OPTNAME, default_output_format)
write_option(MYPROXY_USERNAME_OPTNAME, default_myproxy_username) | module function_definition identifier parameters identifier identifier block if_statement not_operator identifier block expression_statement call identifier argument_list call attribute identifier identifier argument_list concatenated_string string string_start string_content string_end string string_start string_content string_end expression_statement assignment identifier parenthesized_expression call attribute call attribute call attribute identifier identifier argument_list string string_start string_content string_end keyword_argument identifier string string_start string_content string_end identifier argument_list identifier argument_list if_statement comparison_operator identifier tuple string string_start string_content string_end string string_start string_content string_end block expression_statement assignment identifier none if_statement not_operator identifier block expression_statement call identifier argument_list call attribute identifier identifier argument_list string string_start string_content string_end expression_statement assignment identifier call attribute call attribute identifier identifier argument_list string string_start string_content string_end keyword_argument identifier string string_start string_end keyword_argument identifier false identifier argument_list expression_statement call identifier argument_list call attribute string string_start string_content escape_sequence escape_sequence string_end identifier argument_list call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end expression_statement call identifier argument_list identifier identifier expression_statement call identifier argument_list identifier identifier | Executor for `globus config init` |
def setup(self, app):
super().setup(app)
self.enabled = len(self.cfg.backends)
self.default = self.cfg.default
if not self.default and self.enabled:
self.default = self.cfg.backends[0][0]
self.backends_hash = {name: parse.urlparse(loc) for (name, loc) in self.cfg.backends}
if self.default and self.default not in self.backends_hash:
raise PluginException('Backend not found: %s' % self.default) | module function_definition identifier parameters identifier identifier block expression_statement call attribute call identifier argument_list identifier argument_list identifier expression_statement assignment attribute identifier identifier call identifier argument_list attribute attribute identifier identifier identifier expression_statement assignment attribute identifier identifier attribute attribute identifier identifier identifier if_statement boolean_operator not_operator attribute identifier identifier attribute identifier identifier block expression_statement assignment attribute identifier identifier subscript subscript attribute attribute identifier identifier identifier integer integer expression_statement assignment attribute identifier identifier dictionary_comprehension pair identifier call attribute identifier identifier argument_list identifier for_in_clause tuple_pattern identifier identifier attribute attribute identifier identifier identifier if_statement boolean_operator attribute identifier identifier comparison_operator attribute identifier identifier attribute identifier identifier block raise_statement call identifier argument_list binary_operator string string_start string_content string_end attribute identifier identifier | Parse and prepare the plugin's configuration. |
def namedb_get_all_revealed_namespace_ids( self, current_block ):
query = "SELECT namespace_id FROM namespaces WHERE op = ? AND reveal_block < ?;"
args = (NAMESPACE_REVEAL, current_block + NAMESPACE_REVEAL_EXPIRE )
namespace_rows = namedb_query_execute( cur, query, args )
ret = []
for namespace_row in namespace_rows:
ret.append( namespace_row['namespace_id'] )
return ret | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier string string_start string_content string_end expression_statement assignment identifier tuple identifier binary_operator identifier identifier expression_statement assignment identifier call identifier argument_list identifier identifier identifier expression_statement assignment identifier list for_statement identifier identifier block expression_statement call attribute identifier identifier argument_list subscript identifier string string_start string_content string_end return_statement identifier | Get all non-expired revealed namespaces. |
def _max_args(self, f):
if f.func_defaults is None:
return f.func_code.co_argcount
return f.func_code.co_argcount + len(f.func_defaults) | module function_definition identifier parameters identifier identifier block if_statement comparison_operator attribute identifier identifier none block return_statement attribute attribute identifier identifier identifier return_statement binary_operator attribute attribute identifier identifier identifier call identifier argument_list attribute identifier identifier | Returns maximum number of arguments accepted by given function. |
def expose(self, binder, interface, annotation=None):
private_module = self
class Provider(object):
def get(self):
return private_module.private_injector.get_instance(
interface, annotation)
self.original_binder.bind(interface, annotated_with=annotation,
to_provider=Provider) | module function_definition identifier parameters identifier identifier identifier default_parameter identifier none block expression_statement assignment identifier identifier class_definition identifier argument_list identifier block function_definition identifier parameters identifier block return_statement call attribute attribute identifier identifier identifier argument_list identifier identifier expression_statement call attribute attribute identifier identifier identifier argument_list identifier keyword_argument identifier identifier keyword_argument identifier identifier | Expose the child injector to the parent inject for a binding. |
def tracked(self):
results = json.loads(self.client('track'))
results['jobs'] = [Job(self, **job) for job in results['jobs']]
return results | module function_definition identifier parameters identifier block expression_statement assignment identifier call attribute identifier identifier argument_list call attribute identifier identifier argument_list string string_start string_content string_end expression_statement assignment subscript identifier string string_start string_content string_end list_comprehension call identifier argument_list identifier dictionary_splat identifier for_in_clause identifier subscript identifier string string_start string_content string_end return_statement identifier | Return an array of job objects that are being tracked |
def iterate(self, word):
for p in reversed(self.positions(word)):
if p.data:
change, index, cut = p.data
if word.isupper():
change = change.upper()
c1, c2 = change.split('=')
yield word[:p+index] + c1, c2 + word[p+index+cut:]
else:
yield word[:p], word[p:] | module function_definition identifier parameters identifier identifier block for_statement identifier call identifier argument_list call attribute identifier identifier argument_list identifier block if_statement attribute identifier identifier block expression_statement assignment pattern_list identifier identifier identifier attribute identifier identifier if_statement call attribute identifier identifier argument_list block expression_statement assignment identifier call attribute identifier identifier argument_list expression_statement assignment pattern_list identifier identifier call attribute identifier identifier argument_list string string_start string_content string_end expression_statement yield expression_list binary_operator subscript identifier slice binary_operator identifier identifier identifier binary_operator identifier subscript identifier slice binary_operator binary_operator identifier identifier identifier else_clause block expression_statement yield expression_list subscript identifier slice identifier subscript identifier slice identifier | Iterate over all hyphenation possibilities, the longest first. |
def calcPosition(self,parent_circle):
if r not in self:
raise AttributeError("radius must be calculated before position.")
if theta not in self:
raise AttributeError("theta must be set before position can be calculated.")
x_offset = math.cos(t_radians) * (parent_circle.r + self.r)
y_offset = math.sin(t_radians) * (parent_circle.r + self.r)
self.x = parent_circle.x + x_offset
self.y = parent_circle.y + y_offset | module function_definition identifier parameters identifier identifier block if_statement comparison_operator identifier identifier block raise_statement call identifier argument_list string string_start string_content string_end if_statement comparison_operator identifier identifier block raise_statement call identifier argument_list string string_start string_content string_end expression_statement assignment identifier binary_operator call attribute identifier identifier argument_list identifier parenthesized_expression binary_operator attribute identifier identifier attribute identifier identifier expression_statement assignment identifier binary_operator call attribute identifier identifier argument_list identifier parenthesized_expression binary_operator attribute identifier identifier attribute identifier identifier expression_statement assignment attribute identifier identifier binary_operator attribute identifier identifier identifier expression_statement assignment attribute identifier identifier binary_operator attribute identifier identifier identifier | Position the circle tangent to the parent circle with the line connecting the centers of the two circles meeting the x axis at angle theta. |
def add_column(connection, column):
stmt = alembic.ddl.base.AddColumn(_State.table.name, column)
connection.execute(stmt)
_State.reflect_metadata() | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call attribute attribute attribute identifier identifier identifier identifier argument_list attribute attribute identifier identifier identifier identifier expression_statement call attribute identifier identifier argument_list identifier expression_statement call attribute identifier identifier argument_list | Add a column to the current table. |
def _run_arvados(args):
assert not args.no_container, "Arvados runs require containers"
assert "ARVADOS_API_TOKEN" in os.environ and "ARVADOS_API_HOST" in os.environ, \
"Need to set ARVADOS_API_TOKEN and ARVADOS_API_HOST in environment to run"
main_file, json_file, project_name = _get_main_and_json(args.directory)
flags = ["--enable-reuse", "--api", "containers", "--submit", "--no-wait"]
cmd = ["arvados-cwl-runner"] + flags + args.toolargs + [main_file, json_file]
_run_tool(cmd) | module function_definition identifier parameters identifier block assert_statement not_operator attribute identifier identifier string string_start string_content string_end assert_statement boolean_operator comparison_operator string string_start string_content string_end attribute identifier identifier comparison_operator string string_start string_content string_end attribute identifier identifier string string_start string_content string_end expression_statement assignment pattern_list identifier identifier identifier call identifier argument_list attribute identifier identifier expression_statement assignment identifier list string string_start string_content string_end string string_start string_content string_end string string_start string_content string_end string string_start string_content string_end string string_start string_content string_end expression_statement assignment identifier binary_operator binary_operator binary_operator list string string_start string_content string_end identifier attribute identifier identifier list identifier identifier expression_statement call identifier argument_list identifier | Run CWL on Arvados. |
def run_kernel(self, func, gpu_args, instance):
logging.debug('run_kernel %s', instance.name)
logging.debug('thread block dims (%d, %d, %d)', *instance.threads)
logging.debug('grid dims (%d, %d, %d)', *instance.grid)
try:
self.dev.run_kernel(func, gpu_args, instance.threads, instance.grid)
except Exception as e:
if "too many resources requested for launch" in str(e) or "OUT_OF_RESOURCES" in str(e):
logging.debug('ignoring runtime failure due to too many resources required')
return False
else:
logging.debug('encountered unexpected runtime failure: ' + str(e))
raise e
return True | module function_definition identifier parameters identifier identifier identifier identifier block expression_statement call attribute identifier identifier argument_list string string_start string_content string_end attribute identifier identifier expression_statement call attribute identifier identifier argument_list string string_start string_content string_end list_splat attribute identifier identifier expression_statement call attribute identifier identifier argument_list string string_start string_content string_end list_splat attribute identifier identifier try_statement block expression_statement call attribute attribute identifier identifier identifier argument_list identifier identifier attribute identifier identifier attribute identifier identifier except_clause as_pattern identifier as_pattern_target identifier block if_statement boolean_operator comparison_operator string string_start string_content string_end call identifier argument_list identifier comparison_operator string string_start string_content string_end call identifier argument_list identifier block expression_statement call attribute identifier identifier argument_list string string_start string_content string_end return_statement false else_clause block expression_statement call attribute identifier identifier argument_list binary_operator string string_start string_content string_end call identifier argument_list identifier raise_statement identifier return_statement true | Run a compiled kernel instance on a device |
def _did_timeout(self):
bambou_logger.debug('Bambou %s on %s has timeout (timeout=%ss)..' % (self._request.method, self._request.url, self.timeout))
self._has_timeouted = True
if self.async:
self._callback(self)
else:
return self | module function_definition identifier parameters identifier block expression_statement call attribute identifier identifier argument_list binary_operator string string_start string_content string_end tuple attribute attribute identifier identifier identifier attribute attribute identifier identifier identifier attribute identifier identifier expression_statement assignment attribute identifier identifier true if_statement attribute identifier identifier block expression_statement call attribute identifier identifier argument_list identifier else_clause block return_statement identifier | Called when a resquest has timeout |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.