content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def simplify_control(A, B, x0, u0):
"""
Given the linarized A and B matrices corresponding to the state:
x = [u, v, w, p, q, r, phi, th, dpsi, x_r, y_r, z_r]
u = [T, a, e, r]
this function simplifies the model to assume the body rates p, q, r
are directly controlled, by essentially just removing the ro... | 5a39f02300a272ae235bb5e6b2c2195b2455dd3b | 3,617,900 |
def hdot_chart_line(datum: int) -> str:
"""Produce one line of a dot chart (without the label)."""
return lit.HDOT_ONE * datum | ad84600ed6b37d7440d07368841da054366328af | 3,617,901 |
from typing import Counter
import torch
def align_features_to_words(roberta, features, alignment):
"""
Align given features to words. Without assert.
Args:
roberta (RobertaHubInterface): RoBERTa instance
features (torch.Tensor): features to align of shape `(T_bpe x C)`
alignment: ... | e041f0a9657767dbfd51927c331fe55f80688570 | 3,617,902 |
import json
def img_one_day(request, date):
"""
get one-day detected faces
:param request:http request
:param date: the day client chose
:return:url list of one-day detected faces, formatted with JSon
"""
result_list = reader.get_one_day_img(date)
return HttpResponse(json.dumps(result_... | 2e1f43ee8a128732f8f94ad61961c122a098ff12 | 3,617,903 |
from datetime import datetime
def get_date_age(date):
"""
Take a datetime and return its "age" as a string.
The age can be in second, minute, hour, day, month or year. Only the
biggest unit is considered, e.g. if it's 2 days and 3 hours, "2 days" will
be returned.
Make sure date is not in the ... | a70d1d1368c69d10cfebd6f23a96b5f68337de48 | 3,617,904 |
import json
import logging
def SubtractHistogram(histogram_json, start_histogram_json):
"""Subtracts a previous histogram from a histogram. Both parameters are json
serializations of histograms."""
start_histogram = json.loads(start_histogram_json)
# It's ok if the start histogram is empty (we had no data, ma... | ac346f7d2e132b8577c957f89cd7fb6150207bf1 | 3,617,905 |
def lev_from_alignment(x_y_alignment_list, lengths):
"""
Given a list of aligned pairs and a list of lengths, computes the
Levenshtein for each pair in the list. Returns a list of distances.
:param x_y_alignment_list: a list where each element is itself a list
containing tuples representing the... | ea9148eb052e7af1db79876e23de74bbccdc8bf8 | 3,617,906 |
def get_shortest_path_lengths(G: nx.Graph, origin_nodes: list, destination_nodes: list, weight: str):
"""
This function calculates the shortest paths based on weight parameter.
---
Args:
origin_nodes (list): list of origin nodes
destination_nodes (list): list of destination nodes
... | 7722c3cfee41b61fd1249bd114bbb68ee8d3fb50 | 3,617,907 |
def evaluateAllQuestions(groundtruth_list, predictions_list):
""" Prints classification report for all questions
Parameters
----------
groundtruth_list :
list of event tuples for all questions
predictions_list :
list of event tuples for all questions
"""
questions = ["Type 1... | caa8755a2640bea6c4052c850266e5b5ac923da1 | 3,617,908 |
def _front_left_tire_pressure_supported(data):
"""Determine if front left tire pressure is supported."""
return data["status"]["tirePressure"]["frontLeftTirePressurePsi"] is not None | b59ab6f4a9b3d0801c1c5c8798e7da2fab0b580d | 3,617,909 |
def index_exists(name: str) -> bool:
"""
Check if an index with this name exists
"""
return es.indices.exists(index=name) | 4aa20debf29d098a48e633d50e76034cc723a301 | 3,617,910 |
import _ssl
def sslwrap_simple (sock, keyfile=None, certfile=None):
"""A replacement for the old socket.ssl function. Designed
for compability with Python 2.5 and earlier. Will disappear in
Python 3.0."""
ssl_sock = _ssl.sslwrap(sock._sock, 0, keyfile, certfile, CERT_NONE,
... | 9ad4a2d87533d3bb91a31b067a1385fdf3cdb0e7 | 3,617,911 |
def count_missing_doc_types(articles):
"""
:param articles A PyMongo collection of articles
:return: int: Number or articles without a a 'doc_type' property or having
it equal to the empty string ('')
"""
return articles.count_documents(
{"$or": [{"doc_type": {"$exists": False}}, {"doc_t... | b0e734590c4b74572382e377f9cd861fa5162af7 | 3,617,912 |
def segment_length(p1 : np.ndarray, p2 : np.ndarray):
"""
p1 (2,)
p2 (2,)
"""
return npla.norm(p2-p1) | b36f7638d6a7bcc463e0a34c4102b10a12b98c20 | 3,617,913 |
from sys import path
def get_file_messages(fn, verbosity=0):
"""Returns a list of messages from an individual JSON file"""
channel = path.basename(path.dirname(fn))
msgs = []
for conv in load(open(fn)):
if conv['type'] == 'message' and 'text' in conv and conv['text'] and 'client_msg_id' in con... | 51edeed7a076e60d6e87edab8c0f500188eb8112 | 3,617,914 |
def calculate_average(storage):
"""
Function prototype:
calculate_average(storage)
Function parameters (required):
storage - a list of tuples with RGB values; this list will be iterated and, using the values obtained,
will find the average RGB value
Function parameters ... | 1fd9ff8637c610dbb65153efa7b64f94e29bb475 | 3,617,915 |
import argparse
def parse_args():
""" Parses the arguments of the command line """
parser = argparse.ArgumentParser(
description="Checks a file for british and american spellings")
parser.add_argument('files', metavar="files", type=str, nargs='+',
help='file where to check the spe... | 1ea6d692eedbd2c448138cf0adc3a85cf2a85283 | 3,617,916 |
def update():
""" """
lan_object = Languages()
lan_object.update()
message = lan_object.message
status = lan_object.status
data = {
"success": True,
}
return data | 2d628e95f733fd83d307b462094b227cf0fd98d4 | 3,617,917 |
from tensorflow.python.eager import context
import logging
def convert_keras(model, name=None, doc_string='', target_opset=None,
channel_first_inputs=None, debug_mode=False, custom_op_conversions=None):
# type: (keras.Model, str, str, int, [], bool, {}) -> onnx.ModelProto
"""
:param mode... | 0c378280b7ecbaa73be0fcf84497215049e1e6c2 | 3,617,918 |
def combineSeries(series, methods=MethodType.Unknown, reverse=False, squeeze=False, warn=True, shapeTolerance=0.01,
spacingTolerance=0.1):
"""Combines a series into an N-D Numpy array and returns some information about the volume
Many of the parameters are from the :meth:`sortSeries` function... | c1e9254c8bdac448f71a4c9eb3f8b1a3ea313d8b | 3,617,919 |
from datetime import datetime
def now_int():
"""
Returns the current POSIX time as an integer.
:return: integer POSIX time
"""
now = datetime.now() - datetime(1970, 1, 1)
return int(now.total_seconds()) | 3c70a3324b549d24aaac01f49a2ed7ef480a8eb7 | 3,617,920 |
def gradient_pred(model, ref, ref_rc, alt, alt_rc, mutation_positions, out_annotation_all_outputs,
output_filter_mask=None, out_annotation=None):
"""Gradient-based (saliency) variant effect prediction
Based on the idea of [saliency maps](https://arxiv.org/pdf/1312.6034.pdf) the gradient-based... | cec33798831f9f427f6484558d0dcd97c6c41c73 | 3,617,921 |
import logging
def compute_fid_from_activations(fake_activations, real_activations):
"""Returns the FID based on activations.
Args:
fake_activations: NumPy array with fake activations.
real_activations: NumPy array with real activations.
Returns:
A float, the Frechet Inception Distance.
"""
log... | ef145dcfdd8635069868edd5c61c5d679807ea53 | 3,617,922 |
def homoRunForOneVariant(chr_fa_seq, variant):
"""
Calculate and return the length of the largest homopolymer
touching this variant. Compute homopolymer lengths on the
left and right, and return the largest.
Args:
chr_fa_seq: A fasta sequence of chromosome in `varianti.CHROM`
varian... | d4119e6e7234b9bbe9cc754afcf16a74f4919b0e | 3,617,923 |
def _get_exon_junction_dict(metadata_list, strand):
""" Creates an auxiliary dictionary used for filtering. Assigns to each junction all overlapping exon pairs.
Parameters
----------
metadata_list: List(Output_metadata).
Returns
-------
exon_dict: dict. (read_frame, pos_mid_1, pos_mid_2, v... | 045fa4adac1ba16c27a992e244c4f543c1829cf6 | 3,617,924 |
from typing import Tuple
from typing import List
def _align_dtypes(
df_a: pd.DataFrame, df_b: pd.DataFrame
) -> Tuple[List[int], pd.DataFrame, pd.DataFrame]:
"""Try to enforce the dtypes of non-object type of one dataframe
on the other. Return a list of index values for those columns
where it is not p... | bd36b3b40e7e48baa668b7e91468a85d10e3cc3e | 3,617,925 |
from typing import Set
from typing import Tuple
def matrix_cfpq(
graph: nx.MultiDiGraph,
cfg: CFG,
start_nodes: Set[int] = None,
final_nodes: Set[int] = None,
start_variable: Variable = Variable("S"),
) -> Set[Tuple[int, int]]:
"""
Context-Free Path Querying based on matrix multiplication
... | fadcdb320264ea3f1d4e13dee715d2fe78dfe139 | 3,617,926 |
def module_loaded(module):
"""
Checks if the specified kernel-module has been loaded.
:param module: Name of the module to check
:return: True if the module is loaded, False if not.
"""
return any(s.startswith(module) for s in open("/proc/modules").readlines()) | f09e719acba7f8e2aed59816d3b99bd9575edcfd | 3,617,927 |
def IsMonophyleticForTaxa(tree,
taxa,
support=None):
"""check if a tree is monophyletic for a list of taxa.
Arguments
---------
tree : :class:`Tree`
Tree to analyse
taxa : list
List of taxa
support : float
Minimum bo... | fcb0066c4083183cc7b81195a0845897d95b1cde | 3,617,928 |
def cleanfieldlower(value):
"""
remove spaces and convert to lower case
so flag error
"""
if not value:
return None
value = str(value)
value = value.strip()
value = value.lower()
return value | 1745c75293ca69419408de7b2c77e8293b252e1e | 3,617,929 |
import re
def bs_preprocess(html):
"""remove distracting whitespaces and newline characters
(c) mail-group of beautifulsoup4"""
pat = re.compile('(^[\s]+)|([\s]+$)', re.MULTILINE)
html = re.sub(pat, '', html) # remove leading and trailing whitespaces
return html | 22d759a7b48970d01782fa01c031cc60e29ad416 | 3,617,930 |
def query_done_cb(request, server_id):
"""
A callback for query completion notification. When the query is done,
BeeswaxServer notifies us by sending a GET request to this view.
"""
message_template = '<html><head></head>%(message)s<body></body></html>'
message = {'message': 'error'}
try:
query_histo... | 2c358392a2f5a0579db9452e9a47382203f18d83 | 3,617,931 |
def get_user_info(request):
"""
A helper function which uses the user information in the request to get the Player object (which also contains the
user object).
:param request: A html request with user data (specifically username)
:return: None if no user found, otherwise the Player object.
"""... | 59bd9abbc3a0158a38b2afd1088ff06346f204f8 | 3,617,932 |
def enthalpyliq(temp=None,pres=None,dliq=None,chkvals=False,
chktol=_CHKTOL,temp0=None,pres0=None,dliq0=None,chkbnd=False,
mathargs=None):
"""Calculate ice-liquid liquid water enthalpy.
Calculate the specific enthalpy of liquid water for ice and liquid
water in equilibrium.
:arg temp: ... | e0b0c6419f4d3a6cc3ce1f8d118a91038fd54988 | 3,617,933 |
def dataset(directory, images_file, labels_file):
"""Download and parse MNIST dataset."""
images_file = download(directory, images_file)
labels_file = download(directory, labels_file)
check_image_file_header(images_file)
check_labels_file_header(labels_file)
def decode_image(image):
#... | 07aa40b33aab7aa5ea93c6b02ac8ed1dc1830650 | 3,617,934 |
def web3_get_code_sha256_hash(web3, addr):
"""
web3: Web3
addr: address in hex string
"""
code = web3.eth.getCode(to_checksum_address(addr))
return compute_code_sha256_hash(code) | 8caa66bf1ed3c12ea10292d1bdb5f7bbd01857c0 | 3,617,935 |
def complete_cluster(cluster: Cluster, host: Host) -> Cluster:
"""Add service, component and host to cluster"""
cluster.host_add(host)
service = cluster.service_add(name="first_service")
cluster.hostcomponent_set((host, service.component(name="first_service_component_1")))
return cluster | 6011a6af4ee1ea32776a33528d7e65e1e3b6895a | 3,617,936 |
def year_range(entry):
"""Show an interval of employment in years."""
val = ""
if entry.get("start_date") is None or entry["start_date"]["year"]["value"] is None:
val = "unknown"
else:
val = entry["start_date"]["year"]["value"]
val += "-"
if entry.get("end_date") is None or ent... | 92f7f0bcb450303161b7f766148a9feac62f98d1 | 3,617,937 |
def hamming_dist(a,b):
"""Return number of non-equal entries of a and b."""
return np.linalg.norm(a-b,ord=1) | 6b86ac73cf598f71598289b62a396d1cd9eb782f | 3,617,938 |
from splitgraph.core.output import parse_repo_tag_or_hash
from typing import Callable
from typing import Tuple
import logging
def prepare_splitfile_sql(sql: str, image_mapper: Callable) -> Tuple[str, str]:
"""
Transform an SQL query to prepare for it to be used in a Splitfile SQL command and validate it.
... | 8d67a25c0de66a3d59133345d1734e753656989f | 3,617,939 |
def grr_hostname(line):
"""Returns hostname of the selected client.
Args:
line: A string representing arguments passed to the magic command.
Returns:
String representing hostname of a client.
Raises:
NoClientSelectedError: Client is not selected to perform this operation.
"""
del line # Unus... | f7e40c2edd49f54f66e2e54039ee24cb0e496a4f | 3,617,940 |
def halo_bias(cosmo, halo_mass, a, overdensity=200):
"""Tinker et al. (2010) halo bias
Args:
cosmo (:obj:`Cosmology`): Cosmological parameters.
halo_mass (float or array_like): Halo masses; Msun.
a (float): Scale factor.
overdensity (float): Overdensity parameter (default: 200).... | 378366193a7e613193ba90e42abd91669b9ee797 | 3,617,941 |
def test_targets():
"""Returns the test targets which contain the main package and tests folder
"""
return [package_name(), 'tests'] | 440929fc8a6f41a078c5bf2f743c54779234f986 | 3,617,942 |
def LU_lndet(matrix, permutation, sign):
"""
Compute the determinant of {matrix} given its LU decomposition
"""
# easy enough
return gsl.linalg_LU_lndet(matrix.data) | 6fa3ec99b83ec31ff1bfaf9c49a98ff317dc0fd9 | 3,617,943 |
def _sample_household_cluster(sampler, bin_lower, bin_upper, reference_age, n):
"""
Return list of ages in a household/location based on mixing matrix and reference person age
"""
ages = [reference_age] # The reference person is in the household/location
if n > 1:
idx = np.digitize(refere... | d0f1c3b37b4376bb89396cdaa6624f393361145f | 3,617,944 |
def extract_BIO_tagged_tokens(text, source_spans, tokenizer):
""" Разобьем на bio-токены по безпробельной разметке """
tokens_w_tags = []
for span in source_spans:
s,e,tag = span
tokens = tokenizer(text[s:e])
if tag == 'Other':
tokens_w_tags += [(token,ta... | 7b56295f36040b68a3ba7d6f8c817d9f9b4c5094 | 3,617,945 |
def delete_user(id):
"""Get a particular user with it's ID and delete it."""
user = Users.query.get(id)
if user.role_id is 1:
return jsonify({
"message": "YOU DON'T WANNA DO THAT! YOU CANT DELETE AN ADMIN",
"status": 400
}), 400
user.delete()
return jsonify({
... | 2826c5ae27cf5517b4eb50ec53a076f4bc18f688 | 3,617,946 |
import glob
import os
def find_ifgs_for_dates(ifg_dir, master_date, slc_dates=None):
"""Find all the interferograms for a set of SLC dates and a given master
date.
Arguments
---------
ifg_dir : str
The directory to search for interferograms. Interferograms should be
named as SLAVE_MAS... | 1293d57ab6308e7d8ccd3c27e035b09f29debd2e | 3,617,947 |
def configure_extensions(flask_app, cli):
"""configure flask extensions
"""
db.init_app(flask_app)
cors.init_app(flask_app)
db.app = flask_app
bcrypt.init_app(flask_app)
if cli is True:
migrate.init_app(flask_app, db)
return flask_app | 1cff800aaf988db380cf5a12fc7372b3ad647039 | 3,617,948 |
import typing
import inspect
def on(
event: str,
type: EventTypes = EventTypes.COMMAND,
func: typing.Callable = None,
):
"""A proxy decorator for registering commands. This decorator will add a number of attributes within the object.
You can use this decorator to register commands with ``.register... | 350d5adebdcfb5e0d4866ffd837b15bd6807820d | 3,617,949 |
from datetime import datetime
def get_current_time()->int:
"""
Returns current timestamp in milliseconds
"""
return int(datetime.datetime.now().timestamp() * 1000) | fabde93e63770e668c0f8326a6aeb0717277d88e | 3,617,950 |
def tokenize(sentence):
"""
Using the bag words algorithm, every sentence has to be deconstructed to a
list of relevant particles. This function ecibes a sequence and uses the
nltk.word_tokenize() functtion to return a tokenized list.
>>>tokenize('How are you?')
['how', 'are', 'you', '?']
"""
return nltk.word_... | 0441a54fe4f29697330aa05658c8b5b10b821acf | 3,617,951 |
def d_key_pressed(environment, ambient=0.001):
""" Takes user input for theta and updates display. Function called
after 'd' pressed during interactive mode.
"""
environment.clearSources()
environment.updateAmbient(ambient)
dir_mag = 1.0
dir_phi = 5 * np.pi / 4
while True:
... | 896aa9fc982dbe7f8ced1c038c38e19601611102 | 3,617,952 |
def format_duration(dur: float) -> str:
"""Formats duration (from minutes) into a readable format"""
if float(dur) >= 1.0:
return "{} min".format(int(dur))
else:
return "{} sec".format(int(round(dur * 60))) | 02393e051b751001af9c8092ff64ebcef7596d6f | 3,617,953 |
import sys
def get_displacement_spectra_coeffs(tr_disp, tr_noise_disp=None, plot_switch=False, return_spectra_data=False, manual_fixed_fc_Hz=None, apply_Brune_fit_bounds=False, manual_fixed_t_star=None):
"""Function to get long-period spectral level, for calculating moment. Also finds the corner frequency and
... | 8f53fbc7b59415a2833659331b72ead82ed7f1bd | 3,617,954 |
import struct
def unpack(structure, data):
"""
Unpack little endian hexlified binary string into a list.
"""
return struct.unpack('<' + structure, bytes.fromhex(data)) | 530cf57b74be1e171a6f0c7ba148bdf73e8a7612 | 3,617,955 |
def generate_setup(field_height, cleared_rows, shape, shape_x, shape_y):
"""Generate field (in list form) to find setups for a shape at x,y that clears cleared_rows.
Todo: this whole thing needs some error handling, especially the drop-in part
"""
# initialize with all margin cells
field = [[3]... | caca0e0db576447bb66743af7170f009af131eac | 3,617,956 |
import time
def identify_missing(df=None):
"""Detect missing values.
Identify the common missing characters such as 'n/a', 'na', '--'
and '?' as missing. User can also customize the characters to be
identified as missing.
Parameters
----------
df : DataFrame
Raw data for... | 8e543f95ad8667341fc80313b4ff81e706fe7ad7 | 3,617,957 |
def get_recall(indices, targets):
""" Calculates the recall score for the given predictions and targets
Args:
indices (Bxk): torch.LongTensor. top-k indices predicted by the model.
targets (B): torch.LongTensor. actual target indices.
Returns:
recall (float): the recall score
"... | 63f4d7f36f63d3110c33989b03f264e1fa4aa4ff | 3,617,958 |
import os
def fixture_encode_wav_s24():
"""fixture_encode_wav_s24"""
wav_path = os.path.join(
os.path.dirname(os.path.abspath(__file__)),
"test_audio",
"ZASFX_ADSR_no_sustain.wav",
)
audio = tf.audio.decode_wav(tf.io.read_file(wav_path))
value = audio.audio * (1 << 31)
... | bb57cce2dd486d6d763286c768192298c7066f65 | 3,617,959 |
def get_collection_no(row):
"""Get the collection number from an expedition row."""
if row.get('collector_number'):
return row.collector_number
num = row.get('collector_number_numeric_only', '')
verb = row.get('collector_number_verbatim', '')
if verb and len(num) < 2:
return row.coll... | a3e92e24a6a5a95651b7ccde183ecc6b083a649a | 3,617,960 |
def _mi_dr(X, Y, sigma, n_bases, maxiter):
"""Estimate mutual information between X and Y using density ratio estimation.
Parameters
----------
X : array-like, shape (n_samples, n_features_x) or (n_samples)
Observations of a variable.
Y : array-like, shape (n_samples, n_features_y) or (n_sa... | e483916b9499e53c73a47adb00b2961368c8a09f | 3,617,961 |
def normalizeRows(x):
""" Row normalization function
Implement a function that normalizes each row of a matrix to have
unit length.
"""
### YOUR CODE HERE
x_sum = np.sum(x)
x = x / x_sum
### END YOUR CODE
return x | 690eacd3dfc88526640a5241cbb2570aeda66845 | 3,617,962 |
import requests
def retrieve_cluster_info(cluster_type, cluster_name):
"""
获取指定集群的信息
:param cluster_type: 集群类型
:param cluster_name: 集群名
:return: 集群信息
"""
url = "{}/storekit/clusters/{}/{}/".format(DATAHUB_API_ROOT, cluster_type, cluster_name)
res = requests.get(url=url)
if res.sta... | 6f4d73760005aa43e75431670b41d95cd0677c7f | 3,617,963 |
from typing import Union
def merge_titles(existing_work: Work, inserting_work: Work) -> Union[str, None]:
"""
Merge two titles into the best possible option
:return: string if best is changed from existing else None
"""
if existing_work.title == inserting_work.title:
best_title = N... | 1b83dc8b882f5a1372725412c697790852048f4d | 3,617,964 |
def HzanalCirc(sig, f, I, a, flag):
"""
Hz component of analytic solution for half-space (Circular-loop source)
Src and Rx are on the surface and receiver is located at the center of the loop.
.. math::
H_z = -\\frac{I}{k^2a^3} \
\\left( 3 -(3+\\imath\\ k... | fbc3b9fe91ddf55ee8611d09a568829a738d3fee | 3,617,965 |
def _get_versioned_config(config, version = ""):
"""select version from config
Args:
config: config
version: specified version, default is "".
Returns:
updated config with specified version
"""
versioned_config = {}
versioned_config.update(config)
used_version = co... | 70528e14148358613d2561c90e741b3f49569136 | 3,617,966 |
def fitDtm(initWorkingSetName,
stepName,
requestInfo,
jobId,
outputFolder,
dsmFile,
outputPrefix,
iterations=None,
tension=None):
"""
Run a Girder Worker job to fit a Digital Terrain Model (DTM) to a
Digital Surface Mode... | 88d242406ad786731e147b21b27fa918141d6b91 | 3,617,967 |
from typing import Union
def deserialize_timestamp_from_kraken(time: Union[str, FVal, int, float]) -> Timestamp:
"""Deserializes a timestamp from a kraken api query result entry
Kraken has timestamps in floating point strings. Example: '1561161486.3056'.
If the dictionary has passed through rlk_jsonloads... | 294d96b4c1aa69ef8a4aec9b8c84d283c6cd2296 | 3,617,968 |
def anti_alias_filter(x,params):
"""
Anti_aliasing: use Nyquist frequ cutoff low-pass filter
:return: anti-aliased signal
"""
fs = params['fs']
assert(type(x)==np.ndarray)
# def build_aa_filter(fs):
# """
# :param fs: sampling rate
# :return: 1D array impulse respo... | e140183050c88c27e5d8b6923cb6660ad2860525 | 3,617,969 |
import os
def build_config(config_file, args):
"""Build a ``Configuration`` instance and populate it with file data and
user inputs."""
config = Configuration()
if os.path.exists(config_file):
config.load_from_file(config_file)
config.load_from_arguments(args)
return config | 68f5299b7118b4d061e9ae0e0ccedd7b006744c2 | 3,617,970 |
import torch
def get_optimizer(optimizer_name: str, *args, **kwargs) -> torch.optim.Optimizer:
"""
A simple utility function for retrieving the desired optimizer.
Not the most optimized algorithm, but the number of optimizers should never
exceed even 100 in my opinion so a linear time algorithm is acc... | cc2a58248147aef39308d20a6ce4ddb7388f4a05 | 3,617,971 |
def rand_unselected_dut(request, duthosts, rand_one_dut_hostname):
"""
Return the left duthost after random selection.
Return None for non dualtor testbed
"""
dut_hostnames = generate_params_dut_hostname(request)
if len(dut_hostnames) <= 1:
return None
idx = dut_hostnames.index(rand_... | 3880899961d6ee9b967716d91e05c6f5b101a9e9 | 3,617,972 |
def query_author_by_org(Session, orgs):
"""Return a query that, if run, would return all RFCs whose authors'
organizations match every string in `orgs`.
The matching on `orgs` is case-insensitive. Asterisks (*) in passed orgs
are replaced with percent signs (%) to function as wildcards in the actual
... | f4d92ab991064b8e4b11dfbb4e30254b782ed284 | 3,617,973 |
import configparser
from typing import Union
def _prompt_for_option_name (ARG_config_object: configparser.ConfigParser, ARG_section: str) -> Union[str, None]:
"""Prompts the user to enter a valid option name. Checks that option name exists.
Parameters
----------
ARG_config_object : configparser.Confi... | b9aea1ba8a19d0c3a104a4e661a4043e9ad33889 | 3,617,974 |
from typing import Union
from typing import BinaryIO
from typing import Tuple
def read_leader(f: Union[str, BinaryIO]) -> Tuple[Vocab, Vectors]:
"""Read vectors from a leader file.
This is our fully binary vector format.
The first line is a header for the leader format and it is a 3-tuple.
The eleme... | 0de3bab630d555277917e0e473d2024235a4f10f | 3,617,975 |
def find_direct_conflicts(pull_ops, unversioned_ops):
"""
Detect conflicts where there's both unversioned and pulled
operations, update or delete ones, referering to the same tracked
object. This procedure relies on the uniqueness of the primary
keys through time.
"""
return [
(pull_... | 5832a41b81cffd7e5c7d1f79472f9c44eaa3127a | 3,617,976 |
def unknown_id_to_symbol(unknown_id, header="X"):
"""Get the symbol of unknown whose id is |unknown_id|.
:type unknown_id: int
:type header: str
:param unknown_id: The ID of the unknown.
:param header: The symbol header.
:rtype : str
:return: A string that contains the symbol.
"""
... | 53081447eb0c5daf70d1af936337b35bffe4caf0 | 3,617,977 |
def SurfaceEnergy(images, natoms, calc, fmax=0.01, debug=False):
"""Calculate the surface energy from a list of slab images.
Parameters
----------
images: List of slab images which the calculation is based on. The x and
y dimensions of the images unit cell must be conserved.
natoms: Number of ... | b9ec3164ce46ca9b285d6479885cbc46317edd9e | 3,617,978 |
def get_bulk_subgraphs(bulk_structure_sg):
"""
Get all subgraphs of molecules that within or crosses the boundary of
original bulk.
Parameters:
-----------
bulk_structure_sg: StructureGraph.
The structure graph of bulk with local env strategy.
Returns:
--------
super_graphs... | e66eff5bc6ec99f7934606365d775b3ba046c1f6 | 3,617,979 |
def main(instrument=None, runfile=None, **kwargs):
"""
Main function for apero_explorer.py
:param instrument: str, the instrument name
:param runfile: str, the run file to run (see the /run/ folder)
:param kwargs: additional keyword arguments
:type instrument: str
:type runfile: str
:... | e016e9e626af3fffe8341a128f04531e80723f19 | 3,617,980 |
import subprocess
def _get_git_revision_hash():
""" ref: https://stackoverflow.com/questions/14989858/get-the-current-git-hash-in-a-python-script """
return subprocess.check_output(['git', 'rev-parse', 'HEAD']).decode('ascii').strip() | 368d8873df7b06ecdc5cbddb04cfe7fa57e553a2 | 3,617,981 |
import re
def markdown_to_doxygen(string):
"""Markdown to Doxygen equations"""
long_equations = re.sub(
r"(?<!\\)\$\$(.*?)(?<!\\)\$\$", r"\\f[\g<1>\\f]", string, flags=re.DOTALL
)
inline_equations = re.sub(r"(?<!(\\|\$))\$(?!\$)", r"\\f$", long_equations)
return inline_equations | 2cae07ccb661ef22fab518d4fae4a0cc22868d84 | 3,617,982 |
def dijkstra(graph, src, dest):
"""Find shortest path from src to dest
graph:
dict[list[(int, int)]]: {node: [adj_node1, adj_node2,...]}
src (int):
dest (int):
"""
to_process = PriorityQueue()
# Start with the source and zero cost
to_process.put((0, src))
# Now as y... | 6387e0e28a84a4ae94c8163c1757bd2d2f73fdcb | 3,617,983 |
def convert_3_class(data_dir, out_dir='three_class/'):
"""
Transform attribute labels in the dataset in data_dir to create a separate prediction class for not visible attributes
"""
def filter_not_visible(d):
certainty = np.array(d['attribute_certainty'])
not_visible_idx = np.where(cert... | 2564b42d1af6e7109d6043a6f12f6eb358891a9c | 3,617,984 |
from ggrc.notifications import cron_jobs
def get_jobs_to_register(name):
"""Get cron job handlers defined in `notifications` package.
Get cron job handlers defined in `notifications` package as `name`. Note
that handlers will be returned only if `NOTIFICATIONS_ENABLED` flag in
settings is set to `True` value... | ee2ac7487a96244b636a67dad4333f728a1e02e7 | 3,617,985 |
def is_network_exists(vca_client, network_name):
"""
network already exist
"""
return bool(vca_client.get_network(get_vcloud_config()['vdc'],
network_name)) | 6d72651019be58cefd878551970e257cf0bf78c4 | 3,617,986 |
def xml_dict_to_point(data: dict) -> Point:
"""
Create a Point from a dict representing a location in KML
Args:
data: xml dict data
Returns:
Point
"""
point = Point()
point.description = data['description']
point.name = data['name']
point.style = data['styleUrl']
... | b3a03be7a9bbdefad7e9401b3b623b6ed5c0ab3b | 3,617,987 |
import random
def randprime(a, b):
"""Return a random prime number in the range [a, b)"""
n = random.randint(a-1, b)
p = nextprime(n)
if p >= b:
p = prevprime(b)
if p < a:
raise ValueError("no primes exist in the specified range")
return p | 7999e40599b76889a4212d7e84192c9f7d5c6ae6 | 3,617,988 |
import re
def pep8ify(name):
"""PEP8ify name"""
if '.' in name:
name = name[name.rfind('.') + 1:]
if name[0].isdigit():
name = "level_" + name
name = name.replace(".", "_")
if '_' in name:
return name.lower()
s1 = re.sub('(.)([A-Z][a-z]+)', r'\1_\2', name)
return re... | 355ad069c76a9a2f23821cf05ebba6fb56238984 | 3,617,989 |
from typing import Optional
from typing import List
from typing import Dict
import requests
def grip_availability(day: date, area: int = 803) -> Optional[List[Dict[str, str]]]:
"""Get the availability for date"""
response = requests.get(
GRIP_URL,
params={
"date": day.isoformat(),
... | 7f9392e513335c17c76a947c9af67ea011223a40 | 3,617,990 |
import os
def write_file(file_name):
"""
Create a file and returns the reference of it
:param file_name: The relative path of the file to be created
:return: The reference of the created file
"""
file_name = os.path.join(dir_name, file_name)
file = open(file_name, "w+")
return file | 9b475740b4bac613510f2d7e3becb7bae41174e7 | 3,617,991 |
from sys import path
def read_expected_result(test_name):
"""
:param test_name:
:return:
"""
data_file_path = path.join(
get_test_data_prefix(test_name),
"Result.xlsx"
)
return pd.read_excel(
data_file_path
) | 6c660e9261f50313e5b5082b154737645bb6164c | 3,617,992 |
import ast
def reduce_slice(obj, sliceobj):
"""generic factory for Slice nodes"""
assert isinstance(sliceobj, SlicelistObject)
if sliceobj.fake_rulename == 'slice':
start = sliceobj.value[0]
end = sliceobj.value[1]
return ast.Slice(obj, consts.OP_APPLY, start, end, sliceobj.lineno)... | 406d3c2d50919b638bff00cf7dc49686a7b2e16b | 3,617,993 |
def skip_while(self, predicate):
"""Bypasses elements in an observable sequence as long as a specified
condition is true and then returns the remaining elements. The
element's index is used in the logic of the predicate function.
1 - source.skip_while(lambda value: value < 10)
2 - source.skip_while... | c8bd569a6b12e9f60df1e22e330672f9a140d34d | 3,617,994 |
def files_inout_handler(ctx, param, value):
"""Process and validate input file names"""
return tuple(file_in_handler(ctx, param, item) for item in value[:-1]) + tuple(value[-1:]) | 9e68bbfc9979e7ce9794b6d7506c1c8d826d18f9 | 3,617,995 |
def car_to_apply(conf):
"""
查询申请车辆的信息
:param conf: 配置
:return: 车辆信息
"""
carlist = get_enter_car_list(conf)
licenseno = conf['User']['licenseno']
for car in carlist:
if car.get('licenseno') == licenseno:
return car
raise FatalError('车牌号:{}在系统中未找到,请在APP中注册。carlist={... | de603f8367c634d582d9bc04347e044ed28b4f92 | 3,617,996 |
import copy
def plugin_reconfigure(handle, new_config):
""" Reconfigures the plugin
it should be called when the configuration of the plugin is changed during the operation of the South device service;
The new configuration category should be passed.
Args:
handle: handle returned by the plug... | b08e5cd54ded08ee31c4fe64aba559d2f5b52724 | 3,617,997 |
import struct
def get_code_objects_in_code_partition(from_opened_file, code_partition_desc: CodePartitionDescriptor,
debug_prints=False):
"""
:param from_opened_file: an opened file handle; e.g. from open(filename,...). It does not have to be cue'd to any
... | ce3aaf695440620eaef4ffc13cba8113bd88f8f5 | 3,617,998 |
import os
def get_timeline():
"""
This function returns the timeline, i.e. time axis data.
Returns:
[List] -- time axis data.
"""
# init timeline
timeline = []
# Import one file @ DATASET_PATH (the "anchor_file")
files = os.listdir(DATASET_PATH)
time_anchor_file_name = ... | d57da3b4a9b5715032bb6b3a5607237f51545b1c | 3,617,999 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.