code stringlengths 51 2.34k | sequence stringlengths 186 3.94k | docstring stringlengths 11 171 |
|---|---|---|
def write(path, doc, mode=MODE_TSV, **kwargs):
if mode == MODE_TSV:
with TxtWriter.from_path(path) as writer:
writer.write_doc(doc)
elif mode == MODE_JSON:
write_json(path, doc, **kwargs) | module function_definition identifier parameters identifier identifier default_parameter identifier identifier dictionary_splat_pattern identifier block if_statement comparison_operator identifier identifier block with_statement with_clause with_item as_pattern call attribute identifier identifier argument_list identifier as_pattern_target identifier block expression_statement call attribute identifier identifier argument_list identifier elif_clause comparison_operator identifier identifier block expression_statement call identifier argument_list identifier identifier dictionary_splat identifier | Helper function to write doc to TTL-TXT format |
def _dump_header(self):
with open(self._file, 'w') as _file:
_file.write(self._hsrt)
self._sptr = _file.tell()
_file.write(self._hend) | module function_definition identifier parameters identifier block with_statement with_clause with_item as_pattern call identifier argument_list attribute identifier identifier string string_start string_content string_end as_pattern_target identifier block expression_statement call attribute identifier identifier argument_list attribute identifier identifier expression_statement assignment attribute identifier identifier call attribute identifier identifier argument_list expression_statement call attribute identifier identifier argument_list attribute identifier identifier | Initially dump file heads and tails. |
def tasks(self, name):
found = self[name]
if isinstance(found, Shovel):
return [v for _, v in found.items()]
return [found] | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier subscript identifier identifier if_statement call identifier argument_list identifier identifier block return_statement list_comprehension identifier for_in_clause pattern_list identifier identifier call attribute identifier identifier argument_list return_statement list identifier | Get all the tasks that match a name |
def sample_double_norm(mean, std_upper, std_lower, size):
from scipy.special import erfinv
samples = np.empty(size)
percentiles = np.random.uniform(0., 1., size)
cutoff = std_lower / (std_lower + std_upper)
w = (percentiles < cutoff)
percentiles[w] *= 0.5 / cutoff
samples[w] = mean + np.sqrt(2) * std_lower * erfinv(2 * percentiles[w] - 1)
w = ~w
percentiles[w] = 1 - (1 - percentiles[w]) * 0.5 / (1 - cutoff)
samples[w] = mean + np.sqrt(2) * std_upper * erfinv(2 * percentiles[w] - 1)
return samples | module function_definition identifier parameters identifier identifier identifier identifier block import_from_statement dotted_name identifier identifier dotted_name identifier expression_statement assignment identifier call attribute identifier identifier argument_list identifier expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list float float identifier expression_statement assignment identifier binary_operator identifier parenthesized_expression binary_operator identifier identifier expression_statement assignment identifier parenthesized_expression comparison_operator identifier identifier expression_statement augmented_assignment subscript identifier identifier binary_operator float identifier expression_statement assignment subscript identifier identifier binary_operator identifier binary_operator binary_operator call attribute identifier identifier argument_list integer identifier call identifier argument_list binary_operator binary_operator integer subscript identifier identifier integer expression_statement assignment identifier unary_operator identifier expression_statement assignment subscript identifier identifier binary_operator integer binary_operator binary_operator parenthesized_expression binary_operator integer subscript identifier identifier float parenthesized_expression binary_operator integer identifier expression_statement assignment subscript identifier identifier binary_operator identifier binary_operator binary_operator call attribute identifier identifier argument_list integer identifier call identifier argument_list binary_operator binary_operator integer subscript identifier identifier integer return_statement identifier | Note that this function requires Scipy. |
def refresh(self, key):
s0 = self[key]
s = self.backtrack(key)
s.persist(**s0.metadata['persist_kwargs']) | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier subscript identifier identifier expression_statement assignment identifier call attribute identifier identifier argument_list identifier expression_statement call attribute identifier identifier argument_list dictionary_splat subscript attribute identifier identifier string string_start string_content string_end | Recreate and re-persist the source for the given unique ID |
def register_jobs(self, job_dict):
njobs = len(job_dict)
sys.stdout.write("Registering %i total jobs: " % njobs)
for i, job_details in enumerate(job_dict.values()):
if i % 10 == 0:
sys.stdout.write('.')
sys.stdout.flush()
self.register_job(job_details)
sys.stdout.write('!\n') | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call identifier argument_list identifier expression_statement call attribute attribute identifier identifier identifier argument_list binary_operator string string_start string_content string_end identifier for_statement pattern_list identifier identifier call identifier argument_list call attribute identifier identifier argument_list block if_statement comparison_operator binary_operator identifier integer integer block expression_statement 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 expression_statement call attribute identifier identifier argument_list identifier expression_statement call attribute attribute identifier identifier identifier argument_list string string_start string_content escape_sequence string_end | Register a bunch of jobs in this archive |
def node_copy(node, nodefactory=Node):
return nodefactory(node.tag, node.attrib.copy(), node.text,
[node_copy(n, nodefactory) for n in node]) | module function_definition identifier parameters identifier default_parameter identifier identifier block return_statement call identifier argument_list attribute identifier identifier call attribute attribute identifier identifier identifier argument_list attribute identifier identifier list_comprehension call identifier argument_list identifier identifier for_in_clause identifier identifier | Make a deep copy of the node |
def expand(self, id_user):
CmtCOLLAPSED.query.filter(db.and_(
CmtCOLLAPSED.id_bibrec == self.id_bibrec,
CmtCOLLAPSED.id_cmtRECORDCOMMENT == self.id,
CmtCOLLAPSED.id_user == id_user)).delete(synchronize_session=False) | module function_definition identifier parameters identifier identifier block expression_statement call attribute call attribute attribute identifier identifier identifier argument_list call attribute identifier identifier argument_list comparison_operator attribute identifier identifier attribute identifier identifier comparison_operator attribute identifier identifier attribute identifier identifier comparison_operator attribute identifier identifier identifier identifier argument_list keyword_argument identifier false | Expand comment beloging to user. |
def export_theta(ckout, data):
cns_file = chromhacks.bed_to_standardonly(ckout["cns"], data, headers="chromosome")
cnr_file = chromhacks.bed_to_standardonly(ckout["cnr"], data, headers="chromosome")
out_file = "%s-theta.input" % utils.splitext_plus(cns_file)[0]
if not utils.file_exists(out_file):
with file_transaction(data, out_file) as tx_out_file:
cmd = [_get_cmd(), "export", "theta", cns_file, cnr_file, "-o", tx_out_file]
do.run(_prep_cmd(cmd, tx_out_file), "Export CNVkit calls as inputs for TheTA2")
ckout["theta_input"] = out_file
return ckout | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list subscript identifier string string_start string_content string_end identifier keyword_argument identifier string string_start string_content string_end expression_statement assignment identifier call attribute identifier identifier argument_list subscript identifier string string_start string_content string_end identifier keyword_argument identifier string string_start string_content string_end expression_statement assignment identifier binary_operator string string_start string_content string_end subscript call attribute identifier identifier argument_list identifier integer if_statement not_operator call attribute identifier identifier argument_list identifier block with_statement with_clause with_item as_pattern call identifier argument_list identifier identifier as_pattern_target identifier block expression_statement assignment identifier list call identifier argument_list string string_start string_content string_end string string_start string_content string_end identifier identifier string string_start string_content string_end identifier expression_statement call attribute identifier identifier argument_list call identifier argument_list identifier identifier string string_start string_content string_end expression_statement assignment subscript identifier string string_start string_content string_end identifier return_statement identifier | Provide updated set of data with export information for TheTA2 input. |
def math_funcdef_handle(tokens):
internal_assert(len(tokens) == 2, "invalid assignment function definition tokens", tokens)
return tokens[0] + ("" if tokens[1].startswith("\n") else " ") + tokens[1] | module function_definition identifier parameters identifier block expression_statement call identifier argument_list comparison_operator call identifier argument_list identifier integer string string_start string_content string_end identifier return_statement binary_operator binary_operator subscript identifier integer parenthesized_expression conditional_expression string string_start string_end call attribute subscript identifier integer identifier argument_list string string_start string_content escape_sequence string_end string string_start string_content string_end subscript identifier integer | Process assignment function definition. |
def _forward_iterator(self):
"Returns a forward iterator over the trie"
path = [(self, 0, Bits())]
while path:
node, idx, prefix = path.pop()
if idx==0 and node.value is not None and not node.prune_value:
yield (self._unpickle_key(prefix), self._unpickle_value(node.value))
if idx<len(node.children):
path.append((node, idx+1, prefix))
link = node.children[idx]
if not link.pruned:
path.append((link.node, 0, prefix + link.prefix)) | module function_definition identifier parameters identifier block expression_statement string string_start string_content string_end expression_statement assignment identifier list tuple identifier integer call identifier argument_list while_statement identifier block expression_statement assignment pattern_list identifier identifier identifier call attribute identifier identifier argument_list if_statement boolean_operator boolean_operator comparison_operator identifier integer comparison_operator attribute identifier identifier none not_operator attribute identifier identifier block expression_statement yield tuple call attribute identifier identifier argument_list identifier call attribute identifier identifier argument_list attribute identifier identifier if_statement comparison_operator identifier call identifier argument_list attribute identifier identifier block expression_statement call attribute identifier identifier argument_list tuple identifier binary_operator identifier integer identifier expression_statement assignment identifier subscript attribute identifier identifier identifier if_statement not_operator attribute identifier identifier block expression_statement call attribute identifier identifier argument_list tuple attribute identifier identifier integer binary_operator identifier attribute identifier identifier | Returns a forward iterator over the trie |
def save(self, *args, **kwargs):
adding_new = False
if not self.pk or (not self.cpu and not self.ram):
if self.model.cpu:
self.cpu = self.model.cpu
if self.model.ram:
self.ram = self.model.ram
adding_new = True
super(DeviceToModelRel, self).save(*args, **kwargs)
try:
antenna_model = self.model.antennamodel
except AntennaModel.DoesNotExist:
antenna_model = False
if adding_new and antenna_model:
antenna = Antenna(
device=self.device,
model=self.model.antennamodel
)
wireless_interfaces = self.device.interface_set.filter(type=2)
if len(wireless_interfaces) > 0:
antenna.radio = wireless_interfaces[0]
antenna.save() | module function_definition identifier parameters identifier list_splat_pattern identifier dictionary_splat_pattern identifier block expression_statement assignment identifier false if_statement boolean_operator not_operator attribute identifier identifier parenthesized_expression boolean_operator not_operator attribute identifier identifier not_operator attribute identifier identifier block if_statement attribute attribute identifier identifier identifier block expression_statement assignment attribute identifier identifier attribute attribute identifier identifier identifier if_statement attribute attribute identifier identifier identifier block expression_statement assignment attribute identifier identifier attribute attribute identifier identifier identifier expression_statement assignment identifier true expression_statement call attribute call identifier argument_list identifier identifier identifier argument_list list_splat identifier dictionary_splat identifier try_statement block expression_statement assignment identifier attribute attribute identifier identifier identifier except_clause attribute identifier identifier block expression_statement assignment identifier false if_statement boolean_operator identifier identifier block expression_statement assignment identifier call identifier argument_list keyword_argument identifier attribute identifier identifier keyword_argument identifier attribute attribute identifier identifier identifier expression_statement assignment identifier call attribute attribute attribute identifier identifier identifier identifier argument_list keyword_argument identifier integer if_statement comparison_operator call identifier argument_list identifier integer block expression_statement assignment attribute identifier identifier subscript identifier integer expression_statement call attribute identifier identifier argument_list | when creating a new record fill CPU and RAM info if available |
def media_kind(kind):
if kind in [1]:
return const.MEDIA_TYPE_UNKNOWN
if kind in [3, 7, 11, 12, 13, 18, 32]:
return const.MEDIA_TYPE_VIDEO
if kind in [2, 4, 10, 14, 17, 21, 36]:
return const.MEDIA_TYPE_MUSIC
if kind in [8, 64]:
return const.MEDIA_TYPE_TV
raise exceptions.UnknownMediaKind('Unknown media kind: ' + str(kind)) | module function_definition identifier parameters identifier block if_statement comparison_operator identifier list integer block return_statement attribute identifier identifier if_statement comparison_operator identifier list integer integer integer integer integer integer integer block return_statement attribute identifier identifier if_statement comparison_operator identifier list integer integer integer integer integer integer integer block return_statement attribute identifier identifier if_statement comparison_operator identifier list integer integer block return_statement attribute identifier identifier raise_statement call attribute identifier identifier argument_list binary_operator string string_start string_content string_end call identifier argument_list identifier | Convert iTunes media kind to API representation. |
def file_exists_on_unit(self, sentry_unit, file_name):
try:
sentry_unit.file_stat(file_name)
return True
except IOError:
return False
except Exception as e:
msg = 'Error checking file {}: {}'.format(file_name, e)
amulet.raise_status(amulet.FAIL, msg=msg) | module function_definition identifier parameters identifier identifier identifier block try_statement block expression_statement call attribute identifier identifier argument_list identifier return_statement true except_clause identifier block return_statement false except_clause as_pattern identifier as_pattern_target identifier block expression_statement assignment identifier call attribute string string_start string_content string_end identifier argument_list identifier identifier expression_statement call attribute identifier identifier argument_list attribute identifier identifier keyword_argument identifier identifier | Check if a file exists on a unit. |
def timestamp(self, timestamp):
clone = copy.deepcopy(self)
clone._timestamp = timestamp
return clone | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list identifier expression_statement assignment attribute identifier identifier identifier return_statement identifier | Allows for custom timestamps to be saved with the record. |
def should_skip_logging(func):
disabled = strtobool(request.headers.get("x-request-nolog", "false"))
return disabled or getattr(func, SKIP_LOGGING, False) | module function_definition identifier parameters identifier block expression_statement assignment identifier call identifier argument_list call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end string string_start string_content string_end return_statement boolean_operator identifier call identifier argument_list identifier identifier false | Should we skip logging for this handler? |
def send_confirm_email_email(self, user, user_email):
if not self.user_manager.USER_ENABLE_EMAIL: return
if not self.user_manager.USER_ENABLE_CONFIRM_EMAIL: return
email = user_email.email if user_email else user.email
object_id = user_email.id if user_email else user.id
token = self.user_manager.generate_token(object_id)
confirm_email_link = url_for('user.confirm_email', token=token, _external=True)
self._render_and_send_email(
email,
user,
self.user_manager.USER_CONFIRM_EMAIL_TEMPLATE,
confirm_email_link=confirm_email_link,
) | module function_definition identifier parameters identifier identifier identifier block if_statement not_operator attribute attribute identifier identifier identifier block return_statement if_statement not_operator attribute attribute identifier identifier identifier block return_statement expression_statement assignment identifier conditional_expression attribute identifier identifier identifier attribute identifier identifier expression_statement assignment identifier conditional_expression attribute identifier identifier identifier attribute identifier identifier expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list identifier expression_statement assignment identifier call identifier argument_list string string_start string_content string_end keyword_argument identifier identifier keyword_argument identifier true expression_statement call attribute identifier identifier argument_list identifier identifier attribute attribute identifier identifier identifier keyword_argument identifier identifier | Send the 'email confirmation' email. |
def lrun(command, *args, **kwargs):
return run('cd {0} && {1}'.format(ROOT, command), *args, **kwargs) | module function_definition identifier parameters identifier list_splat_pattern identifier dictionary_splat_pattern identifier block return_statement call identifier argument_list call attribute string string_start string_content string_end identifier argument_list identifier identifier list_splat identifier dictionary_splat identifier | Run a local command from project root |
def determine_file_extension_based_on_format(format_specifier):
if format_specifier == FMT_INI:
return 'ini'
if format_specifier == FMT_DELIMITED:
return ''
if format_specifier == FMT_XML:
return 'xml'
if format_specifier == FMT_JSON:
return 'json'
if format_specifier == FMT_YAML:
return 'yml'
raise ValueError('invalid format specifier: {}'.format(format_specifier)) | module function_definition identifier parameters identifier block if_statement comparison_operator identifier identifier block return_statement string string_start string_content string_end if_statement comparison_operator identifier identifier block return_statement string string_start string_end if_statement comparison_operator identifier identifier block return_statement string string_start string_content string_end if_statement comparison_operator identifier identifier block return_statement string string_start string_content string_end if_statement comparison_operator identifier identifier block return_statement string string_start string_content string_end raise_statement call identifier argument_list call attribute string string_start string_content string_end identifier argument_list identifier | returns file extension string |
def preprocess_record(self, pid, record, links_factory=None, **kwargs):
links_factory = links_factory or (lambda x, record=None, **k: dict())
metadata = copy.deepcopy(record.replace_refs()) if self.replace_refs \
else record.dumps()
return dict(
pid=pid,
metadata=metadata,
links=links_factory(pid, record=record, **kwargs),
revision=record.revision_id,
created=(pytz.utc.localize(record.created).isoformat()
if record.created else None),
updated=(pytz.utc.localize(record.updated).isoformat()
if record.updated else None),
) | module function_definition identifier parameters identifier identifier identifier default_parameter identifier none dictionary_splat_pattern identifier block expression_statement assignment identifier boolean_operator identifier parenthesized_expression lambda lambda_parameters identifier default_parameter identifier none dictionary_splat_pattern identifier call identifier argument_list expression_statement assignment identifier conditional_expression call attribute identifier identifier argument_list call attribute identifier identifier argument_list attribute identifier identifier line_continuation call attribute identifier identifier argument_list return_statement call identifier argument_list keyword_argument identifier identifier keyword_argument identifier identifier keyword_argument identifier call identifier argument_list identifier keyword_argument identifier identifier dictionary_splat identifier keyword_argument identifier attribute identifier identifier keyword_argument identifier parenthesized_expression conditional_expression call attribute call attribute attribute identifier identifier identifier argument_list attribute identifier identifier identifier argument_list attribute identifier identifier none keyword_argument identifier parenthesized_expression conditional_expression call attribute call attribute attribute identifier identifier identifier argument_list attribute identifier identifier identifier argument_list attribute identifier identifier none | Prepare a record and persistent identifier for serialization. |
def cycle(self, *args):
if not args:
raise TypeError('no items for cycling given')
return args[self.index0 % len(args)] | module function_definition identifier parameters identifier list_splat_pattern identifier block if_statement not_operator identifier block raise_statement call identifier argument_list string string_start string_content string_end return_statement subscript identifier binary_operator attribute identifier identifier call identifier argument_list identifier | Cycles among the arguments with the current loop index. |
def hideEvent(self, event):
super(CallTipWidget, self).hideEvent(event)
self._text_edit.cursorPositionChanged.disconnect(
self._cursor_position_changed)
self._text_edit.removeEventFilter(self) | module function_definition identifier parameters identifier identifier block expression_statement call attribute call identifier argument_list identifier identifier identifier argument_list identifier expression_statement call attribute attribute attribute identifier identifier identifier identifier argument_list attribute identifier identifier expression_statement call attribute attribute identifier identifier identifier argument_list identifier | Reimplemented to disconnect signal handlers and event filter. |
def addOutParameter(self, name, type, namespace=None, element_type=0):
parameter = ParameterInfo(name, type, namespace, element_type)
self.outparams.append(parameter)
return parameter | module function_definition identifier parameters identifier identifier identifier default_parameter identifier none default_parameter identifier integer block expression_statement assignment identifier call identifier argument_list identifier identifier identifier identifier expression_statement call attribute attribute identifier identifier identifier argument_list identifier return_statement identifier | Add an output parameter description to the call info. |
def team_integrationLogs(self, **kwargs) -> SlackResponse:
self._validate_xoxp_token()
return self.api_call("team.integrationLogs", http_verb="GET", params=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 string string_start string_content string_end keyword_argument identifier identifier | Gets the integration logs for the current team. |
def xml(self, text=TEXT):
def convert(line):
xml = " <item>\n"
for f in line.index:
xml += " <field name=\"%s\">%s</field>\n" % (f, line[f])
xml += " </item>\n"
return xml
return "<items>\n" + '\n'.join(self._data.apply(convert, axis=1)) + \
"</items>" | module function_definition identifier parameters identifier default_parameter identifier identifier block function_definition identifier parameters identifier block expression_statement assignment identifier string string_start string_content escape_sequence string_end for_statement identifier attribute identifier identifier block expression_statement augmented_assignment identifier binary_operator string string_start string_content escape_sequence escape_sequence escape_sequence string_end tuple identifier subscript identifier identifier expression_statement augmented_assignment identifier string string_start string_content escape_sequence string_end return_statement identifier return_statement binary_operator binary_operator string string_start string_content escape_sequence string_end call attribute string string_start string_content escape_sequence string_end identifier argument_list call attribute attribute identifier identifier identifier argument_list identifier keyword_argument identifier integer string string_start string_content string_end | Generate an XML output from the report data. |
def _log_send(self, logrecord):
for field, value in self.__log_extensions:
setattr(logrecord, field, value)
self.__send_to_frontend({"band": "log", "payload": logrecord}) | module function_definition identifier parameters identifier identifier block for_statement pattern_list identifier identifier attribute identifier identifier block expression_statement call identifier argument_list identifier identifier identifier expression_statement call attribute identifier identifier argument_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 identifier | Forward log records to the frontend. |
def list_domains(self):
self.connect()
results = self.server.list_domains(self.session_id)
return {i['domain']: i['subdomains'] for i in results} | module function_definition identifier parameters identifier block expression_statement call attribute identifier identifier argument_list expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list attribute identifier identifier return_statement dictionary_comprehension pair subscript identifier string string_start string_content string_end subscript identifier string string_start string_content string_end for_in_clause identifier identifier | Return all domains. Domain is a key, so group by them |
def run_forever(self):
res = self.slack.rtm.start()
self.log.info("current channels: %s",
','.join(c['name'] for c in res.body['channels']
if c['is_member']))
self.id = res.body['self']['id']
self.name = res.body['self']['name']
self.my_mention = "<@%s>" % self.id
self.ws = websocket.WebSocketApp(
res.body['url'],
on_message=self._on_message,
on_error=self._on_error,
on_close=self._on_close,
on_open=self._on_open)
self.prepare_connection(self.config)
self.ws.run_forever() | module function_definition identifier parameters identifier block expression_statement assignment identifier call attribute attribute attribute identifier identifier identifier identifier argument_list expression_statement call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end call attribute string string_start string_content string_end identifier generator_expression subscript identifier string string_start string_content string_end for_in_clause identifier subscript attribute identifier identifier string string_start string_content string_end if_clause subscript identifier string string_start string_content string_end expression_statement assignment attribute identifier identifier subscript subscript attribute identifier identifier string string_start string_content string_end string string_start string_content string_end expression_statement assignment attribute identifier identifier subscript subscript attribute identifier identifier string string_start string_content string_end string string_start string_content string_end expression_statement assignment attribute identifier identifier binary_operator string string_start string_content string_end attribute identifier identifier expression_statement assignment attribute identifier identifier call attribute identifier identifier argument_list subscript attribute identifier identifier string string_start string_content string_end keyword_argument identifier attribute identifier identifier keyword_argument identifier attribute identifier identifier keyword_argument identifier attribute identifier identifier keyword_argument identifier attribute identifier identifier expression_statement call attribute identifier identifier argument_list attribute identifier identifier expression_statement call attribute attribute identifier identifier identifier argument_list | Run the bot, blocking forever. |
def spreadsheet(service, id):
request = service.spreadsheets().get(spreadsheetId=id)
try:
response = request.execute()
except apiclient.errors.HttpError as e:
if e.resp.status == 404:
raise KeyError(id)
else:
raise
return response | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call attribute call attribute identifier identifier argument_list identifier argument_list keyword_argument identifier identifier try_statement block expression_statement assignment identifier call attribute identifier identifier argument_list except_clause as_pattern attribute attribute identifier identifier identifier as_pattern_target identifier block if_statement comparison_operator attribute attribute identifier identifier identifier integer block raise_statement call identifier argument_list identifier else_clause block raise_statement return_statement identifier | Fetch and return spreadsheet meta data with Google sheets API. |
def _init_template(self, cls, base_init_template):
if self.__class__ is not cls:
raise TypeError("Inheritance from classes with @GtkTemplate decorators "
"is not allowed at this time")
connected_signals = set()
self.__connected_template_signals__ = connected_signals
base_init_template(self)
for name in self.__gtemplate_widgets__:
widget = self.get_template_child(cls, name)
self.__dict__[name] = widget
if widget is None:
raise AttributeError("A missing child widget was set using "
"GtkTemplate.Child and the entire "
"template is now broken (widgets: %s)" %
', '.join(self.__gtemplate_widgets__))
for name in self.__gtemplate_methods__.difference(connected_signals):
errmsg = ("Signal '%s' was declared with @GtkTemplate.Callback " +
"but was not present in template") % name
warnings.warn(errmsg, GtkTemplateWarning) | module function_definition identifier parameters identifier identifier identifier block if_statement comparison_operator attribute identifier identifier identifier block raise_statement call identifier argument_list concatenated_string string string_start string_content string_end string string_start string_content string_end expression_statement assignment identifier call identifier argument_list expression_statement assignment attribute identifier identifier identifier expression_statement call identifier argument_list identifier for_statement identifier attribute identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list identifier identifier expression_statement assignment subscript attribute identifier identifier identifier identifier if_statement comparison_operator identifier none 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 string string_start string_content string_end call attribute string string_start string_content string_end identifier argument_list attribute identifier identifier for_statement identifier call attribute attribute identifier identifier identifier argument_list identifier block expression_statement assignment identifier binary_operator parenthesized_expression binary_operator string string_start string_content string_end string string_start string_content string_end identifier expression_statement call attribute identifier identifier argument_list identifier identifier | This would be better as an override for Gtk.Widget |
def _calc_d(aod700, p):
p0 = 101325.
dp = 1/(18 + 152*aod700)
d = -0.337*aod700**2 + 0.63*aod700 + 0.116 + dp*np.log(p/p0)
return d | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier float expression_statement assignment identifier binary_operator integer parenthesized_expression binary_operator integer binary_operator integer identifier expression_statement assignment identifier binary_operator binary_operator binary_operator binary_operator unary_operator float binary_operator identifier integer binary_operator float identifier float binary_operator identifier call attribute identifier identifier argument_list binary_operator identifier identifier return_statement identifier | Calculate the d coefficient. |
def contexts(self):
if not hasattr(self, "_contexts"):
cs = {}
for cr in self.doc["contexts"]:
cs[cr["name"]] = copy.deepcopy(cr["context"])
self._contexts = cs
return self._contexts | module function_definition identifier parameters identifier block if_statement not_operator call identifier argument_list identifier string string_start string_content string_end block expression_statement assignment identifier dictionary for_statement identifier subscript attribute identifier identifier string string_start string_content string_end block expression_statement assignment subscript identifier subscript identifier string string_start string_content string_end call attribute identifier identifier argument_list subscript identifier string string_start string_content string_end expression_statement assignment attribute identifier identifier identifier return_statement attribute identifier identifier | Returns known contexts by exposing as a read-only property. |
def _loopreport(self):
while 1:
eventlet.sleep(0.2)
ac2popenlist = {}
for action in self.session._actions:
for popen in action._popenlist:
if popen.poll() is None:
lst = ac2popenlist.setdefault(action.activity, [])
lst.append(popen)
if not action._popenlist and action in self._actionmayfinish:
super(RetoxReporter, self).logaction_finish(action)
self._actionmayfinish.remove(action)
self.screen.draw_next_frame(repeat=False) | module function_definition identifier parameters identifier block while_statement integer block expression_statement call attribute identifier identifier argument_list float expression_statement assignment identifier dictionary for_statement identifier attribute attribute identifier identifier identifier block for_statement identifier attribute identifier identifier block if_statement comparison_operator call attribute identifier identifier argument_list none block expression_statement assignment identifier call attribute identifier identifier argument_list attribute identifier identifier list expression_statement call attribute identifier identifier argument_list identifier if_statement boolean_operator not_operator attribute identifier identifier comparison_operator identifier attribute identifier identifier block expression_statement call attribute call identifier argument_list identifier identifier identifier argument_list identifier expression_statement call attribute attribute identifier identifier identifier argument_list identifier expression_statement call attribute attribute identifier identifier identifier argument_list keyword_argument identifier false | Loop over the report progress |
def insert_sequences_into_tree(aln, moltype, params={}):
new_aln=get_align_for_phylip(StringIO(aln))
aln2 = Alignment(new_aln)
seqs = aln2.toFasta()
parsinsert_app = ParsInsert(params=params)
result = parsinsert_app(seqs)
tree = DndParser(result['Tree'].read(), constructor=PhyloNode)
result.cleanUp()
return tree | module function_definition identifier parameters identifier identifier default_parameter identifier dictionary block expression_statement assignment identifier call identifier argument_list call identifier argument_list identifier expression_statement assignment identifier call identifier argument_list identifier expression_statement assignment identifier call attribute identifier identifier argument_list expression_statement assignment identifier call identifier argument_list keyword_argument identifier identifier expression_statement assignment identifier call identifier argument_list identifier expression_statement assignment identifier call identifier argument_list call attribute subscript identifier string string_start string_content string_end identifier argument_list keyword_argument identifier identifier expression_statement call attribute identifier identifier argument_list return_statement identifier | Returns a tree from placement of sequences |
def cookie_eater(ctx):
state = ctx.create_state()
state["ready"] = True
for _ in state.when_change("cookies"):
eat_cookie(state) | module function_definition identifier parameters identifier block expression_statement assignment identifier call attribute identifier identifier argument_list expression_statement assignment subscript identifier string string_start string_content string_end true for_statement identifier call attribute identifier identifier argument_list string string_start string_content string_end block expression_statement call identifier argument_list identifier | Eat cookies as they're baked. |
def graft_neuron(root_section):
assert isinstance(root_section, Section)
return Neuron(soma=Soma(root_section.points[:1]), neurites=[Neurite(root_section)]) | module function_definition identifier parameters identifier block assert_statement call identifier argument_list identifier identifier return_statement call identifier argument_list keyword_argument identifier call identifier argument_list subscript attribute identifier identifier slice integer keyword_argument identifier list call identifier argument_list identifier | Returns a neuron starting at root_section |
def version(verbose):
print(Fore.BLUE + '-=' * 15)
print(Fore.YELLOW + 'Superset ' + Fore.CYAN + '{version}'.format(
version=config.get('VERSION_STRING')))
print(Fore.BLUE + '-=' * 15)
if verbose:
print('[DB] : ' + '{}'.format(db.engine))
print(Style.RESET_ALL) | module function_definition identifier parameters identifier block expression_statement call identifier argument_list binary_operator attribute identifier identifier binary_operator string string_start string_content string_end integer expression_statement call identifier argument_list binary_operator binary_operator binary_operator attribute identifier identifier string string_start string_content string_end attribute identifier identifier call attribute string string_start string_content string_end identifier argument_list keyword_argument identifier call attribute identifier identifier argument_list string string_start string_content string_end expression_statement call identifier argument_list binary_operator attribute identifier identifier binary_operator string string_start string_content string_end integer if_statement identifier block expression_statement call identifier argument_list binary_operator 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 identifier argument_list attribute identifier identifier | Prints the current version number |
def space_search(args):
r = fapi.list_workspaces()
fapi._check_response_code(r, 200)
workspaces = r.json()
extra_terms = []
if args.bucket:
workspaces = [w for w in workspaces
if re.search(args.bucket, w['workspace']['bucketName'])]
extra_terms.append('bucket')
pretty_spaces = []
for space in workspaces:
ns = space['workspace']['namespace']
ws = space['workspace']['name']
pspace = ns + '/' + ws
pspace += '\t' + space['workspace']['bucketName']
pretty_spaces.append(pspace)
return sorted(pretty_spaces, key=lambda s: s.lower()) | module function_definition identifier parameters identifier block expression_statement assignment identifier call attribute identifier identifier argument_list expression_statement call attribute identifier identifier argument_list identifier integer expression_statement assignment identifier call attribute identifier identifier argument_list expression_statement assignment identifier list if_statement attribute identifier identifier block expression_statement assignment identifier list_comprehension identifier for_in_clause identifier identifier if_clause call attribute identifier identifier argument_list attribute identifier identifier subscript subscript identifier 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 assignment identifier list for_statement identifier identifier 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 subscript subscript identifier string string_start string_content string_end string string_start string_content string_end expression_statement assignment identifier binary_operator binary_operator identifier string string_start string_content string_end identifier expression_statement augmented_assignment identifier binary_operator string string_start string_content escape_sequence string_end subscript subscript identifier string string_start string_content string_end string string_start string_content string_end expression_statement call attribute identifier identifier argument_list identifier return_statement call identifier argument_list identifier keyword_argument identifier lambda lambda_parameters identifier call attribute identifier identifier argument_list | Search for workspaces matching certain criteria |
def build(self):
self._molecules = []
if self.handedness == 'l':
handedness = -1
else:
handedness = 1
rot_ang = self.rot_ang * handedness
for i in range(self.num_of_repeats):
dup_unit = copy.deepcopy(self.repeat_unit)
z = (self.rise * i) * numpy.array([0, 0, 1])
dup_unit.translate(z)
dup_unit.rotate(rot_ang * i, [0, 0, 1])
self.extend(dup_unit)
self.relabel_all()
return | module function_definition identifier parameters identifier block expression_statement assignment attribute identifier identifier list if_statement comparison_operator attribute identifier identifier string string_start string_content string_end block expression_statement assignment identifier unary_operator integer else_clause block expression_statement assignment identifier integer expression_statement assignment identifier binary_operator attribute identifier identifier identifier for_statement identifier call identifier argument_list attribute identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list attribute identifier identifier expression_statement assignment identifier binary_operator parenthesized_expression binary_operator attribute identifier identifier identifier call attribute identifier identifier argument_list list integer integer integer expression_statement call attribute identifier identifier argument_list identifier expression_statement call attribute identifier identifier argument_list binary_operator identifier identifier list integer integer integer expression_statement call attribute identifier identifier argument_list identifier expression_statement call attribute identifier identifier argument_list return_statement | Builds a Solenoid using the defined attributes. |
def use_comparative_assessment_offered_view(self):
self._object_views['assessment_offered'] = COMPARATIVE
for session in self._get_provider_sessions():
try:
session.use_comparative_assessment_offered_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 AssessmentOfferedLookupSession.use_comparative_assessment_offered_view |
def string_to_char(l):
if not l:
return []
if l == ['']:
l = [' ']
maxlen = reduce(max, map(len, l))
ll = [x.ljust(maxlen) for x in l]
result = []
for s in ll:
result.append([x for x in s])
return result | module function_definition identifier parameters identifier block if_statement not_operator identifier block return_statement list if_statement comparison_operator identifier list string string_start string_end block expression_statement assignment identifier list string string_start string_content string_end expression_statement assignment identifier call identifier argument_list identifier call identifier argument_list identifier identifier expression_statement assignment identifier list_comprehension call attribute identifier identifier argument_list identifier for_in_clause identifier identifier expression_statement assignment identifier list for_statement identifier identifier block expression_statement call attribute identifier identifier argument_list list_comprehension identifier for_in_clause identifier identifier return_statement identifier | Convert 1-D list of strings to 2-D list of chars. |
def setup_debug_logging():
logger = logging.getLogger("xbahn")
logger.setLevel(logging.DEBUG)
ch = logging.StreamHandler()
ch.setLevel(logging.DEBUG)
ch.setFormatter(logging.Formatter("%(name)s: %(message)s"))
logger.addHandler(ch) | module function_definition identifier parameters block expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end expression_statement call attribute identifier identifier argument_list attribute identifier identifier expression_statement assignment identifier call attribute identifier identifier argument_list expression_statement call attribute identifier identifier argument_list attribute identifier identifier expression_statement call attribute identifier identifier argument_list call attribute identifier identifier argument_list string string_start string_content string_end expression_statement call attribute identifier identifier argument_list identifier | set up debug logging |
def dump(self, **kwargs):
import sys
if not self.seq:
self.seq = self.getSequence()
print("StringGenerator version: %s" % (__version__))
print("Python version: %s" % sys.version)
self.seq.dump()
return self.render(**kwargs) | module function_definition identifier parameters identifier dictionary_splat_pattern identifier block import_statement dotted_name identifier if_statement not_operator attribute identifier identifier block expression_statement assignment attribute identifier identifier call attribute identifier identifier argument_list expression_statement call identifier argument_list binary_operator string string_start string_content string_end parenthesized_expression identifier expression_statement call identifier argument_list binary_operator string string_start string_content string_end attribute identifier identifier expression_statement call attribute attribute identifier identifier identifier argument_list return_statement call attribute identifier identifier argument_list dictionary_splat identifier | Print the parse tree and then call render for an example. |
def full_research_organism(soup):
"research-organism list including inline tags, such as italic"
if not raw_parser.research_organism_keywords(soup):
return []
return list(map(node_contents_str, raw_parser.research_organism_keywords(soup))) | module function_definition identifier parameters identifier block expression_statement string string_start string_content string_end if_statement not_operator call attribute identifier identifier argument_list identifier block return_statement list return_statement call identifier argument_list call identifier argument_list identifier call attribute identifier identifier argument_list identifier | research-organism list including inline tags, such as italic |
def lambda_handler(event, context):
print("Client token: " + event['authorizationToken'])
print("Method ARN: " + event['methodArn'])
principalId = "user|a1b2c3d4"
tmp = event['methodArn'].split(':')
apiGatewayArnTmp = tmp[5].split('/')
awsAccountId = tmp[4]
policy = AuthPolicy(principalId, awsAccountId)
policy.restApiId = apiGatewayArnTmp[0]
policy.region = tmp[3]
policy.stage = apiGatewayArnTmp[1]
policy.allowAllMethods()
return policy.build() | module function_definition identifier parameters identifier identifier block expression_statement call identifier argument_list binary_operator string string_start string_content string_end subscript identifier string string_start string_content string_end expression_statement call identifier argument_list binary_operator string string_start string_content string_end subscript identifier string string_start string_content string_end expression_statement assignment identifier string string_start string_content string_end expression_statement assignment identifier call attribute subscript identifier string string_start string_content string_end identifier argument_list string string_start string_content string_end expression_statement assignment identifier call attribute subscript identifier integer identifier argument_list string string_start string_content string_end expression_statement assignment identifier subscript identifier integer expression_statement assignment identifier call identifier argument_list identifier identifier expression_statement assignment attribute identifier identifier subscript identifier integer expression_statement assignment attribute identifier identifier subscript identifier integer expression_statement assignment attribute identifier identifier subscript identifier integer expression_statement call attribute identifier identifier argument_list return_statement call attribute identifier identifier argument_list | validate the incoming token |
def _log_control(self, s):
if self.encoding is not None:
s = s.decode(self.encoding, 'replace')
self._log(s, 'send') | module function_definition identifier parameters identifier identifier block if_statement comparison_operator attribute identifier identifier none block expression_statement assignment identifier call attribute identifier identifier argument_list attribute identifier identifier string string_start string_content string_end expression_statement call attribute identifier identifier argument_list identifier string string_start string_content string_end | Write control characters to the appropriate log files |
def _definition(self):
headerReference = self._sectPr.get_headerReference(self._hdrftr_index)
return self._document_part.header_part(headerReference.rId) | module function_definition identifier parameters identifier block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list attribute identifier identifier return_statement call attribute attribute identifier identifier identifier argument_list attribute identifier identifier | |HeaderPart| object containing content of this header. |
def check_text(self, text):
if to_text_string(text) == u'':
self.button_ok.setEnabled(False)
else:
self.button_ok.setEnabled(True) | module function_definition identifier parameters identifier identifier block if_statement comparison_operator call identifier argument_list identifier string string_start string_end block expression_statement call attribute attribute identifier identifier identifier argument_list false else_clause block expression_statement call attribute attribute identifier identifier identifier argument_list true | Disable empty layout name possibility |
def _jar_classfiles(self, jar_file):
for cls in ClasspathUtil.classpath_entries_contents([jar_file]):
if cls.endswith('.class'):
yield cls | module function_definition identifier parameters identifier identifier block for_statement identifier call attribute identifier identifier argument_list list identifier block if_statement call attribute identifier identifier argument_list string string_start string_content string_end block expression_statement yield identifier | Returns an iterator over the classfiles inside jar_file. |
def _maybeCleanSessions(self):
sinceLast = self._clock.seconds() - self._lastClean
if sinceLast > self.sessionCleanFrequency:
self._cleanSessions() | module function_definition identifier parameters identifier block expression_statement assignment identifier binary_operator call attribute attribute identifier identifier identifier argument_list attribute identifier identifier if_statement comparison_operator identifier attribute identifier identifier block expression_statement call attribute identifier identifier argument_list | Clean expired sessions if it's been long enough since the last clean. |
def pass_outputs_v1(self):
der = self.parameters.derived.fastaccess
flu = self.sequences.fluxes.fastaccess
out = self.sequences.outlets.fastaccess
for bdx in range(der.nmbbranches):
out.branched[bdx][0] += flu.outputs[bdx] | module function_definition identifier parameters identifier block expression_statement assignment identifier attribute attribute attribute identifier identifier identifier identifier expression_statement assignment identifier attribute attribute attribute identifier identifier identifier identifier expression_statement assignment identifier attribute attribute attribute identifier identifier identifier identifier for_statement identifier call identifier argument_list attribute identifier identifier block expression_statement augmented_assignment subscript subscript attribute identifier identifier identifier integer subscript attribute identifier identifier identifier | Updates |Branched| based on |Outputs|. |
def reputation(self, query, include_reasons=False, **kwargs):
return self._results('reputation', '/v1/reputation', domain=query, include_reasons=include_reasons,
cls=Reputation, **kwargs) | module function_definition identifier parameters identifier identifier default_parameter identifier false dictionary_splat_pattern identifier block return_statement call attribute identifier identifier argument_list string string_start string_content string_end string string_start string_content string_end keyword_argument identifier identifier keyword_argument identifier identifier keyword_argument identifier identifier dictionary_splat identifier | Pass in a domain name to see its reputation score |
def dbus_readBytesFD(self, fd, byte_count):
f = os.fdopen(fd, 'rb')
result = f.read(byte_count)
f.close()
return bytearray(result) | module function_definition identifier parameters identifier identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list identifier string string_start string_content string_end expression_statement assignment identifier call attribute identifier identifier argument_list identifier expression_statement call attribute identifier identifier argument_list return_statement call identifier argument_list identifier | Reads byte_count bytes from fd and returns them. |
def eval_now(self, code):
result = eval(self.reformat(code))
if result is None or isinstance(result, (bool, int, float, complex)):
return repr(result)
elif isinstance(result, bytes):
return "b" + self.wrap_str_of(result)
elif isinstance(result, str):
return self.wrap_str_of(result)
else:
return None | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call identifier argument_list call attribute identifier identifier argument_list identifier if_statement boolean_operator comparison_operator identifier none call identifier argument_list identifier tuple identifier identifier identifier identifier block return_statement call identifier argument_list identifier elif_clause call identifier argument_list identifier identifier block return_statement binary_operator string string_start string_content string_end call attribute identifier identifier argument_list identifier elif_clause call identifier argument_list identifier identifier block return_statement call attribute identifier identifier argument_list identifier else_clause block return_statement none | Reformat and evaluate a code snippet and return code for the result. |
def _setattr_default(obj, attr, value, default):
if value is None:
setattr(obj, attr, default)
else:
setattr(obj, attr, value) | module function_definition identifier parameters identifier identifier identifier identifier block if_statement comparison_operator identifier none block expression_statement call identifier argument_list identifier identifier identifier else_clause block expression_statement call identifier argument_list identifier identifier identifier | Set an attribute of an object to a value or default value. |
def simulate(self, n):
self.tree._tree.seed_node.states = self.ancestral_states(n)
categories = np.random.randint(self.ncat, size=n).astype(np.intc)
for node in self.tree.preorder(skip_seed=True):
node.states = self.evolve_states(node.parent_node.states, categories, node.pmats)
if node.is_leaf():
self.sequences[node.taxon.label] = node.states
return self.sequences_to_string() | module function_definition identifier parameters identifier identifier block expression_statement assignment attribute attribute attribute attribute identifier identifier identifier identifier identifier call attribute identifier identifier argument_list identifier expression_statement assignment identifier call attribute call attribute attribute identifier identifier identifier argument_list attribute identifier identifier keyword_argument identifier identifier identifier argument_list attribute identifier identifier for_statement identifier call attribute attribute identifier identifier identifier argument_list keyword_argument identifier true block expression_statement assignment attribute identifier identifier call attribute identifier identifier argument_list attribute attribute identifier identifier identifier identifier attribute identifier identifier if_statement call attribute identifier identifier argument_list block expression_statement assignment subscript attribute identifier identifier attribute attribute identifier identifier identifier attribute identifier identifier return_statement call attribute identifier identifier argument_list | Evolve multiple sites during one tree traversal |
def lookup(ctx, path):
regions = parse_intervals(path, as_context=ctx.obj['semantic'])
_report_from_regions(regions, ctx.obj) | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call identifier argument_list identifier keyword_argument identifier subscript attribute identifier identifier string string_start string_content string_end expression_statement call identifier argument_list identifier attribute identifier identifier | Determine which tests intersect a source interval. |
def dispatch(self):
try:
webapp2.RequestHandler.dispatch(self)
finally:
self.session_store.save_sessions(self.response) | module function_definition identifier parameters identifier block try_statement block expression_statement call attribute attribute identifier identifier identifier argument_list identifier finally_clause block expression_statement call attribute attribute identifier identifier identifier argument_list attribute identifier identifier | Wraps the dispatch method to add session support. |
def thread_pool():
if not LocalImage._thread_pool:
logger.info("Starting LocalImage threadpool")
LocalImage._thread_pool = concurrent.futures.ThreadPoolExecutor(
thread_name_prefix="Renderer")
return LocalImage._thread_pool | module function_definition identifier parameters block if_statement not_operator attribute identifier identifier block expression_statement call attribute identifier identifier argument_list string string_start string_content string_end expression_statement assignment attribute identifier identifier call attribute attribute identifier identifier identifier argument_list keyword_argument identifier string string_start string_content string_end return_statement attribute identifier identifier | Get the rendition threadpool |
def show_flavor(self, flavor, **_params):
return self.get(self.flavor_path % (flavor), params=_params) | module function_definition identifier parameters identifier identifier dictionary_splat_pattern identifier block return_statement call attribute identifier identifier argument_list binary_operator attribute identifier identifier parenthesized_expression identifier keyword_argument identifier identifier | Fetches information for a certain Neutron service flavor. |
def parse(cls, s, schema_only=False):
a = cls()
a.state = 'comment'
a.lineno = 1
for l in s.splitlines():
a.parseline(l)
a.lineno += 1
if schema_only and a.state == 'data':
break
return a | module function_definition identifier parameters identifier identifier default_parameter identifier false block expression_statement assignment identifier call identifier argument_list expression_statement assignment attribute identifier identifier string string_start string_content string_end expression_statement assignment attribute identifier identifier integer for_statement identifier call attribute identifier identifier argument_list block expression_statement call attribute identifier identifier argument_list identifier expression_statement augmented_assignment attribute identifier identifier integer if_statement boolean_operator identifier comparison_operator attribute identifier identifier string string_start string_content string_end block break_statement return_statement identifier | Parse an ARFF File already loaded into a string. |
def runCommandSplits(splits, silent=False, shell=False):
try:
if silent:
with open(os.devnull, 'w') as devnull:
subprocess.check_call(
splits, stdout=devnull, stderr=devnull, shell=shell)
else:
subprocess.check_call(splits, shell=shell)
except OSError as exception:
if exception.errno == 2:
raise Exception(
"Can't find command while trying to run {}".format(splits))
else:
raise | module function_definition identifier parameters identifier default_parameter identifier false default_parameter identifier false block try_statement block if_statement identifier block with_statement with_clause with_item as_pattern call identifier argument_list attribute identifier identifier string string_start string_content string_end as_pattern_target identifier block expression_statement call attribute identifier identifier argument_list identifier keyword_argument identifier identifier keyword_argument identifier identifier keyword_argument identifier identifier else_clause block expression_statement call attribute identifier identifier argument_list identifier keyword_argument identifier identifier except_clause as_pattern identifier as_pattern_target identifier block if_statement comparison_operator attribute identifier identifier integer block raise_statement call identifier argument_list call attribute string string_start string_content string_end identifier argument_list identifier else_clause block raise_statement | Run a shell command given the command's parsed command line |
def _unix_word_rubout(text, pos):
words = text[:pos].rsplit(None, 1)
if len(words) < 2:
return text[pos:], 0
else:
index = text.rfind(words[1], 0, pos)
return text[:index] + text[pos:], index | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call attribute subscript identifier slice identifier identifier argument_list none integer if_statement comparison_operator call identifier argument_list identifier integer block return_statement expression_list subscript identifier slice identifier integer else_clause block expression_statement assignment identifier call attribute identifier identifier argument_list subscript identifier integer integer identifier return_statement expression_list binary_operator subscript identifier slice identifier subscript identifier slice identifier identifier | Kill the word behind pos, using white space as a word boundary. |
def all_subclasses(cls):
subclasses = cls.__subclasses__()
descendants = (descendant for subclass in subclasses
for descendant in all_subclasses(subclass))
return set(subclasses) | set(descendants) | module function_definition identifier parameters identifier block expression_statement assignment identifier call attribute identifier identifier argument_list expression_statement assignment identifier generator_expression identifier for_in_clause identifier identifier for_in_clause identifier call identifier argument_list identifier return_statement binary_operator call identifier argument_list identifier call identifier argument_list identifier | Recursively returns all the subclasses of the provided class. |
def execute(self, elem_list):
if self.condition.is_true(elem_list):
return self.action.act(elem_list)
else:
return elem_list | module function_definition identifier parameters identifier identifier block if_statement call attribute attribute identifier identifier identifier argument_list identifier block return_statement call attribute attribute identifier identifier identifier argument_list identifier else_clause block return_statement identifier | If condition, return a new elem_list provided by executing action. |
def augment_reading_list(self, primary_query, augment_query=None, reverse_negate=False):
primary_query = self.validate_query(primary_query)
augment_query = self.get_validated_augment_query(augment_query=augment_query)
try:
if reverse_negate:
primary_query = primary_query.filter(NegateQueryFilter(augment_query))
else:
augment_query = augment_query.filter(NegateQueryFilter(primary_query))
augment_query = randomize_es(augment_query)
return FirstSlotSlicer(primary_query, augment_query)
except TransportError:
return primary_query | module function_definition identifier parameters identifier identifier default_parameter identifier none default_parameter identifier false block expression_statement assignment identifier call attribute identifier identifier argument_list identifier expression_statement assignment identifier call attribute identifier identifier argument_list keyword_argument identifier identifier try_statement block if_statement identifier block expression_statement assignment identifier call attribute identifier identifier argument_list call identifier argument_list identifier else_clause block expression_statement assignment identifier call attribute identifier identifier argument_list call identifier argument_list identifier expression_statement assignment identifier call identifier argument_list identifier return_statement call identifier argument_list identifier identifier except_clause identifier block return_statement identifier | Apply injected logic for slicing reading lists with additional content. |
def seconds_to_time(x):
t = int(x * 10**6)
ms = t % 10**6
t = t // 10**6
s = t % 60
t = t // 60
m = t % 60
t = t // 60
h = t
return time(h, m, s, ms) | module function_definition identifier parameters identifier block expression_statement assignment identifier call identifier argument_list binary_operator identifier binary_operator integer integer expression_statement assignment identifier binary_operator identifier binary_operator integer integer expression_statement assignment identifier binary_operator identifier binary_operator integer integer expression_statement assignment identifier binary_operator identifier integer expression_statement assignment identifier binary_operator identifier integer expression_statement assignment identifier binary_operator identifier integer expression_statement assignment identifier binary_operator identifier integer expression_statement assignment identifier identifier return_statement call identifier argument_list identifier identifier identifier identifier | Convert a number of second into a time |
def update_portfolio(self):
if not self._dirty_portfolio:
return
portfolio = self._portfolio
pt = self.position_tracker
portfolio.positions = pt.get_positions()
position_stats = pt.stats
portfolio.positions_value = position_value = (
position_stats.net_value
)
portfolio.positions_exposure = position_stats.net_exposure
self._cash_flow(self._get_payout_total(pt.positions))
start_value = portfolio.portfolio_value
portfolio.portfolio_value = end_value = portfolio.cash + position_value
pnl = end_value - start_value
if start_value != 0:
returns = pnl / start_value
else:
returns = 0.0
portfolio.pnl += pnl
portfolio.returns = (
(1 + portfolio.returns) *
(1 + returns) -
1
)
self._dirty_portfolio = False | module function_definition identifier parameters identifier block if_statement not_operator attribute identifier identifier block return_statement expression_statement assignment identifier attribute identifier identifier expression_statement assignment identifier attribute identifier identifier expression_statement assignment attribute identifier identifier call attribute identifier identifier argument_list expression_statement assignment identifier attribute identifier identifier expression_statement assignment attribute identifier identifier assignment identifier parenthesized_expression attribute identifier identifier expression_statement assignment attribute identifier identifier attribute identifier identifier expression_statement call attribute identifier identifier argument_list call attribute identifier identifier argument_list attribute identifier identifier expression_statement assignment identifier attribute identifier identifier expression_statement assignment attribute identifier identifier assignment identifier binary_operator attribute identifier identifier identifier expression_statement assignment identifier binary_operator identifier identifier if_statement comparison_operator identifier integer block expression_statement assignment identifier binary_operator identifier identifier else_clause block expression_statement assignment identifier float expression_statement augmented_assignment attribute identifier identifier identifier expression_statement assignment attribute identifier identifier parenthesized_expression binary_operator binary_operator parenthesized_expression binary_operator integer attribute identifier identifier parenthesized_expression binary_operator integer identifier integer expression_statement assignment attribute identifier identifier false | Force a computation of the current portfolio state. |
def _connect_to_rabbitmq(self):
global pending_rabbitmq_connection, rabbitmq_connection
if not rabbitmq_connection:
LOGGER.info('Creating a new RabbitMQ connection')
pending_rabbitmq_connection = self._new_rabbitmq_connection() | module function_definition identifier parameters identifier block global_statement identifier identifier if_statement not_operator identifier block expression_statement call attribute identifier identifier argument_list string string_start string_content string_end expression_statement assignment identifier call attribute identifier identifier argument_list | Connect to RabbitMQ and assign a local attribute |
def _graph_reduction(adj, x, g, f):
as_list = set()
as_nodes = {v for v in adj if len(adj[v]) <= f and is_almost_simplicial(adj, v)}
while as_nodes:
as_list.union(as_nodes)
for n in as_nodes:
dv = len(adj[n])
if dv > g:
g = dv
if g > f:
f = g
x.append(n)
_elim_adj(adj, n)
as_nodes = {v for v in adj if len(adj[v]) <= f and is_almost_simplicial(adj, v)}
return g, f, as_list | module function_definition identifier parameters identifier identifier identifier identifier block expression_statement assignment identifier call identifier argument_list expression_statement assignment identifier set_comprehension identifier for_in_clause identifier identifier if_clause boolean_operator comparison_operator call identifier argument_list subscript identifier identifier identifier call identifier argument_list identifier identifier while_statement identifier block expression_statement call attribute identifier identifier argument_list identifier for_statement identifier identifier block expression_statement assignment identifier call identifier argument_list subscript identifier identifier if_statement comparison_operator identifier identifier block expression_statement assignment identifier identifier if_statement comparison_operator identifier identifier block expression_statement assignment identifier identifier expression_statement call attribute identifier identifier argument_list identifier expression_statement call identifier argument_list identifier identifier expression_statement assignment identifier set_comprehension identifier for_in_clause identifier identifier if_clause boolean_operator comparison_operator call identifier argument_list subscript identifier identifier identifier call identifier argument_list identifier identifier return_statement expression_list identifier identifier identifier | we can go ahead and remove any simplicial or almost-simplicial vertices from adj. |
def add_membership(self, user, role):
targetGroup = AuthGroup.objects(role=role, creator=self.client).first()
if not targetGroup:
return False
target = AuthMembership.objects(user=user, creator=self.client).first()
if not target:
target = AuthMembership(user=user, creator=self.client)
if not role in [i.role for i in target.groups]:
target.groups.append(targetGroup)
target.save()
return True | module function_definition identifier parameters identifier identifier identifier block expression_statement assignment identifier call attribute call attribute identifier identifier argument_list keyword_argument identifier identifier keyword_argument identifier attribute identifier identifier identifier argument_list if_statement not_operator identifier block return_statement false expression_statement assignment identifier call attribute call attribute identifier identifier argument_list keyword_argument identifier identifier keyword_argument identifier attribute identifier identifier identifier argument_list if_statement not_operator identifier block expression_statement assignment identifier call identifier argument_list keyword_argument identifier identifier keyword_argument identifier attribute identifier identifier if_statement not_operator comparison_operator identifier list_comprehension attribute identifier identifier for_in_clause identifier attribute identifier identifier block expression_statement call attribute attribute identifier identifier identifier argument_list identifier expression_statement call attribute identifier identifier argument_list return_statement true | make user a member of a group |
def remove_xml_element_string(name, content):
ET.register_namespace("", "http://soap.sforce.com/2006/04/metadata")
tree = ET.fromstring(content)
tree = remove_xml_element(name, tree)
clean_content = ET.tostring(tree, encoding=UTF8)
return clean_content | module function_definition identifier parameters identifier identifier block expression_statement call attribute identifier identifier argument_list string string_start string_end string string_start string_content string_end expression_statement assignment identifier call attribute identifier identifier argument_list identifier expression_statement assignment identifier call identifier argument_list identifier identifier expression_statement assignment identifier call attribute identifier identifier argument_list identifier keyword_argument identifier identifier return_statement identifier | Remove XML elements from a string |
async def send_command(self, command):
_LOGGER.debug("Sending command to projector %s", command)
if self.__checkLock():
return False
self.__setLock(command)
response = await self.send_request(
timeout=self.__get_timeout(command),
params=EPSON_KEY_COMMANDS[command],
type='directsend',
command=command)
return response | module function_definition identifier parameters identifier identifier block expression_statement call attribute identifier identifier argument_list string string_start string_content string_end identifier if_statement call attribute identifier identifier argument_list block return_statement false expression_statement call attribute identifier identifier argument_list identifier expression_statement assignment identifier await call attribute identifier identifier argument_list keyword_argument identifier call attribute identifier identifier argument_list identifier keyword_argument identifier subscript identifier identifier keyword_argument identifier string string_start string_content string_end keyword_argument identifier identifier return_statement identifier | Send command to Epson. |
def add_edge(self, u, v, key=None, attr_dict=None, **attr):
if attr_dict is None:
attr_dict = attr
else:
try:
attr_dict.update(attr)
except AttributeError:
raise NetworkXError(
"The attr_dict argument must be a dictionary."
)
if u not in self.node:
self.node[u] = {}
if v not in self.node:
self.node[v] = {}
if v in self.succ[u]:
keydict = self.adj[u][v]
if key is None:
key = len(keydict)
while key in keydict:
key += 1
datadict = keydict.get(key, {})
datadict.update(attr_dict)
keydict[key] = datadict
else:
if key is None:
key = 0
datadict = {}
datadict.update(attr_dict)
keydict = {key: datadict}
self.succ[u][v] = keydict
return key | module function_definition identifier parameters identifier identifier identifier default_parameter identifier none default_parameter identifier none dictionary_splat_pattern identifier block if_statement comparison_operator identifier none block expression_statement assignment identifier identifier else_clause block try_statement block expression_statement call attribute identifier identifier argument_list identifier except_clause identifier block raise_statement call identifier argument_list string string_start string_content string_end if_statement comparison_operator identifier attribute identifier identifier block expression_statement assignment subscript attribute identifier identifier identifier dictionary if_statement comparison_operator identifier attribute identifier identifier block expression_statement assignment subscript attribute identifier identifier identifier dictionary if_statement comparison_operator identifier subscript attribute identifier identifier identifier block expression_statement assignment identifier subscript subscript attribute identifier identifier identifier identifier if_statement comparison_operator identifier none block expression_statement assignment identifier call identifier argument_list identifier while_statement comparison_operator identifier identifier block expression_statement augmented_assignment identifier integer expression_statement assignment identifier call attribute identifier identifier argument_list identifier dictionary expression_statement call attribute identifier identifier argument_list identifier expression_statement assignment subscript identifier identifier identifier else_clause block if_statement comparison_operator identifier none block expression_statement assignment identifier integer expression_statement assignment identifier dictionary expression_statement call attribute identifier identifier argument_list identifier expression_statement assignment identifier dictionary pair identifier identifier expression_statement assignment subscript subscript attribute identifier identifier identifier identifier identifier return_statement identifier | Version of add_edge that only writes to the database once. |
def assert_called_once(_mock_self):
self = _mock_self
if not self.call_count == 1:
msg = ("Expected '%s' to have been called once. Called %s times." %
(self._mock_name or 'mock', self.call_count))
raise AssertionError(msg) | module function_definition identifier parameters identifier block expression_statement assignment identifier identifier if_statement not_operator comparison_operator attribute identifier identifier integer block expression_statement assignment identifier parenthesized_expression binary_operator string string_start string_content string_end tuple boolean_operator attribute identifier identifier string string_start string_content string_end attribute identifier identifier raise_statement call identifier argument_list identifier | assert that the mock was called only once. |
def _getshapes_2d(center, max_radius, shape):
index_mean = shape * center
index_radius = max_radius / 2.0 * np.array(shape)
min_idx = np.maximum(np.floor(index_mean - index_radius), 0).astype(int)
max_idx = np.ceil(index_mean + index_radius).astype(int)
idx = [slice(minx, maxx) for minx, maxx in zip(min_idx, max_idx)]
shapes = [(idx[0], slice(None)),
(slice(None), idx[1])]
return tuple(idx), tuple(shapes) | module function_definition identifier parameters identifier identifier identifier block expression_statement assignment identifier binary_operator identifier identifier expression_statement assignment identifier binary_operator binary_operator identifier float call attribute identifier identifier argument_list identifier expression_statement assignment identifier call attribute call attribute identifier identifier argument_list call attribute identifier identifier argument_list binary_operator identifier identifier integer identifier argument_list identifier expression_statement assignment identifier call attribute call attribute identifier identifier argument_list binary_operator identifier identifier identifier argument_list identifier expression_statement assignment identifier list_comprehension call identifier argument_list identifier identifier for_in_clause pattern_list identifier identifier call identifier argument_list identifier identifier expression_statement assignment identifier list tuple subscript identifier integer call identifier argument_list none tuple call identifier argument_list none subscript identifier integer return_statement expression_list call identifier argument_list identifier call identifier argument_list identifier | Calculate indices and slices for the bounding box of a disk. |
def fill_in_by_selector(self, selector, value):
elem = find_element_by_jquery(world.browser, selector)
elem.clear()
elem.send_keys(value) | module function_definition identifier parameters identifier identifier identifier block expression_statement assignment identifier call identifier argument_list attribute identifier identifier identifier expression_statement call attribute identifier identifier argument_list expression_statement call attribute identifier identifier argument_list identifier | Fill in the form element matching the CSS selector. |
def _case_format(self, occur):
if self.occur == 1:
self.attr["nma:implicit"] = "true"
ccnt = len(self.rng_children())
if ccnt == 0: return "<empty/>%s"
if ccnt == 1 or not self.interleave:
return self.start_tag("group") + "%s" + self.end_tag("group")
return (self.start_tag("interleave") + "%s" +
self.end_tag("interleave")) | module function_definition identifier parameters identifier identifier block if_statement comparison_operator attribute identifier identifier integer block expression_statement assignment subscript attribute identifier identifier string string_start string_content string_end string string_start string_content string_end expression_statement assignment identifier call identifier argument_list call attribute identifier identifier argument_list if_statement comparison_operator identifier integer block return_statement string string_start string_content string_end if_statement boolean_operator comparison_operator identifier integer not_operator attribute identifier identifier block return_statement binary_operator binary_operator call attribute identifier identifier argument_list string string_start string_content string_end string string_start string_content string_end call attribute identifier identifier argument_list string string_start string_content string_end return_statement parenthesized_expression binary_operator binary_operator call attribute identifier identifier argument_list string string_start string_content string_end string string_start string_content string_end call attribute identifier identifier argument_list string string_start string_content string_end | Return the serialization format for a case node. |
def session(self):
if self._session is None:
from .tcex_session import TcExSession
self._session = TcExSession(self)
return self._session | module function_definition identifier parameters identifier block if_statement comparison_operator attribute identifier identifier none block import_from_statement relative_import import_prefix dotted_name identifier dotted_name identifier expression_statement assignment attribute identifier identifier call identifier argument_list identifier return_statement attribute identifier identifier | Return an instance of Requests Session configured for the ThreatConnect API. |
def single_case(self, i, case):
if self.single_stack:
self.single_stack.pop()
self.single_stack.append(case)
try:
t = next(i)
if self.use_format and t in _CURLY_BRACKETS:
self.handle_format(t, i)
elif t == '\\':
try:
t = next(i)
self.reference(t, i)
except StopIteration:
self.result.append(t)
raise
elif self.single_stack:
self.result.append(self.convert_case(t, self.get_single_stack()))
except StopIteration:
pass | module function_definition identifier parameters identifier identifier identifier block if_statement attribute identifier identifier block expression_statement call attribute attribute identifier identifier identifier argument_list expression_statement call attribute attribute identifier identifier identifier argument_list identifier try_statement block expression_statement assignment identifier call identifier argument_list identifier if_statement boolean_operator attribute identifier identifier comparison_operator identifier identifier block expression_statement call attribute identifier identifier argument_list identifier identifier elif_clause comparison_operator identifier string string_start string_content escape_sequence string_end block try_statement block expression_statement assignment identifier call identifier argument_list identifier expression_statement call attribute identifier identifier argument_list identifier identifier except_clause identifier block expression_statement call attribute attribute identifier identifier identifier argument_list identifier raise_statement elif_clause attribute identifier identifier block expression_statement call attribute attribute identifier identifier identifier argument_list call attribute identifier identifier argument_list identifier call attribute identifier identifier argument_list except_clause identifier block pass_statement | Uppercase or lowercase the next character. |
def new(self, node: Node):
return Property(self.name, self._setter, node) | module function_definition identifier parameters identifier typed_parameter identifier type identifier block return_statement call identifier argument_list attribute identifier identifier attribute identifier identifier identifier | Creates property for node |
def create_event_object(self,
event_type,
code,
value,
timeval=None):
if not timeval:
timeval = self.__get_timeval()
try:
event_code = self.manager.codes['type_codes'][event_type]
except KeyError:
raise UnknownEventType(
"We don't know what kind of event a %s is." % event_type)
event = struct.pack(EVENT_FORMAT,
timeval[0],
timeval[1],
event_code,
code,
value)
return event | module function_definition identifier parameters identifier identifier identifier identifier default_parameter identifier none block if_statement not_operator identifier block expression_statement assignment identifier call attribute identifier identifier argument_list try_statement block expression_statement assignment identifier subscript subscript attribute attribute identifier identifier identifier string string_start string_content string_end identifier except_clause identifier block raise_statement call identifier argument_list binary_operator string string_start string_content string_end identifier expression_statement assignment identifier call attribute identifier identifier argument_list identifier subscript identifier integer subscript identifier integer identifier identifier identifier return_statement identifier | Create an evdev style object. |
def cross_correlate(self, templates, **kwargs):
if isinstance(templates, (Spectrum1D, )):
template_dispersion = templates.disp
template_fluxes = templates.flux
else:
template_dispersion = templates[0]
template_fluxes = templates[1]
return _cross_correlate(self, template_dispersion, template_fluxes,
**kwargs) | module function_definition identifier parameters identifier identifier dictionary_splat_pattern identifier block if_statement call identifier argument_list identifier tuple identifier block expression_statement assignment identifier attribute identifier identifier expression_statement assignment identifier attribute identifier identifier else_clause block expression_statement assignment identifier subscript identifier integer expression_statement assignment identifier subscript identifier integer return_statement call identifier argument_list identifier identifier identifier dictionary_splat identifier | Cross correlate the spectrum against a set of templates. |
def retrieve_dcnm_subnet_info(self, tenant_id, direc):
serv_obj = self.get_service_obj(tenant_id)
subnet_dict = serv_obj.get_dcnm_subnet_dict(direc)
return subnet_dict | module function_definition identifier parameters identifier 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 return_statement identifier | Retrieves the DCNM subnet info for a tenant. |
def teardown(self):
self.log.debug('teardown: in')
self.running = False
self.shutdown_server()
shutil.rmtree(self.tmp_diff_folder, ignore_errors=True) | module function_definition identifier parameters identifier block expression_statement call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end expression_statement assignment attribute identifier identifier false expression_statement call attribute identifier identifier argument_list expression_statement call attribute identifier identifier argument_list attribute identifier identifier keyword_argument identifier true | Tear down the server or keep it alive. |
def length_limits(max_length_limit, length_limit_step):
string_len = len(str(max_length_limit))
return [
str(i).zfill(string_len) for i in
xrange(
length_limit_step,
max_length_limit + length_limit_step - 1,
length_limit_step
)
] | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call identifier argument_list call identifier argument_list identifier return_statement list_comprehension call attribute call identifier argument_list identifier identifier argument_list identifier for_in_clause identifier call identifier argument_list identifier binary_operator binary_operator identifier identifier integer identifier | Generates the length limits |
def cpp_prog_builder(build_context, target):
yprint(build_context.conf, 'Build CppProg', target)
workspace_dir = build_context.get_workspace('CppProg', target.name)
build_cpp(build_context, target, target.compiler_config, workspace_dir) | module function_definition identifier parameters identifier identifier block expression_statement call identifier argument_list attribute identifier identifier string string_start string_content string_end identifier expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end attribute identifier identifier expression_statement call identifier argument_list identifier identifier attribute identifier identifier identifier | Build a C++ binary executable |
def main():
args = parse_args()
config_logger(args)
logger = structlog.get_logger(__name__)
if args.show_version:
print_version()
sys.exit(0)
version = pkg_resources.get_distribution('lander').version
logger.info('Lander version {0}'.format(version))
config = Configuration(args=args)
if config['is_travis_pull_request']:
logger.info('Skipping build from PR.')
sys.exit(0)
lander = Lander(config)
lander.build_site()
logger.info('Build complete')
if config['upload']:
lander.upload_site()
logger.info('Upload complete')
logger.info('Lander complete') | module function_definition identifier parameters block expression_statement assignment identifier call identifier argument_list expression_statement call identifier argument_list identifier expression_statement assignment identifier call attribute identifier identifier argument_list identifier if_statement attribute identifier identifier block expression_statement call identifier argument_list expression_statement call attribute identifier identifier argument_list integer expression_statement assignment identifier attribute call attribute identifier identifier argument_list string string_start string_content string_end identifier expression_statement call attribute identifier identifier argument_list call attribute string string_start string_content string_end identifier argument_list identifier expression_statement assignment identifier call identifier argument_list keyword_argument identifier identifier if_statement subscript identifier string string_start string_content string_end block expression_statement call attribute identifier identifier argument_list string string_start string_content string_end expression_statement call attribute identifier identifier argument_list integer expression_statement assignment identifier call identifier argument_list identifier expression_statement call attribute identifier identifier argument_list expression_statement call attribute identifier identifier argument_list string string_start string_content string_end if_statement subscript identifier string string_start string_content string_end block expression_statement call attribute identifier identifier argument_list 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 | Entrypoint for ``lander`` executable. |
def read_footer(filename):
with open(filename, 'rb') as file_obj:
if not _check_header_magic_bytes(file_obj) or \
not _check_footer_magic_bytes(file_obj):
raise ParquetFormatException("{0} is not a valid parquet file "
"(missing magic bytes)"
.format(filename))
return _read_footer(file_obj) | module function_definition identifier parameters identifier block with_statement with_clause with_item as_pattern call identifier argument_list identifier string string_start string_content string_end as_pattern_target identifier block if_statement boolean_operator not_operator call identifier argument_list identifier line_continuation not_operator call identifier argument_list identifier block raise_statement call 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 call identifier argument_list identifier | Read the footer and return the FileMetaData for the specified filename. |
def write(self):
dumped = self._fax.codec.dump(self.__state, open(self.state_file, 'w')) | module function_definition identifier parameters identifier block expression_statement assignment identifier call attribute attribute attribute identifier identifier identifier identifier argument_list attribute identifier identifier call identifier argument_list attribute identifier identifier string string_start string_content string_end | write all needed state info to filesystem |
def ratio_and_percentage_with_time_remaining(current, total, time_remaining):
return "{} / {} ({}% completed) (~{} remaining)".format(
current,
total,
int(current / total * 100),
time_remaining) | module function_definition identifier parameters identifier identifier identifier block return_statement call attribute string string_start string_content string_end identifier argument_list identifier identifier call identifier argument_list binary_operator binary_operator identifier identifier integer identifier | Returns the progress ratio, percentage and time remaining. |
def _round_half_hour(record):
k = record.datetime + timedelta(minutes=-(record.datetime.minute % 30))
return datetime(k.year, k.month, k.day, k.hour, k.minute, 0) | module function_definition identifier parameters identifier block expression_statement assignment identifier binary_operator attribute identifier identifier call identifier argument_list keyword_argument identifier unary_operator parenthesized_expression binary_operator attribute attribute identifier identifier identifier integer return_statement call identifier argument_list attribute identifier identifier attribute identifier identifier attribute identifier identifier attribute identifier identifier attribute identifier identifier integer | Round a time DOWN to half nearest half-hour. |
def list_loadbalancers(self, retrieve_all=True, **_params):
return self.list('loadbalancers', self.lbaas_loadbalancers_path,
retrieve_all, **_params) | module function_definition identifier parameters identifier default_parameter identifier true dictionary_splat_pattern identifier block return_statement call attribute identifier identifier argument_list string string_start string_content string_end attribute identifier identifier identifier dictionary_splat identifier | Fetches a list of all loadbalancers for a project. |
def flush(self):
if self._cache_modified_count > 0:
self.storage.write(self.cache)
self._cache_modified_count = 0 | module function_definition identifier parameters identifier block if_statement comparison_operator attribute identifier identifier integer block expression_statement call attribute attribute identifier identifier identifier argument_list attribute identifier identifier expression_statement assignment attribute identifier identifier integer | Flush all unwritten data to disk. |
def check_keyname(self, rule):
keynames = rule.get('keynames')
if not keynames:
self.logdebug('no keynames requirement.\n')
return True
if not isinstance(keynames, list):
keynames = [keynames]
if self.keyname in keynames:
self.logdebug('keyname "%s" matches rule.\n' % self.keyname)
return True
else:
self.logdebug('keyname "%s" does not match rule.\n' % self.keyname)
return False | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end if_statement not_operator identifier block expression_statement call attribute identifier identifier argument_list string string_start string_content escape_sequence string_end return_statement true if_statement not_operator call identifier argument_list identifier identifier block expression_statement assignment identifier list identifier if_statement comparison_operator attribute identifier identifier identifier block expression_statement call attribute identifier identifier argument_list binary_operator string string_start string_content escape_sequence string_end attribute identifier identifier return_statement true else_clause block expression_statement call attribute identifier identifier argument_list binary_operator string string_start string_content escape_sequence string_end attribute identifier identifier return_statement false | If a key name is specified, verify it is permitted. |
async def _on_rpc_command(self, event):
payload = event['payload']
rpc_id = payload['rpc_id']
tag = payload['response_uuid']
args = payload['payload']
result = 'success'
response = b''
if self._rpc_dispatcher is None or not self._rpc_dispatcher.has_rpc(rpc_id):
result = 'rpc_not_found'
else:
try:
response = self._rpc_dispatcher.call_rpc(rpc_id, args)
if inspect.iscoroutine(response):
response = await response
except RPCInvalidArgumentsError:
result = 'invalid_arguments'
except RPCInvalidReturnValueError:
result = 'invalid_response'
except Exception:
self._logger.exception("Exception handling RPC 0x%04X", rpc_id)
result = 'execution_exception'
message = dict(response_uuid=tag, result=result, response=response)
try:
await self.send_command(OPERATIONS.CMD_RESPOND_RPC, message,
MESSAGES.RespondRPCResponse)
except:
self._logger.exception("Error sending response to RPC 0x%04X", rpc_id) | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier subscript identifier string string_start string_content string_end expression_statement assignment identifier subscript identifier string string_start string_content string_end expression_statement assignment identifier subscript identifier string string_start string_content string_end expression_statement assignment identifier subscript identifier string string_start string_content string_end expression_statement assignment identifier string string_start string_content string_end expression_statement assignment identifier string string_start string_end if_statement boolean_operator comparison_operator attribute identifier identifier none not_operator call attribute attribute identifier identifier identifier argument_list identifier block expression_statement assignment identifier string string_start string_content string_end else_clause block try_statement block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list identifier identifier if_statement call attribute identifier identifier argument_list identifier block expression_statement assignment identifier await identifier except_clause identifier block expression_statement assignment identifier string string_start string_content string_end except_clause identifier block expression_statement assignment identifier string string_start string_content string_end except_clause identifier block expression_statement call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end identifier expression_statement assignment identifier string string_start string_content string_end expression_statement assignment identifier call identifier argument_list keyword_argument identifier identifier keyword_argument identifier identifier keyword_argument identifier identifier try_statement block expression_statement await call attribute identifier identifier argument_list attribute identifier identifier identifier attribute identifier identifier except_clause block expression_statement call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end identifier | Received an RPC command that we should execute. |
def _update_names(self):
d = dict(
table=self.table_name,
time=self.time,
space=self.space,
grain=self.grain,
variant=self.variant,
segment=self.segment
)
assert self.dataset
name = PartialPartitionName(**d).promote(self.dataset.identity.name)
self.name = str(name.name)
self.vname = str(name.vname)
self.cache_key = name.cache_key
self.fqname = str(self.identity.fqname) | module function_definition identifier parameters identifier block expression_statement assignment identifier call identifier argument_list keyword_argument identifier attribute identifier identifier keyword_argument identifier attribute identifier identifier keyword_argument identifier attribute identifier identifier keyword_argument identifier attribute identifier identifier keyword_argument identifier attribute identifier identifier keyword_argument identifier attribute identifier identifier assert_statement attribute identifier identifier expression_statement assignment identifier call attribute call identifier argument_list dictionary_splat identifier identifier argument_list attribute attribute attribute identifier identifier identifier identifier expression_statement assignment attribute identifier identifier call identifier argument_list attribute identifier identifier expression_statement assignment attribute identifier identifier call identifier argument_list attribute identifier identifier expression_statement assignment attribute identifier identifier attribute identifier identifier expression_statement assignment attribute identifier identifier call identifier argument_list attribute attribute identifier identifier identifier | Update the derived names |
def detect_converters(pattern: str,
converter_dict: Dict[str, Callable],
default: Callable = str):
converters = {}
for matched in VARS_PT.finditer(pattern):
matchdict = matched.groupdict()
varname = matchdict['varname']
converter = matchdict['converter']
converters[varname] = converter_dict.get(converter, default)
return converters | module function_definition identifier parameters typed_parameter identifier type identifier typed_parameter identifier type generic_type identifier type_parameter type identifier type identifier typed_default_parameter identifier type identifier identifier block expression_statement assignment identifier dictionary for_statement identifier call attribute identifier identifier argument_list identifier block expression_statement assignment identifier call attribute identifier identifier argument_list expression_statement assignment identifier subscript identifier string string_start string_content string_end expression_statement assignment identifier subscript identifier string string_start string_content string_end expression_statement assignment subscript identifier identifier call attribute identifier identifier argument_list identifier identifier return_statement identifier | detect pairs of varname and converter from pattern |
def first_setup(self):
if ATTR_FIRST_SETUP not in self.raw:
return None
return datetime.utcfromtimestamp(self.raw[ATTR_FIRST_SETUP]) | module function_definition identifier parameters identifier block if_statement comparison_operator identifier attribute identifier identifier block return_statement none return_statement call attribute identifier identifier argument_list subscript attribute identifier identifier identifier | This is a guess of the meaning of this value. |
def expr2dimacscnf(ex):
litmap, nvars, clauses = ex.encode_cnf()
return litmap, DimacsCNF(nvars, clauses) | module function_definition identifier parameters identifier block expression_statement assignment pattern_list identifier identifier identifier call attribute identifier identifier argument_list return_statement expression_list identifier call identifier argument_list identifier identifier | Convert an expression into an equivalent DIMACS CNF. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.