text stringlengths 89 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 630 |
|---|---|---|---|
def get_duplicate_vals(self, table, column):
"""Retrieve duplicate values in a column of a table."""
query = 'SELECT {0} FROM {1} GROUP BY {0} HAVING COUNT(*) > 1'.format(join_cols(column), wrap(table))
return self.fetch(query) | [
"def",
"get_duplicate_vals",
"(",
"self",
",",
"table",
",",
"column",
")",
":",
"query",
"=",
"'SELECT {0} FROM {1} GROUP BY {0} HAVING COUNT(*) > 1'",
".",
"format",
"(",
"join_cols",
"(",
"column",
")",
",",
"wrap",
"(",
"table",
")",
")",
"return",
"self",
... | 62 | 20.25 |
def reply_inform(self, connection, inform, orig_req):
"""Send an inform as part of the reply to an earlier request.
Parameters
----------
connection : ClientConnection object
The client to send the inform to.
inform : Message object
The inform message to ... | [
"def",
"reply_inform",
"(",
"self",
",",
"connection",
",",
"inform",
",",
"orig_req",
")",
":",
"if",
"isinstance",
"(",
"connection",
",",
"ClientRequestConnection",
")",
":",
"self",
".",
"_logger",
".",
"warn",
"(",
"'Deprecation warning: do not use self.reply... | 42.333333 | 16 |
def get_resource_area_by_host(self, area_id, host_id):
"""GetResourceAreaByHost.
[Preview API]
:param str area_id:
:param str host_id:
:rtype: :class:`<ResourceAreaInfo> <azure.devops.v5_0.location.models.ResourceAreaInfo>`
"""
route_values = {}
if area_id... | [
"def",
"get_resource_area_by_host",
"(",
"self",
",",
"area_id",
",",
"host_id",
")",
":",
"route_values",
"=",
"{",
"}",
"if",
"area_id",
"is",
"not",
"None",
":",
"route_values",
"[",
"'areaId'",
"]",
"=",
"self",
".",
"_serialize",
".",
"url",
"(",
"'... | 48.526316 | 19.789474 |
def func(f, xmin, xmax, step=None):
"""Create sample points from function <f>, which must be a
single-parameter function that returns a number (e.g., math.sin).
Parameters <xmin> and <xmax> specify the first and last X values, and
<step> specifies the sampling interval.
>>> chart_data.func(math.sin, 0,... | [
"def",
"func",
"(",
"f",
",",
"xmin",
",",
"xmax",
",",
"step",
"=",
"None",
")",
":",
"data",
"=",
"[",
"]",
"x",
"=",
"xmin",
"if",
"not",
"step",
":",
"step",
"=",
"(",
"xmax",
"-",
"xmin",
")",
"/",
"100.0",
"while",
"x",
"<",
"xmax",
"... | 40 | 31 |
def var(
self, axis=None, skipna=None, level=None, ddof=1, numeric_only=None, **kwargs
):
"""Computes variance across the DataFrame.
Args:
axis (int): The axis to take the variance on.
skipna (bool): True to skip NA values, false otherwise.
ddof (... | [
"def",
"var",
"(",
"self",
",",
"axis",
"=",
"None",
",",
"skipna",
"=",
"None",
",",
"level",
"=",
"None",
",",
"ddof",
"=",
"1",
",",
"numeric_only",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"axis",
"=",
"self",
".",
"_get_axis_number",
... | 33.576923 | 18.230769 |
def get_config_value(name, fallback=None):
"""Gets a config by name.
In the case where the config name is not found, will use fallback value."""
cli_config = CLIConfig(SF_CLI_CONFIG_DIR, SF_CLI_ENV_VAR_PREFIX)
return cli_config.get('servicefabric', name, fallback) | [
"def",
"get_config_value",
"(",
"name",
",",
"fallback",
"=",
"None",
")",
":",
"cli_config",
"=",
"CLIConfig",
"(",
"SF_CLI_CONFIG_DIR",
",",
"SF_CLI_ENV_VAR_PREFIX",
")",
"return",
"cli_config",
".",
"get",
"(",
"'servicefabric'",
",",
"name",
",",
"fallback",... | 34.5 | 21 |
def render_highstate(self, matches):
'''
Gather the state files and render them into a single unified salt
high data structure.
'''
highstate = self.building_highstate
all_errors = []
mods = set()
statefiles = []
for saltenv, states in six.iteritem... | [
"def",
"render_highstate",
"(",
"self",
",",
"matches",
")",
":",
"highstate",
"=",
"self",
".",
"building_highstate",
"all_errors",
"=",
"[",
"]",
"mods",
"=",
"set",
"(",
")",
"statefiles",
"=",
"[",
"]",
"for",
"saltenv",
",",
"states",
"in",
"six",
... | 45.666667 | 17.583333 |
def read_playlists(self):
self.playlists = []
self.selected_playlist = -1
files = glob.glob(path.join(self.stations_dir, '*.csv'))
if len(files) == 0:
return 0, -1
else:
for a_file in files:
a_file_name = ''.join(path.basename(a_file).split... | [
"def",
"read_playlists",
"(",
"self",
")",
":",
"self",
".",
"playlists",
"=",
"[",
"]",
"self",
".",
"selected_playlist",
"=",
"-",
"1",
"files",
"=",
"glob",
".",
"glob",
"(",
"path",
".",
"join",
"(",
"self",
".",
"stations_dir",
",",
"'*.csv'",
"... | 44.315789 | 17.368421 |
def rethrow_zerodiv(self):
"""[contextmanager] treat zero div as known exception."""
with np.errstate(divide="raise", invalid="raise"):
try:
yield
except (FloatingPointError, ZeroDivisionError) as e:
self.fail(ZeroDivisionError(*e.args)) | [
"def",
"rethrow_zerodiv",
"(",
"self",
")",
":",
"with",
"np",
".",
"errstate",
"(",
"divide",
"=",
"\"raise\"",
",",
"invalid",
"=",
"\"raise\"",
")",
":",
"try",
":",
"yield",
"except",
"(",
"FloatingPointError",
",",
"ZeroDivisionError",
")",
"as",
"e",... | 43.285714 | 16 |
def hash(self):
'''
:rtype: int
:return: hash of the field
'''
hashed = super(Group, self).hash()
return khash(hashed, frozenset(self._values)) | [
"def",
"hash",
"(",
"self",
")",
":",
"hashed",
"=",
"super",
"(",
"Group",
",",
"self",
")",
".",
"hash",
"(",
")",
"return",
"khash",
"(",
"hashed",
",",
"frozenset",
"(",
"self",
".",
"_values",
")",
")"
] | 26.428571 | 17.857143 |
def bandwidth(self):
"""Target bandwidth in bits/sec"""
self._bandwidth = self.lib.iperf_get_test_rate(self._test)
return self._bandwidth | [
"def",
"bandwidth",
"(",
"self",
")",
":",
"self",
".",
"_bandwidth",
"=",
"self",
".",
"lib",
".",
"iperf_get_test_rate",
"(",
"self",
".",
"_test",
")",
"return",
"self",
".",
"_bandwidth"
] | 39.5 | 14 |
def get(self, *args, **kwargs):
"""
Checks the cache to see if there's a cached entry for this pk. If not, fetches
using super then stores the result in cache.
Most of the logic here was gathered from a careful reading of
``django.db.models.sql.query.add_filter``
"""
... | [
"def",
"get",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"self",
".",
"query",
".",
"where",
":",
"# If there is any other ``where`` filter on this QuerySet just call",
"# super. There will be a where clause if this QuerySet has already",
"# b... | 45.769231 | 21.692308 |
def layers(self) -> Circuit:
"""Split DAGCircuit into layers, where the operations within each
layer operate on different qubits (and therefore commute).
Returns: A Circuit of Circuits, one Circuit per layer
"""
node_depth: Dict[Qubit, int] = {}
G = self.graph
f... | [
"def",
"layers",
"(",
"self",
")",
"->",
"Circuit",
":",
"node_depth",
":",
"Dict",
"[",
"Qubit",
",",
"int",
"]",
"=",
"{",
"}",
"G",
"=",
"self",
".",
"graph",
"for",
"elem",
"in",
"self",
":",
"depth",
"=",
"np",
".",
"max",
"(",
"list",
"("... | 32.478261 | 17.608696 |
def make_registryitem_valuename(valuename, condition='is', negate=False, preserve_case=False):
"""
Create a node for RegistryItem/ValueName
:return: A IndicatorItem represented as an Element node
"""
document = 'RegistryItem'
search = 'RegistryItem/ValueName'
content_type = 'string'
... | [
"def",
"make_registryitem_valuename",
"(",
"valuename",
",",
"condition",
"=",
"'is'",
",",
"negate",
"=",
"False",
",",
"preserve_case",
"=",
"False",
")",
":",
"document",
"=",
"'RegistryItem'",
"search",
"=",
"'RegistryItem/ValueName'",
"content_type",
"=",
"'s... | 41.153846 | 21.923077 |
def moothedata(data, key=None):
"""Return an amusing picture containing an item from a dict.
Parameters
----------
data: mapping
A mapping, such as a raster dataset's ``meta`` or ``profile``
property.
key:
A key of the ``data`` mapping.
"""
if not key:
key = ... | [
"def",
"moothedata",
"(",
"data",
",",
"key",
"=",
"None",
")",
":",
"if",
"not",
"key",
":",
"key",
"=",
"choice",
"(",
"list",
"(",
"data",
".",
"keys",
"(",
")",
")",
")",
"logger",
".",
"debug",
"(",
"\"Using randomly chosen key: %s\"",
",",
"key... | 29.9375 | 19.625 |
def _ConvertDataPropertyType(self, propType):
"""
Convert vmodl.reflect.DynamicTypeManager.PropertyTypeInfo to pyVmomi
data property definition
"""
if propType:
name = propType.name
version = propType.version
aType = propType.type
flags = self._ConvertAn... | [
"def",
"_ConvertDataPropertyType",
"(",
"self",
",",
"propType",
")",
":",
"if",
"propType",
":",
"name",
"=",
"propType",
".",
"name",
"version",
"=",
"propType",
".",
"version",
"aType",
"=",
"propType",
".",
"type",
"flags",
"=",
"self",
".",
"_ConvertA... | 31 | 14 |
def map_structprop_resnums_to_seqprop_resnums(self, resnums, structprop=None, chain_id=None, seqprop=None,
use_representatives=False):
"""Map a residue number in any StructProp + chain ID to any SeqProp's residue number.
Args:
resnums (int, ... | [
"def",
"map_structprop_resnums_to_seqprop_resnums",
"(",
"self",
",",
"resnums",
",",
"structprop",
"=",
"None",
",",
"chain_id",
"=",
"None",
",",
"seqprop",
"=",
"None",
",",
"use_representatives",
"=",
"False",
")",
":",
"resnums",
"=",
"ssbio",
".",
"utils... | 51.444444 | 30.728395 |
def ws_url(self):
"""websocket url matching the current request
turns http[s]://host[:port] into
ws[s]://host[:port]
"""
proto = self.request.protocol.replace('http', 'ws')
host = self.application.ipython_app.websocket_host # default to config value
if ho... | [
"def",
"ws_url",
"(",
"self",
")",
":",
"proto",
"=",
"self",
".",
"request",
".",
"protocol",
".",
"replace",
"(",
"'http'",
",",
"'ws'",
")",
"host",
"=",
"self",
".",
"application",
".",
"ipython_app",
".",
"websocket_host",
"# default to config value",
... | 37.818182 | 14.909091 |
def make_zipfile(zip_filename, base_dir, verbose=0, dry_run=0, compress=True,
mode='w'):
"""Create a zip file from all the files under 'base_dir'. The output
zip file will be named 'base_dir' + ".zip". Uses either the "zipfile"
Python module (if available) or the InfoZIP "zip" utility (if... | [
"def",
"make_zipfile",
"(",
"zip_filename",
",",
"base_dir",
",",
"verbose",
"=",
"0",
",",
"dry_run",
"=",
"0",
",",
"compress",
"=",
"True",
",",
"mode",
"=",
"'w'",
")",
":",
"import",
"zipfile",
"mkpath",
"(",
"os",
".",
"path",
".",
"dirname",
"... | 42.09375 | 20.21875 |
def _validate_isvalid_orcid(self, isvalid_orcid, field, value):
"""Checks for valid ORCID if given.
Args:
isvalid_orcid (`bool`): flag from schema indicating ORCID to be checked.
field (`str`): 'author'
value (`dict`): dictionary of author metadata.
The rule... | [
"def",
"_validate_isvalid_orcid",
"(",
"self",
",",
"isvalid_orcid",
",",
"field",
",",
"value",
")",
":",
"if",
"isvalid_orcid",
"and",
"'ORCID'",
"in",
"value",
":",
"try",
":",
"res",
"=",
"search_orcid",
"(",
"value",
"[",
"'ORCID'",
"]",
")",
"except"... | 42.34375 | 21.34375 |
def open_files(self, idx):
"""Open all files with an activated disk flag."""
for name in self:
if getattr(self, '_%s_diskflag' % name):
path = getattr(self, '_%s_path' % name)
file_ = open(path, 'rb+')
ndim = getattr(self, '_%s_ndim' % name)
... | [
"def",
"open_files",
"(",
"self",
",",
"idx",
")",
":",
"for",
"name",
"in",
"self",
":",
"if",
"getattr",
"(",
"self",
",",
"'_%s_diskflag'",
"%",
"name",
")",
":",
"path",
"=",
"getattr",
"(",
"self",
",",
"'_%s_path'",
"%",
"name",
")",
"file_",
... | 45.076923 | 10.384615 |
def process_action(self, request, queryset):
"""
Deletes the object(s). Successful deletes are logged.
Returns a 'render redirect' to the result of the
`get_done_url` method.
If a ProtectedError is raised, the `render` method
is called with message explaining the error a... | [
"def",
"process_action",
"(",
"self",
",",
"request",
",",
"queryset",
")",
":",
"count",
"=",
"0",
"try",
":",
"with",
"transaction",
".",
"commit_on_success",
"(",
")",
":",
"for",
"obj",
"in",
"queryset",
":",
"self",
".",
"log_action",
"(",
"obj",
... | 43.758621 | 17.344828 |
def utc_dt_to_local_dt(dtm):
"""Convert a UTC datetime to datetime in local timezone"""
utc_zone = mktz("UTC")
if dtm.tzinfo is not None and dtm.tzinfo != utc_zone:
raise ValueError(
"Expected dtm without tzinfo or with UTC, not %r" % (
dtm.tzinfo
)
)
... | [
"def",
"utc_dt_to_local_dt",
"(",
"dtm",
")",
":",
"utc_zone",
"=",
"mktz",
"(",
"\"UTC\"",
")",
"if",
"dtm",
".",
"tzinfo",
"is",
"not",
"None",
"and",
"dtm",
".",
"tzinfo",
"!=",
"utc_zone",
":",
"raise",
"ValueError",
"(",
"\"Expected dtm without tzinfo o... | 31.692308 | 16.769231 |
def delete_member(self, user):
"""Returns a response after attempting to remove
a member from the list.
"""
if not self.email_enabled:
raise EmailNotEnabledError("See settings.EMAIL_ENABLED")
return requests.delete(
f"{self.api_url}/{self.address}/members/... | [
"def",
"delete_member",
"(",
"self",
",",
"user",
")",
":",
"if",
"not",
"self",
".",
"email_enabled",
":",
"raise",
"EmailNotEnabledError",
"(",
"\"See settings.EMAIL_ENABLED\"",
")",
"return",
"requests",
".",
"delete",
"(",
"f\"{self.api_url}/{self.address}/members... | 37.5 | 12 |
def remove_envelop(self, begin, end):
"""
Removes all intervals completely enveloped in the given range.
Completes in O((r+m)*log n) time, where:
* n = size of the tree
* m = number of matches
* r = size of the search range
"""
hitlist = self.envelo... | [
"def",
"remove_envelop",
"(",
"self",
",",
"begin",
",",
"end",
")",
":",
"hitlist",
"=",
"self",
".",
"envelop",
"(",
"begin",
",",
"end",
")",
"for",
"iv",
"in",
"hitlist",
":",
"self",
".",
"remove",
"(",
"iv",
")"
] | 31.416667 | 10.416667 |
def url(self, request):
'''
Return absolute URL for assignment description.
'''
if self.pk:
if self.has_description():
return request.build_absolute_uri(reverse('assignment_description_file', args=[self.pk]))
else:
return self.d... | [
"def",
"url",
"(",
"self",
",",
"request",
")",
":",
"if",
"self",
".",
"pk",
":",
"if",
"self",
".",
"has_description",
"(",
")",
":",
"return",
"request",
".",
"build_absolute_uri",
"(",
"reverse",
"(",
"'assignment_description_file'",
",",
"args",
"=",
... | 32.272727 | 23 |
def revert_job(self, id, version, enforce_prior_version=None):
""" This endpoint reverts the job to an older version.
https://www.nomadproject.io/docs/http/job.html
arguments:
- id
- version, Specifies the job version to revert to.
optional_argume... | [
"def",
"revert_job",
"(",
"self",
",",
"id",
",",
"version",
",",
"enforce_prior_version",
"=",
"None",
")",
":",
"revert_json",
"=",
"{",
"\"JobID\"",
":",
"id",
",",
"\"JobVersion\"",
":",
"version",
",",
"\"EnforcePriorVersion\"",
":",
"enforce_prior_version"... | 46.333333 | 22.857143 |
def phase_uniquizer(all_phases):
"""Makes the names of phase measurement and attachments unique.
This function will make the names of measurements and attachments unique.
It modifies the input all_phases.
Args:
all_phases: the phases to make unique
Returns:
the phases now modified.
"""
measurem... | [
"def",
"phase_uniquizer",
"(",
"all_phases",
")",
":",
"measurement_name_maker",
"=",
"UniqueNameMaker",
"(",
"itertools",
".",
"chain",
".",
"from_iterable",
"(",
"phase",
".",
"measurements",
".",
"keys",
"(",
")",
"for",
"phase",
"in",
"all_phases",
"if",
"... | 37.684211 | 16.631579 |
def post(self, request, *args, **kwargs):
"""
Method for handling POST requests.
Validates submitted form and
formsets. Saves if valid, re displays
page with errors if invalid.
"""
self.object = self.get_object()
form_class = self.get_form_class()
... | [
"def",
"post",
"(",
"self",
",",
"request",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
".",
"object",
"=",
"self",
".",
"get_object",
"(",
")",
"form_class",
"=",
"self",
".",
"get_form_class",
"(",
")",
"form",
"=",
"self",
".",
... | 32.966667 | 10.9 |
def _delete_cgroup(self, path):
"""
Delete the specified cgroup.
:param path: The path of the cgroup to delete.
E.g. cpu/mygroup/mysubgroup
"""
node = trees.Tree().root
path_split = path.split("/")
for path_element in path_split:
name_to_node ... | [
"def",
"_delete_cgroup",
"(",
"self",
",",
"path",
")",
":",
"node",
"=",
"trees",
".",
"Tree",
"(",
")",
".",
"root",
"path_split",
"=",
"path",
".",
"split",
"(",
"\"/\"",
")",
"for",
"path_element",
"in",
"path_split",
":",
"name_to_node",
"=",
"{",... | 35.85 | 11.75 |
def upload_benchmark_run(self, dataset_name, table_name, run_id):
"""Upload benchmark run information to Bigquery.
Args:
dataset_name: string, the name of bigquery dataset where the data will be
uploaded.
table_name: string, the name of bigquery table under the dataset where
the dat... | [
"def",
"upload_benchmark_run",
"(",
"self",
",",
"dataset_name",
",",
"table_name",
",",
"run_id",
")",
":",
"expected_file",
"=",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"_logging_dir",
",",
"logger",
".",
"BENCHMARK_RUN_LOG_FILE_NAME",
")",
"with",... | 44.190476 | 20.428571 |
def find_element_by_class(self, class_, update=False) -> Elements:
'''Finds an element by class.
Args:
class_: The class of the element to be found.
update: If the interface has changed, this option should be True.
Returns:
The element if it was found.
... | [
"def",
"find_element_by_class",
"(",
"self",
",",
"class_",
",",
"update",
"=",
"False",
")",
"->",
"Elements",
":",
"return",
"self",
".",
"find_element",
"(",
"by",
"=",
"By",
".",
"CLASS",
",",
"value",
"=",
"class_",
",",
"update",
"=",
"update",
"... | 31.882353 | 26.470588 |
def d(self, depth=1):
"""Launches an interactive console at the point where it's called."""
info = self.inspect.getframeinfo(self.sys._getframe(1))
s = self.Stanza(self.indent)
s.add([info.function + ': '])
s.add([self.MAGENTA, 'Interactive console opened', self.NORMAL])
... | [
"def",
"d",
"(",
"self",
",",
"depth",
"=",
"1",
")",
":",
"info",
"=",
"self",
".",
"inspect",
".",
"getframeinfo",
"(",
"self",
".",
"sys",
".",
"_getframe",
"(",
"1",
")",
")",
"s",
"=",
"self",
".",
"Stanza",
"(",
"self",
".",
"indent",
")"... | 38.363636 | 14.590909 |
def sort_values(self, return_indexer=False, ascending=True):
"""
Return sorted copy of Index.
"""
if return_indexer:
_as = self.argsort()
if not ascending:
_as = _as[::-1]
sorted_index = self.take(_as)
return sorted_index, _... | [
"def",
"sort_values",
"(",
"self",
",",
"return_indexer",
"=",
"False",
",",
"ascending",
"=",
"True",
")",
":",
"if",
"return_indexer",
":",
"_as",
"=",
"self",
".",
"argsort",
"(",
")",
"if",
"not",
"ascending",
":",
"_as",
"=",
"_as",
"[",
":",
":... | 33.423077 | 13.192308 |
def lex_document(self, cli, document):
"""
Create a lexer function that takes a line number and returns the list
of (Token, text) tuples as the Pygments lexer returns for that line.
"""
# Cache of already lexed lines.
cache = {}
# Pygments generators that are cur... | [
"def",
"lex_document",
"(",
"self",
",",
"cli",
",",
"document",
")",
":",
"# Cache of already lexed lines.",
"cache",
"=",
"{",
"}",
"# Pygments generators that are currently lexing.",
"line_generators",
"=",
"{",
"}",
"# Map lexer generator to the line number.",
"def",
... | 38.057143 | 21.333333 |
def _add_record(table, data, buffer_size):
"""
Prepare and append a Record into its Table; flush to disk if necessary.
"""
fields = table.fields
# remove any keys that aren't relation fields
for invalid_key in set(data).difference([f.name for f in fields]):
del data[invalid_key]
tabl... | [
"def",
"_add_record",
"(",
"table",
",",
"data",
",",
"buffer_size",
")",
":",
"fields",
"=",
"table",
".",
"fields",
"# remove any keys that aren't relation fields",
"for",
"invalid_key",
"in",
"set",
"(",
"data",
")",
".",
"difference",
"(",
"[",
"f",
".",
... | 43.333333 | 13.466667 |
def draw_special_char_key(self, surface, key):
"""Default drawing method for special char key. Drawn as character key.
:param surface: Surface background should be drawn in.
:param key: Target key to be drawn.
"""
key.value = u'#'
if key.is_activated():
key.... | [
"def",
"draw_special_char_key",
"(",
"self",
",",
"surface",
",",
"key",
")",
":",
"key",
".",
"value",
"=",
"u'#'",
"if",
"key",
".",
"is_activated",
"(",
")",
":",
"key",
".",
"value",
"=",
"u'Ab'",
"self",
".",
"draw_character_key",
"(",
"surface",
... | 37.6 | 11.8 |
def use_defaults(self, data):
"""
Combine data with defaults and set aesthetics from parameters
stats should not override this method.
Parameters
----------
data : dataframe
Data used for drawing the geom.
Returns
-------
out : dataf... | [
"def",
"use_defaults",
"(",
"self",
",",
"data",
")",
":",
"missing",
"=",
"(",
"self",
".",
"aesthetics",
"(",
")",
"-",
"self",
".",
"aes_params",
".",
"keys",
"(",
")",
"-",
"set",
"(",
"data",
".",
"columns",
")",
")",
"for",
"ae",
"in",
"mis... | 25.709677 | 16.806452 |
def flush(self):
"""
Write out any data in the write buffer. This may do nothing if write
buffering is not turned on.
"""
self._write_all(self._wbuffer.getvalue())
self._wbuffer = StringIO()
return | [
"def",
"flush",
"(",
"self",
")",
":",
"self",
".",
"_write_all",
"(",
"self",
".",
"_wbuffer",
".",
"getvalue",
"(",
")",
")",
"self",
".",
"_wbuffer",
"=",
"StringIO",
"(",
")",
"return"
] | 30.875 | 13.375 |
def get_error_at(self, cursor):
"""Return error at position `cursor`."""
for error in self._errors:
if error.includes(self._vim.eval("expand('%:p')"), cursor):
return error
return None | [
"def",
"get_error_at",
"(",
"self",
",",
"cursor",
")",
":",
"for",
"error",
"in",
"self",
".",
"_errors",
":",
"if",
"error",
".",
"includes",
"(",
"self",
".",
"_vim",
".",
"eval",
"(",
"\"expand('%:p')\"",
")",
",",
"cursor",
")",
":",
"return",
"... | 38.5 | 13.166667 |
def eval(self, script, numkeys, *keys_and_args):
"""
Execute the Lua ``script``, specifying the ``numkeys`` the script
will touch and the key names and argument values in ``keys_and_args``.
Returns the result of the script.
In practice, use the object returned by ``register_scri... | [
"def",
"eval",
"(",
"self",
",",
"script",
",",
"numkeys",
",",
"*",
"keys_and_args",
")",
":",
"return",
"self",
".",
"execute_command",
"(",
"'EVAL'",
",",
"script",
",",
"numkeys",
",",
"*",
"keys_and_args",
")"
] | 46.7 | 20.5 |
def get_meta(collection):
"""Return the meta-description of a given resource.
:param collection: The collection to get meta-info for
"""
cls = endpoint_class(collection)
description = cls.meta()
return jsonify(description) | [
"def",
"get_meta",
"(",
"collection",
")",
":",
"cls",
"=",
"endpoint_class",
"(",
"collection",
")",
"description",
"=",
"cls",
".",
"meta",
"(",
")",
"return",
"jsonify",
"(",
"description",
")"
] | 24 | 17.8 |
def _setdefault_via_pathlist(external_dict,path_list,**kwargs):
'''
#if path_list already in external_dict, will do nothing
y = {}
path_list = ['c','b']
_setdefault_via_pathlist(y,path_list)
y
_setdefault_via_pathlist(y,path_list)
y = {}
_setdefault_vi... | [
"def",
"_setdefault_via_pathlist",
"(",
"external_dict",
",",
"path_list",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"(",
"'s2n'",
"in",
"kwargs",
")",
":",
"s2n",
"=",
"kwargs",
"[",
"'s2n'",
"]",
"else",
":",
"s2n",
"=",
"0",
"if",
"(",
"'n2s'",
"in... | 26.372549 | 17.745098 |
def handleLocalJob(self, jobNode): # type: (JobNode) -> Optional[int]
"""
To be called by issueBatchJobs.
Returns the jobID if the jobNode has been submitted to the local queue,
otherwise returns None
"""
if (not self.config.runCwlInternalJobsOnWorkers
a... | [
"def",
"handleLocalJob",
"(",
"self",
",",
"jobNode",
")",
":",
"# type: (JobNode) -> Optional[int]",
"if",
"(",
"not",
"self",
".",
"config",
".",
"runCwlInternalJobsOnWorkers",
"and",
"jobNode",
".",
"jobName",
".",
"startswith",
"(",
"CWL_INTERNAL_JOBS",
")",
"... | 37.916667 | 18.583333 |
def _got_response(self, msg):
'''
Decode and dispatch responses from the server.
Has already been unframed and deserialized into an object.
'''
#logger.debug("MSG: %r" % msg)
resp_id = msg.get('id', None)
if resp_id is None:
# subscription ... | [
"def",
"_got_response",
"(",
"self",
",",
"msg",
")",
":",
"#logger.debug(\"MSG: %r\" % msg)",
"resp_id",
"=",
"msg",
".",
"get",
"(",
"'id'",
",",
"None",
")",
"if",
"resp_id",
"is",
"None",
":",
"# subscription traffic comes with method set, but no req id.",
"meth... | 29.22449 | 23.306122 |
def sanity_check_memory_sync(self, wire_src_dict=None):
""" Check that all memories are synchronous unless explicitly specified as async.
While the semantics of 'm' memories reads is asynchronous, if you want your design
to use a block ram (on an FPGA or otherwise) you want to make sure the ind... | [
"def",
"sanity_check_memory_sync",
"(",
"self",
",",
"wire_src_dict",
"=",
"None",
")",
":",
"sync_mems",
"=",
"set",
"(",
"m",
"for",
"m",
"in",
"self",
".",
"logic_subset",
"(",
"'m'",
")",
"if",
"not",
"m",
".",
"op_param",
"[",
"1",
"]",
".",
"as... | 47.228571 | 20.371429 |
def init_atropos_wf(name='atropos_wf',
use_random_seed=True,
omp_nthreads=None,
mem_gb=3.0,
padding=10,
in_segmentation_model=list(ATROPOS_MODELS['T1w'].values())):
"""
Implements supersteps 6 and 7 of ``antsBrai... | [
"def",
"init_atropos_wf",
"(",
"name",
"=",
"'atropos_wf'",
",",
"use_random_seed",
"=",
"True",
",",
"omp_nthreads",
"=",
"None",
",",
"mem_gb",
"=",
"3.0",
",",
"padding",
"=",
"10",
",",
"in_segmentation_model",
"=",
"list",
"(",
"ATROPOS_MODELS",
"[",
"'... | 47.245192 | 21.841346 |
def coverage(self):
"""
Get the fraction of a subject is matched by its set of reads.
@return: The C{float} fraction of a subject matched by its reads.
"""
if self._targetLength == 0:
return 0.0
coverage = 0
for (intervalType, (start, end)) in self.w... | [
"def",
"coverage",
"(",
"self",
")",
":",
"if",
"self",
".",
"_targetLength",
"==",
"0",
":",
"return",
"0.0",
"coverage",
"=",
"0",
"for",
"(",
"intervalType",
",",
"(",
"start",
",",
"end",
")",
")",
"in",
"self",
".",
"walk",
"(",
")",
":",
"i... | 37.125 | 19.125 |
def update(self, **kwargs):
"""
Update a resource by passing in modifications via keyword arguments.
"""
data = self._generate_input_dict(**kwargs)
self.load(self.client.put('/'.join(self.url.split('/')[:-1]) + 's', data=data))
return self | [
"def",
"update",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"data",
"=",
"self",
".",
"_generate_input_dict",
"(",
"*",
"*",
"kwargs",
")",
"self",
".",
"load",
"(",
"self",
".",
"client",
".",
"put",
"(",
"'/'",
".",
"join",
"(",
"self",
".... | 40.142857 | 18.142857 |
def set_snap_server_variables(host, port, snap_extension='.xml', path=None):
""" Change dynamically port and host variable in xml Snap! project file"""
localdir = os.getcwd()
if path is None:
os.chdir(os.path.dirname(os.path.realpath(__file__)))
else:
os.chdir(path)
xml_files = [f f... | [
"def",
"set_snap_server_variables",
"(",
"host",
",",
"port",
",",
"snap_extension",
"=",
"'.xml'",
",",
"path",
"=",
"None",
")",
":",
"localdir",
"=",
"os",
".",
"getcwd",
"(",
")",
"if",
"path",
"is",
"None",
":",
"os",
".",
"chdir",
"(",
"os",
".... | 47 | 24.76 |
def delete_port(self, port_name):
"""
Deletes a port on the OVS instance.
This method is corresponding to the following ovs-vsctl command::
$ ovs-vsctl --if-exists del-port <bridge> <port>
"""
command = ovs_vsctl.VSCtlCommand(
'del-port', (self.br_name, ... | [
"def",
"delete_port",
"(",
"self",
",",
"port_name",
")",
":",
"command",
"=",
"ovs_vsctl",
".",
"VSCtlCommand",
"(",
"'del-port'",
",",
"(",
"self",
".",
"br_name",
",",
"port_name",
")",
",",
"'--if-exists'",
")",
"self",
".",
"run_command",
"(",
"[",
... | 33.818182 | 15.818182 |
def get_checked(self):
"""Return the list of checked items that do not have any child."""
checked = []
def get_checked_children(item):
if not self.tag_has("unchecked", item):
ch = self.get_children(item)
if not ch and self.tag_has("checked", item):
... | [
"def",
"get_checked",
"(",
"self",
")",
":",
"checked",
"=",
"[",
"]",
"def",
"get_checked_children",
"(",
"item",
")",
":",
"if",
"not",
"self",
".",
"tag_has",
"(",
"\"unchecked\"",
",",
"item",
")",
":",
"ch",
"=",
"self",
".",
"get_children",
"(",
... | 33 | 13.941176 |
def html(tag):
"""Return sequence of start and end regex patterns for simple HTML tag"""
return (HTML_START.format(tag=tag), HTML_END.format(tag=tag)) | [
"def",
"html",
"(",
"tag",
")",
":",
"return",
"(",
"HTML_START",
".",
"format",
"(",
"tag",
"=",
"tag",
")",
",",
"HTML_END",
".",
"format",
"(",
"tag",
"=",
"tag",
")",
")"
] | 52 | 17 |
def encode(encoding, data):
"""
Encodes the given data using the encoding that is specified
:param str encoding: encoding to use, should be one of the supported encoding
:param data: data to encode
:type data: str or bytes
:return: multibase encoded data
:rtype: bytes
:raises ValueError... | [
"def",
"encode",
"(",
"encoding",
",",
"data",
")",
":",
"data",
"=",
"ensure_bytes",
"(",
"data",
",",
"'utf8'",
")",
"try",
":",
"return",
"ENCODINGS_LOOKUP",
"[",
"encoding",
"]",
".",
"code",
"+",
"ENCODINGS_LOOKUP",
"[",
"encoding",
"]",
".",
"conve... | 36.625 | 20.375 |
def device_info(index=None):
"""Return a generator with information about each device.
If index is given, only one dictionary for the given device is
returned.
"""
if index is None:
return (device_info(i) for i in range(_pa.Pa_GetDeviceCount()))
else:
info = _pa.Pa_GetDeviceInf... | [
"def",
"device_info",
"(",
"index",
"=",
"None",
")",
":",
"if",
"index",
"is",
"None",
":",
"return",
"(",
"device_info",
"(",
"i",
")",
"for",
"i",
"in",
"range",
"(",
"_pa",
".",
"Pa_GetDeviceCount",
"(",
")",
")",
")",
"else",
":",
"info",
"=",... | 40.266667 | 22.6 |
def requestAccountUpdates(self, subscribe=True):
"""
Register to account updates
https://www.interactivebrokers.com/en/software/api/apiguide/java/reqaccountupdates.htm
"""
if self.subscribeAccount != subscribe:
self.subscribeAccount = subscribe
self.ibConn... | [
"def",
"requestAccountUpdates",
"(",
"self",
",",
"subscribe",
"=",
"True",
")",
":",
"if",
"self",
".",
"subscribeAccount",
"!=",
"subscribe",
":",
"self",
".",
"subscribeAccount",
"=",
"subscribe",
"self",
".",
"ibConn",
".",
"reqAccountUpdates",
"(",
"subsc... | 43.125 | 11.625 |
def avail_locations(call=None):
'''
List all available locations
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_locations function must be called with '
'-f or --function, or with the --list-locations option'
)
ret = {}
params = {'Action'... | [
"def",
"avail_locations",
"(",
"call",
"=",
"None",
")",
":",
"if",
"call",
"==",
"'action'",
":",
"raise",
"SaltCloudSystemExit",
"(",
"'The avail_locations function must be called with '",
"'-f or --function, or with the --list-locations option'",
")",
"ret",
"=",
"{",
... | 26.846154 | 19 |
def create(cls, api, run_id=None, project=None, username=None):
"""Create a run for the given project"""
run_id = run_id or util.generate_id()
project = project or api.settings.get("project")
mutation = gql('''
mutation upsertRun($project: String, $entity: String, $name: String!)... | [
"def",
"create",
"(",
"cls",
",",
"api",
",",
"run_id",
"=",
"None",
",",
"project",
"=",
"None",
",",
"username",
"=",
"None",
")",
":",
"run_id",
"=",
"run_id",
"or",
"util",
".",
"generate_id",
"(",
")",
"project",
"=",
"project",
"or",
"api",
"... | 37.5 | 18.0625 |
def start_server(app: web.Application = None, port: int = None,
address: str = None, **kwargs: Any) -> HTTPServer:
"""Start server with ``app`` on ``localhost:port``.
If port is not specified, use command line option of ``--port``.
"""
app = app or get_app()
port = port if port is ... | [
"def",
"start_server",
"(",
"app",
":",
"web",
".",
"Application",
"=",
"None",
",",
"port",
":",
"int",
"=",
"None",
",",
"address",
":",
"str",
"=",
"None",
",",
"*",
"*",
"kwargs",
":",
"Any",
")",
"->",
"HTTPServer",
":",
"app",
"=",
"app",
"... | 37.947368 | 15.736842 |
def __get_neighbors(self, cell):
"""!
@brief Returns neighbors for specified CLIQUE block as clique_block objects.
@return (list) Neighbors as clique_block objects.
"""
neighbors = []
location_neighbors = cell.get_location_neighbors(self.__amount_intervals)
... | [
"def",
"__get_neighbors",
"(",
"self",
",",
"cell",
")",
":",
"neighbors",
"=",
"[",
"]",
"location_neighbors",
"=",
"cell",
".",
"get_location_neighbors",
"(",
"self",
".",
"__amount_intervals",
")",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"location_nei... | 34.315789 | 21.947368 |
def from_file(cls, path=None):
"""
Read YAML config file. Returns Config object.
:raises IOError: if the path does not exist
"""
# None => use default
if path is None:
for path in cls.default_pathes():
try:
return cls.from_... | [
"def",
"from_file",
"(",
"cls",
",",
"path",
"=",
"None",
")",
":",
"# None => use default",
"if",
"path",
"is",
"None",
":",
"for",
"path",
"in",
"cls",
".",
"default_pathes",
"(",
")",
":",
"try",
":",
"return",
"cls",
".",
"from_file",
"(",
"path",
... | 35.851852 | 13.703704 |
def get_changesets(self, project=None, max_comment_length=None, skip=None, top=None, orderby=None, search_criteria=None):
"""GetChangesets.
Retrieve Tfvc Changesets
:param str project: Project ID or project name
:param int max_comment_length: Include details about associated work items i... | [
"def",
"get_changesets",
"(",
"self",
",",
"project",
"=",
"None",
",",
"max_comment_length",
"=",
"None",
",",
"skip",
"=",
"None",
",",
"top",
"=",
"None",
",",
"orderby",
"=",
"None",
",",
"search_criteria",
"=",
"None",
")",
":",
"route_values",
"=",... | 68.25 | 32.666667 |
def get_specific_nodes(self, node, names):
"""Given a node and a sequence of strings in `names`, return a
dictionary containing the names as keys and child
`ELEMENT_NODEs`, that have a `tagName` equal to the name.
"""
nodes = [(x.tagName, x) for x in node.childNodes
... | [
"def",
"get_specific_nodes",
"(",
"self",
",",
"node",
",",
"names",
")",
":",
"nodes",
"=",
"[",
"(",
"x",
".",
"tagName",
",",
"x",
")",
"for",
"x",
"in",
"node",
".",
"childNodes",
"if",
"x",
".",
"nodeType",
"==",
"x",
".",
"ELEMENT_NODE",
"and... | 41.5 | 13 |
def addSuppression(self, suppressionList):
"""
This method can be used to add patters of warnings that should
not be counted.
It takes a single argument, a list of patterns.
Each pattern is a 4-tuple (FILE-RE, WARN-RE, START, END).
FILE-RE is a regular expression (stri... | [
"def",
"addSuppression",
"(",
"self",
",",
"suppressionList",
")",
":",
"for",
"fileRe",
",",
"warnRe",
",",
"start",
",",
"end",
"in",
"suppressionList",
":",
"if",
"fileRe",
"is",
"not",
"None",
"and",
"isinstance",
"(",
"fileRe",
",",
"str",
")",
":",... | 44.740741 | 25.259259 |
def open_csv(csv_file, mode='r'):
"""
Get mode depending on Python version
Based on: http://stackoverflow.com/questions/29840849/writing-a-csv-file-in-python-that-works-for-both-python-2-7-and-python-3-3-in
""" # noqa
if version_info[0] == 2: # Not named on 2.6
access = '{0}b'.format(mode)... | [
"def",
"open_csv",
"(",
"csv_file",
",",
"mode",
"=",
"'r'",
")",
":",
"# noqa",
"if",
"version_info",
"[",
"0",
"]",
"==",
"2",
":",
"# Not named on 2.6",
"access",
"=",
"'{0}b'",
".",
"format",
"(",
"mode",
")",
"kwargs",
"=",
"{",
"}",
"else",
":"... | 34.846154 | 17 |
def _effective_perm_list_from_iter(self, perm_iter):
"""Return list of effective permissions for for highest permission in
``perm_iter``, ordered lower to higher, or None if ``perm_iter`` is empty."""
highest_perm_str = self._highest_perm_from_iter(perm_iter)
return (
self._e... | [
"def",
"_effective_perm_list_from_iter",
"(",
"self",
",",
"perm_iter",
")",
":",
"highest_perm_str",
"=",
"self",
".",
"_highest_perm_from_iter",
"(",
"perm_iter",
")",
"return",
"(",
"self",
".",
"_equal_or_lower_perm_list",
"(",
"highest_perm_str",
")",
"if",
"hi... | 47.666667 | 15 |
def repeat_reverse(self, start, end):
"""
Starts from 'start' day and counts backwards until 'end' day.
'start' should be >= 'end'. If it's equal to, does nothing.
If a day falls outside of end_repeat, it won't be counted.
"""
day = start
diff = start - end
... | [
"def",
"repeat_reverse",
"(",
"self",
",",
"start",
",",
"end",
")",
":",
"day",
"=",
"start",
"diff",
"=",
"start",
"-",
"end",
"try",
":",
"if",
"date",
"(",
"self",
".",
"year",
",",
"self",
".",
"month",
",",
"day",
")",
"<=",
"self",
".",
... | 40 | 19.565217 |
def get_results_path(self):
"""
Return Item result path
"""
result_path = os.path.join(RESULTS_ROOT, self.uuid)
if not os.path.exists(result_path):
os.makedirs(result_path)
return result_path | [
"def",
"get_results_path",
"(",
"self",
")",
":",
"result_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"RESULTS_ROOT",
",",
"self",
".",
"uuid",
")",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"result_path",
")",
":",
"os",
".",
"makedir... | 30.5 | 7.75 |
def desc(self, description):
'''Describe a parser, when it failed, print out the description text.'''
return self | Parser(lambda _, index: Value.failure(index, description)) | [
"def",
"desc",
"(",
"self",
",",
"description",
")",
":",
"return",
"self",
"|",
"Parser",
"(",
"lambda",
"_",
",",
"index",
":",
"Value",
".",
"failure",
"(",
"index",
",",
"description",
")",
")"
] | 62.666667 | 30.666667 |
def set_topic_config(self, topic, value, kafka_version=(0, 10, )):
"""Set configuration information for specified topic.
:topic : topic whose configuration needs to be changed
:value : config value with which the topic needs to be
updated with. This would be of the form key=value.
... | [
"def",
"set_topic_config",
"(",
"self",
",",
"topic",
",",
"value",
",",
"kafka_version",
"=",
"(",
"0",
",",
"10",
",",
")",
")",
":",
"config_data",
"=",
"dump_json",
"(",
"value",
")",
"try",
":",
"# Change value",
"return_value",
"=",
"self",
".",
... | 37.230769 | 18.269231 |
def _node_rating_count(self):
"""
Return node_rating_count record
or create it if it does not exist
usage:
node = Node.objects.get(pk=1)
node.rating_count
"""
try:
return self.noderatingcount
except ObjectDoesNotExist:
node_rating_count = NodeRatingCount(node=self)
... | [
"def",
"_node_rating_count",
"(",
"self",
")",
":",
"try",
":",
"return",
"self",
".",
"noderatingcount",
"except",
"ObjectDoesNotExist",
":",
"node_rating_count",
"=",
"NodeRatingCount",
"(",
"node",
"=",
"self",
")",
"node_rating_count",
".",
"save",
"(",
")",... | 24.666667 | 12.8 |
def _grab_version(self):
"""Set the version to a non-development version."""
original_version = self.vcs.version
logger.debug("Extracted version: %s", original_version)
if original_version is None:
logger.critical('No version found.')
sys.exit(1)
suggestio... | [
"def",
"_grab_version",
"(",
"self",
")",
":",
"original_version",
"=",
"self",
".",
"vcs",
".",
"version",
"logger",
".",
"debug",
"(",
"\"Extracted version: %s\"",
",",
"original_version",
")",
"if",
"original_version",
"is",
"None",
":",
"logger",
".",
"cri... | 45.923077 | 12.769231 |
def line_and_column(text, position):
"""Return the line number and column of a position in a string."""
position_counter = 0
for idx_line, line in enumerate(text.splitlines(True)):
if (position_counter + len(line.rstrip())) >= position:
return (idx_line, position - position_counter)
... | [
"def",
"line_and_column",
"(",
"text",
",",
"position",
")",
":",
"position_counter",
"=",
"0",
"for",
"idx_line",
",",
"line",
"in",
"enumerate",
"(",
"text",
".",
"splitlines",
"(",
"True",
")",
")",
":",
"if",
"(",
"position_counter",
"+",
"len",
"(",... | 45.5 | 13.5 |
def parsewarn(self, msg, line=None):
"""Emit parse warning."""
if line is None:
line = self.sline
self.dowarn('warning: ' + msg + ' on line {}'.format(line)) | [
"def",
"parsewarn",
"(",
"self",
",",
"msg",
",",
"line",
"=",
"None",
")",
":",
"if",
"line",
"is",
"None",
":",
"line",
"=",
"self",
".",
"sline",
"self",
".",
"dowarn",
"(",
"'warning: '",
"+",
"msg",
"+",
"' on line {}'",
".",
"format",
"(",
"l... | 37.8 | 11.6 |
def set_env_var(key: str, value: str):
"""
Sets environment variable on AV
Args:
key: variable name
value: variable value
"""
elib_run.run(f'appveyor SetVariable -Name {key} -Value {value}')
AV.info('Env', f'set "{key}" -> "{value}"') | [
"def",
"set_env_var",
"(",
"key",
":",
"str",
",",
"value",
":",
"str",
")",
":",
"elib_run",
".",
"run",
"(",
"f'appveyor SetVariable -Name {key} -Value {value}'",
")",
"AV",
".",
"info",
"(",
"'Env'",
",",
"f'set \"{key}\" -> \"{value}\"'",
")"
] | 29.8 | 13 |
def to_string(type):
"""
Converts a TypeCode into its string name.
:param type: the TypeCode to convert into a string.
:return: the name of the TypeCode passed as a string value.
"""
if type == None:
return "unknown"
elif type == TypeCode.Unknown:
... | [
"def",
"to_string",
"(",
"type",
")",
":",
"if",
"type",
"==",
"None",
":",
"return",
"\"unknown\"",
"elif",
"type",
"==",
"TypeCode",
".",
"Unknown",
":",
"return",
"\"unknown\"",
"elif",
"type",
"==",
"TypeCode",
".",
"String",
":",
"return",
"\"string\"... | 29.777778 | 11.666667 |
def _get_redis_keys_opts():
'''
Build the key opts based on the user options.
'''
return {
'bank_prefix': __opts__.get('cache.redis.bank_prefix', _BANK_PREFIX),
'bank_keys_prefix': __opts__.get('cache.redis.bank_keys_prefix', _BANK_KEYS_PREFIX),
'key_prefix': __opts__.get('cache.... | [
"def",
"_get_redis_keys_opts",
"(",
")",
":",
"return",
"{",
"'bank_prefix'",
":",
"__opts__",
".",
"get",
"(",
"'cache.redis.bank_prefix'",
",",
"_BANK_PREFIX",
")",
",",
"'bank_keys_prefix'",
":",
"__opts__",
".",
"get",
"(",
"'cache.redis.bank_keys_prefix'",
",",... | 42 | 30.4 |
def locale_title(locale_name):
"""
Giving a locale name return its title, taken from the settings.EXTRA_COUNTRY_LOCALES
If the locale is not in the settings.EXTRA_COUNTRY_LOCALES, return it unchanged
"""
l = dict(settings.EXTRA_COUNTRY_LOCALES)
if locale_name not in l:
return locale... | [
"def",
"locale_title",
"(",
"locale_name",
")",
":",
"l",
"=",
"dict",
"(",
"settings",
".",
"EXTRA_COUNTRY_LOCALES",
")",
"if",
"locale_name",
"not",
"in",
"l",
":",
"return",
"locale_name",
"return",
"l",
".",
"get",
"(",
"locale_name",
")"
] | 34.6 | 17.8 |
def prepare_refresh_body(self, body='', refresh_token=None, scope=None, **kwargs):
"""Prepare an access token request, using a refresh token.
If the authorization server issued a refresh token to the client, the
client makes a refresh request to the token endpoint by adding the
followin... | [
"def",
"prepare_refresh_body",
"(",
"self",
",",
"body",
"=",
"''",
",",
"refresh_token",
"=",
"None",
",",
"scope",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"refresh_token",
"=",
"refresh_token",
"or",
"self",
".",
"refresh_token",
"return",
"prepa... | 52.818182 | 27.227273 |
def preferred_height(self, cli, width, max_available_height):
"""
Return the preferred height of the float container.
(We don't care about the height of the floats, they should always fit
into the dimensions provided by the container.)
"""
return self.content.preferred_he... | [
"def",
"preferred_height",
"(",
"self",
",",
"cli",
",",
"width",
",",
"max_available_height",
")",
":",
"return",
"self",
".",
"content",
".",
"preferred_height",
"(",
"cli",
",",
"width",
",",
"max_available_height",
")"
] | 50.285714 | 18.571429 |
def delegate(from_owner, to_owner, methods):
"""Creates methods on from_owner to call through to methods on to_owner.
:from_owner: the object to delegate to
:to_owner: the owner on which to delegate from
:methods: a list of methods to delegate
"""
for method in methods:
_delegate(from_owner, to_owner, ... | [
"def",
"delegate",
"(",
"from_owner",
",",
"to_owner",
",",
"methods",
")",
":",
"for",
"method",
"in",
"methods",
":",
"_delegate",
"(",
"from_owner",
",",
"to_owner",
",",
"method",
")"
] | 35.444444 | 8 |
def _draw_line_numbers(self):
"""
Create drawables for the line numbers.
"""
if not self.line_numbers:
return
for p in xrange(self.maxlineno):
n = p + self.line_number_start
if (n % self.line_number_step) == 0:
self._draw_linenu... | [
"def",
"_draw_line_numbers",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"line_numbers",
":",
"return",
"for",
"p",
"in",
"xrange",
"(",
"self",
".",
"maxlineno",
")",
":",
"n",
"=",
"p",
"+",
"self",
".",
"line_number_start",
"if",
"(",
"n",
"%... | 32.1 | 5.9 |
def _get_session(self):
"""Create session as needed.
.. note::
Caller is responsible for cleaning up the session after
all partitions have been processed.
"""
if self._session is None:
session = self._session = self._database.session()
sess... | [
"def",
"_get_session",
"(",
"self",
")",
":",
"if",
"self",
".",
"_session",
"is",
"None",
":",
"session",
"=",
"self",
".",
"_session",
"=",
"self",
".",
"_database",
".",
"session",
"(",
")",
"session",
".",
"create",
"(",
")",
"return",
"self",
".... | 29.166667 | 17.083333 |
def clip(self, X):
"""
Clip values to fall within any global or column-wise min/max constraints
"""
X = np.asarray(X)
if self.min_value is not None:
X[X < self.min_value] = self.min_value
if self.max_value is not None:
X[X > self.max_value] = self.... | [
"def",
"clip",
"(",
"self",
",",
"X",
")",
":",
"X",
"=",
"np",
".",
"asarray",
"(",
"X",
")",
"if",
"self",
".",
"min_value",
"is",
"not",
"None",
":",
"X",
"[",
"X",
"<",
"self",
".",
"min_value",
"]",
"=",
"self",
".",
"min_value",
"if",
"... | 33.7 | 12.5 |
def _svd_sym_koopman(K, C00_train, Ctt_train):
""" Computes the SVD of the symmetrized Koopman operator in the empirical distribution.
"""
from pyemma._ext.variational.solvers.direct import spd_inv_sqrt
# reweight operator to empirical distribution
C0t_re = mdot(C00_train, K)
# symmetrized opera... | [
"def",
"_svd_sym_koopman",
"(",
"K",
",",
"C00_train",
",",
"Ctt_train",
")",
":",
"from",
"pyemma",
".",
"_ext",
".",
"variational",
".",
"solvers",
".",
"direct",
"import",
"spd_inv_sqrt",
"# reweight operator to empirical distribution",
"C0t_re",
"=",
"mdot",
"... | 47.692308 | 11.538462 |
def get_headers(self):
"""Return header for the HTTP request."""
headers = {
"User-Agent": self.http_agent,
"Content-Type": "application/json",
"Accept": "application/json"
}
if self.headers:
headers.update(self.headers)
return hea... | [
"def",
"get_headers",
"(",
"self",
")",
":",
"headers",
"=",
"{",
"\"User-Agent\"",
":",
"self",
".",
"http_agent",
",",
"\"Content-Type\"",
":",
"\"application/json\"",
",",
"\"Accept\"",
":",
"\"application/json\"",
"}",
"if",
"self",
".",
"headers",
":",
"h... | 28.545455 | 13.909091 |
def help_center_user_comments(self, id, **kwargs):
"https://developer.zendesk.com/rest_api/docs/help_center/comments#list-comments"
api_path = "/api/v2/help_center/users/{id}/comments.json"
api_path = api_path.format(id=id)
return self.call(api_path, **kwargs) | [
"def",
"help_center_user_comments",
"(",
"self",
",",
"id",
",",
"*",
"*",
"kwargs",
")",
":",
"api_path",
"=",
"\"/api/v2/help_center/users/{id}/comments.json\"",
"api_path",
"=",
"api_path",
".",
"format",
"(",
"id",
"=",
"id",
")",
"return",
"self",
".",
"c... | 57.6 | 17.6 |
def get_non_compulsory_fields(layer_purpose, layer_subcategory=None):
"""Get non compulsory field based on layer_purpose and layer_subcategory.
Used for get field in InaSAFE Fields step in wizard.
:param layer_purpose: The layer purpose.
:type layer_purpose: str
:param layer_subcategory: Exposure... | [
"def",
"get_non_compulsory_fields",
"(",
"layer_purpose",
",",
"layer_subcategory",
"=",
"None",
")",
":",
"all_fields",
"=",
"get_fields",
"(",
"layer_purpose",
",",
"layer_subcategory",
",",
"replace_null",
"=",
"False",
")",
"compulsory_field",
"=",
"get_compulsory... | 32.952381 | 16.190476 |
def flatten_path_lists(env_dict, env_root=None):
"""Join paths in environment dict down to strings."""
for (key, val) in env_dict.items():
# Lists are presumed to be path components and will be turned back
# to strings
if isinstance(val, list):
env_dict[key] = os.path.join(en... | [
"def",
"flatten_path_lists",
"(",
"env_dict",
",",
"env_root",
"=",
"None",
")",
":",
"for",
"(",
"key",
",",
"val",
")",
"in",
"env_dict",
".",
"items",
"(",
")",
":",
"# Lists are presumed to be path components and will be turned back",
"# to strings",
"if",
"is... | 59.75 | 29.875 |
def hash_model_values(model, clear=True, hash_field='values_hash', hash_fun=hash, ignore_pk=True, ignore_fields=[]):
"""Hash values of DB table records to facilitate tracking changes to the DB table
Intended for comparing records in one table to those in another (with potentially differing id/pk values)
Fo... | [
"def",
"hash_model_values",
"(",
"model",
",",
"clear",
"=",
"True",
",",
"hash_field",
"=",
"'values_hash'",
",",
"hash_fun",
"=",
"hash",
",",
"ignore_pk",
"=",
"True",
",",
"ignore_fields",
"=",
"[",
"]",
")",
":",
"qs",
"=",
"getattr",
"(",
"model",
... | 61.473684 | 34.842105 |
def symmetrize_image(image):
"""
Use registration and reflection to make an image symmetric
ANTsR function: N/A
Arguments
---------
image : ANTsImage
image to make symmetric
Returns
-------
ANTsImage
Example
-------
>>> import ants
>>> image = ants.image_r... | [
"def",
"symmetrize_image",
"(",
"image",
")",
":",
"imager",
"=",
"reflect_image",
"(",
"image",
",",
"axis",
"=",
"0",
")",
"imageavg",
"=",
"imager",
"*",
"0.5",
"+",
"image",
"for",
"i",
"in",
"range",
"(",
"5",
")",
":",
"w1",
"=",
"registration"... | 29.945946 | 24.216216 |
def updateItem(self, instance, subKey, value):
"""Updates a child value. Must be called before the update has actually occurred."""
instanceId = statsId(instance)
container = _Stats.getContainerForObject(instanceId)
self._aggregate(instanceId, container, value, subKey) | [
"def",
"updateItem",
"(",
"self",
",",
"instance",
",",
"subKey",
",",
"value",
")",
":",
"instanceId",
"=",
"statsId",
"(",
"instance",
")",
"container",
"=",
"_Stats",
".",
"getContainerForObject",
"(",
"instanceId",
")",
"self",
".",
"_aggregate",
"(",
... | 47 | 14.166667 |
def close(self):
"""
Destructor for this audio interface. Waits the threads to finish their
streams, if desired.
"""
with self.halting: # Avoid simultaneous "close" threads
if not self.finished: # Ignore all "close" calls, but the first,
self.finished = True # and any call to play wo... | [
"def",
"close",
"(",
"self",
")",
":",
"with",
"self",
".",
"halting",
":",
"# Avoid simultaneous \"close\" threads",
"if",
"not",
"self",
".",
"finished",
":",
"# Ignore all \"close\" calls, but the first,",
"self",
".",
"finished",
"=",
"True",
"# and any call to pl... | 32.870968 | 20.548387 |
def rmtree_log_error (func, path, exc):
"""Error function for shutil.rmtree(). Raises a PatoolError."""
msg = "Error in %s(%s): %s" % (func.__name__, path, str(exc[1]))
util.log_error(msg) | [
"def",
"rmtree_log_error",
"(",
"func",
",",
"path",
",",
"exc",
")",
":",
"msg",
"=",
"\"Error in %s(%s): %s\"",
"%",
"(",
"func",
".",
"__name__",
",",
"path",
",",
"str",
"(",
"exc",
"[",
"1",
"]",
")",
")",
"util",
".",
"log_error",
"(",
"msg",
... | 49.25 | 11.5 |
def connection_info(self):
"""Return an ordered iterator of key/value pairs for pretty-printing.
"""
for key in self._connection_keys():
if key in self._contents:
yield key, self._contents[key] | [
"def",
"connection_info",
"(",
"self",
")",
":",
"for",
"key",
"in",
"self",
".",
"_connection_keys",
"(",
")",
":",
"if",
"key",
"in",
"self",
".",
"_contents",
":",
"yield",
"key",
",",
"self",
".",
"_contents",
"[",
"key",
"]"
] | 40 | 4.333333 |
def submit(self, cmd_string, blocksize, tasks_per_node, job_name="parsl"):
""" Submit a job
Args:
- cmd_string :(String) - Name of the container to initiate
- blocksize :(float) - Number of replicas
- tasks_per_node (int) : command invocations to be launched per... | [
"def",
"submit",
"(",
"self",
",",
"cmd_string",
",",
"blocksize",
",",
"tasks_per_node",
",",
"job_name",
"=",
"\"parsl\"",
")",
":",
"if",
"not",
"self",
".",
"resources",
":",
"cur_timestamp",
"=",
"str",
"(",
"time",
".",
"time",
"(",
")",
"*",
"10... | 50.657895 | 28.631579 |
def OnSearch(self, event):
"""Event handler for starting the search"""
search_string = self.search.GetValue()
if search_string not in self.search_history:
self.search_history.append(search_string)
if len(self.search_history) > 10:
self.search_history.pop(0)
... | [
"def",
"OnSearch",
"(",
"self",
",",
"event",
")",
":",
"search_string",
"=",
"self",
".",
"search",
".",
"GetValue",
"(",
")",
"if",
"search_string",
"not",
"in",
"self",
".",
"search_history",
":",
"self",
".",
"search_history",
".",
"append",
"(",
"se... | 30.578947 | 18.631579 |
def process(self, event):
""" Send events as push notification via Google Cloud Messaging.
Expected settings as follows:
# https://developers.google.com/mobile/add
WALDUR_CORE['GOOGLE_API'] = {
'NOTIFICATION_TITLE': "Waldur notification",
... | [
"def",
"process",
"(",
"self",
",",
"event",
")",
":",
"conf",
"=",
"settings",
".",
"WALDUR_CORE",
".",
"get",
"(",
"'GOOGLE_API'",
")",
"or",
"{",
"}",
"keys",
"=",
"conf",
".",
"get",
"(",
"dict",
"(",
"self",
".",
"Type",
".",
"CHOICES",
")",
... | 36.928571 | 20.47619 |
def demo_usage(n_data=50, n_fit=537, nhead=5, ntail=5, plot=False, alt=0):
"""
Plots a noisy sine curve and the fitting to it.
Also presents the error and the error in the
approximation of its first derivative (cosine curve)
Usage example for benchmarking:
$ time python sine.py --nhead 3 --nta... | [
"def",
"demo_usage",
"(",
"n_data",
"=",
"50",
",",
"n_fit",
"=",
"537",
",",
"nhead",
"=",
"5",
",",
"ntail",
"=",
"5",
",",
"plot",
"=",
"False",
",",
"alt",
"=",
"0",
")",
":",
"x0",
",",
"xend",
"=",
"0",
",",
"5",
"# shaky linspace -5% to +5... | 33.647887 | 20.859155 |
def peer_retrieve(key, relation_name='cluster'):
"""Retrieve a named key from peer relation `relation_name`."""
cluster_rels = relation_ids(relation_name)
if len(cluster_rels) > 0:
cluster_rid = cluster_rels[0]
return relation_get(attribute=key, rid=cluster_rid,
u... | [
"def",
"peer_retrieve",
"(",
"key",
",",
"relation_name",
"=",
"'cluster'",
")",
":",
"cluster_rels",
"=",
"relation_ids",
"(",
"relation_name",
")",
"if",
"len",
"(",
"cluster_rels",
")",
">",
"0",
":",
"cluster_rid",
"=",
"cluster_rels",
"[",
"0",
"]",
"... | 44.9 | 11.3 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.