text stringlengths 89 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 630 |
|---|---|---|---|
def json_to_initkwargs(record_type, json_struct, kwargs=None):
"""This function converts a JSON dict (json_struct) to a set of init
keyword arguments for the passed Record (or JsonRecord).
It is called by the JsonRecord constructor. This function takes a JSON
data structure and returns a keyword argum... | [
"def",
"json_to_initkwargs",
"(",
"record_type",
",",
"json_struct",
",",
"kwargs",
"=",
"None",
")",
":",
"if",
"kwargs",
"is",
"None",
":",
"kwargs",
"=",
"{",
"}",
"if",
"json_struct",
"is",
"None",
":",
"json_struct",
"=",
"{",
"}",
"if",
"not",
"i... | 42.309091 | 14.872727 |
def watch_transient_file(self, filename, mask, proc_class):
"""
Watch a transient file, which will be created and deleted frequently
over time (e.g. pid file).
@attention: Currently under the call to this function it is not
possible to correctly watch the events triggered into t... | [
"def",
"watch_transient_file",
"(",
"self",
",",
"filename",
",",
"mask",
",",
"proc_class",
")",
":",
"dirname",
"=",
"os",
".",
"path",
".",
"dirname",
"(",
"filename",
")",
"if",
"dirname",
"==",
"''",
":",
"return",
"{",
"}",
"# Maintains coherence wit... | 47.15 | 19.25 |
def _pluck_pull_request_info(pull_request_url: str) -> PullRequestInfo:
"""
# Plucks a PullRequestInfo from a valid
>>> _pluck_pull_request_info('https://github.com/zhammer/morning-cd/pull/17')
PullRequestInfo(owner='zhammer', repo='morning-cd', number=17)
# Raises a GithubPrError on bad urls
... | [
"def",
"_pluck_pull_request_info",
"(",
"pull_request_url",
":",
"str",
")",
"->",
"PullRequestInfo",
":",
"match",
"=",
"re",
".",
"search",
"(",
"r'github\\.com/(?P<owner>[\\w-]+)/(?P<repo>[\\w-]+)/pull/(?P<number>\\d+)'",
",",
"pull_request_url",
")",
"if",
"not",
"mat... | 33 | 19.88 |
def wrap_socket(socket, certfile, keyfile, password=None):
"""
Wraps an existing TCP socket and returns an SSLSocket object
:param socket: The socket to wrap
:param certfile: The server certificate file
:param keyfile: The server private key file
:param password: Password for the private key fi... | [
"def",
"wrap_socket",
"(",
"socket",
",",
"certfile",
",",
"keyfile",
",",
"password",
"=",
"None",
")",
":",
"# Log warnings when some",
"logger",
"=",
"logging",
".",
"getLogger",
"(",
"\"ssl_wrap\"",
")",
"def",
"_password_support_error",
"(",
")",
":",
"\"... | 36.139535 | 19.697674 |
def cell_strings(term):
"""Return the strings that represent each possible living cell state.
Return the most colorful ones the terminal supports.
"""
num_colors = term.number_of_colors
if num_colors >= 16:
funcs = term.on_bright_red, term.on_bright_green, term.on_bright_cyan
elif num_... | [
"def",
"cell_strings",
"(",
"term",
")",
":",
"num_colors",
"=",
"term",
".",
"number_of_colors",
"if",
"num_colors",
">=",
"16",
":",
"funcs",
"=",
"term",
".",
"on_bright_red",
",",
"term",
".",
"on_bright_green",
",",
"term",
".",
"on_bright_cyan",
"elif"... | 37.684211 | 17.157895 |
def file_name(self, category=None, extension=None):
"""
:param category: audio|image|office|text|video
:param extension: file extension
"""
extension = extension if extension else self.file_extension(category)
filename = self.generator.word()
return '{0}.{1}'.form... | [
"def",
"file_name",
"(",
"self",
",",
"category",
"=",
"None",
",",
"extension",
"=",
"None",
")",
":",
"extension",
"=",
"extension",
"if",
"extension",
"else",
"self",
".",
"file_extension",
"(",
"category",
")",
"filename",
"=",
"self",
".",
"generator"... | 42 | 9.25 |
def policy_map_clss_span_session(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
policy_map = ET.SubElement(config, "policy-map", xmlns="urn:brocade.com:mgmt:brocade-policer")
po_name_key = ET.SubElement(policy_map, "po-name")
po_name_key.text = ... | [
"def",
"policy_map_clss_span_session",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"config",
"=",
"ET",
".",
"Element",
"(",
"\"config\"",
")",
"policy_map",
"=",
"ET",
".",
"SubElement",
"(",
"config",
",",
"\"policy-map\"",
",",
"xmlns",
"=",
"\"urn:... | 44.125 | 13.0625 |
def process_url(url, key):
"""
Yields DOE CODE records from a DOE CODE .json URL response
Converts a DOE CODE API .json URL response into DOE CODE projects
"""
logger.debug('Fetching DOE CODE JSON: %s', url)
if key is None:
raise ValueError('DOE CODE API Key value is missing!')
re... | [
"def",
"process_url",
"(",
"url",
",",
"key",
")",
":",
"logger",
".",
"debug",
"(",
"'Fetching DOE CODE JSON: %s'",
",",
"url",
")",
"if",
"key",
"is",
"None",
":",
"raise",
"ValueError",
"(",
"'DOE CODE API Key value is missing!'",
")",
"response",
"=",
"req... | 29.625 | 21.375 |
def create_slug(title, plain_len=None):
'''
Tries to create a slug from a title, trading off collision risk with readability and minimized cruft
title - a unicode object with a title to use as basis of the slug
plain_len - the maximum character length preserved (from the beginning) of the title
>>... | [
"def",
"create_slug",
"(",
"title",
",",
"plain_len",
"=",
"None",
")",
":",
"if",
"plain_len",
":",
"title",
"=",
"title",
"[",
":",
"plain_len",
"]",
"pass1",
"=",
"OMIT_FROM_SLUG_PAT",
".",
"sub",
"(",
"'_'",
",",
"title",
")",
".",
"lower",
"(",
... | 45.875 | 26.125 |
def update_data_frames(network, cluster_weights, dates, hours):
""" Updates the snapshots, snapshots weights and the dataframes based on
the original data in the network and the medoids created by clustering
these original data.
Parameters
-----------
network : pyPSA network object
cluster_... | [
"def",
"update_data_frames",
"(",
"network",
",",
"cluster_weights",
",",
"dates",
",",
"hours",
")",
":",
"network",
".",
"snapshot_weightings",
"=",
"network",
".",
"snapshot_weightings",
".",
"loc",
"[",
"dates",
"]",
"network",
".",
"snapshots",
"=",
"netw... | 28.314286 | 20.857143 |
def find_path(name, path=None, exact=False):
"""
Search for a file or directory on your local filesystem by name
(file must be in a directory specified in a PATH environment variable)
Args:
fname (PathLike or str): file name to match.
If exact is False this may be a glob pattern
... | [
"def",
"find_path",
"(",
"name",
",",
"path",
"=",
"None",
",",
"exact",
"=",
"False",
")",
":",
"path",
"=",
"os",
".",
"environ",
".",
"get",
"(",
"'PATH'",
",",
"os",
".",
"defpath",
")",
"if",
"path",
"is",
"None",
"else",
"path",
"dpaths",
"... | 39.163265 | 22.183673 |
def setup_logging(self):
"""Setup logging module based on known modules in the config file
"""
logging.getLogger('amqp').setLevel(str_to_logging(self.get('logging', 'amqp')))
logging.getLogger('rdflib').setLevel(str_to_logging(self.get('logging', 'rdflib'))) | [
"def",
"setup_logging",
"(",
"self",
")",
":",
"logging",
".",
"getLogger",
"(",
"'amqp'",
")",
".",
"setLevel",
"(",
"str_to_logging",
"(",
"self",
".",
"get",
"(",
"'logging'",
",",
"'amqp'",
")",
")",
")",
"logging",
".",
"getLogger",
"(",
"'rdflib'",... | 57.2 | 22.8 |
def _should_allocate_port(pid):
"""Determine if we should allocate a port for use by the given process id."""
if pid <= 0:
log.info('Not allocating a port to invalid pid')
return False
if pid == 1:
# The client probably meant to send us its parent pid but
# had been reparente... | [
"def",
"_should_allocate_port",
"(",
"pid",
")",
":",
"if",
"pid",
"<=",
"0",
":",
"log",
".",
"info",
"(",
"'Not allocating a port to invalid pid'",
")",
"return",
"False",
"if",
"pid",
"==",
"1",
":",
"# The client probably meant to send us its parent pid but",
"#... | 34.75 | 17.5625 |
def _proxy(self):
"""
Generate an instance context for the instance, the context is capable of
performing various actions. All instance actions are proxied to the context
:returns: MessageInteractionContext for this MessageInteractionInstance
:rtype: twilio.rest.proxy.v1.servic... | [
"def",
"_proxy",
"(",
"self",
")",
":",
"if",
"self",
".",
"_context",
"is",
"None",
":",
"self",
".",
"_context",
"=",
"MessageInteractionContext",
"(",
"self",
".",
"_version",
",",
"service_sid",
"=",
"self",
".",
"_solution",
"[",
"'service_sid'",
"]",... | 45.529412 | 22.941176 |
def field_get_subfields(field):
""" Given a field, will place all subfields into a dictionary
Parameters:
* field - tuple: The field to get subfields for
Returns: a dictionary, codes as keys and a list of values as the value """
pairs = {}
for key, value in field[0]:
if key in pairs and... | [
"def",
"field_get_subfields",
"(",
"field",
")",
":",
"pairs",
"=",
"{",
"}",
"for",
"key",
",",
"value",
"in",
"field",
"[",
"0",
"]",
":",
"if",
"key",
"in",
"pairs",
"and",
"pairs",
"[",
"key",
"]",
"!=",
"value",
":",
"pairs",
"[",
"key",
"]"... | 35.916667 | 12.666667 |
def _consume_flags(self):
"""Read flags until we encounter the first token that isn't a flag."""
flags = []
while self._at_flag():
flag = self._unconsumed_args.pop()
if not self._check_for_help_request(flag):
flags.append(flag)
return flags | [
"def",
"_consume_flags",
"(",
"self",
")",
":",
"flags",
"=",
"[",
"]",
"while",
"self",
".",
"_at_flag",
"(",
")",
":",
"flag",
"=",
"self",
".",
"_unconsumed_args",
".",
"pop",
"(",
")",
"if",
"not",
"self",
".",
"_check_for_help_request",
"(",
"flag... | 33.625 | 12.625 |
def enrich_pubmed_citations(graph: BELGraph, manager: Manager) -> Set[str]:
"""Overwrite all PubMed citations with values from NCBI's eUtils lookup service.
:return: A set of PMIDs for which the eUtils service crashed
"""
pmids = get_pubmed_identifiers(graph)
pmid_data, errors = get_citations_by_pm... | [
"def",
"enrich_pubmed_citations",
"(",
"graph",
":",
"BELGraph",
",",
"manager",
":",
"Manager",
")",
"->",
"Set",
"[",
"str",
"]",
":",
"pmids",
"=",
"get_pubmed_identifiers",
"(",
"graph",
")",
"pmid_data",
",",
"errors",
"=",
"get_citations_by_pmids",
"(",
... | 36.315789 | 23.315789 |
def _linkFeature(self, feature):
"""
Link a feature with its parents.
"""
parentNames = feature.attributes.get("Parent")
if parentNames is None:
self.roots.add(feature)
else:
for parentName in parentNames:
self._linkToParent(feature... | [
"def",
"_linkFeature",
"(",
"self",
",",
"feature",
")",
":",
"parentNames",
"=",
"feature",
".",
"attributes",
".",
"get",
"(",
"\"Parent\"",
")",
"if",
"parentNames",
"is",
"None",
":",
"self",
".",
"roots",
".",
"add",
"(",
"feature",
")",
"else",
"... | 32.4 | 8 |
def _check_required_group(self):
"""
Returns True if the group requirement (AUTH_LDAP_REQUIRE_GROUP) is
met. Always returns True if AUTH_LDAP_REQUIRE_GROUP is None.
"""
required_group_dn = self.settings.REQUIRE_GROUP
if required_group_dn is not None:
is_membe... | [
"def",
"_check_required_group",
"(",
"self",
")",
":",
"required_group_dn",
"=",
"self",
".",
"settings",
".",
"REQUIRE_GROUP",
"if",
"required_group_dn",
"is",
"not",
"None",
":",
"is_member",
"=",
"self",
".",
"_get_groups",
"(",
")",
".",
"is_member_of",
"(... | 39.384615 | 22.307692 |
def git_list_tags(repo_dir, with_messages=False):
"""Return a list of git tags for the git repo in `repo_dir`."""
command = ['git', 'tag', '-l']
if with_messages:
command.append('-n1')
raw = execute_git_command(command, repo_dir=repo_dir).splitlines()
output = [l.strip() for l in raw if l.st... | [
"def",
"git_list_tags",
"(",
"repo_dir",
",",
"with_messages",
"=",
"False",
")",
":",
"command",
"=",
"[",
"'git'",
",",
"'tag'",
",",
"'-l'",
"]",
"if",
"with_messages",
":",
"command",
".",
"append",
"(",
"'-n1'",
")",
"raw",
"=",
"execute_git_command",... | 41.636364 | 13.909091 |
def set_tag(self, name, tag_class):
"""
Define a new tag parser method
:param name: The name of the tag
:type name: str
:param tag_class: The Tag class, this must be a subclass of base parser.tags.Tag
:type tag_class: Tag
"""
# Has this tag already been... | [
"def",
"set_tag",
"(",
"self",
",",
"name",
",",
"tag_class",
")",
":",
"# Has this tag already been defined?",
"if",
"name",
"in",
"self",
".",
"_tags",
":",
"self",
".",
"_log",
".",
"warn",
"(",
"'Overwriting an existing Tag class: {tag}'",
".",
"format",
"("... | 40.85 | 22.75 |
def _torque_queue_nodes(queue):
"""Retrieve the nodes available for a queue.
Parses out nodes from `acl_hosts` in qstat -Qf and extracts the
initial names of nodes used in pbsnodes.
"""
qstat_out = subprocess.check_output(["qstat", "-Qf", queue]).decode()
hosts = []
in_hosts = False
for... | [
"def",
"_torque_queue_nodes",
"(",
"queue",
")",
":",
"qstat_out",
"=",
"subprocess",
".",
"check_output",
"(",
"[",
"\"qstat\"",
",",
"\"-Qf\"",
",",
"queue",
"]",
")",
".",
"decode",
"(",
")",
"hosts",
"=",
"[",
"]",
"in_hosts",
"=",
"False",
"for",
... | 37.736842 | 17.368421 |
def proxy(opts, functions=None, returners=None, whitelist=None, utils=None):
'''
Returns the proxy module for this salt-proxy-minion
'''
ret = LazyLoader(
_module_dirs(opts, 'proxy'),
opts,
tag='proxy',
pack={'__salt__': functions, '__ret__': returners, '__utils__': utils... | [
"def",
"proxy",
"(",
"opts",
",",
"functions",
"=",
"None",
",",
"returners",
"=",
"None",
",",
"whitelist",
"=",
"None",
",",
"utils",
"=",
"None",
")",
":",
"ret",
"=",
"LazyLoader",
"(",
"_module_dirs",
"(",
"opts",
",",
"'proxy'",
")",
",",
"opts... | 26 | 26.857143 |
def namespace(self, key, glob=False):
"""Return a namespace for keyring"""
if not self.name:
self.name = os.environ['DJANGO_SETTINGS_MODULE']
ns = '.'.join([key, self._glob]) if glob else '.'.join([self.name, self._glob])
return ns | [
"def",
"namespace",
"(",
"self",
",",
"key",
",",
"glob",
"=",
"False",
")",
":",
"if",
"not",
"self",
".",
"name",
":",
"self",
".",
"name",
"=",
"os",
".",
"environ",
"[",
"'DJANGO_SETTINGS_MODULE'",
"]",
"ns",
"=",
"'.'",
".",
"join",
"(",
"[",
... | 45.166667 | 18.166667 |
async def edit(self, **fields):
"""|coro|
Edits the current profile of the client.
If a bot account is used then a password field is optional,
otherwise it is required.
Note
-----
To upload an avatar, a :term:`py:bytes-like object` must be passed in that
... | [
"async",
"def",
"edit",
"(",
"self",
",",
"*",
"*",
"fields",
")",
":",
"try",
":",
"avatar_bytes",
"=",
"fields",
"[",
"'avatar'",
"]",
"except",
"KeyError",
":",
"avatar",
"=",
"self",
".",
"avatar",
"else",
":",
"if",
"avatar_bytes",
"is",
"not",
... | 33.142857 | 19.367347 |
def sync_auth(self, vault_client, resources):
"""Synchronizes auth mount wrappers. These happen
early in the cycle, to ensure that user backends
are proper. They may also be used to set mount
tuning"""
for auth in self.auths():
auth.sync(vault_client)
auth_re... | [
"def",
"sync_auth",
"(",
"self",
",",
"vault_client",
",",
"resources",
")",
":",
"for",
"auth",
"in",
"self",
".",
"auths",
"(",
")",
":",
"auth",
".",
"sync",
"(",
"vault_client",
")",
"auth_resources",
"=",
"[",
"x",
"for",
"x",
"in",
"resources",
... | 38.866667 | 12.333333 |
def send_packet(self, packet, protocol='json', time_precision=None):
"""Send an UDP packet.
:param packet: the packet to be sent
:type packet: (if protocol is 'json') dict
(if protocol is 'line') list of line protocol strings
:param protocol: protocol of input data... | [
"def",
"send_packet",
"(",
"self",
",",
"packet",
",",
"protocol",
"=",
"'json'",
",",
"time_precision",
"=",
"None",
")",
":",
"if",
"protocol",
"==",
"'json'",
":",
"data",
"=",
"make_lines",
"(",
"packet",
",",
"time_precision",
")",
".",
"encode",
"(... | 46.5625 | 18.75 |
def parse_datetime(self, text):
'''Parse datetime from line of text.'''
return parse_datetime(text, date_format=self.date_format,
is_day_period=self.is_day_period) | [
"def",
"parse_datetime",
"(",
"self",
",",
"text",
")",
":",
"return",
"parse_datetime",
"(",
"text",
",",
"date_format",
"=",
"self",
".",
"date_format",
",",
"is_day_period",
"=",
"self",
".",
"is_day_period",
")"
] | 51.5 | 16 |
def sample(self, initial_pos, num_samples, trajectory_length, stepsize=None, return_type='dataframe'):
"""
Method to return samples using Hamiltonian Monte Carlo
Parameters
----------
initial_pos: A 1d array like object
Vector representing values of parameter positio... | [
"def",
"sample",
"(",
"self",
",",
"initial_pos",
",",
"num_samples",
",",
"trajectory_length",
",",
"stepsize",
"=",
"None",
",",
"return_type",
"=",
"'dataframe'",
")",
":",
"self",
".",
"accepted_proposals",
"=",
"1.0",
"initial_pos",
"=",
"_check_1d_array_ob... | 43.494118 | 24.294118 |
def time_to_channels(embedded_video):
"""Put time dimension on channels in an embedded video."""
video_shape = common_layers.shape_list(embedded_video)
if len(video_shape) != 5:
raise ValueError("Assuming videos given as tensors in the format "
"[batch, time, height, width, channels] but ... | [
"def",
"time_to_channels",
"(",
"embedded_video",
")",
":",
"video_shape",
"=",
"common_layers",
".",
"shape_list",
"(",
"embedded_video",
")",
"if",
"len",
"(",
"video_shape",
")",
"!=",
"5",
":",
"raise",
"ValueError",
"(",
"\"Assuming videos given as tensors in t... | 47.166667 | 15.833333 |
def number_of_records_per_hour(self, value=None):
"""Corresponds to IDD Field `number_of_records_per_hour`
Args:
value (int): value for IDD Field `number_of_records_per_hour`
if `value` is None it will not be checked against the
specification and is assumed t... | [
"def",
"number_of_records_per_hour",
"(",
"self",
",",
"value",
"=",
"None",
")",
":",
"if",
"value",
"is",
"not",
"None",
":",
"try",
":",
"value",
"=",
"int",
"(",
"value",
")",
"except",
"ValueError",
":",
"raise",
"ValueError",
"(",
"'value {} need to ... | 34.952381 | 20.904762 |
def fetch(self):
"""
Fetch a AuthorizedConnectAppInstance
:returns: Fetched AuthorizedConnectAppInstance
:rtype: twilio.rest.api.v2010.account.authorized_connect_app.AuthorizedConnectAppInstance
"""
params = values.of({})
payload = self._version.fetch(
... | [
"def",
"fetch",
"(",
"self",
")",
":",
"params",
"=",
"values",
".",
"of",
"(",
"{",
"}",
")",
"payload",
"=",
"self",
".",
"_version",
".",
"fetch",
"(",
"'GET'",
",",
"self",
".",
"_uri",
",",
"params",
"=",
"params",
",",
")",
"return",
"Autho... | 28.142857 | 20.047619 |
def crop_box(im, box=False, **kwargs):
"""Uses box coordinates to crop an image without resizing it first."""
if box:
im = im.crop(box)
return im | [
"def",
"crop_box",
"(",
"im",
",",
"box",
"=",
"False",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"box",
":",
"im",
"=",
"im",
".",
"crop",
"(",
"box",
")",
"return",
"im"
] | 32.2 | 14.6 |
def score(self, X, y, **kwargs):
"""
Generates a 2D array where each row is the count of the
predicted classes and each column is the true class
Parameters
----------
X : ndarray or DataFrame of shape n x m
A matrix of n instances with m features
y :... | [
"def",
"score",
"(",
"self",
",",
"X",
",",
"y",
",",
"*",
"*",
"kwargs",
")",
":",
"# We're relying on predict to raise NotFitted",
"y_pred",
"=",
"self",
".",
"predict",
"(",
"X",
")",
"y_type",
",",
"y_true",
",",
"y_pred",
"=",
"_check_targets",
"(",
... | 32.384615 | 20.961538 |
def setup(self, extra_args=tuple()):
"""
Configure the cluster nodes.
Actual action is delegated to the
:py:class:`elasticluster.providers.AbstractSetupProvider` that
was provided at construction time.
:param list extra_args:
List of additional command-line ar... | [
"def",
"setup",
"(",
"self",
",",
"extra_args",
"=",
"tuple",
"(",
")",
")",
":",
"try",
":",
"# setup the cluster using the setup provider",
"ret",
"=",
"self",
".",
"_setup_provider",
".",
"setup_cluster",
"(",
"self",
",",
"extra_args",
")",
"except",
"Exce... | 34.935484 | 19.387097 |
def restore_config():
'''
Reapplies the previous configuration.
.. versionadded:: 2017.7.5
.. note::
The current configuration will be come the previous configuration. If
run a second time back-to-back it is like toggling between two configs.
Returns:
bool: True if success... | [
"def",
"restore_config",
"(",
")",
":",
"cmd",
"=",
"'Restore-DscConfiguration'",
"try",
":",
"_pshell",
"(",
"cmd",
",",
"ignore_retcode",
"=",
"True",
")",
"except",
"CommandExecutionError",
"as",
"exc",
":",
"if",
"'A previous configuration does not exist'",
"in"... | 25.333333 | 24.8 |
def read(self, size=-1):
'''This reads at most "size" bytes from the file (less if the read hits
EOF before obtaining size bytes). If the size argument is negative or
omitted, read all data until EOF is reached. The bytes are returned as
a string object. An empty string is returned when ... | [
"def",
"read",
"(",
"self",
",",
"size",
"=",
"-",
"1",
")",
":",
"if",
"size",
"==",
"0",
":",
"return",
"self",
".",
"string_type",
"(",
")",
"if",
"size",
"<",
"0",
":",
"# delimiter default is EOF",
"self",
".",
"expect",
"(",
"self",
".",
"del... | 47.714286 | 23.142857 |
async def trigger_act(self, addr):
"""Trigger agent in :attr:`addr` to act.
This method is quite inefficient if used repeatedly for a large number
of agents.
.. seealso::
:py:meth:`creamas.mp.MultiEnvironment.trigger_all`
"""
r_agent = await self.env.connec... | [
"async",
"def",
"trigger_act",
"(",
"self",
",",
"addr",
")",
":",
"r_agent",
"=",
"await",
"self",
".",
"env",
".",
"connect",
"(",
"addr",
",",
"timeout",
"=",
"TIMEOUT",
")",
"return",
"await",
"r_agent",
".",
"act",
"(",
")"
] | 30.666667 | 21.416667 |
def attach_team(context, id, team_id):
"""attach_team(context, id, team_id)
Attach a team to a topic.
>>> dcictl topic-attach-team [OPTIONS]
:param string id: ID of the topic to attach to [required]
:param string team_id: ID of the team to attach to this topic [required]
"""
team_id = tea... | [
"def",
"attach_team",
"(",
"context",
",",
"id",
",",
"team_id",
")",
":",
"team_id",
"=",
"team_id",
"or",
"identity",
".",
"my_team_id",
"(",
"context",
")",
"result",
"=",
"topic",
".",
"attach_team",
"(",
"context",
",",
"id",
"=",
"id",
",",
"team... | 35.076923 | 18.076923 |
def migrate_autoload_details(autoload_details, shell_name, shell_type):
""" Migrate autoload details. Add namespace for attributes
:param autoload_details:
:param shell_name:
:param shell_type:
:return:
"""
mapping = {}
for resource in autoload_details.resources:
resource.model... | [
"def",
"migrate_autoload_details",
"(",
"autoload_details",
",",
"shell_name",
",",
"shell_type",
")",
":",
"mapping",
"=",
"{",
"}",
"for",
"resource",
"in",
"autoload_details",
".",
"resources",
":",
"resource",
".",
"model",
"=",
"\"{shell_name}.{model}\"",
"."... | 42 | 30.791667 |
def expand_dict_as_keys(d):
"""Expands a dictionary into a list of immutables with cartesian product
:param d: dictionary (of strings or lists)
:returns: cartesian product of list parts
"""
to_product = []
for key, values in sorted(d.items()):
# if we sort the inputs here, itertools.pro... | [
"def",
"expand_dict_as_keys",
"(",
"d",
")",
":",
"to_product",
"=",
"[",
"]",
"for",
"key",
",",
"values",
"in",
"sorted",
"(",
"d",
".",
"items",
"(",
")",
")",
":",
"# if we sort the inputs here, itertools.product will keep a stable sort order for us later",
"key... | 43.384615 | 17.307692 |
def bookSSE(symbols=None, on_data=None, token='', version=''):
'''Book shows IEX’s bids and asks for given symbols.
https://iexcloud.io/docs/api/#deep-book
Args:
symbols (string); Tickers to request
on_data (function): Callback on data
token (string); Access token
version (... | [
"def",
"bookSSE",
"(",
"symbols",
"=",
"None",
",",
"on_data",
"=",
"None",
",",
"token",
"=",
"''",
",",
"version",
"=",
"''",
")",
":",
"return",
"_runSSE",
"(",
"'book'",
",",
"symbols",
",",
"on_data",
",",
"token",
",",
"version",
")"
] | 30.615385 | 20 |
def sender(self):
"""
:returns: A :class:`~okcupyd.profile.Profile` instance belonging
to the sender of this message.
"""
return (self._message_thread.user_profile
if 'from_me' in self._message_element.attrib['class']
else self._message_t... | [
"def",
"sender",
"(",
"self",
")",
":",
"return",
"(",
"self",
".",
"_message_thread",
".",
"user_profile",
"if",
"'from_me'",
"in",
"self",
".",
"_message_element",
".",
"attrib",
"[",
"'class'",
"]",
"else",
"self",
".",
"_message_thread",
".",
"correspond... | 42.625 | 15.625 |
def create(self):
"""
Create an instance of the Parking Planning Service with the
typical starting settings.
"""
self.service.create()
os.environ[self.__module__ + '.uri'] = self.service.settings.data['url']
os.environ[self.__module__ + '.zone_id'] = self.get_pred... | [
"def",
"create",
"(",
"self",
")",
":",
"self",
".",
"service",
".",
"create",
"(",
")",
"os",
".",
"environ",
"[",
"self",
".",
"__module__",
"+",
"'.uri'",
"]",
"=",
"self",
".",
"service",
".",
"settings",
".",
"data",
"[",
"'url'",
"]",
"os",
... | 40.625 | 17.875 |
def make_prediction_output_tensors(args, features, input_ops, model_fn_ops,
keep_target):
"""Makes the final prediction output layer."""
target_name = feature_transforms.get_target_name(features)
key_names = get_key_names(features)
outputs = {}
outputs.update({key_name: tf.... | [
"def",
"make_prediction_output_tensors",
"(",
"args",
",",
"features",
",",
"input_ops",
",",
"model_fn_ops",
",",
"keep_target",
")",
":",
"target_name",
"=",
"feature_transforms",
".",
"get_target_name",
"(",
"features",
")",
"key_names",
"=",
"get_key_names",
"("... | 36.3125 | 22.0125 |
def _previous_pages_count(self):
'A generator of previous page integers.'
skip = self.skip
if skip == 0:
return 0
count, remainder = divmod(skip, self.limit)
return count | [
"def",
"_previous_pages_count",
"(",
"self",
")",
":",
"skip",
"=",
"self",
".",
"skip",
"if",
"skip",
"==",
"0",
":",
"return",
"0",
"count",
",",
"remainder",
"=",
"divmod",
"(",
"skip",
",",
"self",
".",
"limit",
")",
"return",
"count"
] | 30.857143 | 14.571429 |
def add_button_box(self, stdbtns):
"""Create dialog button box and add it to the dialog layout"""
bbox = QDialogButtonBox(stdbtns)
run_btn = bbox.addButton(_("Run"), QDialogButtonBox.AcceptRole)
run_btn.clicked.connect(self.run_btn_clicked)
bbox.accepted.connect(self.accept)... | [
"def",
"add_button_box",
"(",
"self",
",",
"stdbtns",
")",
":",
"bbox",
"=",
"QDialogButtonBox",
"(",
"stdbtns",
")",
"run_btn",
"=",
"bbox",
".",
"addButton",
"(",
"_",
"(",
"\"Run\"",
")",
",",
"QDialogButtonBox",
".",
"AcceptRole",
")",
"run_btn",
".",
... | 45.545455 | 7.272727 |
def plotBoostTrace(sp, inputVectors, columnIndex):
"""
Plot boostfactor for a selected column
Note that learning is ON for SP here
:param sp: sp instance
:param inputVectors: input data
:param columnIndex: index for the column of interest
"""
numInputVector, inputSize = inputVectors.shape
columnNumb... | [
"def",
"plotBoostTrace",
"(",
"sp",
",",
"inputVectors",
",",
"columnIndex",
")",
":",
"numInputVector",
",",
"inputSize",
"=",
"inputVectors",
".",
"shape",
"columnNumber",
"=",
"np",
".",
"prod",
"(",
"sp",
".",
"getColumnDimensions",
"(",
")",
")",
"boost... | 36.487805 | 16.487805 |
def get_filename_block_as_codepoints(self):
"""
TODO: Support tokenized BASIC. Now we only create ASCII BASIC.
"""
codepoints = []
codepoints += list(string2codepoint(self.filename.ljust(8, " ")))
codepoints.append(self.cfg.FTYPE_BASIC) # one byte file type
codepo... | [
"def",
"get_filename_block_as_codepoints",
"(",
"self",
")",
":",
"codepoints",
"=",
"[",
"]",
"codepoints",
"+=",
"list",
"(",
"string2codepoint",
"(",
"self",
".",
"filename",
".",
"ljust",
"(",
"8",
",",
"\" \"",
")",
")",
")",
"codepoints",
".",
"appen... | 42.586207 | 24.172414 |
def list2cmdline(seq):
"""
Translate a sequence of arguments into a command line
string, using the same rules as the MS C runtime:
1) Arguments are delimited by white space, which is either a
space or a tab.
2) A string surrounded by double quotation marks is
interpreted as a single ... | [
"def",
"list2cmdline",
"(",
"seq",
")",
":",
"# See",
"# http://msdn.microsoft.com/en-us/library/17w5ykft.aspx",
"# or search http://msdn.microsoft.com for",
"# \"Parsing C++ Command-Line Arguments\"",
"result",
"=",
"[",
"]",
"needquote",
"=",
"False",
"for",
"arg",
"in",
"s... | 30.911765 | 19.411765 |
def ISINSTANCE(instance, A_tuple): # noqa
"""
Allows you to do isinstance checks on futures.
Really, I discourage this because duck-typing is usually better.
But this can provide you with a way to use isinstance with futures.
Works with other objects too.
:param instance:
:param A_tuple:
... | [
"def",
"ISINSTANCE",
"(",
"instance",
",",
"A_tuple",
")",
":",
"# noqa",
"try",
":",
"instance",
"=",
"instance",
".",
"_redpipe_future_result",
"except",
"AttributeError",
":",
"pass",
"return",
"isinstance",
"(",
"instance",
",",
"A_tuple",
")"
] | 27.352941 | 18.294118 |
def _result_handler(self, response: Dict[str, Any]):
"""应答结果响应处理.
将结果解析出来设置给任务对应的Future对象上
Parameters:
(response): - 响应的python字典形式数据
Return:
(bool): - 准确地说没有错误就会返回True
"""
res = response.get("MESSAGE")
result = res.get("RESULT")
... | [
"def",
"_result_handler",
"(",
"self",
",",
"response",
":",
"Dict",
"[",
"str",
",",
"Any",
"]",
")",
":",
"res",
"=",
"response",
".",
"get",
"(",
"\"MESSAGE\"",
")",
"result",
"=",
"res",
".",
"get",
"(",
"\"RESULT\"",
")",
"return",
"result"
] | 21.333333 | 17.133333 |
def ranked_in_list_in(self, leaderboard_name, members, **options):
'''
Retrieve a page of leaders from the named leaderboard for a given list of members.
@param leaderboard_name [String] Name of the leaderboard.
@param members [Array] Member names.
@param options [Hash] Options ... | [
"def",
"ranked_in_list_in",
"(",
"self",
",",
"leaderboard_name",
",",
"members",
",",
"*",
"*",
"options",
")",
":",
"ranks_for_members",
"=",
"[",
"]",
"pipeline",
"=",
"self",
".",
"redis_connection",
".",
"pipeline",
"(",
")",
"for",
"member",
"in",
"m... | 40.04918 | 23.491803 |
def b2a_qp(data, quotetabs=False, istext=True, header=False):
"""quotetabs=True means that tab and space characters are always
quoted.
istext=False means that \r and \n are treated as regular characters
header=True encodes space characters with '_' and requires
real '_' characters to be ... | [
"def",
"b2a_qp",
"(",
"data",
",",
"quotetabs",
"=",
"False",
",",
"istext",
"=",
"True",
",",
"header",
"=",
"False",
")",
":",
"MAXLINESIZE",
"=",
"76",
"# See if this string is using CRLF line ends",
"lf",
"=",
"data",
".",
"find",
"(",
"'\\n'",
")",
"c... | 36.014493 | 15.304348 |
def parent(groups,ID):
"""given a groups dictionary and an ID, return its actual parent ID."""
if ID in groups.keys():
return ID # already a parent
if not ID in groups.keys():
for actualParent in groups.keys():
if ID in groups[actualParent]:
return actualParent # ... | [
"def",
"parent",
"(",
"groups",
",",
"ID",
")",
":",
"if",
"ID",
"in",
"groups",
".",
"keys",
"(",
")",
":",
"return",
"ID",
"# already a parent",
"if",
"not",
"ID",
"in",
"groups",
".",
"keys",
"(",
")",
":",
"for",
"actualParent",
"in",
"groups",
... | 39 | 10.444444 |
def rewire_inputs(data_list):
"""Rewire inputs of provided data objects.
Input parameter is a list of original and copied data object model
instances: ``[{'original': original, 'copy': copy}]``. This
function finds which objects reference other objects (in the list)
on the input and replaces origin... | [
"def",
"rewire_inputs",
"(",
"data_list",
")",
":",
"if",
"len",
"(",
"data_list",
")",
"<",
"2",
":",
"return",
"data_list",
"mapped_ids",
"=",
"{",
"bundle",
"[",
"'original'",
"]",
".",
"id",
":",
"bundle",
"[",
"'copy'",
"]",
".",
"id",
"for",
"b... | 34.4 | 26.485714 |
def write_options_to_YAML(self, filename):
"""Writes the options in YAML format to a file.
:param str filename: Target file to write the options.
"""
fd = open(filename, "w")
yaml.dump(_options_to_dict(self.gc), fd, default_flow_style=False)
fd.close() | [
"def",
"write_options_to_YAML",
"(",
"self",
",",
"filename",
")",
":",
"fd",
"=",
"open",
"(",
"filename",
",",
"\"w\"",
")",
"yaml",
".",
"dump",
"(",
"_options_to_dict",
"(",
"self",
".",
"gc",
")",
",",
"fd",
",",
"default_flow_style",
"=",
"False",
... | 36.75 | 16 |
def infer_cm(tpm):
"""Infer the connectivity matrix associated with a state-by-node TPM in
multidimensional form.
"""
network_size = tpm.shape[-1]
all_contexts = tuple(all_states(network_size - 1))
cm = np.empty((network_size, network_size), dtype=int)
for a, b in np.ndindex(cm.shape):
... | [
"def",
"infer_cm",
"(",
"tpm",
")",
":",
"network_size",
"=",
"tpm",
".",
"shape",
"[",
"-",
"1",
"]",
"all_contexts",
"=",
"tuple",
"(",
"all_states",
"(",
"network_size",
"-",
"1",
")",
")",
"cm",
"=",
"np",
".",
"empty",
"(",
"(",
"network_size",
... | 37.4 | 12 |
def deploy_paying_proxy_contract(self, initializer=b'', deployer_account=None, deployer_private_key=None) -> str:
"""
Deploy proxy contract. Takes deployer_account (if unlocked in the node) or the deployer private key
:param initializer: Initializer
:param deployer_account: Unlocked ethe... | [
"def",
"deploy_paying_proxy_contract",
"(",
"self",
",",
"initializer",
"=",
"b''",
",",
"deployer_account",
"=",
"None",
",",
"deployer_private_key",
"=",
"None",
")",
"->",
"str",
":",
"assert",
"deployer_account",
"or",
"deployer_private_key",
"deployer_address",
... | 61.190476 | 32.428571 |
def allowed_domains(self):
"""
This property lists the allowed domains for a load balancer.
The allowed domains are restrictions set for the allowed domain names
used for adding load balancer nodes. In order to submit a domain name
as an address for the load balancer node to add... | [
"def",
"allowed_domains",
"(",
"self",
")",
":",
"if",
"self",
".",
"_allowed_domains",
"is",
"None",
":",
"uri",
"=",
"\"/loadbalancers/alloweddomains\"",
"resp",
",",
"body",
"=",
"self",
".",
"method_get",
"(",
"uri",
")",
"dom_list",
"=",
"body",
"[",
... | 47.5 | 18.055556 |
def add_vertex(self, vertex, **attr):
"""
Add vertex and update vertex attributes
"""
self.vertices[vertex] = []
if attr:
self.nodes[vertex] = attr
self.pred[vertex] = []
self.succ[vertex] = [] | [
"def",
"add_vertex",
"(",
"self",
",",
"vertex",
",",
"*",
"*",
"attr",
")",
":",
"self",
".",
"vertices",
"[",
"vertex",
"]",
"=",
"[",
"]",
"if",
"attr",
":",
"self",
".",
"nodes",
"[",
"vertex",
"]",
"=",
"attr",
"self",
".",
"pred",
"[",
"v... | 29 | 6.555556 |
def lv_voltage_deviation(network, mode=None, voltage_levels='mv_lv'):
"""
Checks for voltage stability issues in LV grids.
Parameters
----------
network : :class:`~.grid.network.Network`
mode : None or String
If None voltage at all nodes in LV grid is checked. If mode is set to
... | [
"def",
"lv_voltage_deviation",
"(",
"network",
",",
"mode",
"=",
"None",
",",
"voltage_levels",
"=",
"'mv_lv'",
")",
":",
"crit_nodes",
"=",
"{",
"}",
"v_dev_allowed_per_case",
"=",
"{",
"}",
"if",
"voltage_levels",
"==",
"'mv_lv'",
":",
"offset",
"=",
"netw... | 43.237805 | 21.25 |
def sleeping_func(arg, secs=10, result_queue=None):
"""This methods illustrates how the workers can be used."""
import time
time.sleep(secs)
if result_queue is not None:
result_queue.put(arg)
else:
return arg | [
"def",
"sleeping_func",
"(",
"arg",
",",
"secs",
"=",
"10",
",",
"result_queue",
"=",
"None",
")",
":",
"import",
"time",
"time",
".",
"sleep",
"(",
"secs",
")",
"if",
"result_queue",
"is",
"not",
"None",
":",
"result_queue",
".",
"put",
"(",
"arg",
... | 29.625 | 16 |
def show_editor_buffer(self, editor_buffer):
"""
Open this `EditorBuffer` in the active window.
"""
assert isinstance(editor_buffer, EditorBuffer)
self.active_window.editor_buffer = editor_buffer | [
"def",
"show_editor_buffer",
"(",
"self",
",",
"editor_buffer",
")",
":",
"assert",
"isinstance",
"(",
"editor_buffer",
",",
"EditorBuffer",
")",
"self",
".",
"active_window",
".",
"editor_buffer",
"=",
"editor_buffer"
] | 38.333333 | 8 |
def commit(self, project_id, mode, mutations, transaction=None):
"""Perform a ``commit`` request.
:type project_id: str
:param project_id: The project to connect to. This is
usually your project name in the cloud console.
:type mode: :class:`.gapic.datastore.... | [
"def",
"commit",
"(",
"self",
",",
"project_id",
",",
"mode",
",",
"mutations",
",",
"transaction",
"=",
"None",
")",
":",
"request_pb",
"=",
"_datastore_pb2",
".",
"CommitRequest",
"(",
"project_id",
"=",
"project_id",
",",
"mode",
"=",
"mode",
",",
"tran... | 36.918919 | 20.243243 |
def replace_all(filepath, searchExp, replaceExp):
"""
Replace all the ocurrences (in a file) of a string with another value.
"""
for line in fileinput.input(filepath, inplace=1):
if searchExp in line:
line = line.replace(searchExp, replaceExp)
sys.stdout.write(line) | [
"def",
"replace_all",
"(",
"filepath",
",",
"searchExp",
",",
"replaceExp",
")",
":",
"for",
"line",
"in",
"fileinput",
".",
"input",
"(",
"filepath",
",",
"inplace",
"=",
"1",
")",
":",
"if",
"searchExp",
"in",
"line",
":",
"line",
"=",
"line",
".",
... | 37.875 | 11.375 |
def main():
"""Main entry point for CLI commands."""
options = docopt(__doc__, version=__version__)
if options['segment']:
segment(
options['<file>'],
options['--output'],
options['--target-duration'],
options['--mpegts'],
) | [
"def",
"main",
"(",
")",
":",
"options",
"=",
"docopt",
"(",
"__doc__",
",",
"version",
"=",
"__version__",
")",
"if",
"options",
"[",
"'segment'",
"]",
":",
"segment",
"(",
"options",
"[",
"'<file>'",
"]",
",",
"options",
"[",
"'--output'",
"]",
",",
... | 29.1 | 13.5 |
def depolarizeCells(self, basalInput, apicalInput, learn):
"""
Calculate predictions.
@param basalInput (numpy array)
List of active input bits for the basal dendrite segments
@param apicalInput (numpy array)
List of active input bits for the apical dendrite segments
@param learn (bool)
... | [
"def",
"depolarizeCells",
"(",
"self",
",",
"basalInput",
",",
"apicalInput",
",",
"learn",
")",
":",
"(",
"activeApicalSegments",
",",
"matchingApicalSegments",
",",
"apicalPotentialOverlaps",
")",
"=",
"self",
".",
"_calculateApicalSegmentActivity",
"(",
"self",
"... | 40.302326 | 21.697674 |
def createDataFromFile(self, filePath, inputEncoding = None, defaultFps = None):
"""Fetch a given filePath and parse its contents.
May raise the following exceptions:
* RuntimeError - generic exception telling that parsing was unsuccessfull
* IOError - failed to open a file at given fil... | [
"def",
"createDataFromFile",
"(",
"self",
",",
"filePath",
",",
"inputEncoding",
"=",
"None",
",",
"defaultFps",
"=",
"None",
")",
":",
"file_",
"=",
"File",
"(",
"filePath",
")",
"if",
"inputEncoding",
"is",
"None",
":",
"inputEncoding",
"=",
"file_",
"."... | 40.518519 | 21.62963 |
def Brkic_2011_1(Re, eD):
r'''Calculates Darcy friction factor using the method in Brkic
(2011) [2]_ as shown in [1]_.
.. math::
f_d = [-2\log(10^{-0.4343\beta} + \frac{\epsilon}{3.71D})]^{-2}
.. math::
\beta = \ln \frac{Re}{1.816\ln\left(\frac{1.1Re}{\ln(1+1.1Re)}\right)}
Paramet... | [
"def",
"Brkic_2011_1",
"(",
"Re",
",",
"eD",
")",
":",
"beta",
"=",
"log",
"(",
"Re",
"/",
"(",
"1.816",
"*",
"log",
"(",
"1.1",
"*",
"Re",
"/",
"log",
"(",
"1",
"+",
"1.1",
"*",
"Re",
")",
")",
")",
")",
"return",
"(",
"-",
"2",
"*",
"lo... | 28.409091 | 25 |
def search_golr_wrap(id, category, **args):
"""
performs searches in both directions
"""
#assocs1 = search_associations_compact(object=id, subject_category=category, **args)
#assocs2 = search_associations_compact(subject=id, object_category=category, **args)
assocs1, facets1 = search_compact_wra... | [
"def",
"search_golr_wrap",
"(",
"id",
",",
"category",
",",
"*",
"*",
"args",
")",
":",
"#assocs1 = search_associations_compact(object=id, subject_category=category, **args)",
"#assocs2 = search_associations_compact(subject=id, object_category=category, **args)",
"assocs1",
",",
"fac... | 46.083333 | 20.916667 |
def fix_config(self, options):
"""
Fixes the options, if necessary. I.e., it adds all required elements to the dictionary.
:param options: the options to fix
:type options: dict
:return: the (potentially) fixed options
:rtype: dict
"""
options = super(Tri... | [
"def",
"fix_config",
"(",
"self",
",",
"options",
")",
":",
"options",
"=",
"super",
"(",
"Trigger",
",",
"self",
")",
".",
"fix_config",
"(",
"options",
")",
"opt",
"=",
"\"condition\"",
"if",
"opt",
"not",
"in",
"options",
":",
"options",
"[",
"opt",... | 41.190476 | 25 |
def clickMouseButtonLeft(self, coord, interval=None):
"""Click the left mouse button without modifiers pressed.
Parameters: coordinates to click on screen (tuple (x, y))
Returns: None
"""
modFlags = 0
self._queueMouseButton(coord, Quartz.kCGMouseButtonLeft, modFlags)
... | [
"def",
"clickMouseButtonLeft",
"(",
"self",
",",
"coord",
",",
"interval",
"=",
"None",
")",
":",
"modFlags",
"=",
"0",
"self",
".",
"_queueMouseButton",
"(",
"coord",
",",
"Quartz",
".",
"kCGMouseButtonLeft",
",",
"modFlags",
")",
"if",
"interval",
":",
"... | 33.153846 | 19.615385 |
def get_fields_by_class(cls, field_class):
""" Return a list of field names matching a field class
:param field_class: field class object
:return: list
"""
ret = []
for key, val in getattr(cls, '_fields').items():
if isinstance(val, field_class):
... | [
"def",
"get_fields_by_class",
"(",
"cls",
",",
"field_class",
")",
":",
"ret",
"=",
"[",
"]",
"for",
"key",
",",
"val",
"in",
"getattr",
"(",
"cls",
",",
"'_fields'",
")",
".",
"items",
"(",
")",
":",
"if",
"isinstance",
"(",
"val",
",",
"field_class... | 26.769231 | 17.076923 |
def admin_emails(doc):
"""View for admin email addresses (organisation and global)"""
if doc.get('type') == 'user' and doc.get('state') != 'deactivated':
if doc.get('role') == 'administrator':
yield None, doc['email']
for org_id, state in doc.get('organisations', {}).items():
... | [
"def",
"admin_emails",
"(",
"doc",
")",
":",
"if",
"doc",
".",
"get",
"(",
"'type'",
")",
"==",
"'user'",
"and",
"doc",
".",
"get",
"(",
"'state'",
")",
"!=",
"'deactivated'",
":",
"if",
"doc",
".",
"get",
"(",
"'role'",
")",
"==",
"'administrator'",... | 55.125 | 17.375 |
def set_access_control_lists(self, access_control_lists, security_namespace_id):
"""SetAccessControlLists.
Create or update one or more access control lists. All data that currently exists for the ACLs supplied will be overwritten.
:param :class:`<VssJsonCollectionWrapper> <azure.devops.v5_0.sec... | [
"def",
"set_access_control_lists",
"(",
"self",
",",
"access_control_lists",
",",
"security_namespace_id",
")",
":",
"route_values",
"=",
"{",
"}",
"if",
"security_namespace_id",
"is",
"not",
"None",
":",
"route_values",
"[",
"'securityNamespaceId'",
"]",
"=",
"self... | 66.666667 | 32.933333 |
def normalize_serial_number(sn,
max_length=None, left_fill='0', right_fill=str(), blank=str(),
valid_chars=' -0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ',
invalid_chars=None,
strip_whitesp... | [
"def",
"normalize_serial_number",
"(",
"sn",
",",
"max_length",
"=",
"None",
",",
"left_fill",
"=",
"'0'",
",",
"right_fill",
"=",
"str",
"(",
")",
",",
"blank",
"=",
"str",
"(",
")",
",",
"valid_chars",
"=",
"' -0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLM... | 38.490909 | 25.136364 |
def spacing(self):
"""
Get image spacing
Returns
-------
tuple
"""
libfn = utils.get_lib_fn('getSpacing%s'%self._libsuffix)
return libfn(self.pointer) | [
"def",
"spacing",
"(",
"self",
")",
":",
"libfn",
"=",
"utils",
".",
"get_lib_fn",
"(",
"'getSpacing%s'",
"%",
"self",
".",
"_libsuffix",
")",
"return",
"libfn",
"(",
"self",
".",
"pointer",
")"
] | 20.6 | 18.4 |
def unmarshall(values):
"""
Transform a response payload from DynamoDB to a native dict
:param dict values: The response payload from DynamoDB
:rtype: dict
:raises ValueError: if an unsupported type code is encountered
"""
unmarshalled = {}
for key in values:
unmarshalled[key] ... | [
"def",
"unmarshall",
"(",
"values",
")",
":",
"unmarshalled",
"=",
"{",
"}",
"for",
"key",
"in",
"values",
":",
"unmarshalled",
"[",
"key",
"]",
"=",
"_unmarshall_dict",
"(",
"values",
"[",
"key",
"]",
")",
"return",
"unmarshalled"
] | 27.923077 | 19.923077 |
def summary(self, varnames=None, ranefs=False, transformed=False, hpd=.95,
quantiles=None, diagnostics=['effective_n', 'gelman_rubin']):
'''Returns a DataFrame of summary/diagnostic statistics for the parameters.
Args:
varnames (list): List of variable names to include; if N... | [
"def",
"summary",
"(",
"self",
",",
"varnames",
"=",
"None",
",",
"ranefs",
"=",
"False",
",",
"transformed",
"=",
"False",
",",
"hpd",
"=",
".95",
",",
"quantiles",
"=",
"None",
",",
"diagnostics",
"=",
"[",
"'effective_n'",
",",
"'gelman_rubin'",
"]",
... | 50.411765 | 25 |
def clean_draft_pages_from_space(confluence, space_key, count, date_now):
"""
Remove draft pages from space using datetime.now
:param confluence:
:param space_key:
:param count:
:param date_now:
:return: int counter
"""
pages = confluence.get_all_draft_pages_from_space(space=space_ke... | [
"def",
"clean_draft_pages_from_space",
"(",
"confluence",
",",
"space_key",
",",
"count",
",",
"date_now",
")",
":",
"pages",
"=",
"confluence",
".",
"get_all_draft_pages_from_space",
"(",
"space",
"=",
"space_key",
",",
"start",
"=",
"0",
",",
"limit",
"=",
"... | 43.333333 | 22.47619 |
def stream_header_legacy(self, f):
"""Stream the block header in the standard way to the file-like object f."""
stream_struct("L##LL", f, self.version, self.previous_block_hash,
self.merkle_root, self.timestamp, self.difficulty)
f.write(self.nonce[:4]) | [
"def",
"stream_header_legacy",
"(",
"self",
",",
"f",
")",
":",
"stream_struct",
"(",
"\"L##LL\"",
",",
"f",
",",
"self",
".",
"version",
",",
"self",
".",
"previous_block_hash",
",",
"self",
".",
"merkle_root",
",",
"self",
".",
"timestamp",
",",
"self",
... | 58.8 | 16 |
async def download_file(self, file_path: base.String,
destination: Optional[base.InputFile] = None,
timeout: Optional[base.Integer] = sentinel,
chunk_size: Optional[base.Integer] = 65536,
seek: Optional[base.... | [
"async",
"def",
"download_file",
"(",
"self",
",",
"file_path",
":",
"base",
".",
"String",
",",
"destination",
":",
"Optional",
"[",
"base",
".",
"InputFile",
"]",
"=",
"None",
",",
"timeout",
":",
"Optional",
"[",
"base",
".",
"Integer",
"]",
"=",
"s... | 45.885714 | 26.171429 |
def fix_pdf_with_ghostscript_to_tmp_file(input_doc_fname):
"""Attempt to fix a bad PDF file with a Ghostscript command, writing the output
PDF to a temporary file and returning the filename. Caller is responsible for
deleting the file."""
if not gs_executable: init_and_test_gs_executable(exit_on_fail=... | [
"def",
"fix_pdf_with_ghostscript_to_tmp_file",
"(",
"input_doc_fname",
")",
":",
"if",
"not",
"gs_executable",
":",
"init_and_test_gs_executable",
"(",
"exit_on_fail",
"=",
"True",
")",
"temp_file_name",
"=",
"get_temporary_filename",
"(",
"extension",
"=",
"\".pdf\"",
... | 56.782609 | 26.869565 |
def humanize_timedelta(seconds):
"""Creates a string representation of timedelta."""
hours, remainder = divmod(seconds, 3600)
days, hours = divmod(hours, 24)
minutes, seconds = divmod(remainder, 60)
if days:
result = '{}d'.format(days)
if hours:
result += ' {}h'.format(h... | [
"def",
"humanize_timedelta",
"(",
"seconds",
")",
":",
"hours",
",",
"remainder",
"=",
"divmod",
"(",
"seconds",
",",
"3600",
")",
"days",
",",
"hours",
"=",
"divmod",
"(",
"hours",
",",
"24",
")",
"minutes",
",",
"seconds",
"=",
"divmod",
"(",
"remain... | 26 | 16.185185 |
def argsplit(args, sep=','):
"""used to split JS args (it is not that simple as it seems because
sep can be inside brackets).
pass args *without* brackets!
Used also to parse array and object elements, and more"""
parsed_len = 0
last = 0
splits = []
for e in bracket_split(args... | [
"def",
"argsplit",
"(",
"args",
",",
"sep",
"=",
"','",
")",
":",
"parsed_len",
"=",
"0",
"last",
"=",
"0",
"splits",
"=",
"[",
"]",
"for",
"e",
"in",
"bracket_split",
"(",
"args",
",",
"brackets",
"=",
"[",
"'()'",
",",
"'[]'",
",",
"'{}'",
"]",... | 33.210526 | 14.631579 |
def add_column(self, data, column_name="", inplace=False):
"""
Returns an SFrame with a new column. The number of elements in the data
given must match the length of every other column of the SFrame.
If no name is given, a default name is chosen.
If inplace == False (default) th... | [
"def",
"add_column",
"(",
"self",
",",
"data",
",",
"column_name",
"=",
"\"\"",
",",
"inplace",
"=",
"False",
")",
":",
"# Check type for pandas dataframe or SArray?",
"if",
"not",
"isinstance",
"(",
"data",
",",
"SArray",
")",
":",
"if",
"isinstance",
"(",
... | 29.675676 | 20.459459 |
def get_object_from_name(name):
''' Returns the named object.
Arguments:
name (str): A string of form `package.subpackage.etc.module.property`.
This function will import `package.subpackage.etc.module` and
return `property` from that module.
'''
dot = name.rindex(".")
... | [
"def",
"get_object_from_name",
"(",
"name",
")",
":",
"dot",
"=",
"name",
".",
"rindex",
"(",
"\".\"",
")",
"mod_name",
",",
"property_name",
"=",
"name",
"[",
":",
"dot",
"]",
",",
"name",
"[",
"dot",
"+",
"1",
":",
"]",
"__import__",
"(",
"mod_name... | 31.785714 | 23.928571 |
def SetKeyPathPrefix(self, key_path_prefix):
"""Sets the Window Registry key path prefix.
Args:
key_path_prefix (str): Windows Registry key path prefix.
"""
self._key_path_prefix = key_path_prefix
self._key_path_prefix_length = len(key_path_prefix)
self._key_path_prefix_upper = key_path_p... | [
"def",
"SetKeyPathPrefix",
"(",
"self",
",",
"key_path_prefix",
")",
":",
"self",
".",
"_key_path_prefix",
"=",
"key_path_prefix",
"self",
".",
"_key_path_prefix_length",
"=",
"len",
"(",
"key_path_prefix",
")",
"self",
".",
"_key_path_prefix_upper",
"=",
"key_path_... | 36.111111 | 14.666667 |
def signin(request, auth_form=AuthenticationForm,
template_name='userena/signin_form.html',
redirect_field_name=REDIRECT_FIELD_NAME,
redirect_signin_function=signin_redirect, extra_context=None):
"""
Signin using email or username with password.
Signs a user in by combining... | [
"def",
"signin",
"(",
"request",
",",
"auth_form",
"=",
"AuthenticationForm",
",",
"template_name",
"=",
"'userena/signin_form.html'",
",",
"redirect_field_name",
"=",
"REDIRECT_FIELD_NAME",
",",
"redirect_signin_function",
"=",
"signin_redirect",
",",
"extra_context",
"=... | 43.301205 | 24.795181 |
def request_access(self, verifier):
""" Get OAuth access token so we can make requests """
client = OAuth1(
client_key=self._server_cache[self.client.server].key,
client_secret=self._server_cache[self.client.server].secret,
resource_owner_key=self.store["oauth-request... | [
"def",
"request_access",
"(",
"self",
",",
"verifier",
")",
":",
"client",
"=",
"OAuth1",
"(",
"client_key",
"=",
"self",
".",
"_server_cache",
"[",
"self",
".",
"client",
".",
"server",
"]",
".",
"key",
",",
"client_secret",
"=",
"self",
".",
"_server_c... | 36.818182 | 20.545455 |
def secondary_mass(mass1, mass2):
"""Returns the smaller of mass1 and mass2 (s = secondary)."""
mass1, mass2, input_is_array = ensurearray(mass1, mass2)
if mass1.shape != mass2.shape:
raise ValueError("mass1 and mass2 must have same shape")
ms = copy.copy(mass2)
mask = mass1 < mass2
ms[m... | [
"def",
"secondary_mass",
"(",
"mass1",
",",
"mass2",
")",
":",
"mass1",
",",
"mass2",
",",
"input_is_array",
"=",
"ensurearray",
"(",
"mass1",
",",
"mass2",
")",
"if",
"mass1",
".",
"shape",
"!=",
"mass2",
".",
"shape",
":",
"raise",
"ValueError",
"(",
... | 41.555556 | 11.666667 |
def add_command_set(self, command_set):
"""
Adds all of the commands and events from specified CommandSet command set
into this one.
:param command_set: a commands set to add commands from
"""
for command in command_set.get_commands():
self.add_comman... | [
"def",
"add_command_set",
"(",
"self",
",",
"command_set",
")",
":",
"for",
"command",
"in",
"command_set",
".",
"get_commands",
"(",
")",
":",
"self",
".",
"add_command",
"(",
"command",
")",
"for",
"event",
"in",
"command_set",
".",
"get_events",
"(",
")... | 33.416667 | 15.083333 |
def inspect(self, name):
'''Inspect a local image in the database, which typically includes the
basic fields in the model.
'''
print(name)
container = self.get(name)
if container is not None:
collection = container.collection.name
fields = container.__dict__.copy()
fi... | [
"def",
"inspect",
"(",
"self",
",",
"name",
")",
":",
"print",
"(",
"name",
")",
"container",
"=",
"self",
".",
"get",
"(",
"name",
")",
"if",
"container",
"is",
"not",
"None",
":",
"collection",
"=",
"container",
".",
"collection",
".",
"name",
"fie... | 36.375 | 16.5 |
def FlowAccumFromProps(
props,
weights = None,
in_place = False
):
"""Calculates flow accumulation from flow proportions.
Args:
props (rdarray): An elevation model
weights (rdarray): Flow accumulation weights to use. This is the
amount of flow generated ... | [
"def",
"FlowAccumFromProps",
"(",
"props",
",",
"weights",
"=",
"None",
",",
"in_place",
"=",
"False",
")",
":",
"if",
"type",
"(",
"props",
")",
"is",
"not",
"rd3array",
":",
"raise",
"Exception",
"(",
"\"A richdem.rd3array or numpy.ndarray is required!\"",
")"... | 35.857143 | 26.081633 |
def _needs_ref_WCS(reglist):
""" Check if the region list contains shapes in image-like coordinates
"""
from pyregion.wcs_helper import image_like_coordformats
for r in reglist:
if r.coord_format in image_like_coordformats:
return True
return False | [
"def",
"_needs_ref_WCS",
"(",
"reglist",
")",
":",
"from",
"pyregion",
".",
"wcs_helper",
"import",
"image_like_coordformats",
"for",
"r",
"in",
"reglist",
":",
"if",
"r",
".",
"coord_format",
"in",
"image_like_coordformats",
":",
"return",
"True",
"return",
"Fa... | 31.222222 | 16 |
def __query_cmd(self, command, device=None):
"""Calls a command"""
base_url = u'%s&switchcmd=%s' % (self.__homeauto_url_with_sid(), command)
if device is None:
url = base_url
else:
url = '%s&ain=%s' % (base_url, device)
if self.__debug:
print... | [
"def",
"__query_cmd",
"(",
"self",
",",
"command",
",",
"device",
"=",
"None",
")",
":",
"base_url",
"=",
"u'%s&switchcmd=%s'",
"%",
"(",
"self",
".",
"__homeauto_url_with_sid",
"(",
")",
",",
"command",
")",
"if",
"device",
"is",
"None",
":",
"url",
"="... | 28.615385 | 20.076923 |
def sed2(img, contour=None, shape=[3, 4]):
"""
plot tiled image of multiple slices
:param img:
:param contour:
:param shape:
:return:
"""
"""
:param img:
:param contour:
:param shape:
:return:
"""
plt.imshow(slices(img, shape), cmap='gray')
... | [
"def",
"sed2",
"(",
"img",
",",
"contour",
"=",
"None",
",",
"shape",
"=",
"[",
"3",
",",
"4",
"]",
")",
":",
"\"\"\"\r\n :param img:\r\n :param contour:\r\n :param shape:\r\n :return:\r\n \"\"\"",
"plt",
".",
"imshow",
"(",
"slices",
"(",
"img",
",... | 19.473684 | 15.263158 |
def addobject(bunchdt, data, commdct, key, theidf, aname=None, **kwargs):
"""add an object to the eplus model"""
obj = newrawobject(data, commdct, key)
abunch = obj2bunch(data, commdct, obj)
if aname:
namebunch(abunch, aname)
data.dt[key].append(obj)
bunchdt[key].append(abunch)
for k... | [
"def",
"addobject",
"(",
"bunchdt",
",",
"data",
",",
"commdct",
",",
"key",
",",
"theidf",
",",
"aname",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"obj",
"=",
"newrawobject",
"(",
"data",
",",
"commdct",
",",
"key",
")",
"abunch",
"=",
"obj2... | 35.454545 | 12 |
def moreData(ra,dec,box):
"""Search the CFHT archive for more images of this location"""
import cfhtCutout
cdata={'ra_deg': ra, 'dec_deg': dec, 'radius_deg': 0.2}
inter=cfhtCutout.find_images(cdata,0.2) | [
"def",
"moreData",
"(",
"ra",
",",
"dec",
",",
"box",
")",
":",
"import",
"cfhtCutout",
"cdata",
"=",
"{",
"'ra_deg'",
":",
"ra",
",",
"'dec_deg'",
":",
"dec",
",",
"'radius_deg'",
":",
"0.2",
"}",
"inter",
"=",
"cfhtCutout",
".",
"find_images",
"(",
... | 33.666667 | 15.5 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.