content stringlengths 35 416k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
import asyncio
def torch(torch, tensor, awaitable=False): # pragma: no cover
"""PyTorch integration, providing GPU→CPU async transfer, usable as `await sn.torch(torch, x, True)` or `sn.handle(sn.torch(torch, x))`. (Since PyTorch doesn't make this easy.)"""
if not isinstance(tensor, torch.Tensor) or not tensor... | 7fb57691666bdca00de4717f90817120e5b8bef0 | 679,363 |
def update_counter(galini, name, amount, initial_value=0.0):
"""Update a counter, creating the gauge if it does not exists."""
telemetry = galini.telemetry
counter = telemetry.get_counter(name)
if counter is None:
counter = telemetry.create_counter(name, initial_value)
return counter.increme... | a0f325e798b84362596fc6662b295ad0ee378d22 | 679,364 |
def optional(cls):
"""
Returns a Converter for a type which can optionally be missing (represented by None).
"""
def converter(string_or_instance):
if string_or_instance is None or isinstance(string_or_instance, cls):
return string_or_instance
if string_or_instance.strip() ... | c76dd740a74d7aa0ef2dabd290399f0c2cd65825 | 679,366 |
def extract_name(in_line: str) -> str:
"""
Extracts the name from the type construct. Information that is not needed will be removed
such as the stereotype.
"""
types = {'package', 'class', 'abstract', 'interface',
'enum', 'abstract class', 'entity'}
process_type: str = ''
for i... | ff115509c58a83df139a83cdc0473c2841c7dc5a | 679,367 |
import math
def angle_between(point_1, point_2):
"""Compute the angle between two points and return it as an int."""
x_1, y_1 = point_1
x_2, y_2 = point_2
inner_product = x_1 * x_2 + y_1 * y_2
len_1 = math.hypot(x_1, y_1)
len_2 = math.hypot(x_2, y_2)
return math.acos(inner_product / (le... | 22a071d3392371ce5a8633f9e5dfaeb714ce471c | 679,368 |
from typing import Any
def bytes_(s: Any, encoding: str = 'utf-8', errors: str = 'strict') -> Any:
"""Utility to ensure binary-like usability.
If s is type str or int, return s.encode(encoding, errors),
otherwise return s as it is."""
if isinstance(s, int):
s = str(s)
if isinstance(s, str... | f142e3828f4cd386e225d0a575cf0ad9052ed60a | 679,369 |
from pathlib import Path
def N2_BG_exclusion_list(N2_BG_file):
"""takes a file and filters/replaces it depending on occurence in exclusion list mapper"""
if not (isinstance(N2_BG_file, str) or isinstance(N2_BG_file, Path)):
return None
else:
N2_BG_file = Path(N2_BG_file)
# _topdir = "/... | 10f246076a7ad3a410b845da5dd0d2c1c1c063dd | 679,370 |
import csv
import os
def write_dictionary_to_csv(inputList, outputFilename):
"""
This function...
:param inputList:
:param outputFilename:
:return:
"""
csvFile = open(outputFilename, "w")
dWriter = csv.DictWriter(
csvFile,
["LabelCode", "LabelName", "Volume_mm3", "Fil... | 3b17fe06e6d703c3a24e208930e185e8fa58813b | 679,371 |
def get_stopwords():
"""
loads a list of very common "stopwords" to ignore in listing keywords
"""
with open('resources/stopwords.txt') as f:
return set([line.strip() for line in f.readlines()]) | 50026f8406c30bdc14d6ed10b76e84b8c1c895ba | 679,372 |
import os
def isvalidPath(location):
""" Check if file/directory exists """
if os.path.exists(location):
return True
return False | 1d4816091a9c2a09dd822d598c519278ca8972eb | 679,373 |
def _info_from_first_line(line):
"""
Gets the info from the first line of landmarks' txt. The format of the file
is hardcoded for now, e.g. the expected numbers and fields.
It returns a dictionary, which enables future extensions of what is returned.
Along with the functions _from_line_to_vec, from... | b38f19b0bfcca7de6661e1ea929a5ef8017837ad | 679,374 |
def calcBuondingBoxV(listIndex, refTarget):
"""
This function calculates the boundingbox and returns the verts in the bound
"""
offset = listIndex[0]
maxx = refTarget[offset]
minx = refTarget[offset]
maxy = refTarget[offset]
miny = refTarget[offset]
maxz = refTarget[offset]
minz... | f40170cc1dc33a70a0c19c5cae350800b42f4d5e | 679,375 |
def database_test_url() -> str:
"""
generate in memory sqlite db connect url for test purposes
:return: url string for test database connection
"""
return "sqlite+aiosqlite://?cache=shared" | 6aab90ad759ee632ce83e5f110f6e4decaf13aa9 | 679,376 |
def get_demand_share_lhs_and_rhs_loc_tech_carriers(backend_model, group_name, carrier):
"""
Returns
-------
(lhs_loc_tech_carriers, rhs_loc_tech_carriers):
lhs are the supply technologies, rhs are the demand technologies
"""
lhs_loc_techs = getattr(
backend_model,
'group_... | f2b7d149c840d2a0981f99d41c7506c43834226c | 679,377 |
def apply_real_mask(tf_rep, mask, dim=-2):
""" Applies a real-valued mask to a real-valued representation.
It corresponds to ReIm mask in [1].
Args:
tf_rep (:class:`torch.Tensor`): The time frequency representation to
apply the mask to.
mask (:class:`torch.Tensor`): The real-va... | b522aa44858b5785ebe3c750217f5be1c65f4d1d | 679,378 |
import torch
def add_params(size, name=""):
""" Adds parameters to the model.
Inputs:
model (dy.ParameterCollection): The parameter collection for the model.
size (tuple of int): The size to create.
name (str, optional): The name of the parameters.
"""
if len(size) == 1:
... | 6a04a1733ab61b8237b19d666931bb7daf84cd11 | 679,379 |
def subtract(a: int, b, c=5, d=7., e=None):
"""Some cool subtraction.
Parameters
----------
a : int
This is the first complicated parameter
super complicated
b : int, optional
e : int, optional
"""
if e is None:
e = 0
return a - b - c - d - e | c0ffb23e1e79240e64091cf9d7014cac8e32ae2b | 679,380 |
def compute_baselines(returns, probs, env_names):
"""Compute baseline for samples."""
baseline_dict = {}
for ret, p, name in zip(returns, probs, env_names):
if name not in baseline_dict:
baseline_dict[name] = ret * p
else:
baseline_dict[name] += ret * p
return baseline_dict | 2cbec91a5065c655cfc00e22f9c24ad8db91da60 | 679,381 |
import decimal
def format_amount(amount, format="%f"):
"""Replace the thousands separator from '.' to ','
"""
if isinstance(amount, float) or isinstance(amount, decimal.Decimal):
amount = (format % amount).replace('.', ',')
return amount | 8781441bce24e500711b10ff6e6cf169ea36760a | 679,382 |
import itertools
def generate_build_variants( build_descs_by_axis ):
"""Returns a list of BuildDesc generated for the partial BuildDesc for each axis."""
axis_names = build_descs_by_axis.keys()
build_descs = []
for axis_name, axis_build_descs in build_descs_by_axis.items():
if len(build_descs)... | 946edeba56a2a7957fc89c2344b52ebe723e880a | 679,383 |
def class_suffix(slope, cellsize, suffix=''):
"""" Generate LAS classification suffix """
return '%sl2d_s%sc%s.las' % (suffix, slope, cellsize) | 0f845cc137d429d8126942abcbc4a90610159c1b | 679,385 |
from pathlib import Path
def _get_aparc(fs_subject_dir):
"""Fetch infant_recon_all's aparc+aseg"""
aparc = Path(fs_subject_dir) / "mri" / "aparc+aseg.mgz"
if not aparc.exists():
raise FileNotFoundError("Could not find aparc.")
return str(aparc) | 47355a86e349eedb389a8354be6a3e4eb3f1e5ca | 679,386 |
def read_label_file(label_file):
"""
Args:
label_file:
"address"
"book"
...
Returns:
label list
"""
return open(label_file).readlines() | fe0c9c216d518436175fc8700673413c95bb8b62 | 679,387 |
def get_longest_repeating_substring(input_string: str) -> str:
"""
Algorithm for getting the longest repeating substring from a string
Complexity --> O(N)
:param input_string: str
:return longest_substring: str
"""
longest_substring = ""
local_longest_substring = input_string[0]
... | dba6251b500d7d1cbe76af4052dd183c1769f579 | 679,388 |
def count_mol_weights(mol_weights):
"""
Count the number of weights in each bin, and
return a list of counts.
"""
counts = [0 for _ in range(9)]
for mol_weight in mol_weights:
if mol_weight < 250:
counts[0] += 1
elif 250 <= mol_weight < 300:
counts[1... | 59e1e79aba9a07843091364c34b56e59a5a69106 | 679,389 |
import bisect
def bottom_values(values, period=None, num=1):
"""Returns list of bottom num items.
:param values: list of values to iterate and compute stat.
:param period: (optional) # of values included in computation.
* None - includes all values in computation.
:param num: the num in the b... | 7eb80b58ed2cf7c7c005417414aedc66c046f6c9 | 679,390 |
def safemax(data, default=0):
""" Return maximum of array with default value for empty array
Args:
data (array or list ): data to return the maximum
default (obj): default value
Returns:
object: maximum value in the array or the default value
"""
if isinstance(data, list):
... | 1d5a2ea3a6a498cb7be03ec54c3bffef75903444 | 679,391 |
def _linked_environments(package, environments):
""""
Determine what package is linked to which environments
This function is wrapped by :py:func:`linked_environments` to provide a consistent API.
Please call :py:func:`linked_environments` instead.
"""
return tuple(env for env in environments i... | 6a951c7a68a6375b49401a637e760c7d17430730 | 679,392 |
import time
def year():
"""Returns the current year (2005, 2006, etc)"""
return int(time.strftime("%Y", time.gmtime())) | c6f26635543712155d317cf433a8ecca7aa6e1d0 | 679,393 |
import tqdm
def _pbar(x):
"""Create a tqdm progress bar"""
return tqdm.tqdm(x, ascii=True, unit=" scans") | 182ec56e05a5b7f845320add429e01065f952fcd | 679,394 |
def is_yaml(file_path: str) -> bool:
"""Returns True if file_path is YAML, else False
Args:
file_path: Path to YAML file.
Returns:
True if is yaml, else False.
"""
if file_path.endswith("yaml") or file_path.endswith("yml"):
return True
return False | a466e019aa2f59adb3412d2424c1e7e6bb8b2317 | 679,395 |
def get_sig_end_dist(ds):
"""
Obtained directly from GLAH14 data
"""
# calculate the bias between reference range to the bottom of received wf
ref_range_bias = ds.rec_wf_sample_dist.max(dim="rec_bin") - ds.ref_range
return ds.sig_end_offset + ds.ref_range + ref_range_bias | 68899d2bb6f217cb9cf96c5f509484f39bedf741 | 679,396 |
def generate_random(seen, r):
"""
keep generating random numbers
"""
if not seen:
num = 0
else:
num = max(seen) + 1
seen.add(num)
return num, seen | a997bc8aa978cb3f0c15a527ca8a846a1dab5ce1 | 679,397 |
import hashlib
def sha256_file(filename):
"""Calculate sha256 hash of file
"""
buf_size = 65536 # lets read stuff in 64kb chunks!
sha256 = hashlib.sha256()
with open(filename, 'rb') as f:
while True:
data = f.read(buf_size)
if not data:
break
... | dd5da4635281d1742cf864e39eea831920da4359 | 679,398 |
from bisect import bisect_right
def slices_find(slices, start_end):
"""Return the index of the slice that contains a given slice, or -1."""
slice_r = bisect_right(slices, start_end)
start, end = start_end
if slice_r > 0:
(l, r) = slices[slice_r - 1]
if l <= start and end <= r:
... | 3d3bf24abc54a718c8331e2ec384f1c366368cd3 | 679,399 |
def from_octal(oct_data: str, delimiter: str = " ") -> bytes:
"""Converts octal string into bytes object"""
if delimiter == "":
data = [oct_data[i:i+3] for i in range(0, len(oct_data), 3)]
else:
data = oct_data.split(delimiter)
return bytes([int(byte, 8) for byte in data]) | 22cd8237247f737f03ee49f193ed1e86e8d24a3e | 679,400 |
import re
def extract_thread_list(trace_data):
"""Removes the thread list from the given trace data.
Args:
trace_data: The raw trace data (before decompression).
Returns:
A tuple containing the trace data and a map of thread ids to thread names.
"""
threads = {}
parts = re.split('USER +PID +PPID ... | 1e297e65bf33b733fe6453a62e124449e8a6af11 | 679,401 |
def automorphic(number) -> bool:
"""
Takes a Number as input and check whether the number is automorphic or not and return True or false accordingly.
"""
square = str(number**2)
return True if str(number) in square else False | 2b3b9dc4198b2d62e5a93eca67cb1bdb5575044f | 679,403 |
def getDuration(timesarr):
"""
gets the duration of the input time array
:param timesarr: array of times as returned by readCSV
:returns: Duration for which there are times
"""
dur = max(timesarr)-min(timesarr)
return dur | 379e236713902d506856296734b64fde0623aa17 | 679,404 |
import unicodedata
def strip_accents(clean_text):
"""
Args:
clean_text: (str) The cleaned text.
Returns:
Returns a string without the accents.
"""
# clean_text = " ".join(clean_up_punctuation_main(clean_text))
return "".join(c for c in unicodedata.normalize('NFD', clean_text)... | 23ce26f0ee9ce4075a2944233559f1b72ab267d7 | 679,405 |
def predict_url(*args):
"""
Function to make prediction on a URL
"""
message = 'Not implemented in the model (predict_url)'
return message | 973b2f839d5f7ff52d03ec89f6ec75ef24dca10c | 679,407 |
import encodings
def dname2idn(name):
"""Converts canonic domain name in IDN format to unicode string
:param name: (string) domain name
:returns: (unicode string) domain name
"""
return '.'.join([encodings.idna.ToUnicode(a) for a in name.split('.')]) | 2b12b6d0e4b553b7408f0f3787372897371ba54e | 679,408 |
def expand_columns_old(df, columns, drop=True):
"""
Expand a column into word-based columns
:param df:
:param column:
:param drop:
:return:
"""
if isinstance(columns, str):
columns = [columns]
for c in columns:
old_columns = df.columns
new_columns = []
... | 71bc4ef86008cbf2255d8a5d5e0b2aa809f8d6b1 | 679,409 |
def landsat_ts_norm_diff(collection, bands=['Green', 'SWIR1'], threshold=0):
"""Computes a normalized difference index based on a Landsat timeseries.
Args:
collection (ee.ImageCollection): A Landsat timeseries.
bands (list, optional): The bands to use for computing normalized difference. Defaul... | a9026927a69a9c7b0a5551e9f9d71799f50d9115 | 679,410 |
def get_table_name(table_names):
"""
To generate dictinory containing source and target table names.
Args:
table_names(dic):Dictinory with source table name as key and target
table name as value.
Returns:
Returns a dictionary contains source table and target table names
... | f394641c972ca3d22edd1e005fff5eb392fac29d | 679,411 |
import json
def fromJSON(json_file):
"""load json with utf8 encoding"""
with open(str(json_file),"r", encoding='utf8') as fp:
return json.load(fp) | f18a272387609a5eb7f6eb7a04248f55c2466db0 | 679,412 |
def RemoveDuplicatedRows_GetCorLen(data_Comp, dir1="N"):
"""
data_Comp = Data with both North and South data
dir1 = "N" or "S"
returns:
dat_Uniq: Cleaned data,
Duplicated_dat: Data showing duplicated rows,
IsTheDataCleaningCorrect : True, if the cleaning is correct,
Ro... | e4e2d497ada3158ca5223d3832a04e9a72cccbdc | 679,413 |
from typing import Any
from typing import Union
from typing import Tuple
def scale(item: Any, multiply: Union[float, int]=1, divide: Union[float, int]=1) -> Tuple[Any, None]:
"""
AUTHORS:
--------
:author: Samuel Westlake
DESCRIPTION:
------------
Scale an item
PARAMETERS:
----... | d975a725ee0e4bbe03ec59f40421c33e1ad3d867 | 679,414 |
def get_node_attributes(G, name):
"""Get node attributes from graph
Parameters
----------
G : NetworkX Graph
name : string
Attribute name
Returns
-------
Dictionary of attributes keyed by node.
Examples
--------
>>> G=nx.Graph()
>>> G.add_nodes_from([1,2,3],col... | fe1a559179e11feeee532ad7e2c737f40190169e | 679,415 |
def calc_downsample(w, h, target=400):
"""Calculate downsampling value."""
if w > h:
return h / target
elif h >= w:
return w / target | c0c8f5296b03750bdde25b0bcc0350d69017b0b6 | 679,417 |
import sys
def get_to_num() -> int:
"""
Read and return to_num value from argv if specified,
return 100 otherwise.
"""
to_num = 100
if len(sys.argv) >= 2:
to_num = int(sys.argv[1])
return to_num | 59c4180746ce34e4241113b3fd12a2a04301cdc4 | 679,418 |
import numpy as np
def compute_similarity_transform(X, Y, compute_optimal_scale=False):
"""
A port of MATLAB's `procrustes` function to Numpy.
Adapted from http://stackoverflow.com/a/18927641/1884420
Args
X: array NxM of targets, with N number of points and M point dimensionality
Y: array... | 800e27996ff7588dae15990f7c0f5dcdcb14f58f | 679,419 |
import re
def camel_case_split(text: str) -> list:
"""camel_case_split splits strings if they're in CamelCase and need to be not Camel Case.
Args:
str (str): The target string to be split.
Returns:
list: A list of the words split up on account of being Camel Cased.
"""
return re.... | bcbac4f7ba01d133b84fb1275743bea278d64c4c | 679,420 |
def hex_to_bytes(data):
"""Convert an hex string to bytes"""
return bytes.fromhex(data) | aa9f7d5c6d66bccc5fb5bf7ba51bcc075b8580bc | 679,421 |
def concatenate_dicts(*dicts):
"""Concatenate multiple directories into one"""
merged = []
for d in dicts:
merged += list(d.items())
return dict(merged) | def88fc8a8d35856011ed9836e4c545cdccd72af | 679,423 |
import itertools
import collections
def _merge_dicts(dics, container=dict):
"""
:param dics: [<dict/-like object must not have same keys each other>]
:param container: callble to make a container object
:return: <container> object
>>> _merge_dicts(({}, ))
{}
>>> _merge_dicts(({'a': 1}, ))... | 46d62e7a139594abbe0c02b95d4f6cb856d65ad8 | 679,424 |
import textwrap
def multiline_fix(s):
"""Remove indentation from a multi-line string."""
return textwrap.dedent(s).lstrip() | 9cb964eb88ebcaadc00acc222d174d6a320c44cf | 679,426 |
import unicodedata
import re
def slugify(string):
"""Slugify a string.
Args:
string: A string.
Returns:
A 'slug' of the string suitable for URLs. Retains non-ascii
characters.
"""
string = unicodedata.normalize("NFKC", string)
# remove all non-word characters (except... | 48b0575e45b6cd4e750b031cffa914701c5938b0 | 679,427 |
def oc2_pair(actuator_nsid, action_name, target_name):
"""Decorator for your Consumer/Actuator functions.
Use on functions you implement when inheriting
from OpenC2CmdDispatchBase.
Example:
class MyDispatch(OOpenC2CmdDispatchBase):
...
@oc2_pair('slpf', 'deny', 'ipv4_connection')
... | 211c8e22cb052a0117f161f4b90265744023a86c | 679,428 |
def create_diff_Top_Depth_Real_v_predBy_NN1thick(df_new3):
"""
Takes in:
Returns:
"""
df_new3["diff_Top_Depth_Real_v_predBy_NN1thick"] = (
df_new3["TopTarget_DEPTH"] - df_new3["topTarget_Depth_predBy_NN1thick"]
)
return df_new3 | 096c85ec6a2a40315f92912c04718c28d5e5112a | 679,429 |
def get_cus_tile_info(input_x1, input_x2, input_x3):
"""get_cus_tile_info"""
_, mo, _, _ = input_x1.shape
no, _, _, _ = input_x2.shape
c0 = input_x1.shape[-1]
diag_outer = 128 // c0
input_shape = (tuple(input_x1.shape), input_x1.dtype, tuple(input_x2.shape), input_x2.dtype,
tu... | 397cc9b935ad96e7378b3b47ea3e4e1e5c8e1210 | 679,430 |
def host_scan_cycle() -> list:
"""host_scan_cycle() -> list
(internal)
"""
return list() | 893c91a77f9a9a6e40b7e45bf1bb43ac6a25af3b | 679,431 |
def round_next (x,step):
"""Rounds x up or down to the next multiple of step."""
if step == 0: return x
return round(x/step)*step | 212687037567b37f6f62a9dbc3427fe05045476f | 679,432 |
def read_seats(file_location):
"""Read file the code
"""
seats = []
seat_map = open(file_location, 'r').read().split('\n')
for line in seat_map:
if line == '':
continue
seats.append(list(line))
return seats | 239704f19e39b0c715eac9a0bdce013f247c9d55 | 679,433 |
def trim_seq(seq):
"""
Remove 'N's and non-ATCG from beginning and ends
"""
good = ['A','T','C','G']
seq = seq.upper()
n = len(seq)
i = 0
while i < n and seq[i] not in good: i += 1
j = len(seq)-1
while j >= 0 and seq[j] not in good: j -= 1
return seq[i:j+1] | d9fc891c9bef536ad94bcd58eafa212dc40387c8 | 679,434 |
def _extract_patch(img_b, coord, patch_size):
""" Extract a single patch """
x_start = int(coord[0])
x_end = x_start + int(patch_size[0])
y_start = int(coord[1])
y_end = y_start + int(patch_size[1])
patch = img_b[:, x_start:x_end, y_start:y_end]
return patch | 594985f32f366a2613302611868efd7a75582d6c | 679,435 |
def analytical_means(burden, trans, death, trans_non_c, death_non_c, p_compliance=.95,
p_observed=.80):
"""Return the balance population sizes and the approximated mean number of observations in one year
Returns
-------
list
"""
p_c_neg = 1 - p_compliance
# Compute th... | 0a14e66fa1cc1a79640bf80d7d83f26617861b5b | 679,436 |
def none_reporter():
"""Dummy class for no reporting job's."""
return None | a66239c56cc3c02ca77337a935eac2626403af54 | 679,437 |
def validates(entity):
""" Sets Entity to which the validation will run """
def _validates(validation):
validation.validates = entity
return validation
return _validates | 504fc5776ca76448fc4a3391cdd3978245b83a21 | 679,438 |
def do_sql(conn, sql, *vals):
"""
issue an sql query on conn
"""
# print(sql, vals)
return conn.execute(sql, vals) | 1c14cc6e411cda5080bed7ef51e001b4eb1f6d02 | 679,439 |
def get_status(): # no test needed!
"""Applies route for showing that the server is on.
This route fnx is a get request that when the address
http://vcm-23126.vm.duke.edu/ is inputted online, returns a
jsonified string that says "Server is on".
:param: N/A
:returns: json string that the serv... | be7c07726726e44712cd49f8885f80be9f8d0cae | 679,440 |
import numpy
def add_additional_features_to_connections(connections, components_per_node, original_input_dim,
num_features_appended_to_input):
""" Computes a new connections matrix, which extends a regular connection matrix by providing connections to
an auxiliary in... | 52a287e1f8c499e46539831b02f5310d4c77c657 | 679,441 |
from typing import Iterable
def sigma(a: Iterable[int]) -> int:
"""Returns sum of the list of int"""
return sum(a) | e9e55dd4968cd6c94ab62c5fb1be97687e5c9571 | 679,442 |
from typing import Any
def get_canonical_name(namespace: Any) -> str:
"""Return canonical name for a plugin object.
Note that a plugin may be registered under a different name which was
specified by the caller of :meth:`PluginManager.register(plugin, name)
<.PluginManager.register>`. To obtain the na... | f2ee539140c584b9597333e9769bb389cc3ca8d8 | 679,443 |
import time
def _format_time(epoch):
"""Format a UNIX timestamp nicely."""
lctime = time.localtime(epoch)
if lctime.tm_year == time.localtime().tm_year:
return time.strftime("%b %d %H:%M:%S %Z", lctime)
else:
return time.strftime("%b %d, %Y %H:%M:%S %Z", lctime) | 0ac4179c745b3aa2d0677c40fda9fbea881f01bf | 679,444 |
import os
def law_home_path(*paths):
"""
Returns the law home directory (``$LAW_HOME``) that defaults to ``"$HOME/.law"``, optionally
joined with *paths*.
"""
home = os.getenv("LAW_HOME", "$HOME/.law")
home = os.path.expandvars(os.path.expanduser(home))
return os.path.normpath(os.path.join... | 52d8bb95c07e2504b77b934e4883ab7a029ed21d | 679,445 |
def merge(d1, d2):
"""
Merge two dictionaries. In case of duplicate keys, this function will return values from the 2nd dictionary
:return dict: the merged dictionary
"""
d3 = {}
if d1:
d3.update(d1)
if d2:
d3.update(d2)
return d3 | 0cedda124ab6ee310ee3df20784cd05d468b0612 | 679,447 |
import warnings
def convert_examples_to_features(
words,
max_seq_length,
tokenizer,
labels=None,
label_map=None,
cls_token_at_end=False,
cls_token="[CLS]",
cls_token_segment_id=1,
sep_token="[SEP]",
sep_token_extra=False,
pad_on_l... | c6479e381fb5332847891c92178ea51ee83de398 | 679,448 |
def obs_to_dict(obs):
"""
Convert an observation into a dict.
"""
if isinstance(obs, dict):
return obs
return {None: obs} | 0cedf58ce849b3663ac0f9b2c6036ced09815d5d | 679,449 |
import torch
def quotient_central_moments(
fine_values: torch.Tensor, fine_to_coarse: torch.Tensor
) -> torch.Tensor:
"""
Returns (zeroth, first, second) central momemnts of each coarse cluster of
fine values, i.e. (count, mean, stddev).
:returns: A single stacked tensor of shape ``(3,) + fine_va... | 2b382577fb2ec29c24ecde6dd59b7c395e09fe5b | 679,450 |
import torch
def repeat(tensor, K):
"""
[B, ...] => [B*K, ...]
#-- Important --#
Used unsqueeze and transpose to avoid [K*B] when using torch.Tensor.repeat
"""
if isinstance(tensor, torch.Tensor):
B, *size = tensor.size()
repeat_size = [1] + [K] + [1] * (tensor.dim() - 1)
... | c809237d1b6a8c4449d76aed30f9255a745785f1 | 679,451 |
def read_file(file):
"""returns text from input file"""
with open(file, "r") as f:
text = f.read()
return text | be92cd6c1027aa31bbdc6f0efcb5cf992a8c3dd1 | 679,452 |
def update_nested_dict(base_dict, custom_dict):
"""Update nested dict with rather strict rules
Raises
------
TypeError
if type of the update value does not match the original value
KeyError
if custom_dict contains a key not present in base_dict (also
within nested dicts)
... | 55969802c116973fbd0c6a0ea2ca0d38eca38061 | 679,453 |
import os
def getTag(db, schema, tag_id, node, tagname, settings):
"""
This function returns COOL Tags information
:return: tag_id, tag_name
"""
# skip not cool queries
if db == None or schema == None or node == None:
return tag_id, tagname
# parse only queries with db exists in CO... | ca430c14ec8840f9c12ad5f045e6a0a26d6c83ff | 679,454 |
from typing import List
from typing import Any
from typing import Optional
def make_table(rows: List[List[Any]], labels: Optional[List[Any]] = None, centered: bool = False) -> str:
"""
:param rows: 2D list containing objects that have a single-line representation (via `str`).
All rows must be of the same ... | 32f8f379b604e4eaeb809abb37c33892302b75e2 | 679,455 |
def _eval_is_eq(lhs, rhs): # noqa:F811
"""Helper method for Equality with matrices.sympy.
Relational automatically converts matrices to ImmutableDenseMatrix
instances, so this method only applies here. Returns True if the
matrices are definitively the same, False if they are definitively
different... | d0fdd45a503cbd16f2d2700f07ed0a7c91c1cad5 | 679,456 |
import math
def convert_state_to_hex(state: str) -> str:
"""
This assumes that state only has "x"s and Us or Ls or Fs or Rs or Bs or Ds
>>> convert_state_to_hex("xxxU")
'1'
>>> convert_state_to_hex("UxUx")
'a'
>>> convert_state_to_hex("UUxUx")
'1a'
"""
state = (
stat... | d722e07ab69c6b46f834eca04c7a8ba75520b145 | 679,457 |
import os
def get_local_auth_key(auth_key_path, auth_key_file):
"""Return authentification key from local text file inside keys/auth.txt"""
path_to_file = os.path.join(auth_key_path, auth_key_file)
try:
with open(path_to_file, 'r') as f:
key = f.readline()
if isinstanc... | 63129483608a63ed4ed24ebe03b98d6f6d1078ae | 679,458 |
import tempfile
import subprocess
def _text2idngram(vocab_file, corpus_file):
"""
Takes a text stream, plus a vocabulary file, and outputs a list of
every id n-gram which occurred in the text, along with its number of
occurrences.
"""
idngram_file = tempfile.NamedTemporaryFile('w+'... | 6a843f064d57ffb54eee4f491a5d342eca22522d | 679,459 |
def __rm_blanks(subject_row):
"""in templates rms blank spaces: 'time | subject | | ' -> 'time | subject' """
for a in range(len(subject_row) - 1, -1, -1):
if not subject_row[a].isspace() and subject_row[a] != '|':
return subject_row[:a + 1] | 8301fffa83e9135e407b481b5b6adca7b15551e2 | 679,460 |
def get_piece_len(size):
"""Parameters
long size - size of files described by torrent
Return
long - size of pieces to hash
"""
if size > 8 * (2 ** 30): # > 8G file
piece_len_exp = 21 # = 2M pieces
elif size > 2 * (2 ** 30): # > 2G fil... | d5c99e8399ce55009cff7276795f40d906af698d | 679,462 |
import os
def is_empty(path):
""" Check `path` is an empty file """
return not(os.path.getsize(path)) | 13268150054bb0355c43b5206b07e2c69027c832 | 679,463 |
def multivariate_virgin(sigma, phi, vsh, a_0, a_1, a_2, a_3, B):
"""
Calculate velocity using multivariate virgin curve
Parameters
----------
sigma : 1-d ndarray
effective pressure
phi : 1-d ndarray
effective porosity
vsh : 1-d ndarray
shale volume
a_0, a_1, a_2,... | b0bc6973ba9af418cc349b74a368af0515846e52 | 679,464 |
def ArgMinRemove(Q):
""" Dummy Queue with a dictionary """
keys = sorted(Q)
j, d = keys[0], Q[keys[0]]
for v in keys[1:]:
if Q[v] < d:
j, d = v, Q[v]
del Q[j]
return j | c31f503a88d01d8b5d3c0d02a2b3020dfca47569 | 679,465 |
def _lat_hemisphere(latitude):
"""Return the hemisphere (N, S or '' for 0) for the given latitude."""
if latitude > 0:
hemisphere = 'N'
elif latitude < 0:
hemisphere = 'S'
else:
hemisphere = ''
return hemisphere | 17befd8edcedb25575dabe0e5b950debafcdf1ca | 679,466 |
from typing import List
import os
def read_requirements() -> List[str]:
"""Read packages that are required by pipwatch worker."""
current_working_directory = os.path.abspath(os.path.dirname(__file__))
requirements = []
with open(os.path.join(current_working_directory, "requirements.txt"), encoding="ut... | 7903994b343eeb9309853fecc5c333a741493d4b | 679,467 |
import logging
def _reformat_general_modifiers(modifiers_table):
""" Re-formats general modifier table entries for faster lookup of scores """
# Reformat seed modifiers
modifier_tokens = dict()
modifier_lemmas = dict()
# Iterate
logging.info('Re-formatting general modifiers ...')
for term... | 39a2b79a06a485f7c5f8c484cc23dc32e3578a8b | 679,468 |
from typing import List
from typing import Tuple
import operator
def _get_longest_palindrome_boundaries(lps_table: List[int]) -> Tuple[int, int]:
"""Returns real text longest palindrome boundaries based from its lps table.
"""
center_index, radius = max(enumerate(lps_table), key=operator.itemgetter(1))
... | 7c563ee7dda45a85ad3f001b56bd5ed36d241f2c | 679,469 |
def _crc8(byte, polynomial):
"""Manually calculates the 32-bit CRC value for the provided 8-bit input
using the given reversed form CRC polynomial.
"""
polynomial &= 0xFFFFFFFF
crc = byte & 0xFF
for bit in range(8):
xor = crc & 1
crc = (crc >> 1) & 0x7FFFFFFF
if xor:
... | 878d06fbef94f605b2afbeac6d0b01d1f717ca40 | 679,470 |
def parse_word(word):
"""
Split given attribute word to key, value pair.
Values are casted to python equivalents.
:param word: API word.
:returns: Key, value pair.
"""
mapping = {'yes': True, 'true': True, 'no': False, 'false': False}
_, key, value = word.split('=', 2)
try:
... | 89a845c5dbc1f64c2d7c65145535f5b62b06b940 | 679,471 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.