content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def rotate(img):
"""
Rotation:
OpenCV provides scaled rotation with adjustable rotation center so that you can rotate at any location you prefer.
To find this modified transformation matrix, OpenCV provides a function, cv2.getRotationMatrix2D.
Check below example which rotates the image by 9... | 42,700 |
def main():
"""Main entry point."""
# load xarray dataset from file
ds_spectra = xr.open_dataset("spectra.nc")
# extract the (only) array from the dataset
spectra = ds_spectra["spectra"]
# 3D array 8x8x499, with named dimensions
print(spectra)
fig = plt.figure()
axs = fig.add_subpl... | 42,701 |
def set_parent_folder_full_permissions(
ats_config_data: Dict[str, str], path_chain: str, parent_name: str) -> None:
"""Set parent folder--as well as children and files--permissions for Authenticated Users.
Args:
ats_config_data (Dict[str, str]): A dict of ATS configuration data.
path_c... | 42,702 |
def custom_exception_handler(exc, context):
"""Return JSON 500 error responses."""
response = exception_handler(exc, context)
if response is not None:
response.data['status_code'] = response.status_code
else:
if settings.DEBUG:
detail = str(exc)
else:
det... | 42,703 |
def get_sign(data_dict, key):
"""
签名函数
:param data_dict: 需要签名的参数,格式为字典
:param key: 密钥 ,即上面的API_KEY
:return: 字符串
"""
params_list = sorted(data_dict.items(), key=lambda e: e[0], reverse=False) # 参数字典倒排序为列表
params_str = "&".join(u"{}={}".format(k, v) for k, v in params_list) + '&ke... | 42,704 |
def string():
"""String representation."""
return "{:s}".format('something') | 42,705 |
def do_task_show(gc, args):
"""Describe a specific task."""
task = gc.tasks.get(args.id)
ignore = ['self', 'schema']
task = dict([item for item in task.items() if item[0] not in ignore])
utils.print_dict(task) | 42,706 |
def test_synthetic_dark_image():
"""Predict 2017:185 dark cal"""
np.random.seed(100)
dark = synthetic_dark_image('2017:010:12:00:00', t_ccd_ref=-13.55)
assert dark.shape == (1024, 1024)
# Warm pixels above threshold
lims = [100, 200, 1000, 2000, 3000]
wps = []
for lim in lims:
w... | 42,707 |
def find_films_in_location(films: pd.DataFrame) -> pd.DataFrame:
"""finds films filmed in certain location
Args:
films (pd.DataFrame): films with their locations
Returns:
pd.DataFrame: films which were filmed in certain location
"""
films.dropna(inplace=True)
# change for more ... | 42,708 |
def get_saved_schemas() -> Any:
"""Lists file and display names of all saved schemas.
File extensions are stripped, and the names are sorted.
Returns:
A JSON response.
"""
schema_paths = sorted(p for p in SCHEMA_DIR.glob("*.yaml"))
display_files = []
for schema_path in schema_paths... | 42,709 |
def _if_installed(pname):
"""Run if the given program name is installed.
"""
def argcatcher(func):
def decorator(*args, **kwargs):
envs = [x for x in args if hasattr(x, "system_install")]
env = envs[0] if envs else None
if shared.which(pname, env):
... | 42,710 |
def check_gym_environments(env: gym.Env) -> None:
"""Checking for common errors in gym environments.
Args:
env: Environment to be checked.
Warning:
If env has no attribute spec with a sub attribute,
max_episode_steps.
Raises:
AttributeError: If env has no observati... | 42,711 |
def WI(bands: dict) -> xr.DataArray:
"""
Water Index (2015): Fisher et al. (2016)
Args:
bands (dict): Bands as {band_name: xr.DataArray}
Returns:
xr.DataArray: Computed index
"""
return (
1.7204
+ 171 * bands[obn.GREEN]
+ 3 * bands[obn.RED]
- 70 ... | 42,712 |
def readZipData(filePath):
"""
Opening the zip file in READ mode and transform scalars.csv to data frame
:param filePath: path to zip-file
:return: data frame with scalars.csv content
"""
with ZipFile(filePath.as_posix(), 'r') as zip:
scalars = None
for i in zip.namelist():
... | 42,713 |
def atm_func(acc_type):
""" Functions of the ATM depending on account type passed"""
# Define a dictionary for the ATM options and sort it as string
opt_dict = {'1': 'Withdraw Money', '2': 'Deposit Money',
'3': 'Check Balance',
'4': 'Print Mini Statement', '5': 'Exit Session... | 42,714 |
def calc_relative_scale(skeleton, ref_bone_lengths, joint_tree) -> (float, float):
"""Calculate the factor by which the reference is larger than the query skeleton.
Args:
skeleton (torch.DoubleTensor): The query skeleton.
ref_bone_lengths (torch.DoubleTensor): The reference skeleton bone length... | 42,715 |
def vertical_move(t, v_speed=2/320):
"""Probe moves vertically at v_speed [cm/s]"""
return 0.*t, 0*t, v_speed*t | 42,716 |
def check_igl_is_installed():
""" Throws an error if igl python bindings are not installed in the current environment. """
if 'igl' not in packages:
raise PluginNotInstalledError("--------ATTENTION! ----------- \
Libigl library is missing! \
Install it wit... | 42,717 |
def import_config(filepath: str = _CONFIG_LOC_):
"""
Import settings from the given configuration file.
This should be called before running the decompiler.
"""
import configparser
config = configparser.ConfigParser()
with open(_DEFAULT_LOC_) as default:
config.read_file(default)
... | 42,718 |
async def main():
"""
https://pypi.org/project/websockets/
"""
async with serve(echo, "localhost", 8765):
await asyncio.Future() | 42,719 |
def get_favored_peaks(rama_key):
"""
returns exact favored peaks with their score value
"""
assert rama_key in range(6)
if rama_key == RAMA_GENERAL:
return [((-115.0, 131.0), 0.57068),
((-63.0, -43.0), 1.0),
((53.0, 43.0), 0.323004),
((53.0, -127.0), 0.0246619)]
if r... | 42,720 |
def get_all_tablespace_acls(conn):
"""
Returns:
List of :class:`~.types.RelationInfo` objects.
"""
return [RelationInfo(**row) for row in conn.execute(_pg_tablespace_stmt)] | 42,721 |
def chunk_pars(content):
"""Given the context contained between `\\beginnumbering` and
`\\endnumbering`, return list of paragraphs.
This is able to handle paragraphs demarcated by `\\pstart` and `\\pend` as
well as when `\\autopar` is used (see §5.2.2 of the reledmac
documentation). The use of `\\a... | 42,722 |
def bound():
""" Generate boundary for testing"""
bound = data.Boundary()
bound.degree = 3
bound.start = np.array([0.0, 0.0, 0.0])
bound.end = np.array([1.0, 0.0, 0.0])
bound.num_ctrlpts = 5
return bound | 42,723 |
def to_tensor(pic: Union[Image, np.ndarray]) -> Tensor:
"""Convert a ``PIL Image`` or ``numpy.ndarray`` to tensor."""
if not (F_pil._is_pil_image(pic) or _is_numpy(pic)):
raise TypeError(f"input pic should be PIL image or numpy.ndarray, Got {type(pic)}")
if _is_numpy(pic) and not _is_numpy_image(pic... | 42,724 |
def test_stdin_reqs(mock_stdin):
"""Verify that lists of requirements work correctly from stdin, including comment and blank lines"""
mock_stdin("pytest\n# Comment\n\npytest-mock\n")
extra_sources = []
result = _create_input_reqs("-", extra_sources)
assert extra_sources == []
assert set(result... | 42,725 |
def dummy_image():
"""Create a dummy image"""
x = numpy.linspace(-1.5, 1.5, 1024)
xv, yv = numpy.meshgrid(x, x)
signal = numpy.exp(- (xv ** 2 / 0.15 ** 2 + yv ** 2 / 0.25 ** 2))
# add noise
signal += 0.3 * numpy.random.random(size=signal.shape)
return signal | 42,726 |
def test_get_submissions_no_key(client):
"""Make sure users cannot get submissions without the secret key."""
rv = client.get('/api/get_submissions/1')
assert b'Missing secret key' in rv.data | 42,727 |
def GetPicList(basedir):
"""
base_dir
-> batch1
-> we
-> want
-> these
-> images
-> batch2
"""
filename = ''
for name in os.listdir(basedir):
if not name.startswith('.'):
filename = name
break
if n... | 42,728 |
def eda(df):
"""Given dataframe, generate exploratory data analysis"""
# check that input is pandas dataframe
if type(df) != pd.core.frame.DataFrame:
raise TypeError("Only pandas dataframe is allowed as input")
# replace field that's entirely space (or empty) with NaN
df = df.replac... | 42,729 |
def setup_default_metrics(app):
"""
This function adds default middlewares to app
Usage example:
from prometheus_toolbox.expose.flask import setup_default_metrics
app = Flask(__name__)
setup_default_metrics(app)
:param app:
:return: None
"""
app.before_request(before_request_mi... | 42,730 |
def text_coloured_errors(tree,
gold=None,
depth=0,
single_line=False,
missing=None,
extra=None,
compressed=True,
POS=True):
"""Pretty print, with errors marked using colour.
'missing' should contain tuples (or be None):
(start, end, label, crossing-T/F)
"""
# TODO: Add the ability to compress the s... | 42,731 |
def update_user(uid, **kwargs):
"""Updates an existing user account with the specified properties.
Args:
uid: A user ID string.
kwargs: A series of keyword arguments (optional).
Keyword Args:
display_name: The user's display name (optional). Can be removed by explicitly passing
... | 42,732 |
def add_center_dist(nusc: NuScenes,
eval_boxes: EvalBoxes):
"""
Adds the cylindrical (xy) center distance from ego vehicle to each box.
:param nusc: The NuScenes instance.
:param eval_boxes: A set of boxes, either GT or predictions.
:return: eval_boxes augmented with center dista... | 42,733 |
def test_relax_parameters_pos_shape(init_relax_parameters):
"""Test position and shape relxation combinations."""
del init_relax_parameters.relax.volume
massager = ParametersMassage(init_relax_parameters)
parameters = massager.parameters[_DEFAULT_OVERRIDE_NAMESPACE]
assert parameters.isif == 4 | 42,734 |
def check_address(btc_addr, network='test'):
""" Checks if a given string is a Bitcoin address for a given network (or at least if it is formatted as if it is).
:param btc_addr: Bitcoin address to be checked.
:rtype: hex str
:param network: Network to be checked (either mainnet or testnet).
:type n... | 42,735 |
def rl_experiment(exp_num, exp_name, prev_exp_dir, requested_shapes, requested_orientation_list, all_saving_dirs):
""" Train policy according to RL experiment shape, size, orientation combo + stage """
# Fill object list using latin square method
env.Generate_Latin_Square(args.max_episode, "objects.csv", sh... | 42,736 |
def reject(ctx, iface, resource_config, **_):
"""Rejects an AWS EC2 Vpc Peer Request"""
params = dict() if not resource_config else resource_config.copy()
resource_id = \
utils.get_resource_id(
ctx.node,
ctx.instance,
params.get(VPC_PEERING_CONNECTION_ID),
... | 42,737 |
def format_time(record):
"""Format time to ISO 8601.
https://en.wikipedia.org/wiki/ISO_8601
"""
utc_time = time.gmtime(record.created)
time_string = time.strftime('%Y-%m-%d %H:%M:%S', utc_time)
return '%s.%03dZ' % (time_string, record.msecs) | 42,738 |
def _cb_decode(s, maxsize=8192):
"""Decode a list of IDs from storage in a cookie.
``s`` is text as encoded by ``_cb_encode``.
``maxsize`` is the maximum size of uncompressed data. ``0`` means no limit.
Return a list of text IDs.
"""
dec = decompressobj()
squashed = unquote(s).encode('lati... | 42,739 |
def test_getArticleTitles():
"""Test for getArticleTitles function."""
assert getArticleTitles(author="epaga") == [
"A Message to Our Customers",
(
"“Was isolated from 1999 to 2006 with a 486. "
"Built my own late 80s OS”"
),
"Apple’s declining software qu... | 42,740 |
def validate_model(df, fix=False):
"""
Validates the form of a model dataframe. A model dataframe must look something like this:
pos val_A val_C val_G val_T
3 1.1 4.3 -6.19 5.2
4 0.01 3.40 -10.5 5.3
5 0 1.4 10.9 231.0
A 'po... | 42,741 |
def create_training_instances(input_files, tokenizer, max_seq_length,
dupe_factor, short_seq_prob, masked_lm_prob,
max_predictions_per_seq, rng):
"""Create `TrainingInstance`s from raw text."""
all_documents = [[]]
# Input file format:
# (1) One sente... | 42,742 |
def TestParallelModify(instances):
"""PERFORMANCE: Parallel instance modify.
@type instances: list of L{qa_config._QaInstance}
@param instances: list of instances to issue modify commands against
"""
job_driver = _JobQueueDriver()
# set min mem to same value as max mem
new_min_mem = qa_config.get(consta... | 42,743 |
def print_cat() -> None:
"""Prints cat"""
print('\n'.join(
[
r" \ |\---/|",
r" \ | ,_, |",
r" \_`_/-..----.",
r" ___/ ` ' ,\"\"+ \ sk",
r" (__...' __\ |`.___.';",
... | 42,744 |
def cdgmm(A, B, inplace=False):
"""Complex pointwise multiplication.
Complex pointwise multiplication between (batched) tensor A and tensor B.
Parameters
----------
A : tensor
A is a complex tensor of size (B, C, M, N, 2).
B : tensor
B is a compl... | 42,745 |
def test_change_user_password_success(api_client, django_user_model):
"""
Change the user password after providing the old one
"""
user = django_user_model.objects.create_user(username='user', password='old_pass')
token, _ = Token.objects.get_or_create(user=user)
api_client.credentials(HTTP_AUTH... | 42,746 |
def InvocationStartEncKeyVector(builder, numElems):
"""This method is deprecated. Please switch to Start."""
return StartEncKeyVector(builder, numElems) | 42,747 |
def dynamic_partial_sum_product(
sum_op, prod_op, factors, eliminate=frozenset(), plate_to_step=dict()
):
"""
Generalization of the tensor variable elimination algorithm of
:func:`funsor.sum_product.partial_sum_product` to handle higer-order markov
dimensions in addition to plate dimensions. Markov ... | 42,748 |
def range_to_number(interval_str):
"""Converts "X-Y" -> "X"."""
if not '-' in interval_str:
return int(interval_str)
# If first character is -, X is a negative number
if interval_str.startswith('-'):
number = '-' + interval_str.split('-')[1]
else:
number = interval_str.split... | 42,749 |
def load_wav_file_with_wavio(
file_path, sample_rate, mono=True, resample_type="kaiser_best"
):
"""Load a 24-bit wav audio file as a floating point time series. Significantly faster than
load_sound_file."""
wavio_obj = wavio.read(str(file_path))
samples = wavio_obj.data
actual_sample_rate = wav... | 42,750 |
def make_proxy_cls(
remote_cls: netref.BaseNetref,
origin_cls: type,
override: type,
cls_name: str = None,
):
"""
Makes a new class type which inherits from <origin_cls> (for isinstance() and issubtype()),
takes methods from <override> as-is and proxy all requests for other members to <remot... | 42,751 |
def test_bump(fake_keats):
"""We expect the version to be bump by one increment."""
assert fake_keats.v() == "9.9.9"
fake_keats.version.bump()
assert fake_keats.v() == "9.9.10" | 42,752 |
def mesh_transform_numpy(mesh, transformation):
"""Transform a mesh.
Parameters
----------
mesh : compas.datastructures.Mesh
The mesh.
transformation : compas.geometry.Transformation
The transformation.
Notes
-----
The mesh is modified in-place.
Examples
------... | 42,753 |
def as_cidr(cr: CidrRepr) -> Cidr:
"""
Returns a strict network address expressed as in CIDR form: either a string, expressing the network address as
``"<network number><zeros>/<mask bits>"``, or as a ``Cidr`` object, which is returned unaltered.
"""
if isinstance(cr, _BaseNetwork):
return c... | 42,754 |
def backup_mailbox(conn, config, account, mailbox_name, mbox_path):
"""
Backs up a mailbox to an mbox file.
"""
# load the mbox from disk if it exists and determine the Message-ID's already stored
parse_message_id_header = lambda message_id: (lambda m: m.group(1) if m else None)(
MESSAGE_ID_... | 42,755 |
def get_authorship(authorship_uri):
"""
Given a URI, return an object that contains the authorship it represents
"""
from vivofoundation import get_triples
authorship = {'authorship_uri':authorship_uri}
triples = get_triples(authorship_uri)
try:
count = len(triples["results"]["bindin... | 42,756 |
def Init():
""" Инициализации важных переменных """
# Получаем список листов, их Id и название
spreadsheet = service.spreadsheets().get(spreadsheetId = spreadsheet_id).execute()
sheetList = spreadsheet.get('sheets')
sheetUsers = sheetList[0]['properties']['sheetId']
sheetSW = sheetList[1]['p... | 42,757 |
def Nlam_to_Flam(wave, zeropoint, zp_min=5.0, zp_max=30.0):
"""
The factor that when multiplied into N_lam converts to F_lam, i.e. S_lam where S_lam \equiv F_lam/N_lam
Parameters
----------
wave (`numpy.ndarray`_):
Wavelength vector for zeropoint
zeropoint (`numpy.ndarray`_):
zero... | 42,758 |
def base64_values_validate(name, description, color_set):
"""Ensures the string wasn't maliciously fabricated to feed corrupted data into the app, even if the b64 code itself
successfully decoded into a valid string."""
if custom_palette_name_validate(name) or custom_palette_description_validate(description... | 42,759 |
def isIndepFromTarget(df, attr, x):
"""
Determiner si un attr est independant de target
:df: dataframe choisit
:attr: l'argument choisit a etudier
:x: seuil
:retourner true si n attr est independant de target
"""
obs=[[], []]
ref=[]
for t in df.itertuples():
dic=t._asdict... | 42,760 |
def read_docs_md(filename, root=None):
"""
Retrieves an apidoc markdown file to be implemented in swagger_auto_schema
:param(str) root: root base dir, settings.BASE_DIR as default
:param(str) filename: the filename to be retrieved without the .md file type
:return: the content of the md file, None i... | 42,761 |
def unrotate(points, posor):
"""Rotate the matrix of column vectors points according to posor, i.e., from
absolute coordinates to camera coordinates"""
rot_matrix = calc_rot_matrix(posor)
return rot_matrix.I * points | 42,762 |
def main(argdict):
"""Main function for entry point checking.
Expects to be given a dictionary of command line arguments.
"""
# parse trajectory and assign domain indices:
print("--> identifying domain indices...")
nm2ang = 10.0
domain_indices = determine_domain_indices(
argdict["s... | 42,763 |
def exp_tail(d, x):
"""Tail of the exponential series starting at d. Needed in the set sampler.
Parameters
----------
d: int
x: float
Returns
-------
float
"""
result = exp(x)
# Subtract the _first _d terms.
for i in range(d):
result -= (pow(x, i) / factorial(i... | 42,764 |
def check_projects_scores(request, hackathon_id):
""" When a judge submits the score, check if all projects in the Hackathon
were scored by all the judges in all the categories by comparing the
number of objects in HackProjectScore for each projects to the required
number of objects.
If all project... | 42,765 |
def test_uniq_words():
"""Test uniq_words"""
s1 = '?foo, "bar", FOO: $fa,'
s2 = '%Apple.; -Pear. ;bANAna!!!'
assert uniq_words(io.StringIO(s1), 0) == set(['foo', 'bar', 'fa'])
assert uniq_words(io.StringIO(s1), 3) == set(['foo', 'bar'])
assert uniq_words(io.StringIO(s2), 0) == set(['apple', ... | 42,766 |
def test_concat_fails_empty():
"""Check that calling concat with empty or none raises"""
match = "No objects to concatenate"
with pytest.raises(ValueError, match=match):
concat([]) | 42,767 |
def remove_and_create_dir(path):
""" System call to rm -rf and then re-create a dir """
dir = os.path.dirname(path)
print('attempting to delete ', dir, ' path ', path)
if os.path.exists(path):
os.system("rm -rf " + path)
os.system("mkdir -p " + path)
return path | 42,768 |
def _get_week_comfortband(building, zone, date, interval):
"""
Gets the whole comfortband from the zone configuration file. Correctly Resamples the data according to interval
:param date: The date for which we want to start the week. Timezone aware.
:param interval: int:seconds. The interval/frequency o... | 42,769 |
def csv_make_labels(filename, labels):
"""
csvファイルの1行目にラベルを書く
Parameters
----------
filename : str
出力ファイル名
labels : tuple (str)
ラベルのタプル
例: ('r', 'iter', 'F')
"""
with open(filename, 'w') as f:
writer = csv.writer(f)
writer.writerow(labels) | 42,770 |
def setup_testrun_dir():
"""
Sets up a testrun_* directory in the cwd and returns the path to it
"""
test_run = "testrun_{}".format(int(time.time()))
os.mkdir(test_run)
this_files_dir = os.path.dirname(os.path.realpath(__file__))
config_templates = os.path.join(this_files_dir, "integration",... | 42,771 |
def get_path(obj, path, default=None):
"""Get the value at any depth of a nested object based on the path
described by `path`. If path doesn't exist, `default` is returned.
Args:
obj (list|dict): Object to process.
path (str|list): List or ``.`` delimited string of path describing
... | 42,772 |
def get_label_set_args():
"""
Add arguments specific to the "Label Set" experiment.
Return ArgParser object.
"""
cmd = get_general_args()
cmd = get_explainer_args(cmd)
cmd.add('--in_dir', type=str, default='output/influence_set/')
cmd.add('--out_dir', type=str, default='output/label_set... | 42,773 |
def test_spec():
"""
Container should return a valid specification.
"""
try:
jsonschema.validate(instance=get_spec(), schema=LANGUAGE_MODEL_SPEC_SCHEMA)
except jsonschema.exceptions.ValidationError as e:
# Avoid printing enormous schema JSONs.
from pprint import pformat
... | 42,774 |
def literal_label(lit):
""" Invent a nice label name for the given literal """
return '{}_{}'.format(lit.function.name, lit.name) | 42,775 |
def key(element: DOMElement) -> Optional[str]:
"""
Retrieve the key of a particular :class:`.DOMElement` in its parent element, if it can be
referred to by a key (i.e. if it its parent element is a :class:`collections.abc.Mapping`).
:param element: A DOM element
:return: The key of that DOM ... | 42,776 |
def warning_msg(msg):
"""Issue the msg param as warning prefixed by WARNING: to stderr"""
click.echo('WARNING: {}'.format(msg), err=True) | 42,777 |
def absolute_reverse(view_name, query_kwargs=None, args=None, kwargs=None):
"""Like django's `reverse`, except returns an absolute URL. Also add query parameters."""
relative_url = reverse(view_name, kwargs=kwargs)
url = website_util.api_v2_url(relative_url, params=query_kwargs)
return url | 42,778 |
def convert(chinese):
"""converts Chinese numbers to int
in: string
out: string
"""
numbers = {'零':0, '一':1, '二':2, '三':3, '四':4, '五':5, '六':6, '七':7, '八':8, '九':9, '壹':1, '贰':2, '叁':3, '肆':4, '伍':5, '陆':6, '柒':7, '捌':8, '玖':9, '两':2, '廿':20, '卅':30, '卌':40, '虚':50, '圆':60, '近':70, '枯':80, '无'... | 42,779 |
def method_not_raises(UnexpectedException):
"""A decorator that ensures that the underlying function does not raise the UnexpectedException"""
@Decorators.decorator
def method_not_raises(target, *args, **kwargs):
return not_raises(UnexpectedException, target, *args, **kwargs)
return method_not_r... | 42,780 |
def create_random_data(n_randoms, stomp_map):
"""Function for creating randomly positioned unknown objects on the considerd
geomometry. These is used for normalizing the output PDF and properly
estimating the "zero point" of the correlation amplitude. The code returns
a spatially searchable quad tree of... | 42,781 |
def _rotate_flag(flag, rotation):
"""Rotates the square flag by the given number of degrees. Preserves size."""
original_size = flag.size
offset = int(((flag.size[0] * (2**0.5)) - flag.size[0]) / 2)
flag = flag.resize((int(flag.size[0]*(2**0.5)) + 1,)*2, resample=Image.BICUBIC)
flag = flag.rotate(ro... | 42,782 |
def mobilenetv1():
"""Handler da página inicial do modelo de Mobilenet V1
:return:
"""
return render_template("mobilenetv1.html") | 42,783 |
def move(board):
"""Queries the user to move. Returns false if the user puts in an invalid input or move, returns true if the move was successful"""
start_input = input("MOVE WHICH PIECE? ")
if not start_input.isdigit():
return False
start = int(start_input)
if start not in board... | 42,784 |
def calc_vrctst_flux(ini_zma, ts_info, hs_info,
ts_formula, high_mul, active_space,
rct_info, rct_ichs, rct_zmas, rcts_cnf_fs,
grid1, grid2, coord_name,
mod_var_scn_thy_info,
mod_var_sp1_thy_info, var_sp2_thy_info,
... | 42,785 |
def to_timedelta(arg: Literal["huh"]):
"""
usage.xarray: 1
"""
... | 42,786 |
def _read_reaction_kinetic_law_from_sbml(reaction, mass_reaction, f_replace, **kwargs):
"""Read the SBML reaction kinetic law and return it.
Warnings
--------
This method is intended for internal use only.
"""
mass_rid = mass_reaction.id
sbml_species = (
list(reaction.getListOfReac... | 42,787 |
def test_hash_from_estep():
"""
This function test that the returns the hash of a new Auxiliary Vector
with the desired step in the given mode is the correct hash
"""
# Define constants
aux_2000 = AuxiliaryVector([(0, 2)], 4)
aux_1001 = AuxiliaryVector([(0, 1), (3, 1)], 4)
aux_1011 = Aux... | 42,788 |
def _total_probe_count_without_interp(params, probe_counts):
"""Calculate a total probe count without interpolation.
This assumes that params are keys in the datasets of probe_counts.
The result of ic._make_total_probe_count_across_datasets_fn should give
the same count as this function (if params are... | 42,789 |
def existing_file(path):
"""Checks if a file exists.
Returns:
str: The path to the file.
Raises:
argparse.ArgumentTypeError: If a path argument does not exist.
"""
if not os.path.isfile(path):
raise argparse.ArgumentTypeError(
'No such file or directory: "%s"' ... | 42,790 |
def make_divisible(x: Any, divisor: int):
"""Returns x evenly divisible by divisor."""
return math.ceil(x / divisor) * divisor | 42,791 |
def run(tarfolder,outfolder,typeformat="sbml",choice="2",selenzyme_table="N",filenames=''):
"""Main function that runs the tool"""
print(typeformat)
#Initialization
scores={} #scores (thermodynamics values, FBA...)
scores_col={} #scores colors (for gradient mapping)
RdfG_o={}
RdfG_m... | 42,792 |
def one_vehicle_xml():
"""Emulates a XML response for 1 vehicle trajectory"""
STREAM = b'<INST nbVeh="1" val="2.00"><CREATIONS><CREATION entree="Ext_In" id="1" sortie="Ext_Out" type="VL"/></CREATIONS><SORTIES/><TRAJS><TRAJ abs="25.00" acc="0.00" dst="25.00" id="0" ord="0.00" tron="Zone_001" type="VL" vit="25.00... | 42,793 |
def select_data(all_tetrode_data, index):
"""
Select tetrode data by trial indices.
:param all_tetrode_data: (list of 4d numpy arrays) each of format [trial, 1, neuron + tetrode, time]
:param index: (1d numpy array) trial indices
:return: (list of 4d numpy arrays) selected subset of tetrode data
... | 42,794 |
def main(argv: Optional[Sequence[str]] = None) -> None:
"""Entry point for PSK proxy.
Parses command-line arguments, sets up listening sockets
and loops over incoming data on sockets using select().
"""
logging.basicConfig(
format="%(asctime)-15s %(name)s %(levelname)-8s %(message)s",
... | 42,795 |
def normalize(ds_train, ds_cv, ds_test):
"""
Normalization of datasets
Parameters
----------
ds_train: Dataset
Training set
ds_cv: Dataset
Cross-validation set
ds_test: Dataset
Test set
Returns
-------
norm_train: Dataset
Normalized training set
... | 42,796 |
def generate_sequential(num_users=100,
num_items=1000,
num_interactions=10000,
concentration_parameter=0.1,
order=3,
random_state=None):
"""
Generate a dataset of user-item interactions where ... | 42,797 |
def expand(fluid, pfinal, eta):
"""Adiabatically expand a fluid to pressure pfinal, using
a turbine with isentropic efficiency eta."""
h0 = fluid.enthalpy_mass()
s0 = fluid.entropy_mass()
fluid.set(S = s0, P = pfinal)
h1s = fluid.enthalpy_mass()
isentropic_work = h0 - h1s
actual_... | 42,798 |
def test():
"""
API测试
:return:
"""
dataset1 = tf.data.Dataset.from_tensor_slices(tf.random_normal([4, 10]))
print(dataset1.output_shapes)
print(dataset1.output_types)
# 2
dataset2 = tf.data.Dataset.from_tensor_slices({"f": tf.random_normal([4, 10]),
... | 42,799 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.