content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def eval_ws(in_data, ws_labels, n_map, label=None, re_all=False):
"""Evaluate and return the best watershed prediction result
Parameters
----------
in_data : np.array or list
data matrix
ws_labels : np.array
predicted cluster labels from watershed segmentation
n_map : np.array
... | 01120016e3f4975d6eaace31b7b24adc6c07b3e2 | 3,624,600 |
def team_width(positions, points=False):
"""Returns the maximum string width of a team."""
width = 0
for position in positions:
if points:
player_names = [PICKS_FORMAT.format(
player.name, player.gameweek_points,
player.role) for player in position]
... | 168ff4c047728730f87e8f5337841f7eb6340cab | 3,624,601 |
def construct_bbox(all_points):
"""
Construct the bounding box based on all points from the
road and buildings that were discretised.
"""
maximum = list(map(max, zip(*all_points)))
minimum = list(map(min, zip(*all_points)))
bbox = [(minimum[0], minimum[1]),
(minimum[0], maximum... | 77f01466bbef500c7c79eee39ad3a69926ec8fc3 | 3,624,602 |
def OpenDocument(filePath) -> NexDoc:
"""Opens a data file with the specified path. Returns a reference to the opened document."""
return NexRun("OpenDocument", locals()) | 69d4cae74d0525d78cb08fee04e5f62de3c9eabf | 3,624,603 |
def solver_rho_complete_nonorm(dp):
"""
Returns rho.
dp is full param dict (with "k_Gp_rho" and "kGp_myo"
"""
dp["Gt"] = dp["Gt_res"]
dp["k_Gp"] = dp["k_Gp_rho"]
dp["Gpt"] = dp["Gpt_rho"]
r = solver_dict_complete_nonorm(dp)
return r[:,1] | bc044daa721fd4b71a5639ecf5baaed59d9b7e07 | 3,624,604 |
from datetime import datetime
def my_review(book_id):
"""
Check to see whether the user is logged in.
Find a book by the supplied book_id.
Find the review related to that book,
written by the logged-in user.
Render the view_book page with that information.
"""
# Check to see whether th... | 0abd66a76b613459d2123466b9ae13b258c3834d | 3,624,605 |
import os
import zipfile
def unzip_files(file_list, force=False):
"""Given a list of file paths, unzip them in place.
Attempts to skip it if the extracted folder exists.
Parameters
----------
file_list : list of str
Files to extract.
force : bool, default=False
Force the unz... | 185c52329a3b85cf5a25b9f91e12647917fecee3 | 3,624,606 |
def base64encode(byte_arr):
"""
Encodes an array of binary values to a base64 string.
Args:
byte_arr - the array of bytes to encode
Returns:
A base64 encoding of the given binary data
"""
length = len(byte_arr)
paddingAmount = length % 3
base64_string = ""
# blocks o... | ca0201ad7eaf8d1e9db361ce183e1e424a81fa85 | 3,624,607 |
import math
def dist(p1, p2):
"""
Determines the straight line distance between two points p1 and p2 in euclidean space.
"""
d = math.sqrt(math.pow(p1[0] - p2[0], 2) + math.pow(p1[1] - p2[1], 2))
return d | 8a72ba5966452e7ac2e44f4c1f61d78071423ace | 3,624,608 |
def resize(x, p=2):
"""Resize heatmaps."""
return x**p | b39b25e3c35b1bfa4e76deb638b77ba3fca8c781 | 3,624,609 |
def varifocal_loss(pred,
target,
alpha=0.75,
gamma=2.0,
iou_weighted=True,
reduction='mean',):
"""`Varifocal Loss <https://arxiv.org/abs/2008.13367>`_
Args:
pred (torch.Tensor): The prediction with shape (N, ... | ee707342ea414307613b5875e40078b91dfaa5c5 | 3,624,610 |
def pointIsInside(x,y):
"""pointIsInside
Arguments:
x,y -- x and y coordinates of the point.
returns true if it is inside of the Circumference.
"""
return x**2 + y**2 <= 1. | 16e32c8705e08e868355f3bda5a9b5ae6d6a6f8c | 3,624,611 |
def most_probable_words(vocab, topic_word_distrib, doc_topic_distrib, doc_lengths, n=None):
"""
Order the words from `vocab` by marginal word probability from most to least probable. Optionally only
return the `n` most probable words.
.. seealso:: :func:`~tmtoolkit.topicmod.model_stats.marginal_word_di... | a5f266497659127c64c835cd94ae57f34c8635af | 3,624,612 |
def subscribe_to_responsys(campaign, address, format='html', source_url='',
lang='', country='', **kw):
"""
Subscribe a user to a list in responsys. There should be two
fields within the Responsys system named by the "campaign"
parameter: <campaign>_FLG and <campaign>_DATE.
... | ce38dc0402afdab4dcec224b360d81fdac872f50 | 3,624,613 |
from typing import Optional
def _get_vt_api_key() -> Optional[str]:
"""Retrieve the VT key from settings."""
prov_settings = get_provider_settings("TIProviders")
vt_settings = prov_settings.get("VirusTotal")
if vt_settings:
return vt_settings.args.get("AuthKey")
return None | 977843b5d66eac66f5c9c9d084e06201ba2865ab | 3,624,614 |
def test_qubefit_single():
""" This test will load a thin disk data set which includes gaussian noise
and it will try to fit this data set using the qubefit procedure.
"""
# load the thin disk model
Cube = create_thindiskmodel()
# define the mask to use for the fitting
Cube.create_maskarr... | af0353ebcb9105cb93832b5ab58e3519a235c0ad | 3,624,615 |
def create_qso(con, qso):
""" Function for actually writing qso entries, called by getqso()"""
sql = ''' INSERT INTO qso(utcdate, utctime, band, mode,
ocall, ocat, osec, tcall, tcat, tsec)
VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?) '''
cur.execute(sql, qso)
con.commit()
ret... | af68e06445fe2dbc16af4bf489820f64fe45fec4 | 3,624,616 |
def smooth(mat, kernel):
"""
Function that produce a smoothed version of the 2D array
:param mat: Array to smooth
:param nPix: kernel array (output) from the function kernel_square()
:return: smoothed array
"""
r = cv2.filter2D(mat, -1, kernel)
print("Smoothing done ...")
return r | a6f1bb5b371286ff2b89bee836976c03ca924726 | 3,624,617 |
def get_pcs(X, n_pcs, **kwargs):
"""
Assumes X has shape (...,n_features)
"""
shape = X.shape
X = X.reshape((-1,shape[-1]))
max_n_pcs = min(X.shape) # min(n_data_points, n_features)
if n_pcs == -1:
n_pcs = max_n_pcs
assert n_pcs <= max_n_pcs # Can't have more than max_n_pcs
p... | 2b33eb96146929d8ad44f564212d2d6f203c907b | 3,624,618 |
import optparse
def parse_commandline():
"""
returns (files, test_mode) created from the command line arguments
passed to pytddmon.
"""
usage = "usage: %prog [options] [static file list]"
version = "%prog " + '1.0.8'
parser = optparse.OptionParser(usage=usage, version=version)
parser.a... | 5b98e682e05514585dcb488f4386b1a1611f6b5a | 3,624,619 |
def load_candidate(path_to_candidate):
"""Load candidate data from a file.
Args:path_to_candidate (str): path to file to load.
Returns:qid_to_ranked_candidate_passages (dict): dictionary mapping from query_id (int) to a list of 1000 passage ids(int) ranked by relevance and importance
"""
with open(... | c25189f709eb9fa00044bd5e0e3ed5e1d5f54371 | 3,624,620 |
def convert_4d_matrix_to_2d_block(K):
"""Convert a 4D matrix of shape ``M, M, V, V`` to a block matrix of shape ``M*V, M*V``"""
M, _, V, __ = K.shape
_K = np.zeros((M*V, M*V))
for i in range(M):
for j in range(M):
_K[i*V:(i+1)*V,j*V:(j+1)*V] = K[i,j,:,:]
return _K | 89e5288d2c63a47c8407c89c1ab63aaadee667a1 | 3,624,621 |
from typing import List
import glob
def get_l10n_files() -> List[str]:
"""取得所有翻譯相關檔案列表,包括.pot .po .mo。
Returns:
List[str]: 翻譯相關檔案列表,包括.pot .po .mo。
"""
po_parser = 'asaloader/locale/*/LC_MESSAGES/asaloader.po'
pot_file = 'asaloader/locale/asaloader.pot'
po_files = glob.glob(po_parser)... | a783679261e7c9bd617728946d01a440b51cfb6a | 3,624,622 |
import logging
import os
def filter_standardize(data_in, low_frequency, high_factor, order,
sampling_frequency, buffer_size, filename_dat,
n_channels, output_directory):
"""Butterworth filter for a one dimensional time series
Parameters
----------
ts: np.... | d5de1a0e2e7018c0e7852097eb26a13d18c30ff8 | 3,624,623 |
def get_or_create_service_account(
project_id,
account_id,
account_name,
google_credentials
):
"""
Get a service account or create it if it does not exist.
Args:
project_id:
The ID of the project the service account is contained in.
account_id... | 6d09a854bb11dffd3cde434a63e7bc43d9c529e2 | 3,624,624 |
def delivery_pricing_api_url():
"""
Delivery Pricing API
"""
return get_parameter("/ecommerce/{Environment}/delivery-pricing/api/url") | 5c7ffad311f8bbeff05da6b488a37d5d6b8dcc97 | 3,624,625 |
def filter_value(entry, values=None):
"""
Returns True if it should be filtered.
Only take calls with filter values in the list provided
if None provided, assume that filter_value must be PASS or blank '.'
"""
if values is None:
return len(entry.filter) != 0 and 'PASS' not in entry.filte... | 57ee5ab67fa07cb8c1379d303e9d636718025f45 | 3,624,626 |
def sample_nonlinear_icp_sim(
dag,
n_samples,
nonlinearity="id",
noise_df=2,
combination="additive",
intervention_targets=None,
intervention="soft",
intervention_shift=0,
intervention_scale=1,
intervention_pct=None,
random_state=None,
pre_intervention=False,
lambda_no... | 572aef9f2533a31921f039ec655f4ef8bd39afd5 | 3,624,627 |
def process_data(expected_keys, data):
"""
Check for any expected but missing keyword arguments
and raise a TypeError else return the keywords arguments
repackaged in a dictionary i.e the payload.
:param expected_keys:
:param data:
:return payload:
"""
payload = {}
for key in exp... | a7d9b87af72d5217cdd6c67ab27986780bea293a | 3,624,628 |
def restore_scores(scores, shape, shift):
"""
Restores scores to original size using linear interpolation.
Arguments:
scores -- original 'compressed' scores
shape -- shape of the restored scores
shift -- sliding windows shift
"""
new_scores = np.zeros(shape)
for i in range(1, scor... | 8b2b42fabd22c2e0e2fc15d5df2e6950863ac531 | 3,624,629 |
def get_mtime_for_page():
"""获取分时数据"""
rps = {}
rps["status"] = True
if request.form.get("symbol") or request.form.get("timestamp"):
symbol = request.form["symbol"]
timestamp = request.form["timestamp"]
data = get_stock_mtime(symbol, timestamp, tdx)
if data:
... | 77be6a37bd44527919d651f81d8ef079282ce8af | 3,624,630 |
import numpy
import sys
def get_dist_mat(opts, bb_atoms):
"""
Takes a list of prody.Atoms and calls calc_dist_matrix
"""
### Commenting this out, since I don't require <dist> arg in usage
# Distance threshold for contact maps.
# if opts["<dist>"]:
# opts["<dist>"] = float(opts["<dist>"])
if opts["--mask-... | c31e4462fe4cbd83d5501d721006242cba45399a | 3,624,631 |
def make_song_title(artists: list, name: str, delim: str) -> str:
"""
Generates a song title by joining the song title and artist names.
Artist names given in list format are split using the given delimiter.
"""
return f"{delim.join(artists)} - {name}" | 341db19af517c09633a6ebe37726c79c020f4780 | 3,624,632 |
import os
def list_fastmodels(check_models=False):
"""! List all models and configs in fm_agent"""
resource = FastmodelAgent()
model_dict = resource.list_avaliable_models()
columns = ['MODEL NAME', "MODEL Binary Full Path", 'CONFIG NAME' , 'CONFIG FILE', 'AVAILABILITY']
if check_models:
... | f0119c6cde0c288f8fafd515f39eb7401c352f47 | 3,624,633 |
def changeSamplingRateOfSignal(
data,
oldSamplingFrequency,
newSamplingFrequency,
tmpPath = None,
tmpFileName = 'tmp.wav',
sincWidth = 200,
normalize = False
):
"""
change the sampling frequency of a given signal. similar to @ref
changeSamplingRate(), but does not operate on a saved sound file, b... | 5d6fbbbc223590b0d02d2563d03358666bd7400c | 3,624,634 |
def get_mangled_dataframe(metal_currency_key):
"""
Parameter: The key in Redis.
E.g. XAU-USD
"""
currency = metal_currency_key.split('-')[1]
metal = metal_currency_key.split('-')[0]
df = redis_to_dataframe(metal_currency_key)
# convert usd pricing
if currency == 'USD':
... | 90b69dbc326979199103cce9f0fca5847ac0f602 | 3,624,635 |
def value_to_idx(val_range, unique_values, run_idx):
"""Return the index that belongs to the value at run index.
Parameters
----------
range
unique_values
run_idx
Returns
-------
"""
return np.where(unique_values == val_range[run_idx])[0] | 5e455434825e9d4e14a651b935e5908b3d922c74 | 3,624,636 |
def struct_parse(struct, stream, stream_pos=None):
""" Convenience function for using the given struct to parse a stream.
If stream_pos is provided, the stream is seeked to this position before
the parsing is done. Otherwise, the current position of the stream is
used.
Wraps the erro... | ab2629a7155d1d3f199aff1c706663bc93953675 | 3,624,637 |
def DEFAULT_RENAMER(L, Names=None):
"""
Renames overlapping column names of numpy ndarrays with structured dtypes
Rename the columns by using a simple convention:
* If `L` is a list, it will append the number in the list to the key
associated with the array.
* If `L` is a dictionary,... | 62afcc8538d57ca2181419a13acdd5f307895be1 | 3,624,638 |
def authorizeView(user, identifier):
"""
Returns True if a request to view identifier metadata is authorized.
'user' is the requestor and should be an authenticated StoreUser
object. 'identifier' is the identifier in question; it should be a
StoreIdentifier object.
"""
# In EZID, essentially all iden... | c831d74a229043a308226d6ae8078e5630507ded | 3,624,639 |
from pathlib import Path
def create_absolute_installed_file_path(root_dir, file_path):
"""
Return an absolute path to `file_path` given the root directory path at
`root_dir`
"""
file_path = remove_drive_letter(file_path)
# Append the install location to the path string `root_dir`
return st... | 721f610f65b84456e1755e44eea77e0b98744f47 | 3,624,640 |
def test_doc_add_tag_function(flat_mode):
""" Tests that the @add_tag example from doc (functions only) works """
if not flat_mode:
@function_decorator
def add_tag(tag='hi!'):
"""
Example decorator to add a 'tag' attribute to a function.
:param tag: the 'tag'... | 292707b9ba8a4cde589fde26a23c43d7c2445103 | 3,624,641 |
def sort(reader, buf_size, cmp=None, key=None, reverse=False):
"""
Creates a data reader whose data output is sorted.
Output from the iterator that created by original reader will be
buffered into sort buffer, and then sorted. The size of sort buffer
is determined by argument buf_size.
:param ... | f99f21db52c5c85dfad712ad0e5aeb1e7aa9a432 | 3,624,642 |
import glob
import os
def getSequenceNumbers(radar_dir, data_format):
""" Get all the numbers from input file names """
assert isinstance(data_format, list)
assert all(isinstance(x, str) for x in data_format)
assert (len(data_format) == 2 or len(data_format) == 3)
sequence_numbers = []
for thi... | eab5d93871bf1c28f208c8a93dd7abc6f3d4fa45 | 3,624,643 |
def __get_editor_of_statement(uid):
"""
:param uid:
:return:
"""
db_statement = DBDiscussionSession.query(TextVersion).filter_by(statement_uid=uid).order_by(
TextVersion.uid.desc()).first()
db_editor = DBDiscussionSession.query(User).get(db_statement.author_uid)
gravatar = get_profi... | 5edcabe74669711828709ba617dfa2d0409be9bd | 3,624,644 |
import os
import logging
import json
def get_strategy(tpu='', gpus=None):
"""Chooses a distribution strategy.
AI Platform automatically sets TF_CONFIG environment variable based
on provided config file. If training is run on multiple VMs different strategy
needs to be chosen than when it is run on o... | b055bfb8f538fefb98e490877bea7eedb0fe1cd2 | 3,624,645 |
def clean_keyword(kw):
"""Given a keyword parsed from the header of one of the tutorials, return
a 'cleaned' keyword that can be used by the filtering machinery.
- Replaces spaces with capital letters
- Removes . / and space
"""
return kw.strip().title().replace('.', '').replace('/', '').replac... | eb8ab983bf60f5d1ca2996dc9568ded252d00479 | 3,624,646 |
from typing import Union
from pathlib import Path
import hashlib
def compute_md5(path: Union[str, Path], chunk_size: int):
"""Return the MD5 checksum of a file, calculated chunk by chunk.
Parameters
----------
path : str or Path
Path to the file to be read.
chunk_size : int
Chunk ... | 9e718630323b002307a54e7d3bbf936b6b94637a | 3,624,647 |
def is_canonical_emoji_sequence(seq):
"""Return true if this is a canonical emoji sequence (has 'vs' where Unicode
says it should), and is known."""
_load_emoji_sequence_data()
return seq in _emoji_sequence_data | 6ccf079ee2904cb3ff370d41c1478b947d3c43ca | 3,624,648 |
def align_coefs(coefs, lag, verbose=False):
"""
coefs: n* lag x n. the i * lagth row of col k is the auto-coefficient of k on k
# align the coefs:
# split into same lag
return: lag x n x n. the
"""
assert len(coefs.shape) == 2
assert coefs.shape[0] / lag == coefs.shape[1]
n = coef... | b5b10a736b1cca25d692ce5763cd77195727d6fb | 3,624,649 |
def calc_zq(qz, zp, zm, En, aa):
"""
function used in computing polar geodesic coordinates
Parameters:
qz (float)
zp (float): polar root
zm (float): polar root
En (float): energy
aa (float): spin
Returns:
zq (float)
"""
ktheta = (aa ** 2 * (1 - E... | 4cd285a74ba1d86b438ec8ef379aed898e6613f5 | 3,624,650 |
def equation_dw18(dbconn, speccode, biomassassign, dbh, ht):
""" Equation form: ((a + b * dbh + c * (dbh ^ d))-(e + f * dbh + g * (dbh ^ h))) """
qstr = "SELECT a, b, c, d, e, f, g, h FROM VolBioCoeffs WHERE SpecCode = '%s'" % (biomassassign)
c = dbconn.cursor()
c.execute(qstr)
coeffs = c.fetchone()... | de2cc9702bdfcce3686fe5fa50d346571803ce55 | 3,624,651 |
def denormalize(images, min_, max_):
"""scales image back to min_, max_ range"""
return [((i + 1) / 2 * (max_ - min_)) + min_ for i in images] | 3071e3c76754bda8ea2ce9607003cfd1b4f97e48 | 3,624,652 |
def update_config(config, args):
"""Update config by ArgumentParser
Args:
args: ArgumentParser contains options
Return:
config: updated config
"""
if args.cfg:
_update_config_from_file(config, args.cfg)
config.defrost()
if args.dataset:
config.DATA.DATASET = a... | f0c7dbb0ea32b8682ad2b2c7fe60ce0caa0e6b1f | 3,624,653 |
def update_or_create_variable(site, slug, date, value):
"""Update or create variable
"""
variable = None
try:
variable = Variable.objects.get(site=site, slug=slug)
variable.update_value(date, value)
variable.save()
except Variable.DoesNotExist:
LOGGER.info("Variable c... | 75feb3716199354e9b3137dd14f15fd96743bdb2 | 3,624,654 |
def version_is_locked(version):
"""
Determine if a version is locked
"""
return getattr(version, "versionlock", None) | b2f76d89c2d0082ad13d5d896e5360d394c83ee1 | 3,624,655 |
from datetime import datetime
import platform
def generate(request, recipient):
"""
Generate a test email.
:param request: the current request
:type request: pyramid.request.Request
:param recipient: the recipient of the test email
:type recipient: str
:returns: a 4-element tuple contain... | 6b4926e5fb1e1791cc6ef20b6ad53a76a0451b16 | 3,624,656 |
def pssm_scan(pwm, seqs, background_probs=[0.27, 0.23, 0.23, 0.27], pad_mode='median', n_jobs=10, verbose=True):
"""
"""
def pwm2pssm(arr, background_probs):
"""Convert pwm array to pssm array
pwm means that rows sum to one
"""
arr = arr / arr.sum(1, keepdims=True)
ar... | 077ec517fde9d65d626a3473674c400b0199c40b | 3,624,657 |
def build_orientation_img(d, mask):
"""
Args:
d: [.., H, W, 8]
mask: [..., H, W]
"""
y = np.expand_dims(mask, -1)
cw = color_wheel
did = np.argmax(d, -1)
new_shape = []
for ss in xrange(len(y.shape) - 1):
new_shape.append(y.shape[ss])
new_shape.append(3)
c... | 3a67abb8e7a108c7eeb56e3c4717166f90c44869 | 3,624,658 |
def compute_projection_transforms(origins, transformer) -> np.ndarray:
"""
Convert vectors from one coordinate system to another. Unlike positions,
this cannot be done with a simple pyproj call. We first need to set up a
vector start and end point, convert those into the new coordinate system
and th... | 90f86b83c16a9190444c501c88c6bbc09a2388b7 | 3,624,659 |
def get_function_by_name(full_name):
"""
RETURN FUNCTION
"""
# IMPORT MODULE FOR HANDLER
path = full_name.split(".")
function_name = path[-1]
path = ".".join(path[:-1])
constructor = None
try:
temp = __import__(path, globals(), locals(), [function_name], -1)
output =... | 12131fe15f3614518469f217596192692b2e7a51 | 3,624,660 |
def get_app(endpoints):
"""
:param list(Endpoint) endpoints: Endpoints describing the mapper
:rtype: aiohttp.web.Application
:returns: an app configured as describes in endpoints
"""
app = web.Application(middlewares=[error_middleware])
async def on_startup(app):
app['rabbitmq_conne... | bc56aeabefe0ff057721c740d10d0073e51687cd | 3,624,661 |
import os
def FdtFsParse(path):
"""Parse device tree filesystem and return a Fdt instance
Should be /proc/device-tree on a device, or the fusemount.py
mount point.
"""
root = FdtNode("/")
if path.endswith('/'):
path = path[:-1]
nodes = {path: root}
for subpath, subdirs... | 535c86afac2b823d089ba5884f988666d29d81d7 | 3,624,662 |
import copy
def get_abbr_data():
"""
Get a deep copy of the abbreviation map.
Returns
-------
:class:`dict` (:class:`str`, :class:`str`)
A dictionary of the identifiers, the keys are the abbreviation.
"""
return copy.deepcopy(_glass_type_registry) | 98465fa72e64b95f51c7548e233b172be13bdec2 | 3,624,663 |
from typing import Union
def _load_data_input_from_file(path: str, **further_parse_args) -> Union[pd.DataFrame, list]:
"""Load and process the input data according the input file format."""
if path.endswith(CSV):
return from_dataframe_file(path, CSV)
elif path.endswith(XLS_FORMATS):
retur... | 67b3ebe052d78640340850fb7200c1672a550544 | 3,624,664 |
def generate_ceiling_json(conf: ConfigManager, polyline, room_id: str, multiplication_factor: float) -> dict:
"""
Generate a json describing a ceiling.
:param conf: ConfigManager
:param polyline: Outline of the room
:param room_id: id of the room
:param multiplication_factor: Scale factor to rea... | 56617b32543c9dea58ff9c15efe42b82eb7ea002 | 3,624,665 |
def _compute_edge_transforms(node_states,
depth,
num_transforms,
ignore_zero=True,
name="transform"):
"""Helper function that computes transformation for keys and values.
Let B be the number of batch... | 8c7c88014dd33e0b44df953407a0e64c9cabda15 | 3,624,666 |
def optimize(model, **kwargs):
"""Removes LogSoftmax and positive scaling (Mul) layers from the network because they do not change the prediction.
Args:
model (NeuralNet): The NeuralNet model.
Returns:
NeuralNet: The NeuralNet model with removed layers.
"""
while( (isinstance(model... | 6b7cd43377517c2ea301a629cbf8fb46c8f0e4fe | 3,624,667 |
import logging
def fetch_run(workspace: Workspace, run_recovery_id: str) -> Run:
"""
Finds an existing run in an experiment, based on a recovery ID that contains the experiment ID and the actual RunId.
The run can be specified either in the experiment_name:run_id format, or just the run_id.
:param wo... | ba9c3b8d2c5c50cc82ac50ad4485b4348e11f9d1 | 3,624,668 |
def mono_anal(y, fs, param=None):
"""Run pyin on an audio signal y.
Parameters
----------
y : np.array
audio signal
fs : float
audio sample rate
param : dict default=None
threshdistr : int, default=2
Yin threshold distribution identifier.
- 0 ... | 24b2607d97c2254ff5def47370e301cd60199e7e | 3,624,669 |
import os
def add_compilation_details():
"""
Append HTML compilation warnings/errors details
Returns:
a string with formatted HTML details section.
"""
cwd = os.getcwd()
details = ''
with open(os.path.join(cwd, DETAILS_HEADER), 'r') as temp:
details = temp.read()
deta... | 7749466a78bc126dbb3d805fc25e3107883585f1 | 3,624,670 |
import os
import joblib
def load_model(model_file):
"""Load a pretained model from pickel file."""
if not os.path.exists(model_file):
raise IOError("Model file does not exist: %s" %model_file)
model = joblib.load(model_file)
print("INFO: Model %s was loaded successfully." \
%os.pa... | 636a5cdf1188485b3aaf45ec1dfac318f9858cbf | 3,624,671 |
def format_dict(_dict, tidy=True):
"""
This function format a dict. If the main dict or a deep dict has only on element
{"col_name":{0.5: 200}} we get 200
:param _dict: dict to be formatted
:param tidy:
:return:
"""
if tidy is True:
levels = 2
while (levels>=0):
... | 8db7ca24e73202ad409c9ae7e5890dd68fcc64e3 | 3,624,672 |
def get_crc24(data: str) -> dict:
"""
Implementation of the CRC-24 algorithm from OpenPGP.
Returns the CRC-24 checksum value in decimal and hexadecimal format.
"""
data = bytearray(data.encode('utf-8'))
crc = 0x00b704ce
for byte in data:
crc = (CRC24_TABLE[((crc >> 16) ^ byte) & 0xff... | 368fb2565301e54809fa5841fcd504c3547c3c13 | 3,624,673 |
import getpass
from datetime import datetime
import json
import time
def new_ec2_instances(cluster,
n=1,
maxWait=180,
instance_type=None,
ami=None,
key=None,
az=None,
... | 0dd24da9e4e34811c46d4fd7df7916603a98c4e9 | 3,624,674 |
import requests
def create_pivot_value_request_param(request_params: dict, postgrest_host: str) -> dict:
"""Find the pivot value for a seek pagination.
This should only happen if the user is sorting by anything other than `int_id`,
and wants to get data after a certain `int_id`.
NOTE: This function pe... | 7106f84159cdc1b39afaa9a93c46909243797a3c | 3,624,675 |
def pfirst(*args, **kwargs):
"""
For each occurrence of this function in source code, print only on the first call. e.g.
>>> for n in [1, 2]:
... _ = pfirst(n * 10)
... _ = pfirst(n * 100)
10
100
"""
stack = _getstack()
if not stack in pfirst.seen_stacktraces:
pf... | 1ca85da1112543c13f1113c1cf3eb7b1d2f03942 | 3,624,676 |
import gzip
import itertools
def read_obo(file):
""" read ontology from file
:param file: file path of file handle
"""
G = nx.DiGraph()
if isinstance(file, str):
if file.endswith('.gz'):
f = gzip.open(file, 'rt')
else:
f = open(file)
we_opened_file ... | e41e0201f349d1030e16b59bf78b3a3d6ac3c5eb | 3,624,677 |
def _GetColocationNames(op):
"""Returns names of the ops that `op` should be colocated with."""
colocation_names = []
try:
class_values = op.get_attr('_class')
except ValueError:
# No _class attr
return
for val in class_values:
val = compat.as_str(val)
if val.startswith('loc:@'):
col... | d68cb092f878e506b9b1999b4cbd9ff43f571b99 | 3,624,678 |
def _current_trace():
"""Returns the innermost Jax tracer."""
tracers = _masters()
if tracers:
return tracers[-1]
return None | f467c31b1082ae8eb002a4b66f988364876a130f | 3,624,679 |
def tailor_queries(query_item, query_target):
"""
This substitutes common parameters for values from the script.
Later, this will be a data driven exercise.
"""
replacements = dict()
replacements['{{deployment}}'] = query_target.split('_')[0]
replacements['{{org_id}}'] = query_target.split('... | 40a7b0890f9ccb5beffab28567da5f4898b0fd92 | 3,624,680 |
import argparse
import random
def parse_args():
"""Parse command line arguments."""
parser = argparse.ArgumentParser(
description='GloVe with GluonNLP',
formatter_class=argparse.ArgumentDefaultsHelpFormatter)
# Data options
group = parser.add_argument_group('Data arguments')
group... | b40d14c2f3aaa8918453478c64dddbba020d78cf | 3,624,681 |
def enlarge(image, size, axis=1, efunc=energy_function, cfunc=compute_cost, dfunc=duplicate_seam, bfunc=backtrack_seam, rfunc=remove_seam):
"""Enlarges the size of the image by duplicating the low energy seams.
We start by getting the k seams to duplicate through function find_seams.
We iterate through the... | 0eca80d904663cc3ba3ab2e68debd4a2bb76ac7b | 3,624,682 |
import sys
def _extract_traceback(start):
"""
SNAGGED FROM traceback.py
RETURN list OF dicts DESCRIBING THE STACK TRACE
"""
tb = sys.exc_info()[2]
for i in range(start):
tb = tb.tb_next
return _parse_traceback(tb) | 1c6fd9c5a49f930b41e8bc13220bde15a1b7e8b6 | 3,624,683 |
import random
def get_answer(random_country_index):
""" Function that randomly decides the type of the answer (either LANGUAGES or CAPITALS).
It also accesses the dictionary using the randomly generated index and it fetches the
corresponding item from it."""
random_question = random.randint(1,10)
... | 99bff119dd63f6893fcb4693d832873400b6c3ae | 3,624,684 |
def Rx(r):
"""Construct a rotation matrix around X-axis."""
return _Rx(np.cos(r), np.sin(r)) | f225d98c9df560ab32e0834a710e79c5fdb25f41 | 3,624,685 |
from datetime import datetime
def dtime(dstr):
"""Convert datetime strings to datetime instances."""
if isinstance(dstr, bytes):
dstr = dstr.decode()
return datetime.datetime.strptime(dstr, fs_fmt) | fc2c1ec626b9cb11aee9b694a75f0010febfba45 | 3,624,686 |
def _create_split(last_key, next_key, query):
"""Create a new {@link Query} given the query and range..
Args:
last_key: the previous key. If null then assumed to be the beginning.
next_key: the next key. If null then assumed to be the end.
query: the desired query.
Returns:
A split query with fe... | 10f62ce1b5cf36bd04083fac3c601eb6a19ca16d | 3,624,687 |
import struct
def compute_checksum(message):
"""Calculates the 16-bit one's complement of the one's complement sum
of a given message."""
# If the message length isn't a multiple of 2 bytes, we pad with
# zeros
if len(message) % 2:
message += struct.pack('x')
# We build our blocks to... | 30b9665d8fce75d0b55b43f025b9c7c755507522 | 3,624,688 |
import random
import io
import os
def makeFont(showtext, srcfont, tgtfont):
"""制作字体"""
source_font = TTFont(srcfont)
source_cmap = source_font.getBestCmap()
plain_text = _pre_deal_obfuscator_input_str(showtext)
obfuscator_code_list = random.sample(range(0xE000, 0xF8FF), len(plain_text))
_chec... | a98f467b35f0babbb813b49fdc02ebe3de3796d1 | 3,624,689 |
def mockup_return(*args, **kwargs):
"""Mockup to replace regular functions for error injection."""
return False | 92172e58a11e48a09c8f181ac55aa717b5fbb94d | 3,624,690 |
def publish_shelter(shelter_id=None):
"""
Publish/Unpublish a shelter.
"""
shelter = Shelter.query.filter(Shelter.id == shelter_id).first()
if shelter:
shelter.is_published = request.args.get('publish',
not shelter.is_published)
db.sess... | d435229b6e9b78773f25ea058b5a3ad890c817a3 | 3,624,691 |
from datetime import datetime
def convert_utc_to_pdt(time_of_interest: datetime) -> datetime:
""" Get the datetime in Pacific Daylight Timezone (PDT) : UTC-7 given a
datetime in UTC timezone """
return time_of_interest.astimezone(timezone(offset=timedelta(hours=PDT_UTC_OFFSET))) | 72620398f9d6bc5a952fa1a47e062bf70b5477bd | 3,624,692 |
def format_input(param):
"""Return a string with all the inputs property formatted. """
tmp1 = ' {type} {var}{ctor}; XC_LI_.load({var});\n'
tmp2 = ' {type} {var}{ctor}; XC_LI_.load({var}, {sample});\n'
inputs = ''
for par in param:
if 'sample' in par:
inputs += tmp2.format(... | 41b4c26369e3be43b5466c9c375609571d5a04a4 | 3,624,693 |
def example(method):
"""Performs a short example run of the retrievals using local
machine.
Parameters
----------
method : str
The method to use to perform the atmopsheric retrieval; can
either be ``multinest`` or ``emcee``
"""
# Ensure that the method parameter is valid
... | d31cee875522ed9a69e82a70288e3a551b317226 | 3,624,694 |
def patient_sur(N, t, survival, show=False):
""" generate N patient survival time from survival function """
y_n = np.random.uniform(0, 1.0, N)
x_n = np.interp(1 - y_n, 1 - survival, t)
if show:
plt.plot(x_n, y_n, '.')
plt.plot(t, survival)
plt.xlabel('Time')
plt.ylabel... | 40a4388927c3aed7782b8bc94a3fed98109f6a71 | 3,624,695 |
import logging
import os
import json
def validate_args(args):
"""
"""
if not args.output.endswith(".tf"):
logging.exception(f'Output filename should end with .tf (i.e output.tf)')
raise ValueError('Output filename should end with .tf (i.e output.tf)')
if args.input == "ALL":
... | 9a1328b27e741999b8383f63abbe0caccd24e518 | 3,624,696 |
def get_git_project_files():
"""Retrieve a list of all non-ignored files, including untracked files,
excluding deleted files.
:return: sorted list of git project files
:rtype: :class:`list`
"""
cached_and_untracked_files = git_ls_files(
'--cached', # All files cached in the index
... | e856d693a9de3643740e4311ffef310b29b4f490 | 3,624,697 |
def _remove_digital_filter(dic, data):
"""
Remove the digital filter from Bruker data.
nmrglue modified Digital Filter Processing
"""
if "acqus" not in dic:
raise KeyError("dictionary does not contain acqus parameters")
if "DECIM" not in dic["acqus"]:
raise KeyError("dictionary ... | 580e2e0ae8c0091e380e01e9962ab9ddce0cf82d | 3,624,698 |
def add_codes(err_cls):
"""Add error codes to string messages via class attribute names."""
class ErrorsWithCodes(object):
def __getattribute__(self, code):
msg = getattr(err_cls, code)
return "[{code}] {msg}".format(code=code, msg=msg)
return ErrorsWithCodes() | 24ec122c290628c218a01867824fda681c4e7e88 | 3,624,699 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.