content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
from typing import List
import operator
def find_top_slices(metrics: List[metrics_for_slice_pb2.MetricsForSlice],
metric_key: Text,
statistics: statistics_pb2.DatasetFeatureStatisticsList,
comparison_type: Text = 'HIGHER',
min_num_example... | 7d71a2a64001e792b4e7cc9467ae99bfe30ebf99 | 3,637,614 |
def parse_texts(texts):
"""
Create a set of parsed documents from a set of texts.
Parsed documents are sequences of tokens whose embedding vectors can be looked up.
:param texts: text documents to parse
:type texts: sequence of strings
:return: parsed documents
:rtype: sequence of spacy.Do... | 05f39ffa453ca448fe1d724d2a5fbb53c52c8ade | 3,637,615 |
import _json
def dict_to_string(d):
"""Return the passed dict of items converted to a json string.
All items should have the same type
Args:
d (dict): Dictionary to convert
Returns:
str: JSON version of dict
"""
j = {}
for key, value in d.items():
if value is Non... | 3a7b3e464fa68b262be7b08bdefa1c35f603b68f | 3,637,616 |
def load_test_data(path, var, years=slice('2017', '2018')):
"""
Args:
path: Path to nc files
var: variable. Geopotential = 'z', Temperature = 't'
years: slice for time window
Returns:
dataset: Concatenated dataset for 2017 and 2018
"""
assert var in ['z', 't'], 'Test... | fa30a9514654bb3f99f74eaed7b87e3e2eb23430 | 3,637,618 |
def encode(state, b=None):
"""
Encode a base-*b* array of integers into a single integer.
This function uses a `big-endian`__ encoding scheme. That is, the most
significant bits of the encoded integer are determined by the left-most
end of the unencoded state.
>>> from pyinform.uti... | 09b5e96c3b9238d41f02cad938b6cb370a3a41da | 3,637,619 |
from typing import Optional
from typing import Set
def get_equivalent(curie: str, cutoff: Optional[int] = None) -> Set[str]:
"""Get equivalent CURIEs."""
canonicalizer = Canonicalizer.get_default()
r = canonicalizer.single_source_shortest_path(curie=curie, cutoff=cutoff)
return set(r or []) | af5cc4049af258b7724539e81218ef74dd8a3229 | 3,637,620 |
def _standardize_input(y_true, y_pred, multioutput):
"""
This function check the validation of the input
input should be one of list/tuple/ndarray with same shape and not be None
input will be changed to corresponding 2-dim ndarray
"""
if y_true is None or y_pred is None:
raise ValueErro... | c536e777c40a5ce7c886b20f61fac7f20341c20b | 3,637,621 |
import logging
def disk_detach(vmdk_path, vm):
"""detach disk (by full path) from a vm and return None or err(msg)"""
device = findDeviceByPath(vmdk_path, vm)
if not device:
# Could happen if the disk attached to a different VM - attach fails
# and docker will insist to sending "unmount/de... | b0f835c51eec4d97a8a925e12cbd3c7531b13fde | 3,637,622 |
def url_mapper(url, package):
"""
In a package.json, the "url" field is a redirection to a package download
URL published somewhere else than on the public npm registry.
We map it to a download url.
"""
if url:
package.download_urls.append(url)
return package | 95d6b67a42cac14110b457b96216a40a5d5430f9 | 3,637,624 |
import random
def electricPotential(n, V_SD_grid, V_G_grid):
"""
Function to compute the electric potential of the QDot.
:param n: the number of electrons in the dot
:param V_SD_grid: the 2d array of source-drain voltage values
:param V_G_grid: the 2d array of gate voltage values
:return: The... | fedc11b23d781d16c786dca213eaa578de8017f6 | 3,637,625 |
def mettre_a_jour_uids(nom_fichier, organisateurs, uids):
""" Met à jour le fichier CSV UID,EMAIL à partir du dictionnaire """
nouveaux_uids = False
for id_reunion in organisateurs:
if organisateurs[id_reunion]["id_organisateur"] not in uids:
uids[organisateurs[id_reunion]["id_organisate... | ac0f61b135c8a7bb9de9bb6b5b8e3f9fd7b176f0 | 3,637,626 |
import warnings
def _spectrogram(signal, dB=True, log_prefix=20, log_reference=1,
yscale='linear', unit=None,
window='hann', window_length=1024, window_overlap_fct=0.5,
cmap=mpl.cm.get_cmap(name='magma'), ax=None):
"""Plot the magnitude spectrum versus time.
... | 3648918524c73dff4427a49119a9926eea317f81 | 3,637,627 |
import pprint
def _merge_cwlinputs(items_by_key, input_order, parallel):
"""Merge multiple cwl records and inputs, handling multiple data items.
Special cases:
- Single record but multiple variables (merging arrayed jobs). Assign lists
of variables to the record.
"""
items_by_key = _maybe_n... | f78777f391747e964be6d02f77bb5c42db084546 | 3,637,628 |
def polar_distance(x1, x2):
"""
Given two arrays of numbers x1 and x2, pairs the cells that are the
closest and provides the pairing matrix index: x1(index(1,:)) should be as
close as possible to x2(index(2,:)). The function outputs the average of
the absolute value of the differences abs(x1(index(1... | f3f4f564a6645d183b5d7b1ce700e2ddf40241b7 | 3,637,629 |
def _calc_data_point_locations(num_points, x_values=None):
"""Returns the x-axis location for each of the data points to start at.
Note: A numpy array is returned so that the overloaded "+" operator can be
used on the array.
The x-axis locations are scaled by x_values if it is provided, or else the
... | 645af74a2547e25add5e7d7b0d8292568933c177 | 3,637,630 |
def is_base(base_pattern, str):
"""
base_pattern is a compiled python3 regex.
str is a string object.
return True if the string match the base_pattern or False if it is not.
"""
return base_pattern.match(str, 0, len(str)) | d0b0e3291fdbfad49698deffb9f57aefcabdce92 | 3,637,631 |
def stations_by_river(stations):
"""For a list of MonitoringStation objects (stations),
returns a dictionary that maps river names (key) to a list of MonitoringStation objects on a given river."""
# Dictionary containing river names and their corresponding stations
rivers = {}
for station in stati... | c7fc460aa3e387285abdddfcb216a8ec41d27e06 | 3,637,632 |
def dQ_dY(time):
"""Derivative of transformation matrix for nutation/presession with regards to the Y coordinate of CIP in GCRS
"""
# Rotation matrices
R3_E = R3(E(time))
R3_s = R3(s(time))
R2_md = R2(-d(time))
R3_mE = R3(-E(time))
dR3_s = dR3(s(time))
dR3_E = dR3(E(time))
dR3_mE... | 7341de34dccb4134bdc9b3d29e247dcc35b550bb | 3,637,633 |
def calculate(x: int, y: int = 1, operation: str = None) -> int:
"""Calculates the sum (or difference) of two numbers.
Parameters:
`x` : int
The first number
`y` : int, optional
The second number (default is `1`)
`operation`: str, optional
Pass "subtract" to perform subtract... | e2f79940c7329895bafe0c5ad2b17953f8276902 | 3,637,634 |
def get_power_state(instance):
"""Return the power state of the received instance.
:param instance: nova.objects.instance.Instance
:return: nova.compute.power_state
"""
instance_info = manage.VBoxManage.show_vm_info(instance)
return instance_info.get(constants.VM_POWER_STATE) | 407488593d5f29cb4d70387bdab18b5d13db5b23 | 3,637,635 |
def toBoolean(val, default=True):
"""convert strings from CSV to Python bool
if they have an empty string - default to true unless specified otherwise
"""
if default:
trueItems = ["true", "t", "yes", "y", "1", "on", ""]
falseItems = ["false", "f", "no", "n", "none", "0"]
else:
... | d3ca42f73674d0104c2c036462ae421b00501cd3 | 3,637,636 |
from typing import Union
def cache_put(
connection: 'Connection', cache: Union[str, int], key, value,
key_hint=None, value_hint=None, binary=False, query_id=None,
) -> 'APIResult':
"""
Puts a value with a given key to cache (overwriting existing value if any).
:param connection: connection to Ign... | 357141ac0cc128ee2cf9ff9db76bec10d947ede0 | 3,637,637 |
def _process_rows(app, sheet_name, rows, names_map, lang=None):
"""
Processes the rows of a worksheet of translations.
This is the complement of get_bulk_app_sheets_by_name() and
get_bulk_app_single_sheet_by_name(), from
corehq/apps/translations/app_translations/download.py, which creates
these... | 3cb43f813822b1d18ee6afa90412a7a4d6cec7e5 | 3,637,638 |
def parse_line(line, metric):
"""Parses statistics from a line an experiment log file"""
if "top-k" in line:
return f"top-k.{metric}", parse_csv(line)
elif "bottom-k" in line:
return f"bottom-k.{metric}", parse_csv(line)
else:
return f"ml.{metric}", parse_csv(line) | 9f9f263d3a27256ca98bfc42dbb7426044b8ba42 | 3,637,639 |
from typing import Tuple
def get_adjusted_pvalues(pvals: pd.Series, fdr_thresh: float = 0.05) \
-> Tuple[pd.Series, float]:
"""
Function that controls FDR rate.
Accepts an unsorted list of p-values and an FDR threshold (1).
Returns:
1) the FDR associated with each p-value,
2) the p-val... | d77bb4721eedd6af0797d2e4c7ea3fac8ddc0ab4 | 3,637,640 |
def solve_nonogram(constraints):
"""this function is solving all kinds of boards of the game and returning
the all possible solutions for it""" # BTM
return [solve_easy_nonogram(constraints)] | ec4f7a853af8d216ca800cc3aa2bde6a57c07a8b | 3,637,641 |
def uwid(string):
"""Return the width of a string"""
if not PY3:
string = string.decode('utf-8', 'ignore')
return sum(utf_char_width(c) for c in string) | adae434637415293443570f11ba58035eecf7d98 | 3,637,644 |
def check_double_quote(inpstring):
"""
Check if some strings needs of a double quote (if some space are inside the string, it will need to be inside two double quote). E.g.: --sfmt="TIFF (unstitched, 3D)"
Input:
inpstring: input string or array of strings
Output:
newstring = new string (or... | 3da3941d9cd8c4c72643f87c533bcfbfbd9b9a79 | 3,637,645 |
def get_linear_schedule_with_warmup(
num_warmup_steps, num_training_steps, last_epoch=-1
):
"""
Create a schedule with a learning rate that decreases linearly from the initial lr set in the optimizer to 0,
after a warmup period during which it increases linearly from 0 to the initial lr set in the optim... | 10ee7baafd4751c0d578207706653b5c63f192f3 | 3,637,647 |
import base64
def search_image_targets_for_tag(trust_data: dict, image: Image):
"""
Searches in the `trust_data` for a digest, given an `image` with tag.
"""
image_tag = image.tag
if image_tag not in trust_data:
return None
base64_digest = trust_data[image_tag]["hashes"]["sha256"]
... | 11cfb3e0fb985c8730f72f32466e77881a503b8b | 3,637,648 |
def calculate_intersection(a: BoundingBox, b: BoundingBox) -> int:
"""Calculate the intersection of two bounding boxes.
:param BoundingBox a: The first bounding box.
:param BoundingBox b: The second Bounding box.
:returns iou: The intersection of ``a`` and ``b``.
:rtype: int
"""
left = max(... | 74fd375f21a26af23208ba96bbd678ce30367b8f | 3,637,650 |
def build_nn_model(input_shape):
"""Generate NN model
:param: input_shape (tuple): shape of the input
:return model: NN model
"""
model = keras.Sequential([
# input layer
# multi demensional array and flatten it out
# inputs.shape[1]: the intervals
# inpu... | c4f56369875bb5ae99b2f98ac25a91b9a985f5a8 | 3,637,652 |
from typing import Optional
def getLatestCode(appDbConnStr: str) -> Optional[ICode]:
"""get latest created code from db
Args:
appDbConnStr (str): app db connection string
Returns:
Optional[ICode]: code object
"""
latestIdFetchsql = """
select id
from code_... | aba4106f99e1e23cf0127ad45502bd17cde9c33e | 3,637,654 |
def start_initialization_pd(update: Update, context: CallbackContext) -> str:
"""When touch "Заполнить данные"."""
u = User.get_user(update, context)
current_text = update.effective_message.text
update.effective_message.edit_text(
text=current_text
)
context.bot.send_message(
c... | 8af74466b5dc84ef4ee0b5ff5a2d824a275ee5c9 | 3,637,655 |
def rpm_comments(table=RPMComment, prefix='comment_', relationships=False):
"""Get filters for rpm comments.
:param sqlalchemy.ext.declarative.api.declarativemeta table: database model
:param string prefix: prefix of the name of the filter
:return dict: dict of filters
"""
filters = dict(
... | b7e34abdc81e3afa2b19ffe118d129068526b315 | 3,637,656 |
def split_line(line) -> list:
"""Split a line from a dmp file"""
return [x.strip() for x in line.split(" |")] | e9c5fb93bab1007b3deb11b8d71fe0cffd3f5bab | 3,637,657 |
def translate(text):
"""."""
return text | a0732d6a802f9846de5b294863f2c096f72c6c70 | 3,637,658 |
def stream_bytes(data, chunk_size=default_chunk_size):
"""Gets a buffered generator for streaming binary data.
Returns a buffered generator which encodes binary data as
:mimetype:`multipart/form-data` with the corresponding headers.
Parameters
----------
data : bytes
The data bytes to stream
chunk_size : int... | b329f56cae62122dd4e341dfc80c9c6aaae7ba31 | 3,637,659 |
def helper(n, big):
"""
:param n: int, an integer number
:param big: the current largest digit
:return: int, the final largest digit
"""
n = abs(n)
if n == 0:
return big
else:
# check the last digit of a number
if big < int(n % 10):
big = int(n % 10)
# check the rest of the digits
return helper(n/1... | aa7fa862d326d9e3400b58c9c520a10672e7340c | 3,637,660 |
def getPageNumber(ffile):
"""
Extract the page number from the file name
:param ffile:
:return: image URI as a string
"""
return str(ffile).split('_')[-1].split('.')[0] | f78166ae3da8ea234c98436144e6c815f341ff5e | 3,637,663 |
import colorsys
def colors_stepsort(r,g,b,repetitions=1):
"""
Sort colors in hue steps for more perceptually uniform colormaps
"""
lum = np.sqrt( .241 * r + .691 * g + .068 * b )
h, s, v = colorsys.rgb_to_hsv(r,g,b)
h2 = int(h * repetitions)
lum2 = int(lum * repetitions)
v2 = int(v * r... | c9ac5729c4208e681e3a91e09746b3bc8f0b3cc5 | 3,637,664 |
def get_string_hash(string: str, algorithm_name: str):
"""Calculates the hash digest of a string.
Args:
string: str: The string to digest.
algorithm_name: str: The name of the algorithm to hash the string with.
Returns:
A hash digest in string form.
"""
hash_algorithm = _get_alg... | 31eb5504703412ac775ae4344ef1ff2c4176104d | 3,637,665 |
import tqdm
def psd_error(times,rates,errors):
"""
obtain errors for the best frequency estimate of the signal
"""
"""
print(len(times),len(rates),len(errors))
newdatachoice = np.random.choice(len(times),size=int(0.1*len(times)))
newtimes = list(np.array([times[0]])) + list(np.array([times[-1]])) + list(time... | ecb8dcb297872dae1e9c9a0b491feaf2b2c74490 | 3,637,666 |
def solve(global_step):
"""add solver to losses"""
# learning reate
lr = _configure_learning_rate(82783, global_step)
optimizer = _configure_optimizer(lr)
tf.summary.scalar('learning_rate', lr)
# compute and apply gradient
losses = tf.get_collection(tf.GraphKeys.LOSSES)
regular_losses =... | 085317d679495ab1959106c64fdeb10aeeeeab02 | 3,637,667 |
def get_features_from_policy(env, policy):
"""Represent policies with average feature vector.
This only makes sense for linear reward functions, but it is only used for the
HighwayDriving environment.
"""
assert isinstance(env.unwrapped, HighwayDriving)
assert isinstance(policy, FixedPolicy)
... | 524256c80a8c4dec7b30378e5a377ac02456ffa7 | 3,637,668 |
def predicate(line):
"""
Remove lines starting with ` # `
"""
if "#" in line:
return False
return True | ff7d67c1fd7273b149c5a2148963bf898d6a3591 | 3,637,670 |
def pad_slices(ctvol, max_slices): #Done testing
"""For <ctvol> of shape (slices, side, side) pad the slices to shape
max_slices for output of shape (max_slices, side, side)"""
padding_needed = max_slices - ctvol.shape[0]
assert (padding_needed >= 0), 'Image slices exceed max_slices by'+str(-1*padding_n... | 01b03094dd66a770cb40a136399486bbc018e969 | 3,637,671 |
import random
def average_img_from_dir(path_data_dir,filepat="*", \
parentaslabel=False,\
labels=[],\
sampling_rate=0.001,\
title="average image") :
"""
create and visualize average image of given dataset
dataset_path = path to dataset
sampling_r... | 98aaf33c35483a9100bb25d667970f9f177955f8 | 3,637,672 |
def get_size(positions):
"""Get the size of bounding rectangle that embodies positions.
Args:
positions (dict of Dendrogram: np.array): positions xy coordinates of dendrograms
Returns:
Tuple of width and height of bounding rectangle.
"""
max_y_list = [dendrogram.height + coords[1] ... | 2a212541746963d0aa83320d3aa08ddfb5d6f6e0 | 3,637,673 |
def getContactInfo(dic):
"""Returns the Contact info for Chapters.
dic -- Dictionary from the JSON with all values.
"""
return str(dic["content"]["$t"]).split(',')[1].split(':')[1].strip() | 27ed9bcb1e91db3cf58b82023505cfcffab00bcd | 3,637,674 |
import torch
import time
def draw_pointcloud(x: torch.Tensor, x_mask: torch.Tensor, grid_on=True):
""" Make point cloud image
:param x: Tensor([B, N, 3])
:param x_mask: Tensor([B, N])
:param grid_on
:return: Tensor([3 * B, W, H])
"""
tic = time.time()
figw, figh = 16., 12.
W, H = 2... | 8828088f8f319f0033c55a4fb5c63705a882f8cd | 3,637,675 |
def semantic_dsm(word_list, keyed_vectors):
"""Calculate a semantic dissimilarity matrix."""
vectors = np.array([keyed_vectors.word_vec(word) for word in word_list])
dsm = np.clip(pdist(vectors, metric="cosine"), 0, 1)
return dsm | 05a08b09af0cc95dc647c4a2388824a2f94ed7ec | 3,637,676 |
def prompt_id_num(message, length=ID_WIDTH):
""" Asks the user to enter a identifier which is a numeric string.
The length is the length of the identifier asked.
:param message: message to ask the input
:param length: the length of the identifier
:return: input
"""
response = input(message... | 5cf705e600891bf168ac77ecf3d57637144d7b97 | 3,637,677 |
def click_snr(wl, Spec):
"""Calculate snr in a specific range given by clicks on a plot """
plt.figure()
plt.plot(wl, Spec)
plt.show(block=True)
# points from click
# temp values untill implement above
point2 = np.max(wl)
point1 = np.min(wl)
map2 = wl < point2
map1 = wl > point1... | b61216780bce3e63687c4fc79b37de8e138fa756 | 3,637,678 |
def rnn_cell_forward(xt, a_prev, parameters):
"""
Implements a single forward step of the RNN-cell
Arguments:
xt -- your input data at timestep "t", numpy array of shape (n_x, m).
a_prev -- Hidden state at timestep "t-1", numpy array of shape (n_a, m)
parameters -- python dictionary containing:... | 891a5ec7a789dbd4e1ee67598c9e350d9eacffee | 3,637,679 |
def load_song(trainsize=5000, testsize=5000):
""" The million song dataset
Not a good dataset for feature selection or regression
Standard linear regression performs only a little bit better than a random vector.
Additional complex models, such as interesting kernels, are needed
To improve per... | ee428f7c34f256ab9eb3e271751932cc4abcdb4c | 3,637,681 |
def convert_node(node_data: NodeData):
"""
Convenience method for converting NodeData to a packed TLV message.
:param core.emulator.data.NodeData node_data: node data to convert
:return: packed node message
"""
node = node_data.node
services = None
if node.services is not None:
... | bef0f45295325e15c09249152d3252b7ed949b2e | 3,637,682 |
def parse_null_value(
null_value_node: "NullValueNode", schema: "GraphQLSchema"
) -> None:
"""
Returns the value of an AST null value node.
:param null_value_node: AST null value node to treat
:param schema: the GraphQLSchema instance linked to the engine
:type null_value_node: NullValueNode
... | ee4d3f544c83d58abaf40b5cc46aa8953a2745bc | 3,637,683 |
def SetDataTypesFromColInfo(df, tblCI):
"""
Use colinfo dictionaries to set newly-imported (CSV) DataFrame column types and Boolean Flag columns
"""
for col in df.columns:
#If col is a flag column (1/blank), convert to Boolean for memory and feather file size efficiency
if (col in tblCI... | 43b6ac47d760b613be7419a6d1e7910b04c792f8 | 3,637,684 |
def run_and_wait(request, _):
"""Implementation of RunAndWait."""
process_runner = new_process.ProcessRunner(request.executable_path,
request.default_args)
args = {}
protobuf_utils.get_protobuf_field(args, request.popen_args, 'bufsize')
protobuf_utils.get_protobuf_... | a7c505221c44fd40156fa2a17ee31307e82d0a2f | 3,637,685 |
import random
def fight(player, enemy):
"""
This starts a round of combat between the user and their selected enemy.
It returns a list of information relating to combat, to be used in the
view function to display it, if required.
"""
# Random player damage based on 80-100% of player damage s... | bca739be92ccacb92c90d784cdbf5b4abb2e61c0 | 3,637,687 |
def sort_list_by_list(L1,L2):
"""Sort a list by another list"""
return [x for (y,x) in sorted(zip(L2,L1), key=lambda pair: pair[0])] | 04b7c02121620be6d9344af6f56f1b8bfe75e9f3 | 3,637,689 |
def _to_protobuf_value(value: type_utils.PARAMETER_TYPES) -> struct_pb2.Value:
"""Creates a google.protobuf.struct_pb2.Value message out of a provide
value.
Args:
value: The value to be converted to Value message.
Returns:
A google.protobuf.struct_pb2.Value message.
Raises:
... | 2714aa36c4b2ce98795c32993390853172863010 | 3,637,690 |
from typing import Union
from typing import List
def umap(adata, **kwargs) -> Union[Axes, List[Axes], None]:
"""\
Scatter plot in UMAP basis.
Parameters
----------
{adata_color_etc}
{edges_arrows}
{scatter_bulk}
{show_save_ax}
Returns
-------
If `show==False` a :class:`~m... | 454d606a62d783047ce5d09372ed0718cf3f4af4 | 3,637,691 |
def _prepare_grid(times, time_step):
"""Prepares grid of times for path generation.
Args:
times: Rank 1 `Tensor` of increasing positive real values. The times at
which the path points are to be evaluated.
time_step: Scalar real `Tensor`. Maximal distance between time grid points
Returns:
Tupl... | 7765a473ce6cf91281410006b07421daf6ed24a8 | 3,637,692 |
def unpack_singleton(x):
"""Gets the first element if the iterable has only one value.
Otherwise return the iterable.
# Argument:
x: A list or tuple.
# Returns:
The same iterable or the first element.
"""
if len(x) == 1:
return x[0]
return x | cf551f242c8ea585c1f91eadbd19b8e5f73f0096 | 3,637,693 |
def create_markdown_table(table_info: dict, index_name: str='Id') -> str:
"""
Returns a string for a markdown table, formatted
according to the dictionary passed as `table_info`
Parameters:
table_info: Mapping from index to values
index_name: Name to use for the index column
R... | bcda7ddb9338c3f7e656a0ec74a495f0a677eaeb | 3,637,696 |
def _parse_sequence(sequence):
"""Get a string which should describe an event sequence. If it is
successfully parsed as one, return a tuple containing the state (as an int),
the event type (as an index of _types), and the detail - None if none, or a
string if there is one. If the parsing is unsuccessful... | 6ba7ed95bd6bf18e24ae6bce47fdc03868ac4a98 | 3,637,697 |
from typing import List
from typing import Dict
def make_car_dict(key: str, data: List[str]) -> Dict:
"""Organize car data for 106 A/B of the debtor
:param key: The section id
:param data: Content extract from car data section
:return: Organized data for automobile of debtor
"""
return {
... | 671cb2f82f15d14345e34e9823ea390d72cf040a | 3,637,698 |
import ast
def insert_code(src, dest, kind):
"""Insert code in source into destination file."""
source_text = open(src).read().strip()
destination_text = open(dest).read()
destination_lines = destination_text.split('\n')
destination_tree = ast.parse(destination_text)
if not destination_tree... | 7f07e8741f5354fc78b840c803424bfd70fe8997 | 3,637,699 |
def is_aix():
"""
Simple function to return if host is AIX or not
"""
return salt.utils.platform.is_aix() | e4be83dfefc2a7ce5d97894b7a882808658d470a | 3,637,701 |
def draw_support_spring(
fig,
support,
orientation="up",
color='orange',
show_values=True,
row=None,
col=None,
units="N/m"):
"""Draw an anchored spring shape on a plotly figure.
Parameters
----------
fig : plotly figure
plotly figu... | 73c546289ac02d9021375f553504991bdaa4ca89 | 3,637,702 |
def _collins_crt(r, R, P, p, K):
"""Wrapper of CRT for Collins's resultant algorithm. """
return gf_int(gf_crt([r, R], [P, p], K), P*p) | d84f5ad514872acacc5f7ef626cb05f5df7771f3 | 3,637,703 |
def quantity_remover(my_thing):
"""
removes pint quantities to make json output happy
Parameters
----------
my_thing
Returns
-------
"""
if hasattr(my_thing, 'magnitude'):
return 'QUANTITY', my_thing.magnitude, my_thing.units.format_babel()
elif isinstance(my_thing, ... | 54b2db5b638f297ca503513f79eb4eec4ac2afa2 | 3,637,704 |
def sliced_wasserstein(PD1, PD2, M=50):
""" Implementation of Sliced Wasserstein distance as described in
Sliced Wasserstein Kernel for Persistence Diagrams by Mathieu Carriere, Marco Cuturi, Steve Oudot (https://arxiv.org/abs/1706.03358)
Parameters
-----------
PD1: np.ar... | c8de271435b9b393f7230c13f6eb746e3d566828 | 3,637,705 |
def update_handler(request):
"""Responds to any HTTP request.
Args:
request (flask.Request): HTTP request object.
Returns:
The response text or any set of values that can be turned into a
Response object using
`make_response <https://flask.palletsprojects.com/en/1.1.x/api/#fl... | 5fa052ddbd9e4016645e0ee81be1d8aeaaca7531 | 3,637,706 |
def usercourse(request, course_code):
"""
The function is use for course content
"""
user = request.user
extrainfo = ExtraInfo.objects.select_related().get(user=user) # get the type of user
courseid = Courses.objects.select_related().get(code=course_code)
classes = OnlineClasses.objects.sel... | ab5519f211e4c6e2574536f1a1c5a781d3529e7d | 3,637,707 |
def add_device(config_id, name, device_type_id, device_subtype_id, ip4address, ip6address, properties):
"""Add device to BAM."""
response = get_api()._api_client.service.addDevice(config_id, name, device_type_id, device_subtype_id, ip4address,
ip6address, p... | 84c66b5ab3951b764a8669bb49438eb6101e1355 | 3,637,708 |
def cleanse_param_name(name):
"""Converts Chainer parameter names to ONNX names.
Note ONNX identifiers must be a valid C identifier.
Args:
name (str): A Chainer parameter name (e.g., /l/W).
Returns
A valid ONNX name (e.g., param_l_W).
"""
return 'param' + name.replace('/', '_') | 9b7774aabeeab322f53321b91195333359c8ee7b | 3,637,710 |
def calc_checksum_for_ip_change(old_ip_packet, new_ip_packet, old_checksum, is_ipv6=False):
""" ip地址改变之后重新获取校检码
:param old_ip_packet:
:param new_ip_packet:
:param old_checksum:
:param is_ipv6:是否是ipv6
:return:
"""
final_checksum = old_checksum
a = 0
b = 1
# tmpcsum = old_check... | 7bcc7d96b6b8eef9c1ef93ca922ec192194785ff | 3,637,711 |
def get_sender_password():
"""Get sender password
"""
try:
return Setting.objects.get(slug=KEY_SENDER_PASSWORD)
except Setting.DoesNotExist:
return None | 80e0c0843b02f7a27d62727fc6b104a566cc7442 | 3,637,712 |
def standardize_data(df):
"""Standardizes the data by cleaning string values and standardizing column
names.
df: Pandas dataframe to standardize.
"""
# Clean string values in the dataframe.
df = df.applymap(
lambda x: x.replace('"', '').strip() if isinstance(x, str) else x)
# Stand... | 68a00c00003206e1875ca166de02336fb845fce3 | 3,637,713 |
def MatrixExp6(se3mat):
"""Computes the matrix exponential of an se3 representation of
exponential coordinates
:param se3mat: A matrix in se3
:return: The matrix exponential of se3mat
Example Input:
se3mat = np.array([[0, 0, 0, 0],
[0, ... | 5fb0c8ec0a43410c8bb85e98b3edbd8ab23efea0 | 3,637,714 |
import re
def parse_log(content, arg_parser=json_arg_parser):
""" Parse important information from log files.
These log files are small so we are making the logic a little simpler by loading all
the content into memory at once rather than using an iostream.
Args:
content (string): the string ... | 88659c548cdd95bd152ee0a829486301b42956c4 | 3,637,715 |
def _ohlc_dict(df_or_figure, open='', high='', low='', close='', volume='',
validate='', **kwargs):
"""
Returns a dictionary with the actual column names that
correspond to each of the OHLCV values.
df_or_figure : DataFrame or Figure
open : string
Column name to be used for ... | e6512a307217cb79b56942aa8c469a56d3cac8fc | 3,637,716 |
def _s_to_b(value):
"""[string to binary single value]"""
try:
return bytes(value, 'utf-8')
except:
return value | bbabffa2fbd2ec62778a19c8ab3e1fe410b4640f | 3,637,717 |
def get_or_create(
*, db_session, email: str, incident: Incident = None, **kwargs
) -> IndividualContact:
"""Gets or creates an individual."""
# we fetch the individual contact from the database
individual_contact = get_by_email_and_project(
db_session=db_session, email=email, project_id=inciden... | eacc9c048551f430927bdfe8c67a1af5209c0b18 | 3,637,718 |
def stats(request):
"""Return stats as JSON according to different GET query parameters."""
offset = request.GET.get('offset', '0')
limit = request.GET.get('limit', '10')
order_by = request.GET.get('order_by', 'public_backlinks')
return build_stats(offset, limit, order_by) | d252e8654a4a70f4de56e937b14cc449b6e477b6 | 3,637,719 |
def zero_crossing(arr, rank=1):
"""Calculates the zero crossing rate"""
if rank == 1:
nzc = tf.cast(tf.count_nonzero(tf_diff_axis(tf.sign(arr))), tf.float32)
else:
nzc = tf.cast(tf.count_nonzero(tf_diff_axis(tf.sign(arr)), axis=rank - 1), tf.float32)
arrlen = tf.cast(arr.shape[rank - 1]... | c7a6271d1cbf299278a06845e753d0e431716df8 | 3,637,721 |
def normalize_command(command):
"""Convert `command` to the string representation.
"""
if isinstance(command, list):
if len(command) == 1:
# This is either a quoted compound shell command or a simple
# one-item command. Pass it as is.
command = command[0]
... | 700559f7b96ba4ea37f639fdc438db5c2ad70c29 | 3,637,722 |
def make_struct(*args, **kwargs):
"""Create a Struct class according to the given format"""
exec _structdef(*args, **kwargs)
return Struct | 2fece3443e516019492af454f3f4b99bba2bd481 | 3,637,723 |
def link_iterable_by_fields(unlinked, other=None, fields=None, kind=None,
internal=False, relink=False):
"""Generic function to link objects in ``unlinked`` to objects in ``other`` using fields ``fields``.
The database to be linked must have uniqueness for each object for the given ... | 08abab5fd1db346e2fedfc9e7a9ad7542e6424a7 | 3,637,724 |
def is_conn() -> bool:
"""是否连接核心网"""
return param.parent.ia != utz.IA_INVALID and param.parent.is_conn | 8e3b06d49473caf43bf97fb133aec49907535777 | 3,637,725 |
def GetConstants():
"""Returns a list of all available constant values used by some Nexpose Criteria"""
return _get_filtered_classes(NexposeCriteriaConstant) | 24be59ec50dada727efdb394c247435111ab4b5f | 3,637,726 |
import json
def getEmpiresForUser(user_email):
"""Fetches empires for the given user.
Even though the empires should be in the data store already, we force fetch them from the server. This is
because it could be a new user and it hasn't synced yet, but also this provides a way for the user to force
their emp... | 9d2e460c726a36b8071cdf6ea2ebeb8b36e468bc | 3,637,727 |
def netflix(es, ps, e0, l=0.0001):
"""Combine predictions with the optimal weights to minimize RMSE.
Ref: Töscher, A., Jahrer, M., & Bell, R. M. (2009). The bigchaos solution to the netflix grand prize.
Args:
es (list of float): RMSEs of predictions
ps (list of np.array): predictions
... | 359ca02bb6c7f9a3d4d25fe2b41a4bcac5fd086f | 3,637,728 |
import fastapi
async def create_movie(
*,
session: aio_session.AsyncSession = fastapi.Depends(
dependencies.get_session),
movie_in: movie_model.MovieCreate,
current_patron: patron_model.Patron = fastapi.Depends( # pylint: disable=unused-argument
dependencies.get_current_active_patron)... | 88c1acca8980788031e9a64d22dd2ca0e629cc5c | 3,637,730 |
import time
import math
def project_gdf(gdf, to_crs=None, to_latlong=False, verbose=False):
"""
https://github.com/gboeing/osmnx/blob/v0.9/osmnx/projection.py#L58
Project a GeoDataFrame to the UTM zone appropriate for its geometries'
centroid.
The simple calculation in this function works well fo... | aed2c42282301d2623c92dd1516f99d953afc1c2 | 3,637,731 |
from .. import __version__
from ..importer import IMPORTED
from .driver import schema_all_drivers
from .executor import schema_all_executors
from .flow import schema_flow
from .meta import schema_metas
from .request import schema_requests
from .pod import schema_pod
def get_full_schema() -> dict:
"""
Return t... | db31d02fc1ef7ef3ed19cefffc3dcd0cdfdbb237 | 3,637,732 |
def power_method(A, x0, n_iter=1):
"""Compute the first singular components by power method."""
for i in range(n_iter):
x0 = A.T @ A @ x0
v = x0 / norm(x0)
s = norm(A @ v)
u = A @ v / s
return u, s, v | 7efc860520535aab42aeda24e15e4d4f5c340901 | 3,637,733 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.