text stringlengths 89 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 630 |
|---|---|---|---|
def parse_duration(duration):
"""Attepmts to parse an ISO8601 formatted ``duration``.
Returns a ``datetime.timedelta`` object.
"""
duration = str(duration).upper().strip()
elements = ELEMENTS.copy()
for pattern in (SIMPLE_DURATION, COMBINED_DURATION):
if pattern.match(duration):
... | [
"def",
"parse_duration",
"(",
"duration",
")",
":",
"duration",
"=",
"str",
"(",
"duration",
")",
".",
"upper",
"(",
")",
".",
"strip",
"(",
")",
"elements",
"=",
"ELEMENTS",
".",
"copy",
"(",
")",
"for",
"pattern",
"in",
"(",
"SIMPLE_DURATION",
",",
... | 37.846154 | 20.692308 |
def add_setting(self, name, value):
'''
Adds a database setting that will be sent with every request.
For example, `db.add_setting("max_execution_time", 10)` will
limit query execution time to 10 seconds.
The name must be string, and the value is converted to string in case
... | [
"def",
"add_setting",
"(",
"self",
",",
"name",
",",
"value",
")",
":",
"assert",
"isinstance",
"(",
"name",
",",
"string_types",
")",
",",
"'Setting name must be a string'",
"if",
"value",
"is",
"None",
":",
"self",
".",
"settings",
".",
"pop",
"(",
"name... | 45 | 21.153846 |
def delete(self):
"""Stop the profiler."""
CProfileWrapper.profiler.disable()
self.running = False
self.set_status(204)
self.finish() | [
"def",
"delete",
"(",
"self",
")",
":",
"CProfileWrapper",
".",
"profiler",
".",
"disable",
"(",
")",
"self",
".",
"running",
"=",
"False",
"self",
".",
"set_status",
"(",
"204",
")",
"self",
".",
"finish",
"(",
")"
] | 28 | 11.333333 |
def from_shorthand(self, shorthand):
"""Convert from traditional Helmhotz pitch notation.
Examples:
>>> Note().from_shorthand("C,,")
'C-0'
>>> Note().from_shorthand("C")
'C-2'
>>> Note().from_shorthand("c'")
'C-4'
"""
name = ''
oct... | [
"def",
"from_shorthand",
"(",
"self",
",",
"shorthand",
")",
":",
"name",
"=",
"''",
"octave",
"=",
"0",
"for",
"x",
"in",
"shorthand",
":",
"if",
"x",
"in",
"[",
"'a'",
",",
"'b'",
",",
"'c'",
",",
"'d'",
",",
"'e'",
",",
"'f'",
",",
"'g'",
"]... | 28.777778 | 13.851852 |
def pad(self, sid, date):
"""
Fill sid container with empty data through the specified date.
If the last recorded trade is not at the close, then that day will be
padded with zeros until its close. Any day after that (up to and
including the specified date) will be padded with `... | [
"def",
"pad",
"(",
"self",
",",
"sid",
",",
"date",
")",
":",
"table",
"=",
"self",
".",
"_ensure_ctable",
"(",
"sid",
")",
"last_date",
"=",
"self",
".",
"last_date_in_output_for_sid",
"(",
"sid",
")",
"tds",
"=",
"self",
".",
"_session_labels",
"if",
... | 36.285714 | 22.857143 |
def make_random_histogram(center=0.0, stdev=default_stdev, length=default_feature_dim, num_bins=default_num_bins):
"Returns a sequence of histogram density values that sum to 1.0"
hist, bin_edges = np.histogram(get_distr(center, stdev, length),
range=edge_range, bins=num_bins... | [
"def",
"make_random_histogram",
"(",
"center",
"=",
"0.0",
",",
"stdev",
"=",
"default_stdev",
",",
"length",
"=",
"default_feature_dim",
",",
"num_bins",
"=",
"default_num_bins",
")",
":",
"hist",
",",
"bin_edges",
"=",
"np",
".",
"histogram",
"(",
"get_distr... | 40.083333 | 29.25 |
def wraps(self, f):
"""Wrap a function for retrying.
:param f: A function to wraps for retrying.
"""
@_utils.wraps(f)
def wrapped_f(*args, **kw):
return self.call(f, *args, **kw)
def retry_with(*args, **kwargs):
return self.copy(*args, **kwargs).... | [
"def",
"wraps",
"(",
"self",
",",
"f",
")",
":",
"@",
"_utils",
".",
"wraps",
"(",
"f",
")",
"def",
"wrapped_f",
"(",
"*",
"args",
",",
"*",
"*",
"kw",
")",
":",
"return",
"self",
".",
"call",
"(",
"f",
",",
"*",
"args",
",",
"*",
"*",
"kw"... | 25.8125 | 16.125 |
def verify_dataset():
"""Perform checks on experimental datasets"""
parser = verify_dataset_parser()
args = parser.parse_args()
path_in = pathlib.Path(args.path).resolve()
viol, aler, info = load.check_dataset(path_in)
print_info("Checking {}".format(path_in))
for inf in info:
print_... | [
"def",
"verify_dataset",
"(",
")",
":",
"parser",
"=",
"verify_dataset_parser",
"(",
")",
"args",
"=",
"parser",
".",
"parse_args",
"(",
")",
"path_in",
"=",
"pathlib",
".",
"Path",
"(",
"args",
".",
"path",
")",
".",
"resolve",
"(",
")",
"viol",
",",
... | 38 | 15.8 |
def create_datastore_from_yaml_schema(self, yaml_path, delete_first=0,
path=None):
# type: (str, Optional[int], Optional[str]) -> None
"""For tabular data, create a resource in the HDX datastore which enables data preview in HDX from a YAML file
containi... | [
"def",
"create_datastore_from_yaml_schema",
"(",
"self",
",",
"yaml_path",
",",
"delete_first",
"=",
"0",
",",
"path",
"=",
"None",
")",
":",
"# type: (str, Optional[int], Optional[str]) -> None",
"data",
"=",
"load_yaml",
"(",
"yaml_path",
")",
"self",
".",
"create... | 57.941176 | 33.882353 |
def get_app_model_voice(self, app_model_item):
""" App Model voice
Returns the js menu compatible voice dict if the user
can see it, None otherwise
"""
if app_model_item.get('name', None) is None:
raise ImproperlyConfigured('Model menu voices must have a name ... | [
"def",
"get_app_model_voice",
"(",
"self",
",",
"app_model_item",
")",
":",
"if",
"app_model_item",
".",
"get",
"(",
"'name'",
",",
"None",
")",
"is",
"None",
":",
"raise",
"ImproperlyConfigured",
"(",
"'Model menu voices must have a name key'",
")",
"# noqa",
"if... | 45.166667 | 22.333333 |
def place_docker(self, docker, area='top'):
"""
IN DEVELOPMENT
Places a DockWindow instance at the specified area ('top', 'bottom',
'left', 'right', or None)
"""
# map of options
m = dict(top = _g.QtCore.Qt.TopDockWidgetArea,
bottom = ... | [
"def",
"place_docker",
"(",
"self",
",",
"docker",
",",
"area",
"=",
"'top'",
")",
":",
"# map of options",
"m",
"=",
"dict",
"(",
"top",
"=",
"_g",
".",
"QtCore",
".",
"Qt",
".",
"TopDockWidgetArea",
",",
"bottom",
"=",
"_g",
".",
"QtCore",
".",
"Qt... | 32.851852 | 19.740741 |
def set_autosession(self, value=None):
"""
Turn autosession (automatic committing after each modification call) on/off.
If value is None, only query the current value (don't change anything).
"""
if value is not None:
self.rollback()
self.autosession = val... | [
"def",
"set_autosession",
"(",
"self",
",",
"value",
"=",
"None",
")",
":",
"if",
"value",
"is",
"not",
"None",
":",
"self",
".",
"rollback",
"(",
")",
"self",
".",
"autosession",
"=",
"value",
"return",
"self",
".",
"autosession"
] | 38.444444 | 13.555556 |
def encodeEntitiesReentrant(self, input):
"""Do a global encoding of a string, replacing the predefined
entities and non ASCII values with their entities and
CharRef counterparts. Contrary to xmlEncodeEntities, this
routine is reentrant, and result must be deallocated. """
... | [
"def",
"encodeEntitiesReentrant",
"(",
"self",
",",
"input",
")",
":",
"ret",
"=",
"libxml2mod",
".",
"xmlEncodeEntitiesReentrant",
"(",
"self",
".",
"_o",
",",
"input",
")",
"return",
"ret"
] | 56.142857 | 14.285714 |
def add_genes(in_file, data, max_distance=10000, work_dir=None):
"""Add gene annotations to a BED file from pre-prepared RNA-seq data.
max_distance -- only keep annotations within this distance of event
"""
gene_file = regions.get_sv_bed(data, "exons", out_dir=os.path.dirname(in_file))
if gene_file... | [
"def",
"add_genes",
"(",
"in_file",
",",
"data",
",",
"max_distance",
"=",
"10000",
",",
"work_dir",
"=",
"None",
")",
":",
"gene_file",
"=",
"regions",
".",
"get_sv_bed",
"(",
"data",
",",
"\"exons\"",
",",
"out_dir",
"=",
"os",
".",
"path",
".",
"dir... | 49.294118 | 24.117647 |
def convert_frames_to_video(tar_file_path, output_path="output.mp4", framerate=60, overwrite=False):
"""
Try to convert a tar file containing a sequence of frames saved by the
meshcat viewer into a single video file.
This relies on having `ffmpeg` installed on your system.
"""
output_path = os.... | [
"def",
"convert_frames_to_video",
"(",
"tar_file_path",
",",
"output_path",
"=",
"\"output.mp4\"",
",",
"framerate",
"=",
"60",
",",
"overwrite",
"=",
"False",
")",
":",
"output_path",
"=",
"os",
".",
"path",
".",
"abspath",
"(",
"output_path",
")",
"if",
"o... | 43.735294 | 18.352941 |
def _pelita_member_filter(parent_name, item_names):
"""
Filter a list of autodoc items for which to generate documentation.
Include only imports that come from the documented module or its
submodules.
"""
filtered_names = []
if parent_name not in sys.modules:
return item_names
... | [
"def",
"_pelita_member_filter",
"(",
"parent_name",
",",
"item_names",
")",
":",
"filtered_names",
"=",
"[",
"]",
"if",
"parent_name",
"not",
"in",
"sys",
".",
"modules",
":",
"return",
"item_names",
"module",
"=",
"sys",
".",
"modules",
"[",
"parent_name",
... | 28.181818 | 20.727273 |
def start(name):
# type: (str) -> None
""" Start working on a new feature by branching off develop.
This will create a new branch off develop called feature/<name>.
Args:
name (str):
The name of the new feature.
"""
branch = git.current_branch(refresh=True)
task_branch ... | [
"def",
"start",
"(",
"name",
")",
":",
"# type: (str) -> None",
"branch",
"=",
"git",
".",
"current_branch",
"(",
"refresh",
"=",
"True",
")",
"task_branch",
"=",
"'task/'",
"+",
"common",
".",
"to_branch_name",
"(",
"name",
")",
"if",
"branch",
".",
"type... | 30.368421 | 19.473684 |
def _validate_organization_data(organization_data):
""" Validation helper """
if not validators.organization_data_is_valid(organization_data):
exceptions.raise_exception(
"Organization",
organization_data,
exceptions.InvalidOrganizationException
) | [
"def",
"_validate_organization_data",
"(",
"organization_data",
")",
":",
"if",
"not",
"validators",
".",
"organization_data_is_valid",
"(",
"organization_data",
")",
":",
"exceptions",
".",
"raise_exception",
"(",
"\"Organization\"",
",",
"organization_data",
",",
"exc... | 37.5 | 13.625 |
def cast(self, dtype):
"""Cast data and gradient of this Parameter to a new data type.
Parameters
----------
dtype : str or numpy.dtype
The new data type.
"""
self.dtype = dtype
if self._data is None:
return
with autograd.pause():
... | [
"def",
"cast",
"(",
"self",
",",
"dtype",
")",
":",
"self",
".",
"dtype",
"=",
"dtype",
"if",
"self",
".",
"_data",
"is",
"None",
":",
"return",
"with",
"autograd",
".",
"pause",
"(",
")",
":",
"self",
".",
"_data",
"=",
"[",
"i",
".",
"astype",
... | 33.058824 | 16.235294 |
def format_person_name(text):
"""Capitalize first letter for each part of the name.
Example::
person_name = "James Bond"
**中文文档**
将文本修改为人名格式。每个单词的第一个字母大写。
"""
text = text.strip()
if len(text) == 0: # if empty string, return it
return text
else:
text = text.lo... | [
"def",
"format_person_name",
"(",
"text",
")",
":",
"text",
"=",
"text",
".",
"strip",
"(",
")",
"if",
"len",
"(",
"text",
")",
"==",
"0",
":",
"# if empty string, return it",
"return",
"text",
"else",
":",
"text",
"=",
"text",
".",
"lower",
"(",
")",
... | 26.7 | 20 |
def add_collaboration(self, collaboration):
"""Add collaboration.
:param collaboration: collaboration for the current document
:type collaboration: string
"""
collaborations = normalize_collaboration(collaboration)
for collaboration in collaborations:
self._a... | [
"def",
"add_collaboration",
"(",
"self",
",",
"collaboration",
")",
":",
"collaborations",
"=",
"normalize_collaboration",
"(",
"collaboration",
")",
"for",
"collaboration",
"in",
"collaborations",
":",
"self",
".",
"_append_to",
"(",
"'collaborations'",
",",
"{",
... | 35.636364 | 12.545455 |
def is_colliding(self, other):
"""Check to see if two circles are colliding."""
if isinstance(other, BoundingCircle):
#Calculate the distance between two circles.
distance = Vector2.distance(self.coords, other.coords)
#Check to see if the sum of thier radi are greate... | [
"def",
"is_colliding",
"(",
"self",
",",
"other",
")",
":",
"if",
"isinstance",
"(",
"other",
",",
"BoundingCircle",
")",
":",
"#Calculate the distance between two circles.",
"distance",
"=",
"Vector2",
".",
"distance",
"(",
"self",
".",
"coords",
",",
"other",
... | 41.705882 | 21.588235 |
def inverse_transform(self, X):
"""Transform data back to its original space.
Returns an array X_original whose transform would be X.
Parameters
----------
X : array-like, shape (n_samples, n_components)
New data, where n_samples in the number of samples
... | [
"def",
"inverse_transform",
"(",
"self",
",",
"X",
")",
":",
"check_is_fitted",
"(",
"self",
",",
"\"mean_\"",
")",
"if",
"self",
".",
"whiten",
":",
"return",
"(",
"da",
".",
"dot",
"(",
"X",
",",
"np",
".",
"sqrt",
"(",
"self",
".",
"explained_vari... | 29.5 | 22.5 |
def prepare_table(table):
"""Make the table 'symmetric' where the lower left part of the matrix is
the reverse probability
"""
n = len(table)
for i, row in enumerate(table):
assert len(row) == n
for j, el in enumerate(row):
if i == j:
table[i][i] = 0.0
... | [
"def",
"prepare_table",
"(",
"table",
")",
":",
"n",
"=",
"len",
"(",
"table",
")",
"for",
"i",
",",
"row",
"in",
"enumerate",
"(",
"table",
")",
":",
"assert",
"len",
"(",
"row",
")",
"==",
"n",
"for",
"j",
",",
"el",
"in",
"enumerate",
"(",
"... | 30.153846 | 10.538462 |
def deliver(self, project, new_project_name, to_user, share_users, force_send, path_filter, user_message):
"""
Remove access to project_name for to_user, copy to new_project_name if not None,
send message to service to email user so they can have access.
:param project: RemoteProject pre... | [
"def",
"deliver",
"(",
"self",
",",
"project",
",",
"new_project_name",
",",
"to_user",
",",
"share_users",
",",
"force_send",
",",
"path_filter",
",",
"user_message",
")",
":",
"if",
"self",
".",
"_is_current_user",
"(",
"to_user",
")",
":",
"raise",
"Share... | 67 | 31.727273 |
def Hakim_Steinberg_Stiel(T, Tc, Pc, omega, StielPolar=0):
r'''Calculates air-water surface tension using the reference fluids methods
of [1]_.
.. math::
\sigma = 4.60104\times 10^{-7} P_c^{2/3}T_c^{1/3}Q_p \left(\frac{1-T_r}{0.4}\right)^m
Q_p = 0.1574+0.359\omega-1.769\chi-13.69\chi^2-0.5... | [
"def",
"Hakim_Steinberg_Stiel",
"(",
"T",
",",
"Tc",
",",
"Pc",
",",
"omega",
",",
"StielPolar",
"=",
"0",
")",
":",
"Q",
"=",
"(",
"0.1574",
"+",
"0.359",
"*",
"omega",
"-",
"1.769",
"*",
"StielPolar",
"-",
"13.69",
"*",
"StielPolar",
"**",
"2",
"... | 31.25 | 26.357143 |
def to_vcf(in_tsv, data):
"""Convert seq2c output file into BED output.
"""
call_convert = {"Amp": "DUP", "Del": "DEL"}
out_file = "%s.vcf" % utils.splitext_plus(in_tsv)[0]
if not utils.file_uptodate(out_file, in_tsv):
with file_transaction(data, out_file) as tx_out_file:
with op... | [
"def",
"to_vcf",
"(",
"in_tsv",
",",
"data",
")",
":",
"call_convert",
"=",
"{",
"\"Amp\"",
":",
"\"DUP\"",
",",
"\"Del\"",
":",
"\"DEL\"",
"}",
"out_file",
"=",
"\"%s.vcf\"",
"%",
"utils",
".",
"splitext_plus",
"(",
"in_tsv",
")",
"[",
"0",
"]",
"if",... | 64.714286 | 27.285714 |
def delete(self, obj):
"""Required functionality."""
del_id = obj.get_id()
if not del_id:
return
cur = self._conn().cursor()
tabname = obj.__class__.get_table_name()
query = 'delete from %s where id = ?' % tabname
cur.execute(query, (del_id,))
... | [
"def",
"delete",
"(",
"self",
",",
"obj",
")",
":",
"del_id",
"=",
"obj",
".",
"get_id",
"(",
")",
"if",
"not",
"del_id",
":",
"return",
"cur",
"=",
"self",
".",
"_conn",
"(",
")",
".",
"cursor",
"(",
")",
"tabname",
"=",
"obj",
".",
"__class__",... | 25.071429 | 18 |
def logout(cache):
"""
Logs out the current session by removing it from the cache. This is
expected to only occur when a session has
"""
cache.set(flask.session['auth0_key'], None)
flask.session.clear()
return True | [
"def",
"logout",
"(",
"cache",
")",
":",
"cache",
".",
"set",
"(",
"flask",
".",
"session",
"[",
"'auth0_key'",
"]",
",",
"None",
")",
"flask",
".",
"session",
".",
"clear",
"(",
")",
"return",
"True"
] | 29.375 | 13.125 |
def from_dict(cls, d, encoding='base64'):
'''
Construct a ``Report`` object from dictionary.
:type d: dictionary
:param d: dictionary representing the report
:param encoding: encoding of strings in the dictionary (default: 'base64')
:return: Report object
'''
... | [
"def",
"from_dict",
"(",
"cls",
",",
"d",
",",
"encoding",
"=",
"'base64'",
")",
":",
"report",
"=",
"Report",
"(",
"Report",
".",
"_decode",
"(",
"d",
"[",
"'name'",
"]",
",",
"encoding",
")",
")",
"report",
".",
"set_status",
"(",
"Report",
".",
... | 37.565217 | 19.478261 |
def delete_GitHub_token(token_id, *, auth, headers):
"""Delete a temporary GitHub token"""
r = requests.delete('https://api.github.com/authorizations/{id}'.format(id=token_id), auth=auth, headers=headers)
GitHub_raise_for_status(r) | [
"def",
"delete_GitHub_token",
"(",
"token_id",
",",
"*",
",",
"auth",
",",
"headers",
")",
":",
"r",
"=",
"requests",
".",
"delete",
"(",
"'https://api.github.com/authorizations/{id}'",
".",
"format",
"(",
"id",
"=",
"token_id",
")",
",",
"auth",
"=",
"auth"... | 60 | 24.75 |
def api_request(api_base_url='http://localhost:8080/', path='', method='get',
data=None, params={}, verify=True, cert=list()):
"""
Wrapper function for requests
:param api_base_url: Base URL for requests
:param path: Path to request
:param method: HTTP method
:param data: Data for post (ign... | [
"def",
"api_request",
"(",
"api_base_url",
"=",
"'http://localhost:8080/'",
",",
"path",
"=",
"''",
",",
"method",
"=",
"'get'",
",",
"data",
"=",
"None",
",",
"params",
"=",
"{",
"}",
",",
"verify",
"=",
"True",
",",
"cert",
"=",
"list",
"(",
")",
"... | 33.806452 | 17.741935 |
def get_context_dict(self):
""" return a context dict of the desired state """
context_dict = {}
for s in self.sections():
for k, v in self.manifest.items(s):
context_dict["%s:%s" % (s, k)] = v
for k, v in self.inputs.values().items():
context_dict... | [
"def",
"get_context_dict",
"(",
"self",
")",
":",
"context_dict",
"=",
"{",
"}",
"for",
"s",
"in",
"self",
".",
"sections",
"(",
")",
":",
"for",
"k",
",",
"v",
"in",
"self",
".",
"manifest",
".",
"items",
"(",
"s",
")",
":",
"context_dict",
"[",
... | 50.090909 | 17.181818 |
def apply_custom_filter(self, filter_func, to_ngrams=False):
"""
Apply a custom filter function `filter_func` to all tokens or ngrams (if `to_ngrams` is True).
`filter_func` must accept a single parameter: a dictionary of structure `{<doc_label>: <tokens list>}`. It
must return a diction... | [
"def",
"apply_custom_filter",
"(",
"self",
",",
"filter_func",
",",
"to_ngrams",
"=",
"False",
")",
":",
"# Because it is not possible to send a function to the workers, all tokens must be fetched from the workers",
"# first and then the custom function is called and run in a single proces... | 39.438596 | 24.45614 |
def get_num_nodes(properties=None, hadoop_conf_dir=None, offline=False):
"""
Get the number of task trackers in the Hadoop cluster.
All arguments are passed to :func:`get_task_trackers`.
"""
return len(get_task_trackers(properties, hadoop_conf_dir, offline)) | [
"def",
"get_num_nodes",
"(",
"properties",
"=",
"None",
",",
"hadoop_conf_dir",
"=",
"None",
",",
"offline",
"=",
"False",
")",
":",
"return",
"len",
"(",
"get_task_trackers",
"(",
"properties",
",",
"hadoop_conf_dir",
",",
"offline",
")",
")"
] | 39 | 19.857143 |
def contains_vasp_input(dir_name):
"""
Checks if a directory contains valid VASP input.
Args:
dir_name:
Directory name to check.
Returns:
True if directory contains all four VASP input files (INCAR, POSCAR,
KPOINTS and POTCAR).
"""
for f in ["INCAR", "POSCAR... | [
"def",
"contains_vasp_input",
"(",
"dir_name",
")",
":",
"for",
"f",
"in",
"[",
"\"INCAR\"",
",",
"\"POSCAR\"",
",",
"\"POTCAR\"",
",",
"\"KPOINTS\"",
"]",
":",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"os",
".",
"path",
".",
"join",
"(",
... | 29.705882 | 20.058824 |
def filter_callbacks(cls, client, event_data):
"""Filter registered events and yield all of their callbacks."""
for event in cls.filter_events(client, event_data):
for cb in event.callbacks:
yield cb | [
"def",
"filter_callbacks",
"(",
"cls",
",",
"client",
",",
"event_data",
")",
":",
"for",
"event",
"in",
"cls",
".",
"filter_events",
"(",
"client",
",",
"event_data",
")",
":",
"for",
"cb",
"in",
"event",
".",
"callbacks",
":",
"yield",
"cb"
] | 39.833333 | 13.833333 |
def fit_bristow_campbell_params(tmin, tmax, pot_rad_daily, obs_rad_daily):
"""
Fit the A and C parameters for the Bristow & Campbell (1984) model using observed daily
minimum and maximum temperature and mean daily (e.g. aggregated from hourly values) solar
radiation.
Parameters
---------... | [
"def",
"fit_bristow_campbell_params",
"(",
"tmin",
",",
"tmax",
",",
"pot_rad_daily",
",",
"obs_rad_daily",
")",
":",
"def",
"bc_absbias",
"(",
"ac",
")",
":",
"return",
"np",
".",
"abs",
"(",
"np",
".",
"mean",
"(",
"bristow_campbell",
"(",
"df",
".",
"... | 34.925926 | 28.333333 |
def Dropout(p=0, per_channel=False, name=None, deterministic=False, random_state=None):
"""
Augmenter that sets a certain fraction of pixels in images to zero.
dtype support::
See ``imgaug.augmenters.arithmetic.MultiplyElementwise``.
Parameters
----------
p : float or tuple of float o... | [
"def",
"Dropout",
"(",
"p",
"=",
"0",
",",
"per_channel",
"=",
"False",
",",
"name",
"=",
"None",
",",
"deterministic",
"=",
"False",
",",
"random_state",
"=",
"None",
")",
":",
"if",
"ia",
".",
"is_single_number",
"(",
"p",
")",
":",
"p2",
"=",
"i... | 39.204819 | 26.120482 |
def html_to_text(html, base_url='', bodywidth=CONFIG_DEFAULT):
"""
Convert a HTML mesasge to plain text.
"""
def _patched_handle_charref(c):
self = h
charref = self.charref(c)
if self.code or self.pre:
charref = cgi.escape(charref)
self.o(charref, 1)
def ... | [
"def",
"html_to_text",
"(",
"html",
",",
"base_url",
"=",
"''",
",",
"bodywidth",
"=",
"CONFIG_DEFAULT",
")",
":",
"def",
"_patched_handle_charref",
"(",
"c",
")",
":",
"self",
"=",
"h",
"charref",
"=",
"self",
".",
"charref",
"(",
"c",
")",
"if",
"sel... | 35 | 14.818182 |
def get_es_label(obj, def_obj):
"""
Returns object with label for an object that goes into the elacticsearch
'label' field
args:
obj: data object to update
def_obj: the class instance that has defintion values
"""
label_flds = LABEL_FIELDS
if def_obj.es_defs.get('kds_esLabel... | [
"def",
"get_es_label",
"(",
"obj",
",",
"def_obj",
")",
":",
"label_flds",
"=",
"LABEL_FIELDS",
"if",
"def_obj",
".",
"es_defs",
".",
"get",
"(",
"'kds_esLabel'",
")",
":",
"label_flds",
"=",
"def_obj",
".",
"es_defs",
"[",
"'kds_esLabel'",
"]",
"+",
"LABE... | 36.357143 | 17.357143 |
def harvest_fundref(source=None):
"""Harvest funders from FundRef and store as authority records."""
loader = LocalFundRefLoader(source=source) if source \
else RemoteFundRefLoader()
for funder_json in loader.iter_funders():
register_funder.delay(funder_json) | [
"def",
"harvest_fundref",
"(",
"source",
"=",
"None",
")",
":",
"loader",
"=",
"LocalFundRefLoader",
"(",
"source",
"=",
"source",
")",
"if",
"source",
"else",
"RemoteFundRefLoader",
"(",
")",
"for",
"funder_json",
"in",
"loader",
".",
"iter_funders",
"(",
"... | 47 | 6.333333 |
def _qkey_to_ascii(event):
"""
(Try to) convert the Qt key event to the corresponding ASCII sequence for
the terminal. This works fine for standard alphanumerical characters, but
most other characters require terminal specific control_modifier sequences.
The conversion below works for TERM="linux' t... | [
"def",
"_qkey_to_ascii",
"(",
"event",
")",
":",
"if",
"sys",
".",
"platform",
"==",
"'darwin'",
":",
"control_modifier",
"=",
"QtCore",
".",
"Qt",
".",
"MetaModifier",
"else",
":",
"control_modifier",
"=",
"QtCore",
".",
"Qt",
".",
"ControlModifier",
"ctrl"... | 38.215054 | 11.333333 |
def build_stack_docs(root_project_dir, skippedNames=None):
"""Build stack Sphinx documentation (main entrypoint).
Parameters
----------
root_project_dir : `str`
Path to the root directory of the main documentation project. This
is the directory containing the ``conf.py`` file.
skipp... | [
"def",
"build_stack_docs",
"(",
"root_project_dir",
",",
"skippedNames",
"=",
"None",
")",
":",
"logger",
"=",
"logging",
".",
"getLogger",
"(",
"__name__",
")",
"# Create the directory where module content is symlinked",
"# NOTE: this path is hard-wired in for pipelines.lsst.i... | 40.225 | 18.4375 |
def init_from_acceptor(self, acceptor):
"""
Adds a sink state
Args:
alphabet (list): The input alphabet
Returns:
None
"""
self.states = copy.deepcopy(acceptor.states)
self.alphabet = copy.deepcopy(acceptor.alphabet)
self.osyms = cop... | [
"def",
"init_from_acceptor",
"(",
"self",
",",
"acceptor",
")",
":",
"self",
".",
"states",
"=",
"copy",
".",
"deepcopy",
"(",
"acceptor",
".",
"states",
")",
"self",
".",
"alphabet",
"=",
"copy",
".",
"deepcopy",
"(",
"acceptor",
".",
"alphabet",
")",
... | 32.166667 | 12.166667 |
def main(*kw):
"""Command line entry point; arguments must match those defined in
in :meth:`create_parser()`; returns 0 for success, else 1.
Example::
command.main("-i", "**/*.py", "--no-default-excludes")
Runs formic printing out all .py files in the current working directory
and its child... | [
"def",
"main",
"(",
"*",
"kw",
")",
":",
"parser",
"=",
"create_parser",
"(",
")",
"args",
"=",
"parser",
".",
"parse_args",
"(",
"kw",
"if",
"kw",
"else",
"None",
")",
"if",
"args",
".",
"help",
":",
"parser",
".",
"print_help",
"(",
")",
"elif",
... | 30.818966 | 23.068966 |
def non_structured_query(table, query=None, **kwargs):
'''
Run a non-structed (not a dict) query on a servicenow table.
See http://wiki.servicenow.com/index.php?title=Encoded_Query_Strings#gsc.tab=0
for help on constructing a non-structured query string.
:param table: The table name, e.g. sys_user
... | [
"def",
"non_structured_query",
"(",
"table",
",",
"query",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"client",
"=",
"_get_client",
"(",
")",
"client",
".",
"table",
"=",
"table",
"# underlying lib doesn't use six or past.basestring,",
"# does isinstance(x, str... | 34.090909 | 22.272727 |
def rubles(amount, zero_for_kopeck=False):
"""Converts float value to in-words representation (for money)"""
try:
res = numeral.rubles(amount, zero_for_kopeck)
except Exception as err:
# because filter must die silently
res = default_value % {'error': err, 'value': str(amount)}
r... | [
"def",
"rubles",
"(",
"amount",
",",
"zero_for_kopeck",
"=",
"False",
")",
":",
"try",
":",
"res",
"=",
"numeral",
".",
"rubles",
"(",
"amount",
",",
"zero_for_kopeck",
")",
"except",
"Exception",
"as",
"err",
":",
"# because filter must die silently",
"res",
... | 40.25 | 14.125 |
def many(cls, filter=None, **kwargs):
"""Return a list of documents matching the filter"""
from mongoframes.queries import Condition, Group, to_refs
# Flatten the projection
kwargs['projection'], references, subs = \
cls._flatten_projection(
kwargs.ge... | [
"def",
"many",
"(",
"cls",
",",
"filter",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"from",
"mongoframes",
".",
"queries",
"import",
"Condition",
",",
"Group",
",",
"to_refs",
"# Flatten the projection",
"kwargs",
"[",
"'projection'",
"]",
",",
"refe... | 34.08 | 19.44 |
def generate_key(s, pattern="%s.txt"):
"""
Generates the cache key for the given string using the content in pattern
to format the output string
"""
h = hashlib.sha1()
#h.update(s)
h.update(s.encode('utf-8'))
return pattern % h.hexdigest() | [
"def",
"generate_key",
"(",
"s",
",",
"pattern",
"=",
"\"%s.txt\"",
")",
":",
"h",
"=",
"hashlib",
".",
"sha1",
"(",
")",
"#h.update(s)",
"h",
".",
"update",
"(",
"s",
".",
"encode",
"(",
"'utf-8'",
")",
")",
"return",
"pattern",
"%",
"h",
".",
"he... | 29.222222 | 11.666667 |
def do_cmd_private_sub(self, cmd):
'''Remove certificate and key output archived by sosreport. cmd
is the command name from which output is collected (i.e. exlcuding
parameters). Any matching instances are replaced with: '-----SCRUBBED'
and this function does not take a regexp or substit... | [
"def",
"do_cmd_private_sub",
"(",
"self",
",",
"cmd",
")",
":",
"globstr",
"=",
"'*'",
"+",
"cmd",
"+",
"'*'",
"self",
".",
"_log_debug",
"(",
"\"Scrubbing certs and keys for commands matching %s\"",
"%",
"(",
"cmd",
")",
")",
"if",
"not",
"self",
".",
"exec... | 45.297297 | 21.135135 |
def getLoginMethods(store, protocol=None):
"""
Retrieve L{LoginMethod} items from store C{store}, optionally constraining
them by protocol
"""
if protocol is not None:
comp = OR(LoginMethod.protocol == u'*',
LoginMethod.protocol == protocol)
else:
comp = None
... | [
"def",
"getLoginMethods",
"(",
"store",
",",
"protocol",
"=",
"None",
")",
":",
"if",
"protocol",
"is",
"not",
"None",
":",
"comp",
"=",
"OR",
"(",
"LoginMethod",
".",
"protocol",
"==",
"u'*'",
",",
"LoginMethod",
".",
"protocol",
"==",
"protocol",
")",
... | 31.727273 | 13 |
def create_criteria(cls, query):
"""Return a criteria from a dictionary containing a query.
Query should be a dictionary, keyed by field name. If the value is
a list, it will be divided into multiple criteria as required.
"""
criteria = []
for name, value in query.items(... | [
"def",
"create_criteria",
"(",
"cls",
",",
"query",
")",
":",
"criteria",
"=",
"[",
"]",
"for",
"name",
",",
"value",
"in",
"query",
".",
"items",
"(",
")",
":",
"if",
"isinstance",
"(",
"value",
",",
"list",
")",
":",
"for",
"inner_value",
"in",
"... | 36.736842 | 13.421053 |
def set_preferences(self, user=None, **kwargs):
"""Set preferences from keyword arguments."""
if user is None:
user = current_user
d = {pref.key: pref for pref in user.preferences}
for k, v in kwargs.items():
if k in d:
d[k].value = v
... | [
"def",
"set_preferences",
"(",
"self",
",",
"user",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"user",
"is",
"None",
":",
"user",
"=",
"current_user",
"d",
"=",
"{",
"pref",
".",
"key",
":",
"pref",
"for",
"pref",
"in",
"user",
".",
"p... | 34.666667 | 14.416667 |
def sign(self, authenticator):
"""Sign this OMAPI message.
@type authenticator: OmapiAuthenticatorBase
"""
self.authid = authenticator.authid
self.signature = b"\0" * authenticator.authlen # provide authlen
self.signature = authenticator.sign(self.as_string(forsigning=True))
assert len(self.signature) ==... | [
"def",
"sign",
"(",
"self",
",",
"authenticator",
")",
":",
"self",
".",
"authid",
"=",
"authenticator",
".",
"authid",
"self",
".",
"signature",
"=",
"b\"\\0\"",
"*",
"authenticator",
".",
"authlen",
"# provide authlen",
"self",
".",
"signature",
"=",
"auth... | 41.875 | 11.125 |
def filter_correlation(self, x_analyte, y_analyte, window=15,
r_threshold=0.9, p_threshold=0.05, filt=True, recalc=False):
"""
Calculate correlation filter.
Parameters
----------
x_analyte, y_analyte : str
The names of the x and y analytes ... | [
"def",
"filter_correlation",
"(",
"self",
",",
"x_analyte",
",",
"y_analyte",
",",
"window",
"=",
"15",
",",
"r_threshold",
"=",
"0.9",
",",
"p_threshold",
"=",
"0.05",
",",
"filt",
"=",
"True",
",",
"recalc",
"=",
"False",
")",
":",
"# make window odd",
... | 32.875 | 21.375 |
def image1(d, u, v, w, dmind, dtind, beamnum, irange):
""" Parallelizable function for imaging a chunk of data for a single dm.
Assumes data is dedispersed and resampled, so this just images each integration.
Simple one-stage imaging that returns dict of params.
returns dictionary with keys of cand loca... | [
"def",
"image1",
"(",
"d",
",",
"u",
",",
"v",
",",
"w",
",",
"dmind",
",",
"dtind",
",",
"beamnum",
",",
"irange",
")",
":",
"i0",
",",
"i1",
"=",
"irange",
"data_resamp",
"=",
"numpyview",
"(",
"data_resamp_mem",
",",
"'complex64'",
",",
"datashape... | 49.474359 | 23.666667 |
def _create_filenames(filename_schema, feed_type):
"""
Returns a dictionary of beam filename pairs,
keyed on correlation,from the cartesian product
of correlations and real, imaginary pairs
Given 'beam_$(corr)_$(reim).fits' returns:
{
'xx' : ('beam_xx_re.fits', 'beam_xx_im.fits'),
'... | [
"def",
"_create_filenames",
"(",
"filename_schema",
",",
"feed_type",
")",
":",
"template",
"=",
"FitsFilenameTemplate",
"(",
"filename_schema",
")",
"def",
"_re_im_filenames",
"(",
"corr",
",",
"template",
")",
":",
"try",
":",
"return",
"tuple",
"(",
"template... | 33.346939 | 17.346939 |
def to_json(self):
"""
called by VersionEncoder.default() when doing json.dumps() on the object
the json materializes in reverse order from the order used here
"""
return {
"build_number": self._build_number,
"commit_hash": self._commit_hash,
"last_modified": self._last_modif... | [
"def",
"to_json",
"(",
"self",
")",
":",
"return",
"{",
"\"build_number\"",
":",
"self",
".",
"_build_number",
",",
"\"commit_hash\"",
":",
"self",
".",
"_commit_hash",
",",
"\"last_modified\"",
":",
"self",
".",
"_last_modified",
",",
"\"location\"",
":",
"se... | 33 | 12.333333 |
def create(self, messaging_service_sid, friendly_name=values.unset,
attributes=values.unset, date_created=values.unset,
date_updated=values.unset, created_by=values.unset):
"""
Create a new SessionInstance
:param unicode messaging_service_sid: The unique id of the ... | [
"def",
"create",
"(",
"self",
",",
"messaging_service_sid",
",",
"friendly_name",
"=",
"values",
".",
"unset",
",",
"attributes",
"=",
"values",
".",
"unset",
",",
"date_created",
"=",
"values",
".",
"unset",
",",
"date_updated",
"=",
"values",
".",
"unset",... | 43.71875 | 24.53125 |
def _init_virtual_io(self, file):
"""Initialize callback functions for sf_open_virtual()."""
@_ffi.callback("sf_vio_get_filelen")
def vio_get_filelen(user_data):
curr = file.tell()
file.seek(0, SEEK_END)
size = file.tell()
file.seek(curr, SEEK_SET)... | [
"def",
"_init_virtual_io",
"(",
"self",
",",
"file",
")",
":",
"@",
"_ffi",
".",
"callback",
"(",
"\"sf_vio_get_filelen\"",
")",
"def",
"vio_get_filelen",
"(",
"user_data",
")",
":",
"curr",
"=",
"file",
".",
"tell",
"(",
")",
"file",
".",
"seek",
"(",
... | 35.5 | 12.26 |
def raw(self, query: Any, data: Any = None):
"""Run raw query on Repository.
For this stand-in repository, the query string is a json string that contains kwargs
criteria with straigh-forward equality checks. Individual criteria are always ANDed
and the result is always a subset of the ... | [
"def",
"raw",
"(",
"self",
",",
"query",
":",
"Any",
",",
"data",
":",
"Any",
"=",
"None",
")",
":",
"# Ensure that we are dealing with a string, for this repository",
"assert",
"isinstance",
"(",
"query",
",",
"str",
")",
"input_db",
"=",
"self",
".",
"conn",... | 35.371429 | 21.942857 |
def empty():
"""
Create an empty set.
"""
if not hasattr(empty, '_instance'):
empty._instance = Interval(AtomicInterval(OPEN, inf, -inf, OPEN))
return empty._instance | [
"def",
"empty",
"(",
")",
":",
"if",
"not",
"hasattr",
"(",
"empty",
",",
"'_instance'",
")",
":",
"empty",
".",
"_instance",
"=",
"Interval",
"(",
"AtomicInterval",
"(",
"OPEN",
",",
"inf",
",",
"-",
"inf",
",",
"OPEN",
")",
")",
"return",
"empty",
... | 26.857143 | 13.142857 |
def _transform_params(self, **params):
"""Applies all transforms to the given params.
Parameters
----------
\**params :
Key, value pairs of parameters to apply the transforms to.
Returns
-------
dict
A dictionary of the transformed parame... | [
"def",
"_transform_params",
"(",
"self",
",",
"*",
"*",
"params",
")",
":",
"# apply inverse transforms to go from sampling parameters to",
"# variable args",
"if",
"self",
".",
"sampling_transforms",
"is",
"not",
"None",
":",
"params",
"=",
"self",
".",
"sampling_tra... | 37.8 | 20.08 |
def display_url(target):
"""Displaying URL in an IPython notebook to allow the user to click and check on information. With thanks to Fernando Perez for putting together the implementation!
:param target: the url to display.
:type target: string."""
prefix = u"http://" if not target.startswith("http") ... | [
"def",
"display_url",
"(",
"target",
")",
":",
"prefix",
"=",
"u\"http://\"",
"if",
"not",
"target",
".",
"startswith",
"(",
"\"http\"",
")",
"else",
"u\"\"",
"target",
"=",
"prefix",
"+",
"target",
"display",
"(",
"HTML",
"(",
"u'<a href=\"{t}\" target=_blank... | 53.125 | 16.125 |
def create_metrics(self,
configs: Iterable[MetricConfig]) -> Dict[str, Metric]:
"""Create Prometheus metrics from a list of MetricConfigs."""
metrics: Dict[str, Metric] = {
config.name: self._register_metric(config)
for config in configs
}
s... | [
"def",
"create_metrics",
"(",
"self",
",",
"configs",
":",
"Iterable",
"[",
"MetricConfig",
"]",
")",
"->",
"Dict",
"[",
"str",
",",
"Metric",
"]",
":",
"metrics",
":",
"Dict",
"[",
"str",
",",
"Metric",
"]",
"=",
"{",
"config",
".",
"name",
":",
"... | 40.333333 | 14.222222 |
def signature(self):
"Instance file name"
kw = self.get_params()
keys = sorted(kw.keys())
l = []
for k in keys:
n = k[0] + k[-1]
v = kw[k]
if k == 'function_set':
v = "_".join([x.__name__[0] +
x.__n... | [
"def",
"signature",
"(",
"self",
")",
":",
"kw",
"=",
"self",
".",
"get_params",
"(",
")",
"keys",
"=",
"sorted",
"(",
"kw",
".",
"keys",
"(",
")",
")",
"l",
"=",
"[",
"]",
"for",
"k",
"in",
"keys",
":",
"n",
"=",
"k",
"[",
"0",
"]",
"+",
... | 31.555556 | 12.333333 |
def imrphenomc_tmplt(**kwds):
""" Return an IMRPhenomC waveform using CUDA to generate the phase and amplitude
Main Paper: arXiv:1005.3306
"""
# Pull out the input arguments
f_min = float128(kwds['f_lower'])
f_max = float128(kwds['f_final'])
delta_f = float128(kwds['delta_f'])
distance... | [
"def",
"imrphenomc_tmplt",
"(",
"*",
"*",
"kwds",
")",
":",
"# Pull out the input arguments",
"f_min",
"=",
"float128",
"(",
"kwds",
"[",
"'f_lower'",
"]",
")",
"f_max",
"=",
"float128",
"(",
"kwds",
"[",
"'f_final'",
"]",
")",
"delta_f",
"=",
"float128",
... | 34.995763 | 24.432203 |
def trim(self, lower=None, upper=None):
"""Trim values in accordance with :math:`BoWa \\leq NFk`.
>>> from hydpy.models.lland import *
>>> parameterstep('1d')
>>> nhru(5)
>>> nfk(200.)
>>> states.bowa(-100.,0., 100., 200., 300.)
>>> states.bowa
bowa(0.0, ... | [
"def",
"trim",
"(",
"self",
",",
"lower",
"=",
"None",
",",
"upper",
"=",
"None",
")",
":",
"if",
"upper",
"is",
"None",
":",
"upper",
"=",
"self",
".",
"subseqs",
".",
"seqs",
".",
"model",
".",
"parameters",
".",
"control",
".",
"nfk",
"lland_seq... | 35.857143 | 13.571429 |
def default(self, o):
"""Implement this method in a subclass such that it returns a
serializable object for ``o``, or calls the base implementation (to
raise a ``TypeError``).
For example, to support arbitrary iterators, you could implement
default like this::
def d... | [
"def",
"default",
"(",
"self",
",",
"o",
")",
":",
"if",
"isinstance",
"(",
"o",
",",
"datetime",
")",
":",
"return",
"http_date",
"(",
"o",
")",
"if",
"isinstance",
"(",
"o",
",",
"uuid",
".",
"UUID",
")",
":",
"return",
"str",
"(",
"o",
")",
... | 34.125 | 13.375 |
def delete_file(self, target, path):
"""Delete a file from a device
:param target: The device(s) to be targeted with this request
:type target: :class:`devicecloud.sci.TargetABC` or list of :class:`devicecloud.sci.TargetABC` instances
:param path: The path on the target to the file to d... | [
"def",
"delete_file",
"(",
"self",
",",
"target",
",",
"path",
")",
":",
"command_block",
"=",
"FileSystemServiceCommandBlock",
"(",
")",
"command_block",
".",
"add_command",
"(",
"DeleteCommand",
"(",
"path",
")",
")",
"root",
"=",
"_parse_command_response",
"(... | 52.913043 | 27.304348 |
def _set_active_tools(self, plot):
"Activates the list of active tools"
for tool in self.active_tools:
if isinstance(tool, util.basestring):
tool_type = TOOL_TYPES[tool]
matching = [t for t in plot.toolbar.tools
if isinstance(t, too... | [
"def",
"_set_active_tools",
"(",
"self",
",",
"plot",
")",
":",
"for",
"tool",
"in",
"self",
".",
"active_tools",
":",
"if",
"isinstance",
"(",
"tool",
",",
"util",
".",
"basestring",
")",
":",
"tool_type",
"=",
"TOOL_TYPES",
"[",
"tool",
"]",
"matching"... | 47.52381 | 10.761905 |
def asyncPipeStrconcat(context=None, _INPUT=None, conf=None, **kwargs):
"""A string module that asynchronously builds a string. Loopable. No direct
input.
Parameters
----------
context : pipe2py.Context object
_INPUT : asyncPipe like object (twisted Deferred iterable of items)
conf : {
... | [
"def",
"asyncPipeStrconcat",
"(",
"context",
"=",
"None",
",",
"_INPUT",
"=",
"None",
",",
"conf",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"splits",
"=",
"yield",
"asyncGetSplits",
"(",
"_INPUT",
",",
"conf",
"[",
"'part'",
"]",
",",
"*",
"*"... | 31.73913 | 23.478261 |
def _vector_coef_op_right(func):
"""decorator for operator overloading when VectorCoefs is on the
right"""
@wraps(func)
def verif(self, vcoef):
if isinstance(vcoef, numbers.Number):
return VectorCoefs(func(self, self.scoef1._vec, vcoef),
... | [
"def",
"_vector_coef_op_right",
"(",
"func",
")",
":",
"@",
"wraps",
"(",
"func",
")",
"def",
"verif",
"(",
"self",
",",
"vcoef",
")",
":",
"if",
"isinstance",
"(",
"vcoef",
",",
"numbers",
".",
"Number",
")",
":",
"return",
"VectorCoefs",
"(",
"func",... | 43.416667 | 15.25 |
def reduce_cuda(g, x, axes, dtype):
"""Reductions in CUDA use the thrust library for speed and have limited
functionality."""
if axes != 0:
raise NotImplementedError("'axes' keyword is not implemented for CUDA")
return g(x, dtype=dtype) | [
"def",
"reduce_cuda",
"(",
"g",
",",
"x",
",",
"axes",
",",
"dtype",
")",
":",
"if",
"axes",
"!=",
"0",
":",
"raise",
"NotImplementedError",
"(",
"\"'axes' keyword is not implemented for CUDA\"",
")",
"return",
"g",
"(",
"x",
",",
"dtype",
"=",
"dtype",
")... | 36.857143 | 17 |
def connect_to_agent(env=None, sp=subprocess):
"""Connect to GPG agent's UNIX socket."""
sock_path = get_agent_sock_path(sp=sp, env=env)
# Make sure the original gpg-agent is running.
check_output(args=['gpg-connect-agent', '/bye'], sp=sp)
sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
... | [
"def",
"connect_to_agent",
"(",
"env",
"=",
"None",
",",
"sp",
"=",
"subprocess",
")",
":",
"sock_path",
"=",
"get_agent_sock_path",
"(",
"sp",
"=",
"sp",
",",
"env",
"=",
"env",
")",
"# Make sure the original gpg-agent is running.",
"check_output",
"(",
"args",... | 44.125 | 13 |
def login(self, username, password, strict=True):
""" Login as specified user
Args:
username (str): The username to log in with
password (str): The password for the user
strict (bool): `True` to thow an error on failure
Returns:
... | [
"def",
"login",
"(",
"self",
",",
"username",
",",
"password",
",",
"strict",
"=",
"True",
")",
":",
"# get login token",
"params",
"=",
"{",
"\"action\"",
":",
"\"query\"",
",",
"\"meta\"",
":",
"\"tokens\"",
",",
"\"type\"",
":",
"\"login\"",
",",
"\"for... | 34.326087 | 17.934783 |
def _mod_spec(self):
"""
Modified length specifiers: mapping between length modifiers and conversion specifiers. This generates all the
possibilities, i.e. hhd, etc.
"""
mod_spec={}
for mod, sizes in self.int_len_mod.items():
for conv in self.int_sign['signe... | [
"def",
"_mod_spec",
"(",
"self",
")",
":",
"mod_spec",
"=",
"{",
"}",
"for",
"mod",
",",
"sizes",
"in",
"self",
".",
"int_len_mod",
".",
"items",
"(",
")",
":",
"for",
"conv",
"in",
"self",
".",
"int_sign",
"[",
"'signed'",
"]",
":",
"mod_spec",
"[... | 30.125 | 21.375 |
def is_format_supported(self, format_p):
"""Checks if a specific drag'n drop MIME / Content-type format is supported.
in format_p of type str
Format to check for.
return supported of type bool
Returns @c true if the specified format is supported, @c false if not.
... | [
"def",
"is_format_supported",
"(",
"self",
",",
"format_p",
")",
":",
"if",
"not",
"isinstance",
"(",
"format_p",
",",
"basestring",
")",
":",
"raise",
"TypeError",
"(",
"\"format_p can only be an instance of type basestring\"",
")",
"supported",
"=",
"self",
".",
... | 37.266667 | 17.466667 |
def conc(self,H=70.,Om=0.3,overdens=200.,wrtcrit=False,
ro=None,vo=None):
"""
NAME:
conc
PURPOSE:
return the concentration
INPUT:
H= (default: 70) Hubble constant in km/s/Mpc
Om= (default: 0.3) Omega matter
... | [
"def",
"conc",
"(",
"self",
",",
"H",
"=",
"70.",
",",
"Om",
"=",
"0.3",
",",
"overdens",
"=",
"200.",
",",
"wrtcrit",
"=",
"False",
",",
"ro",
"=",
"None",
",",
"vo",
"=",
"None",
")",
":",
"if",
"ro",
"is",
"None",
":",
"ro",
"=",
"self",
... | 30.512195 | 30.365854 |
def add_keyup_callback(self, key, fn):
"""
Allows for custom callback functions for the viewer. Called on key up.
Parameter 'any' will ensure that the callback is called on any key up,
and block default mujoco viewer callbacks from executing, except for
the ESC callback to close... | [
"def",
"add_keyup_callback",
"(",
"self",
",",
"key",
",",
"fn",
")",
":",
"self",
".",
"viewer",
".",
"keyup",
"[",
"key",
"]",
".",
"append",
"(",
"fn",
")"
] | 47.375 | 15.125 |
def _diff_and_summarize(from_csv, to_csv, index_columns, stream=sys.stdout,
sep=',', ignored_columns=None, significance=None):
"""
Print a summary of the difference between the two files.
"""
from_records = list(records.load(from_csv, sep=sep))
to_records = records.load(to_cs... | [
"def",
"_diff_and_summarize",
"(",
"from_csv",
",",
"to_csv",
",",
"index_columns",
",",
"stream",
"=",
"sys",
".",
"stdout",
",",
"sep",
"=",
"','",
",",
"ignored_columns",
"=",
"None",
",",
"significance",
"=",
"None",
")",
":",
"from_records",
"=",
"lis... | 40.176471 | 18.411765 |
def get_prediction_path(self, node_id, missing_id = []):
"""
Return the prediction path from this node to the parent node.
Parameters
----------
node_id : id of the node to get the prediction path.
missing_id : Additional info that contains nodes with missing features... | [
"def",
"get_prediction_path",
"(",
"self",
",",
"node_id",
",",
"missing_id",
"=",
"[",
"]",
")",
":",
"_raise_error_if_not_of_type",
"(",
"node_id",
",",
"[",
"int",
",",
"long",
"]",
",",
"\"node_id\"",
")",
"_numeric_param_check_range",
"(",
"\"node_id\"",
... | 35.768293 | 15.036585 |
def node_contained_in_layer_area_validation(self):
"""
if layer defines an area, ensure node coordinates are contained in the area
"""
# if area is a polygon ensure it contains the node
if self.layer and isinstance(self.layer.area, Polygon) and not self.layer.area.contains(self.geometry):
ra... | [
"def",
"node_contained_in_layer_area_validation",
"(",
"self",
")",
":",
"# if area is a polygon ensure it contains the node",
"if",
"self",
".",
"layer",
"and",
"isinstance",
"(",
"self",
".",
"layer",
".",
"area",
",",
"Polygon",
")",
"and",
"not",
"self",
".",
... | 52.857143 | 22.285714 |
def apply_region_configs(env_config):
"""Override default env configs with region specific configs and nest
all values under a region
Args:
env_config (dict): The environment specific config.
Return:
dict: Newly updated dictionary with region overrides applied.
"""
new_config =... | [
"def",
"apply_region_configs",
"(",
"env_config",
")",
":",
"new_config",
"=",
"env_config",
".",
"copy",
"(",
")",
"for",
"region",
"in",
"env_config",
".",
"get",
"(",
"'regions'",
",",
"REGIONS",
")",
":",
"if",
"isinstance",
"(",
"env_config",
".",
"ge... | 38.368421 | 20.052632 |
def compat_serializer_check_is_valid(serializer):
""" http://www.django-rest-framework.org/topics/3.0-announcement/#using-is_validraise_exceptiontrue """
if DRFVLIST[0] >= 3:
serializer.is_valid(raise_exception=True)
else:
if not serializer.is_valid():
serializers.ValidationError... | [
"def",
"compat_serializer_check_is_valid",
"(",
"serializer",
")",
":",
"if",
"DRFVLIST",
"[",
"0",
"]",
">=",
"3",
":",
"serializer",
".",
"is_valid",
"(",
"raise_exception",
"=",
"True",
")",
"else",
":",
"if",
"not",
"serializer",
".",
"is_valid",
"(",
... | 51.142857 | 15.857143 |
def vsub(v1, v2):
"""
Compute the difference between two 3-dimensional,
double precision vectors.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/vsub_c.html
:param v1: First vector (minuend).
:type v1: 3-Element Array of floats
:param v2: Second vector (subtrahend).
:type v2... | [
"def",
"vsub",
"(",
"v1",
",",
"v2",
")",
":",
"v1",
"=",
"stypes",
".",
"toDoubleVector",
"(",
"v1",
")",
"v2",
"=",
"stypes",
".",
"toDoubleVector",
"(",
"v2",
")",
"vout",
"=",
"stypes",
".",
"emptyDoubleVector",
"(",
"3",
")",
"libspice",
".",
... | 31.526316 | 9.947368 |
def share(
self,
share_id: str,
token: dict = None,
augment: bool = False,
prot: str = "https",
) -> dict:
"""Get information about a specific share and its applications.
:param str token: API auth token
:param str share_id: share UUID
:param ... | [
"def",
"share",
"(",
"self",
",",
"share_id",
":",
"str",
",",
"token",
":",
"dict",
"=",
"None",
",",
"augment",
":",
"bool",
"=",
"False",
",",
"prot",
":",
"str",
"=",
"\"https\"",
",",
")",
"->",
"dict",
":",
"# passing auth parameter",
"share_url"... | 29.5 | 18.710526 |
def get_relativelinenumbertable(self):
"""
a sequence of (code_offset, line_number) pairs. Similar to the
get_linenumbertable method, but the line numbers start at 0
(they are relative to the method, not to the class file)
"""
lnt = self.get_linenumbertable()
if ... | [
"def",
"get_relativelinenumbertable",
"(",
"self",
")",
":",
"lnt",
"=",
"self",
".",
"get_linenumbertable",
"(",
")",
"if",
"lnt",
":",
"lineoff",
"=",
"lnt",
"[",
"0",
"]",
"[",
"1",
"]",
"return",
"tuple",
"(",
"(",
"o",
",",
"l",
"-",
"lineoff",
... | 34.307692 | 16.769231 |
def NewWalker(self, reader):
"""Setup an xmltextReader to parse a preparsed XML document.
This reuses the existing @reader xmlTextReader. """
if reader is None: reader__o = None
else: reader__o = reader._o
ret = libxml2mod.xmlReaderNewWalker(reader__o, self._o)
return ... | [
"def",
"NewWalker",
"(",
"self",
",",
"reader",
")",
":",
"if",
"reader",
"is",
"None",
":",
"reader__o",
"=",
"None",
"else",
":",
"reader__o",
"=",
"reader",
".",
"_o",
"ret",
"=",
"libxml2mod",
".",
"xmlReaderNewWalker",
"(",
"reader__o",
",",
"self",... | 45.285714 | 9.285714 |
def apply_to(self, x, columns=False):
"""Apply this translation to the given object
The argument can be several sorts of objects:
* ``np.array`` with shape (3, )
* ``np.array`` with shape (N, 3)
* ``np.array`` with shape (3, N), use ``columns=True``
* ``T... | [
"def",
"apply_to",
"(",
"self",
",",
"x",
",",
"columns",
"=",
"False",
")",
":",
"if",
"isinstance",
"(",
"x",
",",
"np",
".",
"ndarray",
")",
"and",
"len",
"(",
"x",
".",
"shape",
")",
"==",
"2",
"and",
"x",
".",
"shape",
"[",
"0",
"]",
"==... | 41.5 | 18.852941 |
def _check_once(self):
"""A single attempt to call ismaster.
Returns a ServerDescription, or raises an exception.
"""
address = self._server_description.address
if self._publish:
self._listeners.publish_server_heartbeat_started(address)
with self._pool.get_so... | [
"def",
"_check_once",
"(",
"self",
")",
":",
"address",
"=",
"self",
".",
"_server_description",
".",
"address",
"if",
"self",
".",
"_publish",
":",
"self",
".",
"_listeners",
".",
"publish_server_heartbeat_started",
"(",
"address",
")",
"with",
"self",
".",
... | 40.5 | 17.9 |
def features(self):
"""All available features"""
mycols = []
for col in dfn.feature_names:
if col in self:
mycols.append(col)
mycols.sort()
return mycols | [
"def",
"features",
"(",
"self",
")",
":",
"mycols",
"=",
"[",
"]",
"for",
"col",
"in",
"dfn",
".",
"feature_names",
":",
"if",
"col",
"in",
"self",
":",
"mycols",
".",
"append",
"(",
"col",
")",
"mycols",
".",
"sort",
"(",
")",
"return",
"mycols"
] | 26.75 | 12.75 |
def _refit_islands(self, group, stage, outerclip=None, istart=0):
"""
Do island refitting (priorized fitting) on a group of islands.
Parameters
----------
group : list
A list of components grouped by island.
stage : int
Refitting stage.
... | [
"def",
"_refit_islands",
"(",
"self",
",",
"group",
",",
"stage",
",",
"outerclip",
"=",
"None",
",",
"istart",
"=",
"0",
")",
":",
"global_data",
"=",
"self",
".",
"global_data",
"sources",
"=",
"[",
"]",
"data",
"=",
"global_data",
".",
"data_pix",
"... | 49.068273 | 25.212851 |
def cget(self, item):
"""Return the value of an option"""
return getattr(self, "_" + item) if item in self.options else ttk.Frame.cget(self, item) | [
"def",
"cget",
"(",
"self",
",",
"item",
")",
":",
"return",
"getattr",
"(",
"self",
",",
"\"_\"",
"+",
"item",
")",
"if",
"item",
"in",
"self",
".",
"options",
"else",
"ttk",
".",
"Frame",
".",
"cget",
"(",
"self",
",",
"item",
")"
] | 53.333333 | 25 |
def crypto_secretstream_xchacha20poly1305_push(
state,
m,
ad=None,
tag=crypto_secretstream_xchacha20poly1305_TAG_MESSAGE,
):
"""
Add an encrypted message to the secret stream.
:param state: a secretstream state object
:type state: crypto_secretstream_xchacha20poly1305_state
:param m... | [
"def",
"crypto_secretstream_xchacha20poly1305_push",
"(",
"state",
",",
"m",
",",
"ad",
"=",
"None",
",",
"tag",
"=",
"crypto_secretstream_xchacha20poly1305_TAG_MESSAGE",
",",
")",
":",
"ensure",
"(",
"isinstance",
"(",
"state",
",",
"crypto_secretstream_xchacha20poly13... | 31.241935 | 23.241935 |
def _checkAuth(self, message, server_url):
"""Make a check_authentication request to verify this message.
@returns: True if the request is valid.
@rtype: bool
"""
logging.info('Using OpenID check_authentication')
request = self._createCheckAuthRequest(message)
if... | [
"def",
"_checkAuth",
"(",
"self",
",",
"message",
",",
"server_url",
")",
":",
"logging",
".",
"info",
"(",
"'Using OpenID check_authentication'",
")",
"request",
"=",
"self",
".",
"_createCheckAuthRequest",
"(",
"message",
")",
"if",
"request",
"is",
"None",
... | 38.333333 | 17.611111 |
def sort_by_formula_id(raw_datasets):
"""
Sort a list of formulas by `id`, where `id` represents the accepted
formula id.
Parameters
----------
raw_datasets : list of dictionaries
A list of raw datasets.
Examples
--------
The parameter `raw_datasets` has to be of the format... | [
"def",
"sort_by_formula_id",
"(",
"raw_datasets",
")",
":",
"by_formula_id",
"=",
"defaultdict",
"(",
"list",
")",
"for",
"el",
"in",
"raw_datasets",
":",
"by_formula_id",
"[",
"el",
"[",
"'handwriting'",
"]",
".",
"formula_id",
"]",
".",
"append",
"(",
"el"... | 31.371429 | 15.657143 |
def _verify_dict_list(self, values, keys, name):
'''Validate a list of `dict`, ensuring it has specific keys
and no others.
:param values: A list of `dict` to validate.
:param keys: A list of keys to validate each `dict` against.
:param name: Name describing the values, to show ... | [
"def",
"_verify_dict_list",
"(",
"self",
",",
"values",
",",
"keys",
",",
"name",
")",
":",
"keys",
"=",
"set",
"(",
"keys",
")",
"name",
"=",
"name",
".",
"title",
"(",
")",
"for",
"value",
"in",
"values",
":",
"if",
"not",
"isinstance",
"(",
"val... | 43.636364 | 17.363636 |
def squared_error(eval_data, predictions, scores='ignored', learner='ignored'):
'''
Return the squared error of each prediction in `predictions` with respect
to the correct output in `eval_data`.
>>> data = [Instance('input', (0., 0., 1.)),
... Instance('input', (0., 1., 1.)),
... ... | [
"def",
"squared_error",
"(",
"eval_data",
",",
"predictions",
",",
"scores",
"=",
"'ignored'",
",",
"learner",
"=",
"'ignored'",
")",
":",
"return",
"[",
"np",
".",
"sum",
"(",
"(",
"np",
".",
"array",
"(",
"pred",
")",
"-",
"np",
".",
"array",
"(",
... | 43.769231 | 23.307692 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.