text stringlengths 89 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 630 |
|---|---|---|---|
def dump_hash_prefix_values(self):
"""Export all hash prefix values.
Returns a list of known hash prefix values
"""
q = '''SELECT distinct value from hash_prefix'''
output = []
with self.get_cursor() as dbc:
dbc.execute(q)
output = [bytes(r[0]) fo... | [
"def",
"dump_hash_prefix_values",
"(",
"self",
")",
":",
"q",
"=",
"'''SELECT distinct value from hash_prefix'''",
"output",
"=",
"[",
"]",
"with",
"self",
".",
"get_cursor",
"(",
")",
"as",
"dbc",
":",
"dbc",
".",
"execute",
"(",
"q",
")",
"output",
"=",
... | 32.181818 | 13.272727 |
def create(cls, name, ipv4_network=None, ipv6_network=None,
comment=None):
"""
Create the network element
:param str name: Name of element
:param str ipv4_network: network cidr (optional if ipv6)
:param str ipv6_network: network cidr (optional if ipv4)
:pa... | [
"def",
"create",
"(",
"cls",
",",
"name",
",",
"ipv4_network",
"=",
"None",
",",
"ipv6_network",
"=",
"None",
",",
"comment",
"=",
"None",
")",
":",
"ipv4_network",
"=",
"ipv4_network",
"if",
"ipv4_network",
"else",
"None",
"ipv6_network",
"=",
"ipv6_network... | 38.521739 | 15.565217 |
def main():
'''Main routine.'''
# process arguments
if len(sys.argv) < 3:
usage()
rgname = sys.argv[1]
vmss = sys.argv[2]
# Load Azure app defaults
try:
with open('azurermconfig.json') as config_file:
config_data = json.load(config_file)
except FileNotFound... | [
"def",
"main",
"(",
")",
":",
"# process arguments",
"if",
"len",
"(",
"sys",
".",
"argv",
")",
"<",
"3",
":",
"usage",
"(",
")",
"rgname",
"=",
"sys",
".",
"argv",
"[",
"1",
"]",
"vmss",
"=",
"sys",
".",
"argv",
"[",
"2",
"]",
"# Load Azure app ... | 33.297297 | 26.648649 |
def get_unique_counter(self, redis_conn=None, host='localhost', port=6379,
key='unique_counter', cycle_time=5, start_time=None,
window=SECONDS_1_HOUR, roll=True, keep_max=12):
'''
Generate a new UniqueCounter.
Useful for exactly counting uniq... | [
"def",
"get_unique_counter",
"(",
"self",
",",
"redis_conn",
"=",
"None",
",",
"host",
"=",
"'localhost'",
",",
"port",
"=",
"6379",
",",
"key",
"=",
"'unique_counter'",
",",
"cycle_time",
"=",
"5",
",",
"start_time",
"=",
"None",
",",
"window",
"=",
"SE... | 51.333333 | 23.5 |
def _create_parser(cls):
"""
Need to check the specific symbol "/" in attr_value part as well.
I checked some multipath configuraion files from the sosreport and got
although there are some more specific symbols like "-%", it is enclosed
in double quotes and will be accepted. Fur... | [
"def",
"_create_parser",
"(",
"cls",
")",
":",
"section_name",
"=",
"p",
".",
"Word",
"(",
"p",
".",
"alphas",
"+",
"\"_\"",
")",
"attr_name",
"=",
"attr_value",
"=",
"p",
".",
"Word",
"(",
"p",
".",
"alphanums",
"+",
"\"_/\"",
")",
"LBRACE",
",",
... | 57.230769 | 24.384615 |
def ping(dest_addr: str, timeout: int = 4, unit: str = "s", src_addr: str = None, ttl: int = 64, seq: int = 0, size: int = 56) -> float or None:
"""
Send one ping to destination address with the given timeout.
Args:
dest_addr: The destination address, can be an IP address or a domain name. Ex. "192... | [
"def",
"ping",
"(",
"dest_addr",
":",
"str",
",",
"timeout",
":",
"int",
"=",
"4",
",",
"unit",
":",
"str",
"=",
"\"s\"",
",",
"src_addr",
":",
"str",
"=",
"None",
",",
"ttl",
":",
"int",
"=",
"64",
",",
"seq",
":",
"int",
"=",
"0",
",",
"siz... | 49.594595 | 33.108108 |
def _from_dict(cls, _dict):
"""Initialize a Tables object from a json dictionary."""
args = {}
if 'location' in _dict:
args['location'] = Location._from_dict(_dict.get('location'))
if 'text' in _dict:
args['text'] = _dict.get('text')
if 'section_title' in ... | [
"def",
"_from_dict",
"(",
"cls",
",",
"_dict",
")",
":",
"args",
"=",
"{",
"}",
"if",
"'location'",
"in",
"_dict",
":",
"args",
"[",
"'location'",
"]",
"=",
"Location",
".",
"_from_dict",
"(",
"_dict",
".",
"get",
"(",
"'location'",
")",
")",
"if",
... | 39.333333 | 13.757576 |
def init(obj, resource_root, attrs=None):
"""
Wraper around the real constructor to avoid issues with the 'self'
argument. Call like this, from a subclass's constructor:
- BaseApiObject.init(self, locals())
"""
# This works around http://bugs.python.org/issue2646
# We use unicode strings a... | [
"def",
"init",
"(",
"obj",
",",
"resource_root",
",",
"attrs",
"=",
"None",
")",
":",
"# This works around http://bugs.python.org/issue2646",
"# We use unicode strings as keys in kwargs.",
"str_attrs",
"=",
"{",
"}",
"if",
"attrs",
":",
"for",
"k",
",",
"v",
"in",
... | 35.2 | 13.733333 |
def get_token(opts, tok):
'''
Fetch the token data from the store.
:param opts: Salt master config options
:param tok: Token value to get
:returns: Token data if successful. Empty dict if failed.
'''
redis_client = _redis_client(opts)
if not redis_client:
return {}
serial = ... | [
"def",
"get_token",
"(",
"opts",
",",
"tok",
")",
":",
"redis_client",
"=",
"_redis_client",
"(",
"opts",
")",
"if",
"not",
"redis_client",
":",
"return",
"{",
"}",
"serial",
"=",
"salt",
".",
"payload",
".",
"Serial",
"(",
"opts",
")",
"try",
":",
"... | 27.619048 | 18.857143 |
def Generate(self, items, token=None):
"""Generates archive from a given collection.
Iterates the collection and generates an archive by yielding contents
of every referenced AFF4Stream.
Args:
items: Iterable with items that point to aff4 paths.
token: User's ACLToken.
Yields:
B... | [
"def",
"Generate",
"(",
"self",
",",
"items",
",",
"token",
"=",
"None",
")",
":",
"clients",
"=",
"set",
"(",
")",
"for",
"fd_urn_batch",
"in",
"collection",
".",
"Batch",
"(",
"self",
".",
"_ItemsToUrns",
"(",
"items",
")",
",",
"self",
".",
"BATCH... | 36.835294 | 22.529412 |
def __FieldDescriptorFromProperties(self, name, index, attrs):
"""Create a field descriptor for these attrs."""
field = descriptor.FieldDescriptor()
field.name = self.__names.CleanName(name)
field.number = index
field.label = self.__ComputeLabel(attrs)
new_type_name_hint ... | [
"def",
"__FieldDescriptorFromProperties",
"(",
"self",
",",
"name",
",",
"index",
",",
"attrs",
")",
":",
"field",
"=",
"descriptor",
".",
"FieldDescriptor",
"(",
")",
"field",
".",
"name",
"=",
"self",
".",
"__names",
".",
"CleanName",
"(",
"name",
")",
... | 51.076923 | 13.153846 |
def dec(self,*args,**kwargs):
"""
NAME:
dec
PURPOSE:
return the declination
INPUT:
t - (optional) time at which to get dec
obs=[X,Y,Z] - (optional) position of observer (in kpc)
(default=Object-wide default)
... | [
"def",
"dec",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"_check_roSet",
"(",
"self",
",",
"kwargs",
",",
"'dec'",
")",
"radec",
"=",
"self",
".",
"_radec",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"return",
"radec",... | 34.909091 | 16.545455 |
def keys(self):
"""Return iterable of columns used by this object."""
columns = set()
for name in vars(self):
if (not name) or name[0] == "_":
continue
columns.add(name)
return columns | [
"def",
"keys",
"(",
"self",
")",
":",
"columns",
"=",
"set",
"(",
")",
"for",
"name",
"in",
"vars",
"(",
"self",
")",
":",
"if",
"(",
"not",
"name",
")",
"or",
"name",
"[",
"0",
"]",
"==",
"\"_\"",
":",
"continue",
"columns",
".",
"add",
"(",
... | 26.625 | 15.5 |
def push_accepts_more(self):
"""Return whether a block of interactive input can accept more input.
This method is meant to be used by line-oriented frontends, who need to
guess whether a block is complete or not based solely on prior and
current input lines. The InputSplitter considers... | [
"def",
"push_accepts_more",
"(",
"self",
")",
":",
"# With incomplete input, unconditionally accept more",
"if",
"not",
"self",
".",
"_is_complete",
":",
"return",
"True",
"# If we already have complete input and we're flush left, the answer",
"# depends. In line mode, if there hasn... | 48.032258 | 24.193548 |
def find_node_modules_basedir(self):
"""
Find all node_modules directories configured to be accessible
through this driver instance.
This is typically used for adding the direct instance, and does
not traverse the parent directories like what Node.js does.
Returns a lis... | [
"def",
"find_node_modules_basedir",
"(",
"self",
")",
":",
"paths",
"=",
"[",
"]",
"# First do the working dir.",
"local_node_path",
"=",
"self",
".",
"join_cwd",
"(",
"NODE_MODULES",
")",
"if",
"isdir",
"(",
"local_node_path",
")",
":",
"paths",
".",
"append",
... | 31.8 | 21 |
def no_redirect(pattern, locale_prefix=True, re_flags=None):
"""
Return a url matcher that will stop the redirect middleware and force
Django to continue with regular URL matching. For use when you have a URL pattern
you want to serve, and a broad catch-all pattern you want to redirect.
:param patte... | [
"def",
"no_redirect",
"(",
"pattern",
",",
"locale_prefix",
"=",
"True",
",",
"re_flags",
"=",
"None",
")",
":",
"if",
"locale_prefix",
":",
"pattern",
"=",
"pattern",
".",
"lstrip",
"(",
"'^/'",
")",
"pattern",
"=",
"LOCALE_RE",
"+",
"pattern",
"if",
"r... | 40.090909 | 23.727273 |
def _parse_curves(block, **kwargs):
"""Parse nonlinear curves block."""
count = int(block.pop(0))
curves = []
for i in range(count):
for param in ['mod_reduc', 'damping']:
length, name = parse_fixed_width([(5, int), (65, to_str)], block)
curves.append(
si... | [
"def",
"_parse_curves",
"(",
"block",
",",
"*",
"*",
"kwargs",
")",
":",
"count",
"=",
"int",
"(",
"block",
".",
"pop",
"(",
"0",
")",
")",
"curves",
"=",
"[",
"]",
"for",
"i",
"in",
"range",
"(",
"count",
")",
":",
"for",
"param",
"in",
"[",
... | 38.315789 | 21 |
def CheckTaskToMerge(self, task):
"""Checks if the task should be merged.
Args:
task (Task): task.
Returns:
bool: True if the task should be merged.
Raises:
KeyError: if the task was not queued, processing or abandoned.
"""
with self._lock:
is_abandoned = task.identifi... | [
"def",
"CheckTaskToMerge",
"(",
"self",
",",
"task",
")",
":",
"with",
"self",
".",
"_lock",
":",
"is_abandoned",
"=",
"task",
".",
"identifier",
"in",
"self",
".",
"_tasks_abandoned",
"is_processing",
"=",
"task",
".",
"identifier",
"in",
"self",
".",
"_t... | 31.363636 | 23.818182 |
def json(self):
""" Return a JSON-serializable representation of this result.
The output of this function can be converted to a serialized string
with :any:`json.dumps`.
"""
return {
"status": self.status,
"criteria_name": self.criteria_name,
... | [
"def",
"json",
"(",
"self",
")",
":",
"return",
"{",
"\"status\"",
":",
"self",
".",
"status",
",",
"\"criteria_name\"",
":",
"self",
".",
"criteria_name",
",",
"\"warnings\"",
":",
"[",
"w",
".",
"json",
"(",
")",
"for",
"w",
"in",
"self",
".",
"war... | 33.666667 | 16.5 |
def _convert_markup_images(self, soup):
"""
Convert images of instructions markup. Images are downloaded,
base64-encoded and inserted into <img> tags.
@param soup: BeautifulSoup instance.
@type soup: BeautifulSoup
"""
# 6. Replace <img> assets with actual image c... | [
"def",
"_convert_markup_images",
"(",
"self",
",",
"soup",
")",
":",
"# 6. Replace <img> assets with actual image contents",
"images",
"=",
"[",
"image",
"for",
"image",
"in",
"soup",
".",
"find_all",
"(",
"'img'",
")",
"if",
"image",
".",
"attrs",
".",
"get",
... | 38.76 | 15.64 |
def say(self, event):
"""Chat event handler for incoming events
:param event: say-event with incoming chat message
"""
try:
userid = event.user.uuid
recipient = self._get_recipient(event)
content = self._get_content(event)
message = objec... | [
"def",
"say",
"(",
"self",
",",
"event",
")",
":",
"try",
":",
"userid",
"=",
"event",
".",
"user",
".",
"uuid",
"recipient",
"=",
"self",
".",
"_get_recipient",
"(",
"event",
")",
"content",
"=",
"self",
".",
"_get_content",
"(",
"event",
")",
"mess... | 34.236842 | 18.552632 |
def coffee_compile(source):
"""Compiles the given ``source`` from CoffeeScript to JavaScript"""
with open(COFFEE_COMPILER, 'rb') as coffeescript_js:
return evaljs(
(coffeescript_js.read().decode('utf-8'),
'CoffeeScript.compile(dukpy.coffeecode)'),
coffeecode=source
... | [
"def",
"coffee_compile",
"(",
"source",
")",
":",
"with",
"open",
"(",
"COFFEE_COMPILER",
",",
"'rb'",
")",
"as",
"coffeescript_js",
":",
"return",
"evaljs",
"(",
"(",
"coffeescript_js",
".",
"read",
"(",
")",
".",
"decode",
"(",
"'utf-8'",
")",
",",
"'C... | 40.125 | 14.5 |
def content_type(self, content_type):
"""Sets the content_type of this Notificant.
The value of the Content-Type header of the webhook POST request. # noqa: E501
:param content_type: The content_type of this Notificant. # noqa: E501
:type: str
"""
allowed_values = ["a... | [
"def",
"content_type",
"(",
"self",
",",
"content_type",
")",
":",
"allowed_values",
"=",
"[",
"\"application/json\"",
",",
"\"text/html\"",
",",
"\"text/plain\"",
",",
"\"application/x-www-form-urlencoded\"",
",",
"\"\"",
"]",
"# noqa: E501",
"if",
"content_type",
"n... | 42.6875 | 26.625 |
def contact_addresses(self):
"""
Provides a reference to contact addresses used by this server.
Obtain a reference to manipulate or iterate existing contact
addresses::
>>> from smc.elements.servers import ManagementServer
>>> mgt_server = Manage... | [
"def",
"contact_addresses",
"(",
"self",
")",
":",
"return",
"MultiContactAddress",
"(",
"href",
"=",
"self",
".",
"get_relation",
"(",
"'contact_addresses'",
")",
",",
"type",
"=",
"self",
".",
"typeof",
",",
"name",
"=",
"self",
".",
"name",
")"
] | 38 | 19.238095 |
def decrease_crypto_config(self, crypto_adapters,
crypto_domain_indexes):
"""
Remove crypto adapters and/or crypto domains from the crypto
configuration of this partition.
For the general principle for maintaining crypto configurations of
partition... | [
"def",
"decrease_crypto_config",
"(",
"self",
",",
"crypto_adapters",
",",
"crypto_domain_indexes",
")",
":",
"crypto_adapter_uris",
"=",
"[",
"a",
".",
"uri",
"for",
"a",
"in",
"crypto_adapters",
"]",
"body",
"=",
"{",
"'crypto-adapter-uris'",
":",
"crypto_adapte... | 43.162791 | 24.139535 |
def setQuery(self, query):
"""
Sets the query instance for this widget to the inputed query.
:param query | <orb.Query> || <orb.QueryCompound>
"""
if not query.isNull() and hash(query) == hash(self._query):
return
self._query = ... | [
"def",
"setQuery",
"(",
"self",
",",
"query",
")",
":",
"if",
"not",
"query",
".",
"isNull",
"(",
")",
"and",
"hash",
"(",
"query",
")",
"==",
"hash",
"(",
"self",
".",
"_query",
")",
":",
"return",
"self",
".",
"_query",
"=",
"query",
"if",
"Que... | 33.809524 | 16.47619 |
def read(path):
""" Reads a file located at the given path. """
data = None
with open(path, 'r') as f:
data = f.read()
f.close()
return data | [
"def",
"read",
"(",
"path",
")",
":",
"data",
"=",
"None",
"with",
"open",
"(",
"path",
",",
"'r'",
")",
"as",
"f",
":",
"data",
"=",
"f",
".",
"read",
"(",
")",
"f",
".",
"close",
"(",
")",
"return",
"data"
] | 23.142857 | 18.428571 |
def find_find_repos(where, ignore_error=True):
"""
Search for repositories with GNU find
Args:
where (str): path to search from
ignore_error (bool): if False, raise Exception when the returncode is
not zero.
Yields:
Repository subclass instance
"""
log.debug... | [
"def",
"find_find_repos",
"(",
"where",
",",
"ignore_error",
"=",
"True",
")",
":",
"log",
".",
"debug",
"(",
"(",
"'REPO_REGEX'",
",",
"REPO_REGEX",
")",
")",
"FIND_REPO_REGEXCMD",
"=",
"(",
"\"-regex\"",
",",
"'.*(%s)$'",
"%",
"REPO_REGEX",
")",
"if",
"o... | 32.333333 | 14.098039 |
def _check_submodule_no_git(self):
"""
Like ``_check_submodule_using_git``, but simply parses the .gitmodules file
to determine if the supplied path is a git submodule, and does not exec any
subprocesses.
This can only determine if a path is a submodule--it does not perform
... | [
"def",
"_check_submodule_no_git",
"(",
"self",
")",
":",
"gitmodules_path",
"=",
"os",
".",
"path",
".",
"abspath",
"(",
"'.gitmodules'",
")",
"if",
"not",
"os",
".",
"path",
".",
"isfile",
"(",
"gitmodules_path",
")",
":",
"return",
"False",
"# This is a mi... | 35.578947 | 22.877193 |
def _set_show_linkinfo(self, v, load=False):
"""
Setter method for show_linkinfo, mapped from YANG variable /brocade_fabric_service_rpc/show_linkinfo (rpc)
If this variable is read-only (config: false) in the
source YANG file, then _set_show_linkinfo is considered as a private
method. Backends looki... | [
"def",
"_set_show_linkinfo",
"(",
"self",
",",
"v",
",",
"load",
"=",
"False",
")",
":",
"if",
"hasattr",
"(",
"v",
",",
"\"_utype\"",
")",
":",
"v",
"=",
"v",
".",
"_utype",
"(",
"v",
")",
"try",
":",
"t",
"=",
"YANGDynClass",
"(",
"v",
",",
"... | 69.076923 | 32.923077 |
def _writeBk(target="sentenceContainsTarget(+SID,+WID).", treeDepth="3",
nodeSize="3", numOfClauses="8"):
"""
Writes a background file to disk.
:param target: Target predicate with modes.
:type target: str.
:param treeDepth: Depth of the tree.
:type treeDepth: str.
:param nodeS... | [
"def",
"_writeBk",
"(",
"target",
"=",
"\"sentenceContainsTarget(+SID,+WID).\"",
",",
"treeDepth",
"=",
"\"3\"",
",",
"nodeSize",
"=",
"\"3\"",
",",
"numOfClauses",
"=",
"\"8\"",
")",
":",
"with",
"open",
"(",
"'bk.txt'",
",",
"'w'",
")",
"as",
"bk",
":",
... | 39.075 | 19.675 |
def should_regenerate(self, response):
""" Check if this page was originally generated less than LOCAL_POSTCHECK seconds ago """
if response.has_header('Last-Modified'):
last_modified = parse_http_date(response['Last-Modified'])
next_regen = last_modified + settings.BETTERCACHE_... | [
"def",
"should_regenerate",
"(",
"self",
",",
"response",
")",
":",
"if",
"response",
".",
"has_header",
"(",
"'Last-Modified'",
")",
":",
"last_modified",
"=",
"parse_http_date",
"(",
"response",
"[",
"'Last-Modified'",
"]",
")",
"next_regen",
"=",
"last_modifi... | 53.285714 | 17.142857 |
def apply_conversation_reference(activity: Activity,
reference: ConversationReference,
is_incoming: bool=False) -> Activity:
"""
Updates an activity with the delivery information from a conversation reference. Calling
this... | [
"def",
"apply_conversation_reference",
"(",
"activity",
":",
"Activity",
",",
"reference",
":",
"ConversationReference",
",",
"is_incoming",
":",
"bool",
"=",
"False",
")",
"->",
"Activity",
":",
"activity",
".",
"channel_id",
"=",
"reference",
".",
"channel_id",
... | 41.925926 | 17.037037 |
def discover_yaml(bank=None, **meta):
"""Discovers the YAML format and registers it if available.
Install YAML support via PIP::
pip install PyYAML
:param bank: The format bank to register the format in
:param meta: Extra information associated with the format
"""
try:
import ... | [
"def",
"discover_yaml",
"(",
"bank",
"=",
"None",
",",
"*",
"*",
"meta",
")",
":",
"try",
":",
"import",
"yaml",
"if",
"bank",
"is",
"None",
":",
"bank",
"=",
"default_bank",
"bank",
".",
"register",
"(",
"'yaml'",
",",
"yaml",
".",
"load",
",",
"y... | 27.176471 | 19.058824 |
def _rd_dat_file(file_name, dir_name, pb_dir, fmt, start_byte, n_samp):
"""
Read data from a dat file, either local or remote, into a 1d numpy
array.
This is the lowest level dat reading function (along with
`_stream_dat` which this function may call), and is called by
`_rd_dat_signals`.
P... | [
"def",
"_rd_dat_file",
"(",
"file_name",
",",
"dir_name",
",",
"pb_dir",
",",
"fmt",
",",
"start_byte",
",",
"n_samp",
")",
":",
"# element_count is the number of elements to read using np.fromfile",
"# for local files",
"# byte_count is the number of bytes to read for streaming ... | 33.508475 | 23.305085 |
def format_parameters(params):
'''Reformat parameters into dict of format expected by the API.'''
if not params:
return {}
# expect multiple invocations of --parameters but fall back
# to ; delimited if only one --parameters is specified
if len(params) == 1:
if params[0].find(';') ... | [
"def",
"format_parameters",
"(",
"params",
")",
":",
"if",
"not",
"params",
":",
"return",
"{",
"}",
"# expect multiple invocations of --parameters but fall back",
"# to ; delimited if only one --parameters is specified",
"if",
"len",
"(",
"params",
")",
"==",
"1",
":",
... | 29.741935 | 19.225806 |
def listdir(self, target_directory):
"""Return a list of file names in target_directory.
Args:
target_directory: Path to the target directory within the
fake filesystem.
Returns:
A list of file names within the target directory in arbitrary
o... | [
"def",
"listdir",
"(",
"self",
",",
"target_directory",
")",
":",
"target_directory",
"=",
"self",
".",
"resolve_path",
"(",
"target_directory",
",",
"allow_fd",
"=",
"True",
")",
"directory",
"=",
"self",
".",
"confirmdir",
"(",
"target_directory",
")",
"dire... | 34.388889 | 20.5 |
def formatDecimalMark(value, decimalmark='.'):
"""
Dummy method to replace decimal mark from an input string.
Assumes that 'value' uses '.' as decimal mark and ',' as
thousand mark.
::value:: is a string
::returns:: is a string with the decimal mark if needed
"""
# We... | [
"def",
"formatDecimalMark",
"(",
"value",
",",
"decimalmark",
"=",
"'.'",
")",
":",
"# We have to consider the possibility of working with decimals such as",
"# X.000 where those decimals are important because of the precission",
"# and significant digits matters",
"# Using 'float' the sys... | 40.35 | 18.85 |
def run_multiple_commands_redirect_stdout(
multiple_args_dict,
print_commands=True,
process_limit=-1,
polling_freq=0.5,
**kwargs):
"""
Run multiple shell commands in parallel, write each of their
stdout output to files associated with each command.
Parameters
... | [
"def",
"run_multiple_commands_redirect_stdout",
"(",
"multiple_args_dict",
",",
"print_commands",
"=",
"True",
",",
"process_limit",
"=",
"-",
"1",
",",
"polling_freq",
"=",
"0.5",
",",
"*",
"*",
"kwargs",
")",
":",
"assert",
"len",
"(",
"multiple_args_dict",
")... | 33.950617 | 16.493827 |
def rmon_event_entry_log(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
rmon = ET.SubElement(config, "rmon", xmlns="urn:brocade.com:mgmt:brocade-rmon")
event_entry = ET.SubElement(rmon, "event-entry")
event_index_key = ET.SubElement(event_entry,... | [
"def",
"rmon_event_entry_log",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"config",
"=",
"ET",
".",
"Element",
"(",
"\"config\"",
")",
"rmon",
"=",
"ET",
".",
"SubElement",
"(",
"config",
",",
"\"rmon\"",
",",
"xmlns",
"=",
"\"urn:brocade.com:mgmt:bro... | 43.333333 | 15.25 |
def _refresh_token(self):
"""
Retrieves the OAuth2 token generated by the user's API key and API secret.
Sets the instance property 'token' to this new token.
If the current token is still live, the server will simply return that.
"""
# use basic auth with API key and se... | [
"def",
"_refresh_token",
"(",
"self",
")",
":",
"# use basic auth with API key and secret",
"client_auth",
"=",
"requests",
".",
"auth",
".",
"HTTPBasicAuth",
"(",
"self",
".",
"api_key",
",",
"self",
".",
"api_secret",
")",
"# make request",
"post_data",
"=",
"{"... | 49.8 | 27.8 |
def decode_payload(self, specialize = False):
"""Decode payload from the element passed to the stanza constructor.
Iterates over stanza children and creates StanzaPayload objects for
them. Called automatically by `get_payload()` and other methods that
access the payload.
For th... | [
"def",
"decode_payload",
"(",
"self",
",",
"specialize",
"=",
"False",
")",
":",
"if",
"self",
".",
"_payload",
"is",
"not",
"None",
":",
"# already decoded",
"return",
"if",
"self",
".",
"_element",
"is",
"None",
":",
"raise",
"ValueError",
"(",
"\"This s... | 38.923077 | 15.5 |
def GET_AUTH(self, courseid): # pylint: disable=arguments-differ
""" GET request """
course, _ = self.get_course_and_check_rights(courseid)
return self.page(course) | [
"def",
"GET_AUTH",
"(",
"self",
",",
"courseid",
")",
":",
"# pylint: disable=arguments-differ",
"course",
",",
"_",
"=",
"self",
".",
"get_course_and_check_rights",
"(",
"courseid",
")",
"return",
"self",
".",
"page",
"(",
"course",
")"
] | 46.5 | 13.75 |
def dump(self, full=True, redact=False):
"""Dump the Configuration object to a YAML file.
The order of the keys is determined from the default
configuration file. All keys not in the default configuration
will be appended to the end of the file.
:param filename: The file to du... | [
"def",
"dump",
"(",
"self",
",",
"full",
"=",
"True",
",",
"redact",
"=",
"False",
")",
":",
"if",
"full",
":",
"out_dict",
"=",
"self",
".",
"flatten",
"(",
"redact",
"=",
"redact",
")",
"else",
":",
"# Exclude defaults when flattening.",
"sources",
"="... | 41.268293 | 17.585366 |
def make_model(corpus, lemmatize=False, rm_stops=False, size=100, window=10, min_count=5, workers=4, sg=1,
save_path=None):
"""Train W2V model."""
# Simple training, with one large list
t0 = time.time()
sentences_stream = gen_docs(corpus, lemmatize=lemmatize, rm_stops=rm_stops)
# se... | [
"def",
"make_model",
"(",
"corpus",
",",
"lemmatize",
"=",
"False",
",",
"rm_stops",
"=",
"False",
",",
"size",
"=",
"100",
",",
"window",
"=",
"10",
",",
"min_count",
"=",
"5",
",",
"workers",
"=",
"4",
",",
"sg",
"=",
"1",
",",
"save_path",
"=",
... | 36.73913 | 27.521739 |
def hpd_credible_interval(mu_in, post, alpha=0.9, tolerance=1e-3):
'''
Returns the minimum and maximum rate values of the HPD
(Highest Posterior Density) credible interval for a posterior
post defined at the sample values mu_in. Samples need not be
uniformly spaced and posterior need not be normali... | [
"def",
"hpd_credible_interval",
"(",
"mu_in",
",",
"post",
",",
"alpha",
"=",
"0.9",
",",
"tolerance",
"=",
"1e-3",
")",
":",
"if",
"alpha",
"==",
"1",
":",
"nonzero_samples",
"=",
"mu_in",
"[",
"post",
">",
"0",
"]",
"mu_low",
"=",
"numpy",
".",
"mi... | 42.72 | 19.76 |
def push_activations(activations, from_layer, to_layer):
"""Push activations from one model to another using prerecorded correlations"""
inverse_covariance_matrix = layer_inverse_covariance(from_layer)
activations_decorrelated = np.dot(inverse_covariance_matrix, activations.T).T
covariance_matrix = laye... | [
"def",
"push_activations",
"(",
"activations",
",",
"from_layer",
",",
"to_layer",
")",
":",
"inverse_covariance_matrix",
"=",
"layer_inverse_covariance",
"(",
"from_layer",
")",
"activations_decorrelated",
"=",
"np",
".",
"dot",
"(",
"inverse_covariance_matrix",
",",
... | 66.428571 | 22 |
def legacy_events_view(request):
"""
View to see legacy events.
"""
events = TeacherEvent.objects.all()
event_count = events.count()
paginator = Paginator(events, 100)
page = request.GET.get('page')
try:
events = paginator.page(page)
except PageNotAnInteger:
events =... | [
"def",
"legacy_events_view",
"(",
"request",
")",
":",
"events",
"=",
"TeacherEvent",
".",
"objects",
".",
"all",
"(",
")",
"event_count",
"=",
"events",
".",
"count",
"(",
")",
"paginator",
"=",
"Paginator",
"(",
"events",
",",
"100",
")",
"page",
"=",
... | 27.909091 | 10.909091 |
def _generate_walks(self):
"""
Generates the random walks which will be used as the skip-gram input.
:return: List of walks. Each walk is a list of nodes.
"""
flatten = lambda l: [item for sublist in l for item in sublist]
# Split num_walks for each worker
num_w... | [
"def",
"_generate_walks",
"(",
"self",
")",
":",
"flatten",
"=",
"lambda",
"l",
":",
"[",
"item",
"for",
"sublist",
"in",
"l",
"for",
"item",
"in",
"sublist",
"]",
"# Split num_walks for each worker",
"num_walks_lists",
"=",
"np",
".",
"array_split",
"(",
"r... | 44.62069 | 23.931034 |
def update_user(self, id, **kwargs): # noqa: E501
"""Update user with given user groups and permissions. # noqa: E501
# noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.updat... | [
"def",
"update_user",
"(",
"self",
",",
"id",
",",
"*",
"*",
"kwargs",
")",
":",
"# noqa: E501",
"kwargs",
"[",
"'_return_http_data_only'",
"]",
"=",
"True",
"if",
"kwargs",
".",
"get",
"(",
"'async_req'",
")",
":",
"return",
"self",
".",
"update_user_with... | 48.5 | 25.090909 |
def execute_command(self):
"""
The web command runs the Scrapple web interface through a simple \
`Flask <http://flask.pocoo.org>`_ app.
When the execute_command() method is called from the \
:ref:`runCLI() <implementation-cli>` function, it starts of two simultaneous \
... | [
"def",
"execute_command",
"(",
"self",
")",
":",
"print",
"(",
"Back",
".",
"GREEN",
"+",
"Fore",
".",
"BLACK",
"+",
"\"Scrapple Web Interface\"",
")",
"print",
"(",
"Back",
".",
"RESET",
"+",
"Fore",
".",
"RESET",
")",
"p1",
"=",
"Process",
"(",
"targ... | 46.310345 | 27.62069 |
def copy(src, dst, symlink=False, rellink=False):
"""Copy or symlink the file."""
func = os.symlink if symlink else shutil.copy2
if symlink and os.path.lexists(dst):
os.remove(dst)
if rellink: # relative symlink from dst
func(os.path.relpath(src, os.path.dirname(dst)), dst)
else:
... | [
"def",
"copy",
"(",
"src",
",",
"dst",
",",
"symlink",
"=",
"False",
",",
"rellink",
"=",
"False",
")",
":",
"func",
"=",
"os",
".",
"symlink",
"if",
"symlink",
"else",
"shutil",
".",
"copy2",
"if",
"symlink",
"and",
"os",
".",
"path",
".",
"lexist... | 36.888889 | 12.333333 |
def get_private_room_history(self, room_id, oldest=None, **kwargs):
"""
Get various history of specific private group in this case private
:param room_id:
:param kwargs:
:return:
"""
return GetPrivateRoomHistory(settings=self.settings, **kwargs).call(
... | [
"def",
"get_private_room_history",
"(",
"self",
",",
"room_id",
",",
"oldest",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"GetPrivateRoomHistory",
"(",
"settings",
"=",
"self",
".",
"settings",
",",
"*",
"*",
"kwargs",
")",
".",
"call",
"(... | 29.461538 | 21 |
def whichchain(atom):
"""Returns the residue number of an PyBel or OpenBabel atom."""
atom = atom if not isinstance(atom, Atom) else atom.OBAtom # Convert to OpenBabel Atom
return atom.GetResidue().GetChain() if atom.GetResidue() is not None else None | [
"def",
"whichchain",
"(",
"atom",
")",
":",
"atom",
"=",
"atom",
"if",
"not",
"isinstance",
"(",
"atom",
",",
"Atom",
")",
"else",
"atom",
".",
"OBAtom",
"# Convert to OpenBabel Atom",
"return",
"atom",
".",
"GetResidue",
"(",
")",
".",
"GetChain",
"(",
... | 65.25 | 28 |
def all(self):
r"""Returns all content in this node, regardless of whitespace or
not. This includes all LaTeX needed to reconstruct the original source.
>>> from TexSoup import TexSoup
>>> soup = TexSoup(r'''
... \newcommand{reverseconcat}[3]{#3#2#1}
... ''')
>>>... | [
"def",
"all",
"(",
"self",
")",
":",
"for",
"child",
"in",
"self",
".",
"expr",
".",
"all",
":",
"if",
"isinstance",
"(",
"child",
",",
"TexExpr",
")",
":",
"node",
"=",
"TexNode",
"(",
"child",
")",
"node",
".",
"parent",
"=",
"self",
"yield",
"... | 34.166667 | 13.722222 |
def as_dict(self):
"""Return the configuration as a dict"""
dictionary = {}
for section in self.parser.sections():
dictionary[section] = {}
for option in self.parser.options(section):
dictionary[section][option] = self.parser.get(section, option)
r... | [
"def",
"as_dict",
"(",
"self",
")",
":",
"dictionary",
"=",
"{",
"}",
"for",
"section",
"in",
"self",
".",
"parser",
".",
"sections",
"(",
")",
":",
"dictionary",
"[",
"section",
"]",
"=",
"{",
"}",
"for",
"option",
"in",
"self",
".",
"parser",
"."... | 41.125 | 14.625 |
def generate_calculus_integrate_sample(vlist, ops, min_depth, max_depth,
functions):
"""Randomly generate a symbolic integral dataset sample.
Given an input expression, produce the indefinite integral.
Args:
vlist: Variable list. List of chars that can be used in the e... | [
"def",
"generate_calculus_integrate_sample",
"(",
"vlist",
",",
"ops",
",",
"min_depth",
",",
"max_depth",
",",
"functions",
")",
":",
"var_index",
"=",
"random",
".",
"randrange",
"(",
"len",
"(",
"vlist",
")",
")",
"var",
"=",
"vlist",
"[",
"var_index",
... | 43.205882 | 24.235294 |
def work_request(self, worker_name, md5, subkeys=None):
""" Make a work request for an existing stored sample.
Args:
worker_name: 'strings', 'pe_features', whatever
md5: the md5 of the sample (or sample_set!)
subkeys: just get a subkey of the output: '... | [
"def",
"work_request",
"(",
"self",
",",
"worker_name",
",",
"md5",
",",
"subkeys",
"=",
"None",
")",
":",
"# Pull the worker output",
"work_results",
"=",
"self",
".",
"_recursive_work_resolver",
"(",
"worker_name",
",",
"md5",
")",
"# Subkeys (Fixme this is super ... | 36.5 | 17.571429 |
def checkInstrumentsValidity(self):
"""Checks the validity of the instruments used in the Analyses If an
analysis with an invalid instrument (out-of-date or with calibration
tests failed) is found, a warn message will be displayed.
"""
invalid = []
ans = self.context.getA... | [
"def",
"checkInstrumentsValidity",
"(",
"self",
")",
":",
"invalid",
"=",
"[",
"]",
"ans",
"=",
"self",
".",
"context",
".",
"getAnalyses",
"(",
")",
"for",
"an",
"in",
"ans",
":",
"valid",
"=",
"an",
".",
"isInstrumentValid",
"(",
")",
"if",
"not",
... | 47.7 | 15.15 |
def path_file_to_list(path_file):
"""
:return: A list with the paths which are stored in a text file in a line-by-
line format. Validate each path using is_valid_path
"""
paths = []
path_file_fd = file(path_file)
for line_no, line in enumerate(path_file_fd.readlines(), start=1):
... | [
"def",
"path_file_to_list",
"(",
"path_file",
")",
":",
"paths",
"=",
"[",
"]",
"path_file_fd",
"=",
"file",
"(",
"path_file",
")",
"for",
"line_no",
",",
"line",
"in",
"enumerate",
"(",
"path_file_fd",
".",
"readlines",
"(",
")",
",",
"start",
"=",
"1",... | 26.444444 | 20 |
def get_marker(self, increment=1):
"""
Returns the current marker, then increments the marker by what's specified
"""
i = self.markers_index
self.markers_index += increment
if self.markers_index >= len(self.markers):
self.markers_index = self.markers_index-l... | [
"def",
"get_marker",
"(",
"self",
",",
"increment",
"=",
"1",
")",
":",
"i",
"=",
"self",
".",
"markers_index",
"self",
".",
"markers_index",
"+=",
"increment",
"if",
"self",
".",
"markers_index",
">=",
"len",
"(",
"self",
".",
"markers",
")",
":",
"se... | 34.307692 | 21.384615 |
def _handle_offset_response(self, response):
"""
Handle responses to both OffsetRequest and OffsetFetchRequest, since
they are similar enough.
:param response:
A tuple of a single OffsetFetchResponse or OffsetResponse
"""
# Got a response, clear our outstandi... | [
"def",
"_handle_offset_response",
"(",
"self",
",",
"response",
")",
":",
"# Got a response, clear our outstanding request deferred",
"self",
".",
"_request_d",
"=",
"None",
"# Successful request, reset our retry delay, count, etc",
"self",
".",
"retry_delay",
"=",
"self",
".... | 39.172414 | 17.241379 |
def summary(self):
"""Summary statistics describing the fit.
Set alpha property in the object before calling.
Returns
-------
df : DataFrame
Contains columns coef, np.exp(coef), se(coef), z, p, lower, upper"""
ci = 1 - self.alpha
with np.errstate(inva... | [
"def",
"summary",
"(",
"self",
")",
":",
"ci",
"=",
"1",
"-",
"self",
".",
"alpha",
"with",
"np",
".",
"errstate",
"(",
"invalid",
"=",
"\"ignore\"",
",",
"divide",
"=",
"\"ignore\"",
")",
":",
"df",
"=",
"pd",
".",
"DataFrame",
"(",
"index",
"=",
... | 42.3 | 16.25 |
def update_user(self, user, name=None, password=None, host=None):
"""
Allows you to change one or more of the user's username, password, or
host.
"""
return self._user_manager.update(user, name=name, password=password,
host=host) | [
"def",
"update_user",
"(",
"self",
",",
"user",
",",
"name",
"=",
"None",
",",
"password",
"=",
"None",
",",
"host",
"=",
"None",
")",
":",
"return",
"self",
".",
"_user_manager",
".",
"update",
"(",
"user",
",",
"name",
"=",
"name",
",",
"password",... | 39.857143 | 19.857143 |
def get_methods(self):
"""
Return all method objects
:rtype: a list of :class:`EncodedMethod` objects
"""
l = []
for i in self.classes.class_def:
for j in i.get_methods():
l.append(j)
return l | [
"def",
"get_methods",
"(",
"self",
")",
":",
"l",
"=",
"[",
"]",
"for",
"i",
"in",
"self",
".",
"classes",
".",
"class_def",
":",
"for",
"j",
"in",
"i",
".",
"get_methods",
"(",
")",
":",
"l",
".",
"append",
"(",
"j",
")",
"return",
"l"
] | 24.636364 | 13.363636 |
def getUrlMeta(self, url):
"""
Retrieve various metadata associated with a URL, as seen by Skype.
Args:
url (str): address to ping for info
Returns:
dict: metadata for the website queried
"""
return self.conn("GET", SkypeConnection.API_URL, param... | [
"def",
"getUrlMeta",
"(",
"self",
",",
"url",
")",
":",
"return",
"self",
".",
"conn",
"(",
"\"GET\"",
",",
"SkypeConnection",
".",
"API_URL",
",",
"params",
"=",
"{",
"\"url\"",
":",
"url",
"}",
",",
"auth",
"=",
"SkypeConnection",
".",
"Auth",
".",
... | 32.75 | 21.75 |
def convexHull(self,
geometries,
sr=None):
"""
The convexHull operation is performed on a geometry service resource.
It returns the convex hull of the input geometry. The input geometry can
be a point, multipoint, polyline, or polygon. The convex h... | [
"def",
"convexHull",
"(",
"self",
",",
"geometries",
",",
"sr",
"=",
"None",
")",
":",
"url",
"=",
"self",
".",
"_url",
"+",
"\"/convexHull\"",
"params",
"=",
"{",
"\"f\"",
":",
"\"json\"",
"}",
"if",
"isinstance",
"(",
"geometries",
",",
"list",
")",
... | 46.365854 | 23.243902 |
def _bind_parameter(self, parameter, value):
"""Assigns a parameter value to matching instructions in-place."""
for (instr, param_index) in self._parameter_table[parameter]:
instr.params[param_index] = value | [
"def",
"_bind_parameter",
"(",
"self",
",",
"parameter",
",",
"value",
")",
":",
"for",
"(",
"instr",
",",
"param_index",
")",
"in",
"self",
".",
"_parameter_table",
"[",
"parameter",
"]",
":",
"instr",
".",
"params",
"[",
"param_index",
"]",
"=",
"value... | 58 | 9.5 |
def do_request(self, method, params=None):
"""Make request to Zabbix API.
:type method: str
:param method: ZabbixAPI method, like: `apiinfo.version`.
:type params: str
:param params: ZabbixAPI method arguments.
>>> from pyzabbix import ZabbixAPI
>>> z = ZabbixA... | [
"def",
"do_request",
"(",
"self",
",",
"method",
",",
"params",
"=",
"None",
")",
":",
"request_json",
"=",
"{",
"'jsonrpc'",
":",
"'2.0'",
",",
"'method'",
":",
"method",
",",
"'params'",
":",
"params",
"or",
"{",
"}",
",",
"'id'",
":",
"'1'",
",",
... | 30.722222 | 18.185185 |
def hax(self):
"""
Returns the histogram axes, creating it only on demand.
"""
if make_axes_locatable is None:
raise YellowbrickValueError((
"residuals histogram requires matplotlib 2.0.2 or greater "
"please upgrade matplotlib or set hist=Fals... | [
"def",
"hax",
"(",
"self",
")",
":",
"if",
"make_axes_locatable",
"is",
"None",
":",
"raise",
"YellowbrickValueError",
"(",
"(",
"\"residuals histogram requires matplotlib 2.0.2 or greater \"",
"\"please upgrade matplotlib or set hist=False on the visualizer\"",
")",
")",
"divi... | 32.294118 | 20.647059 |
def build(self, builder):
"""
Build XML by appending to builder
"""
if self.text is None:
raise ValueError("Text is not set.")
params = {}
if self.sponsor_or_site is not None:
params['SponsorOrSite'] = self.sponsor_or_site
builder.start("C... | [
"def",
"build",
"(",
"self",
",",
"builder",
")",
":",
"if",
"self",
".",
"text",
"is",
"None",
":",
"raise",
"ValueError",
"(",
"\"Text is not set.\"",
")",
"params",
"=",
"{",
"}",
"if",
"self",
".",
"sponsor_or_site",
"is",
"not",
"None",
":",
"para... | 29.769231 | 10.538462 |
def plot_residuals(self, plot=None):
""" Plot normalized fit residuals.
The sum of the squares of the residuals equals ``self.chi2``.
Individual residuals should be distributed about one, in
a Gaussian distribution.
Args:
plot: :mod:`matplotlib` plotter. If ``None``... | [
"def",
"plot_residuals",
"(",
"self",
",",
"plot",
"=",
"None",
")",
":",
"if",
"plot",
"is",
"None",
":",
"import",
"matplotlib",
".",
"pyplot",
"as",
"plot",
"x",
"=",
"numpy",
".",
"arange",
"(",
"1",
",",
"len",
"(",
"self",
".",
"residuals",
"... | 33.592593 | 16.148148 |
def discover(timeout=1, retries=1):
"""Discover Raumfeld devices in the network
:param timeout: The timeout in seconds
:param retries: How often the search should be retried
:returns: A list of raumfeld devices, sorted by name
"""
locations = []
group = ('239.255.255.250', 1900)
... | [
"def",
"discover",
"(",
"timeout",
"=",
"1",
",",
"retries",
"=",
"1",
")",
":",
"locations",
"=",
"[",
"]",
"group",
"=",
"(",
"'239.255.255.250'",
",",
"1900",
")",
"service",
"=",
"'ssdp:urn:schemas-upnp-org:device:MediaRenderer:1'",
"# 'ssdp:all'",
"message"... | 40.488889 | 18.088889 |
def make_command(self, ctx, name, info):
"""
make click sub-command from command info
gotten from xbahn engineer
"""
@self.command()
@click.option("--debug/--no-debug", default=False, help="Show debug information")
@doc(info.get("description"))
def func(... | [
"def",
"make_command",
"(",
"self",
",",
"ctx",
",",
"name",
",",
"info",
")",
":",
"@",
"self",
".",
"command",
"(",
")",
"@",
"click",
".",
"option",
"(",
"\"--debug/--no-debug\"",
",",
"default",
"=",
"False",
",",
"help",
"=",
"\"Show debug informati... | 32.964286 | 16.392857 |
def _upsample(self, method, limit=None, fill_value=None):
"""
Parameters
----------
method : string {'backfill', 'bfill', 'pad', 'ffill'}
method for upsampling
limit : int, default None
Maximum size gap to fill when reindexing
fill_value : scalar, ... | [
"def",
"_upsample",
"(",
"self",
",",
"method",
",",
"limit",
"=",
"None",
",",
"fill_value",
"=",
"None",
")",
":",
"# we may need to actually resample as if we are timestamps",
"if",
"self",
".",
"kind",
"==",
"'timestamp'",
":",
"return",
"super",
"(",
")",
... | 30.470588 | 18.823529 |
def allowed(self) -> Set[int]:
"""
Returns the set of constrained words that could follow this one.
For unfinished phrasal constraints, it is the next word in the phrase.
In other cases, it is the list of all unmet constraints.
If all constraints are met, an empty set is returned... | [
"def",
"allowed",
"(",
"self",
")",
"->",
"Set",
"[",
"int",
"]",
":",
"items",
"=",
"set",
"(",
")",
"# type: Set[int]",
"# Add extensions of a started-but-incomplete sequential constraint",
"if",
"self",
".",
"last_met",
"!=",
"-",
"1",
"and",
"self",
".",
"... | 45.541667 | 23.291667 |
def warn(msg,level=2,exit_val=1):
"""Standard warning printer. Gives formatting consistency.
Output is sent to io.stderr (sys.stderr by default).
Options:
-level(2): allows finer control:
0 -> Do nothing, dummy function.
1 -> Print message.
2 -> Print 'WARNING:' + message. (Default ... | [
"def",
"warn",
"(",
"msg",
",",
"level",
"=",
"2",
",",
"exit_val",
"=",
"1",
")",
":",
"if",
"level",
">",
"0",
":",
"header",
"=",
"[",
"''",
",",
"''",
",",
"'WARNING: '",
",",
"'ERROR: '",
",",
"'FATAL ERROR: '",
"]",
"io",
".",
"stderr",
"."... | 33.217391 | 19.26087 |
def windowed_run_count(da, window, dim='time'):
"""Return the number of consecutive true values in array for runs at least as long as given duration.
Parameters
----------
da: N-dimensional Xarray data array (boolean)
Input data array
window : int
Minimum run le... | [
"def",
"windowed_run_count",
"(",
"da",
",",
"window",
",",
"dim",
"=",
"'time'",
")",
":",
"d",
"=",
"rle",
"(",
"da",
",",
"dim",
"=",
"dim",
")",
"out",
"=",
"d",
".",
"where",
"(",
"d",
">=",
"window",
",",
"0",
")",
".",
"sum",
"(",
"dim... | 33 | 19.952381 |
def enroll_users_in_program(cls, enterprise_customer, program_details, course_mode, emails, cohort=None):
"""
Enroll existing users in all courses in a program, and create pending enrollments for nonexisting users.
Args:
enterprise_customer: The EnterpriseCustomer which is sponsorin... | [
"def",
"enroll_users_in_program",
"(",
"cls",
",",
"enterprise_customer",
",",
"program_details",
",",
"course_mode",
",",
"emails",
",",
"cohort",
"=",
"None",
")",
":",
"existing_users",
",",
"unregistered_emails",
"=",
"cls",
".",
"get_users_by_email",
"(",
"em... | 42.775 | 28.025 |
def to_XML(self, xml_declaration=True, xmlns=True):
"""
Dumps object fields to an XML-formatted string. The 'xml_declaration'
switch enables printing of a leading standard XML line containing XML
version and encoding. The 'xmlns' switch enables printing of qualified
XMLNS prefix... | [
"def",
"to_XML",
"(",
"self",
",",
"xml_declaration",
"=",
"True",
",",
"xmlns",
"=",
"True",
")",
":",
"root_node",
"=",
"self",
".",
"_to_DOM",
"(",
")",
"if",
"xmlns",
":",
"xmlutils",
".",
"annotate_with_XMLNS",
"(",
"root_node",
",",
"OZONE_XMLNS_PREF... | 42.285714 | 20.095238 |
def sever_sink_ports(self, context, ports, connected_to=None):
# type: (AContext, APortMap, str) -> None
"""Conditionally sever Sink Ports of the child. If connected_to
is then None then sever all, otherwise restrict to connected_to's
Source Ports
Args:
context (Cont... | [
"def",
"sever_sink_ports",
"(",
"self",
",",
"context",
",",
"ports",
",",
"connected_to",
"=",
"None",
")",
":",
"# type: (AContext, APortMap, str) -> None",
"# Find the Source Ports to connect to",
"if",
"connected_to",
":",
"# Calculate a lookup of the Source Port \"name\" t... | 43.903226 | 18.741935 |
def vcfheader(data, names, ofile):
"""
Prints header for vcf files
"""
## choose reference string
if data.paramsdict["reference_sequence"]:
reference = data.paramsdict["reference_sequence"]
else:
reference = "pseudo-reference (most common base at site)"
##FILTER=<ID=minCov,... | [
"def",
"vcfheader",
"(",
"data",
",",
"names",
",",
"ofile",
")",
":",
"## choose reference string",
"if",
"data",
".",
"paramsdict",
"[",
"\"reference_sequence\"",
"]",
":",
"reference",
"=",
"data",
".",
"paramsdict",
"[",
"\"reference_sequence\"",
"]",
"else"... | 38.454545 | 18.727273 |
def linked_model_for_class(self, cls, make_constants_variable=False, **kwargs):
"""
Create a PriorModel wrapping the specified class with attributes from this instance. Priors can be overridden
using keyword arguments. Any constructor arguments of the new class for which there is no attribute as... | [
"def",
"linked_model_for_class",
"(",
"self",
",",
"cls",
",",
"make_constants_variable",
"=",
"False",
",",
"*",
"*",
"kwargs",
")",
":",
"constructor_args",
"=",
"inspect",
".",
"getfullargspec",
"(",
"cls",
")",
".",
"args",
"attribute_tuples",
"=",
"self",... | 50.538462 | 27.717949 |
def Aitken(s):
"""Accelerate the convergence of the a series
using Aitken's delta-squared process (SCIP calls it Euler).
"""
def accel():
s0, s1, s2 = s >> item[:3]
while 1:
yield s2 - (s2 - s1)**2 / (s0 - 2*s1 + s2)
s0, s1, s2 = s1, s2, next(s)
return accel() | [
"def",
"Aitken",
"(",
"s",
")",
":",
"def",
"accel",
"(",
")",
":",
"s0",
",",
"s1",
",",
"s2",
"=",
"s",
">>",
"item",
"[",
":",
"3",
"]",
"while",
"1",
":",
"yield",
"s2",
"-",
"(",
"s2",
"-",
"s1",
")",
"**",
"2",
"/",
"(",
"s0",
"-"... | 26.6 | 15.4 |
def print_meta(ds, ds_path=None):
"Prints meta data for subjects in given dataset."
print('\n#' + ds_path)
for sub, cls in ds.classes.items():
print('{},{}'.format(sub, cls))
return | [
"def",
"print_meta",
"(",
"ds",
",",
"ds_path",
"=",
"None",
")",
":",
"print",
"(",
"'\\n#'",
"+",
"ds_path",
")",
"for",
"sub",
",",
"cls",
"in",
"ds",
".",
"classes",
".",
"items",
"(",
")",
":",
"print",
"(",
"'{},{}'",
".",
"format",
"(",
"s... | 25 | 18.25 |
def __set_clear_button_visibility(self, text):
"""
Sets the clear button visibility.
:param text: Current field text.
:type text: QString
"""
if text:
self.__clear_button.show()
else:
self.__clear_button.hide() | [
"def",
"__set_clear_button_visibility",
"(",
"self",
",",
"text",
")",
":",
"if",
"text",
":",
"self",
".",
"__clear_button",
".",
"show",
"(",
")",
"else",
":",
"self",
".",
"__clear_button",
".",
"hide",
"(",
")"
] | 23.416667 | 12.916667 |
def construct(parent=None, defaults=None, **kwargs):
"""
Random variable constructor.
Args:
cdf:
Cumulative distribution function. Optional if ``parent`` is used.
bnd:
Boundary interval. Optional if ``parent`` is used.
parent (Dist):
Distribution ... | [
"def",
"construct",
"(",
"parent",
"=",
"None",
",",
"defaults",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"for",
"key",
"in",
"kwargs",
":",
"assert",
"key",
"in",
"LEGAL_ATTRS",
",",
"\"{} is not legal input\"",
".",
"format",
"(",
"key",
")",
... | 31.439394 | 19.893939 |
def fetch(self):
"""
Fetch a ExecutionStepInstance
:returns: Fetched ExecutionStepInstance
:rtype: twilio.rest.studio.v1.flow.execution.execution_step.ExecutionStepInstance
"""
params = values.of({})
payload = self._version.fetch(
'GET',
... | [
"def",
"fetch",
"(",
"self",
")",
":",
"params",
"=",
"values",
".",
"of",
"(",
"{",
"}",
")",
"payload",
"=",
"self",
".",
"_version",
".",
"fetch",
"(",
"'GET'",
",",
"self",
".",
"_uri",
",",
"params",
"=",
"params",
",",
")",
"return",
"Execu... | 26.818182 | 18 |
def register_job(self, job_details):
"""Register a job in this `JobArchive` """
# check to see if the job already exists
try:
job_details_old = self.get_details(job_details.jobname,
job_details.jobkey)
if job_details_old.stat... | [
"def",
"register_job",
"(",
"self",
",",
"job_details",
")",
":",
"# check to see if the job already exists",
"try",
":",
"job_details_old",
"=",
"self",
".",
"get_details",
"(",
"job_details",
".",
"jobname",
",",
"job_details",
".",
"jobkey",
")",
"if",
"job_det... | 49.105263 | 15.421053 |
def create_docker_credentials_file(
username,
password,
file_name='docker.tar.gz'):
""" Create a docker credentials file.
Docker username and password are used to create a `{file_name}`
with `.docker/config.json` containing the credentials.
:param username: docker us... | [
"def",
"create_docker_credentials_file",
"(",
"username",
",",
"password",
",",
"file_name",
"=",
"'docker.tar.gz'",
")",
":",
"import",
"base64",
"auth_hash",
"=",
"base64",
".",
"b64encode",
"(",
"'{}:{}'",
".",
"format",
"(",
"username",
",",
"password",
")",... | 30.404762 | 19.02381 |
def _readable(self):
"""The readable parsed article"""
if not self.candidates:
logger.info("No candidates found in document.")
return self._handle_no_candidates()
# right now we return the highest scoring candidate content
best_candidates = sorted(
(c... | [
"def",
"_readable",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"candidates",
":",
"logger",
".",
"info",
"(",
"\"No candidates found in document.\"",
")",
"return",
"self",
".",
"_handle_no_candidates",
"(",
")",
"# right now we return the highest scoring candid... | 40.571429 | 19.035714 |
def validate_get_arguments(kwargs):
# type: (Dict[Text, Any]) -> None
"""Verify that attribute filtering parameters are not found in the request.
:raises InvalidArgumentError: if banned parameters are found
"""
for arg in ("AttributesToGet", "ProjectionExpression"):
if arg in kwargs:
... | [
"def",
"validate_get_arguments",
"(",
"kwargs",
")",
":",
"# type: (Dict[Text, Any]) -> None",
"for",
"arg",
"in",
"(",
"\"AttributesToGet\"",
",",
"\"ProjectionExpression\"",
")",
":",
"if",
"arg",
"in",
"kwargs",
":",
"raise",
"InvalidArgumentError",
"(",
"'\"{}\" i... | 49.666667 | 26.333333 |
def _set_repository_view(self, session):
"""Sets the underlying repository view to match current view"""
if self._repository_view == FEDERATED:
try:
session.use_federated_repository_view()
except AttributeError:
pass
else:
try:
... | [
"def",
"_set_repository_view",
"(",
"self",
",",
"session",
")",
":",
"if",
"self",
".",
"_repository_view",
"==",
"FEDERATED",
":",
"try",
":",
"session",
".",
"use_federated_repository_view",
"(",
")",
"except",
"AttributeError",
":",
"pass",
"else",
":",
"t... | 34.916667 | 13.5 |
def _get_orb_type_lobster(orb):
"""
Args:
orb: string representation of orbital
Returns:
OrbitalType
"""
orb_labs = ["s", "p_y", "p_z", "p_x", "d_xy", "d_yz", "d_z^2",
"d_xz", "d_x^2-y^2", "f_y(3x^2-y^2)", "f_xyz",
"f_yz^2", "f_z^3", "f_xz^2", "f_z(x^2-y^2)"... | [
"def",
"_get_orb_type_lobster",
"(",
"orb",
")",
":",
"orb_labs",
"=",
"[",
"\"s\"",
",",
"\"p_y\"",
",",
"\"p_z\"",
",",
"\"p_x\"",
",",
"\"d_xy\"",
",",
"\"d_yz\"",
",",
"\"d_z^2\"",
",",
"\"d_xz\"",
",",
"\"d_x^2-y^2\"",
",",
"\"f_y(3x^2-y^2)\"",
",",
"\"... | 30 | 18 |
def __get_stack_trace(self, depth = 16, bUseLabels = True,
bMakePretty = True):
"""
Tries to get a stack trace for the current function using the debug
helper API (dbghelp.dll).
@type depth: int
@param depth: Maximum de... | [
"def",
"__get_stack_trace",
"(",
"self",
",",
"depth",
"=",
"16",
",",
"bUseLabels",
"=",
"True",
",",
"bMakePretty",
"=",
"True",
")",
":",
"aProcess",
"=",
"self",
".",
"get_process",
"(",
")",
"arch",
"=",
"aProcess",
".",
"get_arch",
"(",
")",
"bit... | 39.21519 | 19.468354 |
def to_text(self):
"""Render a MessageElement queue as plain text.
:returns: Plain text representation of the message.
:rtype: str
"""
message = ''
last_was_text = False
for m in self.message:
if last_was_text and not isinstance(m, Text):
... | [
"def",
"to_text",
"(",
"self",
")",
":",
"message",
"=",
"''",
"last_was_text",
"=",
"False",
"for",
"m",
"in",
"self",
".",
"message",
":",
"if",
"last_was_text",
"and",
"not",
"isinstance",
"(",
"m",
",",
"Text",
")",
":",
"message",
"+=",
"'\\n'",
... | 27.05 | 15.85 |
def weave(*iterables):
r"""weave(seq1 [, seq2] [...]) -> iter([seq1[0], seq2[0] ...]).
>>> list(weave([1,2,3], [4,5,6,'A'], [6,7,8, 'B', 'C']))
[1, 4, 6, 2, 5, 7, 3, 6, 8]
Any iterable will work. The first exhausted iterable determines when to
stop. FIXME rethink stopping semantics.
>>> list... | [
"def",
"weave",
"(",
"*",
"iterables",
")",
":",
"iterables",
"=",
"map",
"(",
"iter",
",",
"iterables",
")",
"while",
"True",
":",
"for",
"it",
"in",
"iterables",
":",
"yield",
"it",
".",
"next",
"(",
")"
] | 36.294118 | 18.235294 |
def recode(self, table: pd.DataFrame, validate=False) -> pd.DataFrame:
"""Return a fully recoded dataframe.
Args:
table (pd.DataFrame): A dataframe on which to apply recoding logic.
validate (bool): If ``True``, recoded table must pass validation tests.
"""
df = ... | [
"def",
"recode",
"(",
"self",
",",
"table",
":",
"pd",
".",
"DataFrame",
",",
"validate",
"=",
"False",
")",
"->",
"pd",
".",
"DataFrame",
":",
"df",
"=",
"pd",
".",
"DataFrame",
"(",
"index",
"=",
"table",
".",
"index",
")",
"for",
"column",
"in",... | 36.307692 | 25.153846 |
def cget(self, key):
"""
Query widget option.
:param key: option name
:type key: str
:return: value of the option
To get the list of options for this widget, call the method :meth:`~ScaleEntry.keys`.
"""
if key == 'scalewidth':
return self._s... | [
"def",
"cget",
"(",
"self",
",",
"key",
")",
":",
"if",
"key",
"==",
"'scalewidth'",
":",
"return",
"self",
".",
"_scale",
".",
"cget",
"(",
"'length'",
")",
"elif",
"key",
"==",
"'from'",
":",
"return",
"self",
".",
"_scale",
".",
"cget",
"(",
"'f... | 31.423077 | 12.5 |
def unindent(self):
"""
Un-indents text at cursor position.
"""
_logger().debug('unindent')
cursor = self.editor.textCursor()
_logger().debug('cursor has selection %r', cursor.hasSelection())
if cursor.hasSelection():
cursor.beginEditBlock()
... | [
"def",
"unindent",
"(",
"self",
")",
":",
"_logger",
"(",
")",
".",
"debug",
"(",
"'unindent'",
")",
"cursor",
"=",
"self",
".",
"editor",
".",
"textCursor",
"(",
")",
"_logger",
"(",
")",
".",
"debug",
"(",
"'cursor has selection %r'",
",",
"cursor",
... | 37.233333 | 10.366667 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.