text stringlengths 89 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 630 |
|---|---|---|---|
def toilStageFiles(file_store, cwljob, outdir, index, existing, export,
destBucket=None):
"""Copy input files out of the global file store and update location and
path."""
def _collectDirEntries(obj):
# type: (Union[Dict[Text, Any], List[Dict[Text, Any]]]) -> Iterator[Dict[Text, Any]... | [
"def",
"toilStageFiles",
"(",
"file_store",
",",
"cwljob",
",",
"outdir",
",",
"index",
",",
"existing",
",",
"export",
",",
"destBucket",
"=",
"None",
")",
":",
"def",
"_collectDirEntries",
"(",
"obj",
")",
":",
"# type: (Union[Dict[Text, Any], List[Dict[Text, An... | 37.847458 | 18.423729 |
def toggle_view(self, checked):
"""Toggle view"""
if not self.dockwidget:
return
if checked:
self.dockwidget.show()
self.dockwidget.raise_()
else:
self.dockwidget.hide() | [
"def",
"toggle_view",
"(",
"self",
",",
"checked",
")",
":",
"if",
"not",
"self",
".",
"dockwidget",
":",
"return",
"if",
"checked",
":",
"self",
".",
"dockwidget",
".",
"show",
"(",
")",
"self",
".",
"dockwidget",
".",
"raise_",
"(",
")",
"else",
":... | 26.777778 | 11.555556 |
def _parse_response_for_dict(response):
''' Extracts name-values from response header. Filter out the standard
http headers.'''
if response is None:
return None
http_headers = ['server', 'date', 'location', 'host',
'via', 'proxy-connection', 'connection']
return_dict = _... | [
"def",
"_parse_response_for_dict",
"(",
"response",
")",
":",
"if",
"response",
"is",
"None",
":",
"return",
"None",
"http_headers",
"=",
"[",
"'server'",
",",
"'date'",
",",
"'location'",
",",
"'host'",
",",
"'via'",
",",
"'proxy-connection'",
",",
"'connecti... | 33.533333 | 17.666667 |
def has_reset(self):
"""Checks the grizzly to see if it reset itself because of
voltage sag or other reasons. Useful to reinitialize acceleration or
current limiting."""
currentTime = self._read_as_int(Addr.Uptime, 4)
if currentTime <= self._ticks:
self._ticks = curre... | [
"def",
"has_reset",
"(",
"self",
")",
":",
"currentTime",
"=",
"self",
".",
"_read_as_int",
"(",
"Addr",
".",
"Uptime",
",",
"4",
")",
"if",
"currentTime",
"<=",
"self",
".",
"_ticks",
":",
"self",
".",
"_ticks",
"=",
"currentTime",
"return",
"True",
"... | 39.6 | 12 |
def _decode_error(self):
"""Decode error element of the stanza."""
error_qname = self._ns_prefix + "error"
for child in self._element:
if child.tag == error_qname:
self._error = StanzaErrorElement(child)
return
raise BadRequestProtocolError("Er... | [
"def",
"_decode_error",
"(",
"self",
")",
":",
"error_qname",
"=",
"self",
".",
"_ns_prefix",
"+",
"\"error\"",
"for",
"child",
"in",
"self",
".",
"_element",
":",
"if",
"child",
".",
"tag",
"==",
"error_qname",
":",
"self",
".",
"_error",
"=",
"StanzaEr... | 46.111111 | 13.777778 |
def get_instance(self, payload):
"""
Build an instance of TriggerInstance
:param dict payload: Payload response from the API
:returns: twilio.rest.api.v2010.account.usage.trigger.TriggerInstance
:rtype: twilio.rest.api.v2010.account.usage.trigger.TriggerInstance
"""
... | [
"def",
"get_instance",
"(",
"self",
",",
"payload",
")",
":",
"return",
"TriggerInstance",
"(",
"self",
".",
"_version",
",",
"payload",
",",
"account_sid",
"=",
"self",
".",
"_solution",
"[",
"'account_sid'",
"]",
",",
")"
] | 40.7 | 24.1 |
def _kill(self, kill_sig):
"""Send a signal to the current process."""
if self.pid:
os.kill(self.pid, kill_sig) | [
"def",
"_kill",
"(",
"self",
",",
"kill_sig",
")",
":",
"if",
"self",
".",
"pid",
":",
"os",
".",
"kill",
"(",
"self",
".",
"pid",
",",
"kill_sig",
")"
] | 30.5 | 11.25 |
def _search_pn(self, href=None, limit=None,
embed_items=None, embed_tracks=None, embed_metadata=None,
embed_insights=None):
"""Function called to retrieve pages 2-n."""
url_components = urlparse(href)
path = url_components.path
data = parse_qs(url_c... | [
"def",
"_search_pn",
"(",
"self",
",",
"href",
"=",
"None",
",",
"limit",
"=",
"None",
",",
"embed_items",
"=",
"None",
",",
"embed_tracks",
"=",
"None",
",",
"embed_metadata",
"=",
"None",
",",
"embed_insights",
"=",
"None",
")",
":",
"url_components",
... | 36.088235 | 18.029412 |
def code(self):
"""
code
"""
def uniq(seq):
"""
@type seq: str
@return: None
"""
seen = set()
seen_add = seen.add
return [x for x in seq if x not in seen and not seen_add(x)]
# noinspection PyTy... | [
"def",
"code",
"(",
"self",
")",
":",
"def",
"uniq",
"(",
"seq",
")",
":",
"\"\"\"\n @type seq: str\n @return: None\n \"\"\"",
"seen",
"=",
"set",
"(",
")",
"seen_add",
"=",
"seen",
".",
"add",
"return",
"[",
"x",
"for",
"x",
"... | 23.26087 | 17.695652 |
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 | 20.833333 |
def _set_archive_name(package_name,
package_version,
python_versions,
platform,
build_tag=''):
"""Set the format of the output archive file.
We should aspire for the name of the archive to be
as compatible as possible w... | [
"def",
"_set_archive_name",
"(",
"package_name",
",",
"package_version",
",",
"python_versions",
",",
"platform",
",",
"build_tag",
"=",
"''",
")",
":",
"package_name",
"=",
"package_name",
".",
"replace",
"(",
"'-'",
",",
"'_'",
")",
"python_versions",
"=",
"... | 30.034483 | 17.896552 |
def export(options, service):
""" main export method: export any number of indexes """
start = options.kwargs['start']
end = options.kwargs['end']
fixtail = options.kwargs['fixtail']
once = True
squery = options.kwargs['search']
squery = squery + " index=%s" % options.kwargs['index']
i... | [
"def",
"export",
"(",
"options",
",",
"service",
")",
":",
"start",
"=",
"options",
".",
"kwargs",
"[",
"'start'",
"]",
"end",
"=",
"options",
".",
"kwargs",
"[",
"'end'",
"]",
"fixtail",
"=",
"options",
".",
"kwargs",
"[",
"'fixtail'",
"]",
"once",
... | 31.808511 | 16.361702 |
def save(self):
"""
Update the SouceReading information for the currently recorded observations and then flush those to a file.
@return: mpc_filename of the resulting save.
"""
self.get_writer().flush()
mpc_filename = self.get_writer().get_filename()
self.get_writ... | [
"def",
"save",
"(",
"self",
")",
":",
"self",
".",
"get_writer",
"(",
")",
".",
"flush",
"(",
")",
"mpc_filename",
"=",
"self",
".",
"get_writer",
"(",
")",
".",
"get_filename",
"(",
")",
"self",
".",
"get_writer",
"(",
")",
".",
"close",
"(",
")",... | 37.9 | 16.7 |
def _process_layout(self, layout):
"""Process an LTPage layout and return a list of elements."""
# Here we just group text into paragraphs
elements = []
for lt_obj in layout:
if isinstance(lt_obj, LTTextBox) or isinstance(lt_obj, LTTextLine):
elements.append(P... | [
"def",
"_process_layout",
"(",
"self",
",",
"layout",
")",
":",
"# Here we just group text into paragraphs",
"elements",
"=",
"[",
"]",
"for",
"lt_obj",
"in",
"layout",
":",
"if",
"isinstance",
"(",
"lt_obj",
",",
"LTTextBox",
")",
"or",
"isinstance",
"(",
"lt... | 46.363636 | 15.181818 |
def _determine_weights(self, other, settings):
"""
Return weights of name components based on whether or not they were
omitted
"""
# TODO: Reduce weight for matches by prefix or initials
first_is_used = settings['first']['required'] or \
self.first and other... | [
"def",
"_determine_weights",
"(",
"self",
",",
"other",
",",
"settings",
")",
":",
"# TODO: Reduce weight for matches by prefix or initials",
"first_is_used",
"=",
"settings",
"[",
"'first'",
"]",
"[",
"'required'",
"]",
"or",
"self",
".",
"first",
"and",
"other",
... | 37.428571 | 22.190476 |
def is_spam_akismet(request, form, url):
"""
Identifies form data as being spam, using the http://akismet.com
service. The Akismet API key should be specified in the
``AKISMET_API_KEY`` setting. This function is the default spam
handler defined in the ``SPAM_FILTERS`` setting.
The name, email, ... | [
"def",
"is_spam_akismet",
"(",
"request",
",",
"form",
",",
"url",
")",
":",
"if",
"not",
"settings",
".",
"AKISMET_API_KEY",
":",
"return",
"False",
"protocol",
"=",
"\"http\"",
"if",
"not",
"request",
".",
"is_secure",
"(",
")",
"else",
"\"https\"",
"hos... | 42.140625 | 18.015625 |
def tie_properties(self, class_list):
""" Runs through the classess and ties the properties to the class
args:
class_list: a list of class names to run
"""
log.setLevel(self.log_level)
start = datetime.datetime.now()
log.info(" Tieing properties to the class"... | [
"def",
"tie_properties",
"(",
"self",
",",
"class_list",
")",
":",
"log",
".",
"setLevel",
"(",
"self",
".",
"log_level",
")",
"start",
"=",
"datetime",
".",
"datetime",
".",
"now",
"(",
")",
"log",
".",
"info",
"(",
"\" Tieing properties to the class\"",
... | 43.75 | 13.4375 |
def hsl_to_rgb(h, s=None, l=None):
"""Convert the color from HSL coordinates to RGB.
Parameters:
:h:
The Hue component value [0...1]
:s:
The Saturation component value [0...1]
:l:
The Lightness component value [0...1]
Returns:
The color as an (r, g, b) tuple in the range:
r... | [
"def",
"hsl_to_rgb",
"(",
"h",
",",
"s",
"=",
"None",
",",
"l",
"=",
"None",
")",
":",
"if",
"type",
"(",
"h",
")",
"in",
"[",
"list",
",",
"tuple",
"]",
":",
"h",
",",
"s",
",",
"l",
"=",
"h",
"if",
"s",
"==",
"0",
":",
"return",
"(",
... | 18.368421 | 22.315789 |
def main(args=None):
"""Main function for cli."""
args = get_args(args)
utils.init_log(args.log_level)
if ".csv" not in args.input_file.lower():
logger.warning("Make sure the input file '%s' is in CSV format", args.input_file)
try:
records = csvtools.get_imported_data(args.input_f... | [
"def",
"main",
"(",
"args",
"=",
"None",
")",
":",
"args",
"=",
"get_args",
"(",
"args",
")",
"utils",
".",
"init_log",
"(",
"args",
".",
"log_level",
")",
"if",
"\".csv\"",
"not",
"in",
"args",
".",
"input_file",
".",
"lower",
"(",
")",
":",
"logg... | 29.882353 | 23.588235 |
def get_top_tracks(self, limit=None, cacheable=True):
"""Returns the most played tracks as a sequence of TopItem objects."""
params = {}
if limit:
params["limit"] = limit
doc = _Request(self, "chart.getTopTracks", params).execute(cacheable)
seq = []
for nod... | [
"def",
"get_top_tracks",
"(",
"self",
",",
"limit",
"=",
"None",
",",
"cacheable",
"=",
"True",
")",
":",
"params",
"=",
"{",
"}",
"if",
"limit",
":",
"params",
"[",
"\"limit\"",
"]",
"=",
"limit",
"doc",
"=",
"_Request",
"(",
"self",
",",
"\"chart.g... | 33.555556 | 19.777778 |
def set_up_dirs(proc_name, output_dir=None, work_dir=None, log_dir=None):
""" Creates output_dir, work_dir, and sets up log
"""
output_dir = safe_mkdir(adjust_path(output_dir or join(os.getcwd(), proc_name)), 'output_dir')
debug('Saving results into ' + output_dir)
work_dir = safe_mkdir(work_dir or... | [
"def",
"set_up_dirs",
"(",
"proc_name",
",",
"output_dir",
"=",
"None",
",",
"work_dir",
"=",
"None",
",",
"log_dir",
"=",
"None",
")",
":",
"output_dir",
"=",
"safe_mkdir",
"(",
"adjust_path",
"(",
"output_dir",
"or",
"join",
"(",
"os",
".",
"getcwd",
"... | 44.916667 | 26.583333 |
def set_speed(self, aspirate=None, dispense=None):
"""
Set the speed (mm/second) the :any:`Pipette` plunger will move
during :meth:`aspirate` and :meth:`dispense`
Parameters
----------
aspirate: int
The speed in millimeters-per-second, at which the plunger wi... | [
"def",
"set_speed",
"(",
"self",
",",
"aspirate",
"=",
"None",
",",
"dispense",
"=",
"None",
")",
":",
"if",
"aspirate",
":",
"self",
".",
"speeds",
"[",
"'aspirate'",
"]",
"=",
"aspirate",
"if",
"dispense",
":",
"self",
".",
"speeds",
"[",
"'dispense'... | 33.05 | 18.25 |
def fmttime(tin):
"""Return LaTeX expression with time in scientific notation.
Args:
tin (float): the time.
Returns:
str: the LaTeX expression.
"""
aaa, bbb = '{:.2e}'.format(tin).split('e')
bbb = int(bbb)
return r'$t={} \times 10^{{{}}}$'.format(aaa, bbb) | [
"def",
"fmttime",
"(",
"tin",
")",
":",
"aaa",
",",
"bbb",
"=",
"'{:.2e}'",
".",
"format",
"(",
"tin",
")",
".",
"split",
"(",
"'e'",
")",
"bbb",
"=",
"int",
"(",
"bbb",
")",
"return",
"r'$t={} \\times 10^{{{}}}$'",
".",
"format",
"(",
"aaa",
",",
... | 26.454545 | 16.363636 |
def query_job(request):
"""Rest API to query the job info, with the given job_id.
The url pattern should be like this:
curl http://<server>:<port>/query_job?job_id=<job_id>
The response may be:
{
"running_trials": 0,
"start_time": "2018-07-19 20:49:40",
"current_round": 1... | [
"def",
"query_job",
"(",
"request",
")",
":",
"job_id",
"=",
"request",
".",
"GET",
".",
"get",
"(",
"\"job_id\"",
")",
"jobs",
"=",
"JobRecord",
".",
"objects",
".",
"filter",
"(",
"job_id",
"=",
"job_id",
")",
"trials",
"=",
"TrialRecord",
".",
"obje... | 30.948276 | 16.12069 |
def get(self, path, data=None):
"""Encapsulates GET requests"""
data = data or {}
response = requests.get(self.url(path), params=data, headers=self.request_header())
return self.parse_response(response) | [
"def",
"get",
"(",
"self",
",",
"path",
",",
"data",
"=",
"None",
")",
":",
"data",
"=",
"data",
"or",
"{",
"}",
"response",
"=",
"requests",
".",
"get",
"(",
"self",
".",
"url",
"(",
"path",
")",
",",
"params",
"=",
"data",
",",
"headers",
"="... | 46 | 15.8 |
def get_real(_bytearray, byte_index):
"""
Get real value. create float from 4 bytes
"""
x = _bytearray[byte_index:byte_index + 4]
real = struct.unpack('>f', struct.pack('4B', *x))[0]
return real | [
"def",
"get_real",
"(",
"_bytearray",
",",
"byte_index",
")",
":",
"x",
"=",
"_bytearray",
"[",
"byte_index",
":",
"byte_index",
"+",
"4",
"]",
"real",
"=",
"struct",
".",
"unpack",
"(",
"'>f'",
",",
"struct",
".",
"pack",
"(",
"'4B'",
",",
"*",
"x",... | 30.285714 | 7.714286 |
def make(name):
"""Create a new Token class using ``type()`` and add it to ``__all__``."""
__all__.append(name)
return type(name if py3k else name.encode("utf8"), (Token,), {}) | [
"def",
"make",
"(",
"name",
")",
":",
"__all__",
".",
"append",
"(",
"name",
")",
"return",
"type",
"(",
"name",
"if",
"py3k",
"else",
"name",
".",
"encode",
"(",
"\"utf8\"",
")",
",",
"(",
"Token",
",",
")",
",",
"{",
"}",
")"
] | 46.25 | 17.25 |
def get_api(
profile=None,
config_file=None,
requirements=None):
'''
Generate a datafs.DataAPI object from a config profile
``get_api`` generates a DataAPI object based on a
pre-configured datafs profile specified in your datafs
config file.
To create a datafs config fi... | [
"def",
"get_api",
"(",
"profile",
"=",
"None",
",",
"config_file",
"=",
"None",
",",
"requirements",
"=",
"None",
")",
":",
"config",
"=",
"ConfigFile",
"(",
"config_file",
"=",
"config_file",
")",
"config",
".",
"read_config",
"(",
")",
"if",
"profile",
... | 29.954198 | 20.137405 |
def csort(objs, key):
"""Order-preserving sorting function."""
idxs = dict((obj, i) for (i, obj) in enumerate(objs))
return sorted(objs, key=lambda obj: (key(obj), idxs[obj])) | [
"def",
"csort",
"(",
"objs",
",",
"key",
")",
":",
"idxs",
"=",
"dict",
"(",
"(",
"obj",
",",
"i",
")",
"for",
"(",
"i",
",",
"obj",
")",
"in",
"enumerate",
"(",
"objs",
")",
")",
"return",
"sorted",
"(",
"objs",
",",
"key",
"=",
"lambda",
"o... | 46 | 14.5 |
def query_file(self, path, fetchall=False, **params):
"""Like Connection.query, but takes a filename to load a query from."""
# If path doesn't exists
if not os.path.exists(path):
raise IOError("File '{}' not found!".format(path))
# If it's a directory
if os.path.is... | [
"def",
"query_file",
"(",
"self",
",",
"path",
",",
"fetchall",
"=",
"False",
",",
"*",
"*",
"params",
")",
":",
"# If path doesn't exists",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"path",
")",
":",
"raise",
"IOError",
"(",
"\"File '{}' not f... | 35.470588 | 18.470588 |
def _set_cluster(self):
"""
Compute and set the cluster of atoms as a Molecule object. The siteato
coordinates are translated such that the absorbing atom(aka central
atom) is at the origin.
Returns:
Molecule
"""
center = self.struct[self.center_index... | [
"def",
"_set_cluster",
"(",
"self",
")",
":",
"center",
"=",
"self",
".",
"struct",
"[",
"self",
".",
"center_index",
"]",
".",
"coords",
"sphere",
"=",
"self",
".",
"struct",
".",
"get_neighbors",
"(",
"self",
".",
"struct",
"[",
"self",
".",
"center_... | 38.526316 | 18.842105 |
def BuscarLocalidades(self, cod_prov, cod_localidad=None, consultar=True):
"Devuelve la localidad o la consulta en AFIP (uso interno)"
# si no se especifíca cod_localidad, es util para reconstruir la cache
import wslpg_datos as datos
if not str(cod_localidad) in datos.LOCALIDADES and con... | [
"def",
"BuscarLocalidades",
"(",
"self",
",",
"cod_prov",
",",
"cod_localidad",
"=",
"None",
",",
"consultar",
"=",
"True",
")",
":",
"# si no se especifíca cod_localidad, es util para reconstruir la cache",
"import",
"wslpg_datos",
"as",
"datos",
"if",
"not",
"str",
... | 54.357143 | 20.071429 |
def generate_model_cls(config, schema, model_name, raml_resource,
es_based=True):
""" Generate model class.
Engine DB field types are determined using `type_fields` and only those
types may be used.
:param schema: Model schema dict parsed from RAML.
:param model_name: String... | [
"def",
"generate_model_cls",
"(",
"config",
",",
"schema",
",",
"model_name",
",",
"raml_resource",
",",
"es_based",
"=",
"True",
")",
":",
"from",
"nefertari",
".",
"authentication",
".",
"models",
"import",
"AuthModelMethodsMixin",
"base_cls",
"=",
"engine",
"... | 38.270588 | 19.470588 |
def list_functions(awsclient):
"""List the deployed lambda functions and print configuration.
:return: exit_code
"""
client_lambda = awsclient.get_client('lambda')
response = client_lambda.list_functions()
for function in response['Functions']:
log.info(function['FunctionName'])
... | [
"def",
"list_functions",
"(",
"awsclient",
")",
":",
"client_lambda",
"=",
"awsclient",
".",
"get_client",
"(",
"'lambda'",
")",
"response",
"=",
"client_lambda",
".",
"list_functions",
"(",
")",
"for",
"function",
"in",
"response",
"[",
"'Functions'",
"]",
":... | 40.277778 | 17.777778 |
def dotter(self):
"""Prints formatted time to stdout at the start of a line, as well as a "."
whenever the length of the line is equal or lesser than 80 "." long"""
if self.globalcount <= 80:
sys.stdout.write('.')
self.globalcount += 1
else:
sys.stdout... | [
"def",
"dotter",
"(",
"self",
")",
":",
"if",
"self",
".",
"globalcount",
"<=",
"80",
":",
"sys",
".",
"stdout",
".",
"write",
"(",
"'.'",
")",
"self",
".",
"globalcount",
"+=",
"1",
"else",
":",
"sys",
".",
"stdout",
".",
"write",
"(",
"'\\n.'",
... | 39.777778 | 9.222222 |
def upload(self, f):
"""Upload a file to the Puush account.
Parameters:
* f: The file. Either a path to a file or a file-like object.
"""
if hasattr(f, 'read'):
needs_closing = False
else:
f = open(f, 'rb')
needs_closing = ... | [
"def",
"upload",
"(",
"self",
",",
"f",
")",
":",
"if",
"hasattr",
"(",
"f",
",",
"'read'",
")",
":",
"needs_closing",
"=",
"False",
"else",
":",
"f",
"=",
"open",
"(",
"f",
",",
"'rb'",
")",
"needs_closing",
"=",
"True",
"# The Puush server can't hand... | 37.27907 | 20.930233 |
def open_shot_path(self, *args, **kwargs):
"""Open the currently selected shot in the filebrowser
:returns: None
:rtype: None
:raises: None
"""
f = self.shot_path_le.text()
d = os.path.dirname(f)
osinter = get_interface()
osinter.open_path(d) | [
"def",
"open_shot_path",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"f",
"=",
"self",
".",
"shot_path_le",
".",
"text",
"(",
")",
"d",
"=",
"os",
".",
"path",
".",
"dirname",
"(",
"f",
")",
"osinter",
"=",
"get_interface",
... | 27.727273 | 12 |
def _set_routes(self, v, load=False):
"""
Setter method for routes, mapped from YANG variable /rbridge_id/vrf/address_family/ipv6/unicast/ipv6/import/routes (list)
If this variable is read-only (config: false) in the
source YANG file, then _set_routes is considered as a private
method. Backends look... | [
"def",
"_set_routes",
"(",
"self",
",",
"v",
",",
"load",
"=",
"False",
")",
":",
"if",
"hasattr",
"(",
"v",
",",
"\"_utype\"",
")",
":",
"v",
"=",
"v",
".",
"_utype",
"(",
"v",
")",
"try",
":",
"t",
"=",
"YANGDynClass",
"(",
"v",
",",
"base",
... | 96.25 | 47.625 |
def _sample_next(target_log_prob_fn,
current_state_parts,
step_sizes,
max_doublings,
current_target_log_prob,
batch_rank,
seed=None,
name=None):
"""Applies a single iteration of slice sampling update... | [
"def",
"_sample_next",
"(",
"target_log_prob_fn",
",",
"current_state_parts",
",",
"step_sizes",
",",
"max_doublings",
",",
"current_target_log_prob",
",",
"batch_rank",
",",
"seed",
"=",
"None",
",",
"name",
"=",
"None",
")",
":",
"with",
"tf",
".",
"compat",
... | 44.522293 | 23.503185 |
def unregisterHandler(self, fh):
"""
Unregister a file descriptor. Clean data, if such operation has been scheduled.
Parameters
----------
fh : int
File descriptor.
"""
try:
self.fds.remove(fh)
except KeyError:
pass
... | [
"def",
"unregisterHandler",
"(",
"self",
",",
"fh",
")",
":",
"try",
":",
"self",
".",
"fds",
".",
"remove",
"(",
"fh",
")",
"except",
"KeyError",
":",
"pass",
"self",
".",
"lock",
".",
"acquire",
"(",
")",
"try",
":",
"self",
".",
"data",
".",
"... | 19.185185 | 23.555556 |
def get_occurrences(self, start, end, *, limit=None, query=None, order_by=None, batch=None):
"""
Returns all the occurrences of a seriesMaster event for a specified time range.
:type start: datetime
:param start: the start of the time range
:type end: datetime
:param end:... | [
"def",
"get_occurrences",
"(",
"self",
",",
"start",
",",
"end",
",",
"*",
",",
"limit",
"=",
"None",
",",
"query",
"=",
"None",
",",
"order_by",
"=",
"None",
",",
"batch",
"=",
"None",
")",
":",
"if",
"self",
".",
"event_type",
"!=",
"EventType",
... | 41.171429 | 22.2 |
def generate_method(service_module, service_name, method_name):
"""Generate a method for the given Thrift service.
:param service_module:
Thrift-generated service module
:param service_name:
Name of the Thrift service
:param method_name:
Method being called
"""
assert se... | [
"def",
"generate_method",
"(",
"service_module",
",",
"service_name",
",",
"method_name",
")",
":",
"assert",
"service_module",
"assert",
"service_name",
"assert",
"method_name",
"args_type",
"=",
"getattr",
"(",
"service_module",
",",
"method_name",
"+",
"'_args'",
... | 34.603175 | 18.293651 |
def f_explore(self, build_dict):
"""Prepares the trajectory to explore the parameter space.
To explore the parameter space you need to provide a dictionary with the names of the
parameters to explore as keys and iterables specifying the exploration ranges as values.
All iterables need... | [
"def",
"f_explore",
"(",
"self",
",",
"build_dict",
")",
":",
"for",
"run_idx",
"in",
"range",
"(",
"len",
"(",
"self",
")",
")",
":",
"if",
"self",
".",
"f_is_completed",
"(",
"run_idx",
")",
":",
"raise",
"TypeError",
"(",
"'You cannot explore a trajecto... | 38.513043 | 28.66087 |
def import_string(dotted_path, dotted_attributes=None):
"""
Import a dotted module path and return the attribute/class designated by the
last name in the path. When a dotted attribute path is also provided, the
dotted attribute path would be applied to the attribute/class retrieved from
the first st... | [
"def",
"import_string",
"(",
"dotted_path",
",",
"dotted_attributes",
"=",
"None",
")",
":",
"try",
":",
"module_path",
",",
"class_name",
"=",
"dotted_path",
".",
"rsplit",
"(",
"\".\"",
",",
"1",
")",
"except",
"ValueError",
":",
"raise",
"ImportError",
"(... | 37.289474 | 21.236842 |
def neverCalledWith(cls, spy, *args, **kwargs): #pylint: disable=invalid-name
"""
Checking the inspector is never called with partial args/kwargs
Args: SinonSpy, args/kwargs
"""
cls.__is_spy(spy)
if not (spy.neverCalledWith(*args, **kwargs)):
raise cls.failExc... | [
"def",
"neverCalledWith",
"(",
"cls",
",",
"spy",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"#pylint: disable=invalid-name",
"cls",
".",
"__is_spy",
"(",
"spy",
")",
"if",
"not",
"(",
"spy",
".",
"neverCalledWith",
"(",
"*",
"args",
",",
"*"... | 41.5 | 13.75 |
def transpose(self) -> 'TextDiagramDrawer':
"""Returns the same diagram, but mirrored across its diagonal."""
out = TextDiagramDrawer()
out.entries = {(y, x): _DiagramText(v.transposed_text, v.text)
for (x, y), v in self.entries.items()}
out.vertical_lines = [_Vert... | [
"def",
"transpose",
"(",
"self",
")",
"->",
"'TextDiagramDrawer'",
":",
"out",
"=",
"TextDiagramDrawer",
"(",
")",
"out",
".",
"entries",
"=",
"{",
"(",
"y",
",",
"x",
")",
":",
"_DiagramText",
"(",
"v",
".",
"transposed_text",
",",
"v",
".",
"text",
... | 53.333333 | 15.416667 |
def _restore_and_log_checkpoint(self, actor):
"""Restore an actor from a checkpoint if available and log any errors.
This should only be called on workers that have just executed an actor
creation task.
Args:
actor: The actor to restore from a checkpoint.
"""
... | [
"def",
"_restore_and_log_checkpoint",
"(",
"self",
",",
"actor",
")",
":",
"actor_id",
"=",
"self",
".",
"_worker",
".",
"actor_id",
"try",
":",
"checkpoints",
"=",
"ray",
".",
"actor",
".",
"get_checkpoints_for_actor",
"(",
"actor_id",
")",
"if",
"len",
"("... | 47.815789 | 18.736842 |
def task_succeeded(sender=None, **kwargs): # pylint: disable=unused-argument
"""
Update the status record accordingly when a :py:class:`UserTaskMixin` finishes successfully.
"""
if isinstance(sender, UserTaskMixin):
status = sender.status
# Failed tasks with good exception handling did ... | [
"def",
"task_succeeded",
"(",
"sender",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"# pylint: disable=unused-argument",
"if",
"isinstance",
"(",
"sender",
",",
"UserTaskMixin",
")",
":",
"status",
"=",
"sender",
".",
"status",
"# Failed tasks with good except... | 57.2 | 28.2 |
def _acquire_lock(self, key: str, session_id: str, seconds_to_lock: float, metadata: Any) \
-> Optional[ConnectedConsulLockInformation]:
"""
Attempts to get the lock using the given session.
:param key: name of the lock
:param session_id: the identifier of the Consul session ... | [
"def",
"_acquire_lock",
"(",
"self",
",",
"key",
":",
"str",
",",
"session_id",
":",
"str",
",",
"seconds_to_lock",
":",
"float",
",",
"metadata",
":",
"Any",
")",
"->",
"Optional",
"[",
"ConnectedConsulLockInformation",
"]",
":",
"lock_information",
"=",
"C... | 57.272727 | 25.090909 |
def _c2x(self, c):
""" Convert cheb coordinates to windowdow coordinates """
return 0.5 * (self.window[0] + self.window[1] +
c * (self.window[1] - self.window[0])) | [
"def",
"_c2x",
"(",
"self",
",",
"c",
")",
":",
"return",
"0.5",
"*",
"(",
"self",
".",
"window",
"[",
"0",
"]",
"+",
"self",
".",
"window",
"[",
"1",
"]",
"+",
"c",
"*",
"(",
"self",
".",
"window",
"[",
"1",
"]",
"-",
"self",
".",
"window"... | 49.5 | 14.25 |
def get_deffacts(self):
"""Return the existing deffacts sorted by the internal order"""
return sorted(self._get_by_type(DefFacts), key=lambda d: d.order) | [
"def",
"get_deffacts",
"(",
"self",
")",
":",
"return",
"sorted",
"(",
"self",
".",
"_get_by_type",
"(",
"DefFacts",
")",
",",
"key",
"=",
"lambda",
"d",
":",
"d",
".",
"order",
")"
] | 55.666667 | 16.666667 |
def create_ants_metric(fixed,
moving,
metric_type='MeanSquares',
fixed_mask=None,
moving_mask=None,
sampling_strategy='regular',
sampling_percentage=1):
"""
Arguments
... | [
"def",
"create_ants_metric",
"(",
"fixed",
",",
"moving",
",",
"metric_type",
"=",
"'MeanSquares'",
",",
"fixed_mask",
"=",
"None",
",",
"moving_mask",
"=",
"None",
",",
"sampling_strategy",
"=",
"'regular'",
",",
"sampling_percentage",
"=",
"1",
")",
":",
"di... | 32.104478 | 18.462687 |
def detect_cycle(graph):
"""
search the given directed graph for cycles
returns None if the given graph is cycle free
otherwise it returns a path through the graph that contains a cycle
:param graph:
:return:
"""
visited_nodes = set()
for node in list(graph):
if node not i... | [
"def",
"detect_cycle",
"(",
"graph",
")",
":",
"visited_nodes",
"=",
"set",
"(",
")",
"for",
"node",
"in",
"list",
"(",
"graph",
")",
":",
"if",
"node",
"not",
"in",
"visited_nodes",
":",
"cycle",
"=",
"_dfs_cycle_detect",
"(",
"graph",
",",
"node",
",... | 25.555556 | 19.555556 |
def evaluate(self, verbose=True, passes=None):
"""Summary
Returns:
TYPE: Description
"""
if self.is_pivot:
index, pivot, columns = LazyOpResult(
self.expr,
self.weld_type,
0
).evaluate(verbose=verbose, p... | [
"def",
"evaluate",
"(",
"self",
",",
"verbose",
"=",
"True",
",",
"passes",
"=",
"None",
")",
":",
"if",
"self",
".",
"is_pivot",
":",
"index",
",",
"pivot",
",",
"columns",
"=",
"LazyOpResult",
"(",
"self",
".",
"expr",
",",
"self",
".",
"weld_type"... | 32.057143 | 14.771429 |
def remove_datastore(service_instance, datastore_ref):
'''
Creates a VMFS datastore from a disk_id
service_instance
The Service Instance Object containing the datastore
datastore_ref
The reference to the datastore to remove
'''
ds_props = get_properties_of_managed_object(
... | [
"def",
"remove_datastore",
"(",
"service_instance",
",",
"datastore_ref",
")",
":",
"ds_props",
"=",
"get_properties_of_managed_object",
"(",
"datastore_ref",
",",
"[",
"'host'",
",",
"'info'",
",",
"'name'",
"]",
")",
"ds_name",
"=",
"ds_props",
"[",
"'name'",
... | 38.75 | 15.638889 |
def kerberos_ccache_init(principal, keytab_file, ccache_file=None):
"""
Checks whether kerberos credential cache has ticket-granting ticket that is valid for at least
an hour.
Default ccache is used unless ccache_file is provided. In that case, KRB5CCNAME environment
variable is set to the value of... | [
"def",
"kerberos_ccache_init",
"(",
"principal",
",",
"keytab_file",
",",
"ccache_file",
"=",
"None",
")",
":",
"tgt_valid",
"=",
"False",
"env",
"=",
"{",
"\"LC_ALL\"",
":",
"\"C\"",
"}",
"# klist uses locales to format date on RHEL7+",
"if",
"ccache_file",
":",
... | 39.463415 | 24.04878 |
def fut_ticker(gen_ticker: str, dt, freq: str, log=logs.LOG_LEVEL) -> str:
"""
Get proper ticker from generic ticker
Args:
gen_ticker: generic ticker
dt: date
freq: futures contract frequency
log: level of logs
Returns:
str: exact futures ticker
"""
logg... | [
"def",
"fut_ticker",
"(",
"gen_ticker",
":",
"str",
",",
"dt",
",",
"freq",
":",
"str",
",",
"log",
"=",
"logs",
".",
"LOG_LEVEL",
")",
"->",
"str",
":",
"logger",
"=",
"logs",
".",
"get_logger",
"(",
"fut_ticker",
",",
"level",
"=",
"log",
")",
"d... | 35.293103 | 21.982759 |
def cancel_job(agent, project_name, job_id):
"""
cancel a job.
If the job is pending, it will be removed. If the job is running, it will be terminated.
"""
prevstate = agent.cancel(project_name, job_id)['prevstate']
if prevstate == 'pending':
sqllite_agent.execute(ScrapydJobExtInfoSQLSet... | [
"def",
"cancel_job",
"(",
"agent",
",",
"project_name",
",",
"job_id",
")",
":",
"prevstate",
"=",
"agent",
".",
"cancel",
"(",
"project_name",
",",
"job_id",
")",
"[",
"'prevstate'",
"]",
"if",
"prevstate",
"==",
"'pending'",
":",
"sqllite_agent",
".",
"e... | 42.25 | 18.75 |
def has_hash_of(self, destpath, code, package):
"""Determine if a file has the hash of the code."""
if destpath is not None and os.path.isfile(destpath):
with openfile(destpath, "r") as opened:
compiled = readfile(opened)
hashash = gethash(compiled)
if... | [
"def",
"has_hash_of",
"(",
"self",
",",
"destpath",
",",
"code",
",",
"package",
")",
":",
"if",
"destpath",
"is",
"not",
"None",
"and",
"os",
".",
"path",
".",
"isfile",
"(",
"destpath",
")",
":",
"with",
"openfile",
"(",
"destpath",
",",
"\"r\"",
"... | 48.111111 | 12.888889 |
def auto_complete(self, term, state=None, postcode=None, max_results=None):
"""
Gets a list of addresses that begin with the given term.
"""
self._validate_state(state)
params = {"term": term, "state": state, "postcode": postcode,
"max_results": max_results or s... | [
"def",
"auto_complete",
"(",
"self",
",",
"term",
",",
"state",
"=",
"None",
",",
"postcode",
"=",
"None",
",",
"max_results",
"=",
"None",
")",
":",
"self",
".",
"_validate_state",
"(",
"state",
")",
"params",
"=",
"{",
"\"term\"",
":",
"term",
",",
... | 49.5 | 18 |
def route_stanza(self, stanza):
"""Process stanza not addressed to us.
Return "recipient-unavailable" return if it is not
"error" nor "result" stanza.
This method should be overriden in derived classes if they
are supposed to handle stanzas not addressed directly to local
... | [
"def",
"route_stanza",
"(",
"self",
",",
"stanza",
")",
":",
"if",
"stanza",
".",
"stanza_type",
"not",
"in",
"(",
"\"error\"",
",",
"\"result\"",
")",
":",
"response",
"=",
"stanza",
".",
"make_error_response",
"(",
"u\"recipient-unavailable\"",
")",
"self",
... | 35.235294 | 20 |
def doctemplate(*args):
"""Return a decorator putting ``args`` into the docstring of the decorated ``func``.
>>> @doctemplate('spam', 'spam')
... def spam():
... '''Returns %s, lovely %s.'''
... return 'Spam'
>>> spam.__doc__
'Returns spam, lovely spam.'
"""
def decorator(f... | [
"def",
"doctemplate",
"(",
"*",
"args",
")",
":",
"def",
"decorator",
"(",
"func",
")",
":",
"func",
".",
"__doc__",
"=",
"func",
".",
"__doc__",
"%",
"tuple",
"(",
"args",
")",
"return",
"func",
"return",
"decorator"
] | 26.8 | 15.4 |
def state(self, states=None):
"""Filter by state.
:param tags: States to filter.
:type tags: ``list``
:return: A list of Node objects.
:rtype: ``list`` of :class:`Node`
"""
if states is None or not states:
return self
nodes = []
f... | [
"def",
"state",
"(",
"self",
",",
"states",
"=",
"None",
")",
":",
"if",
"states",
"is",
"None",
"or",
"not",
"states",
":",
"return",
"self",
"nodes",
"=",
"[",
"]",
"for",
"node",
"in",
"self",
".",
"nodes",
":",
"if",
"any",
"(",
"state",
".",... | 28.529412 | 13.470588 |
def join(self,timeout=None):
"""Join all threads in this group.
If the optional "timeout" argument is given, give up after that many
seconds. This method returns True is the threads were successfully
joined, False if a timeout occurred.
"""
if timeout is None:
... | [
"def",
"join",
"(",
"self",
",",
"timeout",
"=",
"None",
")",
":",
"if",
"timeout",
"is",
"None",
":",
"for",
"thread",
"in",
"self",
".",
"__threads",
":",
"thread",
".",
"join",
"(",
")",
"else",
":",
"deadline",
"=",
"_time",
"(",
")",
"+",
"t... | 34.947368 | 12.157895 |
def query(cls, visibility=None, api=None):
"""Query ( List ) datasets
:param visibility: If provided as 'public', retrieves public datasets
:param api: Api instance
:return: Collection object
"""
api = api if api else cls._API
return super(Dataset, cls)._query(
... | [
"def",
"query",
"(",
"cls",
",",
"visibility",
"=",
"None",
",",
"api",
"=",
"None",
")",
":",
"api",
"=",
"api",
"if",
"api",
"else",
"cls",
".",
"_API",
"return",
"super",
"(",
"Dataset",
",",
"cls",
")",
".",
"_query",
"(",
"url",
"=",
"cls",
... | 32.384615 | 11.230769 |
def expand_focussed(self):
"""
Expand currently focussed position; works only if the underlying
tree allows it.
"""
if implementsCollapseAPI(self._tree):
w, focuspos = self.get_focus()
self._tree.expand(focuspos)
self._walker.clear_cache()
... | [
"def",
"expand_focussed",
"(",
"self",
")",
":",
"if",
"implementsCollapseAPI",
"(",
"self",
".",
"_tree",
")",
":",
"w",
",",
"focuspos",
"=",
"self",
".",
"get_focus",
"(",
")",
"self",
".",
"_tree",
".",
"expand",
"(",
"focuspos",
")",
"self",
".",
... | 33.3 | 8.7 |
def failback(self, force_full_copy=None):
"""
Fails back a replication session.
This can be applied on a replication session that is failed over. Fail
back will synchronize the changes done to original destination back to
original source site and will restore the original direct... | [
"def",
"failback",
"(",
"self",
",",
"force_full_copy",
"=",
"None",
")",
":",
"req_body",
"=",
"self",
".",
"_cli",
".",
"make_body",
"(",
"forceFullCopy",
"=",
"force_full_copy",
")",
"resp",
"=",
"self",
".",
"action",
"(",
"'failback'",
",",
"*",
"*"... | 41.666667 | 20.444444 |
def hardware_custom_profile_kap_custom_profile_bfd_vxlan_bfd_vxlan_hello_interval(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
hardware = ET.SubElement(config, "hardware", xmlns="urn:brocade.com:mgmt:brocade-hardware")
custom_profile = ET.SubElement(h... | [
"def",
"hardware_custom_profile_kap_custom_profile_bfd_vxlan_bfd_vxlan_hello_interval",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"config",
"=",
"ET",
".",
"Element",
"(",
"\"config\"",
")",
"hardware",
"=",
"ET",
".",
"SubElement",
"(",
"config",
",",
"\"ha... | 56.133333 | 25.666667 |
def sends(self, tag=None, fromdate=None, todate=None):
"""
Gets a total count of emails you’ve sent out.
"""
return self.call("GET", "/stats/outbound/sends", tag=tag, fromdate=fromdate, todate=todate) | [
"def",
"sends",
"(",
"self",
",",
"tag",
"=",
"None",
",",
"fromdate",
"=",
"None",
",",
"todate",
"=",
"None",
")",
":",
"return",
"self",
".",
"call",
"(",
"\"GET\"",
",",
"\"/stats/outbound/sends\"",
",",
"tag",
"=",
"tag",
",",
"fromdate",
"=",
"... | 45.6 | 17.2 |
def subscribed(self, build_root, handlers):
"""Bulk subscribe generator for StreamableWatchmanClient.
:param str build_root: the build_root for all subscriptions.
:param iterable handlers: a sequence of Watchman.EventHandler namedtuple objects.
:yields: a stream of tuples in the form (subscription_name... | [
"def",
"subscribed",
"(",
"self",
",",
"build_root",
",",
"handlers",
")",
":",
"command_list",
"=",
"[",
"[",
"'subscribe'",
",",
"build_root",
",",
"handler",
".",
"name",
",",
"handler",
".",
"metadata",
"]",
"for",
"handler",
"in",
"handlers",
"]",
"... | 41.037037 | 20.666667 |
def _repr_html_(self, header=True):
"""Representation of the parameters in html for notebook display."""
name = adjust_name_for_printing(self.name) + "."
names = self.parameter_names()
desc = self._description_str
iops = OrderedDict()
for opname in self._index_operations:... | [
"def",
"_repr_html_",
"(",
"self",
",",
"header",
"=",
"True",
")",
":",
"name",
"=",
"adjust_name_for_printing",
"(",
"self",
".",
"name",
")",
"+",
"\".\"",
"names",
"=",
"self",
".",
"parameter_names",
"(",
")",
"desc",
"=",
"self",
".",
"_description... | 70.193548 | 46.806452 |
def _fetch_seq_ncbi(ac, start_i=None, end_i=None):
"""Fetch sequences from NCBI using the eutils interface.
An interbase interval may be optionally provided with start_i and
end_i. NCBI eutils will return just the requested subsequence,
which might greatly reduce payload sizes (especially with
chro... | [
"def",
"_fetch_seq_ncbi",
"(",
"ac",
",",
"start_i",
"=",
"None",
",",
"end_i",
"=",
"None",
")",
":",
"db",
"=",
"\"protein\"",
"if",
"ac",
"[",
"1",
"]",
"==",
"\"P\"",
"else",
"\"nucleotide\"",
"url_fmt",
"=",
"(",
"\"https://eutils.ncbi.nlm.nih.gov/entre... | 33.630769 | 23.246154 |
def snapshot(self):
"""Return a new library item which is a copy of this one with any dynamic behavior made static."""
data_item = self.__class__()
# data format (temporary until moved to buffered data source)
data_item.large_format = self.large_format
data_item.set_data_and_meta... | [
"def",
"snapshot",
"(",
"self",
")",
":",
"data_item",
"=",
"self",
".",
"__class__",
"(",
")",
"# data format (temporary until moved to buffered data source)",
"data_item",
".",
"large_format",
"=",
"self",
".",
"large_format",
"data_item",
".",
"set_data_and_metadata"... | 49.117647 | 13.117647 |
def _print_checker_doc(checker_name, info, stream=None):
"""Helper method for print_full_documentation.
Also used by doc/exts/pylint_extensions.py.
"""
if not stream:
stream = sys.stdout
doc = info.get("doc")
module = info.get("module")
msgs = info.g... | [
"def",
"_print_checker_doc",
"(",
"checker_name",
",",
"info",
",",
"stream",
"=",
"None",
")",
":",
"if",
"not",
"stream",
":",
"stream",
"=",
"sys",
".",
"stdout",
"doc",
"=",
"info",
".",
"get",
"(",
"\"doc\"",
")",
"module",
"=",
"info",
".",
"ge... | 39.052632 | 15.245614 |
def cluster_status(self, cluster_identifier):
"""
Return status of a cluster
:param cluster_identifier: unique identifier of a cluster
:type cluster_identifier: str
"""
conn = self.get_conn()
try:
response = conn.describe_clusters(
Clu... | [
"def",
"cluster_status",
"(",
"self",
",",
"cluster_identifier",
")",
":",
"conn",
"=",
"self",
".",
"get_conn",
"(",
")",
"try",
":",
"response",
"=",
"conn",
".",
"describe_clusters",
"(",
"ClusterIdentifier",
"=",
"cluster_identifier",
")",
"[",
"'Clusters'... | 36.785714 | 13.642857 |
async def send(self, data, namespace=None, callback=None):
"""Send a message to the server.
The only difference with the :func:`socketio.Client.send` method is
that when the ``namespace`` argument is not given the namespace
associated with the class is used.
Note: this method i... | [
"async",
"def",
"send",
"(",
"self",
",",
"data",
",",
"namespace",
"=",
"None",
",",
"callback",
"=",
"None",
")",
":",
"return",
"await",
"self",
".",
"client",
".",
"send",
"(",
"data",
",",
"namespace",
"=",
"namespace",
"or",
"self",
".",
"names... | 42.75 | 18.5 |
def inspect_distribution(self, image, auth_config=None):
"""
Get image digest and platform information by contacting the registry.
Args:
image (str): The image name to inspect
auth_config (dict): Override the credentials that are found in the
config for t... | [
"def",
"inspect_distribution",
"(",
"self",
",",
"image",
",",
"auth_config",
"=",
"None",
")",
":",
"registry",
",",
"_",
"=",
"auth",
".",
"resolve_repository_name",
"(",
"image",
")",
"headers",
"=",
"{",
"}",
"if",
"auth_config",
"is",
"None",
":",
"... | 34.363636 | 22.363636 |
def vis(bs):
"""
Function to visualize byte streams. Split into bytes, print to console.
:param bs: BYTE STRING
"""
bs = bytearray(bs)
symbols_in_one_line = 8
n = len(bs) // symbols_in_one_line
i = 0
for i in range(n):
print(str(i*symbols_in_one_line)+" | "+" ".join(["%02X" %... | [
"def",
"vis",
"(",
"bs",
")",
":",
"bs",
"=",
"bytearray",
"(",
"bs",
")",
"symbols_in_one_line",
"=",
"8",
"n",
"=",
"len",
"(",
"bs",
")",
"//",
"symbols_in_one_line",
"i",
"=",
"0",
"for",
"i",
"in",
"range",
"(",
"n",
")",
":",
"print",
"(",
... | 43.692308 | 27.846154 |
def revoke_role(self, role_name, principal_name, principal_type):
"""
Parameters:
- role_name
- principal_name
- principal_type
"""
self.send_revoke_role(role_name, principal_name, principal_type)
return self.recv_revoke_role() | [
"def",
"revoke_role",
"(",
"self",
",",
"role_name",
",",
"principal_name",
",",
"principal_type",
")",
":",
"self",
".",
"send_revoke_role",
"(",
"role_name",
",",
"principal_name",
",",
"principal_type",
")",
"return",
"self",
".",
"recv_revoke_role",
"(",
")"... | 28.222222 | 16.222222 |
def eq(self, o):
"""
Equal
:param o: The ohter operand
:return: TrueResult(), FalseResult(), or MaybeResult()
"""
if (self.is_integer
and o.is_integer
):
# Two integers
if self.lower_bound == o.lower_bound:
... | [
"def",
"eq",
"(",
"self",
",",
"o",
")",
":",
"if",
"(",
"self",
".",
"is_integer",
"and",
"o",
".",
"is_integer",
")",
":",
"# Two integers",
"if",
"self",
".",
"lower_bound",
"==",
"o",
".",
"lower_bound",
":",
"# They are equal",
"return",
"TrueResult... | 25.310345 | 16.827586 |
def invert_dictset(d):
"""Invert a dictionary with keys matching a set of values, turned into lists."""
# Based on recipe from ASPN
result = {}
for k, c in d.items():
for v in c:
keys = result.setdefault(v, [])
keys.append(k)
return result | [
"def",
"invert_dictset",
"(",
"d",
")",
":",
"# Based on recipe from ASPN",
"result",
"=",
"{",
"}",
"for",
"k",
",",
"c",
"in",
"d",
".",
"items",
"(",
")",
":",
"for",
"v",
"in",
"c",
":",
"keys",
"=",
"result",
".",
"setdefault",
"(",
"v",
",",
... | 31.444444 | 14.111111 |
def nsum0(lx):
"""
Accepts log-values as input, exponentiates them, sums down the rows
(first dimension), normalizes and returns the result.
Handles underflow by rescaling so that the largest values is exactly 1.0.
"""
lx = numpy.asarray(lx)
base = lx.max()
x = numpy.exp(lx - base)
ssum = x.sum(0)
r... | [
"def",
"nsum0",
"(",
"lx",
")",
":",
"lx",
"=",
"numpy",
".",
"asarray",
"(",
"lx",
")",
"base",
"=",
"lx",
".",
"max",
"(",
")",
"x",
"=",
"numpy",
".",
"exp",
"(",
"lx",
"-",
"base",
")",
"ssum",
"=",
"x",
".",
"sum",
"(",
"0",
")",
"re... | 28.0625 | 20.0625 |
def get_git_status(git_path='git'):
"""Returns the state of the git working copy
"""
status_output = subprocess.call((git_path, 'diff-files', '--quiet'))
if status_output != 0:
return 'UNCLEAN: Modified working tree'
else:
# check index for changes
status_output = subprocess.... | [
"def",
"get_git_status",
"(",
"git_path",
"=",
"'git'",
")",
":",
"status_output",
"=",
"subprocess",
".",
"call",
"(",
"(",
"git_path",
",",
"'diff-files'",
",",
"'--quiet'",
")",
")",
"if",
"status_output",
"!=",
"0",
":",
"return",
"'UNCLEAN: Modified worki... | 39.642857 | 14.857143 |
def _read_frame(cls, reader):
'''
Read a single frame from a Reader. Will return None if there is an
incomplete frame in the stream.
Raise MissingFooter if there's a problem reading the footer byte.
'''
frame_type = reader.read_octet()
channel_id = reader.read_s... | [
"def",
"_read_frame",
"(",
"cls",
",",
"reader",
")",
":",
"frame_type",
"=",
"reader",
".",
"read_octet",
"(",
")",
"channel_id",
"=",
"reader",
".",
"read_short",
"(",
")",
"size",
"=",
"reader",
".",
"read_long",
"(",
")",
"payload",
"=",
"Reader",
... | 35.576923 | 21.115385 |
def bm3_p(v, v0, k0, k0p, p_ref=0.0):
"""
calculate pressure from 3rd order Birch-Murnathan equation
:param v: volume at different pressures
:param v0: volume at reference conditions
:param k0: bulk modulus at reference conditions
:param k0p: pressure derivative of bulk modulus at different con... | [
"def",
"bm3_p",
"(",
"v",
",",
"v0",
",",
"k0",
",",
"k0p",
",",
"p_ref",
"=",
"0.0",
")",
":",
"return",
"cal_p_bm3",
"(",
"v",
",",
"[",
"v0",
",",
"k0",
",",
"k0p",
"]",
",",
"p_ref",
"=",
"p_ref",
")"
] | 37.416667 | 13.25 |
def get_measurement_responses(self):
"""Return a dictionary of sip_responses for the modeled SIP spectra
Note that this function does NOT check that each frequency contains the
same configurations!
Returns
-------
responses : dict
Dictionary with configurati... | [
"def",
"get_measurement_responses",
"(",
"self",
")",
":",
"# take configurations from first tomodir",
"configs",
"=",
"self",
".",
"tds",
"[",
"sorted",
"(",
"self",
".",
"tds",
".",
"keys",
"(",
")",
")",
"[",
"0",
"]",
"]",
".",
"configs",
".",
"configs... | 33.807692 | 17.576923 |
def lfsr_next_one_seed(seed_iter, min_value_shift):
"""High-quality seeding for LFSR generators.
The LFSR generator components discard a certain number of their lower bits
when generating each output. The significant bits of their state must not
all be zero. We must ensure that when seeding the gen... | [
"def",
"lfsr_next_one_seed",
"(",
"seed_iter",
",",
"min_value_shift",
")",
":",
"try",
":",
"seed",
"=",
"seed_iter",
".",
"next",
"(",
")",
"except",
"StopIteration",
":",
"return",
"0xFFFFFFFF",
"else",
":",
"if",
"seed",
"is",
"None",
":",
"return",
"0... | 41.2 | 20.5 |
def loads(s, single=False):
"""
Deserialize MRX string representations
Args:
s (str): a MRX string
single (bool): if `True`, only return the first Xmrs object
Returns:
a generator of Xmrs objects (unless *single* is `True`)
"""
corpus = etree.fromstring(s)
if single:... | [
"def",
"loads",
"(",
"s",
",",
"single",
"=",
"False",
")",
":",
"corpus",
"=",
"etree",
".",
"fromstring",
"(",
"s",
")",
"if",
"single",
":",
"ds",
"=",
"_deserialize_mrs",
"(",
"next",
"(",
"corpus",
")",
")",
"else",
":",
"ds",
"=",
"(",
"_de... | 27.375 | 18.375 |
def merge_dictionaries(current, new, only_defaults=False, template_special_case=False):
'''
Merge two settings dictionaries, recording how many changes were needed.
'''
changes = 0
for key, value in new.items():
if key not in current:
if hasattr(global_settings, key):
... | [
"def",
"merge_dictionaries",
"(",
"current",
",",
"new",
",",
"only_defaults",
"=",
"False",
",",
"template_special_case",
"=",
"False",
")",
":",
"changes",
"=",
"0",
"for",
"key",
",",
"value",
"in",
"new",
".",
"items",
"(",
")",
":",
"if",
"key",
"... | 45.254902 | 19.764706 |
def geometry(self):
"""returns the feature geometry"""
if arcpyFound:
if self._geom is None:
if 'feature' in self._dict:
self._geom = arcpy.AsShape(self._dict['feature']['geometry'], esri_json=True)
elif 'geometry' in self._dict:
... | [
"def",
"geometry",
"(",
"self",
")",
":",
"if",
"arcpyFound",
":",
"if",
"self",
".",
"_geom",
"is",
"None",
":",
"if",
"'feature'",
"in",
"self",
".",
"_dict",
":",
"self",
".",
"_geom",
"=",
"arcpy",
".",
"AsShape",
"(",
"self",
".",
"_dict",
"["... | 43.7 | 18.9 |
def read(self, size = -1):
"""
Returns data bytes of size size from the current segment. If size is -1 it returns all the remaining data bytes from memory segment
"""
if size < -1:
raise Exception('You shouldnt be doing this')
if size == -1:
t = self.current_segment.remaining_len(self.current_position)
... | [
"def",
"read",
"(",
"self",
",",
"size",
"=",
"-",
"1",
")",
":",
"if",
"size",
"<",
"-",
"1",
":",
"raise",
"Exception",
"(",
"'You shouldnt be doing this'",
")",
"if",
"size",
"==",
"-",
"1",
":",
"t",
"=",
"self",
".",
"current_segment",
".",
"r... | 38.681818 | 24.681818 |
def create_precipitation_centered_CAG(input, output):
""" Get a CAG that examines the downstream effects of changes in precipitation. """
with open(input, "rb") as f:
G = pickle.load(f)
G = G.get_subgraph_for_concept(
"UN/events/weather/precipitation", depth=2, reverse=False
)
G.pru... | [
"def",
"create_precipitation_centered_CAG",
"(",
"input",
",",
"output",
")",
":",
"with",
"open",
"(",
"input",
",",
"\"rb\"",
")",
"as",
"f",
":",
"G",
"=",
"pickle",
".",
"load",
"(",
"f",
")",
"G",
"=",
"G",
".",
"get_subgraph_for_concept",
"(",
"\... | 35.529412 | 17.588235 |
def xml_to_dict(raw_xml):
"""Convert a XML stream into a dictionary.
This function transforms a xml stream into a dictionary. The
attributes are stored as single elements while child nodes are
stored into lists. The text node is stored using the special
key '__text__'.
This code is based on Wi... | [
"def",
"xml_to_dict",
"(",
"raw_xml",
")",
":",
"def",
"node_to_dict",
"(",
"node",
")",
":",
"d",
"=",
"{",
"}",
"d",
".",
"update",
"(",
"node",
".",
"items",
"(",
")",
")",
"text",
"=",
"getattr",
"(",
"node",
",",
"'text'",
",",
"None",
")",
... | 27.191489 | 23.638298 |
def add(self, coro, args=(), kwargs={}, first=True):
"""Add a coroutine in the scheduler. You can add arguments
(_args_, _kwargs_) to init the coroutine with."""
assert callable(coro), "'%s' not a callable object" % coro
coro = coro(*args, **kwargs)
if first:
se... | [
"def",
"add",
"(",
"self",
",",
"coro",
",",
"args",
"=",
"(",
")",
",",
"kwargs",
"=",
"{",
"}",
",",
"first",
"=",
"True",
")",
":",
"assert",
"callable",
"(",
"coro",
")",
",",
"\"'%s' not a callable object\"",
"%",
"coro",
"coro",
"=",
"coro",
... | 43.1 | 13 |
def _srvc_check_hdf_properties(self, traj):
"""Reads out the properties for storing new data into the hdf5file
:param traj:
The trajectory
"""
for attr_name in HDF5StorageService.ATTR_LIST:
try:
config = traj.f_get('config.hdf5.' + attr_name).f... | [
"def",
"_srvc_check_hdf_properties",
"(",
"self",
",",
"traj",
")",
":",
"for",
"attr_name",
"in",
"HDF5StorageService",
".",
"ATTR_LIST",
":",
"try",
":",
"config",
"=",
"traj",
".",
"f_get",
"(",
"'config.hdf5.'",
"+",
"attr_name",
")",
".",
"f_get",
"(",
... | 45.695652 | 25.413043 |
def create_single_payment(self, order_number, order_description, order_items, amount, return_url, contact=None, currency=None, lang=None, additional_params=None):
"""
Create a single payment.
Args:
contact: JSON describing a payer (see PaymentManager#create_contact)
orde... | [
"def",
"create_single_payment",
"(",
"self",
",",
"order_number",
",",
"order_description",
",",
"order_items",
",",
"amount",
",",
"return_url",
",",
"contact",
"=",
"None",
",",
"currency",
"=",
"None",
",",
"lang",
"=",
"None",
",",
"additional_params",
"="... | 53.096774 | 28.645161 |
def bitop_xor(self, dest, key, *keys):
"""Perform bitwise XOR operations between strings."""
return self.execute(b'BITOP', b'XOR', dest, key, *keys) | [
"def",
"bitop_xor",
"(",
"self",
",",
"dest",
",",
"key",
",",
"*",
"keys",
")",
":",
"return",
"self",
".",
"execute",
"(",
"b'BITOP'",
",",
"b'XOR'",
",",
"dest",
",",
"key",
",",
"*",
"keys",
")"
] | 54 | 8.333333 |
def create_element_dict(self):
"""Convert a UNTL Python object into a UNTL Python dictionary."""
untl_dict = {}
# Loop through all UNTL elements in the Python object.
for element in self.children:
# If an entry for the element list hasn't been made in the
# dictio... | [
"def",
"create_element_dict",
"(",
"self",
")",
":",
"untl_dict",
"=",
"{",
"}",
"# Loop through all UNTL elements in the Python object.",
"for",
"element",
"in",
"self",
".",
"children",
":",
"# If an entry for the element list hasn't been made in the",
"# dictionary, start an... | 46.633333 | 13.266667 |
def get_metadata_path(name):
"""Get reference metadata file path."""
return pkg_resources.resource_filename('voobly', os.path.join(METADATA_PATH, '{}.json'.format(name))) | [
"def",
"get_metadata_path",
"(",
"name",
")",
":",
"return",
"pkg_resources",
".",
"resource_filename",
"(",
"'voobly'",
",",
"os",
".",
"path",
".",
"join",
"(",
"METADATA_PATH",
",",
"'{}.json'",
".",
"format",
"(",
"name",
")",
")",
")"
] | 58.666667 | 25.666667 |
def list(self, log_level=values.unset, start_date=values.unset,
end_date=values.unset, limit=None, page_size=None):
"""
Lists AlertInstance records from the API as a list.
Unlike stream(), this operation is eager and will load `limit` records into
memory before returning.
... | [
"def",
"list",
"(",
"self",
",",
"log_level",
"=",
"values",
".",
"unset",
",",
"start_date",
"=",
"values",
".",
"unset",
",",
"end_date",
"=",
"values",
".",
"unset",
",",
"limit",
"=",
"None",
",",
"page_size",
"=",
"None",
")",
":",
"return",
"li... | 51.259259 | 26.296296 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.