content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def computeJz(bx, by, bx_err, by_err, conf_disambig, bitmap, nx, ny):
"""function: computeJz
This function computes the z-component of the current.
In discretized space like data pixels, the current (or curl of B) is calculated as the integration
of the field Bx and By along the circumference of the ... | 09f831d0bde7a3d1cba3051aad4a0fa7f66132f3 | 54,100 |
def hw5ode3(t, x):
"""Function containing the third ODE
(Van der Pol’s equation with \\eta = 2).
- **parameters**, **types**, **return** and **return types**::
:param t: current time
:param x: state at current time
:type t: np.float
:type x: np.array[float]
:return: Derivative of state at current time
:... | 946cdd729a04c7c0d7da85869092dd0fd1428cc9 | 54,101 |
def write_refkey_to_file(refkey_file, password, key_pem, key_der, cert, encode_format): # pylint: disable=too-many-arguments
"""
Write reference key into file
:param refkey_file: File name to store reference key
:param password: Password for encryption of pkcs12 reference key
:param key_pem: Refere... | b82ab3f95f0f5cde06e10193ceceee82d7ad16f4 | 54,102 |
def plot_learning_curve(sample_sizes, learning_curves, curve_labels, xscale='log', ax=None):
""" Plot the learning curve.
Parameters
----------
sample_sizes : array
The sample sizes in which the classifier is run.
learning_curves : array
List of learning_cur... | aa77b82cf9d20e59f83861286d8169c827c02d29 | 54,103 |
def quantumvolume(nbits=6, measure=True):
"""
This is a nbit quantum volume circuit
reference: https://qiskit.org/textbook/ch-quantum-hardware/measuring-quantum-volume.html
"""
qubit_lists = [list(range(0, nbits))]
qv_circs, qv_circs_nomeas = qv.qv_circuits(qubit_lists, 1)
if measure... | 886e37706cc9bc3b852a63a8a97a3110bc0228ea | 54,104 |
from pathlib import Path
def get_frontend_dir() -> Path:
"""Get the frontend directory."""
if LOCAL_APP_DIR.exists():
logger.info("Using local DEVELOPMENT frontend directory.")
return LOCAL_APP_DIR
elif GLOBAL_FRONTEND_DIR.exists():
logger.info("Using global frontend directory.")
... | df7c656a29ec7fc8377e90954c253391c6fbea6f | 54,105 |
import logging
import os
def test_local_source_dir(gearman_worker):
"""
Verify the source directory exists for a local directory transfer
"""
return_val = []
source_dir = build_source_dir(gearman_worker)
logging.debug("Source Dir: %s", source_dir)
if not os.path.isdir(source_dir):
... | 465cfd00ff5ab53162d929147cf790fcb9e37c73 | 54,106 |
from sklearn.datasets import fetch_mldata
def mnist(missingness="mcar", thr=0.2):
""" Loads corrupted MNIST
Parameters
----------
missingness: ('mcar', 'mar', 'mnar')
Type of missigness you want in your dataset
th: float between [0,1]
Percentage of missing data in generated data
... | 1aca3246dc73f28704249fa56e693eee6165241b | 54,107 |
def run_images(tags):
"""Run a list of docker images, in background."""
print "### Running images ###"
return [run_image(tag) for tag in tags] | 9de9bb498b456ffe3be921ea025bfeeb8f51b3af | 54,108 |
import struct
def _transitive_proto_descriptor_sets_impl(ctx):
"""Implementation of transitive_proto_descriptor_sets rule.
Args:
ctx: The rule context.
Returns:
All transitive proto descriptor files as default output.
"""
gathered = _gather_transitive_protos_deps(ctx.attr.deps)
d... | 3c0aa7c81e25f39a3e10a86ddb5d3d28412c3474 | 54,109 |
import typing
from typing import TypeGuard
from datetime import datetime
def is_timelength_timedelta(
timelength: typing.Any,
) -> TypeGuard[spec.TimelengthTimedelta]:
"""return bool of whether input is TimelengthTimedelta"""
return isinstance(timelength, datetime.timedelta) | de7f4eba31f479bd6a81119f98ad2d9051bc3f46 | 54,110 |
def hef_command(s, *args):
"""
Create fully qualified HEF command (add prefix and postfix the CRC).
:param s: command string
"""
return build_command('3', s, *args) | 6e8b5f3a37205a754bc6d98d92af3a8654d9cdee | 54,111 |
def list_folder():
"""List a folder.
Return a dict mapping unicode filenames to
FileMetadata|FolderMetadata entries.
"""
path = DROPBOX_PROJECT_PATH
try:
res = dbx.files_list_folder(path)
except dropbox.exceptions.ApiError as err:
return {}
else:
return res.entri... | f034e9f41b21809a80d94cf23563fe9978056529 | 54,112 |
def genomic_del1_free_text_lse(genomic_del1_free_text,
genomic_del1_free_text_seq_loc):
"""Create a test fixture for genomic del LSE."""
_id = "ga4gh:VA.DdtLZ_d22R0O0VU020WcCLvNhXNZtU2j"
genomic_del1_free_text["variation_id"] = _id
genomic_del1_free_text["variation"] = {
... | 1a197b97b615e063c6409c48a3cbcd802a66e058 | 54,113 |
def min(iterable):
"""
min() overwrites python built-in,
checks if all constants and computes np.min() in that case
"""
if not any(isinstance(elem, Expression) for elem in iterable):
return np.min(iterable)
return Minimum(iterable) | f7b774a6a671491ce33d3e1cd50946e58c624752 | 54,114 |
from typing import Union
from typing import List
def mode(x: Union[List[float], np.ndarray]) -> float:
"""Calculate the mode of a list of numbers.
Args:
x: List or Numpy array.
Returns:
Mode.
Examples:
>>> mode(x=[1., 2., 3., 4., 5.])
2.0
>>> mode(x=[1., 2., ... | f9324ff8d5b8a45f2183ec02ec882e360c054cdc | 54,115 |
def mapping():
"""
This is the mapping submission page.
"""
title = 'Perform Mapping'
jwt_csrf_token = (get_jwt() or {}).get("csrf")
form = FileUploadForm()
# TODO: change
nemascan_container_url = 'https://github.com/AndersenLab/dockerfile/tree/nemarun/nemarun'
nemascan_github_url = 'https://githu... | 5879e71ebeaa639de6043650c273e3e21e0441dc | 54,116 |
def topic_scores(run_scores):
"""
Use this function for a dictionary that contains the topic scores for each measure outputted by trec_eval.
@param run_scores: The run scores of the previously evaluated run.
@return: Dictionary containing the topic scores for every measure outputted by trec_eval.
"... | 5e909d20304530dc3e4c85f7a342c001e1298c8f | 54,117 |
import collections
def _make_args(args_list, session, fw_props):
"""
Converts the given list of arguments into a list (args) and a
dictionary (kwargs).
All arguments with an assignment are put into kwargs, others in args.
:param args_list: The list of arguments to be treated
:param session: T... | 94f4c25dbfbe5ffb3cef532e5aae85c54abe0783 | 54,118 |
from typing import OrderedDict
def create_profile(name, node):
"""
Create a :class:`Profiler` for the Iteration/Expression tree ``node``.
The following code sections are profiled: ::
* The whole ``node``;
* A sequence of perfectly nested loops that have common :class:`Iteration`
... | 92e076bfdb5d1eacba276a2ead0e5e2c01b24f65 | 54,119 |
def jaccard(pred: np.ndarray, target: np.ndarray, eps: float = 1e-7) -> np.ndarray:
"""
Calculate Jaccard coefficient
Args:
pred (np.ndarray): predicted masks of shape [B, H, W]
target (np.ndarray): target masks of shape [B, H, W]
eps (float): smooth value
Returns:
np.n... | c2054eeb8059efe124f624d73bba30331769ed0e | 54,120 |
def has_prefix(sub_s, d):
"""
:param sub_s:
:return:
"""
for key in d:
if key.startswith(sub_s):
return True | c9544f3937a47eb7d9b18b4209acd3fa9283de12 | 54,121 |
def slow_closest_pair(cluster_list):
"""
Compute the distance between the closest pair of clusters in a list (slow)
Input: cluster_list is the list of clusters
Output: tuple of the form (dist, idx1, idx2) where the centers of the clusters
cluster_list[idx1] and cluster_list[idx2] have minimum ... | 701885531ba00d1a72337651b4e6276e034d61b8 | 54,122 |
def requires_true(attrs=[]):
"""
This decorator is used to require that a certain set of class attributes are
set to True.
Otherwise it will trigger a WebUIError.
"""
return _requires_value(True, attrs) | fbec2bdd2bece58fc987f68bb7c61bd6ef012a12 | 54,123 |
import os
def get_sys_fs_mount() -> str:
"""find the default sysfs mount point"""
try:
if os.path.exists(MTAB):
with open(MTAB, mode='r') as mtab:
mounts: ty.Set[str] = set()
for line in mtab.readlines():
segments = line.split()
... | bf1402543af77f8e527b46eb8e62491bb49935b7 | 54,124 |
import distutils
def _get_ext_suffix():
"""Get the suffix for compiled extensions"""
dist_suffix = distutils.sysconfig.get_config_var("EXT_SUFFIX")
if dist_suffix is None:
dist_suffix = distutils.sysconfig.get_config_var("SO")
return dist_suffix | 387aaa420e930f3efceabdcec5f11da274164082 | 54,125 |
import copy
def explicit_k(obj):
"""explicit_k solver.
Used to compute one time step of systems with x-dependent thermal
contuctivity.
"""
x = copy.copy(obj.temperature)
# computes
for i in range(1, obj.num_points - 1):
eta = obj.dt / (2. * obj.rho[i] * obj.Cp[i] * obj.dx * ob... | d9b90169448a257fbf7e1bbc5604170c19ec6fa6 | 54,126 |
import urllib
import requests
import json
def get_wikidata_desc(wikidata_id):
"""Return the image for the Wikidata item with *wikidata_id*. """
dapp = urllib.parse.urlencode({'action':'wbgetentities','ids':get_wikidata_id(wikidata_id),'languages':'de'})
query_string = "https://www.wikidata.org/w/api.php?"... | 5af37fba17655efaf911bdfa596b59723886f23e | 54,127 |
def bayesdb_generator_modelnos(bdb, generator_id):
"""Return list of model numbers associated with given `generator_id`."""
sql = '''
SELECT modelno FROM bayesdb_generator_model AS m
WHERE generator_id = ?
ORDER BY modelno ASC
'''
return [row[0] for row in bdb.sql_execute... | e7cbb96679f25815df6a28e3eb89ad61e4b20e09 | 54,128 |
import os
def create_folders():
"""
Creates folder for saving data (profile, post or group) according to current driver url
Changes current dir to target_dir
:return: target_dir or None in case of failure
"""
folder = os.path.join(os.getcwd(), "data")
utils.create_folder(folder)
os.chd... | 97dbdc593bfecc13d687baaaf88677f4dcfc00f0 | 54,129 |
from typing import List
def format_terminal_call(cmd: List[str]) -> str:
"""
Format commands to/from the terminal for readability
:param cmd: List of strings much like sys.argv
:return: Formatted string used for display purposes
"""
return ' '.join(cmd).replace("--", " \\ \n\t--") | 63af43a7d8a5cb708f8a9f6d7467e62e378876b4 | 54,130 |
def plot_attribution(a, a_display=None, title=None, ylabel='',
conf_level=0.95):
"""Produce a plot of the ensemble forecasts
Returns
----------
plt object
"""
a = a.reset_index(drop=True)
if type(a) is not pd.core.frame.DataFrame:
raise Exception('a, the attribution data... | e5800e844806145777b6cca2abb5a62b57b48a49 | 54,131 |
def process_first_section(section_text, filename, context):
"""Special treatment for the first top-level section of a Vim doc file."""
output = []
hits, misses = 0, 0
output.append("[discrete]")
output.append("== First section")
mark_unprocessed_text_start(output, context)
for c, line in enu... | 0b47889eb8f00f58fc1e8d41d6279cfaaf9ce163 | 54,132 |
def evaluate_and_log_bleu(estimator, bleu_source, bleu_ref, vocab_file_path):
"""Calculate and record the BLEU score."""
subtokenizer = tokenizer.Subtokenizer(vocab_file_path)
uncased_score, cased_score = translate_and_compute_bleu(
estimator, subtokenizer, bleu_source, bleu_ref)
tf.logging.info("Bleu s... | ca76832397503f56a66cd3adaff4ef67b72653bb | 54,133 |
def isSameCapacityAndSpeed(drives,raids):
""" Check if all the HDDs in the RAID container have the
same capacity and speed. Return True if so, if not
return an error message.
"""
if len(raids) <= 0:
return True
else:
slots = raids[0]['sas_id'].split(',')
drivesOnRAID = fi... | d03f9ae1786370538eebdb17f4cca57528493bf5 | 54,134 |
from typing import Optional
from typing import Tuple
def is_decimal(value: Optional[str]) -> Tuple[bool, Optional[Decimal]]:
"""
none is not a numeric value, otherwise try to parse it by float function
"""
if value is None:
return False, None
try:
v = float(value)
return True, Decimal(v)
except ValueError... | 0d56f329d5063d3788b426e7cb2d7ab1b3246107 | 54,135 |
from typing import Dict
import yaml
def load_config_file(file_path: str) -> Dict:
"""
Load a YAML config file. Uses UnsafeLoader
:rtype: Dict
"""
with open(file_path, 'r') as yaml_file:
cfg = yaml.load(yaml_file, Loader=yaml.UnsafeLoader)
return cfg | 52024a77e8e940f919245bb7b5093043f6d2158c | 54,136 |
def remove_zero_area(shape, properties, fid, zoom):
"""
All features get a numeric area tag, but for points this
is zero. The area probably isn't exactly zero, so it's
probably less confusing to just remove the tag to show
that the value is probably closer to "unspecified".
"""
# remove the... | 51b3b4aaa940d14261d857c3abcb6315ca82d83d | 54,137 |
def get_w(roll_mat_csr, sale_usd):
"""
"""
# Calculate the total sales in USD for each item id:
total_sales_usd = sale_usd.groupby(
['id'], sort=False)['sale_usd'].apply(np.sum).values
# Roll up total sales by ids to higher levels:
weight2 = roll_mat_csr * total_sales_usd
r... | 8fc48e55c00d400c1c449bd35f9493b5149349f5 | 54,138 |
def is_latin_square(row_length: int, array: str) -> bool:
"""Return whether array is a latin square."""
# check horizontally
row = 1
column = 0
numbers = []
for index, digit in enumerate(array):
# check for new row
if index % row_length == 0:
row += 1
col... | f85721f93f27b72797702849375992e43314a847 | 54,139 |
def convert_to_JSON(graph):
"""Converts an igraph into a D3-compatible json file
:returns a json Object
"""
nodes = []
for node in graph.vs:
nodes.append({'id': node['name'],
'label': node['label'],
'size': node['totalCred'],
... | 70bef265f139cc8a33d2f7ffc78ec6202f86c5dc | 54,140 |
import random
def spin_the_roulette() -> str:
"""
Returns one of 'red', 'black', 'green' in random, using the ROULETTE_COLORS chances.
"""
return random.choice(ROULETTE_COLORS) | 1d6f5d38de3128d2682e33f94b695a40a9dfa925 | 54,141 |
def root_mean_square_f(a, axis=None, weights=None, masked=False):
"""The RMS along the specified axes.
:Parameters:
a: array-like
Input array. Not all missing data
axis: `int`, optional
Axis along which to operate. By default, flattened input
is used.
... | 7f5f706a1f3a603904f0b7945977dd8d900504fa | 54,142 |
def format_links(
links,
decimals=4,
headers=False,
delimiter=None,
):
"""Generates a summary table for a hit cluster.
Args:
hits (list): collection of Hit objects
decimals (int): number of decimal points to show
show_headers (bool): show column headers in output
... | 678615ea2eb3f58ea0290e0360638a063fc82280 | 54,143 |
def _apply_slice(data, s):
"""
Apply slice s (given as a string) to the data.
Parameters
----------
data : np.array
The data to be sliced.
s : str
A string representation of the slice, e.g. '[...]', '[0, :]', etc.
Returns
-------
np.array
The sliced data.
... | 42a8e876cbf40ac85a216ba067b0108f7f489a82 | 54,144 |
import numpy
import math
def FindPriorRanges(xs, num_points, num_stderrs=3.0, median_flag=False):
"""Find ranges for mu and sigma with non-negligible likelihood.
xs: sample
num_points: number of values in each dimension
num_stderrs: number of standard errors to include on either side
Returns... | 0bb7fadeaee74ea2c0a1e50f48bf98f2c55721ef | 54,145 |
import os
import logging
def do_popen(command, log=True, force_en_env=False):
"""Connect via Popen and log the result."""
if force_en_env: # force an english environment
force_en_env = os.environ.copy()
force_en_env['LC_ALL'] = 'C'
stdout, stderr = Popen(command, stdout=PIPE, stderr=P... | 98462f187f2af8db2f6287fd8f0b505036a35822 | 54,146 |
def split_color_string(color_string):
"""Split a ``color_string`` by whitespace into a list of it's ``components``. """
if not color_string:
return []
return [thing for thing in regexes["whitespace"].split(color_string) if thing] | a980c43519275332930cfae2aff81eb514dfb4af | 54,147 |
def ask_for_confirmation(title, message):
"""Ask the user to finally remove title from the Kodi library"""
return xbmcgui.Dialog().yesno(heading=title, line1=message) | b333c381b0808842025731270bc09d14d6129e38 | 54,148 |
def serpentine(rows, columns):
""" Make a serpentine pattern """
rows = range(rows)
columns = range(columns)
pos = []
for column in columns:
for row in rows:
pos.append((row,column))
rows.reverse()
return pos | 162c762a4fce76549955ea71b2053f8bc01fc0ce | 54,149 |
def _identity_metric_nested(name, input_tensors):
"""Create identity metrics for a nested tuple of Tensors."""
update_ops = []
value_tensors = []
for tensor_number, tensor in enumerate(nest.flatten(input_tensors)):
value_tensor, update_op = _identity_metric_single(
name="{}_{}".format(name, tensor_n... | ecbbb0cff935c95236862a744f954722c47f1377 | 54,150 |
def lenient_chain_to_quadratic(chain, target_adjacency, chain_strength):
"""Determine the quadratic biases that induce the given chain.
Args:
chain (iterable):
The variables that make up a chain.
target_adjacency (dict/:class:`networkx.Graph`):
Should be a dict of the f... | 90b96904463fb53c225af006db401f8b88949b94 | 54,151 |
import random
import hashlib
import time
import os
def get_random_string(length=12,
allowed_chars='abcdefghijklmnopqrstuvwxyz'
'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'):
"""
Return a securely generated random string.
The default length of 12 with the... | 804d4410742f5ecb7aa7e1bf7ff782c8a8b4770c | 54,152 |
def parse(content: str) -> GherkinDocument:
"""
Parse the content of a file to an AST.
"""
parser = Parser()
try:
parse_result = parser.parse(StringOnlyTokenScanner(content))
except ParserError as e:
raise InvalidInput(e) from e
try:
result = converter.structure(par... | 630488a29b9a1eeb61d28674d2c99d6df8e5c3f9 | 54,153 |
from re import T
def pql_tables(state: State):
"""Returns a table of all the persistent tables in the database.
The resulting table has two columns: name, and type.
"""
names = state.db.list_tables()
values = [(name, state.db.import_table_type(name, None)) for name in names]
tuples = [sql.Tup... | b50814b3e489801591d45d3da47822ede7bbef63 | 54,154 |
import time
def process_area(con=None, area=None, callback=None, tmp_ext=None, folder_path=None, frm="GTiff", minimum_area=0.5, parallel_jobs=1):
"""
TODO: maak iets waarmee het asynchroon kan draaien?
TODO: callback functie maken ipv hier in dit script draaien
This function processes splits up the pr... | 390885382401df8761b6f06864209bbb5c0a06d8 | 54,155 |
from shapely import speedups
def speedups() -> bool:
"""
Speedups are now enabled by default if they are available.
You can check if speedups are enabled with the enabled attribute.
"""
return speedups.enabled | 84ca1180b5aefaaa166c6ab52bda0a1c34314813 | 54,156 |
from pathlib import Path
def graph_to_filenames(graph,root,masks,indir,prefix):
"""
Generate a list of filenames for the sequences of nested taxids from a root.
"""
filenames = defaultdict(list)
def descend(root):
"""
Iteratively descend from a root to generate a list of
f... | 98436e407b5ba11c1d9e575c4f1f40bf24b39c72 | 54,157 |
def _dask_or_eager_func(name, eager_module=np, list_of_args=False,
n_array_args=1):
"""Create a function that dispatches to dask for dask array inputs."""
if has_dask:
def f(*args, **kwargs):
if list_of_args:
dispatch_args = args[0]
else:
... | a10bddbed986545c1881844f742eac496919c804 | 54,158 |
def crop_data(data, box_width=200, center=None, data_only=True, wcs=None, **kwargs):
"""Return a cropped portion of the image
Shape is a box centered around the middle of the data
Args:
data (`numpy.array`): Array of data.
box_width (int, optional): Size of box width in pixels, defaults to... | 8aea5e838f822f895d13d42ed687a933373aad47 | 54,159 |
def load_star_image(): # pragma: no cover
"""Load an optical image with stars.
Returns
-------
hdu : `~astropy.io.fits.ImageHDU`
Image HDU
Examples
--------
.. plot::
:include-source:
from photutils import datasets
hdu = datasets.load_star_image()
... | 958761688d2c817e424bd30dd3acfc2fe6a17e10 | 54,160 |
def build_huffman_tree(list_hufftrees):
"""
构造huffman树
"""
while len(list_hufftrees) > 1:
# 1. 按照 weight 对 huffman 树进行从小到大的排序
list_hufftrees.sort(key=lambda x: x.get_wieght())
# 2. 挑出weight 最小的两个huffman编码树
temp1 = list_hufftrees[0]
temp2 = list_hufftrees[1]
... | 5ce7f1080a922e7957ad562ac3e3c5549d4e1bd3 | 54,161 |
import random
def split_data(data, prob):
"""splits the data into fractions [prob, 1-prob]"""
results = [], []
for row in data:
results[0 if random.random() < prob else 1].append(row)
return results | eb092cff35f9f98498c343162780921981a45ba0 | 54,162 |
import pkg_resources
import pathlib
import sys
def change_dir(monkeypatch):
"""Set current dir to the path of `scaffold` project"""
scaffold_path = pkg_resources.resource_filename(init.__name__, "scaffold")
monkeypatch.chdir(scaffold_path)
cwd = pathlib.Path(scaffold_path).absolute().__str__()
if... | 07c903b7cfb3fe7e8e70ccd418dc3cd802b76b36 | 54,163 |
def mp3_get_file_info(filename: str) -> SoundFileInfo:
"""Fetch some information about the audio file (mp3 format)."""
filenamebytes = _get_filename_bytes(filename)
with ffi.new("drmp3 *") as mp3:
if not lib.drmp3_init_file(mp3, filenamebytes, ffi.NULL):
raise DecodeError("could not open... | 50f47784d670f7c5c590da70975e79743af2c6ab | 54,164 |
from typing import Tuple
from typing import List
from typing import Dict
from typing import Any
def generate_test_data(
method: constants.Method,
num_rows=1,
remove_merchant_id=False
) -> Tuple[List[bigquery.Row], constants.Batch, constants.BatchIdToItemId, Dict[
str, Any]]:
"""Generates a tuple con... | 79064b6f27e1e972f40e23cc42d99968cad36571 | 54,165 |
import itertools
def enumerate_space(extent):
"""Enumerate all the points in a space with the given extent. Use this
function to ensure spaces are always enumerated in the same order.
"""
return itertools.imap(np.asarray, itertools.product(*map(xrange, extent))) | eed3897debf1370b4631e822a54aba25f6e7c5be | 54,166 |
import argparse
def _get_argparser():
"""to organize and clean format argparser args"""
parser = argparse.ArgumentParser()
parser.add_argument(
'arg-1',
help='desc'
)
parser.add_argument(
"--optional-arg-1",
action="store",
dest="optional_arg_1",
... | c30acede95e36de05361a50d8060f497e52afbee | 54,167 |
from pathlib import Path
from typing import Any
from typing import Iterable
def file_resource(
path: Path | str,
value_type: type = Stream,
compress: Any = None,
writeable: bool = False,
publish: bool = True,
policies: Iterable[Policy] | None = None,
) -> type:
"""
Return a new resourc... | 9ed41395a2db5f0abaa810266fa50867608a0e7e | 54,168 |
import tqdm
def sc_get_patient_df_dict(all_file_paths):
"""
Loads all the methylation DF and returns them as a dictionary
:param all_file_paths: List of all the methylation files
:return: A dictionary were the keys are the patient and the values a dictionary of chromosome and the methylation df
""... | 21dfadc1ca965a64e9b2280adf7ad53071b52ae5 | 54,169 |
def rgba2rgb(rgba, background=(255,255,255)):
""" Converts a 4-channel image array to a 3-channel image array
Inputs:
rbga: 4-channel array of image pixel data
Output:
An np array containing the 3-channel array respresenting the pixel values of the image
"""
row, col, ch = rgba.shape
... | 43d2152eac868f6ef4d19eb7d1a1eb3fbb7ae697 | 54,170 |
def get_model_fields(model, m2m=False):
"""
Given a model class, will return the dict of name: field_constructor
mappings.
"""
tree = get_model_tree(model)
if tree is None:
return None
possible_field_defs = tree.find("^ > classdef > suite > stmt > simple_stmt > small_stmt > expr_stmt... | 388b1429845578dc107c213306794cab3ed2201e | 54,171 |
from typing import Optional
import os
def guess_requirements_path(django_directory_path: str,
project_name: str) -> Optional[str]:
"""Guess the absolute path of requirements.txt.
The logic is as the follows:
1. If "requirements.txt" exists in the given directory, return it... | 3a01319bcdd7c90e2357deb9b93cec09650784f8 | 54,172 |
def _handle_no_answer(prediction, ground_truths):
"""Check if there is no groundtruth answer and compute no-answer score."""
score = None
# Check for no-answer: ground_truths can look like ['', '', '']
# the reason there are multiple empty values because we operate at batch
# and append '' to the maximum... | 058d812cc53d10f77db40ebad48902c74f5248d4 | 54,173 |
def recover_request_key_and_name(recovery_date, recovery_secret1):
"""Download the private information about this ID from Freenet."""
secret1 = recovery_date + "--" + recovery_secret1
uploadprefix = recovery_secret_to_ksk(secret1)
return fastget(uploadprefix + "--identity")[1] | 5e8483121034530cc4bc932a5ef3207a9ae6fcc2 | 54,174 |
import os
def _locate(path):
"""Search for a relative path and turn it into an absolute path.
This is handy when hunting for data files to be passed into h2o and used by import file.
Note: This function is for unit testing purposes only.
Parameters
----------
path : str
Path to search f... | 854066396cf9f1e10bba8dc3175342212711ab2b | 54,175 |
def load_motchallenge(matrix_data, min_confidence=-1):
"""Load MOT challenge data.
This is a modification of the function load_motchallenge from the py-motmetrics library, defined in io.py
In this version, the pandas dataframe is generated from a numpy array (matrix_data) instead of a text file.
Param... | 78ed277044bbfee2fd1a10f907d5ca0d3534ae70 | 54,176 |
import re
def verify_route_four_byte_as(device, expected_as_path, peer_address, target_address=None,
protocol_type=None, protocol='bgp', no_protocol_type=False,
max_time=60, check_interval=10):
""" Verify best path counter
Args:
dev... | 5a26469c26cf3eb2f9bb7cfeba5a7443ed08f161 | 54,177 |
from typing import List
from typing import Dict
async def get_resources_from_events(policy_changes: List[Dict]) -> Dict[str, dict]:
"""Returns a dict of resources affected by a list of policy changes along with
the actions and other data points that are relevant to them.
Returned dict format:
{
... | 81a9758ae92ed191dc74248f57ce96136b4e8d73 | 54,178 |
import time
def doSiteStable(site_id, site_type='cntr'):
"""Check if site is created or not
:param site_id: Enter site id
:type site_id: string
:param site_type: Enter site type
:type site_type: string
"""
if site_type == 'cntr':
b = Sites()
elif site_type == 'vcs':
b ... | 38b3f2605ee54aba3c013644e8ea7710ab3e8d4b | 54,179 |
def get_instance_fields(derived_col_names, target_name):
"""
It returns the Instance field element.
Parameters
----------
derived_col_names : List
Contains column names after preprocessing.
target_name : String
Name of the Target column.
Returns
-------
... | 885c9804c50d0e790c044dcafcc0de8eaf0d5dd1 | 54,180 |
import re
from datetime import datetime
import pytz
def cleanupDatetimeRange(requestKeys, queryDict):
"""
cleanupDatetimeRange
... in queryDict merge submitted__lte and submitted__gte filter
fields into submitted__range for all datetime type fields
(e.g. submitted)
... | 9e9464f3aae682583227939e28237fda4bc6c7b6 | 54,181 |
from os.path import dirname, join, exists
def parse_requirements(fname='requirements.txt'):
"""
Parse the package dependencies listed in a requirements file.
CommandLine:
python -c "import setup; print(setup.parse_requirements())"
"""
require_fpath = join(dirname(__file__), fname)
if ... | 85f16a09676db95e86da95ba494c6d2d8f996387 | 54,182 |
def BFGS(f, x, iters=10, tol=1e-10):
""" Run the gradient descent algorithm to minimize a function f.
Parameters
----------
f: callable (function)
x: int, float, or `Variable` object
initial guess/starting point for minimum
iters: integer
maximum number of iterations
tol: float
thi... | c16cf2e4a69f9ddf3b89f870b5ed7d48ba7064ea | 54,183 |
from django.template.loader import get_template
from django.template import Context
def get_admin_options(item_container, user_perms):
""" Personen mit manager-Rechten koennen bestimmte Optionen auswaehlen """
if not user_perms.perm_manage:
return ''
tSection = get_template('app/survey/admin_options.html')
... | 67fe7dd8a4daa49c3475c43fb4591cc377fd46e2 | 54,184 |
from io import StringIO
def FromString(s, more_formatters=lambda x: None, _constructor=None):
"""Like FromFile, but takes a string."""
f = StringIO.StringIO(s)
return FromFile(f, more_formatters=more_formatters, _constructor=_constructor) | 3dbf74df2ee49bcaccf316c755a07dd7ea9d3cf0 | 54,185 |
def xacto(fields,x,y,z):
"""xacto is a function which takes a list of strings iterates through this list until it reaches a passed index 'x' it then runs the recursive function digimon to find the first letter in the string,finds the index of that letter in the string,
splits the string into just numbers 'TopT... | 860101ec00e2ed3734348b3ad2ea12b0da944b58 | 54,186 |
def get_tooltip(mod):
"""Returns the tooltip for the given mod."""
return manifest.get_cfg('mods', mod).get_string('tooltip') | dfce300e9ebd5c479c8352354b5835743ed746f2 | 54,187 |
def dif_prices(p_df_predicciones, p_grupo):
"""
Visualizacion de las diferencias de la mediana del ultimo precio por clase
con respecto a la prediccion
Parameters
---------
p_df_predicciones: DataFrame : resultado de predicciones
p_grupo: str : nombre del grupo de productos
Returns
... | 42788bb49f08adf034742f8d74d0adbd0079a25d | 54,188 |
def divergence(
ts, sample_sets, indexes=None, windows=None, mode="site", span_normalise=True
):
"""
Computes average pairwise divergence between two random choices from x
over the window specified.
"""
windows = ts.parse_windows(windows)
if indexes is None:
indexes = [(0, 1)]
me... | 4d66bbf0eac364c2573d053f6092484065c8e0b6 | 54,189 |
def get_recipe_options(recipe):
"""Retrieves additional options for the given recipe
Args:
recipe: Project recipe
Returns:
dic: Contains recipe params w/ following potential keys,
BAIT
TARGET
MSKQ
MARKDUPLICATES
For Example:
{'BAIT': '/path/to/HemeBrainPACT_v1_BAITS.interval_list',
... | 98bc2961072aba1452011c03d257fb7a8e7aa7a1 | 54,190 |
def plot_data_type(frag):
"""
Create the plot
:param: frag pd.DataFrame -
:param:
"""
data = []
labels = []
for st_pair, st in SUBSTITUTION_TYPES_COMBINED:
st_sizes = frag[frag['Var'].isin(st_pair)]['Size']
if len(st_sizes) > 1:
data.append(st_sizes)
... | 708f0f82b5b198597306025eca8d7034a5804003 | 54,191 |
from typing import Mapping
from typing import List
import more_itertools
def _pick_first_with_field(
datasets_wide: Mapping[MultiRegionDataset, pd.DataFrame],
timeseries_field_datasets: Mapping[FieldName, List[MultiRegionDataset]],
) -> Mapping[MultiRegionDataset, pd.DataFrame]:
"""Creates a DataFrame for... | 5637b84f183d2b0a55871fc4c62ff39951ac01a6 | 54,192 |
from typing import Optional
from typing import Mapping
from typing import Any
import os
import logging
def eval_policy(
_run,
_seed: int,
env_name: str,
eval_n_timesteps: Optional[int],
eval_n_episodes: Optional[int],
num_vec: int,
parallel: bool,
render: bool,
render_fps: int,
... | b2b69780d41d2c19f88f8ef3e5e922bf976586ce | 54,193 |
def hash_id(note):
"""Return hashed id from seed note
:param note: Pytest fixture
:return: hash string from note.id
"""
return hashids.encode(note.id) | c28740cdc355ef1b711bd8fc7599277ff4403a92 | 54,194 |
def build_data(document, publication):
"""
Maps the variables of pt_law_downloader to our form
"""
return {'creator_name': publication['creator'],
'type': publication['type'],
'number': publication['number'],
'text': publication['text'],
'summary': publica... | 1fc7353a288eb0a66be95786a9a6bb69139baf8d | 54,195 |
def get_credit_card():
"""
gets a valid credit card from the user via console
"""
print("- PAYMENT INFORMATION -")
print("Please enter your credit card information. This information will NOT be saved.\n")
card_number = input("Please type your CREDIT CARD NUMBER: ").strip()
card_expiry= input... | 1d949b591f39708f61ec202c5cc1dd28f6378a06 | 54,196 |
import os
def deduplicate(data_name, data_dict, data_dir):
"""
Return a local path for given data path
Args:
data_name: the basename of the target file
data_dict: the existing mapping of local paths
data_dir: the full path of the destination directory
"""
n_dups = 0
bas... | 3cc8c41a424612ad6080b53f47af5d19981dc50f | 54,197 |
def gmx_cluster(input_structure_path: str, input_traj_path: str, output_pdb_path: str, input_index_path: str = None, properties: dict = None, **kwargs) -> int:
"""Execute the :class:`GMXCluster <gromacs.gmx_cluster.GMXCluster>` class and
execute the :meth:`launch() <gromacs.gmx_cluster.GMXCluster.launch>` metho... | b365edb07554cc31572efd61a3d19aa92c192fd2 | 54,198 |
def precision_and_recall(true_labels, labels_limits):
"""Estimate the precision and recall
:param true_labels: true labels
:param labels_limits: predicted labels
:return: precision and recall
"""
_, fp, fn, tp = confusion_matrix(true_labels, labels_limits).ravel()
return tp / (fp + tp), tp... | eb978787f53a4e471e2940350684e2027405c15b | 54,199 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.