text stringlengths 89 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 630 |
|---|---|---|---|
def first_image(self):
"""Ready-only attribute that provides the value of the first non-none image that's
not the thumbnail override field.
"""
# loop through image fields and grab the first non-none one
for model_field in self._meta.fields:
if isinstance(model_field,... | [
"def",
"first_image",
"(",
"self",
")",
":",
"# loop through image fields and grab the first non-none one",
"for",
"model_field",
"in",
"self",
".",
"_meta",
".",
"fields",
":",
"if",
"isinstance",
"(",
"model_field",
",",
"ImageField",
")",
":",
"if",
"model_field"... | 43.428571 | 13.214286 |
def set(self, tclass, tnum, tlvt=0, tdata=''):
"""set the values of the tag."""
if not isinstance(tdata, str):
raise TypeError("tag data must be str")
self.tagClass = tclass
self.tagNumber = tnum
self.tagLVT = tlvt
self.tagData = tdata | [
"def",
"set",
"(",
"self",
",",
"tclass",
",",
"tnum",
",",
"tlvt",
"=",
"0",
",",
"tdata",
"=",
"''",
")",
":",
"if",
"not",
"isinstance",
"(",
"tdata",
",",
"str",
")",
":",
"raise",
"TypeError",
"(",
"\"tag data must be str\"",
")",
"self",
".",
... | 32 | 11.777778 |
def warning(self, message, print_location=True):
"""Displays warning message. Uses exshared for current location of parsing"""
msg = "Warning"
if print_location and (exshared.location != None):
wline = lineno(exshared.location, exshared.text)
wcol = col(exshared.loca... | [
"def",
"warning",
"(",
"self",
",",
"message",
",",
"print_location",
"=",
"True",
")",
":",
"msg",
"=",
"\"Warning\"",
"if",
"print_location",
"and",
"(",
"exshared",
".",
"location",
"!=",
"None",
")",
":",
"wline",
"=",
"lineno",
"(",
"exshared",
".",... | 49.583333 | 14.416667 |
def main():
"Boots up the command line tool"
logging.captureWarnings(True)
args = build_parser().parse_args()
# Configure logging
args.setup_logging(args)
# Dispatch into the appropriate subcommand function.
try:
return args.func(args)
except SystemExit:
raise
except:... | [
"def",
"main",
"(",
")",
":",
"logging",
".",
"captureWarnings",
"(",
"True",
")",
"args",
"=",
"build_parser",
"(",
")",
".",
"parse_args",
"(",
")",
"# Configure logging",
"args",
".",
"setup_logging",
"(",
"args",
")",
"# Dispatch into the appropriate subcomm... | 28.071429 | 17.785714 |
def stubs_clustering(network,use_reduced_coordinates=True, line_length_factor=1.0):
"""Cluster network by reducing stubs and stubby trees
(i.e. sequentially reducing dead-ends).
Parameters
----------
network : pypsa.Network
use_reduced_coordinates : boolean
If True, do not average clust... | [
"def",
"stubs_clustering",
"(",
"network",
",",
"use_reduced_coordinates",
"=",
"True",
",",
"line_length_factor",
"=",
"1.0",
")",
":",
"busmap",
"=",
"busmap_by_stubs",
"(",
"network",
")",
"#reset coordinates to the new reduced guys, rather than taking an average",
"if",... | 36.928571 | 24.571429 |
def subset_by_supported(input_file, get_coords, calls_by_name, work_dir, data,
headers=("#",)):
"""Limit CNVkit input to calls with support from another caller.
get_coords is a function that return chrom, start, end from a line of the
input_file, allowing handling of multiple input ... | [
"def",
"subset_by_supported",
"(",
"input_file",
",",
"get_coords",
",",
"calls_by_name",
",",
"work_dir",
",",
"data",
",",
"headers",
"=",
"(",
"\"#\"",
",",
")",
")",
":",
"support_files",
"=",
"[",
"(",
"c",
",",
"tz",
".",
"get_in",
"(",
"[",
"c",... | 57.735294 | 25 |
def datasets(self) -> tuple:
"""Datasets."""
return tuple(v for _, v in self.items() if isinstance(v, h5py.Dataset)) | [
"def",
"datasets",
"(",
"self",
")",
"->",
"tuple",
":",
"return",
"tuple",
"(",
"v",
"for",
"_",
",",
"v",
"in",
"self",
".",
"items",
"(",
")",
"if",
"isinstance",
"(",
"v",
",",
"h5py",
".",
"Dataset",
")",
")"
] | 43.333333 | 17 |
def MAU(self):
'''Result of preconditioned operator to deflation space, i.e.,
:math:`MM_lAM_rU`.'''
if self._MAU is None:
self._MAU = self.linear_system.M * self.AU
return self._MAU | [
"def",
"MAU",
"(",
"self",
")",
":",
"if",
"self",
".",
"_MAU",
"is",
"None",
":",
"self",
".",
"_MAU",
"=",
"self",
".",
"linear_system",
".",
"M",
"*",
"self",
".",
"AU",
"return",
"self",
".",
"_MAU"
] | 36.666667 | 18 |
def dump_state(self):
"""Dump the current state of this emulated tile as a dictionary.
This function just dumps the status of the config variables. It is designed to
be called in a chained fashion to serialize the complete state of a tile subclass.
Returns:
dict: The curre... | [
"def",
"dump_state",
"(",
"self",
")",
":",
"return",
"{",
"\"config_variables\"",
":",
"{",
"x",
":",
"base64",
".",
"b64encode",
"(",
"y",
".",
"current_value",
")",
".",
"decode",
"(",
"'utf-8'",
")",
"for",
"x",
",",
"y",
"in",
"self",
".",
"_con... | 41.307692 | 34.615385 |
def _extract_shifted_mean_gauss(image, mask = slice(None), offset = None, sigma = 1, voxelspacing = None):
"""
Internal, single-image version of `shifted_mean_gauss`.
"""
# set voxel spacing
if voxelspacing is None:
voxelspacing = [1.] * image.ndim
# set offset
if offset is None:... | [
"def",
"_extract_shifted_mean_gauss",
"(",
"image",
",",
"mask",
"=",
"slice",
"(",
"None",
")",
",",
"offset",
"=",
"None",
",",
"sigma",
"=",
"1",
",",
"voxelspacing",
"=",
"None",
")",
":",
"# set voxel spacing",
"if",
"voxelspacing",
"is",
"None",
":",... | 31.730769 | 16.115385 |
def get_smokedetector_by_name(self, name):
"""Retrieves a smokedetector object by its name
:param name: The name of the smokedetector to return
:return: A smokedetector object
"""
return next((smokedetector for smokedetector in self.smokedetectors
if smokede... | [
"def",
"get_smokedetector_by_name",
"(",
"self",
",",
"name",
")",
":",
"return",
"next",
"(",
"(",
"smokedetector",
"for",
"smokedetector",
"in",
"self",
".",
"smokedetectors",
"if",
"smokedetector",
".",
"name",
".",
"lower",
"(",
")",
"==",
"name",
".",
... | 44.5 | 16.5 |
def _delete_os_nwk(self, tenant_id, tenant_name, direc, is_fw_virt=False):
"""Delete the network created in Openstack.
Function to delete Openstack network, It also releases the associated
segmentation, VLAN and subnets.
"""
serv_obj = self.get_service_obj(tenant_id)
fw_... | [
"def",
"_delete_os_nwk",
"(",
"self",
",",
"tenant_id",
",",
"tenant_name",
",",
"direc",
",",
"is_fw_virt",
"=",
"False",
")",
":",
"serv_obj",
"=",
"self",
".",
"get_service_obj",
"(",
"tenant_id",
")",
"fw_dict",
"=",
"serv_obj",
".",
"get_fw_dict",
"(",
... | 42.023256 | 15.604651 |
def agents(status, all):
'''
List and manage agents.
(admin privilege required)
'''
fields = [
('ID', 'id'),
('Status', 'status'),
('Region', 'region'),
('First Contact', 'first_contact'),
('CPU Usage (%)', 'cpu_cur_pct'),
('Used Memory (MiB)', 'mem_cu... | [
"def",
"agents",
"(",
"status",
",",
"all",
")",
":",
"fields",
"=",
"[",
"(",
"'ID'",
",",
"'id'",
")",
",",
"(",
"'Status'",
",",
"'status'",
")",
",",
"(",
"'Region'",
",",
"'region'",
")",
",",
"(",
"'First Contact'",
",",
"'first_contact'",
")",... | 34.78481 | 17.924051 |
def save(d, output_file, indent=4, spacer=" ", quote='"', newlinechar="\n", end_comment=False, **kwargs):
"""
Write a dictionary to an output Mapfile on disk
Parameters
----------
d: dict
A Python dictionary based on the the mappyfile schema
output_file: string
The output filen... | [
"def",
"save",
"(",
"d",
",",
"output_file",
",",
"indent",
"=",
"4",
",",
"spacer",
"=",
"\" \"",
",",
"quote",
"=",
"'\"'",
",",
"newlinechar",
"=",
"\"\\n\"",
",",
"end_comment",
"=",
"False",
",",
"*",
"*",
"kwargs",
")",
":",
"map_string",
"=",
... | 28.886364 | 24.340909 |
def compactor(conf):
"""
The compactor daemon. This fuction watches the sorted set
containing bucket keys that need to be compacted, performing the
necessary compaction.
:param conf: A turnstile.config.Config instance containing the
configuration for the compactor daemon. Note th... | [
"def",
"compactor",
"(",
"conf",
")",
":",
"# Get the database handle",
"db",
"=",
"conf",
".",
"get_database",
"(",
"'compactor'",
")",
"# Get the limits container",
"limit_map",
"=",
"LimitContainer",
"(",
"conf",
",",
"db",
")",
"# Get the compactor configuration",... | 34.367647 | 19.632353 |
def mutex_opts(dict,ex_op):
"""Check for presence of mutually exclusive keys in a dict.
Call: mutex_opts(dict,[[op1a,op1b],[op2a,op2b]...]"""
for op1,op2 in ex_op:
if op1 in dict and op2 in dict:
raise ValueError,'\n*** ERROR in Arguments *** '\
'Options '+op1+' and '+... | [
"def",
"mutex_opts",
"(",
"dict",
",",
"ex_op",
")",
":",
"for",
"op1",
",",
"op2",
"in",
"ex_op",
":",
"if",
"op1",
"in",
"dict",
"and",
"op2",
"in",
"dict",
":",
"raise",
"ValueError",
",",
"'\\n*** ERROR in Arguments *** '",
"'Options '",
"+",
"op1",
... | 42.875 | 15.125 |
def Collect(self, top_frame):
"""Collects call stack, local variables and objects.
Starts collection from the specified frame. We don't start from the top
frame to exclude the frames due to debugger. Updates the content of
self.breakpoint.
Args:
top_frame: top frame to start data collection.... | [
"def",
"Collect",
"(",
"self",
",",
"top_frame",
")",
":",
"# Evaluate call stack.",
"frame",
"=",
"top_frame",
"top_line",
"=",
"self",
".",
"breakpoint",
"[",
"'location'",
"]",
"[",
"'line'",
"]",
"breakpoint_frames",
"=",
"self",
".",
"breakpoint",
"[",
... | 37.273973 | 20.575342 |
def allow_rwe(self, name):
"""Allow all privileges for a particular name group (user, group, other)."""
assert name in PERMISSIONS.keys()
os.chmod(self.file_path, PERMISSIONS[name]['all']) | [
"def",
"allow_rwe",
"(",
"self",
",",
"name",
")",
":",
"assert",
"name",
"in",
"PERMISSIONS",
".",
"keys",
"(",
")",
"os",
".",
"chmod",
"(",
"self",
".",
"file_path",
",",
"PERMISSIONS",
"[",
"name",
"]",
"[",
"'all'",
"]",
")"
] | 52.25 | 8.25 |
def stop(self, message):
"""
Manually stops timer with the message.
:param message: The display message.
"""
self._stop = time.clock()
VSGLogger.info("{0:<20} - Finished [{1}s]".format(message, self.pprint(self._stop - self._start))) | [
"def",
"stop",
"(",
"self",
",",
"message",
")",
":",
"self",
".",
"_stop",
"=",
"time",
".",
"clock",
"(",
")",
"VSGLogger",
".",
"info",
"(",
"\"{0:<20} - Finished [{1}s]\"",
".",
"format",
"(",
"message",
",",
"self",
".",
"pprint",
"(",
"self",
"."... | 34.5 | 17.5 |
def update_linode(linode_id, update_args=None):
'''
Updates a Linode's properties.
linode_id
The ID of the Linode to shutdown. Required.
update_args
The args to update the Linode with. Must be in dictionary form.
'''
update_args.update({'LinodeID': linode_id})
result = _qu... | [
"def",
"update_linode",
"(",
"linode_id",
",",
"update_args",
"=",
"None",
")",
":",
"update_args",
".",
"update",
"(",
"{",
"'LinodeID'",
":",
"linode_id",
"}",
")",
"result",
"=",
"_query",
"(",
"'linode'",
",",
"'update'",
",",
"args",
"=",
"update_args... | 25.266667 | 24.466667 |
def getCandScoresMap(self, profile):
"""
Returns a dictionary that associates integer representations of each candidate with their
Copeland score.
:ivar Profile profile: A Profile object that represents an election profile.
"""
# Currently, we expect the profile to cont... | [
"def",
"getCandScoresMap",
"(",
"self",
",",
"profile",
")",
":",
"# Currently, we expect the profile to contain complete ordering over candidates. Ties are",
"# allowed however.",
"elecType",
"=",
"profile",
".",
"getElecType",
"(",
")",
"if",
"elecType",
"!=",
"\"soc\"",
... | 39.081081 | 21.459459 |
def onpress(self, event):
"""
Reacts to key commands
:param event: a keyboard event
:return: if 'c' is pressed, clear all region patches
"""
if event.key == 'c': # clears all the contours
for patch in self.region_patches:
patch.remove()
... | [
"def",
"onpress",
"(",
"self",
",",
"event",
")",
":",
"if",
"event",
".",
"key",
"==",
"'c'",
":",
"# clears all the contours",
"for",
"patch",
"in",
"self",
".",
"region_patches",
":",
"patch",
".",
"remove",
"(",
")",
"self",
".",
"region_patches",
"=... | 35.538462 | 7.076923 |
def add_tokens_for_group(self, with_pass=False):
"""Add the tokens for the group signature"""
kls = self.groups.super_kls
name = self.groups.kls_name
# Reset indentation to beginning and add signature
self.reset_indentation('')
self.result.extend(self.tokens.make_describ... | [
"def",
"add_tokens_for_group",
"(",
"self",
",",
"with_pass",
"=",
"False",
")",
":",
"kls",
"=",
"self",
".",
"groups",
".",
"super_kls",
"name",
"=",
"self",
".",
"groups",
".",
"kls_name",
"# Reset indentation to beginning and add signature",
"self",
".",
"re... | 32.428571 | 15.571429 |
def get_items_batch(self, item_request_data, project=None):
"""GetItemsBatch.
Post for retrieving a set of items given a list of paths or a long path. Allows for specifying the recursionLevel and version descriptors for each path.
:param :class:`<TfvcItemRequestData> <azure.devops.v5_0.tfvc.mode... | [
"def",
"get_items_batch",
"(",
"self",
",",
"item_request_data",
",",
"project",
"=",
"None",
")",
":",
"route_values",
"=",
"{",
"}",
"if",
"project",
"is",
"not",
"None",
":",
"route_values",
"[",
"'project'",
"]",
"=",
"self",
".",
"_serialize",
".",
... | 60.705882 | 27.529412 |
def _parse_view_results(self, rows, factory, options):
'''
rows here should be a list of tuples:
- (key, value) for reduce views
- (key, value, id) for nonreduce views without include docs
- (key, value, id, doc) for nonreduce with with include docs
'''
kwargs ... | [
"def",
"_parse_view_results",
"(",
"self",
",",
"rows",
",",
"factory",
",",
"options",
")",
":",
"kwargs",
"=",
"dict",
"(",
")",
"kwargs",
"[",
"'reduced'",
"]",
"=",
"factory",
".",
"use_reduce",
"and",
"options",
".",
"get",
"(",
"'reduce'",
",",
"... | 51.238095 | 22.380952 |
def _MergeSameId(self):
"""Tries to merge entities based on their ids.
This tries to merge only the entities from the old and new schedules which
have the same id. These are added into the merged schedule. Entities which
do not merge or do not have the same id as another entity in the other
schedul... | [
"def",
"_MergeSameId",
"(",
"self",
")",
":",
"a_not_merged",
"=",
"[",
"]",
"b_not_merged",
"=",
"[",
"]",
"for",
"a",
"in",
"self",
".",
"_GetIter",
"(",
"self",
".",
"feed_merger",
".",
"a_schedule",
")",
":",
"try",
":",
"b",
"=",
"self",
".",
... | 38.736842 | 23.491228 |
def from_dict(cls, d, ignore=()):
"""Create an instance from a serialized version of cls
Args:
d(dict): Endpoints of cls to set
ignore(tuple): Keys to ignore
Returns:
Instance of this class
"""
filtered = {}
for k, v in d.items():
... | [
"def",
"from_dict",
"(",
"cls",
",",
"d",
",",
"ignore",
"=",
"(",
")",
")",
":",
"filtered",
"=",
"{",
"}",
"for",
"k",
",",
"v",
"in",
"d",
".",
"items",
"(",
")",
":",
"if",
"k",
"==",
"\"typeid\"",
":",
"assert",
"v",
"==",
"cls",
".",
... | 30.956522 | 14.304348 |
def FromString(self, string):
"""Parse a bool from a string."""
if string.lower() in ("false", "no", "n"):
return False
if string.lower() in ("true", "yes", "y"):
return True
raise TypeValueError("%s is not recognized as a boolean value." % string) | [
"def",
"FromString",
"(",
"self",
",",
"string",
")",
":",
"if",
"string",
".",
"lower",
"(",
")",
"in",
"(",
"\"false\"",
",",
"\"no\"",
",",
"\"n\"",
")",
":",
"return",
"False",
"if",
"string",
".",
"lower",
"(",
")",
"in",
"(",
"\"true\"",
",",... | 30 | 20.555556 |
def tox_addoption(parser):
"""Add arguments and needed monkeypatches."""
parser.add_argument(
'--travis-after', dest='travis_after', action='store_true',
help='Exit successfully after all Travis jobs complete successfully.')
if 'TRAVIS' in os.environ:
pypy_version_monkeypatch()
... | [
"def",
"tox_addoption",
"(",
"parser",
")",
":",
"parser",
".",
"add_argument",
"(",
"'--travis-after'",
",",
"dest",
"=",
"'travis_after'",
",",
"action",
"=",
"'store_true'",
",",
"help",
"=",
"'Exit successfully after all Travis jobs complete successfully.'",
")",
... | 41 | 19.111111 |
def reference(self, t, i, in_group=False):
"""Handle references."""
current = []
if not in_group and t == "m":
current.append(self._re_start_wb)
elif not in_group and t == "M":
current.append(self._re_end_wb)
elif not in_group and t == "R":
c... | [
"def",
"reference",
"(",
"self",
",",
"t",
",",
"i",
",",
"in_group",
"=",
"False",
")",
":",
"current",
"=",
"[",
"]",
"if",
"not",
"in_group",
"and",
"t",
"==",
"\"m\"",
":",
"current",
".",
"append",
"(",
"self",
".",
"_re_start_wb",
")",
"elif"... | 40.787234 | 16.021277 |
def _segment(cls, segment):
"""
Returns a property capable of setting and getting a segment.
"""
return property(
fget=lambda x: cls._get_segment(x, segment),
fset=lambda x, v: cls._set_segment(x, segment, v),
) | [
"def",
"_segment",
"(",
"cls",
",",
"segment",
")",
":",
"return",
"property",
"(",
"fget",
"=",
"lambda",
"x",
":",
"cls",
".",
"_get_segment",
"(",
"x",
",",
"segment",
")",
",",
"fset",
"=",
"lambda",
"x",
",",
"v",
":",
"cls",
".",
"_set_segmen... | 33.5 | 15.75 |
def process_command(command: CommandInput, matrix: VarMatrix) -> List[Command]:
"""Generate all combinations of commands given a variable matrix.
Processes the commands to be sequences of strings.
"""
assert command is not None
if isinstance(command, str):
command_list = [Command(command, ... | [
"def",
"process_command",
"(",
"command",
":",
"CommandInput",
",",
"matrix",
":",
"VarMatrix",
")",
"->",
"List",
"[",
"Command",
"]",
":",
"assert",
"command",
"is",
"not",
"None",
"if",
"isinstance",
"(",
"command",
",",
"str",
")",
":",
"command_list",... | 37.916667 | 19.583333 |
def cofold(self, strand1, strand2, temp=37.0, dangles=2, nolp=False,
nogu=False, noclosinggu=False, constraints=None,
canonicalbponly=False, partition=-1, pfscale=None, gquad=False):
'''Run the RNAcofold command and retrieve the result in a dictionary.
:param strand1: Stra... | [
"def",
"cofold",
"(",
"self",
",",
"strand1",
",",
"strand2",
",",
"temp",
"=",
"37.0",
",",
"dangles",
"=",
"2",
",",
"nolp",
"=",
"False",
",",
"nogu",
"=",
"False",
",",
"noclosinggu",
"=",
"False",
",",
"constraints",
"=",
"None",
",",
"canonical... | 45.349593 | 19.902439 |
def reffinder(sectionObj):
"""
add reference indeces to sectionobj['references']
:param sectionObj
:return: a section obj w references: field
"""
text = sectionObj['text']
reftags = [x for x in refTagRegEx.finditer(text)]
if reftags:
references = []
for tag in reftags:
... | [
"def",
"reffinder",
"(",
"sectionObj",
")",
":",
"text",
"=",
"sectionObj",
"[",
"'text'",
"]",
"reftags",
"=",
"[",
"x",
"for",
"x",
"in",
"refTagRegEx",
".",
"finditer",
"(",
"text",
")",
"]",
"if",
"reftags",
":",
"references",
"=",
"[",
"]",
"for... | 26 | 15.263158 |
def drop_first(count):
"""
Assumes an iterable on the input, returns an iterable with identical items
except for the first `count`.
>>> range(10) > drop_first(5) | tuple
(5, 6, 7, 8, 9)
"""
def _drop_first(iterable):
g = (x for x in range(1, count + 1))
return dropwhile(
... | [
"def",
"drop_first",
"(",
"count",
")",
":",
"def",
"_drop_first",
"(",
"iterable",
")",
":",
"g",
"=",
"(",
"x",
"for",
"x",
"in",
"range",
"(",
"1",
",",
"count",
"+",
"1",
")",
")",
"return",
"dropwhile",
"(",
"lambda",
"i",
":",
"unless",
"("... | 34.153846 | 16.307692 |
def _parse_publisher(details):
"""
Parse publisher of the book.
Args:
details (obj): HTMLElement containing slice of the page with details.
Returns:
str/None: Publisher's name as string or None if not found.
"""
publisher = _get_td_or_none(
details,
"ctl00_Conte... | [
"def",
"_parse_publisher",
"(",
"details",
")",
":",
"publisher",
"=",
"_get_td_or_none",
"(",
"details",
",",
"\"ctl00_ContentPlaceHolder1_tblRowNakladatel\"",
")",
"# publisher is not specified",
"if",
"not",
"publisher",
":",
"return",
"None",
"publisher",
"=",
"dhtm... | 22.115385 | 22.5 |
def set_background(self, background):
""" Set the background color of the widget.
"""
scene = self.scene
scene.setBackgroundBrush(QColor.fromRgba(background.argb)) | [
"def",
"set_background",
"(",
"self",
",",
"background",
")",
":",
"scene",
"=",
"self",
".",
"scene",
"scene",
".",
"setBackgroundBrush",
"(",
"QColor",
".",
"fromRgba",
"(",
"background",
".",
"argb",
")",
")"
] | 31.833333 | 13.833333 |
def diffplot(self, f, delay=1, lfilter=None, **kargs):
"""diffplot(f, delay=1, lfilter=None)
Applies a function to couples (l[i],l[i+delay])
A list of matplotlib.lines.Line2D is returned.
"""
# Get the list of packets
if lfilter is None:
lst_pkts = [f(self.r... | [
"def",
"diffplot",
"(",
"self",
",",
"f",
",",
"delay",
"=",
"1",
",",
"lfilter",
"=",
"None",
",",
"*",
"*",
"kargs",
")",
":",
"# Get the list of packets",
"if",
"lfilter",
"is",
"None",
":",
"lst_pkts",
"=",
"[",
"f",
"(",
"self",
".",
"res",
"[... | 32.923077 | 17.538462 |
def _get_button_attrs(self, tool):
"""
Get the HTML attributes associated with a tool.
There are some standard attributes (class and title) that the template
will always want. Any number of additional attributes can be specified
and passed on. This is kinda awkward and due for a... | [
"def",
"_get_button_attrs",
"(",
"self",
",",
"tool",
")",
":",
"attrs",
"=",
"getattr",
"(",
"tool",
",",
"'attrs'",
",",
"{",
"}",
")",
"# href is not allowed to be set. should an exception be raised instead?",
"if",
"'href'",
"in",
"attrs",
":",
"attrs",
".",
... | 39.3 | 17.633333 |
def build_parameter(field: Field) -> Mapping[str, Any]:
"""
Build JSON parameter from a marshmallow field.
"""
builder = Parameters()
return builder.build(field) | [
"def",
"build_parameter",
"(",
"field",
":",
"Field",
")",
"->",
"Mapping",
"[",
"str",
",",
"Any",
"]",
":",
"builder",
"=",
"Parameters",
"(",
")",
"return",
"builder",
".",
"build",
"(",
"field",
")"
] | 25.142857 | 12.571429 |
def calc_registration(preregistration_map, anchors,
max_steps=2000, max_step_size=0.05, method='random'):
'''
calc_registration is a calculator that creates the registration coordinates.
'''
# if max steps is a tuple (max, stride) then a trajectory is saved into
# the registere... | [
"def",
"calc_registration",
"(",
"preregistration_map",
",",
"anchors",
",",
"max_steps",
"=",
"2000",
",",
"max_step_size",
"=",
"0.05",
",",
"method",
"=",
"'random'",
")",
":",
"# if max steps is a tuple (max, stride) then a trajectory is saved into",
"# the registered_m... | 40.333333 | 13.833333 |
def peripheral_didDiscoverCharacteristicsForService_error_(self, peripheral, service, error):
"""Called when characteristics are discovered for a service."""
logger.debug('peripheral_didDiscoverCharacteristicsForService_error called')
# Stop if there was some kind of error.
if error is n... | [
"def",
"peripheral_didDiscoverCharacteristicsForService_error_",
"(",
"self",
",",
"peripheral",
",",
"service",
",",
"error",
")",
":",
"logger",
".",
"debug",
"(",
"'peripheral_didDiscoverCharacteristicsForService_error called'",
")",
"# Stop if there was some kind of error.",
... | 57.722222 | 20.777778 |
def clone(self, config, **kwargs):
"""Make a clone of this analysis instance."""
gta = GTAnalysis(config, **kwargs)
gta._roi = copy.deepcopy(self.roi)
return gta | [
"def",
"clone",
"(",
"self",
",",
"config",
",",
"*",
"*",
"kwargs",
")",
":",
"gta",
"=",
"GTAnalysis",
"(",
"config",
",",
"*",
"*",
"kwargs",
")",
"gta",
".",
"_roi",
"=",
"copy",
".",
"deepcopy",
"(",
"self",
".",
"roi",
")",
"return",
"gta"
... | 37.8 | 6.4 |
def serialize(ty, *values, **kwargs):
"""
Serialize value using type specification in ty.
ABI.serialize('int256', 1000)
ABI.serialize('(int, int256)', 1000, 2000)
"""
try:
parsed_ty = abitypes.parse(ty)
except Exception as e:
# Catch and re... | [
"def",
"serialize",
"(",
"ty",
",",
"*",
"values",
",",
"*",
"*",
"kwargs",
")",
":",
"try",
":",
"parsed_ty",
"=",
"abitypes",
".",
"parse",
"(",
"ty",
")",
"except",
"Exception",
"as",
"e",
":",
"# Catch and rebrand parsing errors",
"raise",
"EthereumErr... | 38.44 | 15.4 |
def _c3_merge(sequences): # noqa
"""Merges MROs in *sequences* to a single MRO using the C3 algorithm.
Adapted from http://www.python.org/download/releases/2.3/mro/.
"""
result = []
while True:
sequences = [s for s in sequences if s] # purge empty sequences
if not sequences:
... | [
"def",
"_c3_merge",
"(",
"sequences",
")",
":",
"# noqa",
"result",
"=",
"[",
"]",
"while",
"True",
":",
"sequences",
"=",
"[",
"s",
"for",
"s",
"in",
"sequences",
"if",
"s",
"]",
"# purge empty sequences",
"if",
"not",
"sequences",
":",
"return",
"resul... | 34 | 16.230769 |
def list_certs(self, filters=None):
"""Retrieve loaded certificates.
:param filters: retrieve only matching certificates (optional)
:type filters: dict
:return: list of installed trap, drop and bypass policies
:rtype: list
"""
_, cert_list = self.handler.streamed... | [
"def",
"list_certs",
"(",
"self",
",",
"filters",
"=",
"None",
")",
":",
"_",
",",
"cert_list",
"=",
"self",
".",
"handler",
".",
"streamed_request",
"(",
"\"list-certs\"",
",",
"\"list-cert\"",
",",
"filters",
")",
"return",
"cert_list"
] | 39.272727 | 19 |
def formatter(self, value):
'''
Format a enumerate value to enumerate names if possible. Used to generate human readable
dump result.
'''
if not self._bitwise:
n = self.getName(value)
if n is None:
return value
else:
... | [
"def",
"formatter",
"(",
"self",
",",
"value",
")",
":",
"if",
"not",
"self",
".",
"_bitwise",
":",
"n",
"=",
"self",
".",
"getName",
"(",
"value",
")",
"if",
"n",
"is",
"None",
":",
"return",
"value",
"else",
":",
"return",
"n",
"else",
":",
"na... | 31.695652 | 17.173913 |
def is_valid_index(self, code):
"""
returns: True | Flase , based on whether code is valid
"""
index_list = self.get_index_list()
return True if code.upper() in index_list else False | [
"def",
"is_valid_index",
"(",
"self",
",",
"code",
")",
":",
"index_list",
"=",
"self",
".",
"get_index_list",
"(",
")",
"return",
"True",
"if",
"code",
".",
"upper",
"(",
")",
"in",
"index_list",
"else",
"False"
] | 36.166667 | 8.833333 |
def make_linear_workflow(*tasks, **kwargs):
"""Factory method for creating linear workflows.
:param tasks: EOTask's t1,t2,...,tk with dependencies t1->t2->...->tk
:param kwargs: Optional keyword arguments (such as workflow name) forwarded to the constructor
:return: A new EO workfl... | [
"def",
"make_linear_workflow",
"(",
"*",
"tasks",
",",
"*",
"*",
"kwargs",
")",
":",
"warnings",
".",
"warn",
"(",
"\"Method 'make_linear_workflow' will soon be removed. Use LinearWorkflow class instead\"",
",",
"DeprecationWarning",
",",
"stacklevel",
"=",
"2",
")",
"r... | 48.333333 | 24.416667 |
def _step(vertices, d_limit, temperature, placements, l2v, v2n,
vertices_resources, fixed_vertices, machine, has_wrap_around_links,
random):
"""Attempt a single swap operation: the kernel of the Simulated Annealing
algorithm.
Parameters
----------
vertices : [vertex, ...]
... | [
"def",
"_step",
"(",
"vertices",
",",
"d_limit",
",",
"temperature",
",",
"placements",
",",
"l2v",
",",
"v2n",
",",
"vertices_resources",
",",
"fixed_vertices",
",",
"machine",
",",
"has_wrap_around_links",
",",
"random",
")",
":",
"# Special case: If the machine... | 43.692913 | 21.047244 |
def extract_common_fields(self, data):
"""Extract fields from a basic user query."""
email = None
for curr_email in data.get("emails", []):
email = email or curr_email.get("email")
if curr_email.get("verified", False) and \
curr_email.get("primary", Fa... | [
"def",
"extract_common_fields",
"(",
"self",
",",
"data",
")",
":",
"email",
"=",
"None",
"for",
"curr_email",
"in",
"data",
".",
"get",
"(",
"\"emails\"",
",",
"[",
"]",
")",
":",
"email",
"=",
"email",
"or",
"curr_email",
".",
"get",
"(",
"\"email\""... | 36.235294 | 12.529412 |
def operator_complexity(self):
"""Operator complexity of this multigrid hierarchy.
Defined as:
Number of nonzeros in the matrix on all levels /
Number of nonzeros in the matrix on the finest level
"""
return sum([level.A.nnz for level in self.levels]) /\
... | [
"def",
"operator_complexity",
"(",
"self",
")",
":",
"return",
"sum",
"(",
"[",
"level",
".",
"A",
".",
"nnz",
"for",
"level",
"in",
"self",
".",
"levels",
"]",
")",
"/",
"float",
"(",
"self",
".",
"levels",
"[",
"0",
"]",
".",
"A",
".",
"nnz",
... | 34.3 | 17.7 |
def sample_top(a=None, top_k=10):
"""Sample from ``top_k`` probabilities.
Parameters
----------
a : list of float
List of probabilities.
top_k : int
Number of candidates to be considered.
"""
if a is None:
a = []
idx = np.argpartition(a, -top_k)[-top_k:]
pr... | [
"def",
"sample_top",
"(",
"a",
"=",
"None",
",",
"top_k",
"=",
"10",
")",
":",
"if",
"a",
"is",
"None",
":",
"a",
"=",
"[",
"]",
"idx",
"=",
"np",
".",
"argpartition",
"(",
"a",
",",
"-",
"top_k",
")",
"[",
"-",
"top_k",
":",
"]",
"probs",
... | 22.45 | 17.45 |
def transition_retry(self, pipeline_key, retry_message):
"""Marks the given pipeline as requiring another retry.
Does nothing if all attempts have been exceeded.
Args:
pipeline_key: db.Key of the _PipelineRecord that needs to be retried.
retry_message: User-supplied message indicating the reas... | [
"def",
"transition_retry",
"(",
"self",
",",
"pipeline_key",
",",
"retry_message",
")",
":",
"def",
"txn",
"(",
")",
":",
"pipeline_record",
"=",
"db",
".",
"get",
"(",
"pipeline_key",
")",
"if",
"pipeline_record",
"is",
"None",
":",
"logging",
".",
"warni... | 43.301587 | 19.333333 |
def _erc_weights_ccd(x0,
cov,
b,
maximum_iterations,
tolerance):
"""
Calculates the equal risk contribution / risk parity weights given
a DataFrame of returns.
Args:
* x0 (np.array): Starting asset weights.
... | [
"def",
"_erc_weights_ccd",
"(",
"x0",
",",
"cov",
",",
"b",
",",
"maximum_iterations",
",",
"tolerance",
")",
":",
"n",
"=",
"len",
"(",
"x0",
")",
"x",
"=",
"x0",
".",
"copy",
"(",
")",
"var",
"=",
"np",
".",
"diagonal",
"(",
"cov",
")",
"ctr",
... | 30.508475 | 20.372881 |
def www_authenticate(self):
"""The `WWW-Authenticate` header in a parsed form."""
def on_update(www_auth):
if not www_auth and 'www-authenticate' in self.headers:
del self.headers['www-authenticate']
elif www_auth:
self.headers['WWW-Authenticate'] ... | [
"def",
"www_authenticate",
"(",
"self",
")",
":",
"def",
"on_update",
"(",
"www_auth",
")",
":",
"if",
"not",
"www_auth",
"and",
"'www-authenticate'",
"in",
"self",
".",
"headers",
":",
"del",
"self",
".",
"headers",
"[",
"'www-authenticate'",
"]",
"elif",
... | 50.222222 | 15.666667 |
def match_in_kwargs(self, match_args, kwargs):
"""Matches against kwargs."""
for match, default in match_args:
names = get_match_names(match)
if names:
tempvar = self.get_temp_var()
self.add_def(
tempvar + " = "
... | [
"def",
"match_in_kwargs",
"(",
"self",
",",
"match_args",
",",
"kwargs",
")",
":",
"for",
"match",
",",
"default",
"in",
"match_args",
":",
"names",
"=",
"get_match_names",
"(",
"match",
")",
"if",
"names",
":",
"tempvar",
"=",
"self",
".",
"get_temp_var",... | 42.333333 | 15.833333 |
def response_class(self, cls):
"""
Override the default wrapper used for the response.
"""
s = self._clone()
s._response_class = cls
return s | [
"def",
"response_class",
"(",
"self",
",",
"cls",
")",
":",
"s",
"=",
"self",
".",
"_clone",
"(",
")",
"s",
".",
"_response_class",
"=",
"cls",
"return",
"s"
] | 26.142857 | 11 |
def make_all_uppercase(
lst: Union[list, tuple, str, set]
) -> Union[list, tuple, str, set]:
"""Make all characters uppercase.
It supports characters in a (mix of) list, tuple, set or string.
The return value is of the same type of the input value.
"""
if not is... | [
"def",
"make_all_uppercase",
"(",
"lst",
":",
"Union",
"[",
"list",
",",
"tuple",
",",
"str",
",",
"set",
"]",
")",
"->",
"Union",
"[",
"list",
",",
"tuple",
",",
"str",
",",
"set",
"]",
":",
"if",
"not",
"isinstance",
"(",
"lst",
",",
"(",
"list... | 31.242424 | 19.363636 |
def reset_window_layout(self):
"""Reset window layout to default"""
answer = QMessageBox.warning(self, _("Warning"),
_("Window layout will be reset to default settings: "
"this affects window position, size and dockwidgets.\n"
"Do y... | [
"def",
"reset_window_layout",
"(",
"self",
")",
":",
"answer",
"=",
"QMessageBox",
".",
"warning",
"(",
"self",
",",
"_",
"(",
"\"Warning\"",
")",
",",
"_",
"(",
"\"Window layout will be reset to default settings: \"",
"\"this affects window position, size and dockwidgets... | 52.777778 | 14.666667 |
def meraculous_runner(self):
"""
Check to make sure that the allAssembliesDir has been created, if not,
make it. This will only execute for the first time an assembly has been
run in this directory.
Run the directory from allAssembliesDir. The self.callString instance
at... | [
"def",
"meraculous_runner",
"(",
"self",
")",
":",
"#set the dir to temp assembly dir",
"os",
".",
"chdir",
"(",
"self",
".",
"allAssembliesDir",
")",
"print",
"(",
"self",
".",
"callString",
")",
"p",
"=",
"subprocess",
".",
"run",
"(",
"self",
".",
"callSt... | 37.851852 | 20.518519 |
def is_complex_floating_dtype(dtype):
"""Return ``True`` if ``dtype`` is a complex floating point type."""
dtype = np.dtype(dtype)
return np.issubsctype(getattr(dtype, 'base', None), np.complexfloating) | [
"def",
"is_complex_floating_dtype",
"(",
"dtype",
")",
":",
"dtype",
"=",
"np",
".",
"dtype",
"(",
"dtype",
")",
"return",
"np",
".",
"issubsctype",
"(",
"getattr",
"(",
"dtype",
",",
"'base'",
",",
"None",
")",
",",
"np",
".",
"complexfloating",
")"
] | 52.75 | 12.75 |
def team_present(
name,
description=None,
repo_names=None,
privacy='secret',
permission='pull',
members=None,
enforce_mfa=False,
no_mfa_grace_seconds=0,
profile="github",
**kwargs):
'''
Ensure a team is present
name
Thi... | [
"def",
"team_present",
"(",
"name",
",",
"description",
"=",
"None",
",",
"repo_names",
"=",
"None",
",",
"privacy",
"=",
"'secret'",
",",
"permission",
"=",
"'pull'",
",",
"members",
"=",
"None",
",",
"enforce_mfa",
"=",
"False",
",",
"no_mfa_grace_seconds"... | 40.246154 | 22.984615 |
def plot_all(self, t=0, f_start=None, f_stop=None, logged=False, if_id=0, kurtosis=True, **kwargs):
""" Plot waterfall of data as well as spectrum; also, placeholder to make even more complicated plots in the future.
Args:
f_start (float): start frequency, in MHz
f_stop (float):... | [
"def",
"plot_all",
"(",
"self",
",",
"t",
"=",
"0",
",",
"f_start",
"=",
"None",
",",
"f_stop",
"=",
"None",
",",
"logged",
"=",
"False",
",",
"if_id",
"=",
"0",
",",
"kurtosis",
"=",
"True",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"self",
"."... | 39.635036 | 21.20438 |
def add_constraints(self):
"""
Set the base constraints on the relation query.
:rtype: None
"""
if self._constraints:
foreign_key = getattr(self._parent, self._foreign_key, None)
if foreign_key is None:
self._query = None
else:... | [
"def",
"add_constraints",
"(",
"self",
")",
":",
"if",
"self",
".",
"_constraints",
":",
"foreign_key",
"=",
"getattr",
"(",
"self",
".",
"_parent",
",",
"self",
".",
"_foreign_key",
",",
"None",
")",
"if",
"foreign_key",
"is",
"None",
":",
"self",
".",
... | 30.375 | 17.5 |
def run_model(self, times=None, weather=None):
"""
Run the model.
Parameters
----------
times : None or DatetimeIndex, default None
Times at which to evaluate the model. Can be None if
attribute `times` is already set.
weather : None or DataFrame,... | [
"def",
"run_model",
"(",
"self",
",",
"times",
"=",
"None",
",",
"weather",
"=",
"None",
")",
":",
"self",
".",
"prepare_inputs",
"(",
"times",
",",
"weather",
")",
"self",
".",
"aoi_model",
"(",
")",
"self",
".",
"spectral_model",
"(",
")",
"self",
... | 32.944444 | 20.666667 |
def generate_confirmation_key(identity_secret, tag, timestamp):
"""Generate confirmation key for trades. Can only be used once.
:param identity_secret: authenticator identity secret
:type identity_secret: bytes
:param tag: tag identifies what the request, see list below
:type tag: str
:param ti... | [
"def",
"generate_confirmation_key",
"(",
"identity_secret",
",",
"tag",
",",
"timestamp",
")",
":",
"data",
"=",
"struct",
".",
"pack",
"(",
"'>Q'",
",",
"int",
"(",
"timestamp",
")",
")",
"+",
"tag",
".",
"encode",
"(",
"'ascii'",
")",
"# this will NOT st... | 35.409091 | 20.045455 |
def nested_dict_to_list(path, dic, exclusion=None):
"""
Transform nested dict to list
"""
result = []
exclusion = ['__self'] if exclusion is None else exclusion
for key, value in dic.items():
if not any([exclude in key for exclude in exclusion]):
if isinstance(value, dict):... | [
"def",
"nested_dict_to_list",
"(",
"path",
",",
"dic",
",",
"exclusion",
"=",
"None",
")",
":",
"result",
"=",
"[",
"]",
"exclusion",
"=",
"[",
"'__self'",
"]",
"if",
"exclusion",
"is",
"None",
"else",
"exclusion",
"for",
"key",
",",
"value",
"in",
"di... | 28.35 | 16.95 |
def get_plot_data(self):
""" Generates the JSON report to plot the gene boxes
Following the convention of the reports platform, this method returns
a list of JSON/dict objects with the information about each entry in
the abricate file. The information contained in this JSON is::
... | [
"def",
"get_plot_data",
"(",
"self",
")",
":",
"json_dic",
"=",
"{",
"\"plotData\"",
":",
"[",
"]",
"}",
"sample_dic",
"=",
"{",
"}",
"sample_assembly_map",
"=",
"{",
"}",
"for",
"entry",
"in",
"self",
".",
"storage",
".",
"values",
"(",
")",
":",
"s... | 34.090909 | 20.015152 |
def get_user(self, username):
"""Gest a specific user"""
ret = {}
tmp = self._get_user(self._byte_p2(username), ALL_ATTRS)
if tmp is None:
raise UserDoesntExist(username, self.backend_name)
attrs_tmp = tmp[1]
for attr in attrs_tmp:
value_tmp = attr... | [
"def",
"get_user",
"(",
"self",
",",
"username",
")",
":",
"ret",
"=",
"{",
"}",
"tmp",
"=",
"self",
".",
"_get_user",
"(",
"self",
".",
"_byte_p2",
"(",
"username",
")",
",",
"ALL_ATTRS",
")",
"if",
"tmp",
"is",
"None",
":",
"raise",
"UserDoesntExis... | 33.571429 | 12.571429 |
def set_rgbmap(self, rgbmap):
"""Set RGB map object used by this instance.
It controls how the values in the image are mapped to color.
Parameters
----------
rgbmap : `~ginga.RGBMap.RGBMapper`
RGB map.
"""
self.rgbmap = rgbmap
t_ = rgbmap.get... | [
"def",
"set_rgbmap",
"(",
"self",
",",
"rgbmap",
")",
":",
"self",
".",
"rgbmap",
"=",
"rgbmap",
"t_",
"=",
"rgbmap",
".",
"get_settings",
"(",
")",
"t_",
".",
"share_settings",
"(",
"self",
".",
"t_",
",",
"keylist",
"=",
"rgbmap",
".",
"settings_keys... | 31.133333 | 16.8 |
def unlock(name,
zk_hosts=None, # in case you need to unlock without having run lock (failed execution for example)
identifier=None,
max_concurrency=1,
ephemeral_lease=False,
profile=None,
scheme=None,
username=None,
password=None,... | [
"def",
"unlock",
"(",
"name",
",",
"zk_hosts",
"=",
"None",
",",
"# in case you need to unlock without having run lock (failed execution for example)",
"identifier",
"=",
"None",
",",
"max_concurrency",
"=",
"1",
",",
"ephemeral_lease",
"=",
"False",
",",
"profile",
"="... | 33.609756 | 23.95122 |
def set_package_name(self, package_name):
''' Set package_name
>>> docwriter = ApiDocWriter('sphinx')
>>> import sphinx
>>> docwriter.root_path == sphinx.__path__[0]
True
>>> docwriter.package_name = 'docutils'
>>> import docutils
>>> docwriter.root_path ... | [
"def",
"set_package_name",
"(",
"self",
",",
"package_name",
")",
":",
"# It's also possible to imagine caching the module parsing here",
"self",
".",
"_package_name",
"=",
"package_name",
"root_module",
"=",
"self",
".",
"_import",
"(",
"package_name",
")",
"self",
"."... | 35.352941 | 15.352941 |
def build_and_train(iterations, log_stride, test=False):
"""Construct the data, model, loss and optimizer then train."""
# Test mode settings.
batch_size = 2 if test else FLAGS.batch_size
num_mems = 2 if test else FLAGS.num_mems
num_heads = 1 if test else FLAGS.num_mems
num_blocks = 1 if test else FLAGS.nu... | [
"def",
"build_and_train",
"(",
"iterations",
",",
"log_stride",
",",
"test",
"=",
"False",
")",
":",
"# Test mode settings.",
"batch_size",
"=",
"2",
"if",
"test",
"else",
"FLAGS",
".",
"batch_size",
"num_mems",
"=",
"2",
"if",
"test",
"else",
"FLAGS",
".",
... | 41.135593 | 17.847458 |
def image_single_point_source(self, image_model_class, kwargs_lens, kwargs_source, kwargs_lens_light,
kwargs_ps):
"""
return model without including the point source contributions as a list (for each point source individually)
:param image_model_class: ImageMode... | [
"def",
"image_single_point_source",
"(",
"self",
",",
"image_model_class",
",",
"kwargs_lens",
",",
"kwargs_source",
",",
"kwargs_lens_light",
",",
"kwargs_ps",
")",
":",
"# reconstructed model with given psf",
"model",
",",
"error_map",
",",
"cov_param",
",",
"param",
... | 60 | 24.416667 |
def op_right(op):
"""
Returns a type instance method for the given operator, applied
when the instance appears on the right side of the expression.
"""
def method(self, other):
return op(value_left(self, other), value_right(self, other))
return method | [
"def",
"op_right",
"(",
"op",
")",
":",
"def",
"method",
"(",
"self",
",",
"other",
")",
":",
"return",
"op",
"(",
"value_left",
"(",
"self",
",",
"other",
")",
",",
"value_right",
"(",
"self",
",",
"other",
")",
")",
"return",
"method"
] | 34.5 | 17.25 |
def read_lines_from_file(file_path: str) -> List[str]:
""" Read text lines from a file """
# check if the file exists?
with open(file_path) as csv_file:
content = csv_file.readlines()
return content | [
"def",
"read_lines_from_file",
"(",
"file_path",
":",
"str",
")",
"->",
"List",
"[",
"str",
"]",
":",
"# check if the file exists?",
"with",
"open",
"(",
"file_path",
")",
"as",
"csv_file",
":",
"content",
"=",
"csv_file",
".",
"readlines",
"(",
")",
"return... | 36.166667 | 8.333333 |
def get_bank_hierarchy_design_session(self, proxy):
"""Gets the session designing bank hierarchies.
arg: proxy (osid.proxy.Proxy): a proxy
return: (osid.assessment.BankHierarchyDesignSession) - a
``BankHierarchySession``
raise: NullArgument - ``proxy`` is ``null``
... | [
"def",
"get_bank_hierarchy_design_session",
"(",
"self",
",",
"proxy",
")",
":",
"if",
"not",
"self",
".",
"supports_bank_hierarchy_design",
"(",
")",
":",
"raise",
"errors",
".",
"Unimplemented",
"(",
")",
"# pylint: disable=no-member",
"return",
"sessions",
".",
... | 44.944444 | 17.055556 |
def hierarchyLookup(self, record):
"""
Looks up additional hierarchy information for the inputed record.
:param record | <orb.Table>
:return (<subclass of orb.Table> || None, <str> column)
"""
def _get_lookup(cls):
if cls in... | [
"def",
"hierarchyLookup",
"(",
"self",
",",
"record",
")",
":",
"def",
"_get_lookup",
"(",
"cls",
")",
":",
"if",
"cls",
"in",
"self",
".",
"_hierarchyLookup",
":",
"return",
"self",
".",
"_hierarchyLookup",
"[",
"cls",
"]",
"for",
"base",
"in",
"cls",
... | 30.928571 | 14.642857 |
def _delete_state(self, activity, agent, state_id=None, registration=None, etag=None):
"""Private method to delete a specified state from the LRS
:param activity: Activity object of state to be deleted
:type activity: :class:`tincan.activity.Activity`
:param agent: Agent object of state... | [
"def",
"_delete_state",
"(",
"self",
",",
"activity",
",",
"agent",
",",
"state_id",
"=",
"None",
",",
"registration",
"=",
"None",
",",
"etag",
"=",
"None",
")",
":",
"if",
"not",
"isinstance",
"(",
"activity",
",",
"Activity",
")",
":",
"activity",
"... | 35.302326 | 17.232558 |
def check_stripe_api_host(app_configs=None, **kwargs):
"""
Check that STRIPE_API_HOST is not being used in production.
"""
from django.conf import settings
messages = []
if not settings.DEBUG and hasattr(settings, "STRIPE_API_HOST"):
messages.append(
checks.Warning(
"STRIPE_API_HOST should not be set i... | [
"def",
"check_stripe_api_host",
"(",
"app_configs",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"from",
"django",
".",
"conf",
"import",
"settings",
"messages",
"=",
"[",
"]",
"if",
"not",
"settings",
".",
"DEBUG",
"and",
"hasattr",
"(",
"settings",
... | 25.722222 | 24.277778 |
def get_projection(self, axis):
""" Return the projection of this vector onto the given axis. The
axis does not need to be normalized. """
scale = axis.dot(self) / axis.dot(axis)
return axis * scale | [
"def",
"get_projection",
"(",
"self",
",",
"axis",
")",
":",
"scale",
"=",
"axis",
".",
"dot",
"(",
"self",
")",
"/",
"axis",
".",
"dot",
"(",
"axis",
")",
"return",
"axis",
"*",
"scale"
] | 45.6 | 5.8 |
def _validate_markdown(self, expfile):
'''ensure that fields are present in markdown file'''
try:
import yaml
except:
bot.error('Python yaml is required for testing yml/markdown files.')
sys.exit(1)
self.metadata = {}
uid = os.path.basename(e... | [
"def",
"_validate_markdown",
"(",
"self",
",",
"expfile",
")",
":",
"try",
":",
"import",
"yaml",
"except",
":",
"bot",
".",
"error",
"(",
"'Python yaml is required for testing yml/markdown files.'",
")",
"sys",
".",
"exit",
"(",
"1",
")",
"self",
".",
"metada... | 38.075 | 19.925 |
def pmll(self,*args,**kwargs):
"""
NAME:
pmll
PURPOSE:
return proper motion in Galactic longitude (in mas/yr)
INPUT:
t - (optional) time at which to get pmll (can be Quantity)
v obs=[X,Y,Z,vx,vy,vz] - (optional) position and velocity of ob... | [
"def",
"pmll",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"out",
"=",
"self",
".",
"_orb",
".",
"pmll",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"if",
"len",
"(",
"out",
")",
"==",
"1",
":",
"return",
"out",
"[... | 28.837838 | 28.783784 |
def generate_surface_vectors(self, film_millers, substrate_millers):
"""
Generates the film/substrate slab combinations for a set of given
miller indicies
Args:
film_millers(array): all miller indices to generate slabs for
film
substrate_millers(a... | [
"def",
"generate_surface_vectors",
"(",
"self",
",",
"film_millers",
",",
"substrate_millers",
")",
":",
"vector_sets",
"=",
"[",
"]",
"for",
"f",
"in",
"film_millers",
":",
"film_slab",
"=",
"SlabGenerator",
"(",
"self",
".",
"film",
",",
"f",
",",
"20",
... | 39.931034 | 23.724138 |
def set_config_files_(self, *config_files):
"""Set the list of config files.
Args:
config_files (pathlike): path of config files, given in the order
of reading.
"""
self._config_files = tuple(pathlib.Path(path) for path in config_files) | [
"def",
"set_config_files_",
"(",
"self",
",",
"*",
"config_files",
")",
":",
"self",
".",
"_config_files",
"=",
"tuple",
"(",
"pathlib",
".",
"Path",
"(",
"path",
")",
"for",
"path",
"in",
"config_files",
")"
] | 36.25 | 19.875 |
def mapping_get(index, doc_type, hosts=None, profile=None):
'''
Retrieve mapping definition of index or index/type
index
Index for the mapping
doc_type
Name of the document type
CLI example::
salt myminion elasticsearch.mapping_get testindex user
'''
es = _get_inst... | [
"def",
"mapping_get",
"(",
"index",
",",
"doc_type",
",",
"hosts",
"=",
"None",
",",
"profile",
"=",
"None",
")",
":",
"es",
"=",
"_get_instance",
"(",
"hosts",
",",
"profile",
")",
"try",
":",
"return",
"es",
".",
"indices",
".",
"get_mapping",
"(",
... | 31.666667 | 27.952381 |
def reload_context(self, es_based, **kwargs):
""" Reload `self.context` object into a DB or ES object.
A reload is performed by getting the object ID from :kwargs: and then
getting a context key item from the new instance of `self._factory`
which is an ACL class used by the current view... | [
"def",
"reload_context",
"(",
"self",
",",
"es_based",
",",
"*",
"*",
"kwargs",
")",
":",
"from",
".",
"acl",
"import",
"BaseACL",
"key",
"=",
"self",
".",
"_get_context_key",
"(",
"*",
"*",
"kwargs",
")",
"kwargs",
"=",
"{",
"'request'",
":",
"self",
... | 39.125 | 18.5 |
def initialize(self, conf, ctx):
"""Initialization steps:
1. Get :func:`~birding.search.search_manager_from_config`.
2. Prepare to track searched terms as to avoid redundant searches.
"""
self.manager = get_search_manager()
config = get_config()['TwitterSearchBolt']
... | [
"def",
"initialize",
"(",
"self",
",",
"conf",
",",
"ctx",
")",
":",
"self",
".",
"manager",
"=",
"get_search_manager",
"(",
")",
"config",
"=",
"get_config",
"(",
")",
"[",
"'TwitterSearchBolt'",
"]",
"self",
".",
"term_shelf",
"=",
"shelf_from_config",
"... | 39.888889 | 14.666667 |
def _handle_compound(self, node, scope, ctxt, stream):
"""Handle Compound nodes
:node: TODO
:scope: TODO
:ctxt: TODO
:stream: TODO
:returns: TODO
"""
self._dlog("handling compound statement")
#scope.push()
try:
for child in n... | [
"def",
"_handle_compound",
"(",
"self",
",",
"node",
",",
"scope",
",",
"ctxt",
",",
"stream",
")",
":",
"self",
".",
"_dlog",
"(",
"\"handling compound statement\"",
")",
"#scope.push()",
"try",
":",
"for",
"child",
"in",
"node",
".",
"children",
"(",
")"... | 25.272727 | 20.590909 |
def include_feature(self, name):
"""Request inclusion of feature named 'name'"""
if self.feature_is_included(name) == 0:
descr = self.features[name].description
raise DistutilsOptionError(
descr + " is required, but was excluded or is not available"
)... | [
"def",
"include_feature",
"(",
"self",
",",
"name",
")",
":",
"if",
"self",
".",
"feature_is_included",
"(",
"name",
")",
"==",
"0",
":",
"descr",
"=",
"self",
".",
"features",
"[",
"name",
"]",
".",
"description",
"raise",
"DistutilsOptionError",
"(",
"... | 39.1 | 14 |
def transloadsForPeer(self, peer):
"""
Returns an iterator of transloads that apply to a particular peer.
"""
for tl in self.transloads.itervalues():
if peer in tl.peers:
yield tl | [
"def",
"transloadsForPeer",
"(",
"self",
",",
"peer",
")",
":",
"for",
"tl",
"in",
"self",
".",
"transloads",
".",
"itervalues",
"(",
")",
":",
"if",
"peer",
"in",
"tl",
".",
"peers",
":",
"yield",
"tl"
] | 33.285714 | 10.142857 |
def getslide(self,slide_num):
"""
Return the triggers with a specific slide number.
@param slide_num: the slide number to recover (contained in the event_id)
"""
slideTrigs = self.copy()
slideTrigs.extend(row for row in self if row.get_slide_number() == slide_num)
return slideTrigs | [
"def",
"getslide",
"(",
"self",
",",
"slide_num",
")",
":",
"slideTrigs",
"=",
"self",
".",
"copy",
"(",
")",
"slideTrigs",
".",
"extend",
"(",
"row",
"for",
"row",
"in",
"self",
"if",
"row",
".",
"get_slide_number",
"(",
")",
"==",
"slide_num",
")",
... | 36.125 | 16.375 |
def crypto_scalarmult_base(n):
"""
Computes and returns the scalar product of a standard group element and an
integer ``n``.
:param n: bytes
:rtype: bytes
"""
q = ffi.new("unsigned char[]", crypto_scalarmult_BYTES)
rc = lib.crypto_scalarmult_base(q, n)
ensure(rc == 0,
'U... | [
"def",
"crypto_scalarmult_base",
"(",
"n",
")",
":",
"q",
"=",
"ffi",
".",
"new",
"(",
"\"unsigned char[]\"",
",",
"crypto_scalarmult_BYTES",
")",
"rc",
"=",
"lib",
".",
"crypto_scalarmult_base",
"(",
"q",
",",
"n",
")",
"ensure",
"(",
"rc",
"==",
"0",
"... | 26.6875 | 18.6875 |
def parse_reports(self):
""" Find bamtools stats reports and parse their data """
# Set up vars
self.bamtools_stats_data = dict()
regexes = {
'total_reads': r"Total reads:\s*(\d+)",
'mapped_reads': r"Mapped reads:\s*(\d+)",
'mapped_reads_pct': r"Mapped reads:\s*\d+\s+\(([\d\.]+)... | [
"def",
"parse_reports",
"(",
"self",
")",
":",
"# Set up vars",
"self",
".",
"bamtools_stats_data",
"=",
"dict",
"(",
")",
"regexes",
"=",
"{",
"'total_reads'",
":",
"r\"Total reads:\\s*(\\d+)\"",
",",
"'mapped_reads'",
":",
"r\"Mapped reads:\\s*(\\d+)\"",
",",
"'ma... | 42.62037 | 22.583333 |
def _create_session(self):
"""
Creates a fresh session with no/default headers and proxies
"""
logger.debug("Create new phantomjs web driver")
self.driver = webdriver.PhantomJS(desired_capabilities=self.dcap,
**self.driver_args)
s... | [
"def",
"_create_session",
"(",
"self",
")",
":",
"logger",
".",
"debug",
"(",
"\"Create new phantomjs web driver\"",
")",
"self",
".",
"driver",
"=",
"webdriver",
".",
"PhantomJS",
"(",
"desired_capabilities",
"=",
"self",
".",
"dcap",
",",
"*",
"*",
"self",
... | 44.111111 | 13.666667 |
def add(self, *args, **kwargs):
""" add(other, rho=0, inplace=True)
Adds an *other* number instance. The correlation coefficient *rho* can be configured per
uncertainty when passed as a dict. When *inplace* is *False*, a new instance is returned.
"""
return self._apply(operator.a... | [
"def",
"add",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"self",
".",
"_apply",
"(",
"operator",
".",
"add",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | 55.833333 | 23.166667 |
def get_fragment(self, list_of_indextuples, give_only_index=False,
use_lookup=None):
"""Get the indices of the atoms in a fragment.
The list_of_indextuples contains all bondings from the
molecule to the fragment. ``[(1,3), (2,4)]`` means for example that the
fragmen... | [
"def",
"get_fragment",
"(",
"self",
",",
"list_of_indextuples",
",",
"give_only_index",
"=",
"False",
",",
"use_lookup",
"=",
"None",
")",
":",
"if",
"use_lookup",
"is",
"None",
":",
"use_lookup",
"=",
"settings",
"[",
"'defaults'",
"]",
"[",
"'use_lookup'",
... | 44.878788 | 21.757576 |
def _set_response_handlers(self, stanza, res_handler, err_handler,
timeout_handler = None, timeout = None):
"""Same as `set_response_handlers` but assume `self.lock` is
acquired."""
# pylint: disable-msg=R0913
self.fix_out_stanza(stanza)
to_jid = s... | [
"def",
"_set_response_handlers",
"(",
"self",
",",
"stanza",
",",
"res_handler",
",",
"err_handler",
",",
"timeout_handler",
"=",
"None",
",",
"timeout",
"=",
"None",
")",
":",
"# pylint: disable-msg=R0913",
"self",
".",
"fix_out_stanza",
"(",
"stanza",
")",
"to... | 46.086957 | 12.043478 |
def asr_breaking(self, tol_eigendisplacements=1e-5):
"""
Returns the breaking of the acoustic sum rule for the three acoustic modes,
if Gamma is present. None otherwise.
If eigendisplacements are available they are used to determine the acoustic
modes: selects the bands correspon... | [
"def",
"asr_breaking",
"(",
"self",
",",
"tol_eigendisplacements",
"=",
"1e-5",
")",
":",
"for",
"i",
"in",
"range",
"(",
"self",
".",
"nb_qpoints",
")",
":",
"if",
"np",
".",
"allclose",
"(",
"self",
".",
"qpoints",
"[",
"i",
"]",
".",
"frac_coords",
... | 47.62069 | 21.758621 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.