text stringlengths 75 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 0.18 |
|---|---|---|---|
def get_response_content_type(self):
"""Figure out what content type will be used in the response."""
if self._best_response_match is None:
settings = get_settings(self.application, force_instance=True)
acceptable = headers.parse_accept(
self.request.headers.get(
... | [
"def",
"get_response_content_type",
"(",
"self",
")",
":",
"if",
"self",
".",
"_best_response_match",
"is",
"None",
":",
"settings",
"=",
"get_settings",
"(",
"self",
".",
"application",
",",
"force_instance",
"=",
"True",
")",
"acceptable",
"=",
"headers",
".... | 50.380952 | 0.001855 |
def bounds(self):
"""Finds min/max for bounds across blocks
Returns:
tuple(float):
length 6 tuple of floats containing min/max along each axis
"""
bounds = [np.inf,-np.inf, np.inf,-np.inf, np.inf,-np.inf]
def update_bounds(ax, nb, bounds):
... | [
"def",
"bounds",
"(",
"self",
")",
":",
"bounds",
"=",
"[",
"np",
".",
"inf",
",",
"-",
"np",
".",
"inf",
",",
"np",
".",
"inf",
",",
"-",
"np",
".",
"inf",
",",
"np",
".",
"inf",
",",
"-",
"np",
".",
"inf",
"]",
"def",
"update_bounds",
"("... | 33.178571 | 0.00523 |
def filter_feed(self, updated=False, following=False, folder=False,
filter_folder="", sort="updated", nid=None):
"""Get filtered feed
Only one filter type (updated, following, folder) is possible.
:type nid: str
:param nid: This is the ID of the network to get the ... | [
"def",
"filter_feed",
"(",
"self",
",",
"updated",
"=",
"False",
",",
"following",
"=",
"False",
",",
"folder",
"=",
"False",
",",
"filter_folder",
"=",
"\"\"",
",",
"sort",
"=",
"\"updated\"",
",",
"nid",
"=",
"None",
")",
":",
"assert",
"sum",
"(",
... | 36.869565 | 0.002298 |
def _copy_new_parent(self, parent):
"""Copy the current param to a new parent, must be a dummy param."""
if self.parent == "undefined":
param = copy.copy(self)
param.parent = parent.uid
return param
else:
raise ValueError("Cannot copy from non-dumm... | [
"def",
"_copy_new_parent",
"(",
"self",
",",
"parent",
")",
":",
"if",
"self",
".",
"parent",
"==",
"\"undefined\"",
":",
"param",
"=",
"copy",
".",
"copy",
"(",
"self",
")",
"param",
".",
"parent",
"=",
"parent",
".",
"uid",
"return",
"param",
"else",... | 42 | 0.005831 |
def add_user(uid, password, desc=None):
""" Adds user to the DCOS Enterprise. If not description
is provided the uid will be used for the description.
:param uid: user id
:type uid: str
:param password: password
:type password: str
:param desc: description of user
... | [
"def",
"add_user",
"(",
"uid",
",",
"password",
",",
"desc",
"=",
"None",
")",
":",
"try",
":",
"desc",
"=",
"uid",
"if",
"desc",
"is",
"None",
"else",
"desc",
"user_object",
"=",
"{",
"\"description\"",
":",
"desc",
",",
"\"password\"",
":",
"password... | 34.095238 | 0.001359 |
def text(length, choices=string.ascii_letters):
""" returns a random (fixed length) string
:param length: string length
:param choices: string containing all the chars can be used to build the string
.. seealso::
:py:func:`rtext`
"""
return ''.join(choice(choices) for x in range(length)... | [
"def",
"text",
"(",
"length",
",",
"choices",
"=",
"string",
".",
"ascii_letters",
")",
":",
"return",
"''",
".",
"join",
"(",
"choice",
"(",
"choices",
")",
"for",
"x",
"in",
"range",
"(",
"length",
")",
")"
] | 31.2 | 0.006231 |
def get_context_data(self,**kwargs):
''' Add the event and series listing data '''
context = self.get_listing()
context['showDescriptionRule'] = getConstant('registration__showDescriptionRule') or 'all'
context.update(kwargs)
# Update the site session data so that registration p... | [
"def",
"get_context_data",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"context",
"=",
"self",
".",
"get_listing",
"(",
")",
"context",
"[",
"'showDescriptionRule'",
"]",
"=",
"getConstant",
"(",
"'registration__showDescriptionRule'",
")",
"or",
"'all'",
"... | 51.272727 | 0.012195 |
def _fix_pooling(pool_type, inputs, new_attr):
"""onnx pooling operator supports asymmetrical padding
Adding pad operator before pooling in mxnet to work with onnx"""
stride = new_attr.get('stride')
kernel = new_attr.get('kernel')
padding = new_attr.get('pad')
p_value = new_attr.get('p_value')
... | [
"def",
"_fix_pooling",
"(",
"pool_type",
",",
"inputs",
",",
"new_attr",
")",
":",
"stride",
"=",
"new_attr",
".",
"get",
"(",
"'stride'",
")",
"kernel",
"=",
"new_attr",
".",
"get",
"(",
"'kernel'",
")",
"padding",
"=",
"new_attr",
".",
"get",
"(",
"'... | 40.910714 | 0.002984 |
def search_read_all(self, domain, order, fields, batch_size=500,
context=None, offset=0, limit=None):
"""
An endless iterator that iterates over records.
:param domain: A search domain
:param order: The order clause for search read
:param fields: The fiel... | [
"def",
"search_read_all",
"(",
"self",
",",
"domain",
",",
"order",
",",
"fields",
",",
"batch_size",
"=",
"500",
",",
"context",
"=",
"None",
",",
"offset",
"=",
"0",
",",
"limit",
"=",
"None",
")",
":",
"if",
"context",
"is",
"None",
":",
"context"... | 37.965517 | 0.002657 |
def get_base_arguments(parser):
"""
Append base arguments icetea run arguments to parser.
:param parser: argument parser
:return: ArgumentParser
"""
thisfilepath = os.path.abspath(os.path.dirname(__file__))
group = parser.add_mutually_exclusive_group(required=False)
group.add_argument('... | [
"def",
"get_base_arguments",
"(",
"parser",
")",
":",
"thisfilepath",
"=",
"os",
".",
"path",
".",
"abspath",
"(",
"os",
".",
"path",
".",
"dirname",
"(",
"__file__",
")",
")",
"group",
"=",
"parser",
".",
"add_mutually_exclusive_group",
"(",
"required",
"... | 53.313187 | 0.002631 |
def _process_loaded_object(self, path):
"""process the :paramref:`path`.
:param str path: the path to load an svg from
"""
file_name = os.path.basename(path)
name = os.path.splitext(file_name)[0]
with open(path) as file:
string = file.read()
self.... | [
"def",
"_process_loaded_object",
"(",
"self",
",",
"path",
")",
":",
"file_name",
"=",
"os",
".",
"path",
".",
"basename",
"(",
"path",
")",
"name",
"=",
"os",
".",
"path",
".",
"splitext",
"(",
"file_name",
")",
"[",
"0",
"]",
"with",
"open",
"(",
... | 35.9 | 0.005435 |
def surface_area(self):
r"""Calculate all atomic surface area.
:rtype: [float]
"""
return [self.atomic_sa(i) for i in range(len(self.rads))] | [
"def",
"surface_area",
"(",
"self",
")",
":",
"return",
"[",
"self",
".",
"atomic_sa",
"(",
"i",
")",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"self",
".",
"rads",
")",
")",
"]"
] | 28 | 0.011561 |
def rsa_pkcs1v15_sign(private_key, data, hash_algorithm):
"""
Generates an RSASSA-PKCS-v1.5 signature.
When the hash_algorithm is "raw", the operation is identical to RSA
private key encryption. That is: the data is not hashed and no ASN.1
structure with an algorithm identifier of the hash algorith... | [
"def",
"rsa_pkcs1v15_sign",
"(",
"private_key",
",",
"data",
",",
"hash_algorithm",
")",
":",
"if",
"private_key",
".",
"algorithm",
"!=",
"'rsa'",
":",
"raise",
"ValueError",
"(",
"pretty_message",
"(",
"'''\n The key specified is not an RSA private key, but %... | 31.837838 | 0.000824 |
def _remove(self, rtracker):
"""
Remove a resource from the pool.
:param rtracker: A resource.
:type rtracker: :class:`_ResourceTracker`
"""
with self._lock:
i = self._reference_queue.index(rtracker)
self._reference_queue[i] = None
sel... | [
"def",
"_remove",
"(",
"self",
",",
"rtracker",
")",
":",
"with",
"self",
".",
"_lock",
":",
"i",
"=",
"self",
".",
"_reference_queue",
".",
"index",
"(",
"rtracker",
")",
"self",
".",
"_reference_queue",
"[",
"i",
"]",
"=",
"None",
"self",
".",
"_si... | 29.272727 | 0.006024 |
def subn_filter(s, find, replace, count=0):
"""A non-optimal implementation of a regex filter"""
return re.gsub(find, replace, count, s) | [
"def",
"subn_filter",
"(",
"s",
",",
"find",
",",
"replace",
",",
"count",
"=",
"0",
")",
":",
"return",
"re",
".",
"gsub",
"(",
"find",
",",
"replace",
",",
"count",
",",
"s",
")"
] | 47.333333 | 0.006944 |
def post(self, request, *args, **kwargs): # pylint: disable=unused-argument
"""
Inserts a batch of completions.
REST Endpoint Format:
{
"username": "username",
"course_key": "course-key",
"blocks": {
"block_key1": 0.0,
"block_key2":... | [
"def",
"post",
"(",
"self",
",",
"request",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"# pylint: disable=unused-argument",
"batch_object",
"=",
"request",
".",
"data",
"or",
"{",
"}",
"try",
":",
"user",
",",
"course_key",
",",
"blocks",
"=",
... | 32.632653 | 0.002429 |
def mouseDown(self, button):
""" Send a mouse button down at the last set position
button: int: [1-n]
"""
log.debug('mouseDown %s', button)
self.buttons |= 1 << (button - 1)
self.pointerEvent(self.x, self.y, buttonmask=self.buttons)
return self | [
"def",
"mouseDown",
"(",
"self",
",",
"button",
")",
":",
"log",
".",
"debug",
"(",
"'mouseDown %s'",
",",
"button",
")",
"self",
".",
"buttons",
"|=",
"1",
"<<",
"(",
"button",
"-",
"1",
")",
"self",
".",
"pointerEvent",
"(",
"self",
".",
"x",
","... | 27 | 0.006515 |
def _generate_normals(polygons):
"""
Takes a list of polygons and return an array of their normals.
Normals point towards the viewer for a face with its vertices in
counterclockwise order, following the right hand rule.
Uses three points equally spaced around the polygon.
This normal of course m... | [
"def",
"_generate_normals",
"(",
"polygons",
")",
":",
"if",
"isinstance",
"(",
"polygons",
",",
"np",
".",
"ndarray",
")",
":",
"# optimization: polygons all have the same number of points, so can",
"# vectorize",
"n",
"=",
"polygons",
".",
"shape",
"[",
"-",
"2",
... | 43.243243 | 0.000611 |
def getMargin(self, name):
"""Provides the requested margin.
Returns a reference to the margin if found and None otherwise
"""
for margin in self._margins:
if margin.getName() == name:
return margin
return None | [
"def",
"getMargin",
"(",
"self",
",",
"name",
")",
":",
"for",
"margin",
"in",
"self",
".",
"_margins",
":",
"if",
"margin",
".",
"getName",
"(",
")",
"==",
"name",
":",
"return",
"margin",
"return",
"None"
] | 34.25 | 0.007117 |
def read_ASCII_cols(infile, cols=[1, 2, 3]): # noqa: N802
""" Interpret input ASCII file to return arrays for specified columns.
Notes
-----
The specification of the columns should be expected to have lists for
each 'column', with all columns in each list combined into a single
... | [
"def",
"read_ASCII_cols",
"(",
"infile",
",",
"cols",
"=",
"[",
"1",
",",
"2",
",",
"3",
"]",
")",
":",
"# noqa: N802",
"# build dictionary representing format of each row",
"# Format of dictionary: {'colname':col_number,...}",
"# This provides the mapping between column name a... | 34.913043 | 0.001211 |
def sun_declination(day):
"""Compute the declination angle of the sun for the given date.
Uses the Spencer Formula
(found at http://www.illustratingshadows.com/www-formulae-collection.pdf)
:param day: The datetime.date to compute the declination angle for
:returns: The angle, in degrees, of the an... | [
"def",
"sun_declination",
"(",
"day",
")",
":",
"day_of_year",
"=",
"day",
".",
"toordinal",
"(",
")",
"-",
"date",
"(",
"day",
".",
"year",
",",
"1",
",",
"1",
")",
".",
"toordinal",
"(",
")",
"day_angle",
"=",
"2",
"*",
"pi",
"*",
"day_of_year",
... | 33.818182 | 0.001307 |
def execute(path, arguments):
"""
Wrapper around execv():
* fork()s before exec()ing (in order to run the command in a subprocess)
* wait for the subprocess to finish before returning (blocks the parent
process)
This is **hyper** simplistic. This *does not* handle **many** edge cases.
*... | [
"def",
"execute",
"(",
"path",
",",
"arguments",
")",
":",
"pid",
"=",
"os",
".",
"fork",
"(",
")",
"if",
"pid",
"==",
"0",
":",
"try",
":",
"os",
".",
"execv",
"(",
"path",
",",
"arguments",
")",
"finally",
":",
"sys",
".",
"exit",
"(",
"1",
... | 28.961538 | 0.001285 |
def get_analysis_data_for(self, ar):
"""Return the Analysis data for this AR
"""
# Exclude analyses from children (partitions)
analyses = ar.objectValues("Analysis")
out = []
for an in analyses:
info = self.get_base_info(an)
info.update({
... | [
"def",
"get_analysis_data_for",
"(",
"self",
",",
"ar",
")",
":",
"# Exclude analyses from children (partitions)",
"analyses",
"=",
"ar",
".",
"objectValues",
"(",
"\"Analysis\"",
")",
"out",
"=",
"[",
"]",
"for",
"an",
"in",
"analyses",
":",
"info",
"=",
"sel... | 31.692308 | 0.004717 |
def filter_leading_non_json_lines(buf):
'''
used to avoid random output from SSH at the top of JSON output, like messages from
tcagetattr, or where dropbear spews MOTD on every single command (which is nuts).
need to filter anything which starts not with '{', '[', ', '=' or is an empty line.
filter... | [
"def",
"filter_leading_non_json_lines",
"(",
"buf",
")",
":",
"filtered_lines",
"=",
"StringIO",
".",
"StringIO",
"(",
")",
"stop_filtering",
"=",
"False",
"for",
"line",
"in",
"buf",
".",
"splitlines",
"(",
")",
":",
"if",
"stop_filtering",
"or",
"\"=\"",
"... | 42.0625 | 0.007267 |
def get_devices(self, refresh=False, generic_type=None):
"""Get all devices from Lupusec."""
_LOGGER.info("Updating all devices...")
if refresh or self._devices is None:
if self._devices is None:
self._devices = {}
responseObject = self.get_sensors()
... | [
"def",
"get_devices",
"(",
"self",
",",
"refresh",
"=",
"False",
",",
"generic_type",
"=",
"None",
")",
":",
"_LOGGER",
".",
"info",
"(",
"\"Updating all devices...\"",
")",
"if",
"refresh",
"or",
"self",
".",
"_devices",
"is",
"None",
":",
"if",
"self",
... | 36.228571 | 0.001152 |
def walk_tree(self):
"""Generator that yields each :class:`~bloop.stream.shard.Shard` by walking the shard's children in order."""
shards = collections.deque([self])
while shards:
shard = shards.popleft()
yield shard
shards.extend(shard.children) | [
"def",
"walk_tree",
"(",
"self",
")",
":",
"shards",
"=",
"collections",
".",
"deque",
"(",
"[",
"self",
"]",
")",
"while",
"shards",
":",
"shard",
"=",
"shards",
".",
"popleft",
"(",
")",
"yield",
"shard",
"shards",
".",
"extend",
"(",
"shard",
".",... | 42.857143 | 0.009804 |
def predict_heatmap(pdf_path, page_num, model, img_dim=448, img_dir="tmp/img"):
"""
Return an image corresponding to the page of the pdf
documents saved at pdf_path. If the image is not found in img_dir this
function creates it and saves it in img_dir.
:param pdf_path: path to the pdf document.
... | [
"def",
"predict_heatmap",
"(",
"pdf_path",
",",
"page_num",
",",
"model",
",",
"img_dim",
"=",
"448",
",",
"img_dir",
"=",
"\"tmp/img\"",
")",
":",
"if",
"not",
"os",
".",
"path",
".",
"isdir",
"(",
"img_dir",
")",
":",
"print",
"(",
"\"\\nCreating image... | 42.612903 | 0.00074 |
def float_to_fp(signed, n_bits, n_frac):
"""Return a function to convert a floating point value to a fixed point
value.
For example, a function to convert a float to a signed fractional
representation with 8 bits overall and 4 fractional bits (S3.4) can be
constructed and used with::
>>> s... | [
"def",
"float_to_fp",
"(",
"signed",
",",
"n_bits",
",",
"n_frac",
")",
":",
"# Calculate the maximum and minimum values",
"if",
"signed",
":",
"max_v",
"=",
"(",
"1",
"<<",
"(",
"n_bits",
"-",
"1",
")",
")",
"-",
"1",
"min_v",
"=",
"-",
"max_v",
"-",
... | 26.34375 | 0.000572 |
def pull(ctx, source, destination, progress):
""" Copy file(s) from device(s) -> local machine.
@param ctx: The click context paramter, for receiving the object dictionary
| being manipulated by other previous functions. Needed by any
| function with the @click.pass_context decorato... | [
"def",
"pull",
"(",
"ctx",
",",
"source",
",",
"destination",
",",
"progress",
")",
":",
"mp_pool",
"=",
"multiprocessing",
".",
"Pool",
"(",
"multiprocessing",
".",
"cpu_count",
"(",
")",
"*",
"2",
")",
"multi",
"=",
"True",
"if",
"len",
"(",
"ctx",
... | 49.787879 | 0.000597 |
def post_object(self, container, obj, headers=None, query=None, cdn=False,
body=None):
"""
POSTs the object and returns the results. This is used to
update the object's header values. Note that all headers must
be sent with the POST, unlike the account and container P... | [
"def",
"post_object",
"(",
"self",
",",
"container",
",",
"obj",
",",
"headers",
"=",
"None",
",",
"query",
"=",
"None",
",",
"cdn",
"=",
"False",
",",
"body",
"=",
"None",
")",
":",
"path",
"=",
"self",
".",
"_object_path",
"(",
"container",
",",
... | 49.666667 | 0.001795 |
def close_related_clients(self, client):
"""Close all clients related to *client*, except itself"""
related_clients = self.get_related_clients(client)
for cl in related_clients:
self.close_client(client=cl, force=True) | [
"def",
"close_related_clients",
"(",
"self",
",",
"client",
")",
":",
"related_clients",
"=",
"self",
".",
"get_related_clients",
"(",
"client",
")",
"for",
"cl",
"in",
"related_clients",
":",
"self",
".",
"close_client",
"(",
"client",
"=",
"cl",
",",
"forc... | 50.8 | 0.007752 |
def record_type(self, column=None, value=None, **kwargs):
"""
Codes and descriptions indicating whether an award is for a new
project or for the continuation of a currently funded one.
>>> GICS().record_type('record_type_code', 'A')
"""
return self._resolve_call('GIC_REC... | [
"def",
"record_type",
"(",
"self",
",",
"column",
"=",
"None",
",",
"value",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"self",
".",
"_resolve_call",
"(",
"'GIC_RECORD_TYPE'",
",",
"column",
",",
"value",
",",
"*",
"*",
"kwargs",
")"
] | 43.5 | 0.005634 |
def decode_aes256_base64_auto(data, encryption_key):
"""Guesses AES cipher (EBC or CBD) from the length of the base64 encoded data."""
assert isinstance(data, bytes)
length = len(data)
if length == 0:
return b''
elif data[0] == b'!'[0]:
return decode_aes256_cbc_base64(data, encrypti... | [
"def",
"decode_aes256_base64_auto",
"(",
"data",
",",
"encryption_key",
")",
":",
"assert",
"isinstance",
"(",
"data",
",",
"bytes",
")",
"length",
"=",
"len",
"(",
"data",
")",
"if",
"length",
"==",
"0",
":",
"return",
"b''",
"elif",
"data",
"[",
"0",
... | 35.363636 | 0.005013 |
def merge_two(one, other, merge_strategy=MergeStrategy.UNION, silent=False, pixel_strategy=PixelStrategy.FIRST):
# type: (GeoRaster2, GeoRaster2, MergeStrategy, bool, PixelStrategy) -> GeoRaster2
"""Merge two rasters into one.
Parameters
----------
one : GeoRaster2
Left raster to merge.
... | [
"def",
"merge_two",
"(",
"one",
",",
"other",
",",
"merge_strategy",
"=",
"MergeStrategy",
".",
"UNION",
",",
"silent",
"=",
"False",
",",
"pixel_strategy",
"=",
"PixelStrategy",
".",
"FIRST",
")",
":",
"# type: (GeoRaster2, GeoRaster2, MergeStrategy, bool, PixelStrat... | 36.82 | 0.005291 |
def authorize_cache_security_group_ingress(name, region=None, key=None, keyid=None, profile=None, **args):
'''
Authorize network ingress from an ec2 security group to a cache security group.
Example:
.. code-block:: bash
salt myminion boto3_elasticache.authorize_cache_security_group_ingress \... | [
"def",
"authorize_cache_security_group_ingress",
"(",
"name",
",",
"region",
"=",
"None",
",",
"key",
"=",
"None",
",",
"keyid",
"=",
"None",
",",
"profile",
"=",
"None",
",",
"*",
"*",
"args",
")",
":",
"conn",
"=",
"_get_conn",
"(",
"region",
"=",
"r... | 41.5625 | 0.002939 |
def projection(radius=5e-6, sphere_index=1.339, medium_index=1.333,
wavelength=550e-9, pixel_size=1e-7, grid_size=(80, 80),
center=(39.5, 39.5)):
"""Optical path difference projection of a dielectric sphere
Parameters
----------
radius: float
Radius of the sphere [... | [
"def",
"projection",
"(",
"radius",
"=",
"5e-6",
",",
"sphere_index",
"=",
"1.339",
",",
"medium_index",
"=",
"1.333",
",",
"wavelength",
"=",
"550e-9",
",",
"pixel_size",
"=",
"1e-7",
",",
"grid_size",
"=",
"(",
"80",
",",
"80",
")",
",",
"center",
"=... | 32.568627 | 0.000584 |
def lease(self, time_to_live, lease_id=None, timeout=None):
"""
Creates a lease which expires if the server does not
receive a keep alive within a given time to live period.
All keys attached to the lease will be expired and deleted if
the lease expires.
Each expired ke... | [
"def",
"lease",
"(",
"self",
",",
"time_to_live",
",",
"lease_id",
"=",
"None",
",",
"timeout",
"=",
"None",
")",
":",
"assembler",
"=",
"commons",
".",
"LeaseRequestAssembler",
"(",
"self",
".",
"_url",
",",
"time_to_live",
",",
"lease_id",
")",
"obj",
... | 35.903226 | 0.002625 |
def variable_absolute(self, a: float) -> mm.ModelMapper:
"""
Parameters
----------
a
The absolute width of gaussian priors
Returns
-------
A model mapper created by taking results from this phase and creating priors with the defined absolute width.
... | [
"def",
"variable_absolute",
"(",
"self",
",",
"a",
":",
"float",
")",
"->",
"mm",
".",
"ModelMapper",
":",
"return",
"self",
".",
"previous_variable",
".",
"mapper_from_gaussian_tuples",
"(",
"self",
".",
"gaussian_tuples",
",",
"a",
"=",
"a",
")"
] | 34.25 | 0.009479 |
def ends_of_next_whole_turn(self, root):
"""Simulate one complete turn to completion and generate each end of
turn reached during the simulation.
Note on mana drain:
Generates but does not continue simulation of mana drains.
Arguments:
root: a start state with no parent... | [
"def",
"ends_of_next_whole_turn",
"(",
"self",
",",
"root",
")",
":",
"# simple confirmation that the root is actually a root.",
"# otherwise it may seem to work but would be totally out of spec",
"if",
"root",
".",
"parent",
":",
"raise",
"ValueError",
"(",
"'Unexpectedly receiv... | 41.483871 | 0.00152 |
def _cleanup_factory(self):
"""Build a cleanup clojure that doesn't increase our ref count"""
_self = weakref.proxy(self)
def wrapper():
try:
_self.close(timeout=0)
except (ReferenceError, AttributeError):
pass
return wrapper | [
"def",
"_cleanup_factory",
"(",
"self",
")",
":",
"_self",
"=",
"weakref",
".",
"proxy",
"(",
"self",
")",
"def",
"wrapper",
"(",
")",
":",
"try",
":",
"_self",
".",
"close",
"(",
"timeout",
"=",
"0",
")",
"except",
"(",
"ReferenceError",
",",
"Attri... | 33.888889 | 0.009585 |
def main():
"""
NAME
plot_2cdfs.py
DESCRIPTION
makes plots of cdfs of data in input file
SYNTAX
plot_2cdfs.py [-h][command line options]
OPTIONS
-h prints help message and quits
-f FILE1 FILE2
-t TITLE
-fmt [svg,eps,png,pdf,jpg..] specify f... | [
"def",
"main",
"(",
")",
":",
"fmt",
"=",
"'svg'",
"title",
"=",
"\"\"",
"if",
"'-h'",
"in",
"sys",
".",
"argv",
":",
"print",
"(",
"main",
".",
"__doc__",
")",
"sys",
".",
"exit",
"(",
")",
"if",
"'-f'",
"in",
"sys",
".",
"argv",
":",
"ind",
... | 25.272727 | 0.038781 |
def draw_text(self, ax, text, force_trans=None, text_type=None):
"""Process a matplotlib text object and call renderer.draw_text"""
content = text.get_text()
if content:
transform = text.get_transform()
position = text.get_position()
coords, position = self.pr... | [
"def",
"draw_text",
"(",
"self",
",",
"ax",
",",
"text",
",",
"force_trans",
"=",
"None",
",",
"text_type",
"=",
"None",
")",
":",
"content",
"=",
"text",
".",
"get_text",
"(",
")",
"if",
"content",
":",
"transform",
"=",
"text",
".",
"get_transform",
... | 55.071429 | 0.002551 |
def write(self, text, fg='black', bg='white'):
'''write to the console'''
if isinstance(text, str):
sys.stdout.write(text)
else:
sys.stdout.write(str(text))
sys.stdout.flush()
if self.udp.connected():
self.udp.writeln(text)
if self.tcp.... | [
"def",
"write",
"(",
"self",
",",
"text",
",",
"fg",
"=",
"'black'",
",",
"bg",
"=",
"'white'",
")",
":",
"if",
"isinstance",
"(",
"text",
",",
"str",
")",
":",
"sys",
".",
"stdout",
".",
"write",
"(",
"text",
")",
"else",
":",
"sys",
".",
"std... | 32.454545 | 0.00545 |
def filename(self):
""" Name of the file on the client file system, but normalized to ensure
file system compatibility. An empty filename is returned as 'empty'.
Only ASCII letters, digits, dashes, underscores and dots are
allowed in the final filename. Accents are removed, ... | [
"def",
"filename",
"(",
"self",
")",
":",
"fname",
"=",
"self",
".",
"raw_filename",
"if",
"not",
"isinstance",
"(",
"fname",
",",
"unicode",
")",
":",
"fname",
"=",
"fname",
".",
"decode",
"(",
"'utf8'",
",",
"'ignore'",
")",
"fname",
"=",
"normalize"... | 52.333333 | 0.004171 |
def send_location(self, chat_id, latitude, longitude, live_period=None, reply_to_message_id=None, reply_markup=None,
disable_notification=None):
"""
Use this method to send point on the map.
:param chat_id:
:param latitude:
:param longitude:
:param l... | [
"def",
"send_location",
"(",
"self",
",",
"chat_id",
",",
"latitude",
",",
"longitude",
",",
"live_period",
"=",
"None",
",",
"reply_to_message_id",
"=",
"None",
",",
"reply_markup",
"=",
"None",
",",
"disable_notification",
"=",
"None",
")",
":",
"return",
... | 42.4375 | 0.007205 |
def evaluate_binop_comparison(self, operation, left, right, **kwargs):
"""
Evaluate given comparison binary operation with given operands.
"""
if not operation in self.binops_comparison:
raise ValueError("Invalid comparison binary operation '{}'".format(operation))
if... | [
"def",
"evaluate_binop_comparison",
"(",
"self",
",",
"operation",
",",
"left",
",",
"right",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"operation",
"in",
"self",
".",
"binops_comparison",
":",
"raise",
"ValueError",
"(",
"\"Invalid comparison binary opera... | 37.323529 | 0.003072 |
def get_comments(self):
"""
Returns the comments for the job, querying the
server if necessary.
"""
# Lazily load info
if self.info is None:
self.get_info()
if 'comments' in self.info:
return [structure['text'] for structure in self.info['... | [
"def",
"get_comments",
"(",
"self",
")",
":",
"# Lazily load info",
"if",
"self",
".",
"info",
"is",
"None",
":",
"self",
".",
"get_info",
"(",
")",
"if",
"'comments'",
"in",
"self",
".",
"info",
":",
"return",
"[",
"structure",
"[",
"'text'",
"]",
"fo... | 28.230769 | 0.007916 |
def write_data(self, data, data_file, compression=0):
"""Writes the given *preprocessed* data to a file with the given name.
"""
f = bob.io.base.HDF5File(data_file, 'w')
f.set("rate", data[0], compression=compression)
f.set("data", data[1], compression=compression)
f.set("labels", data[2], compr... | [
"def",
"write_data",
"(",
"self",
",",
"data",
",",
"data_file",
",",
"compression",
"=",
"0",
")",
":",
"f",
"=",
"bob",
".",
"io",
".",
"base",
".",
"HDF5File",
"(",
"data_file",
",",
"'w'",
")",
"f",
".",
"set",
"(",
"\"rate\"",
",",
"data",
"... | 47.571429 | 0.00295 |
def secret_hex(self, secret_hex):
"""
Sets the secret_hex of this PreSharedKey.
The secret of the pre-shared key in hexadecimal. It is not case sensitive; 4a is same as 4A, and it is allowed with or without 0x in the beginning. The minimum length of the secret is 128 bits and maximum 256 bits.
... | [
"def",
"secret_hex",
"(",
"self",
",",
"secret_hex",
")",
":",
"if",
"secret_hex",
"is",
"None",
":",
"raise",
"ValueError",
"(",
"\"Invalid value for `secret_hex`, must not be `None`\"",
")",
"if",
"secret_hex",
"is",
"not",
"None",
"and",
"not",
"re",
".",
"se... | 56.071429 | 0.007519 |
def clone(self):
""" Create a copy of the timeout object
Timeout properties are stored per-pool but each request needs a fresh
Timeout object to ensure each one has its own start/stop configured.
:return: a copy of the timeout object
:rtype: :class:`Timeout`
"""
... | [
"def",
"clone",
"(",
"self",
")",
":",
"# We can't use copy.deepcopy because that will also create a new object",
"# for _GLOBAL_DEFAULT_TIMEOUT, which socket.py uses as a sentinel to",
"# detect the user default.",
"return",
"Timeout",
"(",
"connect",
"=",
"self",
".",
"_connect",
... | 42.5 | 0.003289 |
def send_calibrate_accelerometer(self, simple=False):
"""Request accelerometer calibration.
:param simple: if True, perform simple accelerometer calibration
"""
calibration_command = self.message_factory.command_long_encode(
self._handler.target_system, 0, # target_system,... | [
"def",
"send_calibrate_accelerometer",
"(",
"self",
",",
"simple",
"=",
"False",
")",
":",
"calibration_command",
"=",
"self",
".",
"message_factory",
".",
"command_long_encode",
"(",
"self",
".",
"_handler",
".",
"target_system",
",",
"0",
",",
"# target_system, ... | 55.789474 | 0.003711 |
def load_config_file(self, filename, path=None):
"""Load a .py based config file by filename and path."""
loader = PyFileConfigLoader(filename, path=path)
try:
config = loader.load_config()
except ConfigFileNotFound:
# problem finding the file, raise
r... | [
"def",
"load_config_file",
"(",
"self",
",",
"filename",
",",
"path",
"=",
"None",
")",
":",
"loader",
"=",
"PyFileConfigLoader",
"(",
"filename",
",",
"path",
"=",
"path",
")",
"try",
":",
"config",
"=",
"loader",
".",
"load_config",
"(",
")",
"except",... | 46.222222 | 0.003534 |
def _ci_to_hgvs_coord(s, e):
""" Convert continuous interbase (right-open) coordinates (..,-2,-1,0,1,..) to
discontinuous HGVS coordinates (..,-2,-1,1,2,..)
"""
def _ci_to_hgvs(c):
return c + 1 if c >= 0 else c
return (None if s is None else _ci_to_hgvs(s), None if e is None else _ci_to_hg... | [
"def",
"_ci_to_hgvs_coord",
"(",
"s",
",",
"e",
")",
":",
"def",
"_ci_to_hgvs",
"(",
"c",
")",
":",
"return",
"c",
"+",
"1",
"if",
"c",
">=",
"0",
"else",
"c",
"return",
"(",
"None",
"if",
"s",
"is",
"None",
"else",
"_ci_to_hgvs",
"(",
"s",
")",
... | 35.777778 | 0.009091 |
def _do_watch_progress(filename, sock, handler):
"""Function to run in a separate gevent greenlet to read progress
events from a unix-domain socket."""
connection, client_address = sock.accept()
data = b''
try:
while True:
more_data = connection.recv(16)
if not more_d... | [
"def",
"_do_watch_progress",
"(",
"filename",
",",
"sock",
",",
"handler",
")",
":",
"connection",
",",
"client_address",
"=",
"sock",
".",
"accept",
"(",
")",
"data",
"=",
"b''",
"try",
":",
"while",
"True",
":",
"more_data",
"=",
"connection",
".",
"re... | 34.857143 | 0.00133 |
def comment_sync(self, comment):
"""Update comments to host and notify subscribers"""
self.host.update(key="comment", value=comment)
self.host.emit("commented", comment=comment) | [
"def",
"comment_sync",
"(",
"self",
",",
"comment",
")",
":",
"self",
".",
"host",
".",
"update",
"(",
"key",
"=",
"\"comment\"",
",",
"value",
"=",
"comment",
")",
"self",
".",
"host",
".",
"emit",
"(",
"\"commented\"",
",",
"comment",
"=",
"comment",... | 49.5 | 0.00995 |
def write(self, settings=None):
"""
Save the current configuration to its file (as given by :code:`self._config_file`).
Optionally, settings may be passed in to override the current settings before
writing. Returns :code:`None` if the file could not be written to, either due to
p... | [
"def",
"write",
"(",
"self",
",",
"settings",
"=",
"None",
")",
":",
"if",
"\"r\"",
"in",
"self",
".",
"mode",
":",
"raise",
"ConfigReadOnly",
"(",
"\"Cannot write Config while in 'r' mode\"",
")",
"try",
":",
"if",
"settings",
":",
"self",
".",
"settings",
... | 43.380952 | 0.007519 |
def FileHeader(self, zip64=None):
"""Return the per-file header as a string."""
dt = self.date_time
dosdate = (dt[0] - 1980) << 9 | dt[1] << 5 | dt[2]
dostime = dt[3] << 11 | dt[4] << 5 | (dt[5] // 2)
if self.flag_bits & 0x08:
# Set these to zero because we write them... | [
"def",
"FileHeader",
"(",
"self",
",",
"zip64",
"=",
"None",
")",
":",
"dt",
"=",
"self",
".",
"date_time",
"dosdate",
"=",
"(",
"dt",
"[",
"0",
"]",
"-",
"1980",
")",
"<<",
"9",
"|",
"dt",
"[",
"1",
"]",
"<<",
"5",
"|",
"dt",
"[",
"2",
"]"... | 43.911111 | 0.001485 |
def __equalize_densities(self,nominal_bounds,nominal_density):
"""
Calculate the true density along x, and adjust the top and
bottom bounds so that the density along y will be equal.
Returns (adjusted_bounds, true_density)
"""
left,bottom,right,top = nominal_bounds.lbrt(... | [
"def",
"__equalize_densities",
"(",
"self",
",",
"nominal_bounds",
",",
"nominal_density",
")",
":",
"left",
",",
"bottom",
",",
"right",
",",
"top",
"=",
"nominal_bounds",
".",
"lbrt",
"(",
")",
"width",
"=",
"right",
"-",
"left",
"height",
"=",
"top",
... | 43.2 | 0.010193 |
def get_parent(self):
"""Return the parent block of this block, or None if there isn't one."""
if not self.has_cached_parent:
if self.parent is not None:
self._parent_block = self.runtime.get_block(self.parent)
else:
self._parent_block = None
... | [
"def",
"get_parent",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"has_cached_parent",
":",
"if",
"self",
".",
"parent",
"is",
"not",
"None",
":",
"self",
".",
"_parent_block",
"=",
"self",
".",
"runtime",
".",
"get_block",
"(",
"self",
".",
"paren... | 43.111111 | 0.007576 |
def run(command, parser, cl_args, unknown_args):
'''
Submits the topology to the scheduler
* Depending on the topology file name extension, we treat the file as a
fatjar (if the ext is .jar) or a tar file (if the ext is .tar/.tar.gz).
* We upload the topology file to the packer, update zookeeper and l... | [
"def",
"run",
"(",
"command",
",",
"parser",
",",
"cl_args",
",",
"unknown_args",
")",
":",
"Log",
".",
"debug",
"(",
"\"Submit Args %s\"",
",",
"cl_args",
")",
"# get the topology file name",
"topology_file",
"=",
"cl_args",
"[",
"'topology-file-name'",
"]",
"i... | 42.217949 | 0.011573 |
def getOrphanParticleInfos(self, swarmId, genIdx):
"""Return a list of particleStates for all particles in the given
swarm generation that have been orphaned.
Parameters:
---------------------------------------------------------------------
swarmId: A string representation of the sorted list of en... | [
"def",
"getOrphanParticleInfos",
"(",
"self",
",",
"swarmId",
",",
"genIdx",
")",
":",
"entryIdxs",
"=",
"range",
"(",
"len",
"(",
"self",
".",
"_allResults",
")",
")",
"if",
"len",
"(",
"entryIdxs",
")",
"==",
"0",
":",
"return",
"(",
"[",
"]",
",",... | 33.457627 | 0.00935 |
def parse_plays_stream(self):
"""Generate and yield a stream of parsed plays. Useful for per play processing."""
lx_doc = self.html_doc()
if lx_doc is not None:
parser = PlayParser(self.game_key.season, self.game_key.game_type)
plays = lx_doc.xpath('//tr[@class =... | [
"def",
"parse_plays_stream",
"(",
"self",
")",
":",
"lx_doc",
"=",
"self",
".",
"html_doc",
"(",
")",
"if",
"lx_doc",
"is",
"not",
"None",
":",
"parser",
"=",
"PlayParser",
"(",
"self",
".",
"game_key",
".",
"season",
",",
"self",
".",
"game_key",
".",... | 40.25 | 0.010121 |
def upgrade():
"""Upgrade database."""
op.create_table(
'communities_community',
sa.Column('created', sa.DateTime(), nullable=False),
sa.Column('updated', sa.DateTime(), nullable=False),
sa.Column('id', sa.String(length=100), nullable=False),
sa.Column('id_user', sa.Integ... | [
"def",
"upgrade",
"(",
")",
":",
"op",
".",
"create_table",
"(",
"'communities_community'",
",",
"sa",
".",
"Column",
"(",
"'created'",
",",
"sa",
".",
"DateTime",
"(",
")",
",",
"nullable",
"=",
"False",
")",
",",
"sa",
".",
"Column",
"(",
"'updated'"... | 48.92 | 0.000401 |
def step(self, substeps=2):
'''Step the world forward by one frame.
Parameters
----------
substeps : int, optional
Split the step into this many sub-steps. This helps to prevent the
time delta for an update from being too large.
'''
self.frame_no ... | [
"def",
"step",
"(",
"self",
",",
"substeps",
"=",
"2",
")",
":",
"self",
".",
"frame_no",
"+=",
"1",
"dt",
"=",
"self",
".",
"dt",
"/",
"substeps",
"for",
"_",
"in",
"range",
"(",
"substeps",
")",
":",
"self",
".",
"ode_contactgroup",
".",
"empty",... | 34.266667 | 0.003788 |
def send(node_name):
""" Send our information to a remote nago instance
Arguments:
node -- node_name or token for the node this data belongs to
"""
my_data = nago.core.get_my_info()
if not node_name:
node_name = nago.settings.get('server')
node = nago.core.get_node(node_name)
... | [
"def",
"send",
"(",
"node_name",
")",
":",
"my_data",
"=",
"nago",
".",
"core",
".",
"get_my_info",
"(",
")",
"if",
"not",
"node_name",
":",
"node_name",
"=",
"nago",
".",
"settings",
".",
"get",
"(",
"'server'",
")",
"node",
"=",
"nago",
".",
"core"... | 37.529412 | 0.004587 |
def backlink(node):
"""Given a CFG with outgoing links, create incoming links."""
seen = set()
to_see = [node]
while to_see:
node = to_see.pop()
seen.add(node)
for succ in node.next:
succ.prev.add(node)
if succ not in seen:
to_see.append(succ) | [
"def",
"backlink",
"(",
"node",
")",
":",
"seen",
"=",
"set",
"(",
")",
"to_see",
"=",
"[",
"node",
"]",
"while",
"to_see",
":",
"node",
"=",
"to_see",
".",
"pop",
"(",
")",
"seen",
".",
"add",
"(",
"node",
")",
"for",
"succ",
"in",
"node",
"."... | 26.636364 | 0.016502 |
def select_down(self):
"""move cursor down"""
r, c = self._index
self._select_index(r+1, c) | [
"def",
"select_down",
"(",
"self",
")",
":",
"r",
",",
"c",
"=",
"self",
".",
"_index",
"self",
".",
"_select_index",
"(",
"r",
"+",
"1",
",",
"c",
")"
] | 28 | 0.017391 |
def process_der(self, data, name):
"""
DER processing
:param data:
:param name:
:return:
"""
from cryptography.x509.base import load_der_x509_certificate
try:
x509 = load_der_x509_certificate(data, self.get_backend())
self.num_der_c... | [
"def",
"process_der",
"(",
"self",
",",
"data",
",",
"name",
")",
":",
"from",
"cryptography",
".",
"x509",
".",
"base",
"import",
"load_der_x509_certificate",
"try",
":",
"x509",
"=",
"load_der_x509_certificate",
"(",
"data",
",",
"self",
".",
"get_backend",
... | 33.625 | 0.005425 |
def parse_redis_url(redis_url):
'''
>>> parse_redis_url('redis://:pass%20@localhost:1234/selecteddb%20')
('localhost', 1234, 'pass ', 'selecteddb ')
>>> parse_redis_url('redis://:pass%20@localhost:1234/')
('localhost', 1234, 'pass ', None)
>>> parse_redis_url('redis://localhost:1234/')
('loc... | [
"def",
"parse_redis_url",
"(",
"redis_url",
")",
":",
"(",
"use",
",",
"pas",
",",
"hos",
",",
"por",
",",
"pat",
")",
"=",
"_parse_url",
"(",
"redis_url",
",",
"'redis://'",
",",
"def_port",
"=",
"6379",
")",
"return",
"(",
"hos",
",",
"por",
",",
... | 40.052632 | 0.002567 |
def sentinel_get_master_ip(master, host=None, port=None, password=None):
'''
Get ip for sentinel master
.. versionadded: 2016.3.0
CLI Example:
.. code-block:: bash
salt '*' redis.sentinel_get_master_ip 'mymaster'
'''
server = _sconnect(host, port, password)
ret = server.senti... | [
"def",
"sentinel_get_master_ip",
"(",
"master",
",",
"host",
"=",
"None",
",",
"port",
"=",
"None",
",",
"password",
"=",
"None",
")",
":",
"server",
"=",
"_sconnect",
"(",
"host",
",",
"port",
",",
"password",
")",
"ret",
"=",
"server",
".",
"sentinel... | 27 | 0.002387 |
def find_lexer_class_for_filename(_fn, code=None):
"""Get a lexer for a filename.
If multiple lexers match the filename pattern, use ``analyse_text()`` to
figure out which one is more appropriate.
Returns None if not found.
"""
matches = []
fn = basename(_fn)
for modname, name, _, file... | [
"def",
"find_lexer_class_for_filename",
"(",
"_fn",
",",
"code",
"=",
"None",
")",
":",
"matches",
"=",
"[",
"]",
"fn",
"=",
"basename",
"(",
"_fn",
")",
"for",
"modname",
",",
"name",
",",
"_",
",",
"filenames",
",",
"_",
"in",
"itervalues",
"(",
"L... | 38.04878 | 0.000625 |
def create_ca_file(anchor_list, filename):
"""
Concatenate all the certificates (PEM format for the export) in
'anchor_list' and write the result to file 'filename'. On success
'filename' is returned, None otherwise.
If you are used to OpenSSL tools, this function builds a CAfile
that can be us... | [
"def",
"create_ca_file",
"(",
"anchor_list",
",",
"filename",
")",
":",
"try",
":",
"f",
"=",
"open",
"(",
"filename",
",",
"\"w\"",
")",
"for",
"a",
"in",
"anchor_list",
":",
"s",
"=",
"a",
".",
"output",
"(",
"fmt",
"=",
"\"PEM\"",
")",
"f",
".",... | 29.2 | 0.003317 |
def create_bug(self, request):
"""
Create a bugzilla bug with passed params
"""
if settings.BUGFILER_API_KEY is None:
return Response({"failure": "Bugzilla API key not set!"},
status=HTTP_400_BAD_REQUEST)
params = request.data
# A... | [
"def",
"create_bug",
"(",
"self",
",",
"request",
")",
":",
"if",
"settings",
".",
"BUGFILER_API_KEY",
"is",
"None",
":",
"return",
"Response",
"(",
"{",
"\"failure\"",
":",
"\"Bugzilla API key not set!\"",
"}",
",",
"status",
"=",
"HTTP_400_BAD_REQUEST",
")",
... | 40.846154 | 0.002299 |
def concat_batch_variantcalls(items, region_block=True, skip_jointcheck=False):
"""CWL entry point: combine variant calls from regions into single VCF.
"""
items = [utils.to_single_data(x) for x in items]
batch_name = _get_batch_name(items, skip_jointcheck)
variantcaller = _get_batch_variantcaller(i... | [
"def",
"concat_batch_variantcalls",
"(",
"items",
",",
"region_block",
"=",
"True",
",",
"skip_jointcheck",
"=",
"False",
")",
":",
"items",
"=",
"[",
"utils",
".",
"to_single_data",
"(",
"x",
")",
"for",
"x",
"in",
"items",
"]",
"batch_name",
"=",
"_get_b... | 55.210526 | 0.003749 |
def _split_line(s, parts):
"""
Parameters
----------
s: string
Fixed-length string to split
parts: list of (name, length) pairs
Used to break up string, name '_' will be filtered from output.
Returns
-------
Dict of name:contents of string at given location.
"""
... | [
"def",
"_split_line",
"(",
"s",
",",
"parts",
")",
":",
"out",
"=",
"{",
"}",
"start",
"=",
"0",
"for",
"name",
",",
"length",
"in",
"parts",
":",
"out",
"[",
"name",
"]",
"=",
"s",
"[",
"start",
":",
"start",
"+",
"length",
"]",
".",
"strip",
... | 23.1 | 0.002079 |
def analyzeThing(originalThing2):
"""analyze an object and all its attirbutes. Returns a dictionary."""
originalThing = copy.copy(originalThing2)
things={}
for name in sorted(dir(originalThing)):
print("analyzing",name)
thing = copy.copy(originalThing)
if name in webinspec... | [
"def",
"analyzeThing",
"(",
"originalThing2",
")",
":",
"originalThing",
"=",
"copy",
".",
"copy",
"(",
"originalThing2",
")",
"things",
"=",
"{",
"}",
"for",
"name",
"in",
"sorted",
"(",
"dir",
"(",
"originalThing",
")",
")",
":",
"print",
"(",
"\"analy... | 39.655172 | 0.016978 |
def minlen(min_length,
strict=False # type: bool
):
"""
'Minimum length' validation_function generator.
Returns a validation_function to check that len(x) >= min_length (strict=False, default)
or len(x) > min_length (strict=True)
:param min_length: minimum length for x
:p... | [
"def",
"minlen",
"(",
"min_length",
",",
"strict",
"=",
"False",
"# type: bool",
")",
":",
"if",
"strict",
":",
"def",
"minlen_",
"(",
"x",
")",
":",
"if",
"len",
"(",
"x",
")",
">",
"min_length",
":",
"return",
"True",
"else",
":",
"# raise Failure('m... | 38.966667 | 0.006678 |
def comparison_operator_query(comparison_operator):
"""Generate comparison operator checking function."""
def _comparison_operator_query(expression):
"""Apply binary operator to expression."""
def _apply_comparison_operator(index, expression=expression):
"""Return store key for docum... | [
"def",
"comparison_operator_query",
"(",
"comparison_operator",
")",
":",
"def",
"_comparison_operator_query",
"(",
"expression",
")",
":",
"\"\"\"Apply binary operator to expression.\"\"\"",
"def",
"_apply_comparison_operator",
"(",
"index",
",",
"expression",
"=",
"expressi... | 45.3125 | 0.001351 |
def pdf_saver(filehandle, *args, **kwargs):
"Uses werkzeug.FileStorage instance to save the converted image."
fullpath = get_save_path(filehandle.filename)
filehandle.save(fullpath, buffer_size=kwargs.get('buffer_size', 16384)) | [
"def",
"pdf_saver",
"(",
"filehandle",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"fullpath",
"=",
"get_save_path",
"(",
"filehandle",
".",
"filename",
")",
"filehandle",
".",
"save",
"(",
"fullpath",
",",
"buffer_size",
"=",
"kwargs",
".",
"ge... | 59 | 0.004184 |
def set_permissions(username, permissions, uid=None):
'''
Configure users permissions
CLI Example:
.. code-block:: bash
salt dell drac.set_permissions [USERNAME] [PRIVILEGES] [USER INDEX - optional]
salt dell drac.set_permissions diana login,test_alerts,clear_logs 4
DRAC Privileg... | [
"def",
"set_permissions",
"(",
"username",
",",
"permissions",
",",
"uid",
"=",
"None",
")",
":",
"privileges",
"=",
"{",
"'login'",
":",
"'0x0000001'",
",",
"'drac'",
":",
"'0x0000002'",
",",
"'user_management'",
":",
"'0x0000004'",
",",
"'clear_logs'",
":",
... | 34.979167 | 0.001159 |
def _apply_scope(self, config, tags):
"""Add locally scoped tags to config"""
if isinstance(config, dict):
# Recursively _apply_scope for each item in the config
for val in config.values():
self._apply_scope(val, tags)
elif isinstance(config, list):
... | [
"def",
"_apply_scope",
"(",
"self",
",",
"config",
",",
"tags",
")",
":",
"if",
"isinstance",
"(",
"config",
",",
"dict",
")",
":",
"# Recursively _apply_scope for each item in the config",
"for",
"val",
"in",
"config",
".",
"values",
"(",
")",
":",
"self",
... | 36.6 | 0.002663 |
def prepare_mvpa_data(images, conditions, mask):
"""Prepare data for activity-based model training and prediction.
Average the activity within epochs and z-scoring within subject.
Parameters
----------
images: Iterable[SpatialImage]
Data.
conditions: List[UniqueLabelConditionSpec]
... | [
"def",
"prepare_mvpa_data",
"(",
"images",
",",
"conditions",
",",
"mask",
")",
":",
"activity_data",
"=",
"list",
"(",
"mask_images",
"(",
"images",
",",
"mask",
",",
"np",
".",
"float32",
")",
")",
"epoch_info",
"=",
"generate_epochs_info",
"(",
"condition... | 32.692308 | 0.000571 |
def install(name, minimum_version=None, required_version=None, scope=None,
repository=None):
'''
Install a Powershell module from powershell gallery on the system.
:param name: Name of a Powershell module
:type name: ``str``
:param minimum_version: The maximum version to install, e.g.... | [
"def",
"install",
"(",
"name",
",",
"minimum_version",
"=",
"None",
",",
"required_version",
"=",
"None",
",",
"scope",
"=",
"None",
",",
"repository",
"=",
"None",
")",
":",
"# Putting quotes around the parameter protects against command injection",
"flags",
"=",
"... | 31.953488 | 0.001412 |
def build(self, filename, bytecode_compile=True):
"""Package the PEX into a zipfile.
:param filename: The filename where the PEX should be stored.
:param bytecode_compile: If True, precompile .py files into .pyc files.
If the PEXBuilder is not yet frozen, it will be frozen by ``build``. This renders ... | [
"def",
"build",
"(",
"self",
",",
"filename",
",",
"bytecode_compile",
"=",
"True",
")",
":",
"if",
"not",
"self",
".",
"_frozen",
":",
"self",
".",
"freeze",
"(",
"bytecode_compile",
"=",
"bytecode_compile",
")",
"try",
":",
"os",
".",
"unlink",
"(",
... | 38.777778 | 0.011184 |
def run_shell_command(
state, host, command,
get_pty=False, timeout=None, print_output=False,
**command_kwargs
):
'''
Execute a command on the local machine.
Args:
state (``pyinfra.api.State`` obj): state object for this command
hostname (string): hostname of the target
... | [
"def",
"run_shell_command",
"(",
"state",
",",
"host",
",",
"command",
",",
"get_pty",
"=",
"False",
",",
"timeout",
"=",
"None",
",",
"print_output",
"=",
"False",
",",
"*",
"*",
"command_kwargs",
")",
":",
"command",
"=",
"make_command",
"(",
"command",
... | 34.277778 | 0.000394 |
def dispatch(self, receiver):
''' Dispatch handling of this event to a receiver.
This method will invoke ``receiver._session_callback_removed`` if
it exists.
'''
super(SessionCallbackRemoved, self).dispatch(receiver)
if hasattr(receiver, '_session_callback_removed'):
... | [
"def",
"dispatch",
"(",
"self",
",",
"receiver",
")",
":",
"super",
"(",
"SessionCallbackRemoved",
",",
"self",
")",
".",
"dispatch",
"(",
"receiver",
")",
"if",
"hasattr",
"(",
"receiver",
",",
"'_session_callback_removed'",
")",
":",
"receiver",
".",
"_ses... | 36.1 | 0.005405 |
def train(dataset, nef, ndf, ngf, nc, batch_size, Z, lr, beta1, epsilon, ctx, check_point, g_dl_weight, output_path, checkpoint_path, data_path, activation,num_epoch, save_after_every, visualize_after_every, show_after_every):
'''adversarial training of the VAE
'''
#encoder
z_mu, z_lv, z = encoder(nef,... | [
"def",
"train",
"(",
"dataset",
",",
"nef",
",",
"ndf",
",",
"ngf",
",",
"nc",
",",
"batch_size",
",",
"Z",
",",
"lr",
",",
"beta1",
",",
"epsilon",
",",
"ctx",
",",
"check_point",
",",
"g_dl_weight",
",",
"output_path",
",",
"checkpoint_path",
",",
... | 39.09816 | 0.005202 |
def run_from_argv(self, argv):
"""
Set the default Gherkin test runner for its options to be parsed.
"""
self.test_runner = test_runner_class
super(Command, self).run_from_argv(argv) | [
"def",
"run_from_argv",
"(",
"self",
",",
"argv",
")",
":",
"self",
".",
"test_runner",
"=",
"test_runner_class",
"super",
"(",
"Command",
",",
"self",
")",
".",
"run_from_argv",
"(",
"argv",
")"
] | 31 | 0.008969 |
def _buildStartOpts(self, streamUrl, playList=False):
""" Builds the options to pass to subprocess."""
""" Test for newer MPV versions as it supports different IPC flags. """
p = subprocess.Popen([self.PLAYER_CMD, "--input-ipc-server"], stdout=subprocess.PIPE, stdin=subprocess.PIPE, shell=False... | [
"def",
"_buildStartOpts",
"(",
"self",
",",
"streamUrl",
",",
"playList",
"=",
"False",
")",
":",
"\"\"\" Test for newer MPV versions as it supports different IPC flags. \"\"\"",
"p",
"=",
"subprocess",
".",
"Popen",
"(",
"[",
"self",
".",
"PLAYER_CMD",
",",
"\"--inpu... | 45.939394 | 0.005814 |
def _set_survey_scenario(self, survey_scenario):
"""
Set survey scenario
:param survey_scenario: the survey scenario
"""
self.survey_scenario = survey_scenario
# TODO deal with baseline if reform is present
if survey_scenario.simulation is None:
... | [
"def",
"_set_survey_scenario",
"(",
"self",
",",
"survey_scenario",
")",
":",
"self",
".",
"survey_scenario",
"=",
"survey_scenario",
"# TODO deal with baseline if reform is present",
"if",
"survey_scenario",
".",
"simulation",
"is",
"None",
":",
"survey_scenario",
".",
... | 51.8 | 0.016114 |
def load_related_model(self, name, load_only=None, dont_load=None):
'''Load a the :class:`ForeignKey` field ``name`` if this is part of the
fields of this model and if the related object is not already loaded.
It is used by the lazy loading mechanism of :ref:`one-to-many <one-to-many>`
relationships.
:paramete... | [
"def",
"load_related_model",
"(",
"self",
",",
"name",
",",
"load_only",
"=",
"None",
",",
"dont_load",
"=",
"None",
")",
":",
"field",
"=",
"self",
".",
"_meta",
".",
"dfields",
".",
"get",
"(",
"name",
")",
"if",
"not",
"field",
":",
"raise",
"Valu... | 52.705882 | 0.002193 |
def svg_polygons_to_df(svg_source, xpath='//svg:polygon',
namespaces=INKSCAPE_NSMAP):
'''
Construct a data frame with one row per vertex for all shapes (e.g.,
``svg:path``, ``svg:polygon``) in :data:`svg_source``.
Arguments
---------
svg_source : str or file-like
... | [
"def",
"svg_polygons_to_df",
"(",
"svg_source",
",",
"xpath",
"=",
"'//svg:polygon'",
",",
"namespaces",
"=",
"INKSCAPE_NSMAP",
")",
":",
"warnings",
".",
"warn",
"(",
"\"The `svg_polygons_to_df` function is deprecated. Use \"",
"\"`svg_shapes_to_df` instead.\"",
")",
"res... | 41.702703 | 0.000633 |
def create_role(self, role_name, role_type, host_id):
"""
Create a role.
@param role_name: Role name
@param role_type: Role type
@param host_id: ID of the host to assign the role to
@return: An ApiRole object
"""
return roles.create_role(self._get_resource_root(), self.name, role_type,
... | [
"def",
"create_role",
"(",
"self",
",",
"role_name",
",",
"role_type",
",",
"host_id",
")",
":",
"return",
"roles",
".",
"create_role",
"(",
"self",
".",
"_get_resource_root",
"(",
")",
",",
"self",
".",
"name",
",",
"role_type",
",",
"role_name",
",",
"... | 33 | 0.005362 |
def read_sudoers():
""" Read the sudoers entry for the specified user.
args:
username (str): username.
returns:`r
str: sudoers entry for the specified user.
"""
sudoers_path = '/etc/sudoers'
rnd_chars = random_string(length=RANDOM_FILE_EXT_LENGTH)
tmp_sudoers_path = '/tmp/s... | [
"def",
"read_sudoers",
"(",
")",
":",
"sudoers_path",
"=",
"'/etc/sudoers'",
"rnd_chars",
"=",
"random_string",
"(",
"length",
"=",
"RANDOM_FILE_EXT_LENGTH",
")",
"tmp_sudoers_path",
"=",
"'/tmp/sudoers_{0}'",
".",
"format",
"(",
"rnd_chars",
")",
"sudoers_entries",
... | 44.04 | 0.003556 |
def detect(self, text):
"""Detect language of the input text
:param text: The source text(s) whose language you want to identify.
Batch detection is supported via sequence input.
:type text: UTF-8 :class:`str`; :class:`unicode`; string sequence (list, tuple, iterator, gener... | [
"def",
"detect",
"(",
"self",
",",
"text",
")",
":",
"if",
"isinstance",
"(",
"text",
",",
"list",
")",
":",
"result",
"=",
"[",
"]",
"for",
"item",
"in",
"text",
":",
"lang",
"=",
"self",
".",
"detect",
"(",
"item",
")",
"result",
".",
"append",... | 36.576923 | 0.00256 |
def _dist_to_annot_donor_acceptor(df, d, strand, novel_feature):
"""Find nearest annotated upstream/downstream donor/acceptor for novel
donor/acceptors.
Parameters
----------
df : pandas.DataFrame
Dataframe with observed splice junctions (novel and known) with columns
'chrom', 'firs... | [
"def",
"_dist_to_annot_donor_acceptor",
"(",
"df",
",",
"d",
",",
"strand",
",",
"novel_feature",
")",
":",
"if",
"df",
".",
"shape",
"[",
"0",
"]",
">",
"0",
":",
"assert",
"len",
"(",
"set",
"(",
"df",
".",
"strand",
")",
")",
"==",
"1",
"if",
... | 37.626374 | 0.001707 |
def prettify_xml(xml_root):
"""Returns pretty-printed string representation of element tree."""
xml_string = etree.tostring(xml_root, encoding="utf-8", xml_declaration=True, pretty_print=True)
return get_unicode_str(xml_string) | [
"def",
"prettify_xml",
"(",
"xml_root",
")",
":",
"xml_string",
"=",
"etree",
".",
"tostring",
"(",
"xml_root",
",",
"encoding",
"=",
"\"utf-8\"",
",",
"xml_declaration",
"=",
"True",
",",
"pretty_print",
"=",
"True",
")",
"return",
"get_unicode_str",
"(",
"... | 59 | 0.008368 |
def register(self, entry_point):
"""Register an extension
:param str entry_point: extension to register (entry point syntax).
:raise: ValueError if already registered.
"""
if entry_point in self.registered_extensions:
raise ValueError('Extension already registered')... | [
"def",
"register",
"(",
"self",
",",
"entry_point",
")",
":",
"if",
"entry_point",
"in",
"self",
".",
"registered_extensions",
":",
"raise",
"ValueError",
"(",
"'Extension already registered'",
")",
"ep",
"=",
"EntryPoint",
".",
"parse",
"(",
"entry_point",
")",... | 37.842105 | 0.002714 |
def load_data(self, filename, *args, **kwargs):
"""
Load JSON data.
:param filename: name of JSON file with data
:type filename: str
:return: data
:rtype: dict
"""
# append .json extension if needed
if not filename.endswith('.json'):
f... | [
"def",
"load_data",
"(",
"self",
",",
"filename",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"# append .json extension if needed",
"if",
"not",
"filename",
".",
"endswith",
"(",
"'.json'",
")",
":",
"filename",
"+=",
"'.json'",
"# append \"json\" to ... | 47.470588 | 0.001821 |
def _load_from_string(data):
'''Loads the cache from the string'''
global _CACHE
if PYTHON_3:
data = json.loads(data.decode("utf-8"))
else:
data = json.loads(data)
_CACHE = _recursively_convert_unicode_to_str(data)['data'] | [
"def",
"_load_from_string",
"(",
"data",
")",
":",
"global",
"_CACHE",
"if",
"PYTHON_3",
":",
"data",
"=",
"json",
".",
"loads",
"(",
"data",
".",
"decode",
"(",
"\"utf-8\"",
")",
")",
"else",
":",
"data",
"=",
"json",
".",
"loads",
"(",
"data",
")",... | 31.375 | 0.003876 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.