text stringlengths 89 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 630 |
|---|---|---|---|
def hardware_info():
"""
Returns basic hardware information about the computer.
Gives actual number of CPU's in the machine, even when hyperthreading is
turned on.
Returns
-------
info : dict
Dictionary containing cpu and memory information.
"""
try:
if sys.platfor... | [
"def",
"hardware_info",
"(",
")",
":",
"try",
":",
"if",
"sys",
".",
"platform",
"==",
"'darwin'",
":",
"out",
"=",
"_mac_hardware_info",
"(",
")",
"elif",
"sys",
".",
"platform",
"==",
"'win32'",
":",
"out",
"=",
"_win_hardware_info",
"(",
")",
"elif",
... | 23.461538 | 20.153846 |
def autodiscover_siteprefs(admin_site=None):
"""Automatically discovers and registers all preferences available in all apps.
:param admin.AdminSite admin_site: Custom AdminSite object.
"""
if admin_site is None:
admin_site = admin.site
# Do not discover anything if called from manage.py (... | [
"def",
"autodiscover_siteprefs",
"(",
"admin_site",
"=",
"None",
")",
":",
"if",
"admin_site",
"is",
"None",
":",
"admin_site",
"=",
"admin",
".",
"site",
"# Do not discover anything if called from manage.py (e.g. executing commands from cli).",
"if",
"'manage'",
"not",
"... | 39.142857 | 21.428571 |
def load(cls, database, doc_id):
"""Load a specific document from the given database.
:param database: the `Database` object to retrieve the document from
:param doc_id: the document ID
:return: the `Document` instance, or `None` if no document with the
given ID was fou... | [
"def",
"load",
"(",
"cls",
",",
"database",
",",
"doc_id",
")",
":",
"doc",
"=",
"database",
".",
"get",
"(",
"doc_id",
")",
"if",
"doc",
"is",
"None",
":",
"return",
"None",
"return",
"cls",
".",
"wrap",
"(",
"doc",
")"
] | 36.25 | 14.833333 |
def __process_by_python(self):
"""!
@brief Performs cluster analysis using python code.
"""
maximum_change = float('inf')
iteration = 0
if self.__observer is not None:
initial_clusters = self.__update_clusters()
self.__observer.notify... | [
"def",
"__process_by_python",
"(",
"self",
")",
":",
"maximum_change",
"=",
"float",
"(",
"'inf'",
")",
"iteration",
"=",
"0",
"if",
"self",
".",
"__observer",
"is",
"not",
"None",
":",
"initial_clusters",
"=",
"self",
".",
"__update_clusters",
"(",
")",
"... | 36.384615 | 26.038462 |
def read_all(self, n, check_rekey=False):
"""
Read as close to N bytes as possible, blocking as long as necessary.
@param n: number of bytes to read
@type n: int
@return: the data read
@rtype: str
@raise EOFError: if the socket was closed before all the bytes cou... | [
"def",
"read_all",
"(",
"self",
",",
"n",
",",
"check_rekey",
"=",
"False",
")",
":",
"out",
"=",
"''",
"# handle over-reading from reading the banner line",
"if",
"len",
"(",
"self",
".",
"__remainder",
")",
">",
"0",
":",
"out",
"=",
"self",
".",
"__rema... | 37.653061 | 15.163265 |
def cond_init(m:nn.Module, init_func:LayerFunc):
"Initialize the non-batchnorm layers of `m` with `init_func`."
if (not isinstance(m, bn_types)) and requires_grad(m): init_default(m, init_func) | [
"def",
"cond_init",
"(",
"m",
":",
"nn",
".",
"Module",
",",
"init_func",
":",
"LayerFunc",
")",
":",
"if",
"(",
"not",
"isinstance",
"(",
"m",
",",
"bn_types",
")",
")",
"and",
"requires_grad",
"(",
"m",
")",
":",
"init_default",
"(",
"m",
",",
"i... | 66.333333 | 26.333333 |
def ssd(p1, p2):
"""Calculates motif position similarity based on sum of squared distances.
Parameters
----------
p1 : list
Motif position 1.
p2 : list
Motif position 2.
Returns
-------
score : float
"""
return 2 - np.sum([(a-b)**2 for a,b in zip(p1... | [
"def",
"ssd",
"(",
"p1",
",",
"p2",
")",
":",
"return",
"2",
"-",
"np",
".",
"sum",
"(",
"[",
"(",
"a",
"-",
"b",
")",
"**",
"2",
"for",
"a",
",",
"b",
"in",
"zip",
"(",
"p1",
",",
"p2",
")",
"]",
")"
] | 19.4375 | 22.75 |
def query_ehs(
self,
data: Optional[pd.DataFrame] = None,
failure_mode: str = "warning",
progressbar: Optional[Callable[[Iterable], Iterable]] = None,
) -> "Flight":
"""Extend data with extra columns from EHS messages.
By default, raw messages are requested from the ... | [
"def",
"query_ehs",
"(",
"self",
",",
"data",
":",
"Optional",
"[",
"pd",
".",
"DataFrame",
"]",
"=",
"None",
",",
"failure_mode",
":",
"str",
"=",
"\"warning\"",
",",
"progressbar",
":",
"Optional",
"[",
"Callable",
"[",
"[",
"Iterable",
"]",
",",
"It... | 32.754237 | 20.144068 |
def update_bookmark(self, bookmark_id, favorite=None, archive=None, read_percent=None):
"""
Updates given bookmark. The requested bookmark must belong to the
current user.
:param bookmark_id: ID of the bookmark to update.
:param favorite (optional): Whether this article is favor... | [
"def",
"update_bookmark",
"(",
"self",
",",
"bookmark_id",
",",
"favorite",
"=",
"None",
",",
"archive",
"=",
"None",
",",
"read_percent",
"=",
"None",
")",
":",
"rdb_url",
"=",
"self",
".",
"_generate_url",
"(",
"'bookmarks/{0}'",
".",
"format",
"(",
"boo... | 45 | 21 |
def build_link(href, text, cls=None, icon_class=None, **attrs):
"""Builds an html link.
:param href: link for the anchor element
:param text: text for the anchor element
:param attrs: other attribute kwargs
>>> build_link('xyz.com', 'hello', 'big')
u'<a href="xyz.com" class="big">hello</a>'
... | [
"def",
"build_link",
"(",
"href",
",",
"text",
",",
"cls",
"=",
"None",
",",
"icon_class",
"=",
"None",
",",
"*",
"*",
"attrs",
")",
":",
"return",
"build_html_element",
"(",
"tag",
"=",
"'a'",
",",
"text",
"=",
"text",
",",
"href",
"=",
"href",
",... | 38.666667 | 10.777778 |
def calc_scene_bbox(self):
"""Calculate scene bbox"""
bbox_min, bbox_max = None, None
for node in self.root_nodes:
bbox_min, bbox_max = node.calc_global_bbox(
matrix44.create_identity(),
bbox_min,
bbox_max
)
self.bb... | [
"def",
"calc_scene_bbox",
"(",
"self",
")",
":",
"bbox_min",
",",
"bbox_max",
"=",
"None",
",",
"None",
"for",
"node",
"in",
"self",
".",
"root_nodes",
":",
"bbox_min",
",",
"bbox_max",
"=",
"node",
".",
"calc_global_bbox",
"(",
"matrix44",
".",
"create_id... | 30.928571 | 16.071429 |
def get_grounded_agent(gene_name):
"""Return a grounded Agent based on an HGNC symbol."""
db_refs = {'TEXT': gene_name}
if gene_name in hgnc_map:
gene_name = hgnc_map[gene_name]
hgnc_id = hgnc_client.get_hgnc_id(gene_name)
if hgnc_id:
db_refs['HGNC'] = hgnc_id
up_id = hgnc_cl... | [
"def",
"get_grounded_agent",
"(",
"gene_name",
")",
":",
"db_refs",
"=",
"{",
"'TEXT'",
":",
"gene_name",
"}",
"if",
"gene_name",
"in",
"hgnc_map",
":",
"gene_name",
"=",
"hgnc_map",
"[",
"gene_name",
"]",
"hgnc_id",
"=",
"hgnc_client",
".",
"get_hgnc_id",
"... | 34.692308 | 10.384615 |
def _generate_input(options):
"""First send strings from any given file, one string per line, sends
any strings provided on the command line.
:param options: ArgumentParser or equivalent to provide
options.input and options.strings.
:return: string
"""
if options.input:
fp = op... | [
"def",
"_generate_input",
"(",
"options",
")",
":",
"if",
"options",
".",
"input",
":",
"fp",
"=",
"open",
"(",
"options",
".",
"input",
")",
"if",
"options",
".",
"input",
"!=",
"\"-\"",
"else",
"sys",
".",
"stdin",
"for",
"string",
"in",
"fp",
".",... | 32 | 15.125 |
def delete(self, endpoint, json=None, params=None, **kwargs):
"""
DELETE from DHIS2
:param endpoint: DHIS2 API endpoint
:param json: HTTP payload
:param params: HTTP parameters (dict)
:return: requests.Response object
"""
json = kwargs['data'] if 'data' in... | [
"def",
"delete",
"(",
"self",
",",
"endpoint",
",",
"json",
"=",
"None",
",",
"params",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"json",
"=",
"kwargs",
"[",
"'data'",
"]",
"if",
"'data'",
"in",
"kwargs",
"else",
"json",
"return",
"self",
"."... | 40.8 | 11 |
def apply_to(self,
db: Union[BaseDB, ABC_Mutable_Mapping],
apply_deletes: bool = True) -> None:
"""
Apply the changes in this diff to the given database.
You may choose to opt out of deleting any underlying keys.
:param apply_deletes: whether the pendin... | [
"def",
"apply_to",
"(",
"self",
",",
"db",
":",
"Union",
"[",
"BaseDB",
",",
"ABC_Mutable_Mapping",
"]",
",",
"apply_deletes",
":",
"bool",
"=",
"True",
")",
"->",
"None",
":",
"for",
"key",
",",
"value",
"in",
"self",
".",
"_changes",
".",
"items",
... | 33.666667 | 14.142857 |
def string(name, value, expire=None, expireat=None, **connection_args):
'''
Ensure that the key exists in redis with the value specified
name
Redis key to manage
value
Data to persist in key
expire
Sets time to live for key in seconds
expireat
Sets expiration ... | [
"def",
"string",
"(",
"name",
",",
"value",
",",
"expire",
"=",
"None",
",",
"expireat",
"=",
"None",
",",
"*",
"*",
"connection_args",
")",
":",
"ret",
"=",
"{",
"'name'",
":",
"name",
",",
"'changes'",
":",
"{",
"}",
",",
"'result'",
":",
"True",... | 29.833333 | 26.777778 |
def base_address(self):
"""Returns the base address without payment id.
:rtype: :class:`Address`
"""
prefix = 53 if self.is_testnet() else 24 if self.is_stagenet() else 18
data = bytearray([prefix]) + self._decoded[1:65]
checksum = keccak_256(data).digest()[:4]
re... | [
"def",
"base_address",
"(",
"self",
")",
":",
"prefix",
"=",
"53",
"if",
"self",
".",
"is_testnet",
"(",
")",
"else",
"24",
"if",
"self",
".",
"is_stagenet",
"(",
")",
"else",
"18",
"data",
"=",
"bytearray",
"(",
"[",
"prefix",
"]",
")",
"+",
"self... | 45.75 | 13.75 |
def namespace_for_prefix(self, prefix):
"""Get the namespace the given prefix maps to.
Args:
prefix (str): The prefix
Returns:
str: The namespace, or None if the prefix isn't mapped to
anything in this set.
"""
try:
ni = self.... | [
"def",
"namespace_for_prefix",
"(",
"self",
",",
"prefix",
")",
":",
"try",
":",
"ni",
"=",
"self",
".",
"__lookup_prefix",
"(",
"prefix",
")",
"except",
"PrefixNotFoundError",
":",
"return",
"None",
"else",
":",
"return",
"ni",
".",
"uri"
] | 26.75 | 16.5625 |
def parse(cls, parser, text, pos):
"""Imitates parsing a list grammar.
Specifically, this
grammar = [
SimpleValueUnit.date_specifiers_regex,
SimpleValueUnit.arxiv_token_regex,
SimpleValueUnit.token_regex,
SimpleValueUnit.parenthesized_token_gramma... | [
"def",
"parse",
"(",
"cls",
",",
"parser",
",",
"text",
",",
"pos",
")",
":",
"found",
"=",
"False",
"# Attempt to parse date specifier",
"match",
"=",
"cls",
".",
"date_specifiers_regex",
".",
"match",
"(",
"text",
")",
"if",
"match",
":",
"remaining_text",... | 40.642857 | 23.75 |
def add_widget(self):
"""
Adds the Component Widget to the engine.
:return: Method success.
:rtype: bool
"""
LOGGER.debug("> Adding '{0}' Component Widget.".format(self.__class__.__name__))
self.__preferences_manager.Others_Preferences_gridLayout.addWidget(self... | [
"def",
"add_widget",
"(",
"self",
")",
":",
"LOGGER",
".",
"debug",
"(",
"\"> Adding '{0}' Component Widget.\"",
".",
"format",
"(",
"self",
".",
"__class__",
".",
"__name__",
")",
")",
"self",
".",
"__preferences_manager",
".",
"Others_Preferences_gridLayout",
".... | 27.153846 | 26.692308 |
def __search_ca_path(self):
"""
Get CA Path to check the validity of the server host certificate on the client side
"""
if "X509_CERT_DIR" in os.environ:
self._ca_path = os.environ['X509_CERT_DIR']
elif os.path.exists('/etc/grid-security/certificates'):
s... | [
"def",
"__search_ca_path",
"(",
"self",
")",
":",
"if",
"\"X509_CERT_DIR\"",
"in",
"os",
".",
"environ",
":",
"self",
".",
"_ca_path",
"=",
"os",
".",
"environ",
"[",
"'X509_CERT_DIR'",
"]",
"elif",
"os",
".",
"path",
".",
"exists",
"(",
"'/etc/grid-securi... | 37 | 21.833333 |
def params_for_label(instruction):
"""Get the params and format them to add them to a label. None if there
are no params of if the params are numpy.ndarrays."""
if not hasattr(instruction.op, 'params'):
return None
if all([isinstance(param, ndarray) for param in instruction... | [
"def",
"params_for_label",
"(",
"instruction",
")",
":",
"if",
"not",
"hasattr",
"(",
"instruction",
".",
"op",
",",
"'params'",
")",
":",
"return",
"None",
"if",
"all",
"(",
"[",
"isinstance",
"(",
"param",
",",
"ndarray",
")",
"for",
"param",
"in",
"... | 36.375 | 16.1875 |
def remove_user(self, workspace, params={}, **options):
"""The user making this call must be an admin in the workspace.
Returns an empty data record.
Parameters
----------
workspace : {Id} The workspace or organization to invite the user to.
[data] : {Object} Data for t... | [
"def",
"remove_user",
"(",
"self",
",",
"workspace",
",",
"params",
"=",
"{",
"}",
",",
"*",
"*",
"options",
")",
":",
"path",
"=",
"\"/workspaces/%s/removeUser\"",
"%",
"(",
"workspace",
")",
"return",
"self",
".",
"client",
".",
"post",
"(",
"path",
... | 47.5 | 19.785714 |
def generate_pws_in_order(self, n, filter_func=None, N_max=1e6):
"""
Generates passwords in order between upto N_max
@N_max is the maximum size of the priority queue will be tolerated,
so if the size of the queue is bigger than 1.5 * N_max, it will shrink
the size to 0.75 * N_max... | [
"def",
"generate_pws_in_order",
"(",
"self",
",",
"n",
",",
"filter_func",
"=",
"None",
",",
"N_max",
"=",
"1e6",
")",
":",
"# assert alpha < beta, 'alpha={} must be less than beta={}'.format(alpha, beta)",
"states",
"=",
"[",
"(",
"-",
"1.0",
",",
"helper",
".",
... | 45.425532 | 15.680851 |
def worker_stop(obj, worker_ids):
""" Stop running workers.
\b
WORKER_IDS: The IDs of the worker that should be stopped or none to stop them all.
"""
if len(worker_ids) == 0:
msg = 'Would you like to stop all workers?'
else:
msg = '\n{}\n\n{}'.format('\n'.join(worker_ids),
... | [
"def",
"worker_stop",
"(",
"obj",
",",
"worker_ids",
")",
":",
"if",
"len",
"(",
"worker_ids",
")",
"==",
"0",
":",
"msg",
"=",
"'Would you like to stop all workers?'",
"else",
":",
"msg",
"=",
"'\\n{}\\n\\n{}'",
".",
"format",
"(",
"'\\n'",
".",
"join",
"... | 36.4 | 22 |
def addNotice(self, data):
"""
Add custom notice to front-end for this NodeServers
:param data: String of characters to add as a notification in the front-end.
"""
LOGGER.info('Sending addnotice to Polyglot: {}'.format(data))
message = { 'addnotice': data }
self.... | [
"def",
"addNotice",
"(",
"self",
",",
"data",
")",
":",
"LOGGER",
".",
"info",
"(",
"'Sending addnotice to Polyglot: {}'",
".",
"format",
"(",
"data",
")",
")",
"message",
"=",
"{",
"'addnotice'",
":",
"data",
"}",
"self",
".",
"send",
"(",
"message",
")... | 36.111111 | 17.888889 |
def backends(self, back=None):
'''
Return the backend list
'''
if not back:
back = self.opts['fileserver_backend']
else:
if not isinstance(back, list):
try:
back = back.split(',')
except AttributeError:
... | [
"def",
"backends",
"(",
"self",
",",
"back",
"=",
"None",
")",
":",
"if",
"not",
"back",
":",
"back",
"=",
"self",
".",
"opts",
"[",
"'fileserver_backend'",
"]",
"else",
":",
"if",
"not",
"isinstance",
"(",
"back",
",",
"list",
")",
":",
"try",
":"... | 37.163265 | 19.040816 |
def sentry_feature(app):
"""
Sentry feature
Adds basic integration with Sentry via the raven library
"""
# get keys
sentry_public_key = app.config.get('SENTRY_PUBLIC_KEY')
sentry_project_id = app.config.get('SENTRY_PROJECT_ID')
if not sentry_public_key or not sentry_project_id:
... | [
"def",
"sentry_feature",
"(",
"app",
")",
":",
"# get keys",
"sentry_public_key",
"=",
"app",
".",
"config",
".",
"get",
"(",
"'SENTRY_PUBLIC_KEY'",
")",
"sentry_project_id",
"=",
"app",
".",
"config",
".",
"get",
"(",
"'SENTRY_PROJECT_ID'",
")",
"if",
"not",
... | 28.222222 | 20.666667 |
def consume(self, args):
""" Consume the arguments we support. The args are modified inline.
The return value is the number of args eaten. """
consumable = args[:self.max_args]
self.consumed = len(consumable)
del args[:self.consumed]
return self.consumed | [
"def",
"consume",
"(",
"self",
",",
"args",
")",
":",
"consumable",
"=",
"args",
"[",
":",
"self",
".",
"max_args",
"]",
"self",
".",
"consumed",
"=",
"len",
"(",
"consumable",
")",
"del",
"args",
"[",
":",
"self",
".",
"consumed",
"]",
"return",
"... | 42.428571 | 5.428571 |
def from_hsv(cls, h, s, v):
"""Constructs a :class:`Colour` from an HSV tuple."""
rgb = colorsys.hsv_to_rgb(h, s, v)
return cls.from_rgb(*(int(x * 255) for x in rgb)) | [
"def",
"from_hsv",
"(",
"cls",
",",
"h",
",",
"s",
",",
"v",
")",
":",
"rgb",
"=",
"colorsys",
".",
"hsv_to_rgb",
"(",
"h",
",",
"s",
",",
"v",
")",
"return",
"cls",
".",
"from_rgb",
"(",
"*",
"(",
"int",
"(",
"x",
"*",
"255",
")",
"for",
"... | 46.75 | 8 |
def junos_copy_file(src, dst, **kwargs):
'''
.. versionadded:: 2019.2.0
Copies the file on the remote Junos device.
src
The source file path. This argument accepts the usual Salt URIs (e.g.,
``salt://``, ``http://``, ``https://``, ``s3://``, ``ftp://``, etc.).
dst
The dest... | [
"def",
"junos_copy_file",
"(",
"src",
",",
"dst",
",",
"*",
"*",
"kwargs",
")",
":",
"prep",
"=",
"_junos_prep_fun",
"(",
"napalm_device",
")",
"# pylint: disable=undefined-variable",
"if",
"not",
"prep",
"[",
"'result'",
"]",
":",
"return",
"prep",
"cached_sr... | 30.083333 | 28.166667 |
def hurst_rs(data, nvals=None, fit="RANSAC", debug_plot=False,
debug_data=False, plot_file=None, corrected=True, unbiased=True):
"""
Calculates the Hurst exponent by a standard rescaled range (R/S) approach.
Explanation of Hurst exponent:
The Hurst exponent is a measure for the "long-term memory... | [
"def",
"hurst_rs",
"(",
"data",
",",
"nvals",
"=",
"None",
",",
"fit",
"=",
"\"RANSAC\"",
",",
"debug_plot",
"=",
"False",
",",
"debug_data",
"=",
"False",
",",
"plot_file",
"=",
"None",
",",
"corrected",
"=",
"True",
",",
"unbiased",
"=",
"True",
")",... | 49.47644 | 27.183246 |
def auto_discretize(self, max_freq=50., wave_frac=0.2):
"""Subdivide the layers to capture strain variation.
Parameters
----------
max_freq: float
Maximum frequency of interest [Hz].
wave_frac: float
Fraction of wavelength required. Typically 1/3 to 1/5.
... | [
"def",
"auto_discretize",
"(",
"self",
",",
"max_freq",
"=",
"50.",
",",
"wave_frac",
"=",
"0.2",
")",
":",
"layers",
"=",
"[",
"]",
"for",
"l",
"in",
"self",
":",
"if",
"l",
".",
"soil_type",
".",
"is_nonlinear",
":",
"opt_thickness",
"=",
"l",
".",... | 33.962963 | 19.111111 |
def get_key(dotenv_path, key_to_get, verbose=False):
"""
Gets the value of a given key from the given .env
If the .env path given doesn't exist, fails
:param dotenv_path: path
:param key_to_get: key
:param verbose: verbosity flag, raise warning if path does not exist
:return: value of varia... | [
"def",
"get_key",
"(",
"dotenv_path",
",",
"key_to_get",
",",
"verbose",
"=",
"False",
")",
":",
"key_to_get",
"=",
"str",
"(",
"key_to_get",
")",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"dotenv_path",
")",
":",
"if",
"verbose",
":",
"warni... | 35.409091 | 16.045455 |
def get_settings(self):
"""
Returns current settings.
Only accessible if authenticated as the user.
"""
url = self._imgur._base_url + "/3/account/{0}/settings".format(self.name)
return self._imgur._send_request(url) | [
"def",
"get_settings",
"(",
"self",
")",
":",
"url",
"=",
"self",
".",
"_imgur",
".",
"_base_url",
"+",
"\"/3/account/{0}/settings\"",
".",
"format",
"(",
"self",
".",
"name",
")",
"return",
"self",
".",
"_imgur",
".",
"_send_request",
"(",
"url",
")"
] | 32.125 | 15.375 |
def get_current_term():
"""
Returns a uw_sws.models.Term object,
for the current term.
"""
url = "{}/current.json".format(term_res_url_prefix)
term = _json_to_term_model(get_resource(url))
# A term doesn't become "current" until 2 days before the start of
# classes. That's too late to ... | [
"def",
"get_current_term",
"(",
")",
":",
"url",
"=",
"\"{}/current.json\"",
".",
"format",
"(",
"term_res_url_prefix",
")",
"term",
"=",
"_json_to_term_model",
"(",
"get_resource",
"(",
"url",
")",
")",
"# A term doesn't become \"current\" until 2 days before the start o... | 34.2 | 18.2 |
def _process_genotype_features(self, limit=None):
"""
Here we process the genotype_features file, which lists genotypes
together with any intrinsic sequence alterations, their zygosity,
and affected gene.
Because we don't necessarily get allele pair (VSLC) ids
in a single... | [
"def",
"_process_genotype_features",
"(",
"self",
",",
"limit",
"=",
"None",
")",
":",
"raw",
"=",
"'/'",
".",
"join",
"(",
"(",
"self",
".",
"rawdir",
",",
"self",
".",
"files",
"[",
"'geno'",
"]",
"[",
"'file'",
"]",
")",
")",
"if",
"self",
".",
... | 42.169951 | 20.79064 |
def distance_drive(self, x, y, angle):
"""Call this from your :func:`PhysicsEngine.update_sim` function.
Will update the robot's position on the simulation field.
This moves the robot some relative distance and angle from
its current position.
... | [
"def",
"distance_drive",
"(",
"self",
",",
"x",
",",
"y",
",",
"angle",
")",
":",
"with",
"self",
".",
"_lock",
":",
"self",
".",
"vx",
"+=",
"x",
"self",
".",
"vy",
"+=",
"y",
"self",
".",
"angle",
"+=",
"angle",
"c",
"=",
"math",
".",
"cos",
... | 33.782609 | 16.73913 |
def zeq_magic(meas_file='measurements.txt', spec_file='',crd='s',input_dir_path='.', angle=0,
n_plots=5, save_plots=True, fmt="svg", interactive=False, specimen="",
samp_file='samples.txt', contribution=None,fignum=1):
"""
zeq_magic makes zijderveld and equal area plots for magic for... | [
"def",
"zeq_magic",
"(",
"meas_file",
"=",
"'measurements.txt'",
",",
"spec_file",
"=",
"''",
",",
"crd",
"=",
"'s'",
",",
"input_dir_path",
"=",
"'.'",
",",
"angle",
"=",
"0",
",",
"n_plots",
"=",
"5",
",",
"save_plots",
"=",
"True",
",",
"fmt",
"=",
... | 49.015385 | 22.96 |
def prefix_shared_name_attributes(meta_graph, absolute_import_scope):
"""In-place prefixes shared_name attributes of nodes."""
shared_name_attr = "shared_name"
for node in meta_graph.graph_def.node:
shared_name_value = node.attr.get(shared_name_attr, None)
if shared_name_value and shared_name_value.HasFie... | [
"def",
"prefix_shared_name_attributes",
"(",
"meta_graph",
",",
"absolute_import_scope",
")",
":",
"shared_name_attr",
"=",
"\"shared_name\"",
"for",
"node",
"in",
"meta_graph",
".",
"graph_def",
".",
"node",
":",
"shared_name_value",
"=",
"node",
".",
"attr",
".",
... | 51.5 | 14.9 |
def summary(self):
"""
m.summary() -- Return a text string one-line summary of motif and its metrics
"""
m = self
txt = "%-34s (Bits: %5.2f MAP: %7.2f D: %5.3f %3d) E: %7.3f"%(
m, m.totalbits, m.MAP, m.seeddist, m.seednum, nlog10(m.pvalue))
if m.binomial!... | [
"def",
"summary",
"(",
"self",
")",
":",
"m",
"=",
"self",
"txt",
"=",
"\"%-34s (Bits: %5.2f MAP: %7.2f D: %5.3f %3d) E: %7.3f\"",
"%",
"(",
"m",
",",
"m",
".",
"totalbits",
",",
"m",
".",
"MAP",
",",
"m",
".",
"seeddist",
",",
"m",
".",
"seednum",
... | 53.769231 | 25.230769 |
def on_preliminary_config_changed(self, config_m, prop_name, info):
"""Callback when a preliminary config value has been changed
Mainly collects information, delegates handling further to _handle_config_update
:param ConfigModel config_m: The config model that has been changed
:param s... | [
"def",
"on_preliminary_config_changed",
"(",
"self",
",",
"config_m",
",",
"prop_name",
",",
"info",
")",
":",
"self",
".",
"check_for_preliminary_config",
"(",
")",
"method_name",
"=",
"info",
"[",
"'method_name'",
"]",
"# __setitem__, __delitem__, clear, ...",
"if",... | 46.304348 | 22.608696 |
def set_flask_metadata(app, version, repository, description,
api_version="1.0", name=None, auth=None,
route=None):
"""
Sets metadata on the application to be returned via metadata routes.
Parameters
----------
app : :class:`flask.Flask` instance
... | [
"def",
"set_flask_metadata",
"(",
"app",
",",
"version",
",",
"repository",
",",
"description",
",",
"api_version",
"=",
"\"1.0\"",
",",
"name",
"=",
"None",
",",
"auth",
"=",
"None",
",",
"route",
"=",
"None",
")",
":",
"errstr",
"=",
"set_flask_metadata"... | 36.172414 | 20.54023 |
async def create_tunnel_connection(self, req):
"""Create a tunnel connection
"""
tunnel_address = req.tunnel_address
connection = await self.create_connection(tunnel_address)
response = connection.current_consumer()
for event in response.events().values():
eve... | [
"async",
"def",
"create_tunnel_connection",
"(",
"self",
",",
"req",
")",
":",
"tunnel_address",
"=",
"req",
".",
"tunnel_address",
"connection",
"=",
"await",
"self",
".",
"create_connection",
"(",
"tunnel_address",
")",
"response",
"=",
"connection",
".",
"cur... | 40.206897 | 12.551724 |
def delete_message(self, queue, message):
"""
Delete a message from a queue.
:type queue: A :class:`boto.sqs.queue.Queue` object
:param queue: The Queue from which messages are read.
:type message: A :class:`boto.sqs.message.Message` object
:param message: The M... | [
"def",
"delete_message",
"(",
"self",
",",
"queue",
",",
"message",
")",
":",
"params",
"=",
"{",
"'ReceiptHandle'",
":",
"message",
".",
"receipt_handle",
"}",
"return",
"self",
".",
"get_status",
"(",
"'DeleteMessage'",
",",
"params",
",",
"queue",
".",
... | 36.533333 | 17.2 |
def get_end_date(self, obj):
"""
Returns the end date for a model instance
"""
obj_date = getattr(obj, self.get_end_date_field())
try:
obj_date = obj_date.date()
except AttributeError:
# It's a date rather than datetime, so we use it as is
... | [
"def",
"get_end_date",
"(",
"self",
",",
"obj",
")",
":",
"obj_date",
"=",
"getattr",
"(",
"obj",
",",
"self",
".",
"get_end_date_field",
"(",
")",
")",
"try",
":",
"obj_date",
"=",
"obj_date",
".",
"date",
"(",
")",
"except",
"AttributeError",
":",
"#... | 31.090909 | 13.272727 |
def list(self, binding_type=values.unset, limit=None, page_size=None):
"""
Lists UserBindingInstance records from the API as a list.
Unlike stream(), this operation is eager and will load `limit` records into
memory before returning.
:param UserBindingInstance.BindingType bindin... | [
"def",
"list",
"(",
"self",
",",
"binding_type",
"=",
"values",
".",
"unset",
",",
"limit",
"=",
"None",
",",
"page_size",
"=",
"None",
")",
":",
"return",
"list",
"(",
"self",
".",
"stream",
"(",
"binding_type",
"=",
"binding_type",
",",
"limit",
"=",... | 64.944444 | 37.944444 |
def _all_get_or_create_table(self, where, tablename, description, expectedrows=None):
"""Creates a new table, or if the table already exists, returns it."""
where_node = self._hdf5file.get_node(where)
if not tablename in where_node:
if not expectedrows is None:
table... | [
"def",
"_all_get_or_create_table",
"(",
"self",
",",
"where",
",",
"tablename",
",",
"description",
",",
"expectedrows",
"=",
"None",
")",
":",
"where_node",
"=",
"self",
".",
"_hdf5file",
".",
"get_node",
"(",
"where",
")",
"if",
"not",
"tablename",
"in",
... | 53.833333 | 28.5 |
def convert_args(self, rem_path, args):
"""Splits the rest of a URL into its argument parts. The URL is assumed
to start with the dynamic request prefix already removed.
Parameters
----------
rem_path : string
The URL to parse. The URL must start with the dynamic ... | [
"def",
"convert_args",
"(",
"self",
",",
"rem_path",
",",
"args",
")",
":",
"fragment_split",
"=",
"rem_path",
".",
"split",
"(",
"'#'",
",",
"1",
")",
"query_split",
"=",
"fragment_split",
"[",
"0",
"]",
".",
"split",
"(",
"'?'",
",",
"1",
")",
"seg... | 38.0625 | 18.375 |
def get_best_candidate(self):
"""
Returns
----------
best_candidate : the best candidate hyper-parameters as defined by
"""
# TODO make this best mean response
self.incumbent = self.surrogate.Y.max()
# Objective function
def z(x):
# TO... | [
"def",
"get_best_candidate",
"(",
"self",
")",
":",
"# TODO make this best mean response",
"self",
".",
"incumbent",
"=",
"self",
".",
"surrogate",
".",
"Y",
".",
"max",
"(",
")",
"# Objective function",
"def",
"z",
"(",
"x",
")",
":",
"# TODO make spread of poi... | 35.457143 | 17.742857 |
def refreshContents( self ):
"""
Refreshes the contents tab with the latest selection from the browser.
"""
item = self.uiContentsTREE.currentItem()
if not isinstance(item, XdkEntryItem):
return
item.load()
url = item.url()
if url:... | [
"def",
"refreshContents",
"(",
"self",
")",
":",
"item",
"=",
"self",
".",
"uiContentsTREE",
".",
"currentItem",
"(",
")",
"if",
"not",
"isinstance",
"(",
"item",
",",
"XdkEntryItem",
")",
":",
"return",
"item",
".",
"load",
"(",
")",
"url",
"=",
"item... | 28.333333 | 15.666667 |
def is_ancestor_of(self, other, inclusive=False):
""" class or instance level method which returns True if self is
ancestor (closer to root) of other else False. Optional flag
`inclusive` on whether or not to treat self as ancestor of self.
For example see:
* :mod:`sqlalchemy_m... | [
"def",
"is_ancestor_of",
"(",
"self",
",",
"other",
",",
"inclusive",
"=",
"False",
")",
":",
"if",
"inclusive",
":",
"return",
"(",
"self",
".",
"tree_id",
"==",
"other",
".",
"tree_id",
")",
"&",
"(",
"self",
".",
"left",
"<=",
"other",
".",
"left"... | 41.625 | 15.8125 |
def list_images(self):
"""
Return the list of available images for this node type
:returns: Array of hash
"""
try:
return list_images(self._NODE_TYPE)
except OSError as e:
raise aiohttp.web.HTTPConflict(text="Can not list images {}".format(e)) | [
"def",
"list_images",
"(",
"self",
")",
":",
"try",
":",
"return",
"list_images",
"(",
"self",
".",
"_NODE_TYPE",
")",
"except",
"OSError",
"as",
"e",
":",
"raise",
"aiohttp",
".",
"web",
".",
"HTTPConflict",
"(",
"text",
"=",
"\"Can not list images {}\"",
... | 27.909091 | 19.909091 |
def _backup(self):
"""
Backup the database into its file.
"""
if self._authorization():
# We are authorized to work.
# We backup the current state of the datbase.
Dict(PyFunceble.INTERN["whois_db"]).to_json(self.whois_db_path) | [
"def",
"_backup",
"(",
"self",
")",
":",
"if",
"self",
".",
"_authorization",
"(",
")",
":",
"# We are authorized to work.",
"# We backup the current state of the datbase.",
"Dict",
"(",
"PyFunceble",
".",
"INTERN",
"[",
"\"whois_db\"",
"]",
")",
".",
"to_json",
"... | 28.7 | 16.3 |
def _accumulateFrequencyCounts(values, freqCounts=None):
"""
Accumulate a list of values 'values' into the frequency counts 'freqCounts',
and return the updated frequency counts
For example, if values contained the following: [1,1,3,5,1,3,5], and the initial
freqCounts was None, then the return value would b... | [
"def",
"_accumulateFrequencyCounts",
"(",
"values",
",",
"freqCounts",
"=",
"None",
")",
":",
"# How big does our freqCounts vector need to be?",
"values",
"=",
"numpy",
".",
"array",
"(",
"values",
")",
"numEntries",
"=",
"values",
".",
"max",
"(",
")",
"+",
"1... | 34.04878 | 21.560976 |
def wrap(self, func):
""" Wrap :func: to perform aggregation on :func: call.
Should be called with view instance methods.
"""
@six.wraps(func)
def wrapper(*args, **kwargs):
try:
return self.aggregate()
except KeyError:
retu... | [
"def",
"wrap",
"(",
"self",
",",
"func",
")",
":",
"@",
"six",
".",
"wraps",
"(",
"func",
")",
"def",
"wrapper",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"try",
":",
"return",
"self",
".",
"aggregate",
"(",
")",
"except",
"KeyError",
... | 29.666667 | 12.416667 |
def update_attribute(self, attr, value):
"""Set the value of a workspace attribute."""
update = [fapi._attr_up(attr, value)]
r = fapi.update_workspace_attributes(self.namespace, self.name,
update, self.api_url)
fapi._check_response_code(r, 200... | [
"def",
"update_attribute",
"(",
"self",
",",
"attr",
",",
"value",
")",
":",
"update",
"=",
"[",
"fapi",
".",
"_attr_up",
"(",
"attr",
",",
"value",
")",
"]",
"r",
"=",
"fapi",
".",
"update_workspace_attributes",
"(",
"self",
".",
"namespace",
",",
"se... | 52.666667 | 10.5 |
def mask_and_mean_loss(input_tensor, binary_tensor, axis=None):
"""
Mask a loss by using a tensor filled with 0 or 1 and average correctly.
:param input_tensor: A float tensor of shape [batch_size, ...] representing the loss/cross_entropy
:param binary_tensor: A float tensor of shape [batch_size, ...] ... | [
"def",
"mask_and_mean_loss",
"(",
"input_tensor",
",",
"binary_tensor",
",",
"axis",
"=",
"None",
")",
":",
"return",
"mean_on_masked",
"(",
"mask_loss",
"(",
"input_tensor",
",",
"binary_tensor",
")",
",",
"binary_tensor",
",",
"axis",
"=",
"axis",
")"
] | 62.545455 | 35.818182 |
def _setup_core(self):
'''
Set up the core minion attributes.
This is safe to call multiple times.
'''
if not self.ready:
# First call. Initialize.
self.functions, self.returners, self.function_errors, self.executors = self._load_modules()
self... | [
"def",
"_setup_core",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"ready",
":",
"# First call. Initialize.",
"self",
".",
"functions",
",",
"self",
".",
"returners",
",",
"self",
".",
"function_errors",
",",
"self",
".",
"executors",
"=",
"self",
".",... | 48.352941 | 20.588235 |
def check_events(self):
'''check for events, calling registered callbacks as needed'''
while self.event_count() > 0:
event = self.get_event()
for callback in self._callbacks:
callback(event) | [
"def",
"check_events",
"(",
"self",
")",
":",
"while",
"self",
".",
"event_count",
"(",
")",
">",
"0",
":",
"event",
"=",
"self",
".",
"get_event",
"(",
")",
"for",
"callback",
"in",
"self",
".",
"_callbacks",
":",
"callback",
"(",
"event",
")"
] | 40.166667 | 11.166667 |
def create_signed_entities_descriptor(entity_descriptors, security_context, valid_for=None):
"""
:param entity_descriptors: the entity descriptors to put in in an EntitiesDescriptor tag and sign
:param security_context: security context for the signature
:param valid_for: number of hours the metadata sh... | [
"def",
"create_signed_entities_descriptor",
"(",
"entity_descriptors",
",",
"security_context",
",",
"valid_for",
"=",
"None",
")",
":",
"entities_desc",
",",
"xmldoc",
"=",
"entities_descriptor",
"(",
"entity_descriptors",
",",
"valid_for",
"=",
"valid_for",
",",
"na... | 50.235294 | 27.411765 |
def rename(self, name):
"""Renames app to given name."""
r = self._h._http_resource(
method='PUT',
resource=('apps', self.name),
data={'app[name]': name}
)
return r.ok | [
"def",
"rename",
"(",
"self",
",",
"name",
")",
":",
"r",
"=",
"self",
".",
"_h",
".",
"_http_resource",
"(",
"method",
"=",
"'PUT'",
",",
"resource",
"=",
"(",
"'apps'",
",",
"self",
".",
"name",
")",
",",
"data",
"=",
"{",
"'app[name]'",
":",
"... | 25.333333 | 14.888889 |
def delete_branch(self, repo, branch, prefix):
"""
Deletes a branch.
:param repo: github.Repository
:param branch: string name of the branch to delete
"""
# make sure that the name of the branch begins with pyup.
assert branch.startswith(prefix)
obj = repo... | [
"def",
"delete_branch",
"(",
"self",
",",
"repo",
",",
"branch",
",",
"prefix",
")",
":",
"# make sure that the name of the branch begins with pyup.",
"assert",
"branch",
".",
"startswith",
"(",
"prefix",
")",
"obj",
"=",
"repo",
".",
"branches",
".",
"get",
"("... | 35.3 | 8.7 |
def xrefs(self, nid, bidirectional=False):
"""
Fetches xrefs for a node
Arguments
---------
nid : str
Node identifier for entity to be queried
bidirection : bool
If True, include nodes xreffed to nid
Return
------
list[str... | [
"def",
"xrefs",
"(",
"self",
",",
"nid",
",",
"bidirectional",
"=",
"False",
")",
":",
"if",
"self",
".",
"xref_graph",
"is",
"not",
"None",
":",
"xg",
"=",
"self",
".",
"xref_graph",
"if",
"nid",
"not",
"in",
"xg",
":",
"return",
"[",
"]",
"if",
... | 25.6 | 18.16 |
def remove_file(fpath, verbose=None, ignore_errors=True, dryrun=False,
quiet=QUIET):
""" Removes a file """
if verbose is None:
verbose = not quiet
if dryrun:
if verbose:
print('[util_path] Dryrem %r' % fpath)
return
else:
try:
os.r... | [
"def",
"remove_file",
"(",
"fpath",
",",
"verbose",
"=",
"None",
",",
"ignore_errors",
"=",
"True",
",",
"dryrun",
"=",
"False",
",",
"quiet",
"=",
"QUIET",
")",
":",
"if",
"verbose",
"is",
"None",
":",
"verbose",
"=",
"not",
"quiet",
"if",
"dryrun",
... | 31.380952 | 19.285714 |
def nsDefs(self):
"""Get the namespace of a node """
ret = libxml2mod.xmlNodeGetNsDefs(self._o)
if ret is None:return None
__tmp = xmlNs(_obj=ret)
return __tmp | [
"def",
"nsDefs",
"(",
"self",
")",
":",
"ret",
"=",
"libxml2mod",
".",
"xmlNodeGetNsDefs",
"(",
"self",
".",
"_o",
")",
"if",
"ret",
"is",
"None",
":",
"return",
"None",
"__tmp",
"=",
"xmlNs",
"(",
"_obj",
"=",
"ret",
")",
"return",
"__tmp"
] | 32.333333 | 11.333333 |
def iter_languages(self, number=-1, etag=None):
"""Iterate over the programming languages used in the repository.
:param int number: (optional), number of languages to return. Default:
-1 returns all used languages
:param str etag: (optional), ETag from a previous request to the sam... | [
"def",
"iter_languages",
"(",
"self",
",",
"number",
"=",
"-",
"1",
",",
"etag",
"=",
"None",
")",
":",
"url",
"=",
"self",
".",
"_build_url",
"(",
"'languages'",
",",
"base_url",
"=",
"self",
".",
"_api",
")",
"return",
"self",
".",
"_iter",
"(",
... | 46.090909 | 17.181818 |
def retrieve_public_key(user_repo):
"""Retrieve the public key from the Travis API.
The Travis API response is accessed as JSON so that Travis-Encrypt
can easily find the public key that is to be passed to cryptography's
load_pem_public_key function. Due to issues with some public keys being
return... | [
"def",
"retrieve_public_key",
"(",
"user_repo",
")",
":",
"url",
"=",
"'https://api.travis-ci.org/repos/{}/key'",
".",
"format",
"(",
"user_repo",
")",
"response",
"=",
"requests",
".",
"get",
"(",
"url",
")",
"try",
":",
"return",
"response",
".",
"json",
"("... | 38.15625 | 29.65625 |
def count_blank_positions(self):
"""
return a count of blank cells
"""
blanks = 0
for row_ndx in range(self.grid_height - 0):
for col_ndx in range(self.grid_width - 0):
if self.get_tile(row_ndx, col_ndx) == EMPTY:
blanks += 1
... | [
"def",
"count_blank_positions",
"(",
"self",
")",
":",
"blanks",
"=",
"0",
"for",
"row_ndx",
"in",
"range",
"(",
"self",
".",
"grid_height",
"-",
"0",
")",
":",
"for",
"col_ndx",
"in",
"range",
"(",
"self",
".",
"grid_width",
"-",
"0",
")",
":",
"if"... | 32.6 | 10.6 |
def pexpireat(self, name, when):
"""
Set an expire flag on key ``name``. ``when`` can be represented
as an integer representing unix time in milliseconds (unix time * 1000)
or a Python datetime object.
"""
if isinstance(when, datetime.datetime):
ms = int(when.... | [
"def",
"pexpireat",
"(",
"self",
",",
"name",
",",
"when",
")",
":",
"if",
"isinstance",
"(",
"when",
",",
"datetime",
".",
"datetime",
")",
":",
"ms",
"=",
"int",
"(",
"when",
".",
"microsecond",
"/",
"1000",
")",
"when",
"=",
"int",
"(",
"mod_tim... | 46.1 | 14.3 |
def set_imu_config(self, compass_enabled, gyro_enabled, accel_enabled):
"""
Enables and disables the gyroscope, accelerometer and/or magnetometer
input to the orientation functions
"""
# If the consuming code always calls this just before reading the IMU
# the IMU consis... | [
"def",
"set_imu_config",
"(",
"self",
",",
"compass_enabled",
",",
"gyro_enabled",
",",
"accel_enabled",
")",
":",
"# If the consuming code always calls this just before reading the IMU",
"# the IMU consistently fails to read. So prevent unnecessary calls to",
"# IMU config functions usi... | 41.392857 | 20.607143 |
def edits1(word):
"All edits that are one edit away from `word`."
letters = 'qwertyuiopasdfghjklzxcvbnm'
splits = [(word[:i], word[i:]) for i in range(len(word) + 1)]
print('splits = ', splits)
deletes = [L + R[1:] for L, R in splits if R]
print('deletes = ', deletes)
transposes = [L + R[1] ... | [
"def",
"edits1",
"(",
"word",
")",
":",
"letters",
"=",
"'qwertyuiopasdfghjklzxcvbnm'",
"splits",
"=",
"[",
"(",
"word",
"[",
":",
"i",
"]",
",",
"word",
"[",
"i",
":",
"]",
")",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"word",
")",
"+",
"1",
... | 47.6875 | 14.8125 |
def get_network_versions(self, name: str) -> Set[str]:
"""Return all of the versions of a network with the given name."""
return {
version
for version, in self.session.query(Network.version).filter(Network.name == name).all()
} | [
"def",
"get_network_versions",
"(",
"self",
",",
"name",
":",
"str",
")",
"->",
"Set",
"[",
"str",
"]",
":",
"return",
"{",
"version",
"for",
"version",
",",
"in",
"self",
".",
"session",
".",
"query",
"(",
"Network",
".",
"version",
")",
".",
"filte... | 45 | 24.666667 |
def _find_parent_directory(directory, filename):
"""Find a directory in parent tree with a specific filename
:param directory: directory name to find
:param filename: filename to find
:returns: absolute directory path
"""
parent_directory = directory
absolute_dir... | [
"def",
"_find_parent_directory",
"(",
"directory",
",",
"filename",
")",
":",
"parent_directory",
"=",
"directory",
"absolute_directory",
"=",
"'.'",
"while",
"absolute_directory",
"!=",
"os",
".",
"path",
".",
"abspath",
"(",
"parent_directory",
")",
":",
"absolu... | 48.526316 | 16.526316 |
def _find_value(ret_dict, key, path=None):
'''
PRIVATE METHOD
Traverses a dictionary of dictionaries/lists to find key
and return the value stored.
TODO:// this method doesn't really work very well, and it's not really
very useful in its current state. The purpose for this method is
... | [
"def",
"_find_value",
"(",
"ret_dict",
",",
"key",
",",
"path",
"=",
"None",
")",
":",
"if",
"path",
"is",
"None",
":",
"path",
"=",
"key",
"else",
":",
"path",
"=",
"\"{0}:{1}\"",
".",
"format",
"(",
"path",
",",
"key",
")",
"ret",
"=",
"[",
"]"... | 33.228571 | 19.571429 |
def get_list_cluster_admins(self):
"""Get list of cluster admins."""
response = self.request(
url="cluster_admins",
method='GET',
expected_response_code=200
)
return response.json() | [
"def",
"get_list_cluster_admins",
"(",
"self",
")",
":",
"response",
"=",
"self",
".",
"request",
"(",
"url",
"=",
"\"cluster_admins\"",
",",
"method",
"=",
"'GET'",
",",
"expected_response_code",
"=",
"200",
")",
"return",
"response",
".",
"json",
"(",
")"
... | 26.888889 | 13.222222 |
def _build_queries_and_headers(self):
"""
Build a list of query information and headers (pseudo-folders) for consumption by the template.
Strategy: Look for queries with titles of the form "something - else" (eg. with a ' - ' in the middle)
and split on the ' - ', treating the... | [
"def",
"_build_queries_and_headers",
"(",
"self",
")",
":",
"dict_list",
"=",
"[",
"]",
"rendered_headers",
"=",
"[",
"]",
"pattern",
"=",
"re",
".",
"compile",
"(",
"'[\\W_]+'",
")",
"headers",
"=",
"Counter",
"(",
"[",
"q",
".",
"title",
".",
"split",
... | 54.822222 | 32.822222 |
def delete_snapshot_range(self, start_id, end_id):
"""Starts deleting the specified snapshot range. This is limited to
linear snapshot lists, which means there may not be any other child
snapshots other than the direct sequence between the start and end
snapshot. If the start and end sna... | [
"def",
"delete_snapshot_range",
"(",
"self",
",",
"start_id",
",",
"end_id",
")",
":",
"if",
"not",
"isinstance",
"(",
"start_id",
",",
"basestring",
")",
":",
"raise",
"TypeError",
"(",
"\"start_id can only be an instance of type basestring\"",
")",
"if",
"not",
... | 45.976744 | 21.27907 |
def mutant(fn):
"""
Convenience decorator to isolate mutation to within the decorated function (with respect
to the input arguments).
All arguments to the decorated function will be frozen so that they are guaranteed not to change.
The return value is also frozen.
"""
@wraps(fn)
def inn... | [
"def",
"mutant",
"(",
"fn",
")",
":",
"@",
"wraps",
"(",
"fn",
")",
"def",
"inner_f",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"freeze",
"(",
"fn",
"(",
"*",
"[",
"freeze",
"(",
"e",
")",
"for",
"e",
"in",
"args",
"]",
... | 34.846154 | 27 |
def center_widget_on_screen(widget, screen=None):
"""
Centers given Widget on the screen.
:param widget: Current Widget.
:type widget: QWidget
:param screen: Screen used for centering.
:type screen: int
:return: Definition success.
:rtype: bool
"""
screen = screen and screen or... | [
"def",
"center_widget_on_screen",
"(",
"widget",
",",
"screen",
"=",
"None",
")",
":",
"screen",
"=",
"screen",
"and",
"screen",
"or",
"QApplication",
".",
"desktop",
"(",
")",
".",
"primaryScreen",
"(",
")",
"desktop_width",
"=",
"QApplication",
".",
"deskt... | 37 | 21.823529 |
def libvlc_media_player_set_agl(p_mi, drawable):
'''Set the agl handler where the media player should render its video output.
@param p_mi: the Media Player.
@param drawable: the agl handler.
'''
f = _Cfunctions.get('libvlc_media_player_set_agl', None) or \
_Cfunction('libvlc_media_player_se... | [
"def",
"libvlc_media_player_set_agl",
"(",
"p_mi",
",",
"drawable",
")",
":",
"f",
"=",
"_Cfunctions",
".",
"get",
"(",
"'libvlc_media_player_set_agl'",
",",
"None",
")",
"or",
"_Cfunction",
"(",
"'libvlc_media_player_set_agl'",
",",
"(",
"(",
"1",
",",
")",
"... | 47.222222 | 19.222222 |
def _set_exception(self):
"""Called by a Job object to tell that an exception occured
during the processing of the function. The object will become
ready but not successful. The collector's notify_ready()
method will be called, but NOT the callback method"""
assert not self.ready... | [
"def",
"_set_exception",
"(",
"self",
")",
":",
"assert",
"not",
"self",
".",
"ready",
"(",
")",
"self",
".",
"_data",
"=",
"sys",
".",
"exc_info",
"(",
")",
"self",
".",
"_success",
"=",
"False",
"self",
".",
"_event",
".",
"set",
"(",
")",
"if",
... | 44.636364 | 10.454545 |
def getReference(self, id_):
"""
Returns the Reference with the specified ID or raises a
ReferenceNotFoundException if it does not exist.
"""
if id_ not in self._referenceIdMap:
raise exceptions.ReferenceNotFoundException(id_)
return self._referenceIdMap[id_] | [
"def",
"getReference",
"(",
"self",
",",
"id_",
")",
":",
"if",
"id_",
"not",
"in",
"self",
".",
"_referenceIdMap",
":",
"raise",
"exceptions",
".",
"ReferenceNotFoundException",
"(",
"id_",
")",
"return",
"self",
".",
"_referenceIdMap",
"[",
"id_",
"]"
] | 39 | 9.25 |
def available(self):
""" True if any of the supported modules from ``packages`` is available for use.
:return: True if any modules from ``packages`` exist
:rtype: bool
"""
for module_name in self.packages:
if importlib.util.find_spec(module_name):
re... | [
"def",
"available",
"(",
"self",
")",
":",
"for",
"module_name",
"in",
"self",
".",
"packages",
":",
"if",
"importlib",
".",
"util",
".",
"find_spec",
"(",
"module_name",
")",
":",
"return",
"True",
"return",
"False"
] | 30.909091 | 17 |
def _search_archive(pattern, archive, verbosity=0, interactive=True):
"""Search for given pattern in an archive."""
grep = util.find_program("grep")
if not grep:
msg = "The grep(1) program is required for searching archive contents, please install it."
raise util.PatoolError(msg)
tmpdir ... | [
"def",
"_search_archive",
"(",
"pattern",
",",
"archive",
",",
"verbosity",
"=",
"0",
",",
"interactive",
"=",
"True",
")",
":",
"grep",
"=",
"util",
".",
"find_program",
"(",
"\"grep\"",
")",
"if",
"not",
"grep",
":",
"msg",
"=",
"\"The grep(1) program is... | 48 | 25.083333 |
def _validate_search_query(self, returning_query):
"""
Checks to see that the query will not exceed the max query depth
:param returning_query: The PIF system or Dataset query to execute.
:type returning_query: :class:`PifSystemReturningQuery` or :class: `DatasetReturningQuery`
... | [
"def",
"_validate_search_query",
"(",
"self",
",",
"returning_query",
")",
":",
"start_index",
"=",
"returning_query",
".",
"from_index",
"or",
"0",
"size",
"=",
"returning_query",
".",
"size",
"or",
"0",
"if",
"start_index",
"<",
"0",
":",
"raise",
"Citrinati... | 50.65 | 29.15 |
def scrape_musicbed_url(url, login, password, num_tracks=sys.maxsize, folders=False, custom_path=''):
"""
Scrapes provided MusicBed url.
Uses requests' Session object in order to store cookies.
Requires login and password information.
If provided url is of pattern 'https://www.musicbed.com/artists/<... | [
"def",
"scrape_musicbed_url",
"(",
"url",
",",
"login",
",",
"password",
",",
"num_tracks",
"=",
"sys",
".",
"maxsize",
",",
"folders",
"=",
"False",
",",
"custom_path",
"=",
"''",
")",
":",
"session",
"=",
"requests",
".",
"Session",
"(",
")",
"response... | 49.606299 | 30 |
def save_notebook(self):
""" Saves the current notebook by
injecting JavaScript to save to .ipynb file.
"""
try:
from IPython.display import display, Javascript
except ImportError:
log.warning("Could not import IPython Display Function")
print(... | [
"def",
"save_notebook",
"(",
"self",
")",
":",
"try",
":",
"from",
"IPython",
".",
"display",
"import",
"display",
",",
"Javascript",
"except",
"ImportError",
":",
"log",
".",
"warning",
"(",
"\"Could not import IPython Display Function\"",
")",
"print",
"(",
"\... | 43.117647 | 20.235294 |
def update_shortlink(self, shortlink_id, callback_uri=None,
description=None):
"""Update existing shortlink registration
Arguments:
shortlink_id:
Shortlink id assigned by mCASH
"""
arguments = {'callback_uri': callback_uri,
... | [
"def",
"update_shortlink",
"(",
"self",
",",
"shortlink_id",
",",
"callback_uri",
"=",
"None",
",",
"description",
"=",
"None",
")",
":",
"arguments",
"=",
"{",
"'callback_uri'",
":",
"callback_uri",
",",
"'description'",
":",
"description",
"}",
"return",
"se... | 39.230769 | 13.692308 |
def timed_cache(**timed_cache_kwargs):
"""LRU cache decorator with timeout.
Parameters
----------
days: int
seconds: int
microseconds: int
milliseconds: int
minutes: int
hours: int
weeks: int
maxsise: int [default: 128]
typed: bool [default: False]
"""
def _wrap... | [
"def",
"timed_cache",
"(",
"*",
"*",
"timed_cache_kwargs",
")",
":",
"def",
"_wrapper",
"(",
"f",
")",
":",
"maxsize",
"=",
"timed_cache_kwargs",
".",
"pop",
"(",
"'maxsize'",
",",
"128",
")",
"typed",
"=",
"timed_cache_kwargs",
".",
"pop",
"(",
"'typed'",... | 29.173913 | 19.108696 |
def fixchars(self, text):
"""Find and replace problematic characters."""
keys = ''.join(Config.CHARFIXES.keys())
values = ''.join(Config.CHARFIXES.values())
fixed = text.translate(str.maketrans(keys, values))
if fixed != text:
self.modified = True
return fixed | [
"def",
"fixchars",
"(",
"self",
",",
"text",
")",
":",
"keys",
"=",
"''",
".",
"join",
"(",
"Config",
".",
"CHARFIXES",
".",
"keys",
"(",
")",
")",
"values",
"=",
"''",
".",
"join",
"(",
"Config",
".",
"CHARFIXES",
".",
"values",
"(",
")",
")",
... | 39.125 | 11.875 |
def task_failed(sender=None, **kwargs):
"""
Update the status record accordingly when a :py:class:`UserTaskMixin` fails.
"""
if isinstance(sender, UserTaskMixin):
exception = kwargs['exception']
if not isinstance(exception, TaskCanceledException):
# Don't include traceback, s... | [
"def",
"task_failed",
"(",
"sender",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"isinstance",
"(",
"sender",
",",
"UserTaskMixin",
")",
":",
"exception",
"=",
"kwargs",
"[",
"'exception'",
"]",
"if",
"not",
"isinstance",
"(",
"exception",
",",... | 47.6 | 14.6 |
def catalog(self):
"""Primary registered catalog for the wrapped portal type
"""
if self._catalog is None:
logger.debug("SuperModel::catalog: *Fetch catalog*")
self._catalog = self.get_catalog_for(self.brain)
return self._catalog | [
"def",
"catalog",
"(",
"self",
")",
":",
"if",
"self",
".",
"_catalog",
"is",
"None",
":",
"logger",
".",
"debug",
"(",
"\"SuperModel::catalog: *Fetch catalog*\"",
")",
"self",
".",
"_catalog",
"=",
"self",
".",
"get_catalog_for",
"(",
"self",
".",
"brain",
... | 39.857143 | 12.142857 |
def resize_preview(self, dw, dh):
"Resizes preview that is currently dragged"
# identify preview
if self._objects_moving:
id_ = self._objects_moving[0]
tags = self.canvas.gettags(id_)
for tag in tags:
if tag.startswith('preview_'):
... | [
"def",
"resize_preview",
"(",
"self",
",",
"dw",
",",
"dh",
")",
":",
"# identify preview",
"if",
"self",
".",
"_objects_moving",
":",
"id_",
"=",
"self",
".",
"_objects_moving",
"[",
"0",
"]",
"tags",
"=",
"self",
".",
"canvas",
".",
"gettags",
"(",
"... | 36.133333 | 10.266667 |
def show(*actors, **options
# at=None,
# shape=(1, 1),
# N=None,
# pos=(0, 0),
# size="auto",
# screensize="auto",
# title="",
# bg="blackboard",
# bg2=None,
# axes=4,
# infinity=False,
# verbose=True,
# interactive=None,
# offscreen=False,
# resetcam=True,
# zoom=None,
#... | [
"def",
"show",
"(",
"*",
"actors",
",",
"*",
"*",
"options",
"# at=None,",
"# shape=(1, 1),",
"# N=None,",
"# pos=(0, 0),",
"# size=\"auto\",",
"# screensize=\"auto\",",
"# title=\"\",",
"# bg=\"blackboard\",",
"# bg2=None,",
"# axes=4,",
"# inf... | 30.475309 | 17.858025 |
def last(self):
"""
Returns the last object matched or None if there is no
matching object.
::
>>> iterator = Host.objects.iterator()
>>> c = iterator.filter('kali')
>>> if c.exists():
>>> print(c.last())
Hos... | [
"def",
"last",
"(",
"self",
")",
":",
"if",
"len",
"(",
"self",
")",
":",
"self",
".",
"_params",
".",
"update",
"(",
"limit",
"=",
"1",
")",
"if",
"'filter'",
"not",
"in",
"self",
".",
"_params",
":",
"return",
"list",
"(",
"self",
")",
"[",
"... | 30.272727 | 11.454545 |
def uint8sc(im):
"""Scale the image to uint8
Parameters:
-----------
im: 2d array
The image
Returns:
--------
im: 2d array (dtype uint8)
The scaled image to uint8
"""
im = np.asarray(im)
immin = im.min()
immax = im.max()
imrange = immax - immin
retur... | [
"def",
"uint8sc",
"(",
"im",
")",
":",
"im",
"=",
"np",
".",
"asarray",
"(",
"im",
")",
"immin",
"=",
"im",
".",
"min",
"(",
")",
"immax",
"=",
"im",
".",
"max",
"(",
")",
"imrange",
"=",
"immax",
"-",
"immin",
"return",
"cv2",
".",
"convertSca... | 19.833333 | 20.388889 |
def modify_job(self, name, schedule, persist=True):
'''
Modify a job in the scheduler. Ignores jobs from pillar
'''
# ensure job exists, then replace it
if name in self.opts['schedule']:
self.delete_job(name, persist)
elif name in self._get_schedule(include_op... | [
"def",
"modify_job",
"(",
"self",
",",
"name",
",",
"schedule",
",",
"persist",
"=",
"True",
")",
":",
"# ensure job exists, then replace it",
"if",
"name",
"in",
"self",
".",
"opts",
"[",
"'schedule'",
"]",
":",
"self",
".",
"delete_job",
"(",
"name",
","... | 33.733333 | 19.733333 |
def rn(op, rc=None, r=None):
# pylint: disable=redefined-outer-name, invalid-name
"""
This function is a wrapper for
:meth:`~pywbem.WBEMConnection.ReferenceNames`.
Instance-level use: Retrieve the instance paths of the association
instances referencing a source instance.
Class-level use: R... | [
"def",
"rn",
"(",
"op",
",",
"rc",
"=",
"None",
",",
"r",
"=",
"None",
")",
":",
"# pylint: disable=redefined-outer-name, invalid-name",
"return",
"CONN",
".",
"ReferenceNames",
"(",
"op",
",",
"ResultClass",
"=",
"rc",
",",
"Role",
"=",
"r",
")"
] | 35.114754 | 24 |
def get_property(self):
"""Establishes access of Property values"""
scope = self
def fget(self):
"""Call the HasProperties _get method"""
return self._get(scope.name)
def fset(self, value):
"""Validate value and call the HasProperties _set method"""... | [
"def",
"get_property",
"(",
"self",
")",
":",
"scope",
"=",
"self",
"def",
"fget",
"(",
"self",
")",
":",
"\"\"\"Call the HasProperties _get method\"\"\"",
"return",
"self",
".",
"_get",
"(",
"scope",
".",
"name",
")",
"def",
"fset",
"(",
"self",
",",
"val... | 31.9 | 16.7 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.