text stringlengths 89 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 630 |
|---|---|---|---|
def _mark_html_fields_as_safe(self, page):
"""
Mark the html content as safe so we don't have to use the safe
template tag in all cms templates:
"""
page.title = mark_safe(page.title)
page.content = mark_safe(page.content)
return page | [
"def",
"_mark_html_fields_as_safe",
"(",
"self",
",",
"page",
")",
":",
"page",
".",
"title",
"=",
"mark_safe",
"(",
"page",
".",
"title",
")",
"page",
".",
"content",
"=",
"mark_safe",
"(",
"page",
".",
"content",
")",
"return",
"page"
] | 35.375 | 7.875 |
def _consolidate_slices(slices):
"""Consolidate adjacent slices in a list of slices.
"""
result = []
last_slice = slice(None)
for slice_ in slices:
if not isinstance(slice_, slice):
raise ValueError('list element is not a slice: %r' % slice_)
if (result and last_slice.sto... | [
"def",
"_consolidate_slices",
"(",
"slices",
")",
":",
"result",
"=",
"[",
"]",
"last_slice",
"=",
"slice",
"(",
"None",
")",
"for",
"slice_",
"in",
"slices",
":",
"if",
"not",
"isinstance",
"(",
"slice_",
",",
"slice",
")",
":",
"raise",
"ValueError",
... | 37.294118 | 13.764706 |
def fixUTF8(cls, data): # Ensure proper encoding for UA's servers...
""" Convert all strings to UTF-8 """
for key in data:
if isinstance(data[key], str):
data[key] = data[key].encode('utf-8')
return data | [
"def",
"fixUTF8",
"(",
"cls",
",",
"data",
")",
":",
"# Ensure proper encoding for UA's servers...",
"for",
"key",
"in",
"data",
":",
"if",
"isinstance",
"(",
"data",
"[",
"key",
"]",
",",
"str",
")",
":",
"data",
"[",
"key",
"]",
"=",
"data",
"[",
"ke... | 41.833333 | 13.5 |
def _spin(coordinates, theta, around):
"""Rotate a set of coordinates in place around an arbitrary vector.
Parameters
----------
coordinates : np.ndarray, shape=(n,3), dtype=float
The coordinates being spun.
theta : float
The angle by which to spin the coordinates, in radians.
a... | [
"def",
"_spin",
"(",
"coordinates",
",",
"theta",
",",
"around",
")",
":",
"around",
"=",
"np",
".",
"asarray",
"(",
"around",
")",
".",
"reshape",
"(",
"3",
")",
"if",
"np",
".",
"array_equal",
"(",
"around",
",",
"np",
".",
"zeros",
"(",
"3",
"... | 35.095238 | 14.428571 |
def handle_xmlrpc(self, request_text):
"""Handle a single XML-RPC request"""
response = self._marshaled_dispatch(request_text)
print('Content-Type: text/xml')
print('Content-Length: %d' % len(response))
print()
sys.stdout.flush()
sys.stdout.buffer.write(response... | [
"def",
"handle_xmlrpc",
"(",
"self",
",",
"request_text",
")",
":",
"response",
"=",
"self",
".",
"_marshaled_dispatch",
"(",
"request_text",
")",
"print",
"(",
"'Content-Type: text/xml'",
")",
"print",
"(",
"'Content-Length: %d'",
"%",
"len",
"(",
"response",
"... | 31.363636 | 14.363636 |
async def document(
self, file, title=None, *, description=None, type=None,
mime_type=None, attributes=None, force_document=False,
voice_note=False, video_note=False, use_cache=True, id=None,
text=None, parse_mode=(), link_preview=True,
geo=None, period=60, co... | [
"async",
"def",
"document",
"(",
"self",
",",
"file",
",",
"title",
"=",
"None",
",",
"*",
",",
"description",
"=",
"None",
",",
"type",
"=",
"None",
",",
"mime_type",
"=",
"None",
",",
"attributes",
"=",
"None",
",",
"force_document",
"=",
"False",
... | 36.627907 | 19.651163 |
def _init_browser(self):
"""
Ovveride this method with the appropriate way to prepare a logged in
browser.
"""
self.browser = mechanize.Browser()
self.browser.set_handle_robots(False)
self.browser.open(self.server_url + "/youraccount/login")
self.browser.s... | [
"def",
"_init_browser",
"(",
"self",
")",
":",
"self",
".",
"browser",
"=",
"mechanize",
".",
"Browser",
"(",
")",
"self",
".",
"browser",
".",
"set_handle_robots",
"(",
"False",
")",
"self",
".",
"browser",
".",
"open",
"(",
"self",
".",
"server_url",
... | 39.157895 | 13.368421 |
def enforce_timezone(self, value):
"""
When `self.default_timezone` is `None`, always return naive datetimes.
When `self.default_timezone` is not `None`, always return aware datetimes.
"""
field_timezone = getattr(self, 'timezone', self.default_timezone())
if (field_time... | [
"def",
"enforce_timezone",
"(",
"self",
",",
"value",
")",
":",
"field_timezone",
"=",
"getattr",
"(",
"self",
",",
"'timezone'",
",",
"self",
".",
"default_timezone",
"(",
")",
")",
"if",
"(",
"field_timezone",
"is",
"not",
"None",
")",
"and",
"not",
"t... | 47.75 | 23.583333 |
def union(self, *others: 'Substitution') -> 'Substitution':
"""Try to merge the substitutions.
If a variable occurs in multiple substitutions, try to merge the replacements.
See :meth:`union_with_variable` to see how replacements are merged.
Does not modify any of the original substitu... | [
"def",
"union",
"(",
"self",
",",
"*",
"others",
":",
"'Substitution'",
")",
"->",
"'Substitution'",
":",
"new_subst",
"=",
"Substitution",
"(",
"self",
")",
"for",
"other",
"in",
"others",
":",
"for",
"variable_name",
",",
"replacement",
"in",
"other",
".... | 35.3125 | 24.53125 |
def create(buffer_capacity: int, buffer_initial_size: int, frame_stack_compensation: bool = False,
frame_history: int = 1):
""" Vel factory function """
return CircularReplayBufferFactory(
buffer_capacity=buffer_capacity,
buffer_initial_size=buffer_initial_size,
frame_stack_co... | [
"def",
"create",
"(",
"buffer_capacity",
":",
"int",
",",
"buffer_initial_size",
":",
"int",
",",
"frame_stack_compensation",
":",
"bool",
"=",
"False",
",",
"frame_history",
":",
"int",
"=",
"1",
")",
":",
"return",
"CircularReplayBufferFactory",
"(",
"buffer_c... | 43.333333 | 14.444444 |
def cast(self, val: str):
"""converts string to type requested by `cast_as`"""
try:
return getattr(self, 'cast_as_{}'.format(
self.cast_as.__name__.lower()))(val)
except AttributeError:
return self.cast_as(val) | [
"def",
"cast",
"(",
"self",
",",
"val",
":",
"str",
")",
":",
"try",
":",
"return",
"getattr",
"(",
"self",
",",
"'cast_as_{}'",
".",
"format",
"(",
"self",
".",
"cast_as",
".",
"__name__",
".",
"lower",
"(",
")",
")",
")",
"(",
"val",
")",
"exce... | 38.285714 | 11.714286 |
def landweber(op, x, rhs, niter, omega=None, projection=None, callback=None):
r"""Optimized implementation of Landweber's method.
Solves the inverse problem::
A(x) = rhs
Parameters
----------
op : `Operator`
Operator in the inverse problem. ``op.derivative(x).adjoint`` must be
... | [
"def",
"landweber",
"(",
"op",
",",
"x",
",",
"rhs",
",",
"niter",
",",
"omega",
"=",
"None",
",",
"projection",
"=",
"None",
",",
"callback",
"=",
"None",
")",
":",
"# TODO: add a book reference",
"if",
"x",
"not",
"in",
"op",
".",
"domain",
":",
"r... | 33.852632 | 22.084211 |
def create_template(
self,
name,
subject,
html,
text='',
timeout=None
):
""" API call to create a template """
payload = {
'name': name,
'subject': subject,
'html': html,
'text': text
}
r... | [
"def",
"create_template",
"(",
"self",
",",
"name",
",",
"subject",
",",
"html",
",",
"text",
"=",
"''",
",",
"timeout",
"=",
"None",
")",
":",
"payload",
"=",
"{",
"'name'",
":",
"name",
",",
"'subject'",
":",
"subject",
",",
"'html'",
":",
"html",
... | 20.681818 | 19.545455 |
def check(self, src_tgt, actual_deps):
"""Check for missing deps.
See docstring for _compute_missing_deps for details.
"""
if self._check_missing_direct_deps or self._check_unnecessary_deps:
missing_file_deps, missing_direct_tgt_deps = \
self._compute_missing_deps(src_tgt, actual_deps)
... | [
"def",
"check",
"(",
"self",
",",
"src_tgt",
",",
"actual_deps",
")",
":",
"if",
"self",
".",
"_check_missing_direct_deps",
"or",
"self",
".",
"_check_unnecessary_deps",
":",
"missing_file_deps",
",",
"missing_direct_tgt_deps",
"=",
"self",
".",
"_compute_missing_de... | 47.65 | 24.425 |
def add_request_handlers_object(self, rh_obj):
"""Add fake request handlers from an object with request_* method(s)
See :meth:`FakeInspectingClientManager.add_request_handlers_dict` for more detail.
"""
rh_dict = {}
for name in dir(rh_obj):
if not callable(getattr(r... | [
"def",
"add_request_handlers_object",
"(",
"self",
",",
"rh_obj",
")",
":",
"rh_dict",
"=",
"{",
"}",
"for",
"name",
"in",
"dir",
"(",
"rh_obj",
")",
":",
"if",
"not",
"callable",
"(",
"getattr",
"(",
"rh_obj",
",",
"name",
")",
")",
":",
"continue",
... | 37.75 | 17.8125 |
def create(cls, pid_type=None, pid_value=None, object_type=None,
object_uuid=None, status=None, **kwargs):
"""Create a new instance for the given type and pid.
:param pid_type: Persistent identifier type. (Default: None).
:param pid_value: Persistent identifier value. (Default: N... | [
"def",
"create",
"(",
"cls",
",",
"pid_type",
"=",
"None",
",",
"pid_value",
"=",
"None",
",",
"object_type",
"=",
"None",
",",
"object_uuid",
"=",
"None",
",",
"status",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"assert",
"pid_value",
"assert",
... | 41.192308 | 16.538462 |
def connect(url):
"""Connect to UNIX or TCP socket.
url can be either tcp://<host>:port or ipc://<path>
"""
url = urlparse(url)
if url.scheme == 'tcp':
sock = socket()
netloc = tuple(url.netloc.rsplit(':', 1))
hostname = socket.gethostname()
elif url.scheme == 'ipc':... | [
"def",
"connect",
"(",
"url",
")",
":",
"url",
"=",
"urlparse",
"(",
"url",
")",
"if",
"url",
".",
"scheme",
"==",
"'tcp'",
":",
"sock",
"=",
"socket",
"(",
")",
"netloc",
"=",
"tuple",
"(",
"url",
".",
"netloc",
".",
"rsplit",
"(",
"':'",
",",
... | 27.210526 | 16.368421 |
def download(url, file=None):
"""
Pass file as a filename, open file object, or None to return the request bytes
Args:
url (str): URL of file to download
file (Union[str, io, None]): One of the following:
- Filename of output file
- File opened in binary write mode... | [
"def",
"download",
"(",
"url",
",",
"file",
"=",
"None",
")",
":",
"import",
"urllib",
".",
"request",
"import",
"shutil",
"if",
"isinstance",
"(",
"file",
",",
"str",
")",
":",
"file",
"=",
"open",
"(",
"file",
",",
"'wb'",
")",
"try",
":",
"with"... | 28.62963 | 17.37037 |
def get_resources(self, ids, cache=True):
"""Support server side filtering on arns or names
"""
if ids[0].startswith('arn:'):
params = {'LoadBalancerArns': ids}
else:
params = {'Names': ids}
return self.query.filter(self.manager, **params) | [
"def",
"get_resources",
"(",
"self",
",",
"ids",
",",
"cache",
"=",
"True",
")",
":",
"if",
"ids",
"[",
"0",
"]",
".",
"startswith",
"(",
"'arn:'",
")",
":",
"params",
"=",
"{",
"'LoadBalancerArns'",
":",
"ids",
"}",
"else",
":",
"params",
"=",
"{"... | 37 | 7.25 |
def is_panel_visible_for_user(panel, user):
"""
Checks if the user is allowed to see the panel
:param panel: panel ID as string
:param user: a MemberData object
:return: Boolean
"""
roles = user.getRoles()
visibility = get_dashboard_panels_visibility_by_section(panel)
for pair in vis... | [
"def",
"is_panel_visible_for_user",
"(",
"panel",
",",
"user",
")",
":",
"roles",
"=",
"user",
".",
"getRoles",
"(",
")",
"visibility",
"=",
"get_dashboard_panels_visibility_by_section",
"(",
"panel",
")",
"for",
"pair",
"in",
"visibility",
":",
"if",
"pair",
... | 31.307692 | 11 |
def content_type(self, request=None, response=None):
"""Returns the content type that should be used by default for this endpoint"""
if callable(self.outputs.content_type):
return self.outputs.content_type(request=request, response=response)
else:
return self.outputs.cont... | [
"def",
"content_type",
"(",
"self",
",",
"request",
"=",
"None",
",",
"response",
"=",
"None",
")",
":",
"if",
"callable",
"(",
"self",
".",
"outputs",
".",
"content_type",
")",
":",
"return",
"self",
".",
"outputs",
".",
"content_type",
"(",
"request",
... | 53.833333 | 15 |
def _brownian_eigs(n_grid, lag_time, grad_potential, xmin, xmax, reflect_bc):
"""Analytic eigenvalues/eigenvectors for 1D Brownian dynamics
"""
transmat = _brownian_transmat(n_grid, lag_time, grad_potential, xmin, xmax, reflect_bc)
u, lv, rv = _solve_msm_eigensystem(transmat, k=len(transmat) - 1)
re... | [
"def",
"_brownian_eigs",
"(",
"n_grid",
",",
"lag_time",
",",
"grad_potential",
",",
"xmin",
",",
"xmax",
",",
"reflect_bc",
")",
":",
"transmat",
"=",
"_brownian_transmat",
"(",
"n_grid",
",",
"lag_time",
",",
"grad_potential",
",",
"xmin",
",",
"xmax",
","... | 54.166667 | 23.5 |
def _wait_for_exec_ready(self):
"""
Wait for response.
:return: CliResponse object coming in
:raises: TestStepTimeout, TestStepError
"""
while not self.response_received.wait(1) and self.query_timeout != 0:
if self.query_timeout != 0 and self.query_timeout < ... | [
"def",
"_wait_for_exec_ready",
"(",
"self",
")",
":",
"while",
"not",
"self",
".",
"response_received",
".",
"wait",
"(",
"1",
")",
"and",
"self",
".",
"query_timeout",
"!=",
"0",
":",
"if",
"self",
".",
"query_timeout",
"!=",
"0",
"and",
"self",
".",
... | 43.5 | 18.888889 |
def replace_first_key_in_makefile(buf, key, replacement, outfile=None):
'''
Replaces first line in 'buf' matching 'key' with 'replacement'.
Optionally, writes out this new buffer into 'outfile'.
Returns: Buffer after replacement has been done
'''
regexp = re.compile(r'''
\n\s* # ... | [
"def",
"replace_first_key_in_makefile",
"(",
"buf",
",",
"key",
",",
"replacement",
",",
"outfile",
"=",
"None",
")",
":",
"regexp",
"=",
"re",
".",
"compile",
"(",
"r'''\n \\n\\s* # there might be some leading spaces\n ( # start group to return\... | 36.285714 | 19.714286 |
def _init_repo(self):
""" create and initialize a new Git Repo """
log.debug("initializing new Git Repo: {0}".format(self._engine_path))
if os.path.exists(self._engine_path):
log.error("Path already exists! Aborting!")
raise RuntimeError
else:
# create... | [
"def",
"_init_repo",
"(",
"self",
")",
":",
"log",
".",
"debug",
"(",
"\"initializing new Git Repo: {0}\"",
".",
"format",
"(",
"self",
".",
"_engine_path",
")",
")",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"self",
".",
"_engine_path",
")",
":",
"lo... | 48.357143 | 18.071429 |
def __wait_for_one_server_connection(self):
"""Wait until at least one server is connected. Since quitting relies
on a bunch of loops terminating, attempting to quit [cleanly]
immediately will still have to wait for the connections to finish
starting.
"""
_logger.info... | [
"def",
"__wait_for_one_server_connection",
"(",
"self",
")",
":",
"_logger",
".",
"info",
"(",
"\"Waiting for first connection.\"",
")",
"while",
"1",
":",
"is_connected_to_one",
"=",
"False",
"for",
"(",
"n",
",",
"c",
",",
"g",
")",
"in",
"self",
".",
"__c... | 45.34375 | 20.4375 |
def add_triple(self, sub, pred=None, obj=None, **kwargs):
""" Adds a triple to the dataset
args:
sub: The subject of the triple or dictionary contaning a
triple
pred: Optional if supplied in sub, predicate of the triple
obj: Opt... | [
"def",
"add_triple",
"(",
"self",
",",
"sub",
",",
"pred",
"=",
"None",
",",
"obj",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
".",
"__set_map__",
"(",
"*",
"*",
"kwargs",
")",
"strip_orphans",
"=",
"kwargs",
".",
"get",
"(",
"\"strip_... | 39.837838 | 17.864865 |
def msvc_output_flag(target, source, env, for_signature):
"""
Returns the correct /Fo flag for batching.
If batching is disabled or there's only one source file, then we
return an /Fo string that specifies the target explicitly. Otherwise,
we return an /Fo string that just specifies the first targ... | [
"def",
"msvc_output_flag",
"(",
"target",
",",
"source",
",",
"env",
",",
"for_signature",
")",
":",
"# Fixing MSVC_BATCH mode. Previous if did not work when MSVC_BATCH",
"# was set to False. This new version should work better. Removed",
"# len(source)==1 as batch mode can compile only ... | 48.541667 | 23.541667 |
def _output_from_file(self, entry='git_describe'):
"""
Read the version from a .version file that may exist alongside __init__.py.
This file can be generated by piping the following output to file:
git describe --long --match v*.*
"""
try:
vfile = os.path.jo... | [
"def",
"_output_from_file",
"(",
"self",
",",
"entry",
"=",
"'git_describe'",
")",
":",
"try",
":",
"vfile",
"=",
"os",
".",
"path",
".",
"join",
"(",
"os",
".",
"path",
".",
"dirname",
"(",
"self",
".",
"fpath",
")",
",",
"'.version'",
")",
"with",
... | 38.571429 | 20.714286 |
def octocat(self, say=None):
"""Returns an easter egg of the API.
:params str say: (optional), pass in what you'd like Octocat to say
:returns: ascii art of Octocat
"""
url = self._build_url('octocat')
req = self._get(url, params={'s': say})
return req.content if... | [
"def",
"octocat",
"(",
"self",
",",
"say",
"=",
"None",
")",
":",
"url",
"=",
"self",
".",
"_build_url",
"(",
"'octocat'",
")",
"req",
"=",
"self",
".",
"_get",
"(",
"url",
",",
"params",
"=",
"{",
"'s'",
":",
"say",
"}",
")",
"return",
"req",
... | 36.333333 | 11.111111 |
def shutdown(self, msg):
"""Shutdown the scheduler."""
try:
self.cleanup()
self.history.append("Completed on: %s" % time.asctime())
self.history.append("Elapsed time: %s" % self.get_delta_etime())
if self.debug:
print(">>>>> shutdown: Num... | [
"def",
"shutdown",
"(",
"self",
",",
"msg",
")",
":",
"try",
":",
"self",
".",
"cleanup",
"(",
")",
"self",
".",
"history",
".",
"append",
"(",
"\"Completed on: %s\"",
"%",
"time",
".",
"asctime",
"(",
")",
")",
"self",
".",
"history",
".",
"append",... | 37.125 | 21.078125 |
def get_annotation(db_path, db_list):
""" Checks if database is set as annotated. """
annotated = False
for db in db_list:
if db["path"] == db_path:
annotated = db["annotated"]
break
return annotated | [
"def",
"get_annotation",
"(",
"db_path",
",",
"db_list",
")",
":",
"annotated",
"=",
"False",
"for",
"db",
"in",
"db_list",
":",
"if",
"db",
"[",
"\"path\"",
"]",
"==",
"db_path",
":",
"annotated",
"=",
"db",
"[",
"\"annotated\"",
"]",
"break",
"return",... | 24 | 17.1 |
def has(self, name):
"""
Returns True if there is atleast one annotation by a given name, otherwise False.
"""
for a in self.all_annotations:
if a.name == name:
return True
return False | [
"def",
"has",
"(",
"self",
",",
"name",
")",
":",
"for",
"a",
"in",
"self",
".",
"all_annotations",
":",
"if",
"a",
".",
"name",
"==",
"name",
":",
"return",
"True",
"return",
"False"
] | 30.75 | 14.25 |
def _get_distance_term(self, C, mag, rrup):
"""
Returns the distance scaling term
"""
return (C['C4'] + C['C5'] * (mag - 6.3)) *\
np.log(np.sqrt(rrup ** 2. + np.exp(C['H']) ** 2.)) | [
"def",
"_get_distance_term",
"(",
"self",
",",
"C",
",",
"mag",
",",
"rrup",
")",
":",
"return",
"(",
"C",
"[",
"'C4'",
"]",
"+",
"C",
"[",
"'C5'",
"]",
"*",
"(",
"mag",
"-",
"6.3",
")",
")",
"*",
"np",
".",
"log",
"(",
"np",
".",
"sqrt",
"... | 36.5 | 6.166667 |
def random_rescale_to_mahalanobis(self, x):
"""change `x` like for injection, all on genotypic level"""
x -= self.mean
if any(x):
x *= sum(self.randn(len(x))**2)**0.5 / self.mahalanobis_norm(x)
x += self.mean
return x | [
"def",
"random_rescale_to_mahalanobis",
"(",
"self",
",",
"x",
")",
":",
"x",
"-=",
"self",
".",
"mean",
"if",
"any",
"(",
"x",
")",
":",
"x",
"*=",
"sum",
"(",
"self",
".",
"randn",
"(",
"len",
"(",
"x",
")",
")",
"**",
"2",
")",
"**",
"0.5",
... | 37.571429 | 17.142857 |
def scatter(self, x, y, xerr=None, yerr=None, cov=None, corr=None, s_expr=None, c_expr=None, labels=None, selection=None, length_limit=50000,
length_check=True, label=None, xlabel=None, ylabel=None, errorbar_kwargs={}, ellipse_kwargs={}, **kwargs):
"""Viz (small amounts) of data in 2d using a scatter plot
... | [
"def",
"scatter",
"(",
"self",
",",
"x",
",",
"y",
",",
"xerr",
"=",
"None",
",",
"yerr",
"=",
"None",
",",
"cov",
"=",
"None",
",",
"corr",
"=",
"None",
",",
"s_expr",
"=",
"None",
",",
"c_expr",
"=",
"None",
",",
"labels",
"=",
"None",
",",
... | 51.814433 | 22.907216 |
def _intertext_score(full_text):
'''returns tuple of scored sentences
in order of appearance
Note: Doing an A/B test to
compare results, reverting to
original algorithm.'''
sentences = sentence_tokenizer(full_text)
norm = _normalize(sentences)
similarity_matrix = pairwise_k... | [
"def",
"_intertext_score",
"(",
"full_text",
")",
":",
"sentences",
"=",
"sentence_tokenizer",
"(",
"full_text",
")",
"norm",
"=",
"_normalize",
"(",
"sentences",
")",
"similarity_matrix",
"=",
"pairwise_kernels",
"(",
"norm",
",",
"metric",
"=",
"'cosine'",
")"... | 35.666667 | 9.666667 |
def count_lines_of_code(self, fname=''):
""" counts non blank lines """
if fname == '':
fname = self.fullname
loc = 0
try:
with open(fname) as f:
for l in f:
if l.strip() != '':
loc += 1
r... | [
"def",
"count_lines_of_code",
"(",
"self",
",",
"fname",
"=",
"''",
")",
":",
"if",
"fname",
"==",
"''",
":",
"fname",
"=",
"self",
".",
"fullname",
"loc",
"=",
"0",
"try",
":",
"with",
"open",
"(",
"fname",
")",
"as",
"f",
":",
"for",
"l",
"in",... | 31.857143 | 12.571429 |
def search_track(self, artist, album=None, track=None,
full_album_art_uri=False):
"""Search for an artist, an artist's albums, or specific track.
Args:
artist (str): an artist's name.
album (str, optional): an album name. Default `None`.
track (s... | [
"def",
"search_track",
"(",
"self",
",",
"artist",
",",
"album",
"=",
"None",
",",
"track",
"=",
"None",
",",
"full_album_art_uri",
"=",
"False",
")",
":",
"subcategories",
"=",
"[",
"artist",
"]",
"subcategories",
".",
"append",
"(",
"album",
"or",
"''"... | 38.75 | 16.916667 |
def register_module(self, module, namespace=None):
"""
Register a module.
:param module: must be a string or a module object to register.
:type module: str
:param namespace: Namespace tag. If it is None module will be used as namespace tag
:type namespace: str
""... | [
"def",
"register_module",
"(",
"self",
",",
"module",
",",
"namespace",
"=",
"None",
")",
":",
"namespace",
"=",
"namespace",
"if",
"namespace",
"is",
"not",
"None",
"else",
"module",
"if",
"isinstance",
"(",
"module",
",",
"str",
")",
"else",
"module",
... | 40.833333 | 19.166667 |
def insert_ising_model(cur, nodelist, edgelist, linear, quadratic, offset, encoded_data=None):
"""Insert an Ising model into the cache.
Args:
cur (:class:`sqlite3.Cursor`): An sqlite3 cursor. This function
is meant to be run within a :obj:`with` statement.
nodelist (list): The nodes... | [
"def",
"insert_ising_model",
"(",
"cur",
",",
"nodelist",
",",
"edgelist",
",",
"linear",
",",
"quadratic",
",",
"offset",
",",
"encoded_data",
"=",
"None",
")",
":",
"if",
"encoded_data",
"is",
"None",
":",
"encoded_data",
"=",
"{",
"}",
"# insert graph and... | 38.923077 | 18.969231 |
def simulate(self, T):
"""Simulate state and observation processes.
Parameters
----------
T: int
processes are simulated from time 0 to time T-1
Returns
-------
x, y: lists
lists of length T
"""
x = []
for t in ra... | [
"def",
"simulate",
"(",
"self",
",",
"T",
")",
":",
"x",
"=",
"[",
"]",
"for",
"t",
"in",
"range",
"(",
"T",
")",
":",
"law_x",
"=",
"self",
".",
"PX0",
"(",
")",
"if",
"t",
"==",
"0",
"else",
"self",
".",
"PX",
"(",
"t",
",",
"x",
"[",
... | 24.736842 | 18.842105 |
def compute_canonical_key_ids(self, search_amplifier=100):
"""
A canonical key id is the lowest integer key id that maps to
a particular shard. The mapping to canonical key ids depends on the
number of shards.
Returns a dictionary mapping from shard number to canonical key id.
... | [
"def",
"compute_canonical_key_ids",
"(",
"self",
",",
"search_amplifier",
"=",
"100",
")",
":",
"canonical_keys",
"=",
"{",
"}",
"num_shards",
"=",
"self",
".",
"num_shards",
"(",
")",
"# Guarantees enough to find all keys without running forever",
"num_iterations",
"="... | 41.4 | 19.733333 |
def roulette_selection(population, fitnesses):
"""Create a list of parents with roulette selection."""
probabilities = _fitnesses_to_probabilities(fitnesses)
intermediate_population = []
for _ in range(len(population)):
# Choose a random individual
selection = random.uniform(0.0, 1.0)
... | [
"def",
"roulette_selection",
"(",
"population",
",",
"fitnesses",
")",
":",
"probabilities",
"=",
"_fitnesses_to_probabilities",
"(",
"fitnesses",
")",
"intermediate_population",
"=",
"[",
"]",
"for",
"_",
"in",
"range",
"(",
"len",
"(",
"population",
")",
")",
... | 40 | 14.866667 |
def assert_headers(context):
"""
:type context: behave.runner.Context
"""
expected_headers = [(k, v) for k, v in row_table(context).items()]
request = httpretty.last_request()
actual_headers = request.headers.items()
for expected_header in expected_headers:
assert_in(expected_hea... | [
"def",
"assert_headers",
"(",
"context",
")",
":",
"expected_headers",
"=",
"[",
"(",
"k",
",",
"v",
")",
"for",
"k",
",",
"v",
"in",
"row_table",
"(",
"context",
")",
".",
"items",
"(",
")",
"]",
"request",
"=",
"httpretty",
".",
"last_request",
"("... | 33.1 | 10.5 |
def extractDate(text):
""" Tries to extract a date from a given :obj:`str`.
:param str text: Input date. A :obj:`datetime.date` object is passed
thought without modification.
:rtype: :obj:`datetime.date`"""
if type(text) is datetime.date:
return text
match = date_format... | [
"def",
"extractDate",
"(",
"text",
")",
":",
"if",
"type",
"(",
"text",
")",
"is",
"datetime",
".",
"date",
":",
"return",
"text",
"match",
"=",
"date_format",
".",
"search",
"(",
"text",
".",
"lower",
"(",
")",
")",
"if",
"not",
"match",
":",
"rai... | 40.259259 | 14.148148 |
def get_default_config(self):
"""
Returns the default collector settings
"""
config = super(OpenstackSwiftReconCollector, self).get_default_config()
config.update({
'path': 'swiftrecon',
'recon_account_cache': '/var/cache/swift/account.recon',
... | [
"def",
"get_default_config",
"(",
"self",
")",
":",
"config",
"=",
"super",
"(",
"OpenstackSwiftReconCollector",
",",
"self",
")",
".",
"get_default_config",
"(",
")",
"config",
".",
"update",
"(",
"{",
"'path'",
":",
"'swiftrecon'",
",",
"'recon_account_cache'"... | 38.230769 | 17.461538 |
def entitlements(self, request, pk=None): # pylint: disable=invalid-name,unused-argument
"""
Retrieve the list of entitlements available to this learner.
Only those entitlements are returned that satisfy enterprise customer's data sharing setting.
Arguments:
request (HttpR... | [
"def",
"entitlements",
"(",
"self",
",",
"request",
",",
"pk",
"=",
"None",
")",
":",
"# pylint: disable=invalid-name,unused-argument",
"enterprise_customer_user",
"=",
"self",
".",
"get_object",
"(",
")",
"instance",
"=",
"{",
"\"entitlements\"",
":",
"enterprise_c... | 49.176471 | 32.117647 |
def exptime(self):
''' exptime: 下一個日期時間
:returns: 下一個預設時間
'''
return self.nextday + timedelta(hours=self.__hour - 8,
minutes=self.__minutes) | [
"def",
"exptime",
"(",
"self",
")",
":",
"return",
"self",
".",
"nextday",
"+",
"timedelta",
"(",
"hours",
"=",
"self",
".",
"__hour",
"-",
"8",
",",
"minutes",
"=",
"self",
".",
"__minutes",
")"
] | 30.142857 | 22.714286 |
def handle(cls, value, **kwargs):
"""Split the supplied string on the given delimiter, providing a list.
Format of value:
<delimiter>::<value>
For example:
Subnets: ${split ,::subnet-1,subnet-2,subnet-3}
Would result in the variable `Subnets` getting a list c... | [
"def",
"handle",
"(",
"cls",
",",
"value",
",",
"*",
"*",
"kwargs",
")",
":",
"try",
":",
"delimiter",
",",
"text",
"=",
"value",
".",
"split",
"(",
"\"::\"",
",",
"1",
")",
"except",
"ValueError",
":",
"raise",
"ValueError",
"(",
"\"Invalid value for ... | 33.16129 | 26.548387 |
def get_access_token(self, code=None, **params):
"""
Return the memoized access token or go out and fetch one.
"""
if self._access_token is None:
if code is None:
raise ValueError(_('Invalid code.'))
self.access_token_dict = self._get_... | [
"def",
"get_access_token",
"(",
"self",
",",
"code",
"=",
"None",
",",
"*",
"*",
"params",
")",
":",
"if",
"self",
".",
"_access_token",
"is",
"None",
":",
"if",
"code",
"is",
"None",
":",
"raise",
"ValueError",
"(",
"_",
"(",
"'Invalid code.'",
")",
... | 41.4 | 19.4 |
def hicpro_stats_table(self):
""" Add HiC-Pro stats to the general stats table """
headers = OrderedDict()
headers['percent_duplicates'] = {
'title': '% Duplicates',
'description': 'Percent of duplicated valid pairs (%)',
'max': 100,
'min':... | [
"def",
"hicpro_stats_table",
"(",
"self",
")",
":",
"headers",
"=",
"OrderedDict",
"(",
")",
"headers",
"[",
"'percent_duplicates'",
"]",
"=",
"{",
"'title'",
":",
"'% Duplicates'",
",",
"'description'",
":",
"'Percent of duplicated valid pairs (%)'",
",",
"'max'",
... | 34.955357 | 19.5 |
def interact_GxE_1dof(snps,pheno,env,K=None,covs=None, test='lrt'):
"""
Univariate GxE fixed effects interaction linear mixed model test for all
pairs of SNPs and environmental variables.
Args:
snps: [N x S] SP.array of S SNPs for N individuals
pheno: [N x 1] SP.array of 1 phenotype ... | [
"def",
"interact_GxE_1dof",
"(",
"snps",
",",
"pheno",
",",
"env",
",",
"K",
"=",
"None",
",",
"covs",
"=",
"None",
",",
"test",
"=",
"'lrt'",
")",
":",
"N",
"=",
"snps",
".",
"shape",
"[",
"0",
"]",
"if",
"K",
"is",
"None",
":",
"K",
"=",
"S... | 49.052632 | 29.684211 |
def create_from_header(header):
""" Creates a File from an existing header,
allocating the array of point according to the provided header.
The input header is copied.
Parameters
----------
header : existing header to be used to create the file
Returns
-------
pylas.lasdatas.base.... | [
"def",
"create_from_header",
"(",
"header",
")",
":",
"header",
"=",
"copy",
".",
"copy",
"(",
"header",
")",
"header",
".",
"point_count",
"=",
"0",
"points",
"=",
"record",
".",
"PackedPointRecord",
".",
"empty",
"(",
"PointFormat",
"(",
"header",
".",
... | 30.05 | 20.35 |
def _parse_message(self, data):
"""
Parse the bytes received from the socket.
:param data: the bytes received from the socket
:return:
"""
if TwitchChatStream._check_has_ping(data):
self._send_pong()
if TwitchChatStream._check_has_channel(data):
... | [
"def",
"_parse_message",
"(",
"self",
",",
"data",
")",
":",
"if",
"TwitchChatStream",
".",
"_check_has_ping",
"(",
"data",
")",
":",
"self",
".",
"_send_pong",
"(",
")",
"if",
"TwitchChatStream",
".",
"_check_has_channel",
"(",
"data",
")",
":",
"self",
"... | 37.961538 | 17.038462 |
def install(self, module):
"""Install a module into this binder.
In this context the module is one of the following:
* function taking the :class:`Binder` as it's only parameter
::
def configure(binder):
bind(str, to='s')
binder.install(conf... | [
"def",
"install",
"(",
"self",
",",
"module",
")",
":",
"if",
"type",
"(",
"module",
")",
"is",
"type",
"and",
"issubclass",
"(",
"module",
",",
"Module",
")",
":",
"instance",
"=",
"module",
"(",
")",
"else",
":",
"instance",
"=",
"module",
"instanc... | 25.527778 | 23.416667 |
def max_entries(self, entries):
"""
Chance the maximum number of retained log entries
:param entries: The maximum number of log entries to retain at any given time
:type entries: int
"""
self._debug_log.info('Changing maximum log entries from {old} to {new}'
... | [
"def",
"max_entries",
"(",
"self",
",",
"entries",
")",
":",
"self",
".",
"_debug_log",
".",
"info",
"(",
"'Changing maximum log entries from {old} to {new}'",
".",
"format",
"(",
"old",
"=",
"self",
".",
"_log_entries",
",",
"new",
"=",
"entries",
")",
")",
... | 51.75 | 25 |
def _q_to_dcm(self, q):
"""
Create DCM (Matrix3) from q
:param q: array q which represents a quaternion [w, x, y, z]
:returns: Matrix3
"""
assert(len(q) == 4)
arr = super(Quaternion, self)._q_to_dcm(q)
return self._dcm_array_to_matrix3(arr) | [
"def",
"_q_to_dcm",
"(",
"self",
",",
"q",
")",
":",
"assert",
"(",
"len",
"(",
"q",
")",
"==",
"4",
")",
"arr",
"=",
"super",
"(",
"Quaternion",
",",
"self",
")",
".",
"_q_to_dcm",
"(",
"q",
")",
"return",
"self",
".",
"_dcm_array_to_matrix3",
"("... | 32.888889 | 10.444444 |
def pretty_str(something, indent=0):
"""Return a human-readable string representation of an object.
Uses `pretty_str` if the given value is an instance of
`CodeEntity` and `repr` otherwise.
Args:
something: Some value to convert.
Kwargs:
indent (int): The amount of spaces ... | [
"def",
"pretty_str",
"(",
"something",
",",
"indent",
"=",
"0",
")",
":",
"if",
"isinstance",
"(",
"something",
",",
"CodeEntity",
")",
":",
"return",
"something",
".",
"pretty_str",
"(",
"indent",
"=",
"indent",
")",
"else",
":",
"return",
"(",
"' '",
... | 30.375 | 17.6875 |
def _convert_to_image_color(self, color):
""":return: a color that can be used by the image"""
rgb = self._convert_color_to_rrggbb(color)
return self._convert_rrggbb_to_image_color(rgb) | [
"def",
"_convert_to_image_color",
"(",
"self",
",",
"color",
")",
":",
"rgb",
"=",
"self",
".",
"_convert_color_to_rrggbb",
"(",
"color",
")",
"return",
"self",
".",
"_convert_rrggbb_to_image_color",
"(",
"rgb",
")"
] | 51.5 | 6.5 |
def merge_code(left_code, right_code):
"""
{ relative_line:
((left_abs_line, ((offset, op, args), ...)),
(right_abs_line, ((offset, op, args), ...))),
... }
"""
data = dict()
code_lines = (left_code and left_code.iter_code_by_lines()) or tuple()
for abs_line, rel_line, dis i... | [
"def",
"merge_code",
"(",
"left_code",
",",
"right_code",
")",
":",
"data",
"=",
"dict",
"(",
")",
"code_lines",
"=",
"(",
"left_code",
"and",
"left_code",
".",
"iter_code_by_lines",
"(",
")",
")",
"or",
"tuple",
"(",
")",
"for",
"abs_line",
",",
"rel_li... | 29.166667 | 17.666667 |
def rollback_group(self, group_id, version, force=False):
"""Roll a group back to a previous version.
:param str group_id: group ID
:param str version: group version
:param bool force: apply even if a deployment is in progress
:returns: a dict containing the deployment id and v... | [
"def",
"rollback_group",
"(",
"self",
",",
"group_id",
",",
"version",
",",
"force",
"=",
"False",
")",
":",
"params",
"=",
"{",
"'force'",
":",
"force",
"}",
"response",
"=",
"self",
".",
"_do_request",
"(",
"'PUT'",
",",
"'/v2/groups/{group_id}/versions/{v... | 35.705882 | 15.588235 |
def extract(self, *args):
"""
Extract a specific variable
"""
self.time = np.loadtxt(self.abspath,
skiprows=self._attributes['data_idx']+1,
unpack=True, usecols=(0,))
for variable_idx in args:
data ... | [
"def",
"extract",
"(",
"self",
",",
"*",
"args",
")",
":",
"self",
".",
"time",
"=",
"np",
".",
"loadtxt",
"(",
"self",
".",
"abspath",
",",
"skiprows",
"=",
"self",
".",
"_attributes",
"[",
"'data_idx'",
"]",
"+",
"1",
",",
"unpack",
"=",
"True",
... | 50.043478 | 16.478261 |
def _get_split_tasks(args, split_fn, file_key, outfile_i=-1):
"""Split up input files and arguments, returning arguments for parallel processing.
outfile_i specifies the location of the output file in the arguments to
the processing function. Defaults to the last item in the list.
"""
split_args = ... | [
"def",
"_get_split_tasks",
"(",
"args",
",",
"split_fn",
",",
"file_key",
",",
"outfile_i",
"=",
"-",
"1",
")",
":",
"split_args",
"=",
"[",
"]",
"combine_map",
"=",
"{",
"}",
"finished_map",
"=",
"collections",
".",
"OrderedDict",
"(",
")",
"extras",
"=... | 41.153846 | 15.307692 |
def find_external_compartment(model):
"""Find the external compartment in the model.
Uses a simple heuristic where the external compartment should be the one
with the most exchange reactions.
Arguments
---------
model : cobra.Model
A cobra model.
Returns
-------
str
... | [
"def",
"find_external_compartment",
"(",
"model",
")",
":",
"if",
"model",
".",
"boundary",
":",
"counts",
"=",
"pd",
".",
"Series",
"(",
"tuple",
"(",
"r",
".",
"compartments",
")",
"[",
"0",
"]",
"for",
"r",
"in",
"model",
".",
"boundary",
")",
"mo... | 43.280702 | 23.298246 |
def per_section(it, is_delimiter=lambda x: x.isspace()):
"""
From http://stackoverflow.com/a/25226944/610569
"""
ret = []
for line in it:
if is_delimiter(line):
if ret:
yield ret # OR ''.join(ret)
ret = []
else:
ret.append(lin... | [
"def",
"per_section",
"(",
"it",
",",
"is_delimiter",
"=",
"lambda",
"x",
":",
"x",
".",
"isspace",
"(",
")",
")",
":",
"ret",
"=",
"[",
"]",
"for",
"line",
"in",
"it",
":",
"if",
"is_delimiter",
"(",
"line",
")",
":",
"if",
"ret",
":",
"yield",
... | 26.571429 | 16.285714 |
def resolve_input_references(to_resolve, inputs_to_reference):
"""
Resolves input references given in the string to_resolve by using the inputs_to_reference.
See http://www.commonwl.org/user_guide/06-params/index.html for more information.
Example:
"$(inputs.my_file.nameroot).md" -> "filename.md"
... | [
"def",
"resolve_input_references",
"(",
"to_resolve",
",",
"inputs_to_reference",
")",
":",
"splitted",
"=",
"split_input_references",
"(",
"to_resolve",
")",
"result",
"=",
"[",
"]",
"for",
"part",
"in",
"splitted",
":",
"if",
"is_input_reference",
"(",
"part",
... | 32.307692 | 28.846154 |
def _remove_broken_links():
'''
Remove broken links in `<conda prefix>/etc/microdrop/plugins/enabled/`.
Returns
-------
list
List of links removed (if any).
'''
enabled_dir = MICRODROP_CONDA_PLUGINS.joinpath('enabled')
if not enabled_dir.isdir():
return []
broken_li... | [
"def",
"_remove_broken_links",
"(",
")",
":",
"enabled_dir",
"=",
"MICRODROP_CONDA_PLUGINS",
".",
"joinpath",
"(",
"'enabled'",
")",
"if",
"not",
"enabled_dir",
".",
"isdir",
"(",
")",
":",
"return",
"[",
"]",
"broken_links",
"=",
"[",
"]",
"for",
"dir_i",
... | 27.451613 | 21.516129 |
def channel_close(
self,
registry_address: PaymentNetworkID,
token_address: TokenAddress,
partner_address: Address,
retry_timeout: NetworkTimeout = DEFAULT_RETRY_TIMEOUT,
):
"""Close a channel opened with `partner_address` for the given
`to... | [
"def",
"channel_close",
"(",
"self",
",",
"registry_address",
":",
"PaymentNetworkID",
",",
"token_address",
":",
"TokenAddress",
",",
"partner_address",
":",
"Address",
",",
"retry_timeout",
":",
"NetworkTimeout",
"=",
"DEFAULT_RETRY_TIMEOUT",
",",
")",
":",
"self"... | 34.611111 | 14.111111 |
def get_info(node_id, info_id):
"""Get a specific info.
Both the node and info id must be specified in the url.
"""
exp = experiment(session)
# check the node exists
node = models.Node.query.get(node_id)
if node is None:
return error_response(error_type="/info, node does not exist"... | [
"def",
"get_info",
"(",
"node_id",
",",
"info_id",
")",
":",
"exp",
"=",
"experiment",
"(",
"session",
")",
"# check the node exists",
"node",
"=",
"models",
".",
"Node",
".",
"query",
".",
"get",
"(",
"node_id",
")",
"if",
"node",
"is",
"None",
":",
"... | 36.026316 | 18.342105 |
def _pd_post_process(self, cfg):
"""
Take care of those loop headers/tails where we manually broke their
connection to the next BBL
"""
loop_back_edges = self._cfg.get_loop_back_edges()
for b1, b2 in loop_back_edges:
# The edge between b1 and b2 is manually b... | [
"def",
"_pd_post_process",
"(",
"self",
",",
"cfg",
")",
":",
"loop_back_edges",
"=",
"self",
".",
"_cfg",
".",
"get_loop_back_edges",
"(",
")",
"for",
"b1",
",",
"b2",
"in",
"loop_back_edges",
":",
"# The edge between b1 and b2 is manually broken",
"# The post domi... | 36.666667 | 17.555556 |
def _submit_resource_request(self):
"""
**Purpose**: Create and submits a RADICAL Pilot Job as per the user
provided resource description
"""
try:
self._prof.prof('creating rreq', uid=self._uid)
def _pilot_state_cb(pilot, state):
... | [
"def",
"_submit_resource_request",
"(",
"self",
")",
":",
"try",
":",
"self",
".",
"_prof",
".",
"prof",
"(",
"'creating rreq'",
",",
"uid",
"=",
"self",
".",
"_uid",
")",
"def",
"_pilot_state_cb",
"(",
"pilot",
",",
"state",
")",
":",
"self",
".",
"_l... | 33.819277 | 23.216867 |
def getEncodableAttributes(self, obj, codec=None):
"""
Must return a C{dict} of attributes to be encoded, even if its empty.
@param codec: An optional argument that will contain the encoder
instance calling this function.
@since: 0.5
"""
if not self._compiled... | [
"def",
"getEncodableAttributes",
"(",
"self",
",",
"obj",
",",
"codec",
"=",
"None",
")",
":",
"if",
"not",
"self",
".",
"_compiled",
":",
"self",
".",
"compile",
"(",
")",
"if",
"self",
".",
"is_dict",
":",
"return",
"dict",
"(",
"obj",
")",
"if",
... | 28.560606 | 20.590909 |
def _equals(self, b):
'''Checks whether two records are equal by comparing all fields.
:param b: Another _AzureRecord object
:type b: _AzureRecord
:type return: bool
'''
def parse_dict(params):
vals = []
for char in params:
... | [
"def",
"_equals",
"(",
"self",
",",
"b",
")",
":",
"def",
"parse_dict",
"(",
"params",
")",
":",
"vals",
"=",
"[",
"]",
"for",
"char",
"in",
"params",
":",
"if",
"char",
"!=",
"'ttl'",
":",
"list_records",
"=",
"params",
"[",
"char",
"]",
"try",
... | 38.769231 | 18.076923 |
def get_schema_object(self, fully_qualified_name: str) -> 'BaseSchema':
"""
Used to generate a schema object from the given fully_qualified_name.
:param fully_qualified_name: The fully qualified name of the object needed.
:return: An initialized schema object
"""
if full... | [
"def",
"get_schema_object",
"(",
"self",
",",
"fully_qualified_name",
":",
"str",
")",
"->",
"'BaseSchema'",
":",
"if",
"fully_qualified_name",
"not",
"in",
"self",
".",
"_schema_cache",
":",
"spec",
"=",
"self",
".",
"get_schema_spec",
"(",
"fully_qualified_name"... | 47.619048 | 26 |
def sparse_covariance_matrix(self,x,y,names):
"""build a pyemu.Cov instance from GeoStruct
Parameters
----------
x : (iterable of floats)
x-coordinate locations
y : (iterable of floats)
y-coordinate location... | [
"def",
"sparse_covariance_matrix",
"(",
"self",
",",
"x",
",",
"y",
",",
"names",
")",
":",
"if",
"not",
"isinstance",
"(",
"x",
",",
"np",
".",
"ndarray",
")",
":",
"x",
"=",
"np",
".",
"array",
"(",
"x",
")",
"if",
"not",
"isinstance",
"(",
"y"... | 33.767442 | 18.581395 |
def project_dir(self) -> str:
"""Generate a random path to project directory.
:return: Path to project.
:Example:
/home/sherika/Development/Falcon/mercenary
"""
dev_dir = self.dev_dir()
project = self.random.choice(PROJECT_NAMES)
return str(self._pat... | [
"def",
"project_dir",
"(",
"self",
")",
"->",
"str",
":",
"dev_dir",
"=",
"self",
".",
"dev_dir",
"(",
")",
"project",
"=",
"self",
".",
"random",
".",
"choice",
"(",
"PROJECT_NAMES",
")",
"return",
"str",
"(",
"self",
".",
"_pathlib_home",
"/",
"dev_d... | 30.909091 | 15.636364 |
def VerifyServerPEM(self, http_object):
"""Check the server PEM for validity.
This is used to determine connectivity to the server. Sometimes captive
portals return a valid HTTP status, but the data is corrupted.
Args:
http_object: The response received from the server.
Returns:
True ... | [
"def",
"VerifyServerPEM",
"(",
"self",
",",
"http_object",
")",
":",
"try",
":",
"server_pem",
"=",
"http_object",
".",
"data",
"server_url",
"=",
"http_object",
".",
"url",
"if",
"b\"BEGIN CERTIFICATE\"",
"in",
"server_pem",
":",
"# Now we know that this proxy is w... | 35.5 | 23.566667 |
def key_value_convert(dictin, keyfn=lambda x: x, valuefn=lambda x: x, dropfailedkeys=False, dropfailedvalues=False,
exception=ValueError):
# type: (DictUpperBound, Callable[[Any], Any], Callable[[Any], Any], bool, bool, ExceptionUpperBound) -> Dict
"""Convert keys and/or values of dictiona... | [
"def",
"key_value_convert",
"(",
"dictin",
",",
"keyfn",
"=",
"lambda",
"x",
":",
"x",
",",
"valuefn",
"=",
"lambda",
"x",
":",
"x",
",",
"dropfailedkeys",
"=",
"False",
",",
"dropfailedvalues",
"=",
"False",
",",
"exception",
"=",
"ValueError",
")",
":"... | 42.5 | 27.264706 |
def _run_nb_cmd(self, cmd):
'''
cmd iterator
'''
try:
proc = salt.utils.nb_popen.NonBlockingPopen(
cmd,
shell=True,
stderr=subprocess.PIPE,
stdout=subprocess.PIPE,
)
while True:
... | [
"def",
"_run_nb_cmd",
"(",
"self",
",",
"cmd",
")",
":",
"try",
":",
"proc",
"=",
"salt",
".",
"utils",
".",
"nb_popen",
".",
"NonBlockingPopen",
"(",
"cmd",
",",
"shell",
"=",
"True",
",",
"stderr",
"=",
"subprocess",
".",
"PIPE",
",",
"stdout",
"="... | 29.782609 | 13.086957 |
def fragment(self, message):
"""Fragment message based on max payload size
note: if the message doesn't need to fragment,
it will return a list which only contains original
message itself.
:param message: raw message
:return: list of messages whose sizes <= max
... | [
"def",
"fragment",
"(",
"self",
",",
"message",
")",
":",
"if",
"message",
".",
"message_type",
"in",
"[",
"Types",
".",
"CALL_RES",
",",
"Types",
".",
"CALL_REQ",
",",
"Types",
".",
"CALL_REQ_CONTINUE",
",",
"Types",
".",
"CALL_RES_CONTINUE",
"]",
":",
... | 39.857143 | 15.114286 |
def _get_activation(self, F, inputs, activation, **kwargs):
"""Get activation function. Convert if is string"""
func = {'tanh': F.tanh,
'relu': F.relu,
'sigmoid': F.sigmoid,
'softsign': F.softsign}.get(activation)
if func:
return func(i... | [
"def",
"_get_activation",
"(",
"self",
",",
"F",
",",
"inputs",
",",
"activation",
",",
"*",
"*",
"kwargs",
")",
":",
"func",
"=",
"{",
"'tanh'",
":",
"F",
".",
"tanh",
",",
"'relu'",
":",
"F",
".",
"relu",
",",
"'sigmoid'",
":",
"F",
".",
"sigmo... | 48.461538 | 13.923077 |
def common_values_dict():
"""Build a basic values object used in every create method.
All our resources contain a same subset of value. Instead of
redoing this code everytime, this method ensures it is done only at
one place.
"""
now = datetime.datetime.utcnow().isoformat()
etag = ... | [
"def",
"common_values_dict",
"(",
")",
":",
"now",
"=",
"datetime",
".",
"datetime",
".",
"utcnow",
"(",
")",
".",
"isoformat",
"(",
")",
"etag",
"=",
"utils",
".",
"gen_etag",
"(",
")",
"values",
"=",
"{",
"'id'",
":",
"utils",
".",
"gen_uuid",
"(",... | 27.470588 | 20.058824 |
def submit(self, map, method, postfix):
'''Realiza um requisição HTTP para a networkAPI.
:param map: Dicionário com os dados para gerar o XML enviado no corpo da requisição HTTP.
:param method: Método da requisição HTTP ('GET', 'POST', 'PUT' ou 'DELETE').
:param postfix: Posfixo a ser c... | [
"def",
"submit",
"(",
"self",
",",
"map",
",",
"method",
",",
"postfix",
")",
":",
"try",
":",
"rest_request",
"=",
"RestRequest",
"(",
"self",
".",
"get_url",
"(",
"postfix",
")",
",",
"method",
",",
"self",
".",
"user",
",",
"self",
".",
"password"... | 40.863636 | 23.045455 |
def update_policy(self):
"""
Uses demonstration_buffer to update the policy.
"""
self.trainer_metrics.start_policy_update_timer(
number_experiences=len(self.training_buffer.update_buffer['actions']),
mean_return=float(np.mean(self.cumulative_returns_since_policy_u... | [
"def",
"update_policy",
"(",
"self",
")",
":",
"self",
".",
"trainer_metrics",
".",
"start_policy_update_timer",
"(",
"number_experiences",
"=",
"len",
"(",
"self",
".",
"training_buffer",
".",
"update_buffer",
"[",
"'actions'",
"]",
")",
",",
"mean_return",
"="... | 59.375 | 23.375 |
def take_screen_shot_to_array(self, screen_id, width, height, bitmap_format):
"""Takes a guest screen shot of the requested size and format
and returns it as an array of bytes.
in screen_id of type int
The guest monitor to take screenshot from.
in width of type int
... | [
"def",
"take_screen_shot_to_array",
"(",
"self",
",",
"screen_id",
",",
"width",
",",
"height",
",",
"bitmap_format",
")",
":",
"if",
"not",
"isinstance",
"(",
"screen_id",
",",
"baseinteger",
")",
":",
"raise",
"TypeError",
"(",
"\"screen_id can only be an instan... | 40.709677 | 20.645161 |
def send_keysequence_window_up(self, window, keysequence, delay=12000):
"""Send key release (up) events for the given key sequence"""
_libxdo.xdo_send_keysequence_window_up(
self._xdo, window, keysequence, ctypes.c_ulong(delay)) | [
"def",
"send_keysequence_window_up",
"(",
"self",
",",
"window",
",",
"keysequence",
",",
"delay",
"=",
"12000",
")",
":",
"_libxdo",
".",
"xdo_send_keysequence_window_up",
"(",
"self",
".",
"_xdo",
",",
"window",
",",
"keysequence",
",",
"ctypes",
".",
"c_ulo... | 63.25 | 16 |
def merged():
# type: () -> None
""" Cleanup a remotely merged branch. """
develop = conf.get('git.devel_branch', 'develop')
master = conf.get('git.master_branch', 'master')
branch = git.current_branch(refresh=True)
common.assert_branch_type('hotfix')
# Pull master with the merged hotfix
... | [
"def",
"merged",
"(",
")",
":",
"# type: () -> None",
"develop",
"=",
"conf",
".",
"get",
"(",
"'git.devel_branch'",
",",
"'develop'",
")",
"master",
"=",
"conf",
".",
"get",
"(",
"'git.master_branch'",
",",
"'master'",
")",
"branch",
"=",
"git",
".",
"cur... | 26 | 17.086957 |
def write_float(self, value, little_endian=True):
"""
Pack the value as a float and write 4 bytes to the stream.
Args:
value (number): the value to write to the stream.
little_endian (bool): specify the endianness. (Default) Little endian.
Returns:
i... | [
"def",
"write_float",
"(",
"self",
",",
"value",
",",
"little_endian",
"=",
"True",
")",
":",
"if",
"little_endian",
":",
"endian",
"=",
"\"<\"",
"else",
":",
"endian",
"=",
"\">\"",
"return",
"self",
".",
"pack",
"(",
"'%sf'",
"%",
"endian",
",",
"val... | 30.4375 | 19.6875 |
def get_capacity_grav(self, min_voltage=None, max_voltage=None,
use_overall_normalization=True):
"""
Get the gravimetric capacity of the electrode.
Args:
min_voltage (float): The minimum allowable voltage for a given
step.
max_vo... | [
"def",
"get_capacity_grav",
"(",
"self",
",",
"min_voltage",
"=",
"None",
",",
"max_voltage",
"=",
"None",
",",
"use_overall_normalization",
"=",
"True",
")",
":",
"pairs_in_range",
"=",
"self",
".",
"_select_in_voltage_range",
"(",
"min_voltage",
",",
"max_voltag... | 48.32 | 24.4 |
def concat(ctx, *strings):
'''
Yields one string, concatenation of argument strings
'''
strings = flatten([ (s.compute(ctx) if callable(s) else s) for s in strings ])
strings = (next(string_arg(ctx, s), '') for s in strings)
#assert(all(map(lambda x: isinstance(x, str), strings)))
#FIXME: Ch... | [
"def",
"concat",
"(",
"ctx",
",",
"*",
"strings",
")",
":",
"strings",
"=",
"flatten",
"(",
"[",
"(",
"s",
".",
"compute",
"(",
"ctx",
")",
"if",
"callable",
"(",
"s",
")",
"else",
"s",
")",
"for",
"s",
"in",
"strings",
"]",
")",
"strings",
"="... | 39.111111 | 22.888889 |
def get_auth_providers(self, netloc):
"""BIG-IQ specific query for auth providers
BIG-IP doesn't really need this because BIG-IP's multiple auth providers
seem to handle fallthrough just fine. BIG-IQ on the other hand, needs to
have its auth provider specified if you're using one of the... | [
"def",
"get_auth_providers",
"(",
"self",
",",
"netloc",
")",
":",
"url",
"=",
"\"https://%s/info/system?null\"",
"%",
"(",
"netloc",
")",
"response",
"=",
"requests",
".",
"get",
"(",
"url",
",",
"verify",
"=",
"self",
".",
"verify",
")",
"if",
"not",
"... | 41.208333 | 20.208333 |
def locked_get(self):
"""Retrieve the credentials from the dictionary, if they exist.
Returns: A :class:`oauth2client.client.OAuth2Credentials` instance.
"""
serialized = self._dictionary.get(self._key)
if serialized is None:
return None
credentials = clien... | [
"def",
"locked_get",
"(",
"self",
")",
":",
"serialized",
"=",
"self",
".",
"_dictionary",
".",
"get",
"(",
"self",
".",
"_key",
")",
"if",
"serialized",
"is",
"None",
":",
"return",
"None",
"credentials",
"=",
"client",
".",
"OAuth2Credentials",
".",
"f... | 29.428571 | 21.428571 |
def parse_option(self, option, block_name, *values):
""" Parse domain values for option.
"""
_extra_subs = ('www', 'm', 'mobile')
if len(values) == 0: # expect some values here..
raise ValueError
for value in values:
value = value.lower()
... | [
"def",
"parse_option",
"(",
"self",
",",
"option",
",",
"block_name",
",",
"*",
"values",
")",
":",
"_extra_subs",
"=",
"(",
"'www'",
",",
"'m'",
",",
"'mobile'",
")",
"if",
"len",
"(",
"values",
")",
"==",
"0",
":",
"# expect some values here..",
"raise... | 35.75 | 18.25 |
def headers_to_sign(self, http_request):
"""
Select the headers from the request that need to be included
in the StringToSign.
"""
headers_to_sign = {}
headers_to_sign = {'Host' : self.host}
for name, value in http_request.headers.items():
lname = name... | [
"def",
"headers_to_sign",
"(",
"self",
",",
"http_request",
")",
":",
"headers_to_sign",
"=",
"{",
"}",
"headers_to_sign",
"=",
"{",
"'Host'",
":",
"self",
".",
"host",
"}",
"for",
"name",
",",
"value",
"in",
"http_request",
".",
"headers",
".",
"items",
... | 36.333333 | 8.166667 |
def send(self, data):
"""
Sends a packet of data through this connection mode.
This method returns a coroutine.
"""
if not self._connected:
raise ConnectionError('Not connected')
return self._send_queue.put(data) | [
"def",
"send",
"(",
"self",
",",
"data",
")",
":",
"if",
"not",
"self",
".",
"_connected",
":",
"raise",
"ConnectionError",
"(",
"'Not connected'",
")",
"return",
"self",
".",
"_send_queue",
".",
"put",
"(",
"data",
")"
] | 26.5 | 13.9 |
def errorhandler(self, code_or_exception):
"""
Register a function to handle errors by code or exception class.
A decorator that is used to register a function given an
error code. Example::
@app.errorhandler(404)
def page_not_found(error):
retu... | [
"def",
"errorhandler",
"(",
"self",
",",
"code_or_exception",
")",
":",
"def",
"decorator",
"(",
"fn",
")",
":",
"self",
".",
"_defer",
"(",
"lambda",
"app",
":",
"app",
".",
"register_error_handler",
"(",
"code_or_exception",
",",
"fn",
")",
")",
"return"... | 35.666667 | 20.333333 |
def get_version():
"""Get version from git and VERSION file.
In the case where the version is not tagged in git, this function appends
.post0+commit if the version has been released and .dev0+commit if the
version has not yet been released.
Derived from: https://github.com/Changaco/version.py
... | [
"def",
"get_version",
"(",
")",
":",
"d",
"=",
"os",
".",
"path",
".",
"dirname",
"(",
"__file__",
")",
"# get release number from VERSION",
"with",
"open",
"(",
"os",
".",
"path",
".",
"join",
"(",
"d",
",",
"'VERSION'",
")",
")",
"as",
"f",
":",
"v... | 37.378378 | 17.918919 |
def _debug_dump_dom(el):
"""Debugging helper. Prints out `el` contents."""
import xml.dom.minidom
s = [el.nodeName]
att_container = el.attributes
for i in range(att_container.length):
attr = att_container.item(i)
s.append(' @{a}="{v}"'.format(a=attr.name, v=attr.value))
for c in... | [
"def",
"_debug_dump_dom",
"(",
"el",
")",
":",
"import",
"xml",
".",
"dom",
".",
"minidom",
"s",
"=",
"[",
"el",
".",
"nodeName",
"]",
"att_container",
"=",
"el",
".",
"attributes",
"for",
"i",
"in",
"range",
"(",
"att_container",
".",
"length",
")",
... | 39.857143 | 15.642857 |
def to_string(input_):
"""Format an input for representation as text
This method is just a convenience that handles default LaTeX formatting
"""
usetex = rcParams['text.usetex']
if isinstance(input_, units.UnitBase):
return input_.to_string('latex_inline')
if isinstance(input_, (float, ... | [
"def",
"to_string",
"(",
"input_",
")",
":",
"usetex",
"=",
"rcParams",
"[",
"'text.usetex'",
"]",
"if",
"isinstance",
"(",
"input_",
",",
"units",
".",
"UnitBase",
")",
":",
"return",
"input_",
".",
"to_string",
"(",
"'latex_inline'",
")",
"if",
"isinstan... | 34.384615 | 12.538462 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.