text stringlengths 89 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 630 |
|---|---|---|---|
def rotate(x, y, degree):
"""Rotate a coordinate around point (0,0).
- x and y specify the coordinate.
- degree is a number from 0 to 360.
Returns a new coordinate.
"""
radian = float(degree) * 2 * math.pi / 360.0
newx = math.cos(radian) * x - math.sin(radian) * y
newy = math.sin(radian)... | [
"def",
"rotate",
"(",
"x",
",",
"y",
",",
"degree",
")",
":",
"radian",
"=",
"float",
"(",
"degree",
")",
"*",
"2",
"*",
"math",
".",
"pi",
"/",
"360.0",
"newx",
"=",
"math",
".",
"cos",
"(",
"radian",
")",
"*",
"x",
"-",
"math",
".",
"sin",
... | 36.2 | 8.3 |
def packet2chain(packet):
"""Fetch Scapy packet protocol chain."""
if scapy_all is None:
raise ModuleNotFound("No module named 'scapy'", name='scapy')
chain = [packet.name]
payload = packet.payload
while not isinstance(payload, scapy_all.packet.NoPayload):
chain.append(payload.name)
... | [
"def",
"packet2chain",
"(",
"packet",
")",
":",
"if",
"scapy_all",
"is",
"None",
":",
"raise",
"ModuleNotFound",
"(",
"\"No module named 'scapy'\"",
",",
"name",
"=",
"'scapy'",
")",
"chain",
"=",
"[",
"packet",
".",
"name",
"]",
"payload",
"=",
"packet",
... | 37.1 | 13.5 |
def mswe(w, v):
"""
Calculate mean squared weight error between estimated and true filter
coefficients, in respect to iterations.
Parameters
----------
v : array-like
True coefficients used to generate desired signal, must be a
one-dimensional array.
w : array-like
E... | [
"def",
"mswe",
"(",
"w",
",",
"v",
")",
":",
"# Ensure inputs are numpy arrays",
"w",
"=",
"np",
".",
"array",
"(",
"w",
")",
"v",
"=",
"np",
".",
"array",
"(",
"v",
")",
"# Check dimensions",
"if",
"(",
"len",
"(",
"w",
".",
"shape",
")",
"!=",
... | 28.882353 | 22.647059 |
def _flatten_mesh(self, Xs, term):
"""flatten the mesh and distribute into a feature matrix"""
n = Xs[0].size
if self.terms[term].istensor:
terms = self.terms[term]
else:
terms = [self.terms[term]]
X = np.zeros((n, self.statistics_['m_features']))
... | [
"def",
"_flatten_mesh",
"(",
"self",
",",
"Xs",
",",
"term",
")",
":",
"n",
"=",
"Xs",
"[",
"0",
"]",
".",
"size",
"if",
"self",
".",
"terms",
"[",
"term",
"]",
".",
"istensor",
":",
"terms",
"=",
"self",
".",
"terms",
"[",
"term",
"]",
"else",... | 30.923077 | 14.230769 |
def list_permissions(vhost, runas=None):
'''
Lists permissions for vhost via rabbitmqctl list_permissions
CLI Example:
.. code-block:: bash
salt '*' rabbitmq.list_permissions /myvhost
'''
if runas is None and not salt.utils.platform.is_windows():
runas = salt.utils.user.get_us... | [
"def",
"list_permissions",
"(",
"vhost",
",",
"runas",
"=",
"None",
")",
":",
"if",
"runas",
"is",
"None",
"and",
"not",
"salt",
".",
"utils",
".",
"platform",
".",
"is_windows",
"(",
")",
":",
"runas",
"=",
"salt",
".",
"utils",
".",
"user",
".",
... | 27.368421 | 21.052632 |
def p_decl_arr(p):
""" var_arr_decl : DIM idlist LP bound_list RP typedef
"""
if len(p[2]) != 1:
syntax_error(p.lineno(1), "Array declaration only allows one variable name at a time")
else:
id_, lineno = p[2][0]
SYMBOL_TABLE.declare_array(id_, lineno, p[6], p[4])
p[0] = p[2][... | [
"def",
"p_decl_arr",
"(",
"p",
")",
":",
"if",
"len",
"(",
"p",
"[",
"2",
"]",
")",
"!=",
"1",
":",
"syntax_error",
"(",
"p",
".",
"lineno",
"(",
"1",
")",
",",
"\"Array declaration only allows one variable name at a time\"",
")",
"else",
":",
"id_",
","... | 34.888889 | 19.666667 |
def _create_latent_variables(self):
""" Creates model latent variables
Returns
----------
None (changes model attributes)
"""
self.latent_variables.add_z('Constant', fam.Normal(0,10,transform=None), fam.Normal(0,3))
self.latent_variables.add_z('Ability Scale', f... | [
"def",
"_create_latent_variables",
"(",
"self",
")",
":",
"self",
".",
"latent_variables",
".",
"add_z",
"(",
"'Constant'",
",",
"fam",
".",
"Normal",
"(",
"0",
",",
"10",
",",
"transform",
"=",
"None",
")",
",",
"fam",
".",
"Normal",
"(",
"0",
",",
... | 35.8 | 25.1 |
def find1(self, kw: YangIdentifier, arg: str = None,
pref: YangIdentifier = None,
required: bool = False) -> Optional["Statement"]:
"""Return first substatement with the given parameters.
Args:
kw: Statement keyword (local part for extensions).
arg: A... | [
"def",
"find1",
"(",
"self",
",",
"kw",
":",
"YangIdentifier",
",",
"arg",
":",
"str",
"=",
"None",
",",
"pref",
":",
"YangIdentifier",
"=",
"None",
",",
"required",
":",
"bool",
"=",
"False",
")",
"->",
"Optional",
"[",
"\"Statement\"",
"]",
":",
"f... | 41.52381 | 17.904762 |
def _get_memory_contents(self):
"""Runs the scheduler to determine memory contents at every point in time.
Returns:
a list of frozenset of strings, where the ith entry describes the tensors
in memory when executing operation i (where schedule[i] is an index into
GetAllOperationNames()).
"... | [
"def",
"_get_memory_contents",
"(",
"self",
")",
":",
"if",
"self",
".",
"_memory_contents",
"is",
"not",
"None",
":",
"return",
"self",
".",
"_memory_contents",
"schedule",
"=",
"scheduler",
".",
"minimize_peak_memory",
"(",
"self",
".",
"_graph",
",",
"self"... | 37.3125 | 22.5 |
def fix_pyqt5_QGraphicsItem_itemChange():
"""
Attempt to remedy:
https://www.riverbankcomputing.com/pipermail/pyqt/2016-February/037015.html
"""
from PyQt5.QtWidgets import QGraphicsObject, QGraphicsItem
class Obj(QGraphicsObject):
def itemChange(self, change, value):
return... | [
"def",
"fix_pyqt5_QGraphicsItem_itemChange",
"(",
")",
":",
"from",
"PyQt5",
".",
"QtWidgets",
"import",
"QGraphicsObject",
",",
"QGraphicsItem",
"class",
"Obj",
"(",
"QGraphicsObject",
")",
":",
"def",
"itemChange",
"(",
"self",
",",
"change",
",",
"value",
")"... | 37.934783 | 19.804348 |
async def get_windows_kms_host(cls) -> typing.Optional[str]:
"""Windows KMS activation host.
FQDN or IP address of the host that provides the KMS Windows
activation service. (Only needed for Windows deployments using KMS
activation.)
"""
data = await cls.get_config("wind... | [
"async",
"def",
"get_windows_kms_host",
"(",
"cls",
")",
"->",
"typing",
".",
"Optional",
"[",
"str",
"]",
":",
"data",
"=",
"await",
"cls",
".",
"get_config",
"(",
"\"windows_kms_host\"",
")",
"return",
"None",
"if",
"data",
"is",
"None",
"or",
"data",
... | 42.888889 | 19.555556 |
def sys_names(self):
"""
Return a list of unique systematic names from OverallSys and HistoSys
"""
names = {}
for osys in self.overall_sys:
names[osys.name] = None
for hsys in self.histo_sys:
names[hsys.name] = None
return names.keys() | [
"def",
"sys_names",
"(",
"self",
")",
":",
"names",
"=",
"{",
"}",
"for",
"osys",
"in",
"self",
".",
"overall_sys",
":",
"names",
"[",
"osys",
".",
"name",
"]",
"=",
"None",
"for",
"hsys",
"in",
"self",
".",
"histo_sys",
":",
"names",
"[",
"hsys",
... | 30.6 | 11 |
def _build_scalar_declarations(self, with_init=True):
"""Build and return scalar variable declarations"""
# copy scalar declarations from from kernel ast
scalar_declarations = [deepcopy(d) for d in self.kernel_ast.block_items
if type(d) is c_ast.Decl and type(d.typ... | [
"def",
"_build_scalar_declarations",
"(",
"self",
",",
"with_init",
"=",
"True",
")",
":",
"# copy scalar declarations from from kernel ast",
"scalar_declarations",
"=",
"[",
"deepcopy",
"(",
"d",
")",
"for",
"d",
"in",
"self",
".",
"kernel_ast",
".",
"block_items",... | 57.1875 | 24.125 |
def nltides_coefs(amplitude, n, m1, m2):
"""Calculate the coefficents needed to compute the
shift in t(f) and phi(f) due to non-linear tides.
Parameters
----------
amplitude: float
Amplitude of effect
n: float
Growth dependence of effect
m1: float
Mass of component 1... | [
"def",
"nltides_coefs",
"(",
"amplitude",
",",
"n",
",",
"m1",
",",
"m2",
")",
":",
"# Use 100.0 Hz as a reference frequency",
"f_ref",
"=",
"100.0",
"# Calculate chirp mass",
"mc",
"=",
"mchirp_from_mass1_mass2",
"(",
"m1",
",",
"m2",
")",
"mc",
"*=",
"lal",
... | 26.375 | 19 |
def avail_images(conn=None, call=None):
'''
Return a list of the server appliances that are on the provider
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_images function must be called with '
'-f or --function, or with the --list-images option'
)
... | [
"def",
"avail_images",
"(",
"conn",
"=",
"None",
",",
"call",
"=",
"None",
")",
":",
"if",
"call",
"==",
"'action'",
":",
"raise",
"SaltCloudSystemExit",
"(",
"'The avail_images function must be called with '",
"'-f or --function, or with the --list-images option'",
")",
... | 24.421053 | 23.684211 |
def merge_overlaps(self, data_reducer=None, data_initializer=None, strict=True):
"""
Finds all intervals with overlapping ranges and merges them
into a single interval. If provided, uses data_reducer and
data_initializer with similar semantics to Python's built-in
reduce(reducer_... | [
"def",
"merge_overlaps",
"(",
"self",
",",
"data_reducer",
"=",
"None",
",",
"data_initializer",
"=",
"None",
",",
"strict",
"=",
"True",
")",
":",
"if",
"not",
"self",
":",
"return",
"sorted_intervals",
"=",
"sorted",
"(",
"self",
".",
"all_intervals",
")... | 45.5 | 22.1875 |
def _add_data(self, plotter_cls, filename_or_obj, fmt={}, make_plot=True,
draw=False, mf_mode=False, ax=None, engine=None, delete=True,
share=False, clear=False, enable_post=None,
concat_dim=_concat_dim_default, load=False,
*args, **kwargs):
... | [
"def",
"_add_data",
"(",
"self",
",",
"plotter_cls",
",",
"filename_or_obj",
",",
"fmt",
"=",
"{",
"}",
",",
"make_plot",
"=",
"True",
",",
"draw",
"=",
"False",
",",
"mf_mode",
"=",
"False",
",",
"ax",
"=",
"None",
",",
"engine",
"=",
"None",
",",
... | 46.807407 | 20.940741 |
def progress_bar(**kwargs):
"""Create a `tqdm.tqdm` progress bar
This is just a thin wrapper around `tqdm.tqdm` to set some updated defaults
"""
tqdm_kw = {
'desc': 'Processing',
'file': sys.stdout,
'bar_format': TQDM_BAR_FORMAT,
}
tqdm_kw.update(kwargs)
pbar = tqdm(... | [
"def",
"progress_bar",
"(",
"*",
"*",
"kwargs",
")",
":",
"tqdm_kw",
"=",
"{",
"'desc'",
":",
"'Processing'",
",",
"'file'",
":",
"sys",
".",
"stdout",
",",
"'bar_format'",
":",
"TQDM_BAR_FORMAT",
",",
"}",
"tqdm_kw",
".",
"update",
"(",
"kwargs",
")",
... | 26.375 | 16.6875 |
def dask_rolling_wrapper(moving_func, a, window, min_count=None, axis=-1):
'''wrapper to apply bottleneck moving window funcs on dask arrays'''
dtype, fill_value = dtypes.maybe_promote(a.dtype)
a = a.astype(dtype)
# inputs for overlap
if axis < 0:
axis = a.ndim + axis
depth = {d: 0 for d... | [
"def",
"dask_rolling_wrapper",
"(",
"moving_func",
",",
"a",
",",
"window",
",",
"min_count",
"=",
"None",
",",
"axis",
"=",
"-",
"1",
")",
":",
"dtype",
",",
"fill_value",
"=",
"dtypes",
".",
"maybe_promote",
"(",
"a",
".",
"dtype",
")",
"a",
"=",
"... | 39.222222 | 16.111111 |
def choose_samples(samples, force):
""" filter out samples that are already done with this step, unless force"""
## hold samples that pass
subsamples = []
## filter the samples again
if not force:
for sample in samples:
if sample.stats.state >= 2:
print("""\
... | [
"def",
"choose_samples",
"(",
"samples",
",",
"force",
")",
":",
"## hold samples that pass",
"subsamples",
"=",
"[",
"]",
"## filter the samples again",
"if",
"not",
"force",
":",
"for",
"sample",
"in",
"samples",
":",
"if",
"sample",
".",
"stats",
".",
"stat... | 32.892857 | 11.75 |
def memsize(self):
""" Total array cell + indexes size
"""
return self.size + 1 + TYPE.size(gl.BOUND_TYPE) * len(self.bounds) | [
"def",
"memsize",
"(",
"self",
")",
":",
"return",
"self",
".",
"size",
"+",
"1",
"+",
"TYPE",
".",
"size",
"(",
"gl",
".",
"BOUND_TYPE",
")",
"*",
"len",
"(",
"self",
".",
"bounds",
")"
] | 36.5 | 14 |
def get(self, template_name):
"""Get a specific template"""
template = db.Template.find_one(template_name=template_name)
if not template:
return self.make_response('No such template found', HTTP.NOT_FOUND)
return self.make_response({'template': template}) | [
"def",
"get",
"(",
"self",
",",
"template_name",
")",
":",
"template",
"=",
"db",
".",
"Template",
".",
"find_one",
"(",
"template_name",
"=",
"template_name",
")",
"if",
"not",
"template",
":",
"return",
"self",
".",
"make_response",
"(",
"'No such template... | 36.75 | 23.875 |
def _put_text(irods_path, text):
"""Put raw text into iRODS."""
with tempfile.NamedTemporaryFile() as fh:
fpath = fh.name
try:
# Make Python2 compatible.
text = unicode(text, "utf-8")
except (NameError, TypeError):
# NameError: We are running Python3 ... | [
"def",
"_put_text",
"(",
"irods_path",
",",
"text",
")",
":",
"with",
"tempfile",
".",
"NamedTemporaryFile",
"(",
")",
"as",
"fh",
":",
"fpath",
"=",
"fh",
".",
"name",
"try",
":",
"# Make Python2 compatible.",
"text",
"=",
"unicode",
"(",
"text",
",",
"... | 27.347826 | 17.173913 |
def setSectionLength(self, length):
"""
Sets the number of characters per section that are allowed.
:param length | <int>
"""
self._sectionLength = length
for editor in self.editors():
editor.setMaxLength(length) | [
"def",
"setSectionLength",
"(",
"self",
",",
"length",
")",
":",
"self",
".",
"_sectionLength",
"=",
"length",
"for",
"editor",
"in",
"self",
".",
"editors",
"(",
")",
":",
"editor",
".",
"setMaxLength",
"(",
"length",
")"
] | 31.777778 | 8.222222 |
def replace_rsc_img_chars(document):
"""Replace image characters with unicode equivalents."""
image_re = re.compile('http://www.rsc.org/images/entities/(?:h[23]+_)?(?:[ib]+_)?char_([0-9a-f]{4})(?:_([0-9a-f]{4}))?\.gif')
for img in document.xpath('.//img[starts-with(@src, "http://www.rsc.org/images/entities/... | [
"def",
"replace_rsc_img_chars",
"(",
"document",
")",
":",
"image_re",
"=",
"re",
".",
"compile",
"(",
"'http://www.rsc.org/images/entities/(?:h[23]+_)?(?:[ib]+_)?char_([0-9a-f]{4})(?:_([0-9a-f]{4}))?\\.gif'",
")",
"for",
"img",
"in",
"document",
".",
"xpath",
"(",
"'.//img... | 48.5 | 18.75 |
def is_valid_nhs_number(n: int) -> bool:
"""
Validates an integer as an NHS number.
Args:
n: NHS number
Returns:
valid?
Checksum details are at
http://www.datadictionary.nhs.uk/version2/data_dictionary/data_field_notes/n/nhs_number_de.asp
""" # noqa
if not isinsta... | [
"def",
"is_valid_nhs_number",
"(",
"n",
":",
"int",
")",
"->",
"bool",
":",
"# noqa",
"if",
"not",
"isinstance",
"(",
"n",
",",
"int",
")",
":",
"log",
".",
"debug",
"(",
"\"is_valid_nhs_number: parameter was not of integer type\"",
")",
"return",
"False",
"s"... | 28.970588 | 21.382353 |
def result(self, timeout=None):
"""
Set all asynchronous results.
:param timeout:
The number of seconds to wait for the result if the futures aren't
done. If None, then there is no limit on the wait time.
:type timeout: float
:return:
Update ... | [
"def",
"result",
"(",
"self",
",",
"timeout",
"=",
"None",
")",
":",
"it",
",",
"exceptions",
",",
"future_lists",
"=",
"[",
"]",
",",
"[",
"]",
",",
"[",
"]",
"from",
"concurrent",
".",
"futures",
"import",
"Future",
",",
"wait",
"as",
"wait_fut",
... | 32.192308 | 16.615385 |
def _get_skippers(configure, file_name=None):
"""
Returns the skippers of configuration.
:param configure: The configuration of HaTeMiLe.
:type configure: hatemile.util.configure.Configure
:param file_name: The file path of skippers configuration.
:type file_name: str
... | [
"def",
"_get_skippers",
"(",
"configure",
",",
"file_name",
"=",
"None",
")",
":",
"skippers",
"=",
"[",
"]",
"if",
"file_name",
"is",
"None",
":",
"file_name",
"=",
"os",
".",
"path",
".",
"join",
"(",
"os",
".",
"path",
".",
"dirname",
"(",
"os",
... | 38.333333 | 15.533333 |
def ajax_kindcat_arr(self, kind_sig):
'''
Get the sub category.
根据kind值(kind_sig)获取相应分类,返回Json格式
'''
out_arr = {}
for catinfo in MCategory.query_kind_cat(kind_sig):
out_arr[catinfo.uid] = catinfo.name
json.dump(out_arr, self) | [
"def",
"ajax_kindcat_arr",
"(",
"self",
",",
"kind_sig",
")",
":",
"out_arr",
"=",
"{",
"}",
"for",
"catinfo",
"in",
"MCategory",
".",
"query_kind_cat",
"(",
"kind_sig",
")",
":",
"out_arr",
"[",
"catinfo",
".",
"uid",
"]",
"=",
"catinfo",
".",
"name",
... | 28.5 | 16.5 |
def make_strain_from_inj_object(self, inj, delta_t, detector_name,
distance_scale=1):
"""Make a h(t) strain time-series from an injection object as read from
an hdf file.
Parameters
-----------
inj : injection object
The injection ... | [
"def",
"make_strain_from_inj_object",
"(",
"self",
",",
"inj",
",",
"delta_t",
",",
"detector_name",
",",
"distance_scale",
"=",
"1",
")",
":",
"detector",
"=",
"Detector",
"(",
"detector_name",
")",
"# compute the waveform time series",
"hp",
",",
"hc",
"=",
"r... | 33 | 19.05 |
def write(self, value):
"""Set the state of the GPIO to `value`.
Args:
value (bool): ``True`` for high state, ``False`` for low state.
Raises:
GPIOError: if an I/O or OS error occurs.
TypeError: if `value` type is not bool.
"""
if not isinst... | [
"def",
"write",
"(",
"self",
",",
"value",
")",
":",
"if",
"not",
"isinstance",
"(",
"value",
",",
"bool",
")",
":",
"raise",
"TypeError",
"(",
"\"Invalid value type, should be bool.\"",
")",
"# Write value",
"try",
":",
"if",
"value",
":",
"os",
".",
"wri... | 29.071429 | 20.892857 |
def _rdsignal(fp, file_size, header_size, n_sig, bit_width, is_signed, cut_end):
"""
Read the signal
Parameters
----------
cut_end : bool, optional
If True, enables reading the end of files which appear to terminate
with the incorrect number of samples (ie. sample not present for al... | [
"def",
"_rdsignal",
"(",
"fp",
",",
"file_size",
",",
"header_size",
",",
"n_sig",
",",
"bit_width",
",",
"is_signed",
",",
"cut_end",
")",
":",
"# Cannot initially figure out signal length because there",
"# are escape sequences.",
"fp",
".",
"seek",
"(",
"header_siz... | 34.218182 | 18.618182 |
def number(self):
"""Return a multidigit int or float number."""
number = ''
while self.char is not None and self.char.isdigit():
number += self.char
self.advance()
if self.char == '.':
number += self.char
self.advance()
while... | [
"def",
"number",
"(",
"self",
")",
":",
"number",
"=",
"''",
"while",
"self",
".",
"char",
"is",
"not",
"None",
"and",
"self",
".",
"char",
".",
"isdigit",
"(",
")",
":",
"number",
"+=",
"self",
".",
"char",
"self",
".",
"advance",
"(",
")",
"if"... | 26.666667 | 20.666667 |
def elmo_loss2ppl(losses: List[np.ndarray]) -> float:
""" Calculates perplexity by loss
Args:
losses: list of numpy arrays of model losses
Returns:
perplexity : float
"""
avg_loss = np.mean(losses)
return float(np.exp(avg_loss)) | [
"def",
"elmo_loss2ppl",
"(",
"losses",
":",
"List",
"[",
"np",
".",
"ndarray",
"]",
")",
"->",
"float",
":",
"avg_loss",
"=",
"np",
".",
"mean",
"(",
"losses",
")",
"return",
"float",
"(",
"np",
".",
"exp",
"(",
"avg_loss",
")",
")"
] | 23.636364 | 17.636364 |
def read_msr(address):
"""
Read the contents of the specified MSR (Machine Specific Register).
@type address: int
@param address: MSR to read.
@rtype: int
@return: Value of the specified MSR.
@raise WindowsError:
Raises an exception on error.
... | [
"def",
"read_msr",
"(",
"address",
")",
":",
"if",
"win32",
".",
"arch",
"not",
"in",
"(",
"win32",
".",
"ARCH_I386",
",",
"win32",
".",
"ARCH_AMD64",
")",
":",
"raise",
"NotImplementedError",
"(",
"\"MSR reading is only supported on i386 or amd64 processors.\"",
... | 33.3 | 18.033333 |
def start(self):
"""
Start the instance.
"""
rs = self.connection.start_instances([self.id])
if len(rs) > 0:
self._update(rs[0]) | [
"def",
"start",
"(",
"self",
")",
":",
"rs",
"=",
"self",
".",
"connection",
".",
"start_instances",
"(",
"[",
"self",
".",
"id",
"]",
")",
"if",
"len",
"(",
"rs",
")",
">",
"0",
":",
"self",
".",
"_update",
"(",
"rs",
"[",
"0",
"]",
")"
] | 24.857143 | 11.142857 |
def incr(self, key, delta=1):
"""
Add delta to value in the cache. If the key does not exist, raise a
ValueError exception.
"""
value = self.get(key)
if value is None:
raise ValueError("Key '%s' not found" % key)
new_value = value + delta
self.... | [
"def",
"incr",
"(",
"self",
",",
"key",
",",
"delta",
"=",
"1",
")",
":",
"value",
"=",
"self",
".",
"get",
"(",
"key",
")",
"if",
"value",
"is",
"None",
":",
"raise",
"ValueError",
"(",
"\"Key '%s' not found\"",
"%",
"key",
")",
"new_value",
"=",
... | 32.181818 | 11.818182 |
def stream(self, report, callback=None):
"""Queue data for streaming
Args:
report (IOTileReport): A report object to stream to a client
callback (callable): An optional callback that will be called with
a bool value of True when this report actually gets streamed... | [
"def",
"stream",
"(",
"self",
",",
"report",
",",
"callback",
"=",
"None",
")",
":",
"conn_id",
"=",
"self",
".",
"_find_connection",
"(",
"self",
".",
"conn_string",
")",
"if",
"isinstance",
"(",
"report",
",",
"BroadcastReport",
")",
":",
"self",
".",
... | 43.3 | 25.2 |
def ComplementMembership(*args, **kwargs):
"""Change (x not in y) to not(x in y)."""
return ast.Complement(
ast.Membership(*args, **kwargs), **kwargs) | [
"def",
"ComplementMembership",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"ast",
".",
"Complement",
"(",
"ast",
".",
"Membership",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
",",
"*",
"*",
"kwargs",
")"
] | 40.75 | 6.5 |
def label_for(self, name):
'''Get a human readable label for a method given its name'''
method = getattr(self, name)
if method.__doc__ and method.__doc__.strip():
return method.__doc__.strip().splitlines()[0]
return humanize(name.replace(self._prefix, '')) | [
"def",
"label_for",
"(",
"self",
",",
"name",
")",
":",
"method",
"=",
"getattr",
"(",
"self",
",",
"name",
")",
"if",
"method",
".",
"__doc__",
"and",
"method",
".",
"__doc__",
".",
"strip",
"(",
")",
":",
"return",
"method",
".",
"__doc__",
".",
... | 49.166667 | 15.166667 |
def adapters(self, adapters):
"""
Sets the number of Ethernet adapters for this QEMU VM.
:param adapters: number of adapters
"""
self._ethernet_adapters.clear()
for adapter_number in range(0, adapters):
self._ethernet_adapters.append(EthernetAdapter())
... | [
"def",
"adapters",
"(",
"self",
",",
"adapters",
")",
":",
"self",
".",
"_ethernet_adapters",
".",
"clear",
"(",
")",
"for",
"adapter_number",
"in",
"range",
"(",
"0",
",",
"adapters",
")",
":",
"self",
".",
"_ethernet_adapters",
".",
"append",
"(",
"Eth... | 46.785714 | 29.785714 |
def student_t_approx(optimize=True, plot=True):
"""
Example of regressing with a student t likelihood using Laplace
"""
real_std = 0.1
#Start a function, any function
X = np.linspace(0.0, np.pi*2, 100)[:, None]
Y = np.sin(X) + np.random.randn(*X.shape)*real_std
Y = Y/Y.max()
Yc = Y.c... | [
"def",
"student_t_approx",
"(",
"optimize",
"=",
"True",
",",
"plot",
"=",
"True",
")",
":",
"real_std",
"=",
"0.1",
"#Start a function, any function",
"X",
"=",
"np",
".",
"linspace",
"(",
"0.0",
",",
"np",
".",
"pi",
"*",
"2",
",",
"100",
")",
"[",
... | 30.267241 | 18.439655 |
def _get_directory_path(context):
"""Get the storage path fro the output."""
path = os.path.join(settings.BASE_PATH, 'store')
path = context.params.get('path', path)
path = os.path.join(path, context.crawler.name)
path = os.path.abspath(os.path.expandvars(path))
try:
os.makedirs(path)
... | [
"def",
"_get_directory_path",
"(",
"context",
")",
":",
"path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"settings",
".",
"BASE_PATH",
",",
"'store'",
")",
"path",
"=",
"context",
".",
"params",
".",
"get",
"(",
"'path'",
",",
"path",
")",
"path",
"... | 32.545455 | 14.909091 |
def Geometric(p, tag=None):
"""
A Geometric random variate
Parameters
----------
p : scalar
The probability of success
"""
assert (
0 < p < 1
), 'Geometric probability "p" must be between zero and one, non-inclusive'
return uv(ss.geom(p), tag=tag) | [
"def",
"Geometric",
"(",
"p",
",",
"tag",
"=",
"None",
")",
":",
"assert",
"(",
"0",
"<",
"p",
"<",
"1",
")",
",",
"'Geometric probability \"p\" must be between zero and one, non-inclusive'",
"return",
"uv",
"(",
"ss",
".",
"geom",
"(",
"p",
")",
",",
"tag... | 22.461538 | 18.307692 |
def initialize():
"""Initializes the WINDLL resource and populated the CSBI class variable."""
_WindowsCSBI._define_csbi()
_WindowsCSBI.HANDLE_STDERR = _WindowsCSBI.HANDLE_STDERR or _WindowsCSBI.WINDLL.kernel32.GetStdHandle(-12)
_WindowsCSBI.HANDLE_STDOUT = _WindowsCSBI.HANDLE_STDOUT or ... | [
"def",
"initialize",
"(",
")",
":",
"_WindowsCSBI",
".",
"_define_csbi",
"(",
")",
"_WindowsCSBI",
".",
"HANDLE_STDERR",
"=",
"_WindowsCSBI",
".",
"HANDLE_STDERR",
"or",
"_WindowsCSBI",
".",
"WINDLL",
".",
"kernel32",
".",
"GetStdHandle",
"(",
"-",
"12",
")",
... | 62.142857 | 36.285714 |
def model_counts_map(self, name=None, exclude=None, use_mask=False):
"""Return the model expectation map for a single source, a set
of sources, or all sources in the ROI. The map will be
computed using the current model parameters.
Parameters
----------
name : str
... | [
"def",
"model_counts_map",
"(",
"self",
",",
"name",
"=",
"None",
",",
"exclude",
"=",
"None",
",",
"use_mask",
"=",
"False",
")",
":",
"if",
"self",
".",
"projtype",
"==",
"\"WCS\"",
":",
"v",
"=",
"pyLike",
".",
"FloatVector",
"(",
"self",
".",
"np... | 39.869159 | 21.280374 |
def _getphoto_originalsize(self,pid):
"""Asks flickr for photo original size
returns tuple with width,height
"""
logger.debug('%s - Getting original size from flickr'%(pid))
width=None
height=None
resp=self.flickr.photos_getSizes(photo_id=pid)
if resp.a... | [
"def",
"_getphoto_originalsize",
"(",
"self",
",",
"pid",
")",
":",
"logger",
".",
"debug",
"(",
"'%s - Getting original size from flickr'",
"%",
"(",
"pid",
")",
")",
"width",
"=",
"None",
"height",
"=",
"None",
"resp",
"=",
"self",
".",
"flickr",
".",
"p... | 34.958333 | 16.5 |
def timecds2datetime(tcds):
"""Method for converting time_cds-variables to datetime-objectsself.
Works both with a dictionary and a numpy record_array.
"""
days = int(tcds['Days'])
milliseconds = int(tcds['Milliseconds'])
try:
microseconds = int(tcds['Microseconds'])
except (KeyErro... | [
"def",
"timecds2datetime",
"(",
"tcds",
")",
":",
"days",
"=",
"int",
"(",
"tcds",
"[",
"'Days'",
"]",
")",
"milliseconds",
"=",
"int",
"(",
"tcds",
"[",
"'Milliseconds'",
"]",
")",
"try",
":",
"microseconds",
"=",
"int",
"(",
"tcds",
"[",
"'Microsecon... | 30.047619 | 16.857143 |
def safe_pdist(arr, *args, **kwargs):
"""
Kwargs:
metric = ut.absdiff
SeeAlso:
scipy.spatial.distance.pdist
TODO: move to vtool
"""
if arr is None or len(arr) < 2:
return None
else:
import vtool as vt
arr_ = vt.atleast_nd(arr, 2)
return spdis... | [
"def",
"safe_pdist",
"(",
"arr",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"arr",
"is",
"None",
"or",
"len",
"(",
"arr",
")",
"<",
"2",
":",
"return",
"None",
"else",
":",
"import",
"vtool",
"as",
"vt",
"arr_",
"=",
"vt",
".",
... | 20.9375 | 16.1875 |
def to_html(self):
"""Render a Heading MessageElement as html
:returns: The html representation of the Heading MessageElement.
:rtype: str
"""
if self.text is None:
return
level = self.level
if level > 6:
level = 6
return '<h%s%s>... | [
"def",
"to_html",
"(",
"self",
")",
":",
"if",
"self",
".",
"text",
"is",
"None",
":",
"return",
"level",
"=",
"self",
".",
"level",
"if",
"level",
">",
"6",
":",
"level",
"=",
"6",
"return",
"'<h%s%s><a id=\"%s\"></a>%s%s</h%s>'",
"%",
"(",
"level",
"... | 26.210526 | 17.526316 |
def head(self, url):
'''head request, typically used for status code retrieval, etc.
'''
bot.debug('HEAD %s' %url)
return self._call(url, func=requests.head) | [
"def",
"head",
"(",
"self",
",",
"url",
")",
":",
"bot",
".",
"debug",
"(",
"'HEAD %s'",
"%",
"url",
")",
"return",
"self",
".",
"_call",
"(",
"url",
",",
"func",
"=",
"requests",
".",
"head",
")"
] | 33.8 | 19.4 |
def append_known_secrets(self): # type: () -> None
"""
Read key-value pair files with secrets. For example, .conf and .ini files.
:return:
"""
for file_name in self.files:
if "~" in file_name:
file_name = os.path.expanduser(file_name)
if n... | [
"def",
"append_known_secrets",
"(",
"self",
")",
":",
"# type: () -> None",
"for",
"file_name",
"in",
"self",
".",
"files",
":",
"if",
"\"~\"",
"in",
"file_name",
":",
"file_name",
"=",
"os",
".",
"path",
".",
"expanduser",
"(",
"file_name",
")",
"if",
"no... | 40.173913 | 14.434783 |
def _generate_result(self, res_type, channel, result):
"""Generate the result object"""
schema = self.api.ws_result_schema()
schema.context['channel'] = channel
schema.context['response_type'] = res_type
self.callback(schema.load(result), self.context) | [
"def",
"_generate_result",
"(",
"self",
",",
"res_type",
",",
"channel",
",",
"result",
")",
":",
"schema",
"=",
"self",
".",
"api",
".",
"ws_result_schema",
"(",
")",
"schema",
".",
"context",
"[",
"'channel'",
"]",
"=",
"channel",
"schema",
".",
"conte... | 47.833333 | 7.833333 |
def pairwise_dxy(pos, gac, start=None, stop=None, is_accessible=None):
"""Convenience function to calculate a pairwise distance matrix using
nucleotide divergence (a.k.a. Dxy) as the distance metric.
Parameters
----------
pos : array_like, int, shape (n_variants,)
Variant positions.
gac... | [
"def",
"pairwise_dxy",
"(",
"pos",
",",
"gac",
",",
"start",
"=",
"None",
",",
"stop",
"=",
"None",
",",
"is_accessible",
"=",
"None",
")",
":",
"if",
"not",
"isinstance",
"(",
"pos",
",",
"SortedIndex",
")",
":",
"pos",
"=",
"SortedIndex",
"(",
"pos... | 32.73913 | 19.173913 |
def _kill_worker_threads(self):
""" Kill any currently executing worker threads.
See :meth:`ServiceContainer.spawn_worker`
"""
num_workers = len(self._worker_threads)
if num_workers:
_log.warning('killing %s active workers(s)', num_workers)
for worker_ct... | [
"def",
"_kill_worker_threads",
"(",
"self",
")",
":",
"num_workers",
"=",
"len",
"(",
"self",
".",
"_worker_threads",
")",
"if",
"num_workers",
":",
"_log",
".",
"warning",
"(",
"'killing %s active workers(s)'",
",",
"num_workers",
")",
"for",
"worker_ctx",
",",... | 37.666667 | 18.916667 |
def sqlalch_datetime(dt):
"""Convert a SQLAlchemy datetime string to a datetime object."""
if isinstance(dt, str):
return datetime.strptime(dt, "%Y-%m-%d %H:%M:%S.%f").replace(tzinfo=UTC)
if dt.tzinfo is not None and dt.tzinfo.utcoffset(dt) is not None:
return dt.astimezone(UTC)
return d... | [
"def",
"sqlalch_datetime",
"(",
"dt",
")",
":",
"if",
"isinstance",
"(",
"dt",
",",
"str",
")",
":",
"return",
"datetime",
".",
"strptime",
"(",
"dt",
",",
"\"%Y-%m-%d %H:%M:%S.%f\"",
")",
".",
"replace",
"(",
"tzinfo",
"=",
"UTC",
")",
"if",
"dt",
"."... | 47.857143 | 15.857143 |
def partition_horizontal_twice(thelist, numbers):
"""
numbers is split on a comma to n and n2.
Break a list into peices each peice alternating between n and n2 items long
``partition_horizontal_twice(range(14), "3,4")`` gives::
[[0, 1, 2],
[3, 4, 5, 6],
[7, 8, 9],
... | [
"def",
"partition_horizontal_twice",
"(",
"thelist",
",",
"numbers",
")",
":",
"n",
",",
"n2",
"=",
"numbers",
".",
"split",
"(",
"','",
")",
"try",
":",
"n",
"=",
"int",
"(",
"n",
")",
"n2",
"=",
"int",
"(",
"n2",
")",
"thelist",
"=",
"list",
"(... | 26.37037 | 16.592593 |
def _check_timeindex(self):
"""
Check function to check if all feed-in and load time series contain
values for the specified time index.
"""
try:
self.timeseries.generation_fluctuating
self.timeseries.generation_dispatchable
self.timeseries.lo... | [
"def",
"_check_timeindex",
"(",
"self",
")",
":",
"try",
":",
"self",
".",
"timeseries",
".",
"generation_fluctuating",
"self",
".",
"timeseries",
".",
"generation_dispatchable",
"self",
".",
"timeseries",
".",
"load",
"self",
".",
"timeseries",
".",
"generation... | 35.588235 | 14.411765 |
def init():
"""Initialize the pipeline in maya so everything works
Init environment and load plugins.
This also creates the initial Jukebox Menu entry.
:returns: None
:rtype: None
:raises: None
"""
main.init_environment()
pluginpath = os.pathsep.join((os.environ.get('JUKEBOX_PLUGIN... | [
"def",
"init",
"(",
")",
":",
"main",
".",
"init_environment",
"(",
")",
"pluginpath",
"=",
"os",
".",
"pathsep",
".",
"join",
"(",
"(",
"os",
".",
"environ",
".",
"get",
"(",
"'JUKEBOX_PLUGIN_PATH'",
",",
"''",
")",
",",
"BUILTIN_PLUGIN_PATH",
")",
")... | 35.692308 | 19.423077 |
def cubes():
""" Get a listing of all publicly available cubes. """
cubes = []
for cube in get_manager().list_cubes():
cubes.append({
'name': cube
})
return jsonify({
'status': 'ok',
'data': cubes
}) | [
"def",
"cubes",
"(",
")",
":",
"cubes",
"=",
"[",
"]",
"for",
"cube",
"in",
"get_manager",
"(",
")",
".",
"list_cubes",
"(",
")",
":",
"cubes",
".",
"append",
"(",
"{",
"'name'",
":",
"cube",
"}",
")",
"return",
"jsonify",
"(",
"{",
"'status'",
"... | 23 | 19.181818 |
def parse_string(s):
"""Parse a string with units and try to make a bitmath object out of
it.
String inputs may include whitespace characters between the value and
the unit.
"""
# Strings only please
if not isinstance(s, (str, unicode)):
raise ValueError("parse_string only accepts string inputs... | [
"def",
"parse_string",
"(",
"s",
")",
":",
"# Strings only please",
"if",
"not",
"isinstance",
"(",
"s",
",",
"(",
"str",
",",
"unicode",
")",
")",
":",
"raise",
"ValueError",
"(",
"\"parse_string only accepts string inputs but a %s was given\"",
"%",
"type",
"(",... | 33.146341 | 25.073171 |
def report(self, simulation, state):
"""Generate a report.
Parameters
----------
simulation : Simulation
The Simulation to generate a report for
state : State
The current state of the simulation
"""
if not self._initialized:
se... | [
"def",
"report",
"(",
"self",
",",
"simulation",
",",
"state",
")",
":",
"if",
"not",
"self",
".",
"_initialized",
":",
"self",
".",
"_initial_clock_time",
"=",
"datetime",
".",
"now",
"(",
")",
"self",
".",
"_initial_simulation_time",
"=",
"state",
".",
... | 40.542857 | 18.885714 |
def get_random_distorted_bottlenecks(
sess, image_lists, how_many, category, image_dir, input_jpeg_tensor,
distorted_image, resized_input_tensor, bottleneck_tensor):
"""Retrieves bottleneck values for training images, after distortions.
If we're training with distortions like crops, scales, or flips, we ha... | [
"def",
"get_random_distorted_bottlenecks",
"(",
"sess",
",",
"image_lists",
",",
"how_many",
",",
"category",
",",
"image_dir",
",",
"input_jpeg_tensor",
",",
"distorted_image",
",",
"resized_input_tensor",
",",
"bottleneck_tensor",
")",
":",
"class_count",
"=",
"len"... | 48.88 | 21.26 |
def get_rows_to_keep(gctoo, rid=None, row_bool=None, ridx=None, exclude_rid=None):
""" Figure out based on the possible row inputs which rows to keep.
Args:
gctoo (GCToo object):
rid (list of strings):
row_bool (boolean array):
ridx (list of integers):
exclude_rid (list ... | [
"def",
"get_rows_to_keep",
"(",
"gctoo",
",",
"rid",
"=",
"None",
",",
"row_bool",
"=",
"None",
",",
"ridx",
"=",
"None",
",",
"exclude_rid",
"=",
"None",
")",
":",
"# Use rid if provided",
"if",
"rid",
"is",
"not",
"None",
":",
"assert",
"type",
"(",
... | 35.491525 | 24.338983 |
def segment_radii(neurites, neurite_type=NeuriteType.all):
'''arithmetic mean of the radii of the points in segments in a collection of neurites'''
def _seg_radii(sec):
'''vectorized mean radii'''
pts = sec.points[:, COLS.R]
return np.divide(np.add(pts[:-1], pts[1:]), 2.0)
return ma... | [
"def",
"segment_radii",
"(",
"neurites",
",",
"neurite_type",
"=",
"NeuriteType",
".",
"all",
")",
":",
"def",
"_seg_radii",
"(",
"sec",
")",
":",
"'''vectorized mean radii'''",
"pts",
"=",
"sec",
".",
"points",
"[",
":",
",",
"COLS",
".",
"R",
"]",
"ret... | 44.875 | 21.375 |
def kde_partition_data(data, estimate_tails=True):
"""Convenience method for building a partition and weights using a gaussian Kernel Density Estimate and default bandwidth.
Args:
data (list-like): The data from which to construct the estimate
estimate_tails (bool): Whether to estimate the tail... | [
"def",
"kde_partition_data",
"(",
"data",
",",
"estimate_tails",
"=",
"True",
")",
":",
"kde",
"=",
"stats",
".",
"kde",
".",
"gaussian_kde",
"(",
"data",
")",
"evaluation_bins",
"=",
"np",
".",
"linspace",
"(",
"start",
"=",
"np",
".",
"min",
"(",
"da... | 41.756757 | 28.810811 |
async def fetch_batch(self, request):
"""Fetches a specific batch from the validator, specified by id.
Request:
path:
- batch_id: The 128-character id of the batch to be fetched
Response:
data: A JSON object with the data from the fully expanded Batch
... | [
"async",
"def",
"fetch_batch",
"(",
"self",
",",
"request",
")",
":",
"error_traps",
"=",
"[",
"error_handlers",
".",
"BatchNotFoundTrap",
"]",
"batch_id",
"=",
"request",
".",
"match_info",
".",
"get",
"(",
"'batch_id'",
",",
"''",
")",
"self",
".",
"_val... | 35.423077 | 19.846154 |
def convert_inline_formula_elements(self):
"""
<inline-formula> elements must be converted to be conforming
These elements may contain <inline-graphic> elements, textual content,
or both.
"""
for inline in self.main.getroot().findall('.//inline-formula'):
#in... | [
"def",
"convert_inline_formula_elements",
"(",
"self",
")",
":",
"for",
"inline",
"in",
"self",
".",
"main",
".",
"getroot",
"(",
")",
".",
"findall",
"(",
"'.//inline-formula'",
")",
":",
"#inline-formula elements will be modified in situ",
"remove_all_attributes",
"... | 48.935484 | 16.806452 |
def lonlat2xyz(lon, lat):
"""Convert lon lat to cartesian."""
lat = xu.deg2rad(lat)
lon = xu.deg2rad(lon)
x = xu.cos(lat) * xu.cos(lon)
y = xu.cos(lat) * xu.sin(lon)
z = xu.sin(lat)
return x, y, z | [
"def",
"lonlat2xyz",
"(",
"lon",
",",
"lat",
")",
":",
"lat",
"=",
"xu",
".",
"deg2rad",
"(",
"lat",
")",
"lon",
"=",
"xu",
".",
"deg2rad",
"(",
"lon",
")",
"x",
"=",
"xu",
".",
"cos",
"(",
"lat",
")",
"*",
"xu",
".",
"cos",
"(",
"lon",
")"... | 27.125 | 12.75 |
def get_raw_record(self, instance, update_fields=None):
"""
Gets the raw record.
If `update_fields` is set, the raw record will be build with only
the objectID and the given fields. Also, `_geoloc` and `_tags` will
not be included.
"""
tmp = {'objectID': self.obj... | [
"def",
"get_raw_record",
"(",
"self",
",",
"instance",
",",
"update_fields",
"=",
"None",
")",
":",
"tmp",
"=",
"{",
"'objectID'",
":",
"self",
".",
"objectID",
"(",
"instance",
")",
"}",
"if",
"update_fields",
":",
"if",
"isinstance",
"(",
"update_fields"... | 36.357143 | 17.642857 |
def repo(
state, host, name, baseurl,
present=True, description=None, enabled=True, gpgcheck=True, gpgkey=None,
):
'''
Add/remove/update yum repositories.
+ name: filename for the repo (in ``/etc/yum/repos.d/``)
+ baseurl: the baseurl of the repo
+ present: whether the ``.repo`` file should... | [
"def",
"repo",
"(",
"state",
",",
"host",
",",
"name",
",",
"baseurl",
",",
"present",
"=",
"True",
",",
"description",
"=",
"None",
",",
"enabled",
"=",
"True",
",",
"gpgcheck",
"=",
"True",
",",
"gpgkey",
"=",
"None",
",",
")",
":",
"# Description ... | 29.302326 | 20.046512 |
def _validate_inputs(self, inputdict):
""" Validate input links.
"""
# Check inputdict
try:
parameters = inputdict.pop(self.get_linkname('parameters'))
except KeyError:
raise InputValidationError("No parameters specified for this "
... | [
"def",
"_validate_inputs",
"(",
"self",
",",
"inputdict",
")",
":",
"# Check inputdict",
"try",
":",
"parameters",
"=",
"inputdict",
".",
"pop",
"(",
"self",
".",
"get_linkname",
"(",
"'parameters'",
")",
")",
"except",
"KeyError",
":",
"raise",
"InputValidati... | 40.209302 | 19.976744 |
def regions(self):
"""gets the regions value"""
url = "%s/regions" % self.root
params = {"f": "json"}
return self._get(url=url,
param_dict=params,
proxy_url=self._proxy_url,
proxy_port=self._proxy_port) | [
"def",
"regions",
"(",
"self",
")",
":",
"url",
"=",
"\"%s/regions\"",
"%",
"self",
".",
"root",
"params",
"=",
"{",
"\"f\"",
":",
"\"json\"",
"}",
"return",
"self",
".",
"_get",
"(",
"url",
"=",
"url",
",",
"param_dict",
"=",
"params",
",",
"proxy_u... | 38.875 | 9.625 |
def ask_password(*question: Token) -> str:
"""Ask the user to enter a password.
"""
tokens = get_ask_tokens(question)
info(*tokens)
answer = read_password()
return answer | [
"def",
"ask_password",
"(",
"*",
"question",
":",
"Token",
")",
"->",
"str",
":",
"tokens",
"=",
"get_ask_tokens",
"(",
"question",
")",
"info",
"(",
"*",
"tokens",
")",
"answer",
"=",
"read_password",
"(",
")",
"return",
"answer"
] | 26.857143 | 9 |
def _to_representation(self, instance):
"""Uncached `to_representation`."""
if self.enable_optimization:
representation = self._faster_to_representation(instance)
else:
representation = super(
WithDynamicSerializerMixin,
self
)... | [
"def",
"_to_representation",
"(",
"self",
",",
"instance",
")",
":",
"if",
"self",
".",
"enable_optimization",
":",
"representation",
"=",
"self",
".",
"_faster_to_representation",
"(",
"instance",
")",
"else",
":",
"representation",
"=",
"super",
"(",
"WithDyna... | 31.16129 | 16.677419 |
def draw(self,
category,
num_top_words_to_annotate=4,
words_to_annotate=[],
scores=None,
transform=percentile_alphabetical):
'''Outdated. MPLD3 drawing.
Parameters
----------
category
num_top_words_to_annotate
... | [
"def",
"draw",
"(",
"self",
",",
"category",
",",
"num_top_words_to_annotate",
"=",
"4",
",",
"words_to_annotate",
"=",
"[",
"]",
",",
"scores",
"=",
"None",
",",
"transform",
"=",
"percentile_alphabetical",
")",
":",
"try",
":",
"import",
"matplotlib",
".",... | 41.095238 | 20.928571 |
def actor2ImageData(actor, spacing=(1, 1, 1)):
"""
Convert a mesh it into volume representation as ``vtkImageData``
where the foreground (exterior) voxels are 1 and the background
(interior) voxels are 0.
Internally the ``vtkPolyDataToImageStencil`` class is used.
.. hint:: |mesh2volume| |mesh2... | [
"def",
"actor2ImageData",
"(",
"actor",
",",
"spacing",
"=",
"(",
"1",
",",
"1",
",",
"1",
")",
")",
":",
"# https://vtk.org/Wiki/VTK/Examples/Cxx/PolyData/PolyDataToImageData",
"pd",
"=",
"actor",
".",
"polydata",
"(",
")",
"whiteImage",
"=",
"vtk",
".",
"vtk... | 33.425926 | 16.87037 |
def gzip_open_text(path, encoding=None):
"""Opens a plain-text file that may be gzip'ed.
Parameters
----------
path : str
The file.
encoding : str, optional
The encoding to use.
Returns
-------
file-like
A file-like object.
Notes
-----
Generally, re... | [
"def",
"gzip_open_text",
"(",
"path",
",",
"encoding",
"=",
"None",
")",
":",
"if",
"encoding",
"is",
"None",
":",
"encoding",
"=",
"sys",
".",
"getdefaultencoding",
"(",
")",
"assert",
"os",
".",
"path",
".",
"isfile",
"(",
"path",
")",
"is_compressed",... | 22.795918 | 22.591837 |
def LateBind(self, target=None):
"""Bind the field descriptor to the owner once the target is defined."""
self.type = target
self._GetPrimitiveEncoder()
# Now re-add the descriptor to the owner protobuf.
self.late_bound = False
self.owner.AddDescriptor(self) | [
"def",
"LateBind",
"(",
"self",
",",
"target",
"=",
"None",
")",
":",
"self",
".",
"type",
"=",
"target",
"self",
".",
"_GetPrimitiveEncoder",
"(",
")",
"# Now re-add the descriptor to the owner protobuf.",
"self",
".",
"late_bound",
"=",
"False",
"self",
".",
... | 34.5 | 13.5 |
def send_until(self,
send,
regexps,
not_there=False,
cadence=2,
retries=100,
echo=None,
note=None,
debug_command=None,
pause_point_on_fail=True,
nonewline=False... | [
"def",
"send_until",
"(",
"self",
",",
"send",
",",
"regexps",
",",
"not_there",
"=",
"False",
",",
"cadence",
"=",
"2",
",",
"retries",
"=",
"100",
",",
"echo",
"=",
"None",
",",
"note",
"=",
"None",
",",
"debug_command",
"=",
"None",
",",
"pause_po... | 41.472222 | 17.611111 |
def plotGenCost(generators):
""" Plots the costs of the given generators.
"""
figure()
plots = []
for generator in generators:
if generator.pcost_model == PW_LINEAR:
x = [x for x, _ in generator.p_cost]
y = [y for _, y in generator.p_cost]
elif generator.pcost... | [
"def",
"plotGenCost",
"(",
"generators",
")",
":",
"figure",
"(",
")",
"plots",
"=",
"[",
"]",
"for",
"generator",
"in",
"generators",
":",
"if",
"generator",
".",
"pcost_model",
"==",
"PW_LINEAR",
":",
"x",
"=",
"[",
"x",
"for",
"x",
",",
"_",
"in",... | 33.105263 | 14.631579 |
def populate_timestamps(self,update_header=False):
""" Populate time axis.
IF update_header then only return tstart
"""
#Check to see how many integrations requested
ii_start, ii_stop = 0, self.n_ints_in_file
if self.t_start:
ii_start = self.t_start
... | [
"def",
"populate_timestamps",
"(",
"self",
",",
"update_header",
"=",
"False",
")",
":",
"#Check to see how many integrations requested",
"ii_start",
",",
"ii_stop",
"=",
"0",
",",
"self",
".",
"n_ints_in_file",
"if",
"self",
".",
"t_start",
":",
"ii_start",
"=",
... | 30.318182 | 17.727273 |
def _set_preferences(self, node):
'''
Set preferences.
:return:
'''
pref = etree.SubElement(node, 'preferences')
pacman = etree.SubElement(pref, 'packagemanager')
pacman.text = self._get_package_manager()
p_version = etree.SubElement(pref, 'version')
... | [
"def",
"_set_preferences",
"(",
"self",
",",
"node",
")",
":",
"pref",
"=",
"etree",
".",
"SubElement",
"(",
"node",
",",
"'preferences'",
")",
"pacman",
"=",
"etree",
".",
"SubElement",
"(",
"pref",
",",
"'packagemanager'",
")",
"pacman",
".",
"text",
"... | 35.259259 | 18.888889 |
def get_resource_ids_by_bins(self, bin_ids):
"""Gets the list of ``Resource Ids`` corresponding to a list of ``Bin`` objects.
arg: bin_ids (osid.id.IdList): list of bin ``Ids``
return: (osid.id.IdList) - list of resource ``Ids``
raise: NullArgument - ``bin_ids`` is ``null``
... | [
"def",
"get_resource_ids_by_bins",
"(",
"self",
",",
"bin_ids",
")",
":",
"# Implemented from template for",
"# osid.resource.ResourceBinSession.get_resource_ids_by_bins",
"id_list",
"=",
"[",
"]",
"for",
"resource",
"in",
"self",
".",
"get_resources_by_bins",
"(",
"bin_ids... | 44.764706 | 16.705882 |
def sendIq(self, entity):
"""
:type entity: IqProtocolEntity
"""
if entity.getType() == IqProtocolEntity.TYPE_SET and entity.getXmlns() == "w:m":
#media upload!
self._sendIq(entity, self.onRequestUploadSuccess, self.onRequestUploadError) | [
"def",
"sendIq",
"(",
"self",
",",
"entity",
")",
":",
"if",
"entity",
".",
"getType",
"(",
")",
"==",
"IqProtocolEntity",
".",
"TYPE_SET",
"and",
"entity",
".",
"getXmlns",
"(",
")",
"==",
"\"w:m\"",
":",
"#media upload!",
"self",
".",
"_sendIq",
"(",
... | 41 | 18.142857 |
def get_args():
"""Get the script arguments."""
description = "wal - Generate colorschemes on the fly"
arg = argparse.ArgumentParser(description=description)
arg.add_argument("-a", metavar="\"alpha\"",
help="Set terminal background transparency. \
*Only w... | [
"def",
"get_args",
"(",
")",
":",
"description",
"=",
"\"wal - Generate colorschemes on the fly\"",
"arg",
"=",
"argparse",
".",
"ArgumentParser",
"(",
"description",
"=",
"description",
")",
"arg",
".",
"add_argument",
"(",
"\"-a\"",
",",
"metavar",
"=",
"\"\\\"a... | 39.594595 | 23.743243 |
def search_database(word):
'''offline search.'''
conn = sqlite3.connect(os.path.join(DEFAULT_PATH, 'word.db'))
curs = conn.cursor()
curs.execute(r'SELECT expl, pr FROM Word WHERE name LIKE "%s%%"' % word)
res = curs.fetchall()
if res:
print(colored(word + ' 在数据库中存在', 'white', 'on_green'... | [
"def",
"search_database",
"(",
"word",
")",
":",
"conn",
"=",
"sqlite3",
".",
"connect",
"(",
"os",
".",
"path",
".",
"join",
"(",
"DEFAULT_PATH",
",",
"'word.db'",
")",
")",
"curs",
"=",
"conn",
".",
"cursor",
"(",
")",
"curs",
".",
"execute",
"(",
... | 38.666667 | 22.666667 |
def is_iterable(val):
"""
Check if val is not a list, but is a collections.Iterable type. This is used to determine
when list() should be called on val
>>> l = [1, 2]
>>> is_iterable(l)
False
>>> is_iterable(iter(l))
True
:param val: value to check
:return: True if it is not a ... | [
"def",
"is_iterable",
"(",
"val",
")",
":",
"if",
"isinstance",
"(",
"val",
",",
"list",
")",
":",
"return",
"False",
"return",
"isinstance",
"(",
"val",
",",
"collections",
".",
"Iterable",
")"
] | 26.294118 | 20.294118 |
def Parse(self, persistence, knowledge_base, download_pathtype):
"""Convert persistence collector output to downloadable rdfvalues."""
pathspecs = []
if isinstance(persistence, rdf_client.WindowsServiceInformation):
if persistence.HasField("binary"):
pathspecs.append(persistence.binary.pathsp... | [
"def",
"Parse",
"(",
"self",
",",
"persistence",
",",
"knowledge_base",
",",
"download_pathtype",
")",
":",
"pathspecs",
"=",
"[",
"]",
"if",
"isinstance",
"(",
"persistence",
",",
"rdf_client",
".",
"WindowsServiceInformation",
")",
":",
"if",
"persistence",
... | 44.263158 | 22.947368 |
def stress_positions(stress: str, scansion: str) -> List[int]:
"""
Given a stress value and a scansion line, return the index positions of the stresses.
:param stress:
:param scansion:
:return:
>>> stress_positions("-", " - U U - UU - U U")
[0, 3, 6]
"""
line = scansion.re... | [
"def",
"stress_positions",
"(",
"stress",
":",
"str",
",",
"scansion",
":",
"str",
")",
"->",
"List",
"[",
"int",
"]",
":",
"line",
"=",
"scansion",
".",
"replace",
"(",
"\" \"",
",",
"\"\"",
")",
"stresses",
"=",
"[",
"]",
"for",
"idx",
",",
"char... | 26.705882 | 20 |
def count_features_type(features):
""" Counts three different types of features (float, integer, binary).
:param features: pandas.DataFrame
A dataset in a panda's data frame
:returns a tuple (binary, integer, float)
"""
counter={k.name: v for k, v in features.columns.to_series().groupby(... | [
"def",
"count_features_type",
"(",
"features",
")",
":",
"counter",
"=",
"{",
"k",
".",
"name",
":",
"v",
"for",
"k",
",",
"v",
"in",
"features",
".",
"columns",
".",
"to_series",
"(",
")",
".",
"groupby",
"(",
"features",
".",
"dtypes",
")",
"}",
... | 54.615385 | 21.769231 |
def polygon(self):
'''return a polygon for the fence'''
points = []
for fp in self.points[1:]:
points.append((fp.lat, fp.lng))
return points | [
"def",
"polygon",
"(",
"self",
")",
":",
"points",
"=",
"[",
"]",
"for",
"fp",
"in",
"self",
".",
"points",
"[",
"1",
":",
"]",
":",
"points",
".",
"append",
"(",
"(",
"fp",
".",
"lat",
",",
"fp",
".",
"lng",
")",
")",
"return",
"points"
] | 33.833333 | 12.5 |
def create_from_byte(control_flags):
"""Create a ControlFlags class from a control flags byte."""
in_use = bool(control_flags & 1 << 7)
controller = bool(control_flags & 1 << 6)
bit5 = bool(control_flags & 1 << 5)
bit4 = bool(control_flags & 1 << 4)
used_before = bool(con... | [
"def",
"create_from_byte",
"(",
"control_flags",
")",
":",
"in_use",
"=",
"bool",
"(",
"control_flags",
"&",
"1",
"<<",
"7",
")",
"controller",
"=",
"bool",
"(",
"control_flags",
"&",
"1",
"<<",
"6",
")",
"bit5",
"=",
"bool",
"(",
"control_flags",
"&",
... | 46.5 | 8.5 |
def requests(self, code=None, **kwargs):
"""
Retrieve open requests. You can also enter a specific service code
argument.
>>> Three('api.city.gov').requests()
{'all': {'requests': 'data'}}
>>> Three('api.city.gov').requests('123')
{'123': {'requests': 'data'}}
... | [
"def",
"requests",
"(",
"self",
",",
"code",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"code",
":",
"kwargs",
"[",
"'service_code'",
"]",
"=",
"code",
"data",
"=",
"self",
".",
"get",
"(",
"'requests'",
",",
"*",
"*",
"kwargs",
")",
"... | 31.5 | 11.928571 |
def query_bankcard(self, out_trade_no):
"""
企业付款查询接口
:param out_trade_no: 商户调用企业付款API时使用的商户订单号
:return: 返回的结果数据
"""
data = {
'mch_id': self.mch_id,
'partner_trade_no': out_trade_no,
}
return self._post('mmpaysptrans/query_bank', da... | [
"def",
"query_bankcard",
"(",
"self",
",",
"out_trade_no",
")",
":",
"data",
"=",
"{",
"'mch_id'",
":",
"self",
".",
"mch_id",
",",
"'partner_trade_no'",
":",
"out_trade_no",
",",
"}",
"return",
"self",
".",
"_post",
"(",
"'mmpaysptrans/query_bank'",
",",
"d... | 26.416667 | 14.916667 |
def point_line_distance(p, l_p, l_v):
'''Calculate the distance between a point and a line defined
by a point and a direction vector.
'''
l_v = normalize(l_v)
u = p - l_p
return np.linalg.norm(u - np.dot(u, l_v) * l_v) | [
"def",
"point_line_distance",
"(",
"p",
",",
"l_p",
",",
"l_v",
")",
":",
"l_v",
"=",
"normalize",
"(",
"l_v",
")",
"u",
"=",
"p",
"-",
"l_p",
"return",
"np",
".",
"linalg",
".",
"norm",
"(",
"u",
"-",
"np",
".",
"dot",
"(",
"u",
",",
"l_v",
... | 33.714286 | 16.285714 |
def has_verified_email(self):
"""
Has the user verified that the email he has given is legit?
Verified e-mail is required to the gallery. Confirmation happens by
sending an email to the user and the owner of the email user verifying
that he is the same as the Imgur user.
... | [
"def",
"has_verified_email",
"(",
"self",
")",
":",
"url",
"=",
"(",
"self",
".",
"_imgur",
".",
"_base_url",
"+",
"\"/3/account/{0}/\"",
"\"verifyemail\"",
".",
"format",
"(",
"self",
".",
"name",
")",
")",
"return",
"self",
".",
"_imgur",
".",
"_send_req... | 43.818182 | 18.363636 |
def lineincols (inlist,colsize):
"""
Returns a string composed of elements in inlist, with each element
right-aligned in columns of (fixed) colsize.
Usage: lineincols (inlist,colsize) where colsize is an integer
"""
outstr = ''
for item in inlist:
if type(item) != StringType:
item =... | [
"def",
"lineincols",
"(",
"inlist",
",",
"colsize",
")",
":",
"outstr",
"=",
"''",
"for",
"item",
"in",
"inlist",
":",
"if",
"type",
"(",
"item",
")",
"!=",
"StringType",
":",
"item",
"=",
"str",
"(",
"item",
")",
"size",
"=",
"len",
"(",
"item",
... | 29.473684 | 13.578947 |
def _rm_outlier_by_amp(self, params, model, signal, ii):
"""
Helper function to reject outliers based on mean amplitude
"""
maxamps = np.nanmax(np.abs(model),0)
z_score = (maxamps - np.nanmean(maxamps,0))/np.nanstd(maxamps,0)
with warnings.catch_warnings():
wa... | [
"def",
"_rm_outlier_by_amp",
"(",
"self",
",",
"params",
",",
"model",
",",
"signal",
",",
"ii",
")",
":",
"maxamps",
"=",
"np",
".",
"nanmax",
"(",
"np",
".",
"abs",
"(",
"model",
")",
",",
"0",
")",
"z_score",
"=",
"(",
"maxamps",
"-",
"np",
".... | 41.823529 | 11.235294 |
def affinity(self,affinity):
"""Set the affinity for all threads in this group.
If setting affinity fails on any thread, the affinity of all threads
is restored to its previous value.
"""
with self.__lock:
old_affinities = {}
try:
for thre... | [
"def",
"affinity",
"(",
"self",
",",
"affinity",
")",
":",
"with",
"self",
".",
"__lock",
":",
"old_affinities",
"=",
"{",
"}",
"try",
":",
"for",
"thread",
"in",
"self",
".",
"__threads",
":",
"old_affinities",
"[",
"thread",
"]",
"=",
"thread",
".",
... | 36.285714 | 14.333333 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.