content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def GSSO(
directed = False, preprocess = "auto", load_nodes = True, load_node_types = True,
load_edge_weights = True, auto_enable_tradeoffs = True,
sort_tmp_dir = None, verbose = 2, cache = True, cache_path = None,
cache_sys_var = "GRAPH_CACHE_DIR", version = "2.0.5", **kwargs
) -> Graph:
"""Return ... | ac5722afae3bb28321aa9d465873b12852b1f2f6 | 28,600 |
from typing import Optional
from typing import Union
from typing import Sequence
from typing import Dict
def tb(
data: pd.DataFrame,
columns: Optional[Union[Sequence[str], pd.Index]] = None,
subscales: Optional[Dict[str, Sequence[int]]] = None,
) -> pd.DataFrame:
"""Compute the **Technology Commitment... | ac92f6ed7dd484e076b80db32fff6bc9fdd64619 | 28,601 |
def format_date(date: str):
"""
This function formats dates that are in MM-DD-YYYY format,
and will convert to YYYY-MM-DD, which is required sqlite.
:param date: The date to modify.
:return: The modified string.
"""
tmp = date.split("/")
return "{}-{}-{}".format(tmp[2], tmp[0], tmp[1]) | f1a0149bfd96db557c49becdedb84789daa1168c | 28,602 |
def _doUpgradeApply(sUpgradeDir, asMembers):
"""
# Apply the directories and files from the upgrade.
returns True/False/Exception.
"""
#
# Create directories first since that's least intrusive.
#
for sMember in asMembers:
if sMember[-1] == '/':
sMember = sMember[len(... | a181e710db010733828099a881ee7239f90674a7 | 28,603 |
def _parse_atat_lattice(lattice_in):
"""Parse an ATAT-style `lat.in` string.
The parsed string will be in three groups: (Coordinate system) (lattice) (atoms)
where the atom group is split up into subgroups, each describing the position and atom name
"""
float_number = Regex(r'[-+]?[0-9]*\.?[0-9]+([... | 4cb40f7c25519bc300e389d0a2d72383dda3c7f0 | 28,604 |
from typing import Union
def datetime_attribute_timeseries(time_index: Union[pd.DatetimeIndex, TimeSeries],
attribute: str,
one_hot: bool = False) -> TimeSeries:
"""
Returns a new TimeSeries with index `time_index` and one or more dimensions ... | 9330f22d7b81aaeb57130563a3f32009e48e3fe0 | 28,605 |
def hexscale_from_cmap(cmap, N):
"""
Evaluate a colormap at N points.
Parameters
----------
cmap : function
a function taking a scalar value between 0 and 1 and giving a color as
rgb(a) with values between 0 and 1. These are for example the pyplot
colormaps, like plt.cm.viri... | 0c26f7b404ac3643317db81eacac83d0d62e5f80 | 28,606 |
def getFirebaseData(userID):
"""
This gets the data from the Firebase database and converts it to a readable dictionary
Args:
userID (string): the id of the user
"""
cred = credentials.Certificate("serviceAccountKey.json")
a = firebase_admin.initialize_app(cred)
ourDatabase = f... | 4da109004771908009ed431ad69a25ac52d0969c | 28,607 |
def gen_tracer(code, f_globals):
""" Generate a trace function from a code object.
Parameters
----------
code : CodeType
The code object created by the Enaml compiler.
f_globals : dict
The global scope for the returned function.
Returns
-------
result : FunctionType
... | abb9e043ad12f4ced014883b6aee230095b63a18 | 28,608 |
def MAD(AnalogSignal):
""" median absolute deviation of an AnalogSignal """
X = AnalogSignal.magnitude
mad = sp.median(sp.absolute(X - sp.median(X))) * AnalogSignal.units
return mad | 069231a87e755de4bff6541560c0e5beabc91e0d | 28,609 |
def angular_frequency(vacuum_wavelength):
"""Angular frequency :math:`\omega = 2\pi c / \lambda`
Args:
vacuum_wavelength (float): Vacuum wavelength in length unit
Returns:
Angular frequency in the units of c=1 (time units=length units). This is at the same time the vacuum wavenumber.
"... | 305349cff0d7b9489d92eb301c6d058ca11467f0 | 28,610 |
def web_urls():
"""Builds and returns the web_urls for web.py.
"""
urls = (
'/export/?', RestHandler,
'/export/bdbag/?', ExportBag,
'/export/bdbag/([^/]+)', ExportRetrieve,
'/export/bdbag/([^/]+)/(.+)', ExportRetrieve,
'/export/file/?', ExportFiles,
'/export/f... | d2580499a7b4bad8c94494fd103a2fe0f6d607d6 | 28,611 |
import torch
def box_cxcywh_norm_to_cxcywh(box: TensorOrArray, height: int, width: int) -> TensorOrArray:
"""Converts bounding boxes from (cx, cy, w, h) norm format to (cx, cy, w, h)
format.
(cx, cy) refers to center of bounding box.
(a, r) refers to area (width * height) and aspect ratio (width ... | 7cf112b7f3420161513e4b70ef531fb586074431 | 28,612 |
def lyrics_from_url(url):
"""Return a tuple with song's name, author and lyrics."""
source = identify_url(url)
extractor = {
'letras': (lyrics_from_letrasmus, info_from_letrasmus),
'vagalume': (lyrics_from_vagalume, info_from_vagalume)
}
html = html_from_url(url)
if source in ex... | 2034c1ee26ce563f227f49de10b7e1b56092c7c8 | 28,613 |
import json
def _get_pycons():
"""Helper function that retrieves required PyCon data
and returns a list of PyCon objects
"""
with open(pycons_file, "r", encoding="utf-8") as f:
return [
PyCon(
pycon["name"],
pycon["city"],
pycon["c... | 749947829d4c28b08f957505d8ede02fe8d5ecbb | 28,614 |
def f_function(chromosome):
"""Define Fitness Function Here."""
x = chromosome.convert_to_integer()
return (15 * x[0]) - (x[0] * x[0])
# return (((15 * x[0]) - (x[0] * x[0])) * -1) + 1000 To Find Minimum Solution | aee3744c63ada24302857ef4ddb4e6aff35fc69e | 28,615 |
def _GetRevsAroundRev(data_series, revision):
"""Gets a list of revisions from before to after a given revision.
Args:
data_series: A list of (revision, value).
revision: A revision number.
Returns:
A list of revisions.
"""
if not _MAX_SEGMENT_SIZE_AROUND_ANOMALY:
return [revision]
middle... | 966e590f4cc1e017ed6d4588ca15655b9de61d7a | 28,616 |
def get_output_length():
"""Returns the length of the convnet output."""
return conv_base.layers[-1].output_shape[-1] | 6471f0b1331a97147be43b464c5fb5384e185980 | 28,617 |
def rules(command, working_directory=None, root=True, **kargs):
"""
Main entry point for build_rules.py.
When ``makeprojects``, ``cleanme``, or ``buildme`` is executed, they will
call this function to perform the actions required for build customization.
The parameter ``working_directory`` is requ... | 9456822c0956fa847e19917b735d1a6680d0961a | 28,618 |
def get_py_func_body(line_numbers, file_name, annot):
""" Function to get method/function body from files
@parameters
filename: Path to the file
line_num: function/method line number
annot: Annotation condition (Ex: @Test)
@return
This function returns python function... | c6324e13831008118a39a599cce8b9ec3513b0a1 | 28,619 |
from typing import Any
from typing import Union
def extract_optional_annotation(annotation: Any) -> Any:
"""
Determine if the given annotation is an Optional field
"""
if (
hasattr(annotation, "__origin__")
and annotation.__origin__ is Union
and getattr(annotation, "__args__", ... | 024e28f88005b03e45b96c739a44bd56b2115849 | 28,620 |
import itertools
import json
def combine_pred_and_truth(prediction, truth_file):
"""
Combine the predicted labels and the ground truth labels for testing purposes.
:param prediction: The prediction labels.
:param truth_file: The ground truth file.
:return: The combined prediction and ground truth... | d7dee4add59a4b3df7e0bd3a6e5fcc981ff23d59 | 28,621 |
def calc_cogs_time_series(days, cogs_annual):
"""
Cost of Goods Sold Formula
Notes
-----
Can adjust for days/weekly/monthly/annually in the future - ASSUMED: CONSUMABLES PURCHASED MONTHLY
"""
cogs_time_series = []
for i in range(days):
if i % DAYS_IN_MONTH == ... | b3efffc274676549f23f7a20321dd2aac02c1666 | 28,622 |
import os
def make_regridder_L2L(
llres_in, llres_out, weightsdir='.', reuse_weights=False,
in_extent=[-180, 180, -90, 90],
out_extent=[-180, 180, -90, 90]):
"""
Create an xESMF regridder between two lat/lon grids
Args:
llres_in: str
Resolution of input grid in... | 164efa1493845e004d67f86f6e364ec77bcc1409 | 28,623 |
def stations():
""" Returning the all Stations """
station_list = session.query(station.name).all()
jsonify_sation = list(np.ravel(station_list))
#Jsonify results
return jsonify(jsonify_sation) | ce51f8551043d740657da7fc7d3f3d9afcead4d1 | 28,624 |
def test_run_sht_rudeadyet_default(tmpdir) -> int:
"""
Purpose:
Test to make sure sht-rudeadyet run works
Args:
N/A
Returns:
(Int): 0 if passed run, -1 if not
"""
attack = "sht_rudeadyet"
run_config = "configs/mw_locust-sht_rudeadyet.json"
return magicwand_run(tmp... | 072a8608dc5ac8007e62e8babbd3047fbb8b8bce | 28,625 |
def _clean_markdown_cells(ntbk):
"""Clean up cell text of an nbformat NotebookNode."""
# Remove '#' from the end of markdown headers
for cell in ntbk.cells:
if cell.cell_type == "markdown":
cell_lines = cell.source.split('\n')
for ii, line in enumerate(cell_lines):
... | 8b34ff6713a323340ea27f6d8f498a215ca9d98a | 28,626 |
import asyncio
def get_thread_wrapper(target, name):
"""Returns a target thread that prints unexpected exceptions to the logging.
Args:
target: Func or coroutine to wrap.
name(str): Task name.
"""
@wraps(target)
def wrapper(*args, **kwargs):
try:
result = targ... | 75ddf5ca81825769e51fd8ed4f850ec9db18a31e | 28,627 |
from sys import path
def scale_pairs(arr, scalgo="deseq"):
"""Scales observed paired columns of read-overlap counts.
- arr(``path``) input array regions x (markX in A, markX in B, markY in A, markY in B ...)
- scalgo(``str``) scaling algorithm
"""
chk_exit(*inp_file(path(arr)))
with open(... | 99c6805d7c5b7fe171452a61a5013b9a5538b4de | 28,628 |
def getStructType(ea):
"""
Get type information from an ea. Used to get the structure type id
"""
flags = idaapi.getFlags(ea)
ti = idaapi.opinfo_t()
oi = idaapi.get_opinfo(ea, 0, flags, ti)
if oi is not None:
return ti
else:
return None | 3ed8a000405f87b0e069d165dd72215852d22bd5 | 28,629 |
def confirm_email(token):
"""
GET endpoint that confirms the new officer user. This endpoint link is normally within
the confirmation email.
"""
club_email = flask_exts.email_verifier.confirm_token(token, 'confirm-email')
if club_email is None:
raise JsonError(status='error', reason='Th... | 2e8feb0607361ec0d53b3b62766a83f131ae75c6 | 28,630 |
def xcrun_field_value_from_output(field: str, output: str) -> str:
"""
Get value of a given field from xcrun output.
If field is not found empty string is returned.
"""
field_prefix = field + ': '
for line in output.splitlines():
line = line.strip()
if line.startswith(field_pre... | a99efe76e21239f6ba15b8e7fb12d04d57bfb4de | 28,631 |
def get_all_markets_num():
"""
获取交易所有的市场
:return: "5/2"
"""
markets = list(set([str(i["stockId"]) + "/" + str(i["moneyId"]) for i in res["result"]]))
return markets | 33d9e49aeaa6e6d81ec199f21d4f5e40cdd0fd48 | 28,632 |
def mae(s, o):
"""
Mean Absolute Error
input:
s: simulated
o: observed
output:
maes: mean absolute error
"""
s, o = filter_nan(s, o)
return np.mean(abs(s - o)) | 313d4605bb240d8f32bc13fc62ff2cf12e22cfd8 | 28,633 |
def error_mult_gap_qa_atom(
df_qc, df_qats, target_label, target_charge=0,
basis_set='aug-cc-pV5Z', use_ts=True,
max_qats_order=4, ignore_one_row=False,
considered_lambdas=None, return_qats_vs_qa=False):
"""Computes QATS errors in system multiplicity gaps.
Parameters
----------
df_qc : ... | 3facdc35f0994eb21a74cf0b1fb277db2a70a14b | 28,634 |
def frequency_weighting(frequencies, kind="A", **kw):
"""Compute the weighting of a set of frequencies.
Parameters
----------
frequencies : scalar or np.ndarray [shape=(n,)]
One or more frequencies (in Hz)
kind : str in
The weighting kind. e.g. `'A'`, `'B'`, `'C'`, `'D'`, `'Z'`
... | aa93e01ce17b4f3c15ad8ab95ca358e5b4500b37 | 28,635 |
async def materialize_classpath(request: MaterializedClasspathRequest) -> MaterializedClasspath:
"""Resolve, fetch, and merge various classpath types to a single `Digest` and metadata."""
artifact_requirements_lockfiles = await MultiGet(
Get(CoursierResolvedLockfile, ArtifactRequirements, artifact_requ... | 367a0a49acfb16e3d7c0c0f1034ef946e75928a8 | 28,636 |
def Real_Entropy(timeseries):
""" Calculates an approximation of the time-correlated entropy
Input:
timeseries: list of strings or numbers,
e.g. ['1', '2', '3'] or [1, 2, 3]
Output:
approximation of Real Entropy (time-correlated entropy), e.g. 1.09
"""
def is_sublist(ali... | a2d8948723b0f62e91a9255b3f0fb35ccf4b26d8 | 28,637 |
def hom(X, mode):
"""
It converts transformation X (translation, rotation or rigid motion)
to homogenous form.
Input:
X: tf.float32 array, which can be either
[B, 3] float32, 3D translation vectors
[B, 3, 3] float32, rotation matrices
[B, 3, 4] float32, rigid motion matrix
mode: one of 'T', 'R' or 'P' deno... | e7104789e996b745a8978867925b8ea5e2c1ad01 | 28,638 |
import re
def parse_sl(comments: str):
"""Parses comments for SL on an order"""
parsed = None
sl_at = "(SL\s{0,1}@\s{0,1})"
sl_price = "([0-9]{0,3}\.[0-9]{1,2}((?!\S)|(?=[)])))"
pattern = sl_at + sl_price
match = re.search(pattern, comments)
if match:
match.groups()
parsed ... | d993fc1686fa2623423269812c834aedb0d504e2 | 28,639 |
def nhpp_thinning(rate_fn, tmax, delta, lbound=None):
"""Nonhomogeneous Poisson process with intensity function `rate_fn` for
time range (0, tmax) using the algorithm by Lewis and Shelder 1978.
rate_fn: a function `f(t)` of one variable `t` that returns a finite non negative
value for `t` in trang... | 7761ec918ca1098c17dd997426841e04b93186c2 | 28,640 |
import traceback
import json
def execute_rule_engine(rule_name, body):
"""
:param rule_name:
:param body:
:return:
"""
__logger.info("inside execute_rule_engine for " + rule_name)
__logger.info(json.dumps(body, indent=4, sort_keys=True, default=str))
try:
result = rule_engine... | b413ec4723d1c030e798e21c670ee607a4f4d373 | 28,641 |
import subprocess
def get_tags():
"""
Updates tags, then returns a list of all tags.
"""
print("Pulling latest tags...")
subprocess.run(["git", "fetch", "--tags"], cwd=CPY_DIR, check=True)
result = subprocess.run(
["git", "tag"], cwd=CPY_DIR, check=True, text=True, capture_output=True
... | 62691146c4e6897e98e81d8f2453b073438ef200 | 28,642 |
def get():
"""
Create and return an instance of the FileSelectionContext
subclass which is appropriate to the currently active application.
"""
windowClass = ContextUtils.getForegroundClassNameUnicode()
if windowClass == u"ConsoleWindowClass":
fsContext = NullFileSelectionContext()... | 14e6e94b55801e9b2eb9c8c2738ca6cb8510939a | 28,643 |
def calc_accuracy(y_true, y_predict, display=True):
"""Analysis the score with sklearn.metrics.
This module includes score functions, performance metrics
and pairwise metrics and distance computations.
Parameters
==========
y_true: numpy.array
y_predict: numpy.array
display: Boolea... | e71cc9773dc593ea6456f28f96c90410e6043fe0 | 28,644 |
def HSV_to_HSL(hsv):
"""Converts HSV color space to HSL"""
rgb = HSV_to_RGB(hsv)
return RGB_to_HSL(rgb) | dc847755135f0d96f5b8980154b9ade496c1753f | 28,645 |
def prosodic_meter_query(
collection,
):
"""
Function for returning all Prosodic Meters that contain the queried collection of
:obj:`fragment.GreekFoot` objects.
:param collection: an iterable collection of :obj:`fragment.GreekFoot` objects.
"""
all_prosodic_meters = get_all_prosodic_meters()
res = []
for m... | ec55bc910c246051504f4a66fa12dc10211725d5 | 28,646 |
def get_model(loss=keras.losses.MeanSquaredError(), optimizer=keras.optimizers.Adam(), metrics=[keras.metrics.MeanSquaredError()]):
"""
Loads and compiles the model
"""
model = unet3D_model()
model.compile(loss=loss, optimizer=optimizer, metrics=[metrics])
return model | 0a30796893b2d20885fc5496385317c9fc4f2d08 | 28,647 |
def mps_kph(m_per_s):
"""Convert speed from m/s to km/hr.
:kbd:`m_per_s` may be either a scalar number or a
:py:class:`numpy.ndarray` object,
and the return value will be of the same type.
:arg m_per_s: Speed in m/s to convert.
:returns: Speed in km/hr.
"""
return m_per_s * M_PER_S__K... | a0cb03d04edcb21bb6820918c262c8a3d6e9afc3 | 28,648 |
import torch
def evaluate(model: nn.Module, loss_func: nn.Module, loader: iter, logger: Logger, device: str = None):
""" Evaluate the parameters of the model by computing the loss on the data. """
if device is None:
device = next(model.parameters()).device
model.eval()
y_hats, y_s = [], []
... | 7c7d769dde86771e052703ecd312f4ee62235419 | 28,649 |
def glm_likelihood_bernoulli(parms, X, Y, lamb=1, l_p=1, neg=True, log=True):
"""The likelihood for a logistic regression or bernoulli model with a penalty
term (can accept any norm, default is 1 for L1).
Parameters
----------
parms : numpy array (numeric)
The coefficients (including in... | e125d7284045036d412b5afa76730103369142a4 | 28,650 |
import json
def to_tvm(graph, shape_dict, layout, mode='tensorflow'):
"""convert frontend graph to nnvm graph"""
assert mode in FRAME_SUPPORTED
if mode == 'tensorflow':
mod, params = tvm.relay.frontend.from_tensorflow(graph, layout=layout, shape=shape_dict)
elif mode == 'keras':
mod, p... | 861184aafd6e2d428e08acc8f718a5ef30152d27 | 28,651 |
def getAxes():
""" Get each of the axes over which the data is measured. """
df = load_file("atyeo_covid")
df = df.filter(regex='SampleID|Ig|Fc|SNA|RCA', axis=1)
axes = df.filter(regex='Ig|Fc|SNA|RCA', axis=1)
axes = axes.columns.str.split(" ", expand = True)
subject = df['SampleID']
subje... | d489f1c261a8a92b44563b6842a30cc2c7a880c5 | 28,652 |
import scipy
def stretching_current(ref, cur, dvmin, dvmax, nbtrial, window,t_vec):
"""
Function to perform the stretching of the waveforms:
This function compares the Reference waveform to stretched/compressed current waveforms to get the relative seismic velocity variation (and associated error).
I... | 9442a940e9013c8ef77bb2c2ecc774c4276a99c5 | 28,653 |
def convert_to_int(var):
"""
Tries to convert an number to int.
:param var
:returns the value of the int or None if it fails
"""
try:
return int(var)
except ValueError:
return None | 19ba35d351096f2c7b29d78b8df692fc63a75a6f | 28,654 |
def eval_input_fn(filepath, example_parser, batch_size):
"""
模型的eval阶段input_fn
Args:
filepath (str): 训练集/验证集的路径
example_parser (function): 解析example的函数
batch_size (int): 每个batch样本大小
Returns:
dataset
"""
dataset = tf.data.TFRecordDataset(filepath)
dataset... | 1a67adfe1decd8b38fe8a8d973b7caf1fb6ec85a | 28,655 |
def ring_forming_scission_ts_zmatrix(rxn, ts_geo):
""" z-matrix for a ring-forming scission transition state geometry
:param rxn: a Reaction object
:param ts_geo: a transition state geometry
"""
rxn = rxn.copy()
# 1. Get keys to linear or near-linear atoms
lin_idxs = list(automol.geom.line... | 0d9f09210a533a56b64dd3ba559b5f645381c7b7 | 28,656 |
def trip(u, v):
"""
Returns the scalar triple product of vectors u and v and z axis.
The convention is z dot (u cross v). Dotting with the z axis simplifies
it to the z component of the u cross v
The product is:
positive if v is to the left of u, that is,
the shortest right hand ro... | 5f687ee4b16dc6c1b350ed574cb632a7c9ca996b | 28,657 |
def one_cpc(request, hmc_session): # noqa: F811
"""
Fixture representing a single, arbitrary CPC managed by the HMC.
Returns a `zhmcclient.Cpc` object, with full properties.
"""
client = zhmcclient.Client(hmc_session)
cpcs = client.cpcs.list()
assert len(cpcs) >= 1
cpc = cpcs[0]
cp... | 18a42e9777881bbab5f54cbeebefb1bf487d0994 | 28,658 |
import time
def yield_with_display(future_or_iterable, every, timeout=None):
""" Yields for a future and display status every x seconds
:param future_or_iterable: A future to yield on, or a list of futures
:param every: The number of seconds between updates
:param timeout: The total number... | 07501c913eaf4a4c497ad0c0c3facc87b946e1f5 | 28,659 |
def query(cmd, db, cgi='http://www.ncbi.nlm.nih.gov/sites/entrez',
**keywds):
"""query(cmd, db, cgi='http://www.ncbi.nlm.nih.gov/sites/entrez',
**keywds) -> handle
Query Entrez and return a handle to the results, consisting of
a web page in HTML format.
See the online documentation for an... | 1287e3551eae2be337abeba31ce7888d60938111 | 28,660 |
def Q2B(uchar):
"""单个字符 全角转半角"""
inside_code = ord(uchar)
if inside_code == 0x3000:
inside_code = 0x0020
else:
inside_code -= 0xfee0
if inside_code < 0x0020 or inside_code > 0x7e: # 转完之后不是半角字符返回原来的字符
return uchar
return chr(inside_code) | fa58980c7eb251fa7278caa7bbf6645ad492ed2b | 28,661 |
from datetime import datetime
def parsedate(date, formats=None, bias=None):
"""parse a localized date/time and return a (unixtime, offset) tuple.
The date may be a "unixtime offset" string or in one of the specified
formats. If the date already is a (unixtime, offset) tuple, it is returned.
>>> pars... | 512608fb413fa062a4dff00557fbd95120c5441c | 28,662 |
import glob
def prepare_lv2_data(change_price=False):
"""
read lv1 data and ensemble to make submission
"""
train_files = glob('./models/level1_model_files/train/*')
test_files = glob('./models/level1_model_files/test/*')
num_feat = len(train_files)
nrow = pd.read_csv(train_files[0]).shape... | a10786bf92dccba9cccf7d04c3301b77e008c584 | 28,663 |
def main(global_config, **settings):
""" This function returns a Pyramid WSGI application.
"""
config = Configurator(settings=settings)
config.include('clldmpg')
config.include('clld_glottologfamily_plugin')
config.include('clld_phylogeny_plugin')
config.register_datatable('familys', datatab... | 6d6eaa8b6c3425023e3550ddae1d3455c939c6fd | 28,664 |
import numpy
def dwwc(graph, metapath, damping=0.5, dense_threshold=0, dtype=numpy.float64, dwwc_method=None):
"""
Compute the degree-weighted walk count (DWWC) in which nodes can be
repeated within a path.
Parameters
----------
graph : hetio.hetnet.Graph
metapath : hetio.hetnet.MetaPath
... | aa6d30ed04baf2561e3bac7a992ae9e00b985da8 | 28,665 |
def fba_and_min_enzyme(cobra_model, coefficients_forward, coefficients_reverse):
"""
Performs FBA followed by minimization of enzyme content
"""
with cobra_model as model:
model.optimize()
cobra.util.fix_objective_as_constraint(model)
set_enzymatic_objective(model, coefficients_... | 2e6614be30c7d0f343b9d4206d1e7c34d54436f3 | 28,666 |
def logi_led_shutdown():
""" shutdowns the SDK for the thread. """
if led_dll:
return bool(led_dll.LogiLedShutdown())
else:
return False | fdb7d77b7fb59804458247c32a35e80da44f6c1f | 28,667 |
import os
def is_ci() -> bool:
"""Return whether running in CI environment."""
return os.environ.get("CI", "") != "" | 642b714d55fe52c93849b2775c4e0b4fede9f197 | 28,668 |
from typing import Dict
def get_blank_adjustments_for_strat(transitions: list) -> Dict[str, dict]:
"""
Provide a blank set of flow adjustments to be populated by the update_adjustments_for_strat function below.
Args:
transitions: All the transition flows we will be modifying through the clinical ... | b2e5391280bae48202f92832aa8821d47a288135 | 28,669 |
def get_instance(module, name, config):
"""
Get module indicated in config[name]['type'];
If there are args to specify the module, specify in config[name]['args']
"""
func_args = config[name]['args'] if 'args' in config[name] else None
# if any argument specified in config[name]['args']
if ... | ea57e7097665343199956509bb302e3806fb383a | 28,670 |
def separable_hnn(num_points, input_h_s=None, input_model=None,
save_path='temp_save_path', train=True, epoch_save=100):
"""
Separable Hamiltonian network.
:return:
"""
if input_h_s:
h_s = input_h_s
model = input_model
else:
h_s = HNN1DWaveSeparable(nn.... | c9912f69b4367a2ed83ce367970551f31e0cb087 | 28,671 |
def get_n_largest(n, lst, to_compare=lambda x: x):
"""
This returns largest n elements from list in descending order
"""
largests = [lst[0]]*n # this will be in descending order
for x in lst[1:]:
if to_compare(x) <= to_compare(largests[-1]):
continue
else:
fo... | 4ef85d8656ae152ecab65d3a01bce7f885c47577 | 28,672 |
from natsort import natsorted
import collections
from typing import Optional
from typing import Union
def base_scatter(
x: Optional[Union[np.ndarray, list]],
y: Optional[Union[np.ndarray, list]],
hue: Optional[Union[np.ndarray, list]] = None,
ax=None,
title: str = None,
... | 72e159af3ffad86e66b53789368edbb3a7bc406a | 28,673 |
def lambda_sum_largest_canon(expr, real_args, imag_args, real2imag):
"""Canonicalize nuclear norm with Hermitian matrix input.
"""
# Divide by two because each eigenvalue is repeated twice.
real, imag = hermitian_canon(expr, real_args, imag_args, real2imag)
real.k *= 2
if imag_args[0] is not Non... | 41e2d460fc5d18d65e1d7227093ecaf88a925151 | 28,674 |
def dp_palindrome_length(dp, S, i, j):
"""
Recursive function for finding the length
of the longest palindromic sequence
in a string
This is the algorithm covered in the lecture
It uses memoization to improve performance,
dp "dynamic programming" is a Python dict
containing previously computed values
... | 10a8ac671674ba1ef57cd473413211a339f94e62 | 28,675 |
def ellip_enclose(points, color, inc=1, lw=2, nst=2):
"""
Plot the minimum ellipse around a set of points.
Based on:
https://github.com/joferkington/oost_paper_code/blob/master/error_ellipse.py
"""
def eigsorted(cov):
vals, vecs = np.linalg.eigh(cov)
order = vals.argsort()[::-1... | c6f3fabfb306f29c5c09ffee732d5afea2c1fe33 | 28,676 |
def catalog_dictionary_per_observation(cats, obs_nums, targets, defaults):
"""Translate a dictionary of catalogs from a case of either:
1. Separate catalogs for each target name
2. Separate catalogs for each target name and instrument
into a dictionary of catalogs for each instrument and observation
... | b418e0315b242c251d6796636fdd3fdbcfefbfa5 | 28,677 |
def sierpinkspi(p1, p2, p3, degree, draw, image, colors):
"""
Draw Sierpinksi Triangles.
"""
colour = colors
draw.polygon(((p1[0], p1[1]), (p2[0], p2[1]), (p3[0], p3[1])), fill=colour[degree])
if degree > 0:
sierpinkspi(p1, mid(p1, p2), mid(p1, p3), degree-1, draw, image, colors)
... | c43662d50a655eed4298e34d2f9830e678a0ca96 | 28,678 |
def generate_depth_map(camera, Xw, shape):
"""Render pointcloud on image.
Parameters
----------
camera: Camera
Camera object with appropriately set extrinsics wrt world.
Xw: np.ndarray (N x 3)
3D point cloud (x, y, z) in the world coordinate.
shape: np.ndarray (H, W)
O... | f219d2128bdecf56e8e03aef7d6249b518d55f06 | 28,679 |
def zeros(shape, dtype, allocator=drv.mem_alloc):
"""
Return an array of the given shape and dtype filled with zeros.
Parameters
----------
shape : tuple
Array shape.
dtype : data-type
Data type for the array.
allocator : callable
Returns an object that represents th... | 5d3969e4c3d72cc0699e15e43594ba29657ca68b | 28,680 |
def create_own_child_column(X):
"""
Replaces the column 'relationship' with a binary one called own-child
"""
new_column = X['relationship'] == 'own-child'
X_transformed = X.assign(own_child=new_column)
X_transformed = X_transformed.drop('relationship', axis=1)
return X_transformed | 303ec8f073920f0bba6704740b200c7f3306b7bd | 28,681 |
def find_next_gate(wires, op_list):
"""Given a list of operations, finds the next operation that acts on at least one of
the same set of wires, if present.
Args:
wires (Wires): A set of wires acted on by a quantum operation.
op_list (list[Operation]): A list of operations that are implement... | 287a3b2905f86dff0c75027bcba6bd00bab82fd8 | 28,682 |
def FDilatedConv1d(xC, xP, nnModule):
"""1D DILATED CAUSAL CONVOLUTION"""
convC = nnModule.convC # current
convP = nnModule.convP # previous
output = F.conv1d(xC, convC.weight, convC.bias) + \
F.conv1d(xP, convP.weight, convP.bias)
return output | 900065f6618f1b4c12191b1363ce6706ec28d222 | 28,683 |
def load_spans(file):
"""
Loads the predicted spans
"""
article_id, span_interval = ([], [])
with open(file, 'r', encoding='utf-8') as f:
for line in f.readlines():
art_id, span_begin, span_end = [int(x) for x in line.rstrip().split('\t')]
span_interval.append((span_b... | 8f8de31e1d1df7f0d2a44d8f8db7f846750bd89f | 28,684 |
def is_stupid_header_row(row):
"""returns true if we believe row is what the EPN-TAP people used
as section separators in the columns table.
That is: the text is red:-)
"""
try:
perhaps_p = row.contents[0].contents[0]
perhaps_span = perhaps_p.contents[0]
if perhaps_span.get("style")=='color: rgb(... | 124108520486c020d2da64a8eb6f5d266990ae02 | 28,685 |
def get_cli_parser() -> ArgumentParser:
"""Return an ArgumentParser instance."""
parser = ArgumentParser(description="CLI options for Alice and Bob key share")
parser.add_argument('-p', help='Prime p for information exchange', type=int)
parser.add_argument('-g', help='Prime g for information exchange', ... | 2ca9feff2940064163d8b5724b647ab56f4ea5e6 | 28,686 |
import re
def _get_http_and_https_proxy_ip(creds):
"""
Get the http and https proxy ip.
Args:
creds (dict): Credential information according to the dut inventory
"""
return (re.findall(r'[0-9]+(?:\.[0-9]+){3}', creds.get('proxy_env', {}).get('http_proxy', ''))[0],
re... | b18d89718456830bdb186b3b1e120f4ae7c673c7 | 28,687 |
import os
def multiple_files_multiple_tracks():
"""Returns a path to a CUE file with multiple tracks per source file."""
cue_file = "Non-ISO_extended-ASCII_text_with_CRLF.cue"
return os.path.join("tests", "files", cue_file) | 36659616d2e065a8f8d9b1d7956e2c8326cdc805 | 28,688 |
def geometric_expval(p):
"""
Expected value of geometric distribution.
"""
return 1. / p | 3afb3adb7e9dafa03026f22074dfcc1f81c58ac8 | 28,689 |
def make_ticc_dataset(
clusters=(0, 1, 0), n_dim=3, w_size=5, break_points=None,
n_samples=200, n_dim_lat=0, sparsity_inv_matrix=0.5, T=9,
rand_seed=None, **kwargs):
"""Generate data as the TICC method.
Library implementation of `generate_synthetic_data.py`, original can be
found at... | 7c77d5ea4ff9e87681b0494333c49e24360b7072 | 28,690 |
def tag_tuple(tag):
"""Simple function to decompose a tag for debugging."""
return (tag.tagClass, tag.tagNumber, tag.tagLVT, tag.tagData) | df036529cb4b8bcdbd628d13ee59832df96ef7a5 | 28,691 |
from dustmaps import sfd
from dustmaps import planck
def get_dustmap(sourcemap, useweb=False):
""" get the dustmap (from the dustmaps package) of the given source.
Parameters
---------
sourcemap: [string]
origin of the MW extinction information.
currently implemented: planck, sfd
... | a5daec02601c968d25942afe1577ad301bbb6a55 | 28,692 |
def make_retro_pulse(x, y, z, zenith, azimuth):
"""Retro pulses originate from a DOM with an (x, y, z) coordinate and
(potentially) a zenith and azimuth orientation (though for now the latter
are ignored).
"""
pulse = I3CLSimFlasherPulse()
pulse.type = I3CLSimFlasherPulse.FlasherPulseType.retro... | de6fa8905276122c501b5a80842a12abfa2a81f1 | 28,693 |
def shiftLeft(col, numBits):
"""Shift the given value numBits left.
>>> spark.createDataFrame([(21,)], ['a']).select(shiftLeft('a', 1).alias('r')).collect()
[Row(r=42)]
"""
sc = SparkContext._active_spark_context
return Column(sc._jvm.functions.shiftLeft(_to_java_column(col), numBits)) | 769cbcb4f66473bdeb789c1326aa58e763c4f320 | 28,694 |
def lerp(x0: float, x1: float, p: float) -> float:
"""
Interplates linearly between two values such that when p=0
the interpolated value is x0 and at p=1 it's x1
"""
return (1 - p) * x0 + p * x1 | c4114dcb5636e70b30cd72a6e7ceab1cd683fa8d | 28,695 |
def discard_events(library, session, event_type, mechanism):
"""Discards event occurrences for specified event types and mechanisms in a session.
Corresponds to viDiscardEvents function of the VISA library.
:param library: the visa library wrapped by ctypes.
:param session: Unique logical identifier t... | 72010fae64bb0a1e615ce859d150f7f24f2c7171 | 28,696 |
def getSpeed(spindle=0):
"""Gets the interpreter's speed setting for the specified spindle.
Args:
spindle (int, optional) : The number of the spindle to get the speed
of. If ``spindle`` is not specified spindle 0 is assumed.
Returns:
float: The interpreter speed setting, with a... | a7c759ff91c079aacd77d7aa0141f42aa9ca60af | 28,697 |
def appointment() -> any:
"""
Defines route to appointment booking page.
:return: String of HTML template for appointment booking page or homepage if booking was successful.
"""
if request.method == 'POST':
user_input = request.form.to_dict()
try:
request_is_valid(request... | 5c55c0387300f21cfea45809bdf534ace4137fc6 | 28,698 |
import os
def getfile(basedir, manifest_value, user_argument):
"""Get name for a file that is referenced in a workflow manifest. If the
user argument is given it overrides the respective value in the manifest.
For user arguments we first assume that the path references a file on disk,
either as absolu... | 6ec02bf01ce280843d74bedc731964c6e5f74de4 | 28,699 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.