code stringlengths 51 2.34k | sequence stringlengths 186 3.94k | docstring stringlengths 11 171 |
|---|---|---|
def getProfileImage(self, name):
for p in self.persons:
if 'pseudo' in self.persons[p]:
if name == self.persons[p]['pseudo']:
image_id = self.persons[p]['face']['id']
key = self.persons[p]['face']['key']
return self.getCameraPicture(image_id, key)
return None, None | module function_definition identifier parameters identifier identifier block for_statement identifier attribute identifier identifier block if_statement comparison_operator string string_start string_content string_end subscript attribute identifier identifier identifier block if_statement comparison_operator identifier subscript subscript attribute identifier identifier identifier string string_start string_content string_end block expression_statement assignment identifier subscript subscript subscript attribute identifier identifier identifier string string_start string_content string_end string string_start string_content string_end expression_statement assignment identifier subscript subscript subscript attribute identifier identifier identifier string string_start string_content string_end string string_start string_content string_end return_statement call attribute identifier identifier argument_list identifier identifier return_statement expression_list none none | Retrieve the face of a given person |
def load_average(self):
with io.open(self.load_average_file, 'r') as f:
file_columns = f.readline().strip().split()
return float(file_columns[self._load_average_file_column]) | module function_definition identifier parameters identifier block with_statement with_clause with_item as_pattern call attribute identifier identifier argument_list attribute identifier identifier string string_start string_content string_end as_pattern_target identifier block expression_statement assignment identifier call attribute call attribute call attribute identifier identifier argument_list identifier argument_list identifier argument_list return_statement call identifier argument_list subscript identifier attribute identifier identifier | Returns the current load average. |
def boltzmann_exploration(actions, utilities, temperature, action_counter):
utilities = [utilities[x] for x in actions]
temperature = max(temperature, 0.01)
_max = max(utilities)
_min = min(utilities)
if _max == _min:
return random.choice(actions)
utilities = [math.exp(((u - _min) / (_max - _min)) / temperature) for u in utilities]
probs = [u / sum(utilities) for u in utilities]
i = 0
tot = probs[i]
r = random.random()
while i < len(actions) and r >= tot:
i += 1
tot += probs[i]
return actions[i] | module function_definition identifier parameters identifier identifier identifier identifier block expression_statement assignment identifier list_comprehension subscript identifier identifier for_in_clause identifier identifier expression_statement assignment identifier call identifier argument_list identifier float expression_statement assignment identifier call identifier argument_list identifier expression_statement assignment identifier call identifier argument_list identifier if_statement comparison_operator identifier identifier block return_statement call attribute identifier identifier argument_list identifier expression_statement assignment identifier list_comprehension call attribute identifier identifier argument_list binary_operator parenthesized_expression binary_operator parenthesized_expression binary_operator identifier identifier parenthesized_expression binary_operator identifier identifier identifier for_in_clause identifier identifier expression_statement assignment identifier list_comprehension binary_operator identifier call identifier argument_list identifier for_in_clause identifier identifier expression_statement assignment identifier integer expression_statement assignment identifier subscript identifier identifier expression_statement assignment identifier call attribute identifier identifier argument_list while_statement boolean_operator comparison_operator identifier call identifier argument_list identifier comparison_operator identifier identifier block expression_statement augmented_assignment identifier integer expression_statement augmented_assignment identifier subscript identifier identifier return_statement subscript identifier identifier | returns an action with a probability depending on utilities and temperature |
def _parse(res, params, n, api, **kwds):
cursor = "cursor" in params
if not cursor:
start = params["start"]
if n == 0:
return ""
_json = res.get('search-results', {}).get('entry', [])
while n > 0:
n -= params["count"]
if cursor:
pointer = res['search-results']['cursor'].get('@next')
params.update({'cursor': pointer})
else:
start += params["count"]
params.update({'start': start})
res = download(url=URL[api], params=params, accept="json", **kwds).json()
_json.extend(res.get('search-results', {}).get('entry', []))
return _json | module function_definition identifier parameters identifier identifier identifier identifier dictionary_splat_pattern identifier block expression_statement assignment identifier comparison_operator string string_start string_content string_end identifier if_statement not_operator identifier block expression_statement assignment identifier subscript identifier string string_start string_content string_end if_statement comparison_operator identifier integer block return_statement string string_start string_end expression_statement assignment identifier call attribute call attribute identifier identifier argument_list string string_start string_content string_end dictionary identifier argument_list string string_start string_content string_end list while_statement comparison_operator identifier integer block expression_statement augmented_assignment identifier subscript identifier string string_start string_content string_end if_statement identifier block expression_statement assignment identifier call attribute subscript subscript identifier string string_start string_content string_end string string_start string_content string_end identifier argument_list string string_start string_content string_end expression_statement call attribute identifier identifier argument_list dictionary pair string string_start string_content string_end identifier else_clause block expression_statement augmented_assignment identifier subscript identifier string string_start string_content string_end expression_statement call attribute identifier identifier argument_list dictionary pair string string_start string_content string_end identifier expression_statement assignment identifier call attribute call identifier argument_list keyword_argument identifier subscript identifier identifier keyword_argument identifier identifier keyword_argument identifier string string_start string_content string_end dictionary_splat identifier identifier argument_list expression_statement call attribute identifier identifier argument_list call attribute call attribute identifier identifier argument_list string string_start string_content string_end dictionary identifier argument_list string string_start string_content string_end list return_statement identifier | Auxiliary function to download results and parse json. |
def _do_digest(data, func):
func = FuncReg.get(func)
hash = FuncReg.hash_from_func(func)
if not hash:
raise ValueError("no available hash function for hash", func)
hash.update(data)
return bytes(hash.digest()) | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list identifier expression_statement assignment identifier call attribute identifier identifier argument_list identifier if_statement not_operator identifier block raise_statement call identifier argument_list string string_start string_content string_end identifier expression_statement call attribute identifier identifier argument_list identifier return_statement call identifier argument_list call attribute identifier identifier argument_list | Return the binary digest of `data` with the given `func`. |
def sendcommand(self, name, **kwargs):
self.log("sending command %s(**%s)" % (name, kwargs))
self.channel.send((name, kwargs)) | module function_definition identifier parameters identifier identifier dictionary_splat_pattern identifier block expression_statement call attribute identifier identifier argument_list binary_operator string string_start string_content string_end tuple identifier identifier expression_statement call attribute attribute identifier identifier identifier argument_list tuple identifier identifier | send a named parametrized command to the other side. |
def _get_all_run_infos(self):
info_dir = self._settings.info_dir
if not os.path.isdir(info_dir):
return []
paths = [os.path.join(info_dir, x) for x in os.listdir(info_dir)]
return [d for d in
[RunInfo(os.path.join(p, 'info')).get_as_dict() for p in paths
if os.path.isdir(p) and not os.path.islink(p)]
if 'timestamp' in d] | module function_definition identifier parameters identifier block expression_statement assignment identifier attribute attribute identifier identifier identifier if_statement not_operator call attribute attribute identifier identifier identifier argument_list identifier block return_statement list expression_statement assignment identifier list_comprehension call attribute attribute identifier identifier identifier argument_list identifier identifier for_in_clause identifier call attribute identifier identifier argument_list identifier return_statement list_comprehension identifier for_in_clause identifier list_comprehension call attribute call identifier argument_list call attribute attribute identifier identifier identifier argument_list identifier string string_start string_content string_end identifier argument_list for_in_clause identifier identifier if_clause boolean_operator call attribute attribute identifier identifier identifier argument_list identifier not_operator call attribute attribute identifier identifier identifier argument_list identifier if_clause comparison_operator string string_start string_content string_end identifier | Find the RunInfos for all runs since the last clean-all. |
def detect_language(lang, kernel_source):
if lang is None:
if callable(kernel_source):
raise TypeError("Please specify language when using a code generator function")
kernel_string = get_kernel_string(kernel_source)
if "__global__" in kernel_string:
lang = "CUDA"
elif "__kernel" in kernel_string:
lang = "OpenCL"
else:
lang = "C"
return lang | module function_definition identifier parameters identifier identifier block if_statement comparison_operator identifier none block if_statement call identifier argument_list identifier block raise_statement call identifier argument_list string string_start string_content string_end expression_statement assignment identifier call identifier argument_list identifier if_statement comparison_operator string string_start string_content string_end identifier block expression_statement assignment identifier string string_start string_content string_end elif_clause comparison_operator string string_start string_content string_end identifier block expression_statement assignment identifier string string_start string_content string_end else_clause block expression_statement assignment identifier string string_start string_content string_end return_statement identifier | attempt to detect language from the kernel_string if not specified |
def initialize_environment(app):
env = app.builder.env
if not hasattr(env, 'traceability_all_items'):
env.traceability_all_items = {}
update_available_item_relationships(app) | module function_definition identifier parameters identifier block expression_statement assignment identifier attribute attribute identifier identifier identifier if_statement not_operator call identifier argument_list identifier string string_start string_content string_end block expression_statement assignment attribute identifier identifier dictionary expression_statement call identifier argument_list identifier | Perform initializations needed before the build process starts. |
def _create_node(self, name, factory, directory=None, create=1):
import SCons.Util
node = factory(name, directory, create)
node.set_noclean(self.noclean)
node.set_precious(self.precious)
if self.nodefault:
self.env.Ignore('.', node)
if self.alias:
self.env.AlwaysBuild(self.env.Alias(self.alias, node))
return node | module function_definition identifier parameters identifier identifier identifier default_parameter identifier none default_parameter identifier integer block import_statement dotted_name identifier identifier expression_statement assignment identifier call identifier argument_list identifier identifier identifier expression_statement call attribute identifier identifier argument_list attribute identifier identifier expression_statement call attribute identifier identifier argument_list attribute identifier identifier if_statement attribute identifier identifier block expression_statement call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end identifier if_statement attribute identifier identifier block expression_statement call attribute attribute identifier identifier identifier argument_list call attribute attribute identifier identifier identifier argument_list attribute identifier identifier identifier return_statement identifier | Create node, and set it up to factory settings. |
def contains(self, location):
return self.almostEqual(
sum([coord ** 2 for coord in location]), self.radius ** 2
) | module function_definition identifier parameters identifier identifier block return_statement call attribute identifier identifier argument_list call identifier argument_list list_comprehension binary_operator identifier integer for_in_clause identifier identifier binary_operator attribute identifier identifier integer | Checks that the provided point is on the sphere. |
def read_existing_paths(bt_table):
rows = bt_table.read_rows(
filter_=row_filters.ColumnRangeFilter(
METADATA, SGF_FILENAME, SGF_FILENAME))
names = (row.cell_value(METADATA, SGF_FILENAME).decode() for row in rows)
processed = [os.path.splitext(os.path.basename(r))[0] for r in names]
return processed | module function_definition identifier parameters identifier block expression_statement assignment identifier call attribute identifier identifier argument_list keyword_argument identifier call attribute identifier identifier argument_list identifier identifier identifier expression_statement assignment identifier generator_expression call attribute call attribute identifier identifier argument_list identifier identifier identifier argument_list for_in_clause identifier identifier expression_statement assignment identifier list_comprehension subscript call attribute attribute identifier identifier identifier argument_list call attribute attribute identifier identifier identifier argument_list identifier integer for_in_clause identifier identifier return_statement identifier | Return the SGF filename for each existing eval record. |
def save_legislators(legislators, destination):
logger.info("Saving Legislators To: {0}".format(destination))
legislators.to_csv("{0}/legislators.csv".format(destination),
encoding='utf-8') | module function_definition identifier parameters identifier identifier block expression_statement call attribute identifier identifier argument_list call attribute string string_start string_content string_end identifier argument_list identifier expression_statement call attribute identifier identifier argument_list call attribute string string_start string_content string_end identifier argument_list identifier keyword_argument identifier string string_start string_content string_end | Output legislators datafrom to csv. |
def fetch_libzmq(savedir):
dest = pjoin(savedir, 'zeromq')
if os.path.exists(dest):
info("already have %s" % dest)
return
path = fetch_archive(savedir, libzmq_url, fname=libzmq, checksum=libzmq_checksum)
tf = tarfile.open(path)
with_version = pjoin(savedir, tf.firstmember.path)
tf.extractall(savedir)
tf.close()
shutil.move(with_version, dest) | module function_definition identifier parameters identifier block expression_statement assignment identifier call identifier argument_list identifier string string_start string_content string_end if_statement call attribute attribute identifier identifier identifier argument_list identifier block expression_statement call identifier argument_list binary_operator string string_start string_content string_end identifier return_statement expression_statement assignment identifier call identifier argument_list identifier identifier keyword_argument identifier identifier keyword_argument identifier identifier expression_statement assignment identifier call attribute identifier identifier argument_list identifier expression_statement assignment identifier call identifier argument_list identifier attribute attribute identifier identifier identifier expression_statement call attribute identifier identifier argument_list identifier expression_statement call attribute identifier identifier argument_list expression_statement call attribute identifier identifier argument_list identifier identifier | download and extract libzmq |
def _getitem(self, index):
row = self._records[index]
if row is not None:
pass
elif self.is_attached():
if index < 0:
index = len(self._records) + index
row = next((decode_row(line)
for i, line in self._enum_lines()
if i == index),
None)
if row is None:
raise ItsdbError('could not retrieve row in attached table')
else:
raise ItsdbError('invalid row in detached table: {}'.format(index))
return Record._make(self.fields, row, self, index) | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier subscript attribute identifier identifier identifier if_statement comparison_operator identifier none block pass_statement elif_clause call attribute identifier identifier argument_list block if_statement comparison_operator identifier integer block expression_statement assignment identifier binary_operator call identifier argument_list attribute identifier identifier identifier expression_statement assignment identifier call identifier argument_list generator_expression call identifier argument_list identifier for_in_clause pattern_list identifier identifier call attribute identifier identifier argument_list if_clause comparison_operator identifier identifier none if_statement comparison_operator identifier none block raise_statement call identifier argument_list string string_start string_content string_end else_clause block raise_statement call identifier argument_list call attribute string string_start string_content string_end identifier argument_list identifier return_statement call attribute identifier identifier argument_list attribute identifier identifier identifier identifier identifier | Get a single non-slice index. |
def visit_Module(self, node):
duc = SilentDefUseChains()
duc.visit(node)
for d in duc.locals[node]:
self.result[d.name()] = d.node | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call identifier argument_list expression_statement call attribute identifier identifier argument_list identifier for_statement identifier subscript attribute identifier identifier identifier block expression_statement assignment subscript attribute identifier identifier call attribute identifier identifier argument_list attribute identifier identifier | Import module define a new variable name. |
def canonicalize_edge(edge_data: EdgeData) -> Tuple[str, Optional[Tuple], Optional[Tuple]]:
return (
edge_data[RELATION],
_canonicalize_edge_modifications(edge_data.get(SUBJECT)),
_canonicalize_edge_modifications(edge_data.get(OBJECT)),
) | module function_definition identifier parameters typed_parameter identifier type identifier type generic_type identifier type_parameter type identifier type generic_type identifier type_parameter type identifier type generic_type identifier type_parameter type identifier block return_statement tuple subscript identifier identifier call identifier argument_list call attribute identifier identifier argument_list identifier call identifier argument_list call attribute identifier identifier argument_list identifier | Canonicalize the edge to a tuple based on the relation, subject modifications, and object modifications. |
def load_collectors_from_entry_point(path):
collectors = {}
for ep in pkg_resources.iter_entry_points(path):
try:
mod = ep.load()
except Exception:
logger.error('Failed to import entry_point: %s. %s',
ep.name,
traceback.format_exc())
else:
collectors.update(get_collectors_from_module(mod))
return collectors | module function_definition identifier parameters identifier block expression_statement assignment identifier dictionary for_statement identifier call attribute identifier identifier argument_list identifier block try_statement block expression_statement assignment identifier call attribute identifier identifier argument_list except_clause identifier block expression_statement call attribute identifier identifier argument_list string string_start string_content string_end attribute identifier identifier call attribute identifier identifier argument_list else_clause block expression_statement call attribute identifier identifier argument_list call identifier argument_list identifier return_statement identifier | Load collectors that were installed into an entry_point. |
def eval_Rf(self, Vf):
return sl.inner(self.Df, Vf, axis=self.cri.axisM) - self.Sf | module function_definition identifier parameters identifier identifier block return_statement binary_operator call attribute identifier identifier argument_list attribute identifier identifier identifier keyword_argument identifier attribute attribute identifier identifier identifier attribute identifier identifier | Evaluate smooth term in Vf. |
def _add_extra_files(self, files):
try:
for f in files:
self.logger.con_out("adding additional file for analysis: %s" % f)
fname = os.path.basename(f)
f_new = os.path.join(self.dir_path, fname)
shutil.copyfile(f,f_new)
except IOError as e:
self.logger.con_out("ExtraFileError: %s is not readable or does not exist. Skipping File" % f)
self.logger.exception(e)
pass
except Exception as e:
self.logger.exception(e)
raise Exception("ExtraFileError: Unable to Process Extra File - %s" % f) | module function_definition identifier parameters identifier identifier block try_statement block for_statement identifier identifier block expression_statement call attribute attribute identifier identifier identifier argument_list binary_operator string string_start string_content string_end identifier expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list identifier expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list attribute identifier identifier identifier expression_statement call attribute identifier identifier argument_list identifier identifier except_clause as_pattern identifier as_pattern_target identifier block expression_statement call attribute attribute identifier identifier identifier argument_list binary_operator string string_start string_content string_end identifier expression_statement call attribute attribute identifier identifier identifier argument_list identifier pass_statement except_clause as_pattern identifier as_pattern_target identifier block expression_statement call attribute attribute identifier identifier identifier argument_list identifier raise_statement call identifier argument_list binary_operator string string_start string_content string_end identifier | if extra files are to be analyzed with an sosreport, this will add them to the origin path to be analyzed |
def convert_old(data):
"Convert config data with old schema to new schema"
ret = default_config()
ret['sync'].update(data.get('peeringdb', {}))
ret['orm']['database'].update(data.get('database', {}))
return ret | module function_definition identifier parameters identifier block expression_statement string string_start string_content string_end expression_statement assignment identifier call identifier argument_list expression_statement call attribute subscript identifier string string_start string_content string_end identifier argument_list call attribute identifier identifier argument_list string string_start string_content string_end dictionary expression_statement call attribute subscript subscript identifier string string_start string_content string_end string string_start string_content string_end identifier argument_list call attribute identifier identifier argument_list string string_start string_content string_end dictionary return_statement identifier | Convert config data with old schema to new schema |
def exception(self, *args, **kwargs):
kwargs['api'] = self.api
return exception(*args, **kwargs) | module function_definition identifier parameters identifier list_splat_pattern identifier dictionary_splat_pattern identifier block expression_statement assignment subscript identifier string string_start string_content string_end attribute identifier identifier return_statement call identifier argument_list list_splat identifier dictionary_splat identifier | Defines how this API should handle the provided exceptions |
def as_p(self, show_leaf=True, current_linkable=False, class_current="active_link"):
return self.__do_menu("as_p", show_leaf, current_linkable, class_current) | module function_definition identifier parameters identifier default_parameter identifier true default_parameter identifier false default_parameter identifier string string_start string_content string_end block return_statement call attribute identifier identifier argument_list string string_start string_content string_end identifier identifier identifier | It returns breadcrumb as p |
def lazy_reverse_binmap(f, xs):
return (f(y, x) for x, y in zip(xs, xs[1:])) | module function_definition identifier parameters identifier identifier block return_statement generator_expression call identifier argument_list identifier identifier for_in_clause pattern_list identifier identifier call identifier argument_list identifier subscript identifier slice integer | Same as lazy_binmap, except the parameters are flipped for the binary function |
def del_stream(self, bucket, label):
bucket = self._require_bucket(bucket)
key = self._require_key(bucket, label)
key.delete() | 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 identifier expression_statement call attribute identifier identifier argument_list | Will fail if the bucket or label don't exist |
def on_chanmsg(self, from_, channel, message):
if message == 'hello':
self.privmsg(channel, 'Hello, %s!' % from_[0])
print('%s said hello!' % from_[0])
elif message == '!quit':
self.quit('Bye!') | module function_definition identifier parameters identifier identifier identifier identifier block if_statement comparison_operator identifier string string_start string_content string_end block expression_statement call attribute identifier identifier argument_list identifier binary_operator string string_start string_content string_end subscript identifier integer expression_statement call identifier argument_list binary_operator string string_start string_content string_end subscript identifier integer elif_clause comparison_operator identifier string string_start string_content string_end block expression_statement call attribute identifier identifier argument_list string string_start string_content string_end | Event handler for channel messages. |
def getWindowBounds(self):
fn = self.function_table.getWindowBounds
pnX = c_int32()
pnY = c_int32()
pnWidth = c_uint32()
pnHeight = c_uint32()
fn(byref(pnX), byref(pnY), byref(pnWidth), byref(pnHeight))
return pnX.value, pnY.value, pnWidth.value, pnHeight.value | module function_definition identifier parameters identifier block expression_statement assignment identifier attribute attribute identifier identifier identifier expression_statement assignment identifier call identifier argument_list expression_statement assignment identifier call identifier argument_list expression_statement assignment identifier call identifier argument_list expression_statement assignment identifier call identifier argument_list expression_statement call identifier argument_list call identifier argument_list identifier call identifier argument_list identifier call identifier argument_list identifier call identifier argument_list identifier return_statement expression_list attribute identifier identifier attribute identifier identifier attribute identifier identifier attribute identifier identifier | Size and position that the window needs to be on the VR display. |
def reset(self):
self.pieces = set()
self.occupancy = self.new_vector()
self.exposed_territory = self.new_vector() | module function_definition identifier parameters identifier block expression_statement assignment attribute identifier identifier call identifier argument_list expression_statement assignment attribute identifier identifier call attribute identifier identifier argument_list expression_statement assignment attribute identifier identifier call attribute identifier identifier argument_list | Empty board, remove all pieces and reset internal states. |
def _add_tag_file(zip_file, dir_name, tag_info_list, tag_tup):
tag_name, tag_str = tag_tup
tag_path = d1_common.utils.filesystem.gen_safe_path(dir_name, tag_name)
tag_iter = _create_and_add_tag_iter(zip_file, tag_path, tag_str)
tag_info_list.append(
{
'path': tag_path,
'checksum': d1_common.checksum.calculate_checksum_on_iterator(
tag_iter, TAG_CHECKSUM_ALGO
),
}
) | module function_definition identifier parameters identifier identifier identifier identifier block expression_statement assignment pattern_list identifier identifier identifier expression_statement assignment identifier call attribute attribute attribute identifier identifier identifier identifier argument_list identifier identifier expression_statement assignment identifier call identifier argument_list identifier identifier identifier expression_statement call attribute identifier identifier argument_list dictionary pair string string_start string_content string_end identifier pair string string_start string_content string_end call attribute attribute identifier identifier identifier argument_list identifier identifier | Add a tag file to zip_file and record info for the tag manifest file. |
def check_program(self, name):
if not check_program(name):
raise management.CommandError(
"The program \"{name:s}\" is not available in the shell. "
"Please ensure that \"{name:s}\" is installed and reachable "
"through your PATH environment variable.".format(
name=name)) | module function_definition identifier parameters identifier identifier block if_statement not_operator call identifier argument_list identifier block raise_statement call attribute identifier identifier argument_list call attribute concatenated_string string string_start string_content escape_sequence escape_sequence string_end string string_start string_content escape_sequence escape_sequence string_end string string_start string_content string_end identifier argument_list keyword_argument identifier identifier | Checks whether a program is available on the shell PATH. |
def prep_bam_inputs(out_dir, sample, call_file, bam_file):
base = utils.splitext_plus(os.path.basename(bam_file))[0]
with open(call_file) as in_handle:
for cur_hla in (x.strip() for x in in_handle):
out_file = os.path.join(utils.safe_makedir(os.path.join(out_dir, base)),
"%s.type.%s.filtered.bam" % (base, cur_hla))
if not os.path.exists(out_file):
cmd = ["samtools", "view", "-b","-o", out_file, bam_file, cur_hla]
subprocess.check_call(cmd) | module function_definition identifier parameters identifier identifier identifier identifier block expression_statement assignment identifier subscript call attribute identifier identifier argument_list call attribute attribute identifier identifier identifier argument_list identifier integer with_statement with_clause with_item as_pattern call identifier argument_list identifier as_pattern_target identifier block for_statement identifier generator_expression call attribute identifier identifier argument_list for_in_clause identifier identifier block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list call attribute identifier identifier argument_list call attribute attribute identifier identifier identifier argument_list identifier identifier binary_operator string string_start string_content string_end tuple identifier identifier if_statement not_operator call attribute attribute identifier identifier identifier argument_list identifier block expression_statement assignment identifier list string string_start string_content string_end string string_start string_content string_end string string_start string_content string_end string string_start string_content string_end identifier identifier identifier expression_statement call attribute identifier identifier argument_list identifier | Prepare expected input BAM files from pre-aligned. |
def __checkSPKTimestamp(self):
if time.time() - self.__spk["timestamp"] > self.__spk_timeout:
self.__generateSPK() | module function_definition identifier parameters identifier block if_statement comparison_operator binary_operator call attribute identifier identifier argument_list subscript attribute identifier identifier string string_start string_content string_end attribute identifier identifier block expression_statement call attribute identifier identifier argument_list | Check whether the SPK is too old and generate a new one in that case. |
def esearch(self, db, term):
esr = ESearchResult(self._qs.esearch({'db': db, 'term': term}))
if esr.count > esr.retmax:
logger.warning("NCBI found {esr.count} results, but we truncated the reply at {esr.retmax}"
" results; see https://github.com/biocommons/eutils/issues/124/".format(esr=esr))
return esr | module function_definition identifier parameters identifier identifier identifier block expression_statement assignment identifier call identifier argument_list call attribute attribute identifier identifier identifier argument_list dictionary pair string string_start string_content string_end identifier pair string string_start string_content string_end identifier if_statement comparison_operator attribute identifier identifier attribute identifier identifier block expression_statement call attribute identifier identifier argument_list call attribute concatenated_string string string_start string_content string_end string string_start string_content string_end identifier argument_list keyword_argument identifier identifier return_statement identifier | query the esearch endpoint |
def post_log_artifacts(job_log):
logger.debug("Downloading/parsing log for log %s", job_log.id)
try:
artifact_list = extract_text_log_artifacts(job_log)
except LogSizeException as e:
job_log.update_status(JobLog.SKIPPED_SIZE)
logger.warning('Skipping parsing log for %s: %s', job_log.id, e)
return
except Exception as e:
job_log.update_status(JobLog.FAILED)
if isinstance(e, HTTPError) and e.response.status_code in (403, 404):
logger.warning("Unable to retrieve log for %s: %s", job_log.id, e)
return
logger.error("Failed to download/parse log for %s: %s", job_log.id, e)
raise
try:
serialized_artifacts = serialize_artifact_json_blobs(artifact_list)
store_job_artifacts(serialized_artifacts)
job_log.update_status(JobLog.PARSED)
logger.debug("Stored artifact for %s %s", job_log.job.repository.name,
job_log.job.id)
except Exception as e:
logger.error("Failed to store parsed artifact for %s: %s", job_log.id, e)
raise | module function_definition identifier parameters identifier block expression_statement call attribute identifier identifier argument_list string string_start string_content string_end attribute identifier identifier try_statement block expression_statement assignment identifier call identifier argument_list identifier except_clause as_pattern identifier as_pattern_target identifier block expression_statement call attribute identifier identifier argument_list attribute identifier identifier expression_statement call attribute identifier identifier argument_list string string_start string_content string_end attribute identifier identifier identifier return_statement except_clause as_pattern identifier as_pattern_target identifier block expression_statement call attribute identifier identifier argument_list attribute identifier identifier if_statement boolean_operator call identifier argument_list identifier identifier comparison_operator attribute attribute identifier identifier identifier tuple integer integer block expression_statement call attribute identifier identifier argument_list string string_start string_content string_end attribute identifier identifier identifier return_statement expression_statement call attribute identifier identifier argument_list string string_start string_content string_end attribute identifier identifier identifier raise_statement try_statement block expression_statement assignment identifier call identifier argument_list identifier expression_statement call identifier argument_list identifier expression_statement call attribute identifier identifier argument_list attribute identifier identifier expression_statement call attribute identifier identifier argument_list string string_start string_content string_end attribute attribute attribute identifier identifier identifier identifier attribute attribute identifier identifier identifier except_clause as_pattern identifier as_pattern_target identifier block expression_statement call attribute identifier identifier argument_list string string_start string_content string_end attribute identifier identifier identifier raise_statement | Post a list of artifacts to a job. |
def list_policies_for_vhost(self, vhost):
return self._api_get('/api/policies/{0}'.format(
urllib.parse.quote_plus(vhost)
)) | module function_definition identifier parameters identifier identifier block return_statement call attribute identifier identifier argument_list call attribute string string_start string_content string_end identifier argument_list call attribute attribute identifier identifier identifier argument_list identifier | A list of all policies for a vhost. |
def symbolic_Rz_matrix(symbolic_theta):
return sympy.Matrix([
[sympy.cos(symbolic_theta), -sympy.sin(symbolic_theta), 0],
[sympy.sin(symbolic_theta), sympy.cos(symbolic_theta), 0],
[0, 0, 1]
]) | module function_definition identifier parameters identifier block return_statement call attribute identifier identifier argument_list list list call attribute identifier identifier argument_list identifier unary_operator call attribute identifier identifier argument_list identifier integer list call attribute identifier identifier argument_list identifier call attribute identifier identifier argument_list identifier integer list integer integer integer | Matrice symbolique de rotation autour de l'axe Z |
def insert_into_shaders(self, vertex, fragment):
to_insert = defaultdict(str)
to_insert.update({key: '\n'.join(self._to_insert[key]) + '\n'
for key in self._to_insert})
return _insert_glsl(vertex, fragment, to_insert) | module function_definition identifier parameters identifier identifier identifier block expression_statement assignment identifier call identifier argument_list identifier expression_statement call attribute identifier identifier argument_list dictionary_comprehension pair identifier binary_operator call attribute string string_start string_content escape_sequence string_end identifier argument_list subscript attribute identifier identifier identifier string string_start string_content escape_sequence string_end for_in_clause identifier attribute identifier identifier return_statement call identifier argument_list identifier identifier identifier | Apply the insertions to shader code. |
def slistFloat(slist):
values = [v / 60**(i) for (i,v) in enumerate(slist[1:])]
value = sum(values)
return -value if slist[0] == '-' else value | module function_definition identifier parameters identifier block expression_statement assignment identifier list_comprehension binary_operator identifier binary_operator integer parenthesized_expression identifier for_in_clause tuple_pattern identifier identifier call identifier argument_list subscript identifier slice integer expression_statement assignment identifier call identifier argument_list identifier return_statement conditional_expression unary_operator identifier comparison_operator subscript identifier integer string string_start string_content string_end identifier | Converts signed list to float. |
def serialize(self):
for keys, groups in groupby(self.ports, lambda x: x.io_type):
for seq, port in enumerate(groups):
port.sequence = seq
return super(AlgorithmDef, self).serialize() | module function_definition identifier parameters identifier block for_statement pattern_list identifier identifier call identifier argument_list attribute identifier identifier lambda lambda_parameters identifier attribute identifier identifier block for_statement pattern_list identifier identifier call identifier argument_list identifier block expression_statement assignment attribute identifier identifier identifier return_statement call attribute call identifier argument_list identifier identifier identifier argument_list | Serialize the algorithm definition |
def create_md_row(self, row, header=False):
if not row:
return
cols = row.split('\t')
if len(cols) == 1:
self.out.append(cols[0])
else:
col_md = '|'
underline_md = '|'
if cols:
for col in cols:
col_md += col + '|'
underline_md += '-|'
if header:
self.out.append(col_md + '\n' + underline_md)
else:
self.out.append(col_md) | module function_definition identifier parameters identifier identifier default_parameter identifier false block if_statement not_operator identifier block return_statement expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content escape_sequence string_end if_statement comparison_operator call identifier argument_list identifier integer block expression_statement call attribute attribute identifier identifier identifier argument_list subscript identifier integer else_clause block expression_statement assignment identifier string string_start string_content string_end expression_statement assignment identifier string string_start string_content string_end if_statement identifier block for_statement identifier identifier block expression_statement augmented_assignment identifier binary_operator identifier string string_start string_content string_end expression_statement augmented_assignment identifier string string_start string_content string_end if_statement identifier block expression_statement call attribute attribute identifier identifier identifier argument_list binary_operator binary_operator identifier string string_start string_content escape_sequence string_end identifier else_clause block expression_statement call attribute attribute identifier identifier identifier argument_list identifier | Translate row into markdown format. |
def fun_en_complete_func(self, client, findstart_and_base, base=None):
if isinstance(findstart_and_base, list):
findstart = findstart_and_base[0]
base = findstart_and_base[1]
else:
findstart = findstart_and_base
return client.complete_func(findstart, base) | module function_definition identifier parameters identifier identifier identifier default_parameter identifier none block if_statement call identifier argument_list identifier identifier block expression_statement assignment identifier subscript identifier integer expression_statement assignment identifier subscript identifier integer else_clause block expression_statement assignment identifier identifier return_statement call attribute identifier identifier argument_list identifier identifier | Invokable function from vim and neovim to perform completion. |
def config_delete(args):
r = fapi.delete_workspace_config(args.project, args.workspace,
args.namespace, args.config)
fapi._check_response_code(r, [200,204])
return r.text if r.text else None | module function_definition identifier parameters identifier block expression_statement assignment identifier call attribute identifier identifier argument_list attribute identifier identifier attribute identifier identifier attribute identifier identifier attribute identifier identifier expression_statement call attribute identifier identifier argument_list identifier list integer integer return_statement conditional_expression attribute identifier identifier attribute identifier identifier none | Remove a method config from a workspace |
def table2matrix(table):
if not is_simpletable(table):
raise NotSimpleTable("Not able read a cell in the table as a string")
rows = []
for tr in table('tr'):
row = []
for td in tr('td'):
td = tdbr2EOL(td)
try:
row.append(td.contents[0])
except IndexError:
row.append('')
rows.append(row)
return rows | module function_definition identifier parameters identifier block if_statement not_operator call identifier argument_list identifier block raise_statement call identifier argument_list string string_start string_content string_end expression_statement assignment identifier list for_statement identifier call identifier argument_list string string_start string_content string_end block expression_statement assignment identifier list for_statement identifier call identifier argument_list string string_start string_content string_end block expression_statement assignment identifier call identifier argument_list identifier try_statement block expression_statement call attribute identifier identifier argument_list subscript attribute identifier identifier integer except_clause identifier block expression_statement call attribute identifier identifier argument_list string string_start string_end expression_statement call attribute identifier identifier argument_list identifier return_statement identifier | convert a table to a list of lists - a 2D matrix |
def _create_eval_metric(metric_name: str) -> mx.metric.EvalMetric:
if metric_name == C.ACCURACY:
return utils.Accuracy(ignore_label=C.PAD_ID, output_names=[C.SOFTMAX_OUTPUT_NAME], label_names=[C.TARGET_LABEL_NAME])
elif metric_name == C.PERPLEXITY:
return mx.metric.Perplexity(ignore_label=C.PAD_ID, output_names=[C.SOFTMAX_OUTPUT_NAME], label_names=[C.TARGET_LABEL_NAME], name=C.PERPLEXITY)
elif metric_name == C.LENRATIO_MSE:
return loss.LengthRatioMSEMetric(name=C.LENRATIO_MSE,
output_names=[C.LENRATIO_OUTPUT_NAME], label_names=[C.LENRATIO_LABEL_OUTPUT_NAME])
else:
raise ValueError("unknown metric name") | module function_definition identifier parameters typed_parameter identifier type identifier type attribute attribute identifier identifier identifier block if_statement comparison_operator identifier attribute identifier identifier block return_statement call attribute identifier identifier argument_list keyword_argument identifier attribute identifier identifier keyword_argument identifier list attribute identifier identifier keyword_argument identifier list attribute identifier identifier elif_clause comparison_operator identifier attribute identifier identifier block return_statement call attribute attribute identifier identifier identifier argument_list keyword_argument identifier attribute identifier identifier keyword_argument identifier list attribute identifier identifier keyword_argument identifier list attribute identifier identifier keyword_argument identifier attribute identifier identifier elif_clause comparison_operator identifier attribute identifier identifier block return_statement call attribute identifier identifier argument_list keyword_argument identifier attribute identifier identifier keyword_argument identifier list attribute identifier identifier keyword_argument identifier list attribute identifier identifier else_clause block raise_statement call identifier argument_list string string_start string_content string_end | Creates an EvalMetric given a metric names. |
def _find_last_line_index(contents):
lineno = 0
headerblock = re.compile(r"^{0}.*$".format(_ALL_COMMENT))
if not len(contents):
raise RuntimeError()
while headerblock.match(contents[lineno]):
if lineno + 1 == len(contents):
raise RuntimeError()
lineno = lineno + 1
if lineno < 2:
raise RuntimeError()
return lineno - 1 | module function_definition identifier parameters identifier block expression_statement assignment identifier integer expression_statement assignment identifier call attribute identifier identifier argument_list call attribute string string_start string_content string_end identifier argument_list identifier if_statement not_operator call identifier argument_list identifier block raise_statement call identifier argument_list while_statement call attribute identifier identifier argument_list subscript identifier identifier block if_statement comparison_operator binary_operator identifier integer call identifier argument_list identifier block raise_statement call identifier argument_list expression_statement assignment identifier binary_operator identifier integer if_statement comparison_operator identifier integer block raise_statement call identifier argument_list return_statement binary_operator identifier integer | Find the last line of the headerblock in contents. |
def deprecated(func, *args, **kwargs):
warnings.warn(
'{} is deprecated and should no longer be used.'.format(func),
DeprecationWarning,
stacklevel=3
)
return func(*args, **kwargs) | module function_definition identifier parameters identifier list_splat_pattern identifier dictionary_splat_pattern identifier block expression_statement call attribute identifier identifier argument_list call attribute string string_start string_content string_end identifier argument_list identifier identifier keyword_argument identifier integer return_statement call identifier argument_list list_splat identifier dictionary_splat identifier | Marks a function as deprecated. |
def sub(a, b):
if a is None:
if b is None:
return None
else:
return -1 * b
elif b is None:
return a
return a - b | module function_definition identifier parameters identifier identifier block if_statement comparison_operator identifier none block if_statement comparison_operator identifier none block return_statement none else_clause block return_statement binary_operator unary_operator integer identifier elif_clause comparison_operator identifier none block return_statement identifier return_statement binary_operator identifier identifier | Subtract two values, ignoring None |
def _run(self):
def get_next_interval():
start_time = time.time()
start = 0 if self.eager else 1
for count in itertools.count(start=start):
yield max(start_time + count * self.interval - time.time(), 0)
interval = get_next_interval()
sleep_time = next(interval)
while True:
with Timeout(sleep_time, exception=False):
self.should_stop.wait()
break
self.handle_timer_tick()
self.worker_complete.wait()
self.worker_complete.reset()
sleep_time = next(interval) | module function_definition identifier parameters identifier block function_definition identifier parameters block expression_statement assignment identifier call attribute identifier identifier argument_list expression_statement assignment identifier conditional_expression integer attribute identifier identifier integer for_statement identifier call attribute identifier identifier argument_list keyword_argument identifier identifier block expression_statement yield call identifier argument_list binary_operator binary_operator identifier binary_operator identifier attribute identifier identifier call attribute identifier identifier argument_list integer expression_statement assignment identifier call identifier argument_list expression_statement assignment identifier call identifier argument_list identifier while_statement true block with_statement with_clause with_item call identifier argument_list identifier keyword_argument identifier false block expression_statement call attribute attribute identifier identifier identifier argument_list break_statement expression_statement call attribute identifier identifier argument_list expression_statement call attribute attribute identifier identifier identifier argument_list expression_statement call attribute attribute identifier identifier identifier argument_list expression_statement assignment identifier call identifier argument_list identifier | Runs the interval loop. |
def dim_global_size_dict(self):
return { d.name: d.global_size for d in self._dims.itervalues()} | module function_definition identifier parameters identifier block return_statement dictionary_comprehension pair attribute identifier identifier attribute identifier identifier for_in_clause identifier call attribute attribute identifier identifier identifier argument_list | Returns a mapping of dimension name to global size |
def generate_liveOut_layout():
'Generate the layout per-app, generating each tine a new uuid for the state_uid argument'
return html.Div([
dpd.Pipe(id="named_count_pipe",
value=None,
label="named_counts",
channel_name="live_button_counter"),
html.Div(id="internal_state",
children="No state has been computed yet",
style={'display':'none'}),
dcc.Graph(id="timeseries_plot"),
dcc.Input(value=str(uuid.uuid4()),
id="state_uid",
style={'display':'none'},
)
]) | module function_definition identifier parameters block expression_statement string string_start string_content string_end return_statement call attribute identifier identifier argument_list list call attribute identifier identifier argument_list keyword_argument identifier string string_start string_content string_end keyword_argument identifier none keyword_argument identifier string string_start string_content string_end keyword_argument identifier string string_start string_content string_end call attribute identifier identifier argument_list keyword_argument identifier string string_start string_content string_end keyword_argument identifier string string_start string_content string_end keyword_argument identifier dictionary pair string string_start string_content string_end string string_start string_content string_end call attribute identifier identifier argument_list keyword_argument identifier string string_start string_content string_end call attribute identifier identifier argument_list keyword_argument identifier call identifier argument_list call attribute identifier identifier argument_list keyword_argument identifier string string_start string_content string_end keyword_argument identifier dictionary pair string string_start string_content string_end string string_start string_content string_end | Generate the layout per-app, generating each tine a new uuid for the state_uid argument |
def append_existing_values(schema, config):
for section_name in config:
for option_name in config[section_name]:
option_value = config[section_name][option_name]
schema.setdefault(section_name, {}).setdefault(option_name, {})['value'] = option_value
return schema | module function_definition identifier parameters identifier identifier block for_statement identifier identifier block for_statement identifier subscript identifier identifier block expression_statement assignment identifier subscript subscript identifier identifier identifier expression_statement assignment subscript call attribute call attribute identifier identifier argument_list identifier dictionary identifier argument_list identifier dictionary string string_start string_content string_end identifier return_statement identifier | Adds the values of the existing config to the config dictionary. |
def sync_db():
with cd('/'.join([deployment_root(),'env',env.project_fullname,'project',env.project_package_name,'sitesettings'])):
venv = '/'.join([deployment_root(),'env',env.project_fullname,'bin','activate'])
sites = _get_django_sites()
site_ids = sites.keys()
site_ids.sort()
for site in site_ids:
for settings_file in _sitesettings_files():
site_settings = '.'.join([env.project_package_name,'sitesettings',settings_file.replace('.py','')])
if env.verbosity:
print " * django-admin.py syncdb --noinput --settings=%s"% site_settings
output = sudo(' '.join(['source',venv,'&&',"django-admin.py syncdb --noinput --settings=%s"% site_settings]),
user='site_%s'% site)
if env.verbosity:
print output | module function_definition identifier parameters block with_statement with_clause with_item call identifier argument_list call attribute string string_start string_content string_end identifier argument_list list call identifier argument_list string string_start string_content string_end attribute identifier identifier string string_start string_content string_end attribute identifier identifier string string_start string_content string_end block expression_statement assignment identifier call attribute string string_start string_content string_end identifier argument_list list call identifier argument_list string string_start string_content string_end 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 expression_statement assignment identifier call attribute identifier identifier argument_list expression_statement call attribute identifier identifier argument_list for_statement identifier identifier block for_statement identifier call identifier argument_list block expression_statement assignment identifier call attribute string string_start string_content string_end identifier argument_list list attribute identifier identifier string string_start string_content string_end call attribute identifier identifier argument_list string string_start string_content string_end string string_start string_end if_statement attribute identifier identifier block print_statement binary_operator string string_start string_content string_end identifier expression_statement assignment identifier call identifier argument_list call attribute string string_start string_content string_end identifier argument_list list string string_start string_content string_end identifier string string_start string_content string_end binary_operator string string_start string_content string_end identifier keyword_argument identifier binary_operator string string_start string_content string_end identifier if_statement attribute identifier identifier block print_statement identifier | Runs the django syncdb command |
def cli(ctx, stage):
if not ctx.bubble:
ctx.say_yellow(
'There is no bubble present, will not show any transformer functions')
raise click.Abort()
rule_functions = get_registered_rule_functions()
ctx.gbc.say('before loading functions:' + str(len(rule_functions)))
load_rule_functions(ctx)
ctx.gbc.say('after loading functions:' + str(len(rule_functions)))
ctx.gbc.say('rule_functions:', stuff=rule_functions, verbosity=10)
rule_functions.set_parent(ctx.gbc)
for f in rule_functions:
ctx.say('fun: ' + f, verbosity=1)
ctx.gbc.say('funs: ', stuff=rule_functions.get_rule_functions(), verbosity=100)
return True | module function_definition identifier parameters identifier identifier block if_statement not_operator attribute identifier identifier block expression_statement call attribute identifier identifier argument_list string string_start string_content string_end raise_statement call attribute identifier identifier argument_list expression_statement assignment identifier call identifier argument_list expression_statement call attribute attribute identifier identifier identifier argument_list binary_operator string string_start string_content string_end call identifier argument_list call identifier argument_list identifier expression_statement call identifier argument_list identifier expression_statement call attribute attribute identifier identifier identifier argument_list binary_operator string string_start string_content string_end call identifier argument_list call identifier argument_list identifier expression_statement call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end keyword_argument identifier identifier keyword_argument identifier integer expression_statement call attribute identifier identifier argument_list attribute identifier identifier for_statement identifier identifier block expression_statement call attribute identifier identifier argument_list binary_operator string string_start string_content string_end identifier keyword_argument identifier integer expression_statement call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end keyword_argument identifier call attribute identifier identifier argument_list keyword_argument identifier integer return_statement true | Show the functions that are available, bubble system and custom. |
def absolute_path(string):
if not os.path.isabs(string):
msg = '{0!r} is not an absolute path'.format(string)
raise argparse.ArgumentTypeError(msg)
if not os.path.exists(os.path.dirname(string)):
msg = 'path {0!r} does not exist'.format(string)
raise argparse.ArgumentTypeError(msg)
return string | module function_definition identifier parameters identifier block if_statement not_operator call attribute attribute identifier identifier identifier argument_list identifier block expression_statement assignment identifier call attribute string string_start string_content string_end identifier argument_list identifier raise_statement call attribute identifier identifier argument_list identifier if_statement not_operator call attribute attribute identifier identifier identifier argument_list call attribute attribute identifier identifier identifier argument_list identifier block expression_statement assignment identifier call attribute string string_start string_content string_end identifier argument_list identifier raise_statement call attribute identifier identifier argument_list identifier return_statement identifier | "Convert" a string to a string that is an absolute existing path. |
def _load(self):
self.session_id = self._session_object.get_session_id()
if self.session_id and not self._valid_session_id(self.session_id):
self.session_id = None
if self.session_id:
d = self.store[self.session_id]
if isinstance(d, dict) and d:
self.update(d)
if not self.session_id:
self.session_id = self._session_object.generate_session_id()
if not self._data:
if self._initializer and isinstance(self._initializer, dict):
self.update(deepcopy(self._initializer))
self._session_object.set_session_id(self.session_id) | module function_definition identifier parameters identifier block expression_statement assignment attribute identifier identifier call attribute attribute identifier identifier identifier argument_list if_statement boolean_operator attribute identifier identifier not_operator call attribute identifier identifier argument_list attribute identifier identifier block expression_statement assignment attribute identifier identifier none if_statement attribute identifier identifier block expression_statement assignment identifier subscript attribute identifier identifier attribute identifier identifier if_statement boolean_operator call identifier argument_list identifier identifier identifier block expression_statement call attribute identifier identifier argument_list identifier if_statement not_operator attribute identifier identifier block expression_statement assignment attribute identifier identifier call attribute attribute identifier identifier identifier argument_list if_statement not_operator attribute identifier identifier block if_statement boolean_operator attribute identifier identifier call identifier argument_list attribute identifier identifier identifier block expression_statement call attribute identifier identifier argument_list call identifier argument_list attribute identifier identifier expression_statement call attribute attribute identifier identifier identifier argument_list attribute identifier identifier | Load the session from the store, by the id from cookie |
async def update(self):
if self.client.session.closed:
async with core.Client() as client:
data = await client.request(self.url)
else:
data = await self.client.request(self.url)
self.raw_data = data
self.from_data(data)
return self | module function_definition identifier parameters identifier block if_statement attribute attribute attribute identifier identifier identifier identifier block with_statement with_clause with_item as_pattern call attribute identifier identifier argument_list as_pattern_target identifier block expression_statement assignment identifier await call attribute identifier identifier argument_list attribute identifier identifier else_clause block expression_statement assignment identifier await call attribute attribute identifier identifier identifier argument_list attribute identifier identifier expression_statement assignment attribute identifier identifier identifier expression_statement call attribute identifier identifier argument_list identifier return_statement identifier | Update an object with current info. |
def matchers(self):
return [
self.file_matches,
self.magic_matches,
self.python_func_kw_matches,
self.dict_key_matches,
] | module function_definition identifier parameters identifier block return_statement list attribute identifier identifier attribute identifier identifier attribute identifier identifier attribute identifier identifier | All active matcher routines for completion |
def validate_json_field(dist, attr, value):
try:
is_json_compat(value)
except ValueError as e:
raise DistutilsSetupError("%r %s" % (attr, e))
return True | module function_definition identifier parameters identifier identifier identifier block try_statement block expression_statement call identifier argument_list identifier except_clause as_pattern identifier as_pattern_target identifier block raise_statement call identifier argument_list binary_operator string string_start string_content string_end tuple identifier identifier return_statement true | Check for json validity. |
def best(cls):
if sys.platform == 'win32' or (os.name == 'java' and os._name == 'nt'):
return WindowsScriptWriter.best()
else:
return cls | module function_definition identifier parameters identifier block if_statement boolean_operator comparison_operator attribute identifier identifier string string_start string_content string_end parenthesized_expression boolean_operator comparison_operator attribute identifier identifier string string_start string_content string_end comparison_operator attribute identifier identifier string string_start string_content string_end block return_statement call attribute identifier identifier argument_list else_clause block return_statement identifier | Select the best ScriptWriter for this environment. |
def run(self, module, dependency=False, kwargs={}):
try:
obj = self.load(module, kwargs)
if isinstance(obj, binwalk.core.module.Module) and obj.enabled:
obj.main()
self.status.clear()
if not dependency:
self.executed_modules[module] = obj
obj._unload_dependencies()
obj.unload()
except KeyboardInterrupt as e:
if self.status.running:
self.status.shutdown = True
while not self.status.finished:
time.sleep(0.1)
raise e
return obj | module function_definition identifier parameters identifier identifier default_parameter identifier false default_parameter identifier dictionary block try_statement block expression_statement assignment identifier call attribute identifier identifier argument_list identifier identifier if_statement boolean_operator call identifier argument_list identifier attribute attribute attribute identifier identifier identifier identifier attribute identifier identifier block expression_statement call attribute identifier identifier argument_list expression_statement call attribute attribute identifier identifier identifier argument_list if_statement not_operator identifier block expression_statement assignment subscript attribute identifier identifier identifier identifier expression_statement call attribute identifier identifier argument_list expression_statement call attribute identifier identifier argument_list except_clause as_pattern identifier as_pattern_target identifier block if_statement attribute attribute identifier identifier identifier block expression_statement assignment attribute attribute identifier identifier identifier true while_statement not_operator attribute attribute identifier identifier identifier block expression_statement call attribute identifier identifier argument_list float raise_statement identifier return_statement identifier | Runs a specific module. |
def add_note(note, **kwargs):
note_i = Note()
note_i.ref_key = note.ref_key
note_i.set_ref(note.ref_key, note.ref_id)
note_i.value = note.value
note_i.created_by = kwargs.get('user_id')
db.DBSession.add(note_i)
db.DBSession.flush()
return note_i | module function_definition identifier parameters identifier dictionary_splat_pattern identifier block expression_statement assignment identifier call identifier argument_list expression_statement assignment attribute identifier identifier attribute identifier identifier expression_statement call attribute identifier identifier argument_list attribute identifier identifier attribute identifier identifier expression_statement assignment attribute identifier identifier attribute identifier identifier expression_statement assignment attribute identifier identifier call attribute identifier identifier argument_list string string_start string_content string_end expression_statement call attribute attribute identifier identifier identifier argument_list identifier expression_statement call attribute attribute identifier identifier identifier argument_list return_statement identifier | Add a new note |
def point(self, pos):
return ((1 - pos) ** 3 * self.start) + \
(3 * (1 - pos) ** 2 * pos * self.control1) + \
(3 * (1 - pos) * pos ** 2 * self.control2) + \
(pos ** 3 * self.end) | module function_definition identifier parameters identifier identifier block return_statement binary_operator binary_operator binary_operator parenthesized_expression binary_operator binary_operator parenthesized_expression binary_operator integer identifier integer attribute identifier identifier line_continuation parenthesized_expression binary_operator binary_operator binary_operator integer binary_operator parenthesized_expression binary_operator integer identifier integer identifier attribute identifier identifier line_continuation parenthesized_expression binary_operator binary_operator binary_operator integer parenthesized_expression binary_operator integer identifier binary_operator identifier integer attribute identifier identifier line_continuation parenthesized_expression binary_operator binary_operator identifier integer attribute identifier identifier | Calculate the x,y position at a certain position of the path |
def _sorter(generated):
pairs = [(os.path.dirname(f), os.path.basename(f))
for f in set(list(generated))]
pairs.sort()
return [os.path.join(pair[0], pair[1]) for pair in pairs] | module function_definition identifier parameters identifier block expression_statement assignment identifier list_comprehension tuple call attribute attribute identifier identifier identifier argument_list identifier call attribute attribute identifier identifier identifier argument_list identifier for_in_clause identifier call identifier argument_list call identifier argument_list identifier expression_statement call attribute identifier identifier argument_list return_statement list_comprehension call attribute attribute identifier identifier identifier argument_list subscript identifier integer subscript identifier integer for_in_clause identifier identifier | Return a list of paths sorted by dirname & basename. |
def clear_cache():
del Cache._keys
for k in list(Cache._cache.keys()):
it = Cache._cache.pop(k)
del it
del Cache._cache
Cache._keys = []
Cache._cache = {}
gc.collect() | module function_definition identifier parameters block delete_statement attribute identifier identifier for_statement identifier call identifier argument_list call attribute attribute identifier identifier identifier argument_list block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list identifier delete_statement identifier delete_statement attribute identifier identifier expression_statement assignment attribute identifier identifier list expression_statement assignment attribute identifier identifier dictionary expression_statement call attribute identifier identifier argument_list | Remove all cached objects |
def ListHunts(context=None):
items = context.SendIteratorRequest("ListHunts", hunt_pb2.ApiListHuntsArgs())
return utils.MapItemsIterator(lambda data: Hunt(data=data, context=context),
items) | module function_definition identifier parameters default_parameter identifier none block expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end call attribute identifier identifier argument_list return_statement call attribute identifier identifier argument_list lambda lambda_parameters identifier call identifier argument_list keyword_argument identifier identifier keyword_argument identifier identifier identifier | List all GRR hunts. |
def start(self):
if threading.current_thread().name == 'MainThread':
signal.signal(signal.SIGINT, self.stop)
logging.info('Started on {}'.format(self.address))
while True:
self.process() | module function_definition identifier parameters identifier block if_statement comparison_operator attribute call attribute identifier identifier argument_list identifier string string_start string_content string_end block expression_statement call attribute identifier identifier argument_list attribute identifier identifier attribute identifier identifier expression_statement call attribute identifier identifier argument_list call attribute string string_start string_content string_end identifier argument_list attribute identifier identifier while_statement true block expression_statement call attribute identifier identifier argument_list | Start and listen for calls |
def _attach_to_model(self, model):
if not issubclass(model, ModelWithDynamicFieldMixin):
raise ImplementationError(
'The "%s" model does not inherit from ModelWithDynamicFieldMixin '
'so the "%s" DynamicField cannot be attached to it' % (
model.__name__, self.name))
super(DynamicFieldMixin, self)._attach_to_model(model)
if self.dynamic_version_of is not None:
return
if hasattr(model, self.name):
return
setattr(model, self.name, self) | module function_definition identifier parameters identifier identifier block if_statement not_operator call identifier argument_list identifier identifier block raise_statement call identifier argument_list binary_operator concatenated_string string string_start string_content string_end string string_start string_content string_end tuple attribute identifier identifier attribute identifier identifier expression_statement call attribute call identifier argument_list identifier identifier identifier argument_list identifier if_statement comparison_operator attribute identifier identifier none block return_statement if_statement call identifier argument_list identifier attribute identifier identifier block return_statement expression_statement call identifier argument_list identifier attribute identifier identifier identifier | Check that the model can handle dynamic fields |
def handle_aggregated_quotas(sender, instance, **kwargs):
quota = instance
if quota.scope is None:
return
quota_field = quota.get_field()
if isinstance(quota_field, fields.UsageAggregatorQuotaField) or quota_field is None:
return
signal = kwargs['signal']
for aggregator_quota in quota_field.get_aggregator_quotas(quota):
field = aggregator_quota.get_field()
if signal == signals.post_save:
field.post_child_quota_save(aggregator_quota.scope, child_quota=quota, created=kwargs.get('created'))
elif signal == signals.pre_delete:
field.pre_child_quota_delete(aggregator_quota.scope, child_quota=quota) | module function_definition identifier parameters identifier identifier dictionary_splat_pattern identifier block expression_statement assignment identifier identifier if_statement comparison_operator attribute identifier identifier none block return_statement expression_statement assignment identifier call attribute identifier identifier argument_list if_statement boolean_operator call identifier argument_list identifier attribute identifier identifier comparison_operator identifier none block return_statement expression_statement assignment identifier subscript identifier string string_start string_content string_end for_statement identifier call attribute identifier identifier argument_list identifier block expression_statement assignment identifier call attribute identifier identifier argument_list if_statement comparison_operator identifier attribute identifier identifier block expression_statement call attribute identifier identifier argument_list attribute identifier identifier keyword_argument identifier identifier keyword_argument identifier call attribute identifier identifier argument_list string string_start string_content string_end elif_clause comparison_operator identifier attribute identifier identifier block expression_statement call attribute identifier identifier argument_list attribute identifier identifier keyword_argument identifier identifier | Call aggregated quotas fields update methods |
def _set_master_state(self, state):
if state == 'init':
self._service_state.update_current_state('init', force=True)
self.set_state(DevState.INIT)
elif state == 'on':
self.set_state(DevState.ON)
self._service_state.update_current_state('on') | module function_definition identifier parameters identifier identifier block if_statement comparison_operator identifier string string_start string_content string_end block expression_statement call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end keyword_argument identifier true expression_statement call attribute identifier identifier argument_list attribute identifier identifier elif_clause comparison_operator identifier string string_start string_content string_end block expression_statement call attribute identifier identifier argument_list attribute identifier identifier expression_statement call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end | Set the state of the SDPMaster. |
def to_json(self):
result = super(Role, self).to_json()
result.update({
'name': self.name,
'description': self.description,
'permissions': self.permissions,
'policies': self.policies
})
return result | module function_definition identifier parameters identifier block expression_statement assignment identifier call attribute call identifier argument_list identifier identifier identifier argument_list expression_statement call attribute identifier identifier argument_list dictionary pair string string_start string_content string_end attribute identifier identifier pair string string_start string_content string_end attribute identifier identifier pair string string_start string_content string_end attribute identifier identifier pair string string_start string_content string_end attribute identifier identifier return_statement identifier | Returns the JSON representation of the role. |
def dst(self, dt):
tt = _localtime(_mktime((dt.year, dt.month, dt.day,
dt.hour, dt.minute, dt.second, dt.weekday(), 0, -1)))
if tt.tm_isdst > 0: return _dstdiff
return _zero | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call identifier argument_list call identifier argument_list tuple attribute identifier identifier attribute identifier identifier attribute identifier identifier attribute identifier identifier attribute identifier identifier attribute identifier identifier call attribute identifier identifier argument_list integer unary_operator integer if_statement comparison_operator attribute identifier identifier integer block return_statement identifier return_statement identifier | datetime -> DST offset in minutes east of UTC. |
def _tchelper(tc_deps,evals,deps):
for e in evals:
if e in tc_deps:
continue
else:
if e in deps:
tc_deps[e]=deps[e]
_tchelper(tc_deps,deps[e],deps)
return tc_deps | module function_definition identifier parameters identifier identifier identifier block for_statement identifier identifier block if_statement comparison_operator identifier identifier block continue_statement else_clause block if_statement comparison_operator identifier identifier block expression_statement assignment subscript identifier identifier subscript identifier identifier expression_statement call identifier argument_list identifier subscript identifier identifier identifier return_statement identifier | modifies graph in place |
def transliterate(text):
text = unidecode(six.text_type(text))
text = text.replace('@', 'a')
return text | module function_definition identifier parameters identifier block expression_statement assignment identifier call identifier argument_list call attribute identifier identifier argument_list identifier expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end string string_start string_content string_end return_statement identifier | Utility to properly transliterate text. |
def width(poly):
num = len(poly) - 1
if abs(poly[num][2] - poly[0][2]) < abs(poly[1][2] - poly[0][2]):
return dist(poly[num], poly[0])
elif abs(poly[num][2] - poly[0][2]) > abs(poly[1][2] - poly[0][2]):
return dist(poly[1], poly[0])
else: return max(dist(poly[num], poly[0]), dist(poly[1], poly[0])) | module function_definition identifier parameters identifier block expression_statement assignment identifier binary_operator call identifier argument_list identifier integer if_statement comparison_operator call identifier argument_list binary_operator subscript subscript identifier identifier integer subscript subscript identifier integer integer call identifier argument_list binary_operator subscript subscript identifier integer integer subscript subscript identifier integer integer block return_statement call identifier argument_list subscript identifier identifier subscript identifier integer elif_clause comparison_operator call identifier argument_list binary_operator subscript subscript identifier identifier integer subscript subscript identifier integer integer call identifier argument_list binary_operator subscript subscript identifier integer integer subscript subscript identifier integer integer block return_statement call identifier argument_list subscript identifier integer subscript identifier integer else_clause block return_statement call identifier argument_list call identifier argument_list subscript identifier identifier subscript identifier integer call identifier argument_list subscript identifier integer subscript identifier integer | Width of a polygon poly |
def items(self):
return Topic.objects.filter(forum__in=self.forums, approved=True).order_by('-last_post_on') | module function_definition identifier parameters identifier block return_statement call attribute call attribute attribute identifier identifier identifier argument_list keyword_argument identifier attribute identifier identifier keyword_argument identifier true identifier argument_list string string_start string_content string_end | Returns the items to include into the feed. |
def rotz(t):
c = np.cos(t)
s = np.sin(t)
return np.array([[c, -s, 0],
[s, c, 0],
[0, 0, 1]]) | module function_definition identifier parameters 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 call attribute identifier identifier argument_list list list identifier unary_operator identifier integer list identifier identifier integer list integer integer integer | Rotation about the z-axis. |
def verify(self, h, sig):
val = from_bytes_32(h)
pubkey = self.public_pair()
return self._generator.verify(pubkey, val, sigdecode_der(sig)) | module function_definition identifier parameters identifier identifier identifier block expression_statement assignment identifier call identifier argument_list identifier expression_statement assignment identifier call attribute identifier identifier argument_list return_statement call attribute attribute identifier identifier identifier argument_list identifier identifier call identifier argument_list identifier | Return whether a signature is valid for hash h using this key. |
def create_parser(self, subparsers):
self.parser = subparsers.add_parser(self.name, help=self.help, parents=self.parents)
self.add_arguments()
self.parser.set_defaults(func=self.handle)
return self.parser | module function_definition identifier parameters identifier identifier block expression_statement assignment attribute identifier identifier call attribute identifier identifier argument_list attribute identifier identifier keyword_argument identifier attribute identifier identifier keyword_argument identifier attribute identifier identifier expression_statement call attribute identifier identifier argument_list expression_statement call attribute attribute identifier identifier identifier argument_list keyword_argument identifier attribute identifier identifier return_statement attribute identifier identifier | Creates the subparser for this particular command |
def deserialize(self, apic_frame):
return Image(data=apic_frame.data, desc=apic_frame.desc,
type=apic_frame.type) | module function_definition identifier parameters identifier identifier block return_statement call identifier argument_list keyword_argument identifier attribute identifier identifier keyword_argument identifier attribute identifier identifier keyword_argument identifier attribute identifier identifier | Convert APIC frame into Image. |
def call(self, method, params=None):
start_time = time()
self.check_auth()
self.log(INFO, '[%s-%05d] Calling Zabbix API method "%s"', start_time, self.id, method)
self.log(DEBUG, '\twith parameters: %s', params)
try:
return self.do_request(self.json_obj(method, params=params))
except ZabbixAPIError as ex:
if self.relogin_interval and any(i in ex.error['data'] for i in self.LOGIN_ERRORS):
self.log(WARNING, 'Zabbix API not logged in (%s). Performing Zabbix API relogin', ex)
self.relogin()
return self.do_request(self.json_obj(method, params=params))
raise
finally:
self.log(INFO, '[%s-%05d] Zabbix API method "%s" finished in %g seconds',
start_time, self.id, method, (time() - start_time)) | module function_definition identifier parameters identifier identifier default_parameter identifier none block expression_statement assignment identifier call identifier argument_list expression_statement call attribute identifier identifier argument_list expression_statement call attribute identifier identifier argument_list identifier string string_start string_content string_end identifier attribute identifier identifier identifier expression_statement call attribute identifier identifier argument_list identifier string string_start string_content escape_sequence string_end identifier try_statement block return_statement call attribute identifier identifier argument_list call attribute identifier identifier argument_list identifier keyword_argument identifier identifier except_clause as_pattern identifier as_pattern_target identifier block if_statement boolean_operator attribute identifier identifier call identifier generator_expression comparison_operator identifier subscript attribute identifier identifier string string_start string_content string_end for_in_clause identifier attribute identifier identifier block expression_statement call attribute identifier identifier argument_list identifier string string_start string_content string_end identifier expression_statement call attribute identifier identifier argument_list return_statement call attribute identifier identifier argument_list call attribute identifier identifier argument_list identifier keyword_argument identifier identifier raise_statement finally_clause block expression_statement call attribute identifier identifier argument_list identifier string string_start string_content string_end identifier attribute identifier identifier identifier parenthesized_expression binary_operator call identifier argument_list identifier | Check authentication and perform actual API request and relogin if needed |
def nbcompile(filename, html, basenb, agdir):
filename = os.path.abspath(filename)
pc.nbcompile(os.path.dirname(filename), os.path.basename(filename), html=html, basenb=basenb, agdir=agdir) | module function_definition identifier parameters identifier identifier identifier identifier block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list identifier expression_statement call attribute identifier identifier argument_list call attribute attribute identifier identifier identifier argument_list identifier call attribute attribute identifier identifier identifier argument_list identifier keyword_argument identifier identifier keyword_argument identifier identifier keyword_argument identifier identifier | Compile the baseinteract.ipynb notebook into an analysis notebook for filename |
def _find_realname(self, post_input):
if "lis_person_name_full" in post_input:
return post_input["lis_person_name_full"]
if "lis_person_name_given" in post_input and "lis_person_name_family" in post_input:
return post_input["lis_person_name_given"] + post_input["lis_person_name_family"]
if "lis_person_contact_email_primary" in post_input:
return post_input["lis_person_contact_email_primary"]
if "lis_person_name_family" in post_input:
return post_input["lis_person_name_family"]
if "lis_person_name_given" in post_input:
return post_input["lis_person_name_given"]
return post_input["user_id"] | module function_definition identifier parameters identifier identifier block if_statement comparison_operator string string_start string_content string_end identifier block return_statement subscript identifier string string_start string_content string_end if_statement boolean_operator comparison_operator string string_start string_content string_end identifier comparison_operator string string_start string_content string_end identifier block return_statement binary_operator subscript identifier string string_start string_content string_end subscript identifier string string_start string_content string_end if_statement comparison_operator string string_start string_content string_end identifier block return_statement subscript identifier string string_start string_content string_end if_statement comparison_operator string string_start string_content string_end identifier block return_statement subscript identifier string string_start string_content string_end if_statement comparison_operator string string_start string_content string_end identifier block return_statement subscript identifier string string_start string_content string_end return_statement subscript identifier string string_start string_content string_end | Returns the most appropriate name to identify the user |
def annotations_class(cls):
assert(isclass(cls))
keys = [key for key in cls.__dict__]
for key in keys:
memb = cls.__dict__[key]
if _check_as_func(memb):
annotations_func(memb)
elif isclass(memb):
annotations_class(memb)
return cls | module function_definition identifier parameters identifier block assert_statement parenthesized_expression call identifier argument_list identifier expression_statement assignment identifier list_comprehension identifier for_in_clause identifier attribute identifier identifier for_statement identifier identifier block expression_statement assignment identifier subscript attribute identifier identifier identifier if_statement call identifier argument_list identifier block expression_statement call identifier argument_list identifier elif_clause call identifier argument_list identifier block expression_statement call identifier argument_list identifier return_statement identifier | Works like annotations, but is only applicable to classes. |
def kvp_dict(d):
return ', '.join(
["{}={}".format(k, quotable(v)) for k, v in d.items()]) | module function_definition identifier parameters identifier block return_statement call attribute string string_start string_content string_end identifier argument_list list_comprehension call attribute string string_start string_content string_end identifier argument_list identifier call identifier argument_list identifier for_in_clause pattern_list identifier identifier call attribute identifier identifier argument_list | Format dict to key=value pairs. |
def filtered_notebook_metadata(notebook):
metadata = copy(notebook.metadata)
metadata = filter_metadata(metadata,
notebook.metadata.get('jupytext', {}).get('notebook_metadata_filter'),
_DEFAULT_NOTEBOOK_METADATA)
if 'jupytext' in metadata:
del metadata['jupytext']
return metadata | module function_definition identifier parameters identifier block expression_statement assignment identifier call identifier argument_list attribute identifier identifier expression_statement assignment identifier call identifier argument_list identifier call attribute call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end dictionary identifier argument_list string string_start string_content string_end identifier if_statement comparison_operator string string_start string_content string_end identifier block delete_statement subscript identifier string string_start string_content string_end return_statement identifier | Notebook metadata, filtered for metadata added by Jupytext itself |
def to_jsondict(self):
body = {"oxs_fields": [ofproto.oxs_to_jsondict(k, uv) for k, uv
in self.fields],
"length": self.length}
return {self.__class__.__name__: body} | module function_definition identifier parameters identifier block expression_statement assignment identifier dictionary pair string string_start string_content string_end list_comprehension call attribute identifier identifier argument_list identifier identifier for_in_clause pattern_list identifier identifier attribute identifier identifier pair string string_start string_content string_end attribute identifier identifier return_statement dictionary pair attribute attribute identifier identifier identifier identifier | Returns a dict expressing the flow stats. |
def start_paragraph(self, stylename=None):
if stylename is None:
stylename = self._next_p_style or 'normal-paragraph'
self.start_container(P, stylename=stylename) | module function_definition identifier parameters identifier default_parameter identifier none block if_statement comparison_operator identifier none block expression_statement assignment identifier boolean_operator attribute identifier identifier string string_start string_content string_end expression_statement call attribute identifier identifier argument_list identifier keyword_argument identifier identifier | Start a new paragraph. |
def _from_dict(cls, _dict):
args = {}
if 'models' in _dict:
args['models'] = [
TranslationModel._from_dict(x) for x in (_dict.get('models'))
]
else:
raise ValueError(
'Required property \'models\' not present in TranslationModels JSON'
)
return cls(**args) | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier dictionary if_statement comparison_operator string string_start string_content string_end identifier block expression_statement assignment subscript identifier string string_start string_content string_end list_comprehension call attribute identifier identifier argument_list identifier for_in_clause identifier parenthesized_expression call attribute identifier identifier argument_list string string_start string_content string_end else_clause block raise_statement call identifier argument_list string string_start string_content escape_sequence escape_sequence string_end return_statement call identifier argument_list dictionary_splat identifier | Initialize a TranslationModels object from a json dictionary. |
def configure_job():
training_input = {
"pythonModule": "tensor2tensor.bin.t2t_trainer",
"args": flags_as_args(),
"region": text_encoder.native_to_unicode(default_region()),
"runtimeVersion": RUNTIME_VERSION,
"pythonVersion": "3.5" if sys.version_info.major == 3 else "2.7",
"jobDir": FLAGS.output_dir,
"scaleTier": "CUSTOM",
"masterType": FLAGS.cloud_mlengine_master_type or get_default_master_type(
num_gpus=FLAGS.worker_gpu)
}
if FLAGS.use_tpu:
training_input["masterType"] = (FLAGS.cloud_mlengine_master_type or
"standard")
training_input["workerType"] = "cloud_tpu"
training_input["workerCount"] = 1
if FLAGS.hparams_range:
tf.logging.info("Configuring hyperparameter tuning.")
training_input["hyperparameters"] = configure_autotune(
FLAGS.hparams_range,
FLAGS.autotune_objective,
FLAGS.autotune_maximize,
FLAGS.autotune_max_trials,
FLAGS.autotune_parallel_trials,
)
timestamp = datetime.datetime.now().strftime("%Y%m%d_%H%M%S")
job_spec = {
"jobId": "%s_%s_t2t_%s" % (FLAGS.model, FLAGS.problem, timestamp),
"labels": {
"model": FLAGS.model,
"problem": FLAGS.problem,
"hparams": FLAGS.hparams_set
},
"trainingInput": training_input,
}
return job_spec | module function_definition identifier parameters block expression_statement assignment identifier dictionary pair string string_start string_content string_end string string_start string_content string_end pair string string_start string_content string_end call identifier argument_list pair string string_start string_content string_end call attribute identifier identifier argument_list call identifier argument_list pair string string_start string_content string_end identifier pair string string_start string_content string_end conditional_expression string string_start string_content string_end comparison_operator attribute attribute identifier identifier identifier integer string string_start string_content string_end pair string string_start string_content string_end attribute identifier identifier pair string string_start string_content string_end string string_start string_content string_end pair string string_start string_content string_end boolean_operator attribute identifier identifier call identifier argument_list keyword_argument identifier attribute identifier identifier if_statement attribute identifier identifier block expression_statement assignment subscript identifier string string_start string_content string_end parenthesized_expression boolean_operator attribute identifier identifier string string_start string_content string_end expression_statement assignment subscript identifier string string_start string_content string_end string string_start string_content string_end expression_statement assignment subscript identifier string string_start string_content string_end integer if_statement attribute identifier identifier block expression_statement call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end expression_statement assignment subscript identifier string string_start string_content string_end call identifier argument_list attribute identifier identifier attribute identifier identifier attribute identifier identifier attribute identifier identifier attribute identifier identifier expression_statement assignment identifier call attribute call attribute attribute identifier identifier identifier argument_list identifier argument_list string string_start string_content string_end expression_statement assignment identifier dictionary pair string string_start string_content string_end binary_operator string string_start string_content string_end tuple attribute identifier identifier attribute identifier identifier identifier pair string string_start string_content string_end dictionary pair string string_start string_content string_end attribute identifier identifier pair string string_start string_content string_end attribute identifier identifier pair string string_start string_content string_end attribute identifier identifier pair string string_start string_content string_end identifier return_statement identifier | Construct jobSpec for ML Engine job. |
def name_check(self, original, loc, tokens):
internal_assert(len(tokens) == 1, "invalid name tokens", tokens)
if self.strict:
self.unused_imports.discard(tokens[0])
if tokens[0] == "exec":
return self.check_py("3", "exec function", original, loc, tokens)
elif tokens[0].startswith(reserved_prefix):
raise self.make_err(CoconutSyntaxError, "variable names cannot start with reserved prefix " + reserved_prefix, original, loc)
else:
return tokens[0] | module function_definition identifier parameters identifier identifier identifier identifier block expression_statement call identifier argument_list comparison_operator call identifier argument_list identifier integer string string_start string_content string_end identifier if_statement attribute identifier identifier block expression_statement call attribute attribute identifier identifier identifier argument_list subscript identifier integer if_statement comparison_operator subscript identifier integer string string_start string_content string_end block return_statement call attribute identifier identifier argument_list string string_start string_content string_end string string_start string_content string_end identifier identifier identifier elif_clause call attribute subscript identifier integer identifier argument_list identifier block raise_statement call attribute identifier identifier argument_list identifier binary_operator string string_start string_content string_end identifier identifier identifier else_clause block return_statement subscript identifier integer | Check the given base name. |
def visit_annassign(self, node, parent):
newnode = nodes.AnnAssign(node.lineno, node.col_offset, parent)
annotation = _visit_or_none(node, "annotation", self, newnode)
newnode.postinit(
target=self.visit(node.target, newnode),
annotation=annotation,
simple=node.simple,
value=_visit_or_none(node, "value", self, newnode),
)
return newnode | module function_definition identifier parameters identifier identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list attribute identifier identifier attribute identifier identifier identifier expression_statement assignment identifier call identifier argument_list identifier string string_start string_content string_end identifier identifier expression_statement call attribute identifier identifier argument_list keyword_argument identifier call attribute identifier identifier argument_list attribute identifier identifier identifier keyword_argument identifier identifier keyword_argument identifier attribute identifier identifier keyword_argument identifier call identifier argument_list identifier string string_start string_content string_end identifier identifier return_statement identifier | visit an AnnAssign node by returning a fresh instance of it |
def in_navitem(self, resources, nav_href):
if nav_href.endswith('/index'):
nav_href = nav_href[:-6]
return self.docname.startswith(nav_href) | module function_definition identifier parameters identifier identifier identifier block if_statement call attribute identifier identifier argument_list string string_start string_content string_end block expression_statement assignment identifier subscript identifier slice unary_operator integer return_statement call attribute attribute identifier identifier identifier argument_list identifier | Given href of nav item, determine if resource is in it |
def parse_segdict_key(self, key):
splt = key.split(':')
if len(splt) == 2:
return splt[0], splt[1]
else:
err_msg = "Key should be of the format 'ifo:name', got %s." %(key,)
raise ValueError(err_msg) | 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 comparison_operator call identifier argument_list identifier integer block return_statement expression_list subscript identifier integer subscript identifier integer else_clause block expression_statement assignment identifier binary_operator string string_start string_content string_end tuple identifier raise_statement call identifier argument_list identifier | Return ifo and name from the segdict key. |
async def setup(self):
while True:
fut = self.loop.create_connection(
lambda: SW16Protocol(
self,
disconnect_callback=self.handle_disconnect_callback,
loop=self.loop, logger=self.logger),
host=self.host,
port=self.port)
try:
self.transport, self.protocol = \
await asyncio.wait_for(fut, timeout=self.timeout)
except asyncio.TimeoutError:
self.logger.warning("Could not connect due to timeout error.")
except OSError as exc:
self.logger.warning("Could not connect due to error: %s",
str(exc))
else:
self.is_connected = True
if self.reconnect_callback:
self.reconnect_callback()
break
await asyncio.sleep(self.reconnect_interval) | module function_definition identifier parameters identifier block while_statement true block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list lambda call identifier argument_list 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 try_statement block expression_statement assignment pattern_list attribute identifier identifier attribute identifier identifier line_continuation await call attribute identifier identifier argument_list identifier keyword_argument identifier attribute identifier identifier except_clause attribute identifier identifier block expression_statement call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end except_clause as_pattern identifier as_pattern_target identifier block expression_statement call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end call identifier argument_list identifier else_clause block expression_statement assignment attribute identifier identifier true if_statement attribute identifier identifier block expression_statement call attribute identifier identifier argument_list break_statement expression_statement await call attribute identifier identifier argument_list attribute identifier identifier | Set up the connection with automatic retry. |
def train(self):
for iDriving, cDriving in enumerate(self.drivingOperandSDRs):
minicolumnSDR = self.minicolumnSDRs[iDriving]
self.pairLayerProximalConnections.associate(minicolumnSDR, cDriving)
for iContext, cContext in enumerate(self.contextOperandSDRs):
iResult = (iContext + iDriving) % self.numLocations
cResult = self.resultSDRs[iResult]
self.pairLayer.compute(minicolumnSDR, basalInput=cContext)
cPair = self.pairLayer.getWinnerCells()
self.poolingLayer.associate(cResult, cPair) | module function_definition identifier parameters identifier block for_statement pattern_list identifier identifier call identifier argument_list attribute identifier identifier block expression_statement assignment identifier subscript attribute identifier identifier identifier expression_statement call attribute attribute identifier identifier identifier argument_list identifier identifier for_statement pattern_list identifier identifier call identifier argument_list attribute identifier identifier block expression_statement assignment identifier binary_operator parenthesized_expression binary_operator identifier identifier attribute identifier identifier expression_statement assignment identifier subscript attribute identifier identifier identifier expression_statement call attribute attribute identifier identifier identifier argument_list identifier keyword_argument identifier identifier expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list expression_statement call attribute attribute identifier identifier identifier argument_list identifier identifier | Train the pair layer and pooling layer. |
def relateObjectLocs(obj, entities, selectF):
try: obj = obj.loc
except AttributeError: pass
try: func = obj.direct2dDistance
except AttributeError: raise ValueError("object %s (%s) does not possess and is not a %s"%(obj, type(obj), MapPoint))
try: return selectF([(func(b.loc), b) for b in entities])
except AttributeError: return selectF([(func(b) , b) for b in entities]) | module function_definition identifier parameters identifier identifier identifier block try_statement block expression_statement assignment identifier attribute identifier identifier except_clause identifier block pass_statement try_statement block expression_statement assignment identifier attribute identifier identifier except_clause identifier block raise_statement call identifier argument_list binary_operator string string_start string_content string_end tuple identifier call identifier argument_list identifier identifier try_statement block return_statement call identifier argument_list list_comprehension tuple call identifier argument_list attribute identifier identifier identifier for_in_clause identifier identifier except_clause identifier block return_statement call identifier argument_list list_comprehension tuple call identifier argument_list identifier identifier for_in_clause identifier identifier | calculate the minimum distance to reach any iterable of entities with a loc |
def handle_error(_, client_addr):
exc_type, exc_value, _ = sys.exc_info()
if exc_type is socket.error and exc_value[0] == 32:
pass
elif exc_type is cPickle.UnpicklingError:
sys.stderr.write('Invalid connection from {0}\n'
.format(client_addr[0]))
else:
raise | module function_definition identifier parameters identifier identifier block expression_statement assignment pattern_list identifier identifier identifier call attribute identifier identifier argument_list if_statement boolean_operator comparison_operator identifier attribute identifier identifier comparison_operator subscript identifier integer integer block pass_statement elif_clause comparison_operator identifier attribute identifier identifier block expression_statement call attribute attribute identifier identifier identifier argument_list call attribute string string_start string_content escape_sequence string_end identifier argument_list subscript identifier integer else_clause block raise_statement | Mute tracebacks of common errors. |
def _sync_notes(self, notes_json):
for note_json in notes_json:
note_id = note_json['id']
task_id = note_json['item_id']
if task_id not in self.tasks:
continue
task = self.tasks[task_id]
self.notes[note_id] = Note(note_json, task) | module function_definition identifier parameters identifier identifier block for_statement 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 if_statement comparison_operator identifier attribute identifier identifier block continue_statement expression_statement assignment identifier subscript attribute identifier identifier identifier expression_statement assignment subscript attribute identifier identifier identifier call identifier argument_list identifier identifier | Populate the user's notes from a JSON encoded list. |
def _process_msg(self, client, state, reward, isOver):
if len(client.memory) > 0:
client.memory[-1].reward = reward
if isOver:
self._parse_memory(0, client, True)
else:
if len(client.memory) == LOCAL_TIME_MAX + 1:
R = client.memory[-1].value
self._parse_memory(R, client, False)
self._on_state(state, client) | module function_definition identifier parameters identifier identifier identifier identifier identifier block if_statement comparison_operator call identifier argument_list attribute identifier identifier integer block expression_statement assignment attribute subscript attribute identifier identifier unary_operator integer identifier identifier if_statement identifier block expression_statement call attribute identifier identifier argument_list integer identifier true else_clause block if_statement comparison_operator call identifier argument_list attribute identifier identifier binary_operator identifier integer block expression_statement assignment identifier attribute subscript attribute identifier identifier unary_operator integer identifier expression_statement call attribute identifier identifier argument_list identifier identifier false expression_statement call attribute identifier identifier argument_list identifier identifier | Process a message sent from some client. |
def _encoded_routing_key(self):
topic = self.topic
if config.conf["topic_prefix"]:
topic = ".".join((config.conf["topic_prefix"].rstrip("."), topic))
return topic.encode("utf-8") | module function_definition identifier parameters identifier block expression_statement assignment identifier attribute identifier identifier if_statement subscript attribute identifier identifier string string_start string_content string_end block expression_statement assignment identifier call attribute string string_start string_content string_end identifier argument_list tuple call attribute subscript attribute identifier identifier string string_start string_content string_end identifier argument_list string string_start string_content string_end identifier return_statement call attribute identifier identifier argument_list string string_start string_content string_end | The encoded routing key used to publish the message on the broker. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.