text stringlengths 75 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 0.18 |
|---|---|---|---|
def smoothstep(a, b, x):
""" Returns a smooth transition between 0.0 and 1.0 using Hermite interpolation (cubic spline),
where x is a number between a and b. The return value will ease (slow down) as x nears a or b.
For x smaller than a, returns 0.0. For x bigger than b, returns 1.0.
"""
... | [
"def",
"smoothstep",
"(",
"a",
",",
"b",
",",
"x",
")",
":",
"if",
"x",
"<",
"a",
":",
"return",
"0.0",
"if",
"x",
">=",
"b",
":",
"return",
"1.0",
"x",
"=",
"float",
"(",
"x",
"-",
"a",
")",
"/",
"(",
"b",
"-",
"a",
")",
"return",
"x",
... | 40.090909 | 0.006652 |
def tag_fig_ordinal(tag):
"""
Meant for finding the position of fig tags with respect to whether
they are for a main figure or a child figure
"""
tag_count = 0
if 'specific-use' not in tag.attrs:
# Look for tags with no "specific-use" attribute
return len(list(filter(lambda tag: ... | [
"def",
"tag_fig_ordinal",
"(",
"tag",
")",
":",
"tag_count",
"=",
"0",
"if",
"'specific-use'",
"not",
"in",
"tag",
".",
"attrs",
":",
"# Look for tags with no \"specific-use\" attribute",
"return",
"len",
"(",
"list",
"(",
"filter",
"(",
"lambda",
"tag",
":",
... | 40.8 | 0.004796 |
def score_(self):
"""
The concordance score (also known as the c-index) of the fit. The c-index is a generalization of the ROC AUC
to survival data, including censorships.
For this purpose, the ``score_`` is a measure of the predictive accuracy of the fitted model
onto the trai... | [
"def",
"score_",
"(",
"self",
")",
":",
"# pylint: disable=access-member-before-definition",
"if",
"hasattr",
"(",
"self",
",",
"\"_predicted_hazards_\"",
")",
":",
"self",
".",
"_concordance_score_",
"=",
"concordance_index",
"(",
"self",
".",
"durations",
",",
"-"... | 48.6 | 0.006729 |
def click_partial_link_text(self, partial_link_text,
timeout=settings.SMALL_TIMEOUT):
""" This method clicks the partial link text on a page. """
# If using phantomjs, might need to extract and open the link directly
if self.timeout_multiplier and timeout == setti... | [
"def",
"click_partial_link_text",
"(",
"self",
",",
"partial_link_text",
",",
"timeout",
"=",
"settings",
".",
"SMALL_TIMEOUT",
")",
":",
"# If using phantomjs, might need to extract and open the link directly",
"if",
"self",
".",
"timeout_multiplier",
"and",
"timeout",
"==... | 48.351852 | 0.001126 |
def _python_shell_default(python_shell, __pub_jid):
'''
Set python_shell default based on remote execution and __opts__['cmd_safe']
'''
try:
# Default to python_shell=True when run directly from remote execution
# system. Cross-module calls won't have a jid.
if __pub_jid and pyth... | [
"def",
"_python_shell_default",
"(",
"python_shell",
",",
"__pub_jid",
")",
":",
"try",
":",
"# Default to python_shell=True when run directly from remote execution",
"# system. Cross-module calls won't have a jid.",
"if",
"__pub_jid",
"and",
"python_shell",
"is",
"None",
":",
... | 37.066667 | 0.001754 |
def alias_repository(self, repository_id=None, alias_id=None):
"""Adds an ``Id`` to a ``Repository`` for the purpose of creating compatibility.
The primary ``Id`` of the ``Repository`` is determined by the
provider. The new ``Id`` is an alias to the primary ``Id``. If
the alias is a poi... | [
"def",
"alias_repository",
"(",
"self",
",",
"repository_id",
"=",
"None",
",",
"alias_id",
"=",
"None",
")",
":",
"# Implemented from awsosid template for -",
"# osid.resource.BinAdminSession.alias_bin_template",
"if",
"not",
"self",
".",
"_can",
"(",
"'alias'",
")",
... | 45.666667 | 0.002383 |
def statsHandler(serverName, path=''):
"""Renders a GET request, by showing this nodes stats and children."""
path = path.lstrip('/')
parts = path.split('/')
if not parts[0]:
parts = parts[1:]
statDict = util.lookup(scales.getStats(), parts)
if statDict is None:
abort(404, 'No stats found with path... | [
"def",
"statsHandler",
"(",
"serverName",
",",
"path",
"=",
"''",
")",
":",
"path",
"=",
"path",
".",
"lstrip",
"(",
"'/'",
")",
"parts",
"=",
"path",
".",
"split",
"(",
"'/'",
")",
"if",
"not",
"parts",
"[",
"0",
"]",
":",
"parts",
"=",
"parts",... | 33.652174 | 0.017588 |
def create_bulker(self):
"""
Create a bulker object and return it to allow to manage custom bulk policies
"""
return self.bulker_class(self, bulk_size=self.bulk_size,
raise_on_bulk_item_failure=self.raise_on_bulk_item_failure) | [
"def",
"create_bulker",
"(",
"self",
")",
":",
"return",
"self",
".",
"bulker_class",
"(",
"self",
",",
"bulk_size",
"=",
"self",
".",
"bulk_size",
",",
"raise_on_bulk_item_failure",
"=",
"self",
".",
"raise_on_bulk_item_failure",
")"
] | 47.666667 | 0.013746 |
def read_input(self):
"""Section 3 - Read Input File (.m, file)
Note: UWG_Matlab input files are xlsm, XML, .m, file.
properties:
self._init_param_dict # dictionary of simulation initialization parameters
self.sensAnth # non-building sensible heat (W/m^... | [
"def",
"read_input",
"(",
"self",
")",
":",
"uwg_param_file_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"uwgParamDir",
",",
"self",
".",
"uwgParamFileName",
")",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"uwg_param_file_path",
... | 46.688406 | 0.009271 |
def _condense(self, data):
'''
Condense by adding together all of the lists.
'''
rval = {}
for resolution,histogram in data.items():
for value,count in histogram.items():
rval[ value ] = count + rval.get(value,0)
return rval | [
"def",
"_condense",
"(",
"self",
",",
"data",
")",
":",
"rval",
"=",
"{",
"}",
"for",
"resolution",
",",
"histogram",
"in",
"data",
".",
"items",
"(",
")",
":",
"for",
"value",
",",
"count",
"in",
"histogram",
".",
"items",
"(",
")",
":",
"rval",
... | 28.222222 | 0.026718 |
def _preprocess_inputs(durations, event_observed, timeline, entry, weights):
"""
Cleans and confirms input to what lifelines expects downstream
"""
n = len(durations)
durations = np.asarray(pass_for_numeric_dtypes_or_raise_array(durations)).reshape((n,))
# set to all observed if event_observed... | [
"def",
"_preprocess_inputs",
"(",
"durations",
",",
"event_observed",
",",
"timeline",
",",
"entry",
",",
"weights",
")",
":",
"n",
"=",
"len",
"(",
"durations",
")",
"durations",
"=",
"np",
".",
"asarray",
"(",
"pass_for_numeric_dtypes_or_raise_array",
"(",
"... | 35.541667 | 0.005708 |
def _validate_duplicates(self):
"""
Ensure we're not creating a device that already exists
Runs only when the DeviceConnector object is created, not when is updated
"""
# if connector is being created right now
if not self.id:
duplicates = []
self.... | [
"def",
"_validate_duplicates",
"(",
"self",
")",
":",
"# if connector is being created right now",
"if",
"not",
"self",
".",
"id",
":",
"duplicates",
"=",
"[",
"]",
"self",
".",
"netengine_dict",
"=",
"self",
".",
"netengine",
".",
"to_dict",
"(",
")",
"# loop... | 50.818182 | 0.005268 |
def visit_Dict(self, node: AST, dfltChaining: bool = True) -> str:
"""Return dict representation of `node`s elements."""
items = (': '.join((self.visit(key), self.visit(value)))
for key, value in zip(node.keys, node.values))
return f"{{{', '.join(items)}}}" | [
"def",
"visit_Dict",
"(",
"self",
",",
"node",
":",
"AST",
",",
"dfltChaining",
":",
"bool",
"=",
"True",
")",
"->",
"str",
":",
"items",
"=",
"(",
"': '",
".",
"join",
"(",
"(",
"self",
".",
"visit",
"(",
"key",
")",
",",
"self",
".",
"visit",
... | 58.8 | 0.006711 |
def __get_values(self):
"""
Gets values in this cell range as a tuple.
This is much more effective than reading cell values one by one.
"""
array = self._get_target().getDataArray()
return tuple(itertools.chain.from_iterable(array)) | [
"def",
"__get_values",
"(",
"self",
")",
":",
"array",
"=",
"self",
".",
"_get_target",
"(",
")",
".",
"getDataArray",
"(",
")",
"return",
"tuple",
"(",
"itertools",
".",
"chain",
".",
"from_iterable",
"(",
"array",
")",
")"
] | 34.25 | 0.007117 |
def _actor_method_call(self,
method_name,
args=None,
kwargs=None,
num_return_vals=None):
"""Method execution stub for an actor handle.
This is the function that executes when
`actor.metho... | [
"def",
"_actor_method_call",
"(",
"self",
",",
"method_name",
",",
"args",
"=",
"None",
",",
"kwargs",
"=",
"None",
",",
"num_return_vals",
"=",
"None",
")",
":",
"worker",
"=",
"ray",
".",
"worker",
".",
"get_global_worker",
"(",
")",
"worker",
".",
"ch... | 41.864865 | 0.001892 |
def get_bytes(self, bridge):
"""
Gets the full command as bytes.
:param bridge: The bridge, to which the command should be sent.
"""
if not bridge.is_ready:
raise Exception('The bridge has to be ready to construct command.')
wb1 = bridge.wb1
wb2 = bri... | [
"def",
"get_bytes",
"(",
"self",
",",
"bridge",
")",
":",
"if",
"not",
"bridge",
".",
"is_ready",
":",
"raise",
"Exception",
"(",
"'The bridge has to be ready to construct command.'",
")",
"wb1",
"=",
"bridge",
".",
"wb1",
"wb2",
"=",
"bridge",
".",
"wb2",
"... | 37.95 | 0.002571 |
def __matches(s1, s2, ngrams_fn, n=3):
"""
Returns the n-grams that match between two sequences
See also: SequenceMatcher.get_matching_blocks
Args:
s1: a string
s2: another string
n: an int for the n in n-gram
Returns:
set:
"""
... | [
"def",
"__matches",
"(",
"s1",
",",
"s2",
",",
"ngrams_fn",
",",
"n",
"=",
"3",
")",
":",
"ngrams1",
",",
"ngrams2",
"=",
"set",
"(",
"ngrams_fn",
"(",
"s1",
",",
"n",
"=",
"n",
")",
")",
",",
"set",
"(",
"ngrams_fn",
"(",
"s2",
",",
"n",
"="... | 26 | 0.00232 |
def makedev(self, tarinfo, targetpath):
"""Make a character or block device called targetpath.
"""
if not hasattr(os, "mknod") or not hasattr(os, "makedev"):
raise ExtractError("special devices not supported by system")
mode = tarinfo.mode
if tarinfo.isblk():
... | [
"def",
"makedev",
"(",
"self",
",",
"tarinfo",
",",
"targetpath",
")",
":",
"if",
"not",
"hasattr",
"(",
"os",
",",
"\"mknod\"",
")",
"or",
"not",
"hasattr",
"(",
"os",
",",
"\"makedev\"",
")",
":",
"raise",
"ExtractError",
"(",
"\"special devices not supp... | 34.285714 | 0.004057 |
def parse_pseudo_nth(self, sel, m, has_selector, iselector):
"""Parse `nth` pseudo."""
mdict = m.groupdict()
if mdict.get('pseudo_nth_child'):
postfix = '_child'
else:
postfix = '_type'
mdict['name'] = util.lower(css_unescape(mdict['name']))
conte... | [
"def",
"parse_pseudo_nth",
"(",
"self",
",",
"sel",
",",
"m",
",",
"has_selector",
",",
"iselector",
")",
":",
"mdict",
"=",
"m",
".",
"groupdict",
"(",
")",
"if",
"mdict",
".",
"get",
"(",
"'pseudo_nth_child'",
")",
":",
"postfix",
"=",
"'_child'",
"e... | 36.517241 | 0.004138 |
def _list_tables(self, max_results=None, marker=None, timeout=None, _context=None):
'''
Returns a list of tables under the specified account. Makes a single list
request to the service. Used internally by the list_tables method.
:param int max_results:
The maximum number of... | [
"def",
"_list_tables",
"(",
"self",
",",
"max_results",
"=",
"None",
",",
"marker",
"=",
"None",
",",
"timeout",
"=",
"None",
",",
"_context",
"=",
"None",
")",
":",
"request",
"=",
"HTTPRequest",
"(",
")",
"request",
".",
"method",
"=",
"'GET'",
"requ... | 50.514286 | 0.003885 |
def sanitize_http_headers(client, event):
"""
Sanitizes http request/response headers
:param client: an ElasticAPM client
:param event: a transaction or error event
:return: The modified event
"""
# request headers
try:
headers = event["context"]["request"]["headers"]
ev... | [
"def",
"sanitize_http_headers",
"(",
"client",
",",
"event",
")",
":",
"# request headers",
"try",
":",
"headers",
"=",
"event",
"[",
"\"context\"",
"]",
"[",
"\"request\"",
"]",
"[",
"\"headers\"",
"]",
"event",
"[",
"\"context\"",
"]",
"[",
"\"request\"",
... | 27.956522 | 0.001504 |
def _at_least_x_are_true(a, b, x):
"""At least `x` of `a` and `b` `Tensors` are true."""
match = tf.equal(a, b)
match = tf.cast(match, tf.int32)
return tf.greater_equal(tf.reduce_sum(match), x) | [
"def",
"_at_least_x_are_true",
"(",
"a",
",",
"b",
",",
"x",
")",
":",
"match",
"=",
"tf",
".",
"equal",
"(",
"a",
",",
"b",
")",
"match",
"=",
"tf",
".",
"cast",
"(",
"match",
",",
"tf",
".",
"int32",
")",
"return",
"tf",
".",
"greater_equal",
... | 39.4 | 0.024876 |
def create_sns_topic(self, region):
"""Creates an SNS topic if needed. Returns the ARN if the created SNS topic
Args:
region (str): Region name
Returns:
`str`
"""
sns = self.session.client('sns', region_name=region)
self.log.info('Creating SNS t... | [
"def",
"create_sns_topic",
"(",
"self",
",",
"region",
")",
":",
"sns",
"=",
"self",
".",
"session",
".",
"client",
"(",
"'sns'",
",",
"region_name",
"=",
"region",
")",
"self",
".",
"log",
".",
"info",
"(",
"'Creating SNS topic for {}/{}'",
".",
"format",... | 33 | 0.005698 |
def get_nodes(self, request):
"""
Return menu's node for authors
"""
nodes = []
nodes.append(NavigationNode(_('Authors'),
reverse('zinnia:author_list'),
'authors'))
for author in Author.published.all(... | [
"def",
"get_nodes",
"(",
"self",
",",
"request",
")",
":",
"nodes",
"=",
"[",
"]",
"nodes",
".",
"append",
"(",
"NavigationNode",
"(",
"_",
"(",
"'Authors'",
")",
",",
"reverse",
"(",
"'zinnia:author_list'",
")",
",",
"'authors'",
")",
")",
"for",
"aut... | 39.923077 | 0.003766 |
def _find_template(self, template, tree, blocks, with_filename,
source, comment):
"""
If tree is true, then will display the track of template extend or include
"""
from uliweb import application
from uliweb.core.template import _format_code
de... | [
"def",
"_find_template",
"(",
"self",
",",
"template",
",",
"tree",
",",
"blocks",
",",
"with_filename",
",",
"source",
",",
"comment",
")",
":",
"from",
"uliweb",
"import",
"application",
"from",
"uliweb",
".",
"core",
".",
"template",
"import",
"_format_co... | 35.043478 | 0.002414 |
def send_to_contact(self, obj_id, contact_id):
"""
Send email to a specific contact
:param obj_id: int
:param contact_id: int
:return: dict|str
"""
response = self._client.session.post(
'{url}/{id}/send/contact/{contact_id}'.format(
ur... | [
"def",
"send_to_contact",
"(",
"self",
",",
"obj_id",
",",
"contact_id",
")",
":",
"response",
"=",
"self",
".",
"_client",
".",
"session",
".",
"post",
"(",
"'{url}/{id}/send/contact/{contact_id}'",
".",
"format",
"(",
"url",
"=",
"self",
".",
"endpoint_url",... | 30.785714 | 0.004505 |
def filters(self):
"""
Returns the list of base filters.
:return: the filter list
:rtype: list
"""
objects = javabridge.get_env().get_object_array_elements(
javabridge.call(self.jobject, "getFilters", "()[Lweka/filters/Filter;"))
result = []
f... | [
"def",
"filters",
"(",
"self",
")",
":",
"objects",
"=",
"javabridge",
".",
"get_env",
"(",
")",
".",
"get_object_array_elements",
"(",
"javabridge",
".",
"call",
"(",
"self",
".",
"jobject",
",",
"\"getFilters\"",
",",
"\"()[Lweka/filters/Filter;\"",
")",
")"... | 30.384615 | 0.007371 |
def list_zones(verbose=True, installed=False, configured=False, hide_global=True):
'''
List all zones
verbose : boolean
display additional zone information
installed : boolean
include installed zones in output
configured : boolean
include configured zones in output
hide_... | [
"def",
"list_zones",
"(",
"verbose",
"=",
"True",
",",
"installed",
"=",
"False",
",",
"configured",
"=",
"False",
",",
"hide_global",
"=",
"True",
")",
":",
"zones",
"=",
"{",
"}",
"## fetch zones",
"header",
"=",
"'zoneid:zonename:state:zonepath:uuid:brand:ip-... | 28.916667 | 0.002091 |
def get_serializer_context(self):
"""Adds ``election_day`` to serializer context."""
context = super(StateMixin, self).get_serializer_context()
context["election_date"] = self.kwargs["date"]
return context | [
"def",
"get_serializer_context",
"(",
"self",
")",
":",
"context",
"=",
"super",
"(",
"StateMixin",
",",
"self",
")",
".",
"get_serializer_context",
"(",
")",
"context",
"[",
"\"election_date\"",
"]",
"=",
"self",
".",
"kwargs",
"[",
"\"date\"",
"]",
"return... | 46.6 | 0.008439 |
def _ProcessCompletedRequests(self, notification):
"""Does the actual processing of the completed requests."""
# First ensure that client messages are all removed. NOTE: We make a new
# queue manager here because we want only the client messages to be removed
# ASAP. This must happen before we actually ... | [
"def",
"_ProcessCompletedRequests",
"(",
"self",
",",
"notification",
")",
":",
"# First ensure that client messages are all removed. NOTE: We make a new",
"# queue manager here because we want only the client messages to be removed",
"# ASAP. This must happen before we actually run the flow to ... | 38.767241 | 0.009107 |
def add_filepath(self, filepath, fullpath, copy=False):
"""
Bespoke function to add filepath & fullpath to manifest
object without hashing. Can defer hashing until all files are
added. Hashing all at once is much faster as overhead for
threading is spread over all files
"... | [
"def",
"add_filepath",
"(",
"self",
",",
"filepath",
",",
"fullpath",
",",
"copy",
"=",
"False",
")",
":",
"# Ignore directories",
"if",
"os",
".",
"path",
".",
"isdir",
"(",
"fullpath",
")",
":",
"return",
"False",
"# Ignore anything matching the ignore pattern... | 33.5 | 0.001813 |
def raise_405(instance):
"""Abort the current request with a 405 (Method Not Allowed) response
code. Sets the ``Allow`` response header to the return value of the
:func:`Resource.get_allowed_methods` function.
:param instance: Resource instance (used to access the response)
:type instance: :class:`... | [
"def",
"raise_405",
"(",
"instance",
")",
":",
"instance",
".",
"response",
".",
"status",
"=",
"405",
"instance",
".",
"response",
".",
"headers",
"[",
"'Allow'",
"]",
"=",
"instance",
".",
"get_allowed_methods",
"(",
")",
"raise",
"ResponseException",
"(",... | 47.166667 | 0.001733 |
def renameMenu( self ):
"""
Prompts the user to supply a new name for the menu.
"""
item = self.uiMenuTREE.currentItem()
name, accepted = QInputDialog.getText( self,
'Rename Menu',
... | [
"def",
"renameMenu",
"(",
"self",
")",
":",
"item",
"=",
"self",
".",
"uiMenuTREE",
".",
"currentItem",
"(",
")",
"name",
",",
"accepted",
"=",
"QInputDialog",
".",
"getText",
"(",
"self",
",",
"'Rename Menu'",
",",
"'Name:'",
",",
"QLineEdit",
".",
"Nor... | 38.846154 | 0.015474 |
def androlyze_main(session, filename):
"""
Start an interactive shell
:param session: Session file to load
:param filename: File to analyze, can be APK or DEX (or ODEX)
"""
from androguard.core.androconf import ANDROGUARD_VERSION, CONF
from IPython.terminal.embed import InteractiveShellEmbe... | [
"def",
"androlyze_main",
"(",
"session",
",",
"filename",
")",
":",
"from",
"androguard",
".",
"core",
".",
"androconf",
"import",
"ANDROGUARD_VERSION",
",",
"CONF",
"from",
"IPython",
".",
"terminal",
".",
"embed",
"import",
"InteractiveShellEmbed",
"from",
"tr... | 33.77551 | 0.000881 |
def __getCashToBuyStock(self):
''' calculate the amount of money to buy stock '''
account=self.__strategy.getAccountCopy()
if (account.buyingPower >= account.getTotalValue() / self.__buyingRatio):
return account.getTotalValue() / self.__buyingRatio
else:
return 0 | [
"def",
"__getCashToBuyStock",
"(",
"self",
")",
":",
"account",
"=",
"self",
".",
"__strategy",
".",
"getAccountCopy",
"(",
")",
"if",
"(",
"account",
".",
"buyingPower",
">=",
"account",
".",
"getTotalValue",
"(",
")",
"/",
"self",
".",
"__buyingRatio",
"... | 39.125 | 0.0125 |
def build_where_stmt(self, ident, filters, q_filters=None, source_class=None):
"""
construct a where statement from some filters
"""
if q_filters is not None:
stmts = self._parse_q_filters(ident, q_filters, source_class)
if stmts:
self._ast['where'... | [
"def",
"build_where_stmt",
"(",
"self",
",",
"ident",
",",
"filters",
",",
"q_filters",
"=",
"None",
",",
"source_class",
"=",
"None",
")",
":",
"if",
"q_filters",
"is",
"not",
"None",
":",
"stmts",
"=",
"self",
".",
"_parse_q_filters",
"(",
"ident",
","... | 43.933333 | 0.003712 |
def ivorn_present(session, ivorn):
"""
Predicate, returns whether the IVORN is in the database.
"""
return bool(
session.query(Voevent.id).filter(Voevent.ivorn == ivorn).count()) | [
"def",
"ivorn_present",
"(",
"session",
",",
"ivorn",
")",
":",
"return",
"bool",
"(",
"session",
".",
"query",
"(",
"Voevent",
".",
"id",
")",
".",
"filter",
"(",
"Voevent",
".",
"ivorn",
"==",
"ivorn",
")",
".",
"count",
"(",
")",
")"
] | 32.833333 | 0.00495 |
def get_init(self):
"""Return initial name.
"""
suffix = self._separator + "%s" % str(self._counter_init)
return self._base_name + suffix | [
"def",
"get_init",
"(",
"self",
")",
":",
"suffix",
"=",
"self",
".",
"_separator",
"+",
"\"%s\"",
"%",
"str",
"(",
"self",
".",
"_counter_init",
")",
"return",
"self",
".",
"_base_name",
"+",
"suffix"
] | 27.5 | 0.011765 |
def get_function_node(self, node):
"""Process a function node.
:sig: (Union[ast.FunctionDef, ast.AsyncFunctionDef]) -> FunctionNode
:param node: Node to process.
:return: Generated function node in stub tree.
"""
decorators = []
for d in node.decorator_list:
... | [
"def",
"get_function_node",
"(",
"self",
",",
"node",
")",
":",
"decorators",
"=",
"[",
"]",
"for",
"d",
"in",
"node",
".",
"decorator_list",
":",
"if",
"hasattr",
"(",
"d",
",",
"\"id\"",
")",
":",
"decorators",
".",
"append",
"(",
"d",
".",
"id",
... | 35.606383 | 0.002326 |
def penalize_boundary_complexity(shp, w=20, mask=None, C=0.5):
"""Encourage the boundaries of an image to have less variation and of color C.
Args:
shp: shape of T("input") because this may not be known.
w: width of boundary to penalize. Ignored if mask is set.
mask: mask describing what area should be... | [
"def",
"penalize_boundary_complexity",
"(",
"shp",
",",
"w",
"=",
"20",
",",
"mask",
"=",
"None",
",",
"C",
"=",
"0.5",
")",
":",
"def",
"inner",
"(",
"T",
")",
":",
"arr",
"=",
"T",
"(",
"\"input\"",
")",
"# print shp",
"if",
"mask",
"is",
"None",... | 23.703704 | 0.012012 |
def compute_difficulty(
bomb_delay: int,
parent_header: BlockHeader,
timestamp: int) -> int:
"""
https://github.com/ethereum/EIPs/issues/100
"""
parent_timestamp = parent_header.timestamp
validate_gt(timestamp, parent_timestamp, title="Header.timestamp")
parent_difficult... | [
"def",
"compute_difficulty",
"(",
"bomb_delay",
":",
"int",
",",
"parent_header",
":",
"BlockHeader",
",",
"timestamp",
":",
"int",
")",
"->",
"int",
":",
"parent_timestamp",
"=",
"parent_header",
".",
"timestamp",
"validate_gt",
"(",
"timestamp",
",",
"parent_t... | 30.361111 | 0.001773 |
def methods(self):
"""
Returns all documented methods as `pydoc.Function` objects in
the class, sorted alphabetically with `__init__` always coming
first.
Unfortunately, this also includes class methods.
"""
p = lambda o: (isinstance(o, Function)
... | [
"def",
"methods",
"(",
"self",
")",
":",
"p",
"=",
"lambda",
"o",
":",
"(",
"isinstance",
"(",
"o",
",",
"Function",
")",
"and",
"o",
".",
"method",
"and",
"self",
".",
"module",
".",
"_docfilter",
"(",
"o",
")",
")",
"return",
"filter",
"(",
"p"... | 35.5 | 0.006865 |
def _get_binding_info(hostheader='', ipaddress='*', port=80):
'''
Combine the host header, IP address, and TCP port into bindingInformation format.
'''
ret = r'{0}:{1}:{2}'.format(ipaddress, port, hostheader.replace(' ', ''))
return ret | [
"def",
"_get_binding_info",
"(",
"hostheader",
"=",
"''",
",",
"ipaddress",
"=",
"'*'",
",",
"port",
"=",
"80",
")",
":",
"ret",
"=",
"r'{0}:{1}:{2}'",
".",
"format",
"(",
"ipaddress",
",",
"port",
",",
"hostheader",
".",
"replace",
"(",
"' '",
",",
"'... | 35.857143 | 0.007782 |
def get_names_in_namespace_page(namespace_id, offset, count, proxy=None, hostport=None):
"""
Get a page of names in a namespace
Returns the list of names on success
Returns {'error': ...} on error
"""
assert proxy or hostport, 'Need proxy or hostport'
if proxy is None:
proxy = connec... | [
"def",
"get_names_in_namespace_page",
"(",
"namespace_id",
",",
"offset",
",",
"count",
",",
"proxy",
"=",
"None",
",",
"hostport",
"=",
"None",
")",
":",
"assert",
"proxy",
"or",
"hostport",
",",
"'Need proxy or hostport'",
"if",
"proxy",
"is",
"None",
":",
... | 30.571429 | 0.004074 |
def bestfit_func(self, bestfit_x):
"""
Returns bestfit_function
args:
bestfit_x: scalar, array_like
x value
return: scalar, array_like
bestfit y value
"""
if not self.done_bestfit:
raise KeyError("Do do_bestfit first")
... | [
"def",
"bestfit_func",
"(",
"self",
",",
"bestfit_x",
")",
":",
"if",
"not",
"self",
".",
"done_bestfit",
":",
"raise",
"KeyError",
"(",
"\"Do do_bestfit first\"",
")",
"bestfit_y",
"=",
"self",
".",
"fit_args",
"[",
"1",
"]",
"*",
"(",
"bestfit_x",
"**",
... | 28.714286 | 0.004819 |
def update_enum_option(self, enum_option, params={}, **options):
"""Updates an existing enum option. Enum custom fields require at least one enabled enum option.
Returns the full record of the updated enum option.
Parameters
----------
enum_option : {Id} Globally uniqu... | [
"def",
"update_enum_option",
"(",
"self",
",",
"enum_option",
",",
"params",
"=",
"{",
"}",
",",
"*",
"*",
"options",
")",
":",
"path",
"=",
"\"/enum_options/%s\"",
"%",
"(",
"enum_option",
")",
"return",
"self",
".",
"client",
".",
"put",
"(",
"path",
... | 50.066667 | 0.00915 |
def segment(self,
length,
direction=None,
final_width=None,
final_distance=None,
axis_offset=0,
layer=0,
datatype=0):
"""
Add a straight section to the path.
Parameters
------... | [
"def",
"segment",
"(",
"self",
",",
"length",
",",
"direction",
"=",
"None",
",",
"final_width",
"=",
"None",
",",
"final_distance",
"=",
"None",
",",
"axis_offset",
"=",
"0",
",",
"layer",
"=",
"0",
",",
"datatype",
"=",
"0",
")",
":",
"if",
"direct... | 38.606061 | 0.002296 |
def add_ckpt_state(self, ckpt_id, ckpt_state):
"""Add the checkpoint state message to be sent back the stmgr
:param ckpt_id: The id of the checkpoint
:ckpt_state: The checkpoint state
"""
# first flush any buffered tuples
self._flush_remaining()
msg = ckptmgr_pb2.StoreInstanceStateCheckpoin... | [
"def",
"add_ckpt_state",
"(",
"self",
",",
"ckpt_id",
",",
"ckpt_state",
")",
":",
"# first flush any buffered tuples",
"self",
".",
"_flush_remaining",
"(",
")",
"msg",
"=",
"ckptmgr_pb2",
".",
"StoreInstanceStateCheckpoint",
"(",
")",
"istate",
"=",
"ckptmgr_pb2",... | 35.214286 | 0.001976 |
def _search_metrics_and_metadata(self, metadata_endpoint, query,
order_by=None, offset=None,
limit=None, timeout=None):
"""
generic function for elasticsearch queries; can search metrics,
dimensions, metrictimeseries b... | [
"def",
"_search_metrics_and_metadata",
"(",
"self",
",",
"metadata_endpoint",
",",
"query",
",",
"order_by",
"=",
"None",
",",
"offset",
"=",
"None",
",",
"limit",
"=",
"None",
",",
"timeout",
"=",
"None",
")",
":",
"_logger",
".",
"debug",
"(",
"'Performi... | 49.59375 | 0.002472 |
def tf_demo_loss(self, states, actions, terminal, reward, internals, update, reference=None):
"""
Extends the q-model loss via the dqfd large-margin loss.
"""
embedding = self.network.apply(x=states, internals=internals, update=update)
deltas = list()
for name in sorted(... | [
"def",
"tf_demo_loss",
"(",
"self",
",",
"states",
",",
"actions",
",",
"terminal",
",",
"reward",
",",
"internals",
",",
"update",
",",
"reference",
"=",
"None",
")",
":",
"embedding",
"=",
"self",
".",
"network",
".",
"apply",
"(",
"x",
"=",
"states"... | 50.55 | 0.005337 |
def opt(self, x_init, f_fp=None, f=None, fp=None):
"""
Run the TNC optimizer
"""
tnc_rcstrings = ['Local minimum', 'Converged', 'XConverged', 'Maximum number of f evaluations reached',
'Line search failed', 'Function is constant']
assert f_fp != None, "TNC requires... | [
"def",
"opt",
"(",
"self",
",",
"x_init",
",",
"f_fp",
"=",
"None",
",",
"f",
"=",
"None",
",",
"fp",
"=",
"None",
")",
":",
"tnc_rcstrings",
"=",
"[",
"'Local minimum'",
",",
"'Converged'",
",",
"'XConverged'",
",",
"'Maximum number of f evaluations reached... | 35.666667 | 0.006826 |
def available_languages(self):
"""
Returns a list of languages providing collection of stop words.
"""
available_languages = getattr(self, '_available_languages', None)
if available_languages:
return available_languages
try:
languages = os.listdir(... | [
"def",
"available_languages",
"(",
"self",
")",
":",
"available_languages",
"=",
"getattr",
"(",
"self",
",",
"'_available_languages'",
",",
"None",
")",
"if",
"available_languages",
":",
"return",
"available_languages",
"try",
":",
"languages",
"=",
"os",
".",
... | 41.2 | 0.003165 |
def _get_input_buffer_cursor_line(self):
""" Returns the text of the line of the input buffer that contains the
cursor, or None if there is no such line.
"""
prompt = self._get_input_buffer_cursor_prompt()
if prompt is None:
return None
else:
c... | [
"def",
"_get_input_buffer_cursor_line",
"(",
"self",
")",
":",
"prompt",
"=",
"self",
".",
"_get_input_buffer_cursor_prompt",
"(",
")",
"if",
"prompt",
"is",
"None",
":",
"return",
"None",
"else",
":",
"cursor",
"=",
"self",
".",
"_control",
".",
"textCursor",... | 40.363636 | 0.004405 |
def validate(cls, keystr):
""" raises cls.Bad if keys has errors """
if "#{" in keystr:
# it's a template with keys vars
keys = cls.from_template(keystr)
for k in keys:
cls.validate_one(cls.extract(k))
else:
# plain keys str
... | [
"def",
"validate",
"(",
"cls",
",",
"keystr",
")",
":",
"if",
"\"#{\"",
"in",
"keystr",
":",
"# it's a template with keys vars",
"keys",
"=",
"cls",
".",
"from_template",
"(",
"keystr",
")",
"for",
"k",
"in",
"keys",
":",
"cls",
".",
"validate_one",
"(",
... | 34 | 0.005731 |
def sender(address, use_queue=True, **kwds):
"""
:param str address: a pair (ip_address, port) to pass to socket.connect
:param bool use_queue: if True, run the connection in a different thread
with a queue
"""
return QueuedSender(address, **kwds) if use_queue else Sender(address) | [
"def",
"sender",
"(",
"address",
",",
"use_queue",
"=",
"True",
",",
"*",
"*",
"kwds",
")",
":",
"return",
"QueuedSender",
"(",
"address",
",",
"*",
"*",
"kwds",
")",
"if",
"use_queue",
"else",
"Sender",
"(",
"address",
")"
] | 43.285714 | 0.003236 |
def set_monitored_resource_attributes(span):
"""Set labels to span that can be used for tracing.
:param span: Span object
"""
resource = monitored_resource.get_instance()
if resource is not None:
resource_type = resource.get_type()
resource_labels = resource.get_labels()
if ... | [
"def",
"set_monitored_resource_attributes",
"(",
"span",
")",
":",
"resource",
"=",
"monitored_resource",
".",
"get_instance",
"(",
")",
"if",
"resource",
"is",
"not",
"None",
":",
"resource_type",
"=",
"resource",
".",
"get_type",
"(",
")",
"resource_labels",
"... | 48.948718 | 0.000514 |
def createRepo(self):
"""
Creates the repository for all the data we've just downloaded.
"""
repo = datarepo.SqlDataRepository(self.repoPath)
repo.open("w")
repo.initialise()
referenceSet = references.HtslibReferenceSet("GRCh37-subset")
referenceSet.popul... | [
"def",
"createRepo",
"(",
"self",
")",
":",
"repo",
"=",
"datarepo",
".",
"SqlDataRepository",
"(",
"self",
".",
"repoPath",
")",
"repo",
".",
"open",
"(",
"\"w\"",
")",
"repo",
".",
"initialise",
"(",
")",
"referenceSet",
"=",
"references",
".",
"Htslib... | 41.913043 | 0.001014 |
def set_type(self):
"""
Set the node type
"""
if self.device_info['type'] == 'Router':
self.node['type'] = self.device_info['model'].upper()
else:
self.node['type'] = self.device_info['type'] | [
"def",
"set_type",
"(",
"self",
")",
":",
"if",
"self",
".",
"device_info",
"[",
"'type'",
"]",
"==",
"'Router'",
":",
"self",
".",
"node",
"[",
"'type'",
"]",
"=",
"self",
".",
"device_info",
"[",
"'model'",
"]",
".",
"upper",
"(",
")",
"else",
":... | 31 | 0.007843 |
def dependents_of(self, address):
"""Returns the addresses of the targets that depend on the target at `address`.
This method asserts that the address given is actually in the BuildGraph.
:API: public
"""
assert address in self._target_by_address, (
'Cannot retrieve dependents of {address} b... | [
"def",
"dependents_of",
"(",
"self",
",",
"address",
")",
":",
"assert",
"address",
"in",
"self",
".",
"_target_by_address",
",",
"(",
"'Cannot retrieve dependents of {address} because it is not in the BuildGraph.'",
".",
"format",
"(",
"address",
"=",
"address",
")",
... | 36.333333 | 0.006711 |
def near_to_position(self, position, max_distance):
'''Returns true iff the record is within max_distance of the given position.
Note: chromosome name not checked, so that's up to you to do first.'''
end = self.ref_end_pos()
return self.POS <= position <= end or abs(position - self.POS) ... | [
"def",
"near_to_position",
"(",
"self",
",",
"position",
",",
"max_distance",
")",
":",
"end",
"=",
"self",
".",
"ref_end_pos",
"(",
")",
"return",
"self",
".",
"POS",
"<=",
"position",
"<=",
"end",
"or",
"abs",
"(",
"position",
"-",
"self",
".",
"POS"... | 74 | 0.010695 |
def template(filename, **locals):
''' Returns '''
path = 'templates/{}'.format(filename)
with open(path) as source:
code = compile(source.read(), path, 'exec')
global_vars = {'t': t,
'f': f,
'e': e,
'escape': html.escape,
... | [
"def",
"template",
"(",
"filename",
",",
"*",
"*",
"locals",
")",
":",
"path",
"=",
"'templates/{}'",
".",
"format",
"(",
"filename",
")",
"with",
"open",
"(",
"path",
")",
"as",
"source",
":",
"code",
"=",
"compile",
"(",
"source",
".",
"read",
"(",... | 35.083333 | 0.002315 |
def find_equivalent_sites(self, site):
"""
Finds all symmetrically equivalent sites for a particular site
Args:
site (PeriodicSite): A site in the structure
Returns:
([PeriodicSite]): List of all symmetrically equivalent sites.
"""
for sites in s... | [
"def",
"find_equivalent_sites",
"(",
"self",
",",
"site",
")",
":",
"for",
"sites",
"in",
"self",
".",
"equivalent_sites",
":",
"if",
"site",
"in",
"sites",
":",
"return",
"sites",
"raise",
"ValueError",
"(",
"\"Site not in structure\"",
")"
] | 29.133333 | 0.004435 |
def encode(cls, value):
"""
take an integer and turn it into a string representation
to write into redis.
:param value: int
:return: str
"""
try:
coerced = int(value)
if coerced + 0 == value:
return repr(coerced)
e... | [
"def",
"encode",
"(",
"cls",
",",
"value",
")",
":",
"try",
":",
"coerced",
"=",
"int",
"(",
"value",
")",
"if",
"coerced",
"+",
"0",
"==",
"value",
":",
"return",
"repr",
"(",
"coerced",
")",
"except",
"(",
"TypeError",
",",
"ValueError",
")",
":"... | 23.117647 | 0.00489 |
def acquire(self, timeout=10):
"""Acquire the lock.
:params timeout: Maximum time to wait before returning. `None` means
forever, any other value equal or greater than 0 is
the number of seconds.
:returns: True if the lock has been acquired, Fal... | [
"def",
"acquire",
"(",
"self",
",",
"timeout",
"=",
"10",
")",
":",
"stop",
"=",
"(",
"tenacity",
".",
"stop_never",
"if",
"timeout",
"is",
"None",
"else",
"tenacity",
".",
"stop_after_delay",
"(",
"timeout",
")",
")",
"def",
"wait",
"(",
"previous_attem... | 35.719298 | 0.000956 |
def prefixsearch(self, prefix, results=10):
""" Perform a prefix search using the provided prefix string
Args:
prefix (str): Prefix string to use for search
results (int): Number of pages with the prefix to return
Returns:
list: List of pa... | [
"def",
"prefixsearch",
"(",
"self",
",",
"prefix",
",",
"results",
"=",
"10",
")",
":",
"self",
".",
"_check_query",
"(",
"prefix",
",",
"\"Prefix must be specified\"",
")",
"query_params",
"=",
"{",
"\"list\"",
":",
"\"prefixsearch\"",
",",
"\"pssearch\"",
":... | 39.866667 | 0.001633 |
def insured_losses(losses, deductible, insured_limit):
"""
:param losses: an array of ground-up loss ratios
:param float deductible: the deductible limit in fraction form
:param float insured_limit: the insured limit in fraction form
Compute insured losses for the given asset and losses, from the p... | [
"def",
"insured_losses",
"(",
"losses",
",",
"deductible",
",",
"insured_limit",
")",
":",
"return",
"numpy",
".",
"piecewise",
"(",
"losses",
",",
"[",
"losses",
"<",
"deductible",
",",
"losses",
">",
"insured_limit",
"]",
",",
"[",
"0",
",",
"insured_lim... | 39.3 | 0.001242 |
def smpar(C):
"""Get the running effective SM parameters."""
m2 = C['m2'].real
Lambda = C['Lambda'].real
v = (sqrt(2 * m2 / Lambda) + 3 * m2**(3 / 2) /
(sqrt(2) * Lambda**(5 / 2)) * C['phi'])
GF = 1 / (sqrt(2) * v**2) # TODO
Mh2 = 2 * m2 * (1 - m2 / Lambda * (3 * C['phi'] - 4 * Lambda ... | [
"def",
"smpar",
"(",
"C",
")",
":",
"m2",
"=",
"C",
"[",
"'m2'",
"]",
".",
"real",
"Lambda",
"=",
"C",
"[",
"'Lambda'",
"]",
".",
"real",
"v",
"=",
"(",
"sqrt",
"(",
"2",
"*",
"m2",
"/",
"Lambda",
")",
"+",
"3",
"*",
"m2",
"**",
"(",
"3",... | 35.538462 | 0.00158 |
def rollback(self):
"""Rolls back the current transaction.
This method has necessary side-effects:
- Sets the current transaction's ID to None.
"""
try:
# No need to use the response it contains nothing.
self._client._datastore_api.rollback(self.project,... | [
"def",
"rollback",
"(",
"self",
")",
":",
"try",
":",
"# No need to use the response it contains nothing.",
"self",
".",
"_client",
".",
"_datastore_api",
".",
"rollback",
"(",
"self",
".",
"project",
",",
"self",
".",
"_id",
")",
"finally",
":",
"super",
"(",... | 34.285714 | 0.004057 |
def copy_to_region(self, region):
"""
Create a new key pair of the same new in another region.
Note that the new key pair will use a different ssh
cert than the this key pair. After doing the copy,
you will need to save the material associated with the
new key pair (use ... | [
"def",
"copy_to_region",
"(",
"self",
",",
"region",
")",
":",
"if",
"region",
".",
"name",
"==",
"self",
".",
"region",
":",
"raise",
"BotoClientError",
"(",
"'Unable to copy to the same Region'",
")",
"conn_params",
"=",
"self",
".",
"connection",
".",
"get_... | 42.2 | 0.002317 |
def get_resource_references(self, generated_cfn_resources, supported_resource_refs):
"""
Constructs the list of supported resource references by going through the list of CFN resources generated
by to_cloudformation() on this SAM resource. Each SAM resource must provide a map of properties that ... | [
"def",
"get_resource_references",
"(",
"self",
",",
"generated_cfn_resources",
",",
"supported_resource_refs",
")",
":",
"if",
"supported_resource_refs",
"is",
"None",
":",
"raise",
"ValueError",
"(",
"\"`supported_resource_refs` object is required\"",
")",
"# Create a map of... | 56.916667 | 0.007199 |
def init_widget(self):
""" Initialize the underlying widget.
This reads all items declared in the enamldef block for this node
and sets only the values that have been specified. All other values
will be left as default. Doing it this way makes atom to only create
the ... | [
"def",
"init_widget",
"(",
"self",
")",
":",
"super",
"(",
"AndroidView",
",",
"self",
")",
".",
"init_widget",
"(",
")",
"# Initialize the widget by updating only the members that",
"# have read expressions declared. This saves a lot of time and",
"# simplifies widget initializa... | 43.272727 | 0.010277 |
def PackageVariable(key, help, default, searchfunc=None):
# NB: searchfunc is currently undocumented and unsupported
"""
The input parameters describe a 'package list' option, thus they
are returned with the correct converter and validator appended. The
result is usable for input to opts.Add() .
... | [
"def",
"PackageVariable",
"(",
"key",
",",
"help",
",",
"default",
",",
"searchfunc",
"=",
"None",
")",
":",
"# NB: searchfunc is currently undocumented and unsupported",
"help",
"=",
"'\\n '",
".",
"join",
"(",
"(",
"help",
",",
"'( yes | no | /path/to/%s )'",
"... | 40.8 | 0.00639 |
def masked_relative_local_attention_1d(q,
k,
v,
block_length=128,
make_image_summary=False,
dropout_rate=0.,
... | [
"def",
"masked_relative_local_attention_1d",
"(",
"q",
",",
"k",
",",
"v",
",",
"block_length",
"=",
"128",
",",
"make_image_summary",
"=",
"False",
",",
"dropout_rate",
"=",
"0.",
",",
"heads_share_relative_embedding",
"=",
"False",
",",
"add_relative_to_values",
... | 46.813397 | 0.003403 |
def lap(self):
"""Calculate lap time.
Returns:
float: Lap time. The duration from the previous call of ``lap()``
or initialization at first call.
float: Total time. The duration from initialization.
"""
now = time.time()
lap_time = now -... | [
"def",
"lap",
"(",
"self",
")",
":",
"now",
"=",
"time",
".",
"time",
"(",
")",
"lap_time",
"=",
"now",
"-",
"self",
".",
"lap_time",
"total_time",
"=",
"now",
"-",
"self",
".",
"start",
"self",
".",
"lap_time",
"=",
"now",
"return",
"lap_time",
",... | 30.214286 | 0.004587 |
def merge_pmag_recs(self, old_recs):
"""
Takes in a list of dictionaries old_recs and returns a list of
dictionaries where every dictionary in the returned list has the
same keys as all the others.
Parameters
----------
old_recs : list of dictionaries to fix
... | [
"def",
"merge_pmag_recs",
"(",
"self",
",",
"old_recs",
")",
":",
"recs",
"=",
"{",
"}",
"recs",
"=",
"deepcopy",
"(",
"old_recs",
")",
"headers",
"=",
"[",
"]",
"for",
"rec",
"in",
"recs",
":",
"for",
"key",
"in",
"list",
"(",
"rec",
".",
"keys",
... | 29.692308 | 0.002509 |
def check(self):
""" Check if data and third party tools are available
:raises: RuntimeError
"""
#for path in self.path.values():
# if not os.path.exists(path):
# raise RuntimeError("File '{}' is missing".format(path))
for tool in ('cd-hit', 'prank', ... | [
"def",
"check",
"(",
"self",
")",
":",
"#for path in self.path.values():",
"# if not os.path.exists(path):",
"# raise RuntimeError(\"File '{}' is missing\".format(path))",
"for",
"tool",
"in",
"(",
"'cd-hit'",
",",
"'prank'",
",",
"'hmmbuild'",
",",
"'hmmpress'",
",... | 38.076923 | 0.00789 |
def changelist(self):
"""Which :class:`.Changelist` is this revision in"""
if self._changelist:
return self._changelist
if self._p4dict['change'] == 'default':
return Default(connection=self._connection)
else:
return Changelist(str(self._p4dict['chang... | [
"def",
"changelist",
"(",
"self",
")",
":",
"if",
"self",
".",
"_changelist",
":",
"return",
"self",
".",
"_changelist",
"if",
"self",
".",
"_p4dict",
"[",
"'change'",
"]",
"==",
"'default'",
":",
"return",
"Default",
"(",
"connection",
"=",
"self",
".",... | 37.222222 | 0.005831 |
def getTarget(iid):
'''
A static method which returns a Target object identified by
iid. Returns None if a Target object was not found
'''
db = getDataCommunicator()
verbose('Loading target with id {}'.format(iid))
data = db.getTarget(iid)
if dat... | [
"def",
"getTarget",
"(",
"iid",
")",
":",
"db",
"=",
"getDataCommunicator",
"(",
")",
"verbose",
"(",
"'Loading target with id {}'",
".",
"format",
"(",
"iid",
")",
")",
"data",
"=",
"db",
".",
"getTarget",
"(",
"iid",
")",
"if",
"data",
":",
"verbose",
... | 31.6875 | 0.005747 |
def _maybe_wait_for_initializing_instance(instance):
"""Starts instance if it's stopped, no-op otherwise."""
if not instance:
return
if instance.state['Name'] == 'initializing':
while True:
print(f"Waiting for {instance} to leave state 'initializing'.")
instance.reload()
if instance.s... | [
"def",
"_maybe_wait_for_initializing_instance",
"(",
"instance",
")",
":",
"if",
"not",
"instance",
":",
"return",
"if",
"instance",
".",
"state",
"[",
"'Name'",
"]",
"==",
"'initializing'",
":",
"while",
"True",
":",
"print",
"(",
"f\"Waiting for {instance} to l... | 28.384615 | 0.020997 |
def execute(self, env, args):
""" Displays task time left in minutes.
`env`
Runtime ``Environment`` instance.
`args`
Arguments object from arg parser.
"""
msg = u'Time Left: {0}m' if not args.short else '{0}'
mins = max(0, sel... | [
"def",
"execute",
"(",
"self",
",",
"env",
",",
"args",
")",
":",
"msg",
"=",
"u'Time Left: {0}m'",
"if",
"not",
"args",
".",
"short",
"else",
"'{0}'",
"mins",
"=",
"max",
"(",
"0",
",",
"self",
".",
"total_duration",
"-",
"env",
".",
"task",
".",
... | 32.083333 | 0.005051 |
def rebin2x2(a):
"""
Wrapper around rebin that actually rebins 2 by 2
"""
inshape = np.array(a.shape)
if not (inshape % 2 == np.zeros(2)).all(): # Modulo check to see if size is even
raise RuntimeError, "I want even image shapes !"
return rebin(a, inshape/2) | [
"def",
"rebin2x2",
"(",
"a",
")",
":",
"inshape",
"=",
"np",
".",
"array",
"(",
"a",
".",
"shape",
")",
"if",
"not",
"(",
"inshape",
"%",
"2",
"==",
"np",
".",
"zeros",
"(",
"2",
")",
")",
".",
"all",
"(",
")",
":",
"# Modulo check to see if size... | 32.333333 | 0.016722 |
def file_contents(self, filename, binary=False):
"""Return the file for a given filename.
If you want binary content use ``mode='rb'``.
"""
if binary:
mode = 'rb'
else:
mode = 'r'
try:
with open(filename, mode) as f:
r... | [
"def",
"file_contents",
"(",
"self",
",",
"filename",
",",
"binary",
"=",
"False",
")",
":",
"if",
"binary",
":",
"mode",
"=",
"'rb'",
"else",
":",
"mode",
"=",
"'r'",
"try",
":",
"with",
"open",
"(",
"filename",
",",
"mode",
")",
"as",
"f",
":",
... | 26.666667 | 0.004831 |
def get_fieldsets(self, fieldsets=None):
"""
This method returns a generator which yields fieldset instances.
The method uses the optional fieldsets argument to generate fieldsets for.
If no fieldsets argument is passed, the class property ``fieldsets`` is used.
When generating... | [
"def",
"get_fieldsets",
"(",
"self",
",",
"fieldsets",
"=",
"None",
")",
":",
"fieldsets",
"=",
"fieldsets",
"or",
"self",
".",
"fieldsets",
"if",
"not",
"fieldsets",
":",
"raise",
"StopIteration",
"# Search for primary marker in at least one of the fieldset kwargs.",
... | 40.1875 | 0.005315 |
def SavGol(y, win=49):
'''
Subtracts a second order Savitsky-Golay filter with window size `win`
and returns the result. This acts as a high pass filter.
'''
if len(y) >= win:
return y - savgol_filter(y, win, 2) + np.nanmedian(y)
else:
return y | [
"def",
"SavGol",
"(",
"y",
",",
"win",
"=",
"49",
")",
":",
"if",
"len",
"(",
"y",
")",
">=",
"win",
":",
"return",
"y",
"-",
"savgol_filter",
"(",
"y",
",",
"win",
",",
"2",
")",
"+",
"np",
".",
"nanmedian",
"(",
"y",
")",
"else",
":",
"re... | 25.090909 | 0.003497 |
def __log_density_single(x, mean, covar):
""" This is just a test function to calculate
the normal density at x given mean and covariance matrix.
Note: this function is not efficient, so
_log_multivariate_density is recommended for use.
"""
n_dim = mean.shape[0]
dx = x - ... | [
"def",
"__log_density_single",
"(",
"x",
",",
"mean",
",",
"covar",
")",
":",
"n_dim",
"=",
"mean",
".",
"shape",
"[",
"0",
"]",
"dx",
"=",
"x",
"-",
"mean",
"covar_inv",
"=",
"scipy",
".",
"linalg",
".",
"inv",
"(",
"covar",
")",
"covar_det",
"=",... | 31.5 | 0.00578 |
def resolve_doc(cls, manifest, target_doc_name, target_doc_package,
current_project, node_package):
"""Resolve the given documentation. This follows the same algorithm as
resolve_ref except the is_enabled checks are unnecessary as docs are
always enabled.
"""
... | [
"def",
"resolve_doc",
"(",
"cls",
",",
"manifest",
",",
"target_doc_name",
",",
"target_doc_package",
",",
"current_project",
",",
"node_package",
")",
":",
"if",
"target_doc_package",
"is",
"not",
"None",
":",
"return",
"manifest",
".",
"find_docs_by_name",
"(",
... | 45.352941 | 0.003812 |
def process_async_task(headers, request_body):
"""Process an Async task and execute the requested function."""
async_options = json.loads(request_body)
async = async_from_options(async_options)
_log_task_info(headers,
extra_task_info=async.get_options().get('_extra_task_info'))
... | [
"def",
"process_async_task",
"(",
"headers",
",",
"request_body",
")",
":",
"async_options",
"=",
"json",
".",
"loads",
"(",
"request_body",
")",
"async",
"=",
"async_from_options",
"(",
"async_options",
")",
"_log_task_info",
"(",
"headers",
",",
"extra_task_info... | 32.285714 | 0.012903 |
def entropy(self):
"""
For each string compute its Shannon entropy, if the string is empty the entropy is 0.
:returns: an H2OFrame of Shannon entropies.
"""
fr = H2OFrame._expr(expr=ExprNode("entropy", self))
fr._ex._cache.nrows = self.nrow
fr._ex._cache.ncol = s... | [
"def",
"entropy",
"(",
"self",
")",
":",
"fr",
"=",
"H2OFrame",
".",
"_expr",
"(",
"expr",
"=",
"ExprNode",
"(",
"\"entropy\"",
",",
"self",
")",
")",
"fr",
".",
"_ex",
".",
"_cache",
".",
"nrows",
"=",
"self",
".",
"nrow",
"fr",
".",
"_ex",
".",... | 33.7 | 0.008671 |
def init_app(self, app):
"""Configure a Flask application to use this ZODB extension."""
assert 'zodb' not in app.extensions, \
'app already initiated for zodb'
app.extensions['zodb'] = _ZODBState(self, app)
app.teardown_request(self.close_db) | [
"def",
"init_app",
"(",
"self",
",",
"app",
")",
":",
"assert",
"'zodb'",
"not",
"in",
"app",
".",
"extensions",
",",
"'app already initiated for zodb'",
"app",
".",
"extensions",
"[",
"'zodb'",
"]",
"=",
"_ZODBState",
"(",
"self",
",",
"app",
")",
"app",
... | 47.5 | 0.006897 |
def __focus(self, item):
"""Called when focus item has changed"""
cols = self.__get_display_columns()
for col in cols:
self.__event_info =(col,item)
self.event_generate('<<TreeviewInplaceEdit>>')
if col in self._inplace_widgets:
w = self._inpla... | [
"def",
"__focus",
"(",
"self",
",",
"item",
")",
":",
"cols",
"=",
"self",
".",
"__get_display_columns",
"(",
")",
"for",
"col",
"in",
"cols",
":",
"self",
".",
"__event_info",
"=",
"(",
"col",
",",
"item",
")",
"self",
".",
"event_generate",
"(",
"'... | 43.5 | 0.011257 |
def get(self, queue_name, task_id):
"""
Pops a specific task off the queue by identifier.
:param queue_name: The name of the queue. Usually handled by the
``Gator`` instance.
:type queue_name: string
:param task_id: The identifier of the task.
:type task_id:... | [
"def",
"get",
"(",
"self",
",",
"queue_name",
",",
"task_id",
")",
":",
"self",
".",
"conn",
".",
"lrem",
"(",
"queue_name",
",",
"1",
",",
"task_id",
")",
"data",
"=",
"self",
".",
"conn",
".",
"get",
"(",
"task_id",
")",
"if",
"data",
":",
"sel... | 27.5 | 0.003515 |
def strip_escape(string='', encoding="utf-8"): # pylint: disable=redefined-outer-name
"""
Strip escape characters from string.
:param string: string to work on
:param encoding: string name of the encoding used.
:return: stripped string
"""
matches = []
try:
if hasattr(string, "... | [
"def",
"strip_escape",
"(",
"string",
"=",
"''",
",",
"encoding",
"=",
"\"utf-8\"",
")",
":",
"# pylint: disable=redefined-outer-name",
"matches",
"=",
"[",
"]",
"try",
":",
"if",
"hasattr",
"(",
"string",
",",
"\"decode\"",
")",
":",
"string",
"=",
"string"... | 33.357143 | 0.005203 |
def update_kwargs(self, request, **kwargs):
"""
Hook for adding data to the context before
rendering a template.
:param kwargs: The current context keyword arguments.
:param request: The current request object.
"""
if not 'base' in kwargs:
kwargs['bas... | [
"def",
"update_kwargs",
"(",
"self",
",",
"request",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"'base'",
"in",
"kwargs",
":",
"kwargs",
"[",
"'base'",
"]",
"=",
"self",
".",
"base",
"if",
"request",
".",
"is_ajax",
"(",
")",
"or",
"request",
... | 32.642857 | 0.006383 |
def generate_one_of(self):
"""
Means that value have to be valid by only one of those definitions. It can't be valid
by two or more of them.
.. code-block:: python
{
'oneOf': [
{'type': 'number', 'multipleOf': 3},
{'ty... | [
"def",
"generate_one_of",
"(",
"self",
")",
":",
"self",
".",
"l",
"(",
"'{variable}_one_of_count = 0'",
")",
"for",
"definition_item",
"in",
"self",
".",
"_definition",
"[",
"'oneOf'",
"]",
":",
"# When we know it's failing (one of means exactly once), we do not need to ... | 43.851852 | 0.005785 |
def update(self):
"""This method should be called to update associated Posts
It will call content-specific methods:
_get_data() to obtain list of entries
_store_post() to store obtained entry object
_get_data_source_url() to get an URL to identify Posts from this D... | [
"def",
"update",
"(",
"self",
")",
":",
"#get the raw data",
"# self.posts.all().delete() # TODO: handle in update_posts if source changes without deleting every time",
"data",
"=",
"self",
".",
"_get_data",
"(",
")",
"#iterate through them and for each item",
"msg",
"=",
... | 46.72 | 0.00755 |
def get_map_config_ids(value, maps, default_map_name=None, default_instances=None):
"""
From a value, which can be a string, a iterable of strings, or MapConfigId tuple(s), generates a list of MapConfigId
tuples with expanded groups, listing all input or configured instances, and sorted by map and configura... | [
"def",
"get_map_config_ids",
"(",
"value",
",",
"maps",
",",
"default_map_name",
"=",
"None",
",",
"default_instances",
"=",
"None",
")",
":",
"input_ids",
"=",
"InputConfigIdList",
"(",
"value",
",",
"map_name",
"=",
"default_map_name",
",",
"instances",
"=",
... | 71.875 | 0.007725 |
def get_selected_rows(self):
"""
:returns:
A list containing a :obj:`Gtk.TreePath` for each selected row
and a :obj:`Gtk.TreeModel` or :obj:`None`.
:rtype: (:obj:`Gtk.TreeModel`, [:obj:`Gtk.TreePath`])
{{ docs }}
"""
rows, model = super(TreeSele... | [
"def",
"get_selected_rows",
"(",
"self",
")",
":",
"rows",
",",
"model",
"=",
"super",
"(",
"TreeSelection",
",",
"self",
")",
".",
"get_selected_rows",
"(",
")",
"return",
"(",
"model",
",",
"rows",
")"
] | 28.384615 | 0.005249 |
def pad_to_size(data, shape, value=0.0):
"""
This is similar to `pad`, except you specify the final shape of the array.
Parameters
----------
data : ndarray
Numpy array of any dimension and type.
shape : tuple
Final shape of padded array. Should be tuple of length ``data.ndim``.... | [
"def",
"pad_to_size",
"(",
"data",
",",
"shape",
",",
"value",
"=",
"0.0",
")",
":",
"shape",
"=",
"[",
"data",
".",
"shape",
"[",
"i",
"]",
"if",
"shape",
"[",
"i",
"]",
"==",
"-",
"1",
"else",
"shape",
"[",
"i",
"]",
"for",
"i",
"in",
"rang... | 32.659091 | 0.000676 |
def parse_responsive_length(responsive_length):
"""
Takes a string containing a length definition in pixels or percent and parses it to obtain
a computational length. It returns a tuple where the first element is the length in pixels and
the second element is its length in percent divided by 100.
No... | [
"def",
"parse_responsive_length",
"(",
"responsive_length",
")",
":",
"responsive_length",
"=",
"responsive_length",
".",
"strip",
"(",
")",
"if",
"responsive_length",
".",
"endswith",
"(",
"'px'",
")",
":",
"return",
"(",
"int",
"(",
"responsive_length",
".",
"... | 49.538462 | 0.004573 |
def setAutoRaise(self, state):
"""
Sets whether or not this combo box should automatically
raise up.
:param state | <bool>
"""
self._autoRaise = state
self.setMouseTracking(state)
try:
self.lineEdit().setVisible(not state)
... | [
"def",
"setAutoRaise",
"(",
"self",
",",
"state",
")",
":",
"self",
".",
"_autoRaise",
"=",
"state",
"self",
".",
"setMouseTracking",
"(",
"state",
")",
"try",
":",
"self",
".",
"lineEdit",
"(",
")",
".",
"setVisible",
"(",
"not",
"state",
")",
"except... | 26.769231 | 0.008333 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.