content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def MC1(N,g1,x):
""" Calculating the numerical solution to the integral of the agents value by Monte Carlo of policy 1
Args:
N (int): Number of iterations/draws
g1 (float): Agents value of policy 1
x (float): Drawn from a beta distribution (X)
... | f3a25656f60788e0ec50d75be6d20ff3e497f500 | 18,600 |
def string_between(string, start, end):
"""
Returns a new string between the start and end range.
Args:
string (str): the string to split.
start (str): string to start the split at.
end (str): string to stop the split at.
Returns:
new string between start and end.
"... | fc6f2a3def4112140539c90abe6304f5daa8c1f4 | 18,601 |
def _parse_line(line: str):
"""
行解析,逗号隔开,目前支持3个字段,第一个是展示的名称,第二个是xml中保存的名称,第三个是附带值value的正则标的形式
:param line:
:return:
"""
line = line.strip()
config = line.split(",")
if len(config) == 2:
return config[0], config[1], ""
elif len(config) == 3:
return config[0] + INTER_FL... | 6f325886c82eb5cdb438bd76c893b4ef42c319f5 | 18,602 |
def harvest_zmat(zmat: str) -> Molecule:
"""Parses the contents of the Cfour ZMAT file into array and
coordinate information. The coordinate info is converted into a
rather dinky Molecule (no fragment, but does read charge, mult,
unit). Return qcdb.Molecule. Written for findif zmat* where
geometry a... | aa8b89781c00d4939e7083613cb13fdf9eb4f710 | 18,603 |
import os
def test_ensure_env_decorator_sets_gdal_data_wheel(gdalenv, monkeypatch, tmpdir):
"""fiona.env.ensure_env finds GDAL data in a wheel"""
@ensure_env
def f():
return getenv()['GDAL_DATA']
tmpdir.ensure("gdal_data/pcs.csv")
monkeypatch.delenv('GDAL_DATA', raising=False)
monkeyp... | 8e436810dd13b0dbc83785ac80145b7a4fc1ca7d | 18,604 |
def then_wait(msg_type, criteria_func, context, timeout=None):
"""Wait for a specific message type to fullfil a criteria.
Uses an event-handler to not repeatedly loop.
Args:
msg_type: message type to watch
criteria_func: Function to determine if a message fulfilling the
... | 93f2826b8f976c35ee14cd7cf7462b14db2f6512 | 18,605 |
def interaction_fingerprint_list(interactions, residue_dict, interaction_dict):
"""
Create list of fingerprints for all given structures.
"""
fp_list = []
for sites in interactions.items():
for site_name, site_interactions in sites.items():
if not site_name.startswith("LIG"):
... | 79bc84b1e4ceda4cb1d43653eec96e6f17956fa9 | 18,606 |
def get_dynamic_client(
access_token: str, project_id: str, cluster_id: str, use_cache: bool = True
) -> CoreDynamicClient:
"""
根据 token、cluster_id 等参数,构建访问 Kubernetes 集群的 Client 对象
:param access_token: bcs access_token
:param project_id: 项目 ID
:param cluster_id: 集群 ID
:param use_cache: 是否使... | 41735ffc0ff1722d528c7022988ff47925318c33 | 18,607 |
import sys
import traceback
def _launch(url, runtime, **kwargs):
""" Attempt to launch runtime by its name.
Return (runtime_object, is_launched, error_object)
"""
rt = None
launched = False
try:
if runtime.endswith('-app'):
# Desktop-like app runtime
... | 75481ddccb7f428226b3f38ba484f5da2ece92a4 | 18,608 |
def bucket(db, dummy_location):
"""File system location."""
b1 = Bucket.create()
db.session.commit()
return b1 | 755db301053bab638b1963cb5c6f985760d51688 | 18,609 |
def standardize_str(string):
"""Returns a standardized form of the string-like argument.
This will convert from a `unicode` object to a `str` object.
"""
return str(string) | ea007582363cd1eeee34d4b342a39581fd876c3a | 18,610 |
import json
def lambda_handler(event, context):
"""
スタッフの日毎の空き情報を返却する
Parameters
----------
event : dict
フロントからのパラメータ群
context : dict
コンテキスト内容。
Returns
-------
return_calendar : dict
スタッフの日毎の空き情報(予約がある日のみ空き有無の判定結果を返す)
"""
# パラメータログ、チェック
logger.in... | 8f44cd7f7aa3b62c0fd0c4253f92a05749f94bb4 | 18,611 |
import torch
def init_process_group_and_set_device(world_size, process_id, device_id, config):
"""
This function needs to be called on each spawned process to initiate learning using DistributedDataParallel.
The function initiates the process' process group and assigns it a single GPU to use during traini... | 5647e76b71d6d865487cdf348580ee8c58ba9bc5 | 18,612 |
from meerschaum.utils.warnings import error, warn
from typing import Tuple
from typing import Any
def yes_no(
question : str = '',
options : Tuple[str, str] = ('y', 'n'),
default : str = 'y',
wrappers : Tuple[str, str] = ('[', ']'),
icon : bool = True,
yes : bool = Fals... | 930e0c7f56c0d94e9a00928df764998fd84506b1 | 18,613 |
def load(filename, instrument=None, **kw):
"""
Return a probe for NCNR data.
"""
header, data = parse_file(filename)
return _make_probe(geometry=Polychromatic(), header=header, data=data, **kw) | fbe07b4036cf87f91e07f062bd33d75cae0f08ee | 18,614 |
def get_repeat():
""" get_repeat() -> (delay, interval)
see how held keys are repeated
"""
check_video()
delay, interval = ffi.new('int*'), ffi.new('int*')
sdl.SDL_GetKeyRepeat(delay, interval)
return (delay[0], interval[0]) | 63d4b854b199ec5a55aa6dbbfb2f9e859d892ffa | 18,615 |
def growth(params, ns, rho=None, theta=1.0, gamma=None, h=0.5, sel_params=None):
"""
exponential growth or decay model
params = (nu,T)
nu - final size
T - time in past size changes begin
"""
nu,T = params
if rho == None:
print("Warning: no rho value set. Simulating with rho = 0."... | f797262cfc98f6194fd170ca435949baa123ccf5 | 18,616 |
def mse(y_true, y_pred):
""" Mean Squared Error """
return K.mean(K.square(_error(y_true, y_pred))) | 0bfaa4b8042af681a8c398f8004c8dc1b4838302 | 18,617 |
from sklearn.neighbors import NearestNeighbors
from sklearn.feature_extraction.text import TfidfVectorizer
from typing import Iterable
def knn_name_matching(
A: Iterable[str], B: Iterable[str],
vectorizer_kws: dict = {}, nn_kws: dict = {},
max_distance: float = None, return_B=True) -> list:
... | fcde5e8d50d5696edf9df467f11f61db53b2c765 | 18,618 |
import logging
def setup_platform(hass, config, add_devices, discovery_info=None):
""" Sets up the ISY994 platform. """
logger = logging.getLogger(__name__)
devs = []
# verify connection
if ISY is None or not ISY.connected:
logger.error('A connection has not been made to the ISY controller... | 8ad612cd7f9e9f95f8c299b79e2aafca9c5c331f | 18,619 |
def frames_downsample(arFrames:np.array, nFramesTarget:int) -> np.array:
""" Adjust number of frames (eg 123) to nFramesTarget (eg 79)
works also if originally less frames then nFramesTarget
"""
nSamples, _, _, _ = arFrames.shape
if nSamples == nFramesTarget: return arFrames
# down/upsample th... | 5f597ed79cd31bf146f65e9a5f17dadf42b31bc7 | 18,620 |
def icon_dir():
"""pathname of the directory from which to load custom icons"""
return module_dir()+"/icons" | f531fcd312a36ab3ebcc3d16540cb8de7657340a | 18,621 |
def search_pkgs(db, project_type, pkg_list):
"""
Method to search packages in our vulnerability database
:param db: DB instance
:param project_type: Project type
:param pkg_list: List of packages to search
"""
expanded_list = []
pkg_aliases = {}
for pkg in pkg_list:
variatio... | 8a5c91d0cafad60ece8de2ba7952d97c98f8ab0d | 18,622 |
def post_question():
""" Post a question."""
q_data = request.get_json()
# No data provied
if not q_data:
abort(make_response(jsonify({'status': 400, 'message': 'No data sent'}), 400))
else:
try:
data = QuestionSchema().load(q_data)
if not MeetupModel().ex... | e78e71ef415e465a6ac95d5525d1eba067f51a99 | 18,623 |
def infinitegenerator(generatorfunction):
"""Decorator that makes a generator replay indefinitely
An "infinite" parameter is added to the generator, that if set to True
makes the generator loop indifenitely.
"""
def infgenerator(*args, **kwargs):
if "infinite" in kwargs:
... | 6915a16dd765195e0344b5ebd255c1aca7737699 | 18,624 |
import sys
import string
def clear_punctuation(document):
"""Remove from document all pontuation signals."""
document = str(document)
if sys.version_info[0] < 3:
return document.translate(None, string.punctuation)
else:
return document.translate(str.maketrans("", "", string.punctuation... | 469be4087b026703250f0b05a471929ca56b7d63 | 18,625 |
import string
import random
def id_generator(size=6, chars=string.ascii_uppercase + string.digits):
"""Credit: http://stackoverflow.com/questions/2257441/random-string-generation-with-upper-case-letters-and-digits-in-python"""
return ''.join(random.choice(chars) for _ in range(size)) | b5842d56e548d4054230d300e6fc5e05a18ce18c | 18,626 |
def _update_objective(C_obj, Q, QN, R, R0, xr, z_init, u_init, const_offset, u_prev, N, nx, nu):
"""
Construct MPC objective function
:return:
"""
res = np.hstack(
((C_obj.T @ Q @ (C_obj @ z_init[:, :-1] - xr[:, :-1])).T.flatten(),
C_obj.T @ QN @ (C_obj @ z_init[:, -1] - xr[:, -1]),... | ed22a62a9f9dadfb1d6dc71fc3735cadb299ff2a | 18,627 |
import argparse
from datetime import datetime
def absolute_time(arg):
"""Validate user provided absolute time"""
if not all([t.isdigit() for t in arg.split(':')]):
raise argparse.ArgumentTypeError("Invalid time format: {}".format(arg))
# Valid time (e.g. hour must be between 0..23)
try:
... | 7cdb2950c65fc18e894647ee47f2f0354991ecac | 18,628 |
import torch
def convert(M: any) -> torch.Tensor:
"""
Convert Scipy sparse matrix to pytorch sparse tensor.
Parameters
----------
M : any
Scipy sparse matrix.
Returns
-------
Ms : torch.Tensor
pytorch sparse tensor.
"""
M = M.tocoo()
indices = torch.from_... | d65b4d1200c36baec6b37550c0e53c79c5a6fcaa | 18,629 |
import math
def process_lines(lines):
"""
It classifies the lines and combine them into a CombinedLine
:param lines: np.array with all the lines detected in the image. It should be the output of a HoughLinesP function
:return: np.array with 2 lines
"""
lines_l = CombinedLine()
lines_r = Co... | 37c23e2008c7cf67f937da0720b8e64fac8d7367 | 18,630 |
def get_balances_with_token(token: str):
"""Returns all entries where a token is involved"""
token = token.lower()
conn = create_connection()
with conn:
cursor = conn.cursor()
fiat = confighandler.get_fiat_currency().lower()
cursor.execute(
f"SELECT date,balance_btc,b... | e6a88362edf1e482877f8afca30b0db576663572 | 18,631 |
def relative_cumulative_gain_curve(df: pd.DataFrame,
treatment: str,
outcome: str,
prediction: str,
min_rows: int = 30,
steps: int = 100,
... | 78c2a889100b936a82a615ff0c07028cd1e10021 | 18,632 |
def add_curve_scatter(axis, analysis_spot, color_idx):
"""Ad one of more scatter curves that spot events
Arguments:
y_axis : a pyplot x-y axis
analysis : a dictionnary { 'name': [<datetime>, ...], ... }
"""
curves = []
# each spot analysis has a different y value
spot_value... | ac2fb5c970de52f64de94dc42914f078e8d727c9 | 18,633 |
def get_character_journal(character_ccp_id, page = 1, page_limit=5):
"""
:param self:
:param character_ccp_id:
:param oldest_entry:
:param page_limit:
:return:
"""
character = EVEPlayerCharacter.get_object(character_ccp_id)
if not character.has_esi_scope('esi-wallet.read_character_w... | 3768c7e3548338dc63521cfa045d7da03061a9e2 | 18,634 |
def get_entropy(labels):
"""Calculates entropy using the formula
`-Sum(Prob(class) * log2(Prob(class)))` for each class in labels."""
assert len(labels.shape) == 1
_, count = get_unique_classes_count(labels)
probabilities = count / labels.shape
return -np.sum(probabilities * np.log2(proba... | 244e1be13ade51bc2aa5320b8f1575339559bc24 | 18,635 |
def store():
"""Database storage fixture."""
in_memory_database = Database.in_memory(echo=False)
in_memory_database.create_tables()
return DBResultStorage(in_memory_database) | bf29f10b8f93c341d0e757268784944638458c0a | 18,636 |
import json
def test_homology(dash_threaded):
"""Test the display of a basic homology"""
prop_type = 'dict'
prop_val = {
"chrOne": {
"organism": "9606",
"start": [10001, 105101383],
"stop": [27814790, 156030895],
},
"chrTwo": {
"org... | c03f0d0a33da034c5dfba1a77284bba100e8aca9 | 18,637 |
import subprocess
def coverage():
"""
View a report on test coverage.
Call py.test with coverage turned on.
"""
print("\ncoverage")
return subprocess.run(
[
PYTEST,
"--cov-config",
".coveragerc",
"--cov-report",
"term-missing... | 5f2ace87e5e151b12fbea76d9bda5a5deb1a5ed7 | 18,638 |
import os
def get_files(directory):
"""Gets full path of all files within directory, including subdirectories
Returns a list of paths"""
file_paths = []
for root, dirs, files in os.walk(directory):
for f in files:
filepath = os.path.join(root, f)
file_paths.append(file... | f0ad1ef92c5e00ef637c0b874acefa3344e64395 | 18,639 |
def load_vocab(filename):
"""Loads vocab from a file
Args:
filename: (string) the format of the file must be one word per line.
Returns:
d: dict[word] = index
"""
word2id = dict()
with open(filename, 'r', encoding='utf-8') as f:
for idx, word in enumerate(f):
... | b4c2ea26647d85d610d9293fe8e847ae873d8bf8 | 18,640 |
def load_labels(label_path):
"""
Load labels for VOC2012, Label must be maded txt files and like my label.txt
Label path can be change when run training code , use --label_path
label : { label naem : label color}
index : [ [label color], [label color]]
"""
with open(label_path, "r") as f:
... | 9c0388eb533293912b95ca020cbf3c9e9cb331d3 | 18,641 |
def _make_function_ptr_ctype(restype, argtypes):
"""Return a function pointer ctype for the given return type and argument types.
This ctype can for example be used to cast an existing function to a different signature.
"""
if restype != void:
try:
restype.kind
except AttributeError:
raise TypeError("... | 86381f41face07d00e976c28977292e0c80c367d | 18,642 |
import re
def parse_matl_results(output):
"""Convert MATL output to a custom data structure.
Takes all of the output and parses it out into sections to pass back
to the client which indicates stderr/stdout/images, etc.
"""
result = list()
parts = re.split(r'(\[.*?\][^\n].*\n?)', output)
... | ec3a7c5c77edaea08a6cdf207f5848485fd33d8f | 18,643 |
def astToMongo(ast):
"""Run the AST-to-mongo helper function after converting it to a not-free equivalent AST."""
return _astToMongo_helper(_eliminate_not(ast)) | be2020aa325054147bdbc4c919b19e1c03a10953 | 18,644 |
def write_seqs_fasta(out_fp_seqs_fasta: str, out_fp_seqs_qza: str,
tsv_pd: pd.DataFrame) -> str:
"""
Write the fasta sequences.
:param out_fp_seqs_fasta: output sequences fasta file name.
:param out_fp_seqs_qza: output sequences qiime2 Artefact file name.
:param tsv_pd: table w... | c8af3e589fef023a5e0d2a784f404d682edc1276 | 18,645 |
def f(x,y):
"""
Takes in two numpy arrays that are result of meshgrid.
Returns a numpy array with points representing the iteration number for divergence
"""
max_iter = 100 #maximum number of interations
c = x + 1j*y
z = np.zeros((N,N),dtype=complex)
r = np.zeros((N,N),dtype=int) #return... | d742e48612f4d8063fd4f4f779d014716fb7fb5f | 18,646 |
from typing import List
def _expand_param_name(param: BaseDescriptor) -> List[str]:
"""
Get expanded param names
:param param: The param to expand
"""
if not getattr(param, 'expand', False):
raise ValueError('Cannot expand param that does not have the expand kwarg')
new_arg_names = _g... | 856eece57948111fa59507496fccd3d30b5bcc55 | 18,647 |
def accuracy_top_k(output, target, top_k=(1,)):
"""Computes the precision@k for the specified values of k"""
max_k = max(top_k)
batch_size = target.size(0)
_, pred = output.topk(max_k, 1, True, True)
pred = pred.t()
correct = pred.eq(target.view(1, -1).expand_as(pred))
res = []
for k i... | e615b001d6c95cc64ff6ba123337c9cf8ca9bae9 | 18,648 |
from typing import Optional
def softmax(data: NodeInput, axis: int, name: Optional[str] = None) -> Node:
"""Apply softmax operation on each element of input tensor.
:param data: The tensor providing input data.
:param axis: An axis along which Softmax should be calculated. Can be positive or negative.
... | c066251ba39e3de429d784d643460bd9ee9027a9 | 18,649 |
def get_duts_mac_address(duts):
"""
This is used to get the Duts and its mac addresses mapping
:param duts: List of DUTs
:return : Duts and its mac addresses mapping
"""
duts_mac_addresses = {}
cmd = "show platform syseeprom"
for dut in duts:
if st.is_vsonic(dut):
... | 7a3eb9a7fde99a97a04a8b28278790ff42130c79 | 18,650 |
def crop(sample, crop_area, in_crop_threshold):
"""Crop an image to a given area and transform target accordingly.
Args:
sample: {
"image": PIL.Image,
"bboxes": Numpy array :math:`(N, 4)` (XYXY format),
"keypoints": Numpy array :math:`(N, n, 2)`, (optional)
... | 264f5bbd9407246c38e539b6e750ea39933ec7af | 18,651 |
from datetime import datetime
def get_cpu_utilization(mqueries, region, days):
"""
Gets CPU utilization for instances
"""
client = SESSION.client('cloudwatch', region_name=region)
time_from = (datetime.now() - timedelta(days=days))
time_to = datetime.now()
response = client.get_metric_d... | f2ce39905e34eab66f7ff59735c9365d4c80eb86 | 18,652 |
def std_opt_end_independent(policy_net, target_net, optimizer, memory,
batch_size=128, GAMMA=0.99, device='cuda'):
"""
Apply the standard procedure to an ensemble of deep Q network.
"""
if len(memory) < batch_size:
return 0
total_loss = 0
for ens_num in range... | ea27f65a2227e2a7d4c0c11c7664f79f4c6c5f63 | 18,653 |
from typing import Dict
from typing import Tuple
import logging
import requests
import re
def scrape_forecast_products() -> Dict[str, Tuple[str, str]]:
""" Get list of forecast products by scraping state overivew pages
"""
logging.info("Scraping list of BOM forecast products")
products = dict()
f... | ea67bc047d03bc36b2d82f253df54c24d8624ed3 | 18,654 |
def plate_from_list_spreadsheet(
filename, sheet_name=0, num_wells="infer", wellname_field="wellname"
):
"""Create a plate from a Pandas dataframe where each row contains the
name of a well and metadata on the well.
Parameters
----------
filename
Path to the spreadsheet file.
sheet... | b082a3900ffebf87f443d17e8b934c73c35b910d | 18,655 |
from typing import Optional
def displaced_species_along_mode(species: Species,
mode_number: int,
disp_factor: float = 1.0,
max_atom_disp: float = 99.9) -> Optional[Species]:
"""
Displace the geometry a... | ec0ada73abbbccb6ec24c1afacaa106e851d69a9 | 18,656 |
def constant(pylist, dtype=None, ragged_rank=None, inner_shape=None,
name=None, row_splits_dtype=dtypes.int64):
"""Constructs a constant RaggedTensor from a nested Python list.
Example:
```python
>>> ragged.constant([[1, 2], [3], [4, 5, 6]]).eval()
RaggedTensorValue(values=[1, 2, 3, 4, 5, 6], s... | a08da0da42a6b291671f33e52fc49c5c5a66e22c | 18,657 |
import argparse
def parse_args():
"""Parses command line arguments."""
parser = argparse.ArgumentParser(description='Install cert on device.')
parser.add_argument(
'-n', '--cert-name', default='dummycert', help='certificate name')
parser.add_argument(
'--overwrite', default=False, action='store_tr... | 94070336606f7ed68dfb479bcdd6ee79629c6888 | 18,658 |
def partition(lst, fn):
"""Partition lst by predicate.
- lst: list of items
- fn: function that returns True or False
Returns new list: [a, b], where `a` are items that passed fn test,
and `b` are items that failed fn test.
>>> def is_even(num):
... return num % ... | 94fc669744458952b75b225af489c440da98c740 | 18,659 |
def get_page(token, size):
"""Return portion of s3 backet objects."""
if token:
response = client.list_objects_v2(
Bucket=s3_bucket_name,
MaxKeys=size,
Prefix=s3_pbject_prefix,
ContinuationToken=token,
)
else:
response = client.list_obj... | 363e9566a09b4c73a4949a9cdc43c4706342058d | 18,660 |
import subprocess
import re
def get_segment_base_addr_by_proc_maps(pid:int, filename:str=None) -> dict:
"""Read /proc/pid/maps file to get base address. Return a dictionary obtaining keys: 'code',
'libc', 'ld', 'stack', 'heap', 'vdso'.
Args:
pid (int): Pid of process.
filename (str, optio... | ad5ef5461b55a627811641f542c46591cc4b1884 | 18,661 |
import click
def num_physical_shards_option(f):
"""
Function to parse/validate the --num-physical-shards CLI option to dirbs-db repartition.
:param f: obj
:return: options obj
"""
def callback(ctx, param, value):
if value is not None:
if value < 1 or value > 100:
... | f53eb8003533da0f8562456517110ad92beeea01 | 18,662 |
def _ls(method_name, ls_type, path=None, log_throwing=True):
"""
Private helper method shared by various API methods
:param method_name: calling method name
:param ls_type: the WLST return type requested
:param path: the path (default is the current path)
:param log_throwing: whether or not to l... | 39027d9963a2d621707f5934a440f671915ae7fb | 18,663 |
def serialize_input_str(tx, prevout_n, sequence, script_sig):
"""
Based on project: https://github.com/chaeplin/dashmnb.
"""
s = ['CTxIn(']
s.append('COutPoint(%s, %s)' % (tx, prevout_n))
s.append(', ')
if tx == '00' * 32 and prevout_n == 0xffffffff:
s.append('coinbase %s' % script_s... | c90f194e2627bc2b5aca61066b6febf1fa189bb6 | 18,664 |
def evidence():
"""
Confirm prohibition number and last name matches VIPS and
applicant business rules satisfied to submit evidence.
"""
if request.method == 'POST':
# invoke middleware functions
args = helper.middle_logic(business.is_okay_to_submit_evidence(),
... | f8314d33d86dfa6c0fff5ca7b007cd0a7aa8eeed | 18,665 |
def skop(p, rule="b3s23"):
"""Return a list of pairs (Pattern, minimum population) representing
the smallest known oscillators of the specified period in the given rule.
Assumes that the local installation of lifelib knows about said rule."""
rule = sanirule(rule)
rmod = import_module(f"..{aliases.g... | e2fb0de582d4e124f21066ee2c43deafa4c882e5 | 18,666 |
def relabel_nodes_with_contiguous_numbers(graph_nx, start= 0):
"""
Creates a shallow copy
"""
mapping= {n : (idx + start) for idx, n in enumerate(list(graph_nx.nodes()))}
return nx.relabel.relabel_nodes(graph_nx, mapping, copy= True), mapping | 457cb714179fe8b7d5536858e37807d0ebd60770 | 18,667 |
import yaml
def get_yaml_frontmatter(file):
"""
Get the yaml front matter and the contents of the given file-like object.
"""
line = file.readline()
if line != "---\n":
return (None, line + file.read())
frontmatter = []
for line in file:
if line == "---\n":
brea... | 741941e2b0ab2786eb2e808c9199844514fd713e | 18,668 |
def haversine(coordinate1, coordinate2):
"""
returns the distance between two
coordinates using the haversine formula
"""
lon1 = coordinate1['Longitude']
lat1 = coordinate1['Latitude']
lon2 = coordinate2['Longitude']
lat2 = coordinate2['Latitude']
lon1, lat1, lon2, lat2 = map(radia... | 533aa0fab71bfae78b7f465e11575e444a352987 | 18,669 |
def f1(R1,R2,R3):
""" f1 switching function """
R01,R02,R03 = 1.160, 1.160, 2.320
alpha1 = 1.0
rho1 = R1 - R01
rho2 = R2 - R02
rho3 = R3 - R03
return 0.5 * (1 - adf.tanh(0.5 * alpha1 * (3*rho1 - rho2 - rho3))) | 4ec1d5bf3160e3fa3bd817fc016dcc803ccf5c82 | 18,670 |
def getUser(client, attrs):
"""Get the user, create it as needed.
"""
try:
return client.assertedSearch("User [name='%s']" % attrs['name'])[0]
except icat.SearchResultError:
user = client.new("user")
initobj(user, attrs)
user.create()
return user | 97d084ee5eae18224c981a0348bbbb73457e8827 | 18,671 |
def _fn_pow_ ( self , b ) :
""" Power function: f = pow( a, b ) )
>>> f =
>>> a = f.pow ( b )
>>> a = f ** b
"""
return _fn_make_fun_ ( self ,
b ,
Ostap.MoreRooFit.Power ,
... | 843c793f061b33659220bf06d177a28971bb76b2 | 18,672 |
def funder_trans(params):
"""
:param params:
:return:
"""
if 6 > len(params):
LOG.error('funder_trans: Invalid params {}!'.format(params))
return None
selfpubkey = params[0]
otherpubkey = params[1]
addressFunding = params[2]
scriptFunding = params[3]
deposit = p... | a92b58ba23274c555e3caf17053c4c41feb5cf58 | 18,673 |
def get_replacements_by_guid(replacements_by_name):
"""Returns a lookup table that is by-guid rather than by-name."""
brush_lookup = BrushLookup.get()
def guid_or_name_to_guid(guid_or_name):
if guid_or_name in brush_lookup.guid_to_name:
return guid_or_name
elif guid_or_name in brush_lookup.name_to_... | 47d6e23999c3e414e6e182ad3db334aaa29234f4 | 18,674 |
from typing import Callable
def _make_divergence_numba_1d(bcs: Boundaries) -> Callable:
"""make a 1d divergence operator using numba compilation
Args:
dim (int): The number of support points for each axes
boundaries (:class:`~pde.grids.boundaries.axes.Boundaries`):
{ARG_BOUNDARIES... | f9298f0778b40d183714cfa50767e17b53258f47 | 18,675 |
def draw_predicted_rectangle(image_arr, y, x, half_height, half_width):
"""Draws a rectangle onto the image at the provided coordinates.
Args:
image_arr: Numpy array of the image.
y: y-coordinate of the rectangle (normalized to 0-1).
x: x-coordinate of the rectangle (normalized to 0-1).
... | b7b796135ee8da7cef103f6406cae19c2129ed59 | 18,676 |
from typing import Sequence
from typing import Optional
def my_max(seq: Sequence[ItemType]) -> Optional[ItemType]:
"""Максимальный элемент последовательности
Использует подход динамического программирования.
:param seq: последовательность
:type seq: Sequence[ItemType]
:return: максимальный элеме... | 43fbac6f57d2548f09eff145f58f8f5c9c7c8b92 | 18,677 |
def correct_pm0(ra, dec, pmra, pmdec, dist, vlsr=vlsr0, vx=0, vy=0, vz=0):
"""Corrects the proper motion for the speed of the Sun
Arguments:
ra - RA in deg
dec -- Declination in deg
pmra -- pm in RA in mas/yr
pmdec -- pm in declination in mas/yr
dist -- distance in kpc
... | 986ddf5d01ebacbd699fe80054be32e2e241d8b3 | 18,678 |
def clean_output_type_names(df: pd.DataFrame) -> pd.DataFrame:
"""Convenience function for cleaning up output type names
The `outputs_clean` dict is located in the defaults submodule
:param df: Input data frame to be cleaned up
:type df: pandas DataFrame
:return: DataFrame with output type names cle... | 5732d4b7279046d649cef32a40c0caacf3c368a9 | 18,679 |
def analyze_sentiment(input_text):
"""
Using VADER perform sentiment analysis on the given text
"""
sentiment_analyzer = SentimentIntensityAnalyzer()
sentiment_dict = sentiment_analyzer.polarity_scores(input_text)
return sentiment_dict | 9134a321970ef049580050431c88af53a0e80bc9 | 18,680 |
def get_free_header(filepath, needed_keys=(), original_name=None, observatory=None):
"""Return the complete unconditioned header dictionary of a reference file.
DOES NOT hijack warnings. DOES NOT verify checksums.
Original name is used to determine file type for web upload temporary files
which have... | f3f6460bc2af6a2005df0aeac009b2cbc602faa6 | 18,681 |
def clean_ice(options, args):
"""
Clean all orphaned VMs
"""
if len(args) < 2:
print "The iceage command requires a run name. See --help"
return 1
dbname = args[1]
cb = CloudInitD(options.database, db_name=dbname, log_level=options.loglevel, logdir=options.logdir, terminate=Fal... | fde1f35749ac40945f4225180c53d3cdc45e3067 | 18,682 |
def ADD_CIPD_FILE(api, pkg, platform, image, customization, success=True):
""" mock add cipd file to unpacked image step """
return ADD_FILE(
api, image, customization,
'[CACHE]\\Pkgs\\CIPDPkgs\\resolved-instance_id-of-latest----------' +
'\\{}\\{}\\*'.format(pkg, platform), success) | b6d5ed44c21bbb11c10e607ffe7773fb53909987 | 18,683 |
def row_to_columns(row):
"""Takes a row as a string and returns it as a list of columns."""
return [column for column in row.split() if column.strip() != ''] | 837477f2e9c160b93c339a9753e0598ac56c819e | 18,684 |
def circ_diagonal_mode_mat(bk):
"""Diagonal matrix of radial coefficients for all modes/wavenumbers.
Parameters
----------
bk : (M, N+1) numpy.ndarray
Vector containing values for all wavenumbers :math:`M` and modes up to
order :math:`N`
Returns
-------
Bk : (M, 2*N+1, 2*N+... | 52cc6154e692a10c714c2a4574b7fea5ea464f2c | 18,685 |
def log_updater(log, repetition, average_loss, optimization_time):
"""
Function to update the log object.
"""
index = repetition + 1
log["losses"] = log["losses"] + [[index, average_loss]]
log["times"] = log["times"] + [[index, optimization_time]]
return log | 6517437987693a275a4d8d66416d7b94d0049ec5 | 18,686 |
import queue
import threading
def execute_function_multithreaded(fn,
args_list,
block_until_all_done=True,
max_concurrent_executions=1000):
"""
Executes fn in multiple threads each with one set of the args... | fc7fdfee1cdf04f10d7f7cea25230a4fd361b88e | 18,687 |
def volume_encryption_metadata_get(context, volume_id, session=None):
"""Return the encryption metadata for a given volume."""
volume_ref = _volume_get(context, volume_id)
encryption_ref = volume_type_encryption_get(context,
volume_ref['volume_type_id'])
... | 21794d8d2ccdb5e68cd766cee035bfdc14d51ebc | 18,688 |
def test_shift_to_other_frame(hlwm, direction, frameindex, clients_per_frame):
"""
in a frame grid with 3 columns, where the middle column has 3 rows, we put
the focused window in the middle, and then invoke 'shift' with the given
'direction'. Then, it is checked that the window stays focused but now
... | afeb04d178bd729fccae01118bc59e8e7b0c09dc | 18,689 |
import subprocess
def parse_local_cpus():
"""Return information about available CPU's and cores in local system.
The information is gathered from ``lscpu`` command which besides the available CPUs informations, also returns
information about physical cores in the system, which is usefull for hyper threadi... | c03af3c9f73c828c842fafff3de3ee79787f639b | 18,690 |
def perform_tick(gamefield):
"""
Perfom a tick.
A tick is one round where each cell has a rule check
"""
tick_changes = get_tick_changes(gamefield)
activate_rules(gamefield, tick_changes)
return gamefield | 45b1f26f4040fd5a317eaf348ac6e919e249f3b5 | 18,691 |
import ctypes
def get_cairo_surface(pygame_surface):
""" Black magic. """
class Surface(ctypes.Structure):
_fields_ = [
(
'HEAD', ctypes.c_byte * object.__basicsize__),
(
'SDL_Surface', ctypes.c_void_p)]
class SDL_Surface(ctypes.Structure):
_fields_... | 2e8972c1c57a354527c0f3bb9b3700b80cebc45f | 18,692 |
import io
def string_out_table(dat, columns, caption, preferred_sizes=None, table_size="footnotesize"):
"""
- dat: (Dict String (Array String)), dict of arrays of data for the table
- columns: (Array String), the column names in desired order
- path: string, path to where to save the table
- capti... | c09d3878d39d23a313fa57da9c62f98e2f4fa26b | 18,693 |
def getCreationDate(pdf):
"""Return the creation date of a document."""
r = string_at(libc.pycpdf_getCreationDate(pdf.pdf)).decode()
checkerror()
return r | abede03b35ab87fd4532a8cf7348a992f7406df5 | 18,694 |
from typing import Annotated
async def fast_dependencies(
_: Annotated[int, Dependant(dep_without_delays)]
) -> Response:
"""An endpoint with dependencies that execute instantly"""
return Response() | e4983c262ae5a0327af5128941de8658881dbce7 | 18,695 |
def _pretty_print_bnode(bnode: BNode):
"""Print a blank node."""
return f'😶 {bnode}' | 6cf9f8e55315d8387c31708481751d9e584d497b | 18,696 |
import os
def resource_config():
"""
The path to the resource configuration file.
A file containing the name of the current host and all host containers in
the training.
Returns:
path (str): The absolute path to the resource config JSON
"""
return os.path.join(config(), 'resource... | ba7bc8e47e930bf213a54fcfc2d2d9aa21460200 | 18,697 |
import itertools
import numpy
def combine_div(range1, range2):
"""
Combiner for Divide operation.
>>> import gast as ast
>>> combine(Range(-1, 5), Range(3, 8), ast.Div())
Range(low=-1, high=1)
>>> combine(Range(-1, 5), Range(-5, -4), ast.Div())
Range(low=-2, high=0)
>>> combine(Range(... | 13fad21174e216fd2341d715eef85806ce65def0 | 18,698 |
def air(pos, res=None, shape=None, rowmajor=False, rad=None, ref=None):
"""Setups up an Airy system. See the build function for details."""
pos, res, shape, mid = validate(pos, res, shape, rowmajor)
if rad is None:
if pos.ndim != 2:
raise ValueError("Airy requires either rad or pos[2,2]")
w = angdist(mid[0]*d... | 79fc27074e43bd2f4d714e3d4fa7e6854d02ce14 | 18,699 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.