text stringlengths 89 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 630 |
|---|---|---|---|
def shutdown(opts):
'''
For this proxy shutdown is a no-op
'''
log.debug('dummy proxy shutdown() called...')
DETAILS = _load_state()
if 'filename' in DETAILS:
os.unlink(DETAILS['filename']) | [
"def",
"shutdown",
"(",
"opts",
")",
":",
"log",
".",
"debug",
"(",
"'dummy proxy shutdown() called...'",
")",
"DETAILS",
"=",
"_load_state",
"(",
")",
"if",
"'filename'",
"in",
"DETAILS",
":",
"os",
".",
"unlink",
"(",
"DETAILS",
"[",
"'filename'",
"]",
"... | 26.75 | 15.5 |
def parse_services(config, services):
"""Parse configuration to return number of enabled service checks.
Arguments:
config (obj): A configparser object with the configuration of
anycast-healthchecker.
services (list): A list of section names which holds configuration
for each se... | [
"def",
"parse_services",
"(",
"config",
",",
"services",
")",
":",
"enabled",
"=",
"0",
"for",
"service",
"in",
"services",
":",
"check_disabled",
"=",
"config",
".",
"getboolean",
"(",
"service",
",",
"'check_disabled'",
")",
"if",
"not",
"check_disabled",
... | 28.8 | 21.15 |
def markdown_to_reST(text):
'''This is not a general purpose converter. Only converts this readme'''
# Convert parameters to italics and prepend a newline
text = re.sub(pattern=r"\n (\w+) - (.+)\n",
repl=r"\n\n *\g<1>* - \g<2>\n",
string=text)
# Parse [ht... | [
"def",
"markdown_to_reST",
"(",
"text",
")",
":",
"# Convert parameters to italics and prepend a newline",
"text",
"=",
"re",
".",
"sub",
"(",
"pattern",
"=",
"r\"\\n (\\w+) - (.+)\\n\"",
",",
"repl",
"=",
"r\"\\n\\n *\\g<1>* - \\g<2>\\n\"",
",",
"string",
"="... | 37 | 15.705882 |
def get_batched_changesets(self, changesets_request_data):
"""GetBatchedChangesets.
Returns changesets for a given list of changeset Ids.
:param :class:`<TfvcChangesetsRequestData> <azure.devops.v5_0.tfvc.models.TfvcChangesetsRequestData>` changesets_request_data: List of changeset IDs.
... | [
"def",
"get_batched_changesets",
"(",
"self",
",",
"changesets_request_data",
")",
":",
"content",
"=",
"self",
".",
"_serialize",
".",
"body",
"(",
"changesets_request_data",
",",
"'TfvcChangesetsRequestData'",
")",
"response",
"=",
"self",
".",
"_send",
"(",
"ht... | 62.833333 | 26.916667 |
def _node_add_with_peer_leaflist(self, child_self, child_other):
'''_node_add_with_peer_leaflist
Low-level api: Apply delta child_other to child_self when child_self is
the peer of child_other. Element child_self and child_other are
leaf-list nodes. Element child_self will be modified d... | [
"def",
"_node_add_with_peer_leaflist",
"(",
"self",
",",
"child_self",
",",
"child_other",
")",
":",
"parent_self",
"=",
"child_self",
".",
"getparent",
"(",
")",
"s_node",
"=",
"self",
".",
"device",
".",
"get_schema_node",
"(",
"child_self",
")",
"if",
"chil... | 49.452381 | 21.166667 |
def path_tails(self, rr_id: str) -> str:
"""
Return path to tails file for input revocation registry identifier.
:param rr_id: revocation registry identifier of interest
:return: path to tails file for input revocation registry identifier
"""
return Tails.linked(self._d... | [
"def",
"path_tails",
"(",
"self",
",",
"rr_id",
":",
"str",
")",
"->",
"str",
":",
"return",
"Tails",
".",
"linked",
"(",
"self",
".",
"_dir_tails",
",",
"rr_id",
")"
] | 36.444444 | 20.666667 |
def setup_logger(debug, color):
"""Configure the logger."""
if debug:
log_level = logging.DEBUG
else:
log_level = logging.INFO
logger = logging.getLogger('exifread')
stream = Handler(log_level, debug, color)
logger.addHandler(stream)
logger.setLevel(log_level) | [
"def",
"setup_logger",
"(",
"debug",
",",
"color",
")",
":",
"if",
"debug",
":",
"log_level",
"=",
"logging",
".",
"DEBUG",
"else",
":",
"log_level",
"=",
"logging",
".",
"INFO",
"logger",
"=",
"logging",
".",
"getLogger",
"(",
"'exifread'",
")",
"stream... | 26.818182 | 13.636364 |
def plot_melodic_components(melodic_dir, in_file, tr=None,
out_file='melodic_reportlet.svg',
compress='auto', report_mask=None,
noise_components_file=None):
"""
Plots the spatiotemporal components extracted by FSL MELODIC
fr... | [
"def",
"plot_melodic_components",
"(",
"melodic_dir",
",",
"in_file",
",",
"tr",
"=",
"None",
",",
"out_file",
"=",
"'melodic_reportlet.svg'",
",",
"compress",
"=",
"'auto'",
",",
"report_mask",
"=",
"None",
",",
"noise_components_file",
"=",
"None",
")",
":",
... | 39.514851 | 18.287129 |
def update_configuration(configuration):
"""
Set all configuration specified in :attr:`REQUIRED_SETTINGS`.
Args:
configuration (str): Configuration file content.
Returns:
str: Updated configuration.
"""
for key, val in REQUIRED_SETTINGS.items():
if val in ["$username", ... | [
"def",
"update_configuration",
"(",
"configuration",
")",
":",
"for",
"key",
",",
"val",
"in",
"REQUIRED_SETTINGS",
".",
"items",
"(",
")",
":",
"if",
"val",
"in",
"[",
"\"$username\"",
",",
"\"$groupname\"",
"]",
":",
"val",
"=",
"get_username",
"(",
")",... | 26.647059 | 19.705882 |
def inspect(orm_class, attribute_name):
"""
:param attribute_name: name of the mapped attribute to inspect.
:returns: list of 2-tuples containing information about the inspected
attribute (first element: mapped entity attribute kind; second
attribute: mapped entity attribute)... | [
"def",
"inspect",
"(",
"orm_class",
",",
"attribute_name",
")",
":",
"key",
"=",
"(",
"orm_class",
",",
"attribute_name",
")",
"elems",
"=",
"OrmAttributeInspector",
".",
"__cache",
".",
"get",
"(",
"key",
")",
"if",
"elems",
"is",
"None",
":",
"elems",
... | 44.307692 | 14.307692 |
def simple_paths_by_address(self, start_address, end_address):
"""Return a list of paths between start and end functions.
"""
cfg_start = self.find_function_by_address(start_address)
cfg_end = self.find_function_by_address(end_address)
if not cfg_start or not cfg_end:
... | [
"def",
"simple_paths_by_address",
"(",
"self",
",",
"start_address",
",",
"end_address",
")",
":",
"cfg_start",
"=",
"self",
".",
"find_function_by_address",
"(",
"start_address",
")",
"cfg_end",
"=",
"self",
".",
"find_function_by_address",
"(",
"end_address",
")",... | 41.733333 | 23.266667 |
def set_limits(self, low=None, high=None):
"""
Adjusts the limits on the rows retrieved. We use low/high to set these,
as it makes it more Pythonic to read and write. When the API query is
created, they are converted to the appropriate offset and limit values.
Any limits passed ... | [
"def",
"set_limits",
"(",
"self",
",",
"low",
"=",
"None",
",",
"high",
"=",
"None",
")",
":",
"if",
"high",
"is",
"not",
"None",
":",
"if",
"self",
".",
"high_mark",
"is",
"not",
"None",
":",
"self",
".",
"high_mark",
"=",
"min",
"(",
"self",
".... | 45.65 | 19.65 |
async def add_unknown_id(self, unknown_id, timeout=OTGW_DEFAULT_TIMEOUT):
"""
Inform the gateway that the boiler doesn't support the
specified Data-ID, even if the boiler doesn't indicate that
by returning an Unknown-DataId response. Using this command
allows the gateway to send ... | [
"async",
"def",
"add_unknown_id",
"(",
"self",
",",
"unknown_id",
",",
"timeout",
"=",
"OTGW_DEFAULT_TIMEOUT",
")",
":",
"cmd",
"=",
"OTGW_CMD_UNKNOWN_ID",
"unknown_id",
"=",
"int",
"(",
"unknown_id",
")",
"if",
"unknown_id",
"<",
"1",
"or",
"unknown_id",
">",... | 39.777778 | 16.777778 |
def greenhall_table2(alpha, d):
""" Table 2 from Greenhall 2004 """
row_idx = int(-alpha+2) # map 2-> row0 and -4-> row6
assert(row_idx in [0, 1, 2, 3, 4, 5])
col_idx = int(d-1)
table2 = [[(3.0/2.0, 1.0/2.0), (35.0/18.0, 1.0), (231.0/100.0, 3.0/2.0)], # alpha=+2
[(78.6, 25.2), (790.0, ... | [
"def",
"greenhall_table2",
"(",
"alpha",
",",
"d",
")",
":",
"row_idx",
"=",
"int",
"(",
"-",
"alpha",
"+",
"2",
")",
"# map 2-> row0 and -4-> row6",
"assert",
"(",
"row_idx",
"in",
"[",
"0",
",",
"1",
",",
"2",
",",
"3",
",",
"4",
",",
"5",
"]",
... | 50.866667 | 18.666667 |
def text_pixels(self, text, clear_screen=True, x=0, y=0, text_color='black', font=None):
"""
Display `text` starting at pixel (x, y).
The EV3 display is 178x128 pixels
- (0, 0) would be the top left corner of the display
- (89, 64) would be right in the middle of the display
... | [
"def",
"text_pixels",
"(",
"self",
",",
"text",
",",
"clear_screen",
"=",
"True",
",",
"x",
"=",
"0",
",",
"y",
"=",
"0",
",",
"text_color",
"=",
"'black'",
",",
"font",
"=",
"None",
")",
":",
"if",
"clear_screen",
":",
"self",
".",
"clear",
"(",
... | 41.242424 | 26.939394 |
def streamWrite(self, size):
""" Send or receive a chunk of data.
:arg size: Amount of data. 0 indicates EOT.
"""
size = int(size)
if size == 0:
self._close()
return
self._sendResult(dict(message="writing...", stream=True, size=size))
d... | [
"def",
"streamWrite",
"(",
"self",
",",
"size",
")",
":",
"size",
"=",
"int",
"(",
"size",
")",
"if",
"size",
"==",
"0",
":",
"self",
".",
"_close",
"(",
")",
"return",
"self",
".",
"_sendResult",
"(",
"dict",
"(",
"message",
"=",
"\"writing...\"",
... | 28.153846 | 17.461538 |
def memory(self):
"""
The maximum number of bytes of memory the job will require to run.
"""
if self._memory is not None:
return self._memory
elif self._config is not None:
return self._config.defaultMemory
else:
raise AttributeError("D... | [
"def",
"memory",
"(",
"self",
")",
":",
"if",
"self",
".",
"_memory",
"is",
"not",
"None",
":",
"return",
"self",
".",
"_memory",
"elif",
"self",
".",
"_config",
"is",
"not",
"None",
":",
"return",
"self",
".",
"_config",
".",
"defaultMemory",
"else",
... | 35.9 | 14.7 |
def create_project(self, orch_id, org_name, part_name, dci_id, desc=None):
"""Create project on the DCNM.
:param orch_id: orchestrator ID
:param org_name: name of organization.
:param part_name: name of partition.
:param dci_id: Data Center interconnect id.
:param desc: ... | [
"def",
"create_project",
"(",
"self",
",",
"orch_id",
",",
"org_name",
",",
"part_name",
",",
"dci_id",
",",
"desc",
"=",
"None",
")",
":",
"desc",
"=",
"desc",
"or",
"org_name",
"res",
"=",
"self",
".",
"_create_org",
"(",
"orch_id",
",",
"org_name",
... | 44.45 | 17.7 |
def _join_chemical(query, cas_rn, chemical_id, chemical_name, chemical_definition):
"""helper function to add a query join to Chemical model
:param `sqlalchemy.orm.query.Query` query: SQL Alchemy query
:param cas_rn:
:param chemical_id:
:param chemical_name:
... | [
"def",
"_join_chemical",
"(",
"query",
",",
"cas_rn",
",",
"chemical_id",
",",
"chemical_name",
",",
"chemical_definition",
")",
":",
"if",
"cas_rn",
"or",
"chemical_id",
"or",
"chemical_name",
"or",
"chemical_definition",
":",
"query",
"=",
"query",
".",
"join"... | 38 | 24.5 |
def coroutine(f):
"""
Implementation of a coroutine.
Use as a decorator:
@coroutine
def foo():
result = yield somePromise
The function passed should be a generator yielding instances of the Promise class
(or compatible).
The coroutine waits for the Promise to resolve and sends ... | [
"def",
"coroutine",
"(",
"f",
")",
":",
"@",
"functools",
".",
"wraps",
"(",
"f",
")",
"def",
"_coroutine",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"def",
"_resolver",
"(",
"resolve",
",",
"reject",
")",
":",
"try",
":",
"generator",
... | 37.870968 | 19.354839 |
def _check_basis_label_type(cls, label_or_index):
"""Every object (BasisKet, LocalSigma) that contains a label or index
for an eigenstate of some LocalSpace should call this routine to check
the type of that label or index (or, use
:meth:`_unpack_basis_label_or_index`"""
if not i... | [
"def",
"_check_basis_label_type",
"(",
"cls",
",",
"label_or_index",
")",
":",
"if",
"not",
"isinstance",
"(",
"label_or_index",
",",
"cls",
".",
"_basis_label_types",
")",
":",
"raise",
"TypeError",
"(",
"\"label_or_index must be an instance of one of %s; not %s\"",
"%... | 60.1 | 18.1 |
def set_metadata_index_and_column_names(dim, meta_df):
"""
Sets index and column names to GCTX convention.
Input:
- dim (str): Dimension of metadata to read. Must be either "row" or "col"
- meta_df (pandas.DataFrame): data frame corresponding to metadata fields
of dimension speci... | [
"def",
"set_metadata_index_and_column_names",
"(",
"dim",
",",
"meta_df",
")",
":",
"if",
"dim",
"==",
"\"row\"",
":",
"meta_df",
".",
"index",
".",
"name",
"=",
"\"rid\"",
"meta_df",
".",
"columns",
".",
"name",
"=",
"\"rhd\"",
"elif",
"dim",
"==",
"\"col... | 33.1875 | 16.0625 |
def set(self, logicalId, resource):
"""
Adds the resource to dictionary with given logical Id. It will overwrite, if the logicalId is already used.
:param string logicalId: Logical Id to set to
:param SamResource or dict resource: The actual resource data
"""
resource_d... | [
"def",
"set",
"(",
"self",
",",
"logicalId",
",",
"resource",
")",
":",
"resource_dict",
"=",
"resource",
"if",
"isinstance",
"(",
"resource",
",",
"SamResource",
")",
":",
"resource_dict",
"=",
"resource",
".",
"to_dict",
"(",
")",
"self",
".",
"resources... | 35.846154 | 20.769231 |
def current_user(self):
"""
.. versionadded:: 0.6.0
Requires SMC version >= 6.4
Return the currently logged on API Client user element.
:raises UnsupportedEntryPoint: Current user is only supported with SMC
version >= 6.4
:rtype: Element
... | [
"def",
"current_user",
"(",
"self",
")",
":",
"if",
"self",
".",
"session",
":",
"try",
":",
"response",
"=",
"self",
".",
"session",
".",
"get",
"(",
"self",
".",
"entry_points",
".",
"get",
"(",
"'current_user'",
")",
")",
"if",
"response",
".",
"s... | 38.285714 | 18.380952 |
def b58dec(enc_uid):
'''Decodes a UID from base58, url-safe alphabet back to int.'''
if isinstance(enc_uid, str):
pass
elif isinstance(enc_uid, bytes):
enc_uid = enc_uid.decode('utf8')
else:
raise ValueError('Cannot decode this type: {}'.format(enc_uid))
uid = 0
try:
... | [
"def",
"b58dec",
"(",
"enc_uid",
")",
":",
"if",
"isinstance",
"(",
"enc_uid",
",",
"str",
")",
":",
"pass",
"elif",
"isinstance",
"(",
"enc_uid",
",",
"bytes",
")",
":",
"enc_uid",
"=",
"enc_uid",
".",
"decode",
"(",
"'utf8'",
")",
"else",
":",
"rai... | 34.4 | 20.8 |
def humanize_bytes(b, precision=1):
"""Return a humanized string representation of a number of b.
Assumes `from __future__ import division`.
>>> humanize_bytes(1)
'1 byte'
>>> humanize_bytes(1024)
'1.0 kB'
>>> humanize_bytes(1024*123)
'123.0 kB'
>>> humanize_bytes(1024*12342)
'... | [
"def",
"humanize_bytes",
"(",
"b",
",",
"precision",
"=",
"1",
")",
":",
"# abbrevs = (",
"# (1 << 50L, 'PB'),",
"# (1 << 40L, 'TB'),",
"# (1 << 30L, 'GB'),",
"# (1 << 20L, 'MB'),",
"# (1 << 10L, 'kB'),",
"# (1, 'b')",
"# )",
"abbrevs",
"=",
"(",
"("... | 24.2 | 17.622222 |
def _rows_int2date(self, rows):
"""
Replaces start and end dates in the row set with their integer representation
:param list[dict[str,T]] rows: The list of rows.
"""
for row in rows:
if self._date_type == 'str':
row[self._key_start_date] = datetime.d... | [
"def",
"_rows_int2date",
"(",
"self",
",",
"rows",
")",
":",
"for",
"row",
"in",
"rows",
":",
"if",
"self",
".",
"_date_type",
"==",
"'str'",
":",
"row",
"[",
"self",
".",
"_key_start_date",
"]",
"=",
"datetime",
".",
"date",
".",
"fromordinal",
"(",
... | 49.888889 | 26 |
def env_is_exposed(self, tgt_env):
'''
Check if an environment is exposed by comparing it against a whitelist
and blacklist.
'''
return salt.utils.stringutils.check_whitelist_blacklist(
tgt_env,
whitelist=self.saltenv_whitelist,
blacklist=self.... | [
"def",
"env_is_exposed",
"(",
"self",
",",
"tgt_env",
")",
":",
"return",
"salt",
".",
"utils",
".",
"stringutils",
".",
"check_whitelist_blacklist",
"(",
"tgt_env",
",",
"whitelist",
"=",
"self",
".",
"saltenv_whitelist",
",",
"blacklist",
"=",
"self",
".",
... | 33.9 | 20.5 |
def is_safe(self):
"""
Check if the option is safe.
:rtype : bool
:return: True, if option is safe
"""
if self._number == defines.OptionRegistry.URI_HOST.number \
or self._number == defines.OptionRegistry.URI_PORT.number \
or self._number ... | [
"def",
"is_safe",
"(",
"self",
")",
":",
"if",
"self",
".",
"_number",
"==",
"defines",
".",
"OptionRegistry",
".",
"URI_HOST",
".",
"number",
"or",
"self",
".",
"_number",
"==",
"defines",
".",
"OptionRegistry",
".",
"URI_PORT",
".",
"number",
"or",
"se... | 43.8125 | 22.6875 |
def block(self, article):
"""
Returns all block attachments associated with article_id (Such attachments has ``inline=False``).
Block attachments are displayed as separated files attached to Article.
:param article: Numeric article id or :class:`Article` object.
:return: Genera... | [
"def",
"block",
"(",
"self",
",",
"article",
")",
":",
"return",
"self",
".",
"_query_zendesk",
"(",
"self",
".",
"endpoint",
".",
"block",
",",
"'article_attachment'",
",",
"id",
"=",
"article",
")"
] | 45.5 | 30.3 |
def user_present(name, uid, password, channel=14, callback=False,
link_auth=True, ipmi_msg=True, privilege_level='administrator', **kwargs):
'''
Ensure IPMI user and user privileges.
name
name of user (limit 16 bytes)
uid
user id number (1 to 7)
password
us... | [
"def",
"user_present",
"(",
"name",
",",
"uid",
",",
"password",
",",
"channel",
"=",
"14",
",",
"callback",
"=",
"False",
",",
"link_auth",
"=",
"True",
",",
"ipmi_msg",
"=",
"True",
",",
"privilege_level",
"=",
"'administrator'",
",",
"*",
"*",
"kwargs... | 35.148148 | 23.537037 |
def inject_to(self, objects, field_name, get_inject_object = lambda obj: obj,
select_related = None, **kwargs):
'''
``objects`` is an iterable. Related objects
will be attached to elements of this iterable.
``field_name`` is the attached object attribute name
... | [
"def",
"inject_to",
"(",
"self",
",",
"objects",
",",
"field_name",
",",
"get_inject_object",
"=",
"lambda",
"obj",
":",
"obj",
",",
"select_related",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"#get related data",
"kwargs",
".",
"update",
"(",
"{",
... | 42.352113 | 27.619718 |
def _setSampleSizeBytes(self):
"""
updates the current record of the packet size per sample and the relationship between this and the fifo reads.
"""
self.sampleSizeBytes = self.getPacketSize()
if self.sampleSizeBytes > 0:
self.maxBytesPerFifoRead = (32 // self.sampl... | [
"def",
"_setSampleSizeBytes",
"(",
"self",
")",
":",
"self",
".",
"sampleSizeBytes",
"=",
"self",
".",
"getPacketSize",
"(",
")",
"if",
"self",
".",
"sampleSizeBytes",
">",
"0",
":",
"self",
".",
"maxBytesPerFifoRead",
"=",
"(",
"32",
"//",
"self",
".",
... | 46.428571 | 18.714286 |
def _write_bytes(stream: Union[StdSim, TextIO], to_write: bytes) -> None:
"""
Write bytes to a stream
:param stream: the stream being written to
:param to_write: the bytes being written
"""
try:
stream.buffer.write(to_write)
except BrokenPipeError:
... | [
"def",
"_write_bytes",
"(",
"stream",
":",
"Union",
"[",
"StdSim",
",",
"TextIO",
"]",
",",
"to_write",
":",
"bytes",
")",
"->",
"None",
":",
"try",
":",
"stream",
".",
"buffer",
".",
"write",
"(",
"to_write",
")",
"except",
"BrokenPipeError",
":",
"# ... | 36.272727 | 14.272727 |
def convert_spans(spans, output_encoding, input_encoding=None):
"""Converts encoded spans to a different encoding.
param spans: encoded input spans.
type spans: byte array
param output_encoding: desired output encoding.
type output_encoding: Encoding
param input_encoding: optional input encodin... | [
"def",
"convert_spans",
"(",
"spans",
",",
"output_encoding",
",",
"input_encoding",
"=",
"None",
")",
":",
"if",
"not",
"isinstance",
"(",
"input_encoding",
",",
"Encoding",
")",
":",
"input_encoding",
"=",
"detect_span_version_and_encoding",
"(",
"message",
"=",... | 36.366667 | 18.066667 |
def configure(self):
# type: () -> None
"""
Configures object based on its initialization
"""
for i in vars(self):
if i.startswith("_"):
continue
val = self.__get(i, return_type=type(getattr(self, i)))
if val is not None:
... | [
"def",
"configure",
"(",
"self",
")",
":",
"# type: () -> None",
"for",
"i",
"in",
"vars",
"(",
"self",
")",
":",
"if",
"i",
".",
"startswith",
"(",
"\"_\"",
")",
":",
"continue",
"val",
"=",
"self",
".",
"__get",
"(",
"i",
",",
"return_type",
"=",
... | 31.363636 | 11.363636 |
def import_data_dir(target_zip):
"""
Imports the data specified by param <target_zip>. Renames the data dir if it already exists and
unpacks the zip sub dir __data__ directly within the current active product.
:param target_zip: string path to the zip file.
"""
from django_productline.context im... | [
"def",
"import_data_dir",
"(",
"target_zip",
")",
":",
"from",
"django_productline",
".",
"context",
"import",
"PRODUCT_CONTEXT",
"new_data_dir",
"=",
"'{data_dir}_before_import_{ts}'",
".",
"format",
"(",
"data_dir",
"=",
"PRODUCT_CONTEXT",
".",
"DATA_DIR",
",",
"ts"... | 36.304348 | 22.304348 |
def pack_command(self, *args):
"""
Pack a series of arguments into a value SSDB command
"""
# the client might have included 1 or more literal arguments in
# the command name, e.g., 'CONFIG GET'. The SSDB server expects
# these arguments to be sent separately, so split th... | [
"def",
"pack_command",
"(",
"self",
",",
"*",
"args",
")",
":",
"# the client might have included 1 or more literal arguments in",
"# the command name, e.g., 'CONFIG GET'. The SSDB server expects",
"# these arguments to be sent separately, so split the first",
"# argument manually. All of th... | 38.291667 | 16.958333 |
def sia(transition, direction=Direction.BIDIRECTIONAL):
"""Return the minimal information partition of a transition in a specific
direction.
Args:
transition (Transition): The candidate system.
Returns:
AcSystemIrreducibilityAnalysis: A nested structure containing all the
data ... | [
"def",
"sia",
"(",
"transition",
",",
"direction",
"=",
"Direction",
".",
"BIDIRECTIONAL",
")",
":",
"validate",
".",
"direction",
"(",
"direction",
",",
"allow_bi",
"=",
"True",
")",
"log",
".",
"info",
"(",
"\"Calculating big-alpha for %s...\"",
",",
"transi... | 39.380952 | 19.666667 |
def copy_tree(src, dst):
"""Copy directory tree"""
for root, subdirs, files in os.walk(src):
current_dest = root.replace(src, dst)
if not os.path.exists(current_dest):
os.makedirs(current_dest)
for f in files:
shutil.copy(os.path.join(root, f), os.path.join(curren... | [
"def",
"copy_tree",
"(",
"src",
",",
"dst",
")",
":",
"for",
"root",
",",
"subdirs",
",",
"files",
"in",
"os",
".",
"walk",
"(",
"src",
")",
":",
"current_dest",
"=",
"root",
".",
"replace",
"(",
"src",
",",
"dst",
")",
"if",
"not",
"os",
".",
... | 40.5 | 10.875 |
def ReadAllClientActionRequests(self, client_id, cursor=None):
"""Reads all client messages available for a given client_id."""
query = ("SELECT request, UNIX_TIMESTAMP(leased_until), leased_by, "
"leased_count "
"FROM client_action_requests "
"WHERE client_id = %s")
... | [
"def",
"ReadAllClientActionRequests",
"(",
"self",
",",
"client_id",
",",
"cursor",
"=",
"None",
")",
":",
"query",
"=",
"(",
"\"SELECT request, UNIX_TIMESTAMP(leased_until), leased_by, \"",
"\"leased_count \"",
"\"FROM client_action_requests \"",
"\"WHERE client_id = %s\"",
")... | 39.73913 | 22 |
def parse(ctx, endpoint, check, here):
"""Interactively parse metric info from a Prometheus endpoint."""
if here:
output_dir = os.getcwd()
else:
output_dir = path_join(get_root(), check)
if not dir_exists(output_dir):
abort(
'Check `{check}` does not exist... | [
"def",
"parse",
"(",
"ctx",
",",
"endpoint",
",",
"check",
",",
"here",
")",
":",
"if",
"here",
":",
"output_dir",
"=",
"os",
".",
"getcwd",
"(",
")",
"else",
":",
"output_dir",
"=",
"path_join",
"(",
"get_root",
"(",
")",
",",
"check",
")",
"if",
... | 34.76087 | 21.666667 |
def bitorder_decode(data, out=None, _bitorder=[]):
"""Reverse bits in each byte of byte string or numpy array.
Decode data where pixels with lower column values are stored in the
lower-order bits of the bytes (TIFF FillOrder is LSB2MSB).
Parameters
----------
data : byte string or ndarray
... | [
"def",
"bitorder_decode",
"(",
"data",
",",
"out",
"=",
"None",
",",
"_bitorder",
"=",
"[",
"]",
")",
":",
"if",
"not",
"_bitorder",
":",
"_bitorder",
".",
"append",
"(",
"b'\\x00\\x80@\\xc0 \\xa0`\\xe0\\x10\\x90P\\xd00\\xb0p\\xf0\\x08\\x88H\\xc8('",
"b'\\xa8h\\xe8\\x... | 42.404255 | 23.978723 |
def get_agenda(self,
conservative: bool = False):
"""
Returns an agenda that can be used guide search.
Parameters
----------
conservative : ``bool``
Setting this flag will return a subset of the agenda items that correspond to high
conf... | [
"def",
"get_agenda",
"(",
"self",
",",
"conservative",
":",
"bool",
"=",
"False",
")",
":",
"agenda_items",
"=",
"[",
"]",
"question_tokens",
"=",
"[",
"token",
".",
"text",
"for",
"token",
"in",
"self",
".",
"table_context",
".",
"question_tokens",
"]",
... | 57.067797 | 27.734463 |
def Compile(self, filter_implementation):
"""Compile the binary expression into a filter object."""
operator = self.operator.lower()
if operator in ('and', '&&'):
method = 'AndFilter'
elif operator in ('or', '||'):
method = 'OrFilter'
else:
raise errors.ParseError(
'Inval... | [
"def",
"Compile",
"(",
"self",
",",
"filter_implementation",
")",
":",
"operator",
"=",
"self",
".",
"operator",
".",
"lower",
"(",
")",
"if",
"operator",
"in",
"(",
"'and'",
",",
"'&&'",
")",
":",
"method",
"=",
"'AndFilter'",
"elif",
"operator",
"in",
... | 36.461538 | 14.384615 |
def add_line(psr,f,A,offset=0.5):
"""
Add a line of frequency `f` [Hz] and amplitude `A` [s],
with origin at a fraction `offset` through the dataset.
"""
t = psr.toas()
t0 = offset * (N.max(t) - N.min(t))
sine = A * N.cos(2 * math.pi * f * day * (t - t0))
psr.stoas[:] += sine / day | [
"def",
"add_line",
"(",
"psr",
",",
"f",
",",
"A",
",",
"offset",
"=",
"0.5",
")",
":",
"t",
"=",
"psr",
".",
"toas",
"(",
")",
"t0",
"=",
"offset",
"*",
"(",
"N",
".",
"max",
"(",
"t",
")",
"-",
"N",
".",
"min",
"(",
"t",
")",
")",
"si... | 28.181818 | 15.272727 |
def to_hex_twos_compliment(value, bit_size):
"""
Converts integer value to twos compliment hex representation with given bit_size
"""
if value >= 0:
return to_hex_with_size(value, bit_size)
value = (1 << bit_size) + value
hex_value = hex(value)
hex_value = hex_value.rstrip("L")
... | [
"def",
"to_hex_twos_compliment",
"(",
"value",
",",
"bit_size",
")",
":",
"if",
"value",
">=",
"0",
":",
"return",
"to_hex_with_size",
"(",
"value",
",",
"bit_size",
")",
"value",
"=",
"(",
"1",
"<<",
"bit_size",
")",
"+",
"value",
"hex_value",
"=",
"hex... | 29.636364 | 14.545455 |
def file_rights(filepath, mode=None, uid=None, gid=None):
'''
Change file rights
'''
file_handle = os.open(filepath, os.O_RDONLY)
if mode:
os.fchmod(file_handle, mode)
if uid:
if not gid:
gid = 0
os.fchown(file_handle, uid, gid)
os.close(file_handle) | [
"def",
"file_rights",
"(",
"filepath",
",",
"mode",
"=",
"None",
",",
"uid",
"=",
"None",
",",
"gid",
"=",
"None",
")",
":",
"file_handle",
"=",
"os",
".",
"open",
"(",
"filepath",
",",
"os",
".",
"O_RDONLY",
")",
"if",
"mode",
":",
"os",
".",
"f... | 25.583333 | 18.583333 |
def create_widget(self):
""" Create the underlying widget.
"""
d = self.declaration
self.widget = Switch(self.get_context(), None,
d.style or '@attr/switchStyle') | [
"def",
"create_widget",
"(",
"self",
")",
":",
"d",
"=",
"self",
".",
"declaration",
"self",
".",
"widget",
"=",
"Switch",
"(",
"self",
".",
"get_context",
"(",
")",
",",
"None",
",",
"d",
".",
"style",
"or",
"'@attr/switchStyle'",
")"
] | 31.142857 | 14.571429 |
def refractory(times, refract=0.002):
"""Removes spikes in times list that do not satisfy refractor period
:param times: list(float) of spike times in seconds
:type times: list(float)
:param refract: Refractory period in seconds
:type refract: float
:returns: list(float) of spike times in seconds
For every int... | [
"def",
"refractory",
"(",
"times",
",",
"refract",
"=",
"0.002",
")",
":",
"times_refract",
"=",
"[",
"]",
"times_refract",
".",
"append",
"(",
"times",
"[",
"0",
"]",
")",
"for",
"i",
"in",
"range",
"(",
"1",
",",
"len",
"(",
"times",
")",
")",
... | 34.588235 | 12.176471 |
def finalize(self):
"""
Connects the wires.
"""
self._check_finalized()
self._final = True
for dest_w, values in self.dest_instrs_info.items():
mux_vals = dict(zip(self.instructions, values))
dest_w <<= sparse_mux(self.signal_wire, mux_vals) | [
"def",
"finalize",
"(",
"self",
")",
":",
"self",
".",
"_check_finalized",
"(",
")",
"self",
".",
"_final",
"=",
"True",
"for",
"dest_w",
",",
"values",
"in",
"self",
".",
"dest_instrs_info",
".",
"items",
"(",
")",
":",
"mux_vals",
"=",
"dict",
"(",
... | 30.5 | 15.7 |
def _derY(self,x,y):
'''
Returns the derivative with respect to y of the interpolated function
at each value in x,y. Only called internally by HARKinterpolator2D.derivativeX.
'''
x_pos, y_pos = self.findSector(x,y)
alpha, beta = self.findCoords(x,y,x_pos,y_pos)
#... | [
"def",
"_derY",
"(",
"self",
",",
"x",
",",
"y",
")",
":",
"x_pos",
",",
"y_pos",
"=",
"self",
".",
"findSector",
"(",
"x",
",",
"y",
")",
"alpha",
",",
"beta",
"=",
"self",
".",
"findCoords",
"(",
"x",
",",
"y",
",",
"x_pos",
",",
"y_pos",
"... | 39.425 | 15.625 |
def move_out_8(self, session, space, offset, length, data, extended=False):
"""Moves an 8-bit block of data from local memory to the specified address space and offset.
Corresponds to viMoveOut8* functions of the VISA library.
:param session: Unique logical identifier to a session.
:pa... | [
"def",
"move_out_8",
"(",
"self",
",",
"session",
",",
"space",
",",
"offset",
",",
"length",
",",
"data",
",",
"extended",
"=",
"False",
")",
":",
"raise",
"NotImplementedError"
] | 52.611111 | 25 |
def load(self, model_file, save_dir, verbose=True):
"""Load model from file and rebuild the model.
:param model_file: Saved model file name.
:type model_file: str
:param save_dir: Saved model directory.
:type save_dir: str
:param verbose: Print log or not
:type v... | [
"def",
"load",
"(",
"self",
",",
"model_file",
",",
"save_dir",
",",
"verbose",
"=",
"True",
")",
":",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"save_dir",
")",
":",
"self",
".",
"logger",
".",
"error",
"(",
"\"Loading failed... Directory does... | 33.333333 | 18.766667 |
def vm_configured(name, vm_name, cpu, memory, image, version, interfaces,
disks, scsi_devices, serial_ports, datacenter, datastore,
placement, cd_dvd_drives=None, sata_controllers=None,
advanced_configs=None, template=None, tools=True,
power_on=Fal... | [
"def",
"vm_configured",
"(",
"name",
",",
"vm_name",
",",
"cpu",
",",
"memory",
",",
"image",
",",
"version",
",",
"interfaces",
",",
"disks",
",",
"scsi_devices",
",",
"serial_ports",
",",
"datacenter",
",",
"datastore",
",",
"placement",
",",
"cd_dvd_drive... | 46.430233 | 19.802326 |
def pipe(engine, format, data, renderer=None, formatter=None, quiet=False):
"""Return ``data`` piped through Graphviz ``engine`` into ``format``.
Args:
engine: The layout commmand used for rendering (``'dot'``, ``'neato'``, ...).
format: The output format used for rendering (``'pdf'``, ``'png'`... | [
"def",
"pipe",
"(",
"engine",
",",
"format",
",",
"data",
",",
"renderer",
"=",
"None",
",",
"formatter",
"=",
"None",
",",
"quiet",
"=",
"False",
")",
":",
"cmd",
",",
"_",
"=",
"command",
"(",
"engine",
",",
"format",
",",
"None",
",",
"renderer"... | 56.142857 | 30.809524 |
def chunks(iterable, n):
"""Yield successive n-sized chunks from iterable object. https://stackoverflow.com/a/312464 """
for i in range(0, len(iterable), n):
yield iterable[i:i + n] | [
"def",
"chunks",
"(",
"iterable",
",",
"n",
")",
":",
"for",
"i",
"in",
"range",
"(",
"0",
",",
"len",
"(",
"iterable",
")",
",",
"n",
")",
":",
"yield",
"iterable",
"[",
"i",
":",
"i",
"+",
"n",
"]"
] | 48.5 | 6.25 |
def on_batch_end(self, iteration:int, **kwargs)->None:
"Callback function that writes batch end appropriate data to Tensorboard."
super().on_batch_end(iteration=iteration, **kwargs)
if iteration == 0: return
if iteration % self.visual_iters == 0: self._write_images(iteration=iteration) | [
"def",
"on_batch_end",
"(",
"self",
",",
"iteration",
":",
"int",
",",
"*",
"*",
"kwargs",
")",
"->",
"None",
":",
"super",
"(",
")",
".",
"on_batch_end",
"(",
"iteration",
"=",
"iteration",
",",
"*",
"*",
"kwargs",
")",
"if",
"iteration",
"==",
"0",... | 62.8 | 25.6 |
def skew_y(self, y):
"""Skew element along the y-axis by the given angle.
Parameters
----------
y : float
y-axis skew angle in degrees
"""
self.root.set("transform", "%s skewY(%f)" %
(self.root.get("transform") or '', y))
return ... | [
"def",
"skew_y",
"(",
"self",
",",
"y",
")",
":",
"self",
".",
"root",
".",
"set",
"(",
"\"transform\"",
",",
"\"%s skewY(%f)\"",
"%",
"(",
"self",
".",
"root",
".",
"get",
"(",
"\"transform\"",
")",
"or",
"''",
",",
"y",
")",
")",
"return",
"self"... | 28.545455 | 16.272727 |
def build_ruptures(sources, src_filter, param, monitor):
"""
:param sources: a list with a single UCERF source
:param param: extra parameters
:param monitor: a Monitor instance
:returns: an AccumDict grp_id -> EBRuptures
"""
[src] = sources
res = AccumDict()
res.calc_times = []
s... | [
"def",
"build_ruptures",
"(",
"sources",
",",
"src_filter",
",",
"param",
",",
"monitor",
")",
":",
"[",
"src",
"]",
"=",
"sources",
"res",
"=",
"AccumDict",
"(",
")",
"res",
".",
"calc_times",
"=",
"[",
"]",
"sampl_mon",
"=",
"monitor",
"(",
"'samplin... | 40.545455 | 14.181818 |
def process_payment(self):
'''
Proceed with payment using the payment method selected earlier.
:return: A response having processes the payment.
:rtype: requests.Response
'''
params = {
'__RequestVerificationToken': self.session.cookies,
'method':... | [
"def",
"process_payment",
"(",
"self",
")",
":",
"params",
"=",
"{",
"'__RequestVerificationToken'",
":",
"self",
".",
"session",
".",
"cookies",
",",
"'method'",
":",
"'submit'",
"}",
"return",
"self",
".",
"__post",
"(",
"'/PaymentOptions/Proceed'",
",",
"js... | 30.384615 | 24.538462 |
def datafile_from_hash(hash_, prefix, path):
"""Return pathlib.Path for a data-file with given hash and prefix.
"""
pattern = '%s_%s*.h*' % (prefix, hash_)
datafiles = list(path.glob(pattern))
if len(datafiles) == 0:
raise NoMatchError('No matches for "%s"' % pattern)... | [
"def",
"datafile_from_hash",
"(",
"hash_",
",",
"prefix",
",",
"path",
")",
":",
"pattern",
"=",
"'%s_%s*.h*'",
"%",
"(",
"prefix",
",",
"hash_",
")",
"datafiles",
"=",
"list",
"(",
"path",
".",
"glob",
"(",
"pattern",
")",
")",
"if",
"len",
"(",
"da... | 44.9 | 10.8 |
def revoke_all_tokens(self):
"""
Implementation of :meth:`twitcher.api.ITokenManager.revoke_all_tokens`.
"""
try:
self.store.clear_tokens()
except Exception:
LOGGER.exception('Failed to remove tokens.')
return False
else:
re... | [
"def",
"revoke_all_tokens",
"(",
"self",
")",
":",
"try",
":",
"self",
".",
"store",
".",
"clear_tokens",
"(",
")",
"except",
"Exception",
":",
"LOGGER",
".",
"exception",
"(",
"'Failed to remove tokens.'",
")",
"return",
"False",
"else",
":",
"return",
"Tru... | 29 | 15.727273 |
def to_internal_value(self, data):
"""
Calls super() from DRF, but with an addition.
Creates initial_data and _validated_data for nested
EmbeddedDocumentSerializers, so that recursive_save could make
use of them.
If meets any arbitrary data, not expected by fields,
... | [
"def",
"to_internal_value",
"(",
"self",
",",
"data",
")",
":",
"# for EmbeddedDocumentSerializers create initial data",
"# so that _get_dynamic_data could use them",
"for",
"field",
"in",
"self",
".",
"_writable_fields",
":",
"if",
"isinstance",
"(",
"field",
",",
"Embed... | 41.076923 | 22.384615 |
def ucc_circuit(theta):
"""
Implements
exp(-i theta X_{0}Y_{1})
:param theta: rotation parameter
:return: pyquil.Program
"""
generator = sX(0) * sY(1)
initial_prog = Program().inst(X(1), X(0))
# compiled program
program = initial_prog + exponentiate(float(theta) * generator) ... | [
"def",
"ucc_circuit",
"(",
"theta",
")",
":",
"generator",
"=",
"sX",
"(",
"0",
")",
"*",
"sY",
"(",
"1",
")",
"initial_prog",
"=",
"Program",
"(",
")",
".",
"inst",
"(",
"X",
"(",
"1",
")",
",",
"X",
"(",
"0",
")",
")",
"# compiled program",
"... | 25.733333 | 22.533333 |
def unit(v, lg=1):
""" unit vector
Args:
v: vector (x, y)
lg: length
Raises:
ValueError: Null vector was given
"""
try:
res = scale(v, lg / distance((0, 0), v))
except ZeroDivisionError:
raise ValueError("Null vector was given")
return res | [
"def",
"unit",
"(",
"v",
",",
"lg",
"=",
"1",
")",
":",
"try",
":",
"res",
"=",
"scale",
"(",
"v",
",",
"lg",
"/",
"distance",
"(",
"(",
"0",
",",
"0",
")",
",",
"v",
")",
")",
"except",
"ZeroDivisionError",
":",
"raise",
"ValueError",
"(",
"... | 22.692308 | 15.923077 |
def create(args):
""" Create a model from wavelength and flux files. """
from sick.models.create import create
return create(os.path.join(args.output_dir, args.model_name),
args.grid_points_filename, args.wavelength_filenames,
clobber=args.clobber) | [
"def",
"create",
"(",
"args",
")",
":",
"from",
"sick",
".",
"models",
".",
"create",
"import",
"create",
"return",
"create",
"(",
"os",
".",
"path",
".",
"join",
"(",
"args",
".",
"output_dir",
",",
"args",
".",
"model_name",
")",
",",
"args",
".",
... | 38.857143 | 17.428571 |
def get_installed_extension_by_name(self, publisher_name, extension_name, asset_types=None):
"""GetInstalledExtensionByName.
[Preview API] Get an installed extension by its publisher and extension name.
:param str publisher_name: Name of the publisher. Example: "fabrikam".
:param str ext... | [
"def",
"get_installed_extension_by_name",
"(",
"self",
",",
"publisher_name",
",",
"extension_name",
",",
"asset_types",
"=",
"None",
")",
":",
"route_values",
"=",
"{",
"}",
"if",
"publisher_name",
"is",
"not",
"None",
":",
"route_values",
"[",
"'publisherName'",... | 61.608696 | 26.565217 |
def create_result(self, local_path, container_path, permissions, meta, val, dividers):
"""Default permissions to rw"""
if permissions is NotSpecified:
permissions = 'rw'
return Mount(local_path, container_path, permissions) | [
"def",
"create_result",
"(",
"self",
",",
"local_path",
",",
"container_path",
",",
"permissions",
",",
"meta",
",",
"val",
",",
"dividers",
")",
":",
"if",
"permissions",
"is",
"NotSpecified",
":",
"permissions",
"=",
"'rw'",
"return",
"Mount",
"(",
"local_... | 51 | 15.6 |
def _solve_base_feature_map(self, model_name, dependency_cache=None):
"""
Solves the leaf :class:`revscoring.Feature` from the dependency for
`model_name` using `dependency_cache`. This will return a mapping
between the `str` name of the base features and the solved values.
"""
... | [
"def",
"_solve_base_feature_map",
"(",
"self",
",",
"model_name",
",",
"dependency_cache",
"=",
"None",
")",
":",
"features",
"=",
"list",
"(",
"trim",
"(",
"self",
"[",
"model_name",
"]",
".",
"features",
")",
")",
"feature_values",
"=",
"self",
".",
"ext... | 53.2 | 22 |
def apply_ufunc(
func: Callable,
*args: Any,
input_core_dims: Optional[Sequence[Sequence]] = None,
output_core_dims: Optional[Sequence[Sequence]] = ((),),
exclude_dims: AbstractSet = frozenset(),
vectorize: bool = False,
join: str = 'exact',
dataset_join: str = 'exact',
dataset_fill_... | [
"def",
"apply_ufunc",
"(",
"func",
":",
"Callable",
",",
"*",
"args",
":",
"Any",
",",
"input_core_dims",
":",
"Optional",
"[",
"Sequence",
"[",
"Sequence",
"]",
"]",
"=",
"None",
",",
"output_core_dims",
":",
"Optional",
"[",
"Sequence",
"[",
"Sequence",
... | 45.38488 | 23.879725 |
def jens_transformation_beta(graph: BELGraph) -> DiGraph:
"""Apply Jens' Transformation (Type 2) to the graph.
1. Induce a sub-graph over causal and correlative relations
2. Transform edges with the following rules:
- increases => backwards decreases
- decreases => decreases
- posit... | [
"def",
"jens_transformation_beta",
"(",
"graph",
":",
"BELGraph",
")",
"->",
"DiGraph",
":",
"result",
"=",
"DiGraph",
"(",
")",
"for",
"u",
",",
"v",
",",
"d",
"in",
"graph",
".",
"edges",
"(",
"data",
"=",
"True",
")",
":",
"relation",
"=",
"d",
... | 32.551724 | 18.448276 |
def _get_subnetname_id(subnetname):
'''
Returns the SubnetId of a SubnetName to use
'''
params = {'Action': 'DescribeSubnets'}
for subnet in aws.query(params, location=get_location(),
provider=get_provider(), opts=__opts__, sigver='4'):
tags = subnet.get('tagSet', {}).get('ite... | [
"def",
"_get_subnetname_id",
"(",
"subnetname",
")",
":",
"params",
"=",
"{",
"'Action'",
":",
"'DescribeSubnets'",
"}",
"for",
"subnet",
"in",
"aws",
".",
"query",
"(",
"params",
",",
"location",
"=",
"get_location",
"(",
")",
",",
"provider",
"=",
"get_p... | 37.277778 | 15.722222 |
def normalize(tensor, mean, std, inplace=False):
"""Normalize a tensor image with mean and standard deviation.
.. note::
This transform acts out of place by default, i.e., it does not mutates the input tensor.
See :class:`~torchvision.transforms.Normalize` for more details.
Args:
tens... | [
"def",
"normalize",
"(",
"tensor",
",",
"mean",
",",
"std",
",",
"inplace",
"=",
"False",
")",
":",
"if",
"not",
"_is_tensor_image",
"(",
"tensor",
")",
":",
"raise",
"TypeError",
"(",
"'tensor is not a torch image.'",
")",
"if",
"not",
"inplace",
":",
"te... | 35.807692 | 25.576923 |
def etree_to_string(root, pretty_print=True, xml_declaration=True,
encoding='utf-8'):
"""Dump XML etree as a string."""
return etree.tostring(
root,
pretty_print=pretty_print,
xml_declaration=xml_declaration,
encoding=encoding,
).decode('utf-8') | [
"def",
"etree_to_string",
"(",
"root",
",",
"pretty_print",
"=",
"True",
",",
"xml_declaration",
"=",
"True",
",",
"encoding",
"=",
"'utf-8'",
")",
":",
"return",
"etree",
".",
"tostring",
"(",
"root",
",",
"pretty_print",
"=",
"pretty_print",
",",
"xml_decl... | 33.444444 | 12 |
def libvlc_media_get_codec_description(i_type, i_codec):
'''Get codec description from media elementary stream.
@param i_type: i_type from L{MediaTrack}.
@param i_codec: i_codec or i_original_fourcc from L{MediaTrack}.
@return: codec description.
@version: LibVLC 3.0.0 and later. See L{MediaTrack}.
... | [
"def",
"libvlc_media_get_codec_description",
"(",
"i_type",
",",
"i_codec",
")",
":",
"f",
"=",
"_Cfunctions",
".",
"get",
"(",
"'libvlc_media_get_codec_description'",
",",
"None",
")",
"or",
"_Cfunction",
"(",
"'libvlc_media_get_codec_description'",
",",
"(",
"(",
... | 51.181818 | 20.818182 |
def normalize_array(q):
"""
Normalizes the list with len 4 so that it can be used as quaternion
:param q: array of len 4
:returns: normalized array
"""
assert(len(q) == 4)
q = np.array(q)
n = QuaternionBase.norm_array(q)
return q / n | [
"def",
"normalize_array",
"(",
"q",
")",
":",
"assert",
"(",
"len",
"(",
"q",
")",
"==",
"4",
")",
"q",
"=",
"np",
".",
"array",
"(",
"q",
")",
"n",
"=",
"QuaternionBase",
".",
"norm_array",
"(",
"q",
")",
"return",
"q",
"/",
"n"
] | 29.6 | 11.6 |
def get_variable_values(
schema: GraphQLSchema,
var_def_nodes: List[VariableDefinitionNode],
inputs: Dict[str, Any],
) -> CoercedVariableValues:
"""Get coerced variable values based on provided definitions.
Prepares a dict of variable values of the correct type based on the provided
variable de... | [
"def",
"get_variable_values",
"(",
"schema",
":",
"GraphQLSchema",
",",
"var_def_nodes",
":",
"List",
"[",
"VariableDefinitionNode",
"]",
",",
"inputs",
":",
"Dict",
"[",
"str",
",",
"Any",
"]",
",",
")",
"->",
"CoercedVariableValues",
":",
"errors",
":",
"L... | 45.791667 | 18.625 |
def _get_controller_type(self):
"""Returns the current node's controller type"""
if self.node_type == self.NODE_CONTROLLER_ROOT and self.name in self.CONTROLLERS:
return self.name
elif self.parent:
return self.parent.controller_type
else:
return None | [
"def",
"_get_controller_type",
"(",
"self",
")",
":",
"if",
"self",
".",
"node_type",
"==",
"self",
".",
"NODE_CONTROLLER_ROOT",
"and",
"self",
".",
"name",
"in",
"self",
".",
"CONTROLLERS",
":",
"return",
"self",
".",
"name",
"elif",
"self",
".",
"parent"... | 34.555556 | 19.444444 |
def import_pipeline(conf, args):
"""Import a pipeline from json."""
with open(args.pipeline_json) as pipeline_json:
dst = conf.config['instances'][args.dst_instance]
dst_url = api.build_pipeline_url(build_instance_url(dst))
dst_auth = tuple([conf.creds['instances'][args.dst_instance]['us... | [
"def",
"import_pipeline",
"(",
"conf",
",",
"args",
")",
":",
"with",
"open",
"(",
"args",
".",
"pipeline_json",
")",
"as",
"pipeline_json",
":",
"dst",
"=",
"conf",
".",
"config",
"[",
"'instances'",
"]",
"[",
"args",
".",
"dst_instance",
"]",
"dst_url"... | 61.4 | 23.2 |
def worker_exec(self,
queue_timeout=2,
req_timeout=5,
max_retry=3,
**kwargs):
"""Target method of workers.
Firstly download the page and then call the :func:`parse` method.
A parser thread will exit in either of the... | [
"def",
"worker_exec",
"(",
"self",
",",
"queue_timeout",
"=",
"2",
",",
"req_timeout",
"=",
"5",
",",
"max_retry",
"=",
"3",
",",
"*",
"*",
"kwargs",
")",
":",
"while",
"True",
":",
"if",
"self",
".",
"signal",
".",
"get",
"(",
"'reach_max_num'",
")"... | 46.578313 | 19.650602 |
def next(self):
"""Next point in iteration
"""
while True:
x, y = next(self.scan)
self.index += 1
if (self.index < self.start): continue
if (self.index > self.stop): raise StopIteration("skip stopping")
if ((self.index-self.start) % sel... | [
"def",
"next",
"(",
"self",
")",
":",
"while",
"True",
":",
"x",
",",
"y",
"=",
"next",
"(",
"self",
".",
"scan",
")",
"self",
".",
"index",
"+=",
"1",
"if",
"(",
"self",
".",
"index",
"<",
"self",
".",
"start",
")",
":",
"continue",
"if",
"(... | 35.7 | 15.6 |
def eref(obj, key, is_assoc=None):
"""
Returns element reference
:param obj:
:param key:
:param is_assoc:
:return:
"""
if obj is None:
return None
if isinstance(key, int) or (is_assoc is not None and is_assoc):
return ElemRefArr, get_elem(obj), key
else:
r... | [
"def",
"eref",
"(",
"obj",
",",
"key",
",",
"is_assoc",
"=",
"None",
")",
":",
"if",
"obj",
"is",
"None",
":",
"return",
"None",
"if",
"isinstance",
"(",
"key",
",",
"int",
")",
"or",
"(",
"is_assoc",
"is",
"not",
"None",
"and",
"is_assoc",
")",
... | 24.5 | 16.071429 |
def _to_dict(self):
"""Return a json dictionary representing this model."""
_dict = {}
if hasattr(self, 'text') and self.text is not None:
_dict['text'] = self.text
if hasattr(self, 'emotion') and self.emotion is not None:
_dict['emotion'] = self.emotion._to_dict(... | [
"def",
"_to_dict",
"(",
"self",
")",
":",
"_dict",
"=",
"{",
"}",
"if",
"hasattr",
"(",
"self",
",",
"'text'",
")",
"and",
"self",
".",
"text",
"is",
"not",
"None",
":",
"_dict",
"[",
"'text'",
"]",
"=",
"self",
".",
"text",
"if",
"hasattr",
"(",... | 41.875 | 15.5 |
def to_camel_case(text):
"""Convert to camel case.
:param str text:
:rtype: str
:return:
"""
split = text.split('_')
return split[0] + "".join(x.title() for x in split[1:]) | [
"def",
"to_camel_case",
"(",
"text",
")",
":",
"split",
"=",
"text",
".",
"split",
"(",
"'_'",
")",
"return",
"split",
"[",
"0",
"]",
"+",
"\"\"",
".",
"join",
"(",
"x",
".",
"title",
"(",
")",
"for",
"x",
"in",
"split",
"[",
"1",
":",
"]",
"... | 21.444444 | 17.888889 |
def display(name):
'''
Display alternatives settings for defined command name
CLI Example:
.. code-block:: bash
salt '*' alternatives.display editor
'''
cmd = [_get_cmd(), '--display', name]
out = __salt__['cmd.run_all'](cmd, python_shell=False)
if out['retcode'] > 0 and out['... | [
"def",
"display",
"(",
"name",
")",
":",
"cmd",
"=",
"[",
"_get_cmd",
"(",
")",
",",
"'--display'",
",",
"name",
"]",
"out",
"=",
"__salt__",
"[",
"'cmd.run_all'",
"]",
"(",
"cmd",
",",
"python_shell",
"=",
"False",
")",
"if",
"out",
"[",
"'retcode'"... | 25 | 21.8 |
def _is_word_type(token_type):
"""Return true if this is a word-type token."""
return token_type in [TokenType.Word,
TokenType.QuotedLiteral,
TokenType.UnquotedLiteral,
TokenType.Number,
TokenType.Deref] | [
"def",
"_is_word_type",
"(",
"token_type",
")",
":",
"return",
"token_type",
"in",
"[",
"TokenType",
".",
"Word",
",",
"TokenType",
".",
"QuotedLiteral",
",",
"TokenType",
".",
"UnquotedLiteral",
",",
"TokenType",
".",
"Number",
",",
"TokenType",
".",
"Deref",... | 44.142857 | 5.428571 |
def perform_flag(request, comment):
"""
Actually perform the flagging of a comment from a request.
"""
flag, created = comments.models.CommentFlag.objects.get_or_create(
comment = comment,
user = request.user,
flag = comments.models.CommentFlag.SUGGEST_REMOVAL
)
sig... | [
"def",
"perform_flag",
"(",
"request",
",",
"comment",
")",
":",
"flag",
",",
"created",
"=",
"comments",
".",
"models",
".",
"CommentFlag",
".",
"objects",
".",
"get_or_create",
"(",
"comment",
"=",
"comment",
",",
"user",
"=",
"request",
".",
"user",
"... | 30.1875 | 14.8125 |
def _get_user_info(self, access_token):
"""Return Clef user info."""
info_response = self._call('GET', self.info_url, params={'access_token': access_token})
user_info = info_response.get('info')
return user_info | [
"def",
"_get_user_info",
"(",
"self",
",",
"access_token",
")",
":",
"info_response",
"=",
"self",
".",
"_call",
"(",
"'GET'",
",",
"self",
".",
"info_url",
",",
"params",
"=",
"{",
"'access_token'",
":",
"access_token",
"}",
")",
"user_info",
"=",
"info_r... | 47.8 | 15.4 |
def explain(self, extended=False):
"""Prints the (logical and physical) plans to the console for debugging purpose.
:param extended: boolean, default ``False``. If ``False``, prints only the physical plan.
>>> df.explain()
== Physical Plan ==
*(1) Scan ExistingRDD[age#0,name#1]... | [
"def",
"explain",
"(",
"self",
",",
"extended",
"=",
"False",
")",
":",
"if",
"extended",
":",
"print",
"(",
"self",
".",
"_jdf",
".",
"queryExecution",
"(",
")",
".",
"toString",
"(",
")",
")",
"else",
":",
"print",
"(",
"self",
".",
"_jdf",
".",
... | 29.391304 | 19.782609 |
def supportsType(self, type_uri):
"""Does this endpoint support this type?
I consider C{/server} endpoints to implicitly support C{/signon}.
"""
return (
(type_uri in self.type_uris) or
(type_uri == OPENID_2_0_TYPE and self.isOPIdentifier())
) | [
"def",
"supportsType",
"(",
"self",
",",
"type_uri",
")",
":",
"return",
"(",
"(",
"type_uri",
"in",
"self",
".",
"type_uris",
")",
"or",
"(",
"type_uri",
"==",
"OPENID_2_0_TYPE",
"and",
"self",
".",
"isOPIdentifier",
"(",
")",
")",
")"
] | 33.888889 | 18 |
def get_external_commands(self):
"""Send a HTTP request to the satellite (GET /_external_commands) to
get the external commands from the satellite.
:return: External Command list on success, [] on failure
:rtype: list
"""
res = self.con.get('_external_commands', wait=Fal... | [
"def",
"get_external_commands",
"(",
"self",
")",
":",
"res",
"=",
"self",
".",
"con",
".",
"get",
"(",
"'_external_commands'",
",",
"wait",
"=",
"False",
")",
"logger",
".",
"debug",
"(",
"\"Got %d external commands from %s: %s\"",
",",
"len",
"(",
"res",
"... | 43.9 | 17.4 |
async def skip(source, n):
"""Forward an asynchronous sequence, skipping the first ``n`` elements.
If ``n`` is negative, no elements are skipped.
"""
source = transform.enumerate.raw(source)
async with streamcontext(source) as streamer:
async for i, item in streamer:
if i >= n:
... | [
"async",
"def",
"skip",
"(",
"source",
",",
"n",
")",
":",
"source",
"=",
"transform",
".",
"enumerate",
".",
"raw",
"(",
"source",
")",
"async",
"with",
"streamcontext",
"(",
"source",
")",
"as",
"streamer",
":",
"async",
"for",
"i",
",",
"item",
"i... | 33.7 | 11.1 |
def _versioned_lib_name(env, libnode, version, prefix, suffix, prefix_generator, suffix_generator, **kw):
"""For libnode='/optional/dir/libfoo.so.X.Y.Z' it returns 'libfoo.so'"""
Verbose = False
if Verbose:
print("_versioned_lib_name: libnode={:r}".format(libnode.get_path()))
print("_versio... | [
"def",
"_versioned_lib_name",
"(",
"env",
",",
"libnode",
",",
"version",
",",
"prefix",
",",
"suffix",
",",
"prefix_generator",
",",
"suffix_generator",
",",
"*",
"*",
"kw",
")",
":",
"Verbose",
"=",
"False",
"if",
"Verbose",
":",
"print",
"(",
"\"_versio... | 47.392857 | 27.964286 |
def shouldSkipUrl(self, url, data):
"""Skip pages without images."""
return url in (
self.stripUrl % '130217', # video
self.stripUrl % '130218', # video
self.stripUrl % '130226', # video
self.stripUrl % '130424', # video
) | [
"def",
"shouldSkipUrl",
"(",
"self",
",",
"url",
",",
"data",
")",
":",
"return",
"url",
"in",
"(",
"self",
".",
"stripUrl",
"%",
"'130217'",
",",
"# video",
"self",
".",
"stripUrl",
"%",
"'130218'",
",",
"# video",
"self",
".",
"stripUrl",
"%",
"'1302... | 35.875 | 9.125 |
def _incident_transform(incident):
"""Get output dict from incident."""
return {
'id': incident.get('cdid'),
'type': incident.get('type'),
'timestamp': incident.get('date'),
'lat': incident.get('lat'),
'lon': incident.get('lon'),
'location': incident.get('address'... | [
"def",
"_incident_transform",
"(",
"incident",
")",
":",
"return",
"{",
"'id'",
":",
"incident",
".",
"get",
"(",
"'cdid'",
")",
",",
"'type'",
":",
"incident",
".",
"get",
"(",
"'type'",
")",
",",
"'timestamp'",
":",
"incident",
".",
"get",
"(",
"'dat... | 32.272727 | 8.818182 |
def ComponentsToPath(components):
"""Converts a list of path components to a canonical path representation.
Args:
components: A sequence of path components.
Returns:
A canonical MySQL path representation.
"""
precondition.AssertIterableType(components, Text)
for component in components:
if not... | [
"def",
"ComponentsToPath",
"(",
"components",
")",
":",
"precondition",
".",
"AssertIterableType",
"(",
"components",
",",
"Text",
")",
"for",
"component",
"in",
"components",
":",
"if",
"not",
"component",
":",
"raise",
"ValueError",
"(",
"\"Empty path component ... | 26.857143 | 21.333333 |
def ensure_property_set(host=None, admin_username=None, admin_password=None, property=None, value=None):
'''
.. versionadded:: Fluorine
Ensure that property is set to specific value
host
The chassis host.
admin_username
The username used to access the chassis.
admin_password
... | [
"def",
"ensure_property_set",
"(",
"host",
"=",
"None",
",",
"admin_username",
"=",
"None",
",",
"admin_password",
"=",
"None",
",",
"property",
"=",
"None",
",",
"value",
"=",
"None",
")",
":",
"ret",
"=",
"get_property",
"(",
"host",
",",
"admin_username... | 24.939394 | 28.636364 |
def list_all_cash_on_delivery_payments(cls, **kwargs):
"""List CashOnDeliveryPayments
Return a list of CashOnDeliveryPayments
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async=True
>>> thread = api.list_all_cash_on_d... | [
"def",
"list_all_cash_on_delivery_payments",
"(",
"cls",
",",
"*",
"*",
"kwargs",
")",
":",
"kwargs",
"[",
"'_return_http_data_only'",
"]",
"=",
"True",
"if",
"kwargs",
".",
"get",
"(",
"'async'",
")",
":",
"return",
"cls",
".",
"_list_all_cash_on_delivery_payme... | 40.956522 | 17.086957 |
def getUTC(self):
""" Returns this Datetime localized for UTC. """
timeUTC = self.time.getUTC(self.utcoffset)
dateUTC = Date(round(self.jd))
return Datetime(dateUTC, timeUTC) | [
"def",
"getUTC",
"(",
"self",
")",
":",
"timeUTC",
"=",
"self",
".",
"time",
".",
"getUTC",
"(",
"self",
".",
"utcoffset",
")",
"dateUTC",
"=",
"Date",
"(",
"round",
"(",
"self",
".",
"jd",
")",
")",
"return",
"Datetime",
"(",
"dateUTC",
",",
"time... | 40.4 | 7.2 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.