text stringlengths 89 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 630 |
|---|---|---|---|
def wrap_constant(self, val):
"""
Used for wrapping raw inputs such as numbers in Criterions and Operator.
For example, the expression F('abc')+1 stores the integer part in a ValueWrapper object.
:param val:
Any value.
:return:
Raw string, number, or dec... | [
"def",
"wrap_constant",
"(",
"self",
",",
"val",
")",
":",
"from",
".",
"queries",
"import",
"QueryBuilder",
"if",
"isinstance",
"(",
"val",
",",
"(",
"Term",
",",
"QueryBuilder",
",",
"Interval",
")",
")",
":",
"return",
"val",
"if",
"val",
"is",
"Non... | 32.923077 | 22.769231 |
def from_json(cls, data, result=None):
"""
Create new Relation element from JSON data
:param data: Element data from JSON
:type data: Dict
:param result: The result this element belongs to
:type result: overpy.Result
:return: New instance of Relation
:rty... | [
"def",
"from_json",
"(",
"cls",
",",
"data",
",",
"result",
"=",
"None",
")",
":",
"if",
"data",
".",
"get",
"(",
"\"type\"",
")",
"!=",
"cls",
".",
"_type_value",
":",
"raise",
"exception",
".",
"ElementDataWrongType",
"(",
"type_expected",
"=",
"cls",
... | 31.90566 | 16.018868 |
def WriteHeader(self):
"""Writes the header to the spreadsheet."""
self._column_widths = {}
bold = self._workbook.add_format({'bold': True})
bold.set_align('center')
for index, field_name in enumerate(self._fields):
self._sheet.write(self._current_row, index, field_name, bold)
self._colu... | [
"def",
"WriteHeader",
"(",
"self",
")",
":",
"self",
".",
"_column_widths",
"=",
"{",
"}",
"bold",
"=",
"self",
".",
"_workbook",
".",
"add_format",
"(",
"{",
"'bold'",
":",
"True",
"}",
")",
"bold",
".",
"set_align",
"(",
"'center'",
")",
"for",
"in... | 42.636364 | 13.272727 |
def resize(self, block_size, order=0, mode='constant', cval=False, preserve_range=True):
'''
geo.resize(new_shape, order=0, mode='constant', cval=np.nan, preserve_range=True)
Returns resized georaster
'''
if not cval:
cval = np.nan
raster2 = resize(self.raste... | [
"def",
"resize",
"(",
"self",
",",
"block_size",
",",
"order",
"=",
"0",
",",
"mode",
"=",
"'constant'",
",",
"cval",
"=",
"False",
",",
"preserve_range",
"=",
"True",
")",
":",
"if",
"not",
"cval",
":",
"cval",
"=",
"np",
".",
"nan",
"raster2",
"=... | 55.684211 | 31.473684 |
def getuname(self, uid):
"""
Get the username of a given uid.
"""
uid = int(uid)
try:
return self.uidsmap[uid]
except KeyError:
pass
try:
name = pwd.getpwuid(uid)[0]
except (KeyError, AttributeError):
name =... | [
"def",
"getuname",
"(",
"self",
",",
"uid",
")",
":",
"uid",
"=",
"int",
"(",
"uid",
")",
"try",
":",
"return",
"self",
".",
"uidsmap",
"[",
"uid",
"]",
"except",
"KeyError",
":",
"pass",
"try",
":",
"name",
"=",
"pwd",
".",
"getpwuid",
"(",
"uid... | 21.941176 | 14.882353 |
def load_values(self, dictionary, as_defaults=False, flat=False):
"""
Import config values from a dictionary.
When ``as_defaults`` is set to ``True``, the values
imported will be set as defaults. This can be used to
declare the sections and items of configuration.
Values... | [
"def",
"load_values",
"(",
"self",
",",
"dictionary",
",",
"as_defaults",
"=",
"False",
",",
"flat",
"=",
"False",
")",
":",
"if",
"flat",
":",
"# Deflatten the dictionary and then pass on to the normal case.",
"separator",
"=",
"self",
".",
"settings",
".",
"str_... | 40.653846 | 17.807692 |
def _add_conntrack_stats_metrics(self, conntrack_path, tags):
"""
Parse the output of conntrack -S
Add the parsed metrics
"""
try:
output, _, _ = get_subprocess_output(["sudo", conntrack_path, "-S"], self.log)
# conntrack -S sample:
# cpu=0 fou... | [
"def",
"_add_conntrack_stats_metrics",
"(",
"self",
",",
"conntrack_path",
",",
"tags",
")",
":",
"try",
":",
"output",
",",
"_",
",",
"_",
"=",
"get_subprocess_output",
"(",
"[",
"\"sudo\"",
",",
"conntrack_path",
",",
"\"-S\"",
"]",
",",
"self",
".",
"lo... | 45.230769 | 22.538462 |
def scatter(adata, groupby, groupid, x,y, n=100, special_markers=None,
coloring='scores', size=12, annotate=True):
"""For one group, output a detailed chart analyzing highly ranked genes detailly.
This is a visualization tools that helps to find significant markers and... | [
"def",
"scatter",
"(",
"adata",
",",
"groupby",
",",
"groupid",
",",
"x",
",",
"y",
",",
"n",
"=",
"100",
",",
"special_markers",
"=",
"None",
",",
"coloring",
"=",
"'scores'",
",",
"size",
"=",
"12",
",",
"annotate",
"=",
"True",
")",
":",
"groups... | 43.717172 | 21.212121 |
def _prepare_uri(self, path, query_params={}):
"""
Prepares a full URI with the selected information.
``path``:
Path can be in one of two formats:
- If :attr:`server` was defined, the ``path`` will be appended
to the existing host, or
... | [
"def",
"_prepare_uri",
"(",
"self",
",",
"path",
",",
"query_params",
"=",
"{",
"}",
")",
":",
"query_str",
"=",
"urllib",
".",
"urlencode",
"(",
"query_params",
")",
"# If we have a relative path (as opposed to a full URL), build it of",
"# the connection info",
"if",
... | 34.965517 | 18.689655 |
def none_and_length_check(all_inputs, length=None):
r'''Checks inputs for suitability of use by a mixing rule which requires
all inputs to be of the same length and non-None. A number of variations
were attempted for this function; this was found to be the quickest.
Parameters
----------
all_in... | [
"def",
"none_and_length_check",
"(",
"all_inputs",
",",
"length",
"=",
"None",
")",
":",
"if",
"not",
"length",
":",
"length",
"=",
"len",
"(",
"all_inputs",
"[",
"0",
"]",
")",
"for",
"things",
"in",
"all_inputs",
":",
"if",
"None",
"in",
"things",
"o... | 29.151515 | 23.757576 |
def sample_batch(self, nlive_new=500, update_interval=None,
logl_bounds=None, maxiter=None, maxcall=None,
save_bounds=True):
"""
Generate an additional series of nested samples that will be combined
with the previous set of dead points. Works by hacking ... | [
"def",
"sample_batch",
"(",
"self",
",",
"nlive_new",
"=",
"500",
",",
"update_interval",
"=",
"None",
",",
"logl_bounds",
"=",
"None",
",",
"maxiter",
"=",
"None",
",",
"maxcall",
"=",
"None",
",",
"save_bounds",
"=",
"True",
")",
":",
"# Initialize defau... | 42.996914 | 19.07716 |
def reverse_lookup(self, value, condition=is_active):
''' take a field_name_id and return the label '''
label = get_value_label(value, self._picklist, condition=condition)
return label | [
"def",
"reverse_lookup",
"(",
"self",
",",
"value",
",",
"condition",
"=",
"is_active",
")",
":",
"label",
"=",
"get_value_label",
"(",
"value",
",",
"self",
".",
"_picklist",
",",
"condition",
"=",
"condition",
")",
"return",
"label"
] | 51.25 | 21.25 |
def pauli_product(*elements: Pauli) -> Pauli:
"""Return the product of elements of the Pauli algebra"""
result_terms = []
for terms in product(*elements):
coeff = reduce(mul, [term[1] for term in terms])
ops = (term[0] for term in terms)
out = []
key = itemgetter(0)
... | [
"def",
"pauli_product",
"(",
"*",
"elements",
":",
"Pauli",
")",
"->",
"Pauli",
":",
"result_terms",
"=",
"[",
"]",
"for",
"terms",
"in",
"product",
"(",
"*",
"elements",
")",
":",
"coeff",
"=",
"reduce",
"(",
"mul",
",",
"[",
"term",
"[",
"1",
"]"... | 33.590909 | 14 |
def _get_shade_hdrgos(**kws):
"""If no hdrgo_prt specified, and these conditions are present -> hdrgo_prt=F."""
# KWS: shade_hdrgos hdrgo_prt section_sortby top_n
if 'shade_hdrgos' in kws:
return kws['shade_hdrgos']
# Return user-sepcified hdrgo_prt, if provided
if 'h... | [
"def",
"_get_shade_hdrgos",
"(",
"*",
"*",
"kws",
")",
":",
"# KWS: shade_hdrgos hdrgo_prt section_sortby top_n",
"if",
"'shade_hdrgos'",
"in",
"kws",
":",
"return",
"kws",
"[",
"'shade_hdrgos'",
"]",
"# Return user-sepcified hdrgo_prt, if provided",
"if",
"'hdrgo_prt'",
... | 42.117647 | 11.941176 |
def issue_info(self, issue_id):
"""
Get info about a single issue.
:param issue_id: the id of the issue
:return:
"""
request_url = "{}issue/{}".format(self.create_basic_url(), issue_id)
return_value = self._call_api(request_url)
return return_value | [
"def",
"issue_info",
"(",
"self",
",",
"issue_id",
")",
":",
"request_url",
"=",
"\"{}issue/{}\"",
".",
"format",
"(",
"self",
".",
"create_basic_url",
"(",
")",
",",
"issue_id",
")",
"return_value",
"=",
"self",
".",
"_call_api",
"(",
"request_url",
")",
... | 27.636364 | 16.181818 |
def debug(f, *args, **kwargs):
"""Automatically log progress on function entry and exit. Default logging
value: debug.
*Logging with values contained in the parameters of the decorated function*
Message (args[0]) may be a string to be formatted with parameters passed to
the decorated function. Each... | [
"def",
"debug",
"(",
"f",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"kwargs",
".",
"update",
"(",
"{",
"'log'",
":",
"logging",
".",
"DEBUG",
"}",
")",
"return",
"_stump",
"(",
"f",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | 37.043478 | 22.782609 |
def activate_introjs(driver):
""" Allows you to use IntroJS Tours with SeleniumBase
https://introjs.com/
"""
intro_css = constants.IntroJS.MIN_CSS
intro_js = constants.IntroJS.MIN_JS
verify_script = ("""// Verify IntroJS activated
var intro2 = introJs();
... | [
"def",
"activate_introjs",
"(",
"driver",
")",
":",
"intro_css",
"=",
"constants",
".",
"IntroJS",
".",
"MIN_CSS",
"intro_js",
"=",
"constants",
".",
"IntroJS",
".",
"MIN_JS",
"verify_script",
"=",
"(",
"\"\"\"// Verify IntroJS activated\n var intro2... | 36.366667 | 11.633333 |
def execute_sql(self, result_type=constants.MULTI, chunked_fetch=False,
chunk_size=constants.GET_ITERATOR_CHUNK_SIZE):
"""
Run the query against the database and returns the result(s). The
return value is a single data item if result_type is SINGLE, or an
iterator ove... | [
"def",
"execute_sql",
"(",
"self",
",",
"result_type",
"=",
"constants",
".",
"MULTI",
",",
"chunked_fetch",
"=",
"False",
",",
"chunk_size",
"=",
"constants",
".",
"GET_ITERATOR_CHUNK_SIZE",
")",
":",
"try",
":",
"sql",
",",
"params",
"=",
"self",
".",
"a... | 42.930233 | 21.813953 |
def set_text(self, point, text):
"""Set a text value in the screen canvas."""
if not self.option.legend:
return
if not isinstance(point, Point):
point = Point(point)
for offset, char in enumerate(str(text)):
self.screen.canvas[point.y][point.x + offs... | [
"def",
"set_text",
"(",
"self",
",",
"point",
",",
"text",
")",
":",
"if",
"not",
"self",
".",
"option",
".",
"legend",
":",
"return",
"if",
"not",
"isinstance",
"(",
"point",
",",
"Point",
")",
":",
"point",
"=",
"Point",
"(",
"point",
")",
"for",... | 32.1 | 15.7 |
def extensions(self, component):
"""Return a list of components that declare to implement the
extension point interface.
"""
classes = ComponentMeta._registry.get(self.interface, ())
components = [component.compmgr[cls] for cls in classes]
return [c for c in components if... | [
"def",
"extensions",
"(",
"self",
",",
"component",
")",
":",
"classes",
"=",
"ComponentMeta",
".",
"_registry",
".",
"get",
"(",
"self",
".",
"interface",
",",
"(",
")",
")",
"components",
"=",
"[",
"component",
".",
"compmgr",
"[",
"cls",
"]",
"for",... | 45.285714 | 9.428571 |
def search(self, domain, wildcard=True):
"""
Search crt.sh for the given domain.
domain -- Domain to search for
wildcard -- Whether or not to prepend a wildcard to the domain
(default: True)
Return a list of a certificate dict:
{
"issuer... | [
"def",
"search",
"(",
"self",
",",
"domain",
",",
"wildcard",
"=",
"True",
")",
":",
"base_url",
"=",
"\"https://crt.sh/?q={}&output=json\"",
"if",
"wildcard",
":",
"domain",
"=",
"\"%25.{}\"",
".",
"format",
"(",
"domain",
")",
"url",
"=",
"base_url",
".",
... | 33.842105 | 18.526316 |
def install(replace_existing=False):
"""install dapa programmer."""
bunch = AutoBunch()
bunch.name = 'DAPA'
bunch.protocol = 'dapa'
bunch.force = 'true'
# bunch.delay=200
install_programmer('dapa', bunch, replace_existing=replace_existing) | [
"def",
"install",
"(",
"replace_existing",
"=",
"False",
")",
":",
"bunch",
"=",
"AutoBunch",
"(",
")",
"bunch",
".",
"name",
"=",
"'DAPA'",
"bunch",
".",
"protocol",
"=",
"'dapa'",
"bunch",
".",
"force",
"=",
"'true'",
"# bunch.delay=200",
"install_programm... | 28.888889 | 17.555556 |
def send_button_message(self, recipient_id, text, buttons, notification_type=NotificationType.regular):
"""Send text messages to the specified recipient.
https://developers.facebook.com/docs/messenger-platform/send-api-reference/button-template
Input:
recipient_id: recipient id to se... | [
"def",
"send_button_message",
"(",
"self",
",",
"recipient_id",
",",
"text",
",",
"buttons",
",",
"notification_type",
"=",
"NotificationType",
".",
"regular",
")",
":",
"return",
"self",
".",
"send_message",
"(",
"recipient_id",
",",
"{",
"\"attachment\"",
":",... | 38.85 | 15.05 |
def permission_to_04_acls(permissions):
"""
Legacy acl format kept for bw. compatibility
:param permissions:
:return:
"""
acls = []
for perm in permissions:
if perm.type == "user":
acls.append((perm.user.id, perm.perm_name))
elif perm.type == "group":
... | [
"def",
"permission_to_04_acls",
"(",
"permissions",
")",
":",
"acls",
"=",
"[",
"]",
"for",
"perm",
"in",
"permissions",
":",
"if",
"perm",
".",
"type",
"==",
"\"user\"",
":",
"acls",
".",
"append",
"(",
"(",
"perm",
".",
"user",
".",
"id",
",",
"per... | 29.307692 | 13.615385 |
def export_image(self, filename='refcycle.png', format=None,
dot_executable='dot'):
"""
Export graph as an image.
This requires that Graphviz is installed and that the ``dot``
executable is in your path.
The *filename* argument specifies the output filename... | [
"def",
"export_image",
"(",
"self",
",",
"filename",
"=",
"'refcycle.png'",
",",
"format",
"=",
"None",
",",
"dot_executable",
"=",
"'dot'",
")",
":",
"# Figure out what output format to use.",
"if",
"format",
"is",
"None",
":",
"_",
",",
"extension",
"=",
"os... | 35.384615 | 20.461538 |
def ObjectModifiedEventHandler(obj, event):
"""Object has been modified
"""
# only snapshot supported objects
if not supports_snapshots(obj):
return
# take a new snapshot
take_snapshot(obj, action="edit")
# reindex the object in the auditlog catalog
reindex_object(obj) | [
"def",
"ObjectModifiedEventHandler",
"(",
"obj",
",",
"event",
")",
":",
"# only snapshot supported objects",
"if",
"not",
"supports_snapshots",
"(",
"obj",
")",
":",
"return",
"# take a new snapshot",
"take_snapshot",
"(",
"obj",
",",
"action",
"=",
"\"edit\"",
")"... | 23.076923 | 15.384615 |
def pprint_label(self):
"The pretty-printed label string for the Dimension"
unit = ('' if self.unit is None
else type(self.unit)(self.unit_format).format(unit=self.unit))
return bytes_to_unicode(self.label) + bytes_to_unicode(unit) | [
"def",
"pprint_label",
"(",
"self",
")",
":",
"unit",
"=",
"(",
"''",
"if",
"self",
".",
"unit",
"is",
"None",
"else",
"type",
"(",
"self",
".",
"unit",
")",
"(",
"self",
".",
"unit_format",
")",
".",
"format",
"(",
"unit",
"=",
"self",
".",
"uni... | 53.4 | 20.6 |
def get_version(package_name):
"""find __version__ for making package
Args:
package_name (str): path to _version.py folder (abspath > relpath)
Returns:
str: __version__ value
"""
module = 'prosper.' + package_name + '._version'
package = importlib.import_module(module)
ve... | [
"def",
"get_version",
"(",
"package_name",
")",
":",
"module",
"=",
"'prosper.'",
"+",
"package_name",
"+",
"'._version'",
"package",
"=",
"importlib",
".",
"import_module",
"(",
"module",
")",
"version",
"=",
"package",
".",
"__version__",
"return",
"version"
] | 22 | 22.4375 |
def get_relation_type(self, relation):
"""GetRelationType.
[Preview API] Gets the work item relation type definition.
:param str relation: The relation name
:rtype: :class:`<WorkItemRelationType> <azure.devops.v5_1.work-item-tracking.models.WorkItemRelationType>`
"""
rout... | [
"def",
"get_relation_type",
"(",
"self",
",",
"relation",
")",
":",
"route_values",
"=",
"{",
"}",
"if",
"relation",
"is",
"not",
"None",
":",
"route_values",
"[",
"'relation'",
"]",
"=",
"self",
".",
"_serialize",
".",
"url",
"(",
"'relation'",
",",
"re... | 53.642857 | 20.214286 |
def _call(self, command, ignore_errors=None):
""" Call remote command with logging. """
if ignore_errors is None:
ignore_errors = []
cmd = []
cmd.extend(self._prefix)
cmd.extend([self._path, "-iP"])
cmd.extend(command)
command = cmd
logger.deb... | [
"def",
"_call",
"(",
"self",
",",
"command",
",",
"ignore_errors",
"=",
"None",
")",
":",
"if",
"ignore_errors",
"is",
"None",
":",
"ignore_errors",
"=",
"[",
"]",
"cmd",
"=",
"[",
"]",
"cmd",
".",
"extend",
"(",
"self",
".",
"_prefix",
")",
"cmd",
... | 31.777778 | 18.703704 |
def group_by(resources, key):
"""Return a mapping of key value to resources with the corresponding value.
Key may be specified as dotted form for nested dictionary lookup
"""
resource_map = {}
parts = key.split('.')
for r in resources:
v = r
for k in parts:
v = v.get... | [
"def",
"group_by",
"(",
"resources",
",",
"key",
")",
":",
"resource_map",
"=",
"{",
"}",
"parts",
"=",
"key",
".",
"split",
"(",
"'.'",
")",
"for",
"r",
"in",
"resources",
":",
"v",
"=",
"r",
"for",
"k",
"in",
"parts",
":",
"v",
"=",
"v",
".",... | 29.6 | 15.6 |
def sinogram_as_rytov(uSin, u0=1, align=True):
r"""Convert the complex wave field sinogram to the Rytov phase
This method applies the Rytov approximation to the
recorded complex wave sinogram. To achieve this, the following
filter is applied:
.. math::
u_\mathrm{B}(\mathbf{r}) = u_\mathrm{... | [
"def",
"sinogram_as_rytov",
"(",
"uSin",
",",
"u0",
"=",
"1",
",",
"align",
"=",
"True",
")",
":",
"ndims",
"=",
"len",
"(",
"uSin",
".",
"shape",
")",
"# imaginary part of the complex Rytov phase",
"phiR",
"=",
"np",
".",
"angle",
"(",
"uSin",
"/",
"u0"... | 33.717949 | 20.217949 |
def p_font_face_open(self, p):
""" block_open : css_font_face t_ws brace_open
"""
p[0] = Identifier([p[1], p[2]]).parse(self.scope) | [
"def",
"p_font_face_open",
"(",
"self",
",",
"p",
")",
":",
"p",
"[",
"0",
"]",
"=",
"Identifier",
"(",
"[",
"p",
"[",
"1",
"]",
",",
"p",
"[",
"2",
"]",
"]",
")",
".",
"parse",
"(",
"self",
".",
"scope",
")"
] | 41.75 | 6.75 |
def _parseline(self, line):
"""
https://jira.bikalabs.com/browse/LIMS-1818?focusedCommentId=16915&page=com.atlassian.jira.plugin.system.issuetabpanels:comment-tabpanel#comment-16915
Only first 4 columns are important:
3/24/2015 7:55 AM BOG 651 (IND) - 16 0.10931925301288605 0.0168030817... | [
"def",
"_parseline",
"(",
"self",
",",
"line",
")",
":",
"sline",
"=",
"line",
".",
"split",
"(",
"'\\t'",
")",
"if",
"len",
"(",
"sline",
")",
"<",
"4",
":",
"return",
"-",
"1",
"try",
":",
"raw_dict",
"=",
"{",
"self",
".",
"_analysis1",
":",
... | 33.212121 | 18.666667 |
def afni_wf(name='AFNISkullStripWorkflow', unifize=False, n4_nthreads=1):
"""
Skull-stripping workflow
Originally derived from the `codebase of the
QAP <https://github.com/preprocessed-connectomes-project/\
quality-assessment-protocol/blob/master/qap/anatomical_preproc.py#L105>`_.
Now, this workflo... | [
"def",
"afni_wf",
"(",
"name",
"=",
"'AFNISkullStripWorkflow'",
",",
"unifize",
"=",
"False",
",",
"n4_nthreads",
"=",
"1",
")",
":",
"workflow",
"=",
"pe",
".",
"Workflow",
"(",
"name",
"=",
"name",
")",
"inputnode",
"=",
"pe",
".",
"Node",
"(",
"niu"... | 43.564516 | 24.919355 |
def _link(self, next_worker, next_is_first=False):
"""Link the worker to the given next worker object,
connecting the two workers with communication tubes."""
lock = multiprocessing.Lock()
next_worker._lock_prev_input = lock
self._lock_next_input = lock
lock.acquire()
... | [
"def",
"_link",
"(",
"self",
",",
"next_worker",
",",
"next_is_first",
"=",
"False",
")",
":",
"lock",
"=",
"multiprocessing",
".",
"Lock",
"(",
")",
"next_worker",
".",
"_lock_prev_input",
"=",
"lock",
"self",
".",
"_lock_next_input",
"=",
"lock",
"lock",
... | 34.722222 | 12.777778 |
def click_at_coordinates(self, x, y):
"""
Click at (x,y) coordinates.
"""
self.device.click(int(x), int(y)) | [
"def",
"click_at_coordinates",
"(",
"self",
",",
"x",
",",
"y",
")",
":",
"self",
".",
"device",
".",
"click",
"(",
"int",
"(",
"x",
")",
",",
"int",
"(",
"y",
")",
")"
] | 27 | 1.8 |
def concat_align(fastas):
"""
concatenate alignments
"""
# read in sequences
fa2len = {}
seqs = {}
IDs = []
for fasta in fastas:
seqs[fasta] = {}
for seq in parse_fasta(fasta):
ID = seq[0].split('>')[1].split()[0]
IDs.append(ID)
seqs[fa... | [
"def",
"concat_align",
"(",
"fastas",
")",
":",
"# read in sequences",
"fa2len",
"=",
"{",
"}",
"seqs",
"=",
"{",
"}",
"IDs",
"=",
"[",
"]",
"for",
"fasta",
"in",
"fastas",
":",
"seqs",
"[",
"fasta",
"]",
"=",
"{",
"}",
"for",
"seq",
"in",
"parse_f... | 25.777778 | 14 |
def filterItems(self,
terms,
autoExpand=True,
caseSensitive=False):
"""
Filters the items in this tree based on the inputed text.
:param terms | <str> || {<str> column: [<str> opt, ..]}
... | [
"def",
"filterItems",
"(",
"self",
",",
"terms",
",",
"autoExpand",
"=",
"True",
",",
"caseSensitive",
"=",
"False",
")",
":",
"# create a dictionary of options\r",
"if",
"type",
"(",
"terms",
")",
"!=",
"dict",
":",
"terms",
"=",
"{",
"'*'",
":",
"natives... | 37.571429 | 14.857143 |
def add_real_paths(self, path_list, read_only=True, lazy_dir_read=True):
"""This convenience method adds multiple files and/or directories from
the real file system to the fake file system. See `add_real_file()` and
`add_real_directory()`.
Args:
path_list: List of file and d... | [
"def",
"add_real_paths",
"(",
"self",
",",
"path_list",
",",
"read_only",
"=",
"True",
",",
"lazy_dir_read",
"=",
"True",
")",
":",
"for",
"path",
"in",
"path_list",
":",
"if",
"os",
".",
"path",
".",
"isdir",
"(",
"path",
")",
":",
"self",
".",
"add... | 46.961538 | 21.846154 |
def compute_diffusion_maps(lapl_type, diffusion_map, lambdas, diffusion_time):
""" Credit to Satrajit Ghosh (http://satra.cogitatum.org/) for final steps """
# Check that diffusion maps is using the correct laplacian, warn otherwise
if lapl_type not in ['geometric', 'renormalized']:
warnings.warn("f... | [
"def",
"compute_diffusion_maps",
"(",
"lapl_type",
",",
"diffusion_map",
",",
"lambdas",
",",
"diffusion_time",
")",
":",
"# Check that diffusion maps is using the correct laplacian, warn otherwise",
"if",
"lapl_type",
"not",
"in",
"[",
"'geometric'",
",",
"'renormalized'",
... | 48.277778 | 17.944444 |
def _update_ret(ret, goids, go2color):
"""Update 'GOs' and 'go2color' in dict with goids and go2color."""
if goids:
ret['GOs'].update(goids)
if go2color:
for goid, color in go2color.items():
ret['go2color'][goid] = color | [
"def",
"_update_ret",
"(",
"ret",
",",
"goids",
",",
"go2color",
")",
":",
"if",
"goids",
":",
"ret",
"[",
"'GOs'",
"]",
".",
"update",
"(",
"goids",
")",
"if",
"go2color",
":",
"for",
"goid",
",",
"color",
"in",
"go2color",
".",
"items",
"(",
")",... | 39.714286 | 8.857143 |
def send(self, message):
"""Sends a message to a Riemann server and returns it's response
:param message: The message to send to the Riemann server
:returns: The response message from Riemann
:raises RiemannError: if the server returns an error
"""
message = message.Seri... | [
"def",
"send",
"(",
"self",
",",
"message",
")",
":",
"message",
"=",
"message",
".",
"SerializeToString",
"(",
")",
"self",
".",
"socket",
".",
"sendall",
"(",
"struct",
".",
"pack",
"(",
"'!I'",
",",
"len",
"(",
"message",
")",
")",
"+",
"message",... | 37.444444 | 20.166667 |
def dprint(name, val):
"""Debug print name and val."""
from pprint import pformat
print(
'% 5s: %s' % (
name,
'\n '.join(
pformat(
val, indent=4, width=75,
).split('\n')
),
),
) | [
"def",
"dprint",
"(",
"name",
",",
"val",
")",
":",
"from",
"pprint",
"import",
"pformat",
"print",
"(",
"'% 5s: %s'",
"%",
"(",
"name",
",",
"'\\n '",
".",
"join",
"(",
"pformat",
"(",
"val",
",",
"indent",
"=",
"4",
",",
"width",
"=",
"75",
... | 22.384615 | 17.846154 |
def fill(self, rgb, x=0, y=0, w=None, h=None, name=""):
"""Creates a new fill layer.
Creates a new layer filled with the given rgb color.
For example, fill((255,0,0)) creates a red fill.
The layers fills the entire canvas by default.
"""
if w == None:... | [
"def",
"fill",
"(",
"self",
",",
"rgb",
",",
"x",
"=",
"0",
",",
"y",
"=",
"0",
",",
"w",
"=",
"None",
",",
"h",
"=",
"None",
",",
"name",
"=",
"\"\"",
")",
":",
"if",
"w",
"==",
"None",
":",
"w",
"=",
"self",
".",
"w",
"-",
"x",
"if",
... | 31.357143 | 16.071429 |
def BeginEdit(self, row, col, grid):
"Fetch the value from the table and prepare the edit control"
self.startValue = grid.GetTable().GetValue(row, col)
choices = grid.GetTable().columns[col]._choices
self._tc.Clear()
self._tc.AppendItems(choices)
self._tc.SetStringS... | [
"def",
"BeginEdit",
"(",
"self",
",",
"row",
",",
"col",
",",
"grid",
")",
":",
"self",
".",
"startValue",
"=",
"grid",
".",
"GetTable",
"(",
")",
".",
"GetValue",
"(",
"row",
",",
"col",
")",
"choices",
"=",
"grid",
".",
"GetTable",
"(",
")",
".... | 45.875 | 14.125 |
def cleanup_files(self, bundle=False):
"""Clean up files, remove builds."""
logger.notify('Cleaning up...')
logger.indent += 2
for req in self.reqs_to_cleanup:
req.remove_temporary_source()
remove_dir = []
if self._pip_has_created_build_dir():
rem... | [
"def",
"cleanup_files",
"(",
"self",
",",
"bundle",
"=",
"False",
")",
":",
"logger",
".",
"notify",
"(",
"'Cleaning up...'",
")",
"logger",
".",
"indent",
"+=",
"2",
"for",
"req",
"in",
"self",
".",
"reqs_to_cleanup",
":",
"req",
".",
"remove_temporary_so... | 31.545455 | 14.818182 |
def run(self, deployments=None, command='plan'): # noqa pylint: disable=too-many-branches,too-many-statements
"""Execute apps/code command."""
if deployments is None:
deployments = self.runway_config['deployments']
context = Context(env_name=get_env(self.env_root,
... | [
"def",
"run",
"(",
"self",
",",
"deployments",
"=",
"None",
",",
"command",
"=",
"'plan'",
")",
":",
"# noqa pylint: disable=too-many-branches,too-many-statements",
"if",
"deployments",
"is",
"None",
":",
"deployments",
"=",
"self",
".",
"runway_config",
"[",
"'de... | 45.741935 | 20.83871 |
def resolve(cursor, key):
"""
Get engine or raise exception, resolves Alias-instances to a sibling target.
:param cursor: The object so search in
:param key: The key to get
:return: The object found
"""
try:
result = cursor[key]
# Resolve alias
if isinstance(result,... | [
"def",
"resolve",
"(",
"cursor",
",",
"key",
")",
":",
"try",
":",
"result",
"=",
"cursor",
"[",
"key",
"]",
"# Resolve alias",
"if",
"isinstance",
"(",
"result",
",",
"Alias",
")",
":",
"result",
"=",
"cursor",
"[",
"result",
".",
"target",
"]",
"re... | 25.277778 | 17.722222 |
def _tupleload(l: Loader, value, type_) -> Tuple:
"""
This loads into something like Tuple[int,str]
"""
if HAS_TUPLEARGS:
args = type_.__args__
else:
args = type_.__tuple_params__
if len(args) == 2 and args[1] == ...: # Tuple[something, ...]
return tuple(l.load(i, args[0... | [
"def",
"_tupleload",
"(",
"l",
":",
"Loader",
",",
"value",
",",
"type_",
")",
"->",
"Tuple",
":",
"if",
"HAS_TUPLEARGS",
":",
"args",
"=",
"type_",
".",
"__args__",
"else",
":",
"args",
"=",
"type_",
".",
"__tuple_params__",
"if",
"len",
"(",
"args",
... | 47.411765 | 24 |
def to_sax(self, instance, dest):
"""
Create a child node at `parent` with the tag :attr:`tag`. Set the text
contents to the value of the attribute which this descriptor represents
at `instance`.
If the value is :data:`None`, no element is generated.
"""
value =... | [
"def",
"to_sax",
"(",
"self",
",",
"instance",
",",
"dest",
")",
":",
"value",
"=",
"self",
".",
"__get__",
"(",
"instance",
",",
"type",
"(",
"instance",
")",
")",
"if",
"value",
"==",
"self",
".",
"default",
":",
"return",
"if",
"self",
".",
"dec... | 37.5 | 20.681818 |
def line(self, lines):
"""Creates a POLYLINE shape.
Lines is a collection of lines, each made up of a list of xy values."""
shapeType = POLYLINE
self._shapeparts(parts=lines, shapeType=shapeType) | [
"def",
"line",
"(",
"self",
",",
"lines",
")",
":",
"shapeType",
"=",
"POLYLINE",
"self",
".",
"_shapeparts",
"(",
"parts",
"=",
"lines",
",",
"shapeType",
"=",
"shapeType",
")"
] | 45.4 | 9.2 |
def borrow(ctx, amount, symbol, ratio, account):
""" Borrow a bitasset/market-pegged asset
"""
from bitshares.dex import Dex
dex = Dex(bitshares_instance=ctx.bitshares)
print_tx(
dex.borrow(Amount(amount, symbol), collateral_ratio=ratio, account=account)
) | [
"def",
"borrow",
"(",
"ctx",
",",
"amount",
",",
"symbol",
",",
"ratio",
",",
"account",
")",
":",
"from",
"bitshares",
".",
"dex",
"import",
"Dex",
"dex",
"=",
"Dex",
"(",
"bitshares_instance",
"=",
"ctx",
".",
"bitshares",
")",
"print_tx",
"(",
"dex"... | 31.222222 | 18.555556 |
def _init_metadata(self):
"""stub"""
self._published_metadata = {
'element_id': Id(self.my_osid_object_form._authority,
self.my_osid_object_form._namespace,
'published'),
'element_label': 'Published',
'instruct... | [
"def",
"_init_metadata",
"(",
"self",
")",
":",
"self",
".",
"_published_metadata",
"=",
"{",
"'element_id'",
":",
"Id",
"(",
"self",
".",
"my_osid_object_form",
".",
"_authority",
",",
"self",
".",
"my_osid_object_form",
".",
"_namespace",
",",
"'published'",
... | 37.4 | 12.466667 |
def disassociate_reserved_ip_address(
self, name, service_name, deployment_name, virtual_ip_name=None
):
'''
Disassociate an existing reservedIP from the given deployment.
name:
Required. Name of the reserved IP address.
service_name:
Required. Name ... | [
"def",
"disassociate_reserved_ip_address",
"(",
"self",
",",
"name",
",",
"service_name",
",",
"deployment_name",
",",
"virtual_ip_name",
"=",
"None",
")",
":",
"_validate_not_none",
"(",
"'name'",
",",
"name",
")",
"_validate_not_none",
"(",
"'service_name'",
",",
... | 34.419355 | 21.645161 |
def csv_to_numpy(string_like, dtype=None): # type: (str) -> np.array
"""Convert a CSV object to a numpy array.
Args:
string_like (str): CSV string.
dtype (dtype, optional): Data type of the resulting array. If None, the dtypes will be determined by the
... | [
"def",
"csv_to_numpy",
"(",
"string_like",
",",
"dtype",
"=",
"None",
")",
":",
"# type: (str) -> np.array",
"stream",
"=",
"StringIO",
"(",
"string_like",
")",
"return",
"np",
".",
"genfromtxt",
"(",
"stream",
",",
"dtype",
"=",
"dtype",
",",
"delimiter",
"... | 48.769231 | 28.769231 |
def listen_on_tcp_port():
"""listen_on_tcp_port
Run a simple server for processing messages over ``TCP``.
``LISTEN_ON_HOST`` - listen on this host ip address
``LISTEN_ON_PORT`` - listen on this ``TCP`` port
``LISTEN_SIZE`` - listen on to packets of this size
``LISTEN_SLEEP`` - sleep this nu... | [
"def",
"listen_on_tcp_port",
"(",
")",
":",
"host",
"=",
"os",
".",
"getenv",
"(",
"\"LISTEN_ON_HOST\"",
",",
"\"127.0.0.1\"",
")",
".",
"strip",
"(",
")",
".",
"lstrip",
"(",
")",
"port",
"=",
"int",
"(",
"os",
".",
"getenv",
"(",
"\"LISTEN_ON_PORT\"",
... | 26.631579 | 17.473684 |
async def close(self, exception: BaseException = None) -> None:
"""
Close this context and call any necessary resource teardown callbacks.
If a teardown callback returns an awaitable, the return value is awaited on before calling
any further teardown callbacks.
All callbacks wi... | [
"async",
"def",
"close",
"(",
"self",
",",
"exception",
":",
"BaseException",
"=",
"None",
")",
"->",
"None",
":",
"self",
".",
"_check_closed",
"(",
")",
"self",
".",
"_closed",
"=",
"True",
"exceptions",
"=",
"[",
"]",
"for",
"callback",
",",
"pass_e... | 39.46875 | 26.71875 |
def totextindex(table, index_or_dirname, schema=None, indexname=None,
merge=False, optimize=False):
"""
Load all rows from `table` into a Whoosh index. N.B., this will clear any
existing data in the index before loading. E.g.::
>>> import petl as etl
>>> import datetime
... | [
"def",
"totextindex",
"(",
"table",
",",
"index_or_dirname",
",",
"schema",
"=",
"None",
",",
"indexname",
"=",
"None",
",",
"merge",
"=",
"False",
",",
"optimize",
"=",
"False",
")",
":",
"import",
"whoosh",
".",
"index",
"import",
"whoosh",
".",
"writi... | 33.935065 | 19.467532 |
def q_beta(self):
"""Return Q_beta"""
f = lambda parent, daugther: parent - daugther
return self.derived('Q_beta', (1, -1), f) | [
"def",
"q_beta",
"(",
"self",
")",
":",
"f",
"=",
"lambda",
"parent",
",",
"daugther",
":",
"parent",
"-",
"daugther",
"return",
"self",
".",
"derived",
"(",
"'Q_beta'",
",",
"(",
"1",
",",
"-",
"1",
")",
",",
"f",
")"
] | 36.75 | 11.5 |
def write_to_filterbank(self, filename_out):
""" Write data to blimpy file.
Args:
filename_out (str): Name of output file
"""
print("[Filterbank] Warning: Non-standard function to write in filterbank (.fil) format. Please use Waterfall.")
n_bytes = int(self.header... | [
"def",
"write_to_filterbank",
"(",
"self",
",",
"filename_out",
")",
":",
"print",
"(",
"\"[Filterbank] Warning: Non-standard function to write in filterbank (.fil) format. Please use Waterfall.\"",
")",
"n_bytes",
"=",
"int",
"(",
"self",
".",
"header",
"[",
"b'nbits'",
"]... | 36.210526 | 18.263158 |
def create_logger(name):
"""
Creates a logger with the below attributes.
:param str name: Name of the logger
:return obj: Logger
"""
logging.config.dictConfig({
'version': 1,
'disable_existing_loggers': False,
'formatters': {
'simple': {
'forma... | [
"def",
"create_logger",
"(",
"name",
")",
":",
"logging",
".",
"config",
".",
"dictConfig",
"(",
"{",
"'version'",
":",
"1",
",",
"'disable_existing_loggers'",
":",
"False",
",",
"'formatters'",
":",
"{",
"'simple'",
":",
"{",
"'format'",
":",
"'%(asctime)s ... | 30.8125 | 15.9375 |
def read_val(self, key:str) -> Union[List[float],Tuple[List[float],List[float]]]:
"Read a hyperparameter `key` in the optimizer dictionary."
val = [pg[key] for pg in self.opt.param_groups[::2]]
if is_tuple(val[0]): val = [o[0] for o in val], [o[1] for o in val]
return val | [
"def",
"read_val",
"(",
"self",
",",
"key",
":",
"str",
")",
"->",
"Union",
"[",
"List",
"[",
"float",
"]",
",",
"Tuple",
"[",
"List",
"[",
"float",
"]",
",",
"List",
"[",
"float",
"]",
"]",
"]",
":",
"val",
"=",
"[",
"pg",
"[",
"key",
"]",
... | 60 | 28.8 |
def from_file(cls, path, **kwargs):
"""Create an editor instance from a file on disk."""
lines = lines_from_file(path)
if 'meta' not in kwargs:
kwargs['meta'] = {'from': 'file'}
kwargs['meta']['filepath'] = path
return cls(lines, **kwargs) | [
"def",
"from_file",
"(",
"cls",
",",
"path",
",",
"*",
"*",
"kwargs",
")",
":",
"lines",
"=",
"lines_from_file",
"(",
"path",
")",
"if",
"'meta'",
"not",
"in",
"kwargs",
":",
"kwargs",
"[",
"'meta'",
"]",
"=",
"{",
"'from'",
":",
"'file'",
"}",
"kw... | 40.714286 | 3.857143 |
def plot_plate_limits(axis, ridges, trenches, ymin, ymax):
"""plot lines designating ridges and trenches"""
for trench in trenches:
axis.axvline(
x=trench, ymin=ymin, ymax=ymax,
color='red', ls='dashed', alpha=0.4)
for ridge in ridges:
axis.axvline(
x=ridg... | [
"def",
"plot_plate_limits",
"(",
"axis",
",",
"ridges",
",",
"trenches",
",",
"ymin",
",",
"ymax",
")",
":",
"for",
"trench",
"in",
"trenches",
":",
"axis",
".",
"axvline",
"(",
"x",
"=",
"trench",
",",
"ymin",
"=",
"ymin",
",",
"ymax",
"=",
"ymax",
... | 37.166667 | 10.666667 |
def get(self, dismiss=True):
"""Extract the object this key points to.
Objects are not read or decompressed until this function is explicitly called.
"""
try:
return _classof(self._context, self._fClassName).read(self._source, self._cursor.copied(), self._context, self)
... | [
"def",
"get",
"(",
"self",
",",
"dismiss",
"=",
"True",
")",
":",
"try",
":",
"return",
"_classof",
"(",
"self",
".",
"_context",
",",
"self",
".",
"_fClassName",
")",
".",
"read",
"(",
"self",
".",
"_source",
",",
"self",
".",
"_cursor",
".",
"cop... | 35.090909 | 26.545455 |
def request_status(self):
'''request the status of the card dispenser and return the status code'''
self.sendcommand(Vendapin.REQUEST_STATUS)
# wait for the reply
time.sleep(1)
response = self.receivepacket()
if self.was_packet_accepted(response):
return Venda... | [
"def",
"request_status",
"(",
"self",
")",
":",
"self",
".",
"sendcommand",
"(",
"Vendapin",
".",
"REQUEST_STATUS",
")",
"# wait for the reply",
"time",
".",
"sleep",
"(",
"1",
")",
"response",
"=",
"self",
".",
"receivepacket",
"(",
")",
"if",
"self",
"."... | 38.1 | 14.3 |
def Publish(self, request, context):
"""Dispatches the request to the plugins publish method"""
LOG.debug("Publish called")
try:
self.plugin.publish(
[Metric(pb=m) for m in request.Metrics],
ConfigMap(pb=request.Config)
)
return... | [
"def",
"Publish",
"(",
"self",
",",
"request",
",",
"context",
")",
":",
"LOG",
".",
"debug",
"(",
"\"Publish called\"",
")",
"try",
":",
"self",
".",
"plugin",
".",
"publish",
"(",
"[",
"Metric",
"(",
"pb",
"=",
"m",
")",
"for",
"m",
"in",
"reques... | 38.076923 | 10.384615 |
def _release(self):
"""Upload the release, when desired"""
pypiconfig = pypi.PypiConfig()
# Does the user normally want a real release? We are
# interested in getting a sane default answer here, so you can
# override it in the exceptional case but just hit Enter in
# t... | [
"def",
"_release",
"(",
"self",
")",
":",
"pypiconfig",
"=",
"pypi",
".",
"PypiConfig",
"(",
")",
"# Does the user normally want a real release? We are",
"# interested in getting a sane default answer here, so you can",
"# override it in the exceptional case but just hit Enter in",
... | 42.333333 | 21.4 |
def duration(
days=0, # type: float
seconds=0, # type: float
microseconds=0, # type: float
milliseconds=0, # type: float
minutes=0, # type: float
hours=0, # type: float
weeks=0, # type: float
years=0, # type: float
months=0, # type: float
): # type: (...) -> Duration
""... | [
"def",
"duration",
"(",
"days",
"=",
"0",
",",
"# type: float",
"seconds",
"=",
"0",
",",
"# type: float",
"microseconds",
"=",
"0",
",",
"# type: float",
"milliseconds",
"=",
"0",
",",
"# type: float",
"minutes",
"=",
"0",
",",
"# type: float",
"hours",
"="... | 23.56 | 13.8 |
def make_indices_to_labels(labels: Set[str]) -> Dict[int, str]:
""" Creates a mapping from indices to labels. """
return {index: label for index, label in
enumerate(["pad"] + sorted(list(labels)))} | [
"def",
"make_indices_to_labels",
"(",
"labels",
":",
"Set",
"[",
"str",
"]",
")",
"->",
"Dict",
"[",
"int",
",",
"str",
"]",
":",
"return",
"{",
"index",
":",
"label",
"for",
"index",
",",
"label",
"in",
"enumerate",
"(",
"[",
"\"pad\"",
"]",
"+",
... | 42.8 | 16.2 |
def UploadType(cls, file_path):
""" 上传, 一般,上传页面如果是input,原生file文件框, 如: <input type="file" id="test-image-file" name="test" accept="image/gif">,像这样的,定位到该元素,然后使用 send_keys 上传的文件的绝对路径
@param file_name: 文件名(文件必须存在在工程resource目录下)
"""
if not os.path.isabs(file_path):
... | [
"def",
"UploadType",
"(",
"cls",
",",
"file_path",
")",
":",
"if",
"not",
"os",
".",
"path",
".",
"isabs",
"(",
"file_path",
")",
":",
"return",
"False",
"if",
"os",
".",
"path",
".",
"isfile",
"(",
"file_path",
")",
":",
"cls",
".",
"SendKeys",
"(... | 42.090909 | 9.363636 |
def intersect_curves(nodes1, nodes2):
r"""Intersect two parametric B |eacute| zier curves.
Args:
nodes1 (numpy.ndarray): The nodes in the first curve.
nodes2 (numpy.ndarray): The nodes in the second curve.
Returns:
numpy.ndarray: ``2 x N`` array of intersection parameters.
... | [
"def",
"intersect_curves",
"(",
"nodes1",
",",
"nodes2",
")",
":",
"nodes1",
"=",
"_curve_helpers",
".",
"full_reduce",
"(",
"nodes1",
")",
"nodes2",
"=",
"_curve_helpers",
".",
"full_reduce",
"(",
"nodes2",
")",
"_",
",",
"num_nodes1",
"=",
"nodes1",
".",
... | 34.804348 | 17.782609 |
def _defines(prefix, defs, suffix, env, c=_concat_ixes):
"""A wrapper around _concat_ixes that turns a list or string
into a list of C preprocessor command-line definitions.
"""
return c(prefix, env.subst_path(processDefines(defs)), suffix, env) | [
"def",
"_defines",
"(",
"prefix",
",",
"defs",
",",
"suffix",
",",
"env",
",",
"c",
"=",
"_concat_ixes",
")",
":",
"return",
"c",
"(",
"prefix",
",",
"env",
".",
"subst_path",
"(",
"processDefines",
"(",
"defs",
")",
")",
",",
"suffix",
",",
"env",
... | 42.833333 | 17.666667 |
def launch_from_template(self, template_path, notebook_dir=None,
overwrite=False, output_name=None,
create_dir=False, no_browser=False, **kwargs):
'''
Launch a copy of the specified `.ipynb` (template) file in an IPython
notebook session ... | [
"def",
"launch_from_template",
"(",
"self",
",",
"template_path",
",",
"notebook_dir",
"=",
"None",
",",
"overwrite",
"=",
"False",
",",
"output_name",
"=",
"None",
",",
"create_dir",
"=",
"False",
",",
"no_browser",
"=",
"False",
",",
"*",
"*",
"kwargs",
... | 41.862745 | 24.137255 |
def hide_routemap_holder_route_map_content_set_ip_next_hop_peer_address(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
hide_routemap_holder = ET.SubElement(config, "hide-routemap-holder", xmlns="urn:brocade.com:mgmt:brocade-ip-policy")
route_map = ET.Su... | [
"def",
"hide_routemap_holder_route_map_content_set_ip_next_hop_peer_address",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"config",
"=",
"ET",
".",
"Element",
"(",
"\"config\"",
")",
"hide_routemap_holder",
"=",
"ET",
".",
"SubElement",
"(",
"config",
",",
"\"... | 50.2 | 17.65 |
def from_name(cls, name):
"""Create an author by name, automatically populating the hash."""
return Author(name=name, sha512=cls.hash_name(name)) | [
"def",
"from_name",
"(",
"cls",
",",
"name",
")",
":",
"return",
"Author",
"(",
"name",
"=",
"name",
",",
"sha512",
"=",
"cls",
".",
"hash_name",
"(",
"name",
")",
")"
] | 53.666667 | 11.333333 |
def read_header(fd, endian):
"""Read and return the matrix header."""
flag_class, nzmax = read_elements(fd, endian, ['miUINT32'])
header = {
'mclass': flag_class & 0x0FF,
'is_logical': (flag_class >> 9 & 1) == 1,
'is_global': (flag_class >> 10 & 1) == 1,
'is_complex': (flag_c... | [
"def",
"read_header",
"(",
"fd",
",",
"endian",
")",
":",
"flag_class",
",",
"nzmax",
"=",
"read_elements",
"(",
"fd",
",",
"endian",
",",
"[",
"'miUINT32'",
"]",
")",
"header",
"=",
"{",
"'mclass'",
":",
"flag_class",
"&",
"0x0FF",
",",
"'is_logical'",
... | 40.8125 | 16.5625 |
def range(self, start, end=None, step=1, numSlices=None):
"""
Create a new RDD of int containing elements from `start` to `end`
(exclusive), increased by `step` every element. Can be called the same
way as python's built-in range() function. If called with a single argument,
the ... | [
"def",
"range",
"(",
"self",
",",
"start",
",",
"end",
"=",
"None",
",",
"step",
"=",
"1",
",",
"numSlices",
"=",
"None",
")",
":",
"if",
"end",
"is",
"None",
":",
"end",
"=",
"start",
"start",
"=",
"0",
"return",
"self",
".",
"parallelize",
"(",... | 36.48 | 19.92 |
def enum_sigma_cubic(cutoff, r_axis):
"""
Find all possible sigma values and corresponding rotation angles
within a sigma value cutoff with known rotation axis in cubic system.
The algorithm for this code is from reference, Acta Cryst, A40,108(1984)
Args:
cutoff (inte... | [
"def",
"enum_sigma_cubic",
"(",
"cutoff",
",",
"r_axis",
")",
":",
"sigmas",
"=",
"{",
"}",
"# make sure gcd(r_axis)==1",
"if",
"reduce",
"(",
"gcd",
",",
"r_axis",
")",
"!=",
"1",
":",
"r_axis",
"=",
"[",
"int",
"(",
"round",
"(",
"x",
"/",
"reduce",
... | 47.907895 | 20.907895 |
def compressed_char(self, action):
'''Enable/cancel compressed character printing
Args:
action: Enable or disable compressed character printing. Options are 'on' and 'off'
Returns:
None
Raises:
RuntimeError: Invalid action.
'''
... | [
"def",
"compressed_char",
"(",
"self",
",",
"action",
")",
":",
"if",
"action",
"==",
"'on'",
":",
"action",
"=",
"15",
"elif",
"action",
"==",
"'off'",
":",
"action",
"=",
"18",
"else",
":",
"raise",
"RuntimeError",
"(",
"'Invalid action for function compre... | 32.176471 | 23.117647 |
def notify_command(command_format, mounter):
"""
Command notification tool.
This works similar to Notify, but will issue command instead of showing
the notifications on the desktop. This can then be used to react to events
from shell scripts.
The command can contain modern pythonic format plac... | [
"def",
"notify_command",
"(",
"command_format",
",",
"mounter",
")",
":",
"udisks",
"=",
"mounter",
".",
"udisks",
"for",
"event",
"in",
"[",
"'device_mounted'",
",",
"'device_unmounted'",
",",
"'device_locked'",
",",
"'device_unlocked'",
",",
"'device_added'",
",... | 41.727273 | 20.545455 |
def setAccessPolicy(self, pid, accessPolicy, serialVersion, vendorSpecific=None):
"""See Also: setAccessPolicyResponse()
Args:
pid:
accessPolicy:
serialVersion:
vendorSpecific:
Returns:
"""
response = self.setAccessPolicyResponse(
... | [
"def",
"setAccessPolicy",
"(",
"self",
",",
"pid",
",",
"accessPolicy",
",",
"serialVersion",
",",
"vendorSpecific",
"=",
"None",
")",
":",
"response",
"=",
"self",
".",
"setAccessPolicyResponse",
"(",
"pid",
",",
"accessPolicy",
",",
"serialVersion",
",",
"ve... | 26.375 | 22.3125 |
def load_module(self, module_name, pfx=None, path=None):
"""Load/reload module from the given name."""
try:
if pfx:
name = pfx + '.' + module_name
else:
name = module_name
if name in sys.modules:
module = sys.modules[na... | [
"def",
"load_module",
"(",
"self",
",",
"module_name",
",",
"pfx",
"=",
"None",
",",
"path",
"=",
"None",
")",
":",
"try",
":",
"if",
"pfx",
":",
"name",
"=",
"pfx",
"+",
"'.'",
"+",
"module_name",
"else",
":",
"name",
"=",
"module_name",
"if",
"na... | 34.125 | 18.166667 |
def add_material(self, media_file, media_type='icon'):
"""
上传图片素材
详情请参考
http://mp.weixin.qq.com/wiki/5/e997428269ff189d8f9a4b9e177be2d9.html
:param media_file: 要上传的文件,一个 File-object
:param media_type: 摇一摇素材类型, 取值为 icon或者 license, 默认 icon.
:return: 上传的素材信息
... | [
"def",
"add_material",
"(",
"self",
",",
"media_file",
",",
"media_type",
"=",
"'icon'",
")",
":",
"res",
"=",
"self",
".",
"_post",
"(",
"'shakearound/material/add'",
",",
"files",
"=",
"{",
"'media'",
":",
"media_file",
"}",
",",
"params",
"=",
"{",
"'... | 28.095238 | 17.714286 |
def authorize(self, scope=None, redirect_uri=None, state=None):
"""
Redirect to GitHub and request access to a user's data.
:param scope: List of `Scopes`_ for which to request access, formatted
as a string or comma delimited list of scopes as a
strin... | [
"def",
"authorize",
"(",
"self",
",",
"scope",
"=",
"None",
",",
"redirect_uri",
"=",
"None",
",",
"state",
"=",
"None",
")",
":",
"_logger",
".",
"debug",
"(",
"\"Called authorize()\"",
")",
"params",
"=",
"{",
"'client_id'",
":",
"self",
".",
"client_i... | 46.215385 | 26.584615 |
def is_correct(self):
"""Check if the hosts list configuration is correct ::
* check if any loop exists in each host dependencies
* Call our parent class is_correct checker
:return: True if the configuration is correct, otherwise False
:rtype: bool
"""
state = T... | [
"def",
"is_correct",
"(",
"self",
")",
":",
"state",
"=",
"True",
"# Internal checks before executing inherited function...",
"loop",
"=",
"self",
".",
"no_loop_in_parents",
"(",
"\"self\"",
",",
"\"parents\"",
")",
"if",
"loop",
":",
"self",
".",
"add_error",
"("... | 42.576923 | 23.538462 |
def kwargs(self):
"""The keyword arguments that unpack something.
:type: list(Keyword)
"""
keywords = self.keywords or []
return [keyword for keyword in keywords if keyword.arg is None] | [
"def",
"kwargs",
"(",
"self",
")",
":",
"keywords",
"=",
"self",
".",
"keywords",
"or",
"[",
"]",
"return",
"[",
"keyword",
"for",
"keyword",
"in",
"keywords",
"if",
"keyword",
".",
"arg",
"is",
"None",
"]"
] | 31.428571 | 15.428571 |
def model(UserModel):
"""
Post Model
:param UserModel:
"""
db = UserModel.db
class SlugNameMixin(object):
name = db.Column(db.String(255), index=True)
slug = db.Column(db.String(255), index=True, unique=True)
description = db.Column(db.String(255))
image_url = d... | [
"def",
"model",
"(",
"UserModel",
")",
":",
"db",
"=",
"UserModel",
".",
"db",
"class",
"SlugNameMixin",
"(",
"object",
")",
":",
"name",
"=",
"db",
".",
"Column",
"(",
"db",
".",
"String",
"(",
"255",
")",
",",
"index",
"=",
"True",
")",
"slug",
... | 35.701493 | 16.905473 |
def _equivalent(self, other):
"""Compare two entities of the same class, excluding keys."""
if other.__class__ is not self.__class__: # TODO: What about subclasses?
raise NotImplementedError('Cannot compare different model classes. '
'%s is not %s' % (self.__class__.__name... | [
"def",
"_equivalent",
"(",
"self",
",",
"other",
")",
":",
"if",
"other",
".",
"__class__",
"is",
"not",
"self",
".",
"__class__",
":",
"# TODO: What about subclasses?",
"raise",
"NotImplementedError",
"(",
"'Cannot compare different model classes. '",
"'%s is not %s'",... | 46.68 | 16.4 |
def _find_rankings(self, year):
"""
Retrieve the rankings for each week.
Find and retrieve all AP rankings for the requested year and combine
them on a per-week basis. Each week contains information about the
name, abbreviation, rank, movement, and previous rank for each team
... | [
"def",
"_find_rankings",
"(",
"self",
",",
"year",
")",
":",
"if",
"not",
"year",
":",
"year",
"=",
"utils",
".",
"_find_year_for_season",
"(",
"'ncaaf'",
")",
"page",
"=",
"self",
".",
"_pull_rankings_page",
"(",
"year",
")",
"if",
"not",
"page",
":",
... | 41.894737 | 17.649123 |
def _osd_pct_used(self, health):
"""Take a single health check string, return (OSD name, percentage used)"""
# Full string looks like: osd.2 is full at 95%
# Near full string: osd.1 is near full at 94%
pct = re.compile(r'\d+%').findall(health)
osd = re.compile(r'osd.\d+').findall... | [
"def",
"_osd_pct_used",
"(",
"self",
",",
"health",
")",
":",
"# Full string looks like: osd.2 is full at 95%",
"# Near full string: osd.1 is near full at 94%",
"pct",
"=",
"re",
".",
"compile",
"(",
"r'\\d+%'",
")",
".",
"findall",
"(",
"health",
")",
"osd",
"=",
"... | 44.9 | 9.8 |
def psd_spacing(d_min=None, d_max=None, pts=20, method='logarithmic'):
r'''Create a particle spacing mesh in one of several ways for use in
modeling discrete particle size distributions. The allowable meshes are
'linear', 'logarithmic', a geometric series specified by a Renard number
such as 'R10', or t... | [
"def",
"psd_spacing",
"(",
"d_min",
"=",
"None",
",",
"d_max",
"=",
"None",
",",
"pts",
"=",
"20",
",",
"method",
"=",
"'logarithmic'",
")",
":",
"if",
"method",
"==",
"'logarithmic'",
":",
"return",
"logspace",
"(",
"log10",
"(",
"d_min",
")",
",",
... | 37.297297 | 21.189189 |
def add_params(self, **kw):
"""
Add [possibly many] parameters to the track.
Parameters will be checked against known UCSC parameters and their
supported formats.
E.g.::
add_params(color='128,0,0', visibility='dense')
"""
for k, v in kw.items():
... | [
"def",
"add_params",
"(",
"self",
",",
"*",
"*",
"kw",
")",
":",
"for",
"k",
",",
"v",
"in",
"kw",
".",
"items",
"(",
")",
":",
"if",
"(",
"k",
"not",
"in",
"self",
".",
"params",
")",
"and",
"(",
"k",
"not",
"in",
"self",
".",
"specific_para... | 32.217391 | 21 |
def http_adapter_kwargs():
"""
Provides Zenpy's default HTTPAdapter args for those users providing their own adapter.
"""
return dict(
# Transparently retry requests that are safe to retry, with the exception of 429. This is handled
# in the Api._call_api() metho... | [
"def",
"http_adapter_kwargs",
"(",
")",
":",
"return",
"dict",
"(",
"# Transparently retry requests that are safe to retry, with the exception of 429. This is handled",
"# in the Api._call_api() method.",
"max_retries",
"=",
"Retry",
"(",
"total",
"=",
"3",
",",
"status_forcelist... | 37.714286 | 24.428571 |
def get_state(self):
""" Get the current view state of the camera
Returns a dict of key-value pairs. The exact keys depend on the
camera. Can be passed to set_state() (of this or another camera
of the same type) to reproduce the state.
"""
D = {}
for key in self.... | [
"def",
"get_state",
"(",
"self",
")",
":",
"D",
"=",
"{",
"}",
"for",
"key",
"in",
"self",
".",
"_state_props",
":",
"D",
"[",
"key",
"]",
"=",
"getattr",
"(",
"self",
",",
"key",
")",
"return",
"D"
] | 34.545455 | 16.818182 |
def take(iterrable, howMay):
"""
:return: generator of first n items from iterrable
"""
assert howMay >= 0
if not howMay:
return
last = howMay - 1
for i, item in enumerate(iterrable):
yield item
if i == last:
return | [
"def",
"take",
"(",
"iterrable",
",",
"howMay",
")",
":",
"assert",
"howMay",
">=",
"0",
"if",
"not",
"howMay",
":",
"return",
"last",
"=",
"howMay",
"-",
"1",
"for",
"i",
",",
"item",
"in",
"enumerate",
"(",
"iterrable",
")",
":",
"yield",
"item",
... | 19.142857 | 18.142857 |
def containing_simplex_and_bcc(self, xi, yi):
"""
Returns the simplices containing (xi,yi)
and the local barycentric, normalised coordinates.
Parameters
----------
xi : float / array of floats, shape (l,)
Cartesian coordinates in the x direction
yi ... | [
"def",
"containing_simplex_and_bcc",
"(",
"self",
",",
"xi",
",",
"yi",
")",
":",
"pts",
"=",
"np",
".",
"column_stack",
"(",
"[",
"xi",
",",
"yi",
"]",
")",
"tri",
"=",
"np",
".",
"empty",
"(",
"(",
"pts",
".",
"shape",
"[",
"0",
"]",
",",
"3"... | 29.672727 | 19.890909 |
def add_site_dir(dir_name, before=None, _path=None):
"""Add a pseudo site-packages directory to :data:`python:sys.path`.
:param str dir_name: The directory to add.
:param str before: A directory on :data:`sys.path` that new paths should be
inserted before.
Looks for ``.pth`` files at the t... | [
"def",
"add_site_dir",
"(",
"dir_name",
",",
"before",
"=",
"None",
",",
"_path",
"=",
"None",
")",
":",
"log",
".",
"log",
"(",
"5",
",",
"'add_site_dir(%r, before=%r)'",
",",
"dir_name",
",",
"before",
")",
"# Don't do anything if the folder doesn't exist.",
"... | 33 | 22.142857 |
def referenced(self):
"""
For a cursor that is a reference, returns a cursor
representing the entity that it references.
"""
if not hasattr(self, '_referenced'):
self._referenced = conf.lib.clang_getCursorReferenced(self)
return self._referenced | [
"def",
"referenced",
"(",
"self",
")",
":",
"if",
"not",
"hasattr",
"(",
"self",
",",
"'_referenced'",
")",
":",
"self",
".",
"_referenced",
"=",
"conf",
".",
"lib",
".",
"clang_getCursorReferenced",
"(",
"self",
")",
"return",
"self",
".",
"_referenced"
] | 33.111111 | 14.666667 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.