text stringlengths 89 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 630 |
|---|---|---|---|
def find_item_project(self, eitem):
"""
Find the project for a enriched item
:param eitem: enriched item for which to find the project
:return: the project entry (a dictionary)
"""
# get the data source name relying on the cfg section name, if null use the connector name
... | [
"def",
"find_item_project",
"(",
"self",
",",
"eitem",
")",
":",
"# get the data source name relying on the cfg section name, if null use the connector name",
"ds_name",
"=",
"self",
".",
"cfg_section_name",
"if",
"self",
".",
"cfg_section_name",
"else",
"self",
".",
"get_c... | 47.166667 | 24.203704 |
def delete_item(self, item_uri):
"""Delete an item from a collection
:param item_uri: the URI that references the item
:type item_uri: String
:rtype: String
:returns: a message confirming that the metadata is modified
:raises: APIError if the request was not successful... | [
"def",
"delete_item",
"(",
"self",
",",
"item_uri",
")",
":",
"response",
"=",
"self",
".",
"api_request",
"(",
"item_uri",
",",
"method",
"=",
"'DELETE'",
")",
"return",
"self",
".",
"__check_success",
"(",
"response",
")"
] | 30.642857 | 20.5 |
def bezier_radialrange(seg, origin, return_all_global_extrema=False):
"""returns the tuples (d_min, t_min) and (d_max, t_max) which minimize and
maximize, respectively, the distance d = |self.point(t)-origin|.
return_all_global_extrema: Multiple such t_min or t_max values can exist.
By default, this wi... | [
"def",
"bezier_radialrange",
"(",
"seg",
",",
"origin",
",",
"return_all_global_extrema",
"=",
"False",
")",
":",
"def",
"_radius",
"(",
"tau",
")",
":",
"return",
"abs",
"(",
"seg",
".",
"point",
"(",
"tau",
")",
"-",
"origin",
")",
"shifted_seg_poly",
... | 43.090909 | 18.045455 |
def setArrowStyle( self, state ):
"""
Sets whether or not to use arrows for the grouping mechanism.
:param state | <bool>
"""
self._arrowStyle = state
if not state:
self.setStyleSheet('')
else:
right = reso... | [
"def",
"setArrowStyle",
"(",
"self",
",",
"state",
")",
":",
"self",
".",
"_arrowStyle",
"=",
"state",
"if",
"not",
"state",
":",
"self",
".",
"setStyleSheet",
"(",
"''",
")",
"else",
":",
"right",
"=",
"resources",
".",
"find",
"(",
"'img/treeview/trian... | 36.733333 | 17.666667 |
def unmasked_blurred_image_of_galaxies_from_psf(self, padded_grid_stack, psf):
"""This is a utility function for the function above, which performs the iteration over each plane's galaxies \
and computes each galaxy's unmasked blurred image.
Parameters
----------
padded_grid_sta... | [
"def",
"unmasked_blurred_image_of_galaxies_from_psf",
"(",
"self",
",",
"padded_grid_stack",
",",
"psf",
")",
":",
"return",
"[",
"padded_grid_stack",
".",
"unmasked_blurred_image_from_psf_and_unmasked_image",
"(",
"psf",
",",
"image",
")",
"if",
"not",
"galaxy",
".",
... | 49.692308 | 24 |
def fit(self, struct1, struct2):
"""
Fit two structures.
Args:
struct1 (Structure): 1st structure
struct2 (Structure): 2nd structure
Returns:
True or False.
"""
struct1, struct2 = self._process_species([struct1, struct2])
if ... | [
"def",
"fit",
"(",
"self",
",",
"struct1",
",",
"struct2",
")",
":",
"struct1",
",",
"struct2",
"=",
"self",
".",
"_process_species",
"(",
"[",
"struct1",
",",
"struct2",
"]",
")",
"if",
"not",
"self",
".",
"_subset",
"and",
"self",
".",
"_comparator",... | 30.28 | 21.48 |
def PC_PI_calc(P, TOP, POP):
"""
Calculate percent chance agreement for Scott's Pi.
:param P: condition positive
:type P : dict
:param TOP: test outcome positive
:type TOP : dict
:param POP: population
:type POP:dict
:return: percent chance agreement as float
"""
try:
... | [
"def",
"PC_PI_calc",
"(",
"P",
",",
"TOP",
",",
"POP",
")",
":",
"try",
":",
"result",
"=",
"0",
"for",
"i",
"in",
"P",
".",
"keys",
"(",
")",
":",
"result",
"+=",
"(",
"(",
"P",
"[",
"i",
"]",
"+",
"TOP",
"[",
"i",
"]",
")",
"/",
"(",
... | 24.473684 | 15.947368 |
def analyze_symbol(l, sym, from_ver, to_ver, do_reads=False):
"""
This is a utility function to produce text output with details about the versions of a given symbol.
It is useful for debugging corruption issues and to mark corrupted versions.
Parameters
----------
l : `arctic.store.version_stor... | [
"def",
"analyze_symbol",
"(",
"l",
",",
"sym",
",",
"from_ver",
",",
"to_ver",
",",
"do_reads",
"=",
"False",
")",
":",
"logging",
".",
"info",
"(",
"'Analyzing symbol {}. Versions range is [v{}, v{}]'",
".",
"format",
"(",
"sym",
",",
"from_ver",
",",
"to_ver... | 41.357895 | 25.652632 |
def _create_sbatch(self, ostr):
"""Write sbatch template to output stream
:param ostr: opened file to write to
"""
properties = dict(
sbatch_arguments=self.sbatch_args, hpcbench_command=self.hpcbench_cmd
)
try:
self.sbatch_template.stream(**propert... | [
"def",
"_create_sbatch",
"(",
"self",
",",
"ostr",
")",
":",
"properties",
"=",
"dict",
"(",
"sbatch_arguments",
"=",
"self",
".",
"sbatch_args",
",",
"hpcbench_command",
"=",
"self",
".",
"hpcbench_cmd",
")",
"try",
":",
"self",
".",
"sbatch_template",
".",... | 42.882353 | 16.529412 |
def filter_enzyme_kinase(stmts_in, **kwargs):
"""Filter Phosphorylations to ones where the enzyme is a known kinase.
Parameters
----------
stmts_in : list[indra.statements.Statement]
A list of statements to filter.
save : Optional[str]
The name of a pickle file to save the results (... | [
"def",
"filter_enzyme_kinase",
"(",
"stmts_in",
",",
"*",
"*",
"kwargs",
")",
":",
"logger",
".",
"info",
"(",
"'Filtering %d statements to remove '",
"%",
"len",
"(",
"stmts_in",
")",
"+",
"'phosphorylation by non-kinases...'",
")",
"path",
"=",
"os",
".",
"pat... | 36.029412 | 16 |
def to_dict(self):
"""Convert this Node to a dict representation for passing to the API."""
return {"address": self.address,
"port": self.port,
"condition": self.condition,
"type": self.type,
"id": self.id,
} | [
"def",
"to_dict",
"(",
"self",
")",
":",
"return",
"{",
"\"address\"",
":",
"self",
".",
"address",
",",
"\"port\"",
":",
"self",
".",
"port",
",",
"\"condition\"",
":",
"self",
".",
"condition",
",",
"\"type\"",
":",
"self",
".",
"type",
",",
"\"id\""... | 37.125 | 8.875 |
def import_classes(name, currmodule):
# type: (unicode, unicode) -> Any
"""Import a class using its fully-qualified *name*."""
target = None
# import class or module using currmodule
if currmodule:
target = try_import(currmodule + '.' + name)
# import class or module without currmodule... | [
"def",
"import_classes",
"(",
"name",
",",
"currmodule",
")",
":",
"# type: (unicode, unicode) -> Any",
"target",
"=",
"None",
"# import class or module using currmodule",
"if",
"currmodule",
":",
"target",
"=",
"try_import",
"(",
"currmodule",
"+",
"'.'",
"+",
"name"... | 35.7 | 17.366667 |
def delete(self):
"""
Delete this :term:`Metrics Context` resource.
Raises:
:exc:`~zhmcclient.HTTPError`
:exc:`~zhmcclient.ParseError`
:exc:`~zhmcclient.AuthError`
:exc:`~zhmcclient.ConnectionError`
"""
self.manager.session.delete(self.ur... | [
"def",
"delete",
"(",
"self",
")",
":",
"self",
".",
"manager",
".",
"session",
".",
"delete",
"(",
"self",
".",
"uri",
")",
"self",
".",
"manager",
".",
"_metrics_contexts",
".",
"remove",
"(",
"self",
")"
] | 27.846154 | 12.769231 |
def read(self, structure):
""" Read and advance. """
start = self.offset
self.skip(structure.size)
return structure.read(self.buf, start) | [
"def",
"read",
"(",
"self",
",",
"structure",
")",
":",
"start",
"=",
"self",
".",
"offset",
"self",
".",
"skip",
"(",
"structure",
".",
"size",
")",
"return",
"structure",
".",
"read",
"(",
"self",
".",
"buf",
",",
"start",
")"
] | 33 | 8 |
def do_cat(self, subcmd, opts, *args):
"""Output the content of specified files or URLs.
usage:
cat TARGET...
${cmd_option_list}
"""
print "'svn %s' opts: %s" % (subcmd, opts)
print "'svn %s' args: %s" % (subcmd, args) | [
"def",
"do_cat",
"(",
"self",
",",
"subcmd",
",",
"opts",
",",
"*",
"args",
")",
":",
"print",
"\"'svn %s' opts: %s\"",
"%",
"(",
"subcmd",
",",
"opts",
")",
"print",
"\"'svn %s' args: %s\"",
"%",
"(",
"subcmd",
",",
"args",
")"
] | 27.9 | 14.9 |
def GetMacAddresses(self):
"""MAC addresses from all interfaces."""
result = set()
for interface in self.interfaces:
if (interface.mac_address and
interface.mac_address != b"\x00" * len(interface.mac_address)):
result.add(Text(interface.mac_address.human_readable_address))
return... | [
"def",
"GetMacAddresses",
"(",
"self",
")",
":",
"result",
"=",
"set",
"(",
")",
"for",
"interface",
"in",
"self",
".",
"interfaces",
":",
"if",
"(",
"interface",
".",
"mac_address",
"and",
"interface",
".",
"mac_address",
"!=",
"b\"\\x00\"",
"*",
"len",
... | 41 | 15.25 |
def GetRootFileEntry(self):
"""Retrieves the root file entry.
Returns:
ZipFileEntry: a file entry or None.
"""
path_spec = zip_path_spec.ZipPathSpec(
location=self.LOCATION_ROOT, parent=self._path_spec.parent)
return self.GetFileEntryByPathSpec(path_spec) | [
"def",
"GetRootFileEntry",
"(",
"self",
")",
":",
"path_spec",
"=",
"zip_path_spec",
".",
"ZipPathSpec",
"(",
"location",
"=",
"self",
".",
"LOCATION_ROOT",
",",
"parent",
"=",
"self",
".",
"_path_spec",
".",
"parent",
")",
"return",
"self",
".",
"GetFileEnt... | 31.333333 | 13.333333 |
def _depend_on_lambda_permissions_using_tag(self, bucket, permission):
"""
Since conditional DependsOn is not supported this undocumented way of
implicitely making dependency through tags is used.
See https://stackoverflow.com/questions/34607476/cloudformation-apply-condition-on-depend... | [
"def",
"_depend_on_lambda_permissions_using_tag",
"(",
"self",
",",
"bucket",
",",
"permission",
")",
":",
"properties",
"=",
"bucket",
".",
"get",
"(",
"'Properties'",
",",
"None",
")",
"if",
"properties",
"is",
"None",
":",
"properties",
"=",
"{",
"}",
"bu... | 40.2 | 20.8 |
def row_structural_typicality(self, X_L_list, X_D_list, row_id):
"""Returns the typicality (opposite of anomalousness) of given row.
:param row_id: id of the target row
:type row_id: int
:returns: float, the typicality, from 0 to 1
"""
return su.row_structural_typicalit... | [
"def",
"row_structural_typicality",
"(",
"self",
",",
"X_L_list",
",",
"X_D_list",
",",
"row_id",
")",
":",
"return",
"su",
".",
"row_structural_typicality",
"(",
"X_L_list",
",",
"X_D_list",
",",
"row_id",
")"
] | 37.888889 | 18.333333 |
def _check_mappings(self, doc_type, body):
"""
We desire to index content so that anything we want to be textually searchable(and therefore needing to be
analysed), but the other fields are designed to be filters, and only require an exact match. So, we want to
set up the mappings for th... | [
"def",
"_check_mappings",
"(",
"self",
",",
"doc_type",
",",
"body",
")",
":",
"# Make fields other than content be indexed as unanalyzed terms - content",
"# contains fields that are to be analyzed",
"exclude_fields",
"=",
"[",
"\"content\"",
"]",
"field_properties",
"=",
"get... | 37.6 | 18.906667 |
def _load_simple_section_questions(self, item_ids):
"""For loading the simple section case (common)
just load the questions for the section, and insert the one part
into assessment part map.
"""
self._insert_part_map(
get_default_part_map(self._assessment_part_id,
... | [
"def",
"_load_simple_section_questions",
"(",
"self",
",",
"item_ids",
")",
":",
"self",
".",
"_insert_part_map",
"(",
"get_default_part_map",
"(",
"self",
".",
"_assessment_part_id",
",",
"0",
",",
"self",
".",
"_assessment_part",
".",
"are_items_sequential",
"(",
... | 38.608696 | 16.26087 |
def pagedump(self):
"""
dump the contents of all pages, ignoring links between pages,
this will enable you to view contents of pages which have become
lost due to datacorruption.
"""
self.fh.seek(self.pagesize)
pn = 1
while True:
try:
... | [
"def",
"pagedump",
"(",
"self",
")",
":",
"self",
".",
"fh",
".",
"seek",
"(",
"self",
".",
"pagesize",
")",
"pn",
"=",
"1",
"while",
"True",
":",
"try",
":",
"pagedata",
"=",
"self",
".",
"fh",
".",
"read",
"(",
"self",
".",
"pagesize",
")",
"... | 41.555556 | 19.037037 |
def get_letters_iterable( word ):
""" splits the word into a character-list of tamil/english
characters present in the stream """
WLEN,idx = len(word),0
while (idx < WLEN):
c = word[idx]
#print(idx,hex(ord(c)),len(ta_letters))
if c in uyir_letter_set or c == ayudha_letter:
... | [
"def",
"get_letters_iterable",
"(",
"word",
")",
":",
"WLEN",
",",
"idx",
"=",
"len",
"(",
"word",
")",
",",
"0",
"while",
"(",
"idx",
"<",
"WLEN",
")",
":",
"c",
"=",
"word",
"[",
"idx",
"]",
"#print(idx,hex(ord(c)),len(ta_letters))",
"if",
"c",
"in",... | 29.478261 | 15.391304 |
def _fix_reindent(self, result):
"""Fix a badly indented line.
This is done by adding or removing from its initial indent only.
"""
num_indent_spaces = int(result['info'].split()[1])
line_index = result['line'] - 1
target = self.source[line_index]
self.source[l... | [
"def",
"_fix_reindent",
"(",
"self",
",",
"result",
")",
":",
"num_indent_spaces",
"=",
"int",
"(",
"result",
"[",
"'info'",
"]",
".",
"split",
"(",
")",
"[",
"1",
"]",
")",
"line_index",
"=",
"result",
"[",
"'line'",
"]",
"-",
"1",
"target",
"=",
... | 33.090909 | 19.454545 |
def extend(self, iterable):
"""
Add each item from iterable to the end of the list
"""
with self.lock:
for item in iterable:
self.append(item) | [
"def",
"extend",
"(",
"self",
",",
"iterable",
")",
":",
"with",
"self",
".",
"lock",
":",
"for",
"item",
"in",
"iterable",
":",
"self",
".",
"append",
"(",
"item",
")"
] | 28 | 8.857143 |
def spitOut(s, file, binary=False, expand=False):
r"""Write string `s` into `file` (which can be a string (`str` or
`unicode`) or a `file` instance)."""
mode = "w" + ["b",""][not binary]
file = _normalizeToFile(file, mode=mode, expand=expand)
try: file.write(s)
finally: file.close() | [
"def",
"spitOut",
"(",
"s",
",",
"file",
",",
"binary",
"=",
"False",
",",
"expand",
"=",
"False",
")",
":",
"mode",
"=",
"\"w\"",
"+",
"[",
"\"b\"",
",",
"\"\"",
"]",
"[",
"not",
"binary",
"]",
"file",
"=",
"_normalizeToFile",
"(",
"file",
",",
... | 43.571429 | 8.571429 |
def get_prev_sibling_tags(mention):
"""Return the HTML tag of the Mention's previous siblings.
Previous siblings are Mentions which are at the same level in the HTML tree
as the given mention, but are declared before the given mention. If a
candidate is passed in, only the previous siblings of its firs... | [
"def",
"get_prev_sibling_tags",
"(",
"mention",
")",
":",
"span",
"=",
"_to_span",
"(",
"mention",
")",
"prev_sibling_tags",
"=",
"[",
"]",
"i",
"=",
"_get_node",
"(",
"span",
".",
"sentence",
")",
"while",
"i",
".",
"getprevious",
"(",
")",
"is",
"not",... | 37.722222 | 16.666667 |
def regressfile(filename):
"""
Run all stories in filename 'filename' in python 2 and 3.
"""
_storybook({"rewrite": False}).in_filename(filename).with_params(
**{"python version": "2.7.14"}
).filter(
lambda story: not story.info.get("fails_on_python_2")
).ordered_by_name().play()... | [
"def",
"regressfile",
"(",
"filename",
")",
":",
"_storybook",
"(",
"{",
"\"rewrite\"",
":",
"False",
"}",
")",
".",
"in_filename",
"(",
"filename",
")",
".",
"with_params",
"(",
"*",
"*",
"{",
"\"python version\"",
":",
"\"2.7.14\"",
"}",
")",
".",
"fil... | 34.461538 | 14.307692 |
async def unformat(self):
"""Unformat this partition."""
self._data = await self._handler.unformat(
system_id=self.block_device.node.system_id,
device_id=self.block_device.id, id=self.id) | [
"async",
"def",
"unformat",
"(",
"self",
")",
":",
"self",
".",
"_data",
"=",
"await",
"self",
".",
"_handler",
".",
"unformat",
"(",
"system_id",
"=",
"self",
".",
"block_device",
".",
"node",
".",
"system_id",
",",
"device_id",
"=",
"self",
".",
"blo... | 44.6 | 11 |
def PackageVariable(key, help, default, searchfunc=None):
# NB: searchfunc is currently undocumented and unsupported
"""
The input parameters describe a 'package list' option, thus they
are returned with the correct converter and validator appended. The
result is usable for input to opts.Add() .
... | [
"def",
"PackageVariable",
"(",
"key",
",",
"help",
",",
"default",
",",
"searchfunc",
"=",
"None",
")",
":",
"# NB: searchfunc is currently undocumented and unsupported",
"help",
"=",
"'\\n '",
".",
"join",
"(",
"(",
"help",
",",
"'( yes | no | /path/to/%s )'",
"... | 40.8 | 16.133333 |
def parseSOAPMessage(data, ipAddr):
"parse raw XML data string, return a (minidom) xml document"
try:
dom = minidom.parseString(data)
except Exception:
#print('Failed to parse message from %s\n"%s": %s' % (ipAddr, data, ex), file=sys.stderr)
return None
if dom.getElementsByTagN... | [
"def",
"parseSOAPMessage",
"(",
"data",
",",
"ipAddr",
")",
":",
"try",
":",
"dom",
"=",
"minidom",
".",
"parseString",
"(",
"data",
")",
"except",
"Exception",
":",
"#print('Failed to parse message from %s\\n\"%s\": %s' % (ipAddr, data, ex), file=sys.stderr)",
"return",
... | 37.461538 | 16.615385 |
def remove_behaviour(self, behaviour):
"""
Removes a behaviour from the agent.
The behaviour is first killed.
Args:
behaviour (spade.behaviour.CyclicBehaviour): the behaviour instance to be removed
"""
if not self.has_behaviour(behaviour):
raise Va... | [
"def",
"remove_behaviour",
"(",
"self",
",",
"behaviour",
")",
":",
"if",
"not",
"self",
".",
"has_behaviour",
"(",
"behaviour",
")",
":",
"raise",
"ValueError",
"(",
"\"This behaviour is not registered\"",
")",
"index",
"=",
"self",
".",
"behaviours",
".",
"i... | 33.785714 | 15.071429 |
def call(self):
"""
call: ['mut'] ID ['(' parameters ')']
"""
is_mutable = False
if self.token.nature == Nature.MUT:
is_mutable = True
self._process(Nature.MUT)
identifier = Identifier(name=self.token.value)
self._process(Nature.ID)
... | [
"def",
"call",
"(",
"self",
")",
":",
"is_mutable",
"=",
"False",
"if",
"self",
".",
"token",
".",
"nature",
"==",
"Nature",
".",
"MUT",
":",
"is_mutable",
"=",
"True",
"self",
".",
"_process",
"(",
"Nature",
".",
"MUT",
")",
"identifier",
"=",
"Iden... | 32.4375 | 17.0625 |
def get_lights(self):
'''
Lists all available lights on the bridge.
'''
url = '/api/%s/lights' % self.username
response = self.make_request('GET', url)
lights = []
# Did we get a success response back?
# error responses look like:
# [{'error': {'ad... | [
"def",
"get_lights",
"(",
"self",
")",
":",
"url",
"=",
"'/api/%s/lights'",
"%",
"self",
".",
"username",
"response",
"=",
"self",
".",
"make_request",
"(",
"'GET'",
",",
"url",
")",
"lights",
"=",
"[",
"]",
"# Did we get a success response back?",
"# error re... | 29.833333 | 15.433333 |
def get_bool(self, key: str) -> Optional[bool]:
"""
Returns an optional configuration value, as a bool, by its key, or None if it doesn't exist.
If the configuration value isn't a legal boolean, this function will throw an error.
:param str key: The requested configuration key.
... | [
"def",
"get_bool",
"(",
"self",
",",
"key",
":",
"str",
")",
"->",
"Optional",
"[",
"bool",
"]",
":",
"v",
"=",
"self",
".",
"get",
"(",
"key",
")",
"if",
"v",
"is",
"None",
":",
"return",
"None",
"if",
"v",
"in",
"[",
"'true'",
",",
"'True'",
... | 42.555556 | 22 |
def computePointing(self, ra_deg, dec_deg, roll_deg, cartesian=False):
"""Compute a pointing model without changing the internal object pointing"""
# Roll FOV
Rrotate = r.rotateInXMat(roll_deg) # Roll
# Slew from ra/dec of zero
Ra = r.rightAscensionRotationMatrix(ra_deg)
... | [
"def",
"computePointing",
"(",
"self",
",",
"ra_deg",
",",
"dec_deg",
",",
"roll_deg",
",",
"cartesian",
"=",
"False",
")",
":",
"# Roll FOV",
"Rrotate",
"=",
"r",
".",
"rotateInXMat",
"(",
"roll_deg",
")",
"# Roll",
"# Slew from ra/dec of zero",
"Ra",
"=",
... | 33 | 16.789474 |
def _build_sectors_and_pages(self, keep_unwritten):
"""! @brief Converts the list of flash operations to flash sectors and pages.
@param self
@param keep_unwritten If true, unwritten pages in an erased sector and unwritten
contents of a modified page will be read from the ta... | [
"def",
"_build_sectors_and_pages",
"(",
"self",
",",
"keep_unwritten",
")",
":",
"assert",
"len",
"(",
"self",
".",
"flash_operation_list",
")",
">",
"0",
"self",
".",
"program_byte_count",
"=",
"0",
"flash_addr",
"=",
"self",
".",
"flash_operation_list",
"[",
... | 49.590909 | 23.863636 |
def generate_multiple_parameters(self, parameter_id_list):
"""Returns multiple sets of trial (hyper-)parameters, as iterable of serializable objects.
Call 'generate_parameters()' by 'count' times by default.
User code must override either this function or 'generate_parameters()'.
If ther... | [
"def",
"generate_multiple_parameters",
"(",
"self",
",",
"parameter_id_list",
")",
":",
"result",
"=",
"[",
"]",
"for",
"parameter_id",
"in",
"parameter_id_list",
":",
"try",
":",
"_logger",
".",
"debug",
"(",
"\"generating param for {}\"",
".",
"format",
"(",
"... | 53.411765 | 21.941176 |
def oauth_only(function):
"""Decorator to restrict some GitHubTools methods to run only with OAuth"""
def check_for_oauth(self, *args, **kwargs):
"""
Returns False if GitHubTools instance is not authenticated, or return
the decorated fucntion if it is.
"""
if not self.is... | [
"def",
"oauth_only",
"(",
"function",
")",
":",
"def",
"check_for_oauth",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"\"\"\"\n Returns False if GitHubTools instance is not authenticated, or return\n the decorated fucntion if it is.\n ... | 37.066667 | 15.4 |
def getCallerInfo(depth=2):
"""Utility function to get information about function callers
The information is the tuple (function/method name, filename, class)
The class will be None if the caller is just a function and not an object
method.
:param depth: (int) how far back in the callstack to go to extract ... | [
"def",
"getCallerInfo",
"(",
"depth",
"=",
"2",
")",
":",
"f",
"=",
"sys",
".",
"_getframe",
"(",
"depth",
")",
"method_name",
"=",
"f",
".",
"f_code",
".",
"co_name",
"filename",
"=",
"f",
".",
"f_code",
".",
"co_filename",
"arg_class",
"=",
"None",
... | 31.857143 | 21.761905 |
def format_(blocks):
"""Produce Python module from blocks of tests
Arguments:
blocks (list): Blocks of tests from func:`parse()`
"""
tests = list()
function_count = 0 # For each test to have a unique name
for block in blocks:
# Validate docstring format of body
if n... | [
"def",
"format_",
"(",
"blocks",
")",
":",
"tests",
"=",
"list",
"(",
")",
"function_count",
"=",
"0",
"# For each test to have a unique name",
"for",
"block",
"in",
"blocks",
":",
"# Validate docstring format of body",
"if",
"not",
"any",
"(",
"line",
"[",
":",... | 30.958333 | 22.0625 |
def not_evaluator(conditions, leaf_evaluator):
""" Evaluates a list of conditions as if the evaluator had been applied
to a single entry and NOT was applied to the result.
Args:
conditions: List of conditions ex: [operand_1, operand_2].
leaf_evaluator: Function which will be called to evaluate leaf condi... | [
"def",
"not_evaluator",
"(",
"conditions",
",",
"leaf_evaluator",
")",
":",
"if",
"not",
"len",
"(",
"conditions",
")",
">",
"0",
":",
"return",
"None",
"result",
"=",
"evaluate",
"(",
"conditions",
"[",
"0",
"]",
",",
"leaf_evaluator",
")",
"return",
"N... | 34.526316 | 20.631579 |
def flush_task_and_object_metadata_unsafe():
"""This removes some critical state from the Redis shards.
In a multitenant environment, this will flush metadata for all jobs, which
may be undesirable.
This removes all of the object and task metadata. This can be used to try
to address out-of-memory ... | [
"def",
"flush_task_and_object_metadata_unsafe",
"(",
")",
":",
"ray",
".",
"worker",
".",
"global_worker",
".",
"check_connected",
"(",
")",
"def",
"flush_shard",
"(",
"redis_client",
")",
":",
"# Flush the task table. Note that this also flushes the driver tasks",
"# which... | 44.578947 | 21.394737 |
def _get_base_model(self):
"""
:return: base model from Keras based on user-supplied model name
"""
if self.model_name == 'inception_v3':
return InceptionV3(weights='imagenet', include_top=False)
elif self.model_name == 'xception':
return Xception(weights=... | [
"def",
"_get_base_model",
"(",
"self",
")",
":",
"if",
"self",
".",
"model_name",
"==",
"'inception_v3'",
":",
"return",
"InceptionV3",
"(",
"weights",
"=",
"'imagenet'",
",",
"include_top",
"=",
"False",
")",
"elif",
"self",
".",
"model_name",
"==",
"'xcept... | 46.625 | 15.375 |
def compile_mof_file(self, mof_file, namespace=None, search_paths=None,
verbose=None):
"""
Compile the MOF definitions in the specified file (and its included
files) and add the resulting CIM objects to the specified CIM namespace
of the mock repository.
... | [
"def",
"compile_mof_file",
"(",
"self",
",",
"mof_file",
",",
"namespace",
"=",
"None",
",",
"search_paths",
"=",
"None",
",",
"verbose",
"=",
"None",
")",
":",
"namespace",
"=",
"namespace",
"or",
"self",
".",
"default_namespace",
"self",
".",
"_validate_na... | 39.634921 | 25.793651 |
def close(self):
"""Closes the stream."""
if self.call is None:
return
self._request_queue.put(None)
self.call.cancel()
self._request_generator = None | [
"def",
"close",
"(",
"self",
")",
":",
"if",
"self",
".",
"call",
"is",
"None",
":",
"return",
"self",
".",
"_request_queue",
".",
"put",
"(",
"None",
")",
"self",
".",
"call",
".",
"cancel",
"(",
")",
"self",
".",
"_request_generator",
"=",
"None"
] | 24.5 | 14.5 |
def changeGroupImageRemote(self, image_url, thread_id=None):
"""
Changes a thread image from a URL
:param image_url: URL of an image to upload and change
:param thread_id: User/Group ID to change image. See :ref:`intro_threads`
:raises: FBchatException if request failed
... | [
"def",
"changeGroupImageRemote",
"(",
"self",
",",
"image_url",
",",
"thread_id",
"=",
"None",
")",
":",
"(",
"image_id",
",",
"mimetype",
")",
",",
"=",
"self",
".",
"_upload",
"(",
"get_files_from_urls",
"(",
"[",
"image_url",
"]",
")",
")",
"return",
... | 45.2 | 19 |
def peek(init, exposes, debug=False):
"""
Default deserializer factory.
Arguments:
init (callable): type constructor.
exposes (iterable): attributes to be peeked and passed to `init`.
Returns:
callable: deserializer (`peek` routine).
"""
def _peek(store, container, _... | [
"def",
"peek",
"(",
"init",
",",
"exposes",
",",
"debug",
"=",
"False",
")",
":",
"def",
"_peek",
"(",
"store",
",",
"container",
",",
"_stack",
"=",
"None",
")",
":",
"args",
"=",
"[",
"store",
".",
"peek",
"(",
"objname",
",",
"container",
",",
... | 23.809524 | 19.904762 |
def get_element_by_class_name_or_raise(self, class_name):
"""Return the SchemaElement for the specified class name, asserting that it exists."""
if class_name not in self._elements:
raise InvalidClassError(u'Class does not exist: {}'.format(class_name))
return self._elements[class_n... | [
"def",
"get_element_by_class_name_or_raise",
"(",
"self",
",",
"class_name",
")",
":",
"if",
"class_name",
"not",
"in",
"self",
".",
"_elements",
":",
"raise",
"InvalidClassError",
"(",
"u'Class does not exist: {}'",
".",
"format",
"(",
"class_name",
")",
")",
"re... | 53.166667 | 17.5 |
def wait_for(self, timeout):
"""
A decorator factory that ensures the wrapped function runs in the
reactor thread.
When the wrapped function is called, its result is returned or its
exception raised. Deferreds are handled transparently. Calls will
timeout after the given... | [
"def",
"wait_for",
"(",
"self",
",",
"timeout",
")",
":",
"def",
"decorator",
"(",
"function",
")",
":",
"@",
"wrapt",
".",
"decorator",
"def",
"wrapper",
"(",
"function",
",",
"_",
",",
"args",
",",
"kwargs",
")",
":",
"@",
"self",
".",
"run_in_reac... | 34.8 | 18.742857 |
def max(self):
"""Get maximum target value found and corresponding parametes."""
try:
res = {
'target': self.target.max(),
'params': dict(
zip(self.keys, self.params[self.target.argmax()])
)
}
except Valu... | [
"def",
"max",
"(",
"self",
")",
":",
"try",
":",
"res",
"=",
"{",
"'target'",
":",
"self",
".",
"target",
".",
"max",
"(",
")",
",",
"'params'",
":",
"dict",
"(",
"zip",
"(",
"self",
".",
"keys",
",",
"self",
".",
"params",
"[",
"self",
".",
... | 29.666667 | 18.583333 |
def get_config_bool(name):
"""Checks if a config value is set to a valid bool value."""
cli_config = CLIConfig(SF_CLI_CONFIG_DIR, SF_CLI_ENV_VAR_PREFIX)
return cli_config.getboolean('servicefabric', name, False) | [
"def",
"get_config_bool",
"(",
"name",
")",
":",
"cli_config",
"=",
"CLIConfig",
"(",
"SF_CLI_CONFIG_DIR",
",",
"SF_CLI_ENV_VAR_PREFIX",
")",
"return",
"cli_config",
".",
"getboolean",
"(",
"'servicefabric'",
",",
"name",
",",
"False",
")"
] | 44 | 20.8 |
def _plt_pydot(self, fout_img):
"""Plot using the pydot graphics engine."""
dag = self.get_pydot_graph()
self.wr_pydot_dag(fout_img, dag) | [
"def",
"_plt_pydot",
"(",
"self",
",",
"fout_img",
")",
":",
"dag",
"=",
"self",
".",
"get_pydot_graph",
"(",
")",
"self",
".",
"wr_pydot_dag",
"(",
"fout_img",
",",
"dag",
")"
] | 39.5 | 3.25 |
def _chk_truncate(self):
'''
Checks whether the frame should be truncated. If so, slices
the frame up.
'''
# Column of which first element is used to determine width of a dot col
self.tr_size_col = -1
# Cut the data to the information actually printed
ma... | [
"def",
"_chk_truncate",
"(",
"self",
")",
":",
"# Column of which first element is used to determine width of a dot col",
"self",
".",
"tr_size_col",
"=",
"-",
"1",
"# Cut the data to the information actually printed",
"max_cols",
"=",
"self",
".",
"max_cols",
"max_rows",
"="... | 36.594203 | 17.811594 |
def modified_lines_from_diff(self, diff):
"""Returns the changed lines in a diff.
- Potentially this is vc specific (if not using udiff).
Note: this returns the line numbers in descending order.
"""
from pep8radius.diff import modified_lines_from_udiff
for start, end i... | [
"def",
"modified_lines_from_diff",
"(",
"self",
",",
"diff",
")",
":",
"from",
"pep8radius",
".",
"diff",
"import",
"modified_lines_from_udiff",
"for",
"start",
",",
"end",
"in",
"modified_lines_from_udiff",
"(",
"diff",
")",
":",
"yield",
"start",
",",
"end"
] | 33.909091 | 19.909091 |
def reinforce(self, **kwargs):
"""
Reinforces the grid and calculates grid expansion costs.
See :meth:`edisgo.flex_opt.reinforce_grid` for more information.
"""
results = reinforce_grid(
self, max_while_iterations=kwargs.get(
'max_while_iterations', ... | [
"def",
"reinforce",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"results",
"=",
"reinforce_grid",
"(",
"self",
",",
"max_while_iterations",
"=",
"kwargs",
".",
"get",
"(",
"'max_while_iterations'",
",",
"10",
")",
",",
"copy_graph",
"=",
"kwargs",
".",... | 35.105263 | 18.789474 |
def _access_rule(method,
ip=None,
port=None,
proto='tcp',
direction='in',
port_origin='d',
ip_origin='d',
comment=''):
'''
Handles the cmd execution for allow and deny commands.
'''
if _status... | [
"def",
"_access_rule",
"(",
"method",
",",
"ip",
"=",
"None",
",",
"port",
"=",
"None",
",",
"proto",
"=",
"'tcp'",
",",
"direction",
"=",
"'in'",
",",
"port_origin",
"=",
"'d'",
",",
"ip_origin",
"=",
"'d'",
",",
"comment",
"=",
"''",
")",
":",
"i... | 40.928571 | 18.714286 |
def correct_hyperlinks(book_dir=BOOK_PATH, dest=None, include_tags=None,
ext='.nlpiabak', skip_untitled=True):
""" DEPRECATED (see translate_line_footnotes)
Find bad footnotes (only urls), visit the page, add the title to the footnote
>>> len(correct_hyperlinks(book_dir=BOOK_PATH, ... | [
"def",
"correct_hyperlinks",
"(",
"book_dir",
"=",
"BOOK_PATH",
",",
"dest",
"=",
"None",
",",
"include_tags",
"=",
"None",
",",
"ext",
"=",
"'.nlpiabak'",
",",
"skip_untitled",
"=",
"True",
")",
":",
"# bad_url_lines = find_all_bad_footnote_urls(book_dir=book_dir)",
... | 48.266667 | 27.2 |
def prompt_and_delete(path, no_input=False):
"""
Ask user if it's okay to delete the previously-downloaded file/directory.
If yes, delete it. If no, checks to see if the old version should be
reused. If yes, it's reused; otherwise, Cookiecutter exits.
:param path: Previously downloaded zipfile.
... | [
"def",
"prompt_and_delete",
"(",
"path",
",",
"no_input",
"=",
"False",
")",
":",
"# Suppress prompt if called via API",
"if",
"no_input",
":",
"ok_to_delete",
"=",
"True",
"else",
":",
"question",
"=",
"(",
"\"You've downloaded {} before. \"",
"\"Is it okay to delete a... | 28.054054 | 20.702703 |
def cell_to_text(self):
"""Return the text representation for the cell"""
if self.is_code():
return self.code_to_text()
source = copy(self.source)
if not self.comment:
escape_code_start(source, self.ext, None)
return self.markdown_to_text(source) | [
"def",
"cell_to_text",
"(",
"self",
")",
":",
"if",
"self",
".",
"is_code",
"(",
")",
":",
"return",
"self",
".",
"code_to_text",
"(",
")",
"source",
"=",
"copy",
"(",
"self",
".",
"source",
")",
"if",
"not",
"self",
".",
"comment",
":",
"escape_code... | 33.666667 | 12 |
def pymux_key_to_prompt_toolkit_key_sequence(key):
"""
Turn a pymux description of a key. E.g. "C-a" or "M-x" into a
prompt-toolkit key sequence.
Raises `ValueError` if the key is not known.
"""
# Make the c- and m- prefixes case insensitive.
if key.lower().startswith('m-c-'):
key ... | [
"def",
"pymux_key_to_prompt_toolkit_key_sequence",
"(",
"key",
")",
":",
"# Make the c- and m- prefixes case insensitive.",
"if",
"key",
".",
"lower",
"(",
")",
".",
"startswith",
"(",
"'m-c-'",
")",
":",
"key",
"=",
"'M-C-'",
"+",
"key",
"[",
"4",
":",
"]",
"... | 29.347826 | 14.73913 |
def _BuildOobLink(self, param, mode):
"""Builds out-of-band URL.
Gitkit API GetOobCode() is called and the returning code is combined
with Gitkit widget URL to building the out-of-band url.
Args:
param: dict of request.
mode: string, Gitkit widget mode to handle the oob action after user
... | [
"def",
"_BuildOobLink",
"(",
"self",
",",
"param",
",",
"mode",
")",
":",
"code",
"=",
"self",
".",
"rpc_helper",
".",
"GetOobCode",
"(",
"param",
")",
"if",
"code",
":",
"parsed",
"=",
"list",
"(",
"parse",
".",
"urlparse",
"(",
"self",
".",
"widget... | 28.548387 | 20 |
def load_messages(self, directory, catalogue):
"""
Loads translation found in a directory.
@type directory: string
@param directory: The directory to search
@type catalogue: MessageCatalogue
@param catalogue: The message catalogue to dump
@raises: ValueError
... | [
"def",
"load_messages",
"(",
"self",
",",
"directory",
",",
"catalogue",
")",
":",
"if",
"not",
"os",
".",
"path",
".",
"isdir",
"(",
"directory",
")",
":",
"raise",
"ValueError",
"(",
"\"{0} is not a directory\"",
".",
"format",
"(",
"directory",
")",
")"... | 35.8 | 15.64 |
def send_search(self, url):
""" Queries the Twitter API with a given query string and \
stores the results internally. Also validates returned HTTP status \
code and throws an exception in case of invalid HTTP states. \
Example usage ``sendSearch('?q=One+Two&count=100')``
:param... | [
"def",
"send_search",
"(",
"self",
",",
"url",
")",
":",
"if",
"not",
"isinstance",
"(",
"url",
",",
"str",
"if",
"py3k",
"else",
"basestring",
")",
":",
"raise",
"TwitterSearchException",
"(",
"1009",
")",
"endpoint",
"=",
"self",
".",
"_base_url",
"+",... | 37.42623 | 19.688525 |
def show(cls, msg=None):
"""
Show the log interface on the page.
"""
if msg:
cls.add(msg)
cls.overlay.show()
cls.overlay.el.bind("click", lambda x: cls.hide())
cls.el.style.display = "block"
cls.bind() | [
"def",
"show",
"(",
"cls",
",",
"msg",
"=",
"None",
")",
":",
"if",
"msg",
":",
"cls",
".",
"add",
"(",
"msg",
")",
"cls",
".",
"overlay",
".",
"show",
"(",
")",
"cls",
".",
"overlay",
".",
"el",
".",
"bind",
"(",
"\"click\"",
",",
"lambda",
... | 22.333333 | 16.333333 |
def get_participant(participant_id):
"""Get the participant with the given id."""
try:
ppt = models.Participant.query.filter_by(id=participant_id).one()
except NoResultFound:
return error_response(
error_type="/participant GET: no participant found",
status=403)
... | [
"def",
"get_participant",
"(",
"participant_id",
")",
":",
"try",
":",
"ppt",
"=",
"models",
".",
"Participant",
".",
"query",
".",
"filter_by",
"(",
"id",
"=",
"participant_id",
")",
".",
"one",
"(",
")",
"except",
"NoResultFound",
":",
"return",
"error_r... | 37.153846 | 17.615385 |
def _get_args(self, node, keywords):
"""
Intercept calls to get template and return our own node-specific
template
"""
args = super(ArcanaSlurmGraphPlugin, self)._get_args(
node, keywords)
# Substitute the template arg with the node-specific one
new_ar... | [
"def",
"_get_args",
"(",
"self",
",",
"node",
",",
"keywords",
")",
":",
"args",
"=",
"super",
"(",
"ArcanaSlurmGraphPlugin",
",",
"self",
")",
".",
"_get_args",
"(",
"node",
",",
"keywords",
")",
"# Substitute the template arg with the node-specific one",
"new_ar... | 36.666667 | 14.266667 |
def get_onnx_variable_name(self, seed):
'''
Retrieve the variable ID of the given seed or create one if it is the first time of seeing this seed
'''
if seed in self.variable_name_mapping:
return self.variable_name_mapping[seed][-1]
else:
return self.get_un... | [
"def",
"get_onnx_variable_name",
"(",
"self",
",",
"seed",
")",
":",
"if",
"seed",
"in",
"self",
".",
"variable_name_mapping",
":",
"return",
"self",
".",
"variable_name_mapping",
"[",
"seed",
"]",
"[",
"-",
"1",
"]",
"else",
":",
"return",
"self",
".",
... | 42.125 | 23.625 |
def write_usage(self, prog, args='', prefix='Usage: '):
"""Writes a usage line into the buffer.
:param prog: the program name.
:param args: whitespace separated list of arguments.
:param prefix: the prefix for the first line.
"""
usage_prefix = '%*s%s ' % (self.current_i... | [
"def",
"write_usage",
"(",
"self",
",",
"prog",
",",
"args",
"=",
"''",
",",
"prefix",
"=",
"'Usage: '",
")",
":",
"usage_prefix",
"=",
"'%*s%s '",
"%",
"(",
"self",
".",
"current_indent",
",",
"prefix",
",",
"prog",
")",
"text_width",
"=",
"self",
"."... | 43.730769 | 18.5 |
def _write_wrapped_codestream(self, ofile, box):
"""Write wrapped codestream."""
# Codestreams require a bit more care.
# Am I a raw codestream?
if len(self.box) == 0:
# Yes, just write the codestream box header plus all
# of myself out to file.
ofile.... | [
"def",
"_write_wrapped_codestream",
"(",
"self",
",",
"ofile",
",",
"box",
")",
":",
"# Codestreams require a bit more care.",
"# Am I a raw codestream?",
"if",
"len",
"(",
"self",
".",
"box",
")",
"==",
"0",
":",
"# Yes, just write the codestream box header plus all",
... | 40.16 | 17.54 |
def _setattr_url_map(self):
'''
Set an attribute on the local instance for each key/val in url_map
CherryPy uses class attributes to resolve URLs.
'''
if self.apiopts.get('enable_sessions', True) is False:
url_blacklist = ['login', 'logout', 'minions', 'jobs']
... | [
"def",
"_setattr_url_map",
"(",
"self",
")",
":",
"if",
"self",
".",
"apiopts",
".",
"get",
"(",
"'enable_sessions'",
",",
"True",
")",
"is",
"False",
":",
"url_blacklist",
"=",
"[",
"'login'",
",",
"'logout'",
",",
"'minions'",
",",
"'jobs'",
"]",
"else... | 33.0625 | 23.3125 |
def parallel(view, dist='b', block=None, ordered=True, **flags):
"""Turn a function into a parallel remote function.
This method can be used for map:
In [1]: @parallel(view, block=True)
...: def func(a):
...: pass
"""
def parallel_function(f):
return ParallelFunction(view... | [
"def",
"parallel",
"(",
"view",
",",
"dist",
"=",
"'b'",
",",
"block",
"=",
"None",
",",
"ordered",
"=",
"True",
",",
"*",
"*",
"flags",
")",
":",
"def",
"parallel_function",
"(",
"f",
")",
":",
"return",
"ParallelFunction",
"(",
"view",
",",
"f",
... | 30.076923 | 19.923077 |
def normalize_url(url: 'Union[URL, str]') -> 'URL':
"""Normalize url to make comparisons."""
url = URL(url)
return url.with_query(urlencode(sorted(parse_qsl(url.query_string)))) | [
"def",
"normalize_url",
"(",
"url",
":",
"'Union[URL, str]'",
")",
"->",
"'URL'",
":",
"url",
"=",
"URL",
"(",
"url",
")",
"return",
"url",
".",
"with_query",
"(",
"urlencode",
"(",
"sorted",
"(",
"parse_qsl",
"(",
"url",
".",
"query_string",
")",
")",
... | 46.5 | 16.5 |
def add_file_metadata(self, fname):
"""
collects the files metadata - note that this will fail
with strange errors if network connection drops out to
shared folder, but it is better to stop the program
rather than do a try except otherwise you will get an
incomplete... | [
"def",
"add_file_metadata",
"(",
"self",
",",
"fname",
")",
":",
"file_dict",
"=",
"{",
"}",
"file_dict",
"[",
"\"fullfilename\"",
"]",
"=",
"fname",
"try",
":",
"file_dict",
"[",
"\"name\"",
"]",
"=",
"os",
".",
"path",
".",
"basename",
"(",
"fname",
... | 38.3 | 16 |
def _apply_search_backrefs(pattern, flags=0):
"""Apply the search backrefs to the search pattern."""
if isinstance(pattern, (str, bytes)):
re_verbose = VERBOSE & flags
if flags & V0:
re_version = V0
elif flags & V1:
re_version = V1
else:
re_ve... | [
"def",
"_apply_search_backrefs",
"(",
"pattern",
",",
"flags",
"=",
"0",
")",
":",
"if",
"isinstance",
"(",
"pattern",
",",
"(",
"str",
",",
"bytes",
")",
")",
":",
"re_verbose",
"=",
"VERBOSE",
"&",
"flags",
"if",
"flags",
"&",
"V0",
":",
"re_version"... | 38.8 | 19.6 |
def fitToSize(rect, targetWidth, targetHeight, bounds):
"""
Pads or crops a rectangle as necessary to achieve the target dimensions,
ensuring the modified rectangle falls within the specified bounds.
The input rectangle, bounds, and return value are all a tuple of (x,y,w,h).
"""
# Determine the difference bet... | [
"def",
"fitToSize",
"(",
"rect",
",",
"targetWidth",
",",
"targetHeight",
",",
"bounds",
")",
":",
"# Determine the difference between the current size and target size",
"x",
",",
"y",
",",
"w",
",",
"h",
"=",
"rect",
"diffX",
"=",
"w",
"-",
"targetWidth",
"diff... | 33.470588 | 20.176471 |
def list(self, href):
"""
list of files and directories at remote server
:param href: remote folder
:return: list(folders, files) and list(None,None) if folder doesn't exist
"""
for iTry in range(TRYINGS):
logger.info(u("list(%s): %s") % (iTry, href))
... | [
"def",
"list",
"(",
"self",
",",
"href",
")",
":",
"for",
"iTry",
"in",
"range",
"(",
"TRYINGS",
")",
":",
"logger",
".",
"info",
"(",
"u",
"(",
"\"list(%s): %s\"",
")",
"%",
"(",
"iTry",
",",
"href",
")",
")",
"folders",
"=",
"None",
"files",
"=... | 43.477273 | 13.159091 |
def use_comparative_authorization_view(self):
"""Pass through to provider AuthorizationLookupSession.use_comparative_authorization_view"""
self._object_views['authorization'] = COMPARATIVE
# self._get_provider_session('authorization_lookup_session') # To make sure the session is tracked
... | [
"def",
"use_comparative_authorization_view",
"(",
"self",
")",
":",
"self",
".",
"_object_views",
"[",
"'authorization'",
"]",
"=",
"COMPARATIVE",
"# self._get_provider_session('authorization_lookup_session') # To make sure the session is tracked",
"for",
"session",
"in",
"self",... | 54.555556 | 19 |
def Gf(counts):
r'''Estimates the ideal-gas Gibbs energy of formation at 298.15 K of an
organic compound using the Joback method as a function of chemical
structure only.
.. math::
G_{formation} = 53.88 + \sum {G_{f,i}}
In the above equation,... | [
"def",
"Gf",
"(",
"counts",
")",
":",
"tot",
"=",
"0.0",
"for",
"group",
",",
"count",
"in",
"counts",
".",
"items",
"(",
")",
":",
"tot",
"+=",
"joback_groups_id_dict",
"[",
"group",
"]",
".",
"Gform",
"*",
"count",
"Gf",
"=",
"53.88",
"+",
"tot",... | 32.388889 | 23.666667 |
def constant(duration: int, amp: complex, name: str = None) -> SamplePulse:
"""Generates constant-sampled `SamplePulse`.
Applies `left` sampling strategy to generate discrete pulse from continuous function.
Args:
duration: Duration of pulse. Must be greater than zero.
amp: Complex pulse am... | [
"def",
"constant",
"(",
"duration",
":",
"int",
",",
"amp",
":",
"complex",
",",
"name",
":",
"str",
"=",
"None",
")",
"->",
"SamplePulse",
":",
"return",
"_sampled_constant_pulse",
"(",
"duration",
",",
"amp",
",",
"name",
"=",
"name",
")"
] | 37.818182 | 23 |
def order_search(self, article_code, **kwargs):
'''taobao.vas.order.search 订单记录导出
用于ISV查询自己名下的应用及收费项目的订单记录。目前所有应用调用此接口的频率限制为200次/分钟,即每分钟内,所有应用调用此接口的次数加起来最多为200次。'''
request = TOPRequest('taobao.vas.order.search')
request['article_code'] = article_code
for k, v in kwargs.... | [
"def",
"order_search",
"(",
"self",
",",
"article_code",
",",
"*",
"*",
"kwargs",
")",
":",
"request",
"=",
"TOPRequest",
"(",
"'taobao.vas.order.search'",
")",
"request",
"[",
"'article_code'",
"]",
"=",
"article_code",
"for",
"k",
",",
"v",
"in",
"kwargs",... | 62.272727 | 31.181818 |
async def _request(
self,
method: str,
endpoint: str,
*,
headers: dict = None,
params: dict = None,
json: dict = None,
ssl: bool = True) -> dict:
"""Wrap the generic request method to add access token, etc."""
... | [
"async",
"def",
"_request",
"(",
"self",
",",
"method",
":",
"str",
",",
"endpoint",
":",
"str",
",",
"*",
",",
"headers",
":",
"dict",
"=",
"None",
",",
"params",
":",
"dict",
"=",
"None",
",",
"json",
":",
"dict",
"=",
"None",
",",
"ssl",
":",
... | 32.736842 | 13.421053 |
def get(name, required=False, default=empty, type=None):
"""Generic getter for environment variables. Handles defaults,
required-ness, and what type to expect.
:param name: The name of the environment variable be pulled
:type name: str
:param required: Whether the environment variable is required.... | [
"def",
"get",
"(",
"name",
",",
"required",
"=",
"False",
",",
"default",
"=",
"empty",
",",
"type",
"=",
"None",
")",
":",
"fn",
"=",
"{",
"'int'",
":",
"env_int",
",",
"int",
":",
"env_int",
",",
"'bool'",
":",
"env_bool",
",",
"bool",
":",
"en... | 28.692308 | 21.282051 |
def _get_dbid2goids(associations):
"""Return gene2go data for user-specified taxids."""
id2gos = cx.defaultdict(set)
for ntd in associations:
id2gos[ntd.DB_ID].add(ntd.GO_ID)
return dict(id2gos) | [
"def",
"_get_dbid2goids",
"(",
"associations",
")",
":",
"id2gos",
"=",
"cx",
".",
"defaultdict",
"(",
"set",
")",
"for",
"ntd",
"in",
"associations",
":",
"id2gos",
"[",
"ntd",
".",
"DB_ID",
"]",
".",
"add",
"(",
"ntd",
".",
"GO_ID",
")",
"return",
... | 38.833333 | 5.833333 |
def log_very_verbose(self, message):
"""
Logs a message only when logging level is very verbose.
:param str|list[str] message: The message.
"""
if self.get_verbosity() >= Output.VERBOSITY_VERY_VERBOSE:
self.writeln(message) | [
"def",
"log_very_verbose",
"(",
"self",
",",
"message",
")",
":",
"if",
"self",
".",
"get_verbosity",
"(",
")",
">=",
"Output",
".",
"VERBOSITY_VERY_VERBOSE",
":",
"self",
".",
"writeln",
"(",
"message",
")"
] | 33.625 | 13.625 |
def folderitems(self):
"""Generate folderitems for each version
"""
items = []
# get the snapshots
snapshots = get_snapshots(self.context)
# reverse the order to get the most recent change first
snapshots = list(reversed(snapshots))
# set the total number ... | [
"def",
"folderitems",
"(",
"self",
")",
":",
"items",
"=",
"[",
"]",
"# get the snapshots",
"snapshots",
"=",
"get_snapshots",
"(",
"self",
".",
"context",
")",
"# reverse the order to get the most recent change first",
"snapshots",
"=",
"list",
"(",
"reversed",
"("... | 34.914286 | 19.557143 |
def force_plot(base_value, shap_values, features=None, feature_names=None, out_names=None, link="identity",
plot_cmap="RdBu", matplotlib=False, show=True, figsize=(20,3), ordering_keys=None, ordering_keys_time_format=None,
text_rotation=0):
""" Visualize the given SHAP values with an a... | [
"def",
"force_plot",
"(",
"base_value",
",",
"shap_values",
",",
"features",
"=",
"None",
",",
"feature_names",
"=",
"None",
",",
"out_names",
"=",
"None",
",",
"link",
"=",
"\"identity\"",
",",
"plot_cmap",
"=",
"\"RdBu\"",
",",
"matplotlib",
"=",
"False",
... | 41.744828 | 26.262069 |
def _strip_placeholder_braces(p_matchobj):
"""
Returns string with conditional braces around placeholder stripped and
percent sign glued into placeholder character.
Returned string is composed from 'start', 'before', 'placeholder', 'after',
'whitespace', and 'end' match-groups of p_matchobj. Condit... | [
"def",
"_strip_placeholder_braces",
"(",
"p_matchobj",
")",
":",
"before",
"=",
"p_matchobj",
".",
"group",
"(",
"'before'",
")",
"or",
"''",
"placeholder",
"=",
"p_matchobj",
".",
"group",
"(",
"'placeholder'",
")",
"after",
"=",
"p_matchobj",
".",
"group",
... | 39.238095 | 21.714286 |
def _reset(self, load):
"""
Reset sorted list load.
The *load* specifies the load-factor of the list. The default load
factor of '1000' works well for lists from tens to tens of millions of
elements. Good practice is to use a value that is the cube root of the
list size... | [
"def",
"_reset",
"(",
"self",
",",
"load",
")",
":",
"values",
"=",
"reduce",
"(",
"iadd",
",",
"self",
".",
"_lists",
",",
"[",
"]",
")",
"self",
".",
"_clear",
"(",
")",
"self",
".",
"_load",
"=",
"load",
"self",
".",
"_half",
"=",
"load",
">... | 39.529412 | 19.529412 |
def __read(self, i: int) -> bytes:
"""Returns a set number (i) of bytes from self.data."""
b = self.data[self.idx: self.idx + i]
self.idx += i
if len(b) != i:
raise bencodepy.DecodingError(
"Incorrect byte length returned between indexes of {0} and {1}. Possib... | [
"def",
"__read",
"(",
"self",
",",
"i",
":",
"int",
")",
"->",
"bytes",
":",
"b",
"=",
"self",
".",
"data",
"[",
"self",
".",
"idx",
":",
"self",
".",
"idx",
"+",
"i",
"]",
"self",
".",
"idx",
"+=",
"i",
"if",
"len",
"(",
"b",
")",
"!=",
... | 46.555556 | 18.666667 |
def export_coreml(self, filename,
include_non_maximum_suppression = True,
iou_threshold = None,
confidence_threshold = None):
"""
Save the model in Core ML format. The Core ML model takes an image of
fixed size as input and produces two output arrays: `confid... | [
"def",
"export_coreml",
"(",
"self",
",",
"filename",
",",
"include_non_maximum_suppression",
"=",
"True",
",",
"iou_threshold",
"=",
"None",
",",
"confidence_threshold",
"=",
"None",
")",
":",
"import",
"mxnet",
"as",
"_mx",
"from",
".",
".",
"_mxnet",
".",
... | 46.469758 | 21.743952 |
def transitive_invalidation_hash(self, fingerprint_strategy=None, depth=0):
"""
:API: public
:param FingerprintStrategy fingerprint_strategy: optional fingerprint strategy to use to compute
the fingerprint of a target
:return: A fingerprint representing this target and all of its dependencies.
... | [
"def",
"transitive_invalidation_hash",
"(",
"self",
",",
"fingerprint_strategy",
"=",
"None",
",",
"depth",
"=",
"0",
")",
":",
"if",
"depth",
">",
"self",
".",
"_MAX_RECURSION_DEPTH",
":",
"# NB(zundel) without this catch, we'll eventually hit the python stack limit",
"#... | 46.653846 | 27.461538 |
def compute_potentials_analytical_hs(grid, configs_raw, rho):
"""Compute the potential superpositions of each current dipole in the
configurations, using the provided resistivity
Parameters
----------
grid:
crt_grid object with loaded FE grid. Used for the electrode positions
configs_ra... | [
"def",
"compute_potentials_analytical_hs",
"(",
"grid",
",",
"configs_raw",
",",
"rho",
")",
":",
"potentials",
"=",
"[",
"]",
"nodes_sorted",
"=",
"grid",
".",
"nodes",
"[",
"'sorted'",
"]",
"nodes_raw",
"=",
"grid",
".",
"nodes",
"[",
"'sorted'",
"]",
"f... | 32.765957 | 17.021277 |
def save_user(user, name, save=None): # noqa: E501
"""Save a script
Save a script # noqa: E501
:param user: Get user with this name
:type user: str
:param name: Get status of a driver with this name
:type name: str
:param save: The data needed to save this user
:type save: dict | byte... | [
"def",
"save_user",
"(",
"user",
",",
"name",
",",
"save",
"=",
"None",
")",
":",
"# noqa: E501",
"if",
"connexion",
".",
"request",
".",
"is_json",
":",
"save",
"=",
"Save",
".",
"from_dict",
"(",
"connexion",
".",
"request",
".",
"get_json",
"(",
")"... | 28 | 19.966667 |
def info(gandi, email):
"""Display information about a mailbox."""
login, domain = email
output_keys = ['login', 'aliases', 'fallback', 'quota', 'responder']
mailbox = gandi.mail.info(domain, login)
output_mailbox(gandi, mailbox, output_keys)
return mailbox | [
"def",
"info",
"(",
"gandi",
",",
"email",
")",
":",
"login",
",",
"domain",
"=",
"email",
"output_keys",
"=",
"[",
"'login'",
",",
"'aliases'",
",",
"'fallback'",
",",
"'quota'",
",",
"'responder'",
"]",
"mailbox",
"=",
"gandi",
".",
"mail",
".",
"inf... | 30.555556 | 19.666667 |
def is_year(self):
"""Determine if a data record is of type YEAR."""
dt = DATA_TYPES['year']
if dt['min'] and dt['max']:
if type(self.data) is dt['type'] and dt['min'] < self.data < dt['max']:
self.type = 'year'.upper()
self.len = None
... | [
"def",
"is_year",
"(",
"self",
")",
":",
"dt",
"=",
"DATA_TYPES",
"[",
"'year'",
"]",
"if",
"dt",
"[",
"'min'",
"]",
"and",
"dt",
"[",
"'max'",
"]",
":",
"if",
"type",
"(",
"self",
".",
"data",
")",
"is",
"dt",
"[",
"'type'",
"]",
"and",
"dt",
... | 40.5 | 12.875 |
def process_tree_files(tree):
""" process_tree_files: Download files from nodes
Args:
tree (ChannelManager): manager to handle communication to Kolibri Studio
Returns: None
"""
# Fill in values necessary for next steps
config.LOGGER.info("Processing content...")
files_to_... | [
"def",
"process_tree_files",
"(",
"tree",
")",
":",
"# Fill in values necessary for next steps",
"config",
".",
"LOGGER",
".",
"info",
"(",
"\"Processing content...\"",
")",
"files_to_diff",
"=",
"tree",
".",
"process_tree",
"(",
"tree",
".",
"channel",
")",
"config... | 44.333333 | 16.666667 |
def hue(self, img1, img2):
"""Applies the hue blend mode.
Hues image img1 with image img2.
The hue filter replaces the hues of pixels in img1
with the hues of pixels in img2.
Returns a composite image with the alpha channel retained.
"""
import col... | [
"def",
"hue",
"(",
"self",
",",
"img1",
",",
"img2",
")",
":",
"import",
"colorsys",
"p1",
"=",
"list",
"(",
"img1",
".",
"getdata",
"(",
")",
")",
"p2",
"=",
"list",
"(",
"img2",
".",
"getdata",
"(",
")",
")",
"for",
"i",
"in",
"range",
"(",
... | 26.55 | 17.625 |
def _get_corpus_properties(self, corpus_name):
"""Check whether a corpus is available for import.
:type corpus_name: str
:param corpus_name: Name of available corpus.
:rtype : str
"""
try:
# corpora = LANGUAGE_CORPORA[self.language]
corpora = self.... | [
"def",
"_get_corpus_properties",
"(",
"self",
",",
"corpus_name",
")",
":",
"try",
":",
"# corpora = LANGUAGE_CORPORA[self.language]",
"corpora",
"=",
"self",
".",
"all_corpora",
"except",
"NameError",
"as",
"name_error",
":",
"msg",
"=",
"'Corpus not available for lang... | 40.761905 | 9.952381 |
def addItem(self, itemType, itemContents, itemID=None):
"""
:param str itemType: The type of the item, note, place, todo
:param dict itemContents: A dictionary of the item contents
:param int itemID: When editing a note, send the ID along with it
"""
if itemT... | [
"def",
"addItem",
"(",
"self",
",",
"itemType",
",",
"itemContents",
",",
"itemID",
"=",
"None",
")",
":",
"if",
"itemType",
"not",
"in",
"self",
".",
"noteDB",
".",
"collection_names",
"(",
")",
":",
"fields",
"=",
"[",
"(",
"ii",
",",
"pymongo",
".... | 39.62963 | 18.518519 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.