text stringlengths 75 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 0.18 |
|---|---|---|---|
def nodeDumpOutput(self, buf, cur, level, format, encoding):
"""Dump an XML node, recursive behaviour, children are printed
too. Note that @format = 1 provide node indenting only if
xmlIndentTreeOutput = 1 or xmlKeepBlanksDefault(0) was
called """
if buf is None: buf__o = ... | [
"def",
"nodeDumpOutput",
"(",
"self",
",",
"buf",
",",
"cur",
",",
"level",
",",
"format",
",",
"encoding",
")",
":",
"if",
"buf",
"is",
"None",
":",
"buf__o",
"=",
"None",
"else",
":",
"buf__o",
"=",
"buf",
".",
"_o",
"if",
"cur",
"is",
"None",
... | 50 | 0.013752 |
def service(ctx):
"""Install systemd service configuration"""
install_service(ctx.obj['instance'], ctx.obj['dbhost'], ctx.obj['dbname'], ctx.obj['port']) | [
"def",
"service",
"(",
"ctx",
")",
":",
"install_service",
"(",
"ctx",
".",
"obj",
"[",
"'instance'",
"]",
",",
"ctx",
".",
"obj",
"[",
"'dbhost'",
"]",
",",
"ctx",
".",
"obj",
"[",
"'dbname'",
"]",
",",
"ctx",
".",
"obj",
"[",
"'port'",
"]",
")"... | 39.75 | 0.012346 |
async def minizinc(
mzn, *dzn_files, args=None, data=None, include=None, stdlib_dir=None,
globals_dir=None, declare_enums=True, allow_multiple_assignments=False,
keep=False, output_vars=None, output_base=None, output_mode='dict',
solver=None, timeout=None, two_pass=None, pre_passes=None,
output_obje... | [
"async",
"def",
"minizinc",
"(",
"mzn",
",",
"*",
"dzn_files",
",",
"args",
"=",
"None",
",",
"data",
"=",
"None",
",",
"include",
"=",
"None",
",",
"stdlib_dir",
"=",
"None",
",",
"globals_dir",
"=",
"None",
",",
"declare_enums",
"=",
"True",
",",
"... | 43.731343 | 0.001335 |
def oracle_grover(oracle: Program, qubits: List[int], num_iter: int = None) -> Program:
"""
Implementation of Grover's Algorithm for a given oracle.
:param oracle: An oracle defined as a Program. It should send :math:`\ket{x}`
to :math:`(-1)^{f(x)}\ket{x}`, where the range of f is {... | [
"def",
"oracle_grover",
"(",
"oracle",
":",
"Program",
",",
"qubits",
":",
"List",
"[",
"int",
"]",
",",
"num_iter",
":",
"int",
"=",
"None",
")",
"->",
"Program",
":",
"if",
"num_iter",
"is",
"None",
":",
"num_iter",
"=",
"int",
"(",
"round",
"(",
... | 59.235294 | 0.010753 |
def draw_hydrogen_bonds(self,color="black"):
"""For each bond that has been determined to be important, a line gets drawn.
"""
self.draw_hbonds=""
if self.hbonds!=None:
for bond in self.hbonds.hbonds_for_drawing:
x = str((self.molecule.x_dim-self.molecule.molsize1)/2)
y = str((self.molecule.y_dim-sel... | [
"def",
"draw_hydrogen_bonds",
"(",
"self",
",",
"color",
"=",
"\"black\"",
")",
":",
"self",
".",
"draw_hbonds",
"=",
"\"\"",
"if",
"self",
".",
"hbonds",
"!=",
"None",
":",
"for",
"bond",
"in",
"self",
".",
"hbonds",
".",
"hbonds_for_drawing",
":",
"x",... | 120.2 | 0.017747 |
async def _on_push_data(self, data_bytes):
"""Parse push data and trigger events."""
logger.debug('Received chunk:\n{}'.format(data_bytes))
for chunk in self._chunk_parser.get_chunks(data_bytes):
# Consider the channel connected once the first chunk is received.
if not s... | [
"async",
"def",
"_on_push_data",
"(",
"self",
",",
"data_bytes",
")",
":",
"logger",
".",
"debug",
"(",
"'Received chunk:\\n{}'",
".",
"format",
"(",
"data_bytes",
")",
")",
"for",
"chunk",
"in",
"self",
".",
"_chunk_parser",
".",
"get_chunks",
"(",
"data_by... | 46.84 | 0.001674 |
def conference_kick(self, call_params):
"""REST Conference Kick helper
"""
path = '/' + self.api_version + '/ConferenceKick/'
method = 'POST'
return self.request(path, method, call_params) | [
"def",
"conference_kick",
"(",
"self",
",",
"call_params",
")",
":",
"path",
"=",
"'/'",
"+",
"self",
".",
"api_version",
"+",
"'/ConferenceKick/'",
"method",
"=",
"'POST'",
"return",
"self",
".",
"request",
"(",
"path",
",",
"method",
",",
"call_params",
... | 37.166667 | 0.008772 |
def greedy_merge(
variant_sequences,
min_overlap_size=MIN_VARIANT_SEQUENCE_ASSEMBLY_OVERLAP_SIZE):
"""
Greedily merge overlapping sequences into longer sequences.
Accepts a collection of VariantSequence objects and returns another
collection of elongated variant sequences. The reads fie... | [
"def",
"greedy_merge",
"(",
"variant_sequences",
",",
"min_overlap_size",
"=",
"MIN_VARIANT_SEQUENCE_ASSEMBLY_OVERLAP_SIZE",
")",
":",
"merged_any",
"=",
"True",
"while",
"merged_any",
":",
"variant_sequences",
",",
"merged_any",
"=",
"greedy_merge_helper",
"(",
"variant_... | 37.647059 | 0.001524 |
def knapsack(items, maxweight, method='recursive'):
r"""
Solve the knapsack problem by finding the most valuable subsequence of
`items` subject that weighs no more than `maxweight`.
Args:
items (tuple): is a sequence of tuples `(value, weight, id_)`, where
`value` is a number and `w... | [
"def",
"knapsack",
"(",
"items",
",",
"maxweight",
",",
"method",
"=",
"'recursive'",
")",
":",
"if",
"method",
"==",
"'recursive'",
":",
"return",
"knapsack_recursive",
"(",
"items",
",",
"maxweight",
")",
"elif",
"method",
"==",
"'iterative'",
":",
"return... | 45.798658 | 0.000143 |
def set_owner(obj_name, principal, obj_type='file'):
'''
Set the owner of an object. This can be a file, folder, registry key,
printer, service, etc...
Args:
obj_name (str):
The object for which to set owner. This can be the path to a file or
folder, a registry key, pri... | [
"def",
"set_owner",
"(",
"obj_name",
",",
"principal",
",",
"obj_type",
"=",
"'file'",
")",
":",
"sid",
"=",
"get_sid",
"(",
"principal",
")",
"obj_flags",
"=",
"flags",
"(",
")",
"# Validate obj_type",
"if",
"obj_type",
".",
"lower",
"(",
")",
"not",
"i... | 32.546667 | 0.001193 |
def job_count_enabled(self):
"""
Return the number of enabled jobs.
:return: The number of jobs that are enabled.
:rtype: int
"""
enabled = 0
for job_desc in self._jobs.values():
if job_desc['enabled']:
enabled += 1
return enabled | [
"def",
"job_count_enabled",
"(",
"self",
")",
":",
"enabled",
"=",
"0",
"for",
"job_desc",
"in",
"self",
".",
"_jobs",
".",
"values",
"(",
")",
":",
"if",
"job_desc",
"[",
"'enabled'",
"]",
":",
"enabled",
"+=",
"1",
"return",
"enabled"
] | 20.25 | 0.047244 |
def _get_struct_fillstyle(self, shape_number):
"""Get the values for the FILLSTYLE record."""
obj = _make_object("FillStyle")
obj.FillStyleType = style_type = unpack_ui8(self._src)
if style_type == 0x00:
if shape_number <= 2:
obj.Color = self._get_struct_rgb(... | [
"def",
"_get_struct_fillstyle",
"(",
"self",
",",
"shape_number",
")",
":",
"obj",
"=",
"_make_object",
"(",
"\"FillStyle\"",
")",
"obj",
".",
"FillStyleType",
"=",
"style_type",
"=",
"unpack_ui8",
"(",
"self",
".",
"_src",
")",
"if",
"style_type",
"==",
"0x... | 37.478261 | 0.002262 |
def extract_common(self, keys):
"""
Return a new segmentlistdict containing only those
segmentlists associated with the keys in keys, with each
set to their mutual intersection. The offsets are
preserved.
"""
keys = set(keys)
new = self.__class__()
intersection = self.intersection(keys)
for key in ... | [
"def",
"extract_common",
"(",
"self",
",",
"keys",
")",
":",
"keys",
"=",
"set",
"(",
"keys",
")",
"new",
"=",
"self",
".",
"__class__",
"(",
")",
"intersection",
"=",
"self",
".",
"intersection",
"(",
"keys",
")",
"for",
"key",
"in",
"keys",
":",
... | 31.428571 | 0.033113 |
def inside(self, other):
""" Return true if this rectangle is inside the given shape. """
return ( self.left >= other.left and
self.right <= other.right and
self.top <= other.top and
self.bottom >= other.bottom) | [
"def",
"inside",
"(",
"self",
",",
"other",
")",
":",
"return",
"(",
"self",
".",
"left",
">=",
"other",
".",
"left",
"and",
"self",
".",
"right",
"<=",
"other",
".",
"right",
"and",
"self",
".",
"top",
"<=",
"other",
".",
"top",
"and",
"self",
"... | 45.5 | 0.010791 |
def _output(calls, args):
"""
Outputs `calls`.
:param calls: List of :class:`_PyconfigCall` instances
:param args: :class:`~argparse.ArgumentParser` instance
:type calls: list
:type args: argparse.ArgumentParser
"""
# Sort the keys appropriately
if args.natural_sort or args.source:... | [
"def",
"_output",
"(",
"calls",
",",
"args",
")",
":",
"# Sort the keys appropriately",
"if",
"args",
".",
"natural_sort",
"or",
"args",
".",
"source",
":",
"calls",
"=",
"sorted",
"(",
"calls",
",",
"key",
"=",
"lambda",
"c",
":",
"(",
"c",
".",
"file... | 26.098039 | 0.000724 |
def parse_get(prs, conn):
"""Retrieve records.
Arguments:
prs: parser object of argparse
conn: dictionary of connection information
"""
prs_get = prs.add_parser(
'get', help='retrieve all zones or records with a specific zone')
prs_get.add_argument('--domain', action='stor... | [
"def",
"parse_get",
"(",
"prs",
",",
"conn",
")",
":",
"prs_get",
"=",
"prs",
".",
"add_parser",
"(",
"'get'",
",",
"help",
"=",
"'retrieve all zones or records with a specific zone'",
")",
"prs_get",
".",
"add_argument",
"(",
"'--domain'",
",",
"action",
"=",
... | 30.866667 | 0.002096 |
def watch_instances(self, flag):
"""Whether or not the Class Instances are being watched."""
lib.EnvSetDefclassWatchInstances(self._env, int(flag), self._cls) | [
"def",
"watch_instances",
"(",
"self",
",",
"flag",
")",
":",
"lib",
".",
"EnvSetDefclassWatchInstances",
"(",
"self",
".",
"_env",
",",
"int",
"(",
"flag",
")",
",",
"self",
".",
"_cls",
")"
] | 57.333333 | 0.011494 |
def Extract_Checkpoints(self):
'''
Extract the checkpoints and store in self.tracking_data
'''
# Make sure page is available
if self.page is None:
raise Exception("The HTML data was not fetched due to some reasons")
# Check for invalid tracking number
if 'Invalid number / data not currently availabl... | [
"def",
"Extract_Checkpoints",
"(",
"self",
")",
":",
"# Make sure page is available",
"if",
"self",
".",
"page",
"is",
"None",
":",
"raise",
"Exception",
"(",
"\"The HTML data was not fetched due to some reasons\"",
")",
"# Check for invalid tracking number",
"if",
"'Invali... | 36.041667 | 0.036579 |
def fetch(self, key: object, default=None):
""" Retrieves the related value from the stored user data. """
return self._user_data.get(key, default) | [
"def",
"fetch",
"(",
"self",
",",
"key",
":",
"object",
",",
"default",
"=",
"None",
")",
":",
"return",
"self",
".",
"_user_data",
".",
"get",
"(",
"key",
",",
"default",
")"
] | 54.333333 | 0.012121 |
def get_task_data(self, chemsys_formula_id, prop=""):
"""
Flexible method to get any data using the Materials Project REST
interface. Generally used by other methods for more specific queries.
Unlike the :func:`get_data`_, this method queries the task collection
for specific run ... | [
"def",
"get_task_data",
"(",
"self",
",",
"chemsys_formula_id",
",",
"prop",
"=",
"\"\"",
")",
":",
"sub_url",
"=",
"\"/tasks/%s\"",
"%",
"chemsys_formula_id",
"if",
"prop",
":",
"sub_url",
"+=",
"\"/\"",
"+",
"prop",
"return",
"self",
".",
"_make_request",
... | 45.608696 | 0.001867 |
def is_vertex_coloring(G, coloring):
"""Determines whether the given coloring is a vertex coloring of graph G.
Parameters
----------
G : NetworkX graph
The graph on which the vertex coloring is applied.
coloring : dict
A coloring of the nodes of G. Should be a dict of the form
... | [
"def",
"is_vertex_coloring",
"(",
"G",
",",
"coloring",
")",
":",
"return",
"all",
"(",
"coloring",
"[",
"u",
"]",
"!=",
"coloring",
"[",
"v",
"]",
"for",
"u",
",",
"v",
"in",
"G",
".",
"edges",
")"
] | 31.571429 | 0.001756 |
def sliding_impl(wrap, size, step, sequence):
"""
Implementation for sliding_t
:param wrap: wrap children values with this
:param size: size of window
:param step: step size
:param sequence: sequence to create sliding windows from
:return: sequence of sliding windows
"""
i = 0
n ... | [
"def",
"sliding_impl",
"(",
"wrap",
",",
"size",
",",
"step",
",",
"sequence",
")",
":",
"i",
"=",
"0",
"n",
"=",
"len",
"(",
"sequence",
")",
"while",
"i",
"+",
"size",
"<=",
"n",
"or",
"(",
"step",
"!=",
"1",
"and",
"i",
"<",
"n",
")",
":",... | 30.857143 | 0.002247 |
async def start(self, rtfromfile=False):
"""Start RT from file. You need to be in control of QTM to be able to do this.
"""
cmd = "start" + (" rtfromfile" if rtfromfile else "")
return await asyncio.wait_for(
self._protocol.send_command(cmd), timeout=self._timeout
) | [
"async",
"def",
"start",
"(",
"self",
",",
"rtfromfile",
"=",
"False",
")",
":",
"cmd",
"=",
"\"start\"",
"+",
"(",
"\" rtfromfile\"",
"if",
"rtfromfile",
"else",
"\"\"",
")",
"return",
"await",
"asyncio",
".",
"wait_for",
"(",
"self",
".",
"_protocol",
... | 44.571429 | 0.009434 |
def pages(self, limit=0):
"""Return iterator for pages"""
if limit > 0:
self.iterator.limit = limit
return self.iterator | [
"def",
"pages",
"(",
"self",
",",
"limit",
"=",
"0",
")",
":",
"if",
"limit",
">",
"0",
":",
"self",
".",
"iterator",
".",
"limit",
"=",
"limit",
"return",
"self",
".",
"iterator"
] | 30.4 | 0.012821 |
def HH(n):
"""constructs the HH context"""
if (n<=0):return Context('1')
else:
LL1=LL(n-1)
HH1=HH(n-1)
r1 = C1(3**(n-1),2**(n-1)) - LL1 - HH1
r2 = HH1 - HH1 - HH1
return r1 + r2 | [
"def",
"HH",
"(",
"n",
")",
":",
"if",
"(",
"n",
"<=",
"0",
")",
":",
"return",
"Context",
"(",
"'1'",
")",
"else",
":",
"LL1",
"=",
"LL",
"(",
"n",
"-",
"1",
")",
"HH1",
"=",
"HH",
"(",
"n",
"-",
"1",
")",
"r1",
"=",
"C1",
"(",
"3",
... | 24.555556 | 0.030568 |
def reset(cls, *args, **kwargs):
"""Undo call to prepare, useful for testing."""
cls.local.tchannel = None
cls.args = None
cls.kwargs = None
cls.prepared = False | [
"def",
"reset",
"(",
"cls",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"cls",
".",
"local",
".",
"tchannel",
"=",
"None",
"cls",
".",
"args",
"=",
"None",
"cls",
".",
"kwargs",
"=",
"None",
"cls",
".",
"prepared",
"=",
"False"
] | 32.666667 | 0.00995 |
def addText(self, text, width=None):
"""
Adds a simple text item to this group.
:param text | <str>
maximumWidth | <float> || None
maximumHeight | <float> || None
"""
item = QtGui.QGraphicsTextItem()
... | [
"def",
"addText",
"(",
"self",
",",
"text",
",",
"width",
"=",
"None",
")",
":",
"item",
"=",
"QtGui",
".",
"QGraphicsTextItem",
"(",
")",
"font",
"=",
"item",
".",
"font",
"(",
")",
"font",
".",
"setFamily",
"(",
"'Arial'",
")",
"font",
".",
"setP... | 29 | 0.009736 |
def on_widget__button_release_event(self, widget, event):
'''
Called when any mouse button is released.
.. versionchanged:: 0.11.3
Always reset pending route, regardless of whether a route was
completed. This includes a) removing temporary routes from routes
... | [
"def",
"on_widget__button_release_event",
"(",
"self",
",",
"widget",
",",
"event",
")",
":",
"event",
"=",
"event",
".",
"copy",
"(",
")",
"if",
"self",
".",
"mode",
"==",
"'register_video'",
"and",
"(",
"event",
".",
"button",
"==",
"1",
"and",
"self",... | 50.877193 | 0.001691 |
def get_probs(self, x, **kwargs):
"""
:param x: A symbolic representation (Tensor) of the network input
:return: A symbolic representation (Tensor) of the output
probabilities (i.e., the output values produced by the softmax layer).
"""
d = self.fprop(x, **kwargs)
if self.O_PROBS in d:
... | [
"def",
"get_probs",
"(",
"self",
",",
"x",
",",
"*",
"*",
"kwargs",
")",
":",
"d",
"=",
"self",
".",
"fprop",
"(",
"x",
",",
"*",
"*",
"kwargs",
")",
"if",
"self",
".",
"O_PROBS",
"in",
"d",
":",
"output",
"=",
"d",
"[",
"self",
".",
"O_PROBS... | 41.454545 | 0.009646 |
def randomEarlyShared(store, role):
"""
If there are no explicitly-published public index pages to display, find a
shared item to present to the user as first.
"""
for r in role.allRoles():
share = store.findFirst(Share, Share.sharedTo == r,
sort=Share.storeID... | [
"def",
"randomEarlyShared",
"(",
"store",
",",
"role",
")",
":",
"for",
"r",
"in",
"role",
".",
"allRoles",
"(",
")",
":",
"share",
"=",
"store",
".",
"findFirst",
"(",
"Share",
",",
"Share",
".",
"sharedTo",
"==",
"r",
",",
"sort",
"=",
"Share",
"... | 41.636364 | 0.002137 |
def setImageMode(self):
""" Extracts color ordering and 24 vs. 32 bpp info out of the pixel format information
"""
if self._version_server == 3.889:
self.setPixelFormat(
bpp = 16, depth = 16, bigendian = 0, truecolor = 1,
redmax = 31, greenmax ... | [
"def",
"setImageMode",
"(",
"self",
")",
":",
"if",
"self",
".",
"_version_server",
"==",
"3.889",
":",
"self",
".",
"setPixelFormat",
"(",
"bpp",
"=",
"16",
",",
"depth",
"=",
"16",
",",
"bigendian",
"=",
"0",
",",
"truecolor",
"=",
"1",
",",
"redma... | 46.7 | 0.026233 |
def parse_list_multipart_uploads(data, bucket_name):
"""
Parser for list multipart uploads response.
:param data: Response data for list multipart uploads.
:param bucket_name: Response for the bucket.
:return: Replies back four distinctive components.
- List of :class:`IncompleteUpload <Inco... | [
"def",
"parse_list_multipart_uploads",
"(",
"data",
",",
"bucket_name",
")",
":",
"root",
"=",
"S3Element",
".",
"fromstring",
"(",
"'ListMultipartUploadsResult'",
",",
"data",
")",
"is_truncated",
"=",
"root",
".",
"get_child_text",
"(",
"'IsTruncated'",
")",
"."... | 43.461538 | 0.000866 |
def locate_path(dname, recurse_down=True):
""" Search for a path """
tried_fpaths = []
root_dir = os.getcwd()
while root_dir is not None:
dpath = join(root_dir, dname)
if exists(dpath):
return dpath
else:
tried_fpaths.append(dpath)
_new_root = dirn... | [
"def",
"locate_path",
"(",
"dname",
",",
"recurse_down",
"=",
"True",
")",
":",
"tried_fpaths",
"=",
"[",
"]",
"root_dir",
"=",
"os",
".",
"getcwd",
"(",
")",
"while",
"root_dir",
"is",
"not",
"None",
":",
"dpath",
"=",
"join",
"(",
"root_dir",
",",
... | 28.590909 | 0.001538 |
def register_model(self, *fields, **kw):
"""Registers a single model for fulltext search. This basically creates
a simple PonyWhoosh.Index for the model and calls self.register_index on it.
Args:
*fields: all the fields indexed from the model.
**kw: The options for each field, sortedby, sto... | [
"def",
"register_model",
"(",
"self",
",",
"*",
"fields",
",",
"*",
"*",
"kw",
")",
":",
"index",
"=",
"PonyWhooshIndex",
"(",
"pw",
"=",
"self",
")",
"index",
".",
"_kw",
"=",
"kw",
"index",
".",
"_fields",
"=",
"fields",
"def",
"inner",
"(",
"mod... | 31.938931 | 0.012286 |
def _poll_vq_single(self, dname, use_devmode, ddresp):
"""
Initiate a view query for a view located in a design document
:param ddresp: The design document to poll (as JSON)
:return: True if successful, False if no views.
"""
vname = None
query = None
v_mr... | [
"def",
"_poll_vq_single",
"(",
"self",
",",
"dname",
",",
"use_devmode",
",",
"ddresp",
")",
":",
"vname",
"=",
"None",
"query",
"=",
"None",
"v_mr",
"=",
"ddresp",
".",
"get",
"(",
"'views'",
",",
"{",
"}",
")",
"v_spatial",
"=",
"ddresp",
".",
"get... | 30.296296 | 0.00237 |
def _report_volume_count(self):
"""Report volume count per state (dangling or not)"""
m_func = FUNC_MAP[GAUGE][self.use_histogram]
attached_volumes = self.docker_util.client.volumes(filters={'dangling': False})
dangling_volumes = self.docker_util.client.volumes(filters={'dangling': True... | [
"def",
"_report_volume_count",
"(",
"self",
")",
":",
"m_func",
"=",
"FUNC_MAP",
"[",
"GAUGE",
"]",
"[",
"self",
".",
"use_histogram",
"]",
"attached_volumes",
"=",
"self",
".",
"docker_util",
".",
"client",
".",
"volumes",
"(",
"filters",
"=",
"{",
"'dang... | 64.1 | 0.009231 |
def getSpec(cls):
"""
Overrides :meth:`~nupic.bindings.regions.PyRegion.PyRegion.getSpec`.
The parameters collection is constructed based on the parameters specified
by the various components (spatialSpec, temporalSpec and otherSpec)
"""
spec = cls.getBaseSpec()
t, o = _getAdditionalSpecs(t... | [
"def",
"getSpec",
"(",
"cls",
")",
":",
"spec",
"=",
"cls",
".",
"getBaseSpec",
"(",
")",
"t",
",",
"o",
"=",
"_getAdditionalSpecs",
"(",
"temporalImp",
"=",
"gDefaultTemporalImp",
")",
"spec",
"[",
"'parameters'",
"]",
".",
"update",
"(",
"t",
")",
"s... | 32.461538 | 0.002304 |
def wwln_to_geopandas(file):
"""Read data from Blitzorg first using pandas.read_csv for convienence, and
then convert lat, lon points to a shaleply geometry POINT type.
Finally put this gemoetry into a geopandas dataframe and return it."""
tmp = pd.read_csv(file, parse_dates=True, header=None,
... | [
"def",
"wwln_to_geopandas",
"(",
"file",
")",
":",
"tmp",
"=",
"pd",
".",
"read_csv",
"(",
"file",
",",
"parse_dates",
"=",
"True",
",",
"header",
"=",
"None",
",",
"names",
"=",
"[",
"'date'",
",",
"'time'",
",",
"'lat'",
",",
"'lon'",
",",
"'err'",... | 55.75 | 0.001471 |
def building_name(self):
"""
:example 김구아파트
"""
pattern = self.random_element(self.building_name_formats)
return self.generator.parse(pattern) | [
"def",
"building_name",
"(",
"self",
")",
":",
"pattern",
"=",
"self",
".",
"random_element",
"(",
"self",
".",
"building_name_formats",
")",
"return",
"self",
".",
"generator",
".",
"parse",
"(",
"pattern",
")"
] | 29.5 | 0.010989 |
def parse_log(log, context_size=3):
"""Parses latex log output and tries to extract error messages.
Requires ``-file-line-error`` to be active.
:param log: The contents of the logfile as a string.
:param context_size: Number of lines to keep as context, including the
original ... | [
"def",
"parse_log",
"(",
"log",
",",
"context_size",
"=",
"3",
")",
":",
"lines",
"=",
"log",
".",
"splitlines",
"(",
")",
"errors",
"=",
"[",
"]",
"for",
"n",
",",
"line",
"in",
"enumerate",
"(",
"lines",
")",
":",
"m",
"=",
"LATEX_ERR_RE",
".",
... | 35.892857 | 0.000969 |
def VOICE(input_shape,
conv_layers,
dense_layers,
output_layer=[1, 'sigmoid'],
padding='same',
optimizer='adam',
loss='binary_crossentropy'):
"""Conv1D CNN used primarily for voice data.
Args:
input_shape (tuple): The shape of the i... | [
"def",
"VOICE",
"(",
"input_shape",
",",
"conv_layers",
",",
"dense_layers",
",",
"output_layer",
"=",
"[",
"1",
",",
"'sigmoid'",
"]",
",",
"padding",
"=",
"'same'",
",",
"optimizer",
"=",
"'adam'",
",",
"loss",
"=",
"'binary_crossentropy'",
")",
":",
"in... | 35.510638 | 0.011079 |
def value(self):
""" Returns the node's value. """
if self.is_multi_select():
return [opt.value()
for opt in self.xpath(".//option")
if opt["selected"]]
else:
return self._invoke("value") | [
"def",
"value",
"(",
"self",
")",
":",
"if",
"self",
".",
"is_multi_select",
"(",
")",
":",
"return",
"[",
"opt",
".",
"value",
"(",
")",
"for",
"opt",
"in",
"self",
".",
"xpath",
"(",
"\".//option\"",
")",
"if",
"opt",
"[",
"\"selected\"",
"]",
"]... | 29 | 0.012552 |
def init(self, **settings):
"""Initialize cluster."""
if self.get_status() != 'not-initialized':
raise ClusterError(
'cluster in {!r} has already been initialized'.format(
self._data_dir))
process = subprocess.run(
[self._pg_basebackup... | [
"def",
"init",
"(",
"self",
",",
"*",
"*",
"settings",
")",
":",
"if",
"self",
".",
"get_status",
"(",
")",
"!=",
"'not-initialized'",
":",
"raise",
"ClusterError",
"(",
"'cluster in {!r} has already been initialized'",
".",
"format",
"(",
"self",
".",
"_data_... | 37.5 | 0.001733 |
def copy(self):
"""Make a deep copy of this object.
Example::
>>> c2 = c.copy()
"""
vec = np.copy(self._vec)
return ScalarCoefs(vec, self.nmax, self.mmax) | [
"def",
"copy",
"(",
"self",
")",
":",
"vec",
"=",
"np",
".",
"copy",
"(",
"self",
".",
"_vec",
")",
"return",
"ScalarCoefs",
"(",
"vec",
",",
"self",
".",
"nmax",
",",
"self",
".",
"mmax",
")"
] | 22.5 | 0.017094 |
def parse_value(proto):
"""
Convers a Protobuf `Value` from the API into a python native value
"""
if proto.HasField('floatValue'):
return proto.floatValue
elif proto.HasField('doubleValue'):
return proto.doubleValue
elif proto.HasField('sint32Value'):
return proto.sint32... | [
"def",
"parse_value",
"(",
"proto",
")",
":",
"if",
"proto",
".",
"HasField",
"(",
"'floatValue'",
")",
":",
"return",
"proto",
".",
"floatValue",
"elif",
"proto",
".",
"HasField",
"(",
"'doubleValue'",
")",
":",
"return",
"proto",
".",
"doubleValue",
"eli... | 39.588235 | 0.00145 |
def get_function_from_settings(settings_key):
"""Gets a function from the string path defined in a settings file.
Example:
# my_app/my_file.py
def some_function():
# do something
pass
# settings.py
SOME_FUNCTION = 'my_app.my_file.some_function'
> get_function_from_setting... | [
"def",
"get_function_from_settings",
"(",
"settings_key",
")",
":",
"renderer_func_str",
"=",
"getattr",
"(",
"settings",
",",
"settings_key",
",",
"None",
")",
"if",
"not",
"renderer_func_str",
":",
"return",
"None",
"module_str",
",",
"renderer_func_name",
"=",
... | 24.892857 | 0.001381 |
def get_wells(self, plate_name=None):
'''Gets information about wells.
Parameters
----------
plate_name: str, optional
name of the parent plate
Returns
-------
List[Dict[str, str]]
id, name and description of each well
See also
... | [
"def",
"get_wells",
"(",
"self",
",",
"plate_name",
"=",
"None",
")",
":",
"logger",
".",
"info",
"(",
"'get wells of experiment \"%s\"'",
",",
"self",
".",
"experiment_name",
")",
"params",
"=",
"dict",
"(",
")",
"if",
"plate_name",
"is",
"not",
"None",
"... | 29.1875 | 0.002073 |
def resource_references(self, resource) -> Mapping[str, List[Any]]:
""" Resolve and return reference resources pointed to by object
Fields in resource.props can flag that they are references by
using the references type. This method scans the model,
finds any fields that are referenc... | [
"def",
"resource_references",
"(",
"self",
",",
"resource",
")",
"->",
"Mapping",
"[",
"str",
",",
"List",
"[",
"Any",
"]",
"]",
":",
"references",
"=",
"dict",
"(",
")",
"for",
"reference_label",
"in",
"resource",
".",
"props",
".",
"references",
":",
... | 42.961538 | 0.001751 |
def get_object_from_content(entity, key):
"""Get an object from the database given an entity and the content key.
:param entity: Class type of the object to retrieve.
:param key: Array that defines the path of the value inside the message.
"""
def object_from_content_function(service, message):
... | [
"def",
"get_object_from_content",
"(",
"entity",
",",
"key",
")",
":",
"def",
"object_from_content_function",
"(",
"service",
",",
"message",
")",
":",
"\"\"\"Actual implementation of get_object_from_content function.\n\n :param service: SelenolService object.\n :param ... | 41 | 0.001325 |
def add(self, name, interface, inputs=None, outputs=None,
requirements=None, wall_time=None, annotations=None, **kwargs):
"""
Adds a processing Node to the pipeline
Parameters
----------
name : str
Name for the node
interface : nipype.Interface
... | [
"def",
"add",
"(",
"self",
",",
"name",
",",
"interface",
",",
"inputs",
"=",
"None",
",",
"outputs",
"=",
"None",
",",
"requirements",
"=",
"None",
",",
"wall_time",
"=",
"None",
",",
"annotations",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
... | 49.522936 | 0.000545 |
def set_readable_web_pdf(self, value):
''' setter '''
if isinstance(value, ReadableWebPDF) is False and value is not None:
raise TypeError("The type of __readable_web_pdf must be ReadableWebPDF.")
self.__readable_web_pdf = value | [
"def",
"set_readable_web_pdf",
"(",
"self",
",",
"value",
")",
":",
"if",
"isinstance",
"(",
"value",
",",
"ReadableWebPDF",
")",
"is",
"False",
"and",
"value",
"is",
"not",
"None",
":",
"raise",
"TypeError",
"(",
"\"The type of __readable_web_pdf must be Readable... | 52 | 0.011364 |
def search(self, ngram):
'''
Parameters
----------
ngram, str or unicode, string to search for
Returns
-------
pd.DataFrame, {self._parsed_col: <matching texts>, self._category_col: <corresponding categories>, ...}
'''
mask = self._document_index... | [
"def",
"search",
"(",
"self",
",",
"ngram",
")",
":",
"mask",
"=",
"self",
".",
"_document_index_mask",
"(",
"ngram",
")",
"return",
"self",
".",
"_df",
"[",
"mask",
"]"
] | 26.923077 | 0.008287 |
def render_props(**kwargs):
"""
Return a valid property for cleaner referencing in :class:`Part <cqparts.Part>`
child classes.
:param template: name of template to use (any of ``TEMPLATE.keys()``)
:type template: :class:`str`
:param doc: description of parameter for sphinx docs
:type doc: :... | [
"def",
"render_props",
"(",
"*",
"*",
"kwargs",
")",
":",
"# Pop named args",
"template",
"=",
"kwargs",
".",
"pop",
"(",
"'template'",
",",
"'default'",
")",
"doc",
"=",
"kwargs",
".",
"pop",
"(",
"'doc'",
",",
"\"render properties\"",
")",
"params",
"=",... | 29.139535 | 0.001544 |
def get_filelikeobject(filename: str = None,
blob: bytes = None) -> BinaryIO:
"""
Open a file-like object.
Guard the use of this function with ``with``.
Args:
filename: for specifying via a filename
blob: for specifying via an in-memory ``bytes`` object
Retu... | [
"def",
"get_filelikeobject",
"(",
"filename",
":",
"str",
"=",
"None",
",",
"blob",
":",
"bytes",
"=",
"None",
")",
"->",
"BinaryIO",
":",
"if",
"not",
"filename",
"and",
"not",
"blob",
":",
"raise",
"ValueError",
"(",
"\"no filename and no blob\"",
")",
"... | 27.863636 | 0.001577 |
def _augment(self):
"""
Finds a minimum cost path and adds it to the matching
"""
#build a minimum cost tree
_pred, _ready, istar, j, mu = self._build_tree()
#update prices
self._v[_ready] += self._d[_ready] - mu
#augment the solution with the minimum co... | [
"def",
"_augment",
"(",
"self",
")",
":",
"#build a minimum cost tree",
"_pred",
",",
"_ready",
",",
"istar",
",",
"j",
",",
"mu",
"=",
"self",
".",
"_build_tree",
"(",
")",
"#update prices",
"self",
".",
"_v",
"[",
"_ready",
"]",
"+=",
"self",
".",
"_... | 28.681818 | 0.010736 |
def _change_resource_record_sets(self, change_set, comment=None):
"""
Given a ChangeSet, POST it to the Route53 API.
.. note:: You probably shouldn't be using this method directly,
as there are convenience methods on the ResourceRecordSet
sub-classes.
:param cha... | [
"def",
"_change_resource_record_sets",
"(",
"self",
",",
"change_set",
",",
"comment",
"=",
"None",
")",
":",
"body",
"=",
"xml_generators",
".",
"change_resource_record_set_writer",
"(",
"connection",
"=",
"self",
",",
"change_set",
"=",
"change_set",
",",
"comme... | 34.4 | 0.002423 |
def clear_obj(self, obj):
"""Clear values and nodes of `obj` and their dependants."""
removed = self.cellgraph.clear_obj(obj)
for node in removed:
del node[OBJ].data[node[KEY]] | [
"def",
"clear_obj",
"(",
"self",
",",
"obj",
")",
":",
"removed",
"=",
"self",
".",
"cellgraph",
".",
"clear_obj",
"(",
"obj",
")",
"for",
"node",
"in",
"removed",
":",
"del",
"node",
"[",
"OBJ",
"]",
".",
"data",
"[",
"node",
"[",
"KEY",
"]",
"]... | 41.6 | 0.009434 |
def liveNeighbours(self, z, y, x):
"""Returns the number of live neighbours."""
count = 0
for oz, oy, ox in self.offsets:
cz, cy, cx = z + oz, y + oy, x + ox
if cz >= self.depth:
cz = 0
if cy >= self.height:
cy = 0
... | [
"def",
"liveNeighbours",
"(",
"self",
",",
"z",
",",
"y",
",",
"x",
")",
":",
"count",
"=",
"0",
"for",
"oz",
",",
"oy",
",",
"ox",
"in",
"self",
".",
"offsets",
":",
"cz",
",",
"cy",
",",
"cx",
"=",
"z",
"+",
"oz",
",",
"y",
"+",
"oy",
"... | 32 | 0.002092 |
def option(self, key=None):
"""
Get the value of a command option.
"""
if key is None:
return self._args.options()
return self._args.option(key) | [
"def",
"option",
"(",
"self",
",",
"key",
"=",
"None",
")",
":",
"if",
"key",
"is",
"None",
":",
"return",
"self",
".",
"_args",
".",
"options",
"(",
")",
"return",
"self",
".",
"_args",
".",
"option",
"(",
"key",
")"
] | 23.75 | 0.010152 |
def _file_chunks(self, data, chunk_size):
""" Yield compressed chunks from a data array"""
for i in xrange(0, len(data), chunk_size):
yield self.compressor(data[i:i+chunk_size]) | [
"def",
"_file_chunks",
"(",
"self",
",",
"data",
",",
"chunk_size",
")",
":",
"for",
"i",
"in",
"xrange",
"(",
"0",
",",
"len",
"(",
"data",
")",
",",
"chunk_size",
")",
":",
"yield",
"self",
".",
"compressor",
"(",
"data",
"[",
"i",
":",
"i",
"+... | 50.5 | 0.009756 |
def set_zones(token, action, relay=None, time=None):
"""
Controls the zone relays to turn sprinklers on and off.
:param token: The users API token.
:type token: string
:param action: The action to perform. Available actions are: run, runall,
stop, stopall, suspend, and suspendall... | [
"def",
"set_zones",
"(",
"token",
",",
"action",
",",
"relay",
"=",
"None",
",",
"time",
"=",
"None",
")",
":",
"# Actions must be one from this list.",
"action_list",
"=",
"[",
"'run'",
",",
"# Run a zone for an amount of time.",
"'runall'",
",",
"# Run all zones f... | 35.458333 | 0.000381 |
def instantiate(self, **extra_args):
""" Instantiate the model """
input_block = self.input_block.instantiate()
backbone = self.backbone.instantiate(**extra_args)
return StochasticPolicyRnnModel(input_block, backbone, extra_args['action_space']) | [
"def",
"instantiate",
"(",
"self",
",",
"*",
"*",
"extra_args",
")",
":",
"input_block",
"=",
"self",
".",
"input_block",
".",
"instantiate",
"(",
")",
"backbone",
"=",
"self",
".",
"backbone",
".",
"instantiate",
"(",
"*",
"*",
"extra_args",
")",
"retur... | 45.5 | 0.010791 |
def directive_DCB(self, label, params):
"""
label DCB value[, value ...]
Allocate a byte space in read only memory for the value or list of values
"""
# TODO make this read only
# TODO check for byte size
self.labels[label] = self.space_pointer
if param... | [
"def",
"directive_DCB",
"(",
"self",
",",
"label",
",",
"params",
")",
":",
"# TODO make this read only",
"# TODO check for byte size",
"self",
".",
"labels",
"[",
"label",
"]",
"=",
"self",
".",
"space_pointer",
"if",
"params",
"in",
"self",
".",
"equates",
"... | 37 | 0.008114 |
def get_post_by_id(self, post_id):
"""
Fetch the blog post given by ``post_id``
:param post_id: The post identifier for the blog post
:type post_id: str
:return: If the ``post_id`` is valid, the post data is retrieved, else
returns ``None``.
"""
r = None... | [
"def",
"get_post_by_id",
"(",
"self",
",",
"post_id",
")",
":",
"r",
"=",
"None",
"post_id",
"=",
"_as_int",
"(",
"post_id",
")",
"with",
"self",
".",
"_engine",
".",
"begin",
"(",
")",
"as",
"conn",
":",
"try",
":",
"post_statement",
"=",
"sqla",
".... | 34.852941 | 0.001642 |
def _kwargs_to_qs(**kwargs):
"""Converts kwargs given to PSF to a querystring.
:returns: the querystring.
"""
# start with defaults
inpOptDef = inputs_options_defaults()
opts = {
name: dct['value']
for name, dct in inpOptDef.items()
}
# clean up keys and values
for ... | [
"def",
"_kwargs_to_qs",
"(",
"*",
"*",
"kwargs",
")",
":",
"# start with defaults",
"inpOptDef",
"=",
"inputs_options_defaults",
"(",
")",
"opts",
"=",
"{",
"name",
":",
"dct",
"[",
"'value'",
"]",
"for",
"name",
",",
"dct",
"in",
"inpOptDef",
".",
"items"... | 34.1 | 0.000356 |
def memoize(fun):
"""Memoizes return values of the decorated function.
Similar to l0cache, but the cache persists for the duration of the process, unless clear_cache()
is called on the function.
"""
argspec = inspect2.getfullargspec(fun)
arg_names = argspec.args + argspec.kwonlyargs
kwargs... | [
"def",
"memoize",
"(",
"fun",
")",
":",
"argspec",
"=",
"inspect2",
".",
"getfullargspec",
"(",
"fun",
")",
"arg_names",
"=",
"argspec",
".",
"args",
"+",
"argspec",
".",
"kwonlyargs",
"kwargs_defaults",
"=",
"get_kwargs_defaults",
"(",
"argspec",
")",
"def"... | 30.678571 | 0.002257 |
def _vggconv_block(x, filters, kernel, stride, kernel_posterior_fn):
"""Network block for VGG."""
out = tfp.layers.Convolution2DFlipout(
filters,
kernel,
padding='same',
kernel_posterior_fn=kernel_posterior_fn)(x)
out = tf.keras.layers.BatchNormalization()(out)
out = tf.keras.layers.Acti... | [
"def",
"_vggconv_block",
"(",
"x",
",",
"filters",
",",
"kernel",
",",
"stride",
",",
"kernel_posterior_fn",
")",
":",
"out",
"=",
"tfp",
".",
"layers",
".",
"Convolution2DFlipout",
"(",
"filters",
",",
"kernel",
",",
"padding",
"=",
"'same'",
",",
"kernel... | 31.380952 | 0.014728 |
def download(self):
''' Downloads HTML from url. '''
self.page = requests.get(self.url)
self.tree = html.fromstring(self.page.text) | [
"def",
"download",
"(",
"self",
")",
":",
"self",
".",
"page",
"=",
"requests",
".",
"get",
"(",
"self",
".",
"url",
")",
"self",
".",
"tree",
"=",
"html",
".",
"fromstring",
"(",
"self",
".",
"page",
".",
"text",
")"
] | 26.8 | 0.036232 |
def progress_bar(**kwargs):
"""Create a `tqdm.tqdm` progress bar
This is just a thin wrapper around `tqdm.tqdm` to set some updated defaults
"""
tqdm_kw = {
'desc': 'Processing',
'file': sys.stdout,
'bar_format': TQDM_BAR_FORMAT,
}
tqdm_kw.update(kwargs)
pbar = tqdm(... | [
"def",
"progress_bar",
"(",
"*",
"*",
"kwargs",
")",
":",
"tqdm_kw",
"=",
"{",
"'desc'",
":",
"'Processing'",
",",
"'file'",
":",
"sys",
".",
"stdout",
",",
"'bar_format'",
":",
"TQDM_BAR_FORMAT",
",",
"}",
"tqdm_kw",
".",
"update",
"(",
"kwargs",
")",
... | 26.375 | 0.002288 |
def user_licenses(self):
"""Download the user current trial/paid licenses."""
url = '{domain}/license'.format(domain=self.domain)
res = self.session.get(url)
self._check_response(res)
return res.json() | [
"def",
"user_licenses",
"(",
"self",
")",
":",
"url",
"=",
"'{domain}/license'",
".",
"format",
"(",
"domain",
"=",
"self",
".",
"domain",
")",
"res",
"=",
"self",
".",
"session",
".",
"get",
"(",
"url",
")",
"self",
".",
"_check_response",
"(",
"res",... | 39.333333 | 0.008299 |
def lint(exclude, skip_untracked, commit_only):
# type: (List[str], bool, bool) -> None
""" Lint python files.
Args:
exclude (list[str]):
A list of glob string patterns to test against. If the file/path
matches any of those patters, it will be filtered out.
skip_untr... | [
"def",
"lint",
"(",
"exclude",
",",
"skip_untracked",
",",
"commit_only",
")",
":",
"# type: (List[str], bool, bool) -> None",
"exclude",
"=",
"list",
"(",
"exclude",
")",
"+",
"conf",
".",
"get",
"(",
"'lint.exclude'",
",",
"[",
"]",
")",
"runner",
"=",
"Li... | 35.833333 | 0.001511 |
def list_user_topics(self, start=0):
"""
发表的话题
:param start: 翻页
:return: 带下一页的列表
"""
xml = self.api.xml(API_GROUP_LIST_USER_PUBLISHED_TOPICS % self.api.user_alias, params={'start': start})
return build_list_result(self._parse_topic_table(xml, 'title,comme... | [
"def",
"list_user_topics",
"(",
"self",
",",
"start",
"=",
"0",
")",
":",
"xml",
"=",
"self",
".",
"api",
".",
"xml",
"(",
"API_GROUP_LIST_USER_PUBLISHED_TOPICS",
"%",
"self",
".",
"api",
".",
"user_alias",
",",
"params",
"=",
"{",
"'start'",
":",
"start... | 37.333333 | 0.014535 |
def continuous_query_exists(database, name, **client_args):
'''
Check if continuous query with given name exists on the database.
database
Name of the database for which the continuous query was
defined.
name
Name of the continuous query to check.
CLI Example:
.. code... | [
"def",
"continuous_query_exists",
"(",
"database",
",",
"name",
",",
"*",
"*",
"client_args",
")",
":",
"if",
"get_continuous_query",
"(",
"database",
",",
"name",
",",
"*",
"*",
"client_args",
")",
":",
"return",
"True",
"return",
"False"
] | 23.142857 | 0.001976 |
def _create_metadata_converter_action(self):
"""Create action for showing metadata converter dialog."""
icon = resources_path('img', 'icons', 'show-metadata-converter.svg')
self.action_metadata_converter = QAction(
QIcon(icon),
self.tr('InaSAFE Metadata Converter'),
... | [
"def",
"_create_metadata_converter_action",
"(",
"self",
")",
":",
"icon",
"=",
"resources_path",
"(",
"'img'",
",",
"'icons'",
",",
"'show-metadata-converter.svg'",
")",
"self",
".",
"action_metadata_converter",
"=",
"QAction",
"(",
"QIcon",
"(",
"icon",
")",
","... | 53.133333 | 0.002466 |
def plot_cumulative_moment(year, mag, figure_size=(8, 6),
filename=None, filetype='png', dpi=300, ax=None):
'''Calculation of Mmax using aCumulative Moment approach, adapted from
the cumulative strain energy method of Makropoulos & Burton (1983)
:param year: Year of Earthquake
... | [
"def",
"plot_cumulative_moment",
"(",
"year",
",",
"mag",
",",
"figure_size",
"=",
"(",
"8",
",",
"6",
")",
",",
"filename",
"=",
"None",
",",
"filetype",
"=",
"'png'",
",",
"dpi",
"=",
"300",
",",
"ax",
"=",
"None",
")",
":",
"# Calculate seismic mome... | 40.046512 | 0.000567 |
def set_provenance_to_project_variables(provenances):
"""Helper method to update / create provenance in project variables.
:param provenances: Keys and values from provenances.
:type provenances: dict
"""
def write_project_variable(key, value):
"""Helper to write project variable for base_k... | [
"def",
"set_provenance_to_project_variables",
"(",
"provenances",
")",
":",
"def",
"write_project_variable",
"(",
"key",
",",
"value",
")",
":",
"\"\"\"Helper to write project variable for base_key and value.\n\n The key will be:\n - base_key__KEY: value for dictionary.\n ... | 39.516129 | 0.000398 |
def generate_express_checkout_redirect_url(self, token, useraction=None):
"""Returns the URL to redirect the user to for the Express checkout.
Express Checkouts must be verified by the customer by redirecting them
to the PayPal website. Use the token returned in the response from
:meth:... | [
"def",
"generate_express_checkout_redirect_url",
"(",
"self",
",",
"token",
",",
"useraction",
"=",
"None",
")",
":",
"url_vars",
"=",
"(",
"self",
".",
"config",
".",
"PAYPAL_URL_BASE",
",",
"token",
")",
"url",
"=",
"\"%s?cmd=_express-checkout&token=%s\"",
"%",
... | 49.76 | 0.001577 |
def get_dataset(self, key, info):
"""Load dataset designated by the given key from file"""
logger.debug('Reading dataset {}'.format(key.name))
# Read data from file and calibrate if necessary
if 'longitude' in key.name:
data = self.geo_data['lon']
elif 'latitude' in ... | [
"def",
"get_dataset",
"(",
"self",
",",
"key",
",",
"info",
")",
":",
"logger",
".",
"debug",
"(",
"'Reading dataset {}'",
".",
"format",
"(",
"key",
".",
"name",
")",
")",
"# Read data from file and calibrate if necessary",
"if",
"'longitude'",
"in",
"key",
"... | 35.192308 | 0.002128 |
def Serialize(self, writer):
"""
Serialize full object.
Args:
writer (neo.IO.BinaryWriter):
"""
self.SerializeUnsigned(writer)
writer.WriteByte(1)
self.Script.Serialize(writer) | [
"def",
"Serialize",
"(",
"self",
",",
"writer",
")",
":",
"self",
".",
"SerializeUnsigned",
"(",
"writer",
")",
"writer",
".",
"WriteByte",
"(",
"1",
")",
"self",
".",
"Script",
".",
"Serialize",
"(",
"writer",
")"
] | 23.6 | 0.008163 |
def options(self):
"""Train tickets query options."""
arg = self.get(0)
if arg.startswith('-') and not self.is_asking_for_help:
return arg[1:]
return ''.join(x for x in arg if x in 'dgktz') | [
"def",
"options",
"(",
"self",
")",
":",
"arg",
"=",
"self",
".",
"get",
"(",
"0",
")",
"if",
"arg",
".",
"startswith",
"(",
"'-'",
")",
"and",
"not",
"self",
".",
"is_asking_for_help",
":",
"return",
"arg",
"[",
"1",
":",
"]",
"return",
"''",
".... | 38 | 0.008584 |
def _read(self, stream, text, byte_order):
'''
Read the actual data from a PLY file.
'''
dtype = self.dtype(byte_order)
if text:
self._read_txt(stream)
elif _can_mmap(stream) and not self._have_list:
# Loading the data is straightforward. We will... | [
"def",
"_read",
"(",
"self",
",",
"stream",
",",
"text",
",",
"byte_order",
")",
":",
"dtype",
"=",
"self",
".",
"dtype",
"(",
"byte_order",
")",
"if",
"text",
":",
"self",
".",
"_read_txt",
"(",
"stream",
")",
"elif",
"_can_mmap",
"(",
"stream",
")"... | 38.407407 | 0.001881 |
def parse_pretty_midi(self, pm, mode='max', algorithm='normal',
binarized=False, skip_empty_tracks=True,
collect_onsets_only=False, threshold=0,
first_beat_time=None):
"""
Parse a :class:`pretty_midi.PrettyMIDI` object. The da... | [
"def",
"parse_pretty_midi",
"(",
"self",
",",
"pm",
",",
"mode",
"=",
"'max'",
",",
"algorithm",
"=",
"'normal'",
",",
"binarized",
"=",
"False",
",",
"skip_empty_tracks",
"=",
"True",
",",
"collect_onsets_only",
"=",
"False",
",",
"threshold",
"=",
"0",
"... | 46.728643 | 0.001264 |
def calculate_content_width(self):
"""
Calculate the width of inner content of the border. This will be the width of the menu borders,
minus the left and right padding, and minus the two vertical border characters.
For example, given a border width of 77, with left and right margins eac... | [
"def",
"calculate_content_width",
"(",
"self",
")",
":",
"return",
"self",
".",
"calculate_border_width",
"(",
")",
"-",
"self",
".",
"padding",
".",
"left",
"-",
"self",
".",
"padding",
".",
"right",
"-",
"2"
] | 50.454545 | 0.010619 |
def transitive_dependents_of_addresses(self, addresses):
"""Given an iterable of addresses, yield all of those addresses dependents, transitively."""
closure = set()
result = []
to_visit = deque(addresses)
while to_visit:
address = to_visit.popleft()
if address in closure:
conti... | [
"def",
"transitive_dependents_of_addresses",
"(",
"self",
",",
"addresses",
")",
":",
"closure",
"=",
"set",
"(",
")",
"result",
"=",
"[",
"]",
"to_visit",
"=",
"deque",
"(",
"addresses",
")",
"while",
"to_visit",
":",
"address",
"=",
"to_visit",
".",
"pop... | 30.117647 | 0.015152 |
def index(self, item, **kwargs):
# type: (Any, dict) -> int
"""
Get index of the parameter.
:param item: Item for which get the index.
:return: Index of the parameter in the WeakList.
"""
return list.index(self, self.ref(item), **kwargs) | [
"def",
"index",
"(",
"self",
",",
"item",
",",
"*",
"*",
"kwargs",
")",
":",
"# type: (Any, dict) -> int",
"return",
"list",
".",
"index",
"(",
"self",
",",
"self",
".",
"ref",
"(",
"item",
")",
",",
"*",
"*",
"kwargs",
")"
] | 35.75 | 0.010239 |
def handle_request(self):
"""Handle a single JSON-RPC request.
Read a request, call the appropriate handler method, and
return the encoded result. Errors in the handler method are
caught and encoded as error objects. Errors in the decoding
phase are not caught, as we can not res... | [
"def",
"handle_request",
"(",
"self",
")",
":",
"request",
"=",
"self",
".",
"read_json",
"(",
")",
"if",
"'method'",
"not",
"in",
"request",
":",
"raise",
"ValueError",
"(",
"\"Received a bad request: {0}\"",
".",
"format",
"(",
"request",
")",
")",
"method... | 40.405405 | 0.001306 |
def find(self, path, all=False):
'''
Looks for files in the app directories.
'''
found = os.path.join(settings.STATIC_ROOT, path)
if all:
return [found]
else:
return found | [
"def",
"find",
"(",
"self",
",",
"path",
",",
"all",
"=",
"False",
")",
":",
"found",
"=",
"os",
".",
"path",
".",
"join",
"(",
"settings",
".",
"STATIC_ROOT",
",",
"path",
")",
"if",
"all",
":",
"return",
"[",
"found",
"]",
"else",
":",
"return"... | 26.111111 | 0.00823 |
def run(self):
"""Executed by Sphinx.
:returns: Single DisqusNode instance with config values passed as arguments.
:rtype: list
"""
disqus_shortname = self.get_shortname()
disqus_identifier = self.get_identifier()
return [DisqusNode(disqus_shortname, disqus_ident... | [
"def",
"run",
"(",
"self",
")",
":",
"disqus_shortname",
"=",
"self",
".",
"get_shortname",
"(",
")",
"disqus_identifier",
"=",
"self",
".",
"get_identifier",
"(",
")",
"return",
"[",
"DisqusNode",
"(",
"disqus_shortname",
",",
"disqus_identifier",
")",
"]"
] | 35.444444 | 0.009174 |
def create(cls, d):
""" Create a :class:`~pypot.primitive.move.Move` from a dictionary. """
move = cls(d['framerate'])
move._timed_positions.update(d['positions'])
return move | [
"def",
"create",
"(",
"cls",
",",
"d",
")",
":",
"move",
"=",
"cls",
"(",
"d",
"[",
"'framerate'",
"]",
")",
"move",
".",
"_timed_positions",
".",
"update",
"(",
"d",
"[",
"'positions'",
"]",
")",
"return",
"move"
] | 40.6 | 0.009662 |
def get_queues(*queue_names, **kwargs):
"""
Return queue instances from specified queue names.
All instances must use the same Redis connection.
"""
from .settings import QUEUES
if len(queue_names) <= 1:
# Return "default" queue if no queue name is specified
# or one queue with ... | [
"def",
"get_queues",
"(",
"*",
"queue_names",
",",
"*",
"*",
"kwargs",
")",
":",
"from",
".",
"settings",
"import",
"QUEUES",
"if",
"len",
"(",
"queue_names",
")",
"<=",
"1",
":",
"# Return \"default\" queue if no queue name is specified",
"# or one queue with speci... | 37.555556 | 0.001442 |
def create_fpath_dir(self, fpath: str):
"""Creates directory for fpath."""
os.makedirs(os.path.dirname(fpath), exist_ok=True) | [
"def",
"create_fpath_dir",
"(",
"self",
",",
"fpath",
":",
"str",
")",
":",
"os",
".",
"makedirs",
"(",
"os",
".",
"path",
".",
"dirname",
"(",
"fpath",
")",
",",
"exist_ok",
"=",
"True",
")"
] | 46.333333 | 0.014184 |
def start_scan(self, active):
"""Start the scanning task"""
self._command_task.sync_command(['_start_scan', active])
self.scanning = True | [
"def",
"start_scan",
"(",
"self",
",",
"active",
")",
":",
"self",
".",
"_command_task",
".",
"sync_command",
"(",
"[",
"'_start_scan'",
",",
"active",
"]",
")",
"self",
".",
"scanning",
"=",
"True"
] | 39.5 | 0.012422 |
def get_account_api_key(self, account_id, api_key, **kwargs): # noqa: E501
"""Get API key details. # noqa: E501
An endpoint for retrieving API key details. **Example usage:** `curl https://api.us-east-1.mbedcloud.com/v3/accounts/{accountID}/api-keys/{apiKey} -H 'Authorization: Bearer API_KEY'` # n... | [
"def",
"get_account_api_key",
"(",
"self",
",",
"account_id",
",",
"api_key",
",",
"*",
"*",
"kwargs",
")",
":",
"# noqa: E501",
"kwargs",
"[",
"'_return_http_data_only'",
"]",
"=",
"True",
"if",
"kwargs",
".",
"get",
"(",
"'asynchronous'",
")",
":",
"return... | 55.227273 | 0.001618 |
def from_sources_field(sources, spec_path):
"""Return a BaseGlobs for the given sources field.
`sources` may be None, a list/tuple/set, a string or a BaseGlobs instance.
"""
if sources is None:
return Files(spec_path=spec_path)
elif isinstance(sources, BaseGlobs):
return sources
eli... | [
"def",
"from_sources_field",
"(",
"sources",
",",
"spec_path",
")",
":",
"if",
"sources",
"is",
"None",
":",
"return",
"Files",
"(",
"spec_path",
"=",
"spec_path",
")",
"elif",
"isinstance",
"(",
"sources",
",",
"BaseGlobs",
")",
":",
"return",
"sources",
... | 42.75 | 0.011445 |
def build_funcs(modules):
"""Build a used functions and modules list
for later consumption.
"""
kernel32 = ['kernel32_']
try:
kernel32 += remove_dups(modules['kernel32'])
except KeyError:
if len(modules) and 'LoadLibraryA' not in kernel32:
... | [
"def",
"build_funcs",
"(",
"modules",
")",
":",
"kernel32",
"=",
"[",
"'kernel32_'",
"]",
"try",
":",
"kernel32",
"+=",
"remove_dups",
"(",
"modules",
"[",
"'kernel32'",
"]",
")",
"except",
"KeyError",
":",
"if",
"len",
"(",
"modules",
")",
"and",
"'Load... | 41.15 | 0.002375 |
def _improve_method_docs(obj, name, lines):
"""Improve the documentation of various methods.
:param obj: the instance of the method to document.
:param name: full dotted path to the object.
:param lines: expected documentation lines.
"""
if not lines:
# Not doing obj.__module__ lookups ... | [
"def",
"_improve_method_docs",
"(",
"obj",
",",
"name",
",",
"lines",
")",
":",
"if",
"not",
"lines",
":",
"# Not doing obj.__module__ lookups to avoid performance issues.",
"if",
"name",
".",
"endswith",
"(",
"'_display'",
")",
":",
"match",
"=",
"RE_GET_FOO_DISPLA... | 45.4 | 0.001438 |
def get_x(self, var, coords=None):
"""
Get the centers of the triangles in the x-dimension
Parameters
----------
%(CFDecoder.get_y.parameters)s
Returns
-------
%(CFDecoder.get_y.returns)s"""
if coords is None:
coords = self.ds.coords
... | [
"def",
"get_x",
"(",
"self",
",",
"var",
",",
"coords",
"=",
"None",
")",
":",
"if",
"coords",
"is",
"None",
":",
"coords",
"=",
"self",
".",
"ds",
".",
"coords",
"# first we try the super class",
"ret",
"=",
"super",
"(",
"UGridDecoder",
",",
"self",
... | 38.333333 | 0.001885 |
def CompareEndpoints(self, srcEndPoint: int, textRange: 'TextRange', targetEndPoint: int) -> int:
"""
Call IUIAutomationTextRange::CompareEndpoints.
srcEndPoint: int, a value in class `TextPatternRangeEndpoint`.
textRange: `TextRange`.
targetEndPoint: int, a value in class `TextP... | [
"def",
"CompareEndpoints",
"(",
"self",
",",
"srcEndPoint",
":",
"int",
",",
"textRange",
":",
"'TextRange'",
",",
"targetEndPoint",
":",
"int",
")",
"->",
"int",
":",
"return",
"self",
".",
"textRange",
".",
"CompareEndpoints",
"(",
"srcEndPoint",
",",
"tex... | 75.25 | 0.008753 |
def isPeBounded(self):
"""
Determines if the current L{PE} instance is bounded, i.e. has a C{BOUND_IMPORT_DIRECTORY}.
@rtype: bool
@return: Returns C{True} if the current L{PE} instance is bounded. Otherwise, returns C{False}.
"""
boundImportsDir = self.ntHeaders... | [
"def",
"isPeBounded",
"(",
"self",
")",
":",
"boundImportsDir",
"=",
"self",
".",
"ntHeaders",
".",
"optionalHeader",
".",
"dataDirectory",
"[",
"consts",
".",
"BOUND_IMPORT_DIRECTORY",
"]",
"if",
"boundImportsDir",
".",
"rva",
".",
"value",
"and",
"boundImports... | 44 | 0.012146 |
def p_expression_eq(self, p):
'expression : expression EQ expression'
p[0] = Eq(p[1], p[3], lineno=p.lineno(1))
p.set_lineno(0, p.lineno(1)) | [
"def",
"p_expression_eq",
"(",
"self",
",",
"p",
")",
":",
"p",
"[",
"0",
"]",
"=",
"Eq",
"(",
"p",
"[",
"1",
"]",
",",
"p",
"[",
"3",
"]",
",",
"lineno",
"=",
"p",
".",
"lineno",
"(",
"1",
")",
")",
"p",
".",
"set_lineno",
"(",
"0",
",",... | 40.25 | 0.012195 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.