code stringlengths 51 2.34k | sequence stringlengths 186 3.94k | docstring stringlengths 11 171 |
|---|---|---|
def _get_signature(self, entry):
if self._sha1_sigs:
if not os.path.exists(entry.filename):
return None
try:
with open(entry.filename, "r") as f:
data = f.read()
return hashlib.sha1(data.encode("utf-8")).digest()
except IOError as e:
print("Cannot determine sha1 digest:", e)
return None
else:
try:
return os.path.getmtime(entry.filename)
except OSError:
return None | module function_definition identifier parameters identifier identifier block if_statement attribute identifier identifier block if_statement not_operator call attribute attribute identifier identifier identifier argument_list attribute identifier identifier block return_statement none try_statement 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 identifier call attribute identifier identifier argument_list return_statement call attribute call attribute identifier identifier argument_list call attribute identifier identifier argument_list string string_start string_content string_end identifier argument_list except_clause as_pattern identifier as_pattern_target identifier block expression_statement call identifier argument_list string string_start string_content string_end identifier return_statement none else_clause block try_statement block return_statement call attribute attribute identifier identifier identifier argument_list attribute identifier identifier except_clause identifier block return_statement none | Return the signature of the file stored in entry. |
def length(self):
return sum([shot.length for shot in self.shots if not shot.is_splay]) | module function_definition identifier parameters identifier block return_statement call identifier argument_list list_comprehension attribute identifier identifier for_in_clause identifier attribute identifier identifier if_clause not_operator attribute identifier identifier | Total surveyed cave length, not including splays. |
def close_connection (self):
if self.url_connection is not None:
try:
self.url_connection.quit()
except Exception:
pass
self.url_connection = None | module function_definition identifier parameters identifier block if_statement comparison_operator attribute identifier identifier none block try_statement block expression_statement call attribute attribute identifier identifier identifier argument_list except_clause identifier block pass_statement expression_statement assignment attribute identifier identifier none | Release the open connection from the connection pool. |
def run_actor(self, actor):
set_actor(actor)
if not actor.mailbox.address:
address = ('127.0.0.1', 0)
actor._loop.create_task(
actor.mailbox.start_serving(address=address)
)
actor._loop.run_forever() | module function_definition identifier parameters identifier identifier block expression_statement call identifier argument_list identifier if_statement not_operator attribute attribute identifier identifier identifier block expression_statement assignment identifier tuple string string_start string_content string_end integer expression_statement call attribute attribute identifier identifier identifier argument_list call attribute attribute identifier identifier identifier argument_list keyword_argument identifier identifier expression_statement call attribute attribute identifier identifier identifier argument_list | Start running the ``actor``. |
def as_dict(self):
"Get the WorkResult as a dict."
return {
'output': self.output,
'test_outcome': self.test_outcome,
'worker_outcome': self.worker_outcome,
'diff': self.diff,
} | module function_definition identifier parameters identifier block expression_statement string string_start string_content string_end return_statement dictionary pair string string_start string_content string_end attribute identifier identifier pair string string_start string_content string_end attribute identifier identifier pair string string_start string_content string_end attribute identifier identifier pair string string_start string_content string_end attribute identifier identifier | Get the WorkResult as a dict. |
def encode(value, encoding='utf-8', encoding_errors='strict'):
if isinstance(value, bytes):
return value
if not isinstance(value, basestring):
value = str(value)
if isinstance(value, unicode):
value = value.encode(encoding, encoding_errors)
return value | 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 not_operator call identifier argument_list identifier identifier 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 identifier identifier return_statement identifier | Return a bytestring representation of the value. |
def function_end(self):
self.newline_label(self.shared.function_name + "_exit", True, True)
self.move("%14", "%15")
self.pop("%14")
self.newline_text("RET", True) | module function_definition identifier parameters identifier block expression_statement call attribute identifier identifier argument_list binary_operator attribute attribute identifier identifier identifier string string_start string_content string_end true true expression_statement call attribute identifier identifier argument_list string string_start string_content string_end string string_start string_content string_end expression_statement call attribute identifier 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 true | Inserts an exit label and function return instructions |
def param_dict_to_list(dict,skeys=None):
RV = SP.concatenate([dict[key].flatten() for key in skeys])
return RV
pass | module function_definition identifier parameters identifier default_parameter identifier none block expression_statement assignment identifier call attribute identifier identifier argument_list list_comprehension call attribute subscript identifier identifier identifier argument_list for_in_clause identifier identifier return_statement identifier pass_statement | convert from param dictionary to list |
def render_registration(self):
surface = self.get_surface()
if self.canvas is None or self.df_canvas_corners.shape[0] == 0:
return surface
corners = self.df_canvas_corners.copy()
corners['w'] = 1
transform = self.canvas.shapes_to_canvas_transform
canvas_corners = corners.values.dot(transform.T.values).T
points_x = canvas_corners[0]
points_y = canvas_corners[1]
cairo_context = cairo.Context(surface)
cairo_context.move_to(points_x[0], points_y[0])
for x, y in zip(points_x[1:], points_y[1:]):
cairo_context.line_to(x, y)
cairo_context.line_to(points_x[0], points_y[0])
cairo_context.set_source_rgb(1, 0, 0)
cairo_context.stroke()
return surface | module function_definition identifier parameters identifier block expression_statement assignment identifier call attribute identifier identifier argument_list if_statement boolean_operator comparison_operator attribute identifier identifier none comparison_operator subscript attribute attribute identifier identifier identifier integer integer block return_statement identifier expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list expression_statement assignment subscript identifier string string_start string_content string_end integer expression_statement assignment identifier attribute attribute identifier identifier identifier expression_statement assignment identifier attribute call attribute attribute identifier identifier identifier argument_list attribute attribute identifier identifier identifier identifier expression_statement assignment identifier subscript identifier integer expression_statement assignment identifier subscript identifier integer expression_statement assignment identifier call attribute identifier identifier argument_list identifier expression_statement call attribute identifier identifier argument_list subscript identifier integer subscript identifier integer for_statement pattern_list identifier identifier call identifier argument_list subscript identifier slice integer subscript identifier slice integer block expression_statement call attribute identifier identifier argument_list identifier identifier expression_statement call attribute identifier identifier argument_list subscript identifier integer subscript identifier integer expression_statement call attribute identifier identifier argument_list integer integer integer expression_statement call attribute identifier identifier argument_list return_statement identifier | Render pinned points on video frame as red rectangle. |
def fileserver(opts, backends):
return LazyLoader(_module_dirs(opts, 'fileserver'),
opts,
tag='fileserver',
whitelist=backends,
pack={'__utils__': utils(opts)}) | module function_definition identifier parameters identifier identifier block return_statement call identifier argument_list call identifier argument_list identifier string string_start string_content string_end identifier keyword_argument identifier string string_start string_content string_end keyword_argument identifier identifier keyword_argument identifier dictionary pair string string_start string_content string_end call identifier argument_list identifier | Returns the file server modules |
def on_batch_begin(self, train, **kwargs:Any)->None:
"Record learning rate and momentum at beginning of batch."
if train:
self.lrs.append(self.opt.lr)
self.moms.append(self.opt.mom) | module function_definition identifier parameters identifier identifier typed_parameter dictionary_splat_pattern identifier type identifier type none block expression_statement string string_start string_content string_end if_statement identifier block expression_statement call attribute attribute identifier identifier identifier argument_list attribute attribute identifier identifier identifier expression_statement call attribute attribute identifier identifier identifier argument_list attribute attribute identifier identifier identifier | Record learning rate and momentum at beginning of batch. |
def precheck():
cfg_path = local_config['PROJECT']['CONFIG_PATH']
logging = set_logging(local_config)
if os.path.exists(cfg_path):
logger.info('%s: config_path parameter: %s' % (inspect.stack()[0][3], cfg_path))
logger.info(
'%s: Existing configuration file found. precheck pass.' %
(inspect.stack()[0][3]))
return True
elif not os.path.exists(cfg_path) and logging is False:
logger.info(
'%s: No pre-existing configuration file found at %s. Using defaults. Logging disabled.' %
(inspect.stack()[0][3], cfg_path)
)
return True
if logging:
logger.info(
'%s: Logging enabled per config file (%s).' %
(inspect.stack()[0][3], cfg_path)
)
return True
return False | module function_definition identifier parameters block expression_statement assignment identifier subscript subscript identifier string string_start string_content string_end string string_start string_content string_end expression_statement assignment identifier call identifier argument_list 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 tuple subscript subscript call attribute identifier identifier argument_list integer integer identifier expression_statement call attribute identifier identifier argument_list binary_operator string string_start string_content string_end parenthesized_expression subscript subscript call attribute identifier identifier argument_list integer integer return_statement true elif_clause boolean_operator not_operator call attribute attribute identifier identifier identifier argument_list identifier comparison_operator identifier false block expression_statement call attribute identifier identifier argument_list binary_operator string string_start string_content string_end tuple subscript subscript call attribute identifier identifier argument_list integer integer identifier return_statement true if_statement identifier block expression_statement call attribute identifier identifier argument_list binary_operator string string_start string_content string_end tuple subscript subscript call attribute identifier identifier argument_list integer integer identifier return_statement true return_statement false | Verify project runtime dependencies |
def add_dependency(self, value):
if value.name in self.dependencies:
self.dependencies[value.name.lower()].append(value)
else:
self.dependencies[value.name.lower()] = [ value ] | module function_definition identifier parameters identifier identifier block if_statement comparison_operator attribute identifier identifier attribute identifier identifier block expression_statement call attribute subscript attribute identifier identifier call attribute attribute identifier identifier identifier argument_list identifier argument_list identifier else_clause block expression_statement assignment subscript attribute identifier identifier call attribute attribute identifier identifier identifier argument_list list identifier | Adds the specified executable dependency to the list for this executable. |
def NoCache(self, *targets):
tlist = []
for t in targets:
tlist.extend(self.arg2nodes(t, self.fs.Entry))
for t in tlist:
t.set_nocache()
return tlist | module function_definition identifier parameters identifier list_splat_pattern identifier block expression_statement assignment identifier list for_statement identifier identifier block expression_statement call attribute identifier identifier argument_list call attribute identifier identifier argument_list identifier attribute attribute identifier identifier identifier for_statement identifier identifier block expression_statement call attribute identifier identifier argument_list return_statement identifier | Tags a target so that it will not be cached |
def parse_field(source, loc, tokens):
name = tokens[0].lower()
value = normalize_value(tokens[2])
if name == 'author' and ' and ' in value:
value = [field.strip() for field in value.split(' and ')]
return (name, value) | module function_definition identifier parameters identifier identifier identifier block expression_statement assignment identifier call attribute subscript identifier integer identifier argument_list expression_statement assignment identifier call identifier argument_list subscript identifier integer if_statement boolean_operator comparison_operator identifier string string_start string_content string_end comparison_operator string string_start string_content string_end identifier block expression_statement assignment identifier list_comprehension call attribute identifier identifier argument_list for_in_clause identifier call attribute identifier identifier argument_list string string_start string_content string_end return_statement tuple identifier identifier | Returns the tokens of a field as key-value pair. |
def writeln(self, text, fg='black', bg='white'):
if not isinstance(text, str):
text = str(text)
self.write(text + '\n', fg=fg, bg=bg) | module function_definition identifier parameters identifier identifier default_parameter identifier string string_start string_content string_end default_parameter identifier string string_start string_content string_end block if_statement not_operator call identifier argument_list identifier identifier block expression_statement assignment identifier call identifier argument_list identifier expression_statement call attribute identifier identifier argument_list binary_operator identifier string string_start string_content escape_sequence string_end keyword_argument identifier identifier keyword_argument identifier identifier | write to the console with linefeed |
def send_keys(self, keyserver, *keyids):
result = self._result_map['list'](self)
log.debug('send_keys: %r', keyids)
data = _util._make_binary_stream("", self._encoding)
args = ['--keyserver', keyserver, '--send-keys']
args.extend(keyids)
self._handle_io(args, data, result, binary=True)
log.debug('send_keys result: %r', result.__dict__)
data.close()
return result | module function_definition identifier parameters identifier identifier list_splat_pattern identifier block expression_statement assignment identifier call subscript attribute identifier identifier string string_start string_content string_end argument_list identifier expression_statement call attribute identifier identifier argument_list string string_start string_content string_end identifier expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_end attribute identifier identifier expression_statement assignment identifier list string string_start string_content string_end identifier string string_start string_content string_end expression_statement call attribute identifier identifier argument_list identifier expression_statement call attribute identifier identifier argument_list identifier identifier identifier keyword_argument identifier true 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 return_statement identifier | Send keys to a keyserver. |
def to_det_id(self, det_id_or_det_oid):
try:
int(det_id_or_det_oid)
except ValueError:
return self.get_det_id(det_id_or_det_oid)
else:
return det_id_or_det_oid | module function_definition identifier parameters identifier identifier block try_statement block expression_statement call identifier argument_list identifier except_clause identifier block return_statement call attribute identifier identifier argument_list identifier else_clause block return_statement identifier | Convert det ID or OID to det ID |
def pack_value(self, val):
if isinstance(val, bytes):
val = list(iterbytes(val))
slen = len(val)
if self.pad:
pad = b'\0\0' * (slen % 2)
else:
pad = b''
return struct.pack('>' + 'H' * slen, *val) + pad, slen, None | module function_definition identifier parameters identifier identifier block if_statement call identifier argument_list identifier identifier block expression_statement assignment identifier call identifier argument_list call identifier argument_list identifier expression_statement assignment identifier call identifier argument_list identifier if_statement attribute identifier identifier block expression_statement assignment identifier binary_operator string string_start string_content escape_sequence escape_sequence string_end parenthesized_expression binary_operator identifier integer else_clause block expression_statement assignment identifier string string_start string_end return_statement expression_list binary_operator call attribute identifier identifier argument_list binary_operator string string_start string_content string_end binary_operator string string_start string_content string_end identifier list_splat identifier identifier identifier none | Convert 8-byte string into 16-byte list |
def builds(self, confs):
self._named_builds = {}
self._builds = []
for values in confs:
if len(values) == 2:
self._builds.append(BuildConf(values[0], values[1], {}, {}, self.reference))
elif len(values) == 4:
self._builds.append(BuildConf(values[0], values[1], values[2], values[3],
self.reference))
elif len(values) != 5:
raise Exception("Invalid build configuration, has to be a tuple of "
"(settings, options, env_vars, build_requires, reference)")
else:
self._builds.append(BuildConf(*values)) | module function_definition identifier parameters identifier identifier block expression_statement assignment attribute identifier identifier dictionary expression_statement assignment attribute identifier identifier list for_statement identifier identifier block if_statement comparison_operator call identifier argument_list identifier integer block expression_statement call attribute attribute identifier identifier identifier argument_list call identifier argument_list subscript identifier integer subscript identifier integer dictionary dictionary attribute identifier identifier elif_clause comparison_operator call identifier argument_list identifier integer block expression_statement call attribute attribute identifier identifier identifier argument_list call identifier argument_list subscript identifier integer subscript identifier integer subscript identifier integer subscript identifier integer attribute identifier identifier elif_clause comparison_operator call identifier argument_list identifier integer block raise_statement call identifier argument_list concatenated_string string string_start string_content string_end string string_start string_content string_end else_clause block expression_statement call attribute attribute identifier identifier identifier argument_list call identifier argument_list list_splat identifier | For retro compatibility directly assigning builds |
def _svg_path(self, pathcodes, data):
def gen_path_elements(pathcodes, data):
counts = {'M': 1, 'L': 1, 'C': 3, 'Z': 0}
it = iter(data)
for code in pathcodes:
yield code
for _ in range(counts[code]):
p = next(it)
yield str(p[0])
yield str(p[1])
return ' '.join(gen_path_elements(pathcodes, data)) | module function_definition identifier parameters identifier identifier identifier block function_definition identifier parameters identifier identifier block expression_statement assignment identifier dictionary pair string string_start string_content string_end integer pair string string_start string_content string_end integer pair string string_start string_content string_end integer pair string string_start string_content string_end integer expression_statement assignment identifier call identifier argument_list identifier for_statement identifier identifier block expression_statement yield identifier for_statement identifier call identifier argument_list subscript identifier identifier block expression_statement assignment identifier call identifier argument_list identifier expression_statement yield call identifier argument_list subscript identifier integer expression_statement yield call identifier argument_list subscript identifier integer return_statement call attribute string string_start string_content string_end identifier argument_list call identifier argument_list identifier identifier | Return the SVG path's 'd' element. |
def getStats(jobStore):
def aggregateStats(fileHandle,aggregateObject):
try:
stats = json.load(fileHandle, object_hook=Expando)
for key in list(stats.keys()):
if key in aggregateObject:
aggregateObject[key].append(stats[key])
else:
aggregateObject[key]=[stats[key]]
except ValueError:
logger.critical("File %s contains corrupted json. Skipping file." % fileHandle)
pass
aggregateObject = Expando()
callBack = partial(aggregateStats, aggregateObject=aggregateObject)
jobStore.readStatsAndLogging(callBack, readAll=True)
return aggregateObject | module function_definition identifier parameters identifier block function_definition identifier parameters identifier identifier block try_statement block expression_statement assignment identifier call attribute identifier identifier argument_list identifier keyword_argument identifier identifier for_statement identifier call identifier argument_list call attribute identifier identifier argument_list block if_statement comparison_operator identifier identifier block expression_statement call attribute subscript identifier identifier identifier argument_list subscript identifier identifier else_clause block expression_statement assignment subscript identifier identifier list subscript identifier identifier except_clause identifier block expression_statement call attribute identifier identifier argument_list binary_operator string string_start string_content string_end identifier pass_statement expression_statement assignment identifier call identifier argument_list expression_statement assignment identifier call identifier argument_list identifier keyword_argument identifier identifier expression_statement call attribute identifier identifier argument_list identifier keyword_argument identifier true return_statement identifier | Collect and return the stats and config data. |
def _register_data_plane_account_arguments(self, command_name):
from azure.cli.core.commands.parameters import get_resource_name_completion_list
from ._validators import validate_client_parameters
command = self.command_loader.command_table.get(command_name, None)
if not command:
return
group_name = 'Storage Account'
command.add_argument('account_name', '--account-name', required=False, default=None,
arg_group=group_name,
completer=get_resource_name_completion_list('Microsoft.Storage/storageAccounts'),
help='Storage account name. Related environment variable: AZURE_STORAGE_ACCOUNT. Must be '
'used in conjunction with either storage account key or a SAS token. If neither are '
'present, the command will try to query the storage account key using the '
'authenticated Azure account. If a large number of storage commands are executed the '
'API quota may be hit')
command.add_argument('account_key', '--account-key', required=False, default=None,
arg_group=group_name,
help='Storage account key. Must be used in conjunction with storage account name. '
'Environment variable: AZURE_STORAGE_KEY')
command.add_argument('connection_string', '--connection-string', required=False, default=None,
validator=validate_client_parameters, arg_group=group_name,
help='Storage account connection string. Environment variable: '
'AZURE_STORAGE_CONNECTION_STRING')
command.add_argument('sas_token', '--sas-token', required=False, default=None,
arg_group=group_name,
help='A Shared Access Signature (SAS). Must be used in conjunction with storage account '
'name. Environment variable: AZURE_STORAGE_SAS_TOKEN') | module function_definition identifier parameters identifier identifier block import_from_statement dotted_name identifier identifier identifier identifier identifier dotted_name identifier import_from_statement relative_import import_prefix dotted_name identifier dotted_name identifier expression_statement assignment identifier call attribute attribute attribute identifier identifier identifier identifier argument_list identifier none if_statement not_operator identifier block return_statement expression_statement assignment identifier string string_start string_content string_end expression_statement call attribute identifier identifier argument_list string string_start string_content string_end string string_start string_content string_end keyword_argument identifier false keyword_argument identifier none keyword_argument identifier identifier keyword_argument identifier call identifier argument_list string string_start string_content string_end keyword_argument identifier concatenated_string 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 call attribute identifier identifier argument_list string string_start string_content string_end string string_start string_content string_end keyword_argument identifier false keyword_argument identifier none keyword_argument identifier identifier keyword_argument identifier concatenated_string string string_start string_content string_end string string_start string_content string_end expression_statement call attribute identifier identifier argument_list string string_start string_content string_end string string_start string_content string_end keyword_argument identifier false keyword_argument identifier none keyword_argument identifier identifier keyword_argument identifier identifier keyword_argument identifier concatenated_string string string_start string_content string_end string string_start string_content string_end expression_statement call attribute identifier identifier argument_list string string_start string_content string_end string string_start string_content string_end keyword_argument identifier false keyword_argument identifier none keyword_argument identifier identifier keyword_argument identifier concatenated_string string string_start string_content string_end string string_start string_content string_end | Add parameters required to create a storage client |
def _new_sample(self, sink):
if self.running:
buf = sink.emit('pull-sample').get_buffer()
mem = buf.get_all_memory()
success, info = mem.map(Gst.MapFlags.READ)
if success:
data = info.data
mem.unmap(info)
self.queue.put(data)
else:
raise GStreamerError("Unable to map buffer memory while reading the file.")
return Gst.FlowReturn.OK | module function_definition identifier parameters identifier identifier block if_statement attribute identifier identifier block expression_statement assignment identifier call attribute call attribute identifier identifier argument_list string string_start string_content string_end identifier argument_list expression_statement assignment identifier call attribute identifier identifier argument_list expression_statement assignment pattern_list identifier identifier call attribute identifier identifier argument_list attribute attribute identifier identifier identifier if_statement identifier block expression_statement assignment identifier attribute identifier identifier expression_statement call attribute identifier identifier argument_list identifier expression_statement call attribute attribute identifier identifier identifier argument_list identifier else_clause block raise_statement call identifier argument_list string string_start string_content string_end return_statement attribute attribute identifier identifier identifier | The callback for appsink's "new-sample" signal. |
def pid_from_context(_, context):
pid = (context or {}).get('pid')
return pid.pid_value if pid else missing | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call attribute parenthesized_expression boolean_operator identifier dictionary identifier argument_list string string_start string_content string_end return_statement conditional_expression attribute identifier identifier identifier identifier | Get PID from marshmallow context. |
def path(self):
if (self.source_file.startswith('a/') and
self.target_file.startswith('b/')):
filepath = self.source_file[2:]
elif (self.source_file.startswith('a/') and
self.target_file == '/dev/null'):
filepath = self.source_file[2:]
elif (self.target_file.startswith('b/') and
self.source_file == '/dev/null'):
filepath = self.target_file[2:]
else:
filepath = self.source_file
return filepath | module function_definition identifier parameters identifier block if_statement parenthesized_expression boolean_operator call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end block expression_statement assignment identifier subscript attribute identifier identifier slice integer elif_clause parenthesized_expression boolean_operator call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end comparison_operator attribute identifier identifier string string_start string_content string_end block expression_statement assignment identifier subscript attribute identifier identifier slice integer elif_clause parenthesized_expression boolean_operator call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end comparison_operator attribute identifier identifier string string_start string_content string_end block expression_statement assignment identifier subscript attribute identifier identifier slice integer else_clause block expression_statement assignment identifier attribute identifier identifier return_statement identifier | Return the file path abstracted from VCS. |
def DualDBFlow(cls):
if issubclass(cls, flow.GRRFlow):
raise ValueError("Mixin class shouldn't inherit from GRRFlow.")
if cls.__name__[-5:] != "Mixin":
raise ValueError("Flow mixin should have a name that ends in 'Mixin'.")
flow_name = cls.__name__[:-5]
aff4_cls = type(flow_name, (cls, flow.GRRFlow), {})
aff4_cls.__doc__ = cls.__doc__
setattr(aff4_flows, flow_name, aff4_cls)
reldb_cls = type(flow_name, (cls, FlowBase), {})
reldb_cls.__doc__ = cls.__doc__
setattr(sys.modules[cls.__module__], flow_name, reldb_cls)
return cls | module function_definition identifier parameters identifier block if_statement call identifier argument_list identifier attribute identifier identifier block raise_statement call identifier argument_list string string_start string_content string_end if_statement comparison_operator subscript attribute identifier identifier slice unary_operator integer string string_start string_content string_end block raise_statement call identifier argument_list string string_start string_content string_end expression_statement assignment identifier subscript attribute identifier identifier slice unary_operator integer expression_statement assignment identifier call identifier argument_list identifier tuple identifier attribute identifier identifier dictionary expression_statement assignment attribute identifier identifier attribute identifier identifier expression_statement call identifier argument_list identifier identifier identifier expression_statement assignment identifier call identifier argument_list identifier tuple identifier identifier dictionary expression_statement assignment attribute identifier identifier attribute identifier identifier expression_statement call identifier argument_list subscript attribute identifier identifier attribute identifier identifier identifier identifier return_statement identifier | Decorator that creates AFF4 and RELDB flows from a given mixin. |
def _get_ratings_page(self):
self._build_url()
soup = get_soup(self.url)
if soup:
return soup
self._build_url(shorten=False)
soup = get_soup(self.url)
if soup:
return soup
return SearchDaily(self.category, date=self.date).fetch_result() | module function_definition identifier parameters identifier block expression_statement call attribute identifier identifier argument_list expression_statement assignment identifier call identifier argument_list attribute identifier identifier if_statement identifier block return_statement identifier expression_statement call attribute identifier identifier argument_list keyword_argument identifier false expression_statement assignment identifier call identifier argument_list attribute identifier identifier if_statement identifier block return_statement identifier return_statement call attribute call identifier argument_list attribute identifier identifier keyword_argument identifier attribute identifier identifier identifier argument_list | Do a limited search for the correct url. |
def save(cls, filename, config):
mode = os.O_WRONLY | os.O_TRUNC | os.O_CREAT
with os.fdopen(os.open(filename, mode, 0o600), 'w') as fname:
yaml.safe_dump(config, fname, indent=4, default_flow_style=False) | module function_definition identifier parameters identifier identifier identifier block expression_statement assignment identifier binary_operator binary_operator attribute identifier identifier attribute identifier identifier attribute identifier identifier with_statement with_clause with_item as_pattern call attribute identifier identifier argument_list call attribute identifier identifier argument_list identifier identifier integer string string_start string_content string_end as_pattern_target identifier block expression_statement call attribute identifier identifier argument_list identifier identifier keyword_argument identifier integer keyword_argument identifier false | Save configuration to yaml file. |
def read_calibration(
detx=None, det_id=None, from_file=False, det_id_table=None
):
from km3pipe.calib import Calibration
if not (detx or det_id or from_file):
return None
if detx is not None:
return Calibration(filename=detx)
if from_file:
det_ids = np.unique(det_id_table)
if len(det_ids) > 1:
log.critical("Multiple detector IDs found in events.")
det_id = det_ids[0]
if det_id is not None:
if det_id < 0:
log.warning(
"Negative detector ID found ({0}). This is a MC "
"detector and cannot be retrieved from the DB.".format(det_id)
)
return None
return Calibration(det_id=det_id)
return None | module function_definition identifier parameters default_parameter identifier none default_parameter identifier none default_parameter identifier false default_parameter identifier none block import_from_statement dotted_name identifier identifier dotted_name identifier if_statement not_operator parenthesized_expression boolean_operator boolean_operator identifier identifier identifier block return_statement none if_statement comparison_operator identifier none block return_statement call identifier argument_list keyword_argument identifier identifier if_statement identifier block expression_statement assignment identifier call attribute identifier identifier argument_list identifier if_statement comparison_operator call identifier argument_list identifier integer block expression_statement call attribute identifier identifier argument_list string string_start string_content string_end expression_statement assignment identifier subscript identifier integer if_statement comparison_operator identifier none block if_statement comparison_operator identifier integer block expression_statement call attribute identifier identifier argument_list call attribute concatenated_string string string_start string_content string_end string string_start string_content string_end identifier argument_list identifier return_statement none return_statement call identifier argument_list keyword_argument identifier identifier return_statement none | Retrive calibration from file, the DB. |
def resolve(self,size, distribution):
if not self.variablesize():
raise Exception("Can only resize patterns with * wildcards")
nrofwildcards = 0
for x in self.sequence:
if x == '*':
nrofwildcards += 1
assert (len(distribution) == nrofwildcards)
wildcardnr = 0
newsequence = []
for x in self.sequence:
if x == '*':
newsequence += [True] * distribution[wildcardnr]
wildcardnr += 1
else:
newsequence.append(x)
d = { 'matchannotation':self.matchannotation, 'matchannotationset':self.matchannotationset, 'casesensitive':self.casesensitive }
yield Pattern(*newsequence, **d ) | module function_definition identifier parameters identifier identifier identifier block if_statement not_operator call attribute identifier identifier argument_list block raise_statement call identifier argument_list string string_start string_content string_end expression_statement assignment identifier integer for_statement identifier attribute identifier identifier block if_statement comparison_operator identifier string string_start string_content string_end block expression_statement augmented_assignment identifier integer assert_statement parenthesized_expression comparison_operator call identifier argument_list identifier identifier expression_statement assignment identifier integer expression_statement assignment identifier list for_statement identifier attribute identifier identifier block if_statement comparison_operator identifier string string_start string_content string_end block expression_statement augmented_assignment identifier binary_operator list true subscript identifier identifier expression_statement augmented_assignment identifier integer else_clause block expression_statement call attribute identifier identifier argument_list identifier expression_statement assignment identifier dictionary pair string string_start string_content string_end attribute identifier identifier pair string string_start string_content string_end attribute identifier identifier pair string string_start string_content string_end attribute identifier identifier expression_statement yield call identifier argument_list list_splat identifier dictionary_splat identifier | Resolve a variable sized pattern to all patterns of a certain fixed size |
def calculate_quality_metrics(metrics, designs, verbose=False):
for metric in metrics:
if metric.progress_update:
print metric.progress_update
metric.load(designs, verbose) | module function_definition identifier parameters identifier identifier default_parameter identifier false block for_statement identifier identifier block if_statement attribute identifier identifier block print_statement attribute identifier identifier expression_statement call attribute identifier identifier argument_list identifier identifier | Have each metric calculate all the information it needs. |
def make_compound_ctype(self, varname):
compoundname = self.get_var_type(varname)
nfields = self.inq_compound(compoundname)
fields = []
for i in range(nfields):
(fieldname, fieldtype,
fieldrank, fieldshape) = self.inq_compound_field(compoundname, i)
assert fieldrank <= 1
fieldctype = CTYPESMAP[fieldtype]
if fieldrank == 1:
fieldctype = fieldctype * fieldshape[0]
fields.append((fieldname, fieldctype))
class COMPOUND(Structure):
_fields_ = fields
rank = self.get_var_rank(varname)
assert rank <= 1, "we can't handle >=2 dimensional compounds yet"
if rank == 1:
shape = self.get_var_shape(varname)
valtype = POINTER(ARRAY(COMPOUND, shape[0]))
else:
valtype = POINTER(COMPOUND)
return valtype | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list identifier expression_statement assignment identifier call attribute identifier identifier argument_list identifier expression_statement assignment identifier list for_statement identifier call identifier argument_list identifier block expression_statement assignment tuple_pattern identifier identifier identifier identifier call attribute identifier identifier argument_list identifier identifier assert_statement comparison_operator identifier integer expression_statement assignment identifier subscript identifier identifier if_statement comparison_operator identifier integer block expression_statement assignment identifier binary_operator identifier subscript identifier integer expression_statement call attribute identifier identifier argument_list tuple identifier identifier class_definition identifier argument_list identifier block expression_statement assignment identifier identifier expression_statement assignment identifier call attribute identifier identifier argument_list identifier assert_statement comparison_operator identifier integer string string_start string_content string_end if_statement comparison_operator identifier integer block expression_statement assignment identifier call attribute identifier identifier argument_list identifier expression_statement assignment identifier call identifier argument_list call identifier argument_list identifier subscript identifier integer else_clause block expression_statement assignment identifier call identifier argument_list identifier return_statement identifier | Create a ctypes type that corresponds to a compound type in memory. |
def _fetch_metric(self, metric_name):
request = {
'Namespace': self.CLOUDWATCH_NAMESPACE,
'MetricName': metric_name,
'Dimensions': [
{
'Name': 'TrainingJobName',
'Value': self.name
}
],
'StartTime': self._time_interval['start_time'],
'EndTime': self._time_interval['end_time'],
'Period': self._period,
'Statistics': ['Average'],
}
raw_cwm_data = self._cloudwatch.get_metric_statistics(**request)['Datapoints']
if len(raw_cwm_data) == 0:
logging.warning("Warning: No metrics called %s found" % metric_name)
return
base_time = min(raw_cwm_data, key=lambda pt: pt['Timestamp'])['Timestamp']
all_xy = []
for pt in raw_cwm_data:
y = pt['Average']
x = (pt['Timestamp'] - base_time).total_seconds()
all_xy.append([x, y])
all_xy = sorted(all_xy, key=lambda x: x[0])
for elapsed_seconds, value in all_xy:
self._add_single_metric(elapsed_seconds, metric_name, value) | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier dictionary pair string string_start string_content string_end attribute identifier identifier pair string string_start string_content string_end identifier pair string string_start string_content string_end list 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 identifier identifier pair string string_start string_content string_end subscript attribute identifier identifier string string_start string_content string_end pair string string_start string_content string_end subscript attribute identifier identifier string string_start string_content string_end pair string string_start string_content string_end attribute identifier identifier pair string string_start string_content string_end list string string_start string_content string_end expression_statement assignment identifier subscript call attribute attribute identifier identifier identifier argument_list dictionary_splat identifier string string_start string_content string_end if_statement comparison_operator call identifier argument_list identifier integer block expression_statement call attribute identifier identifier argument_list binary_operator string string_start string_content string_end identifier return_statement expression_statement assignment identifier subscript call identifier argument_list identifier keyword_argument identifier lambda lambda_parameters identifier subscript identifier string string_start string_content string_end string string_start string_content string_end expression_statement assignment identifier list for_statement identifier identifier block expression_statement assignment identifier subscript identifier string string_start string_content string_end expression_statement assignment identifier call attribute parenthesized_expression binary_operator subscript identifier string string_start string_content string_end identifier identifier argument_list expression_statement call attribute identifier identifier argument_list list identifier identifier expression_statement assignment identifier call identifier argument_list identifier keyword_argument identifier lambda lambda_parameters identifier subscript identifier integer for_statement pattern_list identifier identifier identifier block expression_statement call attribute identifier identifier argument_list identifier identifier identifier | Fetch all the values of a named metric, and add them to _data |
def token(self):
if AUTH_TOKEN_HEADER in self.request.headers:
return self.request.headers[AUTH_TOKEN_HEADER]
else:
return self.get_cookie(AUTH_COOKIE_NAME) | module function_definition identifier parameters identifier block if_statement comparison_operator identifier attribute attribute identifier identifier identifier block return_statement subscript attribute attribute identifier identifier identifier identifier else_clause block return_statement call attribute identifier identifier argument_list identifier | The token used for the request |
def simplify_recursive(typ):
if isinstance(typ, UnionType):
return combine_types(typ.items)
elif isinstance(typ, ClassType):
simplified = ClassType(typ.name, [simplify_recursive(arg) for arg in typ.args])
args = simplified.args
if (simplified.name == 'Dict' and len(args) == 2
and isinstance(args[0], ClassType) and args[0].name in ('str', 'Text')
and isinstance(args[1], UnionType) and not is_optional(args[1])):
return ClassType('Dict', [args[0], AnyType()])
return simplified
elif isinstance(typ, TupleType):
return TupleType([simplify_recursive(item) for item in typ.items])
return typ | module function_definition identifier parameters identifier block if_statement call identifier argument_list identifier identifier block return_statement call identifier argument_list attribute identifier identifier elif_clause call identifier argument_list identifier identifier block expression_statement assignment identifier call identifier argument_list attribute identifier identifier list_comprehension call identifier argument_list identifier for_in_clause identifier attribute identifier identifier expression_statement assignment identifier attribute identifier identifier if_statement parenthesized_expression boolean_operator boolean_operator boolean_operator boolean_operator boolean_operator comparison_operator attribute identifier identifier string string_start string_content string_end comparison_operator call identifier argument_list identifier integer call identifier argument_list subscript identifier integer identifier comparison_operator attribute subscript identifier integer identifier tuple string string_start string_content string_end string string_start string_content string_end call identifier argument_list subscript identifier integer identifier not_operator call identifier argument_list subscript identifier integer block return_statement call identifier argument_list string string_start string_content string_end list subscript identifier integer call identifier argument_list return_statement identifier elif_clause call identifier argument_list identifier identifier block return_statement call identifier argument_list list_comprehension call identifier argument_list identifier for_in_clause identifier attribute identifier identifier return_statement identifier | Simplify all components of a type. |
def _remove_deprecated_options(self, old_version):
old_defaults = self._load_old_defaults(old_version)
for section in old_defaults.sections():
for option, _ in old_defaults.items(section, raw=self.raw):
if self.get_default(section, option) is NoDefault:
try:
self.remove_option(section, option)
if len(self.items(section, raw=self.raw)) == 0:
self.remove_section(section)
except cp.NoSectionError:
self.remove_section(section) | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list identifier for_statement identifier call attribute identifier identifier argument_list block for_statement pattern_list identifier identifier call attribute identifier identifier argument_list identifier keyword_argument identifier attribute identifier identifier block if_statement comparison_operator call attribute identifier identifier argument_list identifier identifier identifier block try_statement block expression_statement call attribute identifier identifier argument_list identifier identifier if_statement comparison_operator call identifier argument_list call attribute identifier identifier argument_list identifier keyword_argument identifier attribute identifier identifier integer block expression_statement call attribute identifier identifier argument_list identifier except_clause attribute identifier identifier block expression_statement call attribute identifier identifier argument_list identifier | Remove options which are present in the .ini file but not in defaults |
def _lab_to_rgb(labs):
labs, n_dim = _check_color_dim(labs)
y = (labs[:, 0] + 16.) / 116.
x = (labs[:, 1] / 500.) + y
z = y - (labs[:, 2] / 200.)
xyz = np.concatenate(([x], [y], [z]))
over = xyz > 0.2068966
xyz[over] = xyz[over] ** 3.
xyz[~over] = (xyz[~over] - 0.13793103448275862) / 7.787
rgbs = np.dot(_xyz2rgb_norm, xyz).T
over = rgbs > 0.0031308
rgbs[over] = 1.055 * (rgbs[over] ** (1. / 2.4)) - 0.055
rgbs[~over] *= 12.92
if n_dim == 4:
rgbs = np.concatenate((rgbs, labs[:, 3]), axis=1)
rgbs = np.clip(rgbs, 0., 1.)
return rgbs | module function_definition identifier parameters identifier block expression_statement assignment pattern_list identifier identifier call identifier argument_list identifier expression_statement assignment identifier binary_operator parenthesized_expression binary_operator subscript identifier slice integer float float expression_statement assignment identifier binary_operator parenthesized_expression binary_operator subscript identifier slice integer float identifier expression_statement assignment identifier binary_operator identifier parenthesized_expression binary_operator subscript identifier slice integer float expression_statement assignment identifier call attribute identifier identifier argument_list tuple list identifier list identifier list identifier expression_statement assignment identifier comparison_operator identifier float expression_statement assignment subscript identifier identifier binary_operator subscript identifier identifier float expression_statement assignment subscript identifier unary_operator identifier binary_operator parenthesized_expression binary_operator subscript identifier unary_operator identifier float float expression_statement assignment identifier attribute call attribute identifier identifier argument_list identifier identifier identifier expression_statement assignment identifier comparison_operator identifier float expression_statement assignment subscript identifier identifier binary_operator binary_operator float parenthesized_expression binary_operator subscript identifier identifier parenthesized_expression binary_operator float float float expression_statement augmented_assignment subscript identifier unary_operator identifier float if_statement comparison_operator identifier integer block expression_statement assignment identifier call attribute identifier identifier argument_list tuple identifier subscript identifier slice integer keyword_argument identifier integer expression_statement assignment identifier call attribute identifier identifier argument_list identifier float float return_statement identifier | Convert Nx3 or Nx4 lab to rgb |
def __init_yaml():
global _yaml_initialized
if not _yaml_initialized:
_yaml_initialized = True
yaml.add_constructor(u'tag:yaml.org,2002:Frame', _frame_constructor)
yaml.add_constructor(u'tag:yaml.org,2002:Signal', _signal_constructor)
yaml.add_representer(canmatrix.Frame, _frame_representer) | module function_definition identifier parameters block global_statement identifier if_statement not_operator identifier block expression_statement assignment identifier true expression_statement call attribute identifier identifier argument_list string string_start string_content string_end 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 attribute identifier identifier identifier | Lazy init yaml because canmatrix might not be fully loaded when loading this format. |
def copy_from(self, other_state):
for prop in self.properties().values():
setattr(self, prop.name, getattr(other_state, prop.name)) | module function_definition identifier parameters identifier identifier block for_statement identifier call attribute call attribute identifier identifier argument_list identifier argument_list block expression_statement call identifier argument_list identifier attribute identifier identifier call identifier argument_list identifier attribute identifier identifier | Copy data from another shard state entity to self. |
def _get_config(self, rel_path, view, api_version=1):
self._require_min_api_version(api_version)
params = view and dict(view=view) or None
resp = self._get_resource_root().get(self._path() + '/' + rel_path,
params=params)
return json_to_config(resp, view == 'full') | module function_definition identifier parameters identifier identifier identifier default_parameter identifier integer block expression_statement call attribute identifier identifier argument_list identifier expression_statement assignment identifier boolean_operator boolean_operator identifier call identifier argument_list keyword_argument identifier identifier none expression_statement assignment identifier call attribute call attribute identifier identifier argument_list identifier argument_list binary_operator binary_operator call attribute identifier identifier argument_list string string_start string_content string_end identifier keyword_argument identifier identifier return_statement call identifier argument_list identifier comparison_operator identifier string string_start string_content string_end | Retrieves an ApiConfig list from the given relative path. |
def _convert_value(value):
try:
return restore(ast.literal_eval(value))
except (ValueError, SyntaxError):
if SETTINGS.COMMAND_LINE.STRICT_PARSING:
raise
return value | module function_definition identifier parameters identifier block try_statement block return_statement call identifier argument_list call attribute identifier identifier argument_list identifier except_clause tuple identifier identifier block if_statement attribute attribute identifier identifier identifier block raise_statement return_statement identifier | Parse string as python literal if possible and fallback to string. |
def isRealmUser(self, realmname, username, environ):
try:
course = self.course_factory.get_course(realmname)
ok = self.user_manager.has_admin_rights_on_course(course, username=username)
return ok
except:
return False | module function_definition identifier parameters identifier identifier identifier identifier block try_statement block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list identifier expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list identifier keyword_argument identifier identifier return_statement identifier except_clause block return_statement false | Returns True if this username is valid for the realm, False otherwise. |
def gen_procfile(ctx, wsgi, dev):
if wsgi is None:
if os.path.exists("wsgi.py"):
wsgi = "wsgi.py"
elif os.path.exists("app.py"):
wsgi = "app.py"
else:
wsgi = "app.py"
ctx.invoke(gen_apppy)
def write_procfile(filename, server_process, debug):
processes = [server_process] + current_app.processes
procfile = []
for name, cmd in procfile_processes(processes, debug).iteritems():
procfile.append("%s: %s" % (name, cmd))
with open(filename, "w") as f:
f.write("\n".join(procfile))
write_procfile("Procfile", ("web", ["gunicorn", wsgi]), False)
if dev:
write_procfile("Procfile.dev", ("web", ["frasco", "serve"]), True) | module function_definition identifier parameters identifier identifier identifier block if_statement comparison_operator identifier none block if_statement call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end block expression_statement assignment identifier string string_start string_content string_end elif_clause call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end block expression_statement assignment identifier string string_start string_content string_end else_clause block expression_statement assignment identifier string string_start string_content string_end expression_statement call attribute identifier identifier argument_list identifier function_definition identifier parameters identifier identifier identifier block expression_statement assignment identifier binary_operator list identifier attribute identifier identifier expression_statement assignment identifier list for_statement pattern_list identifier identifier call attribute call identifier argument_list identifier identifier identifier argument_list block expression_statement call attribute identifier identifier argument_list binary_operator string string_start string_content string_end tuple identifier identifier 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 call attribute identifier identifier argument_list call attribute string string_start string_content escape_sequence string_end identifier argument_list identifier expression_statement call identifier argument_list string string_start string_content string_end tuple string string_start string_content string_end list string string_start string_content string_end identifier false if_statement identifier block expression_statement call identifier argument_list string string_start string_content string_end tuple string string_start string_content string_end list string string_start string_content string_end string string_start string_content string_end true | Generates Procfiles which can be used with honcho or foreman. |
def indexables(self):
if self._indexables is None:
d = self.description
self._indexables = [GenericIndexCol(name='index', axis=0)]
for i, n in enumerate(d._v_names):
dc = GenericDataIndexableCol(
name=n, pos=i, values=[n], version=self.version)
self._indexables.append(dc)
return self._indexables | module function_definition identifier parameters identifier block if_statement comparison_operator attribute identifier identifier none block expression_statement assignment identifier attribute identifier identifier expression_statement assignment attribute identifier identifier list call identifier argument_list keyword_argument identifier string string_start string_content string_end keyword_argument identifier integer for_statement pattern_list identifier identifier call identifier argument_list attribute identifier identifier block expression_statement assignment identifier call identifier argument_list keyword_argument identifier identifier keyword_argument identifier identifier keyword_argument identifier list identifier keyword_argument identifier attribute identifier identifier expression_statement call attribute attribute identifier identifier identifier argument_list identifier return_statement attribute identifier identifier | create the indexables from the table description |
def textbetween(variable,
firstnum=None,
secondnum=None,
locationoftext='regular'):
if locationoftext == 'regular':
return variable[firstnum:secondnum]
elif locationoftext == 'toend':
return variable[firstnum:]
elif locationoftext == 'tostart':
return variable[:secondnum] | module function_definition identifier parameters identifier default_parameter identifier none default_parameter identifier none default_parameter identifier string string_start string_content string_end block if_statement comparison_operator identifier string string_start string_content string_end block return_statement subscript identifier slice identifier identifier elif_clause comparison_operator identifier string string_start string_content string_end block return_statement subscript identifier slice identifier elif_clause comparison_operator identifier string string_start string_content string_end block return_statement subscript identifier slice identifier | Get The Text Between Two Parts |
def complex_out_dtype(self):
if self.__complex_out_dtype is None:
raise AttributeError(
'no complex variant of output dtype {} defined'
''.format(dtype_repr(self.scalar_out_dtype)))
else:
return self.__complex_out_dtype | module function_definition identifier parameters identifier block if_statement comparison_operator attribute identifier identifier none block raise_statement call identifier argument_list call attribute concatenated_string string string_start string_content string_end string string_start string_end identifier argument_list call identifier argument_list attribute identifier identifier else_clause block return_statement attribute identifier identifier | The complex dtype corresponding to this space's `out_dtype`. |
def date(ctx, year, month, day):
return _date(conversions.to_integer(year, ctx), conversions.to_integer(month, ctx), conversions.to_integer(day, ctx)) | module function_definition identifier parameters identifier identifier identifier identifier block return_statement call identifier argument_list call attribute identifier identifier argument_list identifier identifier call attribute identifier identifier argument_list identifier identifier call attribute identifier identifier argument_list identifier identifier | Defines a date value |
def npd_to_pmf(nodal_plane_dist, use_default=False):
if isinstance(nodal_plane_dist, PMF):
return nodal_plane_dist
else:
if use_default:
return PMF([(1.0, NodalPlane(0.0, 90.0, 0.0))])
else:
raise ValueError('Nodal Plane distribution not defined') | module function_definition identifier parameters identifier default_parameter identifier false block if_statement call identifier argument_list identifier identifier block return_statement identifier else_clause block if_statement identifier block return_statement call identifier argument_list list tuple float call identifier argument_list float float float else_clause block raise_statement call identifier argument_list string string_start string_content string_end | Returns the nodal plane distribution as an instance of the PMF class |
def _from_dict(cls, _dict):
args = {}
if 'grammars' in _dict:
args['grammars'] = [
Grammar._from_dict(x) for x in (_dict.get('grammars'))
]
else:
raise ValueError(
'Required property \'grammars\' not present in Grammars JSON')
return cls(**args) | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier dictionary if_statement comparison_operator string string_start string_content string_end identifier block expression_statement assignment subscript identifier string string_start string_content string_end list_comprehension call attribute identifier identifier argument_list identifier for_in_clause identifier parenthesized_expression call attribute identifier identifier argument_list string string_start string_content string_end else_clause block raise_statement call identifier argument_list string string_start string_content escape_sequence escape_sequence string_end return_statement call identifier argument_list dictionary_splat identifier | Initialize a Grammars object from a json dictionary. |
def run(self):
for msg in self.messages:
col = getattr(msg, 'col', 0)
yield msg.lineno, col, (msg.tpl % msg.message_args), msg.__class__ | module function_definition identifier parameters identifier block for_statement identifier attribute identifier identifier block expression_statement assignment identifier call identifier argument_list identifier string string_start string_content string_end integer expression_statement yield expression_list attribute identifier identifier identifier parenthesized_expression binary_operator attribute identifier identifier attribute identifier identifier attribute identifier identifier | Yield the error messages. |
def kdists(matrix, k=7, ix=None):
ix = ix or kindex(matrix, k)
return matrix[ix][np.newaxis].T | module function_definition identifier parameters identifier default_parameter identifier integer default_parameter identifier none block expression_statement assignment identifier boolean_operator identifier call identifier argument_list identifier identifier return_statement attribute subscript subscript identifier identifier attribute identifier identifier identifier | Returns the k-th nearest distances, row-wise, as a column vector |
def use_plenary_composition_view(self):
self._object_views['composition'] = PLENARY
for session in self._get_provider_sessions():
try:
session.use_plenary_composition_view()
except AttributeError:
pass | module function_definition identifier parameters identifier block expression_statement assignment subscript attribute identifier identifier string string_start string_content string_end identifier for_statement identifier call attribute identifier identifier argument_list block try_statement block expression_statement call attribute identifier identifier argument_list except_clause identifier block pass_statement | Pass through to provider CompositionLookupSession.use_plenary_composition_view |
def _get_opts_seaborn(self, opts, style):
if opts is None:
if self.chart_opts is None:
opts = {}
else:
opts = self.chart_opts
if style is None:
if self.chart_style is None:
style = self.chart_style
else:
style = {}
return opts, style | module function_definition identifier parameters identifier identifier identifier block if_statement comparison_operator identifier none block if_statement comparison_operator attribute identifier identifier none block expression_statement assignment identifier dictionary else_clause block expression_statement assignment identifier attribute identifier identifier if_statement comparison_operator identifier none block if_statement comparison_operator attribute identifier identifier none block expression_statement assignment identifier attribute identifier identifier else_clause block expression_statement assignment identifier dictionary return_statement expression_list identifier identifier | Initialialize for chart rendering |
def main():
actions = []
try:
options, arguments = getopt.getopt(sys.argv[1:], 'cdh', [
'convert', 'to-html', 'demo', 'help',
])
for option, value in options:
if option in ('-c', '--convert', '--to-html'):
actions.append(functools.partial(convert_command_output, *arguments))
arguments = []
elif option in ('-d', '--demo'):
actions.append(demonstrate_colored_logging)
elif option in ('-h', '--help'):
usage(__doc__)
return
else:
assert False, "Programming error: Unhandled option!"
if not actions:
usage(__doc__)
return
except Exception as e:
warning("Error: %s", e)
sys.exit(1)
for function in actions:
function() | module function_definition identifier parameters block expression_statement assignment identifier list try_statement block expression_statement assignment pattern_list identifier identifier call attribute identifier identifier argument_list subscript attribute identifier identifier slice integer string string_start string_content string_end 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 for_statement pattern_list identifier identifier identifier block if_statement comparison_operator identifier tuple string string_start string_content string_end string string_start string_content string_end string string_start string_content string_end block expression_statement call attribute identifier identifier argument_list call attribute identifier identifier argument_list identifier list_splat identifier expression_statement assignment identifier list elif_clause comparison_operator identifier tuple string string_start string_content string_end string string_start string_content string_end block expression_statement call attribute identifier identifier argument_list identifier elif_clause comparison_operator identifier tuple string string_start string_content string_end string string_start string_content string_end block expression_statement call identifier argument_list identifier return_statement else_clause block assert_statement false string string_start string_content string_end if_statement not_operator identifier block expression_statement call identifier argument_list identifier return_statement except_clause as_pattern identifier as_pattern_target identifier block expression_statement call identifier argument_list string string_start string_content string_end identifier expression_statement call attribute identifier identifier argument_list integer for_statement identifier identifier block expression_statement call identifier argument_list | Command line interface for the ``coloredlogs`` program. |
def page_prev(self):
window_start = (self.parent.value('window_start') -
self.parent.value('window_length'))
if window_start < 0:
return
self.parent.overview.update_position(window_start) | module function_definition identifier parameters identifier block expression_statement assignment identifier parenthesized_expression binary_operator call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end if_statement comparison_operator identifier integer block return_statement expression_statement call attribute attribute attribute identifier identifier identifier identifier argument_list identifier | Go to the previous page. |
def close(self):
for channel in self._listening_to:
self.toredis.unsubscribe(channel)
self.toredis.unsubscribe(self.group_pubsub) | module function_definition identifier parameters identifier block for_statement identifier attribute identifier identifier block expression_statement call attribute attribute identifier identifier identifier argument_list identifier expression_statement call attribute attribute identifier identifier identifier argument_list attribute identifier identifier | Unsubscribe the group and all jobs being listened too |
def stop(self):
if self._thread is not None and self._thread.isAlive():
self._done.set() | module function_definition identifier parameters identifier block if_statement boolean_operator comparison_operator attribute identifier identifier none call attribute attribute identifier identifier identifier argument_list block expression_statement call attribute attribute identifier identifier identifier argument_list | Stop the running task |
def _setup_http_session(self):
headers = {"Content-type": "application/json"}
if (self._id_token):
headers.update({"authorization": "Bearer {}".format(
self._id_token)})
self._session.headers.update(headers)
self._session.verify = False | module function_definition identifier parameters identifier block expression_statement assignment identifier dictionary pair string string_start string_content string_end string string_start string_content string_end if_statement parenthesized_expression attribute identifier identifier block expression_statement call attribute identifier identifier argument_list dictionary pair string string_start string_content string_end call attribute string string_start string_content string_end identifier argument_list attribute identifier identifier expression_statement call attribute attribute attribute identifier identifier identifier identifier argument_list identifier expression_statement assignment attribute attribute identifier identifier identifier false | Sets up the common HTTP session parameters used by requests. |
def field_from_json(self, key_and_type, json_value):
assert ':' in key_and_type
key, type_code = key_and_type.split(':', 1)
from_json = self.field_function(type_code, 'from_json')
value = from_json(json_value)
return key, value | module function_definition identifier parameters identifier identifier identifier block assert_statement comparison_operator string string_start string_content string_end identifier expression_statement assignment pattern_list identifier identifier call attribute identifier identifier argument_list string string_start string_content string_end integer expression_statement assignment identifier call attribute identifier identifier argument_list identifier string string_start string_content string_end expression_statement assignment identifier call identifier argument_list identifier return_statement expression_list identifier identifier | Convert a JSON-serializable representation back to a field. |
def convert_table(app, docname, source):
num_tables = 0
for i,j in enumerate(source):
table = []
output = ''
in_table = False
for l in j.split('\n'):
r = l.strip()
if r.startswith('|'):
table.append(r)
in_table = True
else:
if in_table is True:
converted = _convert_md_table_to_rst(table)
if converted is '':
print("Failed to convert the markdown table")
print(table)
else:
num_tables += 1
output += converted
in_table = False
table = []
output += l + '\n'
source[i] = output
if num_tables > 0:
print('Converted %d tables in %s' % (num_tables, docname)) | module function_definition identifier parameters identifier identifier identifier block expression_statement assignment identifier integer for_statement pattern_list identifier identifier call identifier argument_list identifier block expression_statement assignment identifier list expression_statement assignment identifier string string_start string_end expression_statement assignment identifier false for_statement identifier call attribute identifier identifier argument_list string string_start string_content escape_sequence string_end block expression_statement assignment identifier call attribute identifier identifier argument_list if_statement call attribute identifier identifier argument_list string string_start string_content string_end block expression_statement call attribute identifier identifier argument_list identifier expression_statement assignment identifier true else_clause block if_statement comparison_operator identifier true block expression_statement assignment identifier call identifier argument_list identifier if_statement comparison_operator identifier string string_start string_end block expression_statement call identifier argument_list string string_start string_content string_end expression_statement call identifier argument_list identifier else_clause block expression_statement augmented_assignment identifier integer expression_statement augmented_assignment identifier identifier expression_statement assignment identifier false expression_statement assignment identifier list expression_statement augmented_assignment identifier binary_operator identifier string string_start string_content escape_sequence string_end expression_statement assignment subscript identifier identifier identifier if_statement comparison_operator identifier integer block expression_statement call identifier argument_list binary_operator string string_start string_content string_end tuple identifier identifier | Find tables in a markdown and then convert them into the rst format |
def distance(a, b):
R = 3963
lat1, lon1 = math.radians(a[0]), math.radians(a[1])
lat2, lon2 = math.radians(b[0]), math.radians(b[1])
return math.acos(math.sin(lat1) * math.sin(lat2) +
math.cos(lat1) * math.cos(lat2) * math.cos(lon1 - lon2)) * R | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier integer expression_statement assignment pattern_list identifier identifier expression_list call attribute identifier identifier argument_list subscript identifier integer call attribute identifier identifier argument_list subscript identifier integer expression_statement assignment pattern_list identifier identifier expression_list call attribute identifier identifier argument_list subscript identifier integer call attribute identifier identifier argument_list subscript identifier integer return_statement binary_operator call attribute identifier identifier argument_list binary_operator binary_operator call attribute identifier identifier argument_list identifier call attribute identifier identifier argument_list identifier binary_operator binary_operator call attribute identifier identifier argument_list identifier call attribute identifier identifier argument_list identifier call attribute identifier identifier argument_list binary_operator identifier identifier identifier | Calculates distance between two latitude-longitude coordinates. |
def create_cookie(name, value, domain, httponly=None, **kwargs):
if domain == 'localhost':
domain = ''
config = dict(
name=name,
value=value,
version=0,
port=None,
domain=domain,
path='/',
secure=False,
expires=None,
discard=True,
comment=None,
comment_url=None,
rfc2109=False,
rest={'HttpOnly': httponly},
)
for key in kwargs:
if key not in config:
raise GrabMisuseError('Function `create_cookie` does not accept '
'`%s` argument' % key)
config.update(**kwargs)
config['rest']['HttpOnly'] = httponly
config['port_specified'] = bool(config['port'])
config['domain_specified'] = bool(config['domain'])
config['domain_initial_dot'] = (config['domain'] or '').startswith('.')
config['path_specified'] = bool(config['path'])
return Cookie(**config) | module function_definition identifier parameters identifier identifier identifier default_parameter identifier none dictionary_splat_pattern identifier block if_statement comparison_operator identifier string string_start string_content string_end block expression_statement assignment identifier string string_start string_end expression_statement assignment identifier call identifier argument_list keyword_argument identifier identifier keyword_argument identifier identifier keyword_argument identifier integer keyword_argument identifier none keyword_argument identifier identifier keyword_argument identifier string string_start string_content string_end keyword_argument identifier false keyword_argument identifier none keyword_argument identifier true keyword_argument identifier none keyword_argument identifier none keyword_argument identifier false keyword_argument identifier dictionary pair string string_start string_content string_end identifier for_statement identifier identifier block if_statement comparison_operator identifier identifier block raise_statement call identifier argument_list binary_operator concatenated_string string string_start string_content string_end string string_start string_content string_end identifier expression_statement call attribute identifier identifier argument_list dictionary_splat 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 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 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 call attribute parenthesized_expression boolean_operator subscript identifier string string_start string_content string_end string string_start string_end identifier argument_list string string_start string_content string_end expression_statement assignment subscript identifier string string_start string_content string_end call identifier argument_list subscript identifier string string_start string_content string_end return_statement call identifier argument_list dictionary_splat identifier | Creates `cookielib.Cookie` instance |
def must_contain(self, value, q, strict=False):
if value is not None:
if value.find(q) != -1:
return
self.shout('Value %r does not contain %r', strict, value, q) | module function_definition identifier parameters identifier identifier identifier default_parameter identifier false block if_statement comparison_operator identifier none block if_statement comparison_operator call attribute identifier identifier argument_list identifier unary_operator integer block return_statement expression_statement call attribute identifier identifier argument_list string string_start string_content string_end identifier identifier identifier | if value must contain q |
def _raise_on_error(data: Union[str, dict]) -> None:
if isinstance(data, str):
raise_error(data)
elif 'status' in data and data['status'] != 'success':
raise_error(data['data']['message']) | module function_definition identifier parameters typed_parameter identifier type generic_type identifier type_parameter type identifier type identifier type none block if_statement call identifier argument_list identifier identifier block expression_statement call identifier argument_list identifier elif_clause boolean_operator comparison_operator string string_start string_content string_end identifier comparison_operator subscript identifier string string_start string_content string_end string string_start string_content string_end block expression_statement call identifier argument_list subscript subscript identifier string string_start string_content string_end string string_start string_content string_end | Raise the appropriate exception on error. |
def d(msg, *args, **kwargs):
return logging.log(DEBUG, msg, *args, **kwargs) | module function_definition identifier parameters identifier list_splat_pattern identifier dictionary_splat_pattern identifier block return_statement call attribute identifier identifier argument_list identifier identifier list_splat identifier dictionary_splat identifier | log a message at debug level; |
def _serialize(self, include_run_logs=False, strict_json=False):
result = {'command': self.command,
'name': self.name,
'started_at': self.started_at,
'completed_at': self.completed_at,
'success': self.successful,
'soft_timeout': self.soft_timeout,
'hard_timeout': self.hard_timeout,
'hostname': self.hostname}
if include_run_logs:
last_run = self.backend.get_latest_run_log(self.parent_job.job_id,
self.name)
if last_run:
run_log = last_run.get('tasks', {}).get(self.name, {})
if run_log:
result['run_log'] = run_log
if strict_json:
result = json.loads(json.dumps(result, cls=StrictJSONEncoder))
return result | module function_definition identifier parameters identifier default_parameter identifier false default_parameter identifier false block expression_statement assignment identifier dictionary pair string string_start string_content string_end attribute identifier identifier pair string string_start string_content string_end attribute identifier identifier pair string string_start string_content string_end attribute identifier identifier pair string string_start string_content string_end attribute identifier identifier pair string string_start string_content string_end attribute identifier identifier pair string string_start string_content string_end attribute identifier identifier pair string string_start string_content string_end attribute identifier identifier pair string string_start string_content string_end attribute identifier identifier if_statement identifier block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list attribute attribute identifier identifier identifier attribute identifier identifier if_statement identifier block expression_statement assignment identifier call attribute call attribute identifier identifier argument_list string string_start string_content string_end dictionary identifier argument_list attribute identifier identifier dictionary if_statement identifier block expression_statement assignment subscript identifier string string_start string_content string_end identifier if_statement identifier block expression_statement assignment identifier call attribute identifier identifier argument_list call attribute identifier identifier argument_list identifier keyword_argument identifier identifier return_statement identifier | Serialize a representation of this Task to a Python dict. |
def _build_graph(self):
if not self.colors:
self.palette = self.env.get_template('palette.js')
self.template_vars.update({'palette': self.palette.render()})
self.colors = {x['name']: 'palette.color()' for x in self.json_data}
template_vars = []
for index, dataset in enumerate(self.json_data):
group = 'datagroup' + str(index)
template_vars.append({'name': str(dataset['name']),
'color': self.colors[dataset['name']],
'data': 'json[{0}].data'.format(index)})
variables = {'dataset': template_vars, 'width': self.width,
'height': self.height, 'render': self.renderer,
'chart_id': self.chart_id}
if not self.y_zero:
variables.update({'min': "min: 'auto',"})
graph = self.env.get_template('graph.js')
self.template_vars.update({'graph': graph.render(variables)}) | module function_definition identifier parameters identifier block if_statement not_operator attribute identifier identifier block expression_statement assignment attribute identifier identifier call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end expression_statement call attribute attribute identifier identifier identifier argument_list dictionary pair string string_start string_content string_end call attribute attribute identifier identifier identifier argument_list expression_statement assignment attribute identifier identifier dictionary_comprehension pair subscript identifier string string_start string_content string_end string string_start string_content string_end for_in_clause identifier attribute identifier identifier expression_statement assignment identifier list for_statement pattern_list identifier identifier call identifier argument_list attribute identifier identifier block expression_statement assignment identifier binary_operator string string_start string_content string_end call identifier argument_list identifier expression_statement call attribute identifier identifier argument_list dictionary pair string string_start string_content string_end call identifier argument_list subscript identifier string string_start string_content string_end pair string string_start string_content string_end subscript attribute identifier identifier subscript identifier string string_start string_content string_end pair string string_start string_content string_end call attribute string string_start string_content string_end identifier argument_list identifier expression_statement assignment identifier dictionary pair string string_start string_content string_end identifier pair string string_start string_content string_end attribute identifier identifier pair string string_start string_content string_end attribute identifier identifier pair string string_start string_content string_end attribute identifier identifier pair string string_start string_content string_end attribute identifier identifier if_statement not_operator attribute identifier identifier block expression_statement call attribute identifier identifier argument_list dictionary pair string string_start string_content string_end string string_start string_content string_end expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end expression_statement call attribute attribute identifier identifier identifier argument_list dictionary pair string string_start string_content string_end call attribute identifier identifier argument_list identifier | Build Rickshaw graph syntax with all data |
def exclude(self, d, item):
try:
md = d.__metadata__
pmd = getattr(md, '__print__', None)
if pmd is None:
return False
excludes = getattr(pmd, 'excludes', [])
return ( item[0] in excludes )
except:
pass
return False | module function_definition identifier parameters identifier identifier identifier block try_statement block expression_statement assignment identifier attribute identifier identifier expression_statement assignment identifier call identifier argument_list identifier string string_start string_content string_end none if_statement comparison_operator identifier none block return_statement false expression_statement assignment identifier call identifier argument_list identifier string string_start string_content string_end list return_statement parenthesized_expression comparison_operator subscript identifier integer identifier except_clause block pass_statement return_statement false | check metadata for excluded items |
def munge_source(v):
lines = v.split('\n')
if not lines:
return tuple(), ''
firstline = lines[0].lstrip()
while firstline == '' or firstline[0] == '@':
del lines[0]
firstline = lines[0].lstrip()
if not lines:
return tuple(), ''
params = tuple(
parm.strip() for parm in
sig_ex.match(lines[0]).group(1).split(',')
)
del lines[0]
if not lines:
return params, ''
if lines and lines[-1].strip() == 'pass':
del lines[-1]
return params, dedent('\n'.join(lines)) | module function_definition identifier parameters identifier block expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content escape_sequence string_end if_statement not_operator identifier block return_statement expression_list call identifier argument_list string string_start string_end expression_statement assignment identifier call attribute subscript identifier integer identifier argument_list while_statement boolean_operator comparison_operator identifier string string_start string_end comparison_operator subscript identifier integer string string_start string_content string_end block delete_statement subscript identifier integer expression_statement assignment identifier call attribute subscript identifier integer identifier argument_list if_statement not_operator identifier block return_statement expression_list call identifier argument_list string string_start string_end expression_statement assignment identifier call identifier generator_expression call attribute identifier identifier argument_list for_in_clause identifier call attribute call attribute call attribute identifier identifier argument_list subscript identifier integer identifier argument_list integer identifier argument_list string string_start string_content string_end delete_statement subscript identifier integer if_statement not_operator identifier block return_statement expression_list identifier string string_start string_end if_statement boolean_operator identifier comparison_operator call attribute subscript identifier unary_operator integer identifier argument_list string string_start string_content string_end block delete_statement subscript identifier unary_operator integer return_statement expression_list identifier call identifier argument_list call attribute string string_start string_content escape_sequence string_end identifier argument_list identifier | Take Python source code, return a pair of its parameters and the rest of it dedented |
def rm(venv_name):
inenv = InenvManager()
venv = inenv.get_venv(venv_name)
click.confirm("Delete dir {}".format(venv.path))
shutil.rmtree(venv.path) | module function_definition identifier parameters identifier block expression_statement assignment identifier call identifier argument_list expression_statement assignment identifier call attribute identifier identifier argument_list identifier expression_statement call attribute identifier identifier argument_list call attribute string string_start string_content string_end identifier argument_list attribute identifier identifier expression_statement call attribute identifier identifier argument_list attribute identifier identifier | Removes the venv by name |
def bool_str(string):
if string not in BOOL_STRS:
raise ValueError('Invalid boolean string: "{}"'.format(string))
return True if string == 'true' else False | module function_definition identifier parameters identifier block if_statement comparison_operator identifier identifier block raise_statement call identifier argument_list call attribute string string_start string_content string_end identifier argument_list identifier return_statement conditional_expression true comparison_operator identifier string string_start string_content string_end false | Returns a boolean from a string imput of 'true' or 'false |
def describe(self):
description = {
'description': self._description,
'type': self.name,
}
description.update(self.extra_params)
return description | module function_definition identifier parameters identifier block expression_statement assignment identifier dictionary pair string string_start string_content string_end attribute identifier identifier pair string string_start string_content string_end attribute identifier identifier expression_statement call attribute identifier identifier argument_list attribute identifier identifier return_statement identifier | Provide a dictionary with information describing itself. |
def initialize(self):
if self._pooler is None:
params = {
"inputWidth": self.inputWidth,
"lateralInputWidths": [self.cellCount] * self.numOtherCorticalColumns,
"cellCount": self.cellCount,
"sdrSize": self.sdrSize,
"onlineLearning": self.onlineLearning,
"maxSdrSize": self.maxSdrSize,
"minSdrSize": self.minSdrSize,
"synPermProximalInc": self.synPermProximalInc,
"synPermProximalDec": self.synPermProximalDec,
"initialProximalPermanence": self.initialProximalPermanence,
"minThresholdProximal": self.minThresholdProximal,
"sampleSizeProximal": self.sampleSizeProximal,
"connectedPermanenceProximal": self.connectedPermanenceProximal,
"predictedInhibitionThreshold": self.predictedInhibitionThreshold,
"synPermDistalInc": self.synPermDistalInc,
"synPermDistalDec": self.synPermDistalDec,
"initialDistalPermanence": self.initialDistalPermanence,
"activationThresholdDistal": self.activationThresholdDistal,
"sampleSizeDistal": self.sampleSizeDistal,
"connectedPermanenceDistal": self.connectedPermanenceDistal,
"inertiaFactor": self.inertiaFactor,
"seed": self.seed,
}
self._pooler = ColumnPooler(**params) | module function_definition identifier parameters identifier block if_statement comparison_operator attribute identifier identifier none block expression_statement assignment identifier dictionary pair string string_start string_content string_end attribute identifier identifier pair string string_start string_content string_end binary_operator list attribute identifier identifier attribute identifier identifier pair string string_start string_content string_end attribute identifier identifier pair string string_start string_content string_end attribute identifier identifier pair string string_start string_content string_end attribute identifier identifier pair string string_start string_content string_end attribute identifier identifier pair string string_start string_content string_end attribute identifier identifier pair string string_start string_content string_end attribute identifier identifier pair string string_start string_content string_end attribute identifier identifier pair string string_start string_content string_end attribute identifier identifier pair string string_start string_content string_end attribute identifier identifier pair string string_start string_content string_end attribute identifier identifier pair string string_start string_content string_end attribute identifier identifier pair string string_start string_content string_end attribute identifier identifier pair string string_start string_content string_end attribute identifier identifier pair string string_start string_content string_end attribute identifier identifier pair string string_start string_content string_end attribute identifier identifier pair string string_start string_content string_end attribute identifier identifier pair string string_start string_content string_end attribute identifier identifier pair string string_start string_content string_end attribute identifier identifier pair string string_start string_content string_end attribute identifier identifier pair string string_start string_content string_end attribute identifier identifier expression_statement assignment attribute identifier identifier call identifier argument_list dictionary_splat identifier | Initialize the internal objects. |
def read_ncstream_err(fobj):
err = read_proto_object(fobj, stream.Error)
raise RuntimeError(err.message) | module function_definition identifier parameters identifier block expression_statement assignment identifier call identifier argument_list identifier attribute identifier identifier raise_statement call identifier argument_list attribute identifier identifier | Handle reading an NcStream error from a file-like object and raise as error. |
def makeref2namesdct(name2refdct):
ref2namesdct = {}
for key, values in name2refdct.items():
for value in values:
ref2namesdct.setdefault(value, set()).add(key)
return ref2namesdct | module function_definition identifier parameters identifier block expression_statement assignment identifier dictionary for_statement pattern_list identifier identifier call attribute identifier identifier argument_list block for_statement identifier identifier block expression_statement call attribute call attribute identifier identifier argument_list identifier call identifier argument_list identifier argument_list identifier return_statement identifier | make the ref2namesdct in the idd_index |
def _rank_qr(self, choices):
from bernard.platforms.facebook import layers as fbl
try:
qr = self.request.get_layer(fbl.QuickReply)
self.chosen = choices[qr.slug]
self.slug = qr.slug
if self.when is None or self.when == qr.slug:
return 1.0
except KeyError:
pass | module function_definition identifier parameters identifier identifier block import_from_statement dotted_name identifier identifier identifier aliased_import dotted_name identifier identifier try_statement block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list attribute identifier identifier expression_statement assignment attribute identifier identifier subscript identifier attribute identifier identifier expression_statement assignment attribute identifier identifier attribute identifier identifier if_statement boolean_operator comparison_operator attribute identifier identifier none comparison_operator attribute identifier identifier attribute identifier identifier block return_statement float except_clause identifier block pass_statement | Look for the QuickReply layer's slug into available choices. |
def sortable_title(instance):
title = plone_sortable_title(instance)
if safe_callable(title):
title = title()
return title.lower() | module function_definition identifier parameters identifier block expression_statement assignment identifier call identifier argument_list identifier if_statement call identifier argument_list identifier block expression_statement assignment identifier call identifier argument_list return_statement call attribute identifier identifier argument_list | Uses the default Plone sortable_text index lower-case |
def dnd_endSnooze(self, **kwargs) -> SlackResponse:
self._validate_xoxp_token()
return self.api_call("dnd.endSnooze", json=kwargs) | module function_definition identifier parameters identifier dictionary_splat_pattern identifier type identifier block expression_statement call attribute identifier identifier argument_list return_statement call attribute identifier identifier argument_list string string_start string_content string_end keyword_argument identifier identifier | Ends the current user's snooze mode immediately. |
def data_filler_customer(self, number_of_rows, pipe):
try:
for i in range(number_of_rows):
pipe.hmset('customer:%s' % i, {
'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()
})
pipe.execute()
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 for_statement identifier call identifier argument_list identifier block expression_statement call attribute identifier identifier argument_list binary_operator string string_start string_content string_end 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 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 keys with customer data |
def _split_str(s, n):
length = len(s)
return [s[i:i + n] for i in range(0, length, n)] | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call identifier argument_list identifier return_statement list_comprehension subscript identifier slice identifier binary_operator identifier identifier for_in_clause identifier call identifier argument_list integer identifier identifier | split string into list of strings by specified number. |
def refresh_all_state_machines(self):
self.refresh_state_machines(list(self.model.state_machine_manager.state_machines.keys())) | module function_definition identifier parameters identifier block expression_statement call attribute identifier identifier argument_list call identifier argument_list call attribute attribute attribute attribute identifier identifier identifier identifier identifier argument_list | Refreshes all state machine tabs |
def _update_staticmethod(self, oldsm, newsm):
self._update(None, None, oldsm.__get__(0), newsm.__get__(0)) | module function_definition identifier parameters identifier identifier identifier block expression_statement call attribute identifier identifier argument_list none none call attribute identifier identifier argument_list integer call attribute identifier identifier argument_list integer | Update a staticmethod update. |
def remove(self):
self._multivol.deallocate(self.id)
ARRAY_CACHE.pop(self.id, None)
PIXEL_CACHE.pop(self.id, None) | module function_definition identifier parameters identifier block expression_statement call attribute attribute identifier identifier identifier argument_list attribute identifier identifier expression_statement call attribute identifier identifier argument_list attribute identifier identifier none expression_statement call attribute identifier identifier argument_list attribute identifier identifier none | Remove the layer artist for good |
def pick_summary_data(key, summary_df, selected_summaries):
selected_summaries_dict = create_selected_summaries_dict(selected_summaries)
value = selected_summaries_dict[key]
return summary_df.iloc[:, summary_df.columns.get_level_values(1) == value] | module function_definition identifier parameters identifier identifier identifier block expression_statement assignment identifier call identifier argument_list identifier expression_statement assignment identifier subscript identifier identifier return_statement subscript attribute identifier identifier slice comparison_operator call attribute attribute identifier identifier identifier argument_list integer identifier | picks the selected pandas.DataFrame |
def wandb_pty(resize=True):
master_fd, slave_fd = pty.openpty()
try:
tty.setraw(master_fd)
except termios.error:
pass
if resize:
if SIGWINCH_HANDLER is not None:
SIGWINCH_HANDLER.add_fd(master_fd)
return master_fd, slave_fd | module function_definition identifier parameters default_parameter identifier true block expression_statement assignment pattern_list identifier identifier call attribute identifier identifier argument_list try_statement block expression_statement call attribute identifier identifier argument_list identifier except_clause attribute identifier identifier block pass_statement if_statement identifier block if_statement comparison_operator identifier none block expression_statement call attribute identifier identifier argument_list identifier return_statement expression_list identifier identifier | Get a PTY set to raw mode and registered to hear about window size changes. |
def _sign(self,params):
for k, v in params.iteritems():
if type(v) == int: v = str(v)
elif type(v) == float: v = '%.2f'%v
elif type(v) in (list, set):
v = ','.join([str(i) for i in v])
elif type(v) == bool: v = 'true' if v else 'false'
elif type(v) == datetime.datetime: v = v.strftime('%Y-%m-%d %X')
if type(v) == unicode:
params[k] = v.encode('utf-8')
else:
params[k] = v
src = self.APP_SECRET + ''.join(["%s%s" % (k, v) for k, v in sorted(params.iteritems())])
return md5(src).hexdigest().upper() | module function_definition identifier parameters identifier identifier block for_statement pattern_list identifier identifier call attribute identifier identifier argument_list block if_statement comparison_operator call identifier argument_list identifier identifier block expression_statement assignment identifier call identifier argument_list identifier elif_clause comparison_operator call identifier argument_list identifier identifier block expression_statement assignment identifier binary_operator string string_start string_content string_end identifier elif_clause comparison_operator call identifier argument_list identifier tuple identifier identifier block 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 elif_clause comparison_operator call identifier argument_list identifier identifier block expression_statement assignment identifier conditional_expression string string_start string_content string_end identifier string string_start string_content string_end elif_clause comparison_operator call identifier argument_list identifier attribute identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end if_statement comparison_operator call identifier argument_list identifier identifier block expression_statement assignment subscript identifier identifier call attribute identifier identifier argument_list string string_start string_content string_end else_clause block expression_statement assignment subscript identifier identifier identifier expression_statement assignment identifier binary_operator attribute identifier identifier call attribute string string_start string_end identifier argument_list list_comprehension binary_operator string string_start string_content string_end tuple identifier identifier for_in_clause pattern_list identifier identifier call identifier argument_list call attribute identifier identifier argument_list return_statement call attribute call attribute call identifier argument_list identifier identifier argument_list identifier argument_list | Generate API sign code |
def _save_to(self, im, path, format=None):
format = format or im.format
if not format:
_, format = splitext(path)
format = format[1:]
im.format = format.lower()
im.save(filename=path) | module function_definition identifier parameters identifier identifier identifier default_parameter identifier none block expression_statement assignment identifier boolean_operator identifier attribute identifier identifier if_statement not_operator identifier block expression_statement assignment pattern_list identifier identifier call identifier argument_list identifier expression_statement assignment identifier subscript identifier slice integer expression_statement assignment attribute identifier identifier call attribute identifier identifier argument_list expression_statement call attribute identifier identifier argument_list keyword_argument identifier identifier | Save the image for testing. |
def _wf_to_dict(wf):
inputs, outputs = _get_wf_inout(wf)
out = {"name": _id_to_name(wf.tool["id"]).replace("-", "_"), "inputs": inputs,
"outputs": outputs, "steps": [], "subworkflows": [],
"requirements": []}
for step in wf.steps:
inputs, outputs = _get_step_inout(step)
inputs, scatter = _organize_step_scatter(step, inputs)
if isinstance(step.embedded_tool, cwltool.workflow.Workflow):
wf_def = _wf_to_dict(step.embedded_tool)
out["subworkflows"].append({"id": wf_def["name"], "definition": wf_def,
"inputs": inputs, "outputs": outputs, "scatter": scatter})
else:
task_def = _tool_to_dict(step.embedded_tool)
out["steps"].append({"task_id": task_def["name"], "task_definition": task_def,
"inputs": inputs, "outputs": outputs, "scatter": scatter})
return out | module function_definition identifier parameters identifier block expression_statement assignment pattern_list identifier identifier call identifier argument_list identifier expression_statement assignment identifier dictionary pair string string_start string_content string_end call attribute call identifier argument_list subscript attribute identifier identifier string string_start string_content string_end identifier argument_list string string_start string_content string_end string string_start string_content string_end 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 list pair string string_start string_content string_end list pair string string_start string_content string_end list for_statement identifier attribute identifier identifier block expression_statement assignment pattern_list identifier identifier call identifier argument_list identifier expression_statement assignment pattern_list identifier identifier call identifier argument_list identifier identifier if_statement call identifier argument_list attribute identifier identifier attribute attribute identifier identifier identifier block expression_statement assignment identifier call identifier argument_list attribute identifier identifier expression_statement call attribute subscript identifier string string_start string_content string_end identifier argument_list dictionary pair string string_start string_content string_end subscript identifier string string_start string_content string_end 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 identifier pair string string_start string_content string_end identifier else_clause block expression_statement assignment identifier call identifier argument_list attribute identifier identifier expression_statement call attribute subscript identifier string string_start string_content string_end identifier argument_list dictionary pair string string_start string_content string_end subscript identifier string string_start string_content string_end 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 identifier pair string string_start string_content string_end identifier return_statement identifier | Parse a workflow into cwl2wdl style dictionary. |
def send_root_file(self, filename):
cache_timeout = self.get_send_file_max_age(filename)
return send_from_directory(self.config['ROOT_FOLDER'], filename,
cache_timeout=cache_timeout) | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list identifier return_statement call identifier argument_list subscript attribute identifier identifier string string_start string_content string_end identifier keyword_argument identifier identifier | Function used to send static files from the root of the domain. |
def quantile(image, q, nonzero=True):
img_arr = image.numpy()
if isinstance(q, (list,tuple)):
q = [qq*100. if qq <= 1. else qq for qq in q]
if nonzero:
img_arr = img_arr[img_arr>0]
vals = [np.percentile(img_arr, qq) for qq in q]
return tuple(vals)
elif isinstance(q, (float,int)):
if q <= 1.:
q = q*100.
if nonzero:
img_arr = img_arr[img_arr>0]
return np.percentile(img_arr[img_arr>0], q)
else:
raise ValueError('q argument must be list/tuple or float/int') | module function_definition identifier parameters identifier identifier default_parameter identifier true block expression_statement assignment identifier call attribute identifier identifier argument_list if_statement call identifier argument_list identifier tuple identifier identifier block expression_statement assignment identifier list_comprehension conditional_expression binary_operator identifier float comparison_operator identifier float identifier for_in_clause identifier identifier if_statement identifier block expression_statement assignment identifier subscript identifier comparison_operator identifier integer expression_statement assignment identifier list_comprehension call attribute identifier identifier argument_list identifier identifier for_in_clause identifier identifier return_statement call identifier argument_list identifier elif_clause call identifier argument_list identifier tuple identifier identifier block if_statement comparison_operator identifier float block expression_statement assignment identifier binary_operator identifier float if_statement identifier block expression_statement assignment identifier subscript identifier comparison_operator identifier integer return_statement call attribute identifier identifier argument_list subscript identifier comparison_operator identifier integer identifier else_clause block raise_statement call identifier argument_list string string_start string_content string_end | Get the quantile values from an ANTsImage |
def _affine_inv_mult(c, m):
"Applies the inverse affine transform described in `m` to `c`."
size = c.flow.size()
h,w = c.size
m[0,1] *= h/w
m[1,0] *= w/h
c.flow = c.flow.view(-1,2)
a = torch.inverse(m[:2,:2].t())
c.flow = torch.mm(c.flow - m[:2,2], a).view(size)
return c | module function_definition identifier parameters identifier identifier block expression_statement string string_start string_content string_end expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list expression_statement assignment pattern_list identifier identifier attribute identifier identifier expression_statement augmented_assignment subscript identifier integer integer binary_operator identifier identifier expression_statement augmented_assignment subscript identifier integer integer binary_operator identifier identifier expression_statement assignment attribute identifier identifier call attribute attribute identifier identifier identifier argument_list unary_operator integer integer expression_statement assignment identifier call attribute identifier identifier argument_list call attribute subscript identifier slice integer slice integer identifier argument_list expression_statement assignment attribute identifier identifier call attribute call attribute identifier identifier argument_list binary_operator attribute identifier identifier subscript identifier slice integer integer identifier identifier argument_list identifier return_statement identifier | Applies the inverse affine transform described in `m` to `c`. |
def extern_store_f64(self, context_handle, f64):
c = self._ffi.from_handle(context_handle)
return c.to_value(f64) | module function_definition identifier parameters identifier identifier identifier block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list identifier return_statement call attribute identifier identifier argument_list identifier | Given a context and double, return a new Handle to represent the double. |
def lastChild(self):
ret = libxml2mod.xmlGetLastChild(self._o)
if ret is None:raise treeError('xmlGetLastChild() failed')
__tmp = xmlNode(_obj=ret)
return __tmp | module function_definition identifier parameters identifier block expression_statement assignment identifier call attribute identifier identifier argument_list attribute identifier 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 call identifier argument_list keyword_argument identifier identifier return_statement identifier | Search the last child of a node. |
def duration(self):
self._duration = self.lib.iperf_get_test_duration(self._test)
return self._duration | module function_definition identifier parameters identifier block expression_statement assignment attribute identifier identifier call attribute attribute identifier identifier identifier argument_list attribute identifier identifier return_statement attribute identifier identifier | The test duration in seconds. |
def generate_url(self, suffix):
url_base_path = os.path.dirname(self.path)
netloc = "{}:{}".format(*self.server.server_address)
return urlunparse((
"http",
netloc,
url_base_path + "/" + suffix,
"", "", "")) | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list attribute identifier identifier expression_statement assignment identifier call attribute string string_start string_content string_end identifier argument_list list_splat attribute attribute identifier identifier identifier return_statement call identifier argument_list tuple string string_start string_content string_end identifier binary_operator binary_operator identifier string string_start string_content string_end identifier string string_start string_end string string_start string_end string string_start string_end | Return URL by combining server details with a path suffix. |
def _solve(self):
while len(self._remove_constr) > 0:
self._remove_constr.pop().delete()
try:
self._prob.solve(lp.ObjectiveSense.Maximize)
except lp.SolverError as e:
raise_from(FluxBalanceError('Failed to solve: {}'.format(
e), result=self._prob.result), e)
finally:
self._remove_constr = self._temp_constr
self._temp_constr = [] | module function_definition identifier parameters identifier block while_statement comparison_operator call identifier argument_list attribute identifier identifier integer block expression_statement call attribute call attribute attribute identifier identifier identifier argument_list identifier argument_list try_statement block expression_statement call attribute attribute identifier identifier identifier argument_list attribute attribute identifier identifier identifier except_clause as_pattern attribute identifier identifier as_pattern_target identifier block expression_statement call identifier argument_list call identifier argument_list call attribute string string_start string_content string_end identifier argument_list identifier keyword_argument identifier attribute attribute identifier identifier identifier identifier finally_clause block expression_statement assignment attribute identifier identifier attribute identifier identifier expression_statement assignment attribute identifier identifier list | Solve the problem with the current objective. |
def delete_token():
username = get_admin()[0]
admins = get_couchdb_admins()
if username in admins:
print 'I delete {} CouchDB user'.format(username)
delete_couchdb_admin(username)
if os.path.isfile(LOGIN_FILENAME):
print 'I delete {} token file'.format(LOGIN_FILENAME)
os.remove(LOGIN_FILENAME) | module function_definition identifier parameters block expression_statement assignment identifier subscript call identifier argument_list integer expression_statement assignment identifier call identifier argument_list if_statement comparison_operator identifier identifier block print_statement call attribute string string_start string_content string_end identifier argument_list identifier expression_statement call identifier argument_list identifier if_statement call attribute attribute identifier identifier identifier argument_list identifier block print_statement call attribute string string_start string_content string_end identifier argument_list identifier expression_statement call attribute identifier identifier argument_list identifier | Delete current token, file & CouchDB admin user |
def plotnoise(noisepkl, mergepkl, plot_width=950, plot_height=400):
d = pickle.load(open(mergepkl))
ndist, imstd, flagfrac = plotnoisedist(noisepkl, plot_width=plot_width/2, plot_height=plot_height)
fluxscale = calcfluxscale(d, imstd, flagfrac)
logger.info('Median image noise is {0:.3} Jy.'.format(fluxscale*imstd))
ncum, imnoise = plotnoisecum(noisepkl, fluxscale=fluxscale, plot_width=plot_width/2, plot_height=plot_height)
hndle = show(Row(ndist, ncum, width=plot_width, height=plot_height))
return imnoise | module function_definition identifier parameters identifier identifier default_parameter identifier integer default_parameter identifier integer block expression_statement assignment identifier call attribute identifier identifier argument_list call identifier argument_list identifier expression_statement assignment pattern_list identifier identifier identifier call identifier argument_list identifier keyword_argument identifier binary_operator identifier integer keyword_argument identifier identifier expression_statement assignment identifier call identifier argument_list identifier identifier identifier expression_statement call attribute identifier identifier argument_list call attribute string string_start string_content string_end identifier argument_list binary_operator identifier identifier expression_statement assignment pattern_list identifier identifier call identifier argument_list identifier keyword_argument identifier identifier keyword_argument identifier binary_operator identifier integer keyword_argument identifier identifier expression_statement assignment identifier call identifier argument_list call identifier argument_list identifier identifier keyword_argument identifier identifier keyword_argument identifier identifier return_statement identifier | Make two panel plot to summary noise analysis with estimated flux scale |
def _Members(self, group):
group.members = set(group.members).union(self.gids.get(group.gid, []))
return group | module function_definition identifier parameters identifier identifier block expression_statement assignment attribute identifier identifier call attribute call identifier argument_list attribute identifier identifier identifier argument_list call attribute attribute identifier identifier identifier argument_list attribute identifier identifier list return_statement identifier | Unify members of a group and accounts with the group as primary gid. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.