content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def test_assistant_config_no_config_file(fs):
"""Test whether an `AssistantConfig` object raises
`AssistantConfigNotFoundError` when there's no assistant configuration
found in the search path.
"""
with pytest.raises(AssistantConfigNotFoundError):
assistant_config = AssistantConfig() | 8,400 |
def is_open(state: int) -> bool:
"""Return whether a given position (x, y) is open."""
return state == states_id.OPEN | 8,401 |
def gen_model_for_cp2k_simple(molten_salt_system):
"""
Description:
generate initial configuration for pure halide salt by pymatgen module, and transfer cif format to pdb format by Openbabel module
Args:
molten_salt_system: the simulated system
Returns:
no return
"""
global dir_molten_s... | 8,402 |
def sendJabber(sender,
password,
receivers,
body,
senderDomain=NOTIFY_IM_DOMAIN_SENDER,
receiverDomain=NOTIFY_IM_DOMAIN_RECEIVER):
"""
Sends an instant message to the inputted receivers from the
given user. The senderDomain is an ov... | 8,403 |
def loss_plot(model, model_str: str, color: str):
"""Plot the loss plots."""
f, ax = plt.subplots(1, 2, figsize=(18, 6))
ax[0].plot(model.history["loss"], label=f"{model_str} loss", color=color)
ax[0].plot(
model.history["val_loss"], label=f"{model_str} val loss", color=color, ls="--",
)
... | 8,404 |
def variant_sanity_check(m):
"""Convenience function. Given an initialized model try and do a sanity check test with it."""
ref_seq = ref[1]['seq']
pos, stop, refs, alts, p = m.get_variants(ref_seq, seed=10)
if len(pos) == 0:
raise SkipTest('The defaults do not yield any variants to test')
for p, s, r, a... | 8,405 |
def directory_log_summary(config):
"""
Summarise the input and out diretories and key information as text log from matsim config
When submitting jobs via the Bitsim Orchestration
"""
message = []
# add the date
message.append(f"Date:{date.today()}")
# add paths of the input files
me... | 8,406 |
def search():
"""
Searches for users with their name. Excludes the logged in user.
"""
data = json.loads(request.data)
search_term = data['search_term']
this_user = interface.get_user_by_id(get_jwt_identity())
users = interface.search_users(search_term)
result = [user.get_public_data(... | 8,407 |
def test_export_excel():
"""Test set the data in an excel file"""
reference = pandas.read_csv("tests/tracking.txt", sep='\t')
tracking = load.Load("tests/tracking.txt")
tracking.export("tests/test.xlsx", fmt="excel")
test = pandas.read_excel("tests/test.xlsx")
pandas.testing.assert_frame_equal(... | 8,408 |
def get_optics_mode(optics_mode, energy=energy):
"""Return magnet strengths of a given opics mode."""
if optics_mode == 'M0':
# 2019-08-01 Murilo
# tunes fitted to [19.20433 7.31417] for new dipoles segmented model
qf_high_en = 1.65458216649285
qd_high_en = -0.11276026973021
... | 8,409 |
def load_stock_order():
"""加载csv文件,导入并备份为 [.yyyy-mm-dd HH_MM_SS.bak 结尾的文件"""
base_dir = './auto_order_dir'
file_name_list = os.listdir(base_dir)
if file_name_list is None:
log.info('No file')
data_df = None
for file_name in file_name_list:
file_base_name, file_extension = os.pat... | 8,410 |
def _get_last_block_in_previous_epoch(
constants: ConsensusConstants,
sub_height_to_hash: Dict[uint32, bytes32],
sub_blocks: Dict[bytes32, SubBlockRecord],
prev_sb: SubBlockRecord,
) -> SubBlockRecord:
"""
Retrieves the last block (not sub-block) in the previous epoch, which is infused before th... | 8,411 |
def get_current_user():
"""Gets the current logged in user"""
user = User.get_one_by_field('id', value=get_jwt_identity())
response = {
'name': user['name'],
'username': user['username'],
}
return jsonify(response) | 8,412 |
def test_dynamism2a():
"""
parent.val 17
parent.val 18
parent.val 29
[17, 18, 29]
"""
n = Node()
n1 = Node()
n2 = Node()
res = []
def func(*events):
for ev in events:
if n.parent:
res.append(n.parent.val)
else:
... | 8,413 |
def create_kv_store(vm_name, vmdk_path, opts):
""" Create the metadata kv store for a volume """
vol_meta = {kv.STATUS: kv.DETACHED,
kv.VOL_OPTS: opts,
kv.CREATED: time.asctime(time.gmtime()),
kv.CREATED_BY: vm_name}
return kv.create(vmdk_path, vol_meta) | 8,414 |
def main():
""" Main Program """
pygame.init()
# Set the height and width of the screen
size = [SCREEN_WIDTH, SCREEN_HEIGHT]
screen = pygame.display.set_mode(size)
pygame.display.set_caption("SSSSSnake")
# Loop until the user clicks the close button.
done = False
# Used to manage... | 8,415 |
def mapdict(itemfunc, dictionary):
"""
Much like the builtin function 'map', but works on dictionaries.
*itemfunc* should be a function which takes one parameter, a (key,
value) pair, and returns a new (or same) (key, value) pair to go in
the dictionary.
"""
return dict(map(itemfunc, ... | 8,416 |
def get_backup_temp():
"""
This is the function for if the BMP280 malfunctions
"""
try:
temp = BNO055.temperature
logging.warning("Got backup temperature")
return temp
except RuntimeError:
logging.error("BNO055 not connected")
return get_backup_temp_... | 8,417 |
def test_graph(example):
"""
Use our example data to see that the dot output produced matches what we
expect.
"""
# The examples won't be byte-for-byte identical with what we produce unless
# we sort the lines
with open(example + ".dot") as f:
expect = "".join([l.strip() for l in f.r... | 8,418 |
def on_key_event(event):
"""
Keyboard interaction
:param event:
:return:
"""
key = event.key
if key.find("alt") == 0:
key = key.split("+")[1]
curAxis = plt.gca()
if key in "aeiou":
curAxis.set_title("Well done!")
plt.pause(1)
plt.close()
else:
... | 8,419 |
def density_matrix(M, row_part, col_part):
"""
Given a sparse matrix M, row labels, and column labels, constructs a block matrix where each entry contains the proportion of 1-entries in the corresponding rows and columns.
"""
m, n = M.shape
if m <= 0 or n <= 0:
raise ValueError("Matrix M has... | 8,420 |
def isAddressInMyAddressBookSubscriptionsListOrWhitelist(address):
"""
Am I subscribed to this address, is it in my addressbook or whitelist?
"""
if isAddressInMyAddressBook(address):
return True
queryreturn = sqlQuery(
'''SELECT address FROM whitelist where address=?'''
'''... | 8,421 |
def GetDateTimeFromTimeStamp(timestamp, tzinfo=None):
"""Returns the datetime object for a UNIX timestamp.
Args:
timestamp: A UNIX timestamp in int or float seconds since the epoch
(1970-01-01T00:00:00.000000Z).
tzinfo: A tzinfo object for the timestamp timezone or None for the local
timezone.
... | 8,422 |
def success(parsed_args):
"""
:param :py:class:`argparse.Namespace` parsed_args:
:return: Nowcast system message type
:rtype: str
"""
logger.info(
f"FVCOM {parsed_args.model_config} {parsed_args.run_type} run boundary condition "
f'file for {parsed_args.run_date.format("YYYY-MM-... | 8,423 |
def _kv_to_dict(kv_string):
"""
Simple splitting of a key value string to dictionary in "Name: <Key>, Values: [<value>]" form
:param kv_string: String in the form of "key:value"
:return Dictionary of values
"""
dict = {}
if ":" not in kv_string:
log.error(f'Keyvalue parameter not i... | 8,424 |
def get_column_names(df: pd.DataFrame) -> List[str]:
"""Get number of particles from the DataFrame, and return a list of column names
Args:
df: DataFrame
Returns:
List of columns (e.g. PID_xx)
"""
c = df.shape[1]
if c <= 0:
raise IndexError("Please ensure the DataFram... | 8,425 |
def get_default(schema, key):
"""Get default value for key in voluptuous schema."""
for k in schema.keys():
if k == key:
if k.default == vol.UNDEFINED:
return None
return k.default() | 8,426 |
async def send_websocket_messages_from_queue():
""" runs in the background and sends messages to all clients.
This is a janus queue, so it can be filled by sync code"""
try:
while True:
item = await app['message_queue'].async_q.get()
if len (app['websockets']) == 0:
... | 8,427 |
def get_font_loader_class():
"""Get the font loader associated to the current platform
Returns:
FontLoader: specialized version of the font loader class.
"""
if "linux" in sys.platform:
return FontLoaderLinux
if "win" in sys.platform:
return FontLoaderWindows
raise Not... | 8,428 |
def _map_tensor_names(original_tensor_name):
"""
Tensor name mapping
"""
global_tensor_map = {
"model/wte": "word_embedder/w",
"model/wpe": "position_embedder/w",
"model/ln_f/b": "transformer_decoder/beta",
"model/ln_f/g": "transformer_decoder/gamma",
}
if origina... | 8,429 |
def setplot(plotdata=None):
#--------------------------
"""
Specify what is to be plotted at each frame.
Input: plotdata, an instance of pyclaw.plotters.data.ClawPlotData.
Output: a modified version of plotdata.
"""
from clawpack.visclaw import colormaps, geoplot
from numpy import linsp... | 8,430 |
def test_skeleton(opts):
"""
Template of unittest for skeleton.py
:param opts: mapping parameters as dictionary
:return: file content as string
"""
template = get_template("test_skeleton")
return template.substitute(opts) | 8,431 |
def get_classpath(obj):
"""
Return the full module and class path of the obj. For instance,
kgof.density.IsotropicNormal
Return a string.
"""
return obj.__class__.__module__ + "." + obj.__class__.__name__ | 8,432 |
def bill_content(bill_version: str) -> str:
"""
Returns the bill text, broken down by the way the XML was structured
Args:
bill_version (str): bill_version_id used as a fk on the BillContent table
Returns:
str: String json array of bills
"""
results = get_bill_contents(bill_ver... | 8,433 |
def has_default(column: Column) -> bool:
"""Column has server or Sqlalchemy default value."""
if has_server_default(column) or column.default:
return True
else:
return False | 8,434 |
def iterations_median(benchmark_result):
"""A function to calculate the median of the amount of iterations.
Parameters
----------
benchmark_result : list of list of list of namedtuple
The result from a benchmark.
Returns
-------
numpy.ndarray
A 2D array containing the media... | 8,435 |
def _make_list(input_list, proj_ident):
"""Used by other functions, takes input_list and returns a list with items converted"""
if not input_list: return []
output_list = []
for item in input_list:
if item is None:
output_list.append(None)
elif item == '':
output_... | 8,436 |
def another_method():
"""
Another method!
:return:
"""
pass | 8,437 |
def impala_service(docker_ip, docker_services):
"""Ensure that Impala service is up and responsive."""
runner = CliEntryBasedTestRunner(impala_plugin)
# give the server some time to start before checking if it is ready
# before adding this sleep there were intermittent fails of the CI/CD with error:
... | 8,438 |
def monthly_ndvi():
"""Get monthly NDVI from MOD13C2 products."""
mod13c2_dir = os.path.join(DATA_DIR, 'raw', 'MOD13C2')
months = [m for m in range(1, 13)]
cities = [city.id for city in CASE_STUDIES]
ndvi = pd.DataFrame(index=cities, columns=months)
for city, month in product(CASE_STUDIES, month... | 8,439 |
def dvds_s(P, s):
""" Derivative of specific volume [m^3 kg K/ kg kJ]
w.r.t specific entropy at constant pressure"""
T = T_s(P, s)
return dvdT(P, T) / dsdT(P, T) | 8,440 |
def serialize(_cls=None, *, ctor_args: Tuple[str, ...] = ()):
"""Class decorator to register a Proxy class for serialization.
Args:
- ctor_args: names of the attributes to pass to the constructor when deserializing
"""
global _registry
def wrapped(cls):
try:
_serialize... | 8,441 |
def runcmd(args):
"""
Run a given program/shell command and return its output.
Error Handling
==============
If the spawned proccess returns a nonzero exit status, it will print the
program's ``STDERR`` to the running Python iterpreter's ``STDERR``, cause
Python to exit with a return status... | 8,442 |
def get_as_by_asn(asn_):
"""Return an AS by id.
Args:
asn: ASN
"""
try:
as_ = Asn.get_by_asn(asn_)
except AsnNotFoundError as e:
raise exceptions.AsnDoesNotExistException(str(e))
return as_ | 8,443 |
def spoken_form(text: str) -> str:
"""Convert ``text`` into a format compatible with speech lists."""
# TODO: Replace numeric digits with spoken digits
return _RE_NONALPHABETIC_CHAR.sub(" ", text.replace("'", " ")).strip() | 8,444 |
def get_default_group_type():
"""Get the default group type."""
name = CONF.default_group_type
grp_type = {}
if name is not None:
ctxt = context.get_admin_context()
try:
grp_type = get_group_type_by_name(ctxt, name)
except exception.GroupTypeNotFoundByName:
... | 8,445 |
def toHVal(op: Any, suggestedType: Optional[HdlType]=None):
"""Convert python or hdl value/signal object to hdl value/signal object"""
if isinstance(op, Value) or isinstance(op, SignalItem):
return op
elif isinstance(op, InterfaceBase):
return op._sig
else:
if isinstance(op, int)... | 8,446 |
def _make_readiness_probe(port: int) -> Dict[str, Any]:
"""Generate readiness probe.
Args:
port (int): service port.
Returns:
Dict[str, Any]: readiness probe.
"""
return {
"httpGet": {
"path": "/openmano/tenants",
"port": port,
},
"pe... | 8,447 |
def compute_embeddings_and_distances_from_region_adjacency(g,info, metric='euclidean', norm_type = 2, n_jobs=1):
"""
This method runs local graph clustering for each node in the region adjacency graph.
Returns the embeddings for each node in a matrix X. Each row corresponds to an embedding
of a node in ... | 8,448 |
def test_get_worst_rating_shortterm_with_explicit_rating_provider(
rtg_inputs_shortterm,
):
"""Test computation of best ratings on a security (line-by-line) basis."""
actual = rtg.get_worst_ratings(
rtg_inputs_shortterm,
rating_provider_input=["SP", "Moody", "Fitch"],
tenor="short-te... | 8,449 |
def _parse_assoc(lexer: shlex.shlex) -> AssociativeArray:
"""Parse an associative Bash array."""
assert lexer.get_token() == "("
result = {}
while True:
token = lexer.get_token()
assert token != lexer.eof
if token == ")":
break
assert token == "["
k... | 8,450 |
def test_html_whitelist_caption():
"""The caption element represents the title of its parent table."""
check_html_output_contains_text("""
<p>The caption provides context to the table.</p>
<table>
<caption>
Table 1. This shows the possible results of flipping tw... | 8,451 |
def get_addon_by_name(addon_short_name):
"""get Addon object from Short Name."""
for addon in osf_settings.ADDONS_AVAILABLE:
if addon.short_name == addon_short_name:
return addon | 8,452 |
def test_setter_factory():
"""Test using a factory setter.
"""
class FactoryTester(DummyParent):
state = False
feat = Feature(setter=conditional('1 if driver.state else 2', True))
driver = FactoryTester()
driver.feat = None
assert driver.d_set_cmd == 2
driver.state = True... | 8,453 |
def _normpdf(x):
"""Probability density function of a univariate standard Gaussian
distribution with zero mean and unit variance.
"""
return 1.0 / np.sqrt(2.0 * np.pi) * np.exp(-(x * x) / 2.0) | 8,454 |
def scalar_mult(x, y):
"""A function that computes the product between complex matrices and scalars,
complex vectors and scalars or two complex scalars.
"""
y = y.to(x)
re = real(x) * real(y) - imag(x) * imag(y)
im = real(x) * imag(y) + imag(x) * real(y)
return to_complex(re, im) | 8,455 |
def train_trajectory_encoder(trajectories):
"""
Train a fixed neural-network encoder that maps variable-length
trajectories (of states) into fixed length vectors, trained to reconstruct
said trajectories.
Returns TrajectoryEncoder.
Parameters:
trajectories (List of np.ndarray): A list o... | 8,456 |
def flatten_list(x):
"""Flatten a nested list.
Parameters
----------
x : list
nested list of lists to flatten
Returns
-------
x : list
flattened input
"""
if isinstance(x, list):
return [a for i in x for a in flatten_list(i)]
else:
return [x] | 8,457 |
def check_vpg_statuses(url, session, verify):
"""
Return a list of VPGs which meet the SLA and a list of those which don't
"""
good, bad = [], []
for vpg in get_api(url, session, "vpgs", verify):
name = vpg['VpgName']
status = vpg_statuses(vpg['Status'])
if status == vpg_s... | 8,458 |
def get_hits(adj_matrix, EPSILON = 0.001):
"""[summary]
hubs & authorities calculation
Arguments:
adj_matrix {float[][]} -- [input Adjacent matrix lists like [[1, 0], [0, 1]]
Keyword Arguments
EPSILON {float} -- [factor of change comparision] (default: {0.001})
Returns:
... | 8,459 |
def quicksort(seq):
"""
seq is a list of unsorted numbers
return a sorted list of numbers
"""
##stop condition:
if len(seq) <= 1:
return seq
##get the next nodes and process the current node --> call the partition
else:
low, pivot, high = partition(seq)
## s... | 8,460 |
def scan_resource(
location_rid,
scanners,
timeout=DEFAULT_TIMEOUT,
with_timing=False,
with_threading=True,
):
"""
Return a tuple of:
(location, rid, scan_errors, scan_time, scan_results, timings)
by running the `scanners` Scanner objects for the file or directory resource
wi... | 8,461 |
def insert_dummy():
"""
This function fills a existing database with dummy data that is red from dummyData.sql
"""
cnx = get_db()
#cnx = mysql.connector.connect(user='tom', password='jerry',
# host='127.0.0.1',
# database=DB_NAME)
cursor = cnx.cursor()
... | 8,462 |
def label_generator(df_well, df_tops, column_depth, label_name):
"""
Generate Formation (or other) Labels to Well Dataframe
(useful for machine learning and EDA purpose)
Input:
df_well is your well dataframe (that originally doesn't have the intended label)
df_tops is your label dataframe (this dataframe ... | 8,463 |
def tclexec(tcl_code):
"""Run tcl code"""
g[TCL][REQUEST] = tcl_code
g[TCL][RESULT] = tkeval(tcl_code)
return g[TCL][RESULT] | 8,464 |
def cleanFiles(direct, CWD=os.getcwd()):
"""
removes the year and trailing white space, if there is a year
direct holds the file name for the file of the contents of the directory
@return list of the cleaned data
"""
SUBDIR = CWD + "output/" # change directory to ouput folder
contents = os.... | 8,465 |
def test_labels(test_project_data):
"""A list of labels that correspond to SEED_LABELS."""
labels = []
for label in SEED_LABELS:
labels.append(Label.objects.create(name=label, project=test_project_data))
return labels | 8,466 |
def unravel_index_2d(indices, dims):
"""Unravel index, for 2D inputs only.
See Numpy's unravel.
Args:
indices: <int32> [num_elements], coordinates into 2D row-major tensor.
dims: (N, M), dimensions of the 2D tensor.
Returns:
coordinates: <int32> [2, num_elements], row (1st) and column (2nd) indic... | 8,467 |
def np_xcycwh_to_xy_min_xy_max(bbox: np.array) -> np.array:
"""
Convert bbox from shape [xc, yc, w, h] to [xmin, ymin, xmax, ymax]
Args:
bbox A (tf.Tensor) list a bbox (n, 4) with n the number of bbox to convert
Returns:
The converted bbox
"""
# convert the bbox from [xc, yc, w, ... | 8,468 |
def wmedian(spec, wt, cfwidth=100):
""" Performs a weighted median filtering of a 1d spectrum
Operates using a cumulative sum curve
Parameters
----------
spec : numpy.ndarray
Input 1d spectrum to be filtered
wt : numpy.ndarray
A spectrum of equal length as the input array to p... | 8,469 |
def execute_command(cmd, logfile):
"""
Function to execute a non-interactive command and
return the output of the command if there is some
"""
try:
rows, columns = subprocess.check_output(["stty", "size"]).decode().split()
child = pexpect.spawn(
"/bin/bash",
[... | 8,470 |
def _read(filename, format=None, **kwargs):
"""
Reads a single event file into a ObsPy Catalog object.
"""
catalog, format = _read_from_plugin('event', filename, format=format,
**kwargs)
for event in catalog:
event._format = format
return catalog | 8,471 |
def compute_encrypted_key_powers(s, k):
"""
Compute the powers of the custody key s, encrypted using Paillier. The validator
(outsourcer) gives these to the provider so they can compute the proof of custody
for them.
"""
spower = 1
enc_spowers = []
for i in range(k + 2):
enc_spow... | 8,472 |
def idiosyncratic_var_vector(returns, idiosyncratic_var_matrix):
"""
Get the idiosyncratic variance vector
Parameters
----------
returns : DataFrame
Returns for each ticker and date
idiosyncratic_var_matrix : DataFrame
Idiosyncratic variance matrix
Returns
-------
i... | 8,473 |
def get_ticker_quote_type(ticker: str) -> str:
"""Returns the quote type of ticker symbol
Parameters
----------
ticker : str
ticker symbol of organization
Returns
-------
str
quote type of ticker
"""
yf_ticker = yf.Ticker(ticker)
info = yf_ticker.info
return... | 8,474 |
def sensitivity_score(y_true, y_pred):
"""
Compute classification sensitivity score
Classification sensitivity (also named true positive rate or recall) measures
the proportion of actual positives (class 1) that are correctly identified as
positives. It is defined as follows:
... | 8,475 |
def report_tacacs_failure(username: str, existing_fail_count: int, existing_fail_times: list, redis: Redis) -> None:
"""
Given a failure count and list of timestamps, increment them and stash the results in Redis
:param username: Who dun goofed?
:param existing_fail_count: How many failures were in the ... | 8,476 |
def wrap_compute_softmax(topi_compute):
"""Wrap softmax topi compute"""
def _compute_softmax(attrs, inputs, out_type):
axis = attrs.get_int("axis")
return [topi_compute(inputs[0], axis)]
return _compute_softmax | 8,477 |
def post(url: str, **kwargs: Any) -> dict:
"""Helper function for performing a POST request."""
return __make_request(requests.post, url, **kwargs) | 8,478 |
def vote92(path):
"""Reports of voting in the 1992 U.S. Presidential election.
Survey data containing self-reports of vote choice in the 1992 U.S.
Presidential election, with numerous covariates, from the 1992 American
National Election Studies.
A data frame with 909 observations on the following 10 variabl... | 8,479 |
def root_title(inst, attr, value):
"""
Require a title for the defined API.
"""
if not value:
msg = "RAML File does not define an API title."
raise InvalidRootNodeError(msg) | 8,480 |
def csr_full_col_slices(arr_data,arr_indices,arr_indptr,indptr,row):
"""
This algorithm is used for when all column dimensions are full slices with a step of one.
It might be worth it to make two passes over the array and use static arrays instead of lists.
"""
indices = []
data = []
... | 8,481 |
def slide_period(scraping_period, vacancies):
"""Move upper period boundary to the value equal to the timestamp of the
last found vacancy."""
if not vacancies: # for cases when key 'total' = 0
return None
period_start, period_end = scraping_period
log(f'Change upper date {strtime_from_unixt... | 8,482 |
def merge_to_many(gt_data, oba_data, tolerance):
"""
Merge gt_data dataframe and oba_data dataframe using the nearest value between columns 'gt_data.GT_DateTimeOrigUTC' and
'oba_data.Activity Start Date and Time* (UTC)'. Before merging, the data is grouped by 'GT_Collector' on gt_data and
each row on gt... | 8,483 |
def returnDevPage():
"""
Return page for the development input.
:return: rendered dev.html web page
"""
return render_template("dev.html") | 8,484 |
def main():
"""Setup.py entry point."""
setuptools.setup(
name='ucs_detect',
version='0.0.4',
description=(
"Detects the Unicode Version of an interactive terminal for export"),
long_description=codecs.open(
_get_here('README.rst'), 'rb', 'utf8').read(),
... | 8,485 |
def toeplitz(c, r=None):
"""Construct a Toeplitz matrix.
The Toeplitz matrix has constant diagonals, with ``c`` as its first column
and ``r`` as its first row. If ``r`` is not given, ``r == conjugate(c)`` is
assumed.
Args:
c (cupy.ndarray): First column of the matrix. Whatever the actual s... | 8,486 |
def get_humbug_integrations(args: argparse.Namespace) -> None:
"""
Get list of Humbug integrations.
"""
session = SessionLocal()
try:
query = session.query(HumbugEvent)
if args.id is not None:
query = query.filter(HumbugEvent.id == args.id)
if args.group is not No... | 8,487 |
def download_and_unzip(url, zip_path, csv_path, data_folder):
"""Downloads and unzips an online csv file.
Args:
url: Web address
zip_path: Path to download zip file
csv_path: Expected path to csv file
data_folder: Folder in which data is stored.
"""
download_from_url(url... | 8,488 |
def generate_config(config_fp, **kwargs):
"""
Creates a config file.
:param config_fp: Filepath to the config
:param \*\*kwargs: Source for the config data
"""
_local = {}
for k, v in kwargs.items():
_local[k] = v
with open(config_fp, 'w') as c:
... | 8,489 |
def download_private_id_set_from_gcp(public_storage_bucket, storage_base_path):
"""Downloads private ID set file from cloud storage.
Args:
public_storage_bucket (google.cloud.storage.bucket.Bucket): google storage bucket where private_id_set.json
is stored.
storage_base_path (str): The ... | 8,490 |
def get_inflows_from_parent_model(parent_reach_data, inset_reach_data,
mf2005_parent_sfr_outputfile, mf6_parent_sfr_budget_file,
inset_grid, active_area=None):
"""Get places in an inset model SFR network where the parent SFR network crosses
the... | 8,491 |
def test_load_simulated(test_file):
"""Test joining simulation info onto telescope events"""
from ctapipe.io.tableloader import TableLoader
_, dl1_file = test_file
with TableLoader(dl1_file, load_simulated=True) as table_loader:
table = table_loader.read_subarray_events()
assert "true_... | 8,492 |
def matmul_op_select(x1_shape, x2_shape, transpose_x1, transpose_x2):
"""select matmul op"""
x1_dim, x2_dim = len(x1_shape), len(x2_shape)
if x1_dim == 1 and x2_dim == 1:
matmul_op = P.Mul()
elif x1_dim <= 2 and x2_dim <= 2:
transpose_x1 = False if x1_dim == 1 else transpose_x1
t... | 8,493 |
def test_set_proxy_windows():
"""
Test to make sure that we correctly set the proxy info on Windows
"""
calls = [
call(
hive="HKEY_CURRENT_USER",
key="SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Internet Settings",
vname="ProxyServer",
vdata=(
... | 8,494 |
def Align4(i):
"""Round up to the nearest multiple of 4. See unit tests."""
return ((i-1) | 3) + 1 | 8,495 |
def poggendorff_parameters(illusion_strength=0, difference=0):
"""Compute Parameters for Poggendorff Illusion.
Parameters
----------
illusion_strength : float
The strength of the line tilt in biasing the perception of an uncontinuous single line.
Specifically, the orientation of the lin... | 8,496 |
def download_blobs(blobs: List[storage.Blob]) -> List[Tuple[str, str]]:
"""Download blobs from bucket."""
files_list = []
for blob in blobs:
tmp_file_name = "-".join(blob.name.split("/")[1:])
file_name = blob.name.split("/")[-1]
tmp_file_path = f"/tmp/{tmp_file_name}"
blob.d... | 8,497 |
def _test_kron_col_single_matrix(n, k, m):
"""Do one matrix test of utils.kron_col()."""
X = np.random.random((n,k))
Y = np.random.random((m,k))
XY = roi.utils.kron_col(X, Y)
assert XY.ndim == 2
assert XY.shape[0] == X.shape[0] * Y.shape[0]
assert XY.shape[1] == X.shape[1]
for i in range... | 8,498 |
def testMarkov2(X, ns, alpha, verbose=True):
"""Test second-order Markovianity of symbolic sequence X with ns symbols.
Null hypothesis:
first-order MC <=>
p(X[t+1] | X[t], X[t-1]) = p(X[t+1] | X[t], X[t-1], X[t-2])
cf. Kullback, Technometrics (1962), Table 10.2.
Args:
x: symbolic sequen... | 8,499 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.