content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def gradient(v, surf):
"""
:param v: vector of x, y, z coordinates
:param phase: which implicit surface is being used to approximate the structure of this phase
:return: The gradient vector (which is normal to the surface at x)
"""
x = v[0]
y = v[1]
z = v[2]
if surf == 'Ia3d' or su... | 5,339,600 |
def authenticated_client(client, user):
"""
"""
client.post(
'/login',
data={'username': user.username, 'password': 'secret'},
follow_redirects=True,
)
return client | 5,339,601 |
def viterbi(obs, states, start_p, trans_p, emit_p):
"""
請參考李航書中的算法10.5(維特比算法)
HMM共有五個參數,分別是觀察值集合(句子本身, obs),
狀態值集合(all_states, 即trans_p.keys()),
初始機率(start_p),狀態轉移機率矩陣(trans_p),發射機率矩陣(emit_p)
此處的states是為char_state_tab_P,
這是一個用來查詢漢字可能狀態的字典
此處沿用李航書中的符號,令T=len(obs),令N=len(trans_p.key... | 5,339,602 |
def plot_antFeatureMap_2700ns(uvd, _data_sq, JD, pol='ee'):
"""
Plots the positions of all antennas that have data, colored by feature strength.
Parameters
----------
uvd: UVData object
Observation to extract antenna numbers and positions from
_data_sq: Dict
Dictionary structured... | 5,339,603 |
def verifyInstrFomat(expresions, fomatStr, lineNum):
"""
Verify if instruction has a correct format and add errors to error list if not
expresions - array of srings as parts of instruction (letter code followed by parametrs)
fomatStr - format string of the instruction
lineNum - source file line... | 5,339,604 |
def add_merge_variants_arguments(parser):
"""
Add arguments to a parser for sub-command "stitch"
:param parser: argeparse object
:return:
"""
parser.add_argument(
"-vp",
"--vcf_pepper",
type=str,
required=True,
help="Path to VCF file from PEPPER SNP."
... | 5,339,605 |
def set_time_scale_alias(name: str, target: TimeScale):
"""Sets an alias named **name** of TimeScale **target**
Args:
name (str): name of the alias
target (TimeScale): TimeScale that **name** will refer to
"""
import graph_scheduler
name_aliased_time_scales = list(filter(
l... | 5,339,606 |
def process_shared_misc_options(args, include_remote=False):
"""Process shared miscellaneous options in args.
Parse options that the resync-sync, resync-build and resync-explorer scripts use.
"""
if args.checksum:
args.hash.append('md5')
if include_remote:
if args.access_token:
... | 5,339,607 |
def find_bounding_boxes(img):
"""
Find bounding boxes for blobs in the picture
:param img - numpy array 1xWxH, values 0 to 1
:return: bounding boxes of blobs [x0, y0, x1, y1]
"""
img = util.torch_to_cv(img)
img = np.round(img)
img = img.astype(np.uint8)
contours, hierarchy = cv2.fin... | 5,339,608 |
def resolve_day(day: str, next_week: Optional[bool] = False) -> int:
"""Resolves day to index value."""
week = ['monday',
'tuesday',
'wednesday',
'thursday',
'friday',
'saturday',
'sunday']
today = datetime.now()
today_idx = date.w... | 5,339,609 |
def write_image(image,
path,
bit_depth='float32',
method='OpenImageIO',
**kwargs):
"""
Writes given image at given path using given method.
Parameters
----------
image : array_like
Image data.
path : unicode
Image p... | 5,339,610 |
def set_seed(seed: int):
"""
Set the random seed for modules torch, numpy and random.
:param seed: random seed
"""
torch.manual_seed(seed)
np.random.seed(seed)
random.seed(seed) | 5,339,611 |
def get_gsheet_data():
"""
Get's all of the data in the specified Google Sheet.
"""
# Get Credentials from JSON
logging.info('Attempting to read values to Google Sheet.')
creds = ServiceAccountCredentials.from_json_keyfile_name('TrackCompounds-1306f02bc0b1.json', SCOPES)
logging.info('Autho... | 5,339,612 |
def name_tensor(keras_tensor, name):
"""
Add a layer with this ``name`` that does nothing.
Usefull to mark a tensor.
"""
return Activation('linear', name=name)(keras_tensor) | 5,339,613 |
def pluck(ind, seqs, default=no_default):
""" plucks an element or several elements from each item in a sequence.
``pluck`` maps ``itertoolz.get`` over a sequence and returns one or more
elements of each item in the sequence.
This is equivalent to running `map(curried.get(ind), seqs)`
``ind`` can... | 5,339,614 |
def shape_metrics(model):
"""""
Calculates three different shape metrics of the current graph of the model.
Shape metrics: 1. Density 2. Variance of nodal degree 3. Centrality
The calculations are mainly based on the degree statistics of the current
graph
For more information one is referred to... | 5,339,615 |
def evaluate(model, k=10, seed=1234, evalcv=True, evaltest=False, use_feats=True):
"""
Run experiment
k: number of CV folds
test: whether to evaluate on test set
"""
print 'Preparing data...'
traintext, testtext, labels = load_data()
print 'Computing training skipthoughts...'
trainA... | 5,339,616 |
def calculate_actual_sensitivity_to_removal(jac, weights, moments_cov, params_cov):
"""calculate the actual sensitivity to removal.
The sensitivity measure is calculated for each parameter wrt each moment.
It answers the following question: How much precision would be lost if the kth
moment was ex... | 5,339,617 |
def escape_html(text: str) -> str:
"""Replaces all angle brackets with HTML entities."""
return text.replace('<', '<').replace('>', '>') | 5,339,618 |
def pptest(n):
"""
Simple implementation of Miller-Rabin test for
determining probable primehood.
"""
bases = [random.randrange(2,50000) for _ in range(90)]
# if any of the primes is a factor, we're done
if n<=1: return 0
for b in bases:
if n%b==0: return 0
te... | 5,339,619 |
def schedule_conv2d_NCHWc(outs):
"""Schedule for conv2d_NCHW[x]c
Parameters
----------
outs : Array of Tensor
The computation graph description of conv2d_NCHWc
in the format of an array of tensors.
The number of filter, i.e., the output channel.
Returns
-------
sch ... | 5,339,620 |
def calc_E_E_hs_d_t(W_dash_k_d_t, W_dash_s_d_t, W_dash_w_d_t, W_dash_b1_d_t, W_dash_ba1_d_t, W_dash_b2_d_t,
theta_ex_d_Ave_d, L_dashdash_ba2_d_t):
"""1時間当たりの給湯機の消費電力量 (1)
Args:
W_dash_k_d_t(ndarray): 1時間当たりの台所水栓における節湯補正給湯量 (L/h)
W_dash_s_d_t(ndarray): 1時間当たりの浴室シャワー水栓における節湯補正給湯量 ... | 5,339,621 |
def keras_quantile_loss(q):
"""Return keras loss for quantile `q`."""
func = functools.partial(_tilted_loss_scalar, q)
func.__name__ = f'qunatile loss, q={q}'
return func | 5,339,622 |
def writeSolverSettingsToHDF5(
solver: AmiciSolver,
file: Union[str, object],
location: Optional[str] = 'solverSettings'
) -> None:
"""
Convenience wrapper for :fun:`amici.writeSolverSettingsToHDF5`
:param file: hdf5 filename, can also be object created by
:fun:`amici.create... | 5,339,623 |
def MACD(DF, a, b, c):
"""function to calculate MACD
typical values a = 12; b =26, c =9""" | 5,339,624 |
def _load_template_file() -> Dict:
"""
Read and validate the registration definition template file, located in the
same directory as this source file
Returns
-------
Dict
Contents of the registration definition template file JSON, converted to
a Python dictionary
"""
... | 5,339,625 |
def _reactions_table(reaction: reaction_pb2.Reaction, dataset_id: str) -> Mapping[str, Union[str, bytes, None]]:
"""Adds a Reaction to the 'reactions' table.
Args:
reaction: Reaction proto.
dataset_id: Dataset ID.
Returns:
Dict mapping string column names to values.
"""
val... | 5,339,626 |
def get_incidents_for_alert(**kwargs) -> list:
"""
Return List of incidents for alert.
:param kwargs: Contains all required arguments.
:return: Incident List for alert.
"""
incidents: List[Dict[str, Any]] = []
headers = {
'X-FeApi-Token': kwargs['client'].get_api_token(),
'... | 5,339,627 |
def pbar(*args, **kwargs):
"""
Progress bar.
This function is an alias of :func:`dh.thirdparty.tqdm.tqdm()`.
"""
return dh.thirdparty.tqdm.tqdm(*args, **kwargs) | 5,339,628 |
def calc_driver_mask(n_nodes, driver_nodes: set, device='cpu', dtype=torch.float):
"""
Calculates a binary vector mask over graph nodes with unit value on the drive indeces.
:param n_nodes: numeber of driver nodes in graph
:param driver_nodes: driver node indeces.
:param device: the device of the `t... | 5,339,629 |
def all_fermions(fields: List[Field]) -> bool:
"""Checks if all fields are fermions."""
boolean = True
for f in fields:
boolean = boolean and f.is_fermion
return boolean | 5,339,630 |
def open_file(name):
"""
Return an open file object.
"""
return open(name, 'r') | 5,339,631 |
def test_init(mocker, mock_nncli):
"""test nominal initialization"""
nn_obj = nncli.nncli.Nncli(False)
nn_obj.config.get_config.assert_called_once()
nn_obj.ndb.set_update_view.assert_called_once()
assert os.mkdir.call_count == 0 | 5,339,632 |
def _bit_length(n):
"""Return the number of bits necessary to store the number in binary."""
try:
return n.bit_length()
except AttributeError: # pragma: no cover (Python 2.6 only)
import math
return int(math.log(n, 2)) + 1 | 5,339,633 |
def read_dwd_percentile_old(filename):
"""
Read data from .txt file into Iris cube
:param str filename: file to process
:returns: cube
"""
# use header to hard code the final array shapes
longitudes = np.arange(-179.5, 180.5, 1.)
latitudes = np.arange(89.5, -90.5, -1.)
data ... | 5,339,634 |
def assert_allclose(actual: numpy.float64, desired: float, atol: float, err_msg: str):
"""
usage.scipy: 4
"""
... | 5,339,635 |
def media_post():
"""API call to store new media on the BiBli"""
data = request.get_json()
fname = "%s/%s" % (MUSIC_DIR, data["name"])
with open(fname, "wb") as file:
file.write(base64.decodestring(data["b64"]))
audiofile = MP3(fname)
track = {"file": data["name"], "title": "", "artist":... | 5,339,636 |
def obtain_stores_path(options, ensure_existence=True) -> Path:
"""
Gets the store path if present in options or asks the user to input it
if not present between parsed_args.
:param options: the parsed arguments
:param ensure_existence: whether abort if the path does not exist
:return: the store... | 5,339,637 |
def data(interface, obj, _):
"""Communicate the object data. """
kind = xc_type(obj)
if kind in ['C', 'I', 'N', 'R']:
interface.data(obj)
elif kind == 'W':
interface.trans_num(len(obj))
interface.trans_name(obj)
else:
COMMUNICATE_DUMP[type(obj)](data, interface, obj, ... | 5,339,638 |
def extract_res_from_files(exp_dir_base):
"""Takes a directory (or directories) and searches recursively for
subdirs that have a test train and settings file
(meaning a complete experiment was conducted).
Returns:
A list of dictionaries where each element in the list
is an experiment and... | 5,339,639 |
def compute_roc(distrib_noise, distrib_signal):
"""compute ROC given the two distribributions
assuming the distributions are the output of np.histogram
example:
dist_l, _ = np.histogram(acts_l, bins=n_bins, range=histrange)
dist_r, _ = np.histogram(acts_r, bins=n_bins, range=histrange)
tprs, fp... | 5,339,640 |
def main(args):
"""
Please run the train and test methods with the correct arguments to train and test the models.
We have both Machine learning models and Transformer models. Machine learning models support two pre-processing types,
one is `tfidf` and the other is `word embeddings`.
Use the followi... | 5,339,641 |
def pmcfg(cfg):
"""
prints out the core config file to the prompt with a nice stagger Look for
readability
Args:
cfg: dict of dict in a hierarchy of {section, {items, values}}
"""
for sec in cfg.keys():
print(repr(sec))
for item in cfg[sec].keys():
print('\... | 5,339,642 |
def zoom(clip, screensize, show_full_height=False):
"""Zooms preferably image clip for clip duration a little
To make slideshow more movable
Parameters
---------
clip
ImageClip on which to work with duration
screensize
Wanted (width, height) tuple
show_full_height
S... | 5,339,643 |
def create(
host_address: str,
topics: typing.Sequence[str]) -> Subscriber:
"""
Create a subscriber.
:param host_address: The server notify_server address
:param topics: The topics to subscribe to.
:return: A Subscriber instance.
"""
return Subscriber(create_subscriber(host_... | 5,339,644 |
def solution(n):
"""
Return the product of a,b,c which are Pythagorean Triplet that satisfies
the following:
1. a < b < c
2. a**2 + b**2 = c**2
3. a + b + c = 1000
>>> solution(1000)
31875000
"""
product = -1
d = 0
for a in range(1, n // 3):
"""Solving t... | 5,339,645 |
def python2_binary():
"""Tries to find a python 2 executable."""
# Using [0] instead of .major here to support Python 2.6.
if sys.version_info[0] == 2:
return sys.executable or "python"
else:
return "python2" | 5,339,646 |
def write_submission_csv(output_dict, blank_submission_file_path, destination_path):
"""
Write output dictionnary in a csv submission file
"""
print "Writing predictions to csv file.. ",
df = pandas.read_csv(blank_submission_file_path)
df["Class"] = df["Class"].astype("float")
for li... | 5,339,647 |
def with_metaclass(meta, *bases):
"""A Python 2/3 compatible way of declaring a metaclass.
Taken from `Jinja 2 <https://github.com/mitsuhiko/jinja2/blob/master/jinja2
/_compat.py>`_ via `python-future <http://python-future.org>`_. License:
BSD.
Use it like this::
class MyClass(with_metacla... | 5,339,648 |
def energy(particles):
"""total kinetic energy up to a constant multiplier"""
return np.sum([particle.size ** 2 * np.linalg.norm(particle.speed) ** 2 for particle in particles]) | 5,339,649 |
def post_adaptation_non_linear_response_compression_matrix(P_2, a, b):
"""
Returns the post adaptation non linear response compression matrix.
Parameters
----------
P_2 : numeric or array_like
Point :math:`P_2`.
a : numeric or array_like
Opponent colour dimension :math:`a`.
... | 5,339,650 |
async def submissions_search(self, chan, src, msg):
"""
:name: redditsearch
:hook: cmd
:help: search for posts on reddit.
:args: subreddit:str keywords:list
:aliases: rds
"""
await self.msg(modname, chan, ["searching..."])
args = msg.split(" ", 1)
keywords = msg[1:]
sub = ms... | 5,339,651 |
def forward(network, x):
"""
入力信号を出力に変換する関数
Args:
network: ネットワークのDict
x: Inputの配列
Returns:
出力信号
"""
w1, w2, w3 = network['W1'], network['W2'], network['W3']
b1, b2, b3 = network['B1'], network['B2'], network['B3']
# 1層目
a1 = np.dot(x, w1) + b1
z1 = si... | 5,339,652 |
def join_with_and(words: List[str]) -> str:
"""Joins list of strings with "and" between the last two."""
if len(words) > 2:
return ", ".join(words[:-1]) + ", and " + words[-1]
elif len(words) == 2:
return " and ".join(words)
elif len(words) == 1:
return words[0]
else:
... | 5,339,653 |
def condition_generator(single_sub_data, params_name, duration = 2):
"""Build a bunch to show the relationship between each onset and parameter
Build a bunch for make a design matrix for next analysis. This bunch is for describing the relationship
between each onset and parameter.
Args:
single... | 5,339,654 |
def create_pkg(
meta: Dict, fpaths: Iterable[_res_t], basepath: _path_t = "", infer=True
):
"""Create a datapackage from metadata and resources.
If ``resources`` point to files that exist, their schema are inferred and
added to the package. If ``basepath`` is a non empty string, it is treated
as t... | 5,339,655 |
def one_hot(
encoding_size: int, mapping_fn: Callable[[Any], int] = None, dtype="bool"
) -> DatasetTransformFn:
"""Transform data into a one-hot encoded label.
Arguments:
encoding_size {int} -- The size of the encoding
mapping_fn {Callable[[Any], int]} -- A function transforming the input d... | 5,339,656 |
def test_event_manager_installed():
"""Test that EventManager is installed on the Flask app"""
app = create_ctfd()
assert type(app.events_manager) == EventManager
destroy_ctfd(app) | 5,339,657 |
def test_hash_evoked():
"""Test evoked hashing
"""
ave = read_evokeds(fname, 0)
ave_2 = read_evokeds(fname, 0)
assert_equal(hash(ave), hash(ave_2))
# do NOT use assert_equal here, failing output is terrible
assert_true(pickle.dumps(ave) == pickle.dumps(ave_2))
ave_2.data[0, 0] -= 1
... | 5,339,658 |
def compute_perplexity(result):
"""Compute and add the perplexity to the LogReport.
:param dict result: The current observations
"""
# Routine to rewrite the result dictionary of LogReport to add perplexity values
result["perplexity"] = np.exp(result["main/nll"] / result["main/count"])
if "vali... | 5,339,659 |
def is_url_relative(url):
"""
True if a URL is relative, False otherwise.
"""
return url[0] == "/" and url[1] != "/" | 5,339,660 |
def distance_matrix(lats, lons):
"""Compute distance matrix using great-circle distance formula
https://en.wikipedia.org/wiki/Great-circle_distance#Formulae
Parameters
----------
lats : array
Latitudes
lons : array
Longitudes
Returns
-------
dists : matrix
... | 5,339,661 |
def _split_link_ends(link_ends):
"""
Examples
--------
>>> from landlab.grid.unstructured.links import _split_link_ends
>>> _split_link_ends(((0, 1, 2), (3, 4, 5)))
(array([0, 1, 2]), array([3, 4, 5]))
>>> _split_link_ends([(0, 3), (1, 4), (2, 5)])
(array([0, 1, 2]), array([3, 4, 5]))
... | 5,339,662 |
def test_inpschema_dict(data_regression, schema_version):
"""
Test the produced inputschema dicts
"""
from masci_tools.io.parsers.fleur.fleur_schema import InputSchemaDict
inputschema = InputSchemaDict.fromVersion(version=schema_version)
data_regression.check(clean_for_reg_dump(inputschema.get... | 5,339,663 |
def dijkstra(vertex_count: int, source: int, edges):
"""Uses Dijkstra's algorithm to find the shortest path in a graph.
Args:
vertex_count: The number of vertices.
source : Vertex number (0-indexed).
edges : List of (cost, edge) (0-indexed).
Returns:
costs : List ... | 5,339,664 |
def save_canvas_images(images, names):
"""
Saves the canvas images
"""
for image, name in zip(images, names):
cv2.imwrite(name, image) | 5,339,665 |
def save_picture(form_picture):
"""
function for saving the path to the profile picture
"""
app = create_app(config_name=os.getenv('APP_SETTINGS'))
# random hex to be usedin storing the file name to avoid clashes
random_hex = secrets.token_hex(8)
# split method for splitting the filename fro... | 5,339,666 |
def plot_labels(labels, lattice=None, coords_are_cartesian=False, ax=None, **kwargs):
"""
Adds labels to a matplotlib Axes
Args:
labels: dict containing the label as a key and the coordinates as value.
lattice: Lattice object used to convert from reciprocal to Cartesian coordinates
... | 5,339,667 |
def test_nov_sample_problem():
"""Test the sample problem given in the Novendstern correlation paper;
parameters are all calculated and shown in the paper, just using them
to demonstrate that I get the same result with the implemented corr."""
# Dummy class to mock DASSH Coolant, Subchannel, RegionRodd... | 5,339,668 |
def contains(poly0, poly1):
""" Does poly0 contain poly1?
As an initial implementation, returns True if any vertex of poly1 is within
poly0.
"""
# check for bounding box overlap
bb0 = (min(p[0] for p in poly0), min(p[1] for p in poly0),
max(p[0] for p in poly0), max(p[1] for p in poly... | 5,339,669 |
def get_ids_in_annotations(scene, frame, quality):
"""
Returns a set of all ids found in annotations.
"""
annotations_path = os.path.join(scene, '%sPose3d_stage1' % quality,
'body3DScene_%s.json' % frame)
if not os.path.exists(annotations_path):
return se... | 5,339,670 |
def new_halberd(game_state):
"""
A composite component representing a Sword item.
"""
c = Composite()
set_item_components(c, game_state)
set_melee_weapon_component(c)
c.set_child(Description("Halberd",
"A long stick with a with an axe-head at one end."
... | 5,339,671 |
def get_regional_services(service_list: List[AWSService] = None) -> List[AWSService]:
"""List all services which are tied to specific regions."""
services = service_list or get_services()
return [s for s in services if s.is_regional] | 5,339,672 |
def request_master(msys, mode=MasterMode.NORMAL,
timeout=CONF.pypowervm_job_request_timeout):
"""Request master mode for the provided Managed System.
:param msys: Managed System wrapper requesting master mode
:param mode: The requested master mode type.
There are 2 optio... | 5,339,673 |
def _ReapUntilProcessExits(monitored_pid):
"""Reap processes until |monitored_pid| exits, then return its exit status.
This will also reap any other processes ready to be reaped immediately after
|monitored_pid| is reaped.
"""
pid_status = None
options = 0
while True:
try:
(pid, status, _) = os... | 5,339,674 |
def lookup_entry(override_values):
"""Retrieves Data Catalog entry for the given Google Cloud Platform resource."""
# [START datacatalog_lookup_dataset]
# [START data_catalog_lookup_entry]
from google.cloud import datacatalog_v1
datacatalog = datacatalog_v1.DataCatalogClient()
bigquery_project... | 5,339,675 |
def f_setup_config(v_config_filename):
"""This function read the configuration file"""
df_conf_file = pd.read_csv(v_config_filename, delimiter="|", header=0)
api_key = df_conf_file[df_conf_file.CONFIG_VAR == 'API_KEY']['VALUE'].values[0]
data_dir = df_conf_file[df_conf_file.CONFIG_VAR == 'DATA_DIR']['V... | 5,339,676 |
def choose_username(email):
"""
Chooses a unique username for the provided user.
Sets the username to the email parameter umodified if
possible, otherwise adds a numerical suffix to the email.
"""
def get_suffix(number):
return "" if number == 1 else "_"+str(number).zfill(3)
user_mo... | 5,339,677 |
def lms2rgb(image):
"""
Convert an array of pixels from the LMS colorspace to the RGB colorspace. This function assumes that
each pixel in an array of LMS values.
:param image: An np.ndarray containing the image data
:return: An np.ndarray containing the transformed image data
"""
return np... | 5,339,678 |
def __apply_to_property_set (f, property_set):
""" Transform property_set by applying f to each component property.
"""
properties = feature.split (property_set)
return '/'.join (f (properties)) | 5,339,679 |
def make_boxplot(ratios, facecolor, position):
"""Add box and whisker plot of the 300 overconfidence ratios.
Args:
ratios ([300] numpy array): overconfidence ratios on
300 points in middle segment of diagonal line.
facecolor (string): color of boxplot bar
position (float): ho... | 5,339,680 |
def _zip_index(job_context: Dict) -> Dict:
"""Zips the index directory into a single .tar.gz file.
This makes uploading and retrieving the index easier since it will
only be a single file along with compressing the size of the file
during storage.
"""
temp_post_path = job_context["gtf_file"].ge... | 5,339,681 |
def _return_feature_statistics(feature_number: int, feature_value: float, names: list):
"""
Arguments:
feature_number (int) -- number of the feature
feature_value (float) -- value of the feature (used to compute color)
names (list) -- list of feature names
Returns:
"""
per... | 5,339,682 |
def calc_eta_FC(Q_load_W, Q_design_W, phi_threshold, approach_call):
"""
Efficiency for operation of a SOFC (based on LHV of NG) including all auxiliary losses
Valid for Q_load in range of 1-10 [kW_el]
Modeled after:
- **Approach A (NREL Approach)**:
http://energy.gov/eere/fuelcells/d... | 5,339,683 |
def test_storage_profiling():
"""
This test tests the saving and loading of profiles
into HDF5 through pypesto.store.ProfileResultHDF5Writer
and pypesto.store.ProfileResultHDF5Reader. Tests all entries
aside from times and message.
"""
objective = pypesto.Objective(
fun=so.rosen, gra... | 5,339,684 |
def erdos_renyi(
num_genes: int, prob_conn: float, spec_rad: float = 0.8
) -> Tuple[np.ndarray, float]:
"""Initialize an Erdos Renyi network as in Sun–Taylor–Bollt 2015.
If the spectral radius is positive, the matrix is normalized
to a spectral radius of spec_rad and the scale shows the
normalizati... | 5,339,685 |
def new_window(window_name):
"""Create a new window in a byobu session and give it a name.
Parameters
----------
window_name : str
Name for the new byobu window.
"""
subprocess.call(f"byobu new-window", shell=True)
subprocess.call(f"byobu rename-window '{window_name}'", shell=True)... | 5,339,686 |
def IMG_LoadTextureTyped_RW(renderer, src, freesrc, type):
"""Loads an image file from a file object to a texture as a specific format.
This function allows you to explicitly specify the format type of the image
to load. The different possible format strings are listed in the
documentation for :func:`I... | 5,339,687 |
def process_one_email(q, count, id_val, dt, email):
""" Submit an email address to the Full Contact Person API and process
the responses
Process the response object based on the return status code
Parameters
----------
q : an instance of a Priority Queue
count : the count from the origina... | 5,339,688 |
def addOverride(cls, override):
"""Override the serializer to use 'override' as the identifier for instances of 'cls'
This is primarily to shorted the amount of data in the representation and to allow the
representation to remain constant even if classes are moving around or changing names.
override m... | 5,339,689 |
def soft_l1(z: np.ndarray, f_scale):
"""
rho(z) = 2 * ((1 + z)**0.5 - 1)
The smooth approximation of l1 (absolute value) loss. Usually a good choice for robust least squares.
:param z: z = f(x)**2
:param f_scale: rho_(f**2) = C**2 * rho(f**2 / C**2), where C is f_scale
:return:
"""
loss... | 5,339,690 |
def calculate_hit_box_points_detailed(image: Image, hit_box_detail: float = 4.5):
"""
Given an image, this returns points that make up a hit box around it. Attempts
to trim out transparent pixels.
:param Image image: Image get hit box from.
:param int hit_box_detail: How detailed to make the hit bo... | 5,339,691 |
def generate_from_template(file_path, template, **kwargs):
# type: (str, Template, Any[str]) -> None
"""
Generates file according to the template with given arguments
"""
with open(file_path, 'w') as cmake_lists:
target_cmake_lists = template.render(**kwargs)
cmake_lists.write(target... | 5,339,692 |
async def open_local_endpoint(
host="0.0.0.0", port=0, *, queue_size=None, **kwargs
):
"""Open and return a local datagram endpoint.
An optional queue size argument can be provided.
Extra keyword arguments are forwarded to `loop.create_datagram_endpoint`.
"""
return await open_datagram_endpoint(... | 5,339,693 |
def polySplitEdge(q=1,e=1,op="int",cch=1,ch=1,n="string",nds="int"):
"""
http://help.autodesk.com/cloudhelp/2019/ENU/Maya-Tech-Docs/CommandsPython/polySplitEdge.html
-----------------------------------------
polySplitEdge is undoable, queryable, and editable.
Split Edges.
There are two operations for this c... | 5,339,694 |
def parse_bool(value: Union[str, bool]) -> bool:
"""Parse a string value into a boolean.
Uses the sets ``CONSIDERED_TRUE`` and ``CONSIDERED_FALSE`` to determine the boolean value of the string.
Args:
value (Union[str, bool]): the string to parse (is converted to lowercase and stripped of surroundi... | 5,339,695 |
def test_merge_tag_handler_error_handling() -> None:
"""Merge tag should correctly handle errors."""
_check_merge_tag(
ListField(StringField()),
'!merge scalar_value',
expected_error=ErrorCode.UNEXPECTED_NODE_TYPE
)
_check_merge_tag(
ListField(StringField()),
'!m... | 5,339,696 |
def download_progress_hook(count, blockSize, totalSize):
"""A hook to report the progress of a download. This is mostly intended for users with
slow internet connections. Reports every 5% change in download progress.
"""
global last_percent_reported
percent = int(count * blockSize * 100 / totalSize)
if last... | 5,339,697 |
def send_rocketchat_notification(text: str, exc_info: Exception) -> dict:
""" Sends message with specified text to configured Rocketchat channel.
We don't want this method to raise any exceptions, as we don't want to
unintentionally break any kind of error management flow. (We only use
rocket chat noti... | 5,339,698 |
def get_number_of_forms_all_domains_in_couch():
"""
Return number of non-error, non-log forms total across all domains
specifically as stored in couch.
(Can't rewrite to pull from ES or SQL; this function is used as a point
of comparison between row counts in other stores.)
"""
all_forms =... | 5,339,699 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.