text stringlengths 75 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 0.18 |
|---|---|---|---|
def get_tiles(self):
"""Get all TileCoordinates contained in the region"""
for x, y in griditer(self.root_tile.x, self.root_tile.y, ncol=self.tiles_per_row):
yield TileCoordinate(self.root_tile.zoom, x, y) | [
"def",
"get_tiles",
"(",
"self",
")",
":",
"for",
"x",
",",
"y",
"in",
"griditer",
"(",
"self",
".",
"root_tile",
".",
"x",
",",
"self",
".",
"root_tile",
".",
"y",
",",
"ncol",
"=",
"self",
".",
"tiles_per_row",
")",
":",
"yield",
"TileCoordinate",
... | 57.5 | 0.012876 |
def chugid(runas, group=None):
'''
Change the current process to belong to the specified user (and the groups
to which it belongs)
'''
uinfo = pwd.getpwnam(runas)
supgroups = []
supgroups_seen = set()
if group:
try:
target_pw_gid = grp.getgrnam(group).gr_gid
... | [
"def",
"chugid",
"(",
"runas",
",",
"group",
"=",
"None",
")",
":",
"uinfo",
"=",
"pwd",
".",
"getpwnam",
"(",
"runas",
")",
"supgroups",
"=",
"[",
"]",
"supgroups_seen",
"=",
"set",
"(",
")",
"if",
"group",
":",
"try",
":",
"target_pw_gid",
"=",
"... | 33.871429 | 0.00041 |
def SetPlatformArchContext():
"""Add the running contexts to the config system."""
# Initialize the running platform context:
_CONFIG.AddContext("Platform:%s" % platform.system().title())
machine = platform.uname()[4]
if machine in ["x86_64", "AMD64", "i686"]:
# 32 bit binaries running on AMD64 will sti... | [
"def",
"SetPlatformArchContext",
"(",
")",
":",
"# Initialize the running platform context:",
"_CONFIG",
".",
"AddContext",
"(",
"\"Platform:%s\"",
"%",
"platform",
".",
"system",
"(",
")",
".",
"title",
"(",
")",
")",
"machine",
"=",
"platform",
".",
"uname",
"... | 27.842105 | 0.02011 |
def get_required_config(self):
"""because of the exsistance of subparsers, the configman options
that correspond with argparse arguments are not a constant. We need
to produce a copy of the namespace rather than the actual embedded
namespace."""
required_config = Namespace()
... | [
"def",
"get_required_config",
"(",
"self",
")",
":",
"required_config",
"=",
"Namespace",
"(",
")",
"# add current options to a copy of required config",
"for",
"k",
",",
"v",
"in",
"iteritems_breadth_first",
"(",
"self",
".",
"required_config",
")",
":",
"required_co... | 45.65625 | 0.00134 |
def parse_iparamvalue(self, tup_tree):
"""
Parse expected IPARAMVALUE element. I.e.
::
<!ELEMENT IPARAMVALUE (VALUE | VALUE.ARRAY | VALUE.REFERENCE |
INSTANCENAME | CLASSNAME |
QUALIFIER.DECLARATION |
... | [
"def",
"parse_iparamvalue",
"(",
"self",
",",
"tup_tree",
")",
":",
"self",
".",
"check_node",
"(",
"tup_tree",
",",
"'IPARAMVALUE'",
",",
"(",
"'NAME'",
",",
")",
")",
"child",
"=",
"self",
".",
"optional_child",
"(",
"tup_tree",
",",
"(",
"'VALUE'",
",... | 38.375 | 0.001589 |
def doc_create(self,index,itype,value):
'''
Creates a document
'''
request = self.session
url = 'http://%s:%s/%s/%s/' % (self.host, self.port, index, itype)
if self.verbose:
print value
response = request.post(url,value)
return response | [
"def",
"doc_create",
"(",
"self",
",",
"index",
",",
"itype",
",",
"value",
")",
":",
"request",
"=",
"self",
".",
"session",
"url",
"=",
"'http://%s:%s/%s/%s/'",
"%",
"(",
"self",
".",
"host",
",",
"self",
".",
"port",
",",
"index",
",",
"itype",
")... | 30.3 | 0.019231 |
def find_ports(device):
"""
Find the port chain a device is plugged on.
This is done by searching sysfs for a device that matches the device
bus/address combination.
Useful when the underlying usb lib does not return device.port_number for
whatever reason.
"""
bus_id = device.bus
d... | [
"def",
"find_ports",
"(",
"device",
")",
":",
"bus_id",
"=",
"device",
".",
"bus",
"dev_id",
"=",
"device",
".",
"address",
"for",
"dirent",
"in",
"os",
".",
"listdir",
"(",
"USB_SYS_PREFIX",
")",
":",
"matches",
"=",
"re",
".",
"match",
"(",
"USB_PORT... | 31.925926 | 0.001126 |
def _write(self, request):
"""Actually serialize and write the request."""
with sw("serialize_request"):
request_str = request.SerializeToString()
with sw("write_request"):
with catch_websocket_connection_errors():
self._sock.send(request_str) | [
"def",
"_write",
"(",
"self",
",",
"request",
")",
":",
"with",
"sw",
"(",
"\"serialize_request\"",
")",
":",
"request_str",
"=",
"request",
".",
"SerializeToString",
"(",
")",
"with",
"sw",
"(",
"\"write_request\"",
")",
":",
"with",
"catch_websocket_connecti... | 38.428571 | 0.010909 |
def _get_page_content(self, response):
"""Given a :class:`requests.Response`, return the
:class:`xml.etree.Element` of the content `div`.
:param response: a :class:`requests.Response` to parse
:returns: the :class:`Element` of the first content `div` or `None`
"""
docume... | [
"def",
"_get_page_content",
"(",
"self",
",",
"response",
")",
":",
"document",
"=",
"html5lib",
".",
"parse",
"(",
"response",
".",
"content",
",",
"encoding",
"=",
"response",
".",
"encoding",
",",
"treebuilder",
"=",
"'etree'",
",",
"namespaceHTMLElements",... | 35.892857 | 0.001938 |
def approx_eq(val: Any, other: Any, *, atol: Union[int, float] = 1e-8) -> bool:
"""Approximately compares two objects.
If `val` implements SupportsApproxEquality protocol then it is invoked and
takes precedence over all other checks:
- For primitive numeric types `int` and `float` approximate equality... | [
"def",
"approx_eq",
"(",
"val",
":",
"Any",
",",
"other",
":",
"Any",
",",
"*",
",",
"atol",
":",
"Union",
"[",
"int",
",",
"float",
"]",
"=",
"1e-8",
")",
"->",
"bool",
":",
"# Check if val defines approximate equality via _approx_eq_. This takes",
"# precede... | 40.103448 | 0.000839 |
def refresh(self) -> None:
"""Update the actual simulation values based on the toy-value pairs.
Usually, one does not need to call refresh explicitly. The
"magic" methods __call__, __setattr__, and __delattr__ invoke
it automatically, when required.
Instantiate a 1-dimensional... | [
"def",
"refresh",
"(",
"self",
")",
"->",
"None",
":",
"if",
"not",
"self",
":",
"self",
".",
"values",
"[",
":",
"]",
"=",
"0.",
"elif",
"len",
"(",
"self",
")",
"==",
"1",
":",
"values",
"=",
"list",
"(",
"self",
".",
"_toy2values",
".",
"val... | 32.64 | 0.000793 |
def list_pkgs(versions_as_list=False,
removed=False,
purge_desired=False,
**kwargs): # pylint: disable=W0613
'''
List the packages currently installed in a dict::
{'<package_name>': '<version>'}
removed
If ``True``, then only packages which have b... | [
"def",
"list_pkgs",
"(",
"versions_as_list",
"=",
"False",
",",
"removed",
"=",
"False",
",",
"purge_desired",
"=",
"False",
",",
"*",
"*",
"kwargs",
")",
":",
"# pylint: disable=W0613",
"versions_as_list",
"=",
"salt",
".",
"utils",
".",
"data",
".",
"is_tr... | 37.102041 | 0.000268 |
def _windows_rename(self, tmp_filename):
""" Workaround the fact that os.rename raises an OSError on Windows
:param tmp_filename: The file to rename
"""
os.remove(self.input_file) if os.path.isfile(self.input_file) else None
os.rename(tmp_filename, self.input_file) | [
"def",
"_windows_rename",
"(",
"self",
",",
"tmp_filename",
")",
":",
"os",
".",
"remove",
"(",
"self",
".",
"input_file",
")",
"if",
"os",
".",
"path",
".",
"isfile",
"(",
"self",
".",
"input_file",
")",
"else",
"None",
"os",
".",
"rename",
"(",
"tm... | 34.666667 | 0.0125 |
def store_records_for_package(self, entry_point, records):
"""
Given that records are based on the parent, and the same entry
point(s) will reference those same records multiple times, the
actual stored records must be limited.
"""
pkg_records_entry = self._dist_to_packa... | [
"def",
"store_records_for_package",
"(",
"self",
",",
"entry_point",
",",
"records",
")",
":",
"pkg_records_entry",
"=",
"self",
".",
"_dist_to_package_module_map",
"(",
"entry_point",
")",
"pkg_records_entry",
".",
"extend",
"(",
"rec",
"for",
"rec",
"in",
"recor... | 48.588235 | 0.002375 |
def get_normalized_elevation_array(world):
''' Convert raw elevation into normalized values between 0 and 255,
and return a numpy array of these values '''
e = world.layers['elevation'].data
ocean = world.layers['ocean'].data
mask = numpy.ma.array(e, mask=ocean) # only land
min_elev_land ... | [
"def",
"get_normalized_elevation_array",
"(",
"world",
")",
":",
"e",
"=",
"world",
".",
"layers",
"[",
"'elevation'",
"]",
".",
"data",
"ocean",
"=",
"world",
".",
"layers",
"[",
"'ocean'",
"]",
".",
"data",
"mask",
"=",
"numpy",
".",
"ma",
".",
"arra... | 37.869565 | 0.00224 |
def sqlite_by_shell(self, destination):
"""Method with shell and a temp file. This is hopefully fast."""
script_path = new_temp_path()
self.sqlite_dump_shell(script_path)
shell_output('sqlite3 -bail -init "%s" "%s" .quit' % (script, destination))
script.remove() | [
"def",
"sqlite_by_shell",
"(",
"self",
",",
"destination",
")",
":",
"script_path",
"=",
"new_temp_path",
"(",
")",
"self",
".",
"sqlite_dump_shell",
"(",
"script_path",
")",
"shell_output",
"(",
"'sqlite3 -bail -init \"%s\" \"%s\" .quit'",
"%",
"(",
"script",
",",
... | 49.5 | 0.009934 |
def align_vectors(a, b, return_angle=False):
"""
Find a transform between two 3D vectors.
Implements the method described here:
http://ethaneade.com/rot_between_vectors.pdf
Parameters
--------------
a : (3,) float
Source vector
b : (3,) float
Target vector
return_angle ... | [
"def",
"align_vectors",
"(",
"a",
",",
"b",
",",
"return_angle",
"=",
"False",
")",
":",
"# copy of input vectors",
"a",
"=",
"np",
".",
"array",
"(",
"a",
",",
"dtype",
"=",
"np",
".",
"float64",
",",
"copy",
"=",
"True",
")",
"b",
"=",
"np",
".",... | 26.071429 | 0.00044 |
def on_exception(wait_gen,
exception,
max_tries=None,
max_time=None,
jitter=full_jitter,
giveup=lambda e: False,
on_success=None,
on_backoff=None,
on_giveup=None,
logg... | [
"def",
"on_exception",
"(",
"wait_gen",
",",
"exception",
",",
"max_tries",
"=",
"None",
",",
"max_time",
"=",
"None",
",",
"jitter",
"=",
"full_jitter",
",",
"giveup",
"=",
"lambda",
"e",
":",
"False",
",",
"on_success",
"=",
"None",
",",
"on_backoff",
... | 48.333333 | 0.000233 |
def magic_timeit(setup, stmt, ncalls=None, repeat=3, force_ms=False):
"""Time execution of a Python statement or expression
Usage:\\
%timeit [-n<N> -r<R> [-t|-c]] statement
Time execution of a Python statement or expression using the timeit
module.
Options:
-n<N>: execute the given stateme... | [
"def",
"magic_timeit",
"(",
"setup",
",",
"stmt",
",",
"ncalls",
"=",
"None",
",",
"repeat",
"=",
"3",
",",
"force_ms",
"=",
"False",
")",
":",
"import",
"timeit",
"import",
"math",
"units",
"=",
"[",
"\"s\"",
",",
"\"ms\"",
",",
"'us'",
",",
"\"ns\"... | 34.971831 | 0.000392 |
def _deleted_files():
'''
Iterates over /proc/PID/maps and /proc/PID/fd links and returns list of desired deleted files.
Returns:
List of deleted files to analyze, False on failure.
'''
deleted_files = []
for proc in psutil.process_iter(): # pylint: disable=too-many-nested-blocks
... | [
"def",
"_deleted_files",
"(",
")",
":",
"deleted_files",
"=",
"[",
"]",
"for",
"proc",
"in",
"psutil",
".",
"process_iter",
"(",
")",
":",
"# pylint: disable=too-many-nested-blocks",
"try",
":",
"pinfo",
"=",
"proc",
".",
"as_dict",
"(",
"attrs",
"=",
"[",
... | 38.514706 | 0.002234 |
def show(cls, app_id):
"""
Shows an app by issuing a GET request to the /apps/ID endpoint.
"""
conn = Qubole.agent()
return conn.get(cls.element_path(app_id)) | [
"def",
"show",
"(",
"cls",
",",
"app_id",
")",
":",
"conn",
"=",
"Qubole",
".",
"agent",
"(",
")",
"return",
"conn",
".",
"get",
"(",
"cls",
".",
"element_path",
"(",
"app_id",
")",
")"
] | 32.166667 | 0.010101 |
def paintGroup( self, painter ):
"""
Paints this item as the group look.
:param painter | <QPainter>
"""
# generate the rect
rect = self.rect()
padding = self.padding()
gantt = self.scene().ganttWidget()
cell_w = gant... | [
"def",
"paintGroup",
"(",
"self",
",",
"painter",
")",
":",
"# generate the rect\r",
"rect",
"=",
"self",
".",
"rect",
"(",
")",
"padding",
"=",
"self",
".",
"padding",
"(",
")",
"gantt",
"=",
"self",
".",
"scene",
"(",
")",
".",
"ganttWidget",
"(",
... | 33.25 | 0.014988 |
def set_help(self):
"""Set help text markup.
"""
if not (self.field.help_text and self.attrs.get("_help")):
return
self.values["help"] = HELP_TEMPLATE.format(self.field.help_text) | [
"def",
"set_help",
"(",
"self",
")",
":",
"if",
"not",
"(",
"self",
".",
"field",
".",
"help_text",
"and",
"self",
".",
"attrs",
".",
"get",
"(",
"\"_help\"",
")",
")",
":",
"return",
"self",
".",
"values",
"[",
"\"help\"",
"]",
"=",
"HELP_TEMPLATE",... | 27.285714 | 0.035533 |
def _libvirt_creds():
'''
Returns the user and group that the disk images should be owned by
'''
g_cmd = 'grep ^\\s*group /etc/libvirt/qemu.conf'
u_cmd = 'grep ^\\s*user /etc/libvirt/qemu.conf'
try:
stdout = subprocess.Popen(g_cmd,
shell=True,
... | [
"def",
"_libvirt_creds",
"(",
")",
":",
"g_cmd",
"=",
"'grep ^\\\\s*group /etc/libvirt/qemu.conf'",
"u_cmd",
"=",
"'grep ^\\\\s*user /etc/libvirt/qemu.conf'",
"try",
":",
"stdout",
"=",
"subprocess",
".",
"Popen",
"(",
"g_cmd",
",",
"shell",
"=",
"True",
",",
"stdou... | 38.238095 | 0.001215 |
def InnermostClass(self):
"""Get class info on the top of the stack.
Returns:
A _ClassInfo object if we are inside a class, or None otherwise.
"""
for i in range(len(self.stack), 0, -1):
classinfo = self.stack[i - 1]
if isinstance(classinfo, _ClassInfo):
return classinfo
r... | [
"def",
"InnermostClass",
"(",
"self",
")",
":",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"self",
".",
"stack",
")",
",",
"0",
",",
"-",
"1",
")",
":",
"classinfo",
"=",
"self",
".",
"stack",
"[",
"i",
"-",
"1",
"]",
"if",
"isinstance",
"(",
... | 29.090909 | 0.009091 |
def create_file_vdev(size, *vdevs):
'''
Creates file based virtual devices for a zpool
CLI Example:
.. code-block:: bash
salt '*' zpool.create_file_vdev 7G /path/to/vdev1 [/path/to/vdev2] [...]
.. note::
Depending on file size, the above command may take a while to return.
... | [
"def",
"create_file_vdev",
"(",
"size",
",",
"*",
"vdevs",
")",
":",
"ret",
"=",
"OrderedDict",
"(",
")",
"err",
"=",
"OrderedDict",
"(",
")",
"_mkfile_cmd",
"=",
"salt",
".",
"utils",
".",
"path",
".",
"which",
"(",
"'mkfile'",
")",
"for",
"vdev",
"... | 26.268293 | 0.001791 |
def upload(self, name: str) -> bool:
"""
Attempts to upload a given Docker image from this server to DockerHub.
Parameters:
name: the name of the Docker image.
Returns:
`True` if successfully uploaded, otherwise `False`.
"""
try:
out ... | [
"def",
"upload",
"(",
"self",
",",
"name",
":",
"str",
")",
"->",
"bool",
":",
"try",
":",
"out",
"=",
"self",
".",
"__docker",
".",
"images",
".",
"push",
"(",
"name",
",",
"stream",
"=",
"True",
")",
"for",
"line",
"in",
"out",
":",
"line",
"... | 37.08 | 0.002103 |
def count_time(function):
"""
Function: count_time
Summary: get the time to finish a function
print at the end that time to stdout
Examples: <NONE>
Attributes:
@param (function): function
Returns: wrapped function
"""
@wraps(function)
def _wrapper(*args, **kwargs... | [
"def",
"count_time",
"(",
"function",
")",
":",
"@",
"wraps",
"(",
"function",
")",
"def",
"_wrapper",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"before",
"=",
"time",
"(",
")",
"result",
"=",
"function",
"(",
"*",
"args",
",",
"*",
"*... | 27.681818 | 0.001587 |
def handle_GET_ttablegraph(self,params):
"""Draw a Marey graph in SVG for a pattern (collection of trips in a route
that visit the same sequence of stops)."""
schedule = self.server.schedule
marey = MareyGraph()
trip = schedule.GetTrip(params.get('trip', None))
route = schedule.GetRoute(trip.rou... | [
"def",
"handle_GET_ttablegraph",
"(",
"self",
",",
"params",
")",
":",
"schedule",
"=",
"self",
".",
"server",
".",
"schedule",
"marey",
"=",
"MareyGraph",
"(",
")",
"trip",
"=",
"schedule",
".",
"GetTrip",
"(",
"params",
".",
"get",
"(",
"'trip'",
",",
... | 34.342857 | 0.008091 |
def get_error(self):
"""
Get an error string from the device
"""
err_str = hidapi.hid_error(self._device)
if err_str == ffi.NULL:
return None
else:
return ffi.string(err_str) | [
"def",
"get_error",
"(",
"self",
")",
":",
"err_str",
"=",
"hidapi",
".",
"hid_error",
"(",
"self",
".",
"_device",
")",
"if",
"err_str",
"==",
"ffi",
".",
"NULL",
":",
"return",
"None",
"else",
":",
"return",
"ffi",
".",
"string",
"(",
"err_str",
")... | 26.444444 | 0.00813 |
def grouped_mean(arr, spike_clusters):
"""Compute the mean of a spike-dependent quantity for every cluster.
The two arguments should be 1D array with `n_spikes` elements.
The output is a 1D array with `n_clusters` elements. The clusters are
sorted in increasing order.
"""
arr = np.asarray(arr... | [
"def",
"grouped_mean",
"(",
"arr",
",",
"spike_clusters",
")",
":",
"arr",
"=",
"np",
".",
"asarray",
"(",
"arr",
")",
"spike_clusters",
"=",
"np",
".",
"asarray",
"(",
"spike_clusters",
")",
"assert",
"arr",
".",
"ndim",
"==",
"1",
"assert",
"arr",
".... | 37.190476 | 0.001248 |
def _findOverlap(self, img_rgb, overlap, overlapDeviation,
rotation, rotationDeviation):
'''
return offset(x,y) which fit best self._base_img
through template matching
'''
# get gray images
if len(img_rgb.shape) != len(img_rgb.shape):
... | [
"def",
"_findOverlap",
"(",
"self",
",",
"img_rgb",
",",
"overlap",
",",
"overlapDeviation",
",",
"rotation",
",",
"rotationDeviation",
")",
":",
"# get gray images\r",
"if",
"len",
"(",
"img_rgb",
".",
"shape",
")",
"!=",
"len",
"(",
"img_rgb",
".",
"shape"... | 37.738095 | 0.001845 |
def user_organizations(self, user_id, **kwargs):
"https://developer.zendesk.com/rest_api/docs/core/organizations#list-organizations"
api_path = "/api/v2/users/{user_id}/organizations.json"
api_path = api_path.format(user_id=user_id)
return self.call(api_path, **kwargs) | [
"def",
"user_organizations",
"(",
"self",
",",
"user_id",
",",
"*",
"*",
"kwargs",
")",
":",
"api_path",
"=",
"\"/api/v2/users/{user_id}/organizations.json\"",
"api_path",
"=",
"api_path",
".",
"format",
"(",
"user_id",
"=",
"user_id",
")",
"return",
"self",
"."... | 59.4 | 0.009967 |
def raise_(tp, value=None, tb=None):
"""
A function that matches the Python 2.x ``raise`` statement. This
allows re-raising exceptions with the cls value and traceback on
Python 2 and 3.
"""
if value is not None and isinstance(tp, Exception):
raise TypeError("instance exception may not h... | [
"def",
"raise_",
"(",
"tp",
",",
"value",
"=",
"None",
",",
"tb",
"=",
"None",
")",
":",
"if",
"value",
"is",
"not",
"None",
"and",
"isinstance",
"(",
"tp",
",",
"Exception",
")",
":",
"raise",
"TypeError",
"(",
"\"instance exception may not have a separat... | 32.8 | 0.001976 |
def create_atari_environment(name):
"""
Create OpenAI Gym atari environment
:param name: name of the atari game
:return: Preconfigured environment suitable for atari games
"""
env = gym.make(name)
env = NoopResetEnv(env, noop_max=30)
env = EpisodicLifeEnv(env)
env = ClipRewardEnv(env)
action_names... | [
"def",
"create_atari_environment",
"(",
"name",
")",
":",
"env",
"=",
"gym",
".",
"make",
"(",
"name",
")",
"env",
"=",
"NoopResetEnv",
"(",
"env",
",",
"noop_max",
"=",
"30",
")",
"env",
"=",
"EpisodicLifeEnv",
"(",
"env",
")",
"env",
"=",
"ClipReward... | 25.777778 | 0.022869 |
def startup_capabilities(cls, rcfile=False, norc=False, stdin=False,
command=False):
"""
Given a set of options related to shell startup, return the actual
options that will be applied.
@returns 4-tuple representing applied value of each option.
"""
... | [
"def",
"startup_capabilities",
"(",
"cls",
",",
"rcfile",
"=",
"False",
",",
"norc",
"=",
"False",
",",
"stdin",
"=",
"False",
",",
"command",
"=",
"False",
")",
":",
"raise",
"NotImplementedError"
] | 43.125 | 0.008523 |
def add_element(self, element):
"""
Add an element to this ComplexType and also append it to element dict
of parent type graph.
"""
self.elements.append(element)
self.type_graph.add_element(element) | [
"def",
"add_element",
"(",
"self",
",",
"element",
")",
":",
"self",
".",
"elements",
".",
"append",
"(",
"element",
")",
"self",
".",
"type_graph",
".",
"add_element",
"(",
"element",
")"
] | 34.285714 | 0.00813 |
def to_identifier(s):
"""
Convert snake_case to camel_case.
"""
if s.startswith('GPS'):
s = 'Gps' + s[3:]
return ''.join([i.capitalize() for i in s.split('_')]) if '_' in s else s | [
"def",
"to_identifier",
"(",
"s",
")",
":",
"if",
"s",
".",
"startswith",
"(",
"'GPS'",
")",
":",
"s",
"=",
"'Gps'",
"+",
"s",
"[",
"3",
":",
"]",
"return",
"''",
".",
"join",
"(",
"[",
"i",
".",
"capitalize",
"(",
")",
"for",
"i",
"in",
"s",... | 27 | 0.025641 |
def fit_radius_from_potentials(z, SampleFreq, Damping, HistBins=100, show_fig=False):
"""
Fits the dynamical potential to the Steady
State Potential by varying the Radius.
z : ndarray
Position data
SampleFreq : float
frequency at which the position data was
sampled
... | [
"def",
"fit_radius_from_potentials",
"(",
"z",
",",
"SampleFreq",
",",
"Damping",
",",
"HistBins",
"=",
"100",
",",
"show_fig",
"=",
"False",
")",
":",
"dt",
"=",
"1",
"/",
"SampleFreq",
"boltzmann",
"=",
"Boltzmann",
"temp",
"=",
"300",
"# why halved??",
... | 33.15873 | 0.010228 |
def dex_ticker(self):
''' Simply grabs the ticker using the
steem_instance method and adds it
to a class variable.
'''
self.dex = Dex(self.steem_instance())
self.ticker = self.dex.get_ticker();
return self.ticker | [
"def",
"dex_ticker",
"(",
"self",
")",
":",
"self",
".",
"dex",
"=",
"Dex",
"(",
"self",
".",
"steem_instance",
"(",
")",
")",
"self",
".",
"ticker",
"=",
"self",
".",
"dex",
".",
"get_ticker",
"(",
")",
"return",
"self",
".",
"ticker"
] | 32.75 | 0.01487 |
def dBinaryRochedx (r, D, q, F):
"""
Computes a derivative of the potential with respect to x.
@param r: relative radius vector (3 components)
@param D: instantaneous separation
@param q: mass ratio
@param F: synchronicity parameter
"""
return -r[0]*(r[0]*r[0]+r[1]*r... | [
"def",
"dBinaryRochedx",
"(",
"r",
",",
"D",
",",
"q",
",",
"F",
")",
":",
"return",
"-",
"r",
"[",
"0",
"]",
"*",
"(",
"r",
"[",
"0",
"]",
"*",
"r",
"[",
"0",
"]",
"+",
"r",
"[",
"1",
"]",
"*",
"r",
"[",
"1",
"]",
"+",
"r",
"[",
"2... | 41.3 | 0.011848 |
def imrotate(img,
angle,
center=None,
scale=1.0,
border_value=0,
auto_bound=False):
"""Rotate an image.
Args:
img (ndarray): Image to be rotated.
angle (float): Rotation angle in degrees, positive values mean
clockwise... | [
"def",
"imrotate",
"(",
"img",
",",
"angle",
",",
"center",
"=",
"None",
",",
"scale",
"=",
"1.0",
",",
"border_value",
"=",
"0",
",",
"auto_bound",
"=",
"False",
")",
":",
"if",
"center",
"is",
"not",
"None",
"and",
"auto_bound",
":",
"raise",
"Valu... | 33.365854 | 0.00071 |
def complexes(network, state):
"""Return all irreducible complexes of the network.
Args:
network (Network): The |Network| of interest.
state (tuple[int]): The state of the network (a binary tuple).
Yields:
SystemIrreducibilityAnalysis: A |SIA| for each |Subsystem| of the
|N... | [
"def",
"complexes",
"(",
"network",
",",
"state",
")",
":",
"engine",
"=",
"FindIrreducibleComplexes",
"(",
"possible_complexes",
"(",
"network",
",",
"state",
")",
")",
"return",
"engine",
".",
"run",
"(",
"config",
".",
"PARALLEL_COMPLEX_EVALUATION",
")"
] | 37.846154 | 0.001984 |
def get_undecorated_calling_module():
"""Returns the module name of the caller's calling module.
If a.py makes a call to b() in b.py, b() can get the name of the
calling module (i.e. a) by calling get_undecorated_calling_module().
The module also includes its full path.
As the name suggests, this ... | [
"def",
"get_undecorated_calling_module",
"(",
")",
":",
"frame",
"=",
"inspect",
".",
"stack",
"(",
")",
"[",
"2",
"]",
"module",
"=",
"inspect",
".",
"getmodule",
"(",
"frame",
"[",
"0",
"]",
")",
"# Return the module's file and its path",
"# and omit the exten... | 38.333333 | 0.001698 |
def create_lease_object_from_subnet(self, subnet):
"""
Create a lease from ip in a dotted decimal format,
(for example `192.168.200.0/24`). the _cidr will be added if not exist
in `subnet`.
Args:
subnet (str): The value of the third octet
Returns:
... | [
"def",
"create_lease_object_from_subnet",
"(",
"self",
",",
"subnet",
")",
":",
"if",
"'/'",
"not",
"in",
"subnet",
":",
"subnet",
"=",
"'{}/{}'",
".",
"format",
"(",
"subnet",
",",
"self",
".",
"_cidr",
")",
"try",
":",
"if",
"not",
"self",
".",
"is_l... | 33.892857 | 0.002049 |
def get_args(self, state, all_params, remainder, argspec, im_self):
'''
Determines the arguments for a controller based upon parameters
passed the argument specification for the controller.
'''
args = []
varargs = []
kwargs = dict()
valid_args = argspec.ar... | [
"def",
"get_args",
"(",
"self",
",",
"state",
",",
"all_params",
",",
"remainder",
",",
"argspec",
",",
"im_self",
")",
":",
"args",
"=",
"[",
"]",
"varargs",
"=",
"[",
"]",
"kwargs",
"=",
"dict",
"(",
")",
"valid_args",
"=",
"argspec",
".",
"args",
... | 32.684211 | 0.001042 |
def indent_iterable(elems: Sequence[str], num: int = 2) -> List[str]:
"""Indent an iterable."""
return [" " * num + l for l in elems] | [
"def",
"indent_iterable",
"(",
"elems",
":",
"Sequence",
"[",
"str",
"]",
",",
"num",
":",
"int",
"=",
"2",
")",
"->",
"List",
"[",
"str",
"]",
":",
"return",
"[",
"\" \"",
"*",
"num",
"+",
"l",
"for",
"l",
"in",
"elems",
"]"
] | 46.333333 | 0.014184 |
def _to_rfc822(date):
"""_to_rfc822(datetime.datetime) -> str
The datetime `strftime` method is subject to locale-specific
day and month names, so this function hardcodes the conversion."""
months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun',
'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
da... | [
"def",
"_to_rfc822",
"(",
"date",
")",
":",
"months",
"=",
"[",
"'Jan'",
",",
"'Feb'",
",",
"'Mar'",
",",
"'Apr'",
",",
"'May'",
",",
"'Jun'",
",",
"'Jul'",
",",
"'Aug'",
",",
"'Sep'",
",",
"'Oct'",
",",
"'Nov'",
",",
"'Dec'",
"]",
"days",
"=",
"... | 37.235294 | 0.001541 |
def _sanitize_url_components(comp_list, field):
'''
Recursive function to sanitize each component of the url.
'''
if not comp_list:
return ''
elif comp_list[0].startswith('{0}='.format(field)):
ret = '{0}=XXXXXXXXXX&'.format(field)
comp_list.remove(comp_list[0])
retur... | [
"def",
"_sanitize_url_components",
"(",
"comp_list",
",",
"field",
")",
":",
"if",
"not",
"comp_list",
":",
"return",
"''",
"elif",
"comp_list",
"[",
"0",
"]",
".",
"startswith",
"(",
"'{0}='",
".",
"format",
"(",
"field",
")",
")",
":",
"ret",
"=",
"'... | 36.571429 | 0.001905 |
def leastsq_NxN(x, y, fit_offset=False, perc=None):
"""Solution to least squares: gamma = cov(X,Y) / var(X)
"""
if perc is not None:
if not fit_offset and isinstance(perc, (list, tuple)): perc = perc[1]
weights = csr_matrix(get_weight(x, y, perc)).astype(bool)
x, y = weights.multiply... | [
"def",
"leastsq_NxN",
"(",
"x",
",",
"y",
",",
"fit_offset",
"=",
"False",
",",
"perc",
"=",
"None",
")",
":",
"if",
"perc",
"is",
"not",
"None",
":",
"if",
"not",
"fit_offset",
"and",
"isinstance",
"(",
"perc",
",",
"(",
"list",
",",
"tuple",
")",... | 35.774194 | 0.001756 |
def getFileSystemSize(dirPath):
"""
Return the free space, and total size of the file system hosting `dirPath`.
:param str dirPath: A valid path to a directory.
:return: free space and total size of file system
:rtype: tuple
"""
assert os.path.exists(dirPath)
diskStats = os.statvfs(dirP... | [
"def",
"getFileSystemSize",
"(",
"dirPath",
")",
":",
"assert",
"os",
".",
"path",
".",
"exists",
"(",
"dirPath",
")",
"diskStats",
"=",
"os",
".",
"statvfs",
"(",
"dirPath",
")",
"freeSpace",
"=",
"diskStats",
".",
"f_frsize",
"*",
"diskStats",
".",
"f_... | 34.923077 | 0.002146 |
def extractContent(self, text):
"""Extract the content of comment text.
"""
m = self.nextValidComment(text)
return '' if m is None else m.group(1) | [
"def",
"extractContent",
"(",
"self",
",",
"text",
")",
":",
"m",
"=",
"self",
".",
"nextValidComment",
"(",
"text",
")",
"return",
"''",
"if",
"m",
"is",
"None",
"else",
"m",
".",
"group",
"(",
"1",
")"
] | 24.857143 | 0.011111 |
def purge_archived_resources(user, table):
"""Remove the entries to be purged from the database. """
if user.is_not_super_admin():
raise dci_exc.Unauthorized()
where_clause = sql.and_(
table.c.state == 'archived'
)
query = table.delete().where(where_clause)
flask.g.db_conn.exec... | [
"def",
"purge_archived_resources",
"(",
"user",
",",
"table",
")",
":",
"if",
"user",
".",
"is_not_super_admin",
"(",
")",
":",
"raise",
"dci_exc",
".",
"Unauthorized",
"(",
")",
"where_clause",
"=",
"sql",
".",
"and_",
"(",
"table",
".",
"c",
".",
"stat... | 29.923077 | 0.002494 |
def find_ip6_by_id(self, id_ip):
"""
Get an IP6 by ID
:param id_ip: IP6 identifier. Integer value and greater than zero.
:return: Dictionary with the following structure:
::
{'ip': {'id': < id >,
'block1': <block1>,
'block2': <block2>,
... | [
"def",
"find_ip6_by_id",
"(",
"self",
",",
"id_ip",
")",
":",
"if",
"not",
"is_valid_int_param",
"(",
"id_ip",
")",
":",
"raise",
"InvalidParameterError",
"(",
"u'Ipv6 identifier is invalid or was not informed.'",
")",
"url",
"=",
"'ipv6/get/'",
"+",
"str",
"(",
"... | 32.243902 | 0.002203 |
def admin_dropdown_menu(context):
"""
Renders the app list for the admin dropdown menu navigation.
"""
template_vars = context.flatten()
user = context["request"].user
if user.is_staff:
template_vars["dropdown_menu_app_list"] = admin_app_list(
context["request"])
if u... | [
"def",
"admin_dropdown_menu",
"(",
"context",
")",
":",
"template_vars",
"=",
"context",
".",
"flatten",
"(",
")",
"user",
"=",
"context",
"[",
"\"request\"",
"]",
".",
"user",
"if",
"user",
".",
"is_staff",
":",
"template_vars",
"[",
"\"dropdown_menu_app_list... | 38.142857 | 0.001218 |
def startup_config_path(self):
"""
:returns: Path of the startup config
"""
return os.path.join(self._working_directory, "configs", "i{}_startup-config.cfg".format(self._dynamips_id)) | [
"def",
"startup_config_path",
"(",
"self",
")",
":",
"return",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"_working_directory",
",",
"\"configs\"",
",",
"\"i{}_startup-config.cfg\"",
".",
"format",
"(",
"self",
".",
"_dynamips_id",
")",
")"
] | 42.2 | 0.013953 |
def Validate(self, problems, validate_children=True):
"""Validate attributes of this object.
Check that this object has all required values set to a valid value without
reference to the rest of the schedule. If the _schedule attribute is set
then check that references such as route_id and service_id ar... | [
"def",
"Validate",
"(",
"self",
",",
"problems",
",",
"validate_children",
"=",
"True",
")",
":",
"self",
".",
"ValidateRouteId",
"(",
"problems",
")",
"self",
".",
"ValidateServicePeriod",
"(",
"problems",
")",
"self",
".",
"ValidateDirectionId",
"(",
"proble... | 42.086957 | 0.00202 |
def project_layout(proposal, user=None, repo=None, log=None):
"""
generate the project template
proposal is the name of the project,
user is an object containing some information about the user.
- full name,
- github username
- email
"""
proposal = proposal.lower(... | [
"def",
"project_layout",
"(",
"proposal",
",",
"user",
"=",
"None",
",",
"repo",
"=",
"None",
",",
"log",
"=",
"None",
")",
":",
"proposal",
"=",
"proposal",
".",
"lower",
"(",
")",
"#context_file = os.path.expanduser('~/.cookiecutters/cookiecutter-pypackage/cookiec... | 23.015152 | 0.00947 |
def humanize_bandwidth(bits):
'''
Accept some number of bits/sec (i.e., a link capacity) as an
integer, and return a string representing a 'human'(-like)
representation of the capacity, e.g., 10 Mb/s, 1.5 Mb/s,
900 Gb/s.
As is the standard in networking, capacity values are assumed
to be ba... | [
"def",
"humanize_bandwidth",
"(",
"bits",
")",
":",
"unit",
"=",
"''",
"divisor",
"=",
"1",
"if",
"bits",
"<",
"1000",
":",
"unit",
"=",
"'bits'",
"divisor",
"=",
"1",
"elif",
"bits",
"<",
"1000000",
":",
"unit",
"=",
"'Kb'",
"divisor",
"=",
"1000",
... | 26.388889 | 0.001015 |
def predict(self, h=5, intervals=False):
""" Makes forecast with the estimated model
Parameters
----------
h : int (default : 5)
How many steps ahead would you like to forecast?
intervals : boolean (default: False)
Whether to return prediction intervals
... | [
"def",
"predict",
"(",
"self",
",",
"h",
"=",
"5",
",",
"intervals",
"=",
"False",
")",
":",
"if",
"self",
".",
"latent_variables",
".",
"estimated",
"is",
"False",
":",
"raise",
"Exception",
"(",
"\"No latent variables estimated!\"",
")",
"else",
":",
"lm... | 44.681818 | 0.010617 |
def _heighten(self, resource):
"""
Change image size by height
:param resource: Image
:return: Image
"""
original_width, original_height = resource.size
target_height = self.value
target_width = int((float(target_height) / original_height) * original_widt... | [
"def",
"_heighten",
"(",
"self",
",",
"resource",
")",
":",
"original_width",
",",
"original_height",
"=",
"resource",
".",
"size",
"target_height",
"=",
"self",
".",
"value",
"target_width",
"=",
"int",
"(",
"(",
"float",
"(",
"target_height",
")",
"/",
"... | 29.857143 | 0.009281 |
def x(self, x):
"""Project x as y"""
if x is None:
return None
if self._force_vertical:
return super(HorizontalView, self).x(x)
return super(HorizontalView, self).y(x) | [
"def",
"x",
"(",
"self",
",",
"x",
")",
":",
"if",
"x",
"is",
"None",
":",
"return",
"None",
"if",
"self",
".",
"_force_vertical",
":",
"return",
"super",
"(",
"HorizontalView",
",",
"self",
")",
".",
"x",
"(",
"x",
")",
"return",
"super",
"(",
"... | 31 | 0.008969 |
def _shuffle_tfrecord(path, random_gen):
"""Shuffle a single record file in memory."""
# Read all records
record_iter = tf.compat.v1.io.tf_record_iterator(path)
all_records = [
r for r in utils.tqdm(
record_iter, desc="Reading...", unit=" examples", leave=False)
]
# Shuffling in memory
ran... | [
"def",
"_shuffle_tfrecord",
"(",
"path",
",",
"random_gen",
")",
":",
"# Read all records",
"record_iter",
"=",
"tf",
".",
"compat",
".",
"v1",
".",
"io",
".",
"tf_record_iterator",
"(",
"path",
")",
"all_records",
"=",
"[",
"r",
"for",
"r",
"in",
"utils",... | 35.6 | 0.020073 |
def add_codewords(matrix, codewords, version):
"""\
Adds the codewords (data and error correction) to the provided matrix.
ISO/IEC 18004:2015(E) -- 7.7.3 Symbol character placement (page 46)
:param matrix: The matrix to add the codewords into.
:param codewords: Sequence of ints
"""
matrix_... | [
"def",
"add_codewords",
"(",
"matrix",
",",
"codewords",
",",
"version",
")",
":",
"matrix_size",
"=",
"len",
"(",
"matrix",
")",
"is_micro",
"=",
"version",
"<",
"1",
"# Necessary for M1 and M3: The algorithm would start at the upper right",
"# corner, see <https://githu... | 46.621622 | 0.001704 |
def include_(parser, token):
"""Similar to built-in ``include`` template tag, but allowing
template variables to be used in template name and a fallback template,
thus making the tag more dynamic.
.. warning:: Requires Django 1.8+
Example:
{% load etc_misc %}
{% include_ "sub_{{ p... | [
"def",
"include_",
"(",
"parser",
",",
"token",
")",
":",
"bits",
"=",
"token",
".",
"split_contents",
"(",
")",
"dynamic",
"=",
"False",
"# We fallback to built-in `include` if a template name contains no variables.",
"if",
"len",
"(",
"bits",
")",
">=",
"2",
":"... | 27.232143 | 0.001899 |
def format_cmdline(args, maxwidth=80):
'''Format args into a shell-quoted command line.
The result will be wrapped to maxwidth characters where possible,
not breaking a single long argument.
'''
# Leave room for the space and backslash at the end of each line
maxwidth -= 2
def lines():
... | [
"def",
"format_cmdline",
"(",
"args",
",",
"maxwidth",
"=",
"80",
")",
":",
"# Leave room for the space and backslash at the end of each line",
"maxwidth",
"-=",
"2",
"def",
"lines",
"(",
")",
":",
"line",
"=",
"''",
"for",
"a",
"in",
"(",
"shell_quote",
"(",
... | 29.655172 | 0.001126 |
def compute_eigenvalues(in_prefix, out_prefix):
"""Computes the Eigenvalues using smartpca from Eigensoft.
:param in_prefix: the prefix of the input files.
:param out_prefix: the prefix of the output files.
:type in_prefix: str
:type out_prefix: str
Creates a "parameter file" used by smartpca... | [
"def",
"compute_eigenvalues",
"(",
"in_prefix",
",",
"out_prefix",
")",
":",
"# First, we create the parameter file",
"with",
"open",
"(",
"out_prefix",
"+",
"\".parameters\"",
",",
"\"w\"",
")",
"as",
"o_file",
":",
"print",
">>",
"o_file",
",",
"\"genotypename: ... | 38.28 | 0.001019 |
def decode_msg(raw_msg):
"""
Decodes jsonrpc 2.0 raw message objects into JsonRpcMsg objects.
Examples:
Request:
{
"jsonrpc": "2.0",
"id": 1,
"method": "subtract",
"params": [42, 23]
}
Notification:
... | [
"def",
"decode_msg",
"(",
"raw_msg",
")",
":",
"try",
":",
"msg_data",
"=",
"json",
".",
"loads",
"(",
"raw_msg",
")",
"except",
"ValueError",
":",
"raise",
"RpcParseError",
"# check jsonrpc version",
"if",
"'jsonrpc'",
"not",
"in",
"msg_data",
"or",
"not",
... | 28.275229 | 0.000313 |
def trap_ctrl_c_ctrl_break() -> None:
"""
Prevent ``CTRL-C``, ``CTRL-BREAK``, and similar signals from doing
anything.
See
- https://docs.python.org/3/library/signal.html#signal.SIG_IGN
- https://msdn.microsoft.com/en-us/library/xdkz3x12.aspx
- https://msdn.microsoft.com/en-us/libr... | [
"def",
"trap_ctrl_c_ctrl_break",
"(",
")",
"->",
"None",
":",
"# noqa",
"signal",
".",
"signal",
"(",
"signal",
".",
"SIGINT",
",",
"ctrl_c_trapper",
")",
"signal",
".",
"signal",
"(",
"signal",
".",
"SIGTERM",
",",
"sigterm_trapper",
")",
"if",
"platform",
... | 36.583333 | 0.000555 |
def _format_table(fmt, headers, rows, colwidths, colaligns):
"""Produce a plain-text representation of the table."""
lines = []
hidden = fmt.with_header_hide if headers else fmt.without_header_hide
pad = fmt.padding
headerrow = fmt.headerrow if fmt.headerrow else fmt.datarow
if fmt.lineabove an... | [
"def",
"_format_table",
"(",
"fmt",
",",
"headers",
",",
"rows",
",",
"colwidths",
",",
"colaligns",
")",
":",
"lines",
"=",
"[",
"]",
"hidden",
"=",
"fmt",
".",
"with_header_hide",
"if",
"headers",
"else",
"fmt",
".",
"without_header_hide",
"pad",
"=",
... | 40.421053 | 0.000636 |
def findAllBycolumn(self, target):
""" Returns an array of columns in the region (defined by the raster), each
column containing all matches in that column for the target pattern. """
column_matches = []
for column_index in range(self._raster[1]):
column = self.getRow(column_... | [
"def",
"findAllBycolumn",
"(",
"self",
",",
"target",
")",
":",
"column_matches",
"=",
"[",
"]",
"for",
"column_index",
"in",
"range",
"(",
"self",
".",
"_raster",
"[",
"1",
"]",
")",
":",
"column",
"=",
"self",
".",
"getRow",
"(",
"column_index",
")",... | 51.875 | 0.009479 |
def fromMessage(klass, message, op_endpoint):
"""Construct me from an OpenID message.
@raises ProtocolError: When not all required parameters are present
in the message.
@raises MalformedReturnURL: When the C{return_to} URL is not a URL.
@raises UntrustedReturnURL: When th... | [
"def",
"fromMessage",
"(",
"klass",
",",
"message",
",",
"op_endpoint",
")",
":",
"self",
"=",
"klass",
".",
"__new__",
"(",
"klass",
")",
"self",
".",
"message",
"=",
"message",
"self",
".",
"op_endpoint",
"=",
"op_endpoint",
"mode",
"=",
"message",
"."... | 41.903226 | 0.000752 |
def create_file(self, share_name, directory_name, file_name,
content_length, content_settings=None, metadata=None,
timeout=None):
'''
Creates a new file.
See create_file_from_* for high level functions that handle the
creation and upload of large ... | [
"def",
"create_file",
"(",
"self",
",",
"share_name",
",",
"directory_name",
",",
"file_name",
",",
"content_length",
",",
"content_settings",
"=",
"None",
",",
"metadata",
"=",
"None",
",",
"timeout",
"=",
"None",
")",
":",
"_validate_not_none",
"(",
"'share_... | 40.744186 | 0.00223 |
def beacon(config):
'''
Watch the configured files
Example Config
.. code-block:: yaml
beacons:
inotify:
- files:
/path/to/file/or/dir:
mask:
- open
- create
- close_write
... | [
"def",
"beacon",
"(",
"config",
")",
":",
"_config",
"=",
"{",
"}",
"list",
"(",
"map",
"(",
"_config",
".",
"update",
",",
"config",
")",
")",
"ret",
"=",
"[",
"]",
"notifier",
"=",
"_get_notifier",
"(",
"_config",
")",
"wm",
"=",
"notifier",
".",... | 36.836257 | 0.001082 |
def configure_rmq_ssl_on(self, sentry_units, deployment,
port=None, max_wait=60):
"""Turn ssl charm config option on, with optional non-default
ssl port specification. Confirm that it is enabled on every
unit.
:param sentry_units: list of sentry units
... | [
"def",
"configure_rmq_ssl_on",
"(",
"self",
",",
"sentry_units",
",",
"deployment",
",",
"port",
"=",
"None",
",",
"max_wait",
"=",
"60",
")",
":",
"self",
".",
"log",
".",
"debug",
"(",
"'Setting ssl charm config option: on'",
")",
"# Enable RMQ SSL",
"config"... | 35.914286 | 0.002324 |
def validate_instance_dbname(self, dbname):
''' Validate instance database name '''
# 1-64 alphanumeric characters, cannot be a reserved MySQL word
if re.match('[\w-]+$', dbname) is not None:
if len(dbname) <= 41 and len(dbname) >= 1:
if dbname.lower() not in MYSQL_RE... | [
"def",
"validate_instance_dbname",
"(",
"self",
",",
"dbname",
")",
":",
"# 1-64 alphanumeric characters, cannot be a reserved MySQL word",
"if",
"re",
".",
"match",
"(",
"'[\\w-]+$'",
",",
"dbname",
")",
"is",
"not",
"None",
":",
"if",
"len",
"(",
"dbname",
")",
... | 53.777778 | 0.010163 |
def open(self):
""" Search device on USB tree and set is as escpos device """
self.device = usb.core.find(idVendor=self.idVendor, idProduct=self.idProduct)
if self.device is None:
raise NoDeviceError()
try:
if self.device.is_kernel_driver_active(self.inte... | [
"def",
"open",
"(",
"self",
")",
":",
"self",
".",
"device",
"=",
"usb",
".",
"core",
".",
"find",
"(",
"idVendor",
"=",
"self",
".",
"idVendor",
",",
"idProduct",
"=",
"self",
".",
"idProduct",
")",
"if",
"self",
".",
"device",
"is",
"None",
":",
... | 43.769231 | 0.008606 |
def resize_image(fullfile,fullfile_resized,_megapixels):
"""Resizes image (fullfile), saves to fullfile_resized. Image
aspect ratio is conserved, will be scaled to be close to _megapixels in
size. Eg if _megapixels=2, will resize 2560x1920 so each dimension
is scaled by ((2**(20+1*MP))/float(2560*1920)... | [
"def",
"resize_image",
"(",
"fullfile",
",",
"fullfile_resized",
",",
"_megapixels",
")",
":",
"logger",
".",
"debug",
"(",
"\"%s - Resizing to %s MP\"",
"%",
"(",
"fullfile",
",",
"_megapixels",
")",
")",
"img",
"=",
"Image",
".",
"open",
"(",
"fullfile",
"... | 36.657143 | 0.024298 |
def sqlite_by_df(self, destination, progress):
"""Is this fast?"""
db = SQLiteDatabase(destination)
db.create()
for table in progress(self.real_tables): self[table].to_sql(table, con=db.connection)
db.close() | [
"def",
"sqlite_by_df",
"(",
"self",
",",
"destination",
",",
"progress",
")",
":",
"db",
"=",
"SQLiteDatabase",
"(",
"destination",
")",
"db",
".",
"create",
"(",
")",
"for",
"table",
"in",
"progress",
"(",
"self",
".",
"real_tables",
")",
":",
"self",
... | 40.5 | 0.016129 |
def splitEkmDate(dateint):
"""Break out a date from Omnimeter read.
Note a corrupt date will raise an exception when you
convert it to int to hand to this method.
Args:
dateint (int): Omnimeter datetime as int.
Returns:
tuple: Named tuple which breaks ... | [
"def",
"splitEkmDate",
"(",
"dateint",
")",
":",
"date_str",
"=",
"str",
"(",
"dateint",
")",
"dt",
"=",
"namedtuple",
"(",
"'EkmDate'",
",",
"[",
"'yy'",
",",
"'mm'",
",",
"'dd'",
",",
"'weekday'",
",",
"'hh'",
",",
"'minutes'",
",",
"'ss'",
"]",
")... | 31.473684 | 0.002433 |
def human_id(self):
"""Subclasses may override this to provide a pretty ID which can be used
for bash completion.
"""
if self.NAME_ATTR in self.__dict__ and self.HUMAN_ID:
return utils.to_slug(getattr(self, self.NAME_ATTR))
return None | [
"def",
"human_id",
"(",
"self",
")",
":",
"if",
"self",
".",
"NAME_ATTR",
"in",
"self",
".",
"__dict__",
"and",
"self",
".",
"HUMAN_ID",
":",
"return",
"utils",
".",
"to_slug",
"(",
"getattr",
"(",
"self",
",",
"self",
".",
"NAME_ATTR",
")",
")",
"re... | 40.142857 | 0.010453 |
def import_model(self, source):
"""Import and return model instance."""
model = super(NonstrictImporter, self).import_model(source)
sbml.convert_sbml_model(model)
return model | [
"def",
"import_model",
"(",
"self",
",",
"source",
")",
":",
"model",
"=",
"super",
"(",
"NonstrictImporter",
",",
"self",
")",
".",
"import_model",
"(",
"source",
")",
"sbml",
".",
"convert_sbml_model",
"(",
"model",
")",
"return",
"model"
] | 40.6 | 0.009662 |
def cleanup(self):
"""Deletes this worker's subscription."""
if self.subscription:
logger.info("Deleting worker subscription...")
self.subscriber_client.delete_subscription(self.subscription) | [
"def",
"cleanup",
"(",
"self",
")",
":",
"if",
"self",
".",
"subscription",
":",
"logger",
".",
"info",
"(",
"\"Deleting worker subscription...\"",
")",
"self",
".",
"subscriber_client",
".",
"delete_subscription",
"(",
"self",
".",
"subscription",
")"
] | 45.4 | 0.008658 |
def is_reserved(self):
"""Test if the address is otherwise IETF reserved.
Returns:
A boolean, True if the address is within one of the
reserved IPv6 Network ranges.
"""
reserved_nets = [IPv6Network('::/8'), IPv6Network('100::/8'),
IPv6Ne... | [
"def",
"is_reserved",
"(",
"self",
")",
":",
"reserved_nets",
"=",
"[",
"IPv6Network",
"(",
"'::/8'",
")",
",",
"IPv6Network",
"(",
"'100::/8'",
")",
",",
"IPv6Network",
"(",
"'200::/7'",
")",
",",
"IPv6Network",
"(",
"'400::/6'",
")",
",",
"IPv6Network",
... | 45.666667 | 0.002384 |
def calendar_date(jd_integer):
"""Convert Julian Day `jd_integer` into a Gregorian (year, month, day)."""
k = jd_integer + 68569
n = 4 * k // 146097
k = k - (146097 * n + 3) // 4
m = 4000 * (k + 1) // 1461001
k = k - 1461 * m // 4 + 31
month = 80 * k // 2447
day = k - 2447 * month // 8... | [
"def",
"calendar_date",
"(",
"jd_integer",
")",
":",
"k",
"=",
"jd_integer",
"+",
"68569",
"n",
"=",
"4",
"*",
"k",
"//",
"146097",
"k",
"=",
"k",
"-",
"(",
"146097",
"*",
"n",
"+",
"3",
")",
"//",
"4",
"m",
"=",
"4000",
"*",
"(",
"k",
"+",
... | 24.705882 | 0.002294 |
def flat_images(images, grid=None, bfill=1.0, bsz=(1, 1)):
"""
convert batch image to flat image with margin inserted
[B,h,w,c] => [H,W,c]
:param images:
:param grid: patch grid cell size of (Row, Col)
:param bfill: board filling value
:param bsz: int or (int, int) board size
:return: fl... | [
"def",
"flat_images",
"(",
"images",
",",
"grid",
"=",
"None",
",",
"bfill",
"=",
"1.0",
",",
"bsz",
"=",
"(",
"1",
",",
"1",
")",
")",
":",
"if",
"images",
".",
"ndim",
"==",
"4",
"and",
"images",
".",
"shape",
"[",
"-",
"1",
"]",
"==",
"1",... | 32.73913 | 0.001289 |
def blockstack_tx_filter( tx ):
"""
Virtualchain tx filter function:
* only take txs whose OP_RETURN payload starts with 'id'
"""
if not 'nulldata' in tx:
return False
if tx['nulldata'] is None:
return False
payload = binascii.unhexlify( tx['nulldata'] )
if payload.... | [
"def",
"blockstack_tx_filter",
"(",
"tx",
")",
":",
"if",
"not",
"'nulldata'",
"in",
"tx",
":",
"return",
"False",
"if",
"tx",
"[",
"'nulldata'",
"]",
"is",
"None",
":",
"return",
"False",
"payload",
"=",
"binascii",
".",
"unhexlify",
"(",
"tx",
"[",
"... | 23.117647 | 0.017115 |
def read_conf(conf_file, out_format='simple'):
'''
Read in an LXC configuration file. By default returns a simple, unsorted
dict, but can also return a more detailed structure including blank lines
and comments.
out_format:
set to 'simple' if you need the old and unsupported behavior.
... | [
"def",
"read_conf",
"(",
"conf_file",
",",
"out_format",
"=",
"'simple'",
")",
":",
"ret_commented",
"=",
"[",
"]",
"ret_simple",
"=",
"{",
"}",
"with",
"salt",
".",
"utils",
".",
"files",
".",
"fopen",
"(",
"conf_file",
",",
"'r'",
")",
"as",
"fp_",
... | 35.404762 | 0.001309 |
def create(dataset, transformers):
"""
Create a Transformer object to transform data for feature engineering.
Parameters
----------
dataset : SFrame
The dataset to use for training the model.
transformers: Transformer | list[Transformer]
An Transformer or a list of Transformer... | [
"def",
"create",
"(",
"dataset",
",",
"transformers",
")",
":",
"err_msg",
"=",
"\"The parameters 'transformers' must be a valid Transformer object.\"",
"cls",
"=",
"transformers",
".",
"__class__",
"_raise_error_if_not_sframe",
"(",
"dataset",
",",
"\"dataset\"",
")",
"#... | 31.35 | 0.001031 |
def to_jabsorb(value):
"""
Adds information for Jabsorb, if needed.
Converts maps and lists to a jabsorb form.
Keeps tuples as is, to let them be considered as arrays.
:param value: A Python result to send to Jabsorb
:return: The result in a Jabsorb map format (not a JSON object)
"""
#... | [
"def",
"to_jabsorb",
"(",
"value",
")",
":",
"# None ?",
"if",
"value",
"is",
"None",
":",
"return",
"None",
"# Map ?",
"elif",
"isinstance",
"(",
"value",
",",
"dict",
")",
":",
"if",
"JAVA_CLASS",
"in",
"value",
"or",
"JSON_CLASS",
"in",
"value",
":",
... | 30.433333 | 0.000354 |
def unique_bincount(values,
minlength,
return_inverse=True):
"""
For arrays of integers find unique values using bin counting.
Roughly 10x faster for correct input than np.unique
Parameters
--------------
values : (n,) int
Values to find unique memb... | [
"def",
"unique_bincount",
"(",
"values",
",",
"minlength",
",",
"return_inverse",
"=",
"True",
")",
":",
"values",
"=",
"np",
".",
"asanyarray",
"(",
"values",
")",
"if",
"len",
"(",
"values",
".",
"shape",
")",
"!=",
"1",
"or",
"values",
".",
"dtype",... | 30.764706 | 0.000618 |
def xpath(self, expression):
"""
return result for a call to lxml xpath()
output will be a list
"""
self.__expression = expression
self.__namespaces = XPATH_NAMESPACES
return self.__doc.xpath(self.__expression, namespaces=self.__namespaces) | [
"def",
"xpath",
"(",
"self",
",",
"expression",
")",
":",
"self",
".",
"__expression",
"=",
"expression",
"self",
".",
"__namespaces",
"=",
"XPATH_NAMESPACES",
"return",
"self",
".",
"__doc",
".",
"xpath",
"(",
"self",
".",
"__expression",
",",
"namespaces",... | 37.125 | 0.009868 |
def get_anchor(self):
"""Find anchor variable with highest sum of dependence with the rest."""
temp = np.empty([self.n_nodes, 2])
temp[:, 0] = np.arange(self.n_nodes, dtype=int)
temp[:, 1] = np.sum(abs(self.tau_matrix), 1)
anchor = int(temp[0, 0])
return anchor | [
"def",
"get_anchor",
"(",
"self",
")",
":",
"temp",
"=",
"np",
".",
"empty",
"(",
"[",
"self",
".",
"n_nodes",
",",
"2",
"]",
")",
"temp",
"[",
":",
",",
"0",
"]",
"=",
"np",
".",
"arange",
"(",
"self",
".",
"n_nodes",
",",
"dtype",
"=",
"int... | 43.285714 | 0.009709 |
def extra_data(self):
"""Load token data stored in token (ignores expiry date of tokens)."""
if self.token:
return SecretLinkFactory.load_token(self.token, force=True)["data"]
return None | [
"def",
"extra_data",
"(",
"self",
")",
":",
"if",
"self",
".",
"token",
":",
"return",
"SecretLinkFactory",
".",
"load_token",
"(",
"self",
".",
"token",
",",
"force",
"=",
"True",
")",
"[",
"\"data\"",
"]",
"return",
"None"
] | 43.8 | 0.008969 |
def execute(self,
image = None,
command = None,
app = None,
writable = False,
contain = False,
bind = None,
stream = False,
nv = False,
return_result=False):
''' execute: send a command to a container
... | [
"def",
"execute",
"(",
"self",
",",
"image",
"=",
"None",
",",
"command",
"=",
"None",
",",
"app",
"=",
"None",
",",
"writable",
"=",
"False",
",",
"contain",
"=",
"False",
",",
"bind",
"=",
"None",
",",
"stream",
"=",
"False",
",",
"nv",
"=",
"F... | 31.320513 | 0.009127 |
def main(argv=None):
"""script main.
parses command line options in sys.argv, unless *argv* is given.
"""
if argv is None:
argv = sys.argv
# setup command line parser
parser = U.OptionParser(version="%prog version: $Id$",
usage=usage,
... | [
"def",
"main",
"(",
"argv",
"=",
"None",
")",
":",
"if",
"argv",
"is",
"None",
":",
"argv",
"=",
"sys",
".",
"argv",
"# setup command line parser",
"parser",
"=",
"U",
".",
"OptionParser",
"(",
"version",
"=",
"\"%prog version: $Id$\"",
",",
"usage",
"=",
... | 39.492063 | 0.000784 |
def grep(path,
pattern,
*opts):
'''
Grep for a string in the specified file
.. note::
This function's return value is slated for refinement in future
versions of Salt
path
Path to the file to be searched
.. note::
Globbing is supported (i.... | [
"def",
"grep",
"(",
"path",
",",
"pattern",
",",
"*",
"opts",
")",
":",
"path",
"=",
"os",
".",
"path",
".",
"expanduser",
"(",
"path",
")",
"# Backup the path in case the glob returns nothing",
"_path",
"=",
"path",
"path",
"=",
"glob",
".",
"glob",
"(",
... | 30.573333 | 0.001267 |
def infer_dtype_from_scalar(val, pandas_dtype=False):
"""
interpret the dtype from a scalar
Parameters
----------
pandas_dtype : bool, default False
whether to infer dtype including pandas extension types.
If False, scalar belongs to pandas extension types is inferred as
obj... | [
"def",
"infer_dtype_from_scalar",
"(",
"val",
",",
"pandas_dtype",
"=",
"False",
")",
":",
"dtype",
"=",
"np",
".",
"object_",
"# a 1-element ndarray",
"if",
"isinstance",
"(",
"val",
",",
"np",
".",
"ndarray",
")",
":",
"msg",
"=",
"\"invalid ndarray passed t... | 26.972603 | 0.00049 |
def get_kibiter_version(url):
"""
Return kibiter major number version
The url must point to the Elasticsearch used by Kibiter
"""
config_url = '.kibana/config/_search'
# Avoid having // in the URL because ES will fail
if url[-1] != '/':
url += "/"
url += config_url
... | [
"def",
"get_kibiter_version",
"(",
"url",
")",
":",
"config_url",
"=",
"'.kibana/config/_search'",
"# Avoid having // in the URL because ES will fail",
"if",
"url",
"[",
"-",
"1",
"]",
"!=",
"'/'",
":",
"url",
"+=",
"\"/\"",
"url",
"+=",
"config_url",
"r",
"=",
... | 26.304348 | 0.001595 |
def xcoord(self):
"""The x coordinate :class:`xarray.Variable`"""
v = next(self.raw_data.psy.iter_base_variables)
return self.decoder.get_x(v, coords=self.data.coords) | [
"def",
"xcoord",
"(",
"self",
")",
":",
"v",
"=",
"next",
"(",
"self",
".",
"raw_data",
".",
"psy",
".",
"iter_base_variables",
")",
"return",
"self",
".",
"decoder",
".",
"get_x",
"(",
"v",
",",
"coords",
"=",
"self",
".",
"data",
".",
"coords",
"... | 47 | 0.010471 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.