text stringlengths 89 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 630 |
|---|---|---|---|
async def add_alternative(self, alt, timeout=OTGW_DEFAULT_TIMEOUT):
"""
Add the specified Data-ID to the list of alternative commands
to send to the boiler instead of a Data-ID that is known to be
unsupported by the boiler. Alternative Data-IDs will always be
sent to the boiler i... | [
"async",
"def",
"add_alternative",
"(",
"self",
",",
"alt",
",",
"timeout",
"=",
"OTGW_DEFAULT_TIMEOUT",
")",
":",
"cmd",
"=",
"OTGW_CMD_ADD_ALT",
"alt",
"=",
"int",
"(",
"alt",
")",
"if",
"alt",
"<",
"1",
"or",
"alt",
">",
"255",
":",
"return",
"None"... | 43.190476 | 20.142857 |
def stor(ftp=None):
"""Same as ftplib's storbinary() but just sends dummy data
instead of reading it from a real file.
"""
if ftp is None:
ftp = connect()
quit = True
else:
quit = False
ftp.voidcmd('TYPE I')
with contextlib.closing(ftp.transfercmd("STOR " + TESTFN)) a... | [
"def",
"stor",
"(",
"ftp",
"=",
"None",
")",
":",
"if",
"ftp",
"is",
"None",
":",
"ftp",
"=",
"connect",
"(",
")",
"quit",
"=",
"True",
"else",
":",
"quit",
"=",
"False",
"ftp",
".",
"voidcmd",
"(",
"'TYPE I'",
")",
"with",
"contextlib",
".",
"cl... | 26.272727 | 16.318182 |
def render_markdown(self, text, context=github.GithubObject.NotSet):
"""
:calls: `POST /markdown <http://developer.github.com/v3/markdown>`_
:param text: string
:param context: :class:`github.Repository.Repository`
:rtype: string
"""
assert isinstance(text, (str, ... | [
"def",
"render_markdown",
"(",
"self",
",",
"text",
",",
"context",
"=",
"github",
".",
"GithubObject",
".",
"NotSet",
")",
":",
"assert",
"isinstance",
"(",
"text",
",",
"(",
"str",
",",
"unicode",
")",
")",
",",
"text",
"assert",
"context",
"is",
"gi... | 39.095238 | 19.666667 |
def managed(name,
template_name=None,
template_source=None,
template_hash=None,
template_hash_name=None,
saltenv='base',
template_engine='jinja',
skip_verify=False,
context=None,
defaults=None,
test=F... | [
"def",
"managed",
"(",
"name",
",",
"template_name",
"=",
"None",
",",
"template_source",
"=",
"None",
",",
"template_hash",
"=",
"None",
",",
"template_hash_name",
"=",
"None",
",",
"saltenv",
"=",
"'base'",
",",
"template_engine",
"=",
"'jinja'",
",",
"ski... | 42.035443 | 26.541772 |
def _authority(scheme=DEFAULT_SCHEME, host=DEFAULT_HOST, port=DEFAULT_PORT):
"""Construct a URL authority from the given *scheme*, *host*, and *port*.
Named in accordance with RFC2396_, which defines URLs as::
<scheme>://<authority><path>?<query>
.. _RFC2396: http://www.ietf.org/rfc/rfc2396.txt
... | [
"def",
"_authority",
"(",
"scheme",
"=",
"DEFAULT_SCHEME",
",",
"host",
"=",
"DEFAULT_HOST",
",",
"port",
"=",
"DEFAULT_PORT",
")",
":",
"if",
"':'",
"in",
"host",
":",
"# IPv6 addresses must be enclosed in [ ] in order to be well",
"# formed.",
"host",
"=",
"'['",
... | 33.325581 | 23.790698 |
def _method_(name):
""" getter factory """
def _getter_(self):
return getattr(self, self.get_private_name(name))
return _getter_ | [
"def",
"_method_",
"(",
"name",
")",
":",
"def",
"_getter_",
"(",
"self",
")",
":",
"return",
"getattr",
"(",
"self",
",",
"self",
".",
"get_private_name",
"(",
"name",
")",
")",
"return",
"_getter_"
] | 28.8 | 15.2 |
def template_apiserver_hcl(cl_args, masters, zookeepers):
"""
template apiserver.hcl
"""
single_master = masters[0]
apiserver_config_template = "%s/standalone/templates/apiserver.template.hcl" \
% cl_args["config_path"]
apiserver_config_actual = "%s/standalone/resources/apiserv... | [
"def",
"template_apiserver_hcl",
"(",
"cl_args",
",",
"masters",
",",
"zookeepers",
")",
":",
"single_master",
"=",
"masters",
"[",
"0",
"]",
"apiserver_config_template",
"=",
"\"%s/standalone/templates/apiserver.template.hcl\"",
"%",
"cl_args",
"[",
"\"config_path\"",
... | 48.090909 | 26.454545 |
def _dns_info_mapper(self, raw_dns):
"""The method maps the specific fields/flags in a DNS record to human readable form"""
output = {}
# Indentification
output['identification'] = raw_dns['id']
# Pull out all the flags
flags = {}
flags['type'] = 'query' if raw_... | [
"def",
"_dns_info_mapper",
"(",
"self",
",",
"raw_dns",
")",
":",
"output",
"=",
"{",
"}",
"# Indentification",
"output",
"[",
"'identification'",
"]",
"=",
"raw_dns",
"[",
"'id'",
"]",
"# Pull out all the flags",
"flags",
"=",
"{",
"}",
"flags",
"[",
"'type... | 39.421875 | 19.390625 |
def ndsname(self):
"""Name of this channel as stored in the NDS database
"""
if self.type not in [None, 'raw', 'reduced', 'online']:
return '%s,%s' % (self.name, self.type)
return self.name | [
"def",
"ndsname",
"(",
"self",
")",
":",
"if",
"self",
".",
"type",
"not",
"in",
"[",
"None",
",",
"'raw'",
",",
"'reduced'",
",",
"'online'",
"]",
":",
"return",
"'%s,%s'",
"%",
"(",
"self",
".",
"name",
",",
"self",
".",
"type",
")",
"return",
... | 38 | 12 |
def update_terms_translations(self, project_id, file_path=None,
language_code=None, overwrite=False,
sync_terms=False, tags=None, fuzzy_trigger=None):
"""
Updates terms translations
overwrite: set it to True if you want to overwr... | [
"def",
"update_terms_translations",
"(",
"self",
",",
"project_id",
",",
"file_path",
"=",
"None",
",",
"language_code",
"=",
"None",
",",
"overwrite",
"=",
"False",
",",
"sync_terms",
"=",
"False",
",",
"tags",
"=",
"None",
",",
"fuzzy_trigger",
"=",
"None"... | 52.357143 | 24.142857 |
def restart_agent(self, agent_id, **kwargs):
'''tells the host agent running in this agency to restart the agent.'''
host_medium = self.get_medium('host_agent')
agent = host_medium.get_agent()
d = host_medium.get_document(agent_id)
# This is done like this on purpose, we want to ... | [
"def",
"restart_agent",
"(",
"self",
",",
"agent_id",
",",
"*",
"*",
"kwargs",
")",
":",
"host_medium",
"=",
"self",
".",
"get_medium",
"(",
"'host_agent'",
")",
"agent",
"=",
"host_medium",
".",
"get_agent",
"(",
")",
"d",
"=",
"host_medium",
".",
"get_... | 49 | 19.727273 |
def _recursive_get_all_file_names(dir):
"""
Get all the file names in the directory. Gets all the top level file names
only, not the full path.
dir: a directory or string, as to hand to os.walk(). If None, returns empty
list.
"""
if not dir:
return []
result = []
for ba... | [
"def",
"_recursive_get_all_file_names",
"(",
"dir",
")",
":",
"if",
"not",
"dir",
":",
"return",
"[",
"]",
"result",
"=",
"[",
"]",
"for",
"basedir",
",",
"dirs",
",",
"files",
"in",
"os",
".",
"walk",
"(",
"dir",
")",
":",
"result",
".",
"extend",
... | 24.25 | 21.875 |
def write_change(change):
"""
Creates an XML element for the change.
:param tuple change: A change tuple from a ChangeSet. Comes in the form
of ``(action, rrset)``.
:rtype: lxml.etree._Element
:returns: A fully baked Change tag.
"""
action, rrset = change
change_vals = get_cha... | [
"def",
"write_change",
"(",
"change",
")",
":",
"action",
",",
"rrset",
"=",
"change",
"change_vals",
"=",
"get_change_values",
"(",
"change",
")",
"e_change",
"=",
"etree",
".",
"Element",
"(",
"\"Change\"",
")",
"e_action",
"=",
"etree",
".",
"SubElement",... | 32.354839 | 21.225806 |
def add_bfd_session(self, dpid, ofport, src_mac, src_ip,
dst_mac="FF:FF:FF:FF:FF:FF", dst_ip="255.255.255.255",
auth_type=0, auth_keys=None):
"""
Establish a new BFD session and return My Discriminator of new session.
Configure the BFD session wit... | [
"def",
"add_bfd_session",
"(",
"self",
",",
"dpid",
",",
"ofport",
",",
"src_mac",
",",
"src_ip",
",",
"dst_mac",
"=",
"\"FF:FF:FF:FF:FF:FF\"",
",",
"dst_ip",
"=",
"\"255.255.255.255\"",
",",
"auth_type",
"=",
"0",
",",
"auth_keys",
"=",
"None",
")",
":",
... | 42.347826 | 21.768116 |
def _createTimeSeriesObjects(self, timeSeries, filename):
"""
Create GSSHAPY TimeSeries and TimeSeriesValue Objects Method
"""
try:
# Determine number of value columns
valColumns = len(timeSeries[0]['values'])
# Create List of GSSHAPY TimeSeries objec... | [
"def",
"_createTimeSeriesObjects",
"(",
"self",
",",
"timeSeries",
",",
"filename",
")",
":",
"try",
":",
"# Determine number of value columns",
"valColumns",
"=",
"len",
"(",
"timeSeries",
"[",
"0",
"]",
"[",
"'values'",
"]",
")",
"# Create List of GSSHAPY TimeSeri... | 40.071429 | 19.571429 |
def get_diskinfo(opts, show_all=False, local_only=False):
''' Returns a list holding the current disk info.
Stats are divided by the outputunit.
'''
disks = []
outunit = opts.outunit
label_map = get_label_map(opts)
# get mount info
try:
with open(mntfname) as infile:
... | [
"def",
"get_diskinfo",
"(",
"opts",
",",
"show_all",
"=",
"False",
",",
"local_only",
"=",
"False",
")",
":",
"disks",
"=",
"[",
"]",
"outunit",
"=",
"opts",
".",
"outunit",
"label_map",
"=",
"get_label_map",
"(",
"opts",
")",
"# get mount info",
"try",
... | 35.323232 | 16.616162 |
def resolve_child_module_registries_lineage(registry):
"""
For a given child module registry, attempt to resolve the lineage.
Return an iterator, yielding from parent down to the input registry,
inclusive of the input registry.
"""
children = [registry]
while isinstance(registry, BaseChild... | [
"def",
"resolve_child_module_registries_lineage",
"(",
"registry",
")",
":",
"children",
"=",
"[",
"registry",
"]",
"while",
"isinstance",
"(",
"registry",
",",
"BaseChildModuleRegistry",
")",
":",
"if",
"registry",
".",
"parent",
"in",
"children",
":",
"# this sh... | 46.456522 | 20.847826 |
def get_cluster_health(
self, nodes_health_state_filter=0, applications_health_state_filter=0, events_health_state_filter=0, exclude_health_statistics=False, include_system_application_health_statistics=False, timeout=60, custom_headers=None, raw=False, **operation_config):
"""Gets the health of a S... | [
"def",
"get_cluster_health",
"(",
"self",
",",
"nodes_health_state_filter",
"=",
"0",
",",
"applications_health_state_filter",
"=",
"0",
",",
"events_health_state_filter",
"=",
"0",
",",
"exclude_health_statistics",
"=",
"False",
",",
"include_system_application_health_stat... | 56.306748 | 29.877301 |
async def handle_jobs(job_handler, host, port, *, loop):
"""
Connects to the remote master and continuously receives calls, executes
them, then returns a response until interrupted.
"""
try:
try:
reader, writer = await asyncio.open_connection(host, port, loop=loop)
exce... | [
"async",
"def",
"handle_jobs",
"(",
"job_handler",
",",
"host",
",",
"port",
",",
"*",
",",
"loop",
")",
":",
"try",
":",
"try",
":",
"reader",
",",
"writer",
"=",
"await",
"asyncio",
".",
"open_connection",
"(",
"host",
",",
"port",
",",
"loop",
"="... | 29.882353 | 22.529412 |
def lows(self, *args):
"""
Generator yielding only the low tides.
Arguments:
see Tide.extrema()
"""
for t in ifilter(lambda e: e[2] == 'L', self.extrema(*args)):
yield t | [
"def",
"lows",
"(",
"self",
",",
"*",
"args",
")",
":",
"for",
"t",
"in",
"ifilter",
"(",
"lambda",
"e",
":",
"e",
"[",
"2",
"]",
"==",
"'L'",
",",
"self",
".",
"extrema",
"(",
"*",
"args",
")",
")",
":",
"yield",
"t"
] | 22.125 | 14.875 |
def _get_line_array_construct(self):
""" Returns a construct for an array of line data.
"""
from_bus = integer.setResultsName("fbus")
to_bus = integer.setResultsName("tbus")
s_rating = real.setResultsName("s_rating") # MVA
v_rating = real.setResultsName("v_rating") # kV
... | [
"def",
"_get_line_array_construct",
"(",
"self",
")",
":",
"from_bus",
"=",
"integer",
".",
"setResultsName",
"(",
"\"fbus\"",
")",
"to_bus",
"=",
"integer",
".",
"setResultsName",
"(",
"\"tbus\"",
")",
"s_rating",
"=",
"real",
".",
"setResultsName",
"(",
"\"s... | 49.633333 | 21.933333 |
def _hash(self, obj, parent, parents_ids=EMPTY_FROZENSET):
"""The main diff method"""
try:
result = self[obj]
except (TypeError, KeyError):
pass
else:
return result
result = not_hashed
if self._skip_this(obj, parent):
ret... | [
"def",
"_hash",
"(",
"self",
",",
"obj",
",",
"parent",
",",
"parents_ids",
"=",
"EMPTY_FROZENSET",
")",
":",
"try",
":",
"result",
"=",
"self",
"[",
"obj",
"]",
"except",
"(",
"TypeError",
",",
"KeyError",
")",
":",
"pass",
"else",
":",
"return",
"r... | 31.435484 | 22.403226 |
def _get(self, action, show, proxy, timeout):
"""
make HTTP request and cache response
"""
silent = self.flags['silent']
if action in self.cache:
if action != 'imageinfo' and action != 'labels':
utils.stderr("+ %s results in cache" % action, silent)
... | [
"def",
"_get",
"(",
"self",
",",
"action",
",",
"show",
",",
"proxy",
",",
"timeout",
")",
":",
"silent",
"=",
"self",
".",
"flags",
"[",
"'silent'",
"]",
"if",
"action",
"in",
"self",
".",
"cache",
":",
"if",
"action",
"!=",
"'imageinfo'",
"and",
... | 34.382979 | 18.170213 |
def get(self, artifact):
"""Gets the coordinate with the correct version for the given artifact coordinate.
:param M2Coordinate artifact: the coordinate to lookup.
:return: a coordinate which is the same as the input, but with the correct pinned version. If
this artifact set does not pin a version fo... | [
"def",
"get",
"(",
"self",
",",
"artifact",
")",
":",
"coord",
"=",
"self",
".",
"_key",
"(",
"artifact",
")",
"if",
"coord",
"in",
"self",
".",
"_artifacts_to_versions",
":",
"return",
"self",
".",
"_artifacts_to_versions",
"[",
"coord",
"]",
"return",
... | 42.769231 | 19.615385 |
def run(wf, *, display, n_threads=1):
"""Run the workflow using the dynamic-exclusion worker."""
worker = dynamic_exclusion_worker(display, n_threads)
return noodles.Scheduler(error_handler=display.error_handler)\
.run(worker, get_workflow(wf)) | [
"def",
"run",
"(",
"wf",
",",
"*",
",",
"display",
",",
"n_threads",
"=",
"1",
")",
":",
"worker",
"=",
"dynamic_exclusion_worker",
"(",
"display",
",",
"n_threads",
")",
"return",
"noodles",
".",
"Scheduler",
"(",
"error_handler",
"=",
"display",
".",
"... | 52 | 9.6 |
def login_uname_pwd(server, api_key=None):
"""
Prompts user for username and password, gets API key from server
if not provided.
"""
username = click.prompt("Please enter your One Codex (email)")
if api_key is not None:
return username, api_key
password = click.prompt("Please enter ... | [
"def",
"login_uname_pwd",
"(",
"server",
",",
"api_key",
"=",
"None",
")",
":",
"username",
"=",
"click",
".",
"prompt",
"(",
"\"Please enter your One Codex (email)\"",
")",
"if",
"api_key",
"is",
"not",
"None",
":",
"return",
"username",
",",
"api_key",
"pass... | 34.714286 | 20.571429 |
def to_array(self):
"""
Serializes this MaskPosition to a dictionary.
:return: dictionary representation of this object.
:rtype: dict
"""
array = super(MaskPosition, self).to_array()
array['point'] = u(self.point) # py2: type unicode, py3: type str
arra... | [
"def",
"to_array",
"(",
"self",
")",
":",
"array",
"=",
"super",
"(",
"MaskPosition",
",",
"self",
")",
".",
"to_array",
"(",
")",
"array",
"[",
"'point'",
"]",
"=",
"u",
"(",
"self",
".",
"point",
")",
"# py2: type unicode, py3: type str",
"array",
"[",... | 35.285714 | 19.571429 |
def set_context(self, expr, ctx):
"""Set the context of an expression to Store or Del if possible."""
t = type(expr)
try:
# TODO: check if Starred is ok
if t in (ast.Attribute, ast.Name):
if type(ctx) == ast.Store():
mis.check_forbidden... | [
"def",
"set_context",
"(",
"self",
",",
"expr",
",",
"ctx",
")",
":",
"t",
"=",
"type",
"(",
"expr",
")",
"try",
":",
"# TODO: check if Starred is ok",
"if",
"t",
"in",
"(",
"ast",
".",
"Attribute",
",",
"ast",
".",
"Name",
")",
":",
"if",
"type",
... | 44.125 | 13.1875 |
def get_all_instance_status(self, instance_ids=None,
max_results=None, next_token=None,
filters=None):
"""
Retrieve all the instances in your account scheduled for maintenance.
:type instance_ids: list
:param instance_ids: ... | [
"def",
"get_all_instance_status",
"(",
"self",
",",
"instance_ids",
"=",
"None",
",",
"max_results",
"=",
"None",
",",
"next_token",
"=",
"None",
",",
"filters",
"=",
"None",
")",
":",
"params",
"=",
"{",
"}",
"if",
"instance_ids",
":",
"self",
".",
"bui... | 38.756098 | 19.04878 |
def fw_romaji_lt(full, regular):
'''
Generates a lookup table with the fullwidth rōmaji characters
on the left side, and the regular rōmaji characters as the values.
'''
lt = {}
for n in range(len(full)):
fw = full[n]
reg = regular[n]
lt[fw] = reg
return lt | [
"def",
"fw_romaji_lt",
"(",
"full",
",",
"regular",
")",
":",
"lt",
"=",
"{",
"}",
"for",
"n",
"in",
"range",
"(",
"len",
"(",
"full",
")",
")",
":",
"fw",
"=",
"full",
"[",
"n",
"]",
"reg",
"=",
"regular",
"[",
"n",
"]",
"lt",
"[",
"fw",
"... | 24.916667 | 24.25 |
def arrange(df, *args, **kwargs):
"""Calls `pandas.DataFrame.sort_values` to sort a DataFrame according to
criteria.
See:
http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.sort_values.html
For a list of specific keyword arguments for sort_values (which will be
the same in ... | [
"def",
"arrange",
"(",
"df",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"flat_args",
"=",
"[",
"a",
"for",
"a",
"in",
"flatten",
"(",
"args",
")",
"]",
"series",
"=",
"[",
"df",
"[",
"arg",
"]",
"if",
"isinstance",
"(",
"arg",
",",
... | 33.964286 | 24.285714 |
def preview_file(post):
"""
Opens the rendered markdown file (as html) locally in a browser.
"""
with open(post) as f:
content = f.read()
title = os.path.basename(post)
Preview(title, content).preview() | [
"def",
"preview_file",
"(",
"post",
")",
":",
"with",
"open",
"(",
"post",
")",
"as",
"f",
":",
"content",
"=",
"f",
".",
"read",
"(",
")",
"title",
"=",
"os",
".",
"path",
".",
"basename",
"(",
"post",
")",
"Preview",
"(",
"title",
",",
"content... | 28.375 | 10.375 |
def OnMouseWheel(self, event):
"""Event handler for mouse wheel actions
Invokes zoom when mouse when Ctrl is also pressed
"""
if event.ControlDown():
if event.WheelRotation > 0:
post_command_event(self.grid, self.grid.ZoomInMsg)
else:
... | [
"def",
"OnMouseWheel",
"(",
"self",
",",
"event",
")",
":",
"if",
"event",
".",
"ControlDown",
"(",
")",
":",
"if",
"event",
".",
"WheelRotation",
">",
"0",
":",
"post_command_event",
"(",
"self",
".",
"grid",
",",
"self",
".",
"grid",
".",
"ZoomInMsg"... | 34.424242 | 18.878788 |
def get_messages_from_stream(data):
"""Extract complete messages from stream and cut out them from stream.
@data - stream binary data
@return - [list of messages, choped stream data]
"""
messages = []
iterator = HEADER_RE.finditer(data)
last_pos = 0
for match in iterator:
pos =... | [
"def",
"get_messages_from_stream",
"(",
"data",
")",
":",
"messages",
"=",
"[",
"]",
"iterator",
"=",
"HEADER_RE",
".",
"finditer",
"(",
"data",
")",
"last_pos",
"=",
"0",
"for",
"match",
"in",
"iterator",
":",
"pos",
"=",
"match",
".",
"span",
"(",
")... | 29.538462 | 19.730769 |
def write_main_socket(c):
"""Synchronous write to the main socket, wait for ACK"""
the_stdin_thread.socket_write.send(c)
while True:
try:
the_stdin_thread.socket_write.recv(1)
except socket.error as e:
if e.errno != errno.EINTR:
raise
else:
... | [
"def",
"write_main_socket",
"(",
"c",
")",
":",
"the_stdin_thread",
".",
"socket_write",
".",
"send",
"(",
"c",
")",
"while",
"True",
":",
"try",
":",
"the_stdin_thread",
".",
"socket_write",
".",
"recv",
"(",
"1",
")",
"except",
"socket",
".",
"error",
... | 29.454545 | 14.181818 |
def id_maker(obj):
"""
Makes an ID from the object's class name and the datetime now in ISO format.
:param obj: the class from which to make the ID
:return: ID
"""
dtfmt = '%Y%m%d-%H%M%S'
return '%s-%s' % (obj.__class__.__name__, datetime.now().strftime(dtfmt)) | [
"def",
"id_maker",
"(",
"obj",
")",
":",
"dtfmt",
"=",
"'%Y%m%d-%H%M%S'",
"return",
"'%s-%s'",
"%",
"(",
"obj",
".",
"__class__",
".",
"__name__",
",",
"datetime",
".",
"now",
"(",
")",
".",
"strftime",
"(",
"dtfmt",
")",
")"
] | 31.333333 | 20.888889 |
def stream(self, chunk_size=64*1024):
'Returns a generator to iterate over the file contents'
#return self.jfs.stream(url='%s?mode=bin' % self.path, chunk_size=chunk_size)
return self.jfs.stream(url=self.path, params={'mode':'bin'}, chunk_size=chunk_size) | [
"def",
"stream",
"(",
"self",
",",
"chunk_size",
"=",
"64",
"*",
"1024",
")",
":",
"#return self.jfs.stream(url='%s?mode=bin' % self.path, chunk_size=chunk_size)",
"return",
"self",
".",
"jfs",
".",
"stream",
"(",
"url",
"=",
"self",
".",
"path",
",",
"params",
... | 69 | 30.5 |
def BuildChecks(self, request):
"""Parses request and returns a list of filter callables.
Each callable will be called with the StatEntry and returns True if the
entry should be suppressed.
Args:
request: A FindSpec that describes the search.
Returns:
a list of callables which return ... | [
"def",
"BuildChecks",
"(",
"self",
",",
"request",
")",
":",
"result",
"=",
"[",
"]",
"if",
"request",
".",
"HasField",
"(",
"\"start_time\"",
")",
"or",
"request",
".",
"HasField",
"(",
"\"end_time\"",
")",
":",
"def",
"FilterTimestamp",
"(",
"file_stat",... | 28.828571 | 21.985714 |
def register_animation(self, animation_class):
"""Add a new animation"""
self.state.animationClasses.append(animation_class)
return len(self.state.animationClasses) - 1 | [
"def",
"register_animation",
"(",
"self",
",",
"animation_class",
")",
":",
"self",
".",
"state",
".",
"animationClasses",
".",
"append",
"(",
"animation_class",
")",
"return",
"len",
"(",
"self",
".",
"state",
".",
"animationClasses",
")",
"-",
"1"
] | 47.25 | 9 |
def _is_one_arg_pos_call(call):
"""Is this a call with exactly 1 argument,
where that argument is positional?
"""
return isinstance(call, astroid.Call) and len(call.args) == 1 and not call.keywords | [
"def",
"_is_one_arg_pos_call",
"(",
"call",
")",
":",
"return",
"isinstance",
"(",
"call",
",",
"astroid",
".",
"Call",
")",
"and",
"len",
"(",
"call",
".",
"args",
")",
"==",
"1",
"and",
"not",
"call",
".",
"keywords"
] | 41.8 | 11.6 |
def download_data_dictionary(request, dataset_id):
"""Generates and returns compiled data dictionary from database.
Returned as a CSV response.
"""
dataset = Dataset.objects.get(pk=dataset_id)
dataDict = dataset.data_dictionary
fields = DataDictionaryField.objects.filter(
parent_dict=da... | [
"def",
"download_data_dictionary",
"(",
"request",
",",
"dataset_id",
")",
":",
"dataset",
"=",
"Dataset",
".",
"objects",
".",
"get",
"(",
"pk",
"=",
"dataset_id",
")",
"dataDict",
"=",
"dataset",
".",
"data_dictionary",
"fields",
"=",
"DataDictionaryField",
... | 32.666667 | 19.848485 |
def update_segment(self, selector, base, size, perms):
""" Only useful for setting FS right now. """
logger.info("Updating selector %s to 0x%02x (%s bytes) (%s)", selector, base, size, perms)
if selector == 99:
self.set_fs(base)
else:
logger.error("No way to write... | [
"def",
"update_segment",
"(",
"self",
",",
"selector",
",",
"base",
",",
"size",
",",
"perms",
")",
":",
"logger",
".",
"info",
"(",
"\"Updating selector %s to 0x%02x (%s bytes) (%s)\"",
",",
"selector",
",",
"base",
",",
"size",
",",
"perms",
")",
"if",
"se... | 48.285714 | 21.285714 |
def makeExtensionLoginMethod(extensionKey):
'''Return a function that will call the vim.SessionManager.Login() method
with the given parameters. The result of this function can be passed as
the "loginMethod" to a SessionOrientedStub constructor.'''
def _doLogin(soapStub):
si = vim.Serv... | [
"def",
"makeExtensionLoginMethod",
"(",
"extensionKey",
")",
":",
"def",
"_doLogin",
"(",
"soapStub",
")",
":",
"si",
"=",
"vim",
".",
"ServiceInstance",
"(",
"\"ServiceInstance\"",
",",
"soapStub",
")",
"sm",
"=",
"si",
".",
"content",
".",
"sessionManager",
... | 48 | 22 |
def force_auto(service, _type):
"""
Helper for forcing autoserialization of a datatype with already registered explicit
storable instance.
Arguments:
service (StorableService): active storable service.
_type (type): type to be autoserialized.
**Not tested**
"""
storable =... | [
"def",
"force_auto",
"(",
"service",
",",
"_type",
")",
":",
"storable",
"=",
"service",
".",
"byPythonType",
"(",
"_type",
",",
"istype",
"=",
"True",
")",
"version",
"=",
"max",
"(",
"handler",
".",
"version",
"[",
"0",
"]",
"for",
"handler",
"in",
... | 31.352941 | 22.882353 |
def rotate(self, steps):
"""
Return deque with elements rotated steps steps.
>>> x = pdeque([1, 2, 3])
>>> x.rotate(1)
pdeque([3, 1, 2])
>>> x.rotate(-2)
pdeque([3, 1, 2])
"""
popped_deque = self.pop(steps)
if steps >= 0:
retur... | [
"def",
"rotate",
"(",
"self",
",",
"steps",
")",
":",
"popped_deque",
"=",
"self",
".",
"pop",
"(",
"steps",
")",
"if",
"steps",
">=",
"0",
":",
"return",
"popped_deque",
".",
"extendleft",
"(",
"islice",
"(",
"self",
".",
"reverse",
"(",
")",
",",
... | 28 | 16.666667 |
def _collapse_edge_by_namespace(graph: BELGraph,
victim_namespaces: Strings,
survivor_namespaces: str,
relations: Strings) -> None:
"""Collapse pairs of nodes with the given namespaces that have the given relationship.
... | [
"def",
"_collapse_edge_by_namespace",
"(",
"graph",
":",
"BELGraph",
",",
"victim_namespaces",
":",
"Strings",
",",
"survivor_namespaces",
":",
"str",
",",
"relations",
":",
"Strings",
")",
"->",
"None",
":",
"relation_filter",
"=",
"build_relation_predicate",
"(",
... | 42.681818 | 21.545455 |
def compile_file(self, filename, ns):
"""
Compile a MOF file into a namespace of the associated CIM repository.
Parameters:
filename (:term:`string`):
The path name of the MOF file containing the MOF statements to be
compiled.
ns (:term:`string`):
... | [
"def",
"compile_file",
"(",
"self",
",",
"filename",
",",
"ns",
")",
":",
"if",
"self",
".",
"parser",
".",
"verbose",
":",
"self",
".",
"parser",
".",
"log",
"(",
"_format",
"(",
"\"Compiling file {0!A}\"",
",",
"filename",
")",
")",
"if",
"not",
"os"... | 33.026316 | 21.184211 |
def _advapi32_generate_pair(algorithm, bit_size=None):
"""
Generates a public/private key pair using CryptoAPI
:param algorithm:
The key algorithm - "rsa" or "dsa"
:param bit_size:
An integer - used for "rsa" and "dsa". For "rsa" the value maye be 1024,
2048, 3072 or 4096. For ... | [
"def",
"_advapi32_generate_pair",
"(",
"algorithm",
",",
"bit_size",
"=",
"None",
")",
":",
"if",
"algorithm",
"==",
"'rsa'",
":",
"provider",
"=",
"Advapi32Const",
".",
"MS_ENH_RSA_AES_PROV",
"algorithm_id",
"=",
"Advapi32Const",
".",
"CALG_RSA_SIGN",
"struct_type"... | 32.553571 | 22.785714 |
def img2img_transformer2d_n24():
"""Set of hyperparameters."""
hparams = img2img_transformer2d_base()
hparams.batch_size = 1
hparams.hidden_size = 1024
hparams.filter_size = 2048
hparams.layer_prepostprocess_dropout = 0.2
hparams.num_decoder_layers = 8
hparams.query_shape = (8, 16)
hparams.memory_flan... | [
"def",
"img2img_transformer2d_n24",
"(",
")",
":",
"hparams",
"=",
"img2img_transformer2d_base",
"(",
")",
"hparams",
".",
"batch_size",
"=",
"1",
"hparams",
".",
"hidden_size",
"=",
"1024",
"hparams",
".",
"filter_size",
"=",
"2048",
"hparams",
".",
"layer_prep... | 30.818182 | 9.090909 |
def read_file(self, registry):
"""Returns reading file
"""
with open(registry, "r") as file_txt:
read_file = file_txt.read()
file_txt.close()
return read_file | [
"def",
"read_file",
"(",
"self",
",",
"registry",
")",
":",
"with",
"open",
"(",
"registry",
",",
"\"r\"",
")",
"as",
"file_txt",
":",
"read_file",
"=",
"file_txt",
".",
"read",
"(",
")",
"file_txt",
".",
"close",
"(",
")",
"return",
"read_file"
] | 30.285714 | 5.714286 |
def reducePrecision(element):
"""
Because opacities, letter spacings, stroke widths and all that don't need
to be preserved in SVG files with 9 digits of precision.
Takes all of these attributes, in the given element node and its children,
and reduces their precision to the current Decimal context'... | [
"def",
"reducePrecision",
"(",
"element",
")",
":",
"num",
"=",
"0",
"styles",
"=",
"_getStyle",
"(",
"element",
")",
"for",
"lengthAttr",
"in",
"[",
"'opacity'",
",",
"'flood-opacity'",
",",
"'fill-opacity'",
",",
"'stroke-opacity'",
",",
"'stop-opacity'",
",... | 41.659091 | 18.204545 |
def _to_dict(self):
"""Return a json dictionary representing this model."""
_dict = {}
if hasattr(self, 'authors') and self.authors is not None:
_dict['authors'] = [x._to_dict() for x in self.authors]
if hasattr(self,
'publication_date') and self.publicatio... | [
"def",
"_to_dict",
"(",
"self",
")",
":",
"_dict",
"=",
"{",
"}",
"if",
"hasattr",
"(",
"self",
",",
"'authors'",
")",
"and",
"self",
".",
"authors",
"is",
"not",
"None",
":",
"_dict",
"[",
"'authors'",
"]",
"=",
"[",
"x",
".",
"_to_dict",
"(",
"... | 49.2 | 18.466667 |
def get_acls(path, profile=None, hosts=None, scheme=None, username=None, password=None, default_acl=None):
'''
Get acls on a znode
path
path to znode
profile
Configured Zookeeper profile to authenticate with (Default: None)
hosts
Lists of Zookeeper Hosts (Default: '127.0.0... | [
"def",
"get_acls",
"(",
"path",
",",
"profile",
"=",
"None",
",",
"hosts",
"=",
"None",
",",
"scheme",
"=",
"None",
",",
"username",
"=",
"None",
",",
"password",
"=",
"None",
",",
"default_acl",
"=",
"None",
")",
":",
"conn",
"=",
"_get_zk_conn",
"(... | 25.714286 | 30.971429 |
def event(self, name, etype, **info):
"""
Records an event to MongoDB. Events can be later viewed in web status.
Parameters:
name: the name of the event, for example, "Work".
etype: the type of the event, can be either "begin", "end" or
"single".
i... | [
"def",
"event",
"(",
"self",
",",
"name",
",",
"etype",
",",
"*",
"*",
"info",
")",
":",
"if",
"etype",
"not",
"in",
"(",
"\"begin\"",
",",
"\"end\"",
",",
"\"single\"",
")",
":",
"raise",
"ValueError",
"(",
"\"Event type must any of the following: 'begin', ... | 46.807692 | 13.653846 |
def monitor_deletion():
"""
Function for checking for correct deletion of weakref-able objects.
Example usage::
monitor, is_alive = monitor_deletion()
obj = set()
monitor(obj, "obj")
assert is_alive("obj") # True because there is a ref to `obj` is_alive
del obj
... | [
"def",
"monitor_deletion",
"(",
")",
":",
"monitors",
"=",
"{",
"}",
"def",
"set_deleted",
"(",
"x",
")",
":",
"def",
"_",
"(",
"weakref",
")",
":",
"del",
"monitors",
"[",
"x",
"]",
"return",
"_",
"def",
"monitor",
"(",
"item",
",",
"name",
")",
... | 24.035714 | 22.964286 |
def renew(self, requested_timeout=None):
"""Renew the event subscription.
You should not try to renew a subscription which has been
unsubscribed, or once it has expired.
Args:
requested_timeout (int, optional): The period for which a renewal
request should b... | [
"def",
"renew",
"(",
"self",
",",
"requested_timeout",
"=",
"None",
")",
":",
"# NB This code is sometimes called from a separate thread (when",
"# subscriptions are auto-renewed. Be careful to ensure thread-safety",
"if",
"self",
".",
"_has_been_unsubscribed",
":",
"raise",
"SoC... | 40.351852 | 17.037037 |
def _set_vni_mask(self, v, load=False):
"""
Setter method for vni_mask, mapped from YANG variable /overlay/access_list/type/vxlan/standard/seq/vni_mask (string)
If this variable is read-only (config: false) in the
source YANG file, then _set_vni_mask is considered as a private
method. Backends looki... | [
"def",
"_set_vni_mask",
"(",
"self",
",",
"v",
",",
"load",
"=",
"False",
")",
":",
"if",
"hasattr",
"(",
"v",
",",
"\"_utype\"",
")",
":",
"v",
"=",
"v",
".",
"_utype",
"(",
"v",
")",
"try",
":",
"t",
"=",
"YANGDynClass",
"(",
"v",
",",
"base"... | 85.136364 | 40.590909 |
def post_grade2(self, grade, user=None, comment=''):
"""
Post grade to LTI consumer using REST/JSON
URL munging will is related to:
https://openedx.atlassian.net/browse/PLAT-281
:param: grade: 0 <= grade <= 1
:return: True if post successful and grade valid
:exce... | [
"def",
"post_grade2",
"(",
"self",
",",
"grade",
",",
"user",
"=",
"None",
",",
"comment",
"=",
"''",
")",
":",
"content_type",
"=",
"'application/vnd.ims.lis.v2.result+json'",
"if",
"user",
"is",
"None",
":",
"user",
"=",
"self",
".",
"user_id",
"lti2_url",... | 38.0625 | 15.25 |
def _none_subst(self, *args):
""" Helper function to insert full ranges for |None| for X_iter methods.
Custom method, specifically tailored, taking in the arguments from
an X_iter method and performing the replacement of |None| after
error-checking the arguments for a max of one |None| ... | [
"def",
"_none_subst",
"(",
"self",
",",
"*",
"args",
")",
":",
"# Imports",
"import",
"numpy",
"as",
"np",
"# Initialize argument list return value, and as None not found",
"arglist",
"=",
"[",
"a",
"for",
"a",
"in",
"args",
"]",
"none_found",
"=",
"False",
"# C... | 40.126984 | 25.253968 |
def send(self_p, dest, flags):
"""
Send a frame to a socket, destroy frame after sending.
Return -1 on error, 0 on success.
"""
return lib.zframe_send(byref(zframe_p.from_param(self_p)), dest, flags) | [
"def",
"send",
"(",
"self_p",
",",
"dest",
",",
"flags",
")",
":",
"return",
"lib",
".",
"zframe_send",
"(",
"byref",
"(",
"zframe_p",
".",
"from_param",
"(",
"self_p",
")",
")",
",",
"dest",
",",
"flags",
")"
] | 37.666667 | 13 |
def moveVisibleCol(sheet, fromVisColIdx, toVisColIdx):
'Move visible column to another visible index in sheet.'
toVisColIdx = min(max(toVisColIdx, 0), sheet.nVisibleCols)
fromColIdx = sheet.columns.index(sheet.visibleCols[fromVisColIdx])
toColIdx = sheet.columns.index(sheet.visibleCols[toVisColIdx])
... | [
"def",
"moveVisibleCol",
"(",
"sheet",
",",
"fromVisColIdx",
",",
"toVisColIdx",
")",
":",
"toVisColIdx",
"=",
"min",
"(",
"max",
"(",
"toVisColIdx",
",",
"0",
")",
",",
"sheet",
".",
"nVisibleCols",
")",
"fromColIdx",
"=",
"sheet",
".",
"columns",
".",
... | 55.285714 | 20.428571 |
def _incr_exceptions(self):
"""Increment the number of exceptions for the current connection."""
self._pool_manager.get_connection(self.pid, self._conn).exceptions += 1 | [
"def",
"_incr_exceptions",
"(",
"self",
")",
":",
"self",
".",
"_pool_manager",
".",
"get_connection",
"(",
"self",
".",
"pid",
",",
"self",
".",
"_conn",
")",
".",
"exceptions",
"+=",
"1"
] | 60.666667 | 17.333333 |
def get_max_cost(self, class_value, inst=None):
"""
Gets the maximum cost for a particular class value.
:param class_value: the class value to get the maximum cost for
:type class_value: int
:param inst: the Instance
:type inst: Instance
:return: the cost
... | [
"def",
"get_max_cost",
"(",
"self",
",",
"class_value",
",",
"inst",
"=",
"None",
")",
":",
"if",
"inst",
"is",
"None",
":",
"return",
"javabridge",
".",
"call",
"(",
"self",
".",
"jobject",
",",
"\"getMaxCost\"",
",",
"\"(I)D\"",
",",
"class_value",
")"... | 35.588235 | 17.352941 |
def tree_adj_to_prec(graph, root=0):
"""Transforms a tree given as adjacency list into predecessor table form.
if graph is not a tree: will return a DFS spanning tree
:param graph: directed graph in listlist or listdict format
:returns: tree in predecessor table representation
:complexity: linear
... | [
"def",
"tree_adj_to_prec",
"(",
"graph",
",",
"root",
"=",
"0",
")",
":",
"prec",
"=",
"[",
"None",
"]",
"*",
"len",
"(",
"graph",
")",
"prec",
"[",
"root",
"]",
"=",
"root",
"# mark to visit root only once",
"to_visit",
"=",
"[",
"root",
"]",
"while",... | 38.526316 | 12.736842 |
def publish(self, message_type, message_payload):
"""
Publish the specified object that the function automatically converts
into a JSON string representation.
This function use the lowered class name of the service as the AMQP
routing key. For instance, if the class ``ExampleSe... | [
"def",
"publish",
"(",
"self",
",",
"message_type",
",",
"message_payload",
")",
":",
"payload",
"=",
"json",
".",
"dumps",
"(",
"jsonpickle",
".",
"Pickler",
"(",
"unpicklable",
"=",
"False",
")",
".",
"flatten",
"(",
"message_payload",
")",
")",
"message... | 51.518519 | 29.518519 |
def center_eigenvalue_diff(mat):
"""Compute the eigvals of mat and then find the center eigval difference."""
N = len(mat)
evals = np.sort(la.eigvals(mat))
diff = np.abs(evals[N/2] - evals[N/2-1])
return diff | [
"def",
"center_eigenvalue_diff",
"(",
"mat",
")",
":",
"N",
"=",
"len",
"(",
"mat",
")",
"evals",
"=",
"np",
".",
"sort",
"(",
"la",
".",
"eigvals",
"(",
"mat",
")",
")",
"diff",
"=",
"np",
".",
"abs",
"(",
"evals",
"[",
"N",
"/",
"2",
"]",
"... | 37.166667 | 10.833333 |
def endpoint_delete(auth=None, **kwargs):
'''
Delete an endpoint
CLI Example:
.. code-block:: bash
salt '*' keystoneng.endpoint_delete id=3bee4bd8c2b040ee966adfda1f0bfca9
'''
cloud = get_operator_cloud(auth)
kwargs = _clean_kwargs(**kwargs)
return cloud.delete_endpoint(**kwarg... | [
"def",
"endpoint_delete",
"(",
"auth",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"cloud",
"=",
"get_operator_cloud",
"(",
"auth",
")",
"kwargs",
"=",
"_clean_kwargs",
"(",
"*",
"*",
"kwargs",
")",
"return",
"cloud",
".",
"delete_endpoint",
"(",
"*"... | 23.846154 | 22.615385 |
def _get_schema_file(extension, path):
"""
Returns the schema file
:param extension: extension of the schema file usually .schema
:param path: path to the folder containing the schema file
:return: the path to the schema file
"""
for file in os.listdir(path):
... | [
"def",
"_get_schema_file",
"(",
"extension",
",",
"path",
")",
":",
"for",
"file",
"in",
"os",
".",
"listdir",
"(",
"path",
")",
":",
"if",
"file",
".",
"endswith",
"(",
"extension",
")",
":",
"return",
"os",
".",
"path",
".",
"join",
"(",
"path",
... | 39.5 | 8.1 |
def update_reading_events(readings, event_record):
""" Updates readings from a 300 row to reflect any events found in a
subsequent 400 row
"""
# event intervals are 1-indexed
for i in range(event_record.start_interval - 1, event_record.end_interval):
readings[i] = Reading(
t_... | [
"def",
"update_reading_events",
"(",
"readings",
",",
"event_record",
")",
":",
"# event intervals are 1-indexed",
"for",
"i",
"in",
"range",
"(",
"event_record",
".",
"start_interval",
"-",
"1",
",",
"event_record",
".",
"end_interval",
")",
":",
"readings",
"[",... | 42.235294 | 9.588235 |
def list(self, **params):
"""
Retrieve all tags
Returns all tags available to the user, according to the parameters provided
:calls: ``get /tags``
:param dict params: (optional) Search options.
:return: List of dictionaries that support attriubte-style access, which rep... | [
"def",
"list",
"(",
"self",
",",
"*",
"*",
"params",
")",
":",
"_",
",",
"_",
",",
"tags",
"=",
"self",
".",
"http_client",
".",
"get",
"(",
"\"/tags\"",
",",
"params",
"=",
"params",
")",
"return",
"tags"
] | 32.357143 | 25.357143 |
def first(self, default=None, as_dict=False, as_ordereddict=False):
"""Returns a single record for the RecordCollection, or `default`. If
`default` is an instance or subclass of Exception, then raise it
instead of returning it."""
# Try to get a record, or return/raise default.
... | [
"def",
"first",
"(",
"self",
",",
"default",
"=",
"None",
",",
"as_dict",
"=",
"False",
",",
"as_ordereddict",
"=",
"False",
")",
":",
"# Try to get a record, or return/raise default.",
"try",
":",
"record",
"=",
"self",
"[",
"0",
"]",
"except",
"IndexError",
... | 32.8 | 16.9 |
def wiki(self):
"""Returns the wiki markup describing the details of the github pull request
as well as a link to the details on github.
"""
date = self.pull.created_at.strftime("%m/%d/%Y %H:%M")
return "{} {} ({} [{} github])\n".format(self.pull.avatar_url, self.pull.body, date,... | [
"def",
"wiki",
"(",
"self",
")",
":",
"date",
"=",
"self",
".",
"pull",
".",
"created_at",
".",
"strftime",
"(",
"\"%m/%d/%Y %H:%M\"",
")",
"return",
"\"{} {} ({} [{} github])\\n\"",
".",
"format",
"(",
"self",
".",
"pull",
".",
"avatar_url",
",",
"self",
... | 54.714286 | 19.714286 |
def _ReadFloatingPointDataTypeDefinition(
self, definitions_registry, definition_values, definition_name,
is_member=False):
"""Reads a floating-point data type definition.
Args:
definitions_registry (DataTypeDefinitionsRegistry): data type definitions
registry.
definition_valu... | [
"def",
"_ReadFloatingPointDataTypeDefinition",
"(",
"self",
",",
"definitions_registry",
",",
"definition_values",
",",
"definition_name",
",",
"is_member",
"=",
"False",
")",
":",
"return",
"self",
".",
"_ReadFixedSizeDataTypeDefinition",
"(",
"definitions_registry",
","... | 41.52381 | 20.285714 |
def render_template(content, context):
""" renders context aware template """
rendered = Template(content).render(Context(context))
return rendered | [
"def",
"render_template",
"(",
"content",
",",
"context",
")",
":",
"rendered",
"=",
"Template",
"(",
"content",
")",
".",
"render",
"(",
"Context",
"(",
"context",
")",
")",
"return",
"rendered"
] | 39 | 10 |
def get(value: str) -> 'Protocol':
"""
Return enum instance corresponding to input version value ('RsaVerificationKey2018' etc.)
"""
for pktype in PublicKeyType:
if value in (pktype.ver_type, pktype.authn_type):
return pktype
return None | [
"def",
"get",
"(",
"value",
":",
"str",
")",
"->",
"'Protocol'",
":",
"for",
"pktype",
"in",
"PublicKeyType",
":",
"if",
"value",
"in",
"(",
"pktype",
".",
"ver_type",
",",
"pktype",
".",
"authn_type",
")",
":",
"return",
"pktype",
"return",
"None"
] | 33.111111 | 17.777778 |
def fast_scan(self, M, verbose=True):
"""
LMLs, fixed-effect sizes, and scales for single-marker scan.
Parameters
----------
M : array_like
Matrix of fixed-effects across columns.
verbose : bool, optional
``True`` for progress information; ``False... | [
"def",
"fast_scan",
"(",
"self",
",",
"M",
",",
"verbose",
"=",
"True",
")",
":",
"from",
"tqdm",
"import",
"tqdm",
"if",
"M",
".",
"ndim",
"!=",
"2",
":",
"raise",
"ValueError",
"(",
"\"`M` array must be bidimensional.\"",
")",
"p",
"=",
"M",
".",
"sh... | 29.578125 | 17.828125 |
def calibrate_pols(cross_pols,diode_cross,obsI=None,onefile=True,feedtype='l',**kwargs):
'''
Write Stokes-calibrated filterbank file for a given observation
with a calibrator noise diode measurement on the source
Parameters
----------
cross_pols : string
Path to cross polarization filte... | [
"def",
"calibrate_pols",
"(",
"cross_pols",
",",
"diode_cross",
",",
"obsI",
"=",
"None",
",",
"onefile",
"=",
"True",
",",
"feedtype",
"=",
"'l'",
",",
"*",
"*",
"kwargs",
")",
":",
"#Obtain time sample length, frequencies, and noise diode data",
"obs",
"=",
"W... | 42.695122 | 26.695122 |
def has_auth_params(self, scheme):
"""Check whether all information required for a given auth scheme have
been supplied.
Args:
scheme (str): Name of the authentication scheme to check. One of
Gem-Identify, Gem-Device, Gem-Application
Returns:
True if all... | [
"def",
"has_auth_params",
"(",
"self",
",",
"scheme",
")",
":",
"for",
"k",
",",
"v",
"in",
"iteritems",
"(",
"self",
".",
"schemes",
"[",
"scheme",
"]",
"[",
"u'params'",
"]",
")",
":",
"if",
"not",
"v",
":",
"return",
"False",
"return",
"True"
] | 34.933333 | 20.066667 |
def _on_response(self, action, table, attempt, start, response, future,
measurements):
"""Invoked when the HTTP request to the DynamoDB has returned and
is responsible for setting the future result or exception based upon
the HTTP response provided.
:param str actio... | [
"def",
"_on_response",
"(",
"self",
",",
"action",
",",
"table",
",",
"attempt",
",",
"start",
",",
"response",
",",
"future",
",",
"measurements",
")",
":",
"self",
".",
"logger",
".",
"debug",
"(",
"'%s on %s request #%i = %r'",
",",
"action",
",",
"tabl... | 48.415094 | 19.207547 |
def reset(self):
""" Reset target collection (rebuild index).
"""
self.connection.rebuild_index(
self.index, coll_name=self.target_coll_name) | [
"def",
"reset",
"(",
"self",
")",
":",
"self",
".",
"connection",
".",
"rebuild_index",
"(",
"self",
".",
"index",
",",
"coll_name",
"=",
"self",
".",
"target_coll_name",
")"
] | 34.6 | 8.4 |
def write_pid_file(self, overwrite=False):
"""Create a .pid file in the pid_dir with my pid.
This must be called after pre_construct, which sets `self.pid_dir`.
This raises :exc:`PIDFileError` if the pid file exists already.
"""
pid_file = os.path.join(self.profile_dir.pid_dir, ... | [
"def",
"write_pid_file",
"(",
"self",
",",
"overwrite",
"=",
"False",
")",
":",
"pid_file",
"=",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"profile_dir",
".",
"pid_dir",
",",
"self",
".",
"name",
"+",
"u'.pid'",
")",
"if",
"os",
".",
"path",
... | 47 | 17.705882 |
def _prt_txt_desc2nts(self, prt, desc2nts, prtfmt=None):
"""Print grouped and sorted GO IDs."""
if prtfmt is None:
prtfmt = self.get_prtfmt("fmta")
if self.ver_list is not None:
prt.write("# Versions:\n# {VER}\n".format(VER="\n# ".join(self.ver_list)))
self.... | [
"def",
"_prt_txt_desc2nts",
"(",
"self",
",",
"prt",
",",
"desc2nts",
",",
"prtfmt",
"=",
"None",
")",
":",
"if",
"prtfmt",
"is",
"None",
":",
"prtfmt",
"=",
"self",
".",
"get_prtfmt",
"(",
"\"fmta\"",
")",
"if",
"self",
".",
"ver_list",
"is",
"not",
... | 50.428571 | 14.428571 |
def frombytes(self, bytes, offset=0):
"""Load data from array or list of bytes.
Similar to loadbin() method but works directly with iterable bytes.
"""
for b in bytes:
self._buf[offset] = b
offset += 1 | [
"def",
"frombytes",
"(",
"self",
",",
"bytes",
",",
"offset",
"=",
"0",
")",
":",
"for",
"b",
"in",
"bytes",
":",
"self",
".",
"_buf",
"[",
"offset",
"]",
"=",
"b",
"offset",
"+=",
"1"
] | 35.857143 | 11.285714 |
def assemble_schedules(schedules, qobj_id=None, qobj_header=None, run_config=None):
"""Assembles a list of schedules into a qobj which can be run on the backend.
Args:
schedules (list[Schedule]): schedules to assemble
qobj_id (int): identifier for the generated qobj
qobj_header (QobjHead... | [
"def",
"assemble_schedules",
"(",
"schedules",
",",
"qobj_id",
"=",
"None",
",",
"qobj_header",
"=",
"None",
",",
"run_config",
"=",
"None",
")",
":",
"qobj_config",
"=",
"QasmQobjConfig",
"(",
")",
"if",
"run_config",
":",
"qobj_config",
"=",
"QasmQobjConfig"... | 42.20202 | 19.818182 |
def get_name(self):
"""
Tries to get WF name from 'process' or 'collobration' or 'pariticipant'
Returns:
str. WF name.
"""
ns = {'ns': '{%s}' % BPMN_MODEL_NS}
for path in ('.//{ns}process',
'.//{ns}collaboration',
'./... | [
"def",
"get_name",
"(",
"self",
")",
":",
"ns",
"=",
"{",
"'ns'",
":",
"'{%s}'",
"%",
"BPMN_MODEL_NS",
"}",
"for",
"path",
"in",
"(",
"'.//{ns}process'",
",",
"'.//{ns}collaboration'",
",",
"'.//{ns}collaboration/{ns}participant/'",
")",
":",
"tag",
"=",
"self... | 31.882353 | 14.117647 |
def clean_indicators(indicators):
"""Remove any extra details from indicators."""
output = list()
for indicator in indicators:
strip = ['http://', 'https://']
for item in strip:
indicator = indicator.replace(item, '')
indicator = indicator.strip('.').strip()
parts... | [
"def",
"clean_indicators",
"(",
"indicators",
")",
":",
"output",
"=",
"list",
"(",
")",
"for",
"indicator",
"in",
"indicators",
":",
"strip",
"=",
"[",
"'http://'",
",",
"'https://'",
"]",
"for",
"item",
"in",
"strip",
":",
"indicator",
"=",
"indicator",
... | 34 | 9.5 |
def payload(self):
"""Extracts and returns the serialized object."""
try:
rdf_cls = self.classes.get(self.name)
if rdf_cls:
value = rdf_cls.FromSerializedString(self.data)
value.age = self.embedded_age
return value
except TypeError:
return None | [
"def",
"payload",
"(",
"self",
")",
":",
"try",
":",
"rdf_cls",
"=",
"self",
".",
"classes",
".",
"get",
"(",
"self",
".",
"name",
")",
"if",
"rdf_cls",
":",
"value",
"=",
"rdf_cls",
".",
"FromSerializedString",
"(",
"self",
".",
"data",
")",
"value"... | 26.272727 | 18.181818 |
def search(self, pattern, minAddr = None, maxAddr = None):
"""
Search for the given pattern within the process memory.
@type pattern: str, compat.unicode or L{Pattern}
@param pattern: Pattern to search for.
It may be a byte string, a Unicode string, or an instance of
... | [
"def",
"search",
"(",
"self",
",",
"pattern",
",",
"minAddr",
"=",
"None",
",",
"maxAddr",
"=",
"None",
")",
":",
"if",
"isinstance",
"(",
"pattern",
",",
"str",
")",
":",
"return",
"self",
".",
"search_bytes",
"(",
"pattern",
",",
"minAddr",
",",
"m... | 40.878049 | 21.902439 |
def _calculate_dispersion(X: Union[pd.DataFrame, np.ndarray], labels: np.ndarray, centroids: np.ndarray) -> float:
"""
Calculate the dispersion between actual points and their assigned centroids
"""
disp = np.sum(np.sum([np.abs(inst - centroids[label]) ** 2 for inst, label in zip(X, labe... | [
"def",
"_calculate_dispersion",
"(",
"X",
":",
"Union",
"[",
"pd",
".",
"DataFrame",
",",
"np",
".",
"ndarray",
"]",
",",
"labels",
":",
"np",
".",
"ndarray",
",",
"centroids",
":",
"np",
".",
"ndarray",
")",
"->",
"float",
":",
"disp",
"=",
"np",
... | 59.333333 | 36 |
def save(self, name):
"""
Copy the contents of the temporary file somewhere else. Finalizes prior to saving.
:param name: File path.
:type name: unicode | str
"""
self.finalize()
with open(name, 'wb+') as f:
buf = self._fileobj.read()
whil... | [
"def",
"save",
"(",
"self",
",",
"name",
")",
":",
"self",
".",
"finalize",
"(",
")",
"with",
"open",
"(",
"name",
",",
"'wb+'",
")",
"as",
"f",
":",
"buf",
"=",
"self",
".",
"_fileobj",
".",
"read",
"(",
")",
"while",
"buf",
":",
"f",
".",
"... | 29.692308 | 13.846154 |
def maybe_future(x: Any) -> Future:
"""Converts ``x`` into a `.Future`.
If ``x`` is already a `.Future`, it is simply returned; otherwise
it is wrapped in a new `.Future`. This is suitable for use as
``result = yield gen.maybe_future(f())`` when you don't know whether
``f()`` returns a `.Future` o... | [
"def",
"maybe_future",
"(",
"x",
":",
"Any",
")",
"->",
"Future",
":",
"if",
"is_future",
"(",
"x",
")",
":",
"return",
"x",
"else",
":",
"fut",
"=",
"_create_future",
"(",
")",
"fut",
".",
"set_result",
"(",
"x",
")",
"return",
"fut"
] | 36.105263 | 21.578947 |
def to_str(value):
"""Convert the input to a string, unless it is a unicode string in Python 2.
Unicode strings are supported as native strings in Python 3, but ``str()`` cannot be
invoked on unicode strings in Python 2, so we need to check for that case when
converting user-specified values to strings... | [
"def",
"to_str",
"(",
"value",
")",
":",
"if",
"sys",
".",
"version_info",
".",
"major",
"<",
"3",
"and",
"isinstance",
"(",
"value",
",",
"six",
".",
"string_types",
")",
":",
"return",
"value",
"return",
"str",
"(",
"value",
")"
] | 37.4375 | 27 |
def get_background_sids(self, src_filter):
"""
We can apply the filtering of the background sites as a pre-processing
step - this is done here rather than in the sampling of the ruptures
themselves
"""
branch_key = self.idx_set["grid_key"]
idist = src_filter.integ... | [
"def",
"get_background_sids",
"(",
"self",
",",
"src_filter",
")",
":",
"branch_key",
"=",
"self",
".",
"idx_set",
"[",
"\"grid_key\"",
"]",
"idist",
"=",
"src_filter",
".",
"integration_distance",
"(",
"DEFAULT_TRT",
")",
"with",
"h5py",
".",
"File",
"(",
"... | 51.190476 | 16.142857 |
def get_logger():
"""Get or create logger (if it does not exist)
@rtype: RootLogger
"""
name = Logr.get_logger_name()
if name not in Logr.loggers:
Logr.configure_check()
Logr.loggers[name] = logging.Logger(name)
Logr.loggers[name].addHandler(L... | [
"def",
"get_logger",
"(",
")",
":",
"name",
"=",
"Logr",
".",
"get_logger_name",
"(",
")",
"if",
"name",
"not",
"in",
"Logr",
".",
"loggers",
":",
"Logr",
".",
"configure_check",
"(",
")",
"Logr",
".",
"loggers",
"[",
"name",
"]",
"=",
"logging",
"."... | 32.363636 | 11.363636 |
def set_autocamera(self,mode='density'):
"""
- set_autocamera(mode='density'): By default, Scene defines its
own Camera. However, there is no a general way for doing so. Scene
uses a density criterion for getting the point of view. If this is
not a good option for your problem... | [
"def",
"set_autocamera",
"(",
"self",
",",
"mode",
"=",
"'density'",
")",
":",
"self",
".",
"Camera",
".",
"set_autocamera",
"(",
"self",
".",
"_Particles",
",",
"mode",
"=",
"mode",
")",
"self",
".",
"_camera_params",
"=",
"self",
".",
"Camera",
".",
... | 56.230769 | 20.692308 |
def sort_schemas(schemas):
"""Sort a list of SQL schemas in order"""
def keyfun(v):
x = SQL_SCHEMA_REGEXP.match(v).groups()
# x3: 'DEV' should come before ''
return (int(x[0]), x[1], int(x[2]) if x[2] else None,
x[3] if x[3] else 'zzz', int(x[4]))
return sorted(schem... | [
"def",
"sort_schemas",
"(",
"schemas",
")",
":",
"def",
"keyfun",
"(",
"v",
")",
":",
"x",
"=",
"SQL_SCHEMA_REGEXP",
".",
"match",
"(",
"v",
")",
".",
"groups",
"(",
")",
"# x3: 'DEV' should come before ''",
"return",
"(",
"int",
"(",
"x",
"[",
"0",
"]... | 36.333333 | 13.111111 |
def fftp(wave, npoints=None, indep_min=None, indep_max=None, unwrap=True, rad=True):
r"""
Return the phase of the Fast Fourier Transform of a waveform.
:param wave: Waveform
:type wave: :py:class:`peng.eng.Waveform`
:param npoints: Number of points to use in the transform. If **npoints**
... | [
"def",
"fftp",
"(",
"wave",
",",
"npoints",
"=",
"None",
",",
"indep_min",
"=",
"None",
",",
"indep_max",
"=",
"None",
",",
"unwrap",
"=",
"True",
",",
"rad",
"=",
"True",
")",
":",
"return",
"phase",
"(",
"fft",
"(",
"wave",
",",
"npoints",
",",
... | 34.363636 | 25.509091 |
def __init_config_params(self, config):
"""Conditionally enable options in the Server's config file."""
if self.version >= (2, 4):
params = config.get('setParameter', {})
# Set enableTestCommands by default but allow enableTestCommands:0.
params.setdefault('enableTest... | [
"def",
"__init_config_params",
"(",
"self",
",",
"config",
")",
":",
"if",
"self",
".",
"version",
">=",
"(",
"2",
",",
"4",
")",
":",
"params",
"=",
"config",
".",
"get",
"(",
"'setParameter'",
",",
"{",
"}",
")",
"# Set enableTestCommands by default but ... | 57.2 | 20.44 |
def restrict_dates(feed: "Feed", dates: List[str]) -> List[str]:
"""
Given a "Feed" and a date (YYYYMMDD string) or list of dates,
coerce the date/dates into a list and drop the dates not in
``feed.get_dates()``, preserving the original order of ``dates``.
Intended as a helper function.
"""
... | [
"def",
"restrict_dates",
"(",
"feed",
":",
"\"Feed\"",
",",
"dates",
":",
"List",
"[",
"str",
"]",
")",
"->",
"List",
"[",
"str",
"]",
":",
"# Coerce string to set",
"if",
"isinstance",
"(",
"dates",
",",
"str",
")",
":",
"dates",
"=",
"[",
"dates",
... | 35.076923 | 17.538462 |
def update(self, percent=None, text=None):
""" Update the progress bar percentage and message. """
if percent is not None:
self.percent = percent
if text is not None:
self.message = text
super().update() | [
"def",
"update",
"(",
"self",
",",
"percent",
"=",
"None",
",",
"text",
"=",
"None",
")",
":",
"if",
"percent",
"is",
"not",
"None",
":",
"self",
".",
"percent",
"=",
"percent",
"if",
"text",
"is",
"not",
"None",
":",
"self",
".",
"message",
"=",
... | 36.142857 | 7.714286 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.