text stringlengths 75 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 0.18 |
|---|---|---|---|
def __get_config_table_options(conf_file_options):
""" Get all table options from the config file
:type conf_file_options: ordereddict
:param conf_file_options: Dictionary with all config file options
:returns: ordereddict -- E.g. {'table_name': {}}
"""
options = ordereddict()
if not conf_... | [
"def",
"__get_config_table_options",
"(",
"conf_file_options",
")",
":",
"options",
"=",
"ordereddict",
"(",
")",
"if",
"not",
"conf_file_options",
":",
"return",
"options",
"for",
"table_name",
"in",
"conf_file_options",
"[",
"'tables'",
"]",
":",
"options",
"[",... | 41.25 | 0.000987 |
def _calculate_states(self, solution, t, step, int_step):
"""!
@brief Calculates new state of each oscillator in the network.
@param[in] solution (solve_type): Type solver of the differential equation.
@param[in] t (double): Current time of simulation.
@param[in] s... | [
"def",
"_calculate_states",
"(",
"self",
",",
"solution",
",",
"t",
",",
"step",
",",
"int_step",
")",
":",
"next_excitatory",
"=",
"[",
"0.0",
"]",
"*",
"self",
".",
"_num_osc",
"next_inhibitory",
"=",
"[",
"0.0",
"]",
"*",
"self",
".",
"_num_osc",
"n... | 54.5625 | 0.01913 |
def search_user(self, user_name, quiet=False, limit=9):
"""Search user by user name.
:params user_name: user name.
:params quiet: automatically select the best one.
:params limit: user count returned by weapi.
:return: a User object.
"""
result = self.search(use... | [
"def",
"search_user",
"(",
"self",
",",
"user_name",
",",
"quiet",
"=",
"False",
",",
"limit",
"=",
"9",
")",
":",
"result",
"=",
"self",
".",
"search",
"(",
"user_name",
",",
"search_type",
"=",
"1002",
",",
"limit",
"=",
"limit",
")",
"if",
"result... | 38.409091 | 0.002309 |
def percentile_for_in(self, leaderboard_name, member):
'''
Retrieve the percentile for a member in the named leaderboard.
@param leaderboard_name [String] Name of the leaderboard.
@param member [String] Member name.
@return the percentile for a member in the named leaderboard.
... | [
"def",
"percentile_for_in",
"(",
"self",
",",
"leaderboard_name",
",",
"member",
")",
":",
"if",
"not",
"self",
".",
"check_member_in",
"(",
"leaderboard_name",
",",
"member",
")",
":",
"return",
"None",
"responses",
"=",
"self",
".",
"redis_connection",
".",
... | 32 | 0.002247 |
def set_tags(name=None,
tags=None,
call=None,
location=None,
instance_id=None,
resource_id=None,
kwargs=None): # pylint: disable=W0613
'''
Set tags for a resource. Normally a VM name or instance_id is passed in,
but a resource_id... | [
"def",
"set_tags",
"(",
"name",
"=",
"None",
",",
"tags",
"=",
"None",
",",
"call",
"=",
"None",
",",
"location",
"=",
"None",
",",
"instance_id",
"=",
"None",
",",
"resource_id",
"=",
"None",
",",
"kwargs",
"=",
"None",
")",
":",
"# pylint: disable=W0... | 30.663462 | 0.00243 |
def guess(filename, fallback='application/octet-stream'):
"""
Using the mimetypes library, guess the mimetype and
encoding for a given *filename*. If the mimetype
cannot be guessed, *fallback* is assumed instead.
:param filename: Filename- can be absolute path.
:param fallback: A fallback mimet... | [
"def",
"guess",
"(",
"filename",
",",
"fallback",
"=",
"'application/octet-stream'",
")",
":",
"guessed",
",",
"encoding",
"=",
"mimetypes",
".",
"guess_type",
"(",
"filename",
",",
"strict",
"=",
"False",
")",
"if",
"guessed",
"is",
"None",
":",
"return",
... | 36.615385 | 0.002049 |
def _numpy_index_by_percentile(self, data, percentile):
""" Calculate percentile of numpy stack and return the index of the chosen pixel.
numpy percentile function is used with one of the following interpolations {'linear', 'lower', 'higher',
'midpoint', 'nearest'}
"""
d... | [
"def",
"_numpy_index_by_percentile",
"(",
"self",
",",
"data",
",",
"percentile",
")",
":",
"data_perc_low",
"=",
"np",
".",
"nanpercentile",
"(",
"data",
",",
"percentile",
",",
"axis",
"=",
"0",
",",
"interpolation",
"=",
"self",
".",
"interpolation",
")",... | 43.9375 | 0.009749 |
def _draw(self, mode, vertex_list=None):
'''Draw vertices in the domain.
If `vertex_list` is not specified, all vertices in the domain are
drawn. This is the most efficient way to render primitives.
If `vertex_list` specifies a `VertexList`, only primitives in that
list will b... | [
"def",
"_draw",
"(",
"self",
",",
"mode",
",",
"vertex_list",
"=",
"None",
")",
":",
"glPushClientAttrib",
"(",
"GL_CLIENT_VERTEX_ARRAY_BIT",
")",
"for",
"buffer",
",",
"attributes",
"in",
"self",
".",
"buffer_attributes",
":",
"buffer",
".",
"bind",
"(",
")... | 37.695652 | 0.001124 |
def _call(self, x):
"""Return ``self(x)``."""
with self.op.mutex:
x = np.moveaxis(x, 0, -1)
return pyshearlab.SLshearadjoint2D(x, self.op.shearlet_system) | [
"def",
"_call",
"(",
"self",
",",
"x",
")",
":",
"with",
"self",
".",
"op",
".",
"mutex",
":",
"x",
"=",
"np",
".",
"moveaxis",
"(",
"x",
",",
"0",
",",
"-",
"1",
")",
"return",
"pyshearlab",
".",
"SLshearadjoint2D",
"(",
"x",
",",
"self",
".",... | 38 | 0.010309 |
def homepage():
"""Renders the homepage."""
if current_user.is_authenticated():
if not login_fresh():
logging.debug('User needs a fresh token')
abort(login.needs_refresh())
auth.claim_invitations(current_user)
build_list = operations.UserOps(current_user.get_id()).g... | [
"def",
"homepage",
"(",
")",
":",
"if",
"current_user",
".",
"is_authenticated",
"(",
")",
":",
"if",
"not",
"login_fresh",
"(",
")",
":",
"logging",
".",
"debug",
"(",
"'User needs a fresh token'",
")",
"abort",
"(",
"login",
".",
"needs_refresh",
"(",
")... | 33.785714 | 0.002058 |
def _interpret_angle(name, angle_object, angle_float, unit='degrees'):
"""Return an angle in radians from one of two arguments.
It is common for Skyfield routines to accept both an argument like
`alt` that takes an Angle object as well as an `alt_degrees` that
can be given a bare float or a sexagesimal... | [
"def",
"_interpret_angle",
"(",
"name",
",",
"angle_object",
",",
"angle_float",
",",
"unit",
"=",
"'degrees'",
")",
":",
"if",
"angle_object",
"is",
"not",
"None",
":",
"if",
"isinstance",
"(",
"angle_object",
",",
"Angle",
")",
":",
"return",
"angle_object... | 48.647059 | 0.001186 |
def _parse_networks(networks):
'''
Common logic for parsing the networks
'''
networks = salt.utils.args.split_input(networks or [])
if not networks:
networks = {}
else:
# We don't want to recurse the repack, as the values of the kwargs
# being passed when connecting to th... | [
"def",
"_parse_networks",
"(",
"networks",
")",
":",
"networks",
"=",
"salt",
".",
"utils",
".",
"args",
".",
"split_input",
"(",
"networks",
"or",
"[",
"]",
")",
"if",
"not",
"networks",
":",
"networks",
"=",
"{",
"}",
"else",
":",
"# We don't want to r... | 38.246377 | 0.000369 |
def create_from_hdu(cls, hdu, ebins):
""" Creates and returns an HpxMap object from a FITS HDU.
hdu : The FITS
ebins : Energy bin edges [optional]
"""
hpx = HPX.create_from_hdu(hdu, ebins)
colnames = hdu.columns.names
cnames = []
if hpx.conv.convname ... | [
"def",
"create_from_hdu",
"(",
"cls",
",",
"hdu",
",",
"ebins",
")",
":",
"hpx",
"=",
"HPX",
".",
"create_from_hdu",
"(",
"hdu",
",",
"ebins",
")",
"colnames",
"=",
"hdu",
".",
"columns",
".",
"names",
"cnames",
"=",
"[",
"]",
"if",
"hpx",
".",
"co... | 35.148148 | 0.002051 |
def determine_sender(mail, action='reply'):
"""
Inspect a given mail to reply/forward/bounce and find the most appropriate
account to act from and construct a suitable From-Header to use.
:param mail: the email to inspect
:type mail: `email.message.Message`
:param action: intended use case: one... | [
"def",
"determine_sender",
"(",
"mail",
",",
"action",
"=",
"'reply'",
")",
":",
"assert",
"action",
"in",
"[",
"'reply'",
",",
"'forward'",
",",
"'bounce'",
"]",
"# get accounts",
"my_accounts",
"=",
"settings",
".",
"get_accounts",
"(",
")",
"assert",
"my_... | 42.571429 | 0.00041 |
def _make_value(self, value):
"""
Constructs a _child_spec value from a native Python data type, or
an appropriate Asn1Value object
:param value:
A native Python value, or some child of Asn1Value
:return:
An object of type _child_spec
"""
... | [
"def",
"_make_value",
"(",
"self",
",",
"value",
")",
":",
"if",
"isinstance",
"(",
"value",
",",
"self",
".",
"_child_spec",
")",
":",
"new_value",
"=",
"value",
"elif",
"issubclass",
"(",
"self",
".",
"_child_spec",
",",
"Any",
")",
":",
"if",
"isins... | 34.851852 | 0.00155 |
def doPointsExperiment(cellDimensions, cellCoordinateOffsets):
"""
Learn a set of objects. Then try to recognize each object. Output an
interactive visualization.
@param cellDimensions (pair)
The cell dimensions of each module
@param cellCoordinateOffsets (sequence)
The "cellCoordinateOffsets" parameter... | [
"def",
"doPointsExperiment",
"(",
"cellDimensions",
",",
"cellCoordinateOffsets",
")",
":",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"\"traces\"",
")",
":",
"os",
".",
"makedirs",
"(",
"\"traces\"",
")",
"locationConfigs",
"=",
"[",
"]",
"for",
... | 31.206897 | 0.009106 |
def get_share_info(self, grantee_type=None, grantee_id=None,
grantee_name=None, owner=None, owner_type='name'):
"""
:returns: list of dict representing shares informations
"""
params = {}
if grantee_type:
if 'grantee' not in params.keys():
... | [
"def",
"get_share_info",
"(",
"self",
",",
"grantee_type",
"=",
"None",
",",
"grantee_id",
"=",
"None",
",",
"grantee_name",
"=",
"None",
",",
"owner",
"=",
"None",
",",
"owner_type",
"=",
"'name'",
")",
":",
"params",
"=",
"{",
"}",
"if",
"grantee_type"... | 37.514286 | 0.002227 |
def main():
"""
Main application loop.
"""
env = os.environ
try:
host = env['SYSLOG_SERVER']
port = int(env['SYSLOG_PORT'])
socktype = socket.SOCK_DGRAM if env['SYSLOG_PROTO'] == 'udp' \
else socket.SOCK_STREAM
except KeyError:
sys.exit("SYSLOG_SERVE... | [
"def",
"main",
"(",
")",
":",
"env",
"=",
"os",
".",
"environ",
"try",
":",
"host",
"=",
"env",
"[",
"'SYSLOG_SERVER'",
"]",
"port",
"=",
"int",
"(",
"env",
"[",
"'SYSLOG_PORT'",
"]",
")",
"socktype",
"=",
"socket",
".",
"SOCK_DGRAM",
"if",
"env",
... | 26.69697 | 0.001095 |
def cmd_batch(
self,
tgt,
fun,
arg=(),
tgt_type='glob',
ret='',
kwarg=None,
batch='10%',
**kwargs):
'''
Iteratively execute a command on subsets of minions at a time
The function signatur... | [
"def",
"cmd_batch",
"(",
"self",
",",
"tgt",
",",
"fun",
",",
"arg",
"=",
"(",
")",
",",
"tgt_type",
"=",
"'glob'",
",",
"ret",
"=",
"''",
",",
"kwarg",
"=",
"None",
",",
"batch",
"=",
"'10%'",
",",
"*",
"*",
"kwargs",
")",
":",
"# Late import - ... | 31.732394 | 0.000861 |
def desk_locale(self, locale):
"""Return the Desk-style locale for locale."""
locale = locale.lower().replace('-', '_')
return self.vendor_locale_map.get(locale, locale) | [
"def",
"desk_locale",
"(",
"self",
",",
"locale",
")",
":",
"locale",
"=",
"locale",
".",
"lower",
"(",
")",
".",
"replace",
"(",
"'-'",
",",
"'_'",
")",
"return",
"self",
".",
"vendor_locale_map",
".",
"get",
"(",
"locale",
",",
"locale",
")"
] | 38 | 0.010309 |
def check_image_in_spain(glance_url, id, token):
"""It obtain if the image is in Spain
:param glance_url: the sdc url
:param token: the valid token
:param id: image id
"""
url = glance_url + '/images?property-sdc_aware=true'
headers = {'Accept': 'application/json', 'X-Auth-Token': token}
... | [
"def",
"check_image_in_spain",
"(",
"glance_url",
",",
"id",
",",
"token",
")",
":",
"url",
"=",
"glance_url",
"+",
"'/images?property-sdc_aware=true'",
"headers",
"=",
"{",
"'Accept'",
":",
"'application/json'",
",",
"'X-Auth-Token'",
":",
"token",
"}",
"try",
... | 35.055556 | 0.001543 |
def parse_chains(data):
"""
Parse the chain definitions.
"""
chains = odict()
for line in data.splitlines(True):
m = re_chain.match(line)
if m:
policy = None
if m.group(2) != '-':
policy = m.group(2)
chains[m.group(1)] = {
... | [
"def",
"parse_chains",
"(",
"data",
")",
":",
"chains",
"=",
"odict",
"(",
")",
"for",
"line",
"in",
"data",
".",
"splitlines",
"(",
"True",
")",
":",
"m",
"=",
"re_chain",
".",
"match",
"(",
"line",
")",
"if",
"m",
":",
"policy",
"=",
"None",
"i... | 26.235294 | 0.002165 |
def _qkey_to_ascii(event):
"""
(Try to) convert the Qt key event to the corresponding ASCII sequence for
the terminal. This works fine for standard alphanumerical characters, but
most other characters require terminal specific control_modifier sequences.
The conversion below works for TERM="linux' t... | [
"def",
"_qkey_to_ascii",
"(",
"event",
")",
":",
"if",
"sys",
".",
"platform",
"==",
"'darwin'",
":",
"control_modifier",
"=",
"QtCore",
".",
"Qt",
".",
"MetaModifier",
"else",
":",
"control_modifier",
"=",
"QtCore",
".",
"Qt",
".",
"ControlModifier",
"ctrl"... | 38.215054 | 0.000274 |
def run(self):
"""! @brief SWV reader thread routine.
Starts the probe receiving SWO data by calling DebugProbe.swo_start(). For as long as the
thread runs, it reads SWO data from the probe and passes it to the SWO parser created in
init(). When the thread is signaled to stop, i... | [
"def",
"run",
"(",
"self",
")",
":",
"# Stop SWO first in case the probe already had it started. Ignore if this fails.",
"try",
":",
"self",
".",
"_session",
".",
"probe",
".",
"swo_stop",
"(",
")",
"except",
"exceptions",
".",
"ProbeError",
":",
"pass",
"self",
"."... | 39.409091 | 0.011261 |
def as_dict(self):
"""Package up the public attributes as a dict."""
attrs = vars(self)
return {key: attrs[key] for key in attrs if not key.startswith('_')} | [
"def",
"as_dict",
"(",
"self",
")",
":",
"attrs",
"=",
"vars",
"(",
"self",
")",
"return",
"{",
"key",
":",
"attrs",
"[",
"key",
"]",
"for",
"key",
"in",
"attrs",
"if",
"not",
"key",
".",
"startswith",
"(",
"'_'",
")",
"}"
] | 44.25 | 0.011111 |
def splitArgs(self, args):
"""Returns list of arguments parsed by shlex.split() or
raise UsageError if failed"""
try:
return shlex.split(args)
except ValueError as e:
raise UsageError(e) | [
"def",
"splitArgs",
"(",
"self",
",",
"args",
")",
":",
"try",
":",
"return",
"shlex",
".",
"split",
"(",
"args",
")",
"except",
"ValueError",
"as",
"e",
":",
"raise",
"UsageError",
"(",
"e",
")"
] | 33.714286 | 0.008264 |
def setSpeedFactor(self, typeID, factor):
"""setSpeedFactor(string, double) -> None
.
"""
self._connection._sendDoubleCmd(
tc.CMD_SET_VEHICLETYPE_VARIABLE, tc.VAR_SPEED_FACTOR, typeID, factor) | [
"def",
"setSpeedFactor",
"(",
"self",
",",
"typeID",
",",
"factor",
")",
":",
"self",
".",
"_connection",
".",
"_sendDoubleCmd",
"(",
"tc",
".",
"CMD_SET_VEHICLETYPE_VARIABLE",
",",
"tc",
".",
"VAR_SPEED_FACTOR",
",",
"typeID",
",",
"factor",
")"
] | 33 | 0.012658 |
def pad_array(in1):
"""
Simple convenience function to pad arrays for linear convolution.
INPUTS:
in1 (no default): Input array which is to be padded.
OUTPUTS:
out1 Padded version of the input.
"""
padded_size = 2*np.array(in1.shape)
out1 = np.zeros([padd... | [
"def",
"pad_array",
"(",
"in1",
")",
":",
"padded_size",
"=",
"2",
"*",
"np",
".",
"array",
"(",
"in1",
".",
"shape",
")",
"out1",
"=",
"np",
".",
"zeros",
"(",
"[",
"padded_size",
"[",
"0",
"]",
",",
"padded_size",
"[",
"1",
"]",
"]",
")",
"ou... | 25.647059 | 0.00885 |
def _calculate_german_iban_checksum(iban,
iban_fields='DEkkbbbbbbbbcccccccccc'):
"""
Calculate the checksam of the German IBAN format.
Examples
--------
>>> iban = 'DE41500105170123456789'
>>> _calculate_german_iban_checksum(iban)
'41'
"""
... | [
"def",
"_calculate_german_iban_checksum",
"(",
"iban",
",",
"iban_fields",
"=",
"'DEkkbbbbbbbbcccccccccc'",
")",
":",
"number",
"=",
"[",
"value",
"for",
"field_type",
",",
"value",
"in",
"zip",
"(",
"iban_fields",
",",
"iban",
")",
"if",
"field_type",
"in",
"... | 36.16 | 0.001078 |
def read(self, file_or_filename):
""" Parses a PSAT data file and returns a case object
file_or_filename: File object or path to PSAT data file
return: Case object
"""
self.file_or_filename = file_or_filename
logger.info("Parsing PSAT case file [%s]." % file_or_... | [
"def",
"read",
"(",
"self",
",",
"file_or_filename",
")",
":",
"self",
".",
"file_or_filename",
"=",
"file_or_filename",
"logger",
".",
"info",
"(",
"\"Parsing PSAT case file [%s].\"",
"%",
"file_or_filename",
")",
"t0",
"=",
"time",
".",
"time",
"(",
")",
"se... | 34.354167 | 0.001179 |
def _add_default_exposure_class(layer):
"""The layer doesn't have an exposure class, we need to add it.
:param layer: The vector layer.
:type layer: QgsVectorLayer
"""
layer.startEditing()
field = create_field_from_definition(exposure_class_field)
layer.keywords['inasafe_fields'][exposure_... | [
"def",
"_add_default_exposure_class",
"(",
"layer",
")",
":",
"layer",
".",
"startEditing",
"(",
")",
"field",
"=",
"create_field_from_definition",
"(",
"exposure_class_field",
")",
"layer",
".",
"keywords",
"[",
"'inasafe_fields'",
"]",
"[",
"exposure_class_field",
... | 31.25 | 0.001294 |
def capture_update_records(records):
"""Writes all updated configuration info to DynamoDB"""
for rec in records:
data = cloudwatch.get_historical_base_info(rec)
group = describe_group(rec, cloudwatch.get_region(rec))
if len(group) > 1:
raise Exception(f'[X] Multiple groups f... | [
"def",
"capture_update_records",
"(",
"records",
")",
":",
"for",
"rec",
"in",
"records",
":",
"data",
"=",
"cloudwatch",
".",
"get_historical_base_info",
"(",
"rec",
")",
"group",
"=",
"describe_group",
"(",
"rec",
",",
"cloudwatch",
".",
"get_region",
"(",
... | 35.611111 | 0.002278 |
def run_script(self,
script,
in_shell=True,
echo=None,
note=None,
loglevel=logging.DEBUG):
"""Run the passed-in string as a script on the target's command line.
@param script: String representing the script. It will be de-indented
... | [
"def",
"run_script",
"(",
"self",
",",
"script",
",",
"in_shell",
"=",
"True",
",",
"echo",
"=",
"None",
",",
"note",
"=",
"None",
",",
"loglevel",
"=",
"logging",
".",
"DEBUG",
")",
":",
"shutit",
"=",
"self",
".",
"shutit",
"shutit",
".",
"handle_n... | 52.803922 | 0.028436 |
def make_nxml_from_text(text):
"""Return raw text wrapped in NXML structure.
Parameters
----------
text : str
The raw text content to be wrapped in an NXML structure.
Returns
-------
nxml_str : str
The NXML string wrapping the raw text input.
"""
text = _escape_xml(... | [
"def",
"make_nxml_from_text",
"(",
"text",
")",
":",
"text",
"=",
"_escape_xml",
"(",
"text",
")",
"header",
"=",
"'<?xml version=\"1.0\" encoding=\"UTF-8\" ?>'",
"+",
"'<OAI-PMH><article><body><sec id=\"s1\"><p>'",
"footer",
"=",
"'</p></sec></body></article></OAI-PMH>'",
"n... | 27.789474 | 0.001832 |
def threshold(image, block_size=DEFAULT_BLOCKSIZE, mask=None):
"""Applies adaptive thresholding to the given image.
Args:
image: BGRA image.
block_size: optional int block_size to use for adaptive thresholding.
mask: optional mask.
Returns:
Thresholded image.
"""
if ... | [
"def",
"threshold",
"(",
"image",
",",
"block_size",
"=",
"DEFAULT_BLOCKSIZE",
",",
"mask",
"=",
"None",
")",
":",
"if",
"mask",
"is",
"None",
":",
"mask",
"=",
"np",
".",
"zeros",
"(",
"image",
".",
"shape",
"[",
":",
"2",
"]",
",",
"dtype",
"=",
... | 35.35 | 0.001377 |
def _get_pod_uid(self, labels):
"""
Return the id of a pod
:param labels:
:return: str or None
"""
namespace = CadvisorPrometheusScraperMixin._get_container_label(labels, "namespace")
pod_name = CadvisorPrometheusScraperMixin._get_container_label(labels, "pod_name... | [
"def",
"_get_pod_uid",
"(",
"self",
",",
"labels",
")",
":",
"namespace",
"=",
"CadvisorPrometheusScraperMixin",
".",
"_get_container_label",
"(",
"labels",
",",
"\"namespace\"",
")",
"pod_name",
"=",
"CadvisorPrometheusScraperMixin",
".",
"_get_container_label",
"(",
... | 43.777778 | 0.00995 |
def init_stash(stash_path, passphrase, passphrase_size, backend):
r"""Init a stash
`STASH_PATH` is the path to the storage endpoint. If this isn't supplied,
a default path will be used. In the path, you can specify a name
for the stash (which, if omitted, will default to `ghost`) like so:
`ghost in... | [
"def",
"init_stash",
"(",
"stash_path",
",",
"passphrase",
",",
"passphrase_size",
",",
"backend",
")",
":",
"stash_path",
"=",
"stash_path",
"or",
"STORAGE_DEFAULT_PATH_MAPPING",
"[",
"backend",
"]",
"click",
".",
"echo",
"(",
"'Stash: {0} at {1}'",
".",
"format"... | 38.935484 | 0.000404 |
def add(self, data):
"""
Add a single entry to field.
Entries can be added to a rule using the href of the element
or by loading the element directly. Element should be of type
:py:mod:`smc.elements.network`.
After modifying rule, call :py:meth:`~.save`.
Example... | [
"def",
"add",
"(",
"self",
",",
"data",
")",
":",
"if",
"self",
".",
"is_none",
"or",
"self",
".",
"is_any",
":",
"self",
".",
"clear",
"(",
")",
"self",
".",
"data",
"[",
"self",
".",
"typeof",
"]",
"=",
"[",
"]",
"try",
":",
"self",
".",
"g... | 31.677419 | 0.001976 |
def curated(name):
"""Download and return a path to a sample that is curated by the PyAV developers.
Data is handled by :func:`cached_download`.
"""
return cached_download('https://docs.mikeboers.com/pyav/samples/' + name,
os.path.join('pyav-curated', name.replace('/', os.pa... | [
"def",
"curated",
"(",
"name",
")",
":",
"return",
"cached_download",
"(",
"'https://docs.mikeboers.com/pyav/samples/'",
"+",
"name",
",",
"os",
".",
"path",
".",
"join",
"(",
"'pyav-curated'",
",",
"name",
".",
"replace",
"(",
"'/'",
",",
"os",
".",
"path",... | 40.25 | 0.009119 |
def remove(name, rc_file='~/.odoorpcrc'):
"""Remove the session configuration identified by `name`
from the `rc_file` file.
>>> import odoorpc
>>> odoorpc.session.remove('foo') # doctest: +SKIP
.. doctest::
:hide:
>>> import odoorpc
>>> session = '%s_session' % DB
... | [
"def",
"remove",
"(",
"name",
",",
"rc_file",
"=",
"'~/.odoorpcrc'",
")",
":",
"conf",
"=",
"ConfigParser",
"(",
")",
"conf",
".",
"read",
"(",
"[",
"os",
".",
"path",
".",
"expanduser",
"(",
"rc_file",
")",
"]",
")",
"if",
"not",
"conf",
".",
"has... | 29.375 | 0.001374 |
def delete_term(set_id, term_id, access_token):
"""Delete the given term."""
api_call('delete', 'sets/{}/terms/{}'.format(set_id, term_id), access_token=access_token) | [
"def",
"delete_term",
"(",
"set_id",
",",
"term_id",
",",
"access_token",
")",
":",
"api_call",
"(",
"'delete'",
",",
"'sets/{}/terms/{}'",
".",
"format",
"(",
"set_id",
",",
"term_id",
")",
",",
"access_token",
"=",
"access_token",
")"
] | 57.333333 | 0.011494 |
def str_to_etree(xml_str, encoding='utf-8'):
"""Deserialize API XML doc to an ElementTree.
Args:
xml_str: bytes
DataONE API XML doc
encoding: str
Decoder to use when converting the XML doc ``bytes`` to a Unicode str.
Returns:
ElementTree: Matching the API version of the ... | [
"def",
"str_to_etree",
"(",
"xml_str",
",",
"encoding",
"=",
"'utf-8'",
")",
":",
"parser",
"=",
"xml",
".",
"etree",
".",
"ElementTree",
".",
"XMLParser",
"(",
"encoding",
"=",
"encoding",
")",
"return",
"xml",
".",
"etree",
".",
"ElementTree",
".",
"fr... | 28.375 | 0.002132 |
def overlapping_spheres(shape: List[int], radius: int, porosity: float,
iter_max: int = 10, tol: float = 0.01):
r"""
Generate a packing of overlapping mono-disperse spheres
Parameters
----------
shape : list
The size of the image to generate in [Nx, Ny, Nz] where Ni ... | [
"def",
"overlapping_spheres",
"(",
"shape",
":",
"List",
"[",
"int",
"]",
",",
"radius",
":",
"int",
",",
"porosity",
":",
"float",
",",
"iter_max",
":",
"int",
"=",
"10",
",",
"tol",
":",
"float",
"=",
"0.01",
")",
":",
"shape",
"=",
"sp",
".",
... | 31.052632 | 0.001232 |
def sample(self, histogram_logits):
""" Sample from a greedy strategy with given q-value histogram """
histogram_probs = histogram_logits.exp() # Batch size * actions * atoms
atoms = self.support_atoms.view(1, 1, self.atoms) # Need to introduce two new dimensions
return (histogram_prob... | [
"def",
"sample",
"(",
"self",
",",
"histogram_logits",
")",
":",
"histogram_probs",
"=",
"histogram_logits",
".",
"exp",
"(",
")",
"# Batch size * actions * atoms",
"atoms",
"=",
"self",
".",
"support_atoms",
".",
"view",
"(",
"1",
",",
"1",
",",
"self",
"."... | 70.4 | 0.011236 |
def kullback_leibler(h1, h2): # 83 us @array, 109 us @list \w 100 bins
r"""
Kullback-Leibler divergence.
Compute how inefficient it would to be code one histogram into another.
Actually computes :math:`\frac{d_{KL}(h1, h2) + d_{KL}(h2, h1)}{2}` to achieve symmetry.
The Kullback-Leibler div... | [
"def",
"kullback_leibler",
"(",
"h1",
",",
"h2",
")",
":",
"# 83 us @array, 109 us @list \\w 100 bins",
"old_err_state",
"=",
"scipy",
".",
"seterr",
"(",
"divide",
"=",
"'raise'",
")",
"try",
":",
"h1",
",",
"h2",
"=",
"__prepare_histogram",
"(",
"h1",
",",
... | 29.574074 | 0.010303 |
def _finish_connection_action(self, action):
"""Finish a connection attempt
Args:
action (ConnectionAction): the action object describing what we are
connecting to and what the result of the operation was
"""
success = action.data['success']
conn_key... | [
"def",
"_finish_connection_action",
"(",
"self",
",",
"action",
")",
":",
"success",
"=",
"action",
".",
"data",
"[",
"'success'",
"]",
"conn_key",
"=",
"action",
".",
"data",
"[",
"'id'",
"]",
"if",
"self",
".",
"_get_connection_state",
"(",
"conn_key",
"... | 34.742857 | 0.0024 |
def compare_jsone_task_definition(parent_link, rebuilt_definitions):
"""Compare the json-e rebuilt task definition vs the runtime definition.
Args:
parent_link (LinkOfTrust): the parent link to test.
rebuilt_definitions (dict): the rebuilt task definitions.
Raises:
CoTError: on fai... | [
"def",
"compare_jsone_task_definition",
"(",
"parent_link",
",",
"rebuilt_definitions",
")",
":",
"diffs",
"=",
"[",
"]",
"for",
"compare_definition",
"in",
"rebuilt_definitions",
"[",
"'tasks'",
"]",
":",
"# Rebuilt decision tasks have an extra `taskId`; remove",
"if",
"... | 39.121212 | 0.001512 |
def get_network_settings():
'''
Return the contents of the global network script.
CLI Example:
.. code-block:: bash
salt '*' ip.get_network_settings
'''
skip_etc_default_networking = (
__grains__['osfullname'] == 'Ubuntu' and
int(__grains__['osrelease'].split('.')[0]) ... | [
"def",
"get_network_settings",
"(",
")",
":",
"skip_etc_default_networking",
"=",
"(",
"__grains__",
"[",
"'osfullname'",
"]",
"==",
"'Ubuntu'",
"and",
"int",
"(",
"__grains__",
"[",
"'osrelease'",
"]",
".",
"split",
"(",
"'.'",
")",
"[",
"0",
"]",
")",
">... | 28.395349 | 0.000792 |
def list_templates(self, extensions=None, filter_func=None):
"""Returns a list of templates for this environment. This requires
that the loader supports the loader's
:meth:`~BaseLoader.list_templates` method.
If there are other files in the template folder besides the
actual te... | [
"def",
"list_templates",
"(",
"self",
",",
"extensions",
"=",
"None",
",",
"filter_func",
"=",
"None",
")",
":",
"x",
"=",
"self",
".",
"loader",
".",
"list_templates",
"(",
")",
"if",
"extensions",
"is",
"not",
"None",
":",
"if",
"filter_func",
"is",
... | 45.884615 | 0.002463 |
def InitializeDebuggeeLabels(self, flags):
"""Initialize debuggee labels from environment variables and flags.
The caller passes all the flags that the the debuglet got. This function
will only use the flags used to label the debuggee. Flags take precedence
over environment variables.
Debuggee des... | [
"def",
"InitializeDebuggeeLabels",
"(",
"self",
",",
"flags",
")",
":",
"self",
".",
"_debuggee_labels",
"=",
"{",
"}",
"for",
"(",
"label",
",",
"var_names",
")",
"in",
"six",
".",
"iteritems",
"(",
"_DEBUGGEE_LABELS",
")",
":",
"# var_names is a list of poss... | 36.363636 | 0.008117 |
def query_params(self, params, key, def_value, short_hand=None):
"""
updates params dict to use
:param params:
:param key:
:param def_value:
:param short_hand:
:return:
"""
if key not in params and short_hand:
# value is associated with shorthand, move to key
params[k... | [
"def",
"query_params",
"(",
"self",
",",
"params",
",",
"key",
",",
"def_value",
",",
"short_hand",
"=",
"None",
")",
":",
"if",
"key",
"not",
"in",
"params",
"and",
"short_hand",
":",
"# value is associated with shorthand, move to key",
"params",
"[",
"key",
... | 31.52381 | 0.001466 |
def scroll(self, clicks):
"""Zoom using a mouse scroll wheel motion.
Parameters
----------
clicks : int
The number of clicks. Positive numbers indicate forward wheel
movement.
"""
target = self._target
ratio = 0.90
mult = 1.0
... | [
"def",
"scroll",
"(",
"self",
",",
"clicks",
")",
":",
"target",
"=",
"self",
".",
"_target",
"ratio",
"=",
"0.90",
"mult",
"=",
"1.0",
"if",
"clicks",
">",
"0",
":",
"mult",
"=",
"ratio",
"**",
"clicks",
"elif",
"clicks",
"<",
"0",
":",
"mult",
... | 30.30303 | 0.001938 |
def save(self, projects):
"""Save the projects configs to local path
Args:
projects (dict): project_name -> project_data
"""
base_path = os.path.expanduser(self.path)
if not os.path.isdir(base_path):
return
logger.debug("Save projects config to... | [
"def",
"save",
"(",
"self",
",",
"projects",
")",
":",
"base_path",
"=",
"os",
".",
"path",
".",
"expanduser",
"(",
"self",
".",
"path",
")",
"if",
"not",
"os",
".",
"path",
".",
"isdir",
"(",
"base_path",
")",
":",
"return",
"logger",
".",
"debug"... | 34.789474 | 0.010309 |
def rdfs_classes(rdf):
"""Perform RDFS subclass inference.
Mark all resources with a subclass type with the upper class."""
# find out the subclass mappings
upperclasses = {} # key: class val: set([superclass1, superclass2..])
for s, o in rdf.subject_objects(RDFS.subClassOf):
upperclasses... | [
"def",
"rdfs_classes",
"(",
"rdf",
")",
":",
"# find out the subclass mappings",
"upperclasses",
"=",
"{",
"}",
"# key: class val: set([superclass1, superclass2..])",
"for",
"s",
",",
"o",
"in",
"rdf",
".",
"subject_objects",
"(",
"RDFS",
".",
"subClassOf",
")",
":"... | 39.263158 | 0.001309 |
def _resample_data(self, gssha_var):
"""
This function resamples the data to match the GSSHA grid
IN TESTING MODE
"""
self.data = self.data.lsm.resample(gssha_var, self.gssha_grid) | [
"def",
"_resample_data",
"(",
"self",
",",
"gssha_var",
")",
":",
"self",
".",
"data",
"=",
"self",
".",
"data",
".",
"lsm",
".",
"resample",
"(",
"gssha_var",
",",
"self",
".",
"gssha_grid",
")"
] | 35.833333 | 0.009091 |
def get_historical_data(symbols, start=None, end=None, **kwargs):
"""
Function to obtain historical date for a symbol or list of
symbols. Return an instance of HistoricalReader
Parameters
----------
symbols: str or list
A symbol or list of symbols
start: datetime.datetime, default N... | [
"def",
"get_historical_data",
"(",
"symbols",
",",
"start",
"=",
"None",
",",
"end",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"start",
",",
"end",
"=",
"_sanitize_dates",
"(",
"start",
",",
"end",
")",
"return",
"HistoricalReader",
"(",
"symbols",... | 31.434783 | 0.001342 |
def keys(self):
""" :see::meth:RedisMap.keys """
for field in self._client.hkeys(self.key_prefix):
yield self._decode(field) | [
"def",
"keys",
"(",
"self",
")",
":",
"for",
"field",
"in",
"self",
".",
"_client",
".",
"hkeys",
"(",
"self",
".",
"key_prefix",
")",
":",
"yield",
"self",
".",
"_decode",
"(",
"field",
")"
] | 37.25 | 0.013158 |
def _prepare_regex_pattern(self, p):
"Recompile bytes regexes as unicode regexes."
if isinstance(p.pattern, bytes):
p = re.compile(p.pattern.decode(self.encoding), p.flags)
return p | [
"def",
"_prepare_regex_pattern",
"(",
"self",
",",
"p",
")",
":",
"if",
"isinstance",
"(",
"p",
".",
"pattern",
",",
"bytes",
")",
":",
"p",
"=",
"re",
".",
"compile",
"(",
"p",
".",
"pattern",
".",
"decode",
"(",
"self",
".",
"encoding",
")",
",",... | 42.6 | 0.009217 |
def getActionReflexRules(self, analysis, wf_action):
"""
This function returns a list of dictionaries with the rules to be done
for the analysis service.
:analysis: the analysis full object which we want to obtain the
rules for.
:wf_action: it is the workflow action t... | [
"def",
"getActionReflexRules",
"(",
"self",
",",
"analysis",
",",
"wf_action",
")",
":",
"# Setting up the analyses catalog",
"self",
".",
"analyses_catalog",
"=",
"getToolByName",
"(",
"self",
",",
"CATALOG_ANALYSIS_LISTING",
")",
"# Getting the action sets, those that con... | 50.40625 | 0.001217 |
def _compile(self, file_pattern, folder_exclude_pattern):
"""Compile patterns."""
if not isinstance(file_pattern, _wcparse.WcRegexp):
file_pattern = self._compile_wildcard(file_pattern, self.file_pathname)
if not isinstance(folder_exclude_pattern, _wcparse.WcRegexp):
f... | [
"def",
"_compile",
"(",
"self",
",",
"file_pattern",
",",
"folder_exclude_pattern",
")",
":",
"if",
"not",
"isinstance",
"(",
"file_pattern",
",",
"_wcparse",
".",
"WcRegexp",
")",
":",
"file_pattern",
"=",
"self",
".",
"_compile_wildcard",
"(",
"file_pattern",
... | 41.090909 | 0.008658 |
def gf_poly_mul_simple(p, q): # simple equivalent way of multiplying two polynomials without precomputation, but thus it's slower
'''Multiply two polynomials, inside Galois Field'''
# Pre-allocate the result array
r = bytearray(len(p) + len(q) - 1)
# Compute the polynomial multiplication (just like the ... | [
"def",
"gf_poly_mul_simple",
"(",
"p",
",",
"q",
")",
":",
"# simple equivalent way of multiplying two polynomials without precomputation, but thus it's slower",
"# Pre-allocate the result array",
"r",
"=",
"bytearray",
"(",
"len",
"(",
"p",
")",
"+",
"len",
"(",
"q",
")"... | 71.333333 | 0.009231 |
def asyncPipeUniq(context=None, _INPUT=None, conf=None, **kwargs):
"""An operator that asynchronously returns a specified number of items from
the top of a feed. Not loopable.
Parameters
----------
context : pipe2py.Context object
_INPUT : twisted Deferred iterable of items
conf : {
... | [
"def",
"asyncPipeUniq",
"(",
"context",
"=",
"None",
",",
"_INPUT",
"=",
"None",
",",
"conf",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"_input",
"=",
"yield",
"_INPUT",
"asyncFuncs",
"=",
"yield",
"asyncGetSplits",
"(",
"None",
",",
"conf",
",",... | 29.733333 | 0.001086 |
def preprocess(img):
"""Preprocess 210x160x3 uint8 frame into 6400 (80x80) 1D float vector."""
# Crop the image.
img = img[35:195]
# Downsample by factor of 2.
img = img[::2, ::2, 0]
# Erase background (background type 1).
img[img == 144] = 0
# Erase background (background type 2).
i... | [
"def",
"preprocess",
"(",
"img",
")",
":",
"# Crop the image.",
"img",
"=",
"img",
"[",
"35",
":",
"195",
"]",
"# Downsample by factor of 2.",
"img",
"=",
"img",
"[",
":",
":",
"2",
",",
":",
":",
"2",
",",
"0",
"]",
"# Erase background (background type 1)... | 33.538462 | 0.002232 |
def _timeout_thread(self, remain):
"""Timeout before releasing every thing, if nothing was returned"""
time.sleep(remain)
if not self._ended:
self._ended = True
self._release_all() | [
"def",
"_timeout_thread",
"(",
"self",
",",
"remain",
")",
":",
"time",
".",
"sleep",
"(",
"remain",
")",
"if",
"not",
"self",
".",
"_ended",
":",
"self",
".",
"_ended",
"=",
"True",
"self",
".",
"_release_all",
"(",
")"
] | 37.166667 | 0.008772 |
def get_names(self):
"""
Returns a dict where key is the language and value is the name in that language.
Example:
{'it':"Sofocle"}
"""
names = [id for id in self.ecrm_P1_is_identified_by if id.uri == surf.ns.EFRBROO['F12_Name']]
self.names = []
for n... | [
"def",
"get_names",
"(",
"self",
")",
":",
"names",
"=",
"[",
"id",
"for",
"id",
"in",
"self",
".",
"ecrm_P1_is_identified_by",
"if",
"id",
".",
"uri",
"==",
"surf",
".",
"ns",
".",
"EFRBROO",
"[",
"'F12_Name'",
"]",
"]",
"self",
".",
"names",
"=",
... | 35.461538 | 0.010571 |
def update_workers(self):
"""Handles unexpected processes termination."""
for expiration in self.worker_manager.inspect_workers():
self.handle_worker_expiration(expiration)
self.worker_manager.create_workers() | [
"def",
"update_workers",
"(",
"self",
")",
":",
"for",
"expiration",
"in",
"self",
".",
"worker_manager",
".",
"inspect_workers",
"(",
")",
":",
"self",
".",
"handle_worker_expiration",
"(",
"expiration",
")",
"self",
".",
"worker_manager",
".",
"create_workers"... | 40.166667 | 0.00813 |
def from_random(self, power, gm, r0, omega=None, function='geoid',
lmax=None, normalization='4pi', csphase=1,
exact_power=False):
"""
Initialize the class of gravitational potential spherical harmonic
coefficients as random variables with a given spectrum.... | [
"def",
"from_random",
"(",
"self",
",",
"power",
",",
"gm",
",",
"r0",
",",
"omega",
"=",
"None",
",",
"function",
"=",
"'geoid'",
",",
"lmax",
"=",
"None",
",",
"normalization",
"=",
"'4pi'",
",",
"csphase",
"=",
"1",
",",
"exact_power",
"=",
"False... | 43.770701 | 0.000996 |
def script_folder(script_path):
"""
Return the given script's folder or None if it can not be determined.
Script is identified by its __file__ attribute. If the given __file__
attribute value contains no path information, it is expected to identify an
existing file in the current working fold... | [
"def",
"script_folder",
"(",
"script_path",
")",
":",
"# There exist modules whose __file__ attribute does not correspond directly\r",
"# to a disk file, e.g. modules imported from inside zip archives.\r",
"if",
"os",
".",
"path",
".",
"isfile",
"(",
"script_path",
")",
":",
"ret... | 47.666667 | 0.000979 |
def execute(self, *args):
"""Executes single command and returns result."""
command, kwargs = self.parse(*args)
return self._commands.execute(command, **kwargs) | [
"def",
"execute",
"(",
"self",
",",
"*",
"args",
")",
":",
"command",
",",
"kwargs",
"=",
"self",
".",
"parse",
"(",
"*",
"args",
")",
"return",
"self",
".",
"_commands",
".",
"execute",
"(",
"command",
",",
"*",
"*",
"kwargs",
")"
] | 45.25 | 0.01087 |
def load_copy_of_template(self, name, *parameters):
"""Load a copy of message template saved with `Save template` when originally saved values need to be preserved
from test to test.
Optional parameters are default values for message header separated with
colon.
Examples:
... | [
"def",
"load_copy_of_template",
"(",
"self",
",",
"name",
",",
"*",
"parameters",
")",
":",
"template",
",",
"fields",
",",
"header_fields",
"=",
"self",
".",
"_set_templates_fields_and_header_fields",
"(",
"name",
",",
"parameters",
")",
"copy_of_template",
"=",
... | 51.461538 | 0.008811 |
def parse_genotype(variant, ind, pos):
"""Get the genotype information in the proper format
Sv specific format fields:
##FORMAT=<ID=DV,Number=1,Type=Integer,
Description="Number of paired-ends that support the event">
##FORMAT=<ID=PE,Number=1,Type=Integer,
Description="Number of paired-ends t... | [
"def",
"parse_genotype",
"(",
"variant",
",",
"ind",
",",
"pos",
")",
":",
"gt_call",
"=",
"{",
"}",
"ind_id",
"=",
"ind",
"[",
"'individual_id'",
"]",
"gt_call",
"[",
"'individual_id'",
"]",
"=",
"ind_id",
"gt_call",
"[",
"'display_name'",
"]",
"=",
"in... | 30.659218 | 0.001059 |
def booleanise(b):
"""Normalise a 'stringified' Boolean to a proper Python Boolean.
ElasticSearch has a habit of returning "true" and "false" in its
JSON responses when it should be returning `true` and `false`. If
`b` looks like a stringified Boolean true, return True. If `b`
looks like a str... | [
"def",
"booleanise",
"(",
"b",
")",
":",
"s",
"=",
"str",
"(",
"b",
")",
"if",
"s",
".",
"lower",
"(",
")",
"==",
"\"true\"",
":",
"return",
"True",
"if",
"s",
".",
"lower",
"(",
")",
"==",
"\"false\"",
":",
"return",
"False",
"return",
"b"
] | 29.842105 | 0.008547 |
def match_delta(self, value):
'''Search for timedelta information in the string'''
m = self.REGEX_DELTA.search(value)
delta = datetime.timedelta(days=0)
if m:
d = int(m.group(1))
if m.group(3) == 'ago' or m.group(3) == 'before':
d = -d
if m.group(2) == 'minute':
delta ... | [
"def",
"match_delta",
"(",
"self",
",",
"value",
")",
":",
"m",
"=",
"self",
".",
"REGEX_DELTA",
".",
"search",
"(",
"value",
")",
"delta",
"=",
"datetime",
".",
"timedelta",
"(",
"days",
"=",
"0",
")",
"if",
"m",
":",
"d",
"=",
"int",
"(",
"m",
... | 33.368421 | 0.01227 |
def validate_listeners(self):
"""Validates that some listeners are actually registered"""
if self.exception:
# pylint: disable=raising-bad-type
raise self.exception
listeners = self.__listeners_for_thread
if not sum(len(l) for l in listeners):
raise ... | [
"def",
"validate_listeners",
"(",
"self",
")",
":",
"if",
"self",
".",
"exception",
":",
"# pylint: disable=raising-bad-type",
"raise",
"self",
".",
"exception",
"listeners",
"=",
"self",
".",
"__listeners_for_thread",
"if",
"not",
"sum",
"(",
"len",
"(",
"l",
... | 34.4 | 0.008499 |
def default_partfactory(part_number=None, content_length=None,
content_type=None, content_md5=None):
"""Get default part factory.
:param part_number: The part number. (Default: ``None``)
:param content_length: The content length. (Default: ``None``)
:param content_type: The HTTP... | [
"def",
"default_partfactory",
"(",
"part_number",
"=",
"None",
",",
"content_length",
"=",
"None",
",",
"content_type",
"=",
"None",
",",
"content_md5",
"=",
"None",
")",
":",
"return",
"content_length",
",",
"part_number",
",",
"request",
".",
"stream",
",",
... | 47.538462 | 0.001587 |
def slas_policy_create(self, data, **kwargs):
"https://developer.zendesk.com/rest_api/docs/core/sla_policies#create-sla-policy"
api_path = "/api/v2/slas/policies"
return self.call(api_path, method="POST", data=data, **kwargs) | [
"def",
"slas_policy_create",
"(",
"self",
",",
"data",
",",
"*",
"*",
"kwargs",
")",
":",
"api_path",
"=",
"\"/api/v2/slas/policies\"",
"return",
"self",
".",
"call",
"(",
"api_path",
",",
"method",
"=",
"\"POST\"",
",",
"data",
"=",
"data",
",",
"*",
"*... | 61.5 | 0.012048 |
def __get_improved_exception_message(self):
"""
If Chromedriver is out-of-date, make it clear!
Given the high popularity of the following StackOverflow article:
https://stackoverflow.com/questions/49162667/unknown-error-
call-function-result-missing-value-for-selenium-sen... | [
"def",
"__get_improved_exception_message",
"(",
"self",
")",
":",
"exc_message",
"=",
"self",
".",
"__get_exception_message",
"(",
")",
"maybe_using_old_chromedriver",
"=",
"False",
"if",
"\"unknown error: call function result missing\"",
"in",
"exc_message",
":",
"maybe_us... | 56.409091 | 0.001585 |
def _create_command_file(self, expect, send):
"""Internal function. Do not use.
Takes a long command, and puts it in an executable file ready to run. Returns the filename.
"""
shutit = self.shutit
random_id = shutit_util.random_id()
fname = shutit_global.shutit_global_object.shutit_state_dir + '/tmp_' + ra... | [
"def",
"_create_command_file",
"(",
"self",
",",
"expect",
",",
"send",
")",
":",
"shutit",
"=",
"self",
".",
"shutit",
"random_id",
"=",
"shutit_util",
".",
"random_id",
"(",
")",
"fname",
"=",
"shutit_global",
".",
"shutit_global_object",
".",
"shutit_state_... | 51.518519 | 0.028934 |
def set_decdel_rts(self):
"""Figure out the decimal seperator and rows to skip and set
corresponding attributes.
"""
lnr = max(self.rows2skip(','), self.rows2skip('.')) + 1
# If EQUAL_CNT_REQ was not met, raise error. Implement!
if self.cnt > EQUAL_CNT_REQ:
r... | [
"def",
"set_decdel_rts",
"(",
"self",
")",
":",
"lnr",
"=",
"max",
"(",
"self",
".",
"rows2skip",
"(",
"','",
")",
",",
"self",
".",
"rows2skip",
"(",
"'.'",
")",
")",
"+",
"1",
"# If EQUAL_CNT_REQ was not met, raise error. Implement!",
"if",
"self",
".",
... | 45.652174 | 0.001866 |
def _beam_decode_slow(self, features, decode_length, beam_size, top_beams,
alpha, use_tpu=False):
"""Slow version of Beam search decoding.
Quadratic time in decode_length.
Args:
features: an map of string to `Tensor`
decode_length: an integer. How many additional times... | [
"def",
"_beam_decode_slow",
"(",
"self",
",",
"features",
",",
"decode_length",
",",
"beam_size",
",",
"top_beams",
",",
"alpha",
",",
"use_tpu",
"=",
"False",
")",
":",
"batch_size",
"=",
"common_layers",
".",
"shape_list",
"(",
"features",
"[",
"\"inputs\"",... | 38.476636 | 0.008762 |
def start_output (self):
"""
Write start of checking info as sql comment.
"""
super(SQLLogger, self).start_output()
if self.has_part("intro"):
self.write_intro()
self.writeln()
self.flush() | [
"def",
"start_output",
"(",
"self",
")",
":",
"super",
"(",
"SQLLogger",
",",
"self",
")",
".",
"start_output",
"(",
")",
"if",
"self",
".",
"has_part",
"(",
"\"intro\"",
")",
":",
"self",
".",
"write_intro",
"(",
")",
"self",
".",
"writeln",
"(",
")... | 28.555556 | 0.011321 |
def is_regex_type(type_):
""" Checks if the given type is a regex type.
:param type_: The type to check
:return: True if the type is a regex type, otherwise False
:rtype: bool
"""
return (
callable(type_)
and getattr(type_, "__name__", None) == REGEX_TYPE_NAME
and hasat... | [
"def",
"is_regex_type",
"(",
"type_",
")",
":",
"return",
"(",
"callable",
"(",
"type_",
")",
"and",
"getattr",
"(",
"type_",
",",
"\"__name__\"",
",",
"None",
")",
"==",
"REGEX_TYPE_NAME",
"and",
"hasattr",
"(",
"type_",
",",
"\"__supertype__\"",
")",
"an... | 28 | 0.002469 |
def refactor_organize_imports(self):
"""Clean up and organize imports."""
refactor = ImportOrganizer(self.project)
changes = refactor.organize_imports(self.resource)
return translate_changes(changes) | [
"def",
"refactor_organize_imports",
"(",
"self",
")",
":",
"refactor",
"=",
"ImportOrganizer",
"(",
"self",
".",
"project",
")",
"changes",
"=",
"refactor",
".",
"organize_imports",
"(",
"self",
".",
"resource",
")",
"return",
"translate_changes",
"(",
"changes"... | 45.4 | 0.008658 |
def set_summary(self):
"""Parses summary and set value"""
try:
self.summary = self.soup.find('itunes:summary').string
except AttributeError:
self.summary = None | [
"def",
"set_summary",
"(",
"self",
")",
":",
"try",
":",
"self",
".",
"summary",
"=",
"self",
".",
"soup",
".",
"find",
"(",
"'itunes:summary'",
")",
".",
"string",
"except",
"AttributeError",
":",
"self",
".",
"summary",
"=",
"None"
] | 33.833333 | 0.009615 |
def get_temp_dimname(dims: Container[Hashable], new_dim: Hashable) -> Hashable:
""" Get an new dimension name based on new_dim, that is not used in dims.
If the same name exists, we add an underscore(s) in the head.
Example1:
dims: ['a', 'b', 'c']
new_dim: ['_rolling']
-> ['_rolling... | [
"def",
"get_temp_dimname",
"(",
"dims",
":",
"Container",
"[",
"Hashable",
"]",
",",
"new_dim",
":",
"Hashable",
")",
"->",
"Hashable",
":",
"while",
"new_dim",
"in",
"dims",
":",
"new_dim",
"=",
"'_'",
"+",
"str",
"(",
"new_dim",
")",
"return",
"new_dim... | 31.8125 | 0.001908 |
def AddArguments(cls, argument_group):
"""Adds command line arguments the helper supports to an argument group.
This function takes an argument parser or an argument group object and adds
to it all the command line arguments this helper supports.
Args:
argument_group (argparse._ArgumentGroup|arg... | [
"def",
"AddArguments",
"(",
"cls",
",",
"argument_group",
")",
":",
"argument_group",
".",
"add_argument",
"(",
"'--fields'",
",",
"dest",
"=",
"'fields'",
",",
"type",
"=",
"str",
",",
"action",
"=",
"'store'",
",",
"default",
"=",
"cls",
".",
"_DEFAULT_F... | 46.88 | 0.000836 |
def _get_struct_clipactions(self):
"""Get the several CLIPACTIONRECORDs."""
obj = _make_object("ClipActions")
# In SWF 5 and earlier, these are 2 bytes wide; in SWF 6
# and later 4 bytes
clipeventflags_size = 2 if self._version <= 5 else 4
clipactionend_size = 2 if self.... | [
"def",
"_get_struct_clipactions",
"(",
"self",
")",
":",
"obj",
"=",
"_make_object",
"(",
"\"ClipActions\"",
")",
"# In SWF 5 and earlier, these are 2 bytes wide; in SWF 6",
"# and later 4 bytes",
"clipeventflags_size",
"=",
"2",
"if",
"self",
".",
"_version",
"<=",
"5",
... | 39.451613 | 0.001596 |
def _delete(self, pos, idx):
"""Delete the item at the given (pos, idx).
Combines lists that are less than half the load level.
Updates the index when the sublist length is more than half the load
level. This requires decrementing the nodes in a traversal from the leaf
node to ... | [
"def",
"_delete",
"(",
"self",
",",
"pos",
",",
"idx",
")",
":",
"_maxes",
",",
"_lists",
",",
"_index",
"=",
"self",
".",
"_maxes",
",",
"self",
".",
"_lists",
",",
"self",
".",
"_index",
"lists_pos",
"=",
"_lists",
"[",
"pos",
"]",
"del",
"lists_... | 24.54717 | 0.002217 |
def execute_sql(
self,
sql,
params=None,
param_types=None,
query_mode=None,
partition=None,
retry=google.api_core.gapic_v1.method.DEFAULT,
timeout=google.api_core.gapic_v1.method.DEFAULT,
):
"""Perform an ``ExecuteStreamingSql`` API request.
... | [
"def",
"execute_sql",
"(",
"self",
",",
"sql",
",",
"params",
"=",
"None",
",",
"param_types",
"=",
"None",
",",
"query_mode",
"=",
"None",
",",
"partition",
"=",
"None",
",",
"retry",
"=",
"google",
".",
"api_core",
".",
"gapic_v1",
".",
"method",
"."... | 35.238095 | 0.001643 |
def fix_logging_path(config, main_section):
"""
Expand environment variables and user home (~) in the log.file and return
as relative path.
"""
log_file = config.get(main_section, 'log.file')
if log_file:
log_file = os.path.expanduser(os.path.expandvars(log_file))
if os.path.isab... | [
"def",
"fix_logging_path",
"(",
"config",
",",
"main_section",
")",
":",
"log_file",
"=",
"config",
".",
"get",
"(",
"main_section",
",",
"'log.file'",
")",
"if",
"log_file",
":",
"log_file",
"=",
"os",
".",
"path",
".",
"expanduser",
"(",
"os",
".",
"pa... | 35.545455 | 0.002494 |
def _build_action_bound_constraints_table(self):
'''Builds the lower and upper action bound constraint expressions.'''
self.action_lower_bound_constraints = {}
self.action_upper_bound_constraints = {}
for name, preconds in self.local_action_preconditions.items():
for precon... | [
"def",
"_build_action_bound_constraints_table",
"(",
"self",
")",
":",
"self",
".",
"action_lower_bound_constraints",
"=",
"{",
"}",
"self",
".",
"action_upper_bound_constraints",
"=",
"{",
"}",
"for",
"name",
",",
"preconds",
"in",
"self",
".",
"local_action_precon... | 42.413793 | 0.002385 |
def format(self, record):
"""Uses contextstring if request_id is set, otherwise default."""
# NOTE(sdague): default the fancier formating params
# to an empty string so we don't throw an exception if
# they get used
for key in ('instance', 'color'):
if key not in reco... | [
"def",
"format",
"(",
"self",
",",
"record",
")",
":",
"# NOTE(sdague): default the fancier formating params",
"# to an empty string so we don't throw an exception if",
"# they get used",
"for",
"key",
"in",
"(",
"'instance'",
",",
"'color'",
")",
":",
"if",
"key",
"not",... | 42.5 | 0.002092 |
def reviews_query(self, id, **kwargs):
"""
Query the Yelp Reviews API.
documentation: https://www.yelp.com/developers/documentation/v3/business_reviews
required parameters:
* id - business ID
"""
if not id:
raise Value... | [
"def",
"reviews_query",
"(",
"self",
",",
"id",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"id",
":",
"raise",
"ValueError",
"(",
"'A valid business ID (parameter \"id\") must be provided.'",
")",
"return",
"self",
".",
"_query",
"(",
"REVIEWS_API_URL",
"."... | 33.615385 | 0.011136 |
def calc_asymptotic_covariance(hessian, fisher_info_matrix):
"""
Parameters
----------
hessian : 2D ndarray.
It should have shape `(num_vars, num_vars)`. It is the matrix of second
derivatives of the total loss across the dataset, with respect to each
pair of coefficients being e... | [
"def",
"calc_asymptotic_covariance",
"(",
"hessian",
",",
"fisher_info_matrix",
")",
":",
"# Calculate the inverse of the hessian",
"hess_inv",
"=",
"scipy",
".",
"linalg",
".",
"inv",
"(",
"hessian",
")",
"return",
"np",
".",
"dot",
"(",
"hess_inv",
",",
"np",
... | 41.84 | 0.000935 |
def remove_lb_nodes(self, lb_id, node_ids):
"""
Remove one or more nodes
:param string lb_id: Balancer id
:param list node_ids: List of node ids
"""
log.info("Removing load balancer nodes %s" % node_ids)
for node_id in node_ids:
self._request('dele... | [
"def",
"remove_lb_nodes",
"(",
"self",
",",
"lb_id",
",",
"node_ids",
")",
":",
"log",
".",
"info",
"(",
"\"Removing load balancer nodes %s\"",
"%",
"node_ids",
")",
"for",
"node_id",
"in",
"node_ids",
":",
"self",
".",
"_request",
"(",
"'delete'",
",",
"'/l... | 33 | 0.008043 |
def scrypt(password, salt, N=SCRYPT_N, r=SCRYPT_r, p=SCRYPT_p, olen=64):
"""Returns a key derived using the scrypt key-derivarion function
N must be a power of two larger than 1 but no larger than 2 ** 63 (insane)
r and p must be positive numbers such that r * p < 2 ** 30
The default values are:
N... | [
"def",
"scrypt",
"(",
"password",
",",
"salt",
",",
"N",
"=",
"SCRYPT_N",
",",
"r",
"=",
"SCRYPT_r",
",",
"p",
"=",
"SCRYPT_p",
",",
"olen",
"=",
"64",
")",
":",
"check_args",
"(",
"password",
",",
"salt",
",",
"N",
",",
"r",
",",
"p",
",",
"ol... | 37.178571 | 0.001873 |
def create_async_sns_topic(self, lambda_name, lambda_arn):
"""
Create the SNS-based async topic.
"""
topic_name = get_topic_name(lambda_name)
# Create SNS topic
topic_arn = self.sns_client.create_topic(
Name=topic_name)['TopicArn']
# Create subscriptio... | [
"def",
"create_async_sns_topic",
"(",
"self",
",",
"lambda_name",
",",
"lambda_arn",
")",
":",
"topic_name",
"=",
"get_topic_name",
"(",
"lambda_name",
")",
"# Create SNS topic",
"topic_arn",
"=",
"self",
".",
"sns_client",
".",
"create_topic",
"(",
"Name",
"=",
... | 32.903226 | 0.001905 |
def plots(data, **kwargs):
"""
simple wrapper plot with labels and skip x
:param yonly_or_xy:
:param kwargs:
:return:
"""
labels = kwargs.pop('labels', '')
loc = kwargs.pop('loc', 1)
# if len(yonly_or_xy) == 1:
# x = range(len(yonly_or_xy))
# y = yonly_or_xy
# el... | [
"def",
"plots",
"(",
"data",
",",
"*",
"*",
"kwargs",
")",
":",
"labels",
"=",
"kwargs",
".",
"pop",
"(",
"'labels'",
",",
"''",
")",
"loc",
"=",
"kwargs",
".",
"pop",
"(",
"'loc'",
",",
"1",
")",
"# if len(yonly_or_xy) == 1:",
"# x = range(len(yonly... | 23.285714 | 0.001965 |
def request_camera_sensors(blink, network, camera_id):
"""
Request camera sensor info for one camera.
:param blink: Blink instance.
:param network: Sync module network id.
:param camera_id: Camera ID of camera to request sesnor info from.
"""
url = "{}/network/{}/camera/{}/signals".format(b... | [
"def",
"request_camera_sensors",
"(",
"blink",
",",
"network",
",",
"camera_id",
")",
":",
"url",
"=",
"\"{}/network/{}/camera/{}/signals\"",
".",
"format",
"(",
"blink",
".",
"urls",
".",
"base_url",
",",
"network",
",",
"camera_id",
")",
"return",
"http_get",
... | 40.166667 | 0.002028 |
def get_polygon_constraints_m(self, polygons_m, print_out=False):
"""
:param range_polygones: list of numbers of polygones to test.
:return A, b: the constraints on the theta-vector of the form A*theta = b
"""
rows_b = []
rows_A = []
m = len(polygons_m[0])
... | [
"def",
"get_polygon_constraints_m",
"(",
"self",
",",
"polygons_m",
",",
"print_out",
"=",
"False",
")",
":",
"rows_b",
"=",
"[",
"]",
"rows_A",
"=",
"[",
"]",
"m",
"=",
"len",
"(",
"polygons_m",
"[",
"0",
"]",
")",
"rows_b",
".",
"append",
"(",
"(",... | 37.971429 | 0.002201 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.