content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def performStats(dataArray):
"""
Statically calculate and assign summed values of occurances to each entry
"""
yearArray = [[0,0] for i in range(20)]
for entry in dataArray:
oSum = 0
nSum = 0
for k, v in entry.old.items():
# print(k,v)
oSum += v
... | 5,321,400 |
def eventize(stat, teams_regex):
""" Events: End result, goal, penalties
Given statistics text (ottelupöytäkirja), return a list of events
"""
home_team, guest_team, events, current_score = None, None, [], (0,0)
for line in stat.split("\n"):
line=line.strip()
# end result
... | 5,321,401 |
def make_file_list(files, list_filename):
"""
Write a python list of files to a list file witch each element on a new line.
Parameters
----------
files : list
List of files to write to the file list.
list_filename : str
The name of the list file to make.
... | 5,321,402 |
def QuantizeEmulate(to_quantize, quant_params, **kwargs):
"""Use this function to emulate quantization on NN layers during training.
The function accepts a single layer or multiple layers and handles them
appropriately.
Arguments:
to_quantize: A single keras layer, list of keras layers, or a
`tf... | 5,321,403 |
def search_fhir_resource_cls(
resource_type: str, cache: bool = True, fhir_release: str = None
) -> Union[str, NoneType]: # noqa: E999
"""This function finds FHIR resource model class (from fhir.resources) and return dotted path string.
:arg resource_type: the resource type name (required). i.e Organizati... | 5,321,404 |
def get_blockages_from_comments(
filenames: List[Text]) -> Optional[List[List[float]]]:
"""Returns list of blockages if they exist in the file's comments section."""
for filename in filenames:
if not filename:
continue
blockages = []
# Read the first file if filename is comma separated list.
... | 5,321,405 |
def get_tags(file_name):
"""Retreives a list of the tags for a specific file"""
if File.get(File.file_name == file_name):
file_tags = (Tag
.select()
.join(FileTag)
.where(FileTag.file_id == File.get(File.file_name == file_name)))
... | 5,321,406 |
def ispointer(obj: Any) -> bool:
"""Check if a given obj is a pointer (is a remote object).
Args:
obj (Any): Object.
Returns:
bool: True (if pointer) or False (if not).
"""
if type(obj).__name__.endswith("Pointer") and hasattr(obj, "id_at_location"):
return True
return ... | 5,321,407 |
def make_hmmer_presearchbed(nuc_fasta, hmmer_table, outbed, chrom_lens,
slop=3000, windowed=False, e_cutoff=1e-2):
"""
Creates a bed file with regions in which to search based on HMMER output table.
Filters HMMER hits by evalue then applies slop to the envelope regions of the hits.
Output bedfile is... | 5,321,408 |
def GetGCLLogTailer():
"""Return a GCL LogTailer."""
try:
# pylint: disable=g-import-not-at-top
from googlecloudsdk.api_lib.logging import tailing
# pylint: enable=g-import-not-at-top
except ImportError:
log.out.Print(LOG_STREAM_HELP_TEXT)
return None
return tailing.LogTailer() | 5,321,409 |
def login():
"""
Handles project account authentication
"""
if g.project is not None:
return redirect(url_for('home', project_name=g.project['project_name']))
form = LoginForm(request.form)
if form.validate_on_submit():
# On submit, grab name & password
project_name = fo... | 5,321,410 |
def context():
"""context: Overwritten by tests."""
return None | 5,321,411 |
def updateSolarStationsCsv(station_num, tmys, config, years, merged_csv_filepath):
"""
Append tmy information to solar stations csv. If this is in current dir, use that one, because that allows us to
process multiple stations at once. Otherwise download from data source.
"""
new_solar_path, new_file... | 5,321,412 |
def insert_new_group_id_into_library_versions_kt(group_id, artifact_id):
"""Inserts a group ID into the LibrarVersions.kt file.
If one already exists, then this function just returns and reuses
the existing one.
Args:
group_id: group_id of the new library
artifact_id: group_id of the n... | 5,321,413 |
def reraise_remote_error(self, remote_err):
"""
This is a function re-raises the error thrown remotely
:param remote_err: :obj:`twisted.spread.pb.RemoteError`
:return: class
"""
# Get name of remote error
error_name = remote_err.remoteType.split(b".")[-1].decode()
# Get class of remote ... | 5,321,414 |
def postojanost_grubo_jac(x, ds, df, ip, ap, apf, l, Ct, kv, kf, ka):
"""
"""
dfdx0 = (Ct*kv*x[0]**(kv-1.)*x[1]**kf*ap**ka+np.pi*l/1000./x[0]**2./x[1]*
(ip*ds-2.*ap*(ip-1.)))
dfdx1 = (Ct*kf*x[0]**kv*x[1]**(kf-1.)*ap**ka+np.pi*l/1000./x[0]/x[1]**2.*
(ip*ds-2.*ap*... | 5,321,415 |
def find_max_location(scoremap):
""" Returns the coordinates of the given scoremap with maximum value.
# Arguments
scoremap: Numpy array of shape (crop_size, crop-size).
# Returns
keypoints2D: numpy array of shape (num_keypoints, 1).
"""
shape = scoremap.shape
x_grid, y_grid = ... | 5,321,416 |
def menu_func_import(self, context):
"""Defines which options are available in the 'file->import' menu"""
layout = self.layout
layout.operator(
operators.HYDRIDIC_OT_import_chemical_structure.bl_idname,
text="Chemical Structure",
) | 5,321,417 |
def iou_scn(x, gt, threshold=1.0):
"""
outputs: [K, H, W]
labels: [K, H, W]
"""
assert x.dim() == 3
assert gt.dim() == 3
len_x = x.size(0)
len_gt = gt.size(0)
assert len_x == len_gt
M = []
for k in range(len_x):
M.append(iou_pair(x[k], gt[k]))
iou_scores = torc... | 5,321,418 |
def load_word_embedding(filepath):
"""
given a filepath to embeddings file, return a word to vec
dictionary, in other words, word_embedding
E.g. {'word': array([0.1, 0.2, ...])}
"""
def _get_vec(word, *arr):
return word, np.asarray(arr, dtype='float32')
print('load word embeddings... | 5,321,419 |
def upload_subjects(
subject_set_id,
manifest_files,
allow_missing,
remote_location,
mime_type,
file_column,
):
"""
Uploads subjects from each of the given MANIFEST_FILES.
Example with only local files:
$ panoptes subject-set upload-subjects 4667 manifest.csv
Local filenam... | 5,321,420 |
def list_images(dataset, dataset_y, ylabel="", cmap=None):
"""
Display a list of images in a single figure with matplotlib.
Parameters:
images: An np.array compatible with plt.imshow.
lanel (Default = No label): A string to be used as a label for each image.
cmap (Def... | 5,321,421 |
def test_condition_5(base_settings):
"""No. 5 tests collection for Condition.
Test File: condition-example-f001-heart.json
"""
filename = base_settings["unittest_data_dir"] / "condition-example-f001-heart.json"
inst = condition.Condition.parse_file(
filename, content_type="application/json",... | 5,321,422 |
def get_next_prev(qt_id, topic_id):
""" Find the "next" and "previous" qtemplates, by topic, position. """
if not topic_id:
return None, None
# This is very inefficient, but with the way questions are stored,
# I didn't see a better way. Could maybe be revisited some time?
questionli... | 5,321,423 |
def get_text_and_video_items(full_dict):
"""
Return new OrderedDict filtered by hasaudio attribute = False
"""
items_by_has_not_audio = {
k: v
for k,v in full_dict.items() if not v[dk.hasAudio]}
return items_by_has_not_audio | 5,321,424 |
def test_fit_notallzeros(lfrfitmodel):
"""Should not be all zeros.
"""
expected = False
all_zeros = not np.any(lfrfitmodel)
print("allzeros:" + str(all_zeros))
assert all_zeros == expected | 5,321,425 |
def svm_predict(model, samples):
"""Predicts the response based on the trained model"""
return model.predict(samples)[1].ravel() | 5,321,426 |
def _get_sim300(node: ast.Compare) -> List[Tuple[int, int, str]]:
"""
Get a list of all Yoda conditions.
Compare(
left=Constant(value='Yoda', kind=None),
ops=[Eq()],
comparators=[Name(id='i_am', ctx=Load())],
)
"""
errors: List[Tuple[int, ... | 5,321,427 |
def dbl_cos_fit_func(p, x):
# the frequency is fixed
"""
A double sinus (fundamental + 1st harmonic) used as a fit function
"""
startidx = 0
base = 0
if len(p) % 2 != 0:
base = p[0]
startidx = 1
first_harm = p[startidx] * np.cos(
2 * np.pi * x + 2 * np.pi * p[star... | 5,321,428 |
def __none_to_zero(string):
"""
Return '0' if the string is "none" or "null";
return the string itself otherwise.
@type string: C{string}
@param string: The string to test for values of "none" or "null".
@rtype: C{string}
@return: '0' if the string is "none" or "null", the string itself
... | 5,321,429 |
def get_homepage_header():
""" Returns the page header image of the homepage """
homepage_id = get_homepage_id()
if homepage_id is None:
return None
return get_page_header(homepage_id) | 5,321,430 |
def trigger_data_load(
regions: List[str],
cluster_config_path: str,
default_config_path: str,
env_config_path: str,
input_vars: Dict[str, str],
) -> dict:
"""
:param regions: AWS regions in which the EMR job needs to be triggered
:type regions: list
:param cluste... | 5,321,431 |
def _test_afqt(df):
""" NLSY provides percentile information for AFQT scores, reconstructed here
as a check based on NLSY instructions.
"""
# Breaking the logic of the code a bit, copies of the object are drawn from here.
df_internal = df.copy(deep=True)
# Adjust for missing values here, even ... | 5,321,432 |
def _load_roiscsv(fp):
"""
Loads the specified ROIs CSV file.
:param fp: the file object for the ROIs CSV data to load
:type fp: file
:return: the list of predictions
:rtype: list
"""
result = []
reader = csv.DictReader(fp)
for i, row in enumerate(reader):
# score
... | 5,321,433 |
def analyze_command(subaction, subcommand_args):
"""Run the specific docker that analyzes the data"""
docker_client = docker.from_env()
image = _find_docker_image(docker_client, "opencna/analyzer/" + subaction)
if image:
#docker-py does not implement a mechanism to pass the stdin message
... | 5,321,434 |
def argmin(array):
""" Return the index to the maximum element of an array """
return min(zip(array, xrange(len(array))))[1] | 5,321,435 |
def convert_opentopo(proj_info):
"""
Creates another .tif file with the name .converted.tif for every .tif file located
in the passed directory.The converted.tif file is supposed to be converted into the Daymet
custom projection. Depends on theread_meta() method executing correctly. It doesn't check
for the conver... | 5,321,436 |
def braid_group_rep_loss(input_dim=1):
"""
Purpose
-------
loss for the braid group. When the loss is minimal, the braid group relations are satisfied for the generator R_op.
Parameters
----------
input_dim, the dimension of the R_op generator for the brai... | 5,321,437 |
def strains():
"""
Endpoint that returns a list of all available strains.
Returns
-------
strains : JSON
Returns a JSON array of all available strains.
"""
try:
strains = df2.to_json(orient="records")
except Exception as e:
raise e
return strains | 5,321,438 |
def _number_of_digits(number: int) -> int:
""" Returns the number of digits in the given number """
return int(log10(number)) + 1 | 5,321,439 |
def include(d, e):
"""Generate a pair of (directory, file-list) for installation.
'd' -- A directory
'e' -- A glob pattern"""
return (d, [f for f in glob.glob('%s/%s'%(d, e)) if os.path.isfile(f)]) | 5,321,440 |
def get_document(doc_slug: str) -> QuerySet:
""" Возвращает документ по слагу. """
return models.Document.objects.filter(
slug=doc_slug
).select_related('category', 'publisher') | 5,321,441 |
def currentsellings():
"""shows a list of the ites that the user is currently selling"""
items = Item.query.filter(
(Item.user_id == session["user_id"]) & (Item.sold == 0)).all()
return render_template("currentsellings.html", items=items) | 5,321,442 |
def main():
"""The main entry point."""
parser = argparse.ArgumentParser(
description="Test that glibc's signal numbers match the kernel's.")
parser.add_argument('--cc', metavar='CC',
help='C compiler (including options) to use')
args = parser.parse_args()
sys.exit(gl... | 5,321,443 |
def catches(raisable: Raisable, catchable: Catchable):
"""
Tests if raisable value would be catchable by catchable value.
"""
if isinstance(catchable, type):
catchable = [catchable]
if isinstance(raisable, type):
return any(issubclass(raisable, exc) for exc in catchable)
else:
... | 5,321,444 |
def bootstrap_test(
stat_val,
bootstrap_estimates,
nobs,
stat_val_control,
bootstrap_estimates_control,
nobs_control
) -> BootstrapTestResult:
"""
:param stat_val: sample value of statistic in treatment group
:param bootstrap_estimates: bootstrap estimates (10... | 5,321,445 |
def query_ned_by_refcode(refcode='2011ApJS..193...18W',
root_url='http://nedwww.ipac.caltech.edu/cgi-bin/nph-objsearch'):
"""
Query NED for basic data on objects cited in a particular reference.
keywords:
refcode - 19-digit reference code for journal article.
Example: 2011ApJS..193...18W is ... | 5,321,446 |
def batch_iter(x_data, batch_size, pad_len, to_shuffle=True):
"""
Turn dataset into iterable batches.
Args:
data: The data
batch_size: The size of the data batch
pad_len: The padding length
shuffle: Shuffle or not (default: True)
Returns:
A batch iterator for dat... | 5,321,447 |
def calc_distance_between_point_and_line(line_points, p3):
"""[Calcs the perpendicular distance between a point and a line]
Arguments:
line_points {[list]} -- [list of two 2-by-1 np arrays with the two points that define the line]
p3 {[np array]} -- [point to calculate the distance from]
... | 5,321,448 |
def set_hash_status(qhash, **kwargs):
"""
Set the enabled status of a hash
Variables:
qhash => Hash to change the status
Arguments:
None
Data Block:
"true"
Result example:
{"success": True}
"""
user = kwargs['user']
data = request.json
if len(qhash) not... | 5,321,449 |
def test_generate_x(energy_model, xtrajs, sample_energies, max_energy=150,
figsize=None, layout=None, colors=None, titles=True):
""" Generates using x trajectories as an example
Parameters
----------
energy_model : Energy Model
Energy model object that must provide the funct... | 5,321,450 |
def ubatch_to_csv(batch):
"""
Utility function to convert a batch of APIUser data to CSV.
"""
permkey = 'permissions_dict'
fields = [k for k in batch[0].keys() if k != permkey]
fields.extend(batch[0][permkey].keys())
return '{}\n{}'.format(','.join(fields), '\n'.join([
','.join([str(... | 5,321,451 |
def get_user_repositories(username: str, show_forked: bool) -> list[Repository]:
"""
Retrieve the github repositories for a specific user.
Args:
username: The github username
show_forked: Whether to keep or discard forked repos
Returns: The github repositories for the user.
"""
... | 5,321,452 |
def evaluate_sample(
ds,
sample_id,
t=None,
visualise=True,
gt_masked=None,
model=None,
mask_targ=None,
save=False,
pose=None,
):
"""
Evaluate one sample of a dataset (ds). Calculate PSNR and mAP,
and visualise different model components for this sample. Additionally,
... | 5,321,453 |
def retrieve_best_run(
project_id: str, job_id: str
) -> NamedTuple('Outputs', [('metric_value', float), ('alpha', float),
('max_iter', int)]):
"""Retrieves the parameters of the best Hypertune run."""
from googleapiclient import discovery
from googleapiclient import errors
ml ... | 5,321,454 |
def FindDeck(transact, msg_list):
"""
Returns None if not a deck message.
:param transact:
:param msg_list:
:return:
"""
for msg in msg_list:
if 'connectResp' in msg:
try:
deck = msg['connectResp']['deckMessage']['deckCards']
Log('Found Dec... | 5,321,455 |
def mean(x: VariableLike,
dim: Optional[str] = None,
*,
out: Optional[VariableLike] = None) -> VariableLike:
"""Element-wise mean over the specified dimension.
If the input has variances, the variances stored in the output are based on
the "standard deviation of the mean", i.e.,
... | 5,321,456 |
def evaluate(
context: mlrun.MLClientCtx, model_path: str, dataset_path: str, batch_size: int,
):
"""
The evaluation handler. Load the Mask Detection model and run an evaluation on the given parameters. The evaluation
is orchestrated by MLRun.frameworks.pytorch.
:param context: The MLRun Funct... | 5,321,457 |
def HarmonicOscillator(inverse_mass_matrix, k=1.0, m=1.0):
"""Potential and Kinetic energy of an harmonic oscillator."""
def potential_energy(x: TensorVariable) -> TensorVariable:
return at.sum(0.5 * k * at.square(x))
def kinetic_energy(p: TensorVariable) -> TensorVariable:
v = inverse_mas... | 5,321,458 |
def guid_to_num(guid):
"""
Convert a DHT guid to an integer.
Args:
guid: The guid to convert, as a string or unicode, in
hexadecimal.
Returns:
An integer corresponding to the DHT guid given.
"""
return int(guid.rstrip('L'), base=16) | 5,321,459 |
def test_tds_top_catalog():
"""Test parsing top-level catalog."""
url = 'http://thredds.ucar.edu/thredds/catalog.xml'
cat = TDSCatalog(url)
assert cat | 5,321,460 |
def create_gifs(output_filename, *args, **kwargs):
"""
:param self:
:param output_filename:
:param args:
:param kwargs:
:key mask: default True
:key scale: default False
:key band_number:
:key nodata:
:key cmap_name: default Blues
:key cmap: default B... | 5,321,461 |
def script_code(script_name):
"""Returns the four-letter ISO 15924 code of a script from its long name."""
load_data()
folded_script_name = _folded_script_name(script_name)
try:
return _HARD_CODED_FOLDED_SCRIPT_NAME_TO_CODE[folded_script_name]
except:
return _folded_script_name_to_co... | 5,321,462 |
def test_group_retrieval(setup_groups):
"""Test retrieval of the actual group from a path.
The ``group`` attribute will return None
if no group is associated with the path
"""
group_path = GroupPath()
assert group_path['x'].is_virtual
assert not group_path['a'].is_virtual
assert group_p... | 5,321,463 |
def get_dashboard() -> Dict:
"""Get dashboard for user
:return: Returns dictionary with surveys and reports
:rtype: Dict
"""
user = get_user()
user_surveys = get_user_surveys(user)
result = []
for survey in user_surveys:
author = get_user(survey.AuthorId)
result.append(... | 5,321,464 |
def acos(close):
"""Vector Trigonometric ACos
:param close:
:return:
:real:
"""
return ACOS(close) | 5,321,465 |
def register_api_resource(app: Flask):
"""
An entry point to register the rest api resources.
This function is called by the "api.on_app_initialization" function
on the app initialization.
:param api: An "flask_restful_swagger_2.API" object instance.
"""
# API initialization
from flask... | 5,321,466 |
def gather_slice_list_items(slices, key):
"""For a list of slices, get the flattened list of all of a certain key."""
return list(itertools.chain(*[s[key] for s in slices if key in s])) | 5,321,467 |
def mock_rasterio_open_cogs(band):
"""Mock rasterio Open for Sentinel2 dataset."""
assert band.startswith("s3://sentinel-cogs")
band = band.replace("s3://sentinel-cogs", SENTINEL_COG_BUCKET)
return rasterio.open(band) | 5,321,468 |
def advance_time(df, delay, column=None, keep_all_timestep=False):
"""
This function rolls the given columns of the given dataframe by a number of hours defined by the delay.
It also erases the last n-rows (n=delay) of each sequences.
:param df:
:param delay:
:param column:
:param keep_all_t... | 5,321,469 |
def course():
""" Courses Controller """
mode = session.s3.hrm.mode
def prep(r):
if mode is not None:
auth.permission.fail()
if r.component_name == "training":
s3.crud_strings["hrm_training"].label_create = T("Add Trainee")
return True
s3.prep = prep
... | 5,321,470 |
def run_tests(datout, tests, dat_inst=None, sim_id="", trb_exp=False,
hor_avg=False, chunks=None, **kw):
"""Run test functions for WRF output postprocessed with WRFlux.
Thresholds are hard-coded.
Parameters
----------
datout : nested dict
Postprocessed output for all variab... | 5,321,471 |
def reset_password(request):
"""view to reset the password"""
if request.method == "POST":
valid, errors = validate(*['code', 'password'], **get_request_data(request))
if not valid:
return Response({"error": errors}, status=status.HTTP_422_UNPROCESSABLE_ENTITY)
data = get_req... | 5,321,472 |
def str_to_datetime(date: str) -> dt:
"""Convert str to datetime"""
if date is None:
return None
return dt.strptime(date, '%Y-%m-%d') | 5,321,473 |
def test_applies_method_filters(app):
"""Method filters are applied for generated and rendered templates"""
with app.test_request_context():
genshi = app.extensions['genshi']
@genshi.filter('html')
def prepend_title(template):
return template | Transformer('head/title').prep... | 5,321,474 |
def contributions(datafile):
""" text data file => list of string """
contribs = []
with open(datafile, 'r') as data:
for line in data.readlines():
line = line.strip()
line_data = line.split(" ")
info_string = " ".join(line_data[:-1])
contrib = {}
con... | 5,321,475 |
def job_wrapper_io_files(param, user_defined_work_func, register_cleanup, touch_files_only):
"""
run func on any i/o if not up to date
"""
assert(user_defined_work_func)
i,o = param[0:2]
if not touch_files_only:
ret_val = user_defined_work_func(*param)
else:
for f in get_st... | 5,321,476 |
def writeFasta(seqs, outfile):
"""Writes the specified sequences in fasta format to the specified output
file."""
for seqName in seqs.keys():
print >> outfile, ">" + seqName
print >> outfile, seqs[seqName] | 5,321,477 |
def utcnow():
"""
Get the current UTC time which has the time zone info.
"""
return datetime.datetime.now(dateutil.tz.tzutc()) | 5,321,478 |
def test_secret(service_client: Any, arn: str, token: str) -> None:
"""Test the secret
This method validates that the user can login to the Qumulo cluster with the
password in AWSPENDING.
Args:
service_client (client): The secrets manager service client
arn (string): The secret ARN or... | 5,321,479 |
def get_xform_location(xform):
"""
Returns the sql location associated with the user who submitted an xform
"""
from corehq.apps.users.models import CouchUser
user_id = getattr(xform.metadata, 'userID', None)
if not user_id:
return None
user = CouchUser.get_by_user_id(user_id)
i... | 5,321,480 |
def _write_value(value, path):
"""
Writes specified value into path. Note that the value is wrapped in single
quotes in the command, to prevent injecting bash commands.
:param value: The value to write (usually a number or string)
:param path: A valid system path
"""
base_command = "echo '{0... | 5,321,481 |
def test_big_random_list():
"""
Test su tre liste generate casualmente con un numero di elementi che varia tra 10000 e 100000 con numeri che variano tra 1 e 1000000
"""
# test liste create casualmente
list1 = big_random_list_generator()
list2 = big_random_list_generator()
list3 = big_ran... | 5,321,482 |
def wrap_non_picklable_objects(obj, keep_wrapper=True):
"""Wrapper for non-picklable object to use cloudpickle to serialize them.
Note that this wrapper tends to slow down the serialization process as it
is done with cloudpickle which is typically slower compared to pickle. The
proper way to solve seri... | 5,321,483 |
def values(names):
"""
Method decorator that allows inject return values into method parameters.
It tries to find desired value going deep. For convinience injects list with only one value as value.
:param names: dict of "value-name": "method-parameter-name"
"""
def wrapper(func):
@wraps... | 5,321,484 |
def post():
""" Get. """
return render_template('public/post.html') | 5,321,485 |
def ensemble(models: List [training.Model],
model_input: Tensor) -> training.Model:
""" ensemble part
"""
outputs = [model.outputs[0] for model in models]
y = Average()(outputs)
model = Model(model_input, y, name='ensemble')
return model | 5,321,486 |
def save_layout(request, layout_id):
""" Save layout properties """
if request.method != 'POST':
return res.get_only_post_allowed({})
layout_entry = BluesteelLayoutEntry.objects.filter(id=layout_id).first()
if layout_entry is None:
return res.get_response(404, 'Bluesteel layout not foun... | 5,321,487 |
def _to_deck(group: ParseResults) -> Deck:
"""Parse a deck into a python list."""
result: Deck
if "size" in group:
N = int(group["size"])
if group["type"] == "C":
result = ["".join(group.value)]
elif group["type"] == "I":
result = [int("".join(k)) for k in gro... | 5,321,488 |
def build_gabriel_graph_from_delaunay(X, tri, delaunay_adjacency_matrix):
"""Remove edges from delaunay triangulation and returns the adjaceny matrix of a Gabriel graph
:param delaunay_adjacency_matrix: scipy sparse matrix (csr format)
"""
# Convert adjacency matrix to coo format for direct access to ea... | 5,321,489 |
def _npz_headers(npz, namelist=None):
"""
taken from https://stackoverflow.com/a/43223420
Takes a path to an .npz file, which is a Zip archive of .npy files.
Generates a sequence of (name, shape, np.dtype).
namelist is a list with variable names, ending in '.npy'.
e.g. if variable 'var' is in... | 5,321,490 |
def list_image_files(dirs):
"""lists the images files under the dirs.
:return:
a list of tuples
the shape of tuple: (image_filename, subdir, fullpath)
"""
images = []
for a_dir in dirs:
for direntry in os.listdir(a_dir):
# Anything starting with "." is ignored
if direntry[0:1] == '.':
... | 5,321,491 |
def setup_logging(quiet: bool, verbose: bool, debug: bool, logfile_path: Optional[str] = None) -> None:
"""Set up Python logging."""
logger = logging.getLogger("apologies")
logger.setLevel(logging.DEBUG)
handler = logging.FileHandler(logfile_path) if logfile_path else logging.StreamHandler(sys.stdout)
... | 5,321,492 |
def randomize_demand(demand):
"""Return a randomized demand when given a static demand"""
return random.uniform(0, 2.25) * demand | 5,321,493 |
def _collect_input_shape(input_tensors):
"""Collects the output shape(s) of a list of Keras tensors.
# Arguments
input_tensors: list of input tensors (or single input tensor).
# Returns
List of shape tuples (or single tuple), one tuple per input.
"""
input_tensors = to_list(input_t... | 5,321,494 |
def iaga2df(iaga2002_fname, D_to_radians=True):
"""
Parser the magnetometer data record stored in the IAGA-2002 format
file *iaga2002_fname*. If *D_to_radians*, declination data (D) are
converted from degrees to radians. Return the tuple with the
:class:`DataFrame` containing the data and header inf... | 5,321,495 |
def test_plot_screen():
"""Test screen plotting function."""
tmp = np.ones((10, 20, 2))
pytest.raises(ValueError, ea.plot_screen, tmp)
tmp = np.ones((10, 20, 3))
ea.plot_screen(tmp) | 5,321,496 |
def geom_bar(mapping=aes(), *, fill=None, color=None, position="stack", size=None):
"""Create a bar chart that counts occurrences of the various values of the ``x`` aesthetic.
Supported aesthetics: ``x``, ``color``, ``fill``
Returns
-------
:class:`FigureAttribute`
The geom to be applied.
... | 5,321,497 |
def _for_all_familynames(namefile, fn):
"""Call fn passing the family name and style descriptor for
all families in namefile. '#' is a comment to eol, blank lines are
ignored."""
styles = None
with open(namefile, "r") as f:
for name in f:
ix = name.find("#")
if ix >= 0:
... | 5,321,498 |
def parse_args(args):
"""define arguments"""
parser = argparse.ArgumentParser(description="go_term_enrichment")
parser.add_argument(
"file_names",
type=str,
help="Name of folder and filenames for the promoters extracted",
)
parser.add_argument(
"go_directory",
... | 5,321,499 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.