content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def alt2temp_ratio(H, alt_units=default_alt_units):
"""
Return the temperature ratio (temperature / standard temperature for
sea level). The altitude is specified in feet ('ft'), metres ('m'),
statute miles, ('sm') or nautical miles ('nm').
If the units are not specified, the units in defaul... | c46ca3d63169676ccda223f475927a902a82a15e | 1,838 |
def encode_message(key, message):
""" Encodes the message (string) using the key (string) and
pybase64.urlsafe_b64encode functionality """
keycoded = []
if not key:
key = chr(0)
# iterating through the message
for i in range(len(message)):
# assigning a key_character based on ... | ea3a5403878dc58f1faa586c9851863a670c8cd0 | 1,839 |
def add_sibling(data, node_path, new_key, new_data, _i=0):
"""
Traversal-safe method to add a siblings data node.
:param data: The data object you're traversing.
:param node_path: List of path segments pointing to the node you're creating a
sibling of. Same as node_path of traverse()
:param new_key: The sibling... | 4bc11315eab686659edc9f7eb8479508d3ca37fb | 1,842 |
def draw_pnl(ax, df):
"""
Draw p&l line on the chart.
"""
ax.clear()
ax.set_title('Performance')
index = df.index.unique()
dt = index.get_level_values(level=0)
pnl = index.get_level_values(level=4)
ax.plot(
dt, pnl, '-',
color='green',
linewidth=1.0,
... | 6210c1861943bf61a7df8dbe2124f8f0f5e77e89 | 1,843 |
def maxRstat(Z, R, i):
"""
Return the maximum statistic for each non-singleton cluster and its
children.
Parameters
----------
Z : array_like
The hierarchical clustering encoded as a matrix. See `linkage` for more
information.
R : array_like
The inconsistency matrix.... | d63c6370e9d896a2e315012fa92fa650d1acaee8 | 1,844 |
import re
def strip_characters(text):
"""Strip characters in text."""
t = re.sub('\(|\)|:|,|;|\.|’|”|“|\?|%|>|<', '', text)
t = re.sub('/', ' ', t)
t = t.replace("'", '')
return t | 763ddc837ef9be19aa067e362c312ebd88632ed7 | 1,845 |
def make_std_secgroup(name, desc="standard security group"):
"""
Returns a standarized resource group with rules for ping and ssh access.
The returned resource can be further configured with additional rules by the
caller.
The name parameter is used to form the name of the ResourceGroup, and al... | b53a65bdc04871c0d7ca56574c1852906b2d9351 | 1,847 |
def parse_plot_args(*args, **options):
"""Parse the args the same way plt.plot does."""
x = None
y = None
style = None
if len(args) == 1:
y = args[0]
elif len(args) == 2:
if isinstance(args[1], str):
y, style = args
else:
x, y = args
elif len(... | 7687ed00785c1ab20fdf2f7bdc969fde3c75840f | 1,848 |
def publications_classification_terms_get(search=None): # noqa: E501
"""List of Classification Terms
List of Classification Terms # noqa: E501
:param search: search term applied
:type search: str
:rtype: ApiOptions
"""
return 'do some magic!' | 6633c91d59a5df7805979bd85a01f8eb1c269946 | 1,849 |
def lu_decompose(tri_diagonal):
"""Decompose a tri-diagonal matrix into LU form.
Parameters
----------
tri_diagonal : TriDiagonal
Represents the matrix to decompose.
"""
# WHR Appendix B: perform LU decomposition
#
# d[0] = hd[0]
# b[i] = hu[i]
#
# Iterative algorith... | 423bb853d96b534055bd00b3c768158c86826b1b | 1,850 |
def _card(item):
"""Handle card entries
Returns: title (append " - Card" to the name,
username (Card brand),
password (card number),
url (none),
notes (including all card info)
"""
notes = item.get('notes', "") or ""
# Add car... | fc7d5e4b960019b05ffe7ca02fd3d1a94d69b303 | 1,851 |
def s3():
"""Boto3 S3 resource."""
return S3().resource | 6402deaafa2ae7d599de1c8e8c67b9e669c06463 | 1,852 |
def SUE(xmean=None,ymean=None,xstdev=None,ystdev=None,rho=None, \
xskew=None,yskew=None,xmin=None,xmax=None,ymin=None,ymax=None, \
Npt=300,xisln=False,yisln=False):
"""
SKEWED UNCERTAINTY ELLIPSES (SUE)
Function to plot uncertainty SUEs (or 1 sigma contour of a bivariate
split-normal di... | 8b298a2d2ba04a3f1262205f19b1993a4701e279 | 1,853 |
def create_label(places, size, corners, resolution=0.50, x=(0, 90), y=(-50, 50), z=(-4.5, 5.5), scale=4, min_value=np.array([0., -50., -4.5])):
"""Create training Labels which satisfy the range of experiment"""
x_logical = np.logical_and((places[:, 0] < x[1]), (places[:, 0] >= x[0]))
y_logical = np.logical_... | 1ae1ed49674fbcee15fb6a8201e69be2c82630f9 | 1,854 |
def usage():
"""Serve the usage page."""
return render_template("meta/access.html") | 909272906678c9980f379342b87c8af6a00ab89c | 1,855 |
def GetCache(name, create=False):
"""Returns the cache given a cache indentfier name.
Args:
name: The cache name to operate on. May be prefixed by "resource://" for
resource cache names or "file://" for persistent file cache names. If
only the prefix is specified then the default cache name for tha... | b8e1796d772506d4abb9f8261df33b4cf6777934 | 1,856 |
def rf_local_divide_int(tile_col, scalar):
"""Divide a Tile by an integral scalar"""
return _apply_scalar_to_tile('rf_local_divide_int', tile_col, scalar) | 0a8c44cafcc44d323fb931fc1b037759ad907d18 | 1,857 |
from typing import Any
from typing import Dict
def or_(*children: Any) -> Dict[str, Any]:
"""Select devices that match at least one of the given selectors.
>>> or_(tag('sports'), tag('business'))
{'or': [{'tag': 'sports'}, {'tag': 'business'}]}
"""
return {"or": [child for child in children]} | 0bda8654ddc0f5dac80c8eb51b0d6d55b57c9e2a | 1,858 |
def get_width_and_height_from_size(x):
""" Obtains width and height from a int or tuple """
if isinstance(x, int): return x, x
if isinstance(x, list) or isinstance(x, tuple): return x
else: raise TypeError() | 581c9f332613dab5de9b786ce2bac3387ee1bd3b | 1,859 |
def remove_stopwords(lista,stopwords):
"""Function to remove stopwords
Args:
lista ([list]): list of texts
stopwords ([list]): [description]
Returns:
[list]: List of texts without stopwords
"""
lista_out = list()
for idx, text in enumerate(lista):
text = ' '.joi... | edca74bb3a041a65a628fcd3f0c71be5ad4858df | 1,860 |
def get_users_report(valid_users, ibmcloud_account_users):
"""get_users_report()"""
users_report = []
valid_account_users = []
invalid_account_users = []
# use case 1: find users in account not in valid_users
for account_user in ibmcloud_account_users:
# check if account user is in va... | a96f8835496f82d8b6f8cd4f248ed8a03676795b | 1,862 |
def insert_bn(names):
"""Insert bn layer after each conv.
Args:
names (list): The list of layer names.
Returns:
list: The list of layer names with bn layers.
"""
names_bn = []
for name in names:
names_bn.append(name)
if 'conv' in name:
position = nam... | efe1e6a3218fb33f74c17f90a06e2d18d17442e5 | 1,863 |
def convert_format(parameters):
"""Converts dictionary database type format to serial transmission format"""
values = parameters.copy()
for key, (index, format, value) in values.items():
if type(format) == type(db.Int):
values[key] = (index, 'i', value) # signed 32 bit int (arduino long... | fae756d54cbef6ecc7de07d123513b773ccf1433 | 1,864 |
import warnings
def getproj4(epsg):
"""
Get projection file (.prj) text for given epsg code from
spatialreference.org. See: https://www.epsg-registry.org/
.. deprecated:: 3.2.11
This function will be removed in version 3.3.5. Use
:py:class:`flopy.discretization.structuredgrid.Structur... | 80dccf9722f7dd45cca87dcd78775868cfe545ad | 1,866 |
def vpn_tunnel_inside_cidr(cidr):
"""
Property: VpnTunnelOptionsSpecification.TunnelInsideCidr
"""
reserved_cidrs = [
"169.254.0.0/30",
"169.254.1.0/30",
"169.254.2.0/30",
"169.254.3.0/30",
"169.254.4.0/30",
"169.254.5.0/30",
"169.254.169.252/30",
... | 01807a4db2fc80cf8253b0e000e412b0dce1a528 | 1,867 |
def choose_media_type(accept, resource_types):
"""choose_media_type(accept, resource_types) -> resource type
select a media type for the response
accept is the Accept header from the request. If there is no Accept header, '*/*' is assumed. If the Accept header cannot be parsed, HTTP400BadRequest is rai... | 876ad2ace8af69f5c6dc83d91d598220935987d5 | 1,868 |
import math
def get_border_removal_size(image: Image, border_removal_percentage: float = .04, patch_width: int = 8):
"""
This function will compute the border removal size. When computing the boarder removal the patch size becomes
important the output shape of the image will always be an even factor of th... | f0f236b1d2a13058042269e0e85f52f37fb47b5e | 1,869 |
def get_natural_num(msg):
"""
Get a valid natural number from the user!
:param msg: message asking for a natural number
:return: a positive integer converted from the user enter.
"""
valid_enter = False
while not valid_enter:
given_number = input(msg).strip()
i... | 77bed94bf6d3e5ceb56d58eaf37e3e687e3c94ba | 1,870 |
from typing import Optional
def _decode_panoptic_or_depth_map(map_path: str) -> Optional[str]:
"""Decodes the panoptic or depth map from encoded image file.
Args:
map_path: Path to the panoptic or depth map image file.
Returns:
Panoptic or depth map as an encoded int32 numpy array bytes or None if not... | 1f3b81827ba911614d8979b187b8cde7f10078fe | 1,871 |
def splitstr(s, l=25):
""" split string with max length < l
"(i/n)"
"""
arr = [len(x) for x in s.split()]
out = []
counter = 5
tmp_out = ''
for i in xrange(len(arr)):
if counter + arr[i] > l:
out.append(tmp_out)
tmp_out = ''
counter = 5... | 0d84d7bbf420d1f97993be459764c37fed50f8b3 | 1,872 |
import re
def SplitRequirementSpecifier(requirement_specifier):
"""Splits the package name from the other components of a requirement spec.
Only supports PEP 508 `name_req` requirement specifiers. Does not support
requirement specifiers containing environment markers.
Args:
requirement_specifier: str, a... | d71eee50c162756ac7aae0bd120323d50d3ab255 | 1,873 |
def arctanh(var):
"""
Wrapper function for atanh
"""
return atanh(var) | 955d09821d78703c99fc2e51f70ca0fc47b0c943 | 1,874 |
def predict_sentiment(txt: str, direc: str = 'models/sentiment/saved_models/model50') -> float:
"""
predicts sentiment of string
only use for testing not good for large data because
model is loaded each time
input is a txt string
optional directory change for using different models
returns a... | d7ff2d361792032eb097e0b0e9818da6ce3af1e5 | 1,875 |
import numpy
def logfbank(signal,
samplerate=16000,
winlen=0.025,
winstep=0.01,
nfilt=26,
nfft=512,
lowfreq=0,
highfreq=None,
preemph=0.97,
winfunc=lambda x: numpy.ones((x,))):
"""Compute log Mel-fil... | 670d5faf73fcca6da249d9b5c9fb6965eafab855 | 1,876 |
def get_rmsd( pose, second_pose, overhang = 0):
"""
Get RMSD assuming they are both the same length!
"""
#id_map = get_mask_for_alignment(pose, second_pose, cdr, overhang)
#rms = rms_at_corresponding_atoms_no_super(pose, second_pose, id_map)
start = 1 + overhang
end = pose.total_residue()... | 80af3478fe946243cba5e7f3e45c61a8ea9af1d1 | 1,877 |
def inverse(a: int, n: int):
"""
calc the inverse of a in the case of module n, where a and n must be mutually prime.
a * x = 1 (mod n)
:param a: (int)
:param n: (int)
:return: (int) x
"""
assert greatest_common_divisor(a, n) == 1
return greatest_common_divisor_with_coefficient(a, n)... | 1012c4c69b81dccd2ecfd0c5cddf7a7bd9b2c1f8 | 1,878 |
def create_app():
"""Create the Flask application."""
return app | 7ff5c1e66ab48a5f262beb7abfa21e28680605c9 | 1,879 |
def generate_prime_candidate(length):
""" Genera un integer impar aleatorimanete
param size: tamanio del numero deseado
return:integer
"""
p = big_int(length)
p |= (1 << length - 1) | 1
return p | bdae69644156191a5388b23d7cf1853b8b0273b6 | 1,880 |
def PathPrefix(vm):
"""Determines the prefix for a sysbench command based on the operating system.
Args:
vm: VM on which the sysbench command will be executed.
Returns:
A string representing the sysbench command prefix.
"""
if vm.OS_TYPE == os_types.RHEL:
return INSTALL_DIR
else:
return '... | e0ade1847bce77f3b4efd9f801b36b219917f0b8 | 1,881 |
from typing import Union
import asyncio
def get_next_valid_seq_number(
address: str, client: SyncClient, ledger_index: Union[str, int] = "current"
) -> int:
"""
Query the ledger for the next available sequence number for an account.
Args:
address: the account to query.
client: the net... | cb2a502aabc474ab79ea14bd2305dda5bfe8b479 | 1,882 |
import re
def apps_list(api_filter, partial_name, **kwargs):
"""List all defined applications. If you give an optional command line
argument, the apps are filtered by name using this string."""
params = {}
if api_filter:
params = {"filter": api_filter}
rv = okta_manager.call_okta("/apps", ... | bafb2f1eb65e735b40613e302fcbc85507c25cb8 | 1,883 |
def jacquez(s_coords, t_coords, k, permutations=99):
"""
Jacquez k nearest neighbors test for spatio-temporal interaction.
:cite:`Jacquez:1996`
Parameters
----------
s_coords : array
(n, 2), spatial coordinates.
t_coords : array
(n, ... | dc71d74cc0e0159e1164d659ca3f07f3b9a61dd6 | 1,884 |
def array2tensor(array, device='auto'):
"""Convert ndarray to tensor on ['cpu', 'gpu', 'auto']
"""
assert device in ['cpu', 'gpu', 'auto'], "Invalid device"
if device != 'auto':
return t.tensor(array).float().to(t.device(device))
if device == 'auto':
return t.tensor(array).float().to... | 53826ad5b19a4e030bc3e98857c9b3285094370f | 1,885 |
def to_json(graph):
"""Convert this graph to a Node-Link JSON object.
:param BELGraph graph: A BEL graph
:return: A Node-Link JSON object representing the given graph
:rtype: dict
"""
graph_json_dict = node_link_data(graph)
# Convert annotation list definitions (which are sets) to canonica... | 325053a0838bbf1ab70a4fb61e17f93f27c80dab | 1,886 |
def export(df: pd.DataFrame):
"""
From generated pandas dataframe to xml configuration
:param df: computed pandas dataframe
:return:
"""
return df | 445e91a419746afef8062dcc1e6691572ba9390d | 1,887 |
def has_same_attributes(link1, link2):
"""
Return True if the two links have the same attributes for our purposes,
ie it is OK to merge them together into one link
Parameters:
link1 - Link object
link2 - Link object
Return value:
True iff link1 and link2 have compatible attribu... | e80f62d01ef18e547a2e7718ac2bb1ca3001b84f | 1,888 |
def test_signals_creation(test_df, signal_algorithm):
"""Checks signal algorithms can create a signal in a Pandas dataframe."""
test_df_copy = test_df.copy()
original_columns = test_df.columns
# We check if the test series has the columns needed for the rule to calculate.
required_columns = Api.re... | 5a4515092d778090a77ce5933ad2e79b4d62df36 | 1,889 |
def get_prev_day(d):
"""
Returns the date of the previous day.
"""
curr = date(*map(int, d.split('-')))
prev = curr - timedelta(days=1)
return str(prev) | 9195c0be4fc25a68b0bb94e953bafd407c5931a3 | 1,890 |
import types
def copy_function(old_func, updated_module):
"""Copies a function, updating it's globals to point to updated_module."""
new_func = types.FunctionType(old_func.__code__, updated_module.__dict__,
name=old_func.__name__,
argdefs=old_func._... | e09022f734faa1774a3ac592c0e12b0b007ae8e3 | 1,891 |
import random
def get_random_color():
"""
获得一个随机的bootstrap颜色字符串标识
:return: bootstrap颜色字符串
"""
color_str = [
'primary',
'secondary',
'success',
'danger',
'warning',
'info',
'dark',
]
return random.choice(color_str) | 898814996aa5ada8f4000244887af382b8b9e1bc | 1,892 |
def logged_run(cmd, buffer):
"""Return exit code."""
pid = Popen(cmd, stdout=PIPE, stderr=STDOUT)
pid.wait()
buffer.write(pid.stdout.read())
return pid.returncode | 99a1aa4f8997ef7665a8e994b3df3d4ffe8a844b | 1,894 |
import json
def create_iam_role(iam_client):
"""Create an IAM role for the Redshift cluster to have read only access to
S3.
Arguments:
iam_client (boto3.client) - IAM client
Returns:
role_arn (str) - ARN for the IAM Role
"""
# Create the role if it doesn't already exist.
... | 949026bae3edc1dacc5057427ecf3e21490bd9b8 | 1,897 |
import array
def cone_face_to_span(F):
"""
Compute the span matrix F^S of the face matrix F,
that is, a matrix such that
{F x <= 0} if and only if {x = F^S z, z >= 0}.
"""
b, A = zeros((F.shape[0], 1)), -F
# H-representation: A x + b >= 0
F_cdd = Matrix(hstack([b, A]), number_ty... | ae928e179085116fa8ac48fd01841458bdcd38ec | 1,898 |
def neighborhood(index, npoints, maxdist=1):
"""
Returns the neighbourhood of the current index,
= all points of the grid separated by up to
*maxdist* from current point.
@type index: int
@type npoints: int
@type maxdist int
@rtype: list of int
"""
return [index + i for i in ran... | 98166d810daa6b99862a4c9f6d1629fdfa571bd0 | 1,899 |
def data_check(data):
"""Check the data in [0,1]."""
return 0 <= float(data) <= 1 | b292ef07a024e53d82e706f0d88d50d6318d6593 | 1,900 |
import re
def tokenize(text):
"""
Tokenization function to process text data
Args:
text: String. disaster message.
Returns:
clean_tokens: list. token list from text message.
"""
url_regex = 'http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\(\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+'
# g... | d5ee0929c0b6fad243b87c2b7e82270859b9b3f3 | 1,901 |
def get_symbol_historical(symbol_name):
"""Returns the available historical data for a symbol as a dictionary."""
# Get the data
symbol_data = get_symbol_data(symbol_name)
# Build the response
response = symbol_data.to_dict(orient="records")
return response | 37578652a13ff2b705c46185aba8cd47a73dc6e0 | 1,902 |
def guesses(word):
"""
return all of the first and second order guesses for this word
"""
result = list(known(*first_order_variants(word)))
result.sort()
return result | 9a74372e701d526d74df1df613b8648f47830202 | 1,903 |
def em(X, sf, inits, K, L, n_iter=100, n_inner_iter=50, tol=1e-5, zero_inflated=True):
"""
run EM algorithm on the given init centers
return the clustering labels with the highest log likelihood
"""
# add prepare reduced data here
print("start em algorithm")
res = _em(X, sf, inits, K, L, ... | 7a53c14caf56958fed80241bf347071b84a62280 | 1,904 |
def update_logger(evo_logger, x, fitness, memory, top_k, verbose=False):
""" Helper function to keep track of top solutions. """
# Check if there are solutions better than current archive
vals = jnp.hstack([evo_logger["top_values"], fitness])
params = jnp.vstack([evo_logger["top_params"], x])
concat... | 8efd1bbc4f0c1cde17e2ef425ae82cf3f5967df3 | 1,906 |
def ae(nb_features,
input_shape,
nb_levels,
conv_size,
nb_labels,
enc_size,
name='ae',
prefix=None,
feat_mult=1,
pool_size=2,
padding='same',
activation='elu',
use_residuals=False,
nb_conv_per_level=1,
batch_norm=None,
... | ab5bbed13e5636ab506612776920eaffa67b8b3e | 1,907 |
def parser_config(p):
"""JLS file info."""
p.add_argument('--verbose', '-v',
action='store_true',
help='Display verbose information.')
p.add_argument('filename',
help='JLS filename')
return on_cmd | ea9e20fd055933d7e1b1b5f92da76875f7f318e6 | 1,910 |
def decentralized_training_strategy(communication_rounds, epoch_samples, batch_size, total_epochs):
"""
Split one epoch into r rounds and perform model aggregation
:param communication_rounds: the communication rounds in training process
:param epoch_samples: the samples for each epoch
:param batch_... | 3a743208af50d7c7865d5d5f86a4f58b0ba98a4d | 1,911 |
def create_config_file_lines():
"""Wrapper for creating the initial config file content as lines."""
lines = [
"[default]\n",
"config_folder = ~/.zettelkasten.d\n",
"\n",
"def_author = Ammon, Mathias\n",
"def_title = Config Parsed Test Title\n",
"def_location_spec... | d0d1057c3f450636279a8df9d4a39977f1eeef42 | 1,912 |
def p_planes_tangent_to_cylinder(base_point, line_vect, ref_point, dist, ):
"""find tangent planes of a cylinder passing through a given point ()
.. image:: ../images/plane_tangent_to_one_cylinder.png
:scale: 80 %
:align: center
Parameters
----------
base_point : point
poin... | e8928e4314cadede97bef977c0348e32832157ad | 1,913 |
def BOPTools_AlgoTools3D_OrientEdgeOnFace(*args):
"""
* Get the edge <aER> from the face <aF> that is the same as the edge <aE>
:param aE:
:type aE: TopoDS_Edge &
:param aF:
:type aF: TopoDS_Face &
:param aER:
:type aER: TopoDS_Edge &
:rtype: void
"""
return _BOPTools.BOPTools_... | 31da8b90e4ad5838b94a0481d937104845de735c | 1,914 |
def create_store_from_creds(access_key, secret_key, region, **kwargs):
"""
Creates a parameter store object from the provided credentials.
Arguments:
access_key {string} -- The access key for your AWS account
secret_key {string} -- The secret key for you AWS account
region {stri... | 8e0ec2a6579a6013d36b6933ee922a406730ee35 | 1,915 |
import abc
def are_objects_equal(object1, object2):
"""
compare two (collections of) arrays or other objects for equality. Ignores nan.
"""
if isinstance(object1, abc.Sequence):
items = zip(object1, object2)
elif isinstance(object1, dict):
items = [(value, object2[key]) for key, va... | 94b4b9a9f42bc8b1dd44d5e010b422082452f649 | 1,916 |
def get_recipes_from_dict(input_dict: dict) -> dict:
"""Get recipes from dict
Attributes:
input_dict (dict): ISO_639_1 language code
Returns:
recipes (dict): collection of recipes for input language
"""
if not isinstance(input_dict, dict):
raise TypeError("Input is not typ... | e710d9629d10897d4aae7bf3d5de5dbbe18196c5 | 1,917 |
def tasks_from_wdl(wdl):
"""
Return a dictionary of tasks contained in a .wdl file.
The values are task definitions within the wdl
"""
return scopes_from_wdl("task", wdl) | 24d302995dcfa274b4b04868f901f832b36ec5cd | 1,918 |
async def get_category_item_route(category_id: CategoryEnum, item_id: ObjectID,
db: AsyncIOMotorClient = Depends(get_database)) -> ItemInResponse:
"""Get the details about a particular item"""
_res = await db[category_id]["data"].find_one({"_id": item_id})
if _res:
... | 4feed87e3948994f8066268820355d9fdfe4999d | 1,920 |
def weighted_SVD(matrix, error=None, full_matrices=False):
"""
Finds the most important modes of the given matrix given the weightings
given by the error.
matrix a horizontal rectangular matrix
error weighting applied to the dimension corresponding to the rows
"""
if type(error) is type... | 5ca0f54af765f0694fb572ee3b82f4d59642bb06 | 1,921 |
def ingredients():
"""Route to list all ingredients currently in the database.
"""
query = request.args.get("q")
ingredients = db.get_ingredient_subset_from_db(query)
return jsonify(ingredients) | 376bcb8e16c0379676f9748f4a2858ea39ca33ab | 1,922 |
def read_h5_particles(particles_file, refpart, real_particles, bucket_length, comm, verbose):
"""Read an array of particles from an HDF-5 file"""
four_momentum = refpart.get_four_momentum()
pmass = four_momentum.get_mass()
E_0 = four_momentum.get_total_energy()
p0c = four_momentum.get_momentum()
... | caaeb89920b3cc9e0b263c9b1fea5fc1615ad8b3 | 1,923 |
import logging
def readAndMapFile(path):
"""
Main file breaker - this takes a given file and breaks it into arbitrary
fragments, returning and array of fragments. For simplicity, this is breaking on
newline characters to start with. May have to be altered to work with puncuation
and/or special ... | 4a542d1a08fcd88a1660de360c15d87949eddf11 | 1,924 |
def fetch_git_logs(repo, from_date, to_date, args): # pragma: no cover
"""Fetch all logs from Gitiles for the given date range.
Gitiles does not natively support time ranges, so we just fetch
everything until the range is covered. Assume that logs are ordered
in reverse chronological order.
"""
cursor = '... | 1164b373e9b8f7186165712f8ac9e5e3d1a1f10f | 1,925 |
import torch
def _gen_bfp_op(op, name, bfp_args):
"""
Do the 'sandwich'
With an original op:
out = op(x, y)
grad_x, grad_y = op_grad(grad_out)
To the following:
x_, y_ = input_op(x, y)
Where input_op(x, y) -> bfp(x), bfp(y)
and input_op_grad(grad_x, grad_y) -> bfp(grad_x), bfp(gr... | d430bd9d090d0a47fa4d6a8c173c77b08e2fdb66 | 1,926 |
def angleaxis_to_rotation_matrix(aa):
"""Converts the 3 element angle axis representation to a 3x3 rotation matrix
aa: numpy.ndarray with 1 dimension and 3 elements
Returns a 3x3 numpy.ndarray
"""
angle = np.sqrt(aa.dot(aa))
if angle > 1e-6:
c = np.cos(angle);
s = np.sin(a... | 57d849f137684824aa23d393802dc247df987b59 | 1,927 |
def sendOrderFAK(self, orderType, price, volume, symbol, exchange, stop=False):
"""发送委托"""
if self.trading:
# 如果stop为True,则意味着发本地停止单
req = {}
req['sid'] = self.sid
if orderType == CTAORDER_BUY:
req['direction'] = '0'
req['offset'] = '0'
elif orderT... | 5b72ab3cdfa0b4412df2861d1e23a4a55f1d7206 | 1,928 |
import itertools
def unique(lst):
"""
:param lst: a list of lists
:return: a unique list of items appearing in those lists
"""
indices = sorted(list(range(len(lst))), key=lst.__getitem__)
indices = set(next(it) for k, it in
itertools.groupby(indices, key=lst.__getitem__))
... | 0848d693681ff0f8bdbc0d0436b3d4450eee781e | 1,929 |
def max_frequency(sig, FS):
"""Compute max frequency along the specified axes.
Parameters
----------
sig: ndarray
input from which max frequency is computed.
FS: int
sampling frequency
Returns
-------
f_max: int
0.95 of max_frequency using cumsum.
"""
f, ... | 19321fb47d47b99138e1d1551f3728df4c2b7370 | 1,930 |
def split(text):
"""Turns the mobypron.unc file into a dictionary"""
map_word_moby = {}
try:
lines = text.split("\n")
for line in lines:
(word, moby) = line.split(" ", 1)
map_word_moby[word] = moby
except IOError as error:
print(f"Failed due to IOError: {... | ba051724f0399e918949c3e8b7fb010e2d87c9f9 | 1,931 |
def report(key_name=None, priority=-1, **formatters):
""" Use this decorator to indicate what returns to include in the report and how to format it """
def tag_with_report_meta_data(cls):
# guard: prevent bad coding by catching bad return key
if key_name and key_name not in cls.return_keys:
... | 3830135de40bdc2a25bd3c6b6cecc194c6dbebac | 1,932 |
import scipy
def calc_momentum_def(x_loc, X, Y, U):
""" calc_momentum_def() : Calculates the integral momentum deficit of scalar field U stored at \
locations X,Y on a vertical line that runs nearest to x_loc. """
U_line, x_line, x_idx_line = get_line_quantity(x_loc, X, Y, U)
y_line = Y[:,x_i... | 7173450ebd779c07a80cef2deb37954ddb7509be | 1,933 |
def display_unit_title(unit, app_context):
"""Prepare an internationalized display for the unit title."""
course_properties = app_context.get_environ()
template = get_unit_title_template(app_context)
return template % {'index': unit.index, 'title': unit.title} | 9d8ffbf0672388bd890aaabb8e5fbdb5e193d3d2 | 1,934 |
def load_user(user_id):
"""Load the user object from the user ID stored in the session"""
return User.objects(pk=user_id).first() | 96df8d5e21f380369ae0c6ccc404a4f7880bf000 | 1,935 |
def get_complex_replay_list():
"""
For full replays that have crashed or failed to be converted
:return:
"""
return [
'https://cdn.discordapp.com/attachments/493849514680254468/496153554977816576/BOTS_JOINING_AND_LEAVING.replay',
'https://cdn.discordapp.com/attachments/49384951468025... | ef5a75a848289ad9c129c2b73a6d6845dcd07cfe | 1,936 |
import json
def parse_registry():
""" Parses the provided registry.dat file and returns a dictionary of chunk
file names and hashes. (The registry file is just a json dictionary containing
a list of file names and hashes.) """
registry = request.values.get("registry", None)
if registry is None:
... | 71d4cd0f2b9fb33b92861feb9ea882fc32ec7234 | 1,937 |
import math
def get_cosine_with_hard_restarts_schedule_with_warmup(optim: Optimizer,
num_warmup_step: float,
num_training_step: int,
num_cycles: float = ... | 5327cb688885c8ecc271156364a06bffedd97775 | 1,938 |
import typing
def home():
"""
Render Homepage
--------------------------------------------------------------
This site should be cached, because it is the main entry point for many users.
"""
bestseller: typing.List[Device] = get_bestsellers()
specialist_manufacturers = Manufacturer.query.... | ca452264e8a10af83e0cc7b5df592a9f618085ad | 1,939 |
def reject_call():
"""Ends the call when a user does not want to talk to the caller"""
resp = twilio.twiml.Response()
resp.say("I'm sorry, Mr. Baker doesn't want to talk to you. Goodbye scum.", voice='woman', language='en-GB')
resp.hangup()
return str(resp) | 743e58b230a3a63df4c3e882139755b8d2c4bc55 | 1,940 |
def table_prep(data, columns=''):
"""
Data processor for table() function.
You can call it separately as well and in
return get a non-prettyfied summary table.
Unless columns are defined, the three first
columns are chosen by default.
SYNTAX EXAMPLE:
df['quality_score'... | a9d3d75d2ac32ddf5ae4d5a17a10974b61c139ee | 1,941 |
def lerp(a,b,t):
""" Linear interpolation between from @a to @b as @t goes between 0 an 1. """
return (1-t)*a + t*b | 12cb8690ba5e5f2a4c08c1cd29d3497513b63438 | 1,942 |
def convert_to_legacy_v3(
game_tick_packet: game_data_struct.GameTickPacket,
field_info_packet: game_data_struct.FieldInfoPacket = None):
"""
Returns a legacy packet from v3
:param game_tick_packet a game tick packet in the v4 struct format.
:param field_info_packet a field info packet i... | 3e00e165233806957a010871c9218b1c02950063 | 1,943 |
import logging
def _load_audio(audio_path, sample_rate):
"""Load audio file."""
global counter
global label_names
global start
global end
logging.info("Loading '%s'.", audio_path)
try:
lbl1=Alphabet[audio_path[-6]]
lbl2 = Alphabet[audio_path[-5]]
except:
lbl1=1 + counter
lbl2=2 + c... | 5e8112c79164c800965f137c83ceb720aab17bdf | 1,944 |
def generate_annotation_dict(annotation_file):
""" Creates a dictionary where the key is a file name
and the value is a list containing the
- start time
- end time
- bird class.
for each annotation in that file.
"""
annotation_dict = dict()
for line i... | f40f210075e65f3dbe68bb8a594deb060a23ad8b | 1,945 |
def ishom(T, check=False, tol=100):
"""
Test if matrix belongs to SE(3)
:param T: SE(3) matrix to test
:type T: numpy(4,4)
:param check: check validity of rotation submatrix
:type check: bool
:return: whether matrix is an SE(3) homogeneous transformation matrix
:rtype: bool
- ``ish... | b4a0467d22940889e3071bf07d4a093d567409f3 | 1,946 |
def _get_stp_data(step_order=STEP_ORDER, n=N_PER_STEP):
"""Returns np.array of step-type enums data for sample data.
Parameters
----------
step_order : list of (int, char)
List of (Cycle number, step type code) for steps in sample procedure.
n : int
Number of datapoints per step.
... | d96a2604ac67e1a84ead39e0d2d39a5c6183a5cd | 1,947 |
from typing import Union
from typing import List
def fuse_stride_arrays(dims: Union[List[int], np.ndarray],
strides: Union[List[int], np.ndarray]) -> np.ndarray:
"""
Compute linear positions of tensor elements
of a tensor with dimensions `dims` according to `strides`.
Args:
dims: ... | 06185cb0bcfccd30e7b006fa8fe4e28a6f5ae7f3 | 1,949 |
def extract_jasmine_summary(line):
"""
Example SUCCESS karma summary line:
PhantomJS 2.1.1 (Linux 0.0.0): Executed 1 of 1 SUCCESS (0.205 secs / 0.001 secs)
Exmaple FAIL karma summary line:
PhantomJS 2.1.1 (Linux 0.0.0): Executed 1 of 1 (1 FAILED) ERROR (0.21 secs / 0.001 secs)
"""
# get tota... | f795ff015555cc3a2bd2d27527ae505a6dde9231 | 1,950 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.