content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def decode(bytes_sequence, encodings):
"""Return the first successfully decoded string"""
for encoding in encodings:
try:
decoded = bytes_sequence.decode(encoding)
return decoded
except UnicodeDecodeError:
# Try the next in the list.
pass
raise... | dc9a5077da63350dbd0f87fb2c743845fc184f59 | 67,939 |
def SetAnswersAndReportsOnFeatures(features, map_root, topic_id, qids):
"""Sets 'status_color', 'answers', and 'answer_text' on the given Features."""
map_id = map_root.get('id') or ''
topic = GetTopic(map_root, topic_id) or {}
radius = topic.get('cluster_radius', 100)
questions_by_id = {q['id']: q for q in ... | 6a0594d91ea18cacefede3ca3679e5e73e2b3600 | 67,942 |
from typing import List
def get_bond_type_one_hot(bond: RDKitBond,
allowable_set: List[str] = DEFAULT_BOND_TYPE_SET,
include_unknown_set: bool = False) -> List[float]:
"""Get an one-hot feature of bond type.
Parameters
---------
bond: rdkit.Chem.rdchem.Bond... | f56dd1d1bdd3e8643c413f419dcfa1153400ed6e | 67,944 |
def get_neurons_sink(model, connection):
"""Get the sink for connections into the neurons of an ensemble."""
ens = model.object_operators[connection.post_obj.ensemble]
return spec(ObjectPort(ens, EnsembleInputPort.neurons)) | a6b0303942e381dcb42bd4b9235a261fdb795e16 | 67,945 |
def calc_Q_max_H_RAC_d_t(region, A_HCZ):
"""ルームエアコンディショナーの最大暖房出力
Args:
region(int): 省エネルギー地域区分
A_HCZ(float): ルームエアコンディショナー付温水床暖房を設置する暖冷房区画の面積 (m2)
Returns:
ndarray: ルームエアコンディショナーの最大暖房出力
"""
# 外気温度・湿度の取得
outdoor = load_outdoor()
Theta_ex_d_t = get_Theta_ex(region, outdoor... | 064ea0b919dfddfe654f4b9132f56f16af66d1c3 | 67,946 |
def _sub_str_plot_fields(val, f, field_filter):
"""recursive helper function for _str_plot_fields"""
# CSV
type_ = type(val)
if type_ in (bool, int, long, float) or \
isinstance(val, genpy.TVal):
return f
# duck-type check for messages
elif hasattr(val, "_slot_types"):
... | 440c59c1587e739f4ae488414b28e8928bc650b2 | 67,947 |
from typing import List
def get_filtered_schemes(filter_to_apply: SchemeFilterType, schemes: List[Scheme]):
"""Apply filter on schemes and return the filtered list"""
return list(filter(filter_to_apply, schemes)) | dee2142f061d0d742d94c9253dfa3d11ac5f9b6d | 67,948 |
def view_and_manage_application(request, pk):
"""Displays the detail page for a specific application. Login required.
Parameters:
pk: Application id (primary key of Application instance)
"""
if request.user.uapuser.is_student:
messages.warning(request, 'You do not have the permissions t... | 82822fda09d6ce87fdbaa3df2e2ec03b5a58f925 | 67,950 |
def get_sigmas(dist):
"""Gets + and - sigmas from a distribution (gaussian or not). Ignores nan values.
Parameters
----------
dist: np.array
Distribution from which sigmas are needed
Returns
-------
sigma_minus: float
- sigma
sigma_plus: float
+ sigma
"""
... | b25a1a6a90ae16a678b159ad7fbc09b7b0cb8cf6 | 67,951 |
def file_is_pdf(filename: str) -> bool:
"""
Check if `filename` has the .pdf extension.
Args:
filename (str): Any filename, including its path.
Returns:
True if `filename` ends with .pdf, false otherwise.
"""
return filename.endswith(".pdf") | ba9a540a1f0edd33e48010a001de4493bdff80d9 | 67,952 |
def get_logs_schema() -> graphene.Schema:
"""
Get a graphene Schema instace for a nydata.logs schema.
"""
logs_schema = graphene.Schema(query=Query, auto_camelcase=False)
return logs_schema | faf9234169e51cee4d5e661bbab73d7c7336079d | 67,953 |
import re
def _convert_epytext(line):
"""
>>> _convert_epytext("L{A}")
:class:`A`
"""
line = line.replace('@', ':')
for p, sub in RULES:
line = re.sub(p, sub, line)
return line | 49355ff1a30ef029a611fb948a15dcd6778017fb | 67,954 |
def sender(address, use_queue=True, **kwds):
"""
:param str address: a pair (ip_address, port) to pass to socket.connect
:param bool use_queue: if True, run the connection in a different thread
with a queue
"""
return QueuedSender(address, **kwds) if use_queue else Sender(address) | 2af4a64b05a3ff27c58723107bff73d153f1bf77 | 67,955 |
from typing import Callable
from typing import Iterator
from typing import Optional
def mk_omit(skip_func: Callable) -> Callable:
"""The skip function is either minleq or maxgeq"""
def omit_(pot: int,
seqs: Iterator[Iterator[int]]) -> Iterator[Optional[int]]:
"""Given an iterator of ite... | ce1aafd0a67dd1acfbc9fc7b966fd14a76b1e85d | 67,958 |
def reflection_matrix(U):
"""
https://en.wikipedia.org/wiki/Transformation_matrix#Reflection
u = np.ndarray (2,Nvec)
Returns
-------
M : nd array
(2,2,Nvec)
u = np.array([2,2])
U=np.vstack((u,u/2.,2*u)).T
"""
diag_term = (U[0,:]**2)-(U[1,:]**2)
anti_diag = 2*... | 65fb16253293f4f0ecfa4cfd90c9a69f88f5b8e1 | 67,959 |
import random
def generate_password():
""" Generate a random password of 12 to 15 characters"""
nr_letters = random.randint(8, 10)
nr_symbols = random.randint(2, 4)
nr_numbers = random.randint(2, 4)
random_char = [random.choice(characters) for char in range(nr_letters)] # Holds random alphabets ... | 4386d062f7a2bdf3498a9bc6b34045108b264deb | 67,960 |
def convert_to_boolean(data):
"""Converts categorical series or dataframe to boolean."""
if isinstance(data, pd.DataFrame):
return _convert_frame_to_boolean(data)
elif isinstance(data, pd.Series):
return _convert_series_to_boolean(data)
else:
raise ValueError('Unknown data type ... | bfaa724d8b617840424a9925364a0a8ffc7d9426 | 67,961 |
def generateClosures(transactions, generators):
""" Generate the closures of the generators
transactions : list of sets
The list of transactions
generators : lists of lists
The list of generator itemsets whose closures need to be computed
Returns
... | 452f12fec6dff0e3c8903344976fcb44728fa563 | 67,962 |
def _conv(layer_name, inputs, out_channels, kernel_size=[3, 3], strides=[1, 1], paddings=[1, 1], trainable=True, reuse=None):
"""convolution layer with relu and batch normalization
Args:
layer_name: e.g. conv1, conv2
x: input_tensor, [b, h, w, c]
reuse: if reuse==tf.AUTO_REUSE: this conv... | bd3a764ef1a838ac91a8106c7ebcb5710b88b59c | 67,963 |
def get_bad_devops_days():
"""Return records for bad devops days."""
query = """SELECT stats.date,
(CAST(stats.error as FLOAT) / CAST(stats.all as FLOAT) * 100)
FROM (
SELECT DATE(time) as date,
count(*) AS all,
count(*) FILTER (WHERE status != '200 O... | fc2b68d09d2d2c2a9e9a3844d1748924406c419d | 67,964 |
import numpy
def voxelize(mesh, bounding_box, padding=True):
"""
Voxelize a mesh with a given bounding box
"""
# Note: voxels should be addressed with voxels[z][x][y]
voxels = numpy.zeros((bounding_box[2], bounding_box[
0], bounding_box[1]), dtype=bool)
for height in r... | e411a81338f8cc16c8aadd13eaa60ed2acefc49a | 67,965 |
import torch
def torch_hilbert(x_real, n_fft=None):
"""
Obtain imaginary counterpart to a real signal such that there are no negative frequency
components when represented as a complex signal. This is done by using the Hilbert transform.
We end up with an analytic signal and return only the imaginary ... | 33bb230c78beb84ca5569c5fca8ebb61a36fd7c5 | 67,967 |
from typing import Tuple
def validate(modal: Modal, loader: DataLoaderIAM, line_mode: bool) -> Tuple[float, float]:
"""Validates NN."""
print('Validate NN')
loader.validation_set()
preprocessor = Preprocessor(get_img_size(line_mode), line_mode=line_mode)
num_char_err = 0
num_char_total = 0
... | 50f2b91004f7d75a6f93a3e7dc66f8ea18390ac0 | 67,968 |
import numpy
def measured_area_correction(data, rebin=False):
"""
Given a detector measurement (either a flood fill or a main
beam scan) return an area correction based on the pixel widths
estimated from the data.
The resulting correction will scale the pixels to counts per
unit area, so must... | 2d5dbd2f92c00eeec2628ec3b8f527f2705755be | 67,969 |
def alert_if_no_copyright(glob, comment_prefix):
"""Prints names of all files missing a copyright message.
Finds all glob-matching files under the current directory and checks if they
contain the copyright message. Prints the names of all the files that
don't.
Returns the total number of file nam... | 43235e6ac9a0484586c89c88715326ffe6683a1f | 67,970 |
from typing import Callable
def _get_ch(excel_list: list, title_slice: tuple, lvl, nesting, normalize: Callable) -> list:
""" Recursively get a list of children
:param excel_list: excel data
:param title_slice: root category slice
:param lvl: current level
:param nesting: number nested levels
... | 47cb7c6ce62d87b719658687baa5bf5b03d5afe1 | 67,971 |
def _add_padding(df: pd.DataFrame) -> pd.DataFrame:
"""
Add padding to name1 and name2
:param df: input dataframe
:return: input dataframe with name1 and name2 columns padded
"""
df.loc[:, "name1"] = df.loc[:, "name1"].map(add_padding)
df.loc[:, "name2"] = df.loc[:, "name2"].map(add_padding)... | ded1467fb27b27ef543ff22eb7eee476f5855bfa | 67,972 |
from typing import Dict
from typing import Any
async def batch_upsert_samples(
samples: SampleBatchUpsertBody,
connection: Connection = get_project_write_connection,
) -> Dict[str, Any]:
"""Upserts a list of samples with sequences, and returns the list of internal sample IDs"""
# Convert id in sample... | a11da3318c46407a8c7146df02b66f1aac2c5dce | 67,973 |
def read_em(path_to_emfile: str) -> tuple:
"""
Function that reads a .em dataset (in the tom format).
:param path_to_emfile: str, pointing to the .em file
:return: tuple header, value
where header is a dictionary specifying
'Machine_Coding'
'version'
'old_param'
'data_type_code'
... | ad6408e637dc2759d394e875392d52a6270038c2 | 67,974 |
def get_uptime():
""" Returns system uptime.
Uptime is read from /proc/uptime file and converted to human readable
format.
"""
try:
file = open('/proc/uptime', 'r')
data = file.read().split()
file.close()
except IOError:
raise OSInfoError('Unable to open file: /... | 0269df048bdee166d92cb00aed567284cc53ec98 | 67,975 |
import collections
def merge(qrels, run, queries):
"""Merge qrels and runs into a single dict of key: query,
value: tuple(relevant_doc_ids, candidate_doc_ids)"""
data = collections.OrderedDict()
for query_id, candidate_doc_ids in run.items():
try:
query = queries[query_id]
... | 8d30a82dd789d01a03101e0dfc30b8df3f4261cb | 67,976 |
def update_Domain_disable(
ctx,
dbDomain,
dbOperationsEvent=None,
event_status="Domain__mark__inactive",
action="deactivated",
):
"""
Disables a domain
:param ctx: (required) A :class:`lib.utils.ApiContext` instance
:param dbDomain: (required) A :class:`model.objects.Domain` object
... | 405bb4054552c70aa3b46ecb9dd460ce6920cf36 | 67,978 |
def rolling_max_drawdown_nb(returns, window, minp):
"""Rolling version of `max_drawdown_nb`."""
def _apply_func_nb(i, col, _returns):
return max_drawdown_1d_nb(_returns)
return generic_nb.rolling_apply_nb(
returns, window, minp, _apply_func_nb) | b1c0c2aba3ae5f4aedfa1fc50ab1114d37bd0c22 | 67,979 |
from datetime import datetime
import uuid
async def register_output(conn: asyncpg.connection, data: schemas.MsCreateOutput):
"""
This function registers mass_spec processed data.
It registers results of derivation with a given methodcode in the result table and
and the corresponding action of derivati... | b69e08be1577752f767f63f805303501176f9718 | 67,980 |
import requests
import time
def make_request(url, timeout=60, *args, method='GET', **kwargs):
"""
Failure-resistant HTTP GET/HEAD request helper method.
"""
retry_count = 0
max_retries = 5
while True:
try:
response = SESSION.request(method, url, *args, timeout=timeout, **kw... | a7c2c9a66ca6f92036a03705d61b71f5035221d8 | 67,981 |
def _merge(source, destination):
"""
https://stackoverflow.com/a/20666342/3639005
>>> a = { 'first' : { 'all_rows' : { 'pass' : 'dog', 'number' : '1' } } }
>>> b = { 'first' : { 'all_rows' : { 'fail' : 'cat', 'number' : '5' } } }
>>> _merge(b, a) == { 'first' : { 'all_rows' : { 'pass' : 'dog', 'fail... | 237e66acdf108dcf201d5650737b105f18d8561e | 67,982 |
import math
def calcCirclePos(robotIdx, numRobots, radius=3, center=(0,0)):
"""
Helper function to distribute robot positions on a circle.
"""
gamma = 2*math.pi / numRobots
x = radius * math.cos(gamma * robotIdx) + center[0]
y = radius * math.sin(gamma * robotIdx) + center[1]
phi = gamma *... | 393c044dcb4016c34b8efe2a7acd185b45c52467 | 67,983 |
import json
def getToken(username, password):
"""
getToken - Get authentication bearer token.
Get 'username' and 'password', request data on auth endpoint and return token object.
Parameters:
username (str): Username to login (cpf).
password (str): Password of given username (born da... | 61657545b8de2fd3251bec480c90540f2eb7c33b | 67,984 |
def eiffel_activity_triggered_event():
"""Eiffel activity triggered event."""
return {
"meta": {
"version": "3.0.0",
"source": {"name": "eiffel-graphql-api-tests"},
"type": "EiffelActivityTriggeredEvent",
"id": "693c3bac-10a6-4b77-82d7-430139195c1e",
... | 8ab4b52e105708cd70746feb13f8c12522d505ee | 67,985 |
def load_content(key):
""" Returns the value of site content """
content = SiteContent.objects.get(variable = key)
return content.val | 1ff77288c97b12cdc8fa88d8b9139ba35aacc7d8 | 67,986 |
def _valley_kernels(size, flat_list):
"""Generate normalized V-shape and U-shape kernels to compute valley index.
Parameters
----------
size : int
Size of the kernel.
flat_list : list of floats in [0,1[
Fractions of flat along the center line of the V-shape kernels. A certain
... | 58dfaa8bc7de9b164a9c2dca828754a189b6ba81 | 67,987 |
from typing import Dict
from typing import List
def _encode_by_batch(documents: Dict[str, List],
tokenizer: Tokenizer,
nlp: English,
dataset_info: DatasetInfo,
bos_token="<BOS>",
sep_token="<SEP>",
... | f5f5e0d759b2bb3cc57e1f627494a1d9e3d41681 | 67,988 |
def index(lhs, rhs, ctx):
"""Element i
(any, num) -> a[b] (Index)
(str, str) -> enclose b in a # b[0:len(b)//2] + a + b[len(b)//2:]
(any, [x]) -> a[:b] (0 to bth item of a)
(any, [x,y]) -> a[x:y] (x to yth item of a)
(any, [x,y,m]) -> a[x:y:m] (x to yth item of a, taking every mth)
(num, any... | 808c84d1401aaf9b85150fe91f9f2fabb543c93c | 67,989 |
def open_file_handler(file_name):
"""
function returning opened file handler
:param file_name:
:return:
"""
return open(file_name, mode='r', encoding='utf8') | 9f78ba9e11060cff515405ffc87d48a585fdc2ed | 67,991 |
def pdf_from_cf_with_fft(cf, h=0.01, q=9, level=3):
"""Calculates pdf from characteristic function.
Uses fast Fourier transform with Newton-Cotes integration following [WZ].
Defaults to using Simpson's method (3-point Newton-Cotes integration).
Parameters
----------
cf : callable
Singl... | f2d8e95deeeb73269fa9a57c0bbe0e09dfbe9c87 | 67,993 |
def make_polyadic_sampler(input_dim: int, kappa: int = 2) -> XGenerator:
"""Samples with local structure centered around kappa N(0, 1) anchor points.
To make this work in jax we actually implement this by first sampling kappa
anchor points, then randomly the tau batch points from these kappa anchors
(with repl... | 1e38512749cf61ad001f0f9442ef81c1362f1ac8 | 67,995 |
import re
def is_valid_vlive_url(url: str) -> bool:
"""Uses a regex to check if the given url is a valid 'vlive.tv./video/' address."""
# VLIVE videos are only identified by numbers in the url (unlike Youtube IDs,
# for example)
vlive_url_regex = r"(vlive\.tv\/video\/[0-9]*)"
if not re.search(vl... | 35c741ea512cad5edd791ebbb8acef99b19d84d3 | 67,996 |
import functools
def setup_required(func):
"""Decorator to handle routes that need setup to have been completed
This decorator should be applied to nearly all routes"""
@functools.wraps(func)
def decorated_function(*args, **kwargs):
config = get_user_config()
if not config.isConfigured:
raise c... | 908fb802187ec1b2e0fc701c00aff37c15bfe0c7 | 67,997 |
import urllib
def test_http_access(by_ip=False):
"""
Test plain HTTP access and return three values:
1. The result - one of the HTTP_ACCESS_* constants
2. isup.me info - one of the HTTP_ISUP_* constants
3. Subdomain block result
"""
sites = http_list
proxy = proxy_addr
print("[O]... | a748331e800f139c8832ffd3c7054ad2cd64c802 | 67,998 |
from typing import OrderedDict
def unzip(zipped):
"""
Pull parameters from Theano shared variables
"""
new_params = OrderedDict()
for kk, vv in zipped.items():
new_params[kk] = vv.get_value()
return new_params | 44c3a60ba9401a7784ff7966a4d72d2731bf2952 | 68,000 |
from typing import Union
from typing import Callable
def divisible_shape(divisor: AxesLike, axes: AxesLike = None, padding_values: Union[AxesParams, Callable] = 0,
ratio: AxesParams = 0.5):
"""
Pads an incoming array to be divisible by ``divisor`` along the ``axes``. Afterwards the padding... | aba98b6bb298934df54bce73db7472516138088d | 68,001 |
def dQHIIdz(y, z,a,b,c,d): # specify the initial time point t0=0
""" Gives differential eq. for QHII """
theta=(a,b,c,d)
trec = 3.19e2*(1+z)**(-3.) * (3./hz.Ch2)#ch2=3
H0m1 = 9.77*hz.h**(-1) #9.77*h^-1 Gyr
dtdz = -H0m1*1./(1+z)*(hz.Om*(1+z)*... | 00f7ef76a8acb539db157c960ee7dac67b110302 | 68,002 |
def linear(z):
"""The linear activation function"""
return z | da2eaf35354f221461451dc343e37e5e59bad51b | 68,003 |
import torch
def sequence_mask(lens: torch.Tensor, max_len: int = None) -> torch.ByteTensor:
"""
Compute sequence mask.
Parameters
----------
lens : torch.Tensor
Tensor of sequence lengths ``[batch_size]``.
max_len : int, optional (default: None)
The maximum length (optional)... | 084a3e25026e1ea862ab5b6190a4fcc63ede8284 | 68,004 |
def pack_bin(in1):
"""
Pack binary arrary.
Data will be packed with little endian for NVIDIA GPU compatibility.
Parameters
----------
in1 : ndarray
The ndarray to be pack at binary.
Returns
-------
out : ndarray
An 1-dimensional array containing packed binary data.
... | a1bc15d18c51231c2bd34455219023ec3415702a | 68,005 |
def boltzman_average_bond_order(bond_orders):
"""
Calculate the Boltzmann weighted bond order average.
Parameters
----------
bond_orders: Dictionary of bond orders. The key is the energy of the molecule.
Returns
-------
bond_order_arrays: Dictionary of Boltzmann weighted bond orders.
... | 84d71bedc39492c0d59f2d2eef672fbe40fdeee5 | 68,006 |
def compare_mssim(x_true, x_pred, data_range, multidimension, detail=False):
"""
:param x_true:
:param x_pred:
:param data_range:
:param multidimension:
:return:
"""
mssim = [structural_similarity(x_true[:, :, i], x_pred[:, :, i], data_range=data_range, multidimension=multidimension)
... | ccedbe5404463d8eb20eea85a0414de888a5cad1 | 68,007 |
def get_slave_exception_by_error(error: HTTPError) -> SlaveResponseException:
"""
Overview:
Auto transform http error object to slave response exception object.
Arguments:
- error (:obj:`HTTPError`): Http error object
Returns:
- exception (:obj:`SlaveResponseException`): Slave re... | 1923001590fd1a76b055b10faeb68921940cb9b3 | 68,008 |
def model_run(config_data):
"""ModelRun built from config
"""
return ModelRun.from_dict(config_data) | d2705240adf9ddc58cfb43ab42c2de7144692a88 | 68,009 |
def post_user_stats(user_info): # noqa: E501
"""updates current user statistics count
# noqa: E501
:param user_info: Which os and platform is the user on.
:type user_info: dict | bytes
:rtype: None
"""
if user_info is not None:
(stat_id, windowsCount, macosCount, otherCount, isD... | 94db218445abbf1df729731a370389dfcea99bd0 | 68,010 |
def check_game_finish(board, mark):
"""Return boolean value is the game finished or not."""
if win_check(board, mark):
print(f'The player with the mark "{mark}" wins!')
return True
if full_board_check(PLAY_BOARD):
print('The game ended in a draw.')
return True
return Fa... | 3f9bb46ec7f72d63ebcadb2154b2789d0a69ffce | 68,011 |
from operator import inv
def generate_position_field(
affine,
velocity_fields,
velocity_field_resolution,
template_shape,
template_resolution,
target_shape,
target_resolution,
deform_to="template",
):
"""
Integrate velocity_fields and apply affine to produce a position field.
... | dde1ac017fc8d3a0eed804974e16ff949d09212e | 68,012 |
import random
def unique_random_string(model, field, length=16):
""" Generates a random alphanumeric string, unique in code field from a django class model
:param length: Length of the generated string.
:param model: Model class, it has a code field.
:param field: field name to be sure is unique.
... | 9e86acc92a2cfecbd14a37cea54698a1606dcfc4 | 68,013 |
def async_pipe(*args, **kwargs):
"""A processor that asynchronously extracts sub-elements from an item.
Args:
item (dict): The entry to process
kwargs (dict): The keyword arguments passed to the wrapper
Kwargs:
conf (dict): The pipe configuration. Must contain the key 'path'. May
... | bc1bcdd44ad5dd4d9f78fd9f14909aeb2bcaecde | 68,014 |
def nature_cnn_lite(scaled_images, **kwargs):
"""
CNN from Nature paper.
:param scaled_images: (TensorFlow Tensor) Image input placeholder
:param kwargs: (dict) Extra keywords parameters for the convolutional layers of the CNN
:return: (TensorFlow Tensor) The CNN output layer
"""
activ = tf.... | b8282282d4ed0a91f7c3f022f41721fb65142cab | 68,015 |
def extractValue(value, attrVal, attrLang, ttlList):
"""
Helper for getAttributes. It decides which characters are added to the value.
For data properties: ""; for object properties: <>; for language tags: ""@<lang>
"""
if 'acdhi:' in value:
ttlList.append(' '.join([attrVal, value]))
eli... | 99607624d284918369061c8525f331e76b5c46a0 | 68,016 |
def modify_instance_or_cluster_for_verify(database, sg_ids):
"""Modify an RDS Instance or Cluster to allow connections.
Args:
database (:class:`dbsnap.database.Database`): the database or cluster
to modify to allow access for verification routines.
sg_ids (list): Security group ids t... | 0f78e064b19b8d1bb2b032eaa13016608852d1b0 | 68,019 |
def numerordinatio_descendentibus(
numerordinatio: str, collectio: list, ordo_maximo: int = None) -> list:
"""numerordinatio_descendentibus _summary_
Trivia:
- collēctiō, s, f, , nominativus
- dēscendentibus, pl, m/f/n, , dativus,
https://en.wiktionary.org/wiki/descendens#Latin
- ō... | 8df7dbd5d24d51ffabf1f853e4aaa21adfcb474b | 68,021 |
from math import cos, sin
def general_rotation(x, y, z, a, b, c, u, v, w, angle):
""" Rotation about an arbitrary line
x,y,z : point to rotate
a,b,c : line through point
u,v,w : direction vector of the line (normalized)
angle : rotation angle in radians when looked down
the rotation ax... | bcf9f70556ca5c8123e9e83f0bb8215919151838 | 68,022 |
def get_option_block_info(block):
"""."""
os_name = sys_info.get_os_name()
block_info = {'names': []}
heads = get_heads(block)
item_blocks = get_blocks_by_heads(block, heads)
for item_block in item_blocks:
head = get_heads(item_block)[0]
item_block = remove_block_head(item_block... | b23112480429b869f2d8280fc28d463130516e1e | 68,023 |
def read_fasta(filepath, to_df = False):
"""
Read data from a fasta file.
Arguments
---------
filename : str, the path to a file in fasta format.
to_df : bool, should the function return a pandas dataframe
instead of a list of dicts? (default is False)
Returns
---------
out : list, a list of sequence... | 302c0940ea34a2817bfe7d6885fd0ebb30ffab7f | 68,024 |
def pca_localized_set(patient_id):
"""Simplified API for setting clinical PCa localized status w/o FHIR
Requires simple JSON doc to set PCaLocalized diagnosis: '{"value": true}'
Raises 401 if logged-in user lacks permission to edit requested
patient.
---
operationId: setPCaLocalized
tags:... | 82cd55c265f5d18a253d0f840055240c8dd7ce2b | 68,026 |
def compute_min_altitude(height, field_of_regard):
"""
Fast computation of minimum altitude angle required to observe a point.
Args:
height (float): Height (meters) above surface of the observation.
field_of_regard (float): Angular width (degrees) of observation.
Returns:
float... | 69a47d85d42bb2f18a944e8ed7496e05394b6f08 | 68,027 |
import pickle
def load_params():
"""
Load parameters from file
"""
return pickle.load(open('params.p', mode='rb')) | 510b3663c0395a43e607cd46318af85719d3cbb7 | 68,028 |
def parse_request_headers(headers):
"""
@param headers:
@return:
"""
request_headers_keys = set(headers.keys(lower=True))
request_meta_keys = set(XHEADERS_TO_ARGS_DICT.keys())
data_headers_keys = request_headers_keys.intersection(request_meta_keys)
return dict(([XHEADERS_TO_ARGS_DICT[key... | 860bc148273592374aa516867f2c149915aa33f6 | 68,030 |
def insertion_sort(arr):
"""Performs insertion sort of given IntsToSort"""
if len(arr) < 2:
return arr
if len(arr) > 1:
i = 1
while i < len(arr):
curr_val = arr[i]
j = i - 1
# Start with curr val and compare to all previous values
whil... | 0e8da20d1e5e958f8df73dc5e9e83a7bdf6d235b | 68,031 |
from datetime import datetime
def get_latest_news(channel, top=None, show_Body=False):
"""
获取即时新闻
Parameters
-------
channel: str, 待获取的新闻所在频道(id或名称)
top: int, 最多获取多少条新闻,默认None全获取
show_body: bool, 是否返回新闻正文,默认False不返回
Result
-------
pandas.DataFrame, 包括如下列:
... | 8fd63e151eafbd61919c3bea021a180196ace8ed | 68,032 |
def cartesian2spherical(m):
"""Convert from cartesian to spherical"""
# nC = int(len(m)/3)
x = m[:, 0]
y = m[:, 1]
z = m[:, 2]
a = (x**2.0 + y**2.0 + z**2.0) ** 0.5
t = np.zeros_like(x)
t[a > 0] = np.arcsin(z[a > 0] / a[a > 0])
p = np.zeros_like(x)
p[a > 0] = np.arctan2(y[a ... | ce9401177b5dc9ab4a7808c3153007bdc1e6c849 | 68,033 |
import unittest
def nightly_gpu():
"""
Nightly GPU tests.
Runs on CircleCI nightly, and when [gpu] or [long] appears in a commit string.
"""
test_loader = unittest.TestLoader()
test_suite = test_loader.discover('tests/nightly/gpu')
test_suite = _circleci_parallelism(test_suite)
return... | c3fcbd224df17f6004b2281080a0fea2383a36c8 | 68,034 |
def robot_x_fn(state, u = None, dt=1.0):
"""
State update for nonlinear system
Computes next state using the non-linear dynamics
"""
x = state.value[0][0]
y = state.value[1][0]
theta = state.value[2][0]
v = state.value[3][0]
w = state.value[4][0]
x += v * cos(theta)*dt
y +=... | 7f08c22495947a26103973aa3401b4557aa0fd34 | 68,035 |
def default_resolution():
"""Note that this and the number of ts objects created below are fine tuned
for these tests to create just over a week of data, and changing them might
cause the tests to fail. See docstrings of tests for info"""
return 20 | eacfdecb06665c52930f959ea9ee0adfde2775c3 | 68,036 |
def dataframe_to_panel_by_colgroup(df,keylist,prefix='',surfix=''):
"""
transfer a dataframe into panel by separating the columns into different
groups by keywords.
Parameters:
-----------
keylist: a list of strings indicating the keylists used to group the
columns.
"""
if n... | ce3dd00c5b3ba6cdb59d7afa3e38eec258831f31 | 68,037 |
import torch
def embedding_similarity(
batch: torch.Tensor,
similarity: str = 'cosine',
reduction: str = 'none',
zero_diagonal: bool = True
) -> torch.Tensor:
"""
Computes representation similarity
Example:
>>> from pytorch_lightning.metrics.functional import embedding_similarity
... | dda82b8fa4dc4f3760a5c7ec329c77b980f3860c | 68,038 |
def non_independent_joint(a, operation, b):
"""非独立联合事件"""
if operation == 'and' or operation == MathSymbols.intersection:
return a * non_independent_joint(b, MathSymbols.condition, a) | b2bbd7968abc7066db16b7c3cf9aba340adcb83e | 68,039 |
def read_annotation_from_dataset(dataset: (list, tuple, dict), label_key):
"""reads the annotation from dataset. Basically reverting annotate.
Args:
dataset:
label_key:
Returns: annotation
>>> dataset = [{'timestamp': 0., 'audio_length': 1.}, {'timestamp': 2., 'audio_length': 5.}, {'t... | 099b6d288c46cae7ea984b51d6dde48d54983a32 | 68,040 |
def get_plots_figure(should_show_plots, should_write_movie):
"""
:param should_show_plots: Indicates whether the animation of SLAM should be plotted, in real time.
:param should_write_movie: Indicates whether the animation of SLAM should be written to a movie file.
:return: A figure if the plots should ... | 40498845559b794e4ad5def0012cb5af73d3f3b3 | 68,041 |
import requests
import tqdm
def stock_jgdy_tj_em(date: str = "20220101") -> pd.DataFrame:
"""
东方财富网-数据中心-特色数据-机构调研-机构调研统计
http://data.eastmoney.com/jgdy/tj.html
:param date: 开始时间
:type date: str
:return: 机构调研统计
:rtype: pandas.DataFrame
"""
url = "http://datacenter-web.eastmoney.com... | 21b567fa6a3a54f01217c9ed6751528a1eb7111a | 68,042 |
from typing import List
from typing import Dict
from typing import Any
def venue_author_representation(
venues: List[str], published_papers: List[Dict[str, Any]]
) -> np.ndarray:
"""Create an author vector representation based on the venues an author has published at.
The returned vector is N-dimensional... | 86191a749e97334b41b2be64c86efba93d57b723 | 68,043 |
def reconstruct_parallel2d(img, basis, ncores=8, algo=reconstruct_1Dmagic):
"""A simple wrapper to reconstruct 2D images assuming the lines are independent.
Careful, this wrapper consider the lines as independent reconstructions to be
performed.
Args:
- img (numpy 2d matrix mxN): input compressed m... | 3ea09038a5488a4e0a2c05db138ba470d2ea03a8 | 68,044 |
from typing import List
from typing import Dict
from typing import Any
import logging
import json
def entity2tag(token_list: List[str], entities: List[Dict[str, Any]]):
""" 将实体 entity 格式转为 tag 格式,若标注过程中有重叠标注,则会自动将靠后的
实体忽略、删除。针对单条处理,不支持批量处理。
Args:
token_list(List[str]): token 化的文本的 list
en... | 79c0d228da642013dfcbfa59aa2e317185e413c2 | 68,045 |
def results(domain):
"""."""
xn = XNTwist()
results = xn.twist(domain, simple=True)
return render_template('results.html', domain=domain, possible_squats=results['possible_squats'], count=results['count']) | 1d9119c5d845eff8ca94243b1bf65b90f3cf2746 | 68,046 |
import logging
import csv
def write_to_csv(incidents, fields_dict, filename, max_count=None, filter=None, in_log=None):
"""
Write incidents to a CSV file according to the field definition.
This function is factorized out intentionally for better unit test.
:param incidents: list of incidents in... | be8e2aabe1b0257ef6ca65d2e3107c046d02357b | 68,047 |
def add_cell_to_compute_node(compute_node, cell_name):
"""Fix compute_node attributes that should be unique. Allows
API cell to query the 'id' by cell@id.
"""
# NOTE(sbauza): As compute_node is a ComputeNode object, we need to wrap it
# for adding the cell_path information
compute_proxy = Compu... | 4821946a17c0104532c11cbcc1206ded691eb64e | 68,048 |
def im_detect_keypoints_scale(model, im, scale, max_size, boxes, hflip=False):
"""Computes keypoint predictions at the given scale."""
# Store the original scale
orig_scales = cfg.TEST.SCALES
orig_max_size = cfg.TEST.MAX_SIZE
# Perform detection at the given scale
cfg.TEST.SCALES = (scale, )
... | a1065619ec5f26dd488e80f8fcebf3806c376268 | 68,049 |
def bundle_archive(request, tmp_path):
"""
Prepare tar file from dir without using bundle packer
"""
return _pack_bundle(request.param, tmp_path) | 62639e6e1710bd525584168cc16631db2b92b19c | 68,050 |
def lmap(*args, **kwargs):
"""Take map generator and make a list for Python 3 work"""
return list(map(*args, **kwargs)) | 8c68edb2d4f26de6583b4bd8ae95722e2f911578 | 68,052 |
def is_space_element(level_element: LevelElement) -> bool:
"""Determines whether the object is a `Space` level element or not."""
return isinstance(level_element, Space) | ec37c917206b1a0b423f43421c5c325363f770ec | 68,056 |
def fib(n):
"""
Computing the nth of Fib series
Implemetation focusing on 1 time running of fib.
"""
memoire = [0] * 100
def rec_fib(n):
if n == 1 or n == 2:
memoire[n-1] = 1
return 1
else:
if memoire[n - 1] == 0:
mem... | dfeae222af315c55a1010ce73857a8925f20d837 | 68,058 |
def cfg_get(cfgfile,item,delimiter,detail=False, config=None):
"""Get value of a config item.
"""
if not config: config = loadconfig(cfgfile,delimiter,detail=detail)
if config.has_key(item):
return config[item]
else:
return None | 871026fe9896e111f7985ef6d212d0706ef8b72e | 68,059 |
def Find(string1, string2):
"""Looks for a substring inside a specified string."""
return NexRun("Find", locals()) | 79a1712b09953b73eb7bd83f359d993971e640d6 | 68,060 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.