text stringlengths 89 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 630 |
|---|---|---|---|
def convert_cropping(builder, layer, input_names, output_names, keras_layer):
"""
Convert padding layer from keras to coreml.
Keras only supports zero padding at this time.
Parameters
----------
keras_layer: layer
A keras layer object.
builder: NeuralNetworkBuilder
A neural ... | [
"def",
"convert_cropping",
"(",
"builder",
",",
"layer",
",",
"input_names",
",",
"output_names",
",",
"keras_layer",
")",
":",
"_check_data_format",
"(",
"keras_layer",
")",
"# Get input and output names",
"input_name",
",",
"output_name",
"=",
"(",
"input_names",
... | 36.019231 | 17.057692 |
def get_stp_mst_detail_output_cist_port_admin_edge(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_mst_detail = ET.Element("get_stp_mst_detail")
config = get_stp_mst_detail
output = ET.SubElement(get_stp_mst_detail, "output")
cist... | [
"def",
"get_stp_mst_detail_output_cist_port_admin_edge",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"config",
"=",
"ET",
".",
"Element",
"(",
"\"config\"",
")",
"get_stp_mst_detail",
"=",
"ET",
".",
"Element",
"(",
"\"get_stp_mst_detail\"",
")",
"config",
"... | 41.357143 | 12.285714 |
def has_output(state,
text,
incorrect_msg="The checker expected to find {{'' if fixed else 'the pattern '}}`{{text}}` in the output of your command.",
fixed=False,
strip_ansi=True):
"""Check whether student output contains specific text.
Before you us... | [
"def",
"has_output",
"(",
"state",
",",
"text",
",",
"incorrect_msg",
"=",
"\"The checker expected to find {{'' if fixed else 'the pattern '}}`{{text}}` in the output of your command.\"",
",",
"fixed",
"=",
"False",
",",
"strip_ansi",
"=",
"True",
")",
":",
"stu_output",
"=... | 35.3 | 28.66 |
def removeRequest(self, service, *args):
"""
Removes a request from the pending request list.
"""
if isinstance(service, RequestWrapper):
if self.logger:
self.logger.debug('Removing request: %s',
self.requests[self.requests.index(service)]... | [
"def",
"removeRequest",
"(",
"self",
",",
"service",
",",
"*",
"args",
")",
":",
"if",
"isinstance",
"(",
"service",
",",
"RequestWrapper",
")",
":",
"if",
"self",
".",
"logger",
":",
"self",
".",
"logger",
".",
"debug",
"(",
"'Removing request: %s'",
",... | 34.130435 | 19.695652 |
def write_to_png(self, target=None):
"""Writes the contents of surface as a PNG image.
:param target:
A filename,
a binary mode file-like object with a :meth:`~file.write` method,
or :obj:`None`.
:returns:
If :obj:`target` is :obj:`None`,
... | [
"def",
"write_to_png",
"(",
"self",
",",
"target",
"=",
"None",
")",
":",
"return_bytes",
"=",
"target",
"is",
"None",
"if",
"return_bytes",
":",
"target",
"=",
"io",
".",
"BytesIO",
"(",
")",
"if",
"hasattr",
"(",
"target",
",",
"'write'",
")",
":",
... | 35.583333 | 15.416667 |
def fetch(self, refund_id, data={}, **kwargs):
""""
Refund object for given paymnet Id
Args:
refund_id : Refund Id for which refund has to be retrieved
Returns:
Refund dict for given refund Id
"""
return super(Refund, self).fetch(refund_id, data,... | [
"def",
"fetch",
"(",
"self",
",",
"refund_id",
",",
"data",
"=",
"{",
"}",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"super",
"(",
"Refund",
",",
"self",
")",
".",
"fetch",
"(",
"refund_id",
",",
"data",
",",
"*",
"*",
"kwargs",
")"
] | 29.090909 | 18.090909 |
def reorder_pinned_topics_courses(self, order, course_id):
"""
Reorder pinned topics.
Puts the pinned discussion topics in the specified order.
All pinned topics should be included.
"""
path = {}
data = {}
params = {}
# REQUIRED - PATH... | [
"def",
"reorder_pinned_topics_courses",
"(",
"self",
",",
"order",
",",
"course_id",
")",
":",
"path",
"=",
"{",
"}",
"data",
"=",
"{",
"}",
"params",
"=",
"{",
"}",
"# REQUIRED - PATH - course_id\r",
"\"\"\"ID\"\"\"",
"path",
"[",
"\"course_id\"",
"]",
"=",
... | 40.454545 | 25.5 |
def saveSilent(self):
"""
Saves the record, but does not emit the saved signal. This method
is useful when chaining together multiple saves. Check the
saveSignalBlocked value to know if it was muted to know if any
saves occurred.
:return <bool>
... | [
"def",
"saveSilent",
"(",
"self",
")",
":",
"self",
".",
"blockSignals",
"(",
"True",
")",
"success",
"=",
"self",
".",
"save",
"(",
")",
"self",
".",
"blockSignals",
"(",
"False",
")",
"return",
"success"
] | 33.692308 | 16.615385 |
def _set_options(self, options):
'''Private function for setting options used for sealing'''
if not options:
return self.options.copy()
options = options.copy()
if 'magic' in options:
self.set_magic(options['magic'])
del(options['magic'])
if... | [
"def",
"_set_options",
"(",
"self",
",",
"options",
")",
":",
"if",
"not",
"options",
":",
"return",
"self",
".",
"options",
".",
"copy",
"(",
")",
"options",
"=",
"options",
".",
"copy",
"(",
")",
"if",
"'magic'",
"in",
"options",
":",
"self",
".",
... | 32.147059 | 16.735294 |
def worklog(accountable):
"""
List all worklogs for a given issue key.
"""
worklog = accountable.issue_worklog()
headers = ['author_name', 'comment', 'time_spent']
if worklog:
rows = [[v for k, v in sorted(w.items()) if k in headers]
for w in worklog]
rows.insert(... | [
"def",
"worklog",
"(",
"accountable",
")",
":",
"worklog",
"=",
"accountable",
".",
"issue_worklog",
"(",
")",
"headers",
"=",
"[",
"'author_name'",
",",
"'comment'",
",",
"'time_spent'",
"]",
"if",
"worklog",
":",
"rows",
"=",
"[",
"[",
"v",
"for",
"k",... | 30.4375 | 14.5625 |
def get_api_publisher(self, social_user):
"""
owner_id - VK user or group
from_group - 1 by group, 0 by user
message - text
attachments - comma separated links or VK resources ID's
and other https://vk.com/dev.php?method=wall.post
"""
... | [
"def",
"get_api_publisher",
"(",
"self",
",",
"social_user",
")",
":",
"def",
"_post",
"(",
"*",
"*",
"kwargs",
")",
":",
"api",
"=",
"self",
".",
"get_api",
"(",
"social_user",
")",
"response",
"=",
"api",
".",
"wall",
".",
"post",
"(",
"*",
"*",
... | 31.133333 | 13.666667 |
def set_config_file(self, path):
"""
Set the config file. The contents must be valid YAML and there
must be a top-level element 'tasks'. The listed tasks will be
started according to their configuration, and the file will
be watched for future changes. The changes will be acti... | [
"def",
"set_config_file",
"(",
"self",
",",
"path",
")",
":",
"log",
"=",
"self",
".",
"_params",
".",
"get",
"(",
"'log'",
",",
"self",
".",
"_discard",
")",
"if",
"path",
"!=",
"self",
".",
"_config_file",
":",
"if",
"self",
".",
"_config_file",
":... | 48.555556 | 17.666667 |
def naive(seqs, f=None, start=None, key=lambda x: x):
"""Naive cycle detector
See help(cycle_detector) for more context.
Args:
sequence: A sequence to detect cyles in.
f, start: Function and starting state for finite state machine
Yields:
Values yielded by sequence_a if it termi... | [
"def",
"naive",
"(",
"seqs",
",",
"f",
"=",
"None",
",",
"start",
"=",
"None",
",",
"key",
"=",
"lambda",
"x",
":",
"x",
")",
":",
"history",
"=",
"{",
"}",
"for",
"step",
",",
"value",
"in",
"enumerate",
"(",
"seqs",
"[",
"0",
"]",
")",
":",... | 25.933333 | 23.666667 |
def make_FULL_BSE_Densities_folder(self, folder):
"""
mkdir "FULL_BSE_Densities" folder (needed for bse run) in the desired folder
"""
if os.path.exists(folder + "/FULL_BSE_Densities"):
return "FULL_BSE_Densities folder already exists"
else:
os.makedirs(f... | [
"def",
"make_FULL_BSE_Densities_folder",
"(",
"self",
",",
"folder",
")",
":",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"folder",
"+",
"\"/FULL_BSE_Densities\"",
")",
":",
"return",
"\"FULL_BSE_Densities folder already exists\"",
"else",
":",
"os",
".",
"maked... | 39.7 | 18.9 |
def set_pid():
"""
Explicitly ask the ipython kernel for its pid
"""
global pid
lines = '\n'.join(['import os', '_pid = os.getpid()'])
try:
msg_id = send(lines, silent=True, user_variables=['_pid'])
except TypeError: # change in IPython 3.0+
msg_id = send(lines, silent=True,... | [
"def",
"set_pid",
"(",
")",
":",
"global",
"pid",
"lines",
"=",
"'\\n'",
".",
"join",
"(",
"[",
"'import os'",
",",
"'_pid = os.getpid()'",
"]",
")",
"try",
":",
"msg_id",
"=",
"send",
"(",
"lines",
",",
"silent",
"=",
"True",
",",
"user_variables",
"=... | 36.321429 | 22.107143 |
def select(self, column, agg=None, _as=None, distinct=False):
"""
What columnns to select in query.
:column should be a column name or equation to produce column **not** aggregated
:agg should be a valid aggregate method used to producte the figure
:_as should be a string used to... | [
"def",
"select",
"(",
"self",
",",
"column",
",",
"agg",
"=",
"None",
",",
"_as",
"=",
"None",
",",
"distinct",
"=",
"False",
")",
":",
"if",
"agg",
"and",
"not",
"_as",
":",
"raise",
"ValueError",
"(",
"\"Aggregate colunns require `_as` to be specified\"",
... | 48.692308 | 22.846154 |
def feature_enabled(self, feature_name):
"""
Indicates whether the specified feature is enabled for the CPC of this
partition.
The HMC must generally support features, and the specified feature must
be available for the CPC.
For a list of available features, see section... | [
"def",
"feature_enabled",
"(",
"self",
",",
"feature_name",
")",
":",
"feature_list",
"=",
"self",
".",
"prop",
"(",
"'available-features-list'",
",",
"None",
")",
"if",
"feature_list",
"is",
"None",
":",
"raise",
"ValueError",
"(",
"\"Firmware features are not su... | 34.622222 | 22.8 |
def rprop_core(params, gradients, rprop_increase=1.01, rprop_decrease=0.99, rprop_min_step=0, rprop_max_step=100,
learning_rate=0.01):
"""
Rprop optimizer.
See http://sci2s.ugr.es/keel/pdf/algorithm/articulo/2003-Neuro-Igel-IRprop+.pdf.
"""
for param, grad in zip(params, gradients):
... | [
"def",
"rprop_core",
"(",
"params",
",",
"gradients",
",",
"rprop_increase",
"=",
"1.01",
",",
"rprop_decrease",
"=",
"0.99",
",",
"rprop_min_step",
"=",
"0",
",",
"rprop_max_step",
"=",
"100",
",",
"learning_rate",
"=",
"0.01",
")",
":",
"for",
"param",
"... | 43.428571 | 21.047619 |
def get_padding_lengths(self) -> Dict[str, Dict[str, int]]:
"""
Gets the maximum padding lengths from all ``Instances`` in this batch. Each ``Instance``
has multiple ``Fields``, and each ``Field`` could have multiple things that need padding.
We look at all fields in all instances, and ... | [
"def",
"get_padding_lengths",
"(",
"self",
")",
"->",
"Dict",
"[",
"str",
",",
"Dict",
"[",
"str",
",",
"int",
"]",
"]",
":",
"padding_lengths",
":",
"Dict",
"[",
"str",
",",
"Dict",
"[",
"str",
",",
"int",
"]",
"]",
"=",
"defaultdict",
"(",
"dict"... | 62.208333 | 29.791667 |
def calculate_fee(self, input_values):
'''
Tx, list(int) -> int
'''
total_in = sum(input_values)
total_out = sum([utils.le2i(tx_out.value) for tx_out in self.tx_outs])
for js in self.tx_joinsplits:
total_in += utils.le2i(js.vpub_new)
total_out += u... | [
"def",
"calculate_fee",
"(",
"self",
",",
"input_values",
")",
":",
"total_in",
"=",
"sum",
"(",
"input_values",
")",
"total_out",
"=",
"sum",
"(",
"[",
"utils",
".",
"le2i",
"(",
"tx_out",
".",
"value",
")",
"for",
"tx_out",
"in",
"self",
".",
"tx_out... | 36.9 | 13.7 |
def hash_shooter(video_path):
"""Compute a hash using Shooter's algorithm
:param string video_path: path of the video
:return: the hash
:rtype: string
"""
filesize = os.path.getsize(video_path)
readsize = 4096
if os.path.getsize(video_path) < readsize * 2:
return None
offse... | [
"def",
"hash_shooter",
"(",
"video_path",
")",
":",
"filesize",
"=",
"os",
".",
"path",
".",
"getsize",
"(",
"video_path",
")",
"readsize",
"=",
"4096",
"if",
"os",
".",
"path",
".",
"getsize",
"(",
"video_path",
")",
"<",
"readsize",
"*",
"2",
":",
... | 31.105263 | 17.210526 |
def eventFilter(self, watchedObject, event):
""" Deletes an item from an editable combobox when the delete or backspace key is pressed
in the list of items, or when ctrl-delete or ctrl-back space is pressed in the
line-edit.
When the combobox is not editable the filter does ... | [
"def",
"eventFilter",
"(",
"self",
",",
"watchedObject",
",",
"event",
")",
":",
"if",
"self",
".",
"comboBox",
".",
"isEditable",
"(",
")",
"and",
"event",
".",
"type",
"(",
")",
"==",
"QtCore",
".",
"QEvent",
".",
"KeyPress",
":",
"key",
"=",
"even... | 51.72 | 23 |
def unwrap(self, encrypted_data):
"""
Decrypts the data send by the server using the TLS channel negotiated
between the client and the server.
:param encrypted_data: the byte string of the encrypted data
:return: a byte string of the decrypted data
"""
length = s... | [
"def",
"unwrap",
"(",
"self",
",",
"encrypted_data",
")",
":",
"length",
"=",
"self",
".",
"tls_connection",
".",
"bio_write",
"(",
"encrypted_data",
")",
"data",
"=",
"b''",
"counter",
"=",
"0",
"while",
"True",
":",
"try",
":",
"data_chunk",
"=",
"self... | 29.416667 | 19.75 |
def _get_field_comment(field, separator=' - '):
"""
Create SQL comment from field's title and description
:param field: tableschema-py Field, with optional 'title' and 'description' values
:param separator:
:return:
>>> _get_field_comment(tableschema.Field({'title': 'my_title', 'description': ... | [
"def",
"_get_field_comment",
"(",
"field",
",",
"separator",
"=",
"' - '",
")",
":",
"title",
"=",
"field",
".",
"descriptor",
".",
"get",
"(",
"'title'",
")",
"or",
"''",
"description",
"=",
"field",
".",
"descriptor",
".",
"get",
"(",
"'description'",
... | 39.3 | 24.9 |
def GetAttribute(self, name):
"""Provides the value of the attribute with the specified
qualified name. """
ret = libxml2mod.xmlTextReaderGetAttribute(self._o, name)
return ret | [
"def",
"GetAttribute",
"(",
"self",
",",
"name",
")",
":",
"ret",
"=",
"libxml2mod",
".",
"xmlTextReaderGetAttribute",
"(",
"self",
".",
"_o",
",",
"name",
")",
"return",
"ret"
] | 41.4 | 11.6 |
def calc_im_size(img_height, img_width):
'''Calculates shape of data after decoding.
Parameters
----------
img_height : int
Height of encoded data.
img_width : int
Width of encoded data.
Returns
-------
encoded_shape : tuple(int)
Gives back 2-tuple with decoded ... | [
"def",
"calc_im_size",
"(",
"img_height",
",",
"img_width",
")",
":",
"height",
",",
"width",
"=",
"img_height",
",",
"img_width",
"for",
"_",
"in",
"range",
"(",
"5",
")",
":",
"height",
",",
"width",
"=",
"_get_deconv_outsize",
"(",
"(",
"height",
",",... | 25.238095 | 20.190476 |
def company_path(cls, project, company):
"""Return a fully-qualified company string."""
return google.api_core.path_template.expand(
"projects/{project}/companies/{company}", project=project, company=company
) | [
"def",
"company_path",
"(",
"cls",
",",
"project",
",",
"company",
")",
":",
"return",
"google",
".",
"api_core",
".",
"path_template",
".",
"expand",
"(",
"\"projects/{project}/companies/{company}\"",
",",
"project",
"=",
"project",
",",
"company",
"=",
"compan... | 48.2 | 17.8 |
def ok_cred_def_id(token: str, issuer_did: str = None) -> bool:
"""
Whether input token looks like a valid credential definition identifier from input issuer DID (default any); i.e.,
<issuer-did>:3:CL:<schema-seq-no>:<cred-def-id-tag> for protocol >= 1.4, or
<issuer-did>:3:CL:<schema-seq-no> for protoco... | [
"def",
"ok_cred_def_id",
"(",
"token",
":",
"str",
",",
"issuer_did",
":",
"str",
"=",
"None",
")",
"->",
"bool",
":",
"cd_id_m",
"=",
"re",
".",
"match",
"(",
"'([{}]{{21,22}}):3:CL:[1-9][0-9]*(:.+)?$'",
".",
"format",
"(",
"B58",
")",
",",
"token",
"or",... | 52.076923 | 30.384615 |
def drop_edges(self) -> None:
"""Drop all edges in the database."""
t = time.time()
self.session.query(Edge).delete()
self.session.commit()
log.info('dropped all edges in %.2f seconds', time.time() - t) | [
"def",
"drop_edges",
"(",
"self",
")",
"->",
"None",
":",
"t",
"=",
"time",
".",
"time",
"(",
")",
"self",
".",
"session",
".",
"query",
"(",
"Edge",
")",
".",
"delete",
"(",
")",
"self",
".",
"session",
".",
"commit",
"(",
")",
"log",
".",
"in... | 29.625 | 18.75 |
def exec_command(self, cmdstr):
"""
Execute an x3270 command
`cmdstr` gets sent directly to the x3270 subprocess on it's stdin.
"""
if self.is_terminated:
raise TerminatedError("this TerminalClient instance has been terminated")
log.debug("sending co... | [
"def",
"exec_command",
"(",
"self",
",",
"cmdstr",
")",
":",
"if",
"self",
".",
"is_terminated",
":",
"raise",
"TerminatedError",
"(",
"\"this TerminalClient instance has been terminated\"",
")",
"log",
".",
"debug",
"(",
"\"sending command: %s\"",
",",
"cmdstr",
")... | 31.555556 | 17.777778 |
def _rpt_unused_sections(self, prt):
"""Report unused sections."""
sections_unused = set(self.sections_seen).difference(self.section2goids.keys())
for sec in sections_unused:
prt.write(" UNUSED SECTION: {SEC}\n".format(SEC=sec)) | [
"def",
"_rpt_unused_sections",
"(",
"self",
",",
"prt",
")",
":",
"sections_unused",
"=",
"set",
"(",
"self",
".",
"sections_seen",
")",
".",
"difference",
"(",
"self",
".",
"section2goids",
".",
"keys",
"(",
")",
")",
"for",
"sec",
"in",
"sections_unused"... | 52.2 | 16.4 |
def _filter_update_security_group_rule(rule):
'''Only two fields are allowed for modification:
external_service and external_service_id
'''
allowed = ['external_service', 'external_service_id']
filtered = {}
for k, val in rule.iteritems():
if k in allowed:
if isinstance(... | [
"def",
"_filter_update_security_group_rule",
"(",
"rule",
")",
":",
"allowed",
"=",
"[",
"'external_service'",
",",
"'external_service_id'",
"]",
"filtered",
"=",
"{",
"}",
"for",
"k",
",",
"val",
"in",
"rule",
".",
"iteritems",
"(",
")",
":",
"if",
"k",
"... | 33.384615 | 15.692308 |
def _issubclass_Union(subclass, superclass, bound_Generic, bound_typevars,
bound_typevars_readonly, follow_fwd_refs, _recursion_check):
"""Helper for _issubclass, a.k.a pytypes.issubtype.
"""
if not follow_fwd_refs:
return _issubclass_Union_rec(subclass, superclass, bound_Generic, bound_... | [
"def",
"_issubclass_Union",
"(",
"subclass",
",",
"superclass",
",",
"bound_Generic",
",",
"bound_typevars",
",",
"bound_typevars_readonly",
",",
"follow_fwd_refs",
",",
"_recursion_check",
")",
":",
"if",
"not",
"follow_fwd_refs",
":",
"return",
"_issubclass_Union_rec"... | 59.714286 | 28.142857 |
def prefetchDeclarativeIds(self, Declarative, count) -> Deferred:
""" Get PG Sequence Generator
A PostGreSQL sequence generator returns a chunk of IDs for the given
declarative.
:return: A generator that will provide the IDs
:rtype: an iterator, yielding the numbers to assign
... | [
"def",
"prefetchDeclarativeIds",
"(",
"self",
",",
"Declarative",
",",
"count",
")",
"->",
"Deferred",
":",
"return",
"self",
".",
"_dbConn",
".",
"prefetchDeclarativeIds",
"(",
"Declarative",
"=",
"Declarative",
",",
"count",
"=",
"count",
")"
] | 37.272727 | 25.636364 |
def basescript(line):
'''
>>> import pprint
>>> input_line = '{"level": "warning", "timestamp": "2018-02-07T06:37:00.297610Z", "event": "exited via keyboard interrupt", "type": "log", "id": "20180207T063700_4d03fe800bd111e89ecb96000007bc65", "_": {"ln": 58, "file": "/usr/local/lib/python2.7/dist-packages/ba... | [
"def",
"basescript",
"(",
"line",
")",
":",
"log",
"=",
"json",
".",
"loads",
"(",
"line",
")",
"return",
"dict",
"(",
"timestamp",
"=",
"log",
"[",
"'timestamp'",
"]",
",",
"data",
"=",
"log",
",",
"id",
"=",
"log",
"[",
"'id'",
"]",
",",
"type"... | 42.375 | 28.125 |
def make_session(config=None, num_cpu=None, make_default=False, graph=None):
"""Returns a session that will use <num_cpu> CPU's only"""
if num_cpu is None:
num_cpu = int(os.getenv('RCALL_NUM_CPU', multiprocessing.cpu_count()))
if config is None:
config = tf.ConfigProto(
allow_sof... | [
"def",
"make_session",
"(",
"config",
"=",
"None",
",",
"num_cpu",
"=",
"None",
",",
"make_default",
"=",
"False",
",",
"graph",
"=",
"None",
")",
":",
"if",
"num_cpu",
"is",
"None",
":",
"num_cpu",
"=",
"int",
"(",
"os",
".",
"getenv",
"(",
"'RCALL_... | 41.4 | 18.066667 |
def stat(path, hours, offset=None):
"""
Has the metric file at ``path`` been modified since ``hours`` ago?
.. note::
``offset`` is only for compatibility with ``data()`` and is ignored.
"""
return os.stat(path).st_mtime < (time.time() - _to_sec(hours)) | [
"def",
"stat",
"(",
"path",
",",
"hours",
",",
"offset",
"=",
"None",
")",
":",
"return",
"os",
".",
"stat",
"(",
"path",
")",
".",
"st_mtime",
"<",
"(",
"time",
".",
"time",
"(",
")",
"-",
"_to_sec",
"(",
"hours",
")",
")"
] | 34.25 | 20.5 |
def synchronize(self, pid, vendorSpecific=None):
"""See Also: synchronizeResponse() Args: pid: vendorSpecific:
Returns:
"""
response = self.synchronizeResponse(pid, vendorSpecific)
return self._read_boolean_response(response) | [
"def",
"synchronize",
"(",
"self",
",",
"pid",
",",
"vendorSpecific",
"=",
"None",
")",
":",
"response",
"=",
"self",
".",
"synchronizeResponse",
"(",
"pid",
",",
"vendorSpecific",
")",
"return",
"self",
".",
"_read_boolean_response",
"(",
"response",
")"
] | 32.5 | 18.5 |
def _parse(self, raw, next_cls):
'''
Parse a raw bytes object and construct the list of packet header
objects (and possible remaining bytes) that are part of this packet.
'''
if next_cls is None:
from switchyard.lib.packet import Ethernet
next_cls = Ethern... | [
"def",
"_parse",
"(",
"self",
",",
"raw",
",",
"next_cls",
")",
":",
"if",
"next_cls",
"is",
"None",
":",
"from",
"switchyard",
".",
"lib",
".",
"packet",
"import",
"Ethernet",
"next_cls",
"=",
"Ethernet",
"self",
".",
"_headers",
"=",
"[",
"]",
"while... | 37.473684 | 17.789474 |
def metadata_and_language_from_option_line(self, line):
"""Parse code options on the given line. When a start of a code cell
is found, self.metadata is set to a dictionary."""
if self.start_code_re.match(line):
self.language, self.metadata = self.options_to_metadata(line[line.find('%... | [
"def",
"metadata_and_language_from_option_line",
"(",
"self",
",",
"line",
")",
":",
"if",
"self",
".",
"start_code_re",
".",
"match",
"(",
"line",
")",
":",
"self",
".",
"language",
",",
"self",
".",
"metadata",
"=",
"self",
".",
"options_to_metadata",
"(",... | 58.857143 | 14 |
def add_insertions(self, skip=10, window=1, test=False):
'''Adds a random base within window bases around every skip bases. e.g. skip=10, window=1 means a random base added somwhere in theintervals [9,11], [19,21] ... '''
assert 2 * window < skip
new_seq = list(self.seq)
for i in range(l... | [
"def",
"add_insertions",
"(",
"self",
",",
"skip",
"=",
"10",
",",
"window",
"=",
"1",
",",
"test",
"=",
"False",
")",
":",
"assert",
"2",
"*",
"window",
"<",
"skip",
"new_seq",
"=",
"list",
"(",
"self",
".",
"seq",
")",
"for",
"i",
"in",
"range"... | 48.083333 | 24.416667 |
def properties_operator(cls, name):
"""Wraps a container operator to ensure container class is maintained"""
def wrapper(self, *args, **kwargs):
"""Perform operation and cast to container class"""
output = getattr(super(cls, self), name)(*args, **kwargs)
return cls(output)
wrapped ... | [
"def",
"properties_operator",
"(",
"cls",
",",
"name",
")",
":",
"def",
"wrapper",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"\"\"\"Perform operation and cast to container class\"\"\"",
"output",
"=",
"getattr",
"(",
"super",
"(",
"cls"... | 35.5 | 13.25 |
def bulk_attachments(self, article, attachments):
"""
This function implements associating attachments to an article after article creation (for
unassociated attachments).
:param article: Article id or :class:`Article` object
:param attachments: :class:`ArticleAttachment` object... | [
"def",
"bulk_attachments",
"(",
"self",
",",
"article",
",",
"attachments",
")",
":",
"return",
"HelpdeskAttachmentRequest",
"(",
"self",
")",
".",
"post",
"(",
"self",
".",
"endpoint",
".",
"bulk_attachments",
",",
"article",
"=",
"article",
",",
"attachments... | 56.461538 | 31.692308 |
def plugins(cls, enabled=True):
"""
Returns the plugins for the given class.
:param enabled | <bool> || None
:return [<Plugin>, ..]
"""
cls.loadPlugins()
plugs = getattr(cls, '_%s__plugins' % cls.__name__, {}).values()
if enabled... | [
"def",
"plugins",
"(",
"cls",
",",
"enabled",
"=",
"True",
")",
":",
"cls",
".",
"loadPlugins",
"(",
")",
"plugs",
"=",
"getattr",
"(",
"cls",
",",
"'_%s__plugins'",
"%",
"cls",
".",
"__name__",
",",
"{",
"}",
")",
".",
"values",
"(",
")",
"if",
... | 29.071429 | 16.5 |
def check_args(self):
"""
Validates that a valid number of arguments were received and that all arguments were
recognised.
:return: True or False.
"""
parser = get_base_arguments(get_parser())
parser = get_tc_arguments(parser)
# Disable "Do not use len(SE... | [
"def",
"check_args",
"(",
"self",
")",
":",
"parser",
"=",
"get_base_arguments",
"(",
"get_parser",
"(",
")",
")",
"parser",
"=",
"get_tc_arguments",
"(",
"parser",
")",
"# Disable \"Do not use len(SEQ) as condition value\"",
"# pylint: disable=C1801",
"if",
"len",
"(... | 40.727273 | 19.727273 |
def to_internal(self, attribute_profile, external_dict):
"""
Converts the external data from "type" to internal
:type attribute_profile: str
:type external_dict: dict[str, str]
:rtype: dict[str, str]
:param attribute_profile: From which external type to convert (ex: oid... | [
"def",
"to_internal",
"(",
"self",
",",
"attribute_profile",
",",
"external_dict",
")",
":",
"internal_dict",
"=",
"{",
"}",
"for",
"internal_attribute_name",
",",
"mapping",
"in",
"self",
".",
"from_internal_attributes",
".",
"items",
"(",
")",
":",
"if",
"at... | 52.454545 | 31.121212 |
def get_minimum_needs(self):
"""Get the minimum needed information about the minimum needs.
That is the resource and the amount.
:returns: minimum needs
:rtype: OrderedDict
"""
minimum_needs = OrderedDict()
for resource in self.minimum_needs['resources']:
... | [
"def",
"get_minimum_needs",
"(",
"self",
")",
":",
"minimum_needs",
"=",
"OrderedDict",
"(",
")",
"for",
"resource",
"in",
"self",
".",
"minimum_needs",
"[",
"'resources'",
"]",
":",
"if",
"resource",
"[",
"'Unit abbreviation'",
"]",
":",
"name",
"=",
"'%s [... | 34.55 | 11.2 |
def _get_step_inputs(step, file_vs, std_vs, parallel_ids, wf=None):
"""Retrieve inputs for a step from existing variables.
Potentially nests inputs to deal with merging split variables. If
we split previously and are merging now, then we only nest those
coming from the split process.
"""
inputs... | [
"def",
"_get_step_inputs",
"(",
"step",
",",
"file_vs",
",",
"std_vs",
",",
"parallel_ids",
",",
"wf",
"=",
"None",
")",
":",
"inputs",
"=",
"[",
"]",
"skip_inputs",
"=",
"set",
"(",
"[",
"]",
")",
"for",
"orig_input",
"in",
"[",
"_get_variable",
"(",
... | 48.666667 | 19.361111 |
def list_all_stripe_gateways(cls, **kwargs):
"""List StripeGateways
Return a list of StripeGateways
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async=True
>>> thread = api.list_all_stripe_gateways(async=True)
... | [
"def",
"list_all_stripe_gateways",
"(",
"cls",
",",
"*",
"*",
"kwargs",
")",
":",
"kwargs",
"[",
"'_return_http_data_only'",
"]",
"=",
"True",
"if",
"kwargs",
".",
"get",
"(",
"'async'",
")",
":",
"return",
"cls",
".",
"_list_all_stripe_gateways_with_http_info",... | 38.173913 | 15.086957 |
def _matcher(self, other):
"""
CGRContainer < CGRContainer
"""
if isinstance(other, CGRContainer):
return GraphMatcher(other, self, lambda x, y: x == y, lambda x, y: x == y)
raise TypeError('only cgr-cgr possible') | [
"def",
"_matcher",
"(",
"self",
",",
"other",
")",
":",
"if",
"isinstance",
"(",
"other",
",",
"CGRContainer",
")",
":",
"return",
"GraphMatcher",
"(",
"other",
",",
"self",
",",
"lambda",
"x",
",",
"y",
":",
"x",
"==",
"y",
",",
"lambda",
"x",
","... | 37.142857 | 10.857143 |
def update_bin(self, bin_form):
"""Updates an existing bin.
arg: bin_form (osid.resource.BinForm): the form containing
the elements to be updated
raise: IllegalState - ``bin_form`` already used in an update
transaction
raise: InvalidArgument - the fo... | [
"def",
"update_bin",
"(",
"self",
",",
"bin_form",
")",
":",
"# Implemented from template for",
"# osid.resource.BinAdminSession.update_bin_template",
"if",
"self",
".",
"_catalog_session",
"is",
"not",
"None",
":",
"return",
"self",
".",
"_catalog_session",
".",
"updat... | 52.575 | 25.025 |
def download(directory, master_token=None, member=None, access_token=None,
source=None, project_data=False, max_size='128m', verbose=False,
debug=False, memberlist=None, excludelist=None,
id_filename=False):
"""
Download data from project members to the target directory.
... | [
"def",
"download",
"(",
"directory",
",",
"master_token",
"=",
"None",
",",
"member",
"=",
"None",
",",
"access_token",
"=",
"None",
",",
"source",
"=",
"None",
",",
"project_data",
"=",
"False",
",",
"max_size",
"=",
"'128m'",
",",
"verbose",
"=",
"Fals... | 49.853933 | 22.550562 |
def make_parallel_helper(parallel_arg, **kwargs):
"""Return a :class:`ParallelHelper` object that can be used for easy
parallelization of computations. *parallel_arg* is an object that lets the
caller easily specify the kind of parallelization they are interested in.
Allowed values are:
False
... | [
"def",
"make_parallel_helper",
"(",
"parallel_arg",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"parallel_arg",
"is",
"True",
":",
"# note: (True == 1) is True",
"return",
"MultiprocessingPoolHelper",
"(",
"*",
"*",
"kwargs",
")",
"if",
"parallel_arg",
"is",
"False",... | 37.69863 | 22.835616 |
def array_to_hdf5(a, parent, name, **kwargs):
"""Write a Numpy array to an HDF5 dataset.
Parameters
----------
a : ndarray
Data to write.
parent : string or h5py group
Parent HDF5 file or group. If a string, will be treated as HDF5 file
name.
name : string
Name o... | [
"def",
"array_to_hdf5",
"(",
"a",
",",
"parent",
",",
"name",
",",
"*",
"*",
"kwargs",
")",
":",
"import",
"h5py",
"h5f",
"=",
"None",
"if",
"isinstance",
"(",
"parent",
",",
"str",
")",
":",
"h5f",
"=",
"h5py",
".",
"File",
"(",
"parent",
",",
"... | 22.682927 | 22.853659 |
def _column_resized(self, col, old_width, new_width):
"""Update the column width."""
self.dataTable.setColumnWidth(col, new_width)
self._update_layout() | [
"def",
"_column_resized",
"(",
"self",
",",
"col",
",",
"old_width",
",",
"new_width",
")",
":",
"self",
".",
"dataTable",
".",
"setColumnWidth",
"(",
"col",
",",
"new_width",
")",
"self",
".",
"_update_layout",
"(",
")"
] | 44 | 9.75 |
def read_dictionary_file(dictionary_path):
"""Return all words in dictionary file as set."""
try:
return _user_dictionary_cache[dictionary_path]
except KeyError:
if dictionary_path and os.path.exists(dictionary_path):
with open(dictionary_path, "rt") as dict_f:
wo... | [
"def",
"read_dictionary_file",
"(",
"dictionary_path",
")",
":",
"try",
":",
"return",
"_user_dictionary_cache",
"[",
"dictionary_path",
"]",
"except",
"KeyError",
":",
"if",
"dictionary_path",
"and",
"os",
".",
"path",
".",
"exists",
"(",
"dictionary_path",
")",
... | 39.833333 | 19.416667 |
def _find_project_config_file(user_config_file):
"""Find path to project-wide config file
Search from current working directory, and traverse path up to
directory with .versionner.rc file or root directory
:param user_config_file: instance with user-wide config path
:type: pathlib.Path
:rtype: ... | [
"def",
"_find_project_config_file",
"(",
"user_config_file",
")",
":",
"proj_cfg_dir",
"=",
"pathlib",
".",
"Path",
"(",
"'.'",
")",
".",
"absolute",
"(",
")",
"proj_cfg_file",
"=",
"None",
"root",
"=",
"pathlib",
".",
"Path",
"(",
"'/'",
")",
"while",
"pr... | 33.826087 | 16.217391 |
def realpath(self, spec, key):
"""
Resolve and update the path key in the spec with its realpath,
based on the working directory.
"""
if key not in spec:
# do nothing for now
return
if not spec[key]:
logger.warning(
"c... | [
"def",
"realpath",
"(",
"self",
",",
"spec",
",",
"key",
")",
":",
"if",
"key",
"not",
"in",
"spec",
":",
"# do nothing for now",
"return",
"if",
"not",
"spec",
"[",
"key",
"]",
":",
"logger",
".",
"warning",
"(",
"\"cannot resolve realpath of '%s' as it is ... | 28.956522 | 19.217391 |
def net_transform(transform_func, block=None, **kwargs):
"""
Maps nets to new sets of nets according to a custom function
:param transform_func:
Function signature: func(orig_net (logicnet)) -> keep_orig_net (bool)
:return:
"""
block = working_block(block)
with set_working_block(blo... | [
"def",
"net_transform",
"(",
"transform_func",
",",
"block",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"block",
"=",
"working_block",
"(",
"block",
")",
"with",
"set_working_block",
"(",
"block",
",",
"True",
")",
":",
"for",
"net",
"in",
"block",
... | 34.857143 | 13.857143 |
def separate_reach_logs(log_str):
"""Get the list of reach logs from the overall logs."""
log_lines = log_str.splitlines()
reach_logs = []
reach_lines = []
adding_reach_lines = False
for l in log_lines[:]:
if not adding_reach_lines and 'Beginning reach' in l:
adding_reach_lin... | [
"def",
"separate_reach_logs",
"(",
"log_str",
")",
":",
"log_lines",
"=",
"log_str",
".",
"splitlines",
"(",
")",
"reach_logs",
"=",
"[",
"]",
"reach_lines",
"=",
"[",
"]",
"adding_reach_lines",
"=",
"False",
"for",
"l",
"in",
"log_lines",
"[",
":",
"]",
... | 40.157895 | 12.210526 |
def database_caller_creator(self, number_of_rows, username, password, host, port, name=None, custom=None):
'''creates a postgresql db
returns the related connection object
which will be later used to spawn the cursor
'''
cursor = None
conn = None
if name:
... | [
"def",
"database_caller_creator",
"(",
"self",
",",
"number_of_rows",
",",
"username",
",",
"password",
",",
"host",
",",
"port",
",",
"name",
"=",
"None",
",",
"custom",
"=",
"None",
")",
":",
"cursor",
"=",
"None",
"conn",
"=",
"None",
"if",
"name",
... | 36 | 21.621622 |
def get_last_response_xml(self, pretty_print_if_possible=False):
"""
Retrieves the raw XML (decrypted) of the last SAML response,
or the last Logout Response generated or processed
:returns: SAML response XML
:rtype: string|None
"""
response = None
if sel... | [
"def",
"get_last_response_xml",
"(",
"self",
",",
"pretty_print_if_possible",
"=",
"False",
")",
":",
"response",
"=",
"None",
"if",
"self",
".",
"__last_response",
"is",
"not",
"None",
":",
"if",
"isinstance",
"(",
"self",
".",
"__last_response",
",",
"basest... | 38.933333 | 18.133333 |
def close(self, autocommit=True):
"""Close the consumer, waiting indefinitely for any needed cleanup.
Keyword Arguments:
autocommit (bool): If auto-commit is configured for this consumer,
this optional flag causes the consumer to attempt to commit any
pending... | [
"def",
"close",
"(",
"self",
",",
"autocommit",
"=",
"True",
")",
":",
"if",
"self",
".",
"_closed",
":",
"return",
"log",
".",
"debug",
"(",
"\"Closing the KafkaConsumer.\"",
")",
"self",
".",
"_closed",
"=",
"True",
"self",
".",
"_coordinator",
".",
"c... | 36.208333 | 17.541667 |
def anncluster(c, clus_obj, db, type_ann, feature_id="name"):
"""intersect transcription position with annotation files"""
id_sa, id_ea, id_id, id_idl, id_sta = 1, 2, 3, 4, 5
if type_ann == "bed":
id_sb = 7
id_eb = 8
id_stb = 11
id_tag = 9
ida = 0
clus_id = clus_obj.c... | [
"def",
"anncluster",
"(",
"c",
",",
"clus_obj",
",",
"db",
",",
"type_ann",
",",
"feature_id",
"=",
"\"name\"",
")",
":",
"id_sa",
",",
"id_ea",
",",
"id_id",
",",
"id_idl",
",",
"id_sta",
"=",
"1",
",",
"2",
",",
"3",
",",
"4",
",",
"5",
"if",
... | 35.302326 | 13.813953 |
def render(dson_input, saltenv='base', sls='', **kwargs):
'''
Accepts DSON data as a string or as a file object and runs it through the
JSON parser.
:rtype: A Python data structure
'''
if not isinstance(dson_input, six.string_types):
dson_input = dson_input.read()
log.debug('DSON i... | [
"def",
"render",
"(",
"dson_input",
",",
"saltenv",
"=",
"'base'",
",",
"sls",
"=",
"''",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"isinstance",
"(",
"dson_input",
",",
"six",
".",
"string_types",
")",
":",
"dson_input",
"=",
"dson_input",
".",
... | 29.941176 | 20.764706 |
def _initialize_progressbar(self):
"""
Initialize the progressbar.
:return: None
"""
self._progressbar = progressbar.ProgressBar(widgets=Analysis._PROGRESS_WIDGETS, maxval=10000 * 100).start() | [
"def",
"_initialize_progressbar",
"(",
"self",
")",
":",
"self",
".",
"_progressbar",
"=",
"progressbar",
".",
"ProgressBar",
"(",
"widgets",
"=",
"Analysis",
".",
"_PROGRESS_WIDGETS",
",",
"maxval",
"=",
"10000",
"*",
"100",
")",
".",
"start",
"(",
")"
] | 32.428571 | 20.714286 |
def extract_alphabet(alphabet, inputdata, fixed_start = False):
"""
Receives a sequence and an alphabet,
returns a list of PositionTokens with all of the parts of the sequence that
are a subset of the alphabet
"""
if not inputdata:
return []
base_alphabet = alphabet.alphabet
l... | [
"def",
"extract_alphabet",
"(",
"alphabet",
",",
"inputdata",
",",
"fixed_start",
"=",
"False",
")",
":",
"if",
"not",
"inputdata",
":",
"return",
"[",
"]",
"base_alphabet",
"=",
"alphabet",
".",
"alphabet",
"lexer",
"=",
"lexer_factory",
"(",
"alphabet",
",... | 32.354839 | 17.387097 |
def get_options(option_type, from_options):
"""Extract options for specified option type from all options
:param option_type: the object of specified type of options
:param from_options: all options dictionary
:return: the dictionary of options for specified type, each option can be filled by value fro... | [
"def",
"get_options",
"(",
"option_type",
",",
"from_options",
")",
":",
"_options",
"=",
"dict",
"(",
")",
"for",
"key",
"in",
"option_type",
".",
"keys",
":",
"key_with_prefix",
"=",
"f'{option_type.prefix}{key}'",
"if",
"key",
"not",
"in",
"from_options",
"... | 41.55 | 23.15 |
def count_single_dots(self):
"""Count all strokes of this recording that have only a single dot.
"""
pointlist = self.get_pointlist()
single_dots = 0
for stroke in pointlist:
if len(stroke) == 1:
single_dots += 1
return single_dots | [
"def",
"count_single_dots",
"(",
"self",
")",
":",
"pointlist",
"=",
"self",
".",
"get_pointlist",
"(",
")",
"single_dots",
"=",
"0",
"for",
"stroke",
"in",
"pointlist",
":",
"if",
"len",
"(",
"stroke",
")",
"==",
"1",
":",
"single_dots",
"+=",
"1",
"r... | 33.222222 | 7.444444 |
def Tethering_bind(self, port):
"""
Function path: Tethering.bind
Domain: Tethering
Method name: bind
Parameters:
Required arguments:
'port' (type: integer) -> Port number to bind.
No return value.
Description: Request browser port binding.
"""
assert isinstance(port, (int,)
... | [
"def",
"Tethering_bind",
"(",
"self",
",",
"port",
")",
":",
"assert",
"isinstance",
"(",
"port",
",",
"(",
"int",
",",
")",
")",
",",
"\"Argument 'port' must be of type '['int']'. Received type: '%s'\"",
"%",
"type",
"(",
"port",
")",
"subdom_funcs",
"=",
"self... | 26.833333 | 18.944444 |
def validate_args(args):
'''
Apply custom validation and actions based on parsed arguments.
Parameters
----------
args : argparse.Namespace
Result from ``parse_args`` method of ``argparse.ArgumentParser``
instance.
Returns
-------
argparse.Namespace
Reference to... | [
"def",
"validate_args",
"(",
"args",
")",
":",
"logging",
".",
"basicConfig",
"(",
"level",
"=",
"getattr",
"(",
"logging",
",",
"args",
".",
"log_level",
".",
"upper",
"(",
")",
")",
")",
"if",
"getattr",
"(",
"args",
",",
"'command'",
",",
"None",
... | 40.769231 | 23.435897 |
def _erase_display(self, value):
"""
Erases display.
"""
if value == 0:
# delete end of line
self._cursor.movePosition(self._cursor.End, self._cursor.KeepAnchor)
elif value == 1:
# delete start of line
self._cursor.movePosition(self... | [
"def",
"_erase_display",
"(",
"self",
",",
"value",
")",
":",
"if",
"value",
"==",
"0",
":",
"# delete end of line",
"self",
".",
"_cursor",
".",
"movePosition",
"(",
"self",
".",
"_cursor",
".",
"End",
",",
"self",
".",
"_cursor",
".",
"KeepAnchor",
")"... | 39.25 | 16.5 |
def last_event(self):
""" The mouse event immediately prior to this one. This
property is None when no mouse buttons are pressed.
"""
if self.mouse_event.last_event is None:
return None
ev = self.copy()
ev.mouse_event = self.mouse_event.last_event
retu... | [
"def",
"last_event",
"(",
"self",
")",
":",
"if",
"self",
".",
"mouse_event",
".",
"last_event",
"is",
"None",
":",
"return",
"None",
"ev",
"=",
"self",
".",
"copy",
"(",
")",
"ev",
".",
"mouse_event",
"=",
"self",
".",
"mouse_event",
".",
"last_event"... | 35.222222 | 12.555556 |
def value_to_jam(value, methods=False):
"""Makes a token to refer to a Python value inside Jam language code.
The token is merely a string that can be passed around in Jam code and
eventually passed back. For example, we might want to pass PropertySet
instance to a tag function and it might eventually ... | [
"def",
"value_to_jam",
"(",
"value",
",",
"methods",
"=",
"False",
")",
":",
"global",
"__value_id",
"r",
"=",
"__python_to_jam",
".",
"get",
"(",
"value",
",",
"None",
")",
"if",
"r",
":",
"return",
"r",
"exported_name",
"=",
"'###_'",
"+",
"str",
"("... | 35.882353 | 22.941176 |
def gfstep(time):
"""
Return the time step set by the most recent call to :func:`gfsstp`.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/gfstep_c.html
:param time: Ignored ET value.
:type time: float
:return: Time step to take.
:rtype: float
"""
time = ctypes.c_double(time... | [
"def",
"gfstep",
"(",
"time",
")",
":",
"time",
"=",
"ctypes",
".",
"c_double",
"(",
"time",
")",
"step",
"=",
"ctypes",
".",
"c_double",
"(",
")",
"libspice",
".",
"gfstep_c",
"(",
"time",
",",
"ctypes",
".",
"byref",
"(",
"step",
")",
")",
"retur... | 27.066667 | 18 |
def recommendations(self, **kwargs):
"""
Get a list of recommended movies for a movie.
Args:
language: (optional) ISO 639-1 code.
page: (optional) Minimum value of 1. Expected value is an integer.
Returns:
A dict representation of the JSON returned ... | [
"def",
"recommendations",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"path",
"=",
"self",
".",
"_get_id_path",
"(",
"'recommendations'",
")",
"response",
"=",
"self",
".",
"_GET",
"(",
"path",
",",
"kwargs",
")",
"self",
".",
"_set_attrs_to_values",
... | 30.875 | 18.5 |
def is_standalone(text, start, end):
"""check if the string text[start:end] is standalone by checking forwards
and backwards for blankspaces
:text: TODO
:(start, end): TODO
:returns: the start of next index after text[start:end]
"""
left = False
start -= 1
while start >= 0 and text[... | [
"def",
"is_standalone",
"(",
"text",
",",
"start",
",",
"end",
")",
":",
"left",
"=",
"False",
"start",
"-=",
"1",
"while",
"start",
">=",
"0",
"and",
"text",
"[",
"start",
"]",
"in",
"spaces_not_newline",
":",
"start",
"-=",
"1",
"if",
"start",
"<",... | 28.555556 | 18.222222 |
def _bracket_complete_sig(self, symbol, fullsymbol):
"""Returns the call signature and docstring for the executable
immediately preceding a bracket '(' that was typed."""
if symbol != fullsymbol:
#We have a sym%sym%... chain and the completion just needs to
#be the signat... | [
"def",
"_bracket_complete_sig",
"(",
"self",
",",
"symbol",
",",
"fullsymbol",
")",
":",
"if",
"symbol",
"!=",
"fullsymbol",
":",
"#We have a sym%sym%... chain and the completion just needs to",
"#be the signature of the member method.",
"target",
",",
"targmod",
"=",
"self... | 49.966667 | 16.7 |
def GetNotificationShard(self, queue):
"""Gets a single shard for a given queue."""
queue_name = str(queue)
QueueManager.notification_shard_counters.setdefault(queue_name, 0)
QueueManager.notification_shard_counters[queue_name] += 1
notification_shard_index = (
QueueManager.notification_shar... | [
"def",
"GetNotificationShard",
"(",
"self",
",",
"queue",
")",
":",
"queue_name",
"=",
"str",
"(",
"queue",
")",
"QueueManager",
".",
"notification_shard_counters",
".",
"setdefault",
"(",
"queue_name",
",",
"0",
")",
"QueueManager",
".",
"notification_shard_count... | 40.916667 | 14.083333 |
def get_embedded_tweet(tweet):
"""
Get the retweeted Tweet OR the quoted Tweet and return it as a dictionary
Args:
tweet (Tweet): A Tweet object (not simply a dict)
Returns:
dict (or None, if the Tweet is neither a quote tweet or a Retweet):
a dictionary representing the quote ... | [
"def",
"get_embedded_tweet",
"(",
"tweet",
")",
":",
"if",
"tweet",
".",
"retweeted_tweet",
"is",
"not",
"None",
":",
"return",
"tweet",
".",
"retweeted_tweet",
"elif",
"tweet",
".",
"quoted_tweet",
"is",
"not",
"None",
":",
"return",
"tweet",
".",
"quoted_t... | 30.352941 | 19.176471 |
def _CreatePerformanceTarget(client, campaign_group_id):
"""Creates a performance target for the campaign group.
Args:
client: an AdWordsClient instance.
campaign_group_id: an integer ID for the campaign group.
"""
# Get the CampaignGroupPerformanceTargetService.
cgpt_service = client.GetService('Cam... | [
"def",
"_CreatePerformanceTarget",
"(",
"client",
",",
"campaign_group_id",
")",
":",
"# Get the CampaignGroupPerformanceTargetService.",
"cgpt_service",
"=",
"client",
".",
"GetService",
"(",
"'CampaignGroupPerformanceTargetService'",
",",
"version",
"=",
"'v201809'",
")",
... | 37.418605 | 18.674419 |
def valuePasses(self, value):
'''Returns whether this value passes this filter'''
return self._conditional_cmp[self.op](value, self.value) | [
"def",
"valuePasses",
"(",
"self",
",",
"value",
")",
":",
"return",
"self",
".",
"_conditional_cmp",
"[",
"self",
".",
"op",
"]",
"(",
"value",
",",
"self",
".",
"value",
")"
] | 48 | 15.333333 |
def update_phase(self, environment, data, prediction, user, item, correct, time, answer_id, **kwargs):
"""
After the prediction update the environment and persist some
information for the predictive model.
Args:
environment (proso.models.environment.Environment):
... | [
"def",
"update_phase",
"(",
"self",
",",
"environment",
",",
"data",
",",
"prediction",
",",
"user",
",",
"item",
",",
"correct",
",",
"time",
",",
"answer_id",
",",
"*",
"*",
"kwargs",
")",
":",
"pass"
] | 37.944444 | 18.5 |
def find_link(self, *args, **kwargs):
"""Find and return a link, as a bs4.element.Tag object.
The search can be refined by specifying any argument that is accepted
by :func:`links`. If several links match, return the first one found.
If no link is found, raise :class:`LinkNotFoundError... | [
"def",
"find_link",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"links",
"=",
"self",
".",
"links",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"if",
"len",
"(",
"links",
")",
"==",
"0",
":",
"raise",
"LinkNotFoundError"... | 36.461538 | 18.307692 |
def _InitApiApprovalFromAff4Object(api_approval, approval_obj):
"""Initializes Api(Client|Hunt|CronJob)Approval from an AFF4 object."""
api_approval.id = approval_obj.urn.Basename()
api_approval.reason = approval_obj.Get(approval_obj.Schema.REASON)
api_approval.requestor = approval_obj.Get(approval_obj.Schema.... | [
"def",
"_InitApiApprovalFromAff4Object",
"(",
"api_approval",
",",
"approval_obj",
")",
":",
"api_approval",
".",
"id",
"=",
"approval_obj",
".",
"urn",
".",
"Basename",
"(",
")",
"api_approval",
".",
"reason",
"=",
"approval_obj",
".",
"Get",
"(",
"approval_obj... | 39.264706 | 21.117647 |
def in1d_sorted(ar1, ar2):
"""
Does the same than np.in1d but uses the fact that ar1 and ar2 are sorted. Is therefore much faster.
"""
if ar1.shape[0] == 0 or ar2.shape[0] == 0: # check for empty arrays to avoid crash
return []
inds = ar2.searchsorted(ar1)
inds[inds == len(ar2)] = 0
... | [
"def",
"in1d_sorted",
"(",
"ar1",
",",
"ar2",
")",
":",
"if",
"ar1",
".",
"shape",
"[",
"0",
"]",
"==",
"0",
"or",
"ar2",
".",
"shape",
"[",
"0",
"]",
"==",
"0",
":",
"# check for empty arrays to avoid crash",
"return",
"[",
"]",
"inds",
"=",
"ar2",
... | 33.6 | 21.8 |
def get_node(manager, handle_id, legacy=True):
"""
:param manager: Manager to handle sessions and transactions
:param handle_id: Unique id
:param legacy: Backwards compatibility
:type manager: norduniclient.contextmanager.Neo4jDBSessionManager
:type handle_id: str|unicode
:type legacy: Bool... | [
"def",
"get_node",
"(",
"manager",
",",
"handle_id",
",",
"legacy",
"=",
"True",
")",
":",
"q",
"=",
"'MATCH (n:Node { handle_id: {handle_id} }) RETURN n'",
"with",
"manager",
".",
"session",
"as",
"s",
":",
"result",
"=",
"s",
".",
"run",
"(",
"q",
",",
"... | 32.190476 | 15.904762 |
def deserialize_single_input_output(self, transformer, node_path, attributes_map=None):
"""
:attributes_map: Map of attributes names. For example StandardScaler has `mean_` but is serialized as `mean`
:param transformer: Scikit or Pandas transformer
:param node: bundle.ml node json file
... | [
"def",
"deserialize_single_input_output",
"(",
"self",
",",
"transformer",
",",
"node_path",
",",
"attributes_map",
"=",
"None",
")",
":",
"# Load the model file",
"with",
"open",
"(",
"\"{}/model.json\"",
".",
"format",
"(",
"node_path",
")",
")",
"as",
"json_dat... | 46.575758 | 25.181818 |
def convert(self, pedalboard_path, system_effect=None):
"""
:param Path pedalboard_path: Path that the pedalboard has been persisted.
Generally is in format `path/to/pedalboard/name.pedalboard`
:param SystemEffect system_effect: Effect that contains the audio... | [
"def",
"convert",
"(",
"self",
",",
"pedalboard_path",
",",
"system_effect",
"=",
"None",
")",
":",
"info",
"=",
"self",
".",
"get_pedalboard_info",
"(",
"pedalboard_path",
")",
"if",
"system_effect",
"is",
"None",
":",
"system_effect",
"=",
"self",
".",
"di... | 40.028571 | 24.314286 |
def scale_cb(self, setting, value):
"""Handle callback related to image scaling."""
zoomlevel = self.zoom.calc_level(value)
self.t_.set(zoomlevel=zoomlevel)
self.redraw(whence=0) | [
"def",
"scale_cb",
"(",
"self",
",",
"setting",
",",
"value",
")",
":",
"zoomlevel",
"=",
"self",
".",
"zoom",
".",
"calc_level",
"(",
"value",
")",
"self",
".",
"t_",
".",
"set",
"(",
"zoomlevel",
"=",
"zoomlevel",
")",
"self",
".",
"redraw",
"(",
... | 34.333333 | 10.5 |
def add_redistribution(self, protocol, route_map_name=None):
"""Adds a protocol redistribution to OSPF
Args:
protocol (str): protocol to redistribute
route_map_name (str): route-map to be used to
filter the protocols
Retu... | [
"def",
"add_redistribution",
"(",
"self",
",",
"protocol",
",",
"route_map_name",
"=",
"None",
")",
":",
"protocols",
"=",
"[",
"'bgp'",
",",
"'rip'",
",",
"'static'",
",",
"'connected'",
"]",
"if",
"protocol",
"not",
"in",
"protocols",
":",
"raise",
"Valu... | 45.913043 | 19.043478 |
def make_headers(headers):
""" Make the cache control headers based on a previous request's
response headers
"""
out = {}
if 'etag' in headers:
out['if-none-match'] = headers['etag']
if 'last-modified' in headers:
out['if-modified-since'] = headers['last-modified']
return out | [
"def",
"make_headers",
"(",
"headers",
")",
":",
"out",
"=",
"{",
"}",
"if",
"'etag'",
"in",
"headers",
":",
"out",
"[",
"'if-none-match'",
"]",
"=",
"headers",
"[",
"'etag'",
"]",
"if",
"'last-modified'",
"in",
"headers",
":",
"out",
"[",
"'if-modified-... | 31.1 | 13.4 |
def load_data(path_dir):
'''Load data, directory parameters, and accelerometer parameter names
Args
----
path_dir: str
Path to the data directory
Returns
-------
data: pandas.DataFrame
Experiment data
params_tag: dict
A dictionary of parameters parsed from the d... | [
"def",
"load_data",
"(",
"path_dir",
")",
":",
"import",
"os",
"import",
"pylleo",
"exp_name",
"=",
"os",
".",
"path",
".",
"split",
"(",
"path_dir",
")",
"[",
"1",
"]",
"params_tag",
"=",
"pylleo",
".",
"utils",
".",
"parse_experiment_params",
"(",
"exp... | 31.588235 | 24.588235 |
def getworker():
'''
return settings dictionnary
'''
if not Configuration.worker_initialized:
Configuration._initconf()
Configuration.worker_settings = Configuration.settings['worker']
Configuration.worker_initialized = True
return Configuratio... | [
"def",
"getworker",
"(",
")",
":",
"if",
"not",
"Configuration",
".",
"worker_initialized",
":",
"Configuration",
".",
"_initconf",
"(",
")",
"Configuration",
".",
"worker_settings",
"=",
"Configuration",
".",
"settings",
"[",
"'worker'",
"]",
"Configuration",
"... | 36.555556 | 16.555556 |
def _reads_in_peaks(bam_file, peaks_file, sample):
"""Calculate number of reads in peaks"""
if not peaks_file:
return {}
rip = number_of_mapped_reads(sample, bam_file, bed_file = peaks_file)
return {"metrics": {"RiP": rip}} | [
"def",
"_reads_in_peaks",
"(",
"bam_file",
",",
"peaks_file",
",",
"sample",
")",
":",
"if",
"not",
"peaks_file",
":",
"return",
"{",
"}",
"rip",
"=",
"number_of_mapped_reads",
"(",
"sample",
",",
"bam_file",
",",
"bed_file",
"=",
"peaks_file",
")",
"return"... | 40.333333 | 14.666667 |
def _parse_doc(docs):
"""
Converts a well-formed docstring into documentation
to be fed into argparse.
See signature_parser for details.
shorts: (-k for --keyword -k, or "from" for "frm/from")
metavars: (FILE for --input=FILE)
helps: (docs for --keyword: docs)
... | [
"def",
"_parse_doc",
"(",
"docs",
")",
":",
"name",
"=",
"\"(?:[a-zA-Z][a-zA-Z0-9-_]*)\"",
"re_var",
"=",
"re",
".",
"compile",
"(",
"r\"^ *(%s)(?: */(%s))? *:(.*)$\"",
"%",
"(",
"name",
",",
"name",
")",
")",
"re_opt",
"=",
"re",
".",
"compile",
"(",
"r\"^ ... | 28.853659 | 18.609756 |
def run(self, debug=False, reload=None):
"""
Convenience method for running bots in getUpdates mode
:param bool debug: Enable debug logging and automatic reloading
:param bool reload: Automatically reload bot on code change
:Example:
>>> if __name__ == '__main__':
... | [
"def",
"run",
"(",
"self",
",",
"debug",
"=",
"False",
",",
"reload",
"=",
"None",
")",
":",
"loop",
"=",
"asyncio",
".",
"get_event_loop",
"(",
")",
"logging",
".",
"basicConfig",
"(",
"level",
"=",
"logging",
".",
"DEBUG",
"if",
"debug",
"else",
"l... | 26.285714 | 22.095238 |
def fetch_github_token(self):
"""
Fetch GitHub token. First try to use variable provided
by --token option, otherwise try to fetch it from git config
and last CHANGELOG_GITHUB_TOKEN env variable.
:returns: Nothing
"""
if not self.options.token:
try:
... | [
"def",
"fetch_github_token",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"options",
".",
"token",
":",
"try",
":",
"for",
"v",
"in",
"GH_CFG_VARS",
":",
"cmd",
"=",
"[",
"'git'",
",",
"'config'",
",",
"'--get'",
",",
"'{0}'",
".",
"format",
"(",... | 38.304348 | 17 |
def input_from_cons(constupl, datas):
' solve bytes in |datas| based on '
def make_chr(c):
try:
return chr(c)
except Exception:
return c
newset = constraints_to_constraintset(constupl)
ret = ''
for data in datas:
for c in data:
ret += make... | [
"def",
"input_from_cons",
"(",
"constupl",
",",
"datas",
")",
":",
"def",
"make_chr",
"(",
"c",
")",
":",
"try",
":",
"return",
"chr",
"(",
"c",
")",
"except",
"Exception",
":",
"return",
"c",
"newset",
"=",
"constraints_to_constraintset",
"(",
"constupl",... | 25.357143 | 18.5 |
def run(self, action):
"""
Runs through the phases defined by :attr:`action`.
:param str action: Either ``deploy`` or ``inventory``.
"""
deployer = self.__class__.__name__
log.info('Running %s...' % deployer)
try:
if action == 'deploy':
... | [
"def",
"run",
"(",
"self",
",",
"action",
")",
":",
"deployer",
"=",
"self",
".",
"__class__",
".",
"__name__",
"log",
".",
"info",
"(",
"'Running %s...'",
"%",
"deployer",
")",
"try",
":",
"if",
"action",
"==",
"'deploy'",
":",
"self",
".",
"deploy",
... | 28.388889 | 13.944444 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.