text stringlengths 89 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 630 |
|---|---|---|---|
def write_plain(self, text, attr=None):
u'''write text at current cursor position.'''
log(u'write("%s", %s)' %(text, attr))
if attr is None:
attr = self.attr
n = c_int(0)
self.SetConsoleTextAttribute(self.hout, attr)
self.WriteConsoleA(self.hout, text, ... | [
"def",
"write_plain",
"(",
"self",
",",
"text",
",",
"attr",
"=",
"None",
")",
":",
"log",
"(",
"u'write(\"%s\", %s)'",
"%",
"(",
"text",
",",
"attr",
")",
")",
"if",
"attr",
"is",
"None",
":",
"attr",
"=",
"self",
".",
"attr",
"n",
"=",
"c_int",
... | 40.444444 | 14 |
def combine_files(samples):
"""
after quantitation, combine the counts/FPKM/TPM/etc into a single table with
all samples
"""
data = samples[0][0]
# prefer the supplied transcriptome gtf file
gtf_file = dd.get_transcriptome_gtf(data, None)
if not gtf_file:
gtf_file = dd.get_gtf_fi... | [
"def",
"combine_files",
"(",
"samples",
")",
":",
"data",
"=",
"samples",
"[",
"0",
"]",
"[",
"0",
"]",
"# prefer the supplied transcriptome gtf file",
"gtf_file",
"=",
"dd",
".",
"get_transcriptome_gtf",
"(",
"data",
",",
"None",
")",
"if",
"not",
"gtf_file",... | 45.205479 | 22.60274 |
def TimeField(formatter=types.DEFAULT_TIME_FORMAT, default=NOTHING,
required=True, repr=True, cmp=True, key=None):
"""
Create new time field on a model.
:param formatter: time formatter string (default: "%H:%M:%S")
:param default: any time or string that can be converted to a time value
... | [
"def",
"TimeField",
"(",
"formatter",
"=",
"types",
".",
"DEFAULT_TIME_FORMAT",
",",
"default",
"=",
"NOTHING",
",",
"required",
"=",
"True",
",",
"repr",
"=",
"True",
",",
"cmp",
"=",
"True",
",",
"key",
"=",
"None",
")",
":",
"default",
"=",
"_init_f... | 53.111111 | 21.888889 |
def read_vcf(vcf_file, ref_file):
"""
Reads in a vcf/vcf.gz file and associated
reference sequence fasta (to which the VCF file is mapped).
Parses mutations, insertions, and deletions and stores them in a nested dict,
see 'returns' for the dict structure.
Calls with heterozygous values... | [
"def",
"read_vcf",
"(",
"vcf_file",
",",
"ref_file",
")",
":",
"#Programming Note:\r",
"# Note on VCF Format\r",
"# -------------------\r",
"# 'Insertion where there are also deletions' (special handling)\r",
"# Ex:\r",
"# REF ALT Seq1 Seq2\r",
"# GC G... | 38.82197 | 21.109848 |
def set_descriptor(dev, desc, desc_type, desc_index, wIndex = None):
r"""Update an existing descriptor or add a new one.
dev is the Device object to which the request will be
sent to.
The desc parameter is the descriptor to be sent to the device.
desc_type and desc_index are the descriptor type an... | [
"def",
"set_descriptor",
"(",
"dev",
",",
"desc",
",",
"desc_type",
",",
"desc_index",
",",
"wIndex",
"=",
"None",
")",
":",
"wValue",
"=",
"desc_index",
"|",
"(",
"desc_type",
"<<",
"8",
")",
"bmRequestType",
"=",
"util",
".",
"build_request_type",
"(",
... | 34.28 | 18.36 |
def parse(self, limit=None):
"""
Given the input taxa, expects files in the raw directory
with the name {tax_id}_anat_entity_all_data_Pan_troglodytes.tsv.zip
:param limit: int Limit to top ranked anatomy associations per group
:return: None
"""
files_to_download... | [
"def",
"parse",
"(",
"self",
",",
"limit",
"=",
"None",
")",
":",
"files_to_download",
",",
"ftp",
"=",
"self",
".",
"_get_file_list",
"(",
"self",
".",
"files",
"[",
"'anat_entity'",
"]",
"[",
"'path'",
"]",
",",
"self",
".",
"files",
"[",
"'anat_enti... | 39.944444 | 18.388889 |
def _require_staff_for_shared_settings(request, view, obj=None):
""" Allow to execute action only if service settings are not shared or user is staff """
if obj is None:
return
if obj.settings.shared and not request.user.is_staff:
raise PermissionDenied(_('Only staff use... | [
"def",
"_require_staff_for_shared_settings",
"(",
"request",
",",
"view",
",",
"obj",
"=",
"None",
")",
":",
"if",
"obj",
"is",
"None",
":",
"return",
"if",
"obj",
".",
"settings",
".",
"shared",
"and",
"not",
"request",
".",
"user",
".",
"is_staff",
":"... | 53.285714 | 27.857143 |
def run(self, pre_execute=True, concurrent_tasks=None, close=True, **kw):
"""
Run the calculation and return the exported outputs.
"""
with self._monitor:
self._monitor.username = kw.get('username', '')
self._monitor.hdf5 = self.datastore.hdf5
if concu... | [
"def",
"run",
"(",
"self",
",",
"pre_execute",
"=",
"True",
",",
"concurrent_tasks",
"=",
"None",
",",
"close",
"=",
"True",
",",
"*",
"*",
"kw",
")",
":",
"with",
"self",
".",
"_monitor",
":",
"self",
".",
"_monitor",
".",
"username",
"=",
"kw",
"... | 42.438596 | 12.719298 |
def control_group(self, control_group_id, ctrl, shift, alt):
"""Act on a control group, selecting, setting, etc."""
action = sc_pb.Action()
select = action.action_ui.control_group
mod = sc_ui.ActionControlGroup
if not ctrl and not shift and not alt:
select.action = mod.Recall
elif ctrl an... | [
"def",
"control_group",
"(",
"self",
",",
"control_group_id",
",",
"ctrl",
",",
"shift",
",",
"alt",
")",
":",
"action",
"=",
"sc_pb",
".",
"Action",
"(",
")",
"select",
"=",
"action",
".",
"action_ui",
".",
"control_group",
"mod",
"=",
"sc_ui",
".",
"... | 34.4 | 9.9 |
def _parse_patterns(self, pattern):
"""Parse patterns."""
self.pattern = []
self.npatterns = None
npattern = []
for p in pattern:
if _wcparse.is_negative(p, self.flags):
# Treat the inverse pattern as a normal pattern if it matches, we will exclude.
... | [
"def",
"_parse_patterns",
"(",
"self",
",",
"pattern",
")",
":",
"self",
".",
"pattern",
"=",
"[",
"]",
"self",
".",
"npatterns",
"=",
"None",
"npattern",
"=",
"[",
"]",
"for",
"p",
"in",
"pattern",
":",
"if",
"_wcparse",
".",
"is_negative",
"(",
"p"... | 50.9 | 29.15 |
def from_quad_tree(cls, quad_tree):
"""Creates a tile from a Microsoft QuadTree"""
assert bool(re.match('^[0-3]*$', quad_tree)), 'QuadTree value can only consists of the digits 0, 1, 2 and 3.'
zoom = len(str(quad_tree))
offset = int(math.pow(2, zoom)) - 1
google_x, google_y = [re... | [
"def",
"from_quad_tree",
"(",
"cls",
",",
"quad_tree",
")",
":",
"assert",
"bool",
"(",
"re",
".",
"match",
"(",
"'^[0-3]*$'",
",",
"quad_tree",
")",
")",
",",
"'QuadTree value can only consists of the digits 0, 1, 2 and 3.'",
"zoom",
"=",
"len",
"(",
"str",
"("... | 67.888889 | 28.777778 |
def mcmc_CH(self, walkerRatio, n_run, n_burn, mean_start, sigma_start, threadCount=1, init_pos=None, mpi=False):
"""
runs mcmc on the parameter space given parameter bounds with CosmoHammerSampler
returns the chain
"""
lowerLimit, upperLimit = self.lower_limit, self.upper_limit
... | [
"def",
"mcmc_CH",
"(",
"self",
",",
"walkerRatio",
",",
"n_run",
",",
"n_burn",
",",
"mean_start",
",",
"sigma_start",
",",
"threadCount",
"=",
"1",
",",
"init_pos",
"=",
"None",
",",
"mpi",
"=",
"False",
")",
":",
"lowerLimit",
",",
"upperLimit",
"=",
... | 38.506849 | 13.219178 |
def viscosity_kinematic_chem(conc_chem, temp, en_chem):
"""Return the dynamic viscosity of water at a given temperature.
If given units, the function will automatically convert to Kelvin.
If not given units, the function will assume Kelvin.
"""
if en_chem == 0:
nu = viscosity_kinematic_a... | [
"def",
"viscosity_kinematic_chem",
"(",
"conc_chem",
",",
"temp",
",",
"en_chem",
")",
":",
"if",
"en_chem",
"==",
"0",
":",
"nu",
"=",
"viscosity_kinematic_alum",
"(",
"conc_chem",
",",
"temp",
")",
".",
"magnitude",
"if",
"en_chem",
"==",
"1",
":",
"nu",... | 40.461538 | 18.461538 |
def _check_rotated_filename_candidates(self):
"""
Check for various rotated logfile filename patterns and return the first
match we find.
"""
# savelog(8)
candidate = "%s.0" % self.filename
if (exists(candidate) and exists("%s.1.gz" % self.filename) and
... | [
"def",
"_check_rotated_filename_candidates",
"(",
"self",
")",
":",
"# savelog(8)",
"candidate",
"=",
"\"%s.0\"",
"%",
"self",
".",
"filename",
"if",
"(",
"exists",
"(",
"candidate",
")",
"and",
"exists",
"(",
"\"%s.1.gz\"",
"%",
"self",
".",
"filename",
")",
... | 45.25 | 24.958333 |
def model_saved(sender, instance,
created,
raw,
using,
**kwargs):
"""
Automatically triggers "created" and "updated" actions.
"""
opts = get_opts(instance)
model = '.'.join([opts.app_label, opts.object_na... | [
"def",
"model_saved",
"(",
"sender",
",",
"instance",
",",
"created",
",",
"raw",
",",
"using",
",",
"*",
"*",
"kwargs",
")",
":",
"opts",
"=",
"get_opts",
"(",
"instance",
")",
"model",
"=",
"'.'",
".",
"join",
"(",
"[",
"opts",
".",
"app_label",
... | 34.25 | 8.75 |
def unicorn_edit(path, **kwargs):
"""Edit Unicorn node interactively.
"""
ctx = Context(**kwargs)
ctx.timeout = None
ctx.execute_action('unicorn:edit', **{
'unicorn': ctx.repo.create_secure_service('unicorn'),
'path': path,
}) | [
"def",
"unicorn_edit",
"(",
"path",
",",
"*",
"*",
"kwargs",
")",
":",
"ctx",
"=",
"Context",
"(",
"*",
"*",
"kwargs",
")",
"ctx",
".",
"timeout",
"=",
"None",
"ctx",
".",
"execute_action",
"(",
"'unicorn:edit'",
",",
"*",
"*",
"{",
"'unicorn'",
":",... | 28.666667 | 12.666667 |
def remove_edge(self, id1, id2):
""" Remove edges between nodes with given id's.
"""
for e in list(self.edges):
if id1 in (e.node1.id, e.node2.id) and \
id2 in (e.node1.id, e.node2.id):
e.node1.links.remove(e.node2)
e.n... | [
"def",
"remove_edge",
"(",
"self",
",",
"id1",
",",
"id2",
")",
":",
"for",
"e",
"in",
"list",
"(",
"self",
".",
"edges",
")",
":",
"if",
"id1",
"in",
"(",
"e",
".",
"node1",
".",
"id",
",",
"e",
".",
"node2",
".",
"id",
")",
"and",
"id2",
... | 33.909091 | 10.090909 |
def labeled(**kwargs):
"""decorator to give practices labels"""
def for_practice(practice):
"""assigns label to practice"""
practice.code = kwargs.pop('code')
practice.msg = kwargs.pop('msg')
practice.solution = kwargs.pop('solution')
return practice
return for_practi... | [
"def",
"labeled",
"(",
"*",
"*",
"kwargs",
")",
":",
"def",
"for_practice",
"(",
"practice",
")",
":",
"\"\"\"assigns label to practice\"\"\"",
"practice",
".",
"code",
"=",
"kwargs",
".",
"pop",
"(",
"'code'",
")",
"practice",
".",
"msg",
"=",
"kwargs",
"... | 34.888889 | 8.111111 |
def channel_submit_row(context):
"""
Display the row of buttons for delete and save.
"""
change = context['change']
is_popup = context['is_popup']
save_as = context['save_as']
show_save = context.get('show_save', True)
show_save_and_continue = context.get('show_save_and_continue', True)
... | [
"def",
"channel_submit_row",
"(",
"context",
")",
":",
"change",
"=",
"context",
"[",
"'change'",
"]",
"is_popup",
"=",
"context",
"[",
"'is_popup'",
"]",
"save_as",
"=",
"context",
"[",
"'save_as'",
"]",
"show_save",
"=",
"context",
".",
"get",
"(",
"'sho... | 37.7 | 15.166667 |
def _nuke_set_zero_margins(widget_object):
"""Remove Nuke margins when docked UI
.. _More info:
https://gist.github.com/maty974/4739917
"""
parentApp = QtWidgets.QApplication.allWidgets()
parentWidgetList = []
for parent in parentApp:
for child in parent.children():
i... | [
"def",
"_nuke_set_zero_margins",
"(",
"widget_object",
")",
":",
"parentApp",
"=",
"QtWidgets",
".",
"QApplication",
".",
"allWidgets",
"(",
")",
"parentWidgetList",
"=",
"[",
"]",
"for",
"parent",
"in",
"parentApp",
":",
"for",
"child",
"in",
"parent",
".",
... | 41.304348 | 11.565217 |
def is_name_revoked( self, name ):
"""
Determine if a name is revoked at this block.
"""
name = self.get_name( name )
if name is None:
return False
if name['revoked']:
return True
else:
return False | [
"def",
"is_name_revoked",
"(",
"self",
",",
"name",
")",
":",
"name",
"=",
"self",
".",
"get_name",
"(",
"name",
")",
"if",
"name",
"is",
"None",
":",
"return",
"False",
"if",
"name",
"[",
"'revoked'",
"]",
":",
"return",
"True",
"else",
":",
"return... | 23.416667 | 13.916667 |
def _get_full_paths(fastq_dir, config, config_file):
"""Retrieve full paths for directories in the case of relative locations.
"""
if fastq_dir:
fastq_dir = utils.add_full_path(fastq_dir)
config_dir = utils.add_full_path(os.path.dirname(config_file))
galaxy_config_file = utils.add_full_path(... | [
"def",
"_get_full_paths",
"(",
"fastq_dir",
",",
"config",
",",
"config_file",
")",
":",
"if",
"fastq_dir",
":",
"fastq_dir",
"=",
"utils",
".",
"add_full_path",
"(",
"fastq_dir",
")",
"config_dir",
"=",
"utils",
".",
"add_full_path",
"(",
"os",
".",
"path",... | 54.222222 | 18.888889 |
def docstr(self, prefix='', include_label=True):
"""Returns the ``docstr`` of each parameter joined together."""
return '\n'.join([x.docstr(prefix, include_label) for x in self]) | [
"def",
"docstr",
"(",
"self",
",",
"prefix",
"=",
"''",
",",
"include_label",
"=",
"True",
")",
":",
"return",
"'\\n'",
".",
"join",
"(",
"[",
"x",
".",
"docstr",
"(",
"prefix",
",",
"include_label",
")",
"for",
"x",
"in",
"self",
"]",
")"
] | 64 | 13.666667 |
def process_response(self, request, response):
"""Sets the cache, if needed."""
# never cache headers + ETag
add_never_cache_headers(response)
if not hasattr(request, '_cache_update_cache') or not request._cache_update_cache:
# We don't need to update the cache, just return... | [
"def",
"process_response",
"(",
"self",
",",
"request",
",",
"response",
")",
":",
"# never cache headers + ETag",
"add_never_cache_headers",
"(",
"response",
")",
"if",
"not",
"hasattr",
"(",
"request",
",",
"'_cache_update_cache'",
")",
"or",
"not",
"request",
"... | 42.407407 | 21.148148 |
def _find_sources(im, target, sources, polarity):
"""Get the subset of source nodes with paths to the target.
Given a target, a list of sources, and a path polarity, perform a
breadth-first search upstream from the target to determine whether any of
the queried sources have paths to the target with the... | [
"def",
"_find_sources",
"(",
"im",
",",
"target",
",",
"sources",
",",
"polarity",
")",
":",
"# First, create a list of visited nodes",
"# Adapted from",
"# networkx.algorithms.traversal.breadth_first_search.bfs_edges",
"visited",
"=",
"set",
"(",
"[",
"(",
"target",
",",... | 45.4 | 21.430769 |
def nextline(self):
"""Fetches a next line that ends either with \\r or \\n.
"""
linebuf = b''
linepos = self.bufpos + self.charpos
eol = False
while 1:
self.fillbuf()
if eol:
c = self.buf[self.charpos]
# handle b'\r... | [
"def",
"nextline",
"(",
"self",
")",
":",
"linebuf",
"=",
"b''",
"linepos",
"=",
"self",
".",
"bufpos",
"+",
"self",
".",
"charpos",
"eol",
"=",
"False",
"while",
"1",
":",
"self",
".",
"fillbuf",
"(",
")",
"if",
"eol",
":",
"c",
"=",
"self",
"."... | 32.586207 | 12.344828 |
def fixedvar(self):
"""Returns the name of a member in this type that is non-custom
so that it would terminate the auto-class variable context chain.
"""
possible = [m for m in self.members.values() if not m.is_custom]
#If any of the possible variables is not allocatable or point... | [
"def",
"fixedvar",
"(",
"self",
")",
":",
"possible",
"=",
"[",
"m",
"for",
"m",
"in",
"self",
".",
"members",
".",
"values",
"(",
")",
"if",
"not",
"m",
".",
"is_custom",
"]",
"#If any of the possible variables is not allocatable or pointer, it will always",
"#... | 49.230769 | 18 |
def load(self, patterns, dirs, ignore=None, **kwargs):
"""Load objects from the filesystem into the ``paths`` dictionary.
If the setting ``autoapi_patterns`` was not specified, look for a
``docfx.json`` file by default. A ``docfx.json`` should be treated as
the canonical source before ... | [
"def",
"load",
"(",
"self",
",",
"patterns",
",",
"dirs",
",",
"ignore",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"raise_error",
"=",
"kwargs",
".",
"get",
"(",
"\"raise_error\"",
",",
"True",
")",
"all_files",
"=",
"set",
"(",
")",
"if",
"n... | 42 | 14.303571 |
def delete_intel_notifications(self, ids, timeout=None):
""" Programmatically delete notifications via the Intel API.
:param ids: A list of IDs to delete from the notification feed.
:returns: The post response.
"""
if not isinstance(ids, list):
raise TypeError("ids m... | [
"def",
"delete_intel_notifications",
"(",
"self",
",",
"ids",
",",
"timeout",
"=",
"None",
")",
":",
"if",
"not",
"isinstance",
"(",
"ids",
",",
"list",
")",
":",
"raise",
"TypeError",
"(",
"\"ids must be a list\"",
")",
"# VirusTotal needs ids as a stringified ar... | 35.818182 | 17.318182 |
def _load_next(self):
"""Load the next days data (or file) without incrementing the date.
Repeated calls will not advance date/file and will produce the same data
Uses info stored in object to either increment the date,
or the file. Looks for self._load_by_date flag.
... | [
"def",
"_load_next",
"(",
"self",
")",
":",
"if",
"self",
".",
"_load_by_date",
":",
"next_date",
"=",
"self",
".",
"date",
"+",
"pds",
".",
"DateOffset",
"(",
"days",
"=",
"1",
")",
"return",
"self",
".",
"_load_data",
"(",
"date",
"=",
"next_date",
... | 40.538462 | 18.384615 |
def drop(self):
"""Drop the table from the database.
Deletes both the schema and all the contents within it.
"""
with self.db.lock:
if self.exists:
self._threading_warn()
self.table.drop(self.db.executable, checkfirst=True)
sel... | [
"def",
"drop",
"(",
"self",
")",
":",
"with",
"self",
".",
"db",
".",
"lock",
":",
"if",
"self",
".",
"exists",
":",
"self",
".",
"_threading_warn",
"(",
")",
"self",
".",
"table",
".",
"drop",
"(",
"self",
".",
"db",
".",
"executable",
",",
"che... | 32.6 | 15.1 |
def make_object_graph(obj, fpath='sample_graph.png'):
""" memoryprofile with objgraph
Examples:
#import objgraph
#objgraph.show_most_common_types()
#objgraph.show_growth()
#memtrack.report()
#memtrack.report()
#objgraph.show_growth()
#import gc
#g... | [
"def",
"make_object_graph",
"(",
"obj",
",",
"fpath",
"=",
"'sample_graph.png'",
")",
":",
"import",
"objgraph",
"objgraph",
".",
"show_most_common_types",
"(",
")",
"#print(objgraph.by_type('ndarray'))",
"#objgraph.find_backref_chain(",
"# random.choice(objgraph.by_type('n... | 28.62069 | 14.62069 |
def save_ndarray_to_fits(array=None, file_name=None,
main_header=None,
cast_to_float=True,
crpix1=None, crval1=None, cdelt1=None,
overwrite=True):
"""Save numpy array(s) into a FITS file with the provided filename.
... | [
"def",
"save_ndarray_to_fits",
"(",
"array",
"=",
"None",
",",
"file_name",
"=",
"None",
",",
"main_header",
"=",
"None",
",",
"cast_to_float",
"=",
"True",
",",
"crpix1",
"=",
"None",
",",
"crval1",
"=",
"None",
",",
"cdelt1",
"=",
"None",
",",
"overwri... | 40.579832 | 17.084034 |
def walk_tree_and_replace(self, data, overrides):
'''
Walk the tree. Rely on json decoding to insert instances of dict and list
ie we use a dna test for anatine, rather than our eyes and ears...
'''
if isinstance(data, dict):
response = {}
replacements = {... | [
"def",
"walk_tree_and_replace",
"(",
"self",
",",
"data",
",",
"overrides",
")",
":",
"if",
"isinstance",
"(",
"data",
",",
"dict",
")",
":",
"response",
"=",
"{",
"}",
"replacements",
"=",
"{",
"}",
"# look for id entry",
"thisID",
"=",
"data",
".",
"ge... | 42.68 | 16.44 |
def linearize(self, x0: np.array=None, u0: np.array=None) -> List[np.array]:
"""
Numerical linearization
:param x0: initial state
:param u0: initial input
:return: list of Jacobians
"""
ss = self.linearize_symbolic()
ss_eval = []
ss_subs = {}
... | [
"def",
"linearize",
"(",
"self",
",",
"x0",
":",
"np",
".",
"array",
"=",
"None",
",",
"u0",
":",
"np",
".",
"array",
"=",
"None",
")",
"->",
"List",
"[",
"np",
".",
"array",
"]",
":",
"ss",
"=",
"self",
".",
"linearize_symbolic",
"(",
")",
"ss... | 37.62963 | 11.62963 |
def get_user_details(self, response):
"""
Return user details from Dataporten
Set username to email address
"""
user = super(DataportenEmailOAuth2, self).get_user_details(response)
user['username'] = user['email']
return user | [
"def",
"get_user_details",
"(",
"self",
",",
"response",
")",
":",
"user",
"=",
"super",
"(",
"DataportenEmailOAuth2",
",",
"self",
")",
".",
"get_user_details",
"(",
"response",
")",
"user",
"[",
"'username'",
"]",
"=",
"user",
"[",
"'email'",
"]",
"retur... | 30.444444 | 11.777778 |
def user_remove(self, domain, userid):
"""
Remove a user
:param AuthDomain domain: The authentication domain for the user.
:param userid: The user ID to remove
:raise: :exc:`couchbase.exceptions.HTTPError` if the user does not exist.
:return: :class:`~.HttpResult`
... | [
"def",
"user_remove",
"(",
"self",
",",
"domain",
",",
"userid",
")",
":",
"path",
"=",
"self",
".",
"_get_management_path",
"(",
"domain",
",",
"userid",
")",
"return",
"self",
".",
"http_request",
"(",
"path",
"=",
"path",
",",
"method",
"=",
"'DELETE'... | 42.272727 | 11.727273 |
def reward(self,
state: Sequence[tf.Tensor],
action: Sequence[tf.Tensor],
next_state: Sequence[tf.Tensor]) -> tf.Tensor:
'''Compiles the reward function given the current `state`, `action` and
`next_state`.
Args:
state (Sequence[tf.Tensor... | [
"def",
"reward",
"(",
"self",
",",
"state",
":",
"Sequence",
"[",
"tf",
".",
"Tensor",
"]",
",",
"action",
":",
"Sequence",
"[",
"tf",
".",
"Tensor",
"]",
",",
"next_state",
":",
"Sequence",
"[",
"tf",
".",
"Tensor",
"]",
")",
"->",
"tf",
".",
"T... | 41.05 | 21.65 |
def extract_name(self, data):
"""Extract man page name from web page."""
name = re.search('<h1[^>]*>(.+?)</h1>', data).group(1)
name = re.sub(r'<([^>]+)>', r'', name)
name = re.sub(r'>', r'>', name)
name = re.sub(r'<', r'<', name)
return name | [
"def",
"extract_name",
"(",
"self",
",",
"data",
")",
":",
"name",
"=",
"re",
".",
"search",
"(",
"'<h1[^>]*>(.+?)</h1>'",
",",
"data",
")",
".",
"group",
"(",
"1",
")",
"name",
"=",
"re",
".",
"sub",
"(",
"r'<([^>]+)>'",
",",
"r''",
",",
"name",
"... | 41.428571 | 9.142857 |
def _runner(self, classpath, main, jvm_options, args, cwd=None):
"""Runner factory. Called via Executor.execute()."""
command = self._create_command(classpath, main, jvm_options, args)
class Runner(self.Runner):
@property
def executor(this):
return self
@property
def comman... | [
"def",
"_runner",
"(",
"self",
",",
"classpath",
",",
"main",
",",
"jvm_options",
",",
"args",
",",
"cwd",
"=",
"None",
")",
":",
"command",
"=",
"self",
".",
"_create_command",
"(",
"classpath",
",",
"main",
",",
"jvm_options",
",",
"args",
")",
"clas... | 40.142857 | 25.642857 |
def auto_model(layout, scan_length=None, one_vs_rest=False):
'''Create a simple default model for each of the tasks in a BIDSLayout.
Contrasts each trial type against all other trial types and trial types
at the run level and then uses t-tests at each other level present to
aggregate these results up.
... | [
"def",
"auto_model",
"(",
"layout",
",",
"scan_length",
"=",
"None",
",",
"one_vs_rest",
"=",
"False",
")",
":",
"base_name",
"=",
"split",
"(",
"layout",
".",
"root",
")",
"[",
"-",
"1",
"]",
"tasks",
"=",
"layout",
".",
"entities",
"[",
"'task'",
"... | 39.057692 | 21.788462 |
def get_sample_data(sample_file):
"""Read and returns sample data to fill form with default sample sequence. """
sequence_sample_in_fasta = None
with open(sample_file) as handle:
sequence_sample_in_fasta = handle.read()
return sequence_sample_in_fasta | [
"def",
"get_sample_data",
"(",
"sample_file",
")",
":",
"sequence_sample_in_fasta",
"=",
"None",
"with",
"open",
"(",
"sample_file",
")",
"as",
"handle",
":",
"sequence_sample_in_fasta",
"=",
"handle",
".",
"read",
"(",
")",
"return",
"sequence_sample_in_fasta"
] | 33.875 | 13.5 |
def combine_metadata(*metadata_objects, **kwargs):
"""Combine the metadata of two or more Datasets.
If any keys are not equal or do not exist in all provided dictionaries
then they are not included in the returned dictionary.
By default any keys with the word 'time' in them and consisting
of dateti... | [
"def",
"combine_metadata",
"(",
"*",
"metadata_objects",
",",
"*",
"*",
"kwargs",
")",
":",
"average_times",
"=",
"kwargs",
".",
"get",
"(",
"'average_times'",
",",
"True",
")",
"# python 2 compatibility (no kwarg after *args)",
"shared_keys",
"=",
"None",
"info_dic... | 38.632653 | 21.183673 |
def leftMouseDragged(self, stopCoord, strCoord=(0, 0), speed=1):
"""Click the left mouse button and drag object.
Parameters: stopCoord, the position of dragging stopped
strCoord, the position of dragging started
(0,0) will get current position
... | [
"def",
"leftMouseDragged",
"(",
"self",
",",
"stopCoord",
",",
"strCoord",
"=",
"(",
"0",
",",
"0",
")",
",",
"speed",
"=",
"1",
")",
":",
"self",
".",
"_leftMouseDragged",
"(",
"stopCoord",
",",
"strCoord",
",",
"speed",
")"
] | 44.8 | 18 |
def _generate_date_indicators(catalog, tolerance=0.2, only_numeric=False):
"""Genera indicadores relacionados a las fechas de publicación
y actualización del catálogo pasado por parámetro. La evaluación de si
un catálogo se encuentra actualizado o no tiene un porcentaje de
tolerancia hasta que se lo con... | [
"def",
"_generate_date_indicators",
"(",
"catalog",
",",
"tolerance",
"=",
"0.2",
",",
"only_numeric",
"=",
"False",
")",
":",
"result",
"=",
"{",
"'datasets_desactualizados_cant'",
":",
"None",
",",
"'datasets_actualizados_cant'",
":",
"None",
",",
"'datasets_actua... | 37.598131 | 20.35514 |
def list_processed_parameter_group_histogram(self, group=None, start=None, stop=None, merge_time=20):
"""
Reads index records related to processed parameter groups between the
specified start and stop time.
Each iteration returns a chunk of chronologically-sorted records.
:para... | [
"def",
"list_processed_parameter_group_histogram",
"(",
"self",
",",
"group",
"=",
"None",
",",
"start",
"=",
"None",
",",
"stop",
"=",
"None",
",",
"merge_time",
"=",
"20",
")",
":",
"params",
"=",
"{",
"}",
"if",
"group",
"is",
"not",
"None",
":",
"p... | 38.928571 | 19.642857 |
def touch(self):
"""
Mark this update as complete.
The document id would be sufficent but,
for documentation,
we index the parameters `update_id`, `target_index`, `target_doc_type` and `date` as well.
"""
self.create_marker_index()
self.es.index(index=sel... | [
"def",
"touch",
"(",
"self",
")",
":",
"self",
".",
"create_marker_index",
"(",
")",
"self",
".",
"es",
".",
"index",
"(",
"index",
"=",
"self",
".",
"marker_index",
",",
"doc_type",
"=",
"self",
".",
"marker_doc_type",
",",
"id",
"=",
"self",
".",
"... | 43 | 17.705882 |
def parse_application_name(setup_filename):
"""Parse a setup.py file for the name.
Returns:
name, or None
"""
with open(setup_filename, 'rt') as setup_file:
fst = RedBaron(setup_file.read())
for node in fst:
if (
no... | [
"def",
"parse_application_name",
"(",
"setup_filename",
")",
":",
"with",
"open",
"(",
"setup_filename",
",",
"'rt'",
")",
"as",
"setup_file",
":",
"fst",
"=",
"RedBaron",
"(",
"setup_file",
".",
"read",
"(",
")",
")",
"for",
"node",
"in",
"fst",
":",
"i... | 35.304348 | 12.304348 |
def presence_handler(stream, type_, from_, cb):
"""
Context manager to temporarily register a callback to handle presence
stanzas on a :class:`StanzaStream`.
:param stream: Stanza stream to register the coroutine at
:type stream: :class:`StanzaStream`
:param type_: Presence type to listen for.
... | [
"def",
"presence_handler",
"(",
"stream",
",",
"type_",
",",
"from_",
",",
"cb",
")",
":",
"stream",
".",
"register_presence_callback",
"(",
"type_",
",",
"from_",
",",
"cb",
",",
")",
"try",
":",
"yield",
"finally",
":",
"stream",
".",
"unregister_presenc... | 27.5625 | 20.0625 |
def find_hal(self, atoms):
"""Look for halogen bond donors (X-C, with X=F, Cl, Br, I)"""
data = namedtuple('hal_donor', 'x orig_x x_orig_idx c c_orig_idx')
a_set = []
for a in atoms:
if self.is_functional_group(a, 'halocarbon'):
n_atoms = [na for na in pybel.o... | [
"def",
"find_hal",
"(",
"self",
",",
"atoms",
")",
":",
"data",
"=",
"namedtuple",
"(",
"'hal_donor'",
",",
"'x orig_x x_orig_idx c c_orig_idx'",
")",
"a_set",
"=",
"[",
"]",
"for",
"a",
"in",
"atoms",
":",
"if",
"self",
".",
"is_functional_group",
"(",
"a... | 61.6 | 31.133333 |
def scale_factors(self, tile_width, tile_height=None):
"""Return a set of scale factors for given tile and window size.
Gives a set of scale factors, starting at 1, and in multiples
of 2. Largest scale_factor is so that one tile will cover the
entire image (self.width,self.height).
... | [
"def",
"scale_factors",
"(",
"self",
",",
"tile_width",
",",
"tile_height",
"=",
"None",
")",
":",
"if",
"(",
"not",
"tile_height",
")",
":",
"tile_height",
"=",
"tile_width",
"sf",
"=",
"1",
"scale_factors",
"=",
"[",
"sf",
"]",
"for",
"j",
"in",
"ran... | 38.285714 | 16.047619 |
def _groupby_new_state(index, outputs, decisions):
"""Groups the simulants in the index by their new output state.
Parameters
----------
index : iterable of ints
An iterable of integer labels for the simulants.
outputs : iterable
A list of possible output states.
decisions : `pa... | [
"def",
"_groupby_new_state",
"(",
"index",
",",
"outputs",
",",
"decisions",
")",
":",
"output_map",
"=",
"{",
"o",
":",
"i",
"for",
"i",
",",
"o",
"in",
"enumerate",
"(",
"outputs",
")",
"}",
"groups",
"=",
"pd",
".",
"Series",
"(",
"index",
")",
... | 39.461538 | 21.307692 |
def properties(self, var_or_nodeid, as_list=False):
"""
Return a dictionary of variable properties for *var_or_nodeid*.
Args:
var_or_nodeid: if a variable, return the properties
associated with the variable; if a nodeid, return the
properties associat... | [
"def",
"properties",
"(",
"self",
",",
"var_or_nodeid",
",",
"as_list",
"=",
"False",
")",
":",
"props",
"=",
"[",
"]",
"if",
"var_or_nodeid",
"in",
"self",
".",
"_vars",
":",
"props",
"=",
"self",
".",
"_vars",
"[",
"var_or_nodeid",
"]",
"[",
"'props'... | 38.47619 | 16.761905 |
def restore(self, state):
"""Restore the contents of this virtual stream walker.
Args:
state (dict): The previously serialized state.
Raises:
ArgumentError: If the serialized state does not have
a matching selector.
"""
selector = DataS... | [
"def",
"restore",
"(",
"self",
",",
"state",
")",
":",
"selector",
"=",
"DataStreamSelector",
".",
"FromString",
"(",
"state",
".",
"get",
"(",
"u'selector'",
")",
")",
"if",
"self",
".",
"selector",
"!=",
"selector",
":",
"raise",
"ArgumentError",
"(",
... | 38.157895 | 27.368421 |
def create(cls, uri, tlp_level=0, tags=[]):
"""
Create a new :class:`URISample` on the server.
:param uri: The uri as a string.
:param tlp_level: The TLP-Level
:param tags: Tags to add to the sample.
:return: The created sample.
"""
return cls._create(uri... | [
"def",
"create",
"(",
"cls",
",",
"uri",
",",
"tlp_level",
"=",
"0",
",",
"tags",
"=",
"[",
"]",
")",
":",
"return",
"cls",
".",
"_create",
"(",
"uri",
"=",
"uri",
",",
"tlp_level",
"=",
"tlp_level",
",",
"tags",
"=",
"tags",
")"
] | 34.8 | 9.6 |
def tokenize(self, string):
"""Used to parce a string into tokens
This function is to take in a string and return a list of tokens
Args:
string(str): This is a string of words or a sentance to be parsed into tokens
Returns:
list: a list of tokens from the strin... | [
"def",
"tokenize",
"(",
"self",
",",
"string",
")",
":",
"s",
"=",
"string",
"s",
"=",
"re",
".",
"sub",
"(",
"'\\t'",
",",
"\" \"",
",",
"s",
")",
"s",
"=",
"re",
".",
"sub",
"(",
"\"(\"",
"+",
"regex_separator",
"+",
"\")\"",
",",
"\" \\g<1> \"... | 38.488889 | 24.622222 |
def patch_ui_functions(wrapper):
'''Wrap all termui functions with a custom decorator.'''
NONE = object()
import click
saved = []
for name, info in sorted(_ui_functions.items()):
f = getattr(click, name, NONE)
if f is NONE:
continue
new_f = wrapper(_copy_fn(f),... | [
"def",
"patch_ui_functions",
"(",
"wrapper",
")",
":",
"NONE",
"=",
"object",
"(",
")",
"import",
"click",
"saved",
"=",
"[",
"]",
"for",
"name",
",",
"info",
"in",
"sorted",
"(",
"_ui_functions",
".",
"items",
"(",
")",
")",
":",
"f",
"=",
"getattr"... | 25.930233 | 20.44186 |
def to_scales(val):
"""Parse *val* to return an array of scale factors.
"""
res = []
for i in val:
if len(i) == 3:
res.append((i[0], type(i[2])))
else:
try:
res.append((i[0], i[3].dtype, i[2]))
except AttributeError:
res... | [
"def",
"to_scales",
"(",
"val",
")",
":",
"res",
"=",
"[",
"]",
"for",
"i",
"in",
"val",
":",
"if",
"len",
"(",
"i",
")",
"==",
"3",
":",
"res",
".",
"append",
"(",
"(",
"i",
"[",
"0",
"]",
",",
"type",
"(",
"i",
"[",
"2",
"]",
")",
")"... | 24.5 | 20 |
def detokenize(tokens):
"""
Detokenizing a text undoes the tokenizing operation, restores
punctuation and spaces to the places that people expect them to be.
Ideally, `detokenize(tokenize(text))` should be identical to `text`,
except for line breaks.
"""
text = ' '.join(tokens)
step0 = t... | [
"def",
"detokenize",
"(",
"tokens",
")",
":",
"text",
"=",
"' '",
".",
"join",
"(",
"tokens",
")",
"step0",
"=",
"text",
".",
"replace",
"(",
"'. . .'",
",",
"'...'",
")",
"step1",
"=",
"step0",
".",
"replace",
"(",
"\"`` \"",
",",
"'\"'",
")",
"."... | 44 | 15.058824 |
def getTotalBulkPrice(self):
"""Compute total bulk price
"""
price = self.getBulkPrice()
vat = self.getVAT()
price = price and price or 0
vat = vat and vat or 0
return float(price) + (float(price) * float(vat)) / 100 | [
"def",
"getTotalBulkPrice",
"(",
"self",
")",
":",
"price",
"=",
"self",
".",
"getBulkPrice",
"(",
")",
"vat",
"=",
"self",
".",
"getVAT",
"(",
")",
"price",
"=",
"price",
"and",
"price",
"or",
"0",
"vat",
"=",
"vat",
"and",
"vat",
"or",
"0",
"retu... | 33.125 | 8.375 |
def __list_updates(update_type, update_list):
"""
Function used to list package updates by update type in console
:param update_type: string
:param update_list: list
"""
if len(update_list):
print(" %s:" % update_type)
for update_item in update_list:
print(" -- %(v... | [
"def",
"__list_updates",
"(",
"update_type",
",",
"update_list",
")",
":",
"if",
"len",
"(",
"update_list",
")",
":",
"print",
"(",
"\" %s:\"",
"%",
"update_type",
")",
"for",
"update_item",
"in",
"update_list",
":",
"print",
"(",
"\" -- %(version)s on %(uploa... | 32.090909 | 13.181818 |
def split_unescaped(char, string, include_empty_strings=False):
'''
:param char: The character on which to split the string
:type char: string
:param string: The string to split
:type string: string
:returns: List of substrings of *string*
:rtype: list of strings
Splits *string* wheneve... | [
"def",
"split_unescaped",
"(",
"char",
",",
"string",
",",
"include_empty_strings",
"=",
"False",
")",
":",
"words",
"=",
"[",
"]",
"pos",
"=",
"len",
"(",
"string",
")",
"lastpos",
"=",
"pos",
"while",
"pos",
">=",
"0",
":",
"pos",
"=",
"get_last_pos_... | 31.148148 | 20.259259 |
def derivativeZ(self,mLvl,pLvl,MedShk):
'''
Evaluate the derivative of consumption and medical care with respect to
medical need shock at given levels of market resources, permanent income,
and medical need shocks.
Parameters
----------
mLvl : np.array
... | [
"def",
"derivativeZ",
"(",
"self",
",",
"mLvl",
",",
"pLvl",
",",
"MedShk",
")",
":",
"xLvl",
"=",
"self",
".",
"xFunc",
"(",
"mLvl",
",",
"pLvl",
",",
"MedShk",
")",
"dxdShk",
"=",
"self",
".",
"xFunc",
".",
"derivativeZ",
"(",
"mLvl",
",",
"pLvl"... | 37.333333 | 20.2 |
def append(self, payload):
""" Function __iadd__
@param payload: The payload corresponding to the object to add
@return RETURN: A ForemanItem
"""
if self.objType.setInParentPayload:
print('Error, {} is not elibible to addition, but only set'
.format... | [
"def",
"append",
"(",
"self",
",",
"payload",
")",
":",
"if",
"self",
".",
"objType",
".",
"setInParentPayload",
":",
"print",
"(",
"'Error, {} is not elibible to addition, but only set'",
".",
"format",
"(",
"self",
".",
"objName",
")",
")",
"return",
"False",
... | 41.666667 | 17 |
def insert(self, song):
"""在当前歌曲后插入一首歌曲"""
if song in self._songs:
return
if self._current_song is None:
self._songs.append(song)
else:
index = self._songs.index(self._current_song)
self._songs.insert(index + 1, song) | [
"def",
"insert",
"(",
"self",
",",
"song",
")",
":",
"if",
"song",
"in",
"self",
".",
"_songs",
":",
"return",
"if",
"self",
".",
"_current_song",
"is",
"None",
":",
"self",
".",
"_songs",
".",
"append",
"(",
"song",
")",
"else",
":",
"index",
"=",... | 32.111111 | 11.666667 |
def xavier_init(fan_in, fan_out, constant=1):
""" Xavier initialization of network weights"""
# https://stackoverflow.com/questions/33640581/how-to-do-xavier-initialization-on-tensorflow
low = -constant*np.sqrt(6.0/(fan_in + fan_out))
high = constant*np.sqrt(6.0/(fan_in + fan_out))
return tf.rando... | [
"def",
"xavier_init",
"(",
"fan_in",
",",
"fan_out",
",",
"constant",
"=",
"1",
")",
":",
"# https://stackoverflow.com/questions/33640581/how-to-do-xavier-initialization-on-tensorflow",
"low",
"=",
"-",
"constant",
"*",
"np",
".",
"sqrt",
"(",
"6.0",
"/",
"(",
"fan_... | 55.5 | 14.125 |
def validate(self):
"""Validate the configuration file."""
validator = Draft4Validator(self.SCHEMA)
if not validator.is_valid(self.config):
for err in validator.iter_errors(self.config):
LOGGER.error(str(err.message))
validator.validate(self.config) | [
"def",
"validate",
"(",
"self",
")",
":",
"validator",
"=",
"Draft4Validator",
"(",
"self",
".",
"SCHEMA",
")",
"if",
"not",
"validator",
".",
"is_valid",
"(",
"self",
".",
"config",
")",
":",
"for",
"err",
"in",
"validator",
".",
"iter_errors",
"(",
"... | 43.857143 | 9 |
def user_with_student_id(self, student_id):
"""Get a unique user object by FCPS student ID. (Ex. 1624472)"""
results = User.objects.filter(student_id=student_id)
if len(results) == 1:
return results.first()
return None | [
"def",
"user_with_student_id",
"(",
"self",
",",
"student_id",
")",
":",
"results",
"=",
"User",
".",
"objects",
".",
"filter",
"(",
"student_id",
"=",
"student_id",
")",
"if",
"len",
"(",
"results",
")",
"==",
"1",
":",
"return",
"results",
".",
"first"... | 42.833333 | 10.166667 |
def _validate_signature(minion_id, signature, impersonated_by_master):
'''
Validate that either minion with id minion_id, or the master, signed the
request
'''
pki_dir = __opts__['pki_dir']
if impersonated_by_master:
public_key = '{0}/master.pub'.format(pki_dir)
else:
public_... | [
"def",
"_validate_signature",
"(",
"minion_id",
",",
"signature",
",",
"impersonated_by_master",
")",
":",
"pki_dir",
"=",
"__opts__",
"[",
"'pki_dir'",
"]",
"if",
"impersonated_by_master",
":",
"public_key",
"=",
"'{0}/master.pub'",
".",
"format",
"(",
"pki_dir",
... | 38.722222 | 23.277778 |
def __parse_drac(output):
'''
Parse Dell DRAC output
'''
drac = {}
section = ''
for i in output.splitlines():
if i.strip().endswith(':') and '=' not in i:
section = i[0:-1]
drac[section] = {}
if i.rstrip() and '=' in i:
if section in drac:
... | [
"def",
"__parse_drac",
"(",
"output",
")",
":",
"drac",
"=",
"{",
"}",
"section",
"=",
"''",
"for",
"i",
"in",
"output",
".",
"splitlines",
"(",
")",
":",
"if",
"i",
".",
"strip",
"(",
")",
".",
"endswith",
"(",
"':'",
")",
"and",
"'='",
"not",
... | 26.409091 | 17.772727 |
def deriv(self, n=1):
""" Compute *n*-th derivative of ``self``.
:param n: Number of derivatives.
:type n: positive integer
:returns: *n*-th derivative of ``self``.
"""
if n==1:
if self.order > 0:
return PowerSeries(self.c[1:]*range(1,len(self... | [
"def",
"deriv",
"(",
"self",
",",
"n",
"=",
"1",
")",
":",
"if",
"n",
"==",
"1",
":",
"if",
"self",
".",
"order",
">",
"0",
":",
"return",
"PowerSeries",
"(",
"self",
".",
"c",
"[",
"1",
":",
"]",
"*",
"range",
"(",
"1",
",",
"len",
"(",
... | 30.3125 | 14.625 |
def save_resource(plugin_name, resource_name, resource_data):
"""
Save a resource in local cache
:param plugin_name: Name of plugin this resource belongs to
:type plugin_name: str
:param resource_name: Name of resource
:type resource_name: str
:param resource_data: Resource content - base64... | [
"def",
"save_resource",
"(",
"plugin_name",
",",
"resource_name",
",",
"resource_data",
")",
":",
"path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"resource_dir_path",
",",
"plugin_name",
")",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"path",
... | 34.105263 | 12.315789 |
def isa(self, ns1, id1, ns2, id2):
"""Return True if one entity has an "isa" relationship to another.
Parameters
----------
ns1 : str
Namespace code for an entity.
id1 : string
URI for an entity.
ns2 : str
Namespace code for an entity.... | [
"def",
"isa",
"(",
"self",
",",
"ns1",
",",
"id1",
",",
"ns2",
",",
"id2",
")",
":",
"rel_fun",
"=",
"lambda",
"node",
",",
"graph",
":",
"self",
".",
"isa_objects",
"(",
"node",
")",
"return",
"self",
".",
"directly_or_indirectly_related",
"(",
"ns1",... | 33.583333 | 19.791667 |
def configure_hit(self, hit_config):
''' Configure HIT '''
# Qualification:
quals = []
quals.append(dict(
QualificationTypeId=PERCENT_ASSIGNMENTS_APPROVED_QUAL_ID,
Comparator='GreaterThanOrEqualTo',
IntegerValues=[int(hit_config['approve_requirement']... | [
"def",
"configure_hit",
"(",
"self",
",",
"hit_config",
")",
":",
"# Qualification:",
"quals",
"=",
"[",
"]",
"quals",
".",
"append",
"(",
"dict",
"(",
"QualificationTypeId",
"=",
"PERCENT_ASSIGNMENTS_APPROVED_QUAL_ID",
",",
"Comparator",
"=",
"'GreaterThanOrEqualTo... | 35.184783 | 19.945652 |
def update_from(self, mapping):
"""
Updates the set of parameters from a mapping for keys that already exist
"""
for key, value in mapping.items():
if key in self:
if isinstance(value, Parameter):
value = value.value
self[ke... | [
"def",
"update_from",
"(",
"self",
",",
"mapping",
")",
":",
"for",
"key",
",",
"value",
"in",
"mapping",
".",
"items",
"(",
")",
":",
"if",
"key",
"in",
"self",
":",
"if",
"isinstance",
"(",
"value",
",",
"Parameter",
")",
":",
"value",
"=",
"valu... | 36.444444 | 8.222222 |
def fix_reference_name(name, blacklist=None):
"""Return a syntax-valid Python reference name from an arbitrary name"""
name = "".join(re.split(r'[^0-9a-zA-Z_]', name))
while name and not re.match(r'([a-zA-Z]+[0-9a-zA-Z_]*)$', name):
if not re.match(r'[a-zA-Z]', name[0]):
name = name[1:]
... | [
"def",
"fix_reference_name",
"(",
"name",
",",
"blacklist",
"=",
"None",
")",
":",
"name",
"=",
"\"\"",
".",
"join",
"(",
"re",
".",
"split",
"(",
"r'[^0-9a-zA-Z_]'",
",",
"name",
")",
")",
"while",
"name",
"and",
"not",
"re",
".",
"match",
"(",
"r'(... | 37.352941 | 15 |
def reset(self):
"""Remove all annotations from window."""
self.idx_annotations.setText('Load Annotation File...')
self.idx_rater.setText('')
self.annot = None
self.dataset_markers = None
# remove dataset marker
self.idx_marker.clearContents()
self.idx_m... | [
"def",
"reset",
"(",
"self",
")",
":",
"self",
".",
"idx_annotations",
".",
"setText",
"(",
"'Load Annotation File...'",
")",
"self",
".",
"idx_rater",
".",
"setText",
"(",
"''",
")",
"self",
".",
"annot",
"=",
"None",
"self",
".",
"dataset_markers",
"=",
... | 29.965517 | 13.172414 |
async def async_run(self) -> None:
"""
Asynchronously run the worker, does not close connections. Useful when testing.
"""
self.main_task = self.loop.create_task(self.main())
await self.main_task | [
"async",
"def",
"async_run",
"(",
"self",
")",
"->",
"None",
":",
"self",
".",
"main_task",
"=",
"self",
".",
"loop",
".",
"create_task",
"(",
"self",
".",
"main",
"(",
")",
")",
"await",
"self",
".",
"main_task"
] | 38.333333 | 14 |
def time(value):
"""
Returns a time literal if value is likely coercible to a time
Parameters
----------
value : time value as string
Returns
--------
result : TimeScalar
"""
if isinstance(value, str):
value = to_time(value)
return literal(value, type=dt.time) | [
"def",
"time",
"(",
"value",
")",
":",
"if",
"isinstance",
"(",
"value",
",",
"str",
")",
":",
"value",
"=",
"to_time",
"(",
"value",
")",
"return",
"literal",
"(",
"value",
",",
"type",
"=",
"dt",
".",
"time",
")"
] | 20 | 18.933333 |
def generate(self, x, **kwargs):
"""
Returns the graph for Fast Gradient Method adversarial examples.
:param x: The model's symbolic inputs.
:param kwargs: See `parse_params`
"""
# Parse and save attack-specific parameters
assert self.parse_params(**kwargs)
labels, _nb_classes = self.g... | [
"def",
"generate",
"(",
"self",
",",
"x",
",",
"*",
"*",
"kwargs",
")",
":",
"# Parse and save attack-specific parameters",
"assert",
"self",
".",
"parse_params",
"(",
"*",
"*",
"kwargs",
")",
"labels",
",",
"_nb_classes",
"=",
"self",
".",
"get_or_guess_label... | 27.454545 | 15.363636 |
def egress_subnets(rid=None, unit=None):
"""
Retrieve the egress-subnets from a relation.
This function is to be used on the providing side of the
relation, and provides the ranges of addresses that client
connections may come from. The result is uninteresting on
the consuming side of a relatio... | [
"def",
"egress_subnets",
"(",
"rid",
"=",
"None",
",",
"unit",
"=",
"None",
")",
":",
"def",
"_to_range",
"(",
"addr",
")",
":",
"if",
"re",
".",
"search",
"(",
"r'^(?:\\d{1,3}\\.){3}\\d{1,3}$'",
",",
"addr",
")",
"is",
"not",
"None",
":",
"addr",
"+="... | 38.057143 | 18.228571 |
def merged(cls, *flatterms: 'FlatTerm') -> 'FlatTerm':
"""Concatenate the given flatterms to a single flatterm.
Args:
*flatterms:
The flatterms which are concatenated.
Returns:
The concatenated flatterms.
"""
return cls(cls._combined_wild... | [
"def",
"merged",
"(",
"cls",
",",
"*",
"flatterms",
":",
"'FlatTerm'",
")",
"->",
"'FlatTerm'",
":",
"return",
"cls",
"(",
"cls",
".",
"_combined_wildcards_iter",
"(",
"sum",
"(",
"flatterms",
",",
"cls",
".",
"empty",
"(",
")",
")",
")",
")"
] | 31.818182 | 19.363636 |
def untar_file(tarname, target_dir='.'):
'''Uncompress a tar file.'''
o = tarfile.open(tarname, 'r:gz')
members = o.getmembers()
for member in members:
o.extract(member, target_dir)
o.close() | [
"def",
"untar_file",
"(",
"tarname",
",",
"target_dir",
"=",
"'.'",
")",
":",
"o",
"=",
"tarfile",
".",
"open",
"(",
"tarname",
",",
"'r:gz'",
")",
"members",
"=",
"o",
".",
"getmembers",
"(",
")",
"for",
"member",
"in",
"members",
":",
"o",
".",
"... | 26.625 | 13.375 |
def _load_entries(self):
"""Check for availability of lemmatizer for French."""
rel_path = os.path.join('~','cltk_data',
'french',
'text','french_data_cltk'
,'entries.py')
path = os.path.expanduser(r... | [
"def",
"_load_entries",
"(",
"self",
")",
":",
"rel_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"'~'",
",",
"'cltk_data'",
",",
"'french'",
",",
"'text'",
",",
"'french_data_cltk'",
",",
"'entries.py'",
")",
"path",
"=",
"os",
".",
"path",
".",
"e... | 42 | 13.384615 |
def setBreak(self,breakFlag = True):
"""Method to invoke the Python pdb debugger when this element is
about to be parsed. Set breakFlag to True to enable, False to
disable.
"""
if breakFlag:
_parseMethod = self._parse
def breaker(instring, loc, doAct... | [
"def",
"setBreak",
"(",
"self",
",",
"breakFlag",
"=",
"True",
")",
":",
"if",
"breakFlag",
":",
"_parseMethod",
"=",
"self",
".",
"_parse",
"def",
"breaker",
"(",
"instring",
",",
"loc",
",",
"doActions",
"=",
"True",
",",
"callPreParse",
"=",
"True",
... | 41.823529 | 16.235294 |
def assign_ranks_to_grid(grid, ranks):
"""
Takes a 2D array of binary numbers represented as strings and a dictionary
mapping binary strings to integers representing the rank of the cluster
they belong to, and returns a grid in which each binary number has been
replaced with the rank of its cluster.... | [
"def",
"assign_ranks_to_grid",
"(",
"grid",
",",
"ranks",
")",
":",
"assignments",
"=",
"deepcopy",
"(",
"grid",
")",
"ranks",
"[",
"\"0b0\"",
"]",
"=",
"0",
"ranks",
"[",
"\"-0b1\"",
"]",
"=",
"-",
"1",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
... | 35.3 | 16.8 |
def find(self, sought, view='lemma'):
'''
Returns a word instance for the hit if the "sought" word is found in the text.
Per default the "lemma" view of the words is compared.
You can specify the desired view with the optional "view" option.
'''
hits = []
for sent... | [
"def",
"find",
"(",
"self",
",",
"sought",
",",
"view",
"=",
"'lemma'",
")",
":",
"hits",
"=",
"[",
"]",
"for",
"sentence",
"in",
"self",
".",
"_sentences",
":",
"hits",
"+=",
"sentence",
".",
"find",
"(",
"sought",
",",
"view",
")",
"return",
"hit... | 40.3 | 21.3 |
def list_files(tag='north', sat_id=None, data_path=None, format_str=None):
"""Return a Pandas Series of every file for chosen satellite data
Parameters
-----------
tag : (string)
Denotes type of file to load. Accepted types are 'north' and 'south'.
(default='north')
sat_id : (strin... | [
"def",
"list_files",
"(",
"tag",
"=",
"'north'",
",",
"sat_id",
"=",
"None",
",",
"data_path",
"=",
"None",
",",
"format_str",
"=",
"None",
")",
":",
"if",
"format_str",
"is",
"None",
"and",
"tag",
"is",
"not",
"None",
":",
"if",
"tag",
"==",
"'north... | 41.5 | 22.5 |
def negative_label_inference(self, label):
'''Return a generator of inferred negative label relationships.
Construct ad-hoc negative labels between ``label.content_id1``
and the positive connected component of ``label.content_id2``,
and ``label.content_id2`` to the connected component o... | [
"def",
"negative_label_inference",
"(",
"self",
",",
"label",
")",
":",
"assert",
"label",
".",
"value",
"==",
"CorefValue",
".",
"Negative",
"yield",
"label",
"cid2_comp",
"=",
"self",
".",
"connected_component",
"(",
"label",
".",
"content_id2",
")",
"for",
... | 42.242424 | 19.333333 |
def stringify_query(query):
"""Stringifies the query (dict or QueryBuilder) into a ServiceNow-compatible format
:return:
- ServiceNow-compatible string-type query
"""
if isinstance(query, QueryBuilder):
# Get string-representation of the passed :class:`pysnow.Qu... | [
"def",
"stringify_query",
"(",
"query",
")",
":",
"if",
"isinstance",
"(",
"query",
",",
"QueryBuilder",
")",
":",
"# Get string-representation of the passed :class:`pysnow.QueryBuilder` object",
"return",
"str",
"(",
"query",
")",
"elif",
"isinstance",
"(",
"query",
... | 40.166667 | 19.611111 |
def hscan(self, name, key_start, key_end, limit=10):
"""
Return a dict mapping key/value in the top ``limit`` keys between
``key_start`` and ``key_end`` within hash ``name`` in ascending order
Similiar with **Redis.HSCAN**
.. note:: The range is (``key_start``, ``key_end``]. Th... | [
"def",
"hscan",
"(",
"self",
",",
"name",
",",
"key_start",
",",
"key_end",
",",
"limit",
"=",
"10",
")",
":",
"limit",
"=",
"get_positive_integer",
"(",
"'limit'",
",",
"limit",
")",
"return",
"self",
".",
"execute_command",
"(",
"'hscan'",
",",
"name",... | 44.433333 | 20.5 |
def implementation(self, for_type=None, for_types=None):
"""Return a decorator that will register the implementation.
Example:
@multimethod
def add(x, y):
pass
@add.implementation(for_type=int)
def add(x, y):
return x + y
... | [
"def",
"implementation",
"(",
"self",
",",
"for_type",
"=",
"None",
",",
"for_types",
"=",
"None",
")",
":",
"for_types",
"=",
"self",
".",
"__get_types",
"(",
"for_type",
",",
"for_types",
")",
"def",
"_decorator",
"(",
"implementation",
")",
":",
"self",... | 27.869565 | 18.26087 |
def bucket_and_path(self, url):
"""Split an S3-prefixed URL into bucket and path."""
url = compat.as_str_any(url)
if url.startswith("s3://"):
url = url[len("s3://"):]
idx = url.index("/")
bucket = url[:idx]
path = url[(idx + 1):]
return bucket, path | [
"def",
"bucket_and_path",
"(",
"self",
",",
"url",
")",
":",
"url",
"=",
"compat",
".",
"as_str_any",
"(",
"url",
")",
"if",
"url",
".",
"startswith",
"(",
"\"s3://\"",
")",
":",
"url",
"=",
"url",
"[",
"len",
"(",
"\"s3://\"",
")",
":",
"]",
"idx"... | 34.333333 | 7.888889 |
def role(args):
"""
%prog role htang
Change aws role.
"""
src_acct, src_username, dst_acct, dst_role = \
"205134639408 htang 114692162163 mvrad-datasci-role".split()
p = OptionParser(role.__doc__)
p.add_option("--profile", default="mvrad-datasci-role", help="Profile name")
p.ad... | [
"def",
"role",
"(",
"args",
")",
":",
"src_acct",
",",
"src_username",
",",
"dst_acct",
",",
"dst_role",
"=",
"\"205134639408 htang 114692162163 mvrad-datasci-role\"",
".",
"split",
"(",
")",
"p",
"=",
"OptionParser",
"(",
"role",
".",
"__doc__",
")",
"p",
"."... | 47.425532 | 22.148936 |
def generate_sb(date: datetime.datetime, project: str,
programme_block: str) -> dict:
"""Generate a Scheduling Block data object.
Args:
date (datetime.datetime): UTC date of the SBI
project (str): Project Name
programme_block (str): Programme
Returns:
str, S... | [
"def",
"generate_sb",
"(",
"date",
":",
"datetime",
".",
"datetime",
",",
"project",
":",
"str",
",",
"programme_block",
":",
"str",
")",
"->",
"dict",
":",
"date",
"=",
"date",
".",
"strftime",
"(",
"'%Y%m%d'",
")",
"instance_id",
"=",
"randint",
"(",
... | 32.823529 | 17.411765 |
def offset_overlays(self, text, offset=0, run_deps=True, **kw):
"""
The heavy lifting is done by fit_overlays. Override just that for
alternatie implementation.
"""
if run_deps and self.dependencies:
text.overlay(self.dependencies)
for ovlf in self.matchers[... | [
"def",
"offset_overlays",
"(",
"self",
",",
"text",
",",
"offset",
"=",
"0",
",",
"run_deps",
"=",
"True",
",",
"*",
"*",
"kw",
")",
":",
"if",
"run_deps",
"and",
"self",
".",
"dependencies",
":",
"text",
".",
"overlay",
"(",
"self",
".",
"dependenci... | 43 | 18.333333 |
def folder_path(preferred_mode, check_other_mode, key):
''' This function implements all heuristics and workarounds for messed up
KNOWNFOLDERID registry values. It's also verbose (OutputDebugStringW)
about whether fallbacks worked or whether they would have worked if
check_other_mode had bee... | [
"def",
"folder_path",
"(",
"preferred_mode",
",",
"check_other_mode",
",",
"key",
")",
":",
"other_mode",
"=",
"'system'",
"if",
"preferred_mode",
"==",
"'user'",
"else",
"'user'",
"path",
",",
"exception",
"=",
"dirs_src",
"[",
"preferred_mode",
"]",
"[",
"ke... | 54.119048 | 25.642857 |
def create_instructor_answer(self, post, content, revision, anonymous=False):
"""Create an instructor's answer to a post `post`.
It seems like if the post has `<p>` tags, then it's treated as HTML,
but is treated as text otherwise. You'll want to provide `content`
accordingly.
... | [
"def",
"create_instructor_answer",
"(",
"self",
",",
"post",
",",
"content",
",",
"revision",
",",
"anonymous",
"=",
"False",
")",
":",
"try",
":",
"cid",
"=",
"post",
"[",
"\"id\"",
"]",
"except",
"KeyError",
":",
"cid",
"=",
"post",
"params",
"=",
"{... | 37.666667 | 20.484848 |
def rest_get_stream(self, url, auth=None, verify=True, cert=None):
"""
Perform a chunked GET request to url with optional authentication
This is specifically to download files.
"""
res = requests.get(url, auth=auth, stream=True, verify=verify, cert=cert)
return res.raw, r... | [
"def",
"rest_get_stream",
"(",
"self",
",",
"url",
",",
"auth",
"=",
"None",
",",
"verify",
"=",
"True",
",",
"cert",
"=",
"None",
")",
":",
"res",
"=",
"requests",
".",
"get",
"(",
"url",
",",
"auth",
"=",
"auth",
",",
"stream",
"=",
"True",
","... | 46.857143 | 15.428571 |
def _wait(self, generator, method, timeout=None, *args, **kwargs):
"""Wait until generator is paused before running 'method'."""
if self.debug:
print("waiting for %s to pause" % generator)
original_timeout = timeout
while timeout is None or timeout > 0:
last_time... | [
"def",
"_wait",
"(",
"self",
",",
"generator",
",",
"method",
",",
"timeout",
"=",
"None",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"self",
".",
"debug",
":",
"print",
"(",
"\"waiting for %s to pause\"",
"%",
"generator",
")",
"origin... | 40 | 18.041667 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.