text stringlengths 89 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 630 |
|---|---|---|---|
def _build_schema(self, s):
"""Recursive schema builder, called by `json_schema`.
"""
w = self._whatis(s)
if w == self.IS_LIST:
w0 = self._whatis(s[0])
js = {"type": "array",
"items": {"type": self._jstype(w0, s[0])}}
elif w == self.IS_DI... | [
"def",
"_build_schema",
"(",
"self",
",",
"s",
")",
":",
"w",
"=",
"self",
".",
"_whatis",
"(",
"s",
")",
"if",
"w",
"==",
"self",
".",
"IS_LIST",
":",
"w0",
"=",
"self",
".",
"_whatis",
"(",
"s",
"[",
"0",
"]",
")",
"js",
"=",
"{",
"\"type\"... | 37.2 | 14.1 |
def sources(
self):
"""*The results of the search returned as a python list of dictionaries*
**Usage:**
.. code-block:: python
sources = tns.sources
"""
sourceResultsList = []
sourceResultsList[:] = [dict(l) for l in self.sourceResultsLi... | [
"def",
"sources",
"(",
"self",
")",
":",
"sourceResultsList",
"=",
"[",
"]",
"sourceResultsList",
"[",
":",
"]",
"=",
"[",
"dict",
"(",
"l",
")",
"for",
"l",
"in",
"self",
".",
"sourceResultsList",
"]",
"return",
"sourceResultsList"
] | 26.461538 | 19.307692 |
def sample(self, cursor):
"""Extract records randomly from the database.
Continue until the target proportion of the items have been
extracted, or until `min_items` if this is larger.
If `max_items` is non-negative, do not extract more than these.
This function is a generator, y... | [
"def",
"sample",
"(",
"self",
",",
"cursor",
")",
":",
"count",
"=",
"cursor",
".",
"count",
"(",
")",
"# special case: empty collection",
"if",
"count",
"==",
"0",
":",
"self",
".",
"_empty",
"=",
"True",
"raise",
"ValueError",
"(",
"\"Empty collection\"",
... | 35.072727 | 17.163636 |
def generate_strings(project_base_dir, localization_bundle_path, tmp_directory, exclude_dirs, include_strings_file,
special_ui_components_prefix):
"""
Calls the builtin 'genstrings' command with JTLocalizedString as the string to search for,
and adds strings extracted from UI elements i... | [
"def",
"generate_strings",
"(",
"project_base_dir",
",",
"localization_bundle_path",
",",
"tmp_directory",
",",
"exclude_dirs",
",",
"include_strings_file",
",",
"special_ui_components_prefix",
")",
":",
"localization_directory",
"=",
"os",
".",
"path",
".",
"join",
"("... | 44.881356 | 30.033898 |
def post_ticket(self, title, body):
'''post_ticket will post a ticket to the uservoice helpdesk
Parameters
==========
title: the title (subject) of the issue
body: the message to send
'''
# Populate the ticket
ticket = {'subject': title,
... | [
"def",
"post_ticket",
"(",
"self",
",",
"title",
",",
"body",
")",
":",
"# Populate the ticket",
"ticket",
"=",
"{",
"'subject'",
":",
"title",
",",
"'message'",
":",
"body",
"}",
"response",
"=",
"self",
".",
"client",
".",
"post",
"(",
"\"/api/v1/tickets... | 30.833333 | 20.166667 |
def render(self, **context):
"""
Render this template by applying it to `context`.
@params:
`context`: a dictionary of values to use in this rendering.
@returns:
The rendered string
"""
# Make the complete context we'll use.
localns = self.envs.copy()
localns.update(context)
try:
exec(str(se... | [
"def",
"render",
"(",
"self",
",",
"*",
"*",
"context",
")",
":",
"# Make the complete context we'll use.",
"localns",
"=",
"self",
".",
"envs",
".",
"copy",
"(",
")",
"localns",
".",
"update",
"(",
"context",
")",
"try",
":",
"exec",
"(",
"str",
"(",
... | 33.46 | 18.78 |
def free_identifier(self, lineno=None):
"""Return a new free identifier as :class:`~jinja2.nodes.InternalName`."""
self._last_identifier += 1
rv = object.__new__(nodes.InternalName)
nodes.Node.__init__(rv, 'fi%d' % self._last_identifier, lineno=lineno)
return rv | [
"def",
"free_identifier",
"(",
"self",
",",
"lineno",
"=",
"None",
")",
":",
"self",
".",
"_last_identifier",
"+=",
"1",
"rv",
"=",
"object",
".",
"__new__",
"(",
"nodes",
".",
"InternalName",
")",
"nodes",
".",
"Node",
".",
"__init__",
"(",
"rv",
",",... | 49.5 | 12.5 |
def user_account(self):
"""Return the user account information."""
self.account_info = None
url = 'https://tccna.honeywell.com/WebAPI/emea/api/v1/userAccount'
response = requests.get(url, headers=self._headers())
response.raise_for_status()
self.account_info = response... | [
"def",
"user_account",
"(",
"self",
")",
":",
"self",
".",
"account_info",
"=",
"None",
"url",
"=",
"'https://tccna.honeywell.com/WebAPI/emea/api/v1/userAccount'",
"response",
"=",
"requests",
".",
"get",
"(",
"url",
",",
"headers",
"=",
"self",
".",
"_headers",
... | 31.818182 | 19.636364 |
def _process_panel_group_configuration(self, config):
"""Adds a panel group to the dashboard."""
panel_group_slug = config.get('PANEL_GROUP')
try:
dashboard = config.get('PANEL_GROUP_DASHBOARD')
if not dashboard:
LOG.warning("Skipping %s because it doesn't... | [
"def",
"_process_panel_group_configuration",
"(",
"self",
",",
"config",
")",
":",
"panel_group_slug",
"=",
"config",
".",
"get",
"(",
"'PANEL_GROUP'",
")",
"try",
":",
"dashboard",
"=",
"config",
".",
"get",
"(",
"'PANEL_GROUP_DASHBOARD'",
")",
"if",
"not",
"... | 48.242424 | 16.242424 |
def get_user_groups(self, user_name):
"""Get a list of groups associated to a user.
:param user_name: name of user to list groups
:returns: list of groups
:raises: HTTPResponseError in case an HTTP error status was returned
"""
res = self._make_ocs_request(
... | [
"def",
"get_user_groups",
"(",
"self",
",",
"user_name",
")",
":",
"res",
"=",
"self",
".",
"_make_ocs_request",
"(",
"'GET'",
",",
"self",
".",
"OCS_SERVICE_CLOUD",
",",
"'users/'",
"+",
"user_name",
"+",
"'/groups'",
",",
")",
"if",
"res",
".",
"status_c... | 30.380952 | 18 |
async def fetch_neighbourhood(lat: float, long: float) -> Optional[dict]:
"""
Gets the neighbourhood from the fetch that is associated with the given postcode.
:return: A neighbourhood object parsed from the fetch.
:raise ApiError: When there was an error connecting to the API.
"""
lookup_url =... | [
"async",
"def",
"fetch_neighbourhood",
"(",
"lat",
":",
"float",
",",
"long",
":",
"float",
")",
"->",
"Optional",
"[",
"dict",
"]",
":",
"lookup_url",
"=",
"f\"https://data.police.uk/api/locate-neighbourhood?q={lat},{long}\"",
"async",
"with",
"ClientSession",
"(",
... | 45.857143 | 23.285714 |
def add_ruleclause_name(self, ns_name, rid) -> bool:
"""Create a tree.Rule"""
ns_name.parser_tree = parsing.Rule(self.value(rid))
return True | [
"def",
"add_ruleclause_name",
"(",
"self",
",",
"ns_name",
",",
"rid",
")",
"->",
"bool",
":",
"ns_name",
".",
"parser_tree",
"=",
"parsing",
".",
"Rule",
"(",
"self",
".",
"value",
"(",
"rid",
")",
")",
"return",
"True"
] | 37.5 | 13 |
def update(self, project, params={}, **options):
"""A specific, existing project can be updated by making a PUT request on the
URL for that project. Only the fields provided in the `data` block will be
updated; any unspecified fields will remain unchanged.
When using this metho... | [
"def",
"update",
"(",
"self",
",",
"project",
",",
"params",
"=",
"{",
"}",
",",
"*",
"*",
"options",
")",
":",
"path",
"=",
"\"/projects/%s\"",
"%",
"(",
"project",
")",
"return",
"self",
".",
"client",
".",
"put",
"(",
"path",
",",
"params",
",",... | 43.055556 | 19.055556 |
def authors(self):
"""
Get the authors of the current :class:`.Paper` instance.
Uses ``authors_full`` if it is available. Otherwise, uses
``authors_init``.
Returns
-------
authors : :class:`.Feature`
Author names are in the format ``LAST F``.
... | [
"def",
"authors",
"(",
"self",
")",
":",
"if",
"hasattr",
"(",
"self",
",",
"'authors_full'",
")",
":",
"return",
"self",
".",
"authors_full",
"elif",
"hasattr",
"(",
"self",
",",
"'authors_init'",
")",
":",
"return",
"self",
".",
"authors_init",
"else",
... | 26.473684 | 17.526316 |
def prepare_recently_opened_state_machines_list_for_storage(self):
""" Reduce number of paths in the recent opened state machines to limit from gui config """
from rafcon.gui.singleton import global_gui_config
num = global_gui_config.get_config_value('NUMBER_OF_RECENT_OPENED_STATE_MACHINES_STORE... | [
"def",
"prepare_recently_opened_state_machines_list_for_storage",
"(",
"self",
")",
":",
"from",
"rafcon",
".",
"gui",
".",
"singleton",
"import",
"global_gui_config",
"num",
"=",
"global_gui_config",
".",
"get_config_value",
"(",
"'NUMBER_OF_RECENT_OPENED_STATE_MACHINES_STOR... | 83.166667 | 33.333333 |
def _compute_term_4(self, C, mag, R):
"""
(a16 + a17.*M + a18.*M.*M + a19.*M.*M.*M).*(d(r).^3)
"""
return (
(C['a16'] + C['a17'] * mag + C['a18'] * np.power(mag, 2) +
C['a19'] * np.power(mag, 3)) * np.power(R, 3)
) | [
"def",
"_compute_term_4",
"(",
"self",
",",
"C",
",",
"mag",
",",
"R",
")",
":",
"return",
"(",
"(",
"C",
"[",
"'a16'",
"]",
"+",
"C",
"[",
"'a17'",
"]",
"*",
"mag",
"+",
"C",
"[",
"'a18'",
"]",
"*",
"np",
".",
"power",
"(",
"mag",
",",
"2"... | 34 | 15.75 |
def init_kernel32(kernel32=None):
"""Load a unique instance of WinDLL into memory, set arg/return types, and get stdout/err handles.
1. Since we are setting DLL function argument types and return types, we need to maintain our own instance of
kernel32 to prevent overriding (or being overwritten by) user... | [
"def",
"init_kernel32",
"(",
"kernel32",
"=",
"None",
")",
":",
"if",
"not",
"kernel32",
":",
"kernel32",
"=",
"ctypes",
".",
"LibraryLoader",
"(",
"ctypes",
".",
"WinDLL",
")",
".",
"kernel32",
"# Load our own instance. Unique memory address.",
"kernel32",
".",
... | 44 | 27.648649 |
def get_serializer_info(self, serializer):
"""
Given an instance of a serializer, return a dictionary of metadata
about its fields.
"""
if hasattr(serializer, 'child'):
# If this is a `ListSerializer` then we want to examine the
# underlying child serializ... | [
"def",
"get_serializer_info",
"(",
"self",
",",
"serializer",
")",
":",
"if",
"hasattr",
"(",
"serializer",
",",
"'child'",
")",
":",
"# If this is a `ListSerializer` then we want to examine the",
"# underlying child serializer instance instead.",
"serializer",
"=",
"serializ... | 37.117647 | 16.647059 |
def list(self, friendly_name=values.unset,
evaluate_worker_attributes=values.unset, worker_sid=values.unset,
limit=None, page_size=None):
"""
Lists TaskQueueInstance records from the API as a list.
Unlike stream(), this operation is eager and will load `limit` records i... | [
"def",
"list",
"(",
"self",
",",
"friendly_name",
"=",
"values",
".",
"unset",
",",
"evaluate_worker_attributes",
"=",
"values",
".",
"unset",
",",
"worker_sid",
"=",
"values",
".",
"unset",
",",
"limit",
"=",
"None",
",",
"page_size",
"=",
"None",
")",
... | 57.642857 | 30.857143 |
def has_cwd(state, dir, incorrect_msg="Your current working directory should be `{{dir}}`. Use `cd {{dir}}` to navigate there."):
"""Check whether the student is in the expected directory.
This check is typically used before using ``has_expr_output()``
to make sure the student didn't navigate somewhere els... | [
"def",
"has_cwd",
"(",
"state",
",",
"dir",
",",
"incorrect_msg",
"=",
"\"Your current working directory should be `{{dir}}`. Use `cd {{dir}}` to navigate there.\"",
")",
":",
"expr",
"=",
"\"[[ $PWD == '{}' ]]\"",
".",
"format",
"(",
"dir",
")",
"_msg",
"=",
"state",
"... | 44.347826 | 32.826087 |
def next(self):
"""Weather data record.
Yields:
dict
"""
record = self.epw_data.next()
local_time = _muck_w_date(record)
record['datetime'] = local_time
# does this fix a specific data set or a general issue?
if self.DST:
localdt =... | [
"def",
"next",
"(",
"self",
")",
":",
"record",
"=",
"self",
".",
"epw_data",
".",
"next",
"(",
")",
"local_time",
"=",
"_muck_w_date",
"(",
"record",
")",
"record",
"[",
"'datetime'",
"]",
"=",
"local_time",
"# does this fix a specific data set or a general iss... | 30.611111 | 17.611111 |
def flatten_top_level_keys(data, top_level_keys):
""" Helper method to flatten a nested dict of dicts (one level)
Example:
{'a': {'b': 'bbb'}} becomes {'a_-_b': 'bbb'}
The separator '_-_' gets formatted later for the column headers
Args:
data: the dict to flatt... | [
"def",
"flatten_top_level_keys",
"(",
"data",
",",
"top_level_keys",
")",
":",
"flattened_data",
"=",
"{",
"}",
"for",
"top_level_key",
"in",
"top_level_keys",
":",
"if",
"data",
"[",
"top_level_key",
"]",
"is",
"None",
":",
"flattened_data",
"[",
"top_level_key... | 33.636364 | 22.454545 |
def dump(self, dump_filename, pickle_protocol=pickle.HIGHEST_PROTOCOL):
"""Saves the profiling result to a file
:param dump_filename: path to a file
:type dump_filename: str
:param pickle_protocol: version of pickle protocol
:type pickle_protocol: int
"""
result... | [
"def",
"dump",
"(",
"self",
",",
"dump_filename",
",",
"pickle_protocol",
"=",
"pickle",
".",
"HIGHEST_PROTOCOL",
")",
":",
"result",
"=",
"self",
".",
"result",
"(",
")",
"with",
"open",
"(",
"dump_filename",
",",
"'wb'",
")",
"as",
"f",
":",
"pickle",
... | 33.846154 | 17.692308 |
def db_ws010c(self, value=None):
""" Corresponds to IDD Field `db_ws010c`
Mean coincident dry-bulb temperature to wind speed corresponding to 1.0% cumulative frequency for coldest month
Args:
value (float): value for IDD Field `db_ws010c`
Unit: C
if ... | [
"def",
"db_ws010c",
"(",
"self",
",",
"value",
"=",
"None",
")",
":",
"if",
"value",
"is",
"not",
"None",
":",
"try",
":",
"value",
"=",
"float",
"(",
"value",
")",
"except",
"ValueError",
":",
"raise",
"ValueError",
"(",
"'value {} need to be of type floa... | 37.714286 | 22.952381 |
def done(self, on_success=None, on_failure=None):
"""Attaches some callbacks to the promise and returns the promise."""
if on_success is not None:
if self._state == 'pending':
self._callbacks.append(on_success)
elif self._state == 'resolved':
on_su... | [
"def",
"done",
"(",
"self",
",",
"on_success",
"=",
"None",
",",
"on_failure",
"=",
"None",
")",
":",
"if",
"on_success",
"is",
"not",
"None",
":",
"if",
"self",
".",
"_state",
"==",
"'pending'",
":",
"self",
".",
"_callbacks",
".",
"append",
"(",
"o... | 42.692308 | 5.384615 |
def get_coefficient(self, metabolite_id):
"""
Return the stoichiometric coefficient of a metabolite.
Parameters
----------
metabolite_id : str or cobra.Metabolite
"""
if isinstance(metabolite_id, Metabolite):
return self._metabolites[metabolite_id]
... | [
"def",
"get_coefficient",
"(",
"self",
",",
"metabolite_id",
")",
":",
"if",
"isinstance",
"(",
"metabolite_id",
",",
"Metabolite",
")",
":",
"return",
"self",
".",
"_metabolites",
"[",
"metabolite_id",
"]",
"_id_to_metabolites",
"=",
"{",
"m",
".",
"id",
":... | 31.428571 | 19 |
def previous_key(self, cache_key):
"""If there was a previous successful build for the given key, return the previous key.
:param cache_key: A CacheKey object (as returned by CacheKeyGenerator.key_for().
:returns: The previous cache_key, or None if there was not a previous build.
"""
if not self.ca... | [
"def",
"previous_key",
"(",
"self",
",",
"cache_key",
")",
":",
"if",
"not",
"self",
".",
"cacheable",
"(",
"cache_key",
")",
":",
"# We should never successfully cache an uncacheable CacheKey.",
"return",
"None",
"previous_hash",
"=",
"self",
".",
"_read_sha",
"(",... | 39.428571 | 19.571429 |
def get_endpoint_path(self, endpoint_id):
'''return the first fullpath to a folder in the endpoint based on
expanding the user's home from the globus config file. This
function is fragile but I don't see any other way to do it.
Parameters
==========
endpoint_id: the endpoint ... | [
"def",
"get_endpoint_path",
"(",
"self",
",",
"endpoint_id",
")",
":",
"config",
"=",
"os",
".",
"path",
".",
"expanduser",
"(",
"\"~/.globusonline/lta/config-paths\"",
")",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"config",
")",
":",
"bot",
"."... | 28.516129 | 24.709677 |
def k_fold_cross_validation(
fitters,
df,
duration_col,
event_col=None,
k=5,
evaluation_measure=concordance_index,
predictor="predict_expectation",
predictor_kwargs={},
fitter_kwargs={},
): # pylint: disable=dangerous-default-value,too-many-arguments,too-many-locals
"""
Perf... | [
"def",
"k_fold_cross_validation",
"(",
"fitters",
",",
"df",
",",
"duration_col",
",",
"event_col",
"=",
"None",
",",
"k",
"=",
"5",
",",
"evaluation_measure",
"=",
"concordance_index",
",",
"predictor",
"=",
"\"predict_expectation\"",
",",
"predictor_kwargs",
"="... | 36.83 | 23.57 |
def pid_exists(value, pidtype=None):
"""Check if a persistent identifier exists.
:param value: The PID value.
:param pidtype: The pid value (Default: None).
:returns: `True` if the PID exists.
"""
try:
PersistentIdentifier.get(pidtype, value)
return True
except PIDDoesNotExi... | [
"def",
"pid_exists",
"(",
"value",
",",
"pidtype",
"=",
"None",
")",
":",
"try",
":",
"PersistentIdentifier",
".",
"get",
"(",
"pidtype",
",",
"value",
")",
"return",
"True",
"except",
"PIDDoesNotExistError",
":",
"return",
"False"
] | 28.166667 | 12.666667 |
def send_response(self, transaction):
"""
Finalize to add the client to the list of observer.
:type transaction: Transaction
:param transaction: the transaction that owns the response
:return: the transaction unmodified
"""
host, port = transaction.request.source... | [
"def",
"send_response",
"(",
"self",
",",
"transaction",
")",
":",
"host",
",",
"port",
"=",
"transaction",
".",
"request",
".",
"source",
"key_token",
"=",
"hash",
"(",
"str",
"(",
"host",
")",
"+",
"str",
"(",
"port",
")",
"+",
"str",
"(",
"transac... | 47.913043 | 20.695652 |
def adjust_chunksize(self, current_chunksize, file_size=None):
"""Get a chunksize close to current that fits within all S3 limits.
:type current_chunksize: int
:param current_chunksize: The currently configured chunksize.
:type file_size: int or None
:param file_size: The size ... | [
"def",
"adjust_chunksize",
"(",
"self",
",",
"current_chunksize",
",",
"file_size",
"=",
"None",
")",
":",
"chunksize",
"=",
"current_chunksize",
"if",
"file_size",
"is",
"not",
"None",
":",
"chunksize",
"=",
"self",
".",
"_adjust_for_max_parts",
"(",
"chunksize... | 43.8125 | 20.6875 |
def file_download(self, item_id: str, item_name: str, dir_name: str) -> bool:
"""
Download file from Google Drive
:param item_id:
:param dir_name:
:return:
"""
service = self.__get_service()
request = service.files().get_media(fileId=item_id)
self.... | [
"def",
"file_download",
"(",
"self",
",",
"item_id",
":",
"str",
",",
"item_name",
":",
"str",
",",
"dir_name",
":",
"str",
")",
"->",
"bool",
":",
"service",
"=",
"self",
".",
"__get_service",
"(",
")",
"request",
"=",
"service",
".",
"files",
"(",
... | 34.117647 | 15.529412 |
def get_group_list(self):
"""
获取分组列表
返回JSON示例::
{
"groups": [
{
"cnt": 8,
"id": 0,
"name": "未分组"
},
{
"cnt": 0... | [
"def",
"get_group_list",
"(",
"self",
")",
":",
"url",
"=",
"'https://mp.weixin.qq.com/cgi-bin/contactmanage?t=user/index&pagesize=10&pageidx=0&type=0&groupid=0&lang=zh_CN&f=json&token={token}'",
".",
"format",
"(",
"token",
"=",
"self",
".",
"__token",
",",
")",
"headers",
"... | 29.680851 | 20.914894 |
def transform(src, dst, converter,
overwrite=False, stream=True, chunksize=1024**2, **kwargs):
"""
A file stream transform IO utility function.
:param src: original file path
:param dst: destination file path
:param converter: binary content converter function
:param overwrite: de... | [
"def",
"transform",
"(",
"src",
",",
"dst",
",",
"converter",
",",
"overwrite",
"=",
"False",
",",
"stream",
"=",
"True",
",",
"chunksize",
"=",
"1024",
"**",
"2",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"overwrite",
":",
"# pragma: no cover",
... | 36.742857 | 13.771429 |
def _run_in_reactor(self, function, _, args, kwargs):
"""
Implementation: A decorator that ensures the wrapped function runs in
the reactor thread.
When the wrapped function is called, an EventualResult is returned.
"""
def runs_in_reactor(result, args, kwargs):
... | [
"def",
"_run_in_reactor",
"(",
"self",
",",
"function",
",",
"_",
",",
"args",
",",
"kwargs",
")",
":",
"def",
"runs_in_reactor",
"(",
"result",
",",
"args",
",",
"kwargs",
")",
":",
"d",
"=",
"maybeDeferred",
"(",
"function",
",",
"*",
"args",
",",
... | 36.625 | 19.5 |
async def install_agent(self, connection, nonce, machine_id):
"""
:param object connection: Connection to Juju API
:param str nonce: The nonce machine specification
:param str machine_id: The id assigned to the machine
:return: bool: If the initialization was successful
... | [
"async",
"def",
"install_agent",
"(",
"self",
",",
"connection",
",",
"nonce",
",",
"machine_id",
")",
":",
"# The path where the Juju agent should be installed.",
"data_dir",
"=",
"\"/var/lib/juju\"",
"# Disabling this prevents `apt-get update` from running initially, so",
"# ch... | 33.96 | 20.44 |
def is_module_installed(module_name, version=None, installed_version=None,
interpreter=None):
"""
Return True if module *module_name* is installed
If version is not None, checking module version
(module must have an attribute named '__version__')
version may starts ... | [
"def",
"is_module_installed",
"(",
"module_name",
",",
"version",
"=",
"None",
",",
"installed_version",
"=",
"None",
",",
"interpreter",
"=",
"None",
")",
":",
"if",
"interpreter",
":",
"if",
"osp",
".",
"isfile",
"(",
"interpreter",
")",
"and",
"(",
"'py... | 41.011494 | 18.114943 |
def _estimate_eval_intervals(ritz, indices, indices_remaining,
eps_min=0,
eps_max=0,
eps_res=None):
'''Estimate evals based on eval inclusion theorem + heuristic.
:returns: Intervals object with inclusion... | [
"def",
"_estimate_eval_intervals",
"(",
"ritz",
",",
"indices",
",",
"indices_remaining",
",",
"eps_min",
"=",
"0",
",",
"eps_max",
"=",
"0",
",",
"eps_res",
"=",
"None",
")",
":",
"if",
"len",
"(",
"indices",
")",
"==",
"0",
":",
"return",
"utils",
".... | 38.866667 | 16.9 |
def setter(self, fset):
"""
To be used as a decorator. Will define the decorated method
as a write pipe method to be called when client writes to the pipe
"""
self.fset = fset
self.pipe_write = PipeWriteType.PIPE_READ_WRITE
return self | [
"def",
"setter",
"(",
"self",
",",
"fset",
")",
":",
"self",
".",
"fset",
"=",
"fset",
"self",
".",
"pipe_write",
"=",
"PipeWriteType",
".",
"PIPE_READ_WRITE",
"return",
"self"
] | 35.5 | 16.25 |
def RV_com2(self):
"""RVs of star 2 relative to center-of-mass
"""
return -self.RV * (self.M1 / (self.M1 + self.M2)) | [
"def",
"RV_com2",
"(",
"self",
")",
":",
"return",
"-",
"self",
".",
"RV",
"*",
"(",
"self",
".",
"M1",
"/",
"(",
"self",
".",
"M1",
"+",
"self",
".",
"M2",
")",
")"
] | 34.25 | 9.75 |
def canny(img, threshold1=255/3, threshold2=255, **kwargs):
""" canny edge """
import cv2
# edges=None, apertureSize=None, L2gradient=None
if img.ndim <= 3:
edge = cv2.Canny(img, threshold1, threshold2, **kwargs)
if edge.ndim == 2:
edge = np.expand_dims(edge, 2)
elif img.... | [
"def",
"canny",
"(",
"img",
",",
"threshold1",
"=",
"255",
"/",
"3",
",",
"threshold2",
"=",
"255",
",",
"*",
"*",
"kwargs",
")",
":",
"import",
"cv2",
"# edges=None, apertureSize=None, L2gradient=None",
"if",
"img",
".",
"ndim",
"<=",
"3",
":",
"edge",
... | 34.625 | 17.5 |
def _checkout(self, treeish):
'''
Helper function to checkout something
:param treeish:
String for '`tag`', '`branch`', or remote tracking '-B `banch`'
'''
return self.m(
'checking out "%s"' % (treeish),
cmdd=dict(cmd='git checkout %s' % (tre... | [
"def",
"_checkout",
"(",
"self",
",",
"treeish",
")",
":",
"return",
"self",
".",
"m",
"(",
"'checking out \"%s\"'",
"%",
"(",
"treeish",
")",
",",
"cmdd",
"=",
"dict",
"(",
"cmd",
"=",
"'git checkout %s'",
"%",
"(",
"treeish",
")",
",",
"cwd",
"=",
... | 28.230769 | 23.615385 |
def init_widget(self):
""" Our widget may not exist yet so we have to diverge from the normal
way of doing initialization. See `update_widget`
"""
if not self.widget:
return
super(AndroidSnackbar, self).init_widget()
d = self.declaration
#:... | [
"def",
"init_widget",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"widget",
":",
"return",
"super",
"(",
"AndroidSnackbar",
",",
"self",
")",
".",
"init_widget",
"(",
")",
"d",
"=",
"self",
".",
"declaration",
"#: Bind events",
"self",
".",
"widget"... | 32.9 | 17.1 |
def interpolate(self, times, proj=PlateCarree()) -> np.ndarray:
"""Interpolates a trajectory in time. """
if proj not in self.interpolator:
self.interpolator[proj] = interp1d(
np.stack(t.to_pydatetime().timestamp() for t in self.timestamp),
proj.transform_poi... | [
"def",
"interpolate",
"(",
"self",
",",
"times",
",",
"proj",
"=",
"PlateCarree",
"(",
")",
")",
"->",
"np",
".",
"ndarray",
":",
"if",
"proj",
"not",
"in",
"self",
".",
"interpolator",
":",
"self",
".",
"interpolator",
"[",
"proj",
"]",
"=",
"interp... | 42.916667 | 15.416667 |
def derivesha256address(self):
""" Derive address using ``RIPEMD160(SHA256(x))`` """
pkbin = unhexlify(repr(self._pubkey))
addressbin = ripemd160(hexlify(hashlib.sha256(pkbin).digest()))
return Base58(hexlify(addressbin).decode('ascii')) | [
"def",
"derivesha256address",
"(",
"self",
")",
":",
"pkbin",
"=",
"unhexlify",
"(",
"repr",
"(",
"self",
".",
"_pubkey",
")",
")",
"addressbin",
"=",
"ripemd160",
"(",
"hexlify",
"(",
"hashlib",
".",
"sha256",
"(",
"pkbin",
")",
".",
"digest",
"(",
")... | 53 | 12.8 |
def _extract_features(self):
"""
Get the feature data from the log file necessary for a reduction
"""
for parsed_line in self.parsed_lines:
result = {'raw': parsed_line}
if 'ip' in parsed_line:
result['ip'] = parsed_line['ip']
if r... | [
"def",
"_extract_features",
"(",
"self",
")",
":",
"for",
"parsed_line",
"in",
"self",
".",
"parsed_lines",
":",
"result",
"=",
"{",
"'raw'",
":",
"parsed_line",
"}",
"if",
"'ip'",
"in",
"parsed_line",
":",
"result",
"[",
"'ip'",
"]",
"=",
"parsed_line",
... | 37.454545 | 13.090909 |
def _set_email_list(self, v, load=False):
"""
Setter method for email_list, mapped from YANG variable /rbridge_id/maps/email/email_list (list)
If this variable is read-only (config: false) in the
source YANG file, then _set_email_list is considered as a private
method. Backends looking to populate t... | [
"def",
"_set_email_list",
"(",
"self",
",",
"v",
",",
"load",
"=",
"False",
")",
":",
"if",
"hasattr",
"(",
"v",
",",
"\"_utype\"",
")",
":",
"v",
"=",
"v",
".",
"_utype",
"(",
"v",
")",
"try",
":",
"t",
"=",
"YANGDynClass",
"(",
"v",
",",
"bas... | 121.681818 | 58.454545 |
def _serie_format(self, serie, value):
"""Format an independent value for the serie"""
kwargs = {'chart': self, 'serie': serie, 'index': None}
formatter = (serie.formatter or self.formatter or self._value_format)
kwargs = filter_kwargs(formatter, kwargs)
return formatter(value, ... | [
"def",
"_serie_format",
"(",
"self",
",",
"serie",
",",
"value",
")",
":",
"kwargs",
"=",
"{",
"'chart'",
":",
"self",
",",
"'serie'",
":",
"serie",
",",
"'index'",
":",
"None",
"}",
"formatter",
"=",
"(",
"serie",
".",
"formatter",
"or",
"self",
"."... | 46.142857 | 16 |
def open(cls, filename):
""" Read an image file from disk
Parameters
----------
filename : string
Name of file to read as an image file. This file may be gzip
(``.gz``) or bzip2 (``.bz2``) compressed.
"""
if filename.endswith('.gz'):
... | [
"def",
"open",
"(",
"cls",
",",
"filename",
")",
":",
"if",
"filename",
".",
"endswith",
"(",
"'.gz'",
")",
":",
"fp",
"=",
"gzip",
".",
"open",
"(",
"filename",
",",
"'rb'",
")",
"try",
":",
"return",
"cls",
"(",
"fp",
",",
"filename",
",",
"com... | 31.708333 | 14.833333 |
def get_project(conn, vm_):
'''
Return the project to use.
'''
try:
projects = conn.ex_list_projects()
except AttributeError:
# with versions <0.15 of libcloud this is causing an AttributeError.
log.warning('Cannot get projects, you may need to update libcloud to 0.15 or late... | [
"def",
"get_project",
"(",
"conn",
",",
"vm_",
")",
":",
"try",
":",
"projects",
"=",
"conn",
".",
"ex_list_projects",
"(",
")",
"except",
"AttributeError",
":",
"# with versions <0.15 of libcloud this is causing an AttributeError.",
"log",
".",
"warning",
"(",
"'Ca... | 31.857143 | 26.809524 |
def decode_list(cls, obj, element_type):
# type: (List[Any], ConjureTypeType) -> List[Any]
"""Decodes json into a list, handling conversion of the elements.
Args:
obj: the json object to decode
element_type: a class object which is the conjure type of
the... | [
"def",
"decode_list",
"(",
"cls",
",",
"obj",
",",
"element_type",
")",
":",
"# type: (List[Any], ConjureTypeType) -> List[Any]",
"if",
"not",
"isinstance",
"(",
"obj",
",",
"list",
")",
":",
"raise",
"Exception",
"(",
"\"expected a python list\"",
")",
"return",
... | 38.6875 | 16.5625 |
def transform_annotation(self, ann, duration):
'''Transform an annotation to static label encoding.
Parameters
----------
ann : jams.Annotation
The annotation to convert
duration : number > 0
The duration of the track
Returns
-------
... | [
"def",
"transform_annotation",
"(",
"self",
",",
"ann",
",",
"duration",
")",
":",
"intervals",
"=",
"np",
".",
"asarray",
"(",
"[",
"[",
"0",
",",
"1",
"]",
"]",
")",
"values",
"=",
"list",
"(",
"[",
"obs",
".",
"value",
"for",
"obs",
"in",
"ann... | 31.172414 | 20.62069 |
def add_file(dk_api, kitchen, recipe_name, message, api_file_key):
"""
returns a string.
:param dk_api: -- api object
:param kitchen: string
:param recipe_name: string
:param message: string -- commit message, string
:param api_file_key: string -- directory wher... | [
"def",
"add_file",
"(",
"dk_api",
",",
"kitchen",
",",
"recipe_name",
",",
"message",
",",
"api_file_key",
")",
":",
"rc",
"=",
"DKReturnCode",
"(",
")",
"if",
"kitchen",
"is",
"None",
"or",
"recipe_name",
"is",
"None",
"or",
"message",
"is",
"None",
"or... | 36.682927 | 19.170732 |
def write_svg_debug(matrix, version, out, scale=15, border=None,
fallback_color='fuchsia', color_mapping=None,
add_legend=True):
"""\
Internal SVG serializer which is useful to debugging purposes.
This function is not exposed to the QRCode class by intention and the
... | [
"def",
"write_svg_debug",
"(",
"matrix",
",",
"version",
",",
"out",
",",
"scale",
"=",
"15",
",",
"border",
"=",
"None",
",",
"fallback_color",
"=",
"'fuchsia'",
",",
"color_mapping",
"=",
"None",
",",
"add_legend",
"=",
"True",
")",
":",
"clr_mapping",
... | 44.767857 | 19.928571 |
def generate_master_proteins(psms, protcol):
"""Fed with a psms generator, this returns the master proteins present
in the PSM table. PSMs with multiple master proteins are excluded."""
master_proteins = {}
if not protcol:
protcol = mzidtsvdata.HEADER_MASTER_PROT
for psm in psms:
pro... | [
"def",
"generate_master_proteins",
"(",
"psms",
",",
"protcol",
")",
":",
"master_proteins",
"=",
"{",
"}",
"if",
"not",
"protcol",
":",
"protcol",
"=",
"mzidtsvdata",
".",
"HEADER_MASTER_PROT",
"for",
"psm",
"in",
"psms",
":",
"protacc",
"=",
"psm",
"[",
... | 36.823529 | 10.058824 |
def configure_arrays(self):
"""Get the SCI and ERR data."""
self.science = self.hdulist['sci', 1].data
self.err = self.hdulist['err', 1].data
self.dq = self.hdulist['dq', 1].data
if (self.ampstring == 'ABCD'):
self.science = np.concatenate(
(self.scien... | [
"def",
"configure_arrays",
"(",
"self",
")",
":",
"self",
".",
"science",
"=",
"self",
".",
"hdulist",
"[",
"'sci'",
",",
"1",
"]",
".",
"data",
"self",
".",
"err",
"=",
"self",
".",
"hdulist",
"[",
"'err'",
",",
"1",
"]",
".",
"data",
"self",
".... | 44.4 | 11.933333 |
def get_readable_time_string(seconds):
"""Returns human readable string from number of seconds"""
seconds = int(seconds)
minutes = seconds // 60
seconds = seconds % 60
hours = minutes // 60
minutes = minutes % 60
days = hours // 24
hours = hours % 24
result = ""
if days > 0:
... | [
"def",
"get_readable_time_string",
"(",
"seconds",
")",
":",
"seconds",
"=",
"int",
"(",
"seconds",
")",
"minutes",
"=",
"seconds",
"//",
"60",
"seconds",
"=",
"seconds",
"%",
"60",
"hours",
"=",
"minutes",
"//",
"60",
"minutes",
"=",
"minutes",
"%",
"60... | 32.809524 | 21.952381 |
def PALIGNR(cpu, dest, src, offset):
"""ALIGNR concatenates the destination operand (the first operand) and the source
operand (the second operand) into an intermediate composite, shifts the composite
at byte granularity to the right by a constant immediate, and extracts the right-
... | [
"def",
"PALIGNR",
"(",
"cpu",
",",
"dest",
",",
"src",
",",
"offset",
")",
":",
"dest",
".",
"write",
"(",
"Operators",
".",
"EXTRACT",
"(",
"Operators",
".",
"CONCAT",
"(",
"dest",
".",
"size",
"*",
"2",
",",
"dest",
".",
"read",
"(",
")",
",",
... | 54.5 | 19.3 |
def getOverlayTexelAspect(self, ulOverlayHandle):
"""Gets the aspect ratio of the texels in the overlay. Defaults to 1.0"""
fn = self.function_table.getOverlayTexelAspect
pfTexelAspect = c_float()
result = fn(ulOverlayHandle, byref(pfTexelAspect))
return result, pfTexelAspect.va... | [
"def",
"getOverlayTexelAspect",
"(",
"self",
",",
"ulOverlayHandle",
")",
":",
"fn",
"=",
"self",
".",
"function_table",
".",
"getOverlayTexelAspect",
"pfTexelAspect",
"=",
"c_float",
"(",
")",
"result",
"=",
"fn",
"(",
"ulOverlayHandle",
",",
"byref",
"(",
"p... | 45.285714 | 12.857143 |
def unpack(self, buff, offset=0):
"""Unpack binary data into python object."""
super().unpack(buff, offset)
code_class = ErrorType(self.error_type).get_class()
self.code = code_class(self.code) | [
"def",
"unpack",
"(",
"self",
",",
"buff",
",",
"offset",
"=",
"0",
")",
":",
"super",
"(",
")",
".",
"unpack",
"(",
"buff",
",",
"offset",
")",
"code_class",
"=",
"ErrorType",
"(",
"self",
".",
"error_type",
")",
".",
"get_class",
"(",
")",
"self"... | 44.2 | 6.2 |
def split(s, posix=True):
"""Split the string s using shell-like syntax.
Args:
s (str): String to split
posix (bool): Use posix split
Returns:
list of str: List of string parts
"""
if isinstance(s, six.binary_type):
s = s.decode("utf-8")
return shlex.split(s, po... | [
"def",
"split",
"(",
"s",
",",
"posix",
"=",
"True",
")",
":",
"if",
"isinstance",
"(",
"s",
",",
"six",
".",
"binary_type",
")",
":",
"s",
"=",
"s",
".",
"decode",
"(",
"\"utf-8\"",
")",
"return",
"shlex",
".",
"split",
"(",
"s",
",",
"posix",
... | 24.461538 | 13.923077 |
def GetMessage(self, log_source, lcid, message_identifier):
"""Retrieves a specific message for a specific Event Log source.
Args:
log_source (str): Event Log source.
lcid (int): language code identifier (LCID).
message_identifier (int): message identifier.
Returns:
str: message st... | [
"def",
"GetMessage",
"(",
"self",
",",
"log_source",
",",
"lcid",
",",
"message_identifier",
")",
":",
"event_log_provider_key",
"=",
"self",
".",
"_GetEventLogProviderKey",
"(",
"log_source",
")",
"if",
"not",
"event_log_provider_key",
":",
"return",
"None",
"gen... | 29.25 | 19.96875 |
def visit_Dict(self, node: ast.Dict) -> Dict[Any, Any]:
"""Visit keys and values and assemble a dictionary with the results."""
recomputed_dict = dict() # type: Dict[Any, Any]
for key, val in zip(node.keys, node.values):
recomputed_dict[self.visit(node=key)] = self.visit(node=val)
... | [
"def",
"visit_Dict",
"(",
"self",
",",
"node",
":",
"ast",
".",
"Dict",
")",
"->",
"Dict",
"[",
"Any",
",",
"Any",
"]",
":",
"recomputed_dict",
"=",
"dict",
"(",
")",
"# type: Dict[Any, Any]",
"for",
"key",
",",
"val",
"in",
"zip",
"(",
"node",
".",
... | 49.75 | 17.375 |
def broadcast(self, gossip_message, message_type, exclude=None):
"""Broadcast gossip messages.
Broadcast the message to all peers unless they are in the excluded
list.
Args:
gossip_message: The message to be broadcast.
message_type: Type of the message.
... | [
"def",
"broadcast",
"(",
"self",
",",
"gossip_message",
",",
"message_type",
",",
"exclude",
"=",
"None",
")",
":",
"with",
"self",
".",
"_lock",
":",
"if",
"exclude",
"is",
"None",
":",
"exclude",
"=",
"[",
"]",
"for",
"connection_id",
"in",
"self",
"... | 38.416667 | 16.666667 |
def map_query_string(self):
"""Maps the GET query string params the the query_key_mapper dict and
updates the request's GET QueryDict with the mapped keys.
"""
if (not self.query_key_mapper or
self.request.method == 'POST'):
# Nothing to map, don't do anything.
... | [
"def",
"map_query_string",
"(",
"self",
")",
":",
"if",
"(",
"not",
"self",
".",
"query_key_mapper",
"or",
"self",
".",
"request",
".",
"method",
"==",
"'POST'",
")",
":",
"# Nothing to map, don't do anything.",
"# return self.request.POST",
"return",
"{",
"}",
... | 39.071429 | 14.785714 |
def update(self, section, params={}, **options):
"""A specific, existing section can be updated by making a PUT request on
the URL for that project. Only the fields provided in the `data` block
will be updated; any unspecified fields will remain unchanged. (note that
at this time, the o... | [
"def",
"update",
"(",
"self",
",",
"section",
",",
"params",
"=",
"{",
"}",
",",
"*",
"*",
"options",
")",
":",
"path",
"=",
"\"/sections/%s\"",
"%",
"(",
"section",
")",
"return",
"self",
".",
"client",
".",
"put",
"(",
"path",
",",
"params",
",",... | 45.473684 | 20.842105 |
def derive_data_encryption_key(source_key, algorithm, message_id):
"""Derives the data encryption key using the defined algorithm.
:param bytes source_key: Raw source key
:param algorithm: Algorithm used to encrypt this body
:type algorithm: aws_encryption_sdk.identifiers.Algorithm
:param bytes mes... | [
"def",
"derive_data_encryption_key",
"(",
"source_key",
",",
"algorithm",
",",
"message_id",
")",
":",
"key",
"=",
"source_key",
"if",
"algorithm",
".",
"kdf_type",
"is",
"not",
"None",
":",
"key",
"=",
"algorithm",
".",
"kdf_type",
"(",
"algorithm",
"=",
"a... | 37.75 | 13.15 |
def setup_data(X, y, tokenizer, proc_data_path, **kwargs):
"""Setup data
Args:
X: text data,
y: data labels,
tokenizer: A Tokenizer instance
proc_data_path: Path for the processed data
"""
# only build vocabulary once (e.g. training data)
train = ... | [
"def",
"setup_data",
"(",
"X",
",",
"y",
",",
"tokenizer",
",",
"proc_data_path",
",",
"*",
"*",
"kwargs",
")",
":",
"# only build vocabulary once (e.g. training data)",
"train",
"=",
"not",
"tokenizer",
".",
"has_vocab",
"if",
"train",
":",
"tokenizer",
".",
... | 28.588235 | 14.941176 |
def hpo_diseases(username, password, hpo_ids, p_value_treshold=1):
"""Return the list of HGNC symbols that match annotated HPO terms.
Args:
username (str): username to use for phenomizer connection
password (str): password to use for phenomizer connection
Returns:
query_result: a g... | [
"def",
"hpo_diseases",
"(",
"username",
",",
"password",
",",
"hpo_ids",
",",
"p_value_treshold",
"=",
"1",
")",
":",
"# skip querying Phenomizer unless at least one HPO terms exists",
"try",
":",
"results",
"=",
"query_phenomizer",
".",
"query",
"(",
"username",
",",... | 33.846154 | 20.115385 |
def stalk_buffer(self, pid, address, size, action = None):
"""
Sets a one-shot page breakpoint and notifies
when the given buffer is accessed.
@see: L{dont_watch_variable}
@type pid: int
@param pid: Process global ID.
@type address: int
@param address... | [
"def",
"stalk_buffer",
"(",
"self",
",",
"pid",
",",
"address",
",",
"size",
",",
"action",
"=",
"None",
")",
":",
"self",
".",
"__set_buffer_watch",
"(",
"pid",
",",
"address",
",",
"size",
",",
"action",
",",
"True",
")"
] | 28.8 | 19.12 |
def ParseOptions(cls, options, analysis_plugin):
"""Parses and validates options.
Args:
options (argparse.Namespace): parser options.
analysis_plugin (WindowsServicePlugin): analysis plugin to configure.
Raises:
BadConfigObject: when the output module object is of the wrong type.
"""... | [
"def",
"ParseOptions",
"(",
"cls",
",",
"options",
",",
"analysis_plugin",
")",
":",
"if",
"not",
"isinstance",
"(",
"analysis_plugin",
",",
"windows_services",
".",
"WindowsServicesAnalysisPlugin",
")",
":",
"raise",
"errors",
".",
"BadConfigObject",
"(",
"(",
... | 37.157895 | 20.368421 |
def handle_wcs(self, pkt):
"""
This part of the protocol is used by IRAF to bidirectionally
communicate metadata about frames in the framebuffers.
IIS WCS format:
name - title\n
a b c d tx ty z1 z2 zt\n
region_name sx sy snx sny dx dy dnx dny\n
object_ref... | [
"def",
"handle_wcs",
"(",
"self",
",",
"pkt",
")",
":",
"self",
".",
"logger",
".",
"debug",
"(",
"\"handle wcs\"",
")",
"if",
"pkt",
".",
"tid",
"&",
"IIS_READ",
":",
"self",
".",
"logger",
".",
"debug",
"(",
"\"iis read\"",
")",
"# Return the WCS for t... | 40.425926 | 19.166667 |
def populateFromRow(self, readGroupRecord):
"""
Populate the instance variables using the specified DB row.
"""
self._sampleName = readGroupRecord.samplename
self._biosampleId = readGroupRecord.biosampleid
self._description = readGroupRecord.description
self._pred... | [
"def",
"populateFromRow",
"(",
"self",
",",
"readGroupRecord",
")",
":",
"self",
".",
"_sampleName",
"=",
"readGroupRecord",
".",
"samplename",
"self",
".",
"_biosampleId",
"=",
"readGroupRecord",
".",
"biosampleid",
"self",
".",
"_description",
"=",
"readGroupRec... | 51.315789 | 14.473684 |
def __check_axes(axes):
'''Check if "axes" is an instance of an axis object. If not, use `gca`.'''
if axes is None:
import matplotlib.pyplot as plt
axes = plt.gca()
elif not isinstance(axes, Axes):
raise ValueError("`axes` must be an instance of matplotlib.axes.Axes. "
... | [
"def",
"__check_axes",
"(",
"axes",
")",
":",
"if",
"axes",
"is",
"None",
":",
"import",
"matplotlib",
".",
"pyplot",
"as",
"plt",
"axes",
"=",
"plt",
".",
"gca",
"(",
")",
"elif",
"not",
"isinstance",
"(",
"axes",
",",
"Axes",
")",
":",
"raise",
"... | 42.222222 | 20.666667 |
def _cmp_by_local_origin(path1, path2):
"""Select locally originating path as best path.
Locally originating routes are network routes, redistributed routes,
or aggregated routes. For now we are going to prefer routes received
through a Flexinet-Peer as locally originating route compared to routes
... | [
"def",
"_cmp_by_local_origin",
"(",
"path1",
",",
"path2",
")",
":",
"# If both paths are from same sources we cannot compare them here.",
"if",
"path1",
".",
"source",
"==",
"path2",
".",
"source",
":",
"return",
"None",
"# Here we consider prefix from NC as locally originat... | 33.318182 | 21.363636 |
def docs(session):
"""Build the docs."""
# Build docs against the latest version of Python, because we can.
session.interpreter = 'python3.6'
# Set the virtualenv dirname.
session.virtualenv_dirname = 'docs'
# Install Sphinx and also all of the google-cloud-* packages.
session.chdir(os.pa... | [
"def",
"docs",
"(",
"session",
")",
":",
"# Build docs against the latest version of Python, because we can.",
"session",
".",
"interpreter",
"=",
"'python3.6'",
"# Set the virtualenv dirname.",
"session",
".",
"virtualenv_dirname",
"=",
"'docs'",
"# Install Sphinx and also all o... | 32.25 | 22.6875 |
def make_axis_dummies(frame, axis='minor', transform=None):
"""
Construct 1-0 dummy variables corresponding to designated axis
labels
Parameters
----------
frame : DataFrame
axis : {'major', 'minor'}, default 'minor'
transform : function, default None
Function to apply to axis l... | [
"def",
"make_axis_dummies",
"(",
"frame",
",",
"axis",
"=",
"'minor'",
",",
"transform",
"=",
"None",
")",
":",
"numbers",
"=",
"{",
"'major'",
":",
"0",
",",
"'minor'",
":",
"1",
"}",
"num",
"=",
"numbers",
".",
"get",
"(",
"axis",
",",
"axis",
")... | 31.176471 | 18.176471 |
def generate_directories(self, overwrite=False):
"""For all possible combinations of 'batchable' parameters. create a unique directory to story outputs
Each directory name is unique and contains the run parameters in the directory name
:param overwrite: If set to True will over write all files... | [
"def",
"generate_directories",
"(",
"self",
",",
"overwrite",
"=",
"False",
")",
":",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"self",
".",
"batch_output",
")",
":",
"try",
":",
"lg",
".",
"info",
"(",
"'Creating batch project directory'",
")",
... | 60.370968 | 33.08871 |
def fixity(self, response_format=None):
'''
Issues fixity check, return parsed graph
Args:
None
Returns:
(dict): ('verdict':(bool): verdict of fixity check, 'premis_graph':(rdflib.Graph): parsed PREMIS graph from check)
'''
# if no response_format, use default
if not response_format:
response... | [
"def",
"fixity",
"(",
"self",
",",
"response_format",
"=",
"None",
")",
":",
"# if no response_format, use default",
"if",
"not",
"response_format",
":",
"response_format",
"=",
"self",
".",
"repo",
".",
"default_serialization",
"# issue GET request for fixity check",
"... | 24.424242 | 28.606061 |
def sign_digest_deterministic(self, digest, hashfunc=None, sigencode=sigencode_string):
"""
Calculates 'k' from data itself, removing the need for strong
random generator and producing deterministic (reproducible) signatures.
See RFC 6979 for more details.
"""
secexp = se... | [
"def",
"sign_digest_deterministic",
"(",
"self",
",",
"digest",
",",
"hashfunc",
"=",
"None",
",",
"sigencode",
"=",
"sigencode_string",
")",
":",
"secexp",
"=",
"self",
".",
"privkey",
".",
"secret_multiplier",
"k",
"=",
"rfc6979",
".",
"generate_k",
"(",
"... | 45.909091 | 20.454545 |
def normalize_unitnumber(unit_number):
"""Returns a normalized unit number, i.e. integers
Raises exception X10InvalidUnitNumber if unit number appears to be invalid
"""
try:
try:
unit_number = int(unit_number)
except ValueError:
raise X10InvalidUnitNumber('%r not ... | [
"def",
"normalize_unitnumber",
"(",
"unit_number",
")",
":",
"try",
":",
"try",
":",
"unit_number",
"=",
"int",
"(",
"unit_number",
")",
"except",
"ValueError",
":",
"raise",
"X10InvalidUnitNumber",
"(",
"'%r not a valid unit number'",
"%",
"unit_number",
")",
"ex... | 41.571429 | 19.642857 |
def post(self, element):
"""
:param element: Element to post to Netuitive
:type element: object
"""
try:
if self.disabled is True:
element.clear_samples()
logging.error('Posting has been disabled. '
... | [
"def",
"post",
"(",
"self",
",",
"element",
")",
":",
"try",
":",
"if",
"self",
".",
"disabled",
"is",
"True",
":",
"element",
".",
"clear_samples",
"(",
")",
"logging",
".",
"error",
"(",
"'Posting has been disabled. '",
"'See previous errors for details.'",
... | 32.783333 | 18.95 |
def get_docstring(self, project_path, source, position, filename):
"""Return signature and docstring for current cursor call context
Some examples of call context::
func(|
func(arg|
func(arg,|
func(arg, func2(| # call context is func2
Signature ... | [
"def",
"get_docstring",
"(",
"self",
",",
"project_path",
",",
"source",
",",
"position",
",",
"filename",
")",
":",
"return",
"self",
".",
"_call",
"(",
"'get_docstring'",
",",
"project_path",
",",
"source",
",",
"position",
",",
"filename",
")"
] | 35.15 | 21.25 |
def login(self, email, password):
"""
:password: user password md5 digest
"""
payload = {
'account': email,
'password': password
}
code, msg, rv = self.request(
'mtop.alimusic.xuser.facade.xiamiuserservice.login',
payload
... | [
"def",
"login",
"(",
"self",
",",
"email",
",",
"password",
")",
":",
"payload",
"=",
"{",
"'account'",
":",
"email",
",",
"'password'",
":",
"password",
"}",
"code",
",",
"msg",
",",
"rv",
"=",
"self",
".",
"request",
"(",
"'mtop.alimusic.xuser.facade.x... | 30.388889 | 12.833333 |
def compiled_quil(self):
"""
If the Quil program associated with the Job was compiled (e.g., to translate it to the
QPU's natural gateset) return this compiled program.
:rtype: Optional[Program]
"""
prog = self._raw.get("program", {}).get("compiled-quil", None)
i... | [
"def",
"compiled_quil",
"(",
"self",
")",
":",
"prog",
"=",
"self",
".",
"_raw",
".",
"get",
"(",
"\"program\"",
",",
"{",
"}",
")",
".",
"get",
"(",
"\"compiled-quil\"",
",",
"None",
")",
"if",
"prog",
"is",
"not",
"None",
":",
"return",
"parse_prog... | 39.6 | 17.866667 |
def get_access_token(self, refresh_token):
"""
Use a refresh token to obtain a new access token
"""
token = requests.post(GOOGLE_OAUTH2_TOKEN_URL, data=dict(
refresh_token=refresh_token,
grant_type='refresh_token',
client_id=self.client_id,
... | [
"def",
"get_access_token",
"(",
"self",
",",
"refresh_token",
")",
":",
"token",
"=",
"requests",
".",
"post",
"(",
"GOOGLE_OAUTH2_TOKEN_URL",
",",
"data",
"=",
"dict",
"(",
"refresh_token",
"=",
"refresh_token",
",",
"grant_type",
"=",
"'refresh_token'",
",",
... | 27.75 | 15 |
async def publish(self, subject, payload,
ack_handler=None,
ack_wait=DEFAULT_ACK_WAIT,
):
"""
Publishes a payload onto a subject. By default, it will block
until the message which has been published has been acked back.
A... | [
"async",
"def",
"publish",
"(",
"self",
",",
"subject",
",",
"payload",
",",
"ack_handler",
"=",
"None",
",",
"ack_wait",
"=",
"DEFAULT_ACK_WAIT",
",",
")",
":",
"stan_subject",
"=",
"''",
".",
"join",
"(",
"[",
"self",
".",
"_pub_prefix",
",",
"'.'",
... | 36.65 | 14.816667 |
def channels(self):
"""The number of channels."""
if self.mf.mode() == mad.MODE_SINGLE_CHANNEL:
return 1
elif self.mf.mode() in (mad.MODE_DUAL_CHANNEL,
mad.MODE_JOINT_STEREO,
mad.MODE_STEREO):
return 2
... | [
"def",
"channels",
"(",
"self",
")",
":",
"if",
"self",
".",
"mf",
".",
"mode",
"(",
")",
"==",
"mad",
".",
"MODE_SINGLE_CHANNEL",
":",
"return",
"1",
"elif",
"self",
".",
"mf",
".",
"mode",
"(",
")",
"in",
"(",
"mad",
".",
"MODE_DUAL_CHANNEL",
","... | 33.090909 | 15.727273 |
def _path(self): # type: () -> str
"""Return the dotted path representation of this object
:rtype: str
"""
if self._parent:
return '{}.{}'.format(self._parent._path(), self._key_name())
return self._key_name() | [
"def",
"_path",
"(",
"self",
")",
":",
"# type: () -> str",
"if",
"self",
".",
"_parent",
":",
"return",
"'{}.{}'",
".",
"format",
"(",
"self",
".",
"_parent",
".",
"_path",
"(",
")",
",",
"self",
".",
"_key_name",
"(",
")",
")",
"return",
"self",
".... | 28.444444 | 18.222222 |
def syntax_check(domain): # pragma: no cover
"""
Check the syntax of the given domain.
:param domain: The domain to check the syntax for.
:type domain: str
:return: The syntax validity.
:rtype: bool
.. warning::
If an empty or a non-string :code:`domain` is given, we return :code... | [
"def",
"syntax_check",
"(",
"domain",
")",
":",
"# pragma: no cover",
"if",
"domain",
"and",
"isinstance",
"(",
"domain",
",",
"str",
")",
":",
"# * The given domain is not empty nor None.",
"# and",
"# * The given domain is a string.",
"# We silently load the configuration."... | 25 | 19.923077 |
def load_multiformat_time_series():
"""Loading time series data from a zip file in the repo"""
data = get_example_data('multiformat_time_series.json.gz')
pdf = pd.read_json(data)
pdf.ds = pd.to_datetime(pdf.ds, unit='s')
pdf.ds2 = pd.to_datetime(pdf.ds2, unit='s')
pdf.to_sql(
'multiform... | [
"def",
"load_multiformat_time_series",
"(",
")",
":",
"data",
"=",
"get_example_data",
"(",
"'multiformat_time_series.json.gz'",
")",
"pdf",
"=",
"pd",
".",
"read_json",
"(",
"data",
")",
"pdf",
".",
"ds",
"=",
"pd",
".",
"to_datetime",
"(",
"pdf",
".",
"ds"... | 33.121622 | 14.067568 |
def create_gc3pie_config_snippet(cluster):
"""
Create a configuration file snippet to be used with GC3Pie.
"""
auth_section = 'auth/elasticluster_%s' % cluster.name
resource_section = 'resource/elasticluster_%s' % cluster.name
cfg = RawConfigParser()
cfg.add_section(auth_section)
front... | [
"def",
"create_gc3pie_config_snippet",
"(",
"cluster",
")",
":",
"auth_section",
"=",
"'auth/elasticluster_%s'",
"%",
"cluster",
".",
"name",
"resource_section",
"=",
"'resource/elasticluster_%s'",
"%",
"cluster",
".",
"name",
"cfg",
"=",
"RawConfigParser",
"(",
")",
... | 42.75 | 20.3 |
def _as_dict(self, r):
"""Convert the record to a dictionary using field names as keys."""
d = dict()
for i, f in enumerate(self._field_names):
d[f] = r[i] if i < len(r) else None
return d | [
"def",
"_as_dict",
"(",
"self",
",",
"r",
")",
":",
"d",
"=",
"dict",
"(",
")",
"for",
"i",
",",
"f",
"in",
"enumerate",
"(",
"self",
".",
"_field_names",
")",
":",
"d",
"[",
"f",
"]",
"=",
"r",
"[",
"i",
"]",
"if",
"i",
"<",
"len",
"(",
... | 32.428571 | 17.142857 |
def add_crl(self, crl):
"""
Add a certificate revocation list to this store.
The certificate revocation lists added to a store will only be used if
the associated flags are configured to check certificate revocation
lists.
.. versionadded:: 16.1.0
:param CRL cr... | [
"def",
"add_crl",
"(",
"self",
",",
"crl",
")",
":",
"_openssl_assert",
"(",
"_lib",
".",
"X509_STORE_add_crl",
"(",
"self",
".",
"_store",
",",
"crl",
".",
"_crl",
")",
"!=",
"0",
")"
] | 36.533333 | 25.2 |
def dump(self, stream, state, mevm, conc_tx=None):
"""
Concretize and write a human readable version of the transaction into the stream. Used during testcase
generation.
:param stream: Output stream to write to. Typically a file.
:param manticore.ethereum.State state: state that... | [
"def",
"dump",
"(",
"self",
",",
"stream",
",",
"state",
",",
"mevm",
",",
"conc_tx",
"=",
"None",
")",
":",
"from",
".",
".",
"ethereum",
"import",
"ABI",
"# circular imports",
"from",
".",
".",
"ethereum",
".",
"manticore",
"import",
"flagged",
"is_som... | 43.903226 | 28.483871 |
def importCell (fileName, cellName, cellArgs = None, cellInstance = False):
h.initnrn()
varList = mechVarList() # list of properties for all density mechanisms and point processes
origGlob = getGlobals(list(varList['mechs'].keys())+list(varList['pointps'].keys()))
origGlob['v_init'] = -65 # add by han... | [
"def",
"importCell",
"(",
"fileName",
",",
"cellName",
",",
"cellArgs",
"=",
"None",
",",
"cellInstance",
"=",
"False",
")",
":",
"h",
".",
"initnrn",
"(",
")",
"varList",
"=",
"mechVarList",
"(",
")",
"# list of properties for all density mechanisms and point pro... | 43.474576 | 26.627119 |
def article(self):
"""
| Comment: Id of the associated article, if present
"""
if self.api and self.article_id:
return self.api._get_article(self.article_id) | [
"def",
"article",
"(",
"self",
")",
":",
"if",
"self",
".",
"api",
"and",
"self",
".",
"article_id",
":",
"return",
"self",
".",
"api",
".",
"_get_article",
"(",
"self",
".",
"article_id",
")"
] | 32.833333 | 9.833333 |
def inverse_transform(self, sequences):
"""Transform a list of sequences from internal indexing into
labels
Parameters
----------
sequences : list
List of sequences, each of which is one-dimensional array of
integers in ``0, ..., n_states_ - 1``.
... | [
"def",
"inverse_transform",
"(",
"self",
",",
"sequences",
")",
":",
"sequences",
"=",
"list_of_1d",
"(",
"sequences",
")",
"inverse_mapping",
"=",
"{",
"v",
":",
"k",
"for",
"k",
",",
"v",
"in",
"self",
".",
"mapping_",
".",
"items",
"(",
")",
"}",
... | 31.678571 | 20.571429 |
def private_vlan_mode(self, **kwargs):
"""Set PVLAN mode (promiscuous, host, trunk).
Args:
int_type (str): Type of interface. (gigabitethernet,
tengigabitethernet, etc)
name (str): Name of interface. (1/0/5, 1/0/10, etc)
mode (str): The switchport PVL... | [
"def",
"private_vlan_mode",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"int_type",
"=",
"kwargs",
".",
"pop",
"(",
"'int_type'",
")",
".",
"lower",
"(",
")",
"name",
"=",
"kwargs",
".",
"pop",
"(",
"'name'",
")",
"mode",
"=",
"kwargs",
".",
"p... | 42.084507 | 19.71831 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.