code stringlengths 51 2.34k | sequence stringlengths 186 3.94k | docstring stringlengths 11 171 |
|---|---|---|
def parallelize_func(iterable, func, chunksz=1, n_jobs=16, *args, **kwargs):
chunker = func
chunks = more_itertools.chunked(iterable, chunksz)
chunks_results = Parallel(n_jobs=n_jobs, verbose=50)(
delayed(chunker)(chunk, *args, **kwargs) for chunk in chunks)
results = more_itertools.flatten(chunks_results)
return list(results) | module function_definition identifier parameters identifier identifier default_parameter identifier integer default_parameter identifier integer list_splat_pattern identifier dictionary_splat_pattern identifier block expression_statement assignment identifier identifier expression_statement assignment identifier call attribute identifier identifier argument_list identifier identifier expression_statement assignment identifier call call identifier argument_list keyword_argument identifier identifier keyword_argument identifier integer generator_expression call call identifier argument_list identifier argument_list identifier list_splat identifier dictionary_splat identifier for_in_clause identifier identifier expression_statement assignment identifier call attribute identifier identifier argument_list identifier return_statement call identifier argument_list identifier | Parallelize a function over each element of an iterable. |
def _from_dict(cls, _dict):
args = {}
if 'section_titles' in _dict:
args['section_titles'] = [
SectionTitles._from_dict(x)
for x in (_dict.get('section_titles'))
]
if 'leading_sentences' in _dict:
args['leading_sentences'] = [
LeadingSentence._from_dict(x)
for x in (_dict.get('leading_sentences'))
]
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 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 return_statement call identifier argument_list dictionary_splat identifier | Initialize a DocStructure object from a json dictionary. |
def _getCharWidths(self, xref, bfname, ext, ordering, limit, idx=0):
if self.isClosed or self.isEncrypted:
raise ValueError("operation illegal for closed / encrypted doc")
return _fitz.Document__getCharWidths(self, xref, bfname, ext, ordering, limit, idx) | module function_definition identifier parameters identifier identifier identifier identifier identifier identifier default_parameter identifier integer block if_statement boolean_operator attribute identifier identifier attribute identifier identifier block raise_statement call identifier argument_list string string_start string_content string_end return_statement call attribute identifier identifier argument_list identifier identifier identifier identifier identifier identifier identifier | Return list of glyphs and glyph widths of a font. |
def make_cube_slice(map_in, loge_bounds):
axis = map_in.geom.axes[0]
i0 = utils.val_to_edge(axis.edges, 10**loge_bounds[0])[0]
i1 = utils.val_to_edge(axis.edges, 10**loge_bounds[1])[0]
new_axis = map_in.geom.axes[0].slice(slice(i0, i1))
geom = map_in.geom.to_image()
geom = geom.to_cube([new_axis])
map_out = WcsNDMap(geom, map_in.data[slice(i0, i1), ...].copy())
return map_out | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier subscript attribute attribute identifier identifier identifier integer expression_statement assignment identifier subscript call attribute identifier identifier argument_list attribute identifier identifier binary_operator integer subscript identifier integer integer expression_statement assignment identifier subscript call attribute identifier identifier argument_list attribute identifier identifier binary_operator integer subscript identifier integer integer expression_statement assignment identifier call attribute subscript attribute attribute identifier identifier identifier integer identifier argument_list call identifier argument_list identifier identifier expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list expression_statement assignment identifier call attribute identifier identifier argument_list list identifier expression_statement assignment identifier call identifier argument_list identifier call attribute subscript attribute identifier identifier call identifier argument_list identifier identifier ellipsis identifier argument_list return_statement identifier | Extract a slice from a map cube object. |
def run(songs):
if not hasattr(songs, '__iter__'):
result = get_lyrics_threaded(songs)
process_result(result)
else:
start = time.time()
stats = run_mp(songs)
end = time.time()
if CONFIG['print_stats']:
stats.print_stats()
total_time = end - start
total_time = '%d:%02d:%02d' % (total_time / 3600,
(total_time / 3600) / 60,
(total_time % 3600) % 60)
print(f'Total time: {total_time}') | module function_definition identifier parameters identifier block if_statement not_operator call identifier argument_list identifier string string_start string_content string_end block expression_statement assignment identifier call identifier argument_list identifier expression_statement call identifier argument_list identifier else_clause block expression_statement assignment identifier call attribute identifier identifier argument_list expression_statement assignment identifier call identifier argument_list identifier expression_statement assignment identifier call attribute identifier identifier argument_list if_statement subscript identifier string string_start string_content string_end block expression_statement call attribute identifier identifier argument_list expression_statement assignment identifier binary_operator identifier identifier expression_statement assignment identifier binary_operator string string_start string_content string_end tuple binary_operator identifier integer binary_operator parenthesized_expression binary_operator identifier integer integer binary_operator parenthesized_expression binary_operator identifier integer integer expression_statement call identifier argument_list string string_start string_content interpolation identifier string_end | Calls get_lyrics_threaded for a song or list of songs. |
def segment_from_cnr(cnr_file, data, out_base):
cns_file = _cnvkit_segment(cnr_file, dd.get_coverage_interval(data),
data, [data], out_file="%s.cns" % out_base, detailed=True)
out = _add_seg_to_output({"cns": cns_file}, data, enumerate_chroms=False)
return out["seg"] | module function_definition identifier parameters identifier identifier identifier block expression_statement assignment identifier call identifier argument_list identifier call attribute identifier identifier argument_list identifier identifier list identifier keyword_argument identifier binary_operator string string_start string_content string_end identifier keyword_argument identifier true expression_statement assignment identifier call identifier argument_list dictionary pair string string_start string_content string_end identifier identifier keyword_argument identifier false return_statement subscript identifier string string_start string_content string_end | Provide segmentation on a cnr file, used in external PureCN integration. |
def update_title(self, _, info):
with self._lock:
self._block.meta.set_label(info.title) | module function_definition identifier parameters identifier identifier identifier block with_statement with_clause with_item attribute identifier identifier block expression_statement call attribute attribute attribute identifier identifier identifier identifier argument_list attribute identifier identifier | Set the label of the Block Meta object |
def showMenu(self, point):
menu = QMenu(self)
acts = {}
acts['edit'] = menu.addAction('Edit quick filter...')
trigger = menu.exec_(self.mapToGlobal(point))
if trigger == acts['edit']:
text, accepted = XTextEdit.getText(self.window(),
'Edit Format',
'Format:',
self.filterFormat(),
wrapped=False)
if accepted:
self.setFilterFormat(text) | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call identifier argument_list identifier expression_statement assignment identifier dictionary expression_statement assignment subscript identifier string string_start string_content string_end call attribute identifier identifier argument_list string string_start string_content string_end expression_statement assignment identifier call attribute identifier identifier argument_list call attribute identifier identifier argument_list identifier if_statement comparison_operator identifier subscript identifier string string_start string_content string_end block expression_statement assignment pattern_list identifier identifier call attribute identifier identifier argument_list call attribute identifier identifier argument_list string string_start string_content string_end string string_start string_content string_end call attribute identifier identifier argument_list keyword_argument identifier false if_statement identifier block expression_statement call attribute identifier identifier argument_list identifier | Displays the menu for this filter widget. |
def _cmd_miraligner(fn, out_file, species, hairpin, out):
tool = _get_miraligner()
path_db = op.dirname(op.abspath(hairpin))
cmd = "{tool} -freq -i {fn} -o {out_file} -s {species} -db {path_db} -sub 1 -trim 3 -add 3"
if not file_exists(out_file):
logger.info("Running miraligner with %s" % fn)
do.run(cmd.format(**locals()), "miraligner with %s" % fn)
shutil.move(out_file + ".mirna", out_file)
return out_file | module function_definition identifier parameters identifier identifier identifier identifier identifier block expression_statement assignment identifier call identifier argument_list expression_statement assignment identifier call attribute identifier identifier argument_list call attribute identifier identifier argument_list identifier expression_statement assignment identifier string string_start string_content string_end if_statement not_operator call identifier argument_list identifier block expression_statement call attribute identifier identifier argument_list binary_operator string string_start string_content string_end identifier expression_statement call attribute identifier identifier argument_list call attribute identifier identifier argument_list dictionary_splat call identifier argument_list binary_operator string string_start string_content string_end identifier expression_statement call attribute identifier identifier argument_list binary_operator identifier string string_start string_content string_end identifier return_statement identifier | Run miraligner for miRNA annotation |
def write_json(self):
with open(self.results_folder_name + '/results-' + str(self.get_global_count()) + '.json', 'a') as f:
json.dump(self.result, f) | module function_definition identifier parameters identifier block with_statement with_clause with_item as_pattern call identifier argument_list binary_operator binary_operator binary_operator attribute identifier identifier string string_start string_content string_end call identifier argument_list call attribute identifier identifier argument_list string string_start string_content string_end string string_start string_content string_end as_pattern_target identifier block expression_statement call attribute identifier identifier argument_list attribute identifier identifier identifier | Dump data into json file. |
def guard_retract(analysis):
if not is_transition_allowed(analysis.getDependents(), "retract"):
return False
dependencies = analysis.getDependencies()
if not dependencies:
return True
if all(map(lambda an: IVerified.providedBy(an), dependencies)):
return False
return True | module function_definition identifier parameters identifier block if_statement not_operator call identifier argument_list call attribute identifier identifier argument_list string string_start string_content string_end block return_statement false expression_statement assignment identifier call attribute identifier identifier argument_list if_statement not_operator identifier block return_statement true if_statement call identifier argument_list call identifier argument_list lambda lambda_parameters identifier call attribute identifier identifier argument_list identifier identifier block return_statement false return_statement true | Return whether the transition "retract" can be performed or not |
def _get_all_packages(mirror=DEFAULT_MIRROR,
cyg_arch='x86_64'):
if 'cyg.all_packages' not in __context__:
__context__['cyg.all_packages'] = {}
if mirror not in __context__['cyg.all_packages']:
__context__['cyg.all_packages'][mirror] = []
if not __context__['cyg.all_packages'][mirror]:
pkg_source = '/'.join([mirror, cyg_arch, 'setup.bz2'])
file_data = _urlopen(pkg_source).read()
file_lines = bz2.decompress(file_data).decode('utf_8',
errors='replace'
).splitlines()
packages = [re.search('^@ ([^ ]+)', line).group(1) for
line in file_lines if re.match('^@ [^ ]+', line)]
__context__['cyg.all_packages'][mirror] = packages
return __context__['cyg.all_packages'][mirror] | module function_definition identifier parameters default_parameter identifier identifier default_parameter identifier string string_start string_content string_end block 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 dictionary if_statement comparison_operator identifier subscript identifier string string_start string_content string_end block expression_statement assignment subscript subscript identifier string string_start string_content string_end identifier list if_statement not_operator subscript subscript identifier string string_start string_content string_end identifier block expression_statement assignment identifier call attribute string string_start string_content string_end identifier argument_list list identifier identifier string string_start string_content string_end expression_statement assignment identifier call attribute call identifier argument_list identifier identifier argument_list expression_statement assignment identifier call attribute call attribute call attribute identifier identifier argument_list identifier identifier argument_list string string_start string_content string_end keyword_argument identifier string string_start string_content string_end identifier argument_list expression_statement assignment identifier list_comprehension call attribute call attribute identifier identifier argument_list string string_start string_content string_end identifier identifier argument_list integer for_in_clause identifier identifier if_clause call attribute identifier identifier argument_list string string_start string_content string_end identifier expression_statement assignment subscript subscript identifier string string_start string_content string_end identifier identifier return_statement subscript subscript identifier string string_start string_content string_end identifier | Return the list of packages based on the mirror provided. |
def url2domain(url):
parsed_uri = urlparse.urlparse(url)
domain = '{uri.netloc}'.format(uri=parsed_uri)
domain = re.sub("^.+@", "", domain)
domain = re.sub(":.+$", "", domain)
return domain | module function_definition identifier parameters identifier block expression_statement assignment identifier call attribute identifier identifier argument_list identifier expression_statement assignment identifier call attribute string string_start string_content string_end identifier argument_list keyword_argument identifier identifier expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end string string_start string_end identifier expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end string string_start string_end identifier return_statement identifier | extract domain from url |
def upload_html(destination, html, name=None):
[project, path, n] = parse_destination(destination)
try:
dxfile = dxpy.upload_string(html, media_type="text/html", project=project, folder=path, hidden=True, name=name or None)
return dxfile.get_id()
except dxpy.DXAPIError as ex:
parser.error("Could not upload HTML report to DNAnexus server! ({ex})".format(ex=ex)) | module function_definition identifier parameters identifier identifier default_parameter identifier none block expression_statement assignment list_pattern identifier identifier identifier call identifier argument_list identifier try_statement block expression_statement assignment identifier call attribute identifier identifier argument_list identifier keyword_argument identifier string string_start string_content string_end keyword_argument identifier identifier keyword_argument identifier identifier keyword_argument identifier true keyword_argument identifier boolean_operator identifier none return_statement call attribute identifier identifier argument_list except_clause as_pattern attribute identifier identifier as_pattern_target identifier block expression_statement call attribute identifier identifier argument_list call attribute string string_start string_content string_end identifier argument_list keyword_argument identifier identifier | Uploads the HTML to a file on the server |
def make_header(field_names, permit_not=False):
slug_chars = SLUG_CHARS if not permit_not else SLUG_CHARS + "^"
header = [
slug(field_name, permitted_chars=slug_chars) for field_name in field_names
]
result = []
for index, field_name in enumerate(header):
if not field_name:
field_name = "field_{}".format(index)
elif field_name[0].isdigit():
field_name = "field_{}".format(field_name)
if field_name in result:
field_name = make_unique_name(
name=field_name, existing_names=result, start=2
)
result.append(field_name)
return result | module function_definition identifier parameters identifier default_parameter identifier false block expression_statement assignment identifier conditional_expression identifier not_operator identifier binary_operator identifier string string_start string_content string_end expression_statement assignment identifier list_comprehension call identifier argument_list identifier keyword_argument identifier identifier for_in_clause identifier identifier expression_statement assignment identifier list for_statement pattern_list identifier identifier call identifier argument_list identifier block if_statement not_operator identifier block expression_statement assignment identifier call attribute string string_start string_content string_end identifier argument_list identifier elif_clause call attribute subscript identifier integer identifier argument_list block expression_statement assignment identifier call attribute string string_start string_content string_end identifier argument_list identifier if_statement comparison_operator identifier identifier block expression_statement assignment identifier call identifier argument_list keyword_argument identifier identifier keyword_argument identifier identifier keyword_argument identifier integer expression_statement call attribute identifier identifier argument_list identifier return_statement identifier | Return unique and slugged field names. |
def help_cli(self):
help = '%sWelcome to Workbench CLI Help:%s' % (color.Yellow, color.Normal)
help += '\n\t%s> help cli_basic %s for getting started help' % (color.Green, color.LightBlue)
help += '\n\t%s> help workers %s for help on available workers' % (color.Green, color.LightBlue)
help += '\n\t%s> help search %s for help on searching samples' % (color.Green, color.LightBlue)
help += '\n\t%s> help dataframe %s for help on making dataframes' % (color.Green, color.LightBlue)
help += '\n\t%s> help commands %s for help on workbench commands' % (color.Green, color.LightBlue)
help += '\n\t%s> help topic %s where topic can be a help, command or worker' % (color.Green, color.LightBlue)
help += '\n\n%sNote: cli commands are transformed into python calls' % (color.Yellow)
help += '\n\t%s> help cli_basic --> help("cli_basic")%s' % (color.Green, color.Normal)
return help | module function_definition identifier parameters identifier block expression_statement assignment identifier binary_operator string string_start string_content string_end tuple attribute identifier identifier attribute identifier identifier expression_statement augmented_assignment identifier binary_operator string string_start string_content escape_sequence escape_sequence string_end tuple attribute identifier identifier attribute identifier identifier expression_statement augmented_assignment identifier binary_operator string string_start string_content escape_sequence escape_sequence string_end tuple attribute identifier identifier attribute identifier identifier expression_statement augmented_assignment identifier binary_operator string string_start string_content escape_sequence escape_sequence string_end tuple attribute identifier identifier attribute identifier identifier expression_statement augmented_assignment identifier binary_operator string string_start string_content escape_sequence escape_sequence string_end tuple attribute identifier identifier attribute identifier identifier expression_statement augmented_assignment identifier binary_operator string string_start string_content escape_sequence escape_sequence string_end tuple attribute identifier identifier attribute identifier identifier expression_statement augmented_assignment identifier binary_operator string string_start string_content escape_sequence escape_sequence string_end tuple attribute identifier identifier attribute identifier identifier expression_statement augmented_assignment identifier binary_operator string string_start string_content escape_sequence escape_sequence string_end parenthesized_expression attribute identifier identifier expression_statement augmented_assignment identifier binary_operator string string_start string_content escape_sequence escape_sequence string_end tuple attribute identifier identifier attribute identifier identifier return_statement identifier | Help on Workbench CLI |
def index_exists(engine: Engine, tablename: str, indexname: str) -> bool:
insp = Inspector.from_engine(engine)
return any(i['name'] == indexname for i in insp.get_indexes(tablename)) | module function_definition identifier parameters typed_parameter identifier type identifier typed_parameter identifier type identifier typed_parameter identifier type identifier type identifier block expression_statement assignment identifier call attribute identifier identifier argument_list identifier return_statement call identifier generator_expression comparison_operator subscript identifier string string_start string_content string_end identifier for_in_clause identifier call attribute identifier identifier argument_list identifier | Does the specified index exist for the specified table? |
def require_mapping(self) -> None:
if not isinstance(self.yaml_node, yaml.MappingNode):
raise RecognitionError(('{}{}A mapping is required here').format(
self.yaml_node.start_mark, os.linesep)) | module function_definition identifier parameters identifier type none block if_statement not_operator call identifier argument_list attribute identifier identifier attribute identifier identifier block raise_statement call identifier argument_list call attribute parenthesized_expression string string_start string_content string_end identifier argument_list attribute attribute identifier identifier identifier attribute identifier identifier | Require the node to be a mapping. |
def readBuffer(self, newLength):
result = Buffer(self.buf, self.offset, newLength)
self.skip(newLength)
return result | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call identifier argument_list attribute identifier identifier attribute identifier identifier identifier expression_statement call attribute identifier identifier argument_list identifier return_statement identifier | Read next chunk as another buffer. |
def _fetch_data(self):
if (self.inputs.surface_target == "fsnative" or
self.inputs.volume_target != "MNI152NLin2009cAsym"):
raise NotImplementedError
annotation_files = sorted(glob(os.path.join(self.inputs.subjects_dir,
self.inputs.surface_target,
'label',
'*h.aparc.annot')))
if not annotation_files:
raise IOError("Freesurfer annotations for %s not found in %s" % (
self.inputs.surface_target, self.inputs.subjects_dir))
label_file = str(get_template(
'MNI152NLin2009cAsym', resolution=2, desc='DKT31', suffix='dseg'))
return annotation_files, label_file | module function_definition identifier parameters identifier block if_statement parenthesized_expression boolean_operator comparison_operator attribute attribute identifier identifier identifier string string_start string_content string_end comparison_operator attribute attribute identifier identifier identifier string string_start string_content string_end block raise_statement identifier expression_statement assignment identifier call identifier argument_list call identifier argument_list call attribute attribute identifier identifier identifier argument_list attribute attribute identifier identifier identifier attribute attribute identifier identifier identifier string string_start string_content string_end string string_start string_content string_end if_statement not_operator identifier block raise_statement call identifier argument_list binary_operator string string_start string_content string_end tuple attribute attribute identifier identifier identifier attribute attribute identifier identifier identifier expression_statement assignment identifier call identifier argument_list call identifier argument_list string string_start string_content string_end keyword_argument identifier integer keyword_argument identifier string string_start string_content string_end keyword_argument identifier string string_start string_content string_end return_statement expression_list identifier identifier | Converts inputspec to files |
async def wait(self) -> None:
if self.triggered_token is not None:
return
futures = [asyncio.ensure_future(self._triggered.wait(), loop=self.loop)]
for token in self._chain:
futures.append(asyncio.ensure_future(token.wait(), loop=self.loop))
def cancel_not_done(fut: 'asyncio.Future[None]') -> None:
for future in futures:
if not future.done():
future.cancel()
async def _wait_for_first(futures: Sequence[Awaitable[Any]]) -> None:
for future in asyncio.as_completed(futures):
await cast(Awaitable[Any], future)
return
fut = asyncio.ensure_future(_wait_for_first(futures), loop=self.loop)
fut.add_done_callback(cancel_not_done)
await fut | module function_definition identifier parameters identifier type none block if_statement comparison_operator attribute identifier identifier none block return_statement expression_statement assignment identifier list call attribute identifier identifier argument_list call attribute attribute identifier identifier identifier argument_list keyword_argument identifier attribute identifier identifier for_statement identifier attribute identifier identifier block expression_statement call attribute identifier identifier argument_list call attribute identifier identifier argument_list call attribute identifier identifier argument_list keyword_argument identifier attribute identifier identifier function_definition identifier parameters typed_parameter identifier type string string_start string_content string_end type none block for_statement identifier identifier block if_statement not_operator call attribute identifier identifier argument_list block expression_statement call attribute identifier identifier argument_list function_definition identifier parameters typed_parameter identifier type generic_type identifier type_parameter type generic_type identifier type_parameter type identifier type none block for_statement identifier call attribute identifier identifier argument_list identifier block expression_statement await call identifier argument_list subscript identifier identifier identifier return_statement expression_statement assignment identifier call attribute identifier identifier argument_list call identifier argument_list identifier keyword_argument identifier attribute identifier identifier expression_statement call attribute identifier identifier argument_list identifier expression_statement await identifier | Coroutine which returns when this token has been triggered |
def session(self) -> BaseFileWriterSession:
return self.session_class(
self._path_namer,
self._file_continuing,
self._headers_included,
self._local_timestamping,
self._adjust_extension,
self._content_disposition,
self._trust_server_names,
) | module function_definition identifier parameters identifier type identifier block return_statement call attribute identifier identifier argument_list attribute identifier identifier attribute identifier identifier attribute identifier identifier attribute identifier identifier attribute identifier identifier attribute identifier identifier attribute identifier identifier | Return the File Writer Session. |
def agent_path(cls, project, agent):
return google.api_core.path_template.expand(
'projects/{project}/agents/{agent}',
project=project,
agent=agent,
) | module function_definition identifier parameters identifier identifier identifier block return_statement call attribute attribute attribute identifier identifier identifier identifier argument_list string string_start string_content string_end keyword_argument identifier identifier keyword_argument identifier identifier | Return a fully-qualified agent string. |
def _sanity_check_fold_scope_locations_are_unique(ir_blocks):
observed_locations = dict()
for block in ir_blocks:
if isinstance(block, Fold):
alternate = observed_locations.get(block.fold_scope_location, None)
if alternate is not None:
raise AssertionError(u'Found two Fold blocks with identical FoldScopeLocations: '
u'{} {} {}'.format(alternate, block, ir_blocks))
observed_locations[block.fold_scope_location] = block | module function_definition identifier parameters identifier block expression_statement assignment identifier call identifier argument_list for_statement identifier identifier block if_statement call identifier argument_list identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list attribute identifier identifier none if_statement comparison_operator identifier none block raise_statement call identifier argument_list call attribute concatenated_string string string_start string_content string_end string string_start string_content string_end identifier argument_list identifier identifier identifier expression_statement assignment subscript identifier attribute identifier identifier identifier | Assert that every FoldScopeLocation that exists on a Fold block is unique. |
def remap_index_fn(ref_file):
snap_dir = os.path.join(os.path.dirname(ref_file), os.pardir, "snap")
assert os.path.exists(snap_dir) and os.path.isdir(snap_dir), snap_dir
return snap_dir | module function_definition identifier parameters identifier block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list call attribute attribute identifier identifier identifier argument_list identifier attribute identifier identifier string string_start string_content string_end assert_statement boolean_operator call attribute attribute identifier identifier identifier argument_list identifier call attribute attribute identifier identifier identifier argument_list identifier identifier return_statement identifier | Map sequence references to snap reference directory, using standard layout. |
def end_tag(self, alt=None):
if alt:
name = alt
else:
name = self.name
return "</" + name + ">" | module function_definition identifier parameters identifier default_parameter identifier none block if_statement identifier block expression_statement assignment identifier identifier else_clause block expression_statement assignment identifier attribute identifier identifier return_statement binary_operator binary_operator string string_start string_content string_end identifier string string_start string_content string_end | Return XML end tag for the receiver. |
def with_args(self, **kwargs):
validators = [
validator.with_args(**kwargs)
if hasattr(validator, 'with_args') else validator
for validator in self.validators
]
return mutablerecords.CopyRecord(
self, name=util.format_string(self.name, kwargs),
docstring=util.format_string(self.docstring, kwargs),
validators=validators,
_cached=None,
) | module function_definition identifier parameters identifier dictionary_splat_pattern identifier block expression_statement assignment identifier list_comprehension conditional_expression call attribute identifier identifier argument_list dictionary_splat identifier call identifier argument_list identifier string string_start string_content string_end identifier for_in_clause identifier attribute identifier identifier return_statement call attribute identifier identifier argument_list identifier keyword_argument identifier call attribute identifier identifier argument_list attribute identifier identifier identifier keyword_argument identifier call attribute identifier identifier argument_list attribute identifier identifier identifier keyword_argument identifier identifier keyword_argument identifier none | String substitution for names and docstrings. |
def validate_keys(dict_, expected, funcname):
expected = set(expected)
received = set(dict_)
missing = expected - received
if missing:
raise ValueError(
"Missing keys in {}:\n"
"Expected Keys: {}\n"
"Received Keys: {}".format(
funcname,
sorted(expected),
sorted(received),
)
)
unexpected = received - expected
if unexpected:
raise ValueError(
"Unexpected keys in {}:\n"
"Expected Keys: {}\n"
"Received Keys: {}".format(
funcname,
sorted(expected),
sorted(received),
)
) | module function_definition identifier parameters identifier identifier identifier block expression_statement assignment identifier call identifier argument_list identifier expression_statement assignment identifier call identifier argument_list identifier expression_statement assignment identifier binary_operator identifier identifier if_statement identifier block raise_statement call identifier argument_list call attribute concatenated_string string string_start string_content escape_sequence string_end string string_start string_content escape_sequence string_end string string_start string_content string_end identifier argument_list identifier call identifier argument_list identifier call identifier argument_list identifier expression_statement assignment identifier binary_operator identifier identifier if_statement identifier block raise_statement call identifier argument_list call attribute concatenated_string string string_start string_content escape_sequence string_end string string_start string_content escape_sequence string_end string string_start string_content string_end identifier argument_list identifier call identifier argument_list identifier call identifier argument_list identifier | Validate that a dictionary has an expected set of keys. |
def ensure_legal(self):
if self._results_dir:
errors = ''
if not os.path.islink(self._results_dir):
errors += '\nThe results_dir is no longer a symlink:\n\t* {}'.format(self._results_dir)
if not os.path.isdir(self._current_results_dir):
errors += '\nThe current_results_dir directory was not found\n\t* {}'.format(self._current_results_dir)
if errors:
raise self.IllegalResultsDir(
'\nThe results_dirs state should not be manually cleaned or recreated by tasks.\n{}'.format(errors)
)
return True | module function_definition identifier parameters identifier block if_statement attribute identifier identifier block expression_statement assignment identifier string string_start string_end if_statement not_operator call attribute attribute identifier identifier identifier argument_list attribute identifier identifier block expression_statement augmented_assignment identifier call attribute string string_start string_content escape_sequence escape_sequence escape_sequence string_end identifier argument_list attribute identifier identifier if_statement not_operator call attribute attribute identifier identifier identifier argument_list attribute identifier identifier block expression_statement augmented_assignment identifier call attribute string string_start string_content escape_sequence escape_sequence escape_sequence string_end identifier argument_list attribute identifier identifier if_statement identifier block raise_statement call attribute identifier identifier argument_list call attribute string string_start string_content escape_sequence escape_sequence string_end identifier argument_list identifier return_statement true | Return True as long as the state does not break any internal contracts. |
def __setupViews(self):
self._collector = Collector(self.windowNumber)
self.configWidget = ConfigWidget(self._configTreeModel)
self.repoWidget = RepoWidget(self.argosApplication.repo, self.collector)
widget = QtWidgets.QWidget()
layout = QtWidgets.QVBoxLayout(widget)
layout.setContentsMargins(CENTRAL_MARGIN, CENTRAL_MARGIN, CENTRAL_MARGIN, CENTRAL_MARGIN)
layout.setSpacing(CENTRAL_SPACING)
self.setCentralWidget(widget)
self.collector.sigContentsChanged.connect(self.collectorContentsChanged)
self._configTreeModel.sigItemChanged.connect(self.configContentsChanged) | module function_definition identifier parameters identifier block expression_statement assignment attribute identifier identifier call identifier argument_list attribute identifier identifier expression_statement assignment attribute identifier identifier call identifier argument_list attribute identifier identifier expression_statement assignment attribute identifier identifier call identifier argument_list attribute attribute identifier identifier identifier attribute identifier identifier expression_statement assignment identifier call attribute identifier identifier argument_list expression_statement assignment identifier call attribute identifier identifier argument_list identifier expression_statement call attribute identifier identifier argument_list identifier identifier identifier identifier expression_statement call attribute identifier identifier argument_list identifier expression_statement call attribute identifier identifier argument_list identifier expression_statement call attribute attribute attribute identifier identifier identifier identifier argument_list attribute identifier identifier expression_statement call attribute attribute attribute identifier identifier identifier identifier argument_list attribute identifier identifier | Creates the UI widgets. |
def seebeck_spb(eta,Lambda=0.5):
from fdint import fdk
return constants.k/constants.e * ((2. + Lambda) * fdk( 1.+ Lambda, eta)/
((1.+Lambda)*fdk(Lambda, eta))- eta) * 1e+6 | module function_definition identifier parameters identifier default_parameter identifier float block import_from_statement dotted_name identifier dotted_name identifier return_statement binary_operator binary_operator binary_operator attribute identifier identifier attribute identifier identifier parenthesized_expression binary_operator binary_operator binary_operator parenthesized_expression binary_operator float identifier call identifier argument_list binary_operator float identifier identifier parenthesized_expression binary_operator parenthesized_expression binary_operator float identifier call identifier argument_list identifier identifier identifier float | Seebeck analytic formula in the single parabolic model |
def communicator(func):
def _call(queue, args, kwargs):
kwargs['queue'] = queue
ret = None
try:
ret = func(*args, **kwargs)
queue.put('END')
except KeyboardInterrupt as ex:
trace = traceback.format_exc()
queue.put('KEYBOARDINT')
queue.put('Keyboard interrupt')
queue.put('{0}\n{1}\n'.format(ex, trace))
except Exception as ex:
trace = traceback.format_exc()
queue.put('ERROR')
queue.put('Exception')
queue.put('{0}\n{1}\n'.format(ex, trace))
except SystemExit as ex:
trace = traceback.format_exc()
queue.put('ERROR')
queue.put('System exit')
queue.put('{0}\n{1}\n'.format(ex, trace))
return ret
return _call | module function_definition identifier parameters identifier block function_definition identifier parameters identifier identifier identifier block expression_statement assignment subscript identifier string string_start string_content string_end identifier expression_statement assignment identifier none try_statement block expression_statement assignment identifier call identifier argument_list list_splat identifier dictionary_splat identifier expression_statement call attribute identifier identifier argument_list string string_start string_content string_end except_clause as_pattern identifier as_pattern_target identifier block expression_statement assignment identifier call attribute identifier identifier argument_list expression_statement call attribute identifier identifier argument_list string string_start string_content string_end expression_statement call attribute identifier identifier argument_list string string_start string_content string_end expression_statement call attribute identifier identifier argument_list call attribute string string_start string_content escape_sequence escape_sequence string_end identifier argument_list identifier identifier except_clause as_pattern identifier as_pattern_target identifier block expression_statement assignment identifier call attribute identifier identifier argument_list expression_statement call attribute identifier identifier argument_list string string_start string_content string_end expression_statement call attribute identifier identifier argument_list string string_start string_content string_end expression_statement call attribute identifier identifier argument_list call attribute string string_start string_content escape_sequence escape_sequence string_end identifier argument_list identifier identifier except_clause as_pattern identifier as_pattern_target identifier block expression_statement assignment identifier call attribute identifier identifier argument_list expression_statement call attribute identifier identifier argument_list string string_start string_content string_end expression_statement call attribute identifier identifier argument_list string string_start string_content string_end expression_statement call attribute identifier identifier argument_list call attribute string string_start string_content escape_sequence escape_sequence string_end identifier argument_list identifier identifier return_statement identifier return_statement identifier | Warning, this is a picklable decorator ! |
def _nested_add(nested_a, nested_b):
return nest.map(lambda a, b: a + b, nested_a, nested_b) | module function_definition identifier parameters identifier identifier block return_statement call attribute identifier identifier argument_list lambda lambda_parameters identifier identifier binary_operator identifier identifier identifier identifier | Add two arbitrarily nested `Tensors`. |
def purge(self, connection):
self._checkpid()
if connection.pid == self.pid:
idx = connection._pattern_idx
if connection in self._in_use_connections[idx]:
self._in_use_connections[idx].remove(connection)
else:
self._available_connections[idx].remove(connection)
connection.disconnect() | module function_definition identifier parameters identifier identifier block expression_statement call attribute identifier identifier argument_list if_statement comparison_operator attribute identifier identifier attribute identifier identifier block expression_statement assignment identifier attribute identifier identifier if_statement comparison_operator identifier subscript attribute identifier identifier identifier block expression_statement call attribute subscript attribute identifier identifier identifier identifier argument_list identifier else_clause block expression_statement call attribute subscript attribute identifier identifier identifier identifier argument_list identifier expression_statement call attribute identifier identifier argument_list | Remove the connection from rotation |
def reduce_sum(attrs, inputs, proto_obj):
new_attrs = translation_utils._fix_attribute_names(attrs, {'axes':'axis'})
return 'sum', new_attrs, inputs | module function_definition identifier parameters identifier identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list identifier dictionary pair string string_start string_content string_end string string_start string_content string_end return_statement expression_list string string_start string_content string_end identifier identifier | Reduce the array along a given axis by sum value |
def project_deidentify_template_path(cls, project, deidentify_template):
return google.api_core.path_template.expand(
"projects/{project}/deidentifyTemplates/{deidentify_template}",
project=project,
deidentify_template=deidentify_template,
) | module function_definition identifier parameters identifier identifier identifier block return_statement call attribute attribute attribute identifier identifier identifier identifier argument_list string string_start string_content string_end keyword_argument identifier identifier keyword_argument identifier identifier | Return a fully-qualified project_deidentify_template string. |
def parse_schedules(username, password, importer, progress, utc_start=None,
utc_stop=None):
file_obj = get_file_object(username, password, utc_start, utc_stop)
process_file_object(file_obj, importer, progress) | module function_definition identifier parameters identifier identifier identifier identifier default_parameter identifier none default_parameter identifier none block expression_statement assignment identifier call identifier argument_list identifier identifier identifier identifier expression_statement call identifier argument_list identifier identifier identifier | A utility function to marry the connecting and reading functions. |
def _loadOneSource(self, sourceFName):
sourceLines = open(sourceFName).readlines()
del sourceLines[0]
if len(sourceLines[0].split("\t"))==2:
self._loadTwoPartSource(sourceFName, sourceLines)
elif len(sourceLines[0].split("\t"))==3:
self._loadThreePartSource(sourceFName, sourceLines)
else:
raise Error, "%s does not appear to be a source authority file" | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call attribute call identifier argument_list identifier identifier argument_list delete_statement subscript identifier integer if_statement comparison_operator call identifier argument_list call attribute subscript identifier integer identifier argument_list string string_start string_content escape_sequence string_end integer block expression_statement call attribute identifier identifier argument_list identifier identifier elif_clause comparison_operator call identifier argument_list call attribute subscript identifier integer identifier argument_list string string_start string_content escape_sequence string_end integer block expression_statement call attribute identifier identifier argument_list identifier identifier else_clause block raise_statement expression_list identifier string string_start string_content string_end | handles one authority file including format auto-detection. |
def _check_response_for_errors(self, response):
try:
doc = minidom.parseString(_string(response).replace("opensearch:", ""))
except Exception as e:
raise MalformedResponseError(self.network, e)
e = doc.getElementsByTagName("lfm")[0]
if e.getAttribute("status") != "ok":
e = doc.getElementsByTagName("error")[0]
status = e.getAttribute("code")
details = e.firstChild.data.strip()
raise WSError(self.network, status, details) | module function_definition identifier parameters identifier identifier block try_statement block expression_statement assignment identifier call attribute identifier identifier argument_list call attribute call identifier argument_list identifier identifier argument_list string string_start string_content string_end string string_start string_end except_clause as_pattern identifier as_pattern_target identifier block raise_statement call identifier argument_list attribute identifier identifier identifier expression_statement assignment identifier subscript call attribute identifier identifier argument_list string string_start string_content string_end integer if_statement comparison_operator call attribute identifier identifier argument_list string string_start string_content string_end string string_start string_content string_end block expression_statement assignment identifier subscript call attribute identifier identifier argument_list string string_start string_content string_end integer expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end expression_statement assignment identifier call attribute attribute attribute identifier identifier identifier identifier argument_list raise_statement call identifier argument_list attribute identifier identifier identifier identifier | Checks the response for errors and raises one if any exists. |
def _write_header(self):
for line in self.header.lines:
print(line.serialize(), file=self.stream)
if self.header.samples.names:
print(
"\t".join(list(parser.REQUIRE_SAMPLE_HEADER) + self.header.samples.names),
file=self.stream,
)
else:
print("\t".join(parser.REQUIRE_NO_SAMPLE_HEADER), file=self.stream) | module function_definition identifier parameters identifier block for_statement identifier attribute attribute identifier identifier identifier block expression_statement call identifier argument_list call attribute identifier identifier argument_list keyword_argument identifier attribute identifier identifier if_statement attribute attribute attribute identifier identifier identifier identifier block expression_statement call identifier argument_list call attribute string string_start string_content escape_sequence string_end identifier argument_list binary_operator call identifier argument_list attribute identifier identifier attribute attribute attribute identifier identifier identifier identifier keyword_argument identifier attribute identifier identifier else_clause block expression_statement call identifier argument_list call attribute string string_start string_content escape_sequence string_end identifier argument_list attribute identifier identifier keyword_argument identifier attribute identifier identifier | Write out the header |
def _center(code, segment_dict):
while code in segment_dict:
segment = segment_dict[code]
yield segment
code = segment.center | module function_definition identifier parameters identifier identifier block while_statement comparison_operator identifier identifier block expression_statement assignment identifier subscript identifier identifier expression_statement yield identifier expression_statement assignment identifier attribute identifier identifier | Starting with `code`, follow segments from target to center. |
def close(self):
self.is_closed = True
try:
self.smtp.quit()
except (TypeError, AttributeError, smtplib.SMTPServerDisconnected):
pass | module function_definition identifier parameters identifier block expression_statement assignment attribute identifier identifier true try_statement block expression_statement call attribute attribute identifier identifier identifier argument_list except_clause tuple identifier identifier attribute identifier identifier block pass_statement | Close the connection to the SMTP server |
def all_from(cls, *args, **kwargs):
pq_items = cls._get_items(*args, **kwargs)
return [cls(item=i) for i in pq_items.items()] | module function_definition identifier parameters identifier list_splat_pattern identifier dictionary_splat_pattern identifier block expression_statement assignment identifier call attribute identifier identifier argument_list list_splat identifier dictionary_splat identifier return_statement list_comprehension call identifier argument_list keyword_argument identifier identifier for_in_clause identifier call attribute identifier identifier argument_list | Query for items passing PyQuery args explicitly. |
def check_buffer(coords, length, buffer):
s = min(coords[0], buffer)
e = min(length - coords[1], buffer)
return [s, e] | module function_definition identifier parameters identifier identifier identifier block expression_statement assignment identifier call identifier argument_list subscript identifier integer identifier expression_statement assignment identifier call identifier argument_list binary_operator identifier subscript identifier integer identifier return_statement list identifier identifier | check to see how much of the buffer is being used |
def _from_selection(self):
return (self.groupby is not None and
(self.groupby.key is not None or
self.groupby.level is not None)) | module function_definition identifier parameters identifier block return_statement parenthesized_expression boolean_operator comparison_operator attribute identifier identifier none parenthesized_expression boolean_operator comparison_operator attribute attribute identifier identifier identifier none comparison_operator attribute attribute identifier identifier identifier none | Is the resampling from a DataFrame column or MultiIndex level. |
def on_train_end(self, **kwargs: Any) -> None:
"Store the notebook and stop run"
self.client.log_artifact(run_id=self.run, local_path=self.nb_path)
self.client.set_terminated(run_id=self.run) | module function_definition identifier parameters identifier typed_parameter dictionary_splat_pattern identifier type identifier type none block expression_statement string string_start string_content string_end expression_statement call attribute attribute identifier identifier identifier argument_list keyword_argument identifier attribute identifier identifier keyword_argument identifier attribute identifier identifier expression_statement call attribute attribute identifier identifier identifier argument_list keyword_argument identifier attribute identifier identifier | Store the notebook and stop run |
def do_extra_polishing(self):
for f in self.EXTRA_POLISH_FUNCTIONS:
if not hasattr(f, 'polish_commit_indexes'):
if hasattr(f, 'polish_urls') and self.URL in f.polish_urls:
f()
if not hasattr(f, 'polish_urls'):
if hasattr(f, 'polish_commit_indexes') and self.CURRENT_COMMIT_INDEX in f.polish_commit_indexes:
f()
if hasattr(f, 'polish_commit_indexes') and hasattr(f, 'polish_urls'):
if self.URL in f.polish_urls and self.CURRENT_COMMIT_INDEX in f.polish_commit_indexes:
f() | module function_definition identifier parameters identifier block for_statement identifier attribute identifier identifier block if_statement not_operator call identifier argument_list identifier string string_start string_content string_end block if_statement boolean_operator call identifier argument_list identifier string string_start string_content string_end comparison_operator attribute identifier identifier attribute identifier identifier block expression_statement call identifier argument_list if_statement not_operator call identifier argument_list identifier string string_start string_content string_end block if_statement boolean_operator call identifier argument_list identifier string string_start string_content string_end comparison_operator attribute identifier identifier attribute identifier identifier block expression_statement call identifier argument_list if_statement boolean_operator call identifier argument_list identifier string string_start string_content string_end call identifier argument_list identifier string string_start string_content string_end block if_statement boolean_operator comparison_operator attribute identifier identifier attribute identifier identifier comparison_operator attribute identifier identifier attribute identifier identifier block expression_statement call identifier argument_list | Goes over each EXTRA_POLISH_FUNCTION to see if it applies to this page, if so, calls it |
def retrain(self):
folder = TrainData.from_folder(self.args.folder)
train_data, test_data = folder.load(True, not self.args.no_validation)
train_data = TrainData.merge(train_data, self.sampled_data)
test_data = TrainData.merge(test_data, self.test)
train_inputs, train_outputs = train_data
print()
try:
self.listener.runner.model.fit(
train_inputs, train_outputs, self.args.batch_size, self.epoch + self.args.epochs,
validation_data=test_data, callbacks=self.callbacks, initial_epoch=self.epoch
)
finally:
self.listener.runner.model.save(self.args.model) | module function_definition identifier parameters identifier block expression_statement assignment identifier call attribute identifier identifier argument_list attribute attribute identifier identifier identifier expression_statement assignment pattern_list identifier identifier call attribute identifier identifier argument_list true not_operator attribute attribute identifier identifier identifier expression_statement assignment identifier call attribute identifier identifier argument_list identifier attribute identifier identifier expression_statement assignment identifier call attribute identifier identifier argument_list identifier attribute identifier identifier expression_statement assignment pattern_list identifier identifier identifier expression_statement call identifier argument_list try_statement block expression_statement call attribute attribute attribute attribute identifier identifier identifier identifier identifier argument_list identifier identifier attribute attribute identifier identifier identifier binary_operator attribute identifier identifier attribute attribute identifier identifier identifier keyword_argument identifier identifier keyword_argument identifier attribute identifier identifier keyword_argument identifier attribute identifier identifier finally_clause block expression_statement call attribute attribute attribute attribute identifier identifier identifier identifier identifier argument_list attribute attribute identifier identifier identifier | Train for a session, pulling in any new data from the filesystem |
def verify_mapillary_tag(filepath):
filepath_keep_original = processing.processed_images_rootpath(filepath)
if os.path.isfile(filepath_keep_original):
filepath = filepath_keep_original
return ExifRead(filepath).mapillary_tag_exists() | module function_definition identifier parameters identifier block expression_statement assignment identifier call attribute identifier identifier argument_list identifier if_statement call attribute attribute identifier identifier identifier argument_list identifier block expression_statement assignment identifier identifier return_statement call attribute call identifier argument_list identifier identifier argument_list | Check that image file has the required Mapillary tag |
def print_spelling_errors(filename, encoding='utf8'):
filesize = os.stat(filename).st_size
if filesize:
sys.stdout.write('Misspelled Words:\n')
with io.open(filename, encoding=encoding) as wordlist:
for line in wordlist:
sys.stdout.write(' ' + line)
return 1 if filesize else 0 | module function_definition identifier parameters identifier default_parameter identifier string string_start string_content string_end block expression_statement assignment identifier attribute call attribute identifier identifier argument_list identifier identifier if_statement identifier block expression_statement call attribute attribute identifier identifier identifier argument_list string string_start string_content escape_sequence string_end with_statement with_clause with_item as_pattern call attribute identifier identifier argument_list identifier keyword_argument identifier identifier as_pattern_target identifier 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 return_statement conditional_expression integer identifier integer | Print misspelled words returned by sphinxcontrib-spelling |
def _get_instance_params(cls, instance):
url = instance.get("url")
if url is None:
raise ConfigurationError("You must specify a url for your instance in `conf.yaml`")
username = instance.get("username")
password = instance.get("password")
ssl_params = None
if url.startswith("ldaps"):
ssl_params = {
"key": instance.get("ssl_key"),
"cert": instance.get("ssl_cert"),
"ca_certs": instance.get("ssl_ca_certs"),
"verify": is_affirmative(instance.get("ssl_verify", True)),
}
custom_queries = instance.get("custom_queries", [])
tags = list(instance.get("tags", []))
tags.append("url:{}".format(url))
return url, username, password, ssl_params, custom_queries, tags | 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 identifier none block raise_statement call identifier argument_list string string_start string_content string_end expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end expression_statement assignment identifier none if_statement call attribute identifier identifier argument_list string string_start string_content string_end block expression_statement assignment identifier dictionary pair string string_start string_content string_end call attribute identifier identifier argument_list string string_start string_content string_end pair string string_start string_content string_end call attribute identifier identifier argument_list string string_start string_content string_end pair string string_start string_content string_end call attribute identifier identifier argument_list string string_start string_content string_end pair string string_start string_content string_end call identifier argument_list call attribute identifier identifier argument_list string string_start string_content string_end true expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end list expression_statement assignment identifier call identifier argument_list call attribute identifier identifier argument_list string string_start string_content string_end list expression_statement call attribute identifier identifier argument_list call attribute string string_start string_content string_end identifier argument_list identifier return_statement expression_list identifier identifier identifier identifier identifier identifier | Parse instance configuration and perform minimal verification |
def dirsize_get(l_filesWithoutPath, **kwargs):
str_path = ""
for k,v in kwargs.items():
if k == 'path': str_path = v
d_ret = {}
l_size = []
size = 0
for f in l_filesWithoutPath:
str_f = '%s/%s' % (str_path, f)
if not os.path.islink(str_f):
try:
size += os.path.getsize(str_f)
except:
pass
str_size = pftree.sizeof_fmt(size)
return {
'status': True,
'diskUsage_raw': size,
'diskUsage_human': str_size
} | module function_definition identifier parameters identifier dictionary_splat_pattern identifier block expression_statement assignment identifier string string_start string_end for_statement pattern_list identifier identifier call attribute identifier identifier argument_list block if_statement comparison_operator identifier string string_start string_content string_end block expression_statement assignment identifier identifier expression_statement assignment identifier dictionary expression_statement assignment identifier list expression_statement assignment identifier integer for_statement identifier identifier block expression_statement assignment 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 try_statement block expression_statement augmented_assignment identifier call attribute attribute identifier identifier identifier argument_list identifier except_clause block pass_statement expression_statement assignment identifier call attribute identifier identifier argument_list identifier return_statement dictionary pair string string_start string_content string_end true pair string string_start string_content string_end identifier pair string string_start string_content string_end identifier | Sample callback that determines a directory size. |
def _check_if_downloaded(self):
if not os.path.isfile(self.path + self.file_name):
print("")
self.msg.template(78)
print("| Download '{0}' file [ {1}FAILED{2} ]".format(
self.file_name, self.meta.color["RED"],
self.meta.color["ENDC"]))
self.msg.template(78)
print("")
if not self.msg.answer() in ["y", "Y"]:
raise SystemExit() | module function_definition identifier parameters identifier block if_statement not_operator call attribute attribute identifier identifier identifier argument_list binary_operator attribute identifier identifier attribute identifier identifier block expression_statement call identifier argument_list string string_start string_end expression_statement call attribute attribute identifier identifier identifier argument_list integer expression_statement call identifier argument_list call attribute string string_start string_content string_end identifier argument_list attribute identifier identifier subscript attribute attribute identifier identifier identifier string string_start string_content string_end subscript attribute attribute identifier identifier identifier string string_start string_content string_end expression_statement call attribute attribute identifier identifier identifier argument_list integer expression_statement call identifier argument_list string string_start string_end if_statement not_operator comparison_operator call attribute attribute identifier identifier identifier argument_list list string string_start string_content string_end string string_start string_content string_end block raise_statement call identifier argument_list | Check if file downloaded |
def YamlLoader(string):
representation = yaml.Parse(string)
result_cls = aff4.FACTORY.AFF4Object(representation["aff4_class"])
aff4_attributes = {}
for predicate, values in iteritems(representation["attributes"]):
attribute = aff4.Attribute.PREDICATES[predicate]
tmp = aff4_attributes[attribute] = []
for rdfvalue_cls_name, value, age in values:
rdfvalue_cls = aff4.FACTORY.RDFValue(rdfvalue_cls_name)
value = rdfvalue_cls(value, age=rdfvalue.RDFDatetime(age))
tmp.append(value)
result = result_cls(
urn=representation["_urn"],
clone=aff4_attributes,
mode="rw",
age=representation["age_policy"])
result.new_attributes, result.synced_attributes = result.synced_attributes, {}
result._dirty = True
return result | module function_definition identifier parameters identifier block expression_statement assignment identifier call attribute identifier identifier argument_list identifier expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list subscript identifier string string_start string_content string_end expression_statement assignment identifier dictionary for_statement pattern_list identifier identifier call identifier argument_list subscript identifier string string_start string_content string_end block expression_statement assignment identifier subscript attribute attribute identifier identifier identifier identifier expression_statement assignment identifier assignment subscript identifier identifier list for_statement pattern_list identifier identifier identifier identifier block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list identifier expression_statement assignment identifier call identifier argument_list identifier keyword_argument identifier call attribute identifier identifier argument_list identifier expression_statement call attribute identifier identifier argument_list identifier expression_statement assignment identifier call identifier argument_list keyword_argument identifier subscript identifier string string_start string_content string_end keyword_argument identifier identifier keyword_argument identifier string string_start string_content string_end keyword_argument identifier subscript identifier string string_start string_content string_end expression_statement assignment pattern_list attribute identifier identifier attribute identifier identifier expression_list attribute identifier identifier dictionary expression_statement assignment attribute identifier identifier true return_statement identifier | Load an AFF4 object from a serialized YAML representation. |
def pool_attr_add(arg, opts, shell_opts):
res = Pool.list({ 'name': arg })
if len(res) < 1:
print("No pool with name '%s' found." % arg, file=sys.stderr)
sys.exit(1)
p = res[0]
for avp in opts.get('extra-attribute', []):
try:
key, value = avp.split('=', 1)
except ValueError:
print("ERROR: Incorrect extra-attribute: %s. Accepted form: 'key=value'\n" % avp, file=sys.stderr)
sys.exit(1)
if key in p.avps:
print("Unable to add extra-attribute: '%s' already exists." % key, file=sys.stderr)
sys.exit(1)
p.avps[key] = value
try:
p.save()
except NipapError as exc:
print("Could not save pool changes: %s" % str(exc), file=sys.stderr)
sys.exit(1)
print("Pool '%s' saved." % p.name) | module function_definition identifier parameters identifier identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list dictionary pair string string_start string_content string_end identifier if_statement comparison_operator call identifier argument_list identifier integer block expression_statement call identifier argument_list binary_operator string string_start string_content string_end identifier keyword_argument identifier attribute identifier identifier expression_statement call attribute identifier identifier argument_list integer expression_statement assignment identifier subscript identifier integer for_statement identifier call attribute identifier identifier argument_list string string_start string_content string_end list block try_statement block expression_statement assignment pattern_list identifier identifier call attribute identifier identifier argument_list string string_start string_content string_end integer except_clause identifier block expression_statement call identifier argument_list binary_operator string string_start string_content escape_sequence string_end identifier keyword_argument identifier attribute identifier identifier expression_statement call attribute identifier identifier argument_list integer if_statement comparison_operator identifier attribute identifier identifier block expression_statement call identifier argument_list binary_operator string string_start string_content string_end identifier keyword_argument identifier attribute identifier identifier expression_statement call attribute identifier identifier argument_list integer expression_statement assignment subscript attribute identifier identifier identifier identifier try_statement block expression_statement call attribute identifier identifier argument_list except_clause as_pattern identifier as_pattern_target identifier block expression_statement call identifier argument_list binary_operator string string_start string_content string_end call identifier argument_list identifier keyword_argument identifier attribute identifier identifier expression_statement call attribute identifier identifier argument_list integer expression_statement call identifier argument_list binary_operator string string_start string_content string_end attribute identifier identifier | Add attributes to a pool |
def _default_logfile(exe_name):
if salt.utils.platform.is_windows():
tmp_dir = os.path.join(__opts__['cachedir'], 'tmp')
if not os.path.isdir(tmp_dir):
os.mkdir(tmp_dir)
logfile_tmp = tempfile.NamedTemporaryFile(dir=tmp_dir,
prefix=exe_name,
suffix='.log',
delete=False)
logfile = logfile_tmp.name
logfile_tmp.close()
else:
logfile = salt.utils.path.join(
'/var/log',
'{0}.log'.format(exe_name)
)
return logfile | module function_definition identifier parameters identifier block if_statement call attribute attribute attribute identifier identifier identifier identifier argument_list block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list subscript identifier string string_start string_content string_end string string_start string_content string_end if_statement not_operator call attribute attribute identifier identifier identifier argument_list identifier block expression_statement call attribute identifier identifier argument_list identifier expression_statement assignment identifier call attribute identifier identifier argument_list keyword_argument identifier identifier keyword_argument identifier identifier keyword_argument identifier string string_start string_content string_end keyword_argument identifier false expression_statement assignment identifier attribute identifier identifier expression_statement call attribute identifier identifier argument_list else_clause block expression_statement assignment identifier call attribute attribute attribute identifier identifier identifier identifier argument_list string string_start string_content string_end call attribute string string_start string_content string_end identifier argument_list identifier return_statement identifier | Retrieve the logfile name |
def store_file(self, filename):
self.workbench = zerorpc.Client(timeout=300, heartbeat=60)
self.workbench.connect("tcp://127.0.0.1:4242")
storage_name = "streaming_pcap" + str(self.pcap_index)
print filename, storage_name
with open(filename,'rb') as f:
self.workbench.store_sample(f.read(), storage_name, 'pcap')
self.pcap_index += 1
self.workbench.close() | module function_definition identifier parameters identifier identifier block expression_statement assignment attribute identifier identifier call attribute identifier identifier argument_list keyword_argument identifier integer keyword_argument identifier integer expression_statement call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end expression_statement assignment identifier binary_operator string string_start string_content string_end call identifier argument_list attribute identifier identifier print_statement identifier identifier with_statement with_clause with_item as_pattern call identifier argument_list identifier string string_start string_content string_end as_pattern_target identifier block expression_statement call attribute attribute identifier identifier identifier argument_list call attribute identifier identifier argument_list identifier string string_start string_content string_end expression_statement augmented_assignment attribute identifier identifier integer expression_statement call attribute attribute identifier identifier identifier argument_list | Store a file into workbench |
def _check_fit_data(self, X):
X = check_array(X, accept_sparse="csr", dtype=[np.float64, np.float32])
n_samples, n_features = X.shape
if X.shape[0] < self.n_clusters:
raise ValueError(
"n_samples=%d should be >= n_clusters=%d"
% (X.shape[0], self.n_clusters)
)
for ee in range(n_samples):
if sp.issparse(X):
n = sp.linalg.norm(X[ee, :])
else:
n = np.linalg.norm(X[ee, :])
if np.abs(n - 1.) > 1e-4:
raise ValueError("Data l2-norm must be 1, found {}".format(n))
return X | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call identifier argument_list identifier keyword_argument identifier string string_start string_content string_end keyword_argument identifier list attribute identifier identifier attribute identifier identifier expression_statement assignment pattern_list identifier identifier attribute identifier identifier if_statement comparison_operator subscript attribute identifier identifier integer attribute identifier identifier block raise_statement call identifier argument_list binary_operator string string_start string_content string_end tuple subscript attribute identifier identifier integer attribute identifier identifier for_statement identifier call identifier argument_list identifier block if_statement call attribute identifier identifier argument_list identifier block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list subscript identifier identifier slice else_clause block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list subscript identifier identifier slice if_statement comparison_operator call attribute identifier identifier argument_list binary_operator identifier float float block raise_statement call identifier argument_list call attribute string string_start string_content string_end identifier argument_list identifier return_statement identifier | Verify that the number of samples given is larger than k |
def unlink_intermediate(self, sourceId, targetId):
source = self.database['items'][(self.database.get('name'), sourceId)]
target = self.database['items'][(self.database.get('name'), targetId)]
production_exchange = [x['input'] for x in source['exchanges'] if x['type'] == 'production'][0]
new_exchanges = [x for x in target['exchanges'] if x['input'] != production_exchange]
target['exchanges'] = new_exchanges
self.parameter_scan()
return True | module function_definition identifier parameters identifier identifier identifier block expression_statement assignment identifier subscript subscript attribute identifier identifier string string_start string_content string_end tuple call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end identifier expression_statement assignment identifier subscript subscript attribute identifier identifier string string_start string_content string_end tuple call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end identifier expression_statement assignment identifier subscript list_comprehension subscript identifier string string_start string_content string_end for_in_clause identifier subscript identifier string string_start string_content string_end if_clause comparison_operator subscript identifier string string_start string_content string_end string string_start string_content string_end integer expression_statement assignment identifier list_comprehension identifier for_in_clause identifier subscript identifier string string_start string_content string_end if_clause comparison_operator subscript identifier string string_start string_content string_end identifier expression_statement assignment subscript identifier string string_start string_content string_end identifier expression_statement call attribute identifier identifier argument_list return_statement true | Remove a link between two processes |
def catch_exceptions(*exceptions):
def wrap(fn):
@functools.wraps(fn)
def wrapped_f(*args, **kwargs):
try:
return fn(*args, **kwargs)
except exceptions:
t, value, traceback = sys.exc_info()
if str(value.status) == '404':
return None
e = CloudApiException(str(value), value.reason, value.status)
raise_(CloudApiException, e, traceback)
return wrapped_f
return wrap | module function_definition identifier parameters list_splat_pattern identifier block function_definition identifier parameters identifier block decorated_definition decorator call attribute identifier identifier argument_list identifier function_definition identifier parameters list_splat_pattern identifier dictionary_splat_pattern identifier block try_statement block return_statement call identifier argument_list list_splat identifier dictionary_splat identifier except_clause identifier block expression_statement assignment pattern_list identifier identifier identifier call attribute identifier identifier argument_list if_statement comparison_operator call identifier argument_list attribute identifier identifier string string_start string_content string_end block return_statement none expression_statement assignment identifier call identifier argument_list call identifier argument_list identifier attribute identifier identifier attribute identifier identifier expression_statement call identifier argument_list identifier identifier identifier return_statement identifier return_statement identifier | Catch all exceptions provided as arguments, and raise CloudApiException instead. |
def calculate_median(given_list):
median = None
if not given_list:
return median
given_list = sorted(given_list)
list_length = len(given_list)
if list_length % 2:
median = given_list[int(list_length / 2)]
else:
median = (given_list[int(list_length / 2)] + given_list[int(list_length / 2) - 1]) / 2.0
return median | module function_definition identifier parameters identifier block expression_statement assignment identifier none if_statement not_operator identifier block return_statement identifier expression_statement assignment identifier call identifier argument_list identifier expression_statement assignment identifier call identifier argument_list identifier if_statement binary_operator identifier integer block expression_statement assignment identifier subscript identifier call identifier argument_list binary_operator identifier integer else_clause block expression_statement assignment identifier binary_operator parenthesized_expression binary_operator subscript identifier call identifier argument_list binary_operator identifier integer subscript identifier binary_operator call identifier argument_list binary_operator identifier integer integer float return_statement identifier | Returns the median of values in the given list. |
def force_delete_file(file_path):
if os.path.isfile(file_path):
try:
os.remove(file_path)
return file_path
except:
return FileSystemUtils.add_unique_postfix(file_path)
else:
return file_path | module function_definition identifier parameters identifier block if_statement call attribute attribute identifier identifier identifier argument_list identifier block try_statement block expression_statement call attribute identifier identifier argument_list identifier return_statement identifier except_clause block return_statement call attribute identifier identifier argument_list identifier else_clause block return_statement identifier | force delete a file |
def create_environment_vip(self):
return EnvironmentVIP(
self.networkapi_url,
self.user,
self.password,
self.user_ldap) | module function_definition identifier parameters identifier block return_statement call identifier argument_list attribute identifier identifier attribute identifier identifier attribute identifier identifier attribute identifier identifier | Get an instance of environment_vip services facade. |
def __stop_decoder(self):
if self.__decoder_thread:
self.__decoder_queue.put(None)
self.__decoder_thread.join()
self.__decoder_thread = None | module function_definition identifier parameters identifier block if_statement attribute identifier identifier block expression_statement call attribute attribute identifier identifier identifier argument_list none expression_statement call attribute attribute identifier identifier identifier argument_list expression_statement assignment attribute identifier identifier none | Stop the decoder thread, which will in turn stop the track. |
def resolve(input, representation, resolvers=None, **kwargs):
resultdict = query(input, representation, resolvers, **kwargs)
result = resultdict[0]['value'] if resultdict else None
if result and len(result) == 1:
result = result[0]
return result | module function_definition identifier parameters identifier identifier default_parameter identifier none dictionary_splat_pattern identifier block expression_statement assignment identifier call identifier argument_list identifier identifier identifier dictionary_splat identifier expression_statement assignment identifier conditional_expression subscript subscript identifier integer string string_start string_content string_end identifier none if_statement boolean_operator identifier comparison_operator call identifier argument_list identifier integer block expression_statement assignment identifier subscript identifier integer return_statement identifier | Resolve input to the specified output representation |
def service_details(self, io_handler, service_id):
svc_ref = self._context.get_service_reference(
None, "({0}={1})".format(constants.SERVICE_ID, service_id)
)
if svc_ref is None:
io_handler.write_line("Service not found: {0}", service_id)
return False
lines = [
"ID............: {0}".format(
svc_ref.get_property(constants.SERVICE_ID)
),
"Rank..........: {0}".format(
svc_ref.get_property(constants.SERVICE_RANKING)
),
"Specifications: {0}".format(
svc_ref.get_property(constants.OBJECTCLASS)
),
"Bundle........: {0}".format(svc_ref.get_bundle()),
"Properties....:",
]
for key, value in sorted(svc_ref.get_properties().items()):
lines.append("\t{0} = {1}".format(key, value))
lines.append("Bundles using this service:")
for bundle in svc_ref.get_using_bundles():
lines.append("\t{0}".format(bundle))
lines.append("")
io_handler.write("\n".join(lines))
return None | module function_definition identifier parameters identifier identifier identifier block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list none call attribute string string_start string_content string_end identifier argument_list attribute identifier identifier identifier if_statement comparison_operator identifier none block expression_statement call attribute identifier identifier argument_list string string_start string_content string_end identifier return_statement false expression_statement assignment identifier list call attribute string string_start string_content string_end identifier argument_list call attribute identifier identifier argument_list attribute identifier identifier call attribute string string_start string_content string_end identifier argument_list call attribute identifier identifier argument_list attribute identifier identifier call attribute string string_start string_content string_end identifier argument_list call attribute identifier identifier argument_list attribute identifier identifier call attribute string string_start string_content string_end identifier argument_list call attribute identifier identifier argument_list string string_start string_content string_end for_statement pattern_list identifier identifier call identifier argument_list call attribute call attribute identifier identifier argument_list identifier argument_list block expression_statement call attribute identifier identifier argument_list call attribute string string_start string_content escape_sequence string_end identifier argument_list identifier identifier expression_statement call attribute identifier identifier argument_list string string_start string_content string_end for_statement identifier call attribute identifier identifier argument_list block expression_statement call attribute identifier identifier argument_list call attribute string string_start string_content escape_sequence string_end identifier argument_list identifier expression_statement call attribute identifier identifier argument_list string string_start string_end expression_statement call attribute identifier identifier argument_list call attribute string string_start string_content escape_sequence string_end identifier argument_list identifier return_statement none | Prints the details of the service with the given ID |
def draw_polygon(
self,
*pts,
close_path:bool=True,
stroke:Color=None,
stroke_width:float=1,
stroke_dash:typing.Sequence=None,
fill:Color=None
) -> None:
pass | module function_definition identifier parameters identifier list_splat_pattern identifier typed_default_parameter identifier type identifier true typed_default_parameter identifier type identifier none typed_default_parameter identifier type identifier integer typed_default_parameter identifier type attribute identifier identifier none typed_default_parameter identifier type identifier none type none block pass_statement | Draws the given linear path. |
def map_nested(function, data_struct, dict_only=False, map_tuple=False):
if isinstance(data_struct, dict):
return {
k: map_nested(function, v, dict_only, map_tuple)
for k, v in data_struct.items()
}
elif not dict_only:
types = [list]
if map_tuple:
types.append(tuple)
if isinstance(data_struct, tuple(types)):
mapped = [map_nested(function, v, dict_only, map_tuple)
for v in data_struct]
if isinstance(data_struct, list):
return mapped
else:
return tuple(mapped)
return function(data_struct) | module function_definition identifier parameters identifier identifier default_parameter identifier false default_parameter identifier false block if_statement call identifier argument_list identifier identifier block return_statement dictionary_comprehension pair identifier call identifier argument_list identifier identifier identifier identifier for_in_clause pattern_list identifier identifier call attribute identifier identifier argument_list elif_clause not_operator identifier block expression_statement assignment identifier list identifier if_statement identifier block expression_statement call attribute identifier identifier argument_list identifier if_statement call identifier argument_list identifier call identifier argument_list identifier block expression_statement assignment identifier list_comprehension call identifier argument_list identifier identifier identifier identifier for_in_clause identifier identifier if_statement call identifier argument_list identifier identifier block return_statement identifier else_clause block return_statement call identifier argument_list identifier return_statement call identifier argument_list identifier | Apply a function recursively to each element of a nested data struct. |
def parse(self, filelike, filename):
self.log = log
self.source = filelike.readlines()
src = ''.join(self.source)
try:
compile(src, filename, 'exec')
except SyntaxError as error:
raise ParseError() from error
self.stream = TokenStream(StringIO(src))
self.filename = filename
self.dunder_all = None
self.dunder_all_error = None
self.future_imports = set()
self._accumulated_decorators = []
return self.parse_module() | module function_definition identifier parameters identifier identifier identifier block expression_statement assignment attribute identifier identifier identifier expression_statement assignment attribute identifier identifier call attribute identifier identifier argument_list expression_statement assignment identifier call attribute string string_start string_end identifier argument_list attribute identifier identifier try_statement block expression_statement call identifier argument_list identifier identifier string string_start string_content string_end except_clause as_pattern identifier as_pattern_target identifier block raise_statement call identifier argument_list identifier expression_statement assignment attribute identifier identifier call identifier argument_list call identifier argument_list identifier expression_statement assignment attribute identifier identifier identifier expression_statement assignment attribute identifier identifier none expression_statement assignment attribute identifier identifier none expression_statement assignment attribute identifier identifier call identifier argument_list expression_statement assignment attribute identifier identifier list return_statement call attribute identifier identifier argument_list | Parse the given file-like object and return its Module object. |
def validate_token_parameters(params):
if 'error' in params:
raise_from_error(params.get('error'), params)
if not 'access_token' in params:
raise MissingTokenError(description="Missing access token parameter.")
if not 'token_type' in params:
if os.environ.get('OAUTHLIB_STRICT_TOKEN_TYPE'):
raise MissingTokenTypeError()
if params.scope_changed:
message = 'Scope has changed from "{old}" to "{new}".'.format(
old=params.old_scope, new=params.scope,
)
scope_changed.send(message=message, old=params.old_scopes, new=params.scopes)
if not os.environ.get('OAUTHLIB_RELAX_TOKEN_SCOPE', None):
w = Warning(message)
w.token = params
w.old_scope = params.old_scopes
w.new_scope = params.scopes
raise w | module function_definition identifier parameters identifier block if_statement comparison_operator string string_start string_content string_end identifier block expression_statement call identifier argument_list call attribute identifier identifier argument_list string string_start string_content string_end identifier if_statement not_operator comparison_operator string string_start string_content string_end identifier block raise_statement call identifier argument_list keyword_argument identifier string string_start string_content string_end if_statement not_operator comparison_operator string string_start string_content string_end identifier block if_statement call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end block raise_statement call identifier argument_list if_statement attribute identifier identifier block expression_statement assignment identifier call attribute string string_start string_content string_end identifier argument_list keyword_argument identifier attribute identifier identifier keyword_argument identifier attribute identifier identifier expression_statement call attribute identifier identifier argument_list keyword_argument identifier identifier keyword_argument identifier attribute identifier identifier keyword_argument identifier attribute identifier identifier if_statement not_operator call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end none block expression_statement assignment identifier call identifier argument_list identifier expression_statement assignment attribute identifier identifier identifier expression_statement assignment attribute identifier identifier attribute identifier identifier expression_statement assignment attribute identifier identifier attribute identifier identifier raise_statement identifier | Ensures token precence, token type, expiration and scope in params. |
def validate_page_size(ctx, param, value):
if value == 0:
raise click.BadParameter("Page size must be non-zero or unset.", param=param)
return value | module function_definition identifier parameters identifier identifier identifier block if_statement comparison_operator identifier integer block raise_statement call attribute identifier identifier argument_list string string_start string_content string_end keyword_argument identifier identifier return_statement identifier | Ensure that a valid value for page size is chosen. |
def _get_component(filename, default="global"):
if hasattr(filename, "decode"):
filename = filename.decode()
parts = filename.split(os.path.sep)
if len(parts) >= 3:
if parts[1] in "modules legacy ext".split():
return parts[2]
if len(parts) >= 2:
if parts[1] in "base celery utils".split():
return parts[1]
if len(parts) >= 1:
if parts[0] in "grunt docs".split():
return parts[0]
return default | module function_definition identifier parameters identifier default_parameter identifier string string_start string_content string_end block if_statement call identifier argument_list identifier string string_start string_content string_end block expression_statement assignment identifier call attribute identifier identifier argument_list expression_statement assignment identifier call attribute identifier identifier argument_list attribute attribute identifier identifier identifier if_statement comparison_operator call identifier argument_list identifier integer block if_statement comparison_operator subscript identifier integer call attribute string string_start string_content string_end identifier argument_list block return_statement subscript identifier integer if_statement comparison_operator call identifier argument_list identifier integer block if_statement comparison_operator subscript identifier integer call attribute string string_start string_content string_end identifier argument_list block return_statement subscript identifier integer if_statement comparison_operator call identifier argument_list identifier integer block if_statement comparison_operator subscript identifier integer call attribute string string_start string_content string_end identifier argument_list block return_statement subscript identifier integer return_statement identifier | Get component name from filename. |
def render_subcommand(args):
if args.subcommand == 'delete':
return 'delete ' + args.delete_subcommand
if args.subcommand in ('wal-prefetch', 'wal-push', 'wal-fetch'):
return None
return args.subcommand | module function_definition identifier parameters identifier block if_statement comparison_operator attribute identifier identifier string string_start string_content string_end block return_statement binary_operator string string_start string_content string_end attribute identifier identifier if_statement comparison_operator attribute identifier identifier tuple string string_start string_content string_end string string_start string_content string_end string string_start string_content string_end block return_statement none return_statement attribute identifier identifier | Render a subcommand for human-centric viewing |
def readlines_bytes(self):
with open_zipfile_archive(self.path, self.filename) as file:
for line in file:
yield line.rstrip(b'\r\n') | module function_definition identifier parameters identifier block with_statement with_clause with_item as_pattern call identifier argument_list attribute identifier identifier attribute identifier identifier as_pattern_target identifier block for_statement identifier identifier block expression_statement yield call attribute identifier identifier argument_list string string_start string_content escape_sequence escape_sequence string_end | Read content into byte str line iterator. |
def dt2str(dt, flagSeconds=True):
if isinstance(dt, str):
return dt
return dt.strftime(_FMTS if flagSeconds else _FMT) | module function_definition identifier parameters identifier default_parameter identifier true block if_statement call identifier argument_list identifier identifier block return_statement identifier return_statement call attribute identifier identifier argument_list conditional_expression identifier identifier identifier | Converts datetime object to str if not yet an str. |
def match(self, feature, gps_precision=None, profile='mapbox.driving'):
profile = self._validate_profile(profile)
feature = self._validate_feature(feature)
geojson_line_feature = json.dumps(feature)
uri = URITemplate(self.baseuri + '/{profile}.json').expand(
profile=profile)
params = None
if gps_precision:
params = {'gps_precision': gps_precision}
res = self.session.post(uri, data=geojson_line_feature, params=params,
headers={'Content-Type': 'application/json'})
self.handle_http_error(res)
def geojson():
return res.json()
res.geojson = geojson
return res | module function_definition identifier parameters identifier identifier default_parameter identifier none default_parameter identifier string string_start string_content string_end block expression_statement assignment identifier call attribute identifier identifier argument_list identifier expression_statement assignment identifier call attribute identifier identifier argument_list identifier expression_statement assignment identifier call attribute identifier identifier argument_list identifier expression_statement assignment identifier call attribute call identifier argument_list binary_operator attribute identifier identifier string string_start string_content string_end identifier argument_list keyword_argument identifier identifier expression_statement assignment identifier none if_statement identifier block expression_statement assignment identifier dictionary pair string string_start string_content string_end identifier expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list identifier keyword_argument identifier identifier keyword_argument identifier identifier keyword_argument identifier dictionary pair string string_start string_content string_end string string_start string_content string_end expression_statement call attribute identifier identifier argument_list identifier function_definition identifier parameters block return_statement call attribute identifier identifier argument_list expression_statement assignment attribute identifier identifier identifier return_statement identifier | Match features to OpenStreetMap data. |
def _pid_is_alive(cls, pid, timeout):
try:
proc = psutil.Process(pid)
except psutil.NoSuchProcess:
return False
try:
proc.wait(timeout=timeout)
except psutil.TimeoutExpired:
return True
return False | module function_definition identifier parameters identifier identifier identifier block try_statement block expression_statement assignment identifier call attribute identifier identifier argument_list identifier except_clause attribute identifier identifier block return_statement false try_statement block expression_statement call attribute identifier identifier argument_list keyword_argument identifier identifier except_clause attribute identifier identifier block return_statement true return_statement false | Check if a PID is alive with a timeout. |
def _check_symlink_ownership(path, user, group, win_owner):
cur_user, cur_group = _get_symlink_ownership(path)
if salt.utils.platform.is_windows():
return win_owner == cur_user
else:
return (cur_user == user) and (cur_group == group) | module function_definition identifier parameters identifier identifier identifier identifier block expression_statement assignment pattern_list identifier identifier call identifier argument_list identifier if_statement call attribute attribute attribute identifier identifier identifier identifier argument_list block return_statement comparison_operator identifier identifier else_clause block return_statement boolean_operator parenthesized_expression comparison_operator identifier identifier parenthesized_expression comparison_operator identifier identifier | Check if the symlink ownership matches the specified user and group |
def request_param_update(self, complete_name):
self.param_updater.request_param_update(
self.toc.get_element_id(complete_name)) | module function_definition identifier parameters identifier identifier block expression_statement call attribute attribute identifier identifier identifier argument_list call attribute attribute identifier identifier identifier argument_list identifier | Request an update of the value for the supplied parameter. |
def get(self, item):
uri = "/%s/%s" % (self.uri_base, utils.get_id(item))
return self._get(uri) | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier binary_operator string string_start string_content string_end tuple attribute identifier identifier call attribute identifier identifier argument_list identifier return_statement call attribute identifier identifier argument_list identifier | Gets a specific item. |
async def tcp_echo_client(message, loop, host, port):
print("Connecting to server at %s:%d" % (host, port))
reader, writer = await asyncio.open_connection(host, port, loop=loop)
writer.write(message.encode())
print('Sent: %r' % message)
data = await reader.read(100)
print('Received: %r' % data.decode())
writer.close() | module function_definition identifier parameters identifier identifier identifier identifier block expression_statement call identifier argument_list binary_operator string string_start string_content string_end tuple identifier identifier expression_statement assignment pattern_list identifier identifier await call attribute identifier identifier argument_list identifier identifier keyword_argument identifier identifier expression_statement call attribute identifier identifier argument_list call attribute identifier identifier argument_list expression_statement call identifier argument_list binary_operator string string_start string_content string_end identifier expression_statement assignment identifier await call attribute identifier identifier argument_list integer expression_statement call identifier argument_list binary_operator string string_start string_content string_end call attribute identifier identifier argument_list expression_statement call attribute identifier identifier argument_list | Generic python tcp echo client |
def close(self):
try:
self.payload.close()
except:
pass
try:
self.model.close()
except:
pass
try:
self.fresh_index.close()
except:
pass
try:
self.opt_index.close()
except:
pass
try:
self.fresh_docs.terminate()
except:
pass | module function_definition identifier parameters identifier block try_statement block expression_statement call attribute attribute identifier identifier identifier argument_list except_clause block pass_statement try_statement block expression_statement call attribute attribute identifier identifier identifier argument_list except_clause block pass_statement try_statement block expression_statement call attribute attribute identifier identifier identifier argument_list except_clause block pass_statement try_statement block expression_statement call attribute attribute identifier identifier identifier argument_list except_clause block pass_statement try_statement block expression_statement call attribute attribute identifier identifier identifier argument_list except_clause block pass_statement | Explicitly close open file handles, databases etc. |
def utc_to_local(time_str, use_12_hour_format, show_datetime=False):
if not (time_str.endswith(" UTC") or time_str.endswith("Z")):
return time_str
today_utc = datetime.datetime.utcnow()
utc_local_diff = today_utc - datetime.datetime.now()
if time_str.endswith(" UTC"):
time_str, _ = time_str.split(" UTC")
utc_time = datetime.datetime.strptime(time_str, '%I:%M %p')
utc_datetime = datetime.datetime(today_utc.year,
today_utc.month,
today_utc.day,
utc_time.hour,
utc_time.minute)
else:
utc_datetime = datetime.datetime.strptime(time_str,
'%Y-%m-%dT%H:%M:%SZ')
local_time = utc_datetime - utc_local_diff
if use_12_hour_format:
date_format = '%I:%M %p' if not show_datetime else '%a %d, %I:%M %p'
else:
date_format = '%H:%M' if not show_datetime else '%a %d, %H:%M'
return datetime.datetime.strftime(local_time, date_format) | module function_definition identifier parameters identifier identifier default_parameter identifier false block if_statement not_operator parenthesized_expression boolean_operator call attribute identifier identifier argument_list string string_start string_content string_end call attribute identifier identifier argument_list string string_start string_content string_end block return_statement identifier expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list expression_statement assignment identifier binary_operator identifier call attribute attribute identifier identifier identifier argument_list if_statement call attribute identifier identifier argument_list string string_start string_content string_end block expression_statement assignment pattern_list identifier identifier call attribute identifier identifier argument_list string string_start string_content string_end expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list identifier string string_start string_content string_end expression_statement assignment identifier call attribute identifier identifier argument_list attribute identifier identifier attribute identifier identifier attribute identifier identifier attribute identifier identifier attribute identifier identifier else_clause block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list identifier string string_start string_content string_end expression_statement assignment identifier binary_operator identifier identifier if_statement identifier block expression_statement assignment identifier conditional_expression string string_start string_content string_end not_operator identifier string string_start string_content string_end else_clause block expression_statement assignment identifier conditional_expression string string_start string_content string_end not_operator identifier string string_start string_content string_end return_statement call attribute attribute identifier identifier identifier argument_list identifier identifier | Converts the API UTC time string to the local user time. |
def OnNodeActivated(self, event):
try:
node = self.sorted[event.GetIndex()]
except IndexError, err:
log.warn(_('Invalid index in node activated: %(index)s'),
index=event.GetIndex())
else:
wx.PostEvent(
self,
squaremap.SquareActivationEvent(node=node, point=None,
map=None)
) | module function_definition identifier parameters identifier identifier block try_statement block expression_statement assignment identifier subscript attribute identifier identifier call attribute identifier identifier argument_list except_clause identifier identifier block expression_statement call attribute identifier identifier argument_list call identifier argument_list string string_start string_content string_end keyword_argument identifier call attribute identifier identifier argument_list else_clause block expression_statement call attribute identifier identifier argument_list identifier call attribute identifier identifier argument_list keyword_argument identifier identifier keyword_argument identifier none keyword_argument identifier none | We have double-clicked for hit enter on a node refocus squaremap to this node |
def parse_line(self, line, lineno):
if line.startswith('[taskcluster '):
self.is_taskcluster = True
if self.is_taskcluster:
line = re.sub(self.RE_TASKCLUSTER_NORMAL_PREFIX, "", line)
if self.is_error_line(line):
self.add(line, lineno) | 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 attribute identifier identifier true if_statement attribute identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list attribute identifier identifier string string_start string_end identifier if_statement call attribute identifier identifier argument_list identifier block expression_statement call attribute identifier identifier argument_list identifier identifier | Check a single line for an error. Keeps track of the linenumber |
def process_request(self, request):
assert hasattr(request, 'user')
if not request.user.is_authenticated():
path = request.path_info.lstrip('/')
if not any(m.match(path) for m in EXEMPT_URLS):
return HttpResponseRedirect(reverse(settings.LOGIN_URL)) | module function_definition identifier parameters identifier identifier block assert_statement call identifier argument_list identifier string string_start string_content string_end if_statement not_operator call attribute attribute identifier identifier identifier argument_list block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end if_statement not_operator call identifier generator_expression call attribute identifier identifier argument_list identifier for_in_clause identifier identifier block return_statement call identifier argument_list call identifier argument_list attribute identifier identifier | Check if user is logged in |
def _get_wmi_setting(wmi_class_name, setting, server):
with salt.utils.winapi.Com():
try:
connection = wmi.WMI(namespace=_WMI_NAMESPACE)
wmi_class = getattr(connection, wmi_class_name)
objs = wmi_class([setting], Name=server)[0]
ret = getattr(objs, setting)
except wmi.x_wmi as error:
_LOG.error('Encountered WMI error: %s', error.com_error)
except (AttributeError, IndexError) as error:
_LOG.error('Error getting %s: %s', wmi_class_name, error)
return ret | module function_definition identifier parameters identifier identifier identifier block with_statement with_clause with_item call attribute attribute attribute identifier identifier identifier identifier argument_list block try_statement block expression_statement assignment identifier call attribute identifier identifier argument_list keyword_argument identifier identifier expression_statement assignment identifier call identifier argument_list identifier identifier expression_statement assignment identifier subscript call identifier argument_list list identifier keyword_argument identifier identifier integer expression_statement assignment identifier call identifier argument_list identifier identifier except_clause as_pattern attribute identifier identifier as_pattern_target identifier block expression_statement call attribute identifier identifier argument_list string string_start string_content string_end attribute identifier identifier except_clause as_pattern tuple identifier identifier as_pattern_target identifier block expression_statement call attribute identifier identifier argument_list string string_start string_content string_end identifier identifier return_statement identifier | Get the value of the setting for the provided class. |
def isIsosceles(self):
return (self.a == self.b) or (self.a == self.c) or (self.b == self.c) | module function_definition identifier parameters identifier block return_statement boolean_operator boolean_operator parenthesized_expression comparison_operator attribute identifier identifier attribute identifier identifier parenthesized_expression comparison_operator attribute identifier identifier attribute identifier identifier parenthesized_expression comparison_operator attribute identifier identifier attribute identifier identifier | True iff two side lengths are equal, boolean. |
def stripe_to_db(self, data):
val = data.get(self.name)
if val is not None:
return val / decimal.Decimal("100") | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list attribute identifier identifier if_statement comparison_operator identifier none block return_statement binary_operator identifier call attribute identifier identifier argument_list string string_start string_content string_end | Convert the raw value to decimal representation. |
def x10(cls, housecode, unitcode):
if housecode.lower() in ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h',
'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p']:
byte_housecode = insteonplm.utils.housecode_to_byte(housecode)
else:
if isinstance(housecode, str):
_LOGGER.error('X10 house code error: %s', housecode)
else:
_LOGGER.error('X10 house code is not a string')
raise ValueError
if unitcode in range(1, 17) or unitcode in range(20, 23):
byte_unitcode = insteonplm.utils.unitcode_to_byte(unitcode)
else:
if isinstance(unitcode, int):
_LOGGER.error('X10 unit code error: %d', unitcode)
else:
_LOGGER.error('X10 unit code is not an integer 1 - 16')
raise ValueError
addr = Address(bytearray([0x00, byte_housecode, byte_unitcode]))
addr.is_x10 = True
return addr | module function_definition identifier parameters identifier identifier identifier block if_statement comparison_operator call attribute identifier identifier argument_list list string string_start string_content string_end string string_start string_content string_end string string_start string_content string_end string string_start string_content string_end string string_start string_content string_end string string_start string_content string_end string string_start string_content string_end string string_start string_content string_end string string_start string_content string_end string string_start string_content string_end string string_start string_content string_end string string_start string_content string_end string string_start string_content string_end string string_start string_content string_end string string_start string_content string_end string string_start string_content string_end block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list identifier else_clause block if_statement call identifier argument_list identifier identifier block expression_statement call attribute identifier identifier argument_list string string_start string_content string_end identifier else_clause block expression_statement call attribute identifier identifier argument_list string string_start string_content string_end raise_statement identifier if_statement boolean_operator comparison_operator identifier call identifier argument_list integer integer comparison_operator identifier call identifier argument_list integer integer block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list identifier else_clause block if_statement call identifier argument_list identifier identifier block expression_statement call attribute identifier identifier argument_list string string_start string_content string_end identifier else_clause block expression_statement call attribute identifier identifier argument_list string string_start string_content string_end raise_statement identifier expression_statement assignment identifier call identifier argument_list call identifier argument_list list integer identifier identifier expression_statement assignment attribute identifier identifier true return_statement identifier | Create an X10 device address. |
def getStatus(self):
command = '$GS'
status = self.sendCommand(command)
return states[int(status[1])] | module function_definition identifier parameters identifier block expression_statement assignment identifier string string_start string_content string_end expression_statement assignment identifier call attribute identifier identifier argument_list identifier return_statement subscript identifier call identifier argument_list subscript identifier integer | Returns the charger's charge status, as a string |
def index(self, request):
objects = self.model.objects.all()
return self._render(
request = request,
template = 'index',
context = {
cc2us(pluralize(self.model.__name__)): objects,
},
status = 200
) | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call attribute attribute attribute identifier identifier identifier identifier argument_list return_statement call attribute identifier identifier argument_list keyword_argument identifier identifier keyword_argument identifier string string_start string_content string_end keyword_argument identifier dictionary pair call identifier argument_list call identifier argument_list attribute attribute identifier identifier identifier identifier keyword_argument identifier integer | Render a list of objects. |
def _free_sequence(tmp1, tmp2=False):
if not tmp1 and not tmp2:
return []
output = []
if tmp1 and tmp2:
output.append('pop de')
output.append('ex (sp), hl')
output.append('push de')
output.append('call __MEM_FREE')
output.append('pop hl')
output.append('call __MEM_FREE')
else:
output.append('ex (sp), hl')
output.append('call __MEM_FREE')
output.append('pop hl')
REQUIRES.add('alloc.asm')
return output | module function_definition identifier parameters identifier default_parameter identifier false block if_statement boolean_operator not_operator identifier not_operator identifier block return_statement list expression_statement assignment identifier list if_statement boolean_operator identifier identifier block expression_statement call attribute identifier identifier argument_list string string_start string_content string_end expression_statement call attribute identifier identifier argument_list string string_start string_content string_end expression_statement call attribute identifier identifier argument_list string string_start string_content string_end expression_statement call attribute identifier identifier argument_list string string_start string_content string_end expression_statement call attribute identifier identifier argument_list string string_start string_content string_end expression_statement call attribute identifier identifier argument_list string string_start string_content string_end else_clause block expression_statement call attribute identifier identifier argument_list string string_start string_content string_end expression_statement call attribute identifier identifier argument_list string string_start string_content string_end expression_statement call attribute identifier identifier argument_list string string_start string_content string_end expression_statement call attribute identifier identifier argument_list string string_start string_content string_end return_statement identifier | Outputs a FREEMEM sequence for 1 or 2 ops |
def iriToURI(iri):
if isinstance(iri, bytes):
iri = str(iri, encoding="utf-8")
return iri.encode('ascii', errors='oid_percent_escape').decode() | module function_definition identifier parameters identifier block if_statement call identifier argument_list identifier identifier block expression_statement assignment identifier call identifier argument_list identifier keyword_argument identifier string string_start string_content string_end return_statement call attribute call attribute identifier identifier argument_list string string_start string_content string_end keyword_argument identifier string string_start string_content string_end identifier argument_list | Transform an IRI to a URI by escaping unicode. |
def update_cache_settings(self, service_id, version_number, name_key, **kwargs):
body = self._formdata(kwargs, FastlyCacheSettings.FIELDS)
content = self._fetch("/service/%s/version/%d/cache_settings/%s" % (service_id, version_number, name_key), method="PUT", body=body)
return FastlyCacheSettings(self, content) | module function_definition identifier parameters identifier identifier identifier identifier dictionary_splat_pattern identifier block expression_statement assignment identifier call attribute identifier identifier argument_list identifier attribute identifier identifier expression_statement assignment identifier call attribute identifier identifier argument_list binary_operator string string_start string_content string_end tuple identifier identifier identifier keyword_argument identifier string string_start string_content string_end keyword_argument identifier identifier return_statement call identifier argument_list identifier identifier | Update a specific cache settings object. |
def p5list(num):
from .website.pocketfives import get_ranked_players
format_str = '{:>4.4} {!s:<15.13}{!s:<18.15}{!s:<9.6}{!s:<10.7}'\
'{!s:<14.11}{!s:<12.9}{!s:<12.9}{!s:<12.9}{!s:<4.4}'
click.echo(format_str.format(
'Rank' , 'Player name', 'Country', 'Triple', 'Monthly', 'Biggest cash',
'PLB score', 'Biggest s', 'Average s', 'Prev'
))
underlines = ['-' * 20] * 10
click.echo(format_str.format(*underlines))
for ind, player in enumerate(get_ranked_players()):
click.echo(format_str.format(str(ind + 1) + '.', *player))
if ind == num - 1:
break | module function_definition identifier parameters identifier block import_from_statement relative_import import_prefix dotted_name identifier identifier dotted_name identifier expression_statement assignment identifier concatenated_string string string_start string_content string_end string string_start string_content string_end expression_statement call attribute identifier identifier argument_list call attribute identifier identifier argument_list string string_start string_content string_end string string_start string_content string_end string string_start string_content string_end string string_start string_content string_end string string_start string_content string_end string string_start string_content string_end string string_start string_content string_end string string_start string_content string_end string string_start string_content string_end string string_start string_content string_end expression_statement assignment identifier binary_operator list binary_operator string string_start string_content string_end integer integer expression_statement call attribute identifier identifier argument_list call attribute identifier identifier argument_list list_splat identifier for_statement pattern_list identifier identifier call identifier argument_list call identifier argument_list block expression_statement call attribute identifier identifier argument_list call attribute identifier identifier argument_list binary_operator call identifier argument_list binary_operator identifier integer string string_start string_content string_end list_splat identifier if_statement comparison_operator identifier binary_operator identifier integer block break_statement | List pocketfives ranked players, max 100 if no NUM, or NUM if specified. |
def createBlendedFolders():
create_folder(os.path.join(cwd, "templates"))
create_folder(os.path.join(cwd, "templates", "assets"))
create_folder(os.path.join(cwd, "templates", "assets", "css"))
create_folder(os.path.join(cwd, "templates", "assets", "js"))
create_folder(os.path.join(cwd, "templates", "assets", "img"))
create_folder(os.path.join(cwd, "content")) | module function_definition identifier parameters block expression_statement call identifier argument_list call attribute attribute identifier identifier identifier argument_list identifier string string_start string_content string_end expression_statement call identifier argument_list call attribute attribute identifier identifier identifier argument_list identifier string string_start string_content string_end string string_start string_content string_end expression_statement call identifier argument_list call attribute attribute identifier identifier identifier argument_list identifier string string_start string_content string_end string string_start string_content string_end string string_start string_content string_end expression_statement call identifier argument_list call attribute attribute identifier identifier identifier argument_list identifier string string_start string_content string_end string string_start string_content string_end string string_start string_content string_end expression_statement call identifier argument_list call attribute attribute identifier identifier identifier argument_list identifier string string_start string_content string_end string string_start string_content string_end string string_start string_content string_end expression_statement call identifier argument_list call attribute attribute identifier identifier identifier argument_list identifier string string_start string_content string_end | Creates the standard folders for a Blended website |
def configs_in(src_dir):
for filename in files_in_dir(src_dir, 'json'):
with open(os.path.join(src_dir, filename), 'rb') as in_f:
yield json.load(in_f) | module function_definition identifier parameters identifier block for_statement identifier call identifier argument_list identifier string string_start string_content string_end block with_statement with_clause with_item as_pattern call identifier argument_list call attribute attribute identifier identifier identifier argument_list identifier identifier string string_start string_content string_end as_pattern_target identifier block expression_statement yield call attribute identifier identifier argument_list identifier | Enumerate all configs in src_dir |
def prioritize():
while True:
hp_qs = Message.objects.high_priority().using('default')
mp_qs = Message.objects.medium_priority().using('default')
lp_qs = Message.objects.low_priority().using('default')
while hp_qs.count() or mp_qs.count():
while hp_qs.count():
for message in hp_qs.order_by("when_added"):
yield message
while hp_qs.count() == 0 and mp_qs.count():
yield mp_qs.order_by("when_added")[0]
while hp_qs.count() == 0 and mp_qs.count() == 0 and lp_qs.count():
yield lp_qs.order_by("when_added")[0]
if Message.objects.non_deferred().using('default').count() == 0:
break | module function_definition identifier parameters block while_statement true block 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 call attribute call attribute attribute identifier identifier identifier argument_list identifier argument_list string string_start string_content string_end expression_statement assignment identifier call attribute call attribute attribute identifier identifier identifier argument_list identifier argument_list string string_start string_content string_end while_statement boolean_operator call attribute identifier identifier argument_list call attribute identifier identifier argument_list block while_statement call attribute identifier identifier argument_list block for_statement identifier call attribute identifier identifier argument_list string string_start string_content string_end block expression_statement yield identifier while_statement boolean_operator comparison_operator call attribute identifier identifier argument_list integer call attribute identifier identifier argument_list block expression_statement yield subscript call attribute identifier identifier argument_list string string_start string_content string_end integer while_statement boolean_operator boolean_operator comparison_operator call attribute identifier identifier argument_list integer comparison_operator call attribute identifier identifier argument_list integer call attribute identifier identifier argument_list block expression_statement yield subscript call attribute identifier identifier argument_list string string_start string_content string_end integer if_statement comparison_operator call attribute call attribute call attribute attribute identifier identifier identifier argument_list identifier argument_list string string_start string_content string_end identifier argument_list integer block break_statement | Yield the messages in the queue in the order they should be sent. |
def remove_summaries():
g = tf.get_default_graph()
key = tf.GraphKeys.SUMMARIES
log_debug("Remove summaries %s" % str(g.get_collection(key)))
del g.get_collection_ref(key)[:]
assert not g.get_collection(key) | module function_definition identifier parameters block expression_statement assignment identifier call attribute identifier identifier argument_list expression_statement assignment identifier attribute attribute identifier identifier identifier expression_statement call identifier argument_list binary_operator string string_start string_content string_end call identifier argument_list call attribute identifier identifier argument_list identifier delete_statement subscript call attribute identifier identifier argument_list identifier slice assert_statement not_operator call attribute identifier identifier argument_list identifier | Remove summaries from the default graph. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.