content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def run_batched_rollout(num_episodes, batched_env, agent):
"""
This function will generate a series of rollouts in a batched manner.
"""
num_envs = batched_env.num_envs
# This part can be left as is
observations = batched_env.batch_reset()
rewards = [0.0 for _ in range(num_envs)]
dones... | 5,303,500 |
def play_notes(scamp_note_list,include_percussion_layer=False):
"""
To play notes
@param scamp_note_list SCAMP notes list [ "Carnatic Note", ["Instrument", Volume_float, Duration_float], ...]
notes list can be obtained from cparser.parser_fi... | 5,303,501 |
def model_params_stats(model, param_dims=None):
"""Returns the model sparsity, weights count, and the count of weights in the sparse model.
Returns:
model_sparsity - the model weights sparsity (in percent)
params_cnt - the number of weights in the entire model (incl. zeros)
params_nnz_c... | 5,303,502 |
def get_connect_dict() -> Dict[str, Any]:
"""Read in database connection settings and return values as a
dictionary.
"""
with open("config.json", "r") as config_file:
config_dict = json.load(config_file)
if "database" in config_dict:
return config_dict["database"] | 5,303,503 |
def peak_transform_sd(data, tm):
"""
Using multiplier of standard-deviation.
data: N x L matrix, N profiles of length L
l = codon density signal profile sequence
tm = threshold multipler.
Returns individual profiles peak values (st) (Series object)
"""
N, L = data.shape
peak_mat... | 5,303,504 |
def unless(predicate, function, value):
"""Tests the final argument by passing it to the given predicate function. If
the predicate is not satisfied, the function will return the result of
calling the whenFalseFn function with the same argument. If the predicate
is satisfied, the argument is returned as... | 5,303,505 |
def getLogger():
"""Helper for retrieve the logger object
"""
return logging.getLogger(__name__) | 5,303,506 |
def pnchunk(darray, maxsize_4d=1000**2, sample_var="u", round_func=round, **kwargs):
""" Chunk `darray` in time while keeping each chunk's size roughly
around `maxsize_4d`. The default `maxsize_4d=1000**2` comes from
xarray's rule of thumb for chunking:
http://xarray.pydata.org/en/stable/dask.html#chun... | 5,303,507 |
def _create_fn(name, local_params: list[str] = [], lines: list[str] = ['pass'], globals: dict = {}):
"""
This function receives a name for the function, and returns a
function with the given locals and globals
"""
lines_as_str = '\n ' + '\n '.join(lines)
fn_text = f'def {name}({", ".join(... | 5,303,508 |
def _RecursiveAssembleBD(disk, owner, as_primary):
"""Activate a block device for an instance.
This is run on the primary and secondary nodes for an instance.
@note: this function is called recursively.
@type disk: L{objects.Disk}
@param disk: the disk we try to assemble
@type owner: str
@param owner: ... | 5,303,509 |
def reformat_raw_matrices(raw_matrix_files):
""" Convert txt format to sparse matrix format. Use csr format (compressed sparse row; triplet format).
:param raw_matrix_files: [txt] raw Hi-C matrices
"""
chr_raw_matrix_col_0 = np.array(raw_matrix_files[:, 0])
chr_raw_matrix_col_1 = np.array(raw_m... | 5,303,510 |
def get_all_folder_ids(service, parent_id=None, drive_id=False):
"""
Returns the id of the destination folder name in Google Drive
"""
parent_ids = []
# build query string
if parent_id:
query = 'mimeType = \'application/vnd.google-apps.folder\'' \
f' and \'{parent_id}\' in pa... | 5,303,511 |
def estimate_wrapped_gaussian_stddev(values, clip_lower, clip_upper):
"""Estimate the stddev of values assuming a wrapped normal distribution.
This function takes an input tensor `values` and estimates the sample standard
deviation of its values with the following assumptions:
1. The values are distributed a... | 5,303,512 |
def show():
"""This is the same as matplotlib's plt.show()"""
plt.show() | 5,303,513 |
def _convert_errno_parm(code_should_be):
""" Convert the code_should_be value to an integer
If code_should_be isn't an integer, then try to use
the code_should_be value as a errno "name" and extract
the errno value from the errno module.
"""
try:
code = int(code_should_be)
except Val... | 5,303,514 |
def find_new_host(RAM, vCPU):
"""
Select a random host from list of 3 hosts with available RAM and CPU
Availability is checked with 200 percent over-commitment.
"""
hosts = current.db(current.db.host.status == 1).select()
hosts = hosts.as_list(True,False)
count = 3
selected_hosts = []
... | 5,303,515 |
def unknownwordftb(word, loc, _lexicon):
"""Model 2 for French of the Stanford parser."""
sig = UNK
if ADVSUFFIX.search(word):
sig += "-ADV"
elif VERBSUFFIX.search(word):
sig += "-VB"
elif NOUNSUFFIX.search(word):
sig += "-NN"
if ADJSUFFIX.search(word):
sig += "-ADV"
if HASDIGIT.search(word):
sig += ... | 5,303,516 |
def patch_src_utils_logger_create_logger(mocker) -> MagicMock:
"""Patch the `src.utils.logger.create_logger` function."""
return mocker.patch("src.utils.logger.create_logger") | 5,303,517 |
def test_multi_bracket_validation_one_curly_true():
"""Test for multi-bracket validity"""
assert multi_bracket_validation('{{abc}}') is True | 5,303,518 |
def rectangleMesh(x_range=(0,1), y_range=(0,1), h=0.25):
"""
Input:
- x's range, (x_min, x_max)
- y's range, (y_min, y_max)
- h, mesh size, can be a tuple
Return the element matrix (NT, 3)
of the mesh a torch.meshgrid
"""
try:
hx, hy = h[0], h[1]
except:
hx, hy... | 5,303,519 |
def create_text(obj, filename, fieldname, database):
"""
Wrapper function that extracts a specific type of text
from the json obj, generates its important terms
and finally creates the graph of words associated
with the text.
"""
text = ''.join(item['text'] for item in obj[fieldname])
if... | 5,303,520 |
def group_notes_to_chords(notes: List[MidiNote], kernel=None) -> List[List[MidiNote]]:
"""
Groups the list of `MidiNote`s by time.
The return value maps time to a list of `MidiNote`s for that time.
"""
if kernel is None:
kernel = kernel_default
# Degenerate case: no notes -> n... | 5,303,521 |
def test_background_color_set(fx_asset):
"""Sets the background color."""
with Image(filename=str(fx_asset.join('croptest.png'))) as img:
with Color('red') as color:
img.background_color = color
assert img.background_color == color
img.background_color = 'green'
a... | 5,303,522 |
def parse_options():
"""Parses the command line options."""
try:
long_options = ["inputDataset=", "outputFile="]
opts, _ = getopt.getopt(sys.argv[1:], "d:o:", long_options)
except getopt.GetoptError as err:
print(str(err))
sys.exit(2)
inputDataset = "undefined"
outpu... | 5,303,523 |
def readVGIline(line,l1dic,l2dic,l3dic):
"""reads and interpretes one line of a VGI file."""
if line.startswith("{"):
#new level 1 heading
if level1 != "":
l2dic[level2] = l3dic
l1dic[level1] = l2dic
level1 = line.lstrip("{").rstrip("}\n")
level2 = ""
... | 5,303,524 |
def garch_fit_and_predict(series, ticker, horizon=1, p=1, q=1, o=1, print_series_name=False):
#p=1,q=1, o=1
#series=returns_df['spy']
#horizon=1
"""
This function takes a series of returns, and get back the GJR-GARCH time series fit for the conditional volatility,
using one shock, and a t-stud... | 5,303,525 |
def find_all_starts_regex(seq):
""" Find the starting index of all start codons in a lowercase seq """
regex_start = re.compile('atg')
# Find the indices of all start codons
starts = []
for match in regex_start.finditer(seq):
starts.append(match.start())
return tuple(starts) | 5,303,526 |
def get(isamAppliance, error_page, check_mode=False, force=False):
"""
Retrieving an error page
"""
return isamAppliance.invoke_get("Retrieving an error page", "{0}{1}".format(module_uri, error_page),
requires_modules=requires_modules, requires_version=requires_versio... | 5,303,527 |
def run_test(test_list, xml_report, timeout=60, verbosity=0):
"""
Runs a specific test suite or test case given with the fully qualified
test name and prints stdout.
Args:
test_list: This is the list of tests to run,filtered based on the
regex_input passed as an argument.
Example: --run_t... | 5,303,528 |
def edit_category(category_id):
"""
Edit category for database.
Inject all existing data from the category document into the form.
"""
the_category = mongo.db.categories.find_one({"_id": ObjectId(category_id)})
return render_template('editcategory.html',
cate... | 5,303,529 |
async def test_bot_local(mocker, test_repo):
"""
bot_local should execute a command
"""
channel_name = "doof_channel"
channel_id = "D1234567"
timezone = "America/New_York"
slack_token = "slack token"
github_token = "github_token"
npm_token = "npm_token"
repos_info = [test_repo]
... | 5,303,530 |
def import_transformer(module_name, trans_name):
"""This function needed, import a transformer for a given module and
appends it to the appropriate lists.
The code inside a module where a transformer is defined should be
standard Python code, which does not need any transformation.
So, ... | 5,303,531 |
def update_blurs(blur_o, blur_d, routing):
"""Signal when all the input fields are full (or at least visited?) and a routing option has been picked."""
if routing == 'slope':
c = 0
elif routing == 'balance':
c = 1
else:
c = 2
if (not blur_o) or (not blur_d):
return 0
... | 5,303,532 |
def index():
"""Basic home page."""
return render_template('hi.html') | 5,303,533 |
def create_tag_query(session, collection=None, document_ids=None, tag_buffer=TAG_BUFFER_SIZE):
"""
returns a query for tags with specified parameters
:param session: session to execute query on
:param collection: filter by collection
:param document_ids: filter by ids
:param tag_buffer: yield pe... | 5,303,534 |
def write_submission_output(dialog_turn_id_data, retrieval_scores, output_submission_format_path):
"""
Write the model_scores in
"""
submission_format_output=[]
for dialog in dialog_turn_id_data:
_dialog=[]
for turn_id in range(len(dialog['turn_info'])):
_turn=dialog['tur... | 5,303,535 |
def test_set_param(set_param):
"""Test setting a parameter value."""
assert par.TestParameter == 56 | 5,303,536 |
def collect_go_info(target, ctx, semantics, ide_info, ide_info_file, output_groups):
"""Updates Go-specific output groups, returns false if not a recognized Go target."""
sources = []
generated = []
# currently there's no Go Skylark API, with the only exception being proto_library targets
if ctx.ru... | 5,303,537 |
def _add(x):
"""
Add all elements of a list.
:param x: List to sum
:return: Sum of all elements in the input list
"""
return sum(x) | 5,303,538 |
def make_data_loader(dataset, batch_size=cfg.batch_size,
shuffle=True, sampler=None):
"""Make dataloader from dataset."""
data_loader = torch.utils.data.DataLoader(
dataset=dataset,
batch_size=batch_size,
shuffle=shuffle if sampler is None else False,
sampler... | 5,303,539 |
def test_isotope_subgraph_isomorphism_molecule_and_group():
"""
Checks that subgraph isomorphism works with enriched molecules and groups
"""
methanei = Molecule().from_adjacency_list("""
1 C u0 p0 c0 i13 {2,S} {3,S} {4,S} {5,S}
2 H u0 p0 c0 {1,S}
3 H u0 p0 c0 {1,S}
4 H u0 p0 c0 {1,S}
... | 5,303,540 |
def to_yaw_angle_quat(qxyzw):
"""
:param qxyzw: a list or numpy array
:return: a float angle [-pi, pi)
"""
qxyzw = qxyzw / np.linalg.norm(qxyzw)
if qxyzw[2] < 0:
theta = math.acos(-qxyzw[3])*2
else:
theta = math.acos(qxyzw[3])*2
if theta > math.pi:
theta -= 2*math.pi
return theta | 5,303,541 |
def get_lexicographic_dirname(dirpath: PathLike, first: bool = False) -> PathLike:
"""
Return the first (or last) subdirectory name ordered lexicographically.
:param dirpath: name of the base path whose subdirectories ought to be listed
:param first: whether the first or the last element should be retu... | 5,303,542 |
def test_delete_ipv6_ptr_recordset_does_not_exist_fails(shared_zone_test_context):
"""
Test deleting a nonexistant IPv6 PTR recordset returns not found
"""
client = shared_zone_test_context.ok_vinyldns_client
client.delete_recordset(shared_zone_test_context.ip6_reverse_zone['id'], '6666', status=404... | 5,303,543 |
async def serverinfo(msg):
"""
Show information about the Server / Guild this Command was used on.
:param msg: The Message invoking the Command
:return: The Bot's response
"""
guild_info = f'**Name**: {msg.guild.name}\n' \
f'**Region**: {msg.guild.region}\n' \
... | 5,303,544 |
def __populate_roles_table():
"""
populates the roles table with the contents of app_src.common.app_roles
Returns:
"""
for app_role_tuple in app_roles.get_app_role_tuples():
user_datastore.find_or_create_role(name=app_role_tuple[0], description=app_role_tuple[1])
user_datastore.com... | 5,303,545 |
def find_water_dept_details(lon, lat):
"""Get or create WaterParcel, WaterAccount for the given lon and lat."""
logger.debug('Getting Water Department data for %f, %f' % (lon, lat))
data = get_point_data(lon, lat)
if not data:
raise Exception('Could not find Water Department data for %f, %f' %
... | 5,303,546 |
def set_cache_context(cache_context):
""" Sets the cache context for this session. Raises an exception if there
was already a cache context associated.
"""
if cache_context is not None:
if getattr(cache_context_storage, "cache_context", None) is not None:
raise CacheException(
... | 5,303,547 |
def create_parser(prog_name):
"""
Creates the ArgumentParser object which parses the bash input and stored
the required parameters to perfrom the command on the
Transaction Family : Category
Args:
prog_name (str): Name of the Transaction Family
Returns:
type: Argume... | 5,303,548 |
def func_rst():
"""Summary line.
Extended description of function.
:param int arg1: Description of arg1
:param str arg2: Description of arg2
a line that extends to next line
:param arg3 : arg3 without any type
:param arg4: arg4 help content
:return: Description of return value
... | 5,303,549 |
def load_and_execute(filename):
"""Loads a network from file and runs it.
The network is loaded via the load-Method. Before running the network, it is
setup.
The networks runs until some input on the console is given
Args:
filename (str): The path to the .rtc file containing a network.
... | 5,303,550 |
def _assign_link_resids(res_link, match):
"""
Given a link at residue level (`res_link`) and
a dict (`match`) specifying to which resids
the res_link nodes map, create a correspondence
dict that maps the higher resolution nodes to
the resids specified in` match`. Each `res_link`
node by defi... | 5,303,551 |
def can_split_pairs(card_one, card_two):
"""
:param card_one: str - first card in hand.
:param card_two: str - second card in hand.
:return: bool - if the hand can be split into two pairs (i.e. cards are of the same value).
"""
if card_one == 'A' or card_two == 'A':
split_pairs = card_... | 5,303,552 |
def batch_random_samples_2_sides(left_trees, right_trees, labels, vectors, vector_lookup, batch_size, batch_type="original"):
"""Creates a generator that returns a tree in BFS order with each node
replaced by its vector embedding, and a child lookup table."""
batch_left_nodes, batch_left_children, = [],... | 5,303,553 |
def _get_pos_neg_loss(cls_loss, labels):
"""get pos neg loss"""
# cls_loss: [N, num_anchors, num_class]
# labels: [N, num_anchors]
batch_size = cls_loss.shape[0]
if cls_loss.shape[-1] == 1 or len(cls_loss.shape) == 2:
cls_pos_loss = (labels > 0).astype(cls_loss.dtype) * cls_loss.view(batch_s... | 5,303,554 |
def parse_args():
"""
Helper function parsing the command line options
@retval ArgumentParser
"""
parser = ArgumentParser(description="PyTorch distributed training launch "
"helper utilty that will spawn up "
"multiple d... | 5,303,555 |
def main():
"""Main function for the pre-commit hook."""
print("--- Running pre-commit hook ---")
# all staged files except delted files
files = subprocess.check_output(
"git diff --name-only --staged --diff-filter=d",
shell=True,
universal_newlines=True)
staged_files = [file... | 5,303,556 |
def filename_to_calurl(filename, suffix=None, source="irsa", verbose=False, check_suffix=True):
"""
"""
_, date, filtercode, ccd_, qid_, *suffix_ = os.path.basename(filename).split("_")
year,month,day = date[:4],date[4:6],date[6:]
suffix_ = "_".join(suffix_)
caltype = suffix_.split(".")[0]
... | 5,303,557 |
def invert(image: Image) -> Image:
"""Return an inverted copy of image; that is, an image that is a colour
negative of the original image.
>>> image = load_image(choose_file())
>>> inverted = invert(image)
>>> show(inverted)
"""
new_image = copy(image)
# Invert the intensities... | 5,303,558 |
def load(quantum_circuit_object, format: str):
"""Load external quantum assembly and quantum circuits from supported frameworks
into PennyLane templates.
.. note::
For more details on which formats are supported
please consult the corresponding plugin documentation:
https://pennyla... | 5,303,559 |
def constrained_sum_sample_nonneg(n, total):
"""
Integer partitioning of random similar size.
NOTE: Return a randomly chosen list of n nonnegative
integers summing to total. Each such list is
equally likely to occur.
ARGUMENTS:
... | 5,303,560 |
def make_batched_features_dataset(file_pattern,
batch_size,
features,
reader=core_readers.TFRecordDataset,
label_key=None,
reader_args=None,
... | 5,303,561 |
def iterate_lines(reader: Reader) -> Iterable[str]:
"""Returns an line iterator."""
it = reader.split("\n") if isinstance(reader, str) else reader
for line in it:
yield line.rstrip() | 5,303,562 |
def batch_update(docs, commit_each_doc=True):
"""
docs Format:
[
"Contract (DocType)": {
"create": [
{
"fieldname": value,
"fieldname": value,
"fieldname": value
}
],... | 5,303,563 |
def disk_util(directory):
""""
<Purpose>
Gets information about disk utilization, and free space.
<Arguments>
directory:
The directory to be queried. This can be a folder, or a drive root.
If set to None, then the current directory will be used.
<Exceptions>
EnvironmentError on bad... | 5,303,564 |
def calculateMinimumTemperature(frd, maj_met, min_met, time, psolid, psolidmap):
""" Minimum nodal temperature for a given PSOLID. """
minTemp = None
for element in psolidmap[psolid]:
temp = frd.results[maj_met][time][min_met][element]
if temp < minTemp or minTemp is None:
... | 5,303,565 |
def _read_wav_batch(dir_path: str, channel: str = 'm') -> MonoAudioBatch:
"""get a list of wav files in `dir_path` as mono float buffs
## Parameters:
- `dir_path`: path to directory containing batch
- `channel`: either 'l', 'r', 'm', 's'
## Notes:
Outputs are not normalized, so if the ori... | 5,303,566 |
def test_non_HP_pheno_to_anatomy(uberon):
"""If the input node is not valid, return an empty result list"""
k = KNode('xx:0011675', type=node_types.PHENOTYPIC_FEATURE)
results = uberon.get_anatomy_by_phenotype_graph( k )
assert len(results) == 0 | 5,303,567 |
def test_agegroup_pop(df):
"""
Compare the age group populations with manually computed
sums from the Excel files
"""
def assert_pop(df, sex, state_name, year, age_group):
return(df[sex][(df.StateName == state_name) &
(df.Year == year) &
(df.AgeG... | 5,303,568 |
def checkrows(sudoku):
"""
Checks if each row contains each value only once
"""
size = len(sudoku)
row_num = 0
for row in sudoku:
numbercontained = [False for x in range(size)]
for value in row:
# if placeholder, ignore it
if value in range(size):
... | 5,303,569 |
def list_is_unique(ls):
"""Check if every element in a list is unique
Parameters
----------
ls: list
Returns
-------
bool
"""
return len(ls) == len(set(ls)) | 5,303,570 |
def get_user_subreddit(chat_id, subreddit_title=None):
"""Get subreddit
Args:
chat_id (int): Telegram user id
subreddit_title (str): Subreddit
Yields:
db.Subreddit: Subreddits
"""
with session():
user = User.get(chat_id)
if user:
for subreddit in... | 5,303,571 |
def ordena_dets_num_adverq(traducao):
"""
Ordena determinantes, numerais e adverbios de quantidade consoante a LGP.
:param traducao: frase
:return:
"""
indice = 0
while indice < len(traducao):
valor = traducao[indice]
classe = valor[2]
# classe.startswith("Z")
if (classe.startswith("DP") or classe.s... | 5,303,572 |
def git_url_prompt(repo):
"""
Ask user if they'd like to add a remote URL to their git repo.
If yes, do it.
"""
print_red_bold("WARNING: If you back up to a public remote, make sure no sensitive files are included by modifying the .gitignore.")
if prompt_yes_no("Would you like to set a remote URL for this git rep... | 5,303,573 |
def get_max_value(obj_in):
"""
Returns the maximum allowed value for a specific object type.
:param obj_in: Object
:return int: Maximum value of object type
"""
# TODO: Generalise, and not rely on parsing a string
if obj_in.dtype == "uint8":
return 255
else:
return 2 ** i... | 5,303,574 |
def shard(digest: str, depth: int, width: int) -> str:
"""This creates a list of `depth` number of tokens with width `width` from the
first part of the id plus the remainder.
TODO examine Clojure's Blocks to see if there's some nicer style here.
"""
first = [digest[i * width:width * (i + 1)] for i in range... | 5,303,575 |
def register_dataset(ds: Dataset, url: str, client: FlaskClient) -> None:
"""Register `url` for dataset `ds` with `client`."""
ds_id = ds.id
url_encoded = url_encode(url)
client.patch(f"/v1/datasets/{ds_id}/urls/{url_encoded}") | 5,303,576 |
def bandit(
historical_info,
type=BANDIT_BLA_ROUTE_NAME,
rest_host=DEFAULT_HOST,
rest_port=DEFAULT_PORT,
testapp=None,
**kwargs
):
"""Hit the rest endpoint for allocating arms of a bandit given arms already sampled (historical info)."""
endpoint = ALL_REST... | 5,303,577 |
def _unify_time_coordinates(cubes):
"""Make sure all cubes' share the same time coordinate.
This function extracts the date information from the cube and
reconstructs the time coordinate, resetting the actual dates to the
15th of the month or 1st of july for yearly data (consistent with
`regrid_tim... | 5,303,578 |
def mark_branch(tree, target_leafs):
"""Mark in the tree the common ancestor of the species in target_leafs"""
tree = deepcopy(tree)
targets_in_tree = [
target
for target in target_leafs
if target in [leaf.name for leaf in tree.get_terminals()]
]
if len(targets_in_tree) == 1:... | 5,303,579 |
def handle_msg(context):
"""关键字响应\n
目前设定了PK, 集资, 补档, 以及关键字撤回和重复刷屏禁言.
"""
if (context['user_id'] != context['self_id']
and context['message_type'] == 'group'):
check_group_list = setting.group_id() + setting.dev_group_id()
for pk_data in setting.pk_datas():
if time... | 5,303,580 |
def GetEigenVectorCentr(*args):
"""
GetEigenVectorCentr(PUNGraph const & Graph, TIntFltH & NIdEigenH, double const & Eps=1e-4, int const & MaxIter=100)
Parameters:
Graph: PUNGraph const &
NIdEigenH: TIntFltH &
Eps: double const &
MaxIter: int const &
GetEigenVectorCentr(P... | 5,303,581 |
def run_random(connection, test_case, all_preds, nr_sums, timeout_s):
""" Run simple random generation baseline.
Args:
connection: connection to database
test_case: summarize for this test case
all_preds: all available predicates
nr_sums: generate so many summaries
t... | 5,303,582 |
def load_cifar_10_data(data_dir, nparts=6, negatives=False):
"""
Return train_data, train_filenames, train_labels, test_data, test_filenames, test_labels
"""
# training data
cifar_train_data = None
cifar_train_filenames = []
cifar_train_labels = []
for i in range(1, nparts+1):
... | 5,303,583 |
def test_objects():
"""For coffin, global objects can be registered.
"""
from coffin.common import env
# Jinja2 global objects, loaded from a Coffin library
assert env.from_string('{{ hello("John") }}').render() == 'Hello John' | 5,303,584 |
def read_queue(project):
"""Read queue csv file
Args:
project (string): project, i.e. CMIP5/CMIP6
Returns:
rows (dict): - prsenting each record stored in the file
dids (set): dataset_ids stored in the file
"""
rows={}
dids=set()
# open csv file and read data in dict... | 5,303,585 |
def normalise_json_testdata(obj, ignore):
"""
Various normalisations of the JSON sourced test data:
- make it immutable to avoid accidental manipulation of baseline values
- remove any keys we want to ignore
- lowercase any values with a key of "id" (since we always lowercase the external IDs in the... | 5,303,586 |
def get_index(ipfs, domain, pin):
""" Get the current index using ./cur_cgt_index_hash or create one if not existent """
if os.path.exists(__CUR_CGT_INDEX_FILE_NAME__):
print("Loading existing index hash from ", __CUR_CGT_INDEX_FILE_NAME__)
with open(__CUR_CGT_INDEX_FILE_NAME__) as f:
... | 5,303,587 |
def RecordFormatFromFilePattern(file_pattern):
"""Return the record format string for a Lingvo file pattern.
Lingvo file patterns take the form of:
tfrecord:/path/to/bar -> tfrecord is the record_format.
This function takes a file pattern and returns a string indicating
which format the filepattern implie... | 5,303,588 |
def save_data(df: pd.DataFrame, database_filename: str):
""" Save clean DataFrame df to a SQLite database
Args:
df: DataFrame. DataFrame of cleaned data to be saved to a Database.
database_filename: str. File path for the SQLite Database
Returns:
None
"""
# Create engine instance
... | 5,303,589 |
def compute_transpose(x):
""" given a matrix, computes the transpose """
xt=[([0]*len(x)) for k in x[0]]
for i, x_row in enumerate(x):
for j, b in enumerate(x_row):
xt[j][i]=x[i][j]
return xt | 5,303,590 |
def test_list_generators_cli():
"""
Test list-generators command.
"""
runner = CliRunner()
result = runner.invoke(textx, ['list-generators'])
assert result.exit_code == 0
assert 'flow-dsl -> PlantUML' in result.output
assert 'flow-codegen[1.0.0]' in result.output | 5,303,591 |
def update_bullets(game_settings, screen, stats, sb, ship, aliens, bullets):
"""Uuendage kuulide asukohta ja eemaldage vanad kuulid"""
bullets.update()
for bullet in bullets.copy():
if bullet.rect.bottom <= 0:
bullets.remove(bullet)
check_bullet_alien_collisions(game_settings, screen... | 5,303,592 |
def make_psf_map(psf, pointing, geom, exposure_map=None):
"""Make a psf map for a single observation
Expected axes : rad and true energy in this specific order
The name of the rad MapAxis is expected to be 'rad'
Parameters
----------
psf : `~gammapy.irf.PSF3D`
the PSF IRF
pointing ... | 5,303,593 |
def task_compile() -> Iterator[Dict[str, Any]]:
"""Add or update requirements using *.in files as input.
Run pip-compile to detect changes in source files and add them to *.txt
files. This will not upgrade versions if it is not necessary, but passing
upgrade=True will upgrade all dependencies.
"""
... | 5,303,594 |
def test_get_and_modify_user(cbcsdk_mock):
"""Tests retrieving and modifying a user."""
def check_put(url, body, **kwargs):
assert body['login_id'] == 6942
assert body['login_name'] == 'jsheridan@babylon5.com'
assert body['email'] == 'jsheridan@zhadum.net'
return None
cbcsdk... | 5,303,595 |
def sort_articles(articles):
"""Sort articles based on score.
:param articles:
:return:
"""
if len(articles) < 1:
raise ValueError('No news')
sorted_articles = sorted(articles, key=lambda x: x.score, reverse=True)
return sorted_articles | 5,303,596 |
def get_interface_sequence(ip_addr_output):
"""
output interface sequence paired to eth0, None on not found
ip_addr_output will be like:
1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue state UNKNOWN group default qlen 1000
link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00
inet 127.0.0.1/8 ... | 5,303,597 |
def test_zero_compaction() -> None:
"""Test compaction coefficient of zero."""
dz_0 = np.full(100, 1.0)
phi_0 = np.full(100, 0.5)
phi_1 = compact(dz_0, phi_0, porosity_max=0.5, c=0.0)
assert np.all(phi_1 == approx(phi_0)) | 5,303,598 |
def body_id(b_name):
"""Return the body id"""
return bodies['id'][where(bodies['name'] == b_name.encode())] | 5,303,599 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.