text stringlengths 75 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 0.18 |
|---|---|---|---|
def _load_vertex_buffers(self):
"""Load each vertex buffer into each material"""
fd = gzip.open(cache_name(self.file_name), 'rb')
for buff in self.meta.vertex_buffers:
mat = self.wavefront.materials.get(buff['material'])
if not mat:
mat = Material(name=b... | [
"def",
"_load_vertex_buffers",
"(",
"self",
")",
":",
"fd",
"=",
"gzip",
".",
"open",
"(",
"cache_name",
"(",
"self",
".",
"file_name",
")",
",",
"'rb'",
")",
"for",
"buff",
"in",
"self",
".",
"meta",
".",
"vertex_buffers",
":",
"mat",
"=",
"self",
"... | 35.8 | 0.00363 |
def _prepare_for_submission(self, tempfolder, inputdict):
"""
Create input files.
:param tempfolder: aiida.common.folders.Folder subclass where
the plugin should put all its files.
:param inputdict: dictionary of the input nodes as they would
be r... | [
"def",
"_prepare_for_submission",
"(",
"self",
",",
"tempfolder",
",",
"inputdict",
")",
":",
"parameters",
",",
"code",
",",
"structure",
",",
"surface_sample",
"=",
"self",
".",
"_validate_inputs",
"(",
"inputdict",
")",
"# Prepare CalcInfo to be returned to aiida",... | 38.387097 | 0.002459 |
def CopyFromDateTimeString(self, time_string):
"""Copies time elements from a date and time string.
Args:
time_string (str): date and time value formatted as:
YYYY-MM-DD hh:mm:ss.######[+-]##:##
Where # are numeric digits ranging from 0 to 9 and the seconds
fraction can be ... | [
"def",
"CopyFromDateTimeString",
"(",
"self",
",",
"time_string",
")",
":",
"date_time_values",
"=",
"self",
".",
"_CopyDateTimeFromString",
"(",
"time_string",
")",
"self",
".",
"_CopyFromDateTimeValues",
"(",
"date_time_values",
")"
] | 38.066667 | 0.001709 |
def get_var_properties(self):
"""
Get some properties of the variables in the current
namespace
"""
from spyder_kernels.utils.nsview import get_remote_data
settings = self.namespace_view_settings
if settings:
ns = self._get_current_namespace()
... | [
"def",
"get_var_properties",
"(",
"self",
")",
":",
"from",
"spyder_kernels",
".",
"utils",
".",
"nsview",
"import",
"get_remote_data",
"settings",
"=",
"self",
".",
"namespace_view_settings",
"if",
"settings",
":",
"ns",
"=",
"self",
".",
"_get_current_namespace"... | 39.354839 | 0.0016 |
def cloud_cover_to_irradiance_liujordan(self, cloud_cover, **kwargs):
"""
Estimates irradiance from cloud cover in the following steps:
1. Determine transmittance using a function of cloud cover e.g.
:py:meth:`~ForecastModel.cloud_cover_to_transmittance_linear`
2. Calculate G... | [
"def",
"cloud_cover_to_irradiance_liujordan",
"(",
"self",
",",
"cloud_cover",
",",
"*",
"*",
"kwargs",
")",
":",
"# in principle, get_solarposition could use the forecast",
"# pressure, temp, etc., but the cloud cover forecast is not",
"# accurate enough to justify using these minor cor... | 39.441176 | 0.001456 |
def send(token, title, **kwargs):
"""
Site: https://boxcar.io/
API: http://help.boxcar.io/knowledgebase/topics/48115-boxcar-api
Desc: Best app for system administrators
"""
headers = {
"Content-type": "application/x-www-form-urlencoded",
"User-Agent": "DBMail/%s" % get_version(),... | [
"def",
"send",
"(",
"token",
",",
"title",
",",
"*",
"*",
"kwargs",
")",
":",
"headers",
"=",
"{",
"\"Content-type\"",
":",
"\"application/x-www-form-urlencoded\"",
",",
"\"User-Agent\"",
":",
"\"DBMail/%s\"",
"%",
"get_version",
"(",
")",
",",
"}",
"data",
... | 28 | 0.001151 |
def _read_mode_tcpao(self, size, kind):
"""Read Authentication option.
Positional arguments:
* size - int, length of option
* kind - int, 29 (TCP Authentication Option)
Returns:
* dict -- extracted Authentication (AO) option
Structure of TCP AOopt [... | [
"def",
"_read_mode_tcpao",
"(",
"self",
",",
"size",
",",
"kind",
")",
":",
"key_",
"=",
"self",
".",
"_read_unpack",
"(",
"1",
")",
"rkey",
"=",
"self",
".",
"_read_unpack",
"(",
"1",
")",
"mac_",
"=",
"self",
".",
"_read_fileng",
"(",
"size",
"-",
... | 33.642857 | 0.002063 |
def directionaldiff(f, x0, vec, **options):
"""
Return directional derivative of a function of n variables
Parameters
----------
fun: callable
analytical function to differentiate.
x0: array
vector location at which to differentiate fun. If x0 is an nxm array,
then fun i... | [
"def",
"directionaldiff",
"(",
"f",
",",
"x0",
",",
"vec",
",",
"*",
"*",
"options",
")",
":",
"x0",
"=",
"np",
".",
"asarray",
"(",
"x0",
")",
"vec",
"=",
"np",
".",
"asarray",
"(",
"vec",
")",
"if",
"x0",
".",
"size",
"!=",
"vec",
".",
"siz... | 29.857143 | 0.000662 |
def generate_GitHub_token(*, note="Doctr token for pushing to gh-pages from Travis", scopes=None, **login_kwargs):
"""
Generate a GitHub token for pushing from Travis
The scope requested is public_repo.
If no password or OTP are provided, they will be requested from the
command line.
The toke... | [
"def",
"generate_GitHub_token",
"(",
"*",
",",
"note",
"=",
"\"Doctr token for pushing to gh-pages from Travis\"",
",",
"scopes",
"=",
"None",
",",
"*",
"*",
"login_kwargs",
")",
":",
"if",
"scopes",
"is",
"None",
":",
"scopes",
"=",
"[",
"'public_repo'",
"]",
... | 32.272727 | 0.002736 |
def copy_to_folder(self, parent, name=None, api=None):
"""Copy file to folder
:param parent: Folder to copy file to
:param name: New file name
:param api: Api instance
:return: New file instance
"""
api = api or self._API
if self.is_folder():
... | [
"def",
"copy_to_folder",
"(",
"self",
",",
"parent",
",",
"name",
"=",
"None",
",",
"api",
"=",
"None",
")",
":",
"api",
"=",
"api",
"or",
"self",
".",
"_API",
"if",
"self",
".",
"is_folder",
"(",
")",
":",
"raise",
"SbgError",
"(",
"'Copying folders... | 27.166667 | 0.002963 |
def get_cmd_output(*args, encoding: str = SYS_ENCODING) -> str:
"""
Returns text output of a command.
"""
log.debug("get_cmd_output(): args = {!r}", args)
p = subprocess.Popen(args, stdout=subprocess.PIPE)
stdout, stderr = p.communicate()
return stdout.decode(encoding, errors='ignore') | [
"def",
"get_cmd_output",
"(",
"*",
"args",
",",
"encoding",
":",
"str",
"=",
"SYS_ENCODING",
")",
"->",
"str",
":",
"log",
".",
"debug",
"(",
"\"get_cmd_output(): args = {!r}\"",
",",
"args",
")",
"p",
"=",
"subprocess",
".",
"Popen",
"(",
"args",
",",
"... | 38.375 | 0.003185 |
def _compile_root_ast_to_ir(schema, ast, type_equivalence_hints=None):
"""Compile a full GraphQL abstract syntax tree (AST) to intermediate representation.
Args:
schema: GraphQL schema object, obtained from the graphql library
ast: the root GraphQL AST node for the query, obtained from the grap... | [
"def",
"_compile_root_ast_to_ir",
"(",
"schema",
",",
"ast",
",",
"type_equivalence_hints",
"=",
"None",
")",
":",
"if",
"len",
"(",
"ast",
".",
"selection_set",
".",
"selections",
")",
"!=",
"1",
":",
"raise",
"GraphQLCompilationError",
"(",
"u'Cannot process A... | 49.691057 | 0.005133 |
def delete_feed_view(self, feed_id, view_id):
"""DeleteFeedView.
[Preview API] Delete a feed view.
:param str feed_id: Name or Id of the feed.
:param str view_id: Name or Id of the view.
"""
route_values = {}
if feed_id is not None:
route_values['feedI... | [
"def",
"delete_feed_view",
"(",
"self",
",",
"feed_id",
",",
"view_id",
")",
":",
"route_values",
"=",
"{",
"}",
"if",
"feed_id",
"is",
"not",
"None",
":",
"route_values",
"[",
"'feedId'",
"]",
"=",
"self",
".",
"_serialize",
".",
"url",
"(",
"'feed_id'"... | 45.066667 | 0.005797 |
def to_array(self, channels=2):
"""Generate the array of multipliers for the dynamic"""
return np.linspace(self.volume, self.volume,
self.duration * channels).reshape(self.duration, channels) | [
"def",
"to_array",
"(",
"self",
",",
"channels",
"=",
"2",
")",
":",
"return",
"np",
".",
"linspace",
"(",
"self",
".",
"volume",
",",
"self",
".",
"volume",
",",
"self",
".",
"duration",
"*",
"channels",
")",
".",
"reshape",
"(",
"self",
".",
"dur... | 54 | 0.013699 |
def d_from_format(self, attr):
""" Find out the local name of an attribute
:param attr: An Attribute dictionary
:return: The local attribute name or "" if no mapping could be made
"""
if attr["name_format"]:
if self.name_format == attr["name_format"]:
... | [
"def",
"d_from_format",
"(",
"self",
",",
"attr",
")",
":",
"if",
"attr",
"[",
"\"name_format\"",
"]",
":",
"if",
"self",
".",
"name_format",
"==",
"attr",
"[",
"\"name_format\"",
"]",
":",
"try",
":",
"return",
"self",
".",
"_fro",
"[",
"attr",
"[",
... | 33 | 0.003101 |
def __load_state(self):
""" Read persisted state from the JSON statefile
"""
try:
return ConfigState(json.load(open(self.config_state_path)))
except (OSError, IOError) as exc:
if exc.errno == errno.ENOENT:
self.__dump_state({})
retu... | [
"def",
"__load_state",
"(",
"self",
")",
":",
"try",
":",
"return",
"ConfigState",
"(",
"json",
".",
"load",
"(",
"open",
"(",
"self",
".",
"config_state_path",
")",
")",
")",
"except",
"(",
"OSError",
",",
"IOError",
")",
"as",
"exc",
":",
"if",
"ex... | 37.1 | 0.005263 |
def load(self, line):
"""Load this keyword from a file-like object"""
words = line.split()
try:
float(words[0])
self.__name = ""
self.__value = " ".join(words)
except ValueError:
self.__name = words[0].upper()
if len(words) > 2 ... | [
"def",
"load",
"(",
"self",
",",
"line",
")",
":",
"words",
"=",
"line",
".",
"split",
"(",
")",
"try",
":",
"float",
"(",
"words",
"[",
"0",
"]",
")",
"self",
".",
"__name",
"=",
"\"\"",
"self",
".",
"__value",
"=",
"\" \"",
".",
"join",
"(",
... | 36.642857 | 0.007605 |
def query(self, sql, param=None, stream=False, row_tuples=False):
"""
RETURN LIST OF dicts
"""
if not self.cursor: # ALLOW NON-TRANSACTIONAL READS
Log.error("must perform all queries inside a transaction")
self._execute_backlog()
try:
if param:
... | [
"def",
"query",
"(",
"self",
",",
"sql",
",",
"param",
"=",
"None",
",",
"stream",
"=",
"False",
",",
"row_tuples",
"=",
"False",
")",
":",
"if",
"not",
"self",
".",
"cursor",
":",
"# ALLOW NON-TRANSACTIONAL READS",
"Log",
".",
"error",
"(",
"\"must perf... | 41.30303 | 0.004301 |
def get_target(self):
"""Return this context’s target surface.
:returns:
An instance of :class:`Surface` or one of its sub-classes,
a new Python object referencing the existing cairo surface.
"""
return Surface._from_pointer(
cairo.cairo_get_target(s... | [
"def",
"get_target",
"(",
"self",
")",
":",
"return",
"Surface",
".",
"_from_pointer",
"(",
"cairo",
".",
"cairo_get_target",
"(",
"self",
".",
"_pointer",
")",
",",
"incref",
"=",
"True",
")"
] | 33.8 | 0.005764 |
def update_build_configuration_set(id, **kwargs):
"""
Update a BuildConfigurationSet
"""
data = update_build_configuration_set_raw(id, **kwargs)
if data:
return utils.format_json(data) | [
"def",
"update_build_configuration_set",
"(",
"id",
",",
"*",
"*",
"kwargs",
")",
":",
"data",
"=",
"update_build_configuration_set_raw",
"(",
"id",
",",
"*",
"*",
"kwargs",
")",
"if",
"data",
":",
"return",
"utils",
".",
"format_json",
"(",
"data",
")"
] | 29.428571 | 0.004717 |
def do_get_aliases(name):
"""
Get aliases for given metric name
"""
metric_schemas = MetricSchemas()
aliases = metric_schemas.get_aliases(name)
for alias in aliases:
do_print(alias) | [
"def",
"do_get_aliases",
"(",
"name",
")",
":",
"metric_schemas",
"=",
"MetricSchemas",
"(",
")",
"aliases",
"=",
"metric_schemas",
".",
"get_aliases",
"(",
"name",
")",
"for",
"alias",
"in",
"aliases",
":",
"do_print",
"(",
"alias",
")"
] | 23.75 | 0.025381 |
def dihed_iter(self, g_nums, ats_1, ats_2, ats_3, ats_4, \
invalid_error=False):
""" Iterator over selected dihedral angles.
Angles are in degrees as with :meth:`dihed_single`.
See `above <toc-generators_>`_ for more information on
ca... | [
"def",
"dihed_iter",
"(",
"self",
",",
"g_nums",
",",
"ats_1",
",",
"ats_2",
",",
"ats_3",
",",
"ats_4",
",",
"invalid_error",
"=",
"False",
")",
":",
"# Suitability of ats_n indices will be checked within the",
"# self.dihed_single() calls and thus no check is needed here... | 31.358696 | 0.002016 |
def _FormatTag(self, event):
"""Formats the event tag.
Args:
event (EventObject): event.
Returns:
str: event tag field.
"""
tag = getattr(event, 'tag', None)
if not tag:
return '-'
return ' '.join(tag.labels) | [
"def",
"_FormatTag",
"(",
"self",
",",
"event",
")",
":",
"tag",
"=",
"getattr",
"(",
"event",
",",
"'tag'",
",",
"None",
")",
"if",
"not",
"tag",
":",
"return",
"'-'",
"return",
"' '",
".",
"join",
"(",
"tag",
".",
"labels",
")"
] | 16.266667 | 0.007752 |
def param_logx_diagram(run_list, **kwargs):
"""Creates diagrams of a nested sampling run's evolution as it iterates
towards higher likelihoods, expressed as a function of log X, where X(L) is
the fraction of the prior volume with likelihood greater than some value L.
For a more detailed description and... | [
"def",
"param_logx_diagram",
"(",
"run_list",
",",
"*",
"*",
"kwargs",
")",
":",
"fthetas",
"=",
"kwargs",
".",
"pop",
"(",
"'fthetas'",
",",
"[",
"lambda",
"theta",
":",
"theta",
"[",
":",
",",
"0",
"]",
",",
"lambda",
"theta",
":",
"theta",
"[",
... | 45.573991 | 0.000096 |
def includeme(config):
""" Add pyramid_webpack methods and config to the app """
settings = config.registry.settings
root_package_name = config.root_package.__name__
config.registry.webpack = {
'DEFAULT': WebpackState(settings, root_package_name)
}
for extra_config in aslist(settings.get... | [
"def",
"includeme",
"(",
"config",
")",
":",
"settings",
"=",
"config",
".",
"registry",
".",
"settings",
"root_package_name",
"=",
"config",
".",
"root_package",
".",
"__name__",
"config",
".",
"registry",
".",
"webpack",
"=",
"{",
"'DEFAULT'",
":",
"Webpac... | 43.684211 | 0.001179 |
def _getParameters(self):
"""Returns the result of this decorator."""
param = self.query._getParameters()
param[self.__key] = self.__value
return param | [
"def",
"_getParameters",
"(",
"self",
")",
":",
"param",
"=",
"self",
".",
"query",
".",
"_getParameters",
"(",
")",
"param",
"[",
"self",
".",
"__key",
"]",
"=",
"self",
".",
"__value",
"return",
"param"
] | 39.8 | 0.019704 |
def bdd(*keywords):
"""
Run tests matching keywords.
"""
settings = _personal_settings().data
_storybook().with_params(
**{"python version": settings["params"]["python version"]}
).only_uninherited().shortcut(*keywords).play() | [
"def",
"bdd",
"(",
"*",
"keywords",
")",
":",
"settings",
"=",
"_personal_settings",
"(",
")",
".",
"data",
"_storybook",
"(",
")",
".",
"with_params",
"(",
"*",
"*",
"{",
"\"python version\"",
":",
"settings",
"[",
"\"params\"",
"]",
"[",
"\"python versio... | 31.375 | 0.003876 |
def shutdown(self):
"""
Unconditionally shuts the TendrilManager down, killing all
threads and closing all tendrils.
"""
super(UDPTendrilManager, self).shutdown()
# Reset the socket and socket event
self._sock = None
self._sock_event.clear() | [
"def",
"shutdown",
"(",
"self",
")",
":",
"super",
"(",
"UDPTendrilManager",
",",
"self",
")",
".",
"shutdown",
"(",
")",
"# Reset the socket and socket event",
"self",
".",
"_sock",
"=",
"None",
"self",
".",
"_sock_event",
".",
"clear",
"(",
")"
] | 27 | 0.006515 |
def nfwAlpha(self, R, Rs, rho0, r_trunc, ax_x, ax_y):
"""
deflection angel of NFW profile along the projection to coordinate axis
:param R: radius of interest
:type R: float/numpy array
:param Rs: scale radius
:type Rs: float
:param rho0: density normalization (c... | [
"def",
"nfwAlpha",
"(",
"self",
",",
"R",
",",
"Rs",
",",
"rho0",
",",
"r_trunc",
",",
"ax_x",
",",
"ax_y",
")",
":",
"if",
"isinstance",
"(",
"R",
",",
"int",
")",
"or",
"isinstance",
"(",
"R",
",",
"float",
")",
":",
"R",
"=",
"max",
"(",
"... | 33.192308 | 0.002252 |
def updateGeometry(self):
"""Move widget to point under cursor
"""
WIDGET_BORDER_MARGIN = 5
SCROLLBAR_WIDTH = 30 # just a guess
sizeHint = self.sizeHint()
width = sizeHint.width()
height = sizeHint.height()
cursorRect = self._qpart.cursorRect()
... | [
"def",
"updateGeometry",
"(",
"self",
")",
":",
"WIDGET_BORDER_MARGIN",
"=",
"5",
"SCROLLBAR_WIDTH",
"=",
"30",
"# just a guess",
"sizeHint",
"=",
"self",
".",
"sizeHint",
"(",
")",
"width",
"=",
"sizeHint",
".",
"width",
"(",
")",
"height",
"=",
"sizeHint",... | 35.297297 | 0.002235 |
def _expand_numparse(disable_numparse, column_count):
"""
Return a list of bools of length `column_count` which indicates whether
number parsing should be used on each column.
If `disable_numparse` is a list of indices, each of those indices are False,
and everything else is True.
If `disable_nu... | [
"def",
"_expand_numparse",
"(",
"disable_numparse",
",",
"column_count",
")",
":",
"if",
"isinstance",
"(",
"disable_numparse",
",",
"Iterable",
")",
":",
"numparses",
"=",
"[",
"True",
"]",
"*",
"column_count",
"for",
"index",
"in",
"disable_numparse",
":",
"... | 41.666667 | 0.00313 |
def simple_equality(cls, first, second, msg=None):
"""
Classmethod equivalent to unittest.TestCase method (longMessage = False.)
"""
if not first==second:
standardMsg = '%s != %s' % (safe_repr(first), safe_repr(second))
raise cls.failureException(msg or standardMs... | [
"def",
"simple_equality",
"(",
"cls",
",",
"first",
",",
"second",
",",
"msg",
"=",
"None",
")",
":",
"if",
"not",
"first",
"==",
"second",
":",
"standardMsg",
"=",
"'%s != %s'",
"%",
"(",
"safe_repr",
"(",
"first",
")",
",",
"safe_repr",
"(",
"second"... | 45.142857 | 0.012422 |
def to_dict(self):
"""
Return a dictionary representation of the dataset.
"""
d = dict(doses=self.doses, ns=self.ns, means=self.means, stdevs=self.stdevs)
d.update(self.kwargs)
return d | [
"def",
"to_dict",
"(",
"self",
")",
":",
"d",
"=",
"dict",
"(",
"doses",
"=",
"self",
".",
"doses",
",",
"ns",
"=",
"self",
".",
"ns",
",",
"means",
"=",
"self",
".",
"means",
",",
"stdevs",
"=",
"self",
".",
"stdevs",
")",
"d",
".",
"update",
... | 32.428571 | 0.012876 |
def _make_spec_file(self):
"""Generates the text of an RPM spec file.
Returns:
A list of strings containing the lines of text.
"""
# Note that bdist_rpm can be an old style class.
if issubclass(BdistRPMCommand, object):
spec_file = super(BdistRPMCommand, se... | [
"def",
"_make_spec_file",
"(",
"self",
")",
":",
"# Note that bdist_rpm can be an old style class.",
"if",
"issubclass",
"(",
"BdistRPMCommand",
",",
"object",
")",
":",
"spec_file",
"=",
"super",
"(",
"BdistRPMCommand",
",",
"self",
")",
".",
"_make_spec_file",
"("... | 32.95082 | 0.000966 |
def useNonce(self, server_url, timestamp, salt):
"""Return whether this nonce is valid.
str -> bool
"""
if abs(timestamp - time.time()) > nonce.SKEW:
return False
if server_url:
proto, rest = server_url.split('://', 1)
else:
# Create ... | [
"def",
"useNonce",
"(",
"self",
",",
"server_url",
",",
"timestamp",
",",
"salt",
")",
":",
"if",
"abs",
"(",
"timestamp",
"-",
"time",
".",
"time",
"(",
")",
")",
">",
"nonce",
".",
"SKEW",
":",
"return",
"False",
"if",
"server_url",
":",
"proto",
... | 31.363636 | 0.001874 |
def get_client_id(self):
""" Attempt to get client_id from soundcloud homepage. """
# FIXME: This method doesn't works
id = re.search(
"\"clientID\":\"([a-z0-9]*)\"",
self.send_request(self.SC_HOME).read().decode("utf-8"))
if not id:
raise serror("Can... | [
"def",
"get_client_id",
"(",
"self",
")",
":",
"# FIXME: This method doesn't works",
"id",
"=",
"re",
".",
"search",
"(",
"\"\\\"clientID\\\":\\\"([a-z0-9]*)\\\"\"",
",",
"self",
".",
"send_request",
"(",
"self",
".",
"SC_HOME",
")",
".",
"read",
"(",
")",
".",
... | 33 | 0.005362 |
def as_bitcode(self):
"""
Return the module's LLVM bitcode, as a bytes object.
"""
ptr = c_char_p(None)
size = c_size_t(-1)
ffi.lib.LLVMPY_WriteBitcodeToString(self, byref(ptr), byref(size))
if not ptr:
raise MemoryError
try:
assert... | [
"def",
"as_bitcode",
"(",
"self",
")",
":",
"ptr",
"=",
"c_char_p",
"(",
"None",
")",
"size",
"=",
"c_size_t",
"(",
"-",
"1",
")",
"ffi",
".",
"lib",
".",
"LLVMPY_WriteBitcodeToString",
"(",
"self",
",",
"byref",
"(",
"ptr",
")",
",",
"byref",
"(",
... | 30.857143 | 0.004494 |
def check_format(cls, tags):
"""
Check the tags arg only contains valid type for tags
:param tags: output of create_tags_from_dict
:return: True if correct format, False otherwise
"""
common, _, _ = tags
for tag in common:
if tag.get_type() != 0: # Un... | [
"def",
"check_format",
"(",
"cls",
",",
"tags",
")",
":",
"common",
",",
"_",
",",
"_",
"=",
"tags",
"for",
"tag",
"in",
"common",
":",
"if",
"tag",
".",
"get_type",
"(",
")",
"!=",
"0",
":",
"# Unknown type -> incorrect",
"return",
"False",
"return",
... | 34.727273 | 0.005102 |
def add_molecular_graph(self, molecular_graph, atom_types=None, charges=None, split=True, molecule=None):
"""Add the molecular graph to the data structure
Argument:
| ``molecular_graph`` -- a MolecularGraph instance
Optional arguments:
| ``atom_types`` -- a li... | [
"def",
"add_molecular_graph",
"(",
"self",
",",
"molecular_graph",
",",
"atom_types",
"=",
"None",
",",
"charges",
"=",
"None",
",",
"split",
"=",
"True",
",",
"molecule",
"=",
"None",
")",
":",
"# add atom numbers and molecule indices",
"new",
"=",
"len",
"("... | 44.326923 | 0.00382 |
def to_user_agent(self):
"""Returns the user-agent string for this client info."""
# Note: the order here is important as the internal metrics system
# expects these items to be in specific locations.
ua = ""
if self.user_agent is not None:
ua += "{user_agent} "
... | [
"def",
"to_user_agent",
"(",
"self",
")",
":",
"# Note: the order here is important as the internal metrics system",
"# expects these items to be in specific locations.",
"ua",
"=",
"\"\"",
"if",
"self",
".",
"user_agent",
"is",
"not",
"None",
":",
"ua",
"+=",
"\"{user_agen... | 29.375 | 0.002747 |
def get(self, user_ids=None, usernames=None, status=None):
"""
:param user_ids: list of int of the user_ids to return
:param usernames: list of str of the usernames to return
:param status: str of the status
:return: list of User
"""
return self.conne... | [
"def",
"get",
"(",
"self",
",",
"user_ids",
"=",
"None",
",",
"usernames",
"=",
"None",
",",
"status",
"=",
"None",
")",
":",
"return",
"self",
".",
"connection",
".",
"get",
"(",
"'user/array'",
",",
"user_ids",
"=",
"user_ids",
",",
"usernames",
"=",... | 44.818182 | 0.003976 |
def load(self):
""" Loads the user's account details and
Raises
parseException
"""
pg = self.usr.getPage("http://www.neopets.com/bank.phtml")
# Verifies account exists
if not "great to see you again" in pg.content:
logging.getL... | [
"def",
"load",
"(",
"self",
")",
":",
"pg",
"=",
"self",
".",
"usr",
".",
"getPage",
"(",
"\"http://www.neopets.com/bank.phtml\"",
")",
"# Verifies account exists",
"if",
"not",
"\"great to see you again\"",
"in",
"pg",
".",
"content",
":",
"logging",
".",
"getL... | 34.714286 | 0.016032 |
def project(*descs, root_file=None):
"""
Make a new project, using recursion and alias resolution.
Use this function in preference to calling Project() directly.
"""
load.ROOT_FILE = root_file
desc = merge.merge(merge.DEFAULT_PROJECT, *descs)
path = desc.get('path', '')
if root_file:
... | [
"def",
"project",
"(",
"*",
"descs",
",",
"root_file",
"=",
"None",
")",
":",
"load",
".",
"ROOT_FILE",
"=",
"root_file",
"desc",
"=",
"merge",
".",
"merge",
"(",
"merge",
".",
"DEFAULT_PROJECT",
",",
"*",
"descs",
")",
"path",
"=",
"desc",
".",
"get... | 25.083333 | 0.0016 |
def get_tool_context(self, tool_alias):
"""Given a visible tool alias, return the name of the context it
belongs to.
Args:
tool_alias (str): Tool alias to search for.
Returns:
(str): Name of the context that exposes a visible instance of this
tool al... | [
"def",
"get_tool_context",
"(",
"self",
",",
"tool_alias",
")",
":",
"tools_dict",
"=",
"self",
".",
"get_tools",
"(",
")",
"data",
"=",
"tools_dict",
".",
"get",
"(",
"tool_alias",
")",
"if",
"data",
":",
"return",
"data",
"[",
"\"context_name\"",
"]",
... | 32.3125 | 0.003759 |
def get(security_token=None, key=None):
""" Get information about this node """
if security_token is None:
security_token = nago.core.get_my_info()['host_name']
data = node_data.get(security_token, {})
if not key:
return data
else:
return data.get(key) | [
"def",
"get",
"(",
"security_token",
"=",
"None",
",",
"key",
"=",
"None",
")",
":",
"if",
"security_token",
"is",
"None",
":",
"security_token",
"=",
"nago",
".",
"core",
".",
"get_my_info",
"(",
")",
"[",
"'host_name'",
"]",
"data",
"=",
"node_data",
... | 32 | 0.003378 |
def sasdata2dataframeCSV(self, table: str, libref: str ='', dsopts: dict = None, tempfile: str=None, tempkeep: bool=False, **kwargs) -> '<Pandas Data Frame object>':
"""
This method exports the SAS Data Set to a Pandas Data Frame, returning the Data Frame object.
table - the name of the SAS Data Se... | [
"def",
"sasdata2dataframeCSV",
"(",
"self",
",",
"table",
":",
"str",
",",
"libref",
":",
"str",
"=",
"''",
",",
"dsopts",
":",
"dict",
"=",
"None",
",",
"tempfile",
":",
"str",
"=",
"None",
",",
"tempkeep",
":",
"bool",
"=",
"False",
",",
"*",
"*"... | 34.616667 | 0.024649 |
def consume(self, routingKey, msg):
"""
Consumer for this (CaptureData) class. Gets the data sent from yieldMetricsValue and
sends it to the storage backends.
"""
build_data = msg['build_data']
builder_info = yield self.master.data.get(("builders", build_data['builderid']... | [
"def",
"consume",
"(",
"self",
",",
"routingKey",
",",
"msg",
")",
":",
"build_data",
"=",
"msg",
"[",
"'build_data'",
"]",
"builder_info",
"=",
"yield",
"self",
".",
"master",
".",
"data",
".",
"get",
"(",
"(",
"\"builders\"",
",",
"build_data",
"[",
... | 54.85 | 0.007168 |
def statvfs(path):
'''
.. versionadded:: 2014.1.0
Perform a statvfs call against the filesystem that the file resides on
CLI Example:
.. code-block:: bash
salt '*' file.statvfs /path/to/file
'''
path = os.path.expanduser(path)
if not os.path.isabs(path):
raise SaltIn... | [
"def",
"statvfs",
"(",
"path",
")",
":",
"path",
"=",
"os",
".",
"path",
".",
"expanduser",
"(",
"path",
")",
"if",
"not",
"os",
".",
"path",
".",
"isabs",
"(",
"path",
")",
":",
"raise",
"SaltInvocationError",
"(",
"'File path must be absolute.'",
")",
... | 28.16 | 0.004121 |
def _input_stmt(self, stmt: object) -> tuple:
"""
takes the input key from kwargs and processes it to aid in the generation of a model statement
:param stmt: str, list, or dict that contains the model information.
:return: tuple of strings one for the class statement one for the model st... | [
"def",
"_input_stmt",
"(",
"self",
",",
"stmt",
":",
"object",
")",
"->",
"tuple",
":",
"code",
"=",
"''",
"cls",
"=",
"''",
"if",
"isinstance",
"(",
"stmt",
",",
"str",
")",
":",
"code",
"+=",
"\"%s \"",
"%",
"(",
"stmt",
")",
"elif",
"isinstance"... | 46.25 | 0.003529 |
def create_command_class(name, func_module):
"""Dynamically creates subclass of MigratingCommand.
Method takes name of the function, module it is part of
and builds the subclass of :py:class:`MigratingCommand`.
Having a subclass of :py:class:`cliff.command.Command` is mandatory
for the osc-lib inte... | [
"def",
"create_command_class",
"(",
"name",
",",
"func_module",
")",
":",
"cmd_name",
"=",
"name",
"[",
"3",
":",
"]",
".",
"replace",
"(",
"'_'",
",",
"'-'",
")",
"callback",
"=",
"getattr",
"(",
"func_module",
",",
"name",
")",
"desc",
"=",
"callback... | 29.833333 | 0.000902 |
def strftime(self, fmt="%d:%H:%M:%S"):
"""Primitive string formatter.
The only directives understood are the following:
============ ==========================
Directive meaning
============ ==========================
%d day as integer
... | [
"def",
"strftime",
"(",
"self",
",",
"fmt",
"=",
"\"%d:%H:%M:%S\"",
")",
":",
"substitutions",
"=",
"{",
"\"%d\"",
":",
"str",
"(",
"self",
".",
"days",
")",
",",
"\"%H\"",
":",
"\"{0:02d}\"",
".",
"format",
"(",
"self",
".",
"dhours",
")",
",",
"\"%... | 38.16 | 0.002045 |
def synth_hangul(string):
"""Convert jamo characters in a string into hcj as much as possible."""
raise NotImplementedError
return ''.join([''.join(''.join(jamo_to_hcj(_)) for _ in string)]) | [
"def",
"synth_hangul",
"(",
"string",
")",
":",
"raise",
"NotImplementedError",
"return",
"''",
".",
"join",
"(",
"[",
"''",
".",
"join",
"(",
"''",
".",
"join",
"(",
"jamo_to_hcj",
"(",
"_",
")",
")",
"for",
"_",
"in",
"string",
")",
"]",
")"
] | 49.75 | 0.00495 |
def thellier_interpreter_BS_pars_calc(self, Grade_As):
'''
calcualte sample or site bootstrap paleointensities
and statistics
Grade_As={}
'''
thellier_interpreter_pars = {}
thellier_interpreter_pars['fail_criteria'] = []
thellier_interpreter_pars['pass_or_... | [
"def",
"thellier_interpreter_BS_pars_calc",
"(",
"self",
",",
"Grade_As",
")",
":",
"thellier_interpreter_pars",
"=",
"{",
"}",
"thellier_interpreter_pars",
"[",
"'fail_criteria'",
"]",
"=",
"[",
"]",
"thellier_interpreter_pars",
"[",
"'pass_or_fail'",
"]",
"=",
"'pas... | 51.564516 | 0.00399 |
def sort(args):
"""
%prog sort gffile
Sort gff file using plain old unix sort based on [chromosome, start coordinate].
or topologically based on hierarchy of features using the gt (genometools) toolkit
"""
valid_sort_methods = ("unix", "topo")
p = OptionParser(sort.__doc__)
p.add_optio... | [
"def",
"sort",
"(",
"args",
")",
":",
"valid_sort_methods",
"=",
"(",
"\"unix\"",
",",
"\"topo\"",
")",
"p",
"=",
"OptionParser",
"(",
"sort",
".",
"__doc__",
")",
"p",
".",
"add_option",
"(",
"\"--method\"",
",",
"default",
"=",
"\"unix\"",
",",
"choice... | 36.595745 | 0.005096 |
def get_container_for(self, instance):
"""Returns the container id used in slots to group analyses
"""
if IReferenceAnalysis.providedBy(instance):
return api.get_uid(instance.getSample())
return instance.getRequestUID() | [
"def",
"get_container_for",
"(",
"self",
",",
"instance",
")",
":",
"if",
"IReferenceAnalysis",
".",
"providedBy",
"(",
"instance",
")",
":",
"return",
"api",
".",
"get_uid",
"(",
"instance",
".",
"getSample",
"(",
")",
")",
"return",
"instance",
".",
"get... | 43 | 0.007605 |
def vboxsf_to_windows(filename, letter='f:'):
"""Convert the Linux path name to a Windows one."""
home = os.path.expanduser('~')
filename = os.path.abspath(filename).replace(home, letter)
return filename.replace('/', '\\') | [
"def",
"vboxsf_to_windows",
"(",
"filename",
",",
"letter",
"=",
"'f:'",
")",
":",
"home",
"=",
"os",
".",
"path",
".",
"expanduser",
"(",
"'~'",
")",
"filename",
"=",
"os",
".",
"path",
".",
"abspath",
"(",
"filename",
")",
".",
"replace",
"(",
"hom... | 46.8 | 0.004202 |
def abort(self, abort_message=''):
"""Mark the entire pipeline up to the root as aborted.
Note this should only be called from *outside* the context of a running
pipeline. Synchronous and generator pipelines should raise the 'Abort'
exception to cause this behavior during execution.
Args:
ab... | [
"def",
"abort",
"(",
"self",
",",
"abort_message",
"=",
"''",
")",
":",
"# TODO: Use thread-local variable to enforce that this is not called",
"# while a pipeline is executing in the current thread.",
"if",
"(",
"self",
".",
"async",
"and",
"self",
".",
"_root_pipeline_key",... | 40.916667 | 0.006965 |
def accumulator(self, value, accum_param=None):
"""
Create an L{Accumulator} with the given initial value, using a given
L{AccumulatorParam} helper object to define how to add values of the
data type if provided. Default AccumulatorParams are used for integers
and floating-point ... | [
"def",
"accumulator",
"(",
"self",
",",
"value",
",",
"accum_param",
"=",
"None",
")",
":",
"if",
"accum_param",
"is",
"None",
":",
"if",
"isinstance",
"(",
"value",
",",
"int",
")",
":",
"accum_param",
"=",
"accumulators",
".",
"INT_ACCUMULATOR_PARAM",
"e... | 52.684211 | 0.002944 |
def main():
"""
Entry point
"""
rc_settings = read_rcfile()
parser = ArgumentParser(description='Millipede generator')
parser.add_argument('-s', '--size',
type=int,
nargs="?",
help='the size of the millipede')
parser.add... | [
"def",
"main",
"(",
")",
":",
"rc_settings",
"=",
"read_rcfile",
"(",
")",
"parser",
"=",
"ArgumentParser",
"(",
"description",
"=",
"'Millipede generator'",
")",
"parser",
".",
"add_argument",
"(",
"'-s'",
",",
"'--size'",
",",
"type",
"=",
"int",
",",
"n... | 29.670588 | 0.000384 |
def render(self, context):
"""
Renders the translated text using the XBlock i18n service, if available.
"""
with self.merge_translation(context):
django_translated = self.do_translate.render(context)
return django_translated | [
"def",
"render",
"(",
"self",
",",
"context",
")",
":",
"with",
"self",
".",
"merge_translation",
"(",
"context",
")",
":",
"django_translated",
"=",
"self",
".",
"do_translate",
".",
"render",
"(",
"context",
")",
"return",
"django_translated"
] | 33.75 | 0.01083 |
def _fetch_data(self):
"""
Retrieve frame data within the current view window.
This method will adjust the view window if it goes out-of-bounds.
"""
self._view_col0 = clamp(self._view_col0, 0, self._max_col0)
self._view_row0 = clamp(self._view_row0, 0, self._max_row0)
... | [
"def",
"_fetch_data",
"(",
"self",
")",
":",
"self",
".",
"_view_col0",
"=",
"clamp",
"(",
"self",
".",
"_view_col0",
",",
"0",
",",
"self",
".",
"_max_col0",
")",
"self",
".",
"_view_row0",
"=",
"clamp",
"(",
"self",
".",
"_view_row0",
",",
"0",
","... | 43.764706 | 0.002632 |
def solve(self, angles0, target):
"""Calculate joint angles and returns it."""
return self.optimizer.optimize(np.array(angles0), target) | [
"def",
"solve",
"(",
"self",
",",
"angles0",
",",
"target",
")",
":",
"return",
"self",
".",
"optimizer",
".",
"optimize",
"(",
"np",
".",
"array",
"(",
"angles0",
")",
",",
"target",
")"
] | 50 | 0.013158 |
def append(self, data, **keys):
"""
Append new rows to a table HDU
parameters
----------
data: ndarray or list of arrays
A numerical python array with fields (recarray) or a list of
arrays. Should have the same fields as the existing table. If only
... | [
"def",
"append",
"(",
"self",
",",
"data",
",",
"*",
"*",
"keys",
")",
":",
"firstrow",
"=",
"self",
".",
"_info",
"[",
"'nrows'",
"]",
"keys",
"[",
"'firstrow'",
"]",
"=",
"firstrow",
"self",
".",
"write",
"(",
"data",
",",
"*",
"*",
"keys",
")"... | 29.954545 | 0.002941 |
def process_tokendef(cls, name, tokendefs=None):
"""Preprocess a dictionary of token definitions."""
processed = cls._all_tokens[name] = {}
tokendefs = tokendefs or cls.tokens[name]
for state in list(tokendefs):
cls._process_state(tokendefs, processed, state)
return p... | [
"def",
"process_tokendef",
"(",
"cls",
",",
"name",
",",
"tokendefs",
"=",
"None",
")",
":",
"processed",
"=",
"cls",
".",
"_all_tokens",
"[",
"name",
"]",
"=",
"{",
"}",
"tokendefs",
"=",
"tokendefs",
"or",
"cls",
".",
"tokens",
"[",
"name",
"]",
"f... | 46 | 0.006098 |
def send_email_confirmation_instructions(self, user):
"""
Sends the confirmation instructions email for the specified user.
Sends signal `confirm_instructions_sent`.
:param user: The user to send the instructions to.
"""
token = self.security_utils_service.generate_conf... | [
"def",
"send_email_confirmation_instructions",
"(",
"self",
",",
"user",
")",
":",
"token",
"=",
"self",
".",
"security_utils_service",
".",
"generate_confirmation_token",
"(",
"user",
")",
"confirmation_link",
"=",
"url_for",
"(",
"'security_controller.confirm_email'",
... | 46.578947 | 0.003322 |
def list_train_dirs(dir_: str, recursive: bool, all_: bool, long: bool, verbose: bool) -> None:
"""
List training dirs contained in the given dir with options and outputs similar to the regular `ls` command.
The function is accessible through cxflow CLI `cxflow ls`.
:param dir_: dir to be listed
:p... | [
"def",
"list_train_dirs",
"(",
"dir_",
":",
"str",
",",
"recursive",
":",
"bool",
",",
"all_",
":",
"bool",
",",
"long",
":",
"bool",
",",
"verbose",
":",
"bool",
")",
"->",
"None",
":",
"if",
"verbose",
":",
"long",
"=",
"True",
"if",
"dir_",
"=="... | 42.638889 | 0.005096 |
def Add(self, other):
"""Returns a copy of this set with a new element added."""
new_descriptors = []
for desc in self.descriptors + other.descriptors:
if desc not in new_descriptors:
new_descriptors.append(desc)
return TypeDescriptorSet(*new_descriptors) | [
"def",
"Add",
"(",
"self",
",",
"other",
")",
":",
"new_descriptors",
"=",
"[",
"]",
"for",
"desc",
"in",
"self",
".",
"descriptors",
"+",
"other",
".",
"descriptors",
":",
"if",
"desc",
"not",
"in",
"new_descriptors",
":",
"new_descriptors",
".",
"appen... | 34.875 | 0.006993 |
def reindex(clear: bool, progressive: bool, batch_size: int):
"""Reindex all content; optionally clear index before.
All is done in asingle transaction by default.
:param clear: clear index content.
:param progressive: don't run in a single transaction.
:param batch_size: number of documents to pr... | [
"def",
"reindex",
"(",
"clear",
":",
"bool",
",",
"progressive",
":",
"bool",
",",
"batch_size",
":",
"int",
")",
":",
"reindexer",
"=",
"Reindexer",
"(",
"clear",
",",
"progressive",
",",
"batch_size",
")",
"reindexer",
".",
"reindex_all",
"(",
")"
] | 44.923077 | 0.001678 |
def _fact_ref_eval(cls, cpeset, wfn):
"""
Returns True if wfn is a non-proper superset (True superset
or equal to) any of the names in cpeset, otherwise False.
:param CPESet cpeset: list of CPE bound Names.
:param CPE2_3_WFN wfn: WFN CPE Name.
:returns: True if wfn is a ... | [
"def",
"_fact_ref_eval",
"(",
"cls",
",",
"cpeset",
",",
"wfn",
")",
":",
"for",
"n",
"in",
"cpeset",
":",
"# Need to convert each n from bound form to WFN",
"if",
"(",
"CPESet2_3",
".",
"cpe_superset",
"(",
"wfn",
",",
"n",
")",
")",
":",
"return",
"True",
... | 34.588235 | 0.004967 |
def unflatten2(flat_list, cumlen_list):
""" Rebuilds unflat list from invertible_flatten1
Args:
flat_list (list): the flattened list
cumlen_list (list): the list which undoes flattenting
Returns:
unflat_list2: original nested list
SeeAlso:
invertible_flatten1
i... | [
"def",
"unflatten2",
"(",
"flat_list",
",",
"cumlen_list",
")",
":",
"unflat_list2",
"=",
"[",
"flat_list",
"[",
"low",
":",
"high",
"]",
"for",
"low",
",",
"high",
"in",
"zip",
"(",
"itertools",
".",
"chain",
"(",
"[",
"0",
"]",
",",
"cumlen_list",
... | 30.5 | 0.001059 |
def byteswap(data, word_size=4):
""" Swap the byte-ordering in a packet with N=4 bytes per word
"""
return reduce(lambda x,y: x+''.join(reversed(y)), chunks(data, word_size), '') | [
"def",
"byteswap",
"(",
"data",
",",
"word_size",
"=",
"4",
")",
":",
"return",
"reduce",
"(",
"lambda",
"x",
",",
"y",
":",
"x",
"+",
"''",
".",
"join",
"(",
"reversed",
"(",
"y",
")",
")",
",",
"chunks",
"(",
"data",
",",
"word_size",
")",
",... | 46.75 | 0.015789 |
def _put_bucket_tagging(self):
"""Add bucket tags to bucket."""
all_tags = self.s3props['tagging']['tags']
all_tags.update({'app_group': self.group, 'app_name': self.app_name})
tag_set = generate_s3_tags.generated_tag_data(all_tags)
tagging_config = {'TagSet': tag_set}
... | [
"def",
"_put_bucket_tagging",
"(",
"self",
")",
":",
"all_tags",
"=",
"self",
".",
"s3props",
"[",
"'tagging'",
"]",
"[",
"'tags'",
"]",
"all_tags",
".",
"update",
"(",
"{",
"'app_group'",
":",
"self",
".",
"group",
",",
"'app_name'",
":",
"self",
".",
... | 44.5 | 0.006608 |
def _is_descendant_of(self, parent):
"""
Returns True if parent is in the list of ancestors, returns False
otherwise.
:type parent: Task
:param parent: The parent that is searched in the ancestors.
:rtype: bool
:returns: Whether the parent was found.
""... | [
"def",
"_is_descendant_of",
"(",
"self",
",",
"parent",
")",
":",
"if",
"self",
".",
"parent",
"is",
"None",
":",
"return",
"False",
"if",
"self",
".",
"parent",
"==",
"parent",
":",
"return",
"True",
"return",
"self",
".",
"parent",
".",
"_is_descendant... | 31.666667 | 0.00409 |
def new_message(cls, from_user, to_users, subject, content):
"""
Create a new Message and Thread.
Mark thread as unread for all recipients, and
mark thread as read and deleted from inbox by creator.
"""
thread = Thread.objects.create(subject=subject)
for user in ... | [
"def",
"new_message",
"(",
"cls",
",",
"from_user",
",",
"to_users",
",",
"subject",
",",
"content",
")",
":",
"thread",
"=",
"Thread",
".",
"objects",
".",
"create",
"(",
"subject",
"=",
"subject",
")",
"for",
"user",
"in",
"to_users",
":",
"thread",
... | 47 | 0.005961 |
def readUserSession(datafile):
"""
Reads the user session record from the file's cursor position
Args:
datafile: Data file whose cursor points at the beginning of the record
Returns:
list of pages in the order clicked by the user
"""
for line in datafile:
pages = line.split()
total = len(pa... | [
"def",
"readUserSession",
"(",
"datafile",
")",
":",
"for",
"line",
"in",
"datafile",
":",
"pages",
"=",
"line",
".",
"split",
"(",
")",
"total",
"=",
"len",
"(",
"pages",
")",
"# Select user sessions with 2 or more pages",
"if",
"total",
"<",
"2",
":",
"c... | 24.818182 | 0.010582 |
def wr_xlsx(fout_xlsx, data_xlsx, **kws):
"""Write a spreadsheet into a xlsx file."""
from goatools.wr_tbl_class import WrXlsx
# optional keyword args: fld2col_widths hdrs prt_if sort_by fld2fmt prt_flds
items_str = kws.get("items", "items") if "items" not in kws else kws["items"]
if data_xlsx:
... | [
"def",
"wr_xlsx",
"(",
"fout_xlsx",
",",
"data_xlsx",
",",
"*",
"*",
"kws",
")",
":",
"from",
"goatools",
".",
"wr_tbl_class",
"import",
"WrXlsx",
"# optional keyword args: fld2col_widths hdrs prt_if sort_by fld2fmt prt_flds",
"items_str",
"=",
"kws",
".",
"get",
"(",... | 46.318182 | 0.002885 |
def unregister(self, model):
"""
Unregister a permission handler from the model
Parameters
----------
model : django model class
A django model class
Raises
------
KeyError
Raise when the model have not registered in registry yet.... | [
"def",
"unregister",
"(",
"self",
",",
"model",
")",
":",
"if",
"model",
"not",
"in",
"self",
".",
"_registry",
":",
"raise",
"KeyError",
"(",
"\"A permission handler class have not been \"",
"\"registered for '%s' yet\"",
"%",
"model",
")",
"# remove from registry",
... | 29.052632 | 0.003509 |
def lookup_providers(self, lookup):
'''
Get a dict describing the configured providers
'''
if lookup is None:
lookup = 'all'
if lookup == 'all':
providers = set()
for alias, drivers in six.iteritems(self.opts['providers']):
for ... | [
"def",
"lookup_providers",
"(",
"self",
",",
"lookup",
")",
":",
"if",
"lookup",
"is",
"None",
":",
"lookup",
"=",
"'all'",
"if",
"lookup",
"==",
"'all'",
":",
"providers",
"=",
"set",
"(",
")",
"for",
"alias",
",",
"drivers",
"in",
"six",
".",
"iter... | 34.744186 | 0.001953 |
def _clean(self, t, capitalize=None):
"""Convert to normalized unicode and strip trailing full stops."""
if self._from_bibtex:
t = latex_to_unicode(t, capitalize=capitalize)
t = ' '.join([el.rstrip('.') if el.count('.') == 1 else el for el in t.split()])
return t | [
"def",
"_clean",
"(",
"self",
",",
"t",
",",
"capitalize",
"=",
"None",
")",
":",
"if",
"self",
".",
"_from_bibtex",
":",
"t",
"=",
"latex_to_unicode",
"(",
"t",
",",
"capitalize",
"=",
"capitalize",
")",
"t",
"=",
"' '",
".",
"join",
"(",
"[",
"el... | 50.333333 | 0.009772 |
def _get_nets_other(self, *args, **kwargs):
"""
Deprecated. This will be removed in a future release.
"""
from warnings import warn
warn('Whois._get_nets_other() has been deprecated and will be '
'removed. You should now use Whois.get_nets_other().')
return ... | [
"def",
"_get_nets_other",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"from",
"warnings",
"import",
"warn",
"warn",
"(",
"'Whois._get_nets_other() has been deprecated and will be '",
"'removed. You should now use Whois.get_nets_other().'",
")",
"retu... | 38.666667 | 0.005618 |
def get_challenge_for_url(url):
""" Gets the challenge for the cached URL.
:param url: the URL the challenge is cached for.
:rtype: HttpBearerChallenge """
if not url:
raise ValueError('URL cannot be None')
url = parse.urlparse(url)
_lock.acquire()
val = _cache.get(url.netloc)
... | [
"def",
"get_challenge_for_url",
"(",
"url",
")",
":",
"if",
"not",
"url",
":",
"raise",
"ValueError",
"(",
"'URL cannot be None'",
")",
"url",
"=",
"parse",
".",
"urlparse",
"(",
"url",
")",
"_lock",
".",
"acquire",
"(",
")",
"val",
"=",
"_cache",
".",
... | 21.125 | 0.002833 |
def from_dict(cls, d):
"""
Returns CompleteDos object from dict representation.
"""
tdos = PhononDos.from_dict(d)
struct = Structure.from_dict(d["structure"])
pdoss = {}
for at, pdos in zip(struct, d["pdos"]):
pdoss[at] = pdos
return cls(struc... | [
"def",
"from_dict",
"(",
"cls",
",",
"d",
")",
":",
"tdos",
"=",
"PhononDos",
".",
"from_dict",
"(",
"d",
")",
"struct",
"=",
"Structure",
".",
"from_dict",
"(",
"d",
"[",
"\"structure\"",
"]",
")",
"pdoss",
"=",
"{",
"}",
"for",
"at",
",",
"pdos",... | 29.545455 | 0.00597 |
def sample_u(self, q):
r"""Extract a sample from random variates uniform on :math:`[0, 1]`.
For a univariate distribution, this is simply evaluating the inverse
CDF. To facilitate efficient sampling, this function returns a *vector*
of PPF values, one value for each variable. Ba... | [
"def",
"sample_u",
"(",
"self",
",",
"q",
")",
":",
"q",
"=",
"scipy",
".",
"atleast_1d",
"(",
"q",
")",
"if",
"len",
"(",
"q",
")",
"!=",
"len",
"(",
"self",
".",
"sigma",
")",
":",
"raise",
"ValueError",
"(",
"\"length of q must equal the number of p... | 48.652174 | 0.006135 |
def icon(self, icontype_or_qfileinfo):
"""Reimplement Qt method"""
if isinstance(icontype_or_qfileinfo, QFileIconProvider.IconType):
return super(IconProvider, self).icon(icontype_or_qfileinfo)
else:
qfileinfo = icontype_or_qfileinfo
fname = osp.normpath... | [
"def",
"icon",
"(",
"self",
",",
"icontype_or_qfileinfo",
")",
":",
"if",
"isinstance",
"(",
"icontype_or_qfileinfo",
",",
"QFileIconProvider",
".",
"IconType",
")",
":",
"return",
"super",
"(",
"IconProvider",
",",
"self",
")",
".",
"icon",
"(",
"icontype_or_... | 53.75 | 0.004577 |
def get_line_and_char(newline_positions, position):
"""Given a list of newline positions, and an offset from the start of the source code
that newline_positions was pulled from, return a 2-tuple of (line, char) coordinates.
"""
if newline_positions:
for line_no, nl_pos in enumerate(newline_positions):
... | [
"def",
"get_line_and_char",
"(",
"newline_positions",
",",
"position",
")",
":",
"if",
"newline_positions",
":",
"for",
"line_no",
",",
"nl_pos",
"in",
"enumerate",
"(",
"newline_positions",
")",
":",
"if",
"nl_pos",
">=",
"position",
":",
"if",
"line_no",
"==... | 41.142857 | 0.01528 |
def load_attachments(self, source, skeleton):
'''Load attachment configuration from the given text source.
The attachment configuration file has a simple format. After discarding
Unix-style comments (any part of a line that starts with the pound (#)
character), each line in the file is ... | [
"def",
"load_attachments",
"(",
"self",
",",
"source",
",",
"skeleton",
")",
":",
"self",
".",
"targets",
"=",
"{",
"}",
"self",
".",
"offsets",
"=",
"{",
"}",
"filename",
"=",
"source",
"if",
"isinstance",
"(",
"source",
",",
"str",
")",
":",
"sourc... | 40.824561 | 0.002098 |
def make(ctx, check, version, initial_release, skip_sign, sign_only):
"""Perform a set of operations needed to release a single check:
\b
* update the version in __about__.py
* update the changelog
* update the requirements-agent-release.txt file
* update in-toto metadata
* commit... | [
"def",
"make",
"(",
"ctx",
",",
"check",
",",
"version",
",",
"initial_release",
",",
"skip_sign",
",",
"sign_only",
")",
":",
"# Import lazily since in-toto runs a subprocess to check for gpg2 on load",
"from",
".",
".",
"signing",
"import",
"update_link_metadata",
","... | 38.021739 | 0.002229 |
def _findMatchingBracket(self, bracket, qpart, block, columnIndex):
"""Find matching bracket for the bracket.
Return (block, columnIndex) or (None, None)
Raise _TimeoutException, if time is over
"""
if bracket in self._START_BRACKETS:
charsGenerator = self._iterateDoc... | [
"def",
"_findMatchingBracket",
"(",
"self",
",",
"bracket",
",",
"qpart",
",",
"block",
",",
"columnIndex",
")",
":",
"if",
"bracket",
"in",
"self",
".",
"_START_BRACKETS",
":",
"charsGenerator",
"=",
"self",
".",
"_iterateDocumentCharsForward",
"(",
"block",
... | 39.818182 | 0.004459 |
def refine_rotation(self):
"""
Helper method for refining rotation matrix by ensuring
that second and third rows are perpindicular to the first.
Gets new y vector from an orthogonal projection of x onto y
and the new z vector from a cross product of the new x and y
Args:... | [
"def",
"refine_rotation",
"(",
"self",
")",
":",
"new_x",
",",
"y",
"=",
"get_uvec",
"(",
"self",
"[",
"0",
"]",
")",
",",
"get_uvec",
"(",
"self",
"[",
"1",
"]",
")",
"# Get a projection on y",
"new_y",
"=",
"y",
"-",
"np",
".",
"dot",
"(",
"new_x... | 34.722222 | 0.003115 |
def write_file(self):
'''save config to local file'''
try:
with open(self.experiment_file, 'w') as file:
json.dump(self.experiments, file)
except IOError as error:
print('Error:', error)
return | [
"def",
"write_file",
"(",
"self",
")",
":",
"try",
":",
"with",
"open",
"(",
"self",
".",
"experiment_file",
",",
"'w'",
")",
"as",
"file",
":",
"json",
".",
"dump",
"(",
"self",
".",
"experiments",
",",
"file",
")",
"except",
"IOError",
"as",
"error... | 32.75 | 0.007435 |
def purge_tokens(self, input_token_attrs=None):
""" Removes all specified token_attrs that exist in instance.token_attrs
:param token_attrs: list(str), list of string values of tokens to remove. If None, removes all
"""
if input_token_attrs is None:
remove_attrs = s... | [
"def",
"purge_tokens",
"(",
"self",
",",
"input_token_attrs",
"=",
"None",
")",
":",
"if",
"input_token_attrs",
"is",
"None",
":",
"remove_attrs",
"=",
"self",
".",
"token_attrs",
"else",
":",
"remove_attrs",
"=",
"[",
"token_attr",
"for",
"token_attr",
"in",
... | 51.363636 | 0.012174 |
def handle_moban_file(moban_file, options):
"""
act upon default moban file
"""
moban_file_configurations = load_data(None, moban_file)
if moban_file_configurations is None:
raise exceptions.MobanfileGrammarException(
constants.ERROR_INVALID_MOBAN_FILE % moban_file
)
... | [
"def",
"handle_moban_file",
"(",
"moban_file",
",",
"options",
")",
":",
"moban_file_configurations",
"=",
"load_data",
"(",
"None",
",",
"moban_file",
")",
"if",
"moban_file_configurations",
"is",
"None",
":",
"raise",
"exceptions",
".",
"MobanfileGrammarException",
... | 37.555556 | 0.000962 |
def count(self, elem):
"""
Return the number of elements equal to elem present in the queue
>>> pdeque([1, 2, 1]).count(1)
2
"""
return self._left_list.count(elem) + self._right_list.count(elem) | [
"def",
"count",
"(",
"self",
",",
"elem",
")",
":",
"return",
"self",
".",
"_left_list",
".",
"count",
"(",
"elem",
")",
"+",
"self",
".",
"_right_list",
".",
"count",
"(",
"elem",
")"
] | 29.5 | 0.00823 |
def clean_fsbackend(opts):
'''
Clean out the old fileserver backends
'''
# Clear remote fileserver backend caches so they get recreated
for backend in ('git', 'hg', 'svn'):
if backend in opts['fileserver_backend']:
env_cache = os.path.join(
opts['cachedir'],
... | [
"def",
"clean_fsbackend",
"(",
"opts",
")",
":",
"# Clear remote fileserver backend caches so they get recreated",
"for",
"backend",
"in",
"(",
"'git'",
",",
"'hg'",
",",
"'svn'",
")",
":",
"if",
"backend",
"in",
"opts",
"[",
"'fileserver_backend'",
"]",
":",
"env... | 35.825 | 0.000679 |
def _get_section(self, event):
"""Get the section of the paper that the event is from."""
sentence_id = event.get('sentence')
section = None
if sentence_id:
qstr = "$.sentences.frames[(@.frame_id is \'%s\')]" % sentence_id
res = self.tree.execute(qstr)
... | [
"def",
"_get_section",
"(",
"self",
",",
"event",
")",
":",
"sentence_id",
"=",
"event",
".",
"get",
"(",
"'sentence'",
")",
"section",
"=",
"None",
"if",
"sentence_id",
":",
"qstr",
"=",
"\"$.sentences.frames[(@.frame_id is \\'%s\\')]\"",
"%",
"sentence_id",
"r... | 40.714286 | 0.001371 |
def get_queryset_by_group_and_key(self, group, key=None):
"""get queryset"""
if key is None:
return self.filter_by(group=group)
else:
return self.filter_by(group=group, key=key) | [
"def",
"get_queryset_by_group_and_key",
"(",
"self",
",",
"group",
",",
"key",
"=",
"None",
")",
":",
"if",
"key",
"is",
"None",
":",
"return",
"self",
".",
"filter_by",
"(",
"group",
"=",
"group",
")",
"else",
":",
"return",
"self",
".",
"filter_by",
... | 31.428571 | 0.00885 |
def existing_analysis(using):
"""
Get the existing analysis for the `using` Elasticsearch connection
"""
es = connections.get_connection(using)
index_name = settings.ELASTICSEARCH_CONNECTIONS[using]['index_name']
if es.indices.exists(index=index_name):
return stringer(es.indices.get_sett... | [
"def",
"existing_analysis",
"(",
"using",
")",
":",
"es",
"=",
"connections",
".",
"get_connection",
"(",
"using",
")",
"index_name",
"=",
"settings",
".",
"ELASTICSEARCH_CONNECTIONS",
"[",
"using",
"]",
"[",
"'index_name'",
"]",
"if",
"es",
".",
"indices",
... | 46 | 0.004739 |
def _send(saltdata, metric_base, opts):
'''
Send the data to carbon
'''
host = opts.get('host')
port = opts.get('port')
skip = opts.get('skip')
metric_base_pattern = opts.get('carbon.metric_base_pattern')
mode = opts.get('mode').lower() if 'mode' in opts else 'text'
log.debug('Carb... | [
"def",
"_send",
"(",
"saltdata",
",",
"metric_base",
",",
"opts",
")",
":",
"host",
"=",
"opts",
".",
"get",
"(",
"'host'",
")",
"port",
"=",
"opts",
".",
"get",
"(",
"'port'",
")",
"skip",
"=",
"opts",
".",
"get",
"(",
"'skip'",
")",
"metric_base_... | 35.225 | 0.002072 |
def _notify_mutated(self, obj, old, hint=None):
''' A method to call when a container is mutated "behind our back"
and we detect it with our |PropertyContainer| wrappers.
Args:
obj (HasProps) :
The object who's container value was mutated
old (object) :
... | [
"def",
"_notify_mutated",
"(",
"self",
",",
"obj",
",",
"old",
",",
"hint",
"=",
"None",
")",
":",
"value",
"=",
"self",
".",
"__get__",
"(",
"obj",
",",
"obj",
".",
"__class__",
")",
"# re-validate because the contents of 'old' have changed,",
"# in some cases ... | 36.558824 | 0.001567 |
def _get_vqsr_annotations(filter_type, data):
"""Retrieve appropriate annotations to use for VQSR based on filter type.
Issues reported with MQ and bwa-mem quality distribution, results in intermittent
failures to use VQSR:
http://gatkforums.broadinstitute.org/discussion/4425/variant-recalibration-fail... | [
"def",
"_get_vqsr_annotations",
"(",
"filter_type",
",",
"data",
")",
":",
"if",
"filter_type",
"==",
"\"SNP\"",
":",
"# MQ, MQRankSum",
"anns",
"=",
"[",
"\"QD\"",
",",
"\"FS\"",
",",
"\"ReadPosRankSum\"",
",",
"\"SOR\"",
"]",
"else",
":",
"assert",
"filter_t... | 41.555556 | 0.002614 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.