content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
import requests
from bs4 import BeautifulSoup
import dateutil
def fetch_events_art_history(base_url='https://www.sas.upenn.edu'):
"""
Fetch events from Art History Department
"""
page = requests.get(urljoin(base_url, '/arthistory/events'))
page_soup = BeautifulSoup(page.content, 'html.parser')
... | 2c17219cbbdd94251db43f52459c196dada014fc | 3,644,500 |
def calc_Q(nu=0.0,delta=0.0,lam=1.0,ret_k=False):
"""
Calculate psic Q in the cartesian lab frame.
nu and delta are in degrees, lam is in angstroms
if ret_k == True return tuple -> (Q,ki,kr)
"""
(ki,kr) = calc_kvecs(nu=nu,delta=delta,lam=lam)
Q = kr - ki
if ret_k == True:
return... | 9c5a9e885b1f78bab7a1de2bbf6a3de2d5723e18 | 3,644,501 |
def build_data(args):
"""
build test data
"""
task_name = args.task_name.lower()
processor = reader.MatchProcessor(data_dir=args.data_dir,
task_name=task_name,
vocab_path=args.vocab_path,
... | ca52d035d34a83e1de0b3cad261f03ce53fd2f0c | 3,644,502 |
def format_date(d):
"""Date format used in the report."""
if type(d) == str:
d = dateutil_parse(d)
return d.isoformat() | de999992e16fe52f42f4b79bbb0a78668d3fa109 | 3,644,503 |
import torch
def pytorch_argmax(op):
"""Implementation of argmax for pytorch."""
def _impl(x, dim):
dim = tuple(sorted(dim))
n = ()
for _s in range(len(x.shape)):
if _s not in dim:
n = n + (_s,)
n = n + dim
x = x.permute(n)
ns = x.sh... | cc466b41c0dd4bb9730dcdf50816b9d0cf66cfaa | 3,644,504 |
import os
def get_wine_quality(num_rows=None):
"""
Wine Quality dataset from UCI repository (
https://archive.ics.uci.edu/ml/datasets/Wine+Quality
Using the white wine data set, not the red.
- Dimensions: 4898 rows, 12 columns.
- Task: Regression
:param num_rows:
:return: X,y
"""... | 2302b8502486261037ed8be92e8c6988dd46e8ea | 3,644,505 |
def parse_eos(eos):
"""Function to interpret input as an EOS"""
if hasattr(eos, 'asq_of_rho_p'):
return eos # already is EOS class
if eos == 'H' or eos == 'h':
return SimpleHydrogen()
try:
return Ideal(float(eos)) # try parsing as a gamma value
except ValueError:
ra... | 2303a9028b89647fae4b9a4fca0363826310b730 | 3,644,506 |
def get_2D_hse_kpoints(struct_for_path, ibzkpth):
"""
Args:
struct_for_path: Structure from which linemode k-points will
be generated.
ibzkpth:
Returns:
the Kpoints file object in the form of a string
ready for execution by MPInterfaces
calibr... | e4ad65df4f4fc41c0af48e84dfd9b9bbddea9e20 | 3,644,507 |
import logging
import os
import pickle
import traceback
def read_cache(logger: logging.Logger, cache_file: str) -> CachedData:
"""Read file with Py pickle in it."""
if not cache_file:
return CachedData()
if not os.path.exists(cache_file):
logger.warning("Cache file '%s' doesn't exist.", c... | 83f309e760f3d63a73fcb9a3f378f535605d7c94 | 3,644,508 |
def neutralize(word, g, word_to_vec_map):
"""
Removes the bias of "word" by projecting it on the space orthogonal to the bias axis.
This function ensures that gender neutral words are zero in the gender subspace.
Arguments:
word -- string indicating the word to debias
g -- numpy-array o... | a732050ef214fe29c6e234cea2f0a7d63b784829 | 3,644,509 |
def loadRowCluster(ndPage,algo):
"""
load cluster algo = aglo
"""
xpCluster = f".//Cluster[@algo='{algo}']"
lClusters= ndPage.xpath(xpCluster)
return lClusters | dcb75214e58d6656f58bee78b904562c05fd36d8 | 3,644,510 |
def _elementwise(f):
""" Enables elementwise operations
The wrapper implements two different modes of argument evaluation
for given p_1,..., p_k that represent the predicted distributions
and and x_1,...,x_m that represent the values to evaluate them on.
"elementwise" (default): Repeat the sequenc... | 7cb9a17c648384e07bde3b57415244efd7e34e8a | 3,644,511 |
def is_valid_task_id(task_id):
"""
Return False if task ID is not valid.
"""
parts = task_id.split('-')
if len(parts) == 5 and [len(i) for i in parts[1:]] == [8, 4, 4, 4]:
tp = RE_TASK_PREFIX.split(parts[0])
return (len(tp) == 5 and
all(i.isdigit() for i in tp[::2])... | d39e26ae52d96f9c6ed0bf5fea2ac317d5b9e8af | 3,644,512 |
def figure_14_9():
"""Return the unweighted, undirected graph from Figure 14.9 of DSAP.
This is the same graph as in Figure 14.10.
"""
E = (
('A', 'B'), ('A', 'E'), ('A', 'F'), ('B', 'C'), ('B', 'F'),
('C', 'D'), ('C', 'G'), ('D', 'G'), ('D', 'H'), ('E', 'F'),
('E', 'I'), ('F' 'I'), ('G', 'J'), ('G', 'K'), (... | d81a11aa46bd62942c880dfa8f0a724801979449 | 3,644,513 |
def audit_umbrelladns(networks_fwrules):
"""Accepts a list of firewall rules for a client
Checks for rules to allow DNS lookups to Umbrella and
deny all other DNS lookups.
Returns a list of clients and a boolean of whether Umbrella DNS
is configured properly"""
umbrelladns_audit = []
host1 =... | 26c01011dee998ba398db03603c61c00845055ea | 3,644,514 |
from typing import Tuple
import itertools
def parse_element_container(elem: ET.Element) -> Tuple[Types.FlexElement, ...]:
"""Parse XML element container into FlexElement subclass instances.
"""
tag = elem.tag
if tag == "FxPositions":
# <FxPositions> contains an <FxLots> wrapper per currency.... | 477776ff49e47fb0ca45767c5a74ff6941d0abb0 | 3,644,515 |
def _is_smooth_across_dateline(mid_lat, transform, rtransform, eps):
"""
test whether the CRS is smooth over the dateline
idea borrowed from IsAntimeridianProjToWGS84 with minor mods...
"""
left_of_dt_x, left_of_dt_y, _ = rtransform.TransformPoint(180-eps, mid_lat)
right_of_dt_x, right_of_dt_y, ... | c1058bb24f254ce7158ec69872cfec1081a3027c | 3,644,516 |
def reverse_args(func: Func) -> fn:
"""
Creates a function that invokes func with the positional arguments order
reversed.
Examples:
>>> concat = sk.reverse_args(lambda x, y, z: x + y + z)
>>> concat("a", "b", "c")
'cba'
"""
func = to_callable(func)
return fn(lambda ... | e1e734f767fb187f9563f51d1f106ebfc17ebbfb | 3,644,517 |
def ar(x, y, z):
"""Offset arange by z/2."""
return z / 2 + np.arange(x, y, z, dtype='float') | 0aca14778dd4ba814d9303146d3226f6645f2366 | 3,644,518 |
def dot(inputs, axes, normalize=False, **kwargs):
"""Functional interface to the `Dot` layer.
Args:
inputs: A list of input tensors (at least 2).
axes: Integer or tuple of integers,
axis or axes along which to take the dot product.
normalize: Whether to L2-normalize samples along the
... | 2e5d83aad376e82b7938ebfec8cef3074bec3c58 | 3,644,519 |
def delete_queue(name, region, opts=None, user=None):
"""
Deletes a queue in the region.
name
Name of the SQS queue to deletes
region
Name of the region to delete the queue from
opts : None
Any additional options to add to the command line
user : None
Run hg as... | b17f54eefab61e682697fe09d26f6a55658b4171 | 3,644,520 |
import inspect
def get_all_methods(klass):
"""Get all method members (regular, static, class method).
"""
if not inspect.isclass(klass):
raise ValueError
pairs = list()
for attr, value in inspect.getmembers(
klass, lambda x: inspect.isroutine(x)):
if not (attr.startswi... | ada4f47c750455ddd1300f26eb3e296b046acefe | 3,644,521 |
import pathlib
def _suffix_directory(key: pathlib.Path):
"""Converts '/folder/.../folder/folder/folder' into 'folder/folder'"""
key = pathlib.Path(key)
shapenet_folder = key.parent.parent
key = key.relative_to(shapenet_folder)
return key | 147539065c3d21ee351b23f2d563c662fe55f04a | 3,644,522 |
def setDesktop( studyID ):
"""This method sets and returns TRUST_PLOT2D desktop"""
global moduleDesktop, desktop
if studyID not in moduleDesktop:
moduleDesktop[studyID] = DynamicDesktop( sgPyQt )
moduleDesktop[studyID].initialize()
desktop = moduleDesktop[studyID]
return desktop | fd7ad5b57a832e4d6d4adbf2b5fbf973cc1b9e3e | 3,644,523 |
def load(file_path: str):
"""Used for loading dataset files that have been downloaded.
Args:
file_path: Path to file to be loaded.
Returns:
x: Data used to train models.
y: Dataset labels.
Example:
>>> data,labels = load("model/mnist.npz")
>>> # Prin... | 47e045d343509322cf9f845f454a99bf6f34cde7 | 3,644,524 |
def xrefchar(*args):
"""
xrefchar(xrtype) -> char
Get character describing the xref type.
@param xrtype: combination of Cross-Reference type flags and a
cref_t of dref_t value (C++: char)
"""
return _ida_xref.xrefchar(*args) | a6991e0a56710359804d21b79b86ed3ead852769 | 3,644,525 |
def problem_5_14_8(scalars, vectors):
"""
>>> u = list2vec([1,1,0,0])
>>> v = list2vec([0,1,1,0])
>>> w = list2vec([0,0,1,1])
>>> x = list2vec([1,0,0,1])
>>> problem_5_14_8([1, -1, 1], [u, v, w]) == x
True
>>> problem_5_14_8([-1, 1, 1], [u, v, x]) == w
True
>>> problem_5_14_8([1,... | e8456cbf7a0e47519003c3b3a414560c1d1ee5ac | 3,644,526 |
def atomic(fn, self, *args, **kwargs):
"""
Atomic method.
"""
return self._atom(fn, args, kwargs) | 96fdd8451bb534deefb2ffbe101526838d75fa6e | 3,644,527 |
def text_to_string(filename, useEncoding):
"""Read a text file and return a string."""
with open(filename, encoding=useEncoding, errors='ignore') as infile:
return infile.read() | f879bb747699496204820b74944fd563658a7117 | 3,644,528 |
def forward_propagation(x, paras, bn_paras, decay=0.9):
""" forward propagation function
Paras
------------------------------------
x: input dataset, of shape (input size, number of examples)
W: weight matrix of shape (size of current layer, size of previous layer)
b: bias vec... | eb2955f9bff056ad1639d2b63a39a6ff40293400 | 3,644,529 |
def sentence_indexes_for_fragment(fragment: Fragment, sentences: list) -> list:
"""Get the start and end indexes in the whole article for the sentences encompassing a fragment."""
start_sentence_index = sentence_index_for_fragment_index(fragment.start, sentences)
end_sentence_index = sentence_index_for_frag... | 08ec8df9c9e7e06f20dd6554a9da3a0ca89e4f53 | 3,644,530 |
import struct
def _watchos_extension_impl(ctx):
"""Implementation of watchos_extension."""
top_level_attrs = [
"app_icons",
"strings",
"resources",
]
# Xcode 11 requires this flag to be passed to the linker, but it is not accepted by earlier
# versions.
# TODO(min(Xcod... | 0e79df610e751e6322888ee68a15a7ff4ceda970 | 3,644,531 |
def train_and_eval(trial: optuna.Trial, ex_dir: str, seed: [int, None]):
"""
Objective function for the Optuna `Study` to maximize.
.. note::
Optuna expects only the `trial` argument, thus we use `functools.partial` to sneak in custom arguments.
:param trial: Optuna Trial object for hyper-para... | 128b94452d3a398efe5b754e4e3dacf25bd5e165 | 3,644,532 |
def alert_query(alert, authz):
"""Construct a search query to find new matching entities and documents
for a particular alert. Update handling is done via a timestamp of the
latest known result."""
# Many users have bookmarked complex queries, otherwise we'd use a
# precise match query.
query = ... | c7181e174613ea61fe67d6165f1022a10ab5862e | 3,644,533 |
def iscomment(s):
"""
Define what we call a comment in MontePython chain files
"""
return s.startswith('#') | ab3a9d240e423c562c9e83cdd9599fddf144b7c3 | 3,644,534 |
import sys
def hxlvalidate_main(args, stdin=STDIN, stdout=sys.stdout, stderr=sys.stderr):
"""
Run hxlvalidate with command-line arguments.
@param args A list of arguments, excluding the script name
@param stdin Standard input for the script
@param stdout Standard output for the script
@param s... | 613b7157f23e9c6234ae3428d18e0f22789131ea | 3,644,535 |
def fix_bayes_factor(bayes_factor):
"""
If one of the bayes factors is 'inf' we get a string instead of a
tuple back. This is hacky but fixes that.
"""
# Maximum cut off for Bayes factor value
max_bf = 1e12
if type(bayes_factor) == str:
bayes_factor = bayes_factor.split(",")
... | 7e7912ea9b0c90f0945f486aa397a2df2d13d5cc | 3,644,536 |
def fiebelkorn_binning(x_trial, t_trial):
"""
Given accuracy and time-points, find the time-smoothed average accuracy
Parameters
----------
x_trial : np.ndarray
Accuracy (Hit: 1, Miss: 0) of each trial
t_trial : np.ndarray
The time-stamp of each trial
Returns
-------
... | 29651c03dba351475c881d77a08da618ba89aa6a | 3,644,537 |
def get_fastest_while_jump(condition:str, jump_tag:str, verdicts: list) -> list:
"""Verdicts like ["while", "a", "<", "10"] """
result = []
jumpables = ("===", ) + tuple(INVERT_TABLE.keys())
if len(verdicts) == 2:
result.append(F"jump-if {jump_tag} {verdicts[1]} != false")
elif verdicts[2] i... | 16f4b8ba1e180dbad22e93f6bf08ab52eecb0086 | 3,644,538 |
import sys
import os
from sys import path
def ChangeUserPath(args):
"""Function to change or create the user repository path. This is where all the user's data is
stored."""
global user_datapath
if user_datapath:
sys.stdout.write("Current user_datapath is: %s\n" % user_datapath)
elif sav... | 1d206e6c1c3bda4b6508a2f5b2f0a60cc81cc2cd | 3,644,539 |
import os
def absolute_path_without_git(directory):
"""
return the absolute path of local git repo
"""
return os.path.abspath(directory + "/..") | 1547bdebd8e6375f6725dbf36ae99a93eec5053b | 3,644,540 |
import os
def find_template(fname):
"""Find absolute path to template.
"""
for dirname in tuple(settings.TEMPLATE_DIRS) + get_app_template_dirs('templates'):
tmpl_path = os.path.join(dirname, fname)
# print "TRYING:", tmpl_path
if os.path.exists(tmpl_path):
return tmpl_... | ae77d4a72cd8eaf34a9a84d05631ccbb96466ad0 | 3,644,541 |
import torch
def create_hcp_sets(skeleton, side, directory, batch_size, handedness=0):
"""
Creates datasets from HCP data
IN: skeleton: boolean, True if input is skeleton, False otherwise,
side: str, 'right' or 'left'
handedness: int, 0 if mixed ind, 1 if right handed, 2 if left handed
... | 32615f19b70b8d78240adc1c2f60c5191f4c93fb | 3,644,542 |
def rtrim(n):
"""Returns a transform that removes the rightmost n points
"""
def t(xarr, yarr, *args):
return (xarr[:-n], yarr[:-n]) + args
t.__name__ = b'rtrim({})'.format(n)
return t | 583e4e2b9eef8281002760ccb1d336b9fdff36af | 3,644,543 |
def analyze_avg_prof_quality_by_department(dict_cursor, departmentID, campus):
"""
>>> analyze_avg_prof_quality_by_department(dict_cursor, 'CSC', 'St. George')
CSC
enthusiasm 3.95
course_atmosphere 3.90
...
(This is not complete)
"""
return __anal... | c44b74181e223c4a543575dd42f1db73b57e48b9 | 3,644,544 |
from os import linesep
def audit(environ):
"""Check a wmt-exe environment.
Parameters
----------
environ : dict
Environment variables.
Returns
-------
str
Warnings/errors.
"""
messages = []
for command in ['TAIL', 'CURL', 'BASH']:
messages.append(ch... | e65afb413501d5aceaf715af5bf409e5e9aa50c5 | 3,644,545 |
import re
import json
def parse_to_json(data_str):
"""
Convert string to a valid json object
"""
json_obj_list = []
obj = data_str.split('%')
for record in obj:
attributes = re.split(',', record)
data = json.dumps(attributes)
data = re.sub(r':', '":"', data)
d... | 288911694548fd603a3a261ac9c51c5c971599e0 | 3,644,546 |
def calculate_elbo(model, X, recon_X):
"""
Compute the ELBO of the model with reconstruction error and KL divergence..
"""
rec_loss = - np.sum(X * np.log(1e-8 + recon_X)
+ (1 - X) * np.log(1e-8 + 1 - recon_X), 1)
mu, logvar = model.transform(X)
kl = -0.5 * np.sum(1 + l... | aa3f2123bcc8ed0ee62b0b28a4fb3aeb0c1c886c | 3,644,547 |
def dice_loss(pred, target):
"""
Dice Loss based on Dice Similarity Coefficient (DSC)
@param pred: torch.tensor, model prediction
@param target: torch.tensor, ground truth label
"""
return 1 - dice_coeff(pred, target) | 9f940c09c4dac7477c6f77f2ecf632b95107f04f | 3,644,548 |
import struct
def parse(transaction):
""" Parses Bitcoin Transaction into it's component parts"""
byteStringLength = 2
# Version
version = struct.unpack('<L', transaction[0:4*byteStringLength].decode("hex"))[0]
offset = 4*byteStringLength
# print "Version is: " + str(version)
# Inputs
... | fcf9eede33b3dda8026a00a8a3a57ab2cd84ef22 | 3,644,549 |
import os
import re
def get_version():
"""Get project version
"""
version_file_path = os.path.join(
os.path.dirname(__file__),
'spowtd',
'VERSION.txt')
with open(version_file_path) as version_file:
version_string = version_file.read().strip()
version_string_re = re... | 4a11ae4efd6269b29acdef0835461ede33cf6e5c | 3,644,550 |
def get_related_items_by_type(parser, token):
"""Gets list of relations from object identified by a content type.
Syntax::
{% get_related_items_by_type [content_type_app_label.content_type_model] for [object] as [varname] [direction] %}
"""
tokens = token.contents.split()
if len(tokens) no... | a774830f92b6e2abc1df9d172c6b696b87dc83d0 | 3,644,551 |
def stitch_valleys(valley_list):
"""Returns a stitched list of valleys to extract seq from."""
valley_collection = utils.LocusCollection(valley_list, 1)
stitched_valley_collection = valley_collection.stitch_collection()
loci = []
regions = []
for valley in stitched_valley_collection.get_loci():
... | d5b4e35d66c9c5ff05a027569454d2ec1b612e45 | 3,644,552 |
def no_gcab_namespace(name, *args):
"""
Mock gi.require_version() to raise an ValueError to
simulate that GCab bindings are not available.
We mock importing the whole 'gi', so that this test
can be run even when the 'gi' package is not available.
"""
if name.startswith("gi"):
m = mo... | 7952d944aa1fb512874874870a2d9bfaa31c5834 | 3,644,553 |
import os
import shutil
def _start_beamtime(
PI_last, saf_num, experimenters=[], wavelength=None, test=False
):
"""function for start a beamtime"""
# check status first
active_beamtime = glbl.get('_active_beamtime')
if active_beamtime is False:
raise xpdAcqError("It appears that end_beamti... | c1daff80fa43e21bca90fba6ac3d6c66f6f62b6e | 3,644,554 |
import logging
def logger(module_name: str):
"""Инициализация и конфигурирования логгера"""
logging.basicConfig(
level=logging.INFO,
format='[%(levelname)s][%(asctime)s] %(name)s: %(message)s'
)
return logging.getLogger(module_name) | 0a436b50d16c752404d31e3f34b38239391236d5 | 3,644,555 |
from typing import List
def cast(op_name: str, expr: Expr, in_xlayers: List[XLayer]) -> XLayer:
"""
Conversion of Relay 'clip' layer
Relay
-----
Type: tvm.relay.op.clip
Ref: https://docs.tvm.ai/langref/relay_op.html
Parameters:
- a (relay.Expr)
The input tensor.
... | e6a7699f64054e3196a512929e1cfbc390ba214e | 3,644,556 |
def __generation_dec(n: int, m: int, x_min: np.array, x_max: np.array) -> np.matrix:
"""
:param n: num rows in returned matrix
:param m: num cols in returned matrix
:param x_min: float array, min possible nums in cols of returned matrix
:param x_max: float array, max possible nums in cols of returne... | d76970858faacc8757c0bfa5b8840f4b5ab200d0 | 3,644,557 |
def apply_tariff(kwh, hour):
"""Calculates cost of electricity for given hour."""
if 0 <= hour < 7:
rate = 12
elif 7 <= hour < 17:
rate = 20
elif 17 <= hour < 24:
rate = 28
else:
raise ValueError(f'Invalid hour: {hour}')
return rate * kwh | fb2c5b458c13456a39612720b6e80e0cd707391e | 3,644,558 |
def _compound_smiles(compound: reaction_pb2.Compound) -> str:
"""Returns the compound SMILES, if defined."""
for identifier in compound.identifiers:
if identifier.type == identifier.SMILES:
return identifier.value
return "" | 44c9f8169442b9a116a4d77ea6be74ec4cc27a31 | 3,644,559 |
import subprocess
def convert_pdf_to_txt(pdf, startpage=None):
"""Convert a pdf file to text and return the text.
This method requires pdftotext to be installed.
Parameters
----------
pdf : str
path to pdf file
startpage : int, optional
the first page we try to convert
R... | 469fe2439e4ca44e396df07d5e8edb2db5e90e87 | 3,644,560 |
def cross_correlizer(sample_rate, max_itd, max_frequency):
"""
Convenience function for creating a CrossCorrelizer with appropriate
parameters.
sample_rate : the sample rate of the wav files to expect.
max_itd : the maximum interaural time difference to test.
max_fre... | 747c42c3db2ad1f7642e575a35e3ce6d3c84b4b2 | 3,644,561 |
import altair as alt
def plot_precision_recall_at_k(
predicate_df, idx_flip, max_k=100, give_random=True, give_ensemble=True
):
"""
Plots precision/recall at `k` values for flipped label experiments.
Returns an interactive altair visualisation. Make sure it is installed beforehand.
Arguments:
... | e2edc16d8648f9dd913df41dfc39e0b48140cfe7 | 3,644,562 |
from typing import List
from typing import Union
def has_permissions(
permissions: int, required: List[Union[int, BasePermission]]
) -> bool:
"""Returns `True` if `permissions` has all required permissions"""
if permissions & Administrator().value:
return True
all_perms = 0
for perm in re... | db32fe9d1a53cd5b14b71522d08901172bbad8f7 | 3,644,563 |
def mat_to_xyz(mat: NDArrayFloat) -> NDArrayFloat:
"""Convert a 3D rotation matrix to a sequence of _extrinsic_ rotations.
In other words, 3D rotation matrix and returns a sequence of Tait-Bryan angles
representing the transformation.
Reference: https://en.wikipedia.org/wiki/Euler_angles#Rotation_matr... | 1f27e503b28f9a932bc4aa703de8a210968f64f6 | 3,644,564 |
import hashlib
def get_user_gravatar(user_id):
"""
Gets link to user's gravatar from serializer.
Usage::
{% get_user_gravatar user_id %}
Examples::
{% get_user_gravatar 1 %}
{% get_user_gravatar user.id %}
"""
try:
user = User.objects.get(pk=user_id)
e... | b8cd883c3ca76a3dc45253457715ac011c04785d | 3,644,565 |
def natural_key(s):
"""Converts string ``s`` into a tuple that will sort "naturally" (i.e.,
``name5`` will come before ``name10`` and ``1`` will come before ``A``).
This function is designed to be used as the ``key`` argument to sorting
functions.
:param s: the str/unicode string to convert.
... | 7eda87824ac9ad952c911d8b1946cc0af43fa4aa | 3,644,566 |
def read_ValidationSets_Sources():
"""Read and return ValidationSets_Sources.csv file"""
df = pd.read_csv(data_dir + 'ValidationSets_Sources.csv',header=0,
dtype={"Year":"str"})
return df | ea653e91ab37abd91297783caf8ea1fa6bd14545 | 3,644,567 |
from sys import int_info
def igcd_lehmer(a, b):
"""Computes greatest common divisor of two integers.
Euclid's algorithm for the computation of the greatest
common divisor gcd(a, b) of two (positive) integers
a and b is based on the division identity
a = q*b + r,
where the quotient q a... | 609db770670f718121fb045f3786aad5f0ff8e5f | 3,644,568 |
def regular_polygon_area_equivalent_radius(n, radius=1.0):
""" Compute equivalent radius to obtain same surface as circle.
\theta = \frac{2 \pi}{n}
r_{eqs} = \sqrt{\frac{\theta r^2}{\sin{\theta}}}
:param radius: circle radius
:param n: number of regular polygon segments
:return... | 4aacc8c2ab57516bef15167e5a22485c9f55bc2d | 3,644,569 |
def get_dashboard_list(project_id=None, page=1, page_size=25, token_info=None, user=None):
"""Get a list of dashboards
:param project_id: Filter dashboards by project ID
:type project_id: str
:param user_id: Filter dashboards by user ID
:type user_id: str
:param limit: Limit the dashboards
... | 9a15c87b081dcdb87e1a5c4778b0114309365a2b | 3,644,570 |
import torch
def _ssim(X, Y, filter, K=(0.01, 0.03)):
""" Calculate ssim index for X and Y"""
K1, K2 = K
# batch, channel, [depth,] height, width = X.shape
C1 = K1 ** 2
C2 = K2 ** 2
filter = filter.to(X.device, dtype=X.dtype)
mu_x = gaussian_filter(X, filter)
mu_y = gaussian_filter(... | 49deca478e06c35f06436f16ad34fb8154ba0cfd | 3,644,571 |
def get_all_messages(notification_queue, **kwargs):
"""
Get all messages on the specified notification queue
Variables:
complete_queue => Queue to get the message from
Arguments:
None
Data Block:
None
Result example:
[] # List of messages
"""
resp_lis... | c0a61d50cc3e6373bc007f8978278d49f66544e9 | 3,644,572 |
def ssa_reconstruct(pc, v, k):
"""
from Vimal
Series reconstruction for given SSA decomposition using vector of components
:param pc: matrix with the principal components from SSA
:param v: matrix of the singular vectors from SSA
:param k: vector with the indices of the components to be reconstr... | 1ac054f2d31ab6f883a369e682a33235305df604 | 3,644,573 |
import os
import sys
def loadImtoolrc(imtoolrc=None):
"""
Locates, then reads in IMTOOLRC configuration file from
system or user-specified location, and returns the
dictionary for reference.
"""
# Find the IMTOOLRC file. Except as noted below, this order
# match... | 68aa55443baaa5c0eb57d80af3f7a989cba1c2d9 | 3,644,574 |
def get_theo_joints_pm(W, b, beta):
"""calculate the theoretical state distribution for a Boltzmann
machine
"""
N = len(b)
joints = []
states = get_states(N)
for s in states:
joints.append(np.exp(-1. * get_energy(W, b, (2. * s - 1.), beta)))
joints /= np.sum(joints)
return j... | c84c518fac47d139f951d4973907dceec1d9c825 | 3,644,575 |
from typing import BinaryIO
def tail(the_file: BinaryIO, lines_2find: int = 20) -> list[bytes]:
"""
From http://stackoverflow.com/questions/136168/get-last-n-lines-of-a-file-with-python-similar-to-tail
"""
lines_found: int = 0
total_bytes_scanned: int = 0
the_file.seek(0, 2)
bytes_in_file... | 094917839d4b26e284244715452982eaf6e8c08a | 3,644,576 |
def add_device_tag_command(client, args):
""" Command to add tag to an existing admin devices entry """
site, concentrator, map = get_site_params()
transmitter_id = args.get('transmitter_id')
tag = args.get('tag')
result = client.add_device_tag(site=site, concentrator=concentrator, map=map,
... | 9aeaff1110515215bb7f2d3aa1a6ab5123cd31b2 | 3,644,577 |
def CommaSeparatedFloats(sFloatsCSV):
"""Read comma-separated floats from string.
[sFloatsCSV]: string, contains comma-separated floats.
<retval>: list, floats parsed from string.
"""
return [float(sFloat) for sFloat in sFloatsCSV.replace(" ","").split(",")] | 1aa12ca7297aa3bd809f6d2ffaf155233a826b49 | 3,644,578 |
def merge_channels(image_list):
"""
Merge channels of multiple scalar ANTsImage types into one
multi-channel ANTsImage
ANTsR function: `mergeChannels`
Arguments
---------
image_list : list/tuple of ANTsImage types
scalar images to merge
Returns
-------
ANTsIma... | 33b5588d6ad4d128ed6206652919408e32520c80 | 3,644,579 |
def get_var(name: str, options: dict) -> str:
"""
Returns the value from the given dict with key 'INPUT_$key',
or if this does not exist, key 'key'.
"""
return options.get('INPUT_{}'.format(name)) or options.get(name) | 9df0e3ec92af83b5719b88ca34f323bdfc7d1d84 | 3,644,580 |
import os
def get_filenames(is_training, data_dir, num_files=1014):
"""Return filenames for dataset."""
if is_training:
return [
os.path.join(data_dir, "train-%05d-of-01014" % i) for i in range(num_files)
]
else:
return [
os.path.join(data_dir, "validation-%... | 4381513fce78d7d491866db4f67a57496530d67c | 3,644,581 |
def create_txt_response(name, txt_records):
"""
Returns an RRSet containing the 'txt_records' as the result of a DNS
query for 'name'.
This takes advantage of the fact that an Answer object mostly behaves
like an RRset.
"""
return dns.rrset.from_text_list(name, 60, "IN", "TXT", txt_records) | 1f649719576b810a40ed7042b9b254653fe1364a | 3,644,582 |
import ast
def bit_xor(*arguments):
"""
Bitwise XOR function.
"""
return ast.BitXor(*arguments) | 07af3232a18796b4122e3ac6a4279ec00032c31d | 3,644,583 |
def get_chromiumdir(platform, release):
"""
Args:
platform (str): a sys.platform str
Returns:
str: path to Chromium User Data Directory
http://www.chromium.org/user-experience/user-data-directory
"""
if platform == 'darwin':
chromedir = os.path.expanduser(
'... | 4ed1a9d70dfd3430911d26ac47322e9612bfdb06 | 3,644,584 |
def make_ts_scorer(
score_func, greater_is_better=True, needs_proba=False, needs_threshold=False, **kwargs,
):
"""Make a scorer from a performance metric or loss function.
This factory function wraps scoring functions for use in `~sklearn.model_selection.GridSearchCV`
and `~sklearn.model_selection.cros... | 9003f82b52a1e915111bd46002fda8f61f6c9b9e | 3,644,585 |
def pfas(x):
"""Parse a JSON array of PFA expressions as a PFA abstract syntax trees.
:type x: open JSON file, JSON string, or Pythonized JSON
:param x: PFA expressions in a JSON array
:rtype: list of titus.pfaast.Expression
:return: parsed expressions as a list of abstract syntax trees
"""
... | e3544a89f16c908752a55ea58bfc3360abbe4121 | 3,644,586 |
def overlap(x, y, a, b):
"""Finds the overlap of (x, y) and (a, b).
Assumes an overlap exists, i.e. y >= a and b >= x.
"""
c = clamp(x, a, b)
d = clamp(y, a, b)
return c, d | c26b2f32ba9c12f72108c756ca4c1b4993fe8d55 | 3,644,587 |
def topological_sort(g):
"""
Returns a list of vertices in directed acyclic graph g in topological
order.
"""
ready = []
topo = []
in_count = {}
for v in g.vertices():
in_count[v] = g.degree(v, outgoing=False)
if in_count[v] == 0: # v has no constraints, i.e no incomin... | 5ac6261bf1b6fa92280abdc3fc95679ad9294e80 | 3,644,588 |
def probability_of_failure_in_any_period(p, n):
"""
Returns the probability that a failure (of probability p in one period)
happens once or more in n periods.
The probability of failure in one period is p, so the probability
of not failing is (1 - p). So the probability of not
failing over n p... | 92439161b6b1e3288fc665c72c145282c6c09bb2 | 3,644,589 |
def stage_1(transformed_token_list):
"""Checks tokens against ngram to unigram dictionary"""
dict_data = pd.read_excel(v.stage_1_input_path, sheet_name=v.input_file_sheet_name)
selected_correct_token_data = pd.DataFrame(dict_data, columns=v.stage_1_input_file_columns)
transformed_state_1 = []
for se... | 6dea5bb1e1e04d183ade142f50c36aea00933ff1 | 3,644,590 |
def _perform_sanity_checks(config, extra_metadata):
"""
Method to perform sanity checks on current classification run.
:param config: dirbs config instance
:param extra_metadata: job extra metadata dict obj
:return: bool (true/false)
"""
curr_conditions = [c.as_dict() for c in config.condit... | fa5fa39bae91393c4f91ab6aa3b595f8a0db2e4f | 3,644,591 |
def get_key_from_id(id : str) -> str:
"""
Gets the key from an id.
:param id:
:return:
"""
assert id in KEYMAP, "ID not found"
return KEYMAP[id] | 7fbf00bbd905382888b993bbee5564c42edf4e73 | 3,644,592 |
import string
def CreateFromDict(registration_dict):
"""Returns the content of the header file."""
template = string.Template("""\
// Copyright 2017 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// This file is... | 08d49b8cbb1275104b4498b98aed00747163e874 | 3,644,593 |
from datetime import datetime
def controller_add_raw_commands_not_privileged():
"""
This view allows a client to send a raw command to a CISCO device in not privileged EXEC mode
:return: <dict> result of the operation. check documentation for details
"""
# TODO: convert print screens to app.logge... | 86ba530e77646d506f1b9961908b30c5d00d4ecf | 3,644,594 |
def static_message_fixture(tmpdir_factory, prefix, message, suffix):
"""A fixture which provides a static message."""
filename = tmpdir_factory.mktemp('data').join('static_message.txt').strpath
file_contents = "{0}{1}{2}".format(prefix, message, suffix)
with open(filename, 'w') as f:
f.write(f... | a9a11508eb10760452cad557e792df30b068e8bc | 3,644,595 |
def entropy_image(filename,bins=30):
"""
extracts the renyi entropy of image stored under filename.
"""
img = cv2.imread(filename,0)/255.0 # gray images
p,_ = np.histogram( img, range=[0.0,1.0],bins=bins )
return -np.log(np.dot(p,p)/(np.sum(p)**2.0)) | b9686647601cb8850a6b03a1c52f4ad0a4218553 | 3,644,596 |
def satisfies_constraint(kel: dict, constraint: dict) -> bool:
"""Determine whether knowledge graph element satisfies constraint.
If the constrained attribute is missing, returns False.
"""
try:
attribute = next(
attribute
for attribute in kel.get("attributes", None) or ... | 39ae764e03c77dcb0145b9091d21df092894850d | 3,644,597 |
def static_unroll(core, input_sequence, initial_state, time_major=True):
"""Performs a static unroll of an RNN.
An *unroll* corresponds to calling the core on each element of the
input sequence in a loop, carrying the state through::
state = initial_state
for t in range(len(input_sequence)):
... | f61c9de5b90a0757617f9db588ab54e69918bc4b | 3,644,598 |
from typing import List
from typing import Tuple
def getElementByClass(className: str, fileName: str) -> List[Tuple[int, str]]:
"""Returns first matching tag from an HTML/XML document"""
nonN: List[str] = []
with open(fileName, "r+") as f:
html: List[str] = f.readlines()
for line in html:
... | 969e4070e16dec2e10e26e97cbaaab9d95e7b904 | 3,644,599 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.