text stringlengths 89 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 630 |
|---|---|---|---|
def get_image_layer(self, image_id):
"""GET /v1/images/(image_id)/json"""
return self._http_call(self.IMAGE_JSON, get, image_id=image_id) | [
"def",
"get_image_layer",
"(",
"self",
",",
"image_id",
")",
":",
"return",
"self",
".",
"_http_call",
"(",
"self",
".",
"IMAGE_JSON",
",",
"get",
",",
"image_id",
"=",
"image_id",
")"
] | 50.333333 | 11.666667 |
def _GetKeyFlagsForModule(self, module):
"""Returns the list of key flags for a module.
Args:
module: A module object or a module name (a string)
Returns:
A new list of Flag objects. Caller may update this list as he
wishes: none of those changes will affect the internals of this
... | [
"def",
"_GetKeyFlagsForModule",
"(",
"self",
",",
"module",
")",
":",
"if",
"not",
"isinstance",
"(",
"module",
",",
"str",
")",
":",
"module",
"=",
"module",
".",
"__name__",
"# Any flag is a key flag for the module that defined it. NOTE:",
"# key_flags is a fresh lis... | 35.166667 | 20.291667 |
def include_items(items, any_all=any, ignore_case=False, normalize_values=False, **kwargs):
"""Include items by matching metadata.
Note:
Metadata values are lowercased when ``normalized_values`` is ``True``,
so ``ignore_case`` is automatically set to ``True``.
Parameters:
items (list): A list of item dicts o... | [
"def",
"include_items",
"(",
"items",
",",
"any_all",
"=",
"any",
",",
"ignore_case",
"=",
"False",
",",
"normalize_values",
"=",
"False",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"kwargs",
":",
"match",
"=",
"functools",
".",
"partial",
"(",
"_match_ite... | 35.393939 | 29.787879 |
def trigger_update(self, trigger_parent=True):
"""
Update the model from the current state.
Make sure that updates are on, otherwise this
method will do nothing
:param bool trigger_parent: Whether to trigger the parent, after self has updated
"""
if not self.upda... | [
"def",
"trigger_update",
"(",
"self",
",",
"trigger_parent",
"=",
"True",
")",
":",
"if",
"not",
"self",
".",
"update_model",
"(",
")",
"or",
"(",
"hasattr",
"(",
"self",
",",
"\"_in_init_\"",
")",
"and",
"self",
".",
"_in_init_",
")",
":",
"#print \"War... | 43.75 | 20.583333 |
def convert_tdc_to_channel(channel):
''' Converts TDC words at a given channel to common TDC header (0x4).
'''
def f(value):
filter_func = logical_and(is_tdc_word, is_tdc_from_channel(channel))
select = filter_func(value)
value[select] = np.bitwise_and(value[select], 0x0FFFFFFF... | [
"def",
"convert_tdc_to_channel",
"(",
"channel",
")",
":",
"def",
"f",
"(",
"value",
")",
":",
"filter_func",
"=",
"logical_and",
"(",
"is_tdc_word",
",",
"is_tdc_from_channel",
"(",
"channel",
")",
")",
"select",
"=",
"filter_func",
"(",
"value",
")",
"valu... | 43.272727 | 22.909091 |
def set_ip(self, ip):
"""Change the current IP."""
self.set(ip=ip, netmask=self._nm) | [
"def",
"set_ip",
"(",
"self",
",",
"ip",
")",
":",
"self",
".",
"set",
"(",
"ip",
"=",
"ip",
",",
"netmask",
"=",
"self",
".",
"_nm",
")"
] | 32.666667 | 6.666667 |
def evaluate(contents, jsonnet_library_paths=None):
'''
Evaluate a jsonnet input string.
contents
Raw jsonnet string to evaluate.
jsonnet_library_paths
List of jsonnet library paths.
'''
if not jsonnet_library_paths:
jsonnet_library_paths = __salt__['config.option'](
... | [
"def",
"evaluate",
"(",
"contents",
",",
"jsonnet_library_paths",
"=",
"None",
")",
":",
"if",
"not",
"jsonnet_library_paths",
":",
"jsonnet_library_paths",
"=",
"__salt__",
"[",
"'config.option'",
"]",
"(",
"'jsonnet.library_paths'",
",",
"[",
"'.'",
"]",
")",
... | 29.55 | 17.65 |
def download_file(self, file_id, dest_file_path,
progress_callback=None,
chunk_size=1024*1024*1):
"""Download a file.
The whole file is never loaded in memory.
The callback(transferred, total) to let you know the download progress.
... | [
"def",
"download_file",
"(",
"self",
",",
"file_id",
",",
"dest_file_path",
",",
"progress_callback",
"=",
"None",
",",
"chunk_size",
"=",
"1024",
"*",
"1024",
"*",
"1",
")",
":",
"with",
"open",
"(",
"dest_file_path",
",",
"'wb'",
")",
"as",
"fp",
":",
... | 39.403846 | 22.826923 |
def showGrid( self ):
"""
Returns whether or not this delegate should draw its grid lines.
:return <bool>
"""
delegate = self.itemDelegate()
if ( isinstance(delegate, XTreeWidgetDelegate) ):
return delegate.showGrid()
return False | [
"def",
"showGrid",
"(",
"self",
")",
":",
"delegate",
"=",
"self",
".",
"itemDelegate",
"(",
")",
"if",
"(",
"isinstance",
"(",
"delegate",
",",
"XTreeWidgetDelegate",
")",
")",
":",
"return",
"delegate",
".",
"showGrid",
"(",
")",
"return",
"False"
] | 31.1 | 13.5 |
def brcktd(number, end1, end2):
"""
Bracket a number. That is, given a number and an acceptable
interval, make sure that the number is contained in the
interval. (If the number is already in the interval, leave it
alone. If not, set it to the nearest endpoint of the interval.)
http://naif.jpl.n... | [
"def",
"brcktd",
"(",
"number",
",",
"end1",
",",
"end2",
")",
":",
"number",
"=",
"ctypes",
".",
"c_double",
"(",
"number",
")",
"end1",
"=",
"ctypes",
".",
"c_double",
"(",
"end1",
")",
"end2",
"=",
"ctypes",
".",
"c_double",
"(",
"end2",
")",
"r... | 36.318182 | 16.590909 |
def playlist_detail(self, playlist_id):
"""获取歌单详情
如果歌单歌曲数超过 100 时,该接口的 songs 字段不会包含所有歌曲,
但是它有个 allSongs 字段,会包含所有歌曲的 ID。
"""
action = 'mtop.alimusic.music.list.collectservice.getcollectdetail'
payload = {'listId': playlist_id}
code, msg, rv = self.request(action, ... | [
"def",
"playlist_detail",
"(",
"self",
",",
"playlist_id",
")",
":",
"action",
"=",
"'mtop.alimusic.music.list.collectservice.getcollectdetail'",
"payload",
"=",
"{",
"'listId'",
":",
"playlist_id",
"}",
"code",
",",
"msg",
",",
"rv",
"=",
"self",
".",
"request",
... | 37 | 10.8 |
def p_ExtendedAttributeArgList(p):
"""ExtendedAttributeArgList : IDENTIFIER "(" ArgumentList ")"
"""
p[0] = model.ExtendedAttribute(
value=model.ExtendedAttributeValue(name=p[1], arguments=p[3])) | [
"def",
"p_ExtendedAttributeArgList",
"(",
"p",
")",
":",
"p",
"[",
"0",
"]",
"=",
"model",
".",
"ExtendedAttribute",
"(",
"value",
"=",
"model",
".",
"ExtendedAttributeValue",
"(",
"name",
"=",
"p",
"[",
"1",
"]",
",",
"arguments",
"=",
"p",
"[",
"3",
... | 40.2 | 7.8 |
def weighted_average(rule, artifact):
"""Evaluate artifact's value to be weighted average of values returned by
rule's subrules.
"""
e = 0
w = 0
for i in range(len(rule.R)):
r = rule.R[i](artifact)
if r is not None:
e += r * rule.W[i]
w += abs(rule.W[i])
... | [
"def",
"weighted_average",
"(",
"rule",
",",
"artifact",
")",
":",
"e",
"=",
"0",
"w",
"=",
"0",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"rule",
".",
"R",
")",
")",
":",
"r",
"=",
"rule",
".",
"R",
"[",
"i",
"]",
"(",
"artifact",
")",
"... | 25.571429 | 14.714286 |
def X_more(self):
"""Zoom in on the x-axis."""
if self.parent.value('window_length') < 0.3:
return
self.parent.value('window_length',
self.parent.value('window_length') * 2)
self.parent.overview.update_position() | [
"def",
"X_more",
"(",
"self",
")",
":",
"if",
"self",
".",
"parent",
".",
"value",
"(",
"'window_length'",
")",
"<",
"0.3",
":",
"return",
"self",
".",
"parent",
".",
"value",
"(",
"'window_length'",
",",
"self",
".",
"parent",
".",
"value",
"(",
"'w... | 39.428571 | 12.857143 |
def parse_obj(o):
"""
Parses a given dictionary with the key being the OBD PID and the value its
returned value by the OBD interface
:param dict o:
:return:
"""
r = {}
for k, v in o.items():
if is_unable_to_connect(v):
r[k] = None
try:
r[k] = pars... | [
"def",
"parse_obj",
"(",
"o",
")",
":",
"r",
"=",
"{",
"}",
"for",
"k",
",",
"v",
"in",
"o",
".",
"items",
"(",
")",
":",
"if",
"is_unable_to_connect",
"(",
"v",
")",
":",
"r",
"[",
"k",
"]",
"=",
"None",
"try",
":",
"r",
"[",
"k",
"]",
"... | 24.941176 | 19.058824 |
async def create_stream_player(self, url, opts=ydl_opts):
"""Creates a streamer that plays from a URL"""
self.current_download_elapsed = 0
self.streamer = await self.vclient.create_ytdl_player(url, ytdl_options=opts, after=self.vafter_ts)
self.state = "ready"
await self.setup_s... | [
"async",
"def",
"create_stream_player",
"(",
"self",
",",
"url",
",",
"opts",
"=",
"ydl_opts",
")",
":",
"self",
".",
"current_download_elapsed",
"=",
"0",
"self",
".",
"streamer",
"=",
"await",
"self",
".",
"vclient",
".",
"create_ytdl_player",
"(",
"url",
... | 43.1 | 26.1 |
def get_window():
"""Get IDA's top level window."""
tform = idaapi.get_current_tform()
# Required sometimes when closing IDBs and not IDA.
if not tform:
tform = idaapi.find_tform("Output window")
widget = form_to_widget(tform)
window = widget.window()
return window | [
"def",
"get_window",
"(",
")",
":",
"tform",
"=",
"idaapi",
".",
"get_current_tform",
"(",
")",
"# Required sometimes when closing IDBs and not IDA.",
"if",
"not",
"tform",
":",
"tform",
"=",
"idaapi",
".",
"find_tform",
"(",
"\"Output window\"",
")",
"widget",
"=... | 26.636364 | 17.636364 |
def File(self, name, directory=None, create=1):
""" Create `SCons.Node.FS.File` """
return self._create_node(name, self.env.fs.File, directory, create) | [
"def",
"File",
"(",
"self",
",",
"name",
",",
"directory",
"=",
"None",
",",
"create",
"=",
"1",
")",
":",
"return",
"self",
".",
"_create_node",
"(",
"name",
",",
"self",
".",
"env",
".",
"fs",
".",
"File",
",",
"directory",
",",
"create",
")"
] | 55 | 14 |
def register_activity_type(domain=None, name=None, version=None, description=None, defaultTaskStartToCloseTimeout=None, defaultTaskHeartbeatTimeout=None, defaultTaskList=None, defaultTaskPriority=None, defaultTaskScheduleToStartTimeout=None, defaultTaskScheduleToCloseTimeout=None):
"""
Registers a new activity ... | [
"def",
"register_activity_type",
"(",
"domain",
"=",
"None",
",",
"name",
"=",
"None",
",",
"version",
"=",
"None",
",",
"description",
"=",
"None",
",",
"defaultTaskStartToCloseTimeout",
"=",
"None",
",",
"defaultTaskHeartbeatTimeout",
"=",
"None",
",",
"defaul... | 78.466102 | 68.90678 |
def p_array(self,t):
"""expression : '{' commalist '}'
| kw_array '[' commalist ']'
"""
if len(t)==4: t[0] = ArrayLit(t[2].children)
elif len(t)==5: t[0] = ArrayLit(t[3].children)
else: raise NotImplementedError('unk_len',len(t)) # pragma: no cover | [
"def",
"p_array",
"(",
"self",
",",
"t",
")",
":",
"if",
"len",
"(",
"t",
")",
"==",
"4",
":",
"t",
"[",
"0",
"]",
"=",
"ArrayLit",
"(",
"t",
"[",
"2",
"]",
".",
"children",
")",
"elif",
"len",
"(",
"t",
")",
"==",
"5",
":",
"t",
"[",
"... | 40 | 10.857143 |
def create_lifetime_chart(self, classname, filename=''):
"""
Create chart that depicts the lifetime of the instance registered with
`classname`. The output is written to `filename`.
"""
try:
from pylab import figure, title, xlabel, ylabel, plot, savefig
except... | [
"def",
"create_lifetime_chart",
"(",
"self",
",",
"classname",
",",
"filename",
"=",
"''",
")",
":",
"try",
":",
"from",
"pylab",
"import",
"figure",
",",
"title",
",",
"xlabel",
",",
"ylabel",
",",
"plot",
",",
"savefig",
"except",
"ImportError",
":",
"... | 31.625 | 16.5 |
def arduino_default_path():
"""platform specific default root path."""
if sys.platform == 'darwin':
s = path('/Applications/Arduino.app/Contents/Resources/Java')
elif sys.platform == 'win32':
s = None
else:
s = path('/usr/share/arduino/')
return s | [
"def",
"arduino_default_path",
"(",
")",
":",
"if",
"sys",
".",
"platform",
"==",
"'darwin'",
":",
"s",
"=",
"path",
"(",
"'/Applications/Arduino.app/Contents/Resources/Java'",
")",
"elif",
"sys",
".",
"platform",
"==",
"'win32'",
":",
"s",
"=",
"None",
"else"... | 31.444444 | 15.666667 |
def prefix_with_ns_if_necessary(name, name_ns, source_ns):
# type: (typing.Text, ApiNamespace, ApiNamespace) -> typing.Text
"""
Returns a name that can be used to reference `name` in namespace `name_ns`
from `source_ns`.
If `source_ns` and `name_ns` are the same, that's just `name`. Otherwise
i... | [
"def",
"prefix_with_ns_if_necessary",
"(",
"name",
",",
"name_ns",
",",
"source_ns",
")",
":",
"# type: (typing.Text, ApiNamespace, ApiNamespace) -> typing.Text",
"if",
"source_ns",
"==",
"name_ns",
":",
"return",
"name",
"return",
"'{}.{}'",
".",
"format",
"(",
"fmt_na... | 37.333333 | 20.5 |
def tomof(self, maxline=MAX_MOF_LINE):
"""
Return a MOF string with the declaration of this CIM class.
The returned MOF string conforms to the ``classDeclaration``
ABNF rule defined in :term:`DSP0004`.
The order of properties, methods, parameters, and qualifiers is
pres... | [
"def",
"tomof",
"(",
"self",
",",
"maxline",
"=",
"MAX_MOF_LINE",
")",
":",
"mof",
"=",
"[",
"]",
"mof",
".",
"append",
"(",
"_qualifiers_tomof",
"(",
"self",
".",
"qualifiers",
",",
"MOF_INDENT",
",",
"maxline",
")",
")",
"mof",
".",
"append",
"(",
... | 27 | 22.319149 |
def _get_indentword(source):
"""Return indentation type."""
indent_word = ' ' # Default in case source has no indentation
try:
for t in generate_tokens(source):
if t[0] == token.INDENT:
indent_word = t[1]
break
except (SyntaxError, tokenize.TokenEr... | [
"def",
"_get_indentword",
"(",
"source",
")",
":",
"indent_word",
"=",
"' '",
"# Default in case source has no indentation",
"try",
":",
"for",
"t",
"in",
"generate_tokens",
"(",
"source",
")",
":",
"if",
"t",
"[",
"0",
"]",
"==",
"token",
".",
"INDENT",
... | 31.909091 | 14.090909 |
def setup_tasks(self, tasks):
"""
Find task classes from category.namespace.name strings
tasks - list of strings
"""
task_classes = []
for task in tasks:
category, namespace, name = task.split(".")
try:
cls = find_in_registry(catego... | [
"def",
"setup_tasks",
"(",
"self",
",",
"tasks",
")",
":",
"task_classes",
"=",
"[",
"]",
"for",
"task",
"in",
"tasks",
":",
"category",
",",
"namespace",
",",
"name",
"=",
"task",
".",
"split",
"(",
"\".\"",
")",
"try",
":",
"cls",
"=",
"find_in_reg... | 39 | 16.733333 |
def save_favorite_query(arg, **_):
"""Save a new favorite query.
Returns (title, rows, headers, status)"""
usage = 'Syntax: \\fs name query.\n\n' + favoritequeries.usage
if not arg:
return [(None, None, None, usage)]
name, _, query = arg.partition(' ')
# If either name or query is mis... | [
"def",
"save_favorite_query",
"(",
"arg",
",",
"*",
"*",
"_",
")",
":",
"usage",
"=",
"'Syntax: \\\\fs name query.\\n\\n'",
"+",
"favoritequeries",
".",
"usage",
"if",
"not",
"arg",
":",
"return",
"[",
"(",
"None",
",",
"None",
",",
"None",
",",
"usage",
... | 32.705882 | 17.294118 |
def add_node(self, node):
"""Add a node, connecting it to all the active nodes."""
nodes = sorted(
self.nodes(),
key=attrgetter('creation_time'), reverse=True)
other_nodes = [n for n in nodes if n.id != node.id]
connecting_nodes = other_nodes[0:(self.n - 1)]
... | [
"def",
"add_node",
"(",
"self",
",",
"node",
")",
":",
"nodes",
"=",
"sorted",
"(",
"self",
".",
"nodes",
"(",
")",
",",
"key",
"=",
"attrgetter",
"(",
"'creation_time'",
")",
",",
"reverse",
"=",
"True",
")",
"other_nodes",
"=",
"[",
"n",
"for",
"... | 31.166667 | 19.333333 |
def convert_op(self, op):
"""
Converts NeuroML arithmetic/logical operators to python equivalents.
@param op: NeuroML operator
@type op: string
@return: Python operator
@rtype: string
"""
if op == '.gt.':
return '>'
elif op == '.ge.... | [
"def",
"convert_op",
"(",
"self",
",",
"op",
")",
":",
"if",
"op",
"==",
"'.gt.'",
":",
"return",
"'>'",
"elif",
"op",
"==",
"'.ge.'",
"or",
"op",
"==",
"'.geq.'",
":",
"return",
"'>='",
"elif",
"op",
"==",
"'.lt.'",
":",
"return",
"'<'",
"elif",
"... | 23.529412 | 17.647059 |
def indices_to_bool_mask(indices, size):
""" Convert indices to a boolean (integer) mask.
>>> list(indices_to_bool_mask(np.array([2, 3]), 4))
[False, False, True, True]
>>> list(indices_to_bool_mask([2, 3], 4))
[False, False, True, True]
>>> indices_to_bool_mask(np.array([5]), 2)
Tracebac... | [
"def",
"indices_to_bool_mask",
"(",
"indices",
",",
"size",
")",
":",
"mask",
"=",
"np",
".",
"zeros",
"(",
"size",
",",
"dtype",
"=",
"bool",
")",
"mask",
"[",
"indices",
"]",
"=",
"1",
"return",
"mask"
] | 27.470588 | 14.823529 |
def _guess_extract_method(fname):
"""Guess extraction method, given file name (or path)."""
for method, extensions in _EXTRACTION_METHOD_TO_EXTS:
for ext in extensions:
if fname.endswith(ext):
return method
return ExtractMethod.NO_EXTRACT | [
"def",
"_guess_extract_method",
"(",
"fname",
")",
":",
"for",
"method",
",",
"extensions",
"in",
"_EXTRACTION_METHOD_TO_EXTS",
":",
"for",
"ext",
"in",
"extensions",
":",
"if",
"fname",
".",
"endswith",
"(",
"ext",
")",
":",
"return",
"method",
"return",
"E... | 36.571429 | 10.428571 |
def build_query_fragment(query):
"""
<query xmlns="http://basex.org/rest">
<text><![CDATA[ (//city/name)[position() <= 5] ]]></text>
</query>
"""
root = etree.Element('query', nsmap={None: 'http://basex.org/rest'})
text = etree.SubElement(root, 'text')
text.text = etree.CDATA(query.s... | [
"def",
"build_query_fragment",
"(",
"query",
")",
":",
"root",
"=",
"etree",
".",
"Element",
"(",
"'query'",
",",
"nsmap",
"=",
"{",
"None",
":",
"'http://basex.org/rest'",
"}",
")",
"text",
"=",
"etree",
".",
"SubElement",
"(",
"root",
",",
"'text'",
")... | 33.4 | 12.2 |
def auth_required_same_user(*args, **kwargs):
"""
Decorator for requiring an authenticated user to be the same as the
user in the URL parameters. By default the user url parameter name to
lookup is ``id``, but this can be customized by passing an argument::
@auth_require_same_user('user_id')
... | [
"def",
"auth_required_same_user",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"auth_kwargs",
"=",
"{",
"}",
"user_id_parameter_name",
"=",
"'id'",
"if",
"not",
"(",
"args",
"and",
"callable",
"(",
"args",
"[",
"0",
"]",
")",
")",
":",
"auth_kw... | 36.02381 | 18.785714 |
def create(self, validated_data):
"""
Perform the enrollment for existing enterprise customer users, or create the pending objects for new users.
"""
enterprise_customer = self.context.get('enterprise_customer')
lms_user = validated_data.get('lms_user_id')
tpa_user = vali... | [
"def",
"create",
"(",
"self",
",",
"validated_data",
")",
":",
"enterprise_customer",
"=",
"self",
".",
"context",
".",
"get",
"(",
"'enterprise_customer'",
")",
"lms_user",
"=",
"validated_data",
".",
"get",
"(",
"'lms_user_id'",
")",
"tpa_user",
"=",
"valida... | 42.84 | 23.96 |
def remove_handler(self, handler):
""" Removes a previously added event handler. """
while handler in self.handlers:
self.handlers.remove(handler) | [
"def",
"remove_handler",
"(",
"self",
",",
"handler",
")",
":",
"while",
"handler",
"in",
"self",
".",
"handlers",
":",
"self",
".",
"handlers",
".",
"remove",
"(",
"handler",
")"
] | 42.75 | 2 |
def manual_dir(self):
"""Returns the directory containing the manually extracted data."""
if not tf.io.gfile.exists(self._manual_dir):
raise AssertionError(
'Manual directory {} does not exist. Create it and download/extract '
'dataset artifacts in there.'.format(self._manual_dir))
... | [
"def",
"manual_dir",
"(",
"self",
")",
":",
"if",
"not",
"tf",
".",
"io",
".",
"gfile",
".",
"exists",
"(",
"self",
".",
"_manual_dir",
")",
":",
"raise",
"AssertionError",
"(",
"'Manual directory {} does not exist. Create it and download/extract '",
"'dataset artif... | 48.285714 | 16.714286 |
def get_segment_length(
linestring: LineString, p: Point, q: Optional[Point] = None
) -> float:
"""
Given a Shapely linestring and two Shapely points,
project the points onto the linestring, and return the distance
along the linestring between the two points.
If ``q is None``, then return the di... | [
"def",
"get_segment_length",
"(",
"linestring",
":",
"LineString",
",",
"p",
":",
"Point",
",",
"q",
":",
"Optional",
"[",
"Point",
"]",
"=",
"None",
")",
"->",
"float",
":",
"# Get projected distances",
"d_p",
"=",
"linestring",
".",
"project",
"(",
"p",
... | 33.736842 | 17 |
def marcxml2mods(marc_xml, uuid, url):
"""
Convert `marc_xml` to MODS. Decide type of the record and what template to
use (monograph, multi-monograph, periodical).
Args:
marc_xml (str): Filename or XML string. Don't use ``\\n`` in case of
filename.
uuid (str): UU... | [
"def",
"marcxml2mods",
"(",
"marc_xml",
",",
"uuid",
",",
"url",
")",
":",
"marc_xml",
"=",
"_read_content_or_path",
"(",
"marc_xml",
")",
"return",
"type_decisioner",
"(",
"marc_xml",
",",
"lambda",
":",
"transform_to_mods_mono",
"(",
"marc_xml",
",",
"uuid",
... | 34.5 | 21.045455 |
def save(self, *args, **kwargs):
"""
Custom save does the following:
* strip trailing whitespace from host attribute
* create device and all other related objects
* store connection config in DB if store attribute is True
"""
self.host = self.host.stri... | [
"def",
"save",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
".",
"host",
"=",
"self",
".",
"host",
".",
"strip",
"(",
")",
"if",
"not",
"self",
".",
"id",
":",
"self",
".",
"device",
"=",
"self",
".",
"__create_devi... | 34.214286 | 15.357143 |
def ajAssims(self):
""" Charge et définit les débuts de mots non-assimilés, associe à chacun sa forme assimilée.
"""
for lin in lignesFichier(self.path("assimilations.la")):
ass1, ass2 = tuple(lin.split(':'))
self.lemmatiseur._assims[ass1] = ass2
self.lemmatis... | [
"def",
"ajAssims",
"(",
"self",
")",
":",
"for",
"lin",
"in",
"lignesFichier",
"(",
"self",
".",
"path",
"(",
"\"assimilations.la\"",
")",
")",
":",
"ass1",
",",
"ass2",
"=",
"tuple",
"(",
"lin",
".",
"split",
"(",
"':'",
")",
")",
"self",
".",
"le... | 50.428571 | 12 |
def train(self, *args, **kwargs):
"""
Perform training on a DataFrame.
The label field is specified by the ``label_field`` method.
:param train_data: DataFrame to be trained. Label field must be specified.
:type train_data: DataFrame
:return: Trained model
:rtyp... | [
"def",
"train",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"objs",
"=",
"self",
".",
"_do_transform",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"obj_list",
"=",
"[",
"objs",
",",
"]",
"if",
"not",
"isinstance",
"(",
... | 40.851852 | 19.296296 |
def flush(self):
"""Flush the write buffer of the serial port, blocking until all bytes
are written.
Raises:
SerialError: if an I/O or OS error occurs.
"""
try:
termios.tcdrain(self._fd)
except termios.error as e:
raise SerialError(e.... | [
"def",
"flush",
"(",
"self",
")",
":",
"try",
":",
"termios",
".",
"tcdrain",
"(",
"self",
".",
"_fd",
")",
"except",
"termios",
".",
"error",
"as",
"e",
":",
"raise",
"SerialError",
"(",
"e",
".",
"errno",
",",
"\"Flushing serial port: \"",
"+",
"e",
... | 29.5 | 19.75 |
def add_scalebar(ax, matchx=True, matchy=True, hidex=True, hidey=True, unitsx='', unitsy='', scalex=1, scaley=1, **kwargs):
""" Add scalebars to axes
Adds a set of scale bars to *ax*, matching the size to the ticks of the plot
and optionally hiding the x and y axes
- ax : the axis to attach ticks to
... | [
"def",
"add_scalebar",
"(",
"ax",
",",
"matchx",
"=",
"True",
",",
"matchy",
"=",
"True",
",",
"hidex",
"=",
"True",
",",
"hidey",
"=",
"True",
",",
"unitsx",
"=",
"''",
",",
"unitsy",
"=",
"''",
",",
"scalex",
"=",
"1",
",",
"scaley",
"=",
"1",
... | 41.645161 | 20.935484 |
def degree(self, kind='out', weighted=True):
'''Returns an array of vertex degrees.
kind : either 'in' or 'out', useful for directed graphs
weighted : controls whether to count edges or sum their weights
'''
if kind == 'out':
axis = 1
adj = self.matrix('dense', 'csc')
else:
axi... | [
"def",
"degree",
"(",
"self",
",",
"kind",
"=",
"'out'",
",",
"weighted",
"=",
"True",
")",
":",
"if",
"kind",
"==",
"'out'",
":",
"axis",
"=",
"1",
"adj",
"=",
"self",
".",
"matrix",
"(",
"'dense'",
",",
"'csc'",
")",
"else",
":",
"axis",
"=",
... | 31.526316 | 16.263158 |
def _serialize_attributes(attributes):
"""Serializes HTML element attributes in a name="value" pair form."""
result = ''
for name, value in attributes.items():
if not value:
continue
result += ' ' + _unmangle_attribute_name(name)
result += '="' + escape(value, True) + '"'... | [
"def",
"_serialize_attributes",
"(",
"attributes",
")",
":",
"result",
"=",
"''",
"for",
"name",
",",
"value",
"in",
"attributes",
".",
"items",
"(",
")",
":",
"if",
"not",
"value",
":",
"continue",
"result",
"+=",
"' '",
"+",
"_unmangle_attribute_name",
"... | 36.666667 | 12.777778 |
def to_si(self, values, from_unit):
"""Return values in SI and the units to which the values have been converted."""
if from_unit == 'W/m2-K':
return values, from_unit
else:
return self.to_unit(values, 'W/m2-K', from_unit), 'W/m2-K' | [
"def",
"to_si",
"(",
"self",
",",
"values",
",",
"from_unit",
")",
":",
"if",
"from_unit",
"==",
"'W/m2-K'",
":",
"return",
"values",
",",
"from_unit",
"else",
":",
"return",
"self",
".",
"to_unit",
"(",
"values",
",",
"'W/m2-K'",
",",
"from_unit",
")",
... | 45.833333 | 12.166667 |
def _assert(self, expression: Bool):
"""Auxiliary method to send an assert"""
assert isinstance(expression, Bool)
smtlib = translate_to_smtlib(expression)
self._send('(assert %s)' % smtlib) | [
"def",
"_assert",
"(",
"self",
",",
"expression",
":",
"Bool",
")",
":",
"assert",
"isinstance",
"(",
"expression",
",",
"Bool",
")",
"smtlib",
"=",
"translate_to_smtlib",
"(",
"expression",
")",
"self",
".",
"_send",
"(",
"'(assert %s)'",
"%",
"smtlib",
"... | 43.4 | 3.4 |
def transformer_tall_pretrain_lm_tpu():
"""Hparams for transformer on LM pretraining on TPU with AdamW."""
hparams = transformer_tall_pretrain_lm_tpu_adafactor()
# Optimizer gets reset in update_hparams_for_tpu so we set it again here.
hparams.learning_rate_constant = 2e-4
hparams.learning_rate_schedule = ("l... | [
"def",
"transformer_tall_pretrain_lm_tpu",
"(",
")",
":",
"hparams",
"=",
"transformer_tall_pretrain_lm_tpu_adafactor",
"(",
")",
"# Optimizer gets reset in update_hparams_for_tpu so we set it again here.",
"hparams",
".",
"learning_rate_constant",
"=",
"2e-4",
"hparams",
".",
"l... | 49.625 | 15.125 |
def system(session, py):
"""Run the system test suite."""
# Sanity check: Only run system tests if the environment variable is set.
if not os.environ.get('GOOGLE_APPLICATION_CREDENTIALS', ''):
session.skip('Credentials must be set via environment variable.')
# Run the system tests against late... | [
"def",
"system",
"(",
"session",
",",
"py",
")",
":",
"# Sanity check: Only run system tests if the environment variable is set.",
"if",
"not",
"os",
".",
"environ",
".",
"get",
"(",
"'GOOGLE_APPLICATION_CREDENTIALS'",
",",
"''",
")",
":",
"session",
".",
"skip",
"(... | 30.5 | 22.423077 |
def compare_seqs_leven(seqs):
"""
calculate Levenshtein ratio of sequences
"""
A, B, ignore_gaps = seqs
a, b = remove_gaps(A[1], B[1]) # actual sequences
if len(a) != len(b):
print('# reads are not the same length', file=sys.stderr)
exit()
pident = lr(a, b) * 100
return A... | [
"def",
"compare_seqs_leven",
"(",
"seqs",
")",
":",
"A",
",",
"B",
",",
"ignore_gaps",
"=",
"seqs",
"a",
",",
"b",
"=",
"remove_gaps",
"(",
"A",
"[",
"1",
"]",
",",
"B",
"[",
"1",
"]",
")",
"# actual sequences",
"if",
"len",
"(",
"a",
")",
"!=",
... | 29.727273 | 11.909091 |
def get_duplicates_for(self, analysis):
"""Returns the duplicates from the current worksheet that were created
by using the analysis passed in as the source
:param analysis: routine analyses used as the source for the duplicates
:return: a list of duplicates generated from the analysis ... | [
"def",
"get_duplicates_for",
"(",
"self",
",",
"analysis",
")",
":",
"if",
"not",
"analysis",
":",
"return",
"list",
"(",
")",
"uid",
"=",
"api",
".",
"get_uid",
"(",
"analysis",
")",
"return",
"filter",
"(",
"lambda",
"dup",
":",
"api",
".",
"get_uid"... | 45.083333 | 17.166667 |
def pipes(stream, *transformers):
"""Pipe several transformers end to end."""
for transformer in transformers:
stream = stream.pipe(transformer)
return stream | [
"def",
"pipes",
"(",
"stream",
",",
"*",
"transformers",
")",
":",
"for",
"transformer",
"in",
"transformers",
":",
"stream",
"=",
"stream",
".",
"pipe",
"(",
"transformer",
")",
"return",
"stream"
] | 34.8 | 7 |
def fasta_motif_scan( fasta_fname, input_tuples, regex_ready=False, allow_overlaps=True, file_buffer=False, molecule='dna' ):
"""
fasta_fname = string path to FASTA file
input_tuples = tuple containing (1) motif sequence, (2) contig name, (3) start position*, (4) end position, (5) strand to search
*start is expec... | [
"def",
"fasta_motif_scan",
"(",
"fasta_fname",
",",
"input_tuples",
",",
"regex_ready",
"=",
"False",
",",
"allow_overlaps",
"=",
"True",
",",
"file_buffer",
"=",
"False",
",",
"molecule",
"=",
"'dna'",
")",
":",
"###################",
"# validity checks #",
"####... | 34.547945 | 25.013699 |
def from_caller_file():
'''return a `Path` from the path of caller file'''
import inspect
curframe = inspect.currentframe()
calframe = inspect.getouterframes(curframe, 2)
filename = calframe[1].filename
if not os.path.isfile(filename):
raise RuntimeError('call... | [
"def",
"from_caller_file",
"(",
")",
":",
"import",
"inspect",
"curframe",
"=",
"inspect",
".",
"currentframe",
"(",
")",
"calframe",
"=",
"inspect",
".",
"getouterframes",
"(",
"curframe",
",",
"2",
")",
"filename",
"=",
"calframe",
"[",
"1",
"]",
".",
... | 40 | 10.444444 |
def set_device_brightness(self, brightness):
"""Hardware specific method to set the global brightness for
this driver's output. This method is required to be implemented,
however, users should call
:py:meth:`.driver_base.DriverBase.set_brightness`
instead of calling this method d... | [
"def",
"set_device_brightness",
"(",
"self",
",",
"brightness",
")",
":",
"packet",
"=",
"util",
".",
"generate_header",
"(",
"CMDTYPE",
".",
"BRIGHTNESS",
",",
"1",
")",
"packet",
".",
"append",
"(",
"self",
".",
"_brightness",
")",
"s",
"=",
"self",
".... | 40.75 | 13.0625 |
def find(self, tag_name, params=None, fn=None, case_sensitive=False):
"""
Same as :meth:`findAll`, but without `endtags`.
You can always get them from :attr:`endtag` property.
"""
return [
x for x in self.findAll(tag_name, params, fn, case_sensitive)
if n... | [
"def",
"find",
"(",
"self",
",",
"tag_name",
",",
"params",
"=",
"None",
",",
"fn",
"=",
"None",
",",
"case_sensitive",
"=",
"False",
")",
":",
"return",
"[",
"x",
"for",
"x",
"in",
"self",
".",
"findAll",
"(",
"tag_name",
",",
"params",
",",
"fn",... | 33.6 | 20.2 |
def open(self, baudrate=None, no_reader_thread=False):
"""
Opens the device.
:param baudrate: baudrate to use
:type baudrate: int
:param no_reader_thread: whether or not to automatically open the reader
thread.
:type no_reader_thread: boo... | [
"def",
"open",
"(",
"self",
",",
"baudrate",
"=",
"None",
",",
"no_reader_thread",
"=",
"False",
")",
":",
"try",
":",
"self",
".",
"_read_thread",
"=",
"Device",
".",
"ReadThread",
"(",
"self",
")",
"self",
".",
"_device",
"=",
"socket",
".",
"socket"... | 29.295455 | 22.477273 |
def resample(self, destination=None, datasets=None, generate=True,
unload=True, resampler=None, reduce_data=True,
**resample_kwargs):
"""Resample datasets and return a new scene.
Args:
destination (AreaDefinition, GridDefinition): area definition to
... | [
"def",
"resample",
"(",
"self",
",",
"destination",
"=",
"None",
",",
"datasets",
"=",
"None",
",",
"generate",
"=",
"True",
",",
"unload",
"=",
"True",
",",
"resampler",
"=",
"None",
",",
"reduce_data",
"=",
"True",
",",
"*",
"*",
"resample_kwargs",
"... | 49.112903 | 23.451613 |
def update_vm_image(self, vm_image_name, vm_image):
'''
Updates a VM Image in the image repository that is associated with the
specified subscription.
vm_image_name:
Name of image to update.
vm_image:
An instance of VMImage class.
vm_image.label: ... | [
"def",
"update_vm_image",
"(",
"self",
",",
"vm_image_name",
",",
"vm_image",
")",
":",
"_validate_not_none",
"(",
"'vm_image_name'",
",",
"vm_image_name",
")",
"_validate_not_none",
"(",
"'vm_image'",
",",
"vm_image",
")",
"return",
"self",
".",
"_perform_put",
"... | 52 | 21.233333 |
def get_relation_fields_from_model(model_class):
""" Get related fields (m2m, FK, and reverse FK) """
relation_fields = []
all_fields_names = _get_all_field_names(model_class)
for field_name in all_fields_names:
field, model, direct, m2m = _get_field_by_name(model_class, field_name)
# ge... | [
"def",
"get_relation_fields_from_model",
"(",
"model_class",
")",
":",
"relation_fields",
"=",
"[",
"]",
"all_fields_names",
"=",
"_get_all_field_names",
"(",
"model_class",
")",
"for",
"field_name",
"in",
"all_fields_names",
":",
"field",
",",
"model",
",",
"direct... | 48.785714 | 15.214286 |
def stack(self, key, labels=None):
"""Takes k original columns and returns two columns, with col. 1 of
all column names and col. 2 of all associated data.
"""
rows, labels = [], labels or self.labels
for row in self.rows:
[rows.append((getattr(row, key), k, v)) for k,... | [
"def",
"stack",
"(",
"self",
",",
"key",
",",
"labels",
"=",
"None",
")",
":",
"rows",
",",
"labels",
"=",
"[",
"]",
",",
"labels",
"or",
"self",
".",
"labels",
"for",
"row",
"in",
"self",
".",
"rows",
":",
"[",
"rows",
".",
"append",
"(",
"(",... | 49.777778 | 12.888889 |
def to_XML(self, xml_declaration=True, xmlns=True):
"""
Dumps object fields to an XML-formatted string. The 'xml_declaration'
switch enables printing of a leading standard XML line containing XML
version and encoding. The 'xmlns' switch enables printing of qualified
XMLNS prefix... | [
"def",
"to_XML",
"(",
"self",
",",
"xml_declaration",
"=",
"True",
",",
"xmlns",
"=",
"True",
")",
":",
"root_node",
"=",
"self",
".",
"_to_DOM",
"(",
")",
"if",
"xmlns",
":",
"xmlutils",
".",
"annotate_with_XMLNS",
"(",
"root_node",
",",
"SO2INDEX_XMLNS_P... | 42.571429 | 20.380952 |
def as_backfill_cron_app(cls):
"""a class decorator for Crontabber Apps. This decorator embues a CronApp
with the parts necessary to be a backfill CronApp. It adds a main method
that forces the base class to use a value of False for 'once'. That means
it will do the work of a backfilling app.
"""... | [
"def",
"as_backfill_cron_app",
"(",
"cls",
")",
":",
"#----------------------------------------------------------------------",
"def",
"main",
"(",
"self",
",",
"function",
"=",
"None",
")",
":",
"return",
"super",
"(",
"cls",
",",
"self",
")",
".",
"main",
"(",
... | 39.133333 | 16.533333 |
def update_mapping(mapping: Dict[ops.Qid, LogicalIndex],
operations: ops.OP_TREE
) -> None:
"""Updates a mapping (in place) from qubits to logical indices according to
a set of permutation gates. Any gates other than permutation gates are
ignored.
Args:
map... | [
"def",
"update_mapping",
"(",
"mapping",
":",
"Dict",
"[",
"ops",
".",
"Qid",
",",
"LogicalIndex",
"]",
",",
"operations",
":",
"ops",
".",
"OP_TREE",
")",
"->",
"None",
":",
"for",
"op",
"in",
"ops",
".",
"flatten_op_tree",
"(",
"operations",
")",
":"... | 40.266667 | 14.666667 |
def add(self, defn):
"""Adds the given Command Definition to this Command Dictionary."""
self[defn.name] = defn
self.opcodes[defn._opcode] = defn | [
"def",
"add",
"(",
"self",
",",
"defn",
")",
":",
"self",
"[",
"defn",
".",
"name",
"]",
"=",
"defn",
"self",
".",
"opcodes",
"[",
"defn",
".",
"_opcode",
"]",
"=",
"defn"
] | 44.25 | 5.5 |
def horizontal_positions(docgraph, sentence_root=None):
"""return map: node ID -> first token index (int) it covers"""
# calculate positions for the whole graph
root_cond = (sentence_root is None) or (sentence_root == docgraph.root)
if root_cond or ('tokens' not in docgraph.node[sentence_root]):
... | [
"def",
"horizontal_positions",
"(",
"docgraph",
",",
"sentence_root",
"=",
"None",
")",
":",
"# calculate positions for the whole graph",
"root_cond",
"=",
"(",
"sentence_root",
"is",
"None",
")",
"or",
"(",
"sentence_root",
"==",
"docgraph",
".",
"root",
")",
"if... | 45.473684 | 16.315789 |
def _require_bucket(self, bucket_name):
""" Also try to create the bucket. """
if not self.exists(bucket_name) and not self.claim_bucket(bucket_name):
raise OFSException("Invalid bucket: %s" % bucket_name)
return self._get_bucket(bucket_name) | [
"def",
"_require_bucket",
"(",
"self",
",",
"bucket_name",
")",
":",
"if",
"not",
"self",
".",
"exists",
"(",
"bucket_name",
")",
"and",
"not",
"self",
".",
"claim_bucket",
"(",
"bucket_name",
")",
":",
"raise",
"OFSException",
"(",
"\"Invalid bucket: %s\"",
... | 54.8 | 14 |
def kill_all(self):
"""kill all slaves and reap the monitor """
for pid in self.children:
try:
os.kill(pid, signal.SIGTRAP)
except OSError:
continue
self.join() | [
"def",
"kill_all",
"(",
"self",
")",
":",
"for",
"pid",
"in",
"self",
".",
"children",
":",
"try",
":",
"os",
".",
"kill",
"(",
"pid",
",",
"signal",
".",
"SIGTRAP",
")",
"except",
"OSError",
":",
"continue",
"self",
".",
"join",
"(",
")"
] | 29.125 | 13.25 |
def _get_cpu_info_internal():
'''
Returns the CPU info by using the best sources of information for your OS.
Returns {} if nothing is found.
'''
# Get the CPU arch and bits
arch, bits = _parse_arch(DataSource.arch_string_raw)
friendly_maxsize = { 2**31-1: '32 bit', 2**63-1: '64 bit' }.get(sys.maxsize) or 'unkn... | [
"def",
"_get_cpu_info_internal",
"(",
")",
":",
"# Get the CPU arch and bits",
"arch",
",",
"bits",
"=",
"_parse_arch",
"(",
"DataSource",
".",
"arch_string_raw",
")",
"friendly_maxsize",
"=",
"{",
"2",
"**",
"31",
"-",
"1",
":",
"'32 bit'",
",",
"2",
"**",
... | 27.079365 | 25.015873 |
def generate_reports(subject_list, output_dir, work_dir, run_uuid, config=None,
packagename=None):
"""
A wrapper to run_reports on a given ``subject_list``
"""
reports_dir = str(Path(work_dir) / 'reportlets')
report_errors = [
run_reports(reports_dir, output_dir, subject... | [
"def",
"generate_reports",
"(",
"subject_list",
",",
"output_dir",
",",
"work_dir",
",",
"run_uuid",
",",
"config",
"=",
"None",
",",
"packagename",
"=",
"None",
")",
":",
"reports_dir",
"=",
"str",
"(",
"Path",
"(",
"work_dir",
")",
"/",
"'reportlets'",
"... | 40.681818 | 21.227273 |
def predict_proba(self, x, **kwargs):
'''Compute class posterior probabilities for the given set of data.
Parameters
----------
x : ndarray (num-examples, num-variables)
An array containing examples to predict. Examples are given as the
rows in this array.
... | [
"def",
"predict_proba",
"(",
"self",
",",
"x",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"self",
".",
"feed_forward",
"(",
"x",
",",
"*",
"*",
"kwargs",
")",
"[",
"self",
".",
"layers",
"[",
"-",
"1",
"]",
".",
"output_name",
"]"
] | 35.3125 | 25.0625 |
def _embedded_frames(frame_list, frame_format):
"""frame_list should be a list of base64-encoded png files"""
template = ' frames[{0}] = "data:image/{1};base64,{2}"\n'
embedded = "\n"
for i, frame_data in enumerate(frame_list):
embedded += template.format(i, frame_format,
... | [
"def",
"_embedded_frames",
"(",
"frame_list",
",",
"frame_format",
")",
":",
"template",
"=",
"' frames[{0}] = \"data:image/{1};base64,{2}\"\\n'",
"embedded",
"=",
"\"\\n\"",
"for",
"i",
",",
"frame_data",
"in",
"enumerate",
"(",
"frame_list",
")",
":",
"embedded",
... | 47.5 | 14.875 |
def register(self, itemtype, item_id, handler):
'''
register the item in zookeeper /list/
itemtype must be a Zooborg constant
item_id must be a string
handler: method to call on conf change
'''
# Create a node with data
#TODO: add system properties in data... | [
"def",
"register",
"(",
"self",
",",
"itemtype",
",",
"item_id",
",",
"handler",
")",
":",
"# Create a node with data",
"#TODO: add system properties in data (ip, os)",
"#TODO: add uniq client id",
"if",
"itemtype",
"not",
"in",
"[",
"ZooConst",
".",
"CLIENT",
",",
"Z... | 41.96 | 14.68 |
def store_param(self, value, param, clobber=False):
""" .. todo:: store_param docstring
"""
# Imports
from ..const import EnumAnharmRepoParam
from ..error import RepoError as RErr
# Must be a valid parameter name
if not param in EnumAnharmRepoParam:
... | [
"def",
"store_param",
"(",
"self",
",",
"value",
",",
"param",
",",
"clobber",
"=",
"False",
")",
":",
"# Imports",
"from",
".",
".",
"const",
"import",
"EnumAnharmRepoParam",
"from",
".",
".",
"error",
"import",
"RepoError",
"as",
"RErr",
"# Must be a valid... | 33.285714 | 17.612245 |
def domain_search(auth=None, **kwargs):
'''
Search domains
CLI Example:
.. code-block:: bash
salt '*' keystoneng.domain_search
salt '*' keystoneng.domain_search name=domain1
'''
cloud = get_operator_cloud(auth)
kwargs = _clean_kwargs(**kwargs)
return cloud.search_domai... | [
"def",
"domain_search",
"(",
"auth",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"cloud",
"=",
"get_operator_cloud",
"(",
"auth",
")",
"kwargs",
"=",
"_clean_kwargs",
"(",
"*",
"*",
"kwargs",
")",
"return",
"cloud",
".",
"search_domains",
"(",
"*",
... | 22.785714 | 19.5 |
def _init_map(self, record_types=None, **kwargs):
"""Initialize form map"""
osid_objects.OsidRelationshipForm._init_map(self, record_types=record_types)
self._my_map['assignedVaultIds'] = [str(kwargs['vault_id'])]
self._my_map['functionId'] = str(kwargs['function_id'])
self._my_m... | [
"def",
"_init_map",
"(",
"self",
",",
"record_types",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"osid_objects",
".",
"OsidRelationshipForm",
".",
"_init_map",
"(",
"self",
",",
"record_types",
"=",
"record_types",
")",
"self",
".",
"_my_map",
"[",
"'... | 50.928571 | 14 |
def map_arguments_to_objects(kwargs, objects, object_key, object_tuple_key, argument_key, result_value, default_result):
"""
:param kwargs: kwargs used to call the multiget function
:param objects: objects returned from the inner function
:param object_key: field or set of fields that map to the kwargs ... | [
"def",
"map_arguments_to_objects",
"(",
"kwargs",
",",
"objects",
",",
"object_key",
",",
"object_tuple_key",
",",
"argument_key",
",",
"result_value",
",",
"default_result",
")",
":",
"# Map each object to the set of desired result data using a key",
"# that corresponds to the... | 65.75 | 35.85 |
def enable_auth_method(self, method_type, description=None, config=None, plugin_name=None, local=False, path=None):
"""Enable a new auth method.
After enabling, the auth method can be accessed and configured via the auth path specified as part of the URL.
This auth path will be nested under the... | [
"def",
"enable_auth_method",
"(",
"self",
",",
"method_type",
",",
"description",
"=",
"None",
",",
"config",
"=",
"None",
",",
"plugin_name",
"=",
"None",
",",
"local",
"=",
"False",
",",
"path",
"=",
"None",
")",
":",
"if",
"path",
"is",
"None",
":",... | 50.865385 | 30.153846 |
def set_end_point_uri(self) -> bool:
"""
Extracts the route from the accessed URL and sets it to __end_point_uri
:rtype: bool
"""
expected_parts = self.__route.split("/")
actual_parts = self.__uri.split("/")
i = 0
for part in expected_parts:
i... | [
"def",
"set_end_point_uri",
"(",
"self",
")",
"->",
"bool",
":",
"expected_parts",
"=",
"self",
".",
"__route",
".",
"split",
"(",
"\"/\"",
")",
"actual_parts",
"=",
"self",
".",
"__uri",
".",
"split",
"(",
"\"/\"",
")",
"i",
"=",
"0",
"for",
"part",
... | 29.176471 | 15.058824 |
def rsr(self):
"""A getter for the relative spectral response (rsr) curve"""
arr = np.array([self.wave.value, self.throughput]).swapaxes(0, 1)
return arr | [
"def",
"rsr",
"(",
"self",
")",
":",
"arr",
"=",
"np",
".",
"array",
"(",
"[",
"self",
".",
"wave",
".",
"value",
",",
"self",
".",
"throughput",
"]",
")",
".",
"swapaxes",
"(",
"0",
",",
"1",
")",
"return",
"arr"
] | 34.8 | 24.2 |
def maybe_convert_platform(values):
""" try to do platform conversion, allow ndarray or list here """
if isinstance(values, (list, tuple)):
values = construct_1d_object_array_from_listlike(list(values))
if getattr(values, 'dtype', None) == np.object_:
if hasattr(values, '_values'):
... | [
"def",
"maybe_convert_platform",
"(",
"values",
")",
":",
"if",
"isinstance",
"(",
"values",
",",
"(",
"list",
",",
"tuple",
")",
")",
":",
"values",
"=",
"construct_1d_object_array_from_listlike",
"(",
"list",
"(",
"values",
")",
")",
"if",
"getattr",
"(",
... | 37 | 15.272727 |
def starttls(self, ssl_context, post_handshake_callback=None):
"""
Start TLS on the transport and wait for it to complete.
The `ssl_context` and `post_handshake_callback` arguments are forwarded
to the transports
:meth:`aioopenssl.STARTTLSTransport.starttls` coroutine method.
... | [
"def",
"starttls",
"(",
"self",
",",
"ssl_context",
",",
"post_handshake_callback",
"=",
"None",
")",
":",
"self",
".",
"_require_connection",
"(",
")",
"if",
"not",
"self",
".",
"can_starttls",
"(",
")",
":",
"raise",
"RuntimeError",
"(",
"\"starttls not avai... | 43.666667 | 24.25 |
def _cleave_interface(self, bulk_silica, tile_x, tile_y, thickness):
"""Carve interface from bulk silica.
Also includes a buffer of O's above and below the surface to ensure the
interface is coated.
"""
O_buffer = self._O_buffer
tile_z = int(math.ceil((thickness + 2*O_bu... | [
"def",
"_cleave_interface",
"(",
"self",
",",
"bulk_silica",
",",
"tile_x",
",",
"tile_y",
",",
"thickness",
")",
":",
"O_buffer",
"=",
"self",
".",
"_O_buffer",
"tile_z",
"=",
"int",
"(",
"math",
".",
"ceil",
"(",
"(",
"thickness",
"+",
"2",
"*",
"O_b... | 55.473684 | 28.578947 |
def mode(self, target, *data):
"""set user or channel mode"""
self.send_line('MODE %s %s' % (target, ' '.join(data)), nowait=True) | [
"def",
"mode",
"(",
"self",
",",
"target",
",",
"*",
"data",
")",
":",
"self",
".",
"send_line",
"(",
"'MODE %s %s'",
"%",
"(",
"target",
",",
"' '",
".",
"join",
"(",
"data",
")",
")",
",",
"nowait",
"=",
"True",
")"
] | 48 | 15.333333 |
def update(cwd, rev, force=False, user=None):
'''
Update to a given revision
cwd
The path to the Mercurial repository
rev
The revision to update to
force : False
Force an update
user : None
Run hg as a user other than what the minion runs as
CLI Example:
... | [
"def",
"update",
"(",
"cwd",
",",
"rev",
",",
"force",
"=",
"False",
",",
"user",
"=",
"None",
")",
":",
"cmd",
"=",
"[",
"'hg'",
",",
"'update'",
",",
"'{0}'",
".",
"format",
"(",
"rev",
")",
"]",
"if",
"force",
":",
"cmd",
".",
"append",
"(",... | 22 | 25.69697 |
def tree(string, token=[WORD, POS, CHUNK, PNP, REL, ANCHOR, LEMMA]):
""" Transforms the output of parse() into a Text object.
The token parameter lists the order of tags in each token in the input string.
"""
return Text(string, token) | [
"def",
"tree",
"(",
"string",
",",
"token",
"=",
"[",
"WORD",
",",
"POS",
",",
"CHUNK",
",",
"PNP",
",",
"REL",
",",
"ANCHOR",
",",
"LEMMA",
"]",
")",
":",
"return",
"Text",
"(",
"string",
",",
"token",
")"
] | 50.2 | 16.8 |
def add_cli_cache(main: click.Group) -> click.Group: # noqa: D202
"""Add several commands to main :mod:`click` function for handling the cache."""
@main.group()
def cache():
"""Manage cached data."""
@cache.command()
@click.pass_obj
def locate(manager):
"""Print the location o... | [
"def",
"add_cli_cache",
"(",
"main",
":",
"click",
".",
"Group",
")",
"->",
"click",
".",
"Group",
":",
"# noqa: D202",
"@",
"main",
".",
"group",
"(",
")",
"def",
"cache",
"(",
")",
":",
"\"\"\"Manage cached data.\"\"\"",
"@",
"cache",
".",
"command",
"... | 26.466667 | 18.766667 |
def import_string(import_name, silent=False):
"""Imports an object based on a string. This is useful if you want to
use import paths as endpoints or something similar. An import path can
be specified either in dotted notation (``xml.sax.saxutils.escape``)
or with a colon as object delimiter (``xml.sax... | [
"def",
"import_string",
"(",
"import_name",
",",
"silent",
"=",
"False",
")",
":",
"#XXX: py3 review needed",
"assert",
"isinstance",
"(",
"import_name",
",",
"string_types",
")",
"# force the import name to automatically convert to strings",
"import_name",
"=",
"str",
"(... | 41.809524 | 15.833333 |
def upload_to(self, buff, remote_path):
"""Uploads file from buffer to remote path on WebDAV server.
More information you can find by link http://webdav.org/specs/rfc4918.html#METHOD_PUT
:param buff: the buffer with content for file.
:param remote_path: the path to save file remotely on... | [
"def",
"upload_to",
"(",
"self",
",",
"buff",
",",
"remote_path",
")",
":",
"urn",
"=",
"Urn",
"(",
"remote_path",
")",
"if",
"urn",
".",
"is_dir",
"(",
")",
":",
"raise",
"OptionNotValid",
"(",
"name",
"=",
"'remote_path'",
",",
"value",
"=",
"remote_... | 42 | 21.666667 |
def notes_placeholder(self):
"""
Return the notes placeholder on this notes slide, the shape that
contains the actual notes text. Return |None| if no notes placeholder
is present; while this is probably uncommon, it can happen if the
notes master does not have a body placeholder,... | [
"def",
"notes_placeholder",
"(",
"self",
")",
":",
"for",
"placeholder",
"in",
"self",
".",
"placeholders",
":",
"if",
"placeholder",
".",
"placeholder_format",
".",
"type",
"==",
"PP_PLACEHOLDER",
".",
"BODY",
":",
"return",
"placeholder",
"return",
"None"
] | 47.666667 | 19 |
async def build_attrib_request(submitter_did: str,
target_did: str,
xhash: Optional[str],
raw: Optional[str],
enc: Optional[str]) -> str:
"""
Builds an ATTRIB request. Request to add attri... | [
"async",
"def",
"build_attrib_request",
"(",
"submitter_did",
":",
"str",
",",
"target_did",
":",
"str",
",",
"xhash",
":",
"Optional",
"[",
"str",
"]",
",",
"raw",
":",
"Optional",
"[",
"str",
"]",
",",
"enc",
":",
"Optional",
"[",
"str",
"]",
")",
... | 43.777778 | 21.111111 |
def mount(self, app, prefix, **options):
''' Mount an application to a specific URL prefix. The prefix is added
to SCIPT_PATH and removed from PATH_INFO before the sub-application
is called.
:param app: an instance of :class:`Bottle`.
:param prefix: path prefix u... | [
"def",
"mount",
"(",
"self",
",",
"app",
",",
"prefix",
",",
"*",
"*",
"options",
")",
":",
"if",
"not",
"isinstance",
"(",
"app",
",",
"Bottle",
")",
":",
"raise",
"TypeError",
"(",
"'Only Bottle instances are supported for now.'",
")",
"prefix",
"=",
"'/... | 45.076923 | 18.538462 |
def refresh_indices(model, block_size=100):
'''
This utility function will iterate over all entities of a provided model,
refreshing their indices. This is primarily useful after adding an index
on a column.
Arguments:
* *model* - the model whose entities you want to reindex
* *blo... | [
"def",
"refresh_indices",
"(",
"model",
",",
"block_size",
"=",
"100",
")",
":",
"conn",
"=",
"_connect",
"(",
"model",
")",
"max_id",
"=",
"int",
"(",
"conn",
".",
"get",
"(",
"'%s:%s:'",
"%",
"(",
"model",
".",
"_namespace",
",",
"model",
".",
"_pk... | 38.470588 | 24.647059 |
def get_google_drive_folder_location():
"""
Try to locate the Google Drive folder.
Returns:
(str) Full path to the current Google Drive folder
"""
gdrive_db_path = 'Library/Application Support/Google/Drive/sync_config.db'
yosemite_gdrive_db_path = ('Library/Application Support/Google/Dr... | [
"def",
"get_google_drive_folder_location",
"(",
")",
":",
"gdrive_db_path",
"=",
"'Library/Application Support/Google/Drive/sync_config.db'",
"yosemite_gdrive_db_path",
"=",
"(",
"'Library/Application Support/Google/Drive/'",
"'user_default/sync_config.db'",
")",
"yosemite_gdrive_db",
... | 34.529412 | 17.058824 |
def load_hdu(self, hdu):
"""
Load an HDU into the viewer.
"""
image = AstroImage.AstroImage(logger=self.logger)
image.load_hdu(hdu)
self.set_image(image) | [
"def",
"load_hdu",
"(",
"self",
",",
"hdu",
")",
":",
"image",
"=",
"AstroImage",
".",
"AstroImage",
"(",
"logger",
"=",
"self",
".",
"logger",
")",
"image",
".",
"load_hdu",
"(",
"hdu",
")",
"self",
".",
"set_image",
"(",
"image",
")"
] | 24.375 | 12.625 |
def _utc_year(self):
"""Return a fractional UTC year, for convenience when plotting.
An experiment, probably superseded by the ``J`` attribute below.
"""
d = self._utc_float() - 1721059.5
#d += offset
C = 365 * 100 + 24
d -= 365
d += d // C - d // (4 * C... | [
"def",
"_utc_year",
"(",
"self",
")",
":",
"d",
"=",
"self",
".",
"_utc_float",
"(",
")",
"-",
"1721059.5",
"#d += offset",
"C",
"=",
"365",
"*",
"100",
"+",
"24",
"d",
"-=",
"365",
"d",
"+=",
"d",
"//",
"C",
"-",
"d",
"//",
"(",
"4",
"*",
"C... | 26.388889 | 17.388889 |
def serialize_instance(instance):
""" Serialize Django model instance """
model_name = force_text(instance._meta)
return '{}:{}'.format(model_name, instance.pk) | [
"def",
"serialize_instance",
"(",
"instance",
")",
":",
"model_name",
"=",
"force_text",
"(",
"instance",
".",
"_meta",
")",
"return",
"'{}:{}'",
".",
"format",
"(",
"model_name",
",",
"instance",
".",
"pk",
")"
] | 42.25 | 5 |
def gps_offset(lat, lon, east, north):
'''return new lat/lon after moving east/north
by the given number of meters'''
bearing = math.degrees(math.atan2(east, north))
distance = math.sqrt(east**2 + north**2)
return gps_newpos(lat, lon, bearing, distance) | [
"def",
"gps_offset",
"(",
"lat",
",",
"lon",
",",
"east",
",",
"north",
")",
":",
"bearing",
"=",
"math",
".",
"degrees",
"(",
"math",
".",
"atan2",
"(",
"east",
",",
"north",
")",
")",
"distance",
"=",
"math",
".",
"sqrt",
"(",
"east",
"**",
"2"... | 44.666667 | 6.666667 |
def UrlGet(url, timeout=10, retries=0):
""" Retrieve content from the given URL. """
# in Python 2.6 we can pass timeout to urllib2.urlopen
socket.setdefaulttimeout(timeout)
attempts = 0
content = None
while not content:
try:
content = urllib2.urlopen(url).read()
except urllib2.URLErr... | [
"def",
"UrlGet",
"(",
"url",
",",
"timeout",
"=",
"10",
",",
"retries",
"=",
"0",
")",
":",
"# in Python 2.6 we can pass timeout to urllib2.urlopen",
"socket",
".",
"setdefaulttimeout",
"(",
"timeout",
")",
"attempts",
"=",
"0",
"content",
"=",
"None",
"while",
... | 32.5 | 14.214286 |
def _process_counter_example(self, mma, w_string):
""""
Process a counterexample in the Rivest-Schapire way.
Args:
mma (DFA): The hypothesis automaton
w_string (str): The examined string to be consumed
Return:
None
"""
if len(w_string) ... | [
"def",
"_process_counter_example",
"(",
"self",
",",
"mma",
",",
"w_string",
")",
":",
"if",
"len",
"(",
"w_string",
")",
"==",
"1",
":",
"self",
".",
"observation_table",
".",
"smi_vector",
".",
"append",
"(",
"w_string",
")",
"for",
"exp",
"in",
"self"... | 46.865385 | 24.307692 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.