text stringlengths 75 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 0.18 |
|---|---|---|---|
def get_sos_decomposition(sdp, y_mat=None, threshold=0.0):
"""Given a solution of the dual problem, it returns the SOS
decomposition.
:param sdp: The SDP relaxation to be solved.
:type sdp: :class:`ncpol2sdpa.sdp`.
:param y_mat: Optional parameter providing the dual solution of the
... | [
"def",
"get_sos_decomposition",
"(",
"sdp",
",",
"y_mat",
"=",
"None",
",",
"threshold",
"=",
"0.0",
")",
":",
"if",
"len",
"(",
"sdp",
".",
"monomial_sets",
")",
"!=",
"1",
":",
"raise",
"Exception",
"(",
"\"Cannot automatically match primal and dual \"",
"+"... | 42.641509 | 0.000433 |
def _parse_hosts_contents(self, hosts_contents):
"""
Parse the inventory contents. This returns a list of sections found in
the inventory, which can then be used to figure out which hosts belong
to which groups and such. Each section has a name, a type ('hosts',
'children', 'vars... | [
"def",
"_parse_hosts_contents",
"(",
"self",
",",
"hosts_contents",
")",
":",
"sections",
"=",
"[",
"]",
"cur_section",
"=",
"{",
"'type'",
":",
"'hosts'",
",",
"'name'",
":",
"None",
",",
"'entries'",
":",
"[",
"]",
"}",
"for",
"line",
"in",
"hosts_cont... | 34.980392 | 0.001091 |
def process_pmc(pmc_id, offline=False, output_fname=default_output_fname):
"""Return a ReachProcessor by processing a paper with a given PMC id.
Uses the PMC client to obtain the full text. If it's not available,
None is returned.
Parameters
----------
pmc_id : str
The ID of a PubmedCe... | [
"def",
"process_pmc",
"(",
"pmc_id",
",",
"offline",
"=",
"False",
",",
"output_fname",
"=",
"default_output_fname",
")",
":",
"xml_str",
"=",
"pmc_client",
".",
"get_xml",
"(",
"pmc_id",
")",
"if",
"xml_str",
"is",
"None",
":",
"return",
"None",
"fname",
... | 33.882353 | 0.000844 |
def remove(self, value):
"""Remove an entry from the catalog """
ret = libxml2mod.xmlACatalogRemove(self._o, value)
return ret | [
"def",
"remove",
"(",
"self",
",",
"value",
")",
":",
"ret",
"=",
"libxml2mod",
".",
"xmlACatalogRemove",
"(",
"self",
".",
"_o",
",",
"value",
")",
"return",
"ret"
] | 36.75 | 0.013333 |
def find_by_id(self, section, params={}, **options):
"""Returns the complete record for a single section.
Parameters
----------
section : {Id} The section to get.
[params] : {Object} Parameters for the request
"""
path = "/sections/%s" % (section)
return... | [
"def",
"find_by_id",
"(",
"self",
",",
"section",
",",
"params",
"=",
"{",
"}",
",",
"*",
"*",
"options",
")",
":",
"path",
"=",
"\"/sections/%s\"",
"%",
"(",
"section",
")",
"return",
"self",
".",
"client",
".",
"get",
"(",
"path",
",",
"params",
... | 35.2 | 0.00831 |
def _two_qubit_accumulate_into_scratch(args: Dict[str, Any]):
"""Accumulates two qubit phase gates into the scratch shards."""
index0, index1 = args['indices']
half_turns = args['half_turns']
scratch = _scratch_shard(args)
projector = _one_projector(args, index0) * _one_projector(args, index1)
... | [
"def",
"_two_qubit_accumulate_into_scratch",
"(",
"args",
":",
"Dict",
"[",
"str",
",",
"Any",
"]",
")",
":",
"index0",
",",
"index1",
"=",
"args",
"[",
"'indices'",
"]",
"half_turns",
"=",
"args",
"[",
"'half_turns'",
"]",
"scratch",
"=",
"_scratch_shard",
... | 43.6 | 0.002247 |
def continue_prompt(message=""):
"""Prompt the user to continue or not
Returns True when the user type Yes.
:param message: message to display
:type message: str
:rtype: bool
"""
answer = False
message = message + "\n'Yes' or 'No' to continue: "
while answer not in ('Yes', 'No'):
... | [
"def",
"continue_prompt",
"(",
"message",
"=",
"\"\"",
")",
":",
"answer",
"=",
"False",
"message",
"=",
"message",
"+",
"\"\\n'Yes' or 'No' to continue: \"",
"while",
"answer",
"not",
"in",
"(",
"'Yes'",
",",
"'No'",
")",
":",
"answer",
"=",
"prompt",
"(",
... | 24.619048 | 0.001862 |
def disconnect(self):
"""
Ends a client authentication session, performs a logout and a clean up.
"""
if self.r_session:
self.session_logout()
self.r_session = None
self.clear() | [
"def",
"disconnect",
"(",
"self",
")",
":",
"if",
"self",
".",
"r_session",
":",
"self",
".",
"session_logout",
"(",
")",
"self",
".",
"r_session",
"=",
"None",
"self",
".",
"clear",
"(",
")"
] | 25.555556 | 0.008403 |
def get_by_id(cls, record_id, execute=True):
"""Return a single instance of the model queried by ID.
Args:
record_id (int): Integer representation of the ID to query on.
Keyword Args:
execute (bool, optional):
Should this method execute the query or retu... | [
"def",
"get_by_id",
"(",
"cls",
",",
"record_id",
",",
"execute",
"=",
"True",
")",
":",
"query",
"=",
"cls",
".",
"base_query",
"(",
")",
".",
"where",
"(",
"cls",
".",
"id",
"==",
"record_id",
")",
"if",
"execute",
":",
"return",
"query",
".",
"g... | 31.038462 | 0.002404 |
def t_direction(self, s):
r'^[+-]$'
# Used in the "list" command
self.add_token('DIRECTION', s)
self.pos += len(s) | [
"def",
"t_direction",
"(",
"self",
",",
"s",
")",
":",
"# Used in the \"list\" command",
"self",
".",
"add_token",
"(",
"'DIRECTION'",
",",
"s",
")",
"self",
".",
"pos",
"+=",
"len",
"(",
"s",
")"
] | 28.4 | 0.013699 |
def _get_conversion_factor(old_units, new_units, dtype):
"""
Get the conversion factor between two units of equivalent dimensions. This
is the number you multiply data by to convert from values in `old_units` to
values in `new_units`.
Parameters
----------
old_units: str or Unit object
... | [
"def",
"_get_conversion_factor",
"(",
"old_units",
",",
"new_units",
",",
"dtype",
")",
":",
"if",
"old_units",
".",
"dimensions",
"!=",
"new_units",
".",
"dimensions",
":",
"raise",
"UnitConversionError",
"(",
"old_units",
",",
"old_units",
".",
"dimensions",
"... | 34.205882 | 0.000836 |
def sscan(self, name, cursor='0', match=None, count=10):
"""Emulate sscan."""
def value_function():
members = list(self.smembers(name))
members.sort() # sort for consistent order
return members
return self._common_scan(value_function, cursor=cursor, match=mat... | [
"def",
"sscan",
"(",
"self",
",",
"name",
",",
"cursor",
"=",
"'0'",
",",
"match",
"=",
"None",
",",
"count",
"=",
"10",
")",
":",
"def",
"value_function",
"(",
")",
":",
"members",
"=",
"list",
"(",
"self",
".",
"smembers",
"(",
"name",
")",
")"... | 47.142857 | 0.008929 |
def _encode_datetime_with_cftime(dates, units, calendar):
"""Fallback method for encoding dates using cftime.
This method is more flexible than xarray's parsing using datetime64[ns]
arrays but also slower because it loops over each element.
"""
cftime = _import_cftime()
if np.issubdtype(dates.... | [
"def",
"_encode_datetime_with_cftime",
"(",
"dates",
",",
"units",
",",
"calendar",
")",
":",
"cftime",
"=",
"_import_cftime",
"(",
")",
"if",
"np",
".",
"issubdtype",
"(",
"dates",
".",
"dtype",
",",
"np",
".",
"datetime64",
")",
":",
"# numpy's broken date... | 38.125 | 0.0016 |
def _verify_signature(certificate_list, crl_issuer):
"""
Verifies the digital signature on an asn1crypto.crl.CertificateList object
:param certificate_list:
An asn1crypto.crl.CertificateList object
:param crl_issuer:
An asn1crypto.x509.Certificate object of the CRL issuer
:raises:... | [
"def",
"_verify_signature",
"(",
"certificate_list",
",",
"crl_issuer",
")",
":",
"signature_algo",
"=",
"certificate_list",
"[",
"'signature_algorithm'",
"]",
".",
"signature_algo",
"hash_algo",
"=",
"certificate_list",
"[",
"'signature_algorithm'",
"]",
".",
"hash_alg... | 34.119048 | 0.002035 |
def reinit_on_backend_changes(tf_bin, # pylint: disable=too-many-arguments
module_path, backend_options, env_name,
env_region, env_vars):
"""Clean terraform directory and run init if necessary.
If deploying a TF module to multiple regions (or any sce... | [
"def",
"reinit_on_backend_changes",
"(",
"tf_bin",
",",
"# pylint: disable=too-many-arguments",
"module_path",
",",
"backend_options",
",",
"env_name",
",",
"env_region",
",",
"env_vars",
")",
":",
"terraform_dir",
"=",
"os",
".",
"path",
".",
"join",
"(",
"module_p... | 47.063492 | 0.00033 |
def delta(self):
"""The delta between the last event and the current event.
For pointer events that are not of type
:attr:`~libinput.constant.EventType.POINTER_MOTION`, this property
raises :exc:`AttributeError`.
If a device employs pointer acceleration, the delta
returned by this method is the accelerate... | [
"def",
"delta",
"(",
"self",
")",
":",
"if",
"self",
".",
"type",
"!=",
"EventType",
".",
"POINTER_MOTION",
":",
"raise",
"AttributeError",
"(",
"_wrong_prop",
".",
"format",
"(",
"self",
".",
"type",
")",
")",
"delta_x",
"=",
"self",
".",
"_libinput",
... | 33.64 | 0.024277 |
def select_string(self, rows: List[Row], column: StringColumn) -> List[str]:
"""
Select function takes a list of rows and a column name and returns a list of strings as
in cells.
"""
return [str(row.values[column.name]) for row in rows if row.values[column.name] is not None] | [
"def",
"select_string",
"(",
"self",
",",
"rows",
":",
"List",
"[",
"Row",
"]",
",",
"column",
":",
"StringColumn",
")",
"->",
"List",
"[",
"str",
"]",
":",
"return",
"[",
"str",
"(",
"row",
".",
"values",
"[",
"column",
".",
"name",
"]",
")",
"f... | 51.666667 | 0.012698 |
def users_get_presence(self, user_id=None, username=None, **kwargs):
"""Gets the online presence of the a user."""
if user_id:
return self.__call_api_get('users.getPresence', userId=user_id, kwargs=kwargs)
elif username:
return self.__call_api_get('users.getPresence', use... | [
"def",
"users_get_presence",
"(",
"self",
",",
"user_id",
"=",
"None",
",",
"username",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"user_id",
":",
"return",
"self",
".",
"__call_api_get",
"(",
"'users.getPresence'",
",",
"userId",
"=",
"user_id"... | 54.25 | 0.00907 |
def mvee(points, tol=0.001):
"""
Returns the minimum-volume enclosing ellipse (MVEE)
of a set of points, using the Khachiyan algorithm.
"""
# This function is a port of the matlab function by
# Nima Moshtagh found here:
# https://www.mathworks.com/matlabcentral/fileexchange/9542-minimum-vol... | [
"def",
"mvee",
"(",
"points",
",",
"tol",
"=",
"0.001",
")",
":",
"# This function is a port of the matlab function by",
"# Nima Moshtagh found here:",
"# https://www.mathworks.com/matlabcentral/fileexchange/9542-minimum-volume-enclosing-ellipsoid",
"# with accompanying writup here:",
"#... | 31.925 | 0.011398 |
def _result_object(result):
"""
Return the JSON payload in the HTTP response as a Python dict.
Parameters:
result (requests.Response): HTTP response object.
Raises:
zhmcclient.ParseError: Error parsing the returned JSON.
"""
content_type = result.headers.get('content-type', Non... | [
"def",
"_result_object",
"(",
"result",
")",
":",
"content_type",
"=",
"result",
".",
"headers",
".",
"get",
"(",
"'content-type'",
",",
"None",
")",
"if",
"content_type",
"is",
"None",
"or",
"content_type",
".",
"startswith",
"(",
"'application/json'",
")",
... | 42.698925 | 0.000246 |
def record_launch(self, queue_id): # retcode):
"""Save submission"""
self.launches.append(
AttrDict(queue_id=queue_id, mpi_procs=self.mpi_procs, omp_threads=self.omp_threads,
mem_per_proc=self.mem_per_proc, timelimit=self.timelimit))
return len(self.launches) | [
"def",
"record_launch",
"(",
"self",
",",
"queue_id",
")",
":",
"# retcode):",
"self",
".",
"launches",
".",
"append",
"(",
"AttrDict",
"(",
"queue_id",
"=",
"queue_id",
",",
"mpi_procs",
"=",
"self",
".",
"mpi_procs",
",",
"omp_threads",
"=",
"self",
".",... | 51.833333 | 0.012658 |
def get_row_list(self, row_idx):
""" get a feature vector for the nth row
:param row_idx: which row
:return: a list of feature values, ordered by column_names
"""
try:
row = self._rows[row_idx]
except TypeError:
row = self._rows[self._row_name_id... | [
"def",
"get_row_list",
"(",
"self",
",",
"row_idx",
")",
":",
"try",
":",
"row",
"=",
"self",
".",
"_rows",
"[",
"row_idx",
"]",
"except",
"TypeError",
":",
"row",
"=",
"self",
".",
"_rows",
"[",
"self",
".",
"_row_name_idx",
"[",
"row_idx",
"]",
"]"... | 32.904762 | 0.011252 |
def proximal_linfty(space):
r"""Proximal operator factory of the ``l_\infty``-norm.
Function for the proximal operator of the functional ``F`` where ``F``
is the ``l_\infty``-norm::
``F(x) = \sup_i |x_i|``
Parameters
----------
space : `LinearSpace`
Domain of ``F``.
Retu... | [
"def",
"proximal_linfty",
"(",
"space",
")",
":",
"class",
"ProximalLInfty",
"(",
"Operator",
")",
":",
"\"\"\"Proximal operator of the linf-norm.\"\"\"",
"def",
"__init__",
"(",
"self",
",",
"sigma",
")",
":",
"\"\"\"Initialize a new instance.\n\n Parameters\n ... | 22.927273 | 0.00076 |
def add_segmented_colorbar(da, colors, direction):
"""
Add 'non-rastered' colorbar to DrawingArea
"""
nbreak = len(colors)
if direction == 'vertical':
linewidth = da.height/nbreak
verts = [None] * nbreak
x1, x2 = 0, da.width
for i, color in enumerate(colors):
... | [
"def",
"add_segmented_colorbar",
"(",
"da",
",",
"colors",
",",
"direction",
")",
":",
"nbreak",
"=",
"len",
"(",
"colors",
")",
"if",
"direction",
"==",
"'vertical'",
":",
"linewidth",
"=",
"da",
".",
"height",
"/",
"nbreak",
"verts",
"=",
"[",
"None",
... | 33.37037 | 0.001079 |
def get_content_disposition_filename(self, private_file):
"""
Return the filename in the download header.
"""
return self.content_disposition_filename or os.path.basename(private_file.relative_name) | [
"def",
"get_content_disposition_filename",
"(",
"self",
",",
"private_file",
")",
":",
"return",
"self",
".",
"content_disposition_filename",
"or",
"os",
".",
"path",
".",
"basename",
"(",
"private_file",
".",
"relative_name",
")"
] | 45.2 | 0.013043 |
def bubble_to_gexf(bblfile:str, gexffile:str=None, oriented:bool=False):
"""Write in bblfile a graph equivalent to those depicted in bubble file"""
tree = BubbleTree.from_bubble_file(bblfile, oriented=bool(oriented))
gexf_converter.tree_to_file(tree, gexffile)
return gexffile | [
"def",
"bubble_to_gexf",
"(",
"bblfile",
":",
"str",
",",
"gexffile",
":",
"str",
"=",
"None",
",",
"oriented",
":",
"bool",
"=",
"False",
")",
":",
"tree",
"=",
"BubbleTree",
".",
"from_bubble_file",
"(",
"bblfile",
",",
"oriented",
"=",
"bool",
"(",
... | 57.6 | 0.027397 |
def next(self):
"""Return the next match; raises Exception if no next match available"""
# Check the state and find the next match as a side-effect if necessary.
if not self.has_next():
raise StopIteration("No next match")
# Don't retain that memory any longer than necessary.... | [
"def",
"next",
"(",
"self",
")",
":",
"# Check the state and find the next match as a side-effect if necessary.",
"if",
"not",
"self",
".",
"has_next",
"(",
")",
":",
"raise",
"StopIteration",
"(",
"\"No next match\"",
")",
"# Don't retain that memory any longer than necessar... | 45.1 | 0.008696 |
def run(self, src_project=None, path_to_zip_file=None):
"""Run deploy the lambdas defined in our project.
Steps:
* Build Artefact
* Read file or deploy to S3. It's defined in config["deploy"]["deploy_method"]
* Reload conf with deploy changes
* check lambda if exist
... | [
"def",
"run",
"(",
"self",
",",
"src_project",
"=",
"None",
",",
"path_to_zip_file",
"=",
"None",
")",
":",
"if",
"path_to_zip_file",
":",
"code",
"=",
"self",
".",
"set_artefact_path",
"(",
"path_to_zip_file",
")",
"elif",
"not",
"self",
".",
"config",
"[... | 35.862069 | 0.008427 |
def parse_method_signature(sig):
""" Parse a method signature of the form: modifier* type name (params) """
match = METH_SIG_RE.match(sig.strip())
if not match:
raise RuntimeError('Method signature invalid: ' + sig)
modifiers, return_type, name, generic_types, params = match.groups()
if para... | [
"def",
"parse_method_signature",
"(",
"sig",
")",
":",
"match",
"=",
"METH_SIG_RE",
".",
"match",
"(",
"sig",
".",
"strip",
"(",
")",
")",
"if",
"not",
"match",
":",
"raise",
"RuntimeError",
"(",
"'Method signature invalid: '",
"+",
"sig",
")",
"modifiers",
... | 43.666667 | 0.001869 |
def src_paths(self):
"""
Return a list of source files in the diff
for which we have coverage information.
"""
return {src for src, summary in self._diff_violations().items()
if len(summary.measured_lines) > 0} | [
"def",
"src_paths",
"(",
"self",
")",
":",
"return",
"{",
"src",
"for",
"src",
",",
"summary",
"in",
"self",
".",
"_diff_violations",
"(",
")",
".",
"items",
"(",
")",
"if",
"len",
"(",
"summary",
".",
"measured_lines",
")",
">",
"0",
"}"
] | 37.571429 | 0.011152 |
def merge(self, add_me):
"""Merge add_me into context and applies interpolation.
Bottom-up merge where add_me merges into context. Applies string
interpolation where the type is a string. Where a key exists in
context already, add_me's value will overwrite what's in context
alre... | [
"def",
"merge",
"(",
"self",
",",
"add_me",
")",
":",
"def",
"merge_recurse",
"(",
"current",
",",
"add_me",
")",
":",
"\"\"\"Walk the current context tree in recursive inner function.\n\n On 1st iteration, current = self (i.e root of context)\n On subsequent re... | 46.098765 | 0.000524 |
async def execute_process(*cmd, log=None, loop=None):
'''
Wrapper around asyncio.create_subprocess_exec.
'''
p = await asyncio.create_subprocess_exec(
*cmd,
stdin=asyncio.subprocess.PIPE,
stdout=asyncio.subprocess.PIPE,
stderr=asyncio.subprocess.PIPE,
loop=loop)
... | [
"async",
"def",
"execute_process",
"(",
"*",
"cmd",
",",
"log",
"=",
"None",
",",
"loop",
"=",
"None",
")",
":",
"p",
"=",
"await",
"asyncio",
".",
"create_subprocess_exec",
"(",
"*",
"cmd",
",",
"stdin",
"=",
"asyncio",
".",
"subprocess",
".",
"PIPE",... | 29.947368 | 0.001704 |
def dtype(self):
"""Pixel data type."""
try:
return self.data.dtype
except AttributeError:
return numpy.dtype('%s%d' % (self._sample_type, self._sample_bytes)) | [
"def",
"dtype",
"(",
"self",
")",
":",
"try",
":",
"return",
"self",
".",
"data",
".",
"dtype",
"except",
"AttributeError",
":",
"return",
"numpy",
".",
"dtype",
"(",
"'%s%d'",
"%",
"(",
"self",
".",
"_sample_type",
",",
"self",
".",
"_sample_bytes",
"... | 33.666667 | 0.014493 |
def _pb_attr_value(val):
"""Given a value, return the protobuf attribute name and proper value.
The Protobuf API uses different attribute names based on value types
rather than inferring the type. This function simply determines the
proper attribute name based on the type of the value provided and
... | [
"def",
"_pb_attr_value",
"(",
"val",
")",
":",
"if",
"isinstance",
"(",
"val",
",",
"datetime",
".",
"datetime",
")",
":",
"name",
"=",
"\"timestamp\"",
"value",
"=",
"_datetime_to_pb_timestamp",
"(",
"val",
")",
"elif",
"isinstance",
"(",
"val",
",",
"Key... | 36.985075 | 0.000393 |
def _evaluate(self,R,z,phi=0.,t=0.):
"""
NAME:
_evaluate
PURPOSE:
evaluate the potential at R,z
INPUT:
R - Galactocentric cylindrical radius
z - vertical height
phi - azimuth
t - time
OUTPUT:
Phi(R,z)
... | [
"def",
"_evaluate",
"(",
"self",
",",
"R",
",",
"z",
",",
"phi",
"=",
"0.",
",",
"t",
"=",
"0.",
")",
":",
"if",
"not",
"self",
".",
"isNonAxi",
":",
"phi",
"=",
"0.",
"x",
",",
"y",
",",
"z",
"=",
"bovy_coords",
".",
"cyl_to_rect",
"(",
"R",... | 28.125 | 0.028653 |
def find_prev_keyword(sql):
""" Find the last sql keyword in an SQL statement
Returns the value of the last keyword, and the text of the query with
everything after the last keyword stripped
"""
if not sql.strip():
return None, ''
parsed = sqlparse.parse(sql)[0]
flattened = list(par... | [
"def",
"find_prev_keyword",
"(",
"sql",
")",
":",
"if",
"not",
"sql",
".",
"strip",
"(",
")",
":",
"return",
"None",
",",
"''",
"parsed",
"=",
"sqlparse",
".",
"parse",
"(",
"sql",
")",
"[",
"0",
"]",
"flattened",
"=",
"list",
"(",
"parsed",
".",
... | 42.3125 | 0.000722 |
def _GetLink(self):
"""Retrieves the link.
Returns:
str: path of the linked file.
"""
if self._link is None:
self._link = ''
if self.entry_type != definitions.FILE_ENTRY_TYPE_LINK:
return self._link
# Note that the SleuthKit does not expose NTFS
# IO_REPARSE_TAG_... | [
"def",
"_GetLink",
"(",
"self",
")",
":",
"if",
"self",
".",
"_link",
"is",
"None",
":",
"self",
".",
"_link",
"=",
"''",
"if",
"self",
".",
"entry_type",
"!=",
"definitions",
".",
"FILE_ENTRY_TYPE_LINK",
":",
"return",
"self",
".",
"_link",
"# Note that... | 27.064516 | 0.011507 |
def from_args(cls, args):
"""
Initialize a WorkflowConfigParser instance using the command line values
parsed in args. args must contain the values provided by the
workflow_command_line_group() function. If you are not using the standard
workflow command line interface, you shoul... | [
"def",
"from_args",
"(",
"cls",
",",
"args",
")",
":",
"# Identify the config files",
"confFiles",
"=",
"[",
"]",
"# files and URLs to resolve",
"if",
"args",
".",
"config_files",
":",
"confFiles",
"+=",
"args",
".",
"config_files",
"# Identify the deletes",
"confDe... | 39.555556 | 0.002284 |
def update_port(context, id, port):
"""Update values of a port.
: param context: neutron api request context
: param id: UUID representing the port to update.
: param port: dictionary with keys indicating fields to update.
valid keys are those that have a value of True for 'allow_put'
a... | [
"def",
"update_port",
"(",
"context",
",",
"id",
",",
"port",
")",
":",
"LOG",
".",
"info",
"(",
"\"update_port %s for tenant %s\"",
"%",
"(",
"id",
",",
"context",
".",
"tenant_id",
")",
")",
"port_db",
"=",
"db_api",
".",
"port_find",
"(",
"context",
"... | 43.483221 | 0.000151 |
def rm(ctx, cluster_id):
"""Terminate a EMR cluster"""
session = create_session(ctx.obj['AWS_PROFILE_NAME'])
client = session.client('emr')
try:
result = client.describe_cluster(ClusterId=cluster_id)
target_dns = result['Cluster']['MasterPublicDnsName']
flag = click.prompt(
... | [
"def",
"rm",
"(",
"ctx",
",",
"cluster_id",
")",
":",
"session",
"=",
"create_session",
"(",
"ctx",
".",
"obj",
"[",
"'AWS_PROFILE_NAME'",
"]",
")",
"client",
"=",
"session",
".",
"client",
"(",
"'emr'",
")",
"try",
":",
"result",
"=",
"client",
".",
... | 40.266667 | 0.001618 |
def status(self, *msg):
"""
Prints a status message
"""
label = colors.yellow("STATUS")
self._msg(label, *msg) | [
"def",
"status",
"(",
"self",
",",
"*",
"msg",
")",
":",
"label",
"=",
"colors",
".",
"yellow",
"(",
"\"STATUS\"",
")",
"self",
".",
"_msg",
"(",
"label",
",",
"*",
"msg",
")"
] | 24.166667 | 0.013333 |
def saveProfileLayout(self, profile):
"""
Saves the profile layout to the inputed profile.
:param profile | <projexui.widgets.xviewwidget.XViewProfile>
"""
if not self.viewWidget():
text = self.profileText()
QMessageBox.information(se... | [
"def",
"saveProfileLayout",
"(",
"self",
",",
"profile",
")",
":",
"if",
"not",
"self",
".",
"viewWidget",
"(",
")",
":",
"text",
"=",
"self",
".",
"profileText",
"(",
")",
"QMessageBox",
".",
"information",
"(",
"self",
".",
"window",
"(",
")",
",",
... | 39.25 | 0.008706 |
def group_indices(groupid_list):
"""
groups indicies of each item in ``groupid_list``
Args:
groupid_list (list): list of group ids
SeeAlso:
vt.group_indices - optimized numpy version
ut.apply_grouping
CommandLine:
python -m utool.util_alg --test-group_indices
... | [
"def",
"group_indices",
"(",
"groupid_list",
")",
":",
"item_list",
"=",
"range",
"(",
"len",
"(",
"groupid_list",
")",
")",
"grouped_dict",
"=",
"util_dict",
".",
"group_items",
"(",
"item_list",
",",
"groupid_list",
")",
"# Sort by groupid for cache efficiency",
... | 32.324324 | 0.000812 |
def peek(self, n=None, constructor=list):
"""
Sees/peeks the next few items in the Stream, without removing them.
Besides that this functions keeps the Stream items, it's the same to the
``Stream.take()`` method.
See Also
--------
Stream.take :
Returns the n first elements from the S... | [
"def",
"peek",
"(",
"self",
",",
"n",
"=",
"None",
",",
"constructor",
"=",
"list",
")",
":",
"return",
"self",
".",
"copy",
"(",
")",
".",
"take",
"(",
"n",
"=",
"n",
",",
"constructor",
"=",
"constructor",
")"
] | 30.25 | 0.001603 |
def x_indexes(self, indexes):
""" :type indexes: list[int] """
self._assert_shape(self._data, indexes, self._y_indexes)
self._x_indexes = indexes
self.x_index = len(indexes) / 2 | [
"def",
"x_indexes",
"(",
"self",
",",
"indexes",
")",
":",
"self",
".",
"_assert_shape",
"(",
"self",
".",
"_data",
",",
"indexes",
",",
"self",
".",
"_y_indexes",
")",
"self",
".",
"_x_indexes",
"=",
"indexes",
"self",
".",
"x_index",
"=",
"len",
"(",... | 41 | 0.009569 |
async def set_agent_neighbors(self):
'''Set neighbors for each agent in each cardinal direction.
This method assumes that the neighboring :class:`GridEnvironment` of
this grid environment have already been set.
'''
for i in range(len(self.grid)):
for j in range(len(s... | [
"async",
"def",
"set_agent_neighbors",
"(",
"self",
")",
":",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"self",
".",
"grid",
")",
")",
":",
"for",
"j",
"in",
"range",
"(",
"len",
"(",
"self",
".",
"grid",
"[",
"0",
"]",
")",
")",
":",
"agent"... | 45.529412 | 0.001265 |
def list_service_certificates(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List certificates associated with the service
CLI Example:
.. code-block:: bash
salt-cloud -f list_service_certificates my-azure name=my_service
'''
if call != 'function':
rai... | [
"def",
"list_service_certificates",
"(",
"kwargs",
"=",
"None",
",",
"conn",
"=",
"None",
",",
"call",
"=",
"None",
")",
":",
"if",
"call",
"!=",
"'function'",
":",
"raise",
"SaltCloudSystemExit",
"(",
"'The list_service_certificates function must be called with -f or... | 25.774194 | 0.002413 |
def flowspec_prefix_del(self, flowspec_family, rules, route_dist=None):
""" This method deletes an advertised Flow Specification route.
``flowspec_family`` specifies one of the flowspec family name.
``rules`` specifies NLRIs of Flow Specification as
a dictionary type value.
``... | [
"def",
"flowspec_prefix_del",
"(",
"self",
",",
"flowspec_family",
",",
"rules",
",",
"route_dist",
"=",
"None",
")",
":",
"func_name",
"=",
"'flowspec.del'",
"# Set required arguments",
"kwargs",
"=",
"{",
"FLOWSPEC_FAMILY",
":",
"flowspec_family",
",",
"FLOWSPEC_R... | 33.875 | 0.002392 |
def t_COMMA(self, t):
r','
t.endlexpos = t.lexpos + len(t.value)
return t | [
"def",
"t_COMMA",
"(",
"self",
",",
"t",
")",
":",
"t",
".",
"endlexpos",
"=",
"t",
".",
"lexpos",
"+",
"len",
"(",
"t",
".",
"value",
")",
"return",
"t"
] | 23.5 | 0.020619 |
def description(self):
"""Retrieves the description of the incident/incidents from the output
response
Returns:
description(namedtuple): List of named tuples of descriptions of
the incident/incidents
"""
resource_list = self.traffic_incident()
des... | [
"def",
"description",
"(",
"self",
")",
":",
"resource_list",
"=",
"self",
".",
"traffic_incident",
"(",
")",
"description",
"=",
"namedtuple",
"(",
"'description'",
",",
"'description'",
")",
"if",
"len",
"(",
"resource_list",
")",
"==",
"1",
"and",
"resour... | 38.090909 | 0.002328 |
def train(self, samples):
"""!
@brief Trains syncpr network using Hebbian rule for adjusting strength of connections between oscillators during training.
@param[in] samples (list): list of patterns where each pattern is represented by list of features that are equal to [-1; 1].
... | [
"def",
"train",
"(",
"self",
",",
"samples",
")",
":",
"# Verify pattern for learning",
"for",
"pattern",
"in",
"samples",
":",
"self",
".",
"__validate_pattern",
"(",
"pattern",
")",
"if",
"(",
"self",
".",
"_ccore_network_pointer",
"is",
"not",
"None",
")",
... | 38.1 | 0.018771 |
def toString(self) -> str:
"""Return string representation of collections."""
return ' '.join(attr.html for attr in self._dict.values()) | [
"def",
"toString",
"(",
"self",
")",
"->",
"str",
":",
"return",
"' '",
".",
"join",
"(",
"attr",
".",
"html",
"for",
"attr",
"in",
"self",
".",
"_dict",
".",
"values",
"(",
")",
")"
] | 50 | 0.013158 |
def automation_create(self, data, **kwargs):
"https://developer.zendesk.com/rest_api/docs/core/automations#create-automation"
api_path = "/api/v2/automations.json"
return self.call(api_path, method="POST", data=data, **kwargs) | [
"def",
"automation_create",
"(",
"self",
",",
"data",
",",
"*",
"*",
"kwargs",
")",
":",
"api_path",
"=",
"\"/api/v2/automations.json\"",
"return",
"self",
".",
"call",
"(",
"api_path",
",",
"method",
"=",
"\"POST\"",
",",
"data",
"=",
"data",
",",
"*",
... | 61.75 | 0.012 |
def __validate_definitions(self, definitions, field):
""" Validate a field's value against its defined rules. """
def validate_rule(rule):
validator = self.__get_rule_handler('validate', rule)
return validator(definitions.get(rule, None), field, value)
definitions = sel... | [
"def",
"__validate_definitions",
"(",
"self",
",",
"definitions",
",",
"field",
")",
":",
"def",
"validate_rule",
"(",
"rule",
")",
":",
"validator",
"=",
"self",
".",
"__get_rule_handler",
"(",
"'validate'",
",",
"rule",
")",
"return",
"validator",
"(",
"de... | 33.631579 | 0.001521 |
def findattr(self,attr,connector='parent'):
"""Returns the attribute named {attr}, from either the self or the self's parents (recursively)."""
if (not hasattr(self,attr)):
if (not hasattr(self,connector)):
return None
else:
con=getattr(self,connector)
if not con:
return None
if type(con)... | [
"def",
"findattr",
"(",
"self",
",",
"attr",
",",
"connector",
"=",
"'parent'",
")",
":",
"if",
"(",
"not",
"hasattr",
"(",
"self",
",",
"attr",
")",
")",
":",
"if",
"(",
"not",
"hasattr",
"(",
"self",
",",
"connector",
")",
")",
":",
"return",
"... | 30.6 | 0.057082 |
def segments_to_numpy(segments):
"""given a list of 4-element tuples, transforms it into a numpy array"""
segments = numpy.array(segments, dtype=SEGMENT_DATATYPE, ndmin=2) # each segment in a row
segments = segments if SEGMENTS_DIRECTION == 0 else numpy.transpose(segments)
return segments | [
"def",
"segments_to_numpy",
"(",
"segments",
")",
":",
"segments",
"=",
"numpy",
".",
"array",
"(",
"segments",
",",
"dtype",
"=",
"SEGMENT_DATATYPE",
",",
"ndmin",
"=",
"2",
")",
"# each segment in a row",
"segments",
"=",
"segments",
"if",
"SEGMENTS_DIRECTION"... | 60.4 | 0.009804 |
def get_authentication_tokens(self, callback_url=None, force_login=False,
screen_name=''):
"""Returns a dict including an authorization URL, ``auth_url``, to
direct a user to
:param callback_url: (optional) Url the user is returned to after
... | [
"def",
"get_authentication_tokens",
"(",
"self",
",",
"callback_url",
"=",
"None",
",",
"force_login",
"=",
"False",
",",
"screen_name",
"=",
"''",
")",
":",
"if",
"self",
".",
"oauth_version",
"!=",
"1",
":",
"raise",
"TwythonError",
"(",
"'This method can on... | 40.637931 | 0.001657 |
def confirm_scopes(self, refresh_token, scopes, request, *args, **kwargs):
"""Ensures the requested scope matches the scope originally granted
by the resource owner. If the scope is omitted it is treated as equal
to the scope originally granted by the resource owner.
DEPRECATION NOTE: T... | [
"def",
"confirm_scopes",
"(",
"self",
",",
"refresh_token",
",",
"scopes",
",",
"request",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"scopes",
":",
"log",
".",
"debug",
"(",
"'Scope omitted for refresh token %r'",
",",
"refresh_token"... | 52.625 | 0.002334 |
def arc_center(points):
"""
Given three points on an arc find:
center, radius, normal, and angle.
This uses the fact that the intersection of the perp
bisectors of the segments between the control points
is the center of the arc.
Parameters
---------
points : (3, dimension) float
... | [
"def",
"arc_center",
"(",
"points",
")",
":",
"# it's a lot easier to treat 2D as 3D with a zero Z value",
"points",
",",
"is_2D",
"=",
"util",
".",
"stack_3D",
"(",
"points",
",",
"return_2D",
"=",
"True",
")",
"# find the two edge vectors of the triangle",
"edge_directi... | 34.6 | 0.000375 |
def walk_data(cls, dist, path='/'):
"""Yields filename, stream for files identified as data in the distribution"""
for rel_fn in filter(None, dist.resource_listdir(path)):
full_fn = os.path.join(path, rel_fn)
if dist.resource_isdir(full_fn):
for fn, stream in cls.walk_data(dist, full_fn):
... | [
"def",
"walk_data",
"(",
"cls",
",",
"dist",
",",
"path",
"=",
"'/'",
")",
":",
"for",
"rel_fn",
"in",
"filter",
"(",
"None",
",",
"dist",
".",
"resource_listdir",
"(",
"path",
")",
")",
":",
"full_fn",
"=",
"os",
".",
"path",
".",
"join",
"(",
"... | 47.222222 | 0.013857 |
def get_trips(
feed: "Feed", date: Optional[str] = None, time: Optional[str] = None
) -> DataFrame:
"""
Return a subset of ``feed.trips``.
Parameters
----------
feed : Feed
date : string
YYYYMMDD date string
time : string
HH:MM:SS time string, possibly with HH > 23
... | [
"def",
"get_trips",
"(",
"feed",
":",
"\"Feed\"",
",",
"date",
":",
"Optional",
"[",
"str",
"]",
"=",
"None",
",",
"time",
":",
"Optional",
"[",
"str",
"]",
"=",
"None",
")",
"->",
"DataFrame",
":",
"if",
"feed",
".",
"trips",
"is",
"None",
"or",
... | 26.528302 | 0.000686 |
def extraction_to_conll(ex: Extraction) -> List[str]:
"""
Return a conll representation of a given input Extraction.
"""
ex = split_predicate(ex)
toks = ex.sent.split(' ')
ret = ['*'] * len(toks)
args = [ex.arg1] + ex.args2
rels_and_args = [("ARG{}".format(arg_ind), arg)
... | [
"def",
"extraction_to_conll",
"(",
"ex",
":",
"Extraction",
")",
"->",
"List",
"[",
"str",
"]",
":",
"ex",
"=",
"split_predicate",
"(",
"ex",
")",
"toks",
"=",
"ex",
".",
"sent",
".",
"split",
"(",
"' '",
")",
"ret",
"=",
"[",
"'*'",
"]",
"*",
"l... | 37.521739 | 0.00226 |
def murmur_hash3_x86_32(data, offset, size, seed=0x01000193):
"""
murmur3 hash function to determine partition
:param data: (byte array), input byte array
:param offset: (long), offset.
:param size: (long), byte length.
:param seed: murmur hash seed hazelcast uses 0x01000193
:return: (int32... | [
"def",
"murmur_hash3_x86_32",
"(",
"data",
",",
"offset",
",",
"size",
",",
"seed",
"=",
"0x01000193",
")",
":",
"key",
"=",
"bytearray",
"(",
"data",
"[",
"offset",
":",
"offset",
"+",
"size",
"]",
")",
"length",
"=",
"len",
"(",
"key",
")",
"nblock... | 27.327273 | 0.000642 |
def learn(self, examples, attributes, parent_examples):
"""
A decision tree learner that *strictly* follows the pseudocode given in
AIMA. In 3rd edition, see Figure 18.5, page 702.
"""
if not examples:
return self.plurality_value(parent_examples)
elif len(set(... | [
"def",
"learn",
"(",
"self",
",",
"examples",
",",
"attributes",
",",
"parent_examples",
")",
":",
"if",
"not",
"examples",
":",
"return",
"self",
".",
"plurality_value",
"(",
"parent_examples",
")",
"elif",
"len",
"(",
"set",
"(",
"map",
"(",
"self",
".... | 45.5 | 0.002392 |
def _get_charge_distribution_df(self):
"""
Return a complete table of fractional coordinates - charge density.
"""
# Fraction coordinates and corresponding indices
axis_grid = np.array([np.array(self.chgcar.get_axis_grid(i)) /
self.structure.lattice.... | [
"def",
"_get_charge_distribution_df",
"(",
"self",
")",
":",
"# Fraction coordinates and corresponding indices",
"axis_grid",
"=",
"np",
".",
"array",
"(",
"[",
"np",
".",
"array",
"(",
"self",
".",
"chgcar",
".",
"get_axis_grid",
"(",
"i",
")",
")",
"/",
"sel... | 38.863636 | 0.002283 |
def execute(self, conn, dsType = "", dataset="", transaction = False):
"""
Lists all primary dataset types if no user input is provided.
"""
sql = self.sql
binds={}
if not dsType and not dataset:
pass
elif dsType and dataset in ("", None, '%'):
... | [
"def",
"execute",
"(",
"self",
",",
"conn",
",",
"dsType",
"=",
"\"\"",
",",
"dataset",
"=",
"\"\"",
",",
"transaction",
"=",
"False",
")",
":",
"sql",
"=",
"self",
".",
"sql",
"binds",
"=",
"{",
"}",
"if",
"not",
"dsType",
"and",
"not",
"dataset",... | 50.117647 | 0.023604 |
def _modem_sm(self):
"""Handle modem response state machine."""
import datetime
read_timeout = READ_IDLE_TIMEOUT
while self.ser:
try:
resp = self.read(read_timeout)
except (serial.SerialException, SystemExit, TypeError):
_LOGGER.de... | [
"def",
"_modem_sm",
"(",
"self",
")",
":",
"import",
"datetime",
"read_timeout",
"=",
"READ_IDLE_TIMEOUT",
"while",
"self",
".",
"ser",
":",
"try",
":",
"resp",
"=",
"self",
".",
"read",
"(",
"read_timeout",
")",
"except",
"(",
"serial",
".",
"SerialExcept... | 34.547945 | 0.000771 |
def wrap(self, availWidth, availHeight):
"""
All table properties should be known by now.
"""
widths = (availWidth - self.rightColumnWidth,
self.rightColumnWidth)
# makes an internal table which does all the work.
# we draw the LAST RUN's entries! If ... | [
"def",
"wrap",
"(",
"self",
",",
"availWidth",
",",
"availHeight",
")",
":",
"widths",
"=",
"(",
"availWidth",
"-",
"self",
".",
"rightColumnWidth",
",",
"self",
".",
"rightColumnWidth",
")",
"# makes an internal table which does all the work.",
"# we draw the LAST RU... | 39.596154 | 0.001896 |
def _unpack_zipfile(filename, extract_dir):
"""Unpack zip `filename` to `extract_dir`
"""
try:
import zipfile
except ImportError:
raise ReadError('zlib not supported, cannot unpack this archive.')
if not zipfile.is_zipfile(filename):
raise ReadError("%s is not a zip file" % ... | [
"def",
"_unpack_zipfile",
"(",
"filename",
",",
"extract_dir",
")",
":",
"try",
":",
"import",
"zipfile",
"except",
"ImportError",
":",
"raise",
"ReadError",
"(",
"'zlib not supported, cannot unpack this archive.'",
")",
"if",
"not",
"zipfile",
".",
"is_zipfile",
"(... | 28.666667 | 0.000937 |
def generate_string(converter, input, format='xml'):
"""
Like generate(), but reads the input from a string instead of
from a file.
:type converter: compiler.Context
:param converter: The compiled converter.
:type input: str
:param input: The string to convert.
:type format: str
... | [
"def",
"generate_string",
"(",
"converter",
",",
"input",
",",
"format",
"=",
"'xml'",
")",
":",
"serializer",
"=",
"generator",
".",
"new",
"(",
"format",
")",
"if",
"serializer",
"is",
"None",
":",
"raise",
"TypeError",
"(",
"'invalid output format '",
"+"... | 31.65 | 0.001534 |
def _init_metadata(self, **kwargs):
"""Initialize form metadata"""
osid_objects.OsidObjectForm._init_metadata(self, **kwargs)
self._level_default = self._mdata['level']['default_id_values'][0]
self._start_time_default = self._mdata['start_time']['default_date_time_values'][0]
sel... | [
"def",
"_init_metadata",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"osid_objects",
".",
"OsidObjectForm",
".",
"_init_metadata",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
"self",
".",
"_level_default",
"=",
"self",
".",
"_mdata",
"[",
"'level'",
"... | 77.363636 | 0.010453 |
def get_suggestions(self, prefix, fuzzy = False, num = 10, with_scores = False, with_payloads=False):
"""
Get a list of suggestions from the AutoCompleter, for a given prefix
### Parameters:
- **prefix**: the prefix we are searching. **Must be valid ascii or utf-8**
- **fuzzy**:... | [
"def",
"get_suggestions",
"(",
"self",
",",
"prefix",
",",
"fuzzy",
"=",
"False",
",",
"num",
"=",
"10",
",",
"with_scores",
"=",
"False",
",",
"with_payloads",
"=",
"False",
")",
":",
"args",
"=",
"[",
"AutoCompleter",
".",
"SUGGET_COMMAND",
",",
"self"... | 48.419355 | 0.011757 |
def _handle_message(self, data):
""" Handle messages. """
if data.type == MSG_SERVER_SETTINGS:
_LOGGER.info(data.payload)
elif data.type == MSG_SAMPLE_FORMAT:
_LOGGER.info(data.payload)
self._connected = True
elif data.type == MSG_TIME:
if ... | [
"def",
"_handle_message",
"(",
"self",
",",
"data",
")",
":",
"if",
"data",
".",
"type",
"==",
"MSG_SERVER_SETTINGS",
":",
"_LOGGER",
".",
"info",
"(",
"data",
".",
"payload",
")",
"elif",
"data",
".",
"type",
"==",
"MSG_SAMPLE_FORMAT",
":",
"_LOGGER",
"... | 40.454545 | 0.002195 |
def oauth_required(f):
"""
decorator to add to a view to require an oauth user
:return: decorated function
"""
@wraps(f)
def decorated_function(*args, **kwargs):
if 'oauth_user_uri' not in session or session['oauth_user_uri'] is None:
return re... | [
"def",
"oauth_required",
"(",
"f",
")",
":",
"@",
"wraps",
"(",
"f",
")",
"def",
"decorated_function",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"'oauth_user_uri'",
"not",
"in",
"session",
"or",
"session",
"[",
"'oauth_user_uri'",
"]",
... | 39.272727 | 0.00905 |
def find_by_hash(self, hash=None, book=-1):
'''Search notes for a given (possibly abbreviated) hash'''
if hash:
self.fyi("nota.find_by_hash() with abbreviated hash %s; book=%s" % (hash, book))
try:
if book < 0:
rows = self.cur.execute("SELECT noteId, hash ... | [
"def",
"find_by_hash",
"(",
"self",
",",
"hash",
"=",
"None",
",",
"book",
"=",
"-",
"1",
")",
":",
"if",
"hash",
":",
"self",
".",
"fyi",
"(",
"\"nota.find_by_hash() with abbreviated hash %s; book=%s\"",
"%",
"(",
"hash",
",",
"book",
")",
")",
"try",
"... | 46.238095 | 0.012607 |
def parse_bugs_details(raw_xml):
"""Parse a Bugilla bugs details XML stream.
This method returns a generator which parses the given XML,
producing an iterator of dictionaries. Each dictionary stores
the information related to a parsed bug.
If the given XML is invalid or does no... | [
"def",
"parse_bugs_details",
"(",
"raw_xml",
")",
":",
"bugs",
"=",
"xml_to_dict",
"(",
"raw_xml",
")",
"if",
"'bug'",
"not",
"in",
"bugs",
":",
"cause",
"=",
"\"No bugs found. XML stream seems to be invalid.\"",
"raise",
"ParseError",
"(",
"cause",
"=",
"cause",
... | 32.12 | 0.002418 |
def cell_data_to_point_data(dataset, pass_cell_data=False):
"""Transforms cell data (i.e., data specified per cell) into point data
(i.e., data specified at cell points).
The method of transformation is based on averaging the data values of
all cells using a particular point. Optionally,... | [
"def",
"cell_data_to_point_data",
"(",
"dataset",
",",
"pass_cell_data",
"=",
"False",
")",
":",
"alg",
"=",
"vtk",
".",
"vtkCellDataToPointData",
"(",
")",
"alg",
".",
"SetInputDataObject",
"(",
"dataset",
")",
"alg",
".",
"SetPassCellData",
"(",
"pass_cell_dat... | 43.157895 | 0.002387 |
def http_retry_with_backoff_middleware(
make_request,
web3, # pylint: disable=unused-argument
errors: Tuple = (
exceptions.ConnectionError,
exceptions.HTTPError,
exceptions.Timeout,
exceptions.TooManyRedirects,
),
retries: int = 10... | [
"def",
"http_retry_with_backoff_middleware",
"(",
"make_request",
",",
"web3",
",",
"# pylint: disable=unused-argument",
"errors",
":",
"Tuple",
"=",
"(",
"exceptions",
".",
"ConnectionError",
",",
"exceptions",
".",
"HTTPError",
",",
"exceptions",
".",
"Timeout",
","... | 34.228571 | 0.000812 |
def local(self):
"""
Access the local
:returns: twilio.rest.api.v2010.account.available_phone_number.local.LocalList
:rtype: twilio.rest.api.v2010.account.available_phone_number.local.LocalList
"""
if self._local is None:
self._local = LocalList(
... | [
"def",
"local",
"(",
"self",
")",
":",
"if",
"self",
".",
"_local",
"is",
"None",
":",
"self",
".",
"_local",
"=",
"LocalList",
"(",
"self",
".",
"_version",
",",
"account_sid",
"=",
"self",
".",
"_solution",
"[",
"'account_sid'",
"]",
",",
"country_co... | 34.714286 | 0.008016 |
def get_one_for_update(self, object_id):
"""
Retrieve an object by its object_id
Does a select for update on the row, results in row level lock for the duration of the transaction
:param object_id: the objects id.
:return: the requested object
:raises: :class: NoResultFo... | [
"def",
"get_one_for_update",
"(",
"self",
",",
"object_id",
")",
":",
"return",
"self",
".",
"session",
".",
"query",
"(",
"self",
".",
"cls",
")",
".",
"with_for_update",
"(",
")",
".",
"filter_by",
"(",
"id",
"=",
"object_id",
")",
".",
"one",
"(",
... | 45.3 | 0.008658 |
def lookup_field(key, lookup_type=None, placeholder=None, html_class="div",
select_type="strapselect", mapping="uuid"):
"""Generates a lookup field for form definitions"""
if lookup_type is None:
lookup_type = key
if placeholder is None:
placeholder = "Select a " + lookup_... | [
"def",
"lookup_field",
"(",
"key",
",",
"lookup_type",
"=",
"None",
",",
"placeholder",
"=",
"None",
",",
"html_class",
"=",
"\"div\"",
",",
"select_type",
"=",
"\"strapselect\"",
",",
"mapping",
"=",
"\"uuid\"",
")",
":",
"if",
"lookup_type",
"is",
"None",
... | 28.043478 | 0.001499 |
def graph_from_adjacency_matrix(matrix, node_prefix='', directed=False):
"""Creates a basic graph out of an adjacency matrix.
The matrix has to be a list of rows of values
representing an adjacency matrix.
The values can be anything: bool, int, float, as long
as they can evaluate to True or False.
... | [
"def",
"graph_from_adjacency_matrix",
"(",
"matrix",
",",
"node_prefix",
"=",
"''",
",",
"directed",
"=",
"False",
")",
":",
"node_orig",
"=",
"1",
"if",
"directed",
":",
"graph",
"=",
"Dot",
"(",
"graph_type",
"=",
"'digraph'",
")",
"else",
":",
"graph",
... | 25.228571 | 0.001091 |
def peek_16(library, session, address):
"""Read an 16-bit value from the specified address.
Corresponds to viPeek16 function of the VISA library.
:param library: the visa library wrapped by ctypes.
:param session: Unique logical identifier to a session.
:param address: Source address to read the v... | [
"def",
"peek_16",
"(",
"library",
",",
"session",
",",
"address",
")",
":",
"value_16",
"=",
"ViUInt16",
"(",
")",
"ret",
"=",
"library",
".",
"viPeek16",
"(",
"session",
",",
"address",
",",
"byref",
"(",
"value_16",
")",
")",
"return",
"value_16",
".... | 40.142857 | 0.001739 |
def extract_chm (archive, compression, cmd, verbosity, interactive, outdir):
"""Extract a CHM archive."""
return [cmd, os.path.abspath(archive), outdir] | [
"def",
"extract_chm",
"(",
"archive",
",",
"compression",
",",
"cmd",
",",
"verbosity",
",",
"interactive",
",",
"outdir",
")",
":",
"return",
"[",
"cmd",
",",
"os",
".",
"path",
".",
"abspath",
"(",
"archive",
")",
",",
"outdir",
"]"
] | 52.666667 | 0.0125 |
def secure(view):
"""
Authentication decorator for views.
If DEBUG is on, we serve the view without authenticating.
Default is 'django.contrib.auth.decorators.login_required'.
Can also be 'django.contrib.admin.views.decorators.staff_member_required'
or a custom decorator.
"""
auth_decor... | [
"def",
"secure",
"(",
"view",
")",
":",
"auth_decorator",
"=",
"import_class",
"(",
"settings",
".",
"AUTH_DECORATOR",
")",
"return",
"(",
"view",
"if",
"project_settings",
".",
"DEBUG",
"else",
"method_decorator",
"(",
"auth_decorator",
",",
"name",
"=",
"'di... | 34.142857 | 0.002037 |
def hl_canvas2table_box(self, canvas, tag):
"""Highlight all markings inside user drawn box on table."""
self.treeview.clear_selection()
# Remove existing box
cobj = canvas.get_object_by_tag(tag)
if cobj.kind != 'rectangle':
return
canvas.delete_object_by_tag... | [
"def",
"hl_canvas2table_box",
"(",
"self",
",",
"canvas",
",",
"tag",
")",
":",
"self",
".",
"treeview",
".",
"clear_selection",
"(",
")",
"# Remove existing box",
"cobj",
"=",
"canvas",
".",
"get_object_by_tag",
"(",
"tag",
")",
"if",
"cobj",
".",
"kind",
... | 30.055556 | 0.001791 |
def as_dict(self):
"""
Creates a dict of composition, energy, and ion name
"""
d = {"ion": self.ion.as_dict(), "energy": self.energy,
"name": self.name}
return d | [
"def",
"as_dict",
"(",
"self",
")",
":",
"d",
"=",
"{",
"\"ion\"",
":",
"self",
".",
"ion",
".",
"as_dict",
"(",
")",
",",
"\"energy\"",
":",
"self",
".",
"energy",
",",
"\"name\"",
":",
"self",
".",
"name",
"}",
"return",
"d"
] | 29.714286 | 0.009346 |
def delete_templatetype(type_id,template_i=None, **kwargs):
"""
Delete a template type and its typeattrs.
"""
try:
tmpltype_i = db.DBSession.query(TemplateType).filter(TemplateType.id == type_id).one()
except NoResultFound:
raise ResourceNotFoundError("Template Type %s not found"... | [
"def",
"delete_templatetype",
"(",
"type_id",
",",
"template_i",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"try",
":",
"tmpltype_i",
"=",
"db",
".",
"DBSession",
".",
"query",
"(",
"TemplateType",
")",
".",
"filter",
"(",
"TemplateType",
".",
"id",... | 34.75 | 0.010508 |
def initialize(self):
"""
Initialize the internal objects.
"""
if self._pooler is None:
params = {
"inputWidth": self.inputWidth,
"lateralInputWidths": [self.cellCount] * self.numOtherCorticalColumns,
"cellCount": self.cellCount,
"sdrSize": self.sdrSize,
"on... | [
"def",
"initialize",
"(",
"self",
")",
":",
"if",
"self",
".",
"_pooler",
"is",
"None",
":",
"params",
"=",
"{",
"\"inputWidth\"",
":",
"self",
".",
"inputWidth",
",",
"\"lateralInputWidths\"",
":",
"[",
"self",
".",
"cellCount",
"]",
"*",
"self",
".",
... | 44.166667 | 0.002216 |
def get_program(name, config, ptype="cmd", default=None):
"""Retrieve program information from the configuration.
This handles back compatible location specification in input
YAML. The preferred location for program information is in
`resources` but the older `program` tag is also supported.
"""
... | [
"def",
"get_program",
"(",
"name",
",",
"config",
",",
"ptype",
"=",
"\"cmd\"",
",",
"default",
"=",
"None",
")",
":",
"# support taking in the data dictionary",
"config",
"=",
"config",
".",
"get",
"(",
"\"config\"",
",",
"config",
")",
"try",
":",
"pconfig... | 37.68 | 0.00207 |
def cds(self):
"""just the parts of the exons that are translated"""
ces = self.coding_exons
if len(ces) < 1: return ces
ces[0] = (self.cdsStart, ces[0][1])
ces[-1] = (ces[-1][0], self.cdsEnd)
assert all((s < e for s, e in ces))
return ces | [
"def",
"cds",
"(",
"self",
")",
":",
"ces",
"=",
"self",
".",
"coding_exons",
"if",
"len",
"(",
"ces",
")",
"<",
"1",
":",
"return",
"ces",
"ces",
"[",
"0",
"]",
"=",
"(",
"self",
".",
"cdsStart",
",",
"ces",
"[",
"0",
"]",
"[",
"1",
"]",
"... | 36 | 0.010169 |
def _remember_videos(page, fetches, stitch_ups=None):
'''
Saves info about videos captured by youtube-dl in `page.videos`.
'''
if not 'videos' in page:
page.videos = []
for fetch in fetches or []:
content_type = fetch['response_headers'].get_content_type()
if (content_type.st... | [
"def",
"_remember_videos",
"(",
"page",
",",
"fetches",
",",
"stitch_ups",
"=",
"None",
")",
":",
"if",
"not",
"'videos'",
"in",
"page",
":",
"page",
".",
"videos",
"=",
"[",
"]",
"for",
"fetch",
"in",
"fetches",
"or",
"[",
"]",
":",
"content_type",
... | 44.692308 | 0.001123 |
def get_context_data(self, **kwargs):
"""
Get context data for datatable server-side response.
See http://www.datatables.net/usage/server-side
"""
sEcho = self.query_data["sEcho"]
context = super(BaseListView, self).get_context_data(**kwargs)
queryset = context["... | [
"def",
"get_context_data",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"sEcho",
"=",
"self",
".",
"query_data",
"[",
"\"sEcho\"",
"]",
"context",
"=",
"super",
"(",
"BaseListView",
",",
"self",
")",
".",
"get_context_data",
"(",
"*",
"*",
"kwargs",
... | 36.258065 | 0.001733 |
def index(config): # pragma: no cover
"""Display group info in raw format."""
client = Client()
client.prepare_connection()
group_api = API(client)
print(group_api.index()) | [
"def",
"index",
"(",
"config",
")",
":",
"# pragma: no cover",
"client",
"=",
"Client",
"(",
")",
"client",
".",
"prepare_connection",
"(",
")",
"group_api",
"=",
"API",
"(",
"client",
")",
"print",
"(",
"group_api",
".",
"index",
"(",
")",
")"
] | 34.666667 | 0.00939 |
def get_file(self, fax_id, **kwargs): # noqa: E501
"""get a file # noqa: E501
Get your fax archive file using it's id. # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async=True
>>> thread = api.get_file(... | [
"def",
"get_file",
"(",
"self",
",",
"fax_id",
",",
"*",
"*",
"kwargs",
")",
":",
"# noqa: E501",
"kwargs",
"[",
"'_return_http_data_only'",
"]",
"=",
"True",
"if",
"kwargs",
".",
"get",
"(",
"'async'",
")",
":",
"return",
"self",
".",
"get_file_with_http_... | 40.136364 | 0.002212 |
def repeat(self, repeat):
"""Set the queue's repeat option"""
shuffle = self.shuffle
self.play_mode = PLAY_MODE_BY_MEANING[(shuffle, repeat)] | [
"def",
"repeat",
"(",
"self",
",",
"repeat",
")",
":",
"shuffle",
"=",
"self",
".",
"shuffle",
"self",
".",
"play_mode",
"=",
"PLAY_MODE_BY_MEANING",
"[",
"(",
"shuffle",
",",
"repeat",
")",
"]"
] | 40.5 | 0.012121 |
def message_search(self, text: str, on_success: callable, peer: Peer=None,
min_date: datetime=None, max_date: datetime=None,
max_id: int=None, offset: int=0, limit: int=255):
"""
Search for messages.
:param text: Text to search for in messages
... | [
"def",
"message_search",
"(",
"self",
",",
"text",
":",
"str",
",",
"on_success",
":",
"callable",
",",
"peer",
":",
"Peer",
"=",
"None",
",",
"min_date",
":",
"datetime",
"=",
"None",
",",
"max_date",
":",
"datetime",
"=",
"None",
",",
"max_id",
":",
... | 49.125 | 0.022472 |
def commit_config(name):
'''
Commits the candidate configuration to the running configuration.
name: The name of the module function to execute.
SLS Example:
.. code-block:: yaml
panos/commit:
panos.commit_config
'''
ret = _default_ret(name)
ret.update({
... | [
"def",
"commit_config",
"(",
"name",
")",
":",
"ret",
"=",
"_default_ret",
"(",
"name",
")",
"ret",
".",
"update",
"(",
"{",
"'commit'",
":",
"__salt__",
"[",
"'panos.commit'",
"]",
"(",
")",
",",
"'result'",
":",
"True",
"}",
")",
"return",
"ret"
] | 17.409091 | 0.002475 |
def _handle_tag_definetext(self):
"""Handle the DefineText tag."""
obj = _make_object("DefineText")
self._generic_definetext_parser(obj, self._get_struct_rgb)
return obj | [
"def",
"_handle_tag_definetext",
"(",
"self",
")",
":",
"obj",
"=",
"_make_object",
"(",
"\"DefineText\"",
")",
"self",
".",
"_generic_definetext_parser",
"(",
"obj",
",",
"self",
".",
"_get_struct_rgb",
")",
"return",
"obj"
] | 39.4 | 0.00995 |
def format_as_dataframes(explanation):
# type: (Explanation) -> Dict[str, pd.DataFrame]
""" Export an explanation to a dictionary with ``pandas.DataFrame`` values
and string keys that correspond to explanation attributes.
Use this method if several dataframes can be exported from a single
explanatio... | [
"def",
"format_as_dataframes",
"(",
"explanation",
")",
":",
"# type: (Explanation) -> Dict[str, pd.DataFrame]",
"result",
"=",
"{",
"}",
"for",
"attr",
"in",
"_EXPORTED_ATTRIBUTES",
":",
"value",
"=",
"getattr",
"(",
"explanation",
",",
"attr",
")",
"if",
"value",
... | 43.833333 | 0.001241 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.