text stringlengths 75 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 0.18 |
|---|---|---|---|
def main():
"""Execute entry function."""
args = parser.parse_args()
args_dict = vars(args)
root_dir = args_dict['root'] if 'root' in args else None
# If a root directory is specified, get the absolute path and
# check if it exists. Abort if it doesn't exist!
if root_dir:
root_dir =... | [
"def",
"main",
"(",
")",
":",
"args",
"=",
"parser",
".",
"parse_args",
"(",
")",
"args_dict",
"=",
"vars",
"(",
"args",
")",
"root_dir",
"=",
"args_dict",
"[",
"'root'",
"]",
"if",
"'root'",
"in",
"args",
"else",
"None",
"# If a root directory is specifie... | 36.882353 | 0.001554 |
def get_metainfo(scriptfile,
keywords=['author', 'contact', 'copyright', 'download', 'git', 'subversion', 'version', 'website'],
special={},
first_line_pattern=r'^(?P<progname>.+)(\s+v(?P<version>\S+))?',
keyword_pattern_template=r'^\s*%(pretty)s:\s*(?... | [
"def",
"get_metainfo",
"(",
"scriptfile",
",",
"keywords",
"=",
"[",
"'author'",
",",
"'contact'",
",",
"'copyright'",
",",
"'download'",
",",
"'git'",
",",
"'subversion'",
",",
"'version'",
",",
"'website'",
"]",
",",
"special",
"=",
"{",
"}",
",",
"first... | 40 | 0.009062 |
def get_band(cls, b, **kwargs):
"""Defines what a "shortcut" band name refers to. Returns phot_system, band
"""
phot = None
# Default to SDSS for these
if b in ['u','g','r','i','z']:
phot = 'SDSS'
band = 'SDSS_{}'.format(b)
elif b in ['U','B','V... | [
"def",
"get_band",
"(",
"cls",
",",
"b",
",",
"*",
"*",
"kwargs",
")",
":",
"phot",
"=",
"None",
"# Default to SDSS for these",
"if",
"b",
"in",
"[",
"'u'",
",",
"'g'",
",",
"'r'",
",",
"'i'",
",",
"'z'",
"]",
":",
"phot",
"=",
"'SDSS'",
"band",
... | 33.589286 | 0.01343 |
def flaskrun(app, default_host="127.0.0.1", default_port="8000"):
"""
Takes a flask.Flask instance and runs it. Parses
command-line flags to configure the app.
"""
# Set up the command-line options
parser = optparse.OptionParser()
parser.add_option(
"-H",
"--host",
h... | [
"def",
"flaskrun",
"(",
"app",
",",
"default_host",
"=",
"\"127.0.0.1\"",
",",
"default_port",
"=",
"\"8000\"",
")",
":",
"# Set up the command-line options",
"parser",
"=",
"optparse",
".",
"OptionParser",
"(",
")",
"parser",
".",
"add_option",
"(",
"\"-H\"",
"... | 29.630435 | 0.00142 |
def make_response(query, recursion_available=False, our_payload=8192):
"""Make a message which is a response for the specified query.
The message returned is really a response skeleton; it has all
of the infrastructure required of a response, but none of the
content.
The response's question section... | [
"def",
"make_response",
"(",
"query",
",",
"recursion_available",
"=",
"False",
",",
"our_payload",
"=",
"8192",
")",
":",
"if",
"query",
".",
"flags",
"&",
"dns",
".",
"flags",
".",
"QR",
":",
"raise",
"dns",
".",
"exception",
".",
"FormError",
"(",
"... | 40.794118 | 0.001408 |
def get(self, session, fields=None):
'''taobao.fenxiao.productcats.get 查询产品线列表
查询供应商的所有产品线数据。根据登陆用户来查询,不需要其他入参'''
request = TOPRequest('taobao.fenxiao.productcats.get')
if fields: request['fields'] = fields
self.create(self.execute(request, session))
return self.... | [
"def",
"get",
"(",
"self",
",",
"session",
",",
"fields",
"=",
"None",
")",
":",
"request",
"=",
"TOPRequest",
"(",
"'taobao.fenxiao.productcats.get'",
")",
"if",
"fields",
":",
"request",
"[",
"'fields'",
"]",
"=",
"fields",
"self",
".",
"create",
"(",
... | 40.5 | 0.012085 |
def primer(dna, tm=65, min_len=10, tm_undershoot=1, tm_overshoot=3,
end_gc=False, tm_parameters='cloning', overhang=None,
structure=False):
'''Design primer to a nearest-neighbor Tm setpoint.
:param dna: Sequence for which to design a primer.
:type dna: coral.DNA
:param tm: Ideal ... | [
"def",
"primer",
"(",
"dna",
",",
"tm",
"=",
"65",
",",
"min_len",
"=",
"10",
",",
"tm_undershoot",
"=",
"1",
",",
"tm_overshoot",
"=",
"3",
",",
"end_gc",
"=",
"False",
",",
"tm_parameters",
"=",
"'cloning'",
",",
"overhang",
"=",
"None",
",",
"stru... | 38.129032 | 0.000275 |
def save_psse(self, fd):
""" Serialize the case as a PSS/E data file.
"""
from pylon.io import PSSEWriter
return PSSEWriter(self).write(fd) | [
"def",
"save_psse",
"(",
"self",
",",
"fd",
")",
":",
"from",
"pylon",
".",
"io",
"import",
"PSSEWriter",
"return",
"PSSEWriter",
"(",
"self",
")",
".",
"write",
"(",
"fd",
")"
] | 33.4 | 0.011696 |
def parseSOAP(xml_str, rules = None):
"""
Replacement for SOAPpy._parseSOAP method to spoof SOAPParser.
"""
try:
from cStringIO import StringIO
except ImportError:
from StringIO import StringIO
parser = xml.sax.make_parser()
t = ZimbraSOAPParser(rules = rules)
parser.set... | [
"def",
"parseSOAP",
"(",
"xml_str",
",",
"rules",
"=",
"None",
")",
":",
"try",
":",
"from",
"cStringIO",
"import",
"StringIO",
"except",
"ImportError",
":",
"from",
"StringIO",
"import",
"StringIO",
"parser",
"=",
"xml",
".",
"sax",
".",
"make_parser",
"(... | 25.142857 | 0.008208 |
def ijk_jlk_to_il(A, B):
"""
Faster version of einsum einsum('ijk,jlk->il', A,B)
"""
res = np.zeros((A.shape[0], B.shape[1]))
[np.add(np.dot(A[:,:,k], B[:,:,k]), res, out=res) for k in range(B.shape[-1])]
return res | [
"def",
"ijk_jlk_to_il",
"(",
"A",
",",
"B",
")",
":",
"res",
"=",
"np",
".",
"zeros",
"(",
"(",
"A",
".",
"shape",
"[",
"0",
"]",
",",
"B",
".",
"shape",
"[",
"1",
"]",
")",
")",
"[",
"np",
".",
"add",
"(",
"np",
".",
"dot",
"(",
"A",
"... | 33.285714 | 0.025105 |
def parsecmap(self, fn):
'''Returns a parser that transforms the produced value of parser with `fn`.'''
return self.bind(lambda res: Parser(lambda _, index: Value.success(index, fn(res)))) | [
"def",
"parsecmap",
"(",
"self",
",",
"fn",
")",
":",
"return",
"self",
".",
"bind",
"(",
"lambda",
"res",
":",
"Parser",
"(",
"lambda",
"_",
",",
"index",
":",
"Value",
".",
"success",
"(",
"index",
",",
"fn",
"(",
"res",
")",
")",
")",
")"
] | 67.333333 | 0.019608 |
def search_packages_info(query):
"""
Gather details from installed distributions. Print distribution name,
version, location, and installed files. Installed files requires a
pip generated 'installed-files.txt' in the distributions '.egg-info'
directory.
"""
installed = {}
for p in pkg_re... | [
"def",
"search_packages_info",
"(",
"query",
")",
":",
"installed",
"=",
"{",
"}",
"for",
"p",
"in",
"pkg_resources",
".",
"working_set",
":",
"installed",
"[",
"canonicalize_name",
"(",
"p",
".",
"project_name",
")",
"]",
"=",
"p",
"query_names",
"=",
"["... | 42.605263 | 0.001208 |
def _log(self, level, msg, args, kwargs):
"""Throttled log output."""
with self._tb_lock:
if self._tb is None:
throttled = 0
should_log = True
else:
throttled = self._tb.throttle_count
should_log = self._tb.check_an... | [
"def",
"_log",
"(",
"self",
",",
"level",
",",
"msg",
",",
"args",
",",
"kwargs",
")",
":",
"with",
"self",
".",
"_tb_lock",
":",
"if",
"self",
".",
"_tb",
"is",
"None",
":",
"throttled",
"=",
"0",
"should_log",
"=",
"True",
"else",
":",
"throttled... | 32.612903 | 0.001921 |
def available_tcp_port(reactor):
"""
Returns a Deferred firing an available TCP port on localhost.
It does so by listening on port 0; then stopListening and fires the
assigned port number.
"""
endpoint = serverFromString(reactor, 'tcp:0:interface=127.0.0.1')
port = yield endpoint.listen(NoO... | [
"def",
"available_tcp_port",
"(",
"reactor",
")",
":",
"endpoint",
"=",
"serverFromString",
"(",
"reactor",
",",
"'tcp:0:interface=127.0.0.1'",
")",
"port",
"=",
"yield",
"endpoint",
".",
"listen",
"(",
"NoOpProtocolFactory",
"(",
")",
")",
"address",
"=",
"port... | 35.333333 | 0.002299 |
def validate_version():
"""Validate version before release."""
import leicacam
version_string = leicacam.__version__
versions = version_string.split('.', 3)
try:
for ver in versions:
int(ver)
except ValueError:
print(
'Only integers are allowed in release ... | [
"def",
"validate_version",
"(",
")",
":",
"import",
"leicacam",
"version_string",
"=",
"leicacam",
".",
"__version__",
"versions",
"=",
"version_string",
".",
"split",
"(",
"'.'",
",",
"3",
")",
"try",
":",
"for",
"ver",
"in",
"versions",
":",
"int",
"(",
... | 31 | 0.002237 |
def get_search_form(self):
"""
Returns search form instance.
:rtype: django.forms.ModelForm.
"""
#noinspection PyUnresolvedReferences
if 'q' in self.request.GET:
#noinspection PyUnresolvedReferences
return self.search_form_class(self.request.GET)
... | [
"def",
"get_search_form",
"(",
"self",
")",
":",
"#noinspection PyUnresolvedReferences",
"if",
"'q'",
"in",
"self",
".",
"request",
".",
"GET",
":",
"#noinspection PyUnresolvedReferences",
"return",
"self",
".",
"search_form_class",
"(",
"self",
".",
"request",
".",... | 32.5 | 0.009975 |
def get_covariance(datargs, outargs, vargs, datvar, outvar):
"""
Get covariance matrix.
:param datargs: data arguments
:param outargs: output arguments
:param vargs: variable arguments
:param datvar: variance of data arguments
:param outvar: variance of output ar... | [
"def",
"get_covariance",
"(",
"datargs",
",",
"outargs",
",",
"vargs",
",",
"datvar",
",",
"outvar",
")",
":",
"# number of formula arguments that are not constant",
"argn",
"=",
"len",
"(",
"vargs",
")",
"# number of observations must be the same for all vargs",
"nobs",
... | 34.086207 | 0.000983 |
def Plot_Impact_3DPoly(T, Leg="", ax=None, Ang=_def.TorPAng,
AngUnit=_def.TorPAngUnit, Pdict=_def.TorP3DFilld,
dLeg=_def.TorLegd,
draw=True, fs=None, wintit=_wintit, Test=True):
""" Plotting the toroidal projection of a Ves instance
D. VEZINE... | [
"def",
"Plot_Impact_3DPoly",
"(",
"T",
",",
"Leg",
"=",
"\"\"",
",",
"ax",
"=",
"None",
",",
"Ang",
"=",
"_def",
".",
"TorPAng",
",",
"AngUnit",
"=",
"_def",
".",
"TorPAngUnit",
",",
"Pdict",
"=",
"_def",
".",
"TorP3DFilld",
",",
"dLeg",
"=",
"_def",... | 50.923077 | 0.022525 |
def SetWriteBack(self, filename):
"""Sets the config file which will receive any modifications.
The main config file can be made writable, but directing all Set()
operations into a secondary location. This secondary location will
receive any updates and will override the options for this file.
Arg... | [
"def",
"SetWriteBack",
"(",
"self",
",",
"filename",
")",
":",
"try",
":",
"self",
".",
"writeback",
"=",
"self",
".",
"LoadSecondaryConfig",
"(",
"filename",
")",
"self",
".",
"MergeData",
"(",
"self",
".",
"writeback",
".",
"RawData",
"(",
")",
",",
... | 44.6 | 0.010241 |
def __search_str(self, obj, item, parent):
"""Compare strings"""
obj_text = obj if self.case_sensitive else obj.lower()
if (self.match_string and item == obj_text) or (not self.match_string and item in obj_text):
self.__report(report_key='matched_values', key=parent, value=obj) | [
"def",
"__search_str",
"(",
"self",
",",
"obj",
",",
"item",
",",
"parent",
")",
":",
"obj_text",
"=",
"obj",
"if",
"self",
".",
"case_sensitive",
"else",
"obj",
".",
"lower",
"(",
")",
"if",
"(",
"self",
".",
"match_string",
"and",
"item",
"==",
"ob... | 51.666667 | 0.009524 |
def remove_parents(bases):
""" removes the parent classes if one base is subclass of
another"""
if len(bases) < 2:
return bases
remove_i = []
bases = list(bases)
for i, base in enumerate(bases):
for j, other in enumerate(bases):
# print(i, j, base, other, remove_i... | [
"def",
"remove_parents",
"(",
"bases",
")",
":",
"if",
"len",
"(",
"bases",
")",
"<",
"2",
":",
"return",
"bases",
"remove_i",
"=",
"[",
"]",
"bases",
"=",
"list",
"(",
"bases",
")",
"for",
"i",
",",
"base",
"in",
"enumerate",
"(",
"bases",
")",
... | 31.857143 | 0.001451 |
def encdec_attention_1d(x,
encoder_output,
encoder_decoder_attention_bias,
hparams):
"""Local 1d self attention."""
x, x_shape, is_4d = maybe_reshape_4d_to_3d(x)
encoder_output, _, _ = maybe_reshape_4d_to_3d(encoder_output)
with tf.variable... | [
"def",
"encdec_attention_1d",
"(",
"x",
",",
"encoder_output",
",",
"encoder_decoder_attention_bias",
",",
"hparams",
")",
":",
"x",
",",
"x_shape",
",",
"is_4d",
"=",
"maybe_reshape_4d_to_3d",
"(",
"x",
")",
"encoder_output",
",",
"_",
",",
"_",
"=",
"maybe_r... | 36.565217 | 0.008111 |
def add_list_opt(self, opt, values):
""" Add an option with a list of non-file parameters.
"""
self.add_opt(opt)
for val in values:
self.add_opt(val) | [
"def",
"add_list_opt",
"(",
"self",
",",
"opt",
",",
"values",
")",
":",
"self",
".",
"add_opt",
"(",
"opt",
")",
"for",
"val",
"in",
"values",
":",
"self",
".",
"add_opt",
"(",
"val",
")"
] | 31.333333 | 0.010363 |
def add_tab_with_frontend(self,frontend,name=None):
""" insert a tab with a given frontend in the tab bar, and give it a name
"""
if not name:
name = 'kernel %i' % self.next_kernel_id
self.tab_widget.addTab(frontend,name)
self.update_tab_bar_visibility()
self... | [
"def",
"add_tab_with_frontend",
"(",
"self",
",",
"frontend",
",",
"name",
"=",
"None",
")",
":",
"if",
"not",
"name",
":",
"name",
"=",
"'kernel %i'",
"%",
"self",
".",
"next_kernel_id",
"self",
".",
"tab_widget",
".",
"addTab",
"(",
"frontend",
",",
"n... | 39.9 | 0.014706 |
def model_fn(model_dir):
"""
Load the gluon model. Called once when hosting service starts.
:param: model_dir The directory where model files are stored.
:return: a model (in this case a Gluon network)
"""
symbol = mx.sym.load('%s/model.json' % model_dir)
outputs = mx.symbol.softmax(data=sy... | [
"def",
"model_fn",
"(",
"model_dir",
")",
":",
"symbol",
"=",
"mx",
".",
"sym",
".",
"load",
"(",
"'%s/model.json'",
"%",
"model_dir",
")",
"outputs",
"=",
"mx",
".",
"symbol",
".",
"softmax",
"(",
"data",
"=",
"symbol",
",",
"name",
"=",
"'softmax_lab... | 39.285714 | 0.001776 |
def image(self, name, x=None, y=None, w=0,h=0,type='',link=''):
"Put an image on the page"
if not name in self.images:
#First use of image, get info
if(type==''):
pos=name.rfind('.')
if(not pos):
self.error('image file has no ex... | [
"def",
"image",
"(",
"self",
",",
"name",
",",
"x",
"=",
"None",
",",
"y",
"=",
"None",
",",
"w",
"=",
"0",
",",
"h",
"=",
"0",
",",
"type",
"=",
"''",
",",
"link",
"=",
"''",
")",
":",
"if",
"not",
"name",
"in",
"self",
".",
"images",
":... | 39.430769 | 0.022459 |
def _get_default_annual_spacing(nyears):
"""
Returns a default spacing between consecutive ticks for annual data.
"""
if nyears < 11:
(min_spacing, maj_spacing) = (1, 1)
elif nyears < 20:
(min_spacing, maj_spacing) = (1, 2)
elif nyears < 50:
(min_spacing, maj_spacing) = (... | [
"def",
"_get_default_annual_spacing",
"(",
"nyears",
")",
":",
"if",
"nyears",
"<",
"11",
":",
"(",
"min_spacing",
",",
"maj_spacing",
")",
"=",
"(",
"1",
",",
"1",
")",
"elif",
"nyears",
"<",
"20",
":",
"(",
"min_spacing",
",",
"maj_spacing",
")",
"="... | 33 | 0.001473 |
def add(self, jam, on_conflict='fail'):
"""Add the contents of another jam to this object.
Note that, by default, this method fails if file_metadata is not
identical and raises a ValueError; either resolve this manually
(because conflicts should almost never happen), force an 'overwrite... | [
"def",
"add",
"(",
"self",
",",
"jam",
",",
"on_conflict",
"=",
"'fail'",
")",
":",
"if",
"on_conflict",
"not",
"in",
"[",
"'overwrite'",
",",
"'fail'",
",",
"'ignore'",
"]",
":",
"raise",
"ParameterError",
"(",
"\"on_conflict='{}' is not in ['fail', \"",
"\"'... | 37.205128 | 0.001343 |
def _main():
"""
Command-line program that reads in JSON from stdin and writes out
pretty-printed messages to stdout.
"""
if argv[1:]:
stdout.write(_CLI_HELP)
raise SystemExit()
for line in stdin:
try:
message = loads(line)
except ValueError:
... | [
"def",
"_main",
"(",
")",
":",
"if",
"argv",
"[",
"1",
":",
"]",
":",
"stdout",
".",
"write",
"(",
"_CLI_HELP",
")",
"raise",
"SystemExit",
"(",
")",
"for",
"line",
"in",
"stdin",
":",
"try",
":",
"message",
"=",
"loads",
"(",
"line",
")",
"excep... | 31.363636 | 0.001406 |
def form_to_params(fn=None, return_json=True):
"""
Convert bottle forms request to parameters for the wrapped function.
Args:
return_json (bool, default True): Should the decorator automatically
convert returned value to JSON?
"""
def forms_to_params_decorator(fn):
... | [
"def",
"form_to_params",
"(",
"fn",
"=",
"None",
",",
"return_json",
"=",
"True",
")",
":",
"def",
"forms_to_params_decorator",
"(",
"fn",
")",
":",
"@",
"handle_type_error",
"@",
"wraps",
"(",
"fn",
")",
"def",
"forms_to_params_wrapper",
"(",
"*",
"args",
... | 28.103448 | 0.001186 |
def _kmp_construct_next(self, pattern):
"""the helper function for KMP-string-searching is to construct the DFA. pattern should be an integer array. return a 2D array representing the DFA for moving the pattern."""
next = [[0 for state in pattern] for input_token in self.ALPHABETA_KMP]
... | [
"def",
"_kmp_construct_next",
"(",
"self",
",",
"pattern",
")",
":",
"next",
"=",
"[",
"[",
"0",
"for",
"state",
"in",
"pattern",
"]",
"for",
"input_token",
"in",
"self",
".",
"ALPHABETA_KMP",
"]",
"next",
"[",
"pattern",
"[",
"0",
"]",
"]",
"[",
"0"... | 68.909091 | 0.009115 |
def incpos(self, length: int=1) -> int:
"""Increment the cursor to the next character."""
if length < 0:
raise ValueError("length must be positive")
i = 0
while (i < length):
if self._cursor.index < self._len:
if self.peek_char == '\n':
... | [
"def",
"incpos",
"(",
"self",
",",
"length",
":",
"int",
"=",
"1",
")",
"->",
"int",
":",
"if",
"length",
"<",
"0",
":",
"raise",
"ValueError",
"(",
"\"length must be positive\"",
")",
"i",
"=",
"0",
"while",
"(",
"i",
"<",
"length",
")",
":",
"if"... | 37.166667 | 0.008753 |
def dispatch_request(self):
""" Handle redirect back from provider """
if current_user.is_authenticated:
return redirect(self.next)
# clear previous!
if 'social_data' in session:
del session['social_data']
res = self.app.authorized_response()
if ... | [
"def",
"dispatch_request",
"(",
"self",
")",
":",
"if",
"current_user",
".",
"is_authenticated",
":",
"return",
"redirect",
"(",
"self",
".",
"next",
")",
"# clear previous!",
"if",
"'social_data'",
"in",
"session",
":",
"del",
"session",
"[",
"'social_data'",
... | 35.380282 | 0.001936 |
def create_weekmatrices(user, split_interval=60):
"""
Computes raw indicators (e.g. number of outgoing calls) for intervals of ~1
hour across each week of user data. These "week-matrices" are returned in a
nested list with each sublist containing [user.name, channel, weekday,
section, value].
P... | [
"def",
"create_weekmatrices",
"(",
"user",
",",
"split_interval",
"=",
"60",
")",
":",
"if",
"not",
"float",
"(",
"24",
"*",
"60",
"/",
"split_interval",
")",
".",
"is_integer",
"(",
")",
":",
"raise",
"ValueError",
"(",
"\"The minute interval set for the week... | 41.954545 | 0.002117 |
def translated(self, value, type):
""" translate using the schema type """
if value is not None:
resolved = type.resolve()
return resolved.translate(value)
else:
return value | [
"def",
"translated",
"(",
"self",
",",
"value",
",",
"type",
")",
":",
"if",
"value",
"is",
"not",
"None",
":",
"resolved",
"=",
"type",
".",
"resolve",
"(",
")",
"return",
"resolved",
".",
"translate",
"(",
"value",
")",
"else",
":",
"return",
"valu... | 32.571429 | 0.008547 |
def expected_param_keys(self):
"""returns a list of params that this ConfigTemplate expects to receive"""
expected_keys = []
r = re.compile('%\(([^\)]+)\)s')
for block in self.keys():
for key in self[block].keys():
s = self[block][key]
i... | [
"def",
"expected_param_keys",
"(",
"self",
")",
":",
"expected_keys",
"=",
"[",
"]",
"r",
"=",
"re",
".",
"compile",
"(",
"'%\\(([^\\)]+)\\)s'",
")",
"for",
"block",
"in",
"self",
".",
"keys",
"(",
")",
":",
"for",
"key",
"in",
"self",
"[",
"block",
... | 40.875 | 0.011958 |
def _query(action=None,
command=None,
args=None,
method='GET',
header_dict=None,
data=None):
'''
Make a web call to RallyDev.
'''
token = _get_token()
username = __opts__.get('rallydev', {}).get('username', None)
password = __opts__.get('ral... | [
"def",
"_query",
"(",
"action",
"=",
"None",
",",
"command",
"=",
"None",
",",
"args",
"=",
"None",
",",
"method",
"=",
"'GET'",
",",
"header_dict",
"=",
"None",
",",
"data",
"=",
"None",
")",
":",
"token",
"=",
"_get_token",
"(",
")",
"username",
... | 23.883333 | 0.00067 |
def main():
"""
Upload a vcl file to a fastly service, cloning the current version if
necessary. The uploaded vcl is set as main unless --include is given.
All existing vcl files will be deleted first if --delete is given.
"""
parser = OptionParser(description=
"Upload ... | [
"def",
"main",
"(",
")",
":",
"parser",
"=",
"OptionParser",
"(",
"description",
"=",
"\"Upload a vcl file (set as main) to a given fastly service. All arguments are required.\"",
")",
"parser",
".",
"add_option",
"(",
"\"-k\"",
",",
"\"--key\"",
",",
"dest",
"=",
"\"ap... | 40.884615 | 0.001225 |
def get_message(self):
"""
Gets the latest object from the backend, and handles unpickling
and validation.
"""
try:
m = self.get_from_backend()
if m and m["type"] not in SKIP_TYPES:
return self.decrypt(m["data"])
except AttributeEr... | [
"def",
"get_message",
"(",
"self",
")",
":",
"try",
":",
"m",
"=",
"self",
".",
"get_from_backend",
"(",
")",
"if",
"m",
"and",
"m",
"[",
"\"type\"",
"]",
"not",
"in",
"SKIP_TYPES",
":",
"return",
"self",
".",
"decrypt",
"(",
"m",
"[",
"\"data\"",
... | 35.235294 | 0.00813 |
def validate_geo_array(extent):
"""Validate a geographic extent.
.. versionadded:: 3.2
:param extent: A list in the form [xmin, ymin, xmax, ymax] where all
coordinates provided are in Geographic / EPSG:4326.
:type extent: list
:return: True if the extent is valid, otherwise False
:rty... | [
"def",
"validate_geo_array",
"(",
"extent",
")",
":",
"min_longitude",
"=",
"extent",
"[",
"0",
"]",
"min_latitude",
"=",
"extent",
"[",
"1",
"]",
"max_longitude",
"=",
"extent",
"[",
"2",
"]",
"max_latitude",
"=",
"extent",
"[",
"3",
"]",
"# min_latitude ... | 25.5 | 0.000994 |
def reset_next_ids(classes):
"""
For each class in the list, if the .next_id attribute is not None
(meaning the table has an ID generator associated with it), set
.next_id to 0. This has the effect of reseting the ID generators,
and is useful in applications that process multiple documents and
add new rows to ta... | [
"def",
"reset_next_ids",
"(",
"classes",
")",
":",
"for",
"cls",
"in",
"classes",
":",
"if",
"cls",
".",
"next_id",
"is",
"not",
"None",
":",
"cls",
".",
"set_next_id",
"(",
"type",
"(",
"cls",
".",
"next_id",
")",
"(",
"0",
")",
")"
] | 39.619048 | 0.0223 |
def get_structures(self, primitive=True):
"""
Return list of structures in CIF file. primitive boolean sets whether a
conventional cell structure or primitive cell structure is returned.
Args:
primitive (bool): Set to False to return conventional unit cells.
... | [
"def",
"get_structures",
"(",
"self",
",",
"primitive",
"=",
"True",
")",
":",
"structures",
"=",
"[",
"]",
"for",
"d",
"in",
"self",
".",
"_cif",
".",
"data",
".",
"values",
"(",
")",
":",
"try",
":",
"s",
"=",
"self",
".",
"_get_structure",
"(",
... | 42.0625 | 0.002179 |
def compamp_to_ac(compamp, window=np.hanning): # convert single or multi-subband compamps into autocorrelation waterfall
'''
Adapted from Gerry Harp at SETI.
'''
header = compamp.header()
cdata = compamp.complex_data()
#Apply Windowing and Padding
cdata = np.multiply(cdata, window(cdata.shape[2]))... | [
"def",
"compamp_to_ac",
"(",
"compamp",
",",
"window",
"=",
"np",
".",
"hanning",
")",
":",
"# convert single or multi-subband compamps into autocorrelation waterfall",
"header",
"=",
"compamp",
".",
"header",
"(",
")",
"cdata",
"=",
"compamp",
".",
"complex_data",
... | 42.888889 | 0.025338 |
def save_hdf(self,filename,path=''):
"""Save to .h5 file.
"""
self.orbpop_long.save_hdf(filename,'{}/long'.format(path))
self.orbpop_short.save_hdf(filename,'{}/short'.format(path)) | [
"def",
"save_hdf",
"(",
"self",
",",
"filename",
",",
"path",
"=",
"''",
")",
":",
"self",
".",
"orbpop_long",
".",
"save_hdf",
"(",
"filename",
",",
"'{}/long'",
".",
"format",
"(",
"path",
")",
")",
"self",
".",
"orbpop_short",
".",
"save_hdf",
"(",
... | 41.8 | 0.028169 |
def parse(packages, static=False):
"""
Parse the output from pkg-config about the passed package or packages.
Builds a dictionary containing the 'libraries', the 'library_dirs', the
'include_dirs', and the 'define_macros' that are presented by pkg-config.
*package* is a string with space-delimited ... | [
"def",
"parse",
"(",
"packages",
",",
"static",
"=",
"False",
")",
":",
"for",
"package",
"in",
"packages",
".",
"split",
"(",
")",
":",
"_raise_if_not_exists",
"(",
"package",
")",
"out",
"=",
"_query",
"(",
"packages",
",",
"*",
"_build_options",
"(",
... | 36.147059 | 0.001585 |
def whitelist_method_generator(base, klass, whitelist):
"""
Yields all GroupBy member defs for DataFrame/Series names in whitelist.
Parameters
----------
base : class
base class
klass : class
class where members are defined.
Should be Series or DataFrame
whitelist : ... | [
"def",
"whitelist_method_generator",
"(",
"base",
",",
"klass",
",",
"whitelist",
")",
":",
"method_wrapper_template",
"=",
"\"\"\"def %(name)s(%(sig)s) :\n \\\"\"\"\n %(doc)s\n \\\"\"\"\n f = %(self)s.__getattr__('%(name)s')\n return f(%(args)s)\"\"\"",
"property_wrapper_te... | 32.548387 | 0.000481 |
def classify_tangent_intersection(
intersection, nodes1, tangent1, nodes2, tangent2
):
"""Helper for func:`classify_intersection` at tangencies.
.. note::
This is a helper used only by :func:`classify_intersection`.
Args:
intersection (.Intersection): An intersection object.
no... | [
"def",
"classify_tangent_intersection",
"(",
"intersection",
",",
"nodes1",
",",
"tangent1",
",",
"nodes2",
",",
"tangent2",
")",
":",
"# Each array is 2 x 1 (i.e. a column vector), we want the vector",
"# dot product.",
"dot_prod",
"=",
"np",
".",
"vdot",
"(",
"tangent1"... | 37.380282 | 0.000367 |
def rel_href(src, dst):
"""For src='foo/bar.html', dst='garply.html#frotz' return relative link '../garply.html#frotz'.
"""
src_dir = os.path.dirname(src)
return os.path.relpath(dst, src_dir) | [
"def",
"rel_href",
"(",
"src",
",",
"dst",
")",
":",
"src_dir",
"=",
"os",
".",
"path",
".",
"dirname",
"(",
"src",
")",
"return",
"os",
".",
"path",
".",
"relpath",
"(",
"dst",
",",
"src_dir",
")"
] | 39 | 0.025126 |
def iter_annotations(self):
"""Yield a tuple for each Flask handler containing annotated methods.
Each tuple contains a heading, routing rule, the view class associated
with the rule, and the annotations for the methods in that class.
"""
# Need to store a list of route, view_cl... | [
"def",
"iter_annotations",
"(",
"self",
")",
":",
"# Need to store a list of route, view_class, and annotations by a",
"# section key so that all methods of a resource are kept together in",
"# the documentation. The key of the section will be the heading that",
"# the route documentation goes un... | 47.146341 | 0.001014 |
def find_connecting_throat(self, P1, P2):
r"""
Return the throat index connecting pairs of pores
Parameters
----------
P1 , P2 : array_like
The indices of the pores whose throats are sought. These can be
vectors of indices, but must be the same length
... | [
"def",
"find_connecting_throat",
"(",
"self",
",",
"P1",
",",
"P2",
")",
":",
"am",
"=",
"self",
".",
"create_adjacency_matrix",
"(",
"weights",
"=",
"self",
".",
"Ts",
",",
"fmt",
"=",
"'coo'",
")",
"sites",
"=",
"sp",
".",
"vstack",
"(",
"(",
"P1",... | 33.852941 | 0.001689 |
def relocate_audio_to_wav_files(self, target_path):
"""
Copies every track to its own wav file in the given folder.
Every track will be stored at ``target_path/track_id.wav``.
"""
if not os.path.isdir(target_path):
os.makedirs(target_path)
new_tracks = {}
... | [
"def",
"relocate_audio_to_wav_files",
"(",
"self",
",",
"target_path",
")",
":",
"if",
"not",
"os",
".",
"path",
".",
"isdir",
"(",
"target_path",
")",
":",
"os",
".",
"makedirs",
"(",
"target_path",
")",
"new_tracks",
"=",
"{",
"}",
"# First create a new co... | 34.551724 | 0.001942 |
def RESTrequest(*args, **kwargs):
"""return and save the blob of data that is returned
from kegg without caring to the format"""
verbose = kwargs.get('verbose', False)
force_download = kwargs.get('force', False)
save = kwargs.get('force', True)
# so you can copy paste from kegg
args = list(... | [
"def",
"RESTrequest",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"verbose",
"=",
"kwargs",
".",
"get",
"(",
"'verbose'",
",",
"False",
")",
"force_download",
"=",
"kwargs",
".",
"get",
"(",
"'force'",
",",
"False",
")",
"save",
"=",
"kwargs... | 37.545455 | 0.000787 |
def format_pathname(
pathname,
max_length):
"""
Format a pathname
:param str pathname: Pathname to format
:param int max_length: Maximum length of result pathname (> 3)
:return: Formatted pathname
:rtype: str
:raises ValueError: If *max_length* is not larger than 3
This... | [
"def",
"format_pathname",
"(",
"pathname",
",",
"max_length",
")",
":",
"if",
"max_length",
"<=",
"3",
":",
"raise",
"ValueError",
"(",
"\"max length must be larger than 3\"",
")",
"if",
"len",
"(",
"pathname",
")",
">",
"max_length",
":",
"pathname",
"=",
"\"... | 33.52 | 0.00116 |
def skip_duplicates(iterable, key=None, fingerprints=()):
# type: (Iterable, Callable, Any) -> Iterable
"""
Returns a generator that will yield all objects from iterable, skipping
duplicates.
Duplicates are identified using the `key` function to calculate a
unique fingerprint. T... | [
"def",
"skip_duplicates",
"(",
"iterable",
",",
"key",
"=",
"None",
",",
"fingerprints",
"=",
"(",
")",
")",
":",
"# type: (Iterable, Callable, Any) -> Iterable",
"fingerprints",
"=",
"fingerprints",
"or",
"set",
"(",
")",
"fingerprint",
"=",
"None",
"# needed on ... | 37.469136 | 0.000321 |
def observable_object_references(instance):
"""Ensure certain observable object properties reference the correct type
of object.
"""
for key, obj in instance['objects'].items():
if 'type' not in obj:
continue
elif obj['type'] not in enums.OBSERVABLE_PROP_REFS:
con... | [
"def",
"observable_object_references",
"(",
"instance",
")",
":",
"for",
"key",
",",
"obj",
"in",
"instance",
"[",
"'objects'",
"]",
".",
"items",
"(",
")",
":",
"if",
"'type'",
"not",
"in",
"obj",
":",
"continue",
"elif",
"obj",
"[",
"'type'",
"]",
"n... | 48.86 | 0.002408 |
def marshal(data, fields, envelope=None):
"""Takes raw data (in the form of a dict, list, object) and a dict of
fields to output and filters the data based on those fields.
:param data: the actual object(s) from which the fields are taken from
:param fields: a dict of whose keys will make up the final ... | [
"def",
"marshal",
"(",
"data",
",",
"fields",
",",
"envelope",
"=",
"None",
")",
":",
"def",
"make",
"(",
"cls",
")",
":",
"if",
"isinstance",
"(",
"cls",
",",
"type",
")",
":",
"return",
"cls",
"(",
")",
"return",
"cls",
"if",
"isinstance",
"(",
... | 35.138889 | 0.001538 |
def wiki(wiki_root, wiki_date, wiki_language, max_vocab_size=None):
"""Wikipedia dump helper.
Parameters
----------
wiki_root : str
Parameter for WikiDumpStream
wiki_date : str
Parameter for WikiDumpStream
wiki_language : str
Parameter for WikiDumpStream
max_vocab_si... | [
"def",
"wiki",
"(",
"wiki_root",
",",
"wiki_date",
",",
"wiki_language",
",",
"max_vocab_size",
"=",
"None",
")",
":",
"data",
"=",
"WikiDumpStream",
"(",
"root",
"=",
"os",
".",
"path",
".",
"expanduser",
"(",
"wiki_root",
")",
",",
"language",
"=",
"wi... | 31.55814 | 0.000715 |
def __setImports(self, schema):
"""Add dictionary of imports to schema instance.
schema -- XMLSchema instance
"""
for ns,val in schema.imports.items():
if self._imports.has_key(ns):
schema.addImportSchema(self._imports[ns]) | [
"def",
"__setImports",
"(",
"self",
",",
"schema",
")",
":",
"for",
"ns",
",",
"val",
"in",
"schema",
".",
"imports",
".",
"items",
"(",
")",
":",
"if",
"self",
".",
"_imports",
".",
"has_key",
"(",
"ns",
")",
":",
"schema",
".",
"addImportSchema",
... | 40.142857 | 0.017422 |
def IndexMiddleware(index='index.html'):
"""Middleware to serve index files (e.g. index.html) when static directories are requested.
Usage:
::
from aiohttp import web
from aiohttp_index import IndexMiddleware
app = web.Application(middlewares=[IndexMiddleware()])
app.router... | [
"def",
"IndexMiddleware",
"(",
"index",
"=",
"'index.html'",
")",
":",
"async",
"def",
"middleware_factory",
"(",
"app",
",",
"handler",
")",
":",
"\"\"\"Middleware factory method.\n\n :type app: aiohttp.web.Application\n :type handler: function\n :returns: The... | 33.454545 | 0.00198 |
def validate_openbin_mode(mode, _valid_chars=frozenset("rwxab+")):
# type: (Text, Union[Set[Text], FrozenSet[Text]]) -> None
"""Check ``mode`` parameter of `~fs.base.FS.openbin` is valid.
Arguments:
mode (str): Mode parameter.
Raises:
`ValueError` if mode is not valid.
"""
if ... | [
"def",
"validate_openbin_mode",
"(",
"mode",
",",
"_valid_chars",
"=",
"frozenset",
"(",
"\"rwxab+\"",
")",
")",
":",
"# type: (Text, Union[Set[Text], FrozenSet[Text]]) -> None",
"if",
"\"t\"",
"in",
"mode",
":",
"raise",
"ValueError",
"(",
"\"text mode not valid in openb... | 34.842105 | 0.001471 |
def context(self, size, placeholder=None, scope=None):
"""Returns this word in context, {size} words to the left, the current word, and {size} words to the right"""
return self.leftcontext(size, placeholder,scope) + [self] + self.rightcontext(size, placeholder,scope) | [
"def",
"context",
"(",
"self",
",",
"size",
",",
"placeholder",
"=",
"None",
",",
"scope",
"=",
"None",
")",
":",
"return",
"self",
".",
"leftcontext",
"(",
"size",
",",
"placeholder",
",",
"scope",
")",
"+",
"[",
"self",
"]",
"+",
"self",
".",
"ri... | 93.666667 | 0.021201 |
def get_public_key(cookie, tokens):
'''获取RSA公钥, 这个用于加密用户的密码
返回的数据如下:
{"errno":'0',"msg":'',"pubkey":'-----BEGIN PUBLIC KEY-----\nMIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDk\/ufXg3IBW8+h5i8L8NoXUzcN\nMeKrh4zEupGBkyrURIPUXKDFLWjrv4n2j3RpMZ8GQn\/ETcfoIHGBoCUKJWcfcvmi\nG+OkYeqT6zyJasF0OlKesKfz0fGogMtdCQ6Kqq7X... | [
"def",
"get_public_key",
"(",
"cookie",
",",
"tokens",
")",
":",
"url",
"=",
"''",
".",
"join",
"(",
"[",
"const",
".",
"PASSPORT_BASE",
",",
"'v2/getpublickey'",
",",
"'?token='",
",",
"tokens",
"[",
"'token'",
"]",
",",
"'&tpl=pp&apiver=v3&tt='",
",",
"u... | 42.1 | 0.00813 |
def wheel_version(source_dir):
# type: (Optional[str]) -> Optional[Tuple[int, ...]]
"""
Return the Wheel-Version of an extracted wheel, if possible.
Otherwise, return None if we couldn't parse / extract it.
"""
try:
dist = [d for d in pkg_resources.find_on_path(None, source_dir)][0]
... | [
"def",
"wheel_version",
"(",
"source_dir",
")",
":",
"# type: (Optional[str]) -> Optional[Tuple[int, ...]]",
"try",
":",
"dist",
"=",
"[",
"d",
"for",
"d",
"in",
"pkg_resources",
".",
"find_on_path",
"(",
"None",
",",
"source_dir",
")",
"]",
"[",
"0",
"]",
"wh... | 31.833333 | 0.001695 |
def _prepare(self, **kwargs):
'''Set up properties for optimization.
This method can be overridden by base classes to provide parameters that
are specific to a particular optimization technique (e.g., setting up a
learning rate value).
'''
self.learning_rate = util.as_fl... | [
"def",
"_prepare",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
".",
"learning_rate",
"=",
"util",
".",
"as_float",
"(",
"kwargs",
".",
"pop",
"(",
"'learning_rate'",
",",
"1e-4",
")",
")",
"self",
".",
"momentum",
"=",
"kwargs",
".",
"pop... | 51.041667 | 0.002404 |
def get_unique_name(self, cursor):
"""get the spelling or create a unique name for a cursor"""
name = ''
if cursor.kind in [CursorKind.UNEXPOSED_DECL]:
return ''
# covers most cases
name = cursor.spelling
# if its a record decl or field decl and its type is un... | [
"def",
"get_unique_name",
"(",
"self",
",",
"cursor",
")",
":",
"name",
"=",
"''",
"if",
"cursor",
".",
"kind",
"in",
"[",
"CursorKind",
".",
"UNEXPOSED_DECL",
"]",
":",
"return",
"''",
"# covers most cases",
"name",
"=",
"cursor",
".",
"spelling",
"# if i... | 48.875 | 0.010658 |
def select_grid_model_ria(lvgd, sector):
"""Select a typified grid for retail/industrial and agricultural
Parameters
----------
lvgd : ding0.core.structure.regions.LVGridDistrictDing0
Low-voltage grid district object
sector : str
Either 'retail/industrial' or 'agricultural'. Dependi... | [
"def",
"select_grid_model_ria",
"(",
"lvgd",
",",
"sector",
")",
":",
"cable_lf",
"=",
"cfg_ding0",
".",
"get",
"(",
"'assumptions'",
",",
"'load_factor_lv_cable_lc_normal'",
")",
"cos_phi_load",
"=",
"cfg_ding0",
".",
"get",
"(",
"'assumptions'",
",",
"'cos_phi_l... | 39.949495 | 0.001234 |
def thread_data(name, value=NOTHING, ct=None):
'''Set or retrieve an attribute ``name`` from thread ``ct``.
If ``ct`` is not given used the current thread. If ``value``
is None, it will get the value otherwise it will set the value.
'''
ct = ct or current_thread()
if is_mainthread(ct):
... | [
"def",
"thread_data",
"(",
"name",
",",
"value",
"=",
"NOTHING",
",",
"ct",
"=",
"None",
")",
":",
"ct",
"=",
"ct",
"or",
"current_thread",
"(",
")",
"if",
"is_mainthread",
"(",
"ct",
")",
":",
"loc",
"=",
"process_data",
"(",
")",
"elif",
"not",
"... | 33.619048 | 0.001377 |
def rectToArray(self, swapWH = False):
"""!
\~english
Rectangles converted to array of coordinates
@return: an array of rect points. eg. (x1,y1,x2,y2)
\~chinese
矩形数据转换为矩形坐标数组
@return: 矩形座标数组, 例如: ( x1,y1,x2,y2 )
"""
if swapWH == False:
... | [
"def",
"rectToArray",
"(",
"self",
",",
"swapWH",
"=",
"False",
")",
":",
"if",
"swapWH",
"==",
"False",
":",
"return",
"[",
"self",
".",
"x",
",",
"self",
".",
"y",
",",
"self",
".",
"x",
"+",
"self",
".",
"width",
",",
"self",
".",
"y",
"+",
... | 33.357143 | 0.014583 |
def load_pk(abspath, compress=False, enable_verbose=True):
"""Load Python Object from Pickle file.
:param abspath: File path. Use absolute path as much as you can. File
extension has to be ``.pickle`` or ``.gz``. (for compressed Pickle)
:type abspath: string
:param compress: (default False) Lo... | [
"def",
"load_pk",
"(",
"abspath",
",",
"compress",
"=",
"False",
",",
"enable_verbose",
"=",
"True",
")",
":",
"abspath",
"=",
"str",
"(",
"abspath",
")",
"# try stringlize",
"msg",
"=",
"Messenger",
"(",
"enable_verbose",
"=",
"enable_verbose",
")",
"if",
... | 29.507937 | 0.000521 |
def index_of_item(self, item):
"""Get the index for the given TreeItem
:param item: the treeitem to query
:type item: :class:`TreeItem`
:returns: the index of the item
:rtype: :class:`QtCore.QModelIndex`
:raises: ValueError
"""
# root has an invalid index... | [
"def",
"index_of_item",
"(",
"self",
",",
"item",
")",
":",
"# root has an invalid index",
"if",
"item",
"==",
"self",
".",
"_root",
":",
"return",
"QtCore",
".",
"QModelIndex",
"(",
")",
"# find all parents to get their index",
"parents",
"=",
"[",
"item",
"]",... | 35.583333 | 0.00152 |
def getChildren(self, returned_properties=None):
"""Get all the children workitems of this workitem
If no children, None will be returned.
:param returned_properties: the returned properties that you want.
Refer to :class:`rtcclient.client.RTCClient` for more explanations
:... | [
"def",
"getChildren",
"(",
"self",
",",
"returned_properties",
"=",
"None",
")",
":",
"children_tag",
"=",
"(",
"\"rtc_cm:com.ibm.team.workitem.linktype.\"",
"\"parentworkitem.children\"",
")",
"rp",
"=",
"returned_properties",
"return",
"(",
"self",
".",
"rtc_obj",
"... | 45.55 | 0.002151 |
def get_and_subtract(self, delta):
"""
Subtracts the given value from the current value and returns the previous value.
:raises NoDataMemberInClusterError: if the cluster does not contain any data members.
:raises UnsupportedOperationError: if the cluster version is less than 3.10.
... | [
"def",
"get_and_subtract",
"(",
"self",
",",
"delta",
")",
":",
"return",
"self",
".",
"_invoke_internal",
"(",
"pn_counter_add_codec",
",",
"delta",
"=",
"-",
"1",
"*",
"delta",
",",
"get_before_update",
"=",
"True",
")"
] | 45.692308 | 0.009901 |
def to_sa_pair_form(self, sparse=True):
"""
Convert this instance of `DiscreteDP` to SA-pair form
Parameters
----------
sparse : bool, optional(default=True)
Should the `Q` matrix be stored as a sparse matrix?
If true the CSR format is used
Retur... | [
"def",
"to_sa_pair_form",
"(",
"self",
",",
"sparse",
"=",
"True",
")",
":",
"if",
"self",
".",
"_sa_pair",
":",
"return",
"self",
"else",
":",
"s_ind",
",",
"a_ind",
"=",
"np",
".",
"where",
"(",
"self",
".",
"R",
">",
"-",
"np",
".",
"inf",
")"... | 28.903226 | 0.00216 |
def run(self):
""" Run tasks from queue. """
while True:
path, params = self.path_queue.get()
errors = run(path, **params)
self.result_queue.put(errors)
self.path_queue.task_done() | [
"def",
"run",
"(",
"self",
")",
":",
"while",
"True",
":",
"path",
",",
"params",
"=",
"self",
".",
"path_queue",
".",
"get",
"(",
")",
"errors",
"=",
"run",
"(",
"path",
",",
"*",
"*",
"params",
")",
"self",
".",
"result_queue",
".",
"put",
"(",... | 34 | 0.008197 |
def logout(self):
"""
Log the user out.
:return: The JSON response from the server
"""
result = self.users.logout_user()
self.client.token = ''
self.client.userid = ''
self.client.username = ''
self.client.cookies = None
return result | [
"def",
"logout",
"(",
"self",
")",
":",
"result",
"=",
"self",
".",
"users",
".",
"logout_user",
"(",
")",
"self",
".",
"client",
".",
"token",
"=",
"''",
"self",
".",
"client",
".",
"userid",
"=",
"''",
"self",
".",
"client",
".",
"username",
"=",... | 20.333333 | 0.047059 |
def make_phase_space_list():
"""
Extract all the phase space information (due to ``EMIT`` commands in the input
file), and create a list of PhaseSpace objects. The primary purpose of this
is for interactive explorations of the data produced during Pynac simulations.
"""
with open('dynac.short')... | [
"def",
"make_phase_space_list",
"(",
")",
":",
"with",
"open",
"(",
"'dynac.short'",
")",
"as",
"f",
":",
"data_str",
"=",
"''",
".",
"join",
"(",
"line",
"for",
"line",
"in",
"f",
".",
"readlines",
"(",
")",
")",
"data_str_array",
"=",
"data_str",
"."... | 51.75 | 0.009494 |
def __crand(self):
"""
conditional randomization
for observation i with ni neighbors, the candidate set cannot include
i (we don't want i being a neighbor of i). we have to sample without
replacement from a set of ids that doesn't include i. numpy doesn't
directly suppo... | [
"def",
"__crand",
"(",
"self",
")",
":",
"lisas",
"=",
"np",
".",
"zeros",
"(",
"(",
"self",
".",
"n",
",",
"self",
".",
"permutations",
")",
")",
"n_1",
"=",
"self",
".",
"n",
"-",
"1",
"prange",
"=",
"list",
"(",
"range",
"(",
"self",
".",
... | 39.59375 | 0.001541 |
def set_student_accommodation_type(self, student_accommodation_type):
"""
Set the student accomodation type.
:param student_accommodation_type: StudentAccomodationType
"""
if not isinstance(student_accommodation_type, StudentAccommodationType):
raise DaftException("st... | [
"def",
"set_student_accommodation_type",
"(",
"self",
",",
"student_accommodation_type",
")",
":",
"if",
"not",
"isinstance",
"(",
"student_accommodation_type",
",",
"StudentAccommodationType",
")",
":",
"raise",
"DaftException",
"(",
"\"student_accommodation_type should be a... | 51.666667 | 0.008457 |
def series_to_yaml_safe(series, ordered=False):
"""
Convert a pandas Series to a dict that will survive YAML serialization
and re-conversion back to a Series.
Parameters
----------
series : pandas.Series
ordered: bool, optional, default False
If True, an OrderedDict is returned.
... | [
"def",
"series_to_yaml_safe",
"(",
"series",
",",
"ordered",
"=",
"False",
")",
":",
"index",
"=",
"series",
".",
"index",
".",
"to_native_types",
"(",
"quoting",
"=",
"True",
")",
"values",
"=",
"series",
".",
"values",
".",
"tolist",
"(",
")",
"if",
... | 25.625 | 0.001567 |
def raise_for_execution_errors(nb, output_path):
"""Assigned parameters into the appropriate place in the input notebook
Parameters
----------
nb : NotebookNode
Executable notebook object
output_path : str
Path to write executed notebook
"""
error = None
for cell in nb.cel... | [
"def",
"raise_for_execution_errors",
"(",
"nb",
",",
"output_path",
")",
":",
"error",
"=",
"None",
"for",
"cell",
"in",
"nb",
".",
"cells",
":",
"if",
"cell",
".",
"get",
"(",
"\"outputs\"",
")",
"is",
"None",
":",
"continue",
"for",
"output",
"in",
"... | 33.74359 | 0.002216 |
def download_and_install_dependencies():
"""Setup URLS and download dependencies for Python 3.6+
"""
try:
import requests
except ImportError:
raise ValueError("Python 3.6+ is required.")
dependencies = {"hmm_databases": HMM_URL}
if sys.platform.startswith("linux") or "bsd" in ... | [
"def",
"download_and_install_dependencies",
"(",
")",
":",
"try",
":",
"import",
"requests",
"except",
"ImportError",
":",
"raise",
"ValueError",
"(",
"\"Python 3.6+ is required.\"",
")",
"dependencies",
"=",
"{",
"\"hmm_databases\"",
":",
"HMM_URL",
"}",
"if",
"sys... | 33.386667 | 0.000388 |
def mainline(self):
""" Returns the main line of the game (variation A) as a 'GameTree'."""
if self.variations:
return GameTree(self.data + self.variations[0].mainline())
else:
return self | [
"def",
"mainline",
"(",
"self",
")",
":",
"if",
"self",
".",
"variations",
":",
"return",
"GameTree",
"(",
"self",
".",
"data",
"+",
"self",
".",
"variations",
"[",
"0",
"]",
".",
"mainline",
"(",
")",
")",
"else",
":",
"return",
"self"
] | 32.5 | 0.035 |
def p_expression_srl(self, p):
'expression : expression RSHIFT expression'
p[0] = Srl(p[1], p[3], lineno=p.lineno(1))
p.set_lineno(0, p.lineno(1)) | [
"def",
"p_expression_srl",
"(",
"self",
",",
"p",
")",
":",
"p",
"[",
"0",
"]",
"=",
"Srl",
"(",
"p",
"[",
"1",
"]",
",",
"p",
"[",
"3",
"]",
",",
"lineno",
"=",
"p",
".",
"lineno",
"(",
"1",
")",
")",
"p",
".",
"set_lineno",
"(",
"0",
",... | 41.75 | 0.011765 |
def get_predicates(self, class_, controller=None):
"""Get full predicate information for given request class, and cache
for subsequent calls.
"""
if class_ not in self._predicates:
if controller is None:
controller = self._find_controller(class_)
e... | [
"def",
"get_predicates",
"(",
"self",
",",
"class_",
",",
"controller",
"=",
"None",
")",
":",
"if",
"class_",
"not",
"in",
"self",
".",
"_predicates",
":",
"if",
"controller",
"is",
"None",
":",
"controller",
"=",
"self",
".",
"_find_controller",
"(",
"... | 44.47619 | 0.002096 |
def split_lines(lines):
"""
split a MagIC upload format file into lists.
the lists are split by the '>>>' lines between file_types.
"""
container = []
new_list = []
for line in lines:
if '>>>' in line:
container.append(new_list)
new_list = []
else:
... | [
"def",
"split_lines",
"(",
"lines",
")",
":",
"container",
"=",
"[",
"]",
"new_list",
"=",
"[",
"]",
"for",
"line",
"in",
"lines",
":",
"if",
"'>>>'",
"in",
"line",
":",
"container",
".",
"append",
"(",
"new_list",
")",
"new_list",
"=",
"[",
"]",
"... | 25.866667 | 0.002488 |
def run(*args, **kwargs):
'''
Execute a puppet run and return a dict with the stderr, stdout,
return code, etc. The first positional argument given is checked as a
subcommand. Following positional arguments should be ordered with arguments
required by the subcommand first, followed by non-keyword ar... | [
"def",
"run",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"puppet",
"=",
"_Puppet",
"(",
")",
"# new args tuple to filter out agent/apply for _Puppet.arguments()",
"buildargs",
"=",
"(",
")",
"for",
"arg",
"in",
"range",
"(",
"len",
"(",
"args",
")"... | 41.157895 | 0.001874 |
def newer(self, source, target):
"""Tell if the target is newer than the source.
Returns true if 'source' exists and is more recently modified than
'target', or if 'source' exists and 'target' doesn't.
Returns false if both exist and 'target' is the same age or younger
than 'so... | [
"def",
"newer",
"(",
"self",
",",
"source",
",",
"target",
")",
":",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"source",
")",
":",
"raise",
"DistlibException",
"(",
"\"file '%r' does not exist\"",
"%",
"os",
".",
"path",
".",
"abspath",
"(",
... | 41.315789 | 0.002491 |
def unflatten1(flat_list, reverse_list):
""" Rebuilds unflat list from invertible_flatten1
Args:
flat_list (list): the flattened list
reverse_list (list): the list which undoes flattenting
Returns:
unflat_list2: original nested list
SeeAlso:
invertible_flatten1
... | [
"def",
"unflatten1",
"(",
"flat_list",
",",
"reverse_list",
")",
":",
"unflat_list2",
"=",
"[",
"[",
"flat_list",
"[",
"index",
"]",
"for",
"index",
"in",
"tup",
"]",
"for",
"tup",
"in",
"reverse_list",
"]",
"return",
"unflat_list2"
] | 23.75 | 0.002024 |
def add_outbound_connection(self, uri):
"""Adds an outbound connection to the network.
Args:
uri (str): The zmq-style (e.g. tcp://hostname:port) uri
to attempt to connect to.
"""
LOGGER.debug("Adding connection to %s", uri)
conn = OutboundConnection(
... | [
"def",
"add_outbound_connection",
"(",
"self",
",",
"uri",
")",
":",
"LOGGER",
".",
"debug",
"(",
"\"Adding connection to %s\"",
",",
"uri",
")",
"conn",
"=",
"OutboundConnection",
"(",
"connections",
"=",
"self",
".",
"_connections",
",",
"endpoint",
"=",
"ur... | 33.971429 | 0.001635 |
def create_consumer(self):
"""Context manager that yields an instance of ``Consumer``."""
with self.connection_pool.acquire(block=True) as conn:
yield self.consumer(conn) | [
"def",
"create_consumer",
"(",
"self",
")",
":",
"with",
"self",
".",
"connection_pool",
".",
"acquire",
"(",
"block",
"=",
"True",
")",
"as",
"conn",
":",
"yield",
"self",
".",
"consumer",
"(",
"conn",
")"
] | 48.75 | 0.010101 |
def from_config(cls, cp, section, variable_args):
"""Returns a distribution based on a configuration file.
The parameters
for the distribution are retrieved from the section titled
"[`section`-`variable_args`]" in the config file.
The file to construct the distribution from mus... | [
"def",
"from_config",
"(",
"cls",
",",
"cp",
",",
"section",
",",
"variable_args",
")",
":",
"return",
"bounded",
".",
"bounded_from_config",
"(",
"cls",
",",
"cp",
",",
"section",
",",
"variable_args",
",",
"bounds_required",
"=",
"False",
")"
] | 35.789474 | 0.001432 |
def pointbiserialr(cats, vals):
"""
Calculates a point-biserial correlation coefficient and the associated
probability value. Taken from Heiman's Basic Statistics for the Behav.
Sci (1st), p.194.
Usage: pointbiserialr(x,y) where x,y are equal-length lists
Returns: Point-biserial r, two-tailed p-value
"""
... | [
"def",
"pointbiserialr",
"(",
"cats",
",",
"vals",
")",
":",
"TINY",
"=",
"1e-30",
"if",
"len",
"(",
"cats",
")",
"!=",
"len",
"(",
"vals",
")",
":",
"raise",
"ValueError",
"(",
"'INPUT VALUES NOT PAIRED IN pointbiserialr. ABORTING.'",
")",
"data",
"=",
"zi... | 42.321429 | 0.00165 |
def set_secondary_channel(self, source, channel_list):
""" General purpose method for setting a secondary channel
This method allows a given source channel to be forked into one or
more channels and sets those forks in the :py:attr:`Process.forks`
attribute. Both the source and the chan... | [
"def",
"set_secondary_channel",
"(",
"self",
",",
"source",
",",
"channel_list",
")",
":",
"logger",
".",
"debug",
"(",
"\"Setting secondary channel for source '{}': {}\"",
".",
"format",
"(",
"source",
",",
"channel_list",
")",
")",
"source",
"=",
"\"{}_{}\"",
".... | 44.84 | 0.000873 |
def _update_cache(self):
"""
INPUT:
hyperparams: dictionary
OUTPUT: dictionary with the fields
K: kernel
Kinv: inverse of the kernel
L: chol(K)
alpha: solve(K,y)
W: D*Kinv * alpha*alpha^T
"""
cov_params_have_changed = ... | [
"def",
"_update_cache",
"(",
"self",
")",
":",
"cov_params_have_changed",
"=",
"self",
".",
"covar",
".",
"params_have_changed",
"if",
"cov_params_have_changed",
"or",
"self",
".",
"Y_has_changed",
":",
"K",
"=",
"self",
".",
"covar",
".",
"K",
"(",
")",
"L"... | 33.555556 | 0.008584 |
def forget(self):
"""
Reset _observed events. Remove self from observers.
:return: Nothing
"""
self._observed_events = {}
if self in self._observers:
self._observers.remove(self) | [
"def",
"forget",
"(",
"self",
")",
":",
"self",
".",
"_observed_events",
"=",
"{",
"}",
"if",
"self",
"in",
"self",
".",
"_observers",
":",
"self",
".",
"_observers",
".",
"remove",
"(",
"self",
")"
] | 28.875 | 0.008403 |
def main(args, stop=False):
"""
Arguments parsing, etc..
"""
daemon = AMQPDaemon(
con_param=getConParams(
settings.RABBITMQ_PDFGEN_VIRTUALHOST
),
queue=settings.RABBITMQ_PDFGEN_INPUT_QUEUE,
out_exch=settings.RABBITMQ_PDFGEN_EXCHANGE,
out_key=settings.R... | [
"def",
"main",
"(",
"args",
",",
"stop",
"=",
"False",
")",
":",
"daemon",
"=",
"AMQPDaemon",
"(",
"con_param",
"=",
"getConParams",
"(",
"settings",
".",
"RABBITMQ_PDFGEN_VIRTUALHOST",
")",
",",
"queue",
"=",
"settings",
".",
"RABBITMQ_PDFGEN_INPUT_QUEUE",
",... | 28.947368 | 0.001761 |
def full_name(self):
"""
The full name of the field. This is the field's entities name
concatenated with the field's name. If the field is unnamed or
not bound to an entity, the result respectively contains None.
"""
entity = self.entity.__name__ if self.entity is not None else None
name = ... | [
"def",
"full_name",
"(",
"self",
")",
":",
"entity",
"=",
"self",
".",
"entity",
".",
"__name__",
"if",
"self",
".",
"entity",
"is",
"not",
"None",
"else",
"None",
"name",
"=",
"self",
".",
"name",
"if",
"self",
".",
"name",
"is",
"not",
"None",
"e... | 32.352941 | 0.008834 |
def detail_poi(self, **kwargs):
"""Obtain detailed info of a given POI.
Args:
family (str): Family code of the POI (3 chars).
lang (str): Language code (*es* or *en*).
id (int): Optional, ID of the POI to query. Passing value -1 will
result in informa... | [
"def",
"detail_poi",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"# Endpoint parameters",
"params",
"=",
"{",
"'language'",
":",
"util",
".",
"language_code",
"(",
"kwargs",
".",
"get",
"(",
"'lang'",
")",
")",
",",
"'family'",
":",
"kwargs",
".",
... | 32.612903 | 0.001921 |
def main( gpu:Param("GPU to run on", str)=None ):
"""Distrubuted training of CIFAR-10.
Fastest speed is if you run as follows:
python -m fastai.launch train_cifar.py"""
gpu = setup_distrib(gpu)
n_gpus = num_distrib()
path = url2path(URLs.CIFAR)
ds_tfms = ([*rand_pad(4, 32), flip_lr(p=0.5... | [
"def",
"main",
"(",
"gpu",
":",
"Param",
"(",
"\"GPU to run on\"",
",",
"str",
")",
"=",
"None",
")",
":",
"gpu",
"=",
"setup_distrib",
"(",
"gpu",
")",
"n_gpus",
"=",
"num_distrib",
"(",
")",
"path",
"=",
"url2path",
"(",
"URLs",
".",
"CIFAR",
")",
... | 46.375 | 0.01321 |
def query_as_ldap(query, compiler, connection):
"""Convert a django.db.models.sql.query.Query to a LdapLookup."""
if query.is_empty():
return
if query.model._meta.model_name == 'migration' and not hasattr(query.model, 'object_classes'):
# FIXME(rbarrois): Support migrations
return
... | [
"def",
"query_as_ldap",
"(",
"query",
",",
"compiler",
",",
"connection",
")",
":",
"if",
"query",
".",
"is_empty",
"(",
")",
":",
"return",
"if",
"query",
".",
"model",
".",
"_meta",
".",
"model_name",
"==",
"'migration'",
"and",
"not",
"hasattr",
"(",
... | 35.888889 | 0.002261 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.