content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def get_ph_bs_symm_line(bands_path, has_nac=False, labels_dict=None):
"""
Creates a pymatgen PhononBandStructure from a band.yaml file.
The labels will be extracted from the dictionary, if present.
If the 'eigenvector' key is found the eigendisplacements will be
calculated according to the formula:... | 40b135c09c829348d0693574b745ad5c114ec037 | 3,658,491 |
def LinterPath():
"""Ascertain the dxl.exe path from this .py files path because sublime.packages_path is unavailable at startup."""
ThisPath = abspath(dirname(__file__))
if isfile(ThisPath):
# We are in a .sublime-package file in the 'Installed Package' folder
return abspath(join(ThisPath, ... | 5e7e8e5761b69ba3383b10af92f4d9a442bab69e | 3,658,493 |
import base64
def encrypt_and_encode(data, key):
""" Encrypts and encodes `data` using `key' """
return base64.urlsafe_b64encode(aes_encrypt(data, key)) | b318e5e17c7a5b8f74036157ce547a3c0d68129c | 3,658,494 |
def _get_undelimited_identifier(identifier):
"""
Removes delimiters from the identifier if it is delimited.
"""
if pd.notna(identifier):
identifier = str(identifier)
if _is_delimited_identifier(identifier):
return identifier[1:-1]
return identifier | cd31b5cd2aea8f6c115fa117da30960f5f6dd8d8 | 3,658,495 |
def has_product_been_used(uuid):
"""Check if this product has been used previously."""
existing = existing_processed_products()
if not isinstance(existing, pd.DataFrame):
return False
has_uuid = not existing.query("uuid == @uuid").empty
return has_uuid | f361c5177c0152179300d6c1356139ba8f7face9 | 3,658,497 |
def _FilterMemberData(
mr, owner_ids, committer_ids, contributor_ids, indirect_member_ids,
project):
"""Return a filtered list of members that the user can view.
In most projects, everyone can view the entire member list. But,
some projects are configured to only allow project owners to see
all member... | be258b2d0559423a70fb5722734144f6a946b70e | 3,658,498 |
def escape_name(name):
"""Escape sensor and request names to be valid Python identifiers."""
return name.replace('.', '_').replace('-', '_') | 856b8fe709e216e027f5ab085dcab91604c93c2e | 3,658,499 |
def show_user_following(user_id):
"""Show list of people this user is following."""
user = User.query.get_or_404(user_id)
return render_template('users/following.html', user=user) | ef1d7d13e9c00c352f27cdde17d215d40ff47b76 | 3,658,500 |
def logout():
"""
This API revokes all the tokens including access and refresh tokens that belong to the user.
"""
current_user = get_jwt_identity()
logout_user(current_user.get('id'))
return jsonify(message="Token revoked."), 200 | d574135099dfaedcdb8d6bdef993d8f773898f63 | 3,658,501 |
def multiset_counter(mset):
"""
Return the sum of occurences of elements present in a token ids multiset,
aka. the multiset cardinality.
"""
return sum(mset.values()) | 36885abd5bf666aa6c77a262a647c227e46d2e88 | 3,658,502 |
def get_v6_subnet(address):
"""derive subnet number for provided ipv6 address
Args:
address (str): ipv6 address in string with mask
Returns:
str: subnet zero == network address
"""
return IPv6(address).subnet_zero() | ed9158b2d2ff8a83dce1b079066ef372ffc623e5 | 3,658,503 |
import yaml
def load_scenario(file_name: str) -> Waypoint:
"""
Create an object Waypoint from a Scenario file
:param file_name:
:return:
"""
# read file
with open(f"{waypoint_directory_path}/{file_name}", "r") as scenario_file:
scenario_data = yaml.load(scenario_file, Loader=yaml.... | db5e246141e014af4545468481739e9449d90a00 | 3,658,505 |
def parse_example(serialized_example):
"""Parse a serialized example proto."""
features = tf.io.parse_single_example(
serialized_example,
dict(
beam_id=tf.io.FixedLenFeature(shape=[], dtype=tf.int64),
image_id=tf.io.FixedLenFeature(shape=[], dtype=tf.int64),
question_id=tf.... | 5c3a76bc121f02ce4484a3af87104f7739db1669 | 3,658,507 |
from typing import Optional
from typing import Tuple
from typing import Union
def _compute_bootstrap_quantiles_point_estimate_custom_bias_corrected_method(
metric_values: np.ndarray,
false_positive_rate: np.float64,
n_resamples: int,
random_seed: Optional[int] = None,
) -> Tuple[Number, Number]:
"... | 50494c15ded4b9cd7c54f4262f7d9b2137d2bd4f | 3,658,508 |
def bytes_to_b64(data: bytes, remove_padding=True) -> str:
"""
byte string to URL safe Base64 string, with option to remove B64 LSB padding
:param data: byte string
:param remove_padding: remove b64 padding (``=`` char). True by default
:return: base64 unicode string
"""
text = urlsafe_b64e... | 8ca495948eb72ab6bb8bf95ae62b4d370a04cbe3 | 3,658,509 |
import re
def _case_sensitive_replace(string, old, new):
"""
Replace text, retaining exact case.
Args:
string (str): String in which to perform replacement.
old (str): Word or substring to replace.
new (str): What to replace `old` with.
Returns:
repl_string (str): Ver... | bf20636146b42f67ec3ad0b4a00a80a9d6cb9ce6 | 3,658,510 |
from typing import Dict
from typing import Any
def deserialize_transaction_from_etherscan(
data: Dict[str, Any],
internal: bool,
) -> EthereumTransaction:
"""Reads dict data of a transaction from etherscan and deserializes it
Can throw DeserializationError if something is wrong
"""
tr... | c4184cea626b229a7c0de8848f95fb29ebdec6d3 | 3,658,511 |
def ar(p):
"""
Given a quaternion p, return the 4x4 matrix A_R(p)
which when multiplied with a column vector q gives
the quaternion product qp.
Parameters
----------
p : numpy.ndarray
4 elements, represents quaternion
Returns
-------
numpy.ndarray
4x4 matrix des... | 0ee437eec9b62c902466de4e77b541fc3cb7a64a | 3,658,512 |
def preprocess_list(lst,tokenizer,max_len=None):
"""
function preprocesses a list of values returning tokenized sequences
Args:
lst: list of strings to be processed
tokenizer: a tokenizer object
max_len: if we need to ensure the same length of strings, we can provide an integer here... | c1ba91ae54b9869ac6dd80664b479a47c34388e2 | 3,658,513 |
def to_dataframe(ticks: list) -> pd.DataFrame:
"""Convert list to Series compatible with the library."""
df = pd.DataFrame(ticks)
df['time'] = pd.to_datetime(df['time'], unit='s')
df.set_index("time", inplace=True)
return df | 6f312e9e8f401d21cebc1404a24ba37738a2819d | 3,658,515 |
def keysCode(code):
"""
Download user's keys from an email link
GET: If the code is valid, download user keys
Else abort with a 404
"""
#Check if code exists and for the correct purpose. Else abort
if (hl.checkCode(code,"Keys")):
user = hl.getUserFromCode(code)
... | 533f17cd4a2fb999f6ffd135a1e647f48266a04c | 3,658,516 |
def lengthenFEN(fen):
"""Lengthen FEN to 71-character form (ex. '3p2Q' becomes '111p11Q')"""
return fen.replace('8','11111111').replace('7','1111111') \
.replace('6','111111').replace('5','11111') \
.replace('4','1111').replace('3','111').replace('2','11') | f49cdf8ad6919fbaaad1abc83e24b1a33a3ed3f8 | 3,658,517 |
def keyboard_mapping(display):
"""Generates a mapping from *keysyms* to *key codes* and required
modifier shift states.
:param Xlib.display.Display display: The display for which to retrieve the
keyboard mapping.
:return: the keyboard mapping
"""
mapping = {}
shift_mask = 1 << 0
... | c9d2e0caea532ab66b00744d17ff6274f42844e9 | 3,658,518 |
def convertPeaks(peaksfile, bedfile):
"""Convert a MACS output file `peaksfile' to a BED file. Also works if the input is already in BED format."""
regnum = 1
with open(bedfile, "w") as out:
with open(peaksfile, "r") as f:
tot = 0
chrom = ""
start = 0
... | 6c9af82254efb98d35c9182ebe53c4f3802cdb7f | 3,658,519 |
def create_freud_box(box: np.ndarray, is_2D=True) -> Box:
"""Convert an array of box values to a box for use with freud functions
The freud package has a special type for the description of the simulation cell, the
Box class. This is a function to take an array of lengths and tilts to simplify the
crea... | 94ea3769d8138907bf29a30fc8afcf6b990264f1 | 3,658,520 |
def hrrr_snotel_pixel(file, x_pixel_index, y_pixel_index):
"""
Read GRIB file surface values, remove unsed dimensions, and
set the time dimension.
Required to be able to concatenate all GRIB file to a time series
"""
hrrr_file = xr.open_dataset(
file.as_posix(),
engine='cfgrib',... | 22a66317d672874b9ababfd0a7daa364d06ea87e | 3,658,521 |
def convert_to_diact_uttseg_interactive_tag(previous, tag):
"""Returns the dialogue act but with the fact it is keeping or
taking the turn.
"""
if not previous:
previous = ""
trp_tag = uttseg_pattern(tag)
return trp_tag.format(convert_to_diact_interactive_tag(previous, tag)) | 06950132147d374002495d92e456fe52a6d9546f | 3,658,522 |
from mne.chpi import compute_chpi_amplitudes, compute_chpi_locs
from mne.chpi import _get_hpi_initial_fit
def compute_good_coils(raw, t_step=0.01, t_window=0.2, dist_limit=0.005,
prefix='', gof_limit=0.98, verbose=None):
"""Comute time-varying coil distances."""
try:
except ImportEr... | 060658dfae82768a5dff31a365f1c200d6f5d223 | 3,658,523 |
def prep_request(items, local_id="id"):
"""
Process the incoming items into an AMR request.
<map name="cite_1">
<val name="{id_type}">{value}</val>
</map>
"""
map_items = ET.Element("map")
for idx, pub in enumerate(items):
if pub is None:
continue
local_i... | 46f1f7a94ffccc4eec2192fe100664c3d9e2d829 | 3,658,524 |
from averages_module import VariableType
from lrc_module import potential_lrc, pressure_lrc
def calc_variables ( ):
"""Calculates all variables of interest.
They are collected and returned as a list, for use in the main program.
"""
# In this example we simulate using the cut (but not shifted) ... | 4d0c066ccf4da82955a60d22c0ec27efc975df6d | 3,658,525 |
def findDocument_MergeFields(document):
"""this function creates a new docx document based on
a template with Merge fields and a JSON content"""
the_document = MailMerge(document)
all_fields = the_document.get_merge_fields()
res = {element:'' for element in all_fields}
return res | 9822f40e5f57bbc72f9292da9bd2a1c134776c2f | 3,658,527 |
def load_mushroom(data_home=None, return_dataset=False):
"""
Loads the mushroom multivariate dataset that is well suited to binary
classification tasks. The dataset contains 8123 instances with 3
categorical attributes and a discrete target.
The Yellowbrick datasets are hosted online and when reque... | e300a1cade8532d18ebea1f5175d9c3001112855 | 3,658,528 |
def get_current_project(user_id):
"""Return from database user current project"""
try:
current = CurrentProject.objects.get(user_id=user_id)
except CurrentProject.DoesNotExist:
return None
keystone = KeystoneNoRequest()
return keystone.project_get(current.project) | dc8b1cf44ccd4c51bf58615657520007f2eca5db | 3,658,529 |
def get_random_successful_answer(intent: str) -> str:
"""
Get a random successful answer for this intent
* `intent`: name-parameter of the yml-section with which the successful answers were imported
**Returns:** None if no successful answers are known for this intent,
otherwise a random eleme... | e8106adff5f5a45c5b5e0ff12130d828fa2f4a55 | 3,658,530 |
from typing import Any
def formatter(
source: str,
language: str,
css_class: str,
options: dict[str, Any],
md: Markdown,
classes: list[str] | None = None,
id_value: str = "",
attrs: dict[str, Any] | None = None,
**kwargs: Any,
) -> str:
"""Execute code and return HTML.
Par... | f141732ff6bd5d3bd7cc1a83895b0e2c020bf8cf | 3,658,531 |
import requests
def get_balance_sheet(ticker, limit, key, period):
"""Get the Balance sheet."""
URL = 'https://financialmodelingprep.com/api/v3/balance-sheet-statement/'
try:
r = requests.get(
'{}{}?period={}&?limit={}&apikey={}'.format(URL,
... | ae31a9d97715e1bc8818f64df48c18c3a7c806a3 | 3,658,534 |
def softmax_loss(scores, y):
"""
Computes the loss and gradient for softmax classification.
Inputs:
- scores: Input data, of shape (N, C) where x[i, j] is the score for the jth
class for the ith input.
- y: Vector of labels, of shape (N,) where y[i] is the label for x[i] and
0 <= y[i] <... | 7cc0e4fc070ab0a8cdc32c75aec342dac34179ab | 3,658,535 |
def text_to_lines(path):
"""
Parse a text file into lines.
Parameters
----------
path : str
Fully specified path to text file
Returns
-------
list
Non-empty lines in the text file
"""
delimiter = None
with open(path, encoding='utf-8-sig', mode='r') as f:
... | df723ee40a490c084301584bd9374445ef73a5ae | 3,658,537 |
def measure_hemijunctions_timelapse(ims_labels, ims_labels_hjs):
"""
Measure the hemijunction traits from a timelapse of a live-imaged epithelium.
Parameters
----------
ims_labels : 3D ndarray (t,y,x)
Each timepoint is a 2D array with labeled regions.
ims_labels_hjs : 3D ndarray (t,y,x)... | c26779cd310a849843b20c8fc02539f972965c1a | 3,658,538 |
def get_compare_tables_checks_tasks():
"""Get list of tasks that will compare tables checks between databases.
Args:
Returns:
list: list of tasks to be executed in a process pool. Each item is a dict instance with following strucutre:
{
'function' (f... | 9c210b1ebf43bffa6e2e9db0c53ebab5ba76c6bf | 3,658,539 |
from typing import Union
from typing import Set
def label_pr_failures(pull: Union[PullRequest, ShortPullRequest]) -> Set[str]:
"""
Labels the given pull request to indicate which checks are failing.
:param pull:
:return: The new labels set for the pull request.
"""
pr_checks = get_checks_for_pr(pull)
failu... | ad36f23aa9e3d695e0ddab5a165e5665fdccf91c | 3,658,540 |
def arrange_images(total_width, total_height, *images_positions):
"""Return a composited image based on the (image, pos) arguments."""
result = mel.lib.common.new_image(total_height, total_width)
for image, pos in images_positions:
mel.lib.common.copy_image_into_image(image, result, pos[1], pos[0])... | 49e167b9b6eb1a8e76c8e2d65bc3fa419d91a8a1 | 3,658,542 |
from typing import Tuple
import importlib
def import_core_utilities() -> Tuple[ModuleType, ModuleType, ModuleType]:
"""Dynamically imports and return Tracing, Logging, and Metrics modules"""
return (
importlib.import_module(TRACING_PACKAGE),
importlib.import_module(LOGGING_PACKAGE),
im... | d627c1405b08975aeb02839f2da9d363f385d8b5 | 3,658,543 |
def pancakeSort(self, A):
# ! 这个方法实际上是在每轮循环中寻找最大的那个数,使其在正确的位置
"""
:type A: List[int]
:rtype: List[int]
"""
bucket = sorted(A)
ans = []
for k in range(len(A),0,-1):
i = A.index(bucket.pop())+1
ans += [i, k]
A = A[i:k][::-1] + A[:i] + A[k:]
print(A)
ret... | 35d358c6631f5cc708232f67a3e55d685116dff8 | 3,658,544 |
def getOrc(orcName):
"""Get an orchestra stored in the user namespace.
One can store an orchestra in the user name space with the %%orc magic.
"""
ip = get_ipython()
return ip.user_ns["__orc"][orcName] | 7fed637d4ab653579b4ad78e1b047e236ca46377 | 3,658,545 |
def get_prompt_data_from_batse(grb: str, **kwargs: None) -> pd.DataFrame:
"""Get prompt emission data from BATSE. Creates a directory structure and saves the data.
Returns the data, though no further action needs to be taken by the user.
:param grb: Telephone number of GRB, e.g., 'GRB140903A' or '140903A' ... | 1bd7848f455401be89466c88efd9e4d44b3b72e9 | 3,658,546 |
def angular_error(a, b):
"""Calculate angular error (via cosine similarity)."""
a = pitchyaw_to_vector(a) if a.shape[1] == 2 else a
b = pitchyaw_to_vector(b) if b.shape[1] == 2 else b
ab = np.sum(np.multiply(a, b), axis=1)
a_norm = np.linalg.norm(a, axis=1)
b_norm = np.linalg.norm(b, axis=1)
... | 89f7a51fc95a55349fc79e58b8f644a1ee6bd8a0 | 3,658,547 |
def includeme(config):
"""
Get build Git repository directory and make it accessible
to all requests generated via Cornice
"""
# Make DB connection accessible as a request property
def _get_repos(request):
_settings = request.registry.settings
repo_dir = _settings['repo_basedir'... | f2d73eb01b616f79059f4001c7b3faad67f48cd2 | 3,658,548 |
from typing import Union
from pathlib import Path
def add_dot_csv(filename: Union[Path, str]) -> str:
"""Adds a .csv extension to filename."""
return add_extension(filename, '.csv') | b0e89ca231675048ddb65b11856179db140a15fb | 3,658,549 |
from typing import Dict
from typing import Any
def load_settings_from_file(filename: str) -> Dict[str, Any]:
"""Load amset configuration settings from a yaml file.
If the settings file does not contain a required parameter, the default
value will be added to the configuration.
An example file is giv... | 8f857ede65c455b51f030edc58577a87cc6159a6 | 3,658,550 |
def execute_query(query, *arguments):
"""Execute a query on the DB with given arguments."""
_db = labpals.model.get_db()
cursor = _db.execute(query, arguments)
rows = cursor.fetchall()
return rows | d1b7aff948ee37b223386af29bbe4a6d0939cde1 | 3,658,551 |
from typing import Dict
from typing import Any
import copy
def format_search_events_results(response: Dict[str, Any], limit: int) -> tuple:
"""
Format the output of the search events results command.
Args:
response (Dict[str,Any]): API response from FortiSIEM.
limit (int):Maximum number of... | de6b12f2009c3a7dab8093bd5842455e2bd2c84a | 3,658,552 |
from datetime import datetime
def radec_obs_vec_mpc(inds, mpc_object_data):
"""Compute vector of observed ra,dec values for MPC tracking data.
Args:
inds (int array): line numbers of data in file
mpc_object_data (ndarray): MPC observation data for object
Returns:
r... | daa0a7bfc5a1532c4a63f4543f4ea5e3db099973 | 3,658,553 |
def mod(x, y) -> ProcessBuilder:
"""
Modulo
:param x: A number to be used as the dividend.
:param y: A number to be used as the divisor.
:return: The remainder after division.
"""
return _process('mod', x=x, y=y) | fb94d3a3e1dcd918d8405232ad11f00943895785 | 3,658,554 |
def get_list_of_encodings() -> list:
"""
Get a list of all implemented encodings.
! Adapt if new encoding is added !
:return: List of all possible encodings
"""
return ['raw', '012', 'onehot', '101'] | 6e0749eb45f85afe4e5c7414e4d23e67335ba2b5 | 3,658,556 |
def region_to_bin(chr_start_bin, bin_size, chr, start):
"""Translate genomic region to Cooler bin idx.
Parameters:
----------
chr_start_bin : dict
Dictionary translating chromosome id to bin start index
bin_size : int
Size of the bin
chr : str
Chromosome
start : int
... | f17b132048b0ceb4bbf2a87b77327d0d63b3fd64 | 3,658,557 |
def cvCalcProbDensity(*args):
"""
cvCalcProbDensity(CvHistogram hist1, CvHistogram hist2, CvHistogram dst_hist,
double scale=255)
"""
return _cv.cvCalcProbDensity(*args) | dc0ce1eb33a07466d29defe0b4112e46cabe1308 | 3,658,559 |
def get_filter_para(node_element):
"""Return paragraph containing the used filter description"""
para = nodes.paragraph()
filter_text = "Used filter:"
filter_text += " status(%s)" % " OR ".join(node_element["status"]) if len(
node_element["status"]) > 0 else ""
if len(node_element["status"])... | 7b3ad6b0a9752a53bd16d9cee2a250f54f43def3 | 3,658,560 |
def mk_multi_line_figax(nrows, ncols, xlabel='time (s)', ylabel='signal (a.u.)'):
"""
Create the figure and axes for a
multipanel 2d-line plot
"""
# ncols and nrows get
# restricted via the plotting frontend
x_size = ncols * pltConfig['mXSize']
y_size = nrows * pltConfig['mYSize']
... | c759b4111a8cb3015aa9896f5afd2f8831ad8665 | 3,658,561 |
def load_sizes(infile_path: str, header: bool=None):
"""
Load and parse a gtf file. More information on the gtf format is here:
https://asia.ensembl.org/info/website/upload/gff.html
Arguments:
(REQUIRED) infile_path: path to gtf file
(OPTIONAL) header: headers in size file (DEFAULT:... | 0b1737bb905b57f719c8f2369d771794dd49666b | 3,658,562 |
import string
import pickle
def load_model(file_path: string):
"""
Used to serialize an save a trained model, so it can be reused later on again.
-----------------------------------------------------------------------------------
Parameters:
-------------------------------------------------------... | 26278c46092dff6199a82b1425203af1883ba49d | 3,658,564 |
import numpy as np
def gfs_mos_forecast(stid, forecast_date):
"""
Do the data retrieval.
"""
# Generate a Forecast object
forecast = Forecast(stid, default_model_name, forecast_date)
forecast.daily.high = np.round(np.random.rand() * 100.)
forecast.daily.low = np.round(np.random.rand() * ... | 8ba16fe350e5eef77f9eb960de4b447bcb420b5f | 3,658,565 |
def evaluate_accuracy_score(preprocessing, prediction_binary):
"""
Evaluates the accuracy score
:param preprocessing: prepared DataPreprocess instance
:param prediction_binary: boolean expression for the predicted classes
"""
accuracy = []
for j in range(len(DETECTION_CLASSES)):
acc ... | 9ee9110f924a930d442d00d4c06a929ba7589e42 | 3,658,566 |
def test_domain_visualize(case, visu_case):
"""
test the domain visualization
"""
dom = pylbm.Domain(case)
views = dom.visualize(**visu_case)
return views.fig | a395aad44955eb0599e257ccfeb326cb08638fcd | 3,658,567 |
import torch
def create_supervised_evaluator(model, metrics,
device=None):
"""
Factory function for creating an evaluator for supervised models
Args:
model (`torch.nn.Module`): the model to train
metrics (dict of str - :class:`ignite.metrics.Metric`): a map... | da5c39b8a8d841181fc63ae48db0c68f9bbfe278 | 3,658,568 |
def get_available_operations():
""" Return a dict of available operations """
return True, runtime.get_available_operations() | 9d0b744061c97cf10fb69ccfdbc403b8f337db3d | 3,658,569 |
def word_distance(word1, word2):
"""Computes the number of differences between two words.
word1, word2: strings
Returns: integer
"""
assert len(word1) == len(word2)
count = 0
for c1, c2 in zip(word1, word2):
if c1 != c2:
count += 1
return count | b3279744c628f3adc05a28d9ab7cc520744b540c | 3,658,570 |
from typing import Union
from typing import Tuple
from typing import Any
def get_parent_child(root: dict,
path: str) -> Union[Tuple[Tuple[None, None],
Tuple[None, None]],
Tuple[Tuple[dict, None],
... | 3e33e32af6b3f67cf41397b6da399ec9ede5491e | 3,658,571 |
def get_data_loaders(personachat, tokenizer, args_num_candidates=1, args_personality_permutations=1, args_max_history=2):
""" Prepare the dataset for training and evaluation """
print("Build inputs and labels")
datasets = {"train": defaultdict(list), "valid": defaultdict(list)}
for dataset_name, da... | 212e7bdcdd880b47c56b76fe2e33ce12c665c650 | 3,658,572 |
def unescape_strict(s):
"""
Re-implements html.unescape to use our own definition of `_charref`
"""
if '&' not in s:
return s
return _charref.sub(_replace_charref, s) | d2b9aace645af58dce1e5a5f5e5cf3be919b759b | 3,658,573 |
def CheckVPythonSpec(input_api, output_api, file_filter=None):
"""Validates any changed .vpython files with vpython verification tool.
Args:
input_api: Bag of input related interfaces.
output_api: Bag of output related interfaces.
file_filter: Custom function that takes a path (relative to client root)... | d6e888b5ce6fec4bbdb35452b3c0572702430c06 | 3,658,574 |
import types
from typing import Tuple
def test_infer_errs() -> None:
"""Test inference applied to functions."""
with f.Fun(MockServer()):
a = f.put(b"bla bla")
b = f.put(3)
with pytest.raises(TypeError):
f.py(lambda x, y, z: (x, y), a, a, b)
# should NOT raise
... | 434e5b19f6ad15d6644224475ddd656184593c19 | 3,658,576 |
def decode_captions(captions, idx_to_word):
""" Decode text captions from index in vocabulary to words.
"""
if captions.ndim == 1:
T = captions.shape[0]
N = 1
else:
N, T = captions.shape
decoded = []
for i in range(N):
words = []
for t in range(T):
... | a56abe824b522418480c80611505dabd0a8af6cc | 3,658,577 |
def make_loc(caller):
"""
turn caller location into a string
"""
# return caller["file"] + ":" + caller["func"] + ":" + caller["line"]
return caller["file"] + ":" + str(caller["line"]) | e0db31ffd5c76636938bfe66184f9a2a6fbca496 | 3,658,579 |
def run_part2(file_content):
"""Implmentation for Part 2."""
numbers = (int(number) for number in file_content.split())
root = _build_tree(numbers)
return _node_value(root) | 47171de36eacabd438f1243bddd866af6187c763 | 3,658,581 |
def get_cap_selected_frame(cap, show_frame):
"""
Gets a frame from an opencv video capture object to a specific frame
"""
cap_set_frame(cap, show_frame)
ret, frame = cap.read()
if not ret:
return None
else:
return frame | 4a5a939368e09faea3094335f60e782a249616ce | 3,658,582 |
def rotate_coords_x(pos, angle):
""" Rotate a set of coordinates about the x-axis
:param pos: (n, 3) xyz coordinates to be rotated
:param angle: angle to rotate them by w.r.t origin
:type pos: numpy.ndarray
:type angle: float
:return: array of rotated coordinates
:rtype: numpy.ndarray
... | af0a95302c44be54e78b88b8f9851bab29556900 | 3,658,583 |
import itertools
def q_learning(env, num_episodes, discount_factor=1.0, alpha=0.5, epsilon=0.1):
"""
Q-Learning algorithm: Off-policy TD control. Finds the optimal greedy policy
while following an epsilon-greedy policy
Args:
env: OpenAI environment.
num_episodes: Number of episodes to... | 380c46f9a1c35424028cbf54d905b7b3df1181ec | 3,658,584 |
import random
def find_rand_source_reg():
"""Find random source register based on readAfterWrite probability"""
prob=random.uniform(0,1)
while len(previousIntegerSources)>numberOfPreviousRegistersToConsider:
previousIntegerSources.popleft()
if prob<readAfterWrite and previousIntegerDestinations:
num=random.ch... | 678223dc137a624b670834bc2fc84d6f5481d130 | 3,658,585 |
def _get_qnode_class(device, interface, diff_method):
"""Returns the class for the specified QNode.
Args:
device (~.Device): a PennyLane-compatible device
interface (str): the interface that will be used for classical backpropagation
diff_method (str, None): the method of differentiatio... | cb87fd664e37074fbad065e7c707554c1632a0d9 | 3,658,586 |
def evaluate_and_log_bleu(model, bleu_source, bleu_ref, vocab_file):
"""Calculate and record the BLEU score."""
subtokenizer = tokenizer.Subtokenizer(vocab_file)
uncased_score, cased_score = translate_and_compute_bleu(
model, subtokenizer, bleu_source, bleu_ref)
tf.compat.v1.logging.info("Bleu score (un... | 5b7665851c69e0edfe526763a76582f10eb88bf0 | 3,658,587 |
def transform_call(red_node):
"""
Converts Python style function calls to VHDL style:
self.d(a) -> d(self, a)
If function owner is not exactly 'self' then 'type' is prepended.
self.next.moving_average.main(x) -> type.main(self.next.moving_average, x)
self.d(a) -> d(self, a)
self.next.d(a) ... | 21091d369d75f5f51065e2a2df95956816d8b968 | 3,658,588 |
import random
def delta_next_time_to_send(G, u, v):
"""How long to wait before U should send a message to V under diffusion
spreading. Per the Bitcoin protocol, this depends on if we have an outgoing
connection or an incoming connection."""
is_outgoing = G[u][v][ORIGINATOR] == u
average_interval_s... | 193e847c8dfe1bf4e23bb3ed0a749c36f83c9f61 | 3,658,589 |
def processData(list_pc, imo):
"""
Cette fonction traite les données de getData pour écrire une seule string
prête à être copié dans le csv et qui contient toutes les lignes d'un bateau
"""
str_pc = ''
for i in range(len(list_pc)):
if list_pc[i] == 'Arrival (UTC)':
tab = list... | abb9d0a8d9f3f1ed35e4f991a3ac14e51621f104 | 3,658,590 |
def wrn(num_classes):
"""Constructs a wideres-28-10 model without dropout.
"""
return Wide_ResNet(28, 10, 0, num_classes) | bcf33fdaf7081389b2c4b2e8f172684531205315 | 3,658,591 |
from typing import Dict
from typing import Any
from typing import Optional
def run(
config: Dict[str, Any],
log_dir: str = "",
kernel_seed: int = 0,
kernel_random_state: Optional[np.random.RandomState] = None,
) -> Dict[str, Any]:
"""
Wrapper function that enables to run one simulation.
It... | c8bb7931c9b74064d3488bfa92fb1376b9f9f474 | 3,658,592 |
def python_to_pydict(script_contents, namespace=None):
"""Load a Python script with dictionaries into a dictionary."""
if namespace is None:
namespace = {}
exec script_contents in {}, namespace
return to_lower(namespace) | 7f1dcf2099b2a5b132b6f7d7355b903d4328a84d | 3,658,593 |
def convertInt(s):
"""Tells if a string can be converted to int and converts it
Args:
s : str
Returns:
s : str
Standardized token 'INT' if s can be turned to an int, s otherwise
"""
try:
int(s)
return "INT"
except:
return s | a0eae31b69d4efcf8f8595e745316ea8622e24b3 | 3,658,594 |
import torch
def pairwise_distance(A, B):
"""
Compute distance between points in A and points in B
:param A: (m,n) -m points, each of n dimension. Every row vector is a point, denoted as A(i).
:param B: (k,n) -k points, each of n dimension. Every row vector is a point, denoted as B(j).
:return: ... | 2142b94f91f9e762d1a8b134fdda4789c564455d | 3,658,595 |
from typing import Tuple
def _split_full_name(full_name: str) -> Tuple[str, str, str]:
"""Extracts the `(ds name, config, version)` from the full_name."""
if not tfds.core.registered.is_full_name(full_name):
raise ValueError(
f'Parsing builder name string {full_name} failed.'
'The builder name... | 2b2ace6e0df3302c8899834be749e0ef23c8df6d | 3,658,596 |
def query_paginate(resources, arguments):
"""Return the resources paginated
Args:
resources(list): List to paginate
arguments(FormsDict): query arguments
Returns:
list: Paginated resource (asc or desc)
"""
if '_page' not in arguments:
return resources
page = i... | caeefb937501945be2f35792dbdec9e7eefcadef | 3,658,597 |
def convert_grad(graph):
"""Remove all instances of SymbolicKeyType in the graphs.
They will be replaced by globally-unique integers.
"""
mng = graph.manager
counter = 0
key_map = {}
for node in mng.all_nodes:
if node.is_constant(SymbolicKeyInstance):
if node.value not... | 7dfec6d6319630024bfb84872fd99b55168f0028 | 3,658,598 |
def site_data(db, settings):
"""Simple fake site data
"""
if organizations_support_sites():
settings.FEATURES['FIGURES_IS_MULTISITE'] = True
site_data = make_site_data()
ce = site_data['enrollments'][0]
lcgm = [
LearnerCourseGradeMetricsFactory(site=site_data['site'],
... | 395751133325b4fb6dc0ea463726c56b95c7d2a7 | 3,658,599 |
def render_curve(name,
data,
x_range=None,
y_range=None,
x_label=None,
y_label=None,
legends=None,
legend_kwargs={},
img_height=None,
img_width=None,
... | f0f60bf64c195f82ec91513f2c79a7c72a25599d | 3,658,600 |
def CreateBooleanUnion1(breps, tolerance, manifoldOnly, multiple=False):
"""
Compute the Boolean Union of a set of Breps.
Args:
breps (IEnumerable<Brep>): Breps to union.
tolerance (double): Tolerance to use for union operation.
manifoldOnly (bool): If true, non-manifold input breps... | ae397d73b9acbcdd52e9e83592322274047d9915 | 3,658,601 |
def make_singleton_class(class_reference, *args, **kwargs):
"""
Make the given class a singleton class.
*class_reference* is a reference to a class type, not an instance of a class.
*args* and *kwargs* are parameters used to instantiate a singleton instance.
To use this, suppose we have a class c... | c33b09f2eee16e23dd1a10a914a8735120efbbfe | 3,658,602 |
def get_coaches(soup):
"""
scrape head coaches
:param soup: html
:return: dict of coaches for game
"""
coaches = soup.find_all('tr', {'id': "HeadCoaches"})
# If it picks up nothing just return the empty list
if not coaches:
return coaches
coaches = coaches[0].find... | 784b355adb885b0eb4f26e72168475e1abbe4d1f | 3,658,603 |
import logging
def create_app(config_name):
"""
Factory to create Flask application context using config option found in
app.config
:param config_name: (string) name of the chosen config option
:return app: (Flask application context)
"""
logging.basicConfig(
filename="app.log",
... | 8dea98c2393b575c7c353debe4b84eea67ff9353 | 3,658,604 |
import math
def _rectify_countdown_or_bool(count_or_bool):
"""
used by recrusive functions to specify which level to turn a bool on in
counting down yeilds True, True, ..., False
conting up yeilds False, False, False, ... True
Args:
count_or_bool (bool or int): if positive will count down... | 63d02cfbd99652bc04cfbac57a7d9306465bbf2b | 3,658,605 |
def POpen (inUV, access, err):
""" Open an image persistent (disk) form
inUV = Python UV object
access = access 1=READONLY, 2=WRITEONLY, 3=READWRITE
err = Python Obit Error/message stack
"""
################################################################
if ('myClass' in inUV.__... | f365a9d5a4fc8a028203e8ea4a51b64d6d19f9bc | 3,658,606 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.