content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def dqAccelerationPropagationCOM(robot : object, dWdqCOM0 : np.array, Wdq : list, WdqCOM : list, dWdq : list, qd : np.array, qdd : np.array, symbolic = False):
"""Using Dual Quaternions, this function computes angular and linear acceleration to the j-th center of mass of a serial robot given reference frames' ones. S... | 9399e82ceb8ad8c9bd75b0ed36de70c6c314bbf3 | 71,355 |
def joinfields(words, sep = ' '):
"""joinfields(list [,sep]) -> string
Return a string composed of the words in list, with
intervening occurences of sep. The default separator is a
single space.
(joinfields and join are synonymous)
"""
res = ''
for w in words:
res = res + (sep + w)
return res[len(sep):] | 0941a43811c992417a24ea59c77b4172117d3510 | 71,357 |
def get_FID(mu1, sigma1, mu2, sigma2, eps=1e-6):
"""
Numpy implementation of the Frechet Distance.
The Frechet distance between two multivariate Gaussians X_1 ~ N(mu_1, C_1)
and X_2 ~ N(mu_2, C_2) is
d^2 = ||mu_1 - mu_2||^2 + Tr(C_1 + C_2 - 2*sqrt(C_1*C_2)).
Stable version by Dougal J. ... | dc0bffb0a970c7cece9eda7925bb45ff2ce99a59 | 71,358 |
from typing import Callable
from typing import Any
def has_results(func: Callable[..., Any]) -> Callable[..., Any]:
"""Check whether a particular function has results when filtering its data.
Args:
func: The function to be decorated
Returns:
The decorated function.
Raises:
I... | d52d43f2044c325a7013a2257c07181742a36610 | 71,359 |
from datetime import datetime
def get_all_to_dest(spark, sqlContext, destination):
"""makes the link between destination and position tables"""
d, p = load_dest_data(spark, sqlContext)
# select every mmsi - day couple going to the destination
dest = d.filter(d.destination == destination).collect()
... | e0e92faa6a6a2332cf4bf04731a8159f05b08813 | 71,360 |
import requests
import shutil
def download(url):
"""Retrieve a file from the Web, return local path."""
filename = p.basename(url)
cache_file = p.join(data_dir, filename)
if not p.exists(cache_file):
print('Retrieving: {}'.format(url))
with requests.get(url, stream=True) as r:
... | 1a92a704139ea245db86db2f11927c54bbc1e07b | 71,361 |
def prompt_import_rsa_key_from_file(filepath):
"""Trys to load the key without password. If a CryptoError occurs, prompts
the user for a password and trys to load the the key again. """
password = None
try:
import_rsa_key_from_file(filepath)
except toto.ssl_commons.exceptions.CryptoError, e:
password ... | e7f77dcec3796e24a855b315eb46eaef656d850d | 71,362 |
def get_histograms(img_list):
"""creates a histogram for each image in the list
Args:
img_list (list): each entry is a decoded image in matrix form
Returns:
list: each entry in this list corresponds to a image from the img_list
each entry is a dict with red, green, blue as keys... | 700488f313eb05ae924933bd195ddba65ee6a515 | 71,363 |
def strip_quotes(want, got):
"""
Strip quotes of doctests output values:
>>> strip_quotes("'foo'")
"foo"
>>> strip_quotes('"foo"')
"foo"
"""
def is_quoted_string(s):
s = s.strip()
return (len(s) >= 2
and s[0] == s[-1]
and s[0] in ('"', "'"... | 7696bc2db290cbba14821908cdbbae2c3c10eab2 | 71,364 |
import glob
import configparser
def load_species_from_param_files(fns,
init_world,
custom_module_fns=None):
"""
Load all available species parameter files.
Parameters
----------
fns : list of str
Input filenames of specie... | 6e82ddd44e394d970803e953fb6f18609b8e2eab | 71,365 |
import abc
def get_rename_function(mapper):
"""
Returns a function that will map names/labels, dependent if mapper
is a dict, Series or just a function.
"""
if isinstance(mapper, (abc.Mapping, ABCSeries)):
def f(x):
if x in mapper:
return mapper[x]
... | 1b5ef2d7454b4c4534886a5d0bddb4678f19ef4a | 71,366 |
import requests
from bs4 import BeautifulSoup
def get_channels(country):
"""
Get the list of channels.
:return: list
"""
channels = []
html = requests.get(MAINLIST[country]).text
mlink = SoupStrainer('div', {'class':'nav fusion-mobile-tab-nav'})
soup = BeautifulSoup(html, parseOnlyThes... | a0fddf203aad975e917b65882e470c4641631557 | 71,367 |
def encrypt_bytes(key, source):
"""
Encrypts pure bytes (used for small sources)
CBC mode, including PKCS#7 padding
"""
encryptor, IV = _build_encryptor(key)
byteOutput = IV
byteOutput += _encrypt_chunk(source, encryptor, True)
return byteOutput | a5234159d4052639ed876d504b6784d6a651a2d0 | 71,368 |
import time
def response_to_dict(response, spider, include_request=True, **kwargs):
"""Returns a dict based on a response from a spider"""
d = {
'time': time.time(),
'status': response.status,
'url': response.url,
'headers': dict(response.headers),
'body': response.body... | 35b725a67fdf025b879e97c5d68b321fedfaf313 | 71,369 |
import socket
import fcntl
import struct
def get_ip_address(ifname):
"""
Get the ip address from the specified interface.
>>> get_ip_address('eth0')
'192.168.0.7'
@type ifname: string
@param ifname: The interface name. Typical names are C{'eth0'},
C{'wlan0'}, etc.
@rtype: string
@retu... | 731575a6b642884d7aa74a950ed109fca1e2086a | 71,370 |
def edge_predicate(func: DictEdgePredicate) -> EdgePredicate: # noqa: D202
"""Decorate an edge predicate function that only takes a dictionary as its singular argument.
Apply this as a decorator to a function that takes a single argument, a PyBEL node data dictionary, to make
sure that it can also accept ... | e5db6490796bec57326e6cf6b36c5fd62bd9af59 | 71,371 |
def totient(n):
"""Takes integer n and returns Euler's Totient function (phi(n))"""
phi = n
factors = set(prime_factors(n))
for _ in factors:
phi *= (1 - 1/_)
return int(phi) | 6edbcf650ebc758daa37c3e527836d5b943611f0 | 71,372 |
def validate_id(id:int)->feed_models.Feed:
"""
Method to verify with id if a feed exists
:param id: feed id
:type id: int
:raise: ValueError
:return bool
"""
try:
feed = feed_models.Feed.objects.get(id=id)
except feed_models.Feed.DoesNotExist as e:
... | 79495ab4bbd62f155c4fd555bb957412dc5a0d94 | 71,375 |
def _parallel_build_trees(X, y, tree, interval, lag, acf_min_values):
"""
Private function used to fit a single tree in parallel.
"""
temp_lag = lag
if temp_lag > interval[1] - interval[0] - acf_min_values:
temp_lag = interval[1] - interval[0] - acf_min_values
if temp_lag < 0:
te... | 45e11faf6fa3a92fb6978759feb5ac3c487dd810 | 71,376 |
def drop_terms_containing(e, e_drops):
"""
Drop terms contaning factors in the list e_drops
"""
if isinstance(e, Add):
# fix this
#e = Add(*(arg for arg in e.args if not any([e_drop in arg.args
# for e_drop in e_drops])))
new_ar... | c2cb330e81cee9927ef2bdb08d1198a7f21488a4 | 71,377 |
def SetLabel(*labels):
"""Sets a label on a function so we can run tests with different types."""
def Decorator(f):
# If the method is not already tagged, we replace its label (the default
# label is "small").
function_labels = getattr(f, "labels", set())
f.labels = function_labels.union(set(labels)... | 8a4415e039d0cb7c69a9fd03a3c17c055d5e8fe4 | 71,378 |
from typing import Optional
def gather(
inp: Tensor, group: Optional[Group] = WORLD, device: Optional[str] = None,
) -> Tensor:
"""
Create gather operator for collective communication.
:param inp: input tensor.
:param group: communication group.
:param device: execution device.
"""
o... | 7d5c5d42e5e403369c670a0b827fc07e460ffe70 | 71,379 |
def _talismane_tree(tree_str: ty.Iterable[str]) -> libginger.Tree:
"""Create an Universal Dependencies tree from a Talismane tree.
Talismane outputs are essentially CoNLL-X files, with incompatible
stylistic idiosyncrasies.
"""
conllx_str = [s.replace("|\t", "\t") for s in tree_str]
return _con... | cb22e30df813a8a4895a4f2746115322e9a35289 | 71,380 |
def get_table_list():
"""
Read the 'TABLES' table found under the hidden '_tables' worksheet.
This table is populated from launcher.json file and is used to
determine the table names defined under each worksheet
Returns:
table(dict): k,v, k=worksheet_name and v=list of tables
"""
t... | 0778e2849122751f12822cf0f0357d4c0b6b651d | 71,381 |
from typing import Counter
def percentile(data: list, p=0.5):
"""
:param data: origin list
:param p: frequency percentile
:return: the element at frequency percentile p
"""
assert 0 < p < 1
boundary = len(data) * p
counter = sorted(Counter(data).items(), key=lambda x: x[0])
keys, c... | ac0a3a4705579c1b6a5165b91e6dcad65afcd1f4 | 71,382 |
def parse(module_text, nodes=None):
"""Return abstract syntax tree for `str`ing `module_text`.
`module_text` is a module specification.
Use the syntax tree classes from `nodes`.
For example:
```python
from tla import parser
from tla.to_str import Nodes
module_text = r'''
---- MODU... | 1bdaf07b92963ecc596677327fcc300b572eaf27 | 71,383 |
def _MatchHandler(handler, path):
"""Match a path to a handler.
Args:
handler: A handler dictionary.
path: The path portion of the url.
Returns:
A Page object or None.
"""
if 'static_dir' in handler:
return _MatchStaticDir(handler, path)
elif 'static_files' in handler:
return _MatchSta... | 29713b4bf4728ee7bb430ad981541a2f48b39a6f | 71,384 |
def _get_path_from_parent(self, parent):
"""
Return a list of PathInfos containing the path from the parent
model to the current model, or an empty list if parent is not a
parent of the current model.
"""
if hasattr(self, 'get_path_from_parent'):
return self.get_path_from_parent(parent)
... | 8f213fcbe3612790d4922d53e0e2a4465b098fe6 | 71,385 |
def first_or_default(self, predicate=None, default_value=None):
"""Returns the first element of an observable sequence that satisfies
the condition in the predicate, or a default value if no such element
exists.
Example:
res = source.first_or_default()
res = source.first_or_default(lambda x: x ... | 35a9896cfec6e17ff0e3f1e8d8144ba1237fa03a | 71,386 |
def get_category(node):
"""Return a category label for a given specific protein ontology node."""
name = bio_ontology.get_name(*bio_ontology.get_ns_id(node))
category = categories.get(name)
if category:
category_node = category_map[category]
return category_node
return None | ed4da8fef5e44193122b02f5175c1708b0fe8f46 | 71,387 |
def assortative_mating(obs, exp, col_x, col_y, boundaries = None):
"""
Assortative mating between genotypes across the hybrid zone, and within
spatial bins.
Assortment probabilities for the whole population are calculated as the mean
number of mating events between individuals of the same genotype.... | 94d8301d0869180cefd68c6e48aa72f86d33887e | 71,389 |
def strdigit_normalize(digit):
"""Normalizes input to format '0x'. Example: '9' -> '09'"""
assert type(digit) is str, 'Invalid input. Must be a string.'
s = int(digit)
assert s >= 0, 'Invalid input. Must be string representing a positive number.'
if s < 10:
return '0' + str(s)
return digit | 41b119b4b8b19f978bf4445fc81273f7e62af59a | 71,390 |
import requests
def request_url(url):
"""
Function to send https or http request to this url and return code result.
Parameters
----------
url : string
This variable contain url must be checked
Returns
-------
status_code : int
Code result
"""
try:
ur... | 884d20d33f02110b31e47a29077cb4e093e93536 | 71,391 |
from typing import Type
from typing import Optional
from typing import List
from typing import Any
def _get_trials_sqa(
experiment_id: int,
trial_sqa_class: Type[SQATrial],
load_trials_in_batches_of_size: Optional[int] = None,
trials_query_options: Optional[List[Any]] = None,
) -> List[SQATrial]:
... | 53f31b62ed84260dd5fb50f43f6cbb23217641fc | 71,392 |
def overlap_and_add(spectrum,
signal,
sample_rate,
frame_length=32,
frame_shift=8,
window_type="hanning",
preemphasis=0.0,
use_log=False,
use_power=False,
... | 8f953bde0b8e9b2c20509f2e8e5dde90438ef0df | 71,393 |
def push_api(request):
""" Update the content of a tile (widget) """
if not check_sanity_request(request):
return handleHttpError(request)
HttpData = request.POST
tile_id = HttpData.get('tile_id', None)
tile_template = HttpData.get('tile_template', None)
tile_data = HttpData.get('data', ... | 4a606bd570a01748c2178406a28485f4d52a2744 | 71,394 |
import csv
def csv_to_list(dataset_fname, header = False, y_column = -1):
"""
Reads a csv file and returns the contents of that file as a 2-D list.
Delineates x (independent) variables from y (dependent) variable.
dataset_fname - the file name for the dataset to read.
header - whether the dataset... | 0cceef9e80f1063305a77d420de5d7a2141ceec5 | 71,396 |
def share_emotion_book() -> FlaskResponse:
"""
XHR procedure adding a new entry into the visitor log. The emotion is
neutral if the user has open a book or it is a like if the user clicked
on the "Like" button.
Raises:
404: if the request is not POST.
"""
if "emotion" not in request... | 4e4ac6082f222a44c7a2443c7e500676729ac9f0 | 71,397 |
def make_field(field_name: str, schema: Schema) -> TextArea:
"""Create a field that's suitable to the specified schema, such as
a TextArea. The schema is used to determine the proper type of field
as well as the validator that applies.
"""
# At the moment, the only supported field type is TextArea. ... | 30f14aaa3fdd1a4ef9eac66b1837ab066ff045af | 71,398 |
import httpx
def call_app(app, event):
"""
call wsgi app
see https://cloud.yandex.ru/docs/functions/concepts/function-invoke
#response
"""
host_url = event["headers"].get("Host", "https://raw-function.net")
if not host_url.startswith("http"):
host_url = f"https://{host_url}"
bo... | 94087d442360de95dbd3251b4fbc675a7a7e79ea | 71,401 |
def split_region(region):
"""
Splits a EE FeatureCollection/Feature into four equal parts
:param region: EE FeatureCollection/Feature to split
:return: dictionary containing the four parts of FeatureCollection
"""
bounding_box = region.geometry().bounds() # gets the bounding box of the region
... | e470fb4200c440e6185263771cc98844e74d08ca | 71,402 |
def general_parser(parser):
"""
This is the parser which collects all the parameters passed through the command to launch the script
- experiment_name
- run_description
- val_freq
- acc_log_freq
- loss_log_freq
- images_log_freq
- SN_log_freq
- save_model_freq
- restore_train... | 12cb2beeb5eb7c821b5ff1380a568c6dd5d1e904 | 71,403 |
def fit_function_general(varying_parameters_values_array,
varying_parameters_keys,
Miller_indices,
allparameters,
absolutespotsindices,
Xexp,
... | 9bd8ea9b0b9febd4844b3de2da68a915c75632e9 | 71,404 |
from typing import Union
def divergence(
adata: AnnData,
basis: str = "pca",
color: Union[str, list, None] = None,
cmap: str = "bwr",
frontier: bool = True,
sym_c: bool = True,
*args,
**kwargs,
):
"""\
Scatter plot with cells colored by the estimated divergence (and other infor... | acc03948606dc26a0b7146f5d095744d872a08cf | 71,405 |
def load_vertex_label(dataset_name):
"""Returns vertex label for each dataset."""
if dataset_name == 'BH':
vertex_label = [
'Y_MEDV', 'CRIM', 'ZN', 'INDUS', 'CHAS', 'NOX', 'RM', 'AGE', 'DIS',
'RAD', 'TAX', 'PTRATIO', 'B', 'LSTAT'
]
elif dataset_name == 'Insurance':
vertex_label = [
... | 087f2e51451eb8f95d3908a2af5e1095dda32684 | 71,406 |
def pad(array, n):
"""
ISO/IEC 9797-1 pad array to blocks of size n
"""
pads = len(array) % n
return array + [0]*(n - (len(array)%n)) | cc128428a8c446c1437b5b87d563d67bb2d11f48 | 71,407 |
def unidecode_country(country):
"""Replaces diacritics with corresponding english characters.
Parameters
----------
country : Country
the Country object to have fields sanitized.
Returns
-------
Country
the Country object after fields were sanitized.
"""
country.nam... | 84f64c7d524a79c5bff6771923d1c8293be6fd3f | 71,408 |
def multiclass_log_loss(y_true, y_pred, eps=1e-15):
"""Multi class version of Logarithmic Loss metric.
https://www.kaggle.com/wiki/MultiClassLogLoss
Parameters
----------
y_true : array, shape = [n_samples]
true class, intergers in [0, n_classes - 1)
y_pred : array, shape = [n_sampl... | 981a877ad369cee8821948c9ef464126eedd09ac | 71,409 |
import tqdm
def convert_dictionary_to_name2cui(dictionary, text_preprocessor=None):
"""
convert dictionary to name2cui to get unique names and the corresponding cuis
Note! For names which are duplicate, concat the cui with '|' delimiter.
Parameters
----------
dictionary : list
... | 3e0726fd12208487801e76ee83bcba7565d02a00 | 71,410 |
def show_year_1():
"""
Render page for year1 selection page
:return: rendered page with selection list
"""
group_list = Y1Group.query.all()
return render_template('year-1.html', group_list=group_list) | 1d354828115693279c837282598e5804f1e40990 | 71,411 |
def train_cascade(train_dataset, eval_dataset, stats, action_eval_list, opt):
"""
Train a cascade of deep neural networks that lift 2D key-points to 3D pose.
"""
# initialize an empty cascade
cascade = model.get_cascade()
stage_record = []
input_size = len(stats['dim_use_2d'])
output_siz... | 7cc3c24f7ae2a4391d656a9a5cb17d042c6ae17a | 71,412 |
def from_binho_error(error_number):
"""
Returns the error class appropriate for the given Binho host adapter error.
"""
error_class = BINHO_ERRORS.get(error_number, binhoError)
message = "Error {}".format(error_number)
return error_class(message) | f60c1208c9a22e3be62a38d4df326d68a7eda956 | 71,413 |
def get_auc(test_values, predicted):
"""
Get area under the curve value
:param test_values: values to test with
:param predicted: predicted values
:return: auc value
"""
auc = metrics.roc_auc_score(test_values, predicted,
multi_class="ovr")
return round(au... | 37330adc88fd206a8e6f30f680f4e950c08fe185 | 71,414 |
import numpy
def MLOG(img):
"""Implements the MLOG focus measure algorithm.
:param img: the image the measure is applied to
:type img: numpy.ndarray
:returns: numpy.float32 -- the degree of focus
"""
return numpy.max(cv2.convertScaleAbs(cv2.Laplacian(img, 3))) | 95b4b1aa6ed090e1d814cc0ca0b5ca09c6b642f2 | 71,415 |
from typing import Tuple
from typing import List
def EPS_get_spectrum(EPS: SLEPc.EPS,
mpc: MultiPointConstraint) -> Tuple[List[complex], List[PETSc.Vec], List[PETSc.Vec]]:
""" Retrieve eigenvalues and eigenfunctions from SLEPc EPS object.
Parameters
----------
EPS
... | 240a1b9547417138bc3bc80cab14ef1ef996b5bb | 71,416 |
from typing import Any
from datetime import datetime
from dateutil import tz
def convert_created_at_to_local_time(row: Any) -> datetime:
"""
Convert the 'createdAt' field from UTC time to the application's local time.
Args:
row: The pandas row to be analysed.
Raises:
N/A
Returns:
... | 1da20cd06ac25be8dd8cba65e3653d33bc6a08a5 | 71,417 |
def obtener_descuento_list():
"""
retorna lista de descuentos de base
:return:
"""
return Disccount.objects.all() | 48977fad25e75514b81436d31a2f37cc24676d2e | 71,418 |
import hashlib
def hash_file(pathname):
"""Returns a byte string that is the SHA-256 hash of the file at the given pathname."""
h = hashlib.sha256()
with open(pathname, 'rb') as ifile:
h.update(ifile.read())
return h.digest() | bdd82aa57abacee91a4631d401af35f0274eb804 | 71,419 |
def ResNetRS350(
include_top=True,
weights="imagenet",
classes=1000,
input_shape=(None, None, 3),
input_tensor=None,
pooling=None,
classifier_activation="softmax",
):
"""Build ResNet-RS350 model."""
allow_bigger_recursion(1500)
return ResNetRS(
depth=350,
include_... | 7fbcaa8c01c893541b6312e515b61587fee48d2b | 71,420 |
def title_value(req):
"""
查询副标题参数
:param req: request
:return:
"""
ret = ResModel()
ret.msg = req_invalid_check(req)
if ret.msg:
# 请求合法性校验不通过
ret.code = ret.ResCode.fail
ret.data = {}
return JsonResponse(ret.to_dic())
ret.code = ret.ResCode.succ
w... | 4aaede177f6a62d906a01496dd55501ec328a426 | 71,421 |
import torch
def test_unbalanced_logging_with_multiple_optimizers(tmpdir):
"""
This tests ensures reduction works in un-balanced logging settings
"""
class TestModel(BoringModel):
loss_1 = []
loss_2 = []
def training_step(self, batch, batch_idx, optimizer_idx):
ou... | 1ba95e55c2d8215977424f920733220b8ac95f39 | 71,422 |
import importlib
def convert(string, convert_type):
"""Execute convert.
This module call convert module selected from choices.
"""
module = importlib.import_module("converter." + convert_type)
return module.convert(string) | b0d89172b813df3f009b904339fe6af672917419 | 71,423 |
def iob_iobes(tags):
"""
IOB -> IOBES
"""
new_tags = []
for i, tag in enumerate(tags):
if tag == 'O':
new_tags.append(tag)
elif tag.split('-')[0] == 'B':
if i + 1 != len(tags) and \
tags[i + 1].split('-')[0] == 'I':
new_tags.appe... | b0ba7d6efc16218a5686ab60a7dedb59aed3ab7d | 71,424 |
from datetime import datetime
def get_local_time():
"""
获取时间
Return:
datetime: 时间
"""
cur = datetime.datetime.now()
cur = cur.strftime('%b-%d-%Y_%H-%M-%S')
return cur | f06e9b8da578bc4fef1fc736323aa0f6642cd02d | 71,425 |
def mask_complex_polygon(image, vertices, triangles, bbox_only=False):
"""
Crops out a complex polygon from an image. The returned image is cropped
to the bounding box of the vertices.
:param image: path or :class:`PIL.Image`
:param vertices: List ``[[x1, y1], [x2, y2]]`` or string
``"x1,... | 93a2d693f6caf784107b523a699c4041c3692064 | 71,426 |
def training(loss, learning_rate):
"""Sets up the training Ops.
Creates a summarizer to track the loss over time in TensorBoard.
Creates an optimizer and applies the gradients to all trainable variables.
The Op returned by this function is what must be passed to the
`sess.run()` call to cause the model to ... | fd7ee15e68c6e6a4726de8ffc1becd670fba0844 | 71,427 |
def set_op_type(*args):
"""set_op_type(ea_t ea, flags_t type, int n) -> bool"""
return _idaapi.set_op_type(*args) | e4ca744e936755d3066dd4b9e6472f4bf6ed91dc | 71,428 |
import copy
import warnings
from typing import Iterable
def jnum2str(jnum, x_orientation=None):
"""
Convert jones polarization number to str according to calfits memo.
Parameters
----------
num : int
antenna (jones) polarization number
x_orientation : str, optional
Orientation... | a8776819aa60eb46a92a7e7ac3a242361da6845a | 71,430 |
def note():
"""Serves a *notes set* **record** page.
Usually from an overview page or a shared link.
The page consists of a sidebar with the details of the notes set,
and the main area displays the notes between the verses.
"""
session.forget(response)
request.vars["mr"] = "r"
request.... | 356c0a047b2ceaf7381143f3c57943a7450cc007 | 71,431 |
def __report_detail(health, items):
"""Report the details of health check item
:type health: dict
:param health: the overall health status
:type items: dict
:param items: a dict that contains all detail items to check
:rtype dict
:return health status including overall status and details ... | eea2cad2c52d62cd40cea757d0a128b9c283f618 | 71,433 |
def clean_field(field):
"""Return a cleaned version of field.
Parameters
==========
field : numeric or string
DataFrame cell to clean
Returns
=======
field : numeric
Cleaned DataFrame cell
Notes
=====
In most cases, pandas will correctly read the contents of a... | 6a19d3b75e5009d3d1f4e34cfa0f9b2f51b4f301 | 71,435 |
def read_iaga(fname, return_xyzf=True):
"""Reads an IAGA-2002 data file and returns data in XYZF format."""
# Get the header information
header_records = read_iaga_header(fname)
# This contains 4 letters stating the reported values
# - XYZF, HDZF, etc...
if len(header_records['reported']) % 4 ... | 9bfaa14544e923a5d41749cf7fc7715f4cf32fce | 71,436 |
def Qpar(sortedEigVec,d=1):
"""concatenation of first d eig vectors . (parallel decompositon of hessian)"""
return np.concatenate(sortedEigVec[0:d]).T | c28123b4f067ef4c8b876aeb6a20ba3e00dd21cd | 71,437 |
def reduce_columns(dataset: Dataset, min_df=5, inplace=False):
"""
Reduces the dimensionality of the instances, represented as a `csr_matrix` (or any subtype of
`scipy.sparse.spmatrix`), of training and test documents by removing the columns of words which are not present
in at least `min_df` instances ... | 6caee331b3ce0cec4186a3ca72bdef4c1748e3b1 | 71,438 |
def tcn(
inputs,
filters,
kernel_size,
strides=1,
padding='valid',
data_format='channels_last',
dilation_rate=1,
activation=None,
use_bias=True,
kernel_initializer=None,
bias_initializer=tf.zeros_initializer(),
kernel_regularizer=None,
bias_regularizer=None,
activ... | 1a2118c67c5d597e9b3f5268570c484493ff49fe | 71,439 |
def integrate(times):
"""
Returns the seconds of staked times for an array of alternating deposit
and withdrawal times for a token.
"""
if len(times) == 1:
return CURRENT_TIME - times[0]
elif len(times) % 2 == 0:
s = 0
for i in range(0, len(times), 2):
s += ti... | 93385d77595014a8fc7540048af74bac3afb3cea | 71,440 |
def get_PLUMBER_metrics(name, site='all', variables=['Qle', 'Qh', 'NEE']):
"""get metrics dataframe from a site, with benchmarks for comparison
:returns: dataframe with metrics for model at site
"""
csv_file = './source/models/{n}/metrics/{n}_{s}_metrics.csv'
# benchmark_names = ['1lin', '2lin', '... | 807a6c3e2fff6b087f6fdcfb9d99f22c417f7209 | 71,443 |
from time_series import Time_series
def _serie_get(project, row, cur, id1, ifecha, ivalue, situaciones, isitu):
"""
hace select a una BDD e instancia un objeto Temporal_series
input
project: tag del proyecto seleccionado
row: fila de select_master correspondiente al punto cuyos umbrales
q... | afc12c3199c66f3471399b4dc1c621ef0ef5bf89 | 71,444 |
import xarray as xr
from scipy.signal import welch
def fft_average( da,
nperseg=None,
noverlap=None,
plot=False,
verbose=True,
trimNegFreqs=False,
normalizeAmplitude=False,
sortFreqIndex=False,
returnAbs=False,
zeroTheZeroFrequency=False,
realAmplitudeUnits=False,
... | c515a67b4a2157131ec241b2b751ca3068880a44 | 71,445 |
def get_resized_size(org_h, org_w, long_size=513):
"""get_resized_size"""
if org_h > org_w:
new_h = long_size
new_w = int(1.0 * long_size * org_w / org_h)
else:
new_w = long_size
new_h = int(1.0 * long_size * org_h / org_w)
return new_h, new_w | 699b91a1fbdb1e5228872d3ea5812dcc29cfbaa5 | 71,446 |
def parse(url, defaultPort=True):
"""
Split the given URL into the scheme, host, port, and path.
@type url: C{str}
@param url: An URL to parse.
@type defaultPort: C{bool}
@param defaultPort: Whether to return the default port associated with the
scheme in the given url, when the url do... | 6bd14455a8e0f72a413c4f1055e372f48708c49f | 71,447 |
def buildPairPosGlyphsSubtable(pairs, glyphMap, valueFormat1=None, valueFormat2=None):
"""Builds a single glyph-based pair adjustment (GPOS2 format 1) subtable.
This builds a PairPos subtable from a dictionary of glyph pairs and
their positioning adjustments. See also :func:`buildPairPosGlyphs`.
Note ... | 68db50654c517cf7cb10e6c87bba05021087e4e7 | 71,448 |
import random
def is_prime(number, test_count):
"""
Uses the Miller-Rabin test for primality to determine, through TEST_COUNT
tests, whether or not NUMBER is prime.
"""
if number == 2 or number == 3:
return True
if number <= 1 or number % 2 == 0:
return False
d = 0
r = ... | 49b0149dad5f053bbf813845a10267766784c775 | 71,449 |
def MergeSequences(seqs):
"""Merge a sequence of sequences into a single sequence.
This code is copied from https://www.python.org/download/releases/2.3/mro/
with print statements removed and modified to take a sequence of sequences.
We use it to merge both MROs and class templates.
Args:
seqs: A sequen... | 24ab5d84dc4c9416810b6e99cf3b18b996b570ad | 71,451 |
def monitor_code(hook, task_name=None):
"""
Provide a context manager to monitor code blocks.
Parameters
----------
hook : callable (:class:`Task`, [exception])
A hook on which to register progress. It must have
- one mandatory argument which is a :class:`Task`instance
- one... | 4f05691ce82a9425c8045c1ba7a336fdb2b28307 | 71,453 |
def setFramerate(absValue=20):
""" This function sets the framrate and returns the value from the camera as it will not be exact """
cam.setProperty(type = PyCapture2.PROPERTY_TYPE.FRAME_RATE, autoManualMode = False, absValue = absValue)
return getFramerate(cam) | aa577419a5a73436ad593745e695a2dd130ca8d8 | 71,454 |
def create_segment(**kwargs):
"""
Takes the same arguments as gparray.Segment's constructor, but with friendly
defaults to minimize typing.
"""
content = kwargs.get('content', 0)
role = kwargs.get('role', gparray.ROLE_PRIMARY)
preferred_role = kwargs.get('preferred_role', ro... | c56dad2692a8d212643d6729192c71c68ebf13f2 | 71,455 |
def compute_f1(actual, predicted):
"""
Computes the F1 score of your predictions. Note that we use 0.5 as the cutoff here.
"""
num = len(actual)
true_positives = 0
false_positives = 0
false_negatives = 0
true_negatives = 0
precision = 0
recall = 0
for i in range(num):
... | 2af79c51056114ac35b6b03fe21f49978f7499e6 | 71,456 |
def learn_d_z_weighted(
X, n_atoms, n_times_atom, func_d=update_d_block, reg=0.1, alpha=1.9,
lmbd_max='fixed', n_iter_global=10, init_tau=False, n_iter_optim=10,
n_iter_mcmc=10, n_burnin_mcmc=0, random_state=None, n_jobs=1,
solver_z='l-bfgs', solver_d_kwargs=dict(), solver_z_kwargs=dict(... | cd1fc156e6d8f94d7539562ed570b2a0ef6bd8d2 | 71,457 |
async def _setup(hass, filter_config):
"""Shared set up for filtering tests."""
config = {
google_pubsub.DOMAIN: {
"project_id": "proj",
"topic_name": "topic",
"credentials_json": "creds",
"filter": filter_config,
}
}
assert await async_set... | 83e63a25d22bbefb578cb0f2d797ae59511b1f52 | 71,458 |
def select_metadata(metadata, **attributes):
"""Select specific metadata describing preprocessed data.
Parameters
----------
metadata : :obj:`list` of :obj:`dict`
A list of metadata describing preprocessed data.
**attributes :
Keyword arguments specifying the required variable attri... | 5ba8c990f77d635c3dcdd21512adf61fd6d18812 | 71,459 |
import cPickle
def search_vars_represent(search_vars):
"""
Unpickle and convert saved search form variables into
a human-readable HTML.
@param search_vars: the (c)pickled search form variables
@returns: HTML as string
"""
s = ""
search_vars = search_vars.replace("&a... | 5f08eb4c0c18929816eab43ea5f489a60ff162b0 | 71,460 |
def main():
"""
main function
"""
print("---- Tengine YOLOv3 Optimize Tool ----\n")
args = parse_args()
if args == None or args.input == None:
usage_info()
return None
print("Input model : %s" % (args.input))
print("Output model : %s" % (args.output))
print... | ee95997338ac666da9f5bfce3a5d3e95306cbb50 | 71,461 |
def weave_fast_clauses(clauses,
embed,
apply_,
not_,
or_,
and_=None,
shuffle=True,
seed=None):
"""Weave serialized FastClauses using TensorLoom.
Computes ... | be39858947805fc656575224c6e75529fe10a602 | 71,462 |
from typing import Iterable
from typing import AnyStr
from typing import Optional
from typing import Iterator
from typing import cast
from typing import List
def iterhtmldecode(
iterable: Iterable[AnyStr],
http_charset: Optional[str] = None,
default_encoding: str = "cp1252",
errors: str = "replace",
... | a5011e7baf889a3702e9afcf9150ab64187c1865 | 71,463 |
def _get_flight_level(aircraft_id):
"""
Get a dataframe with the aircraft's current, requested and cleared flight levels.
Parameters
----------
aircraft_id : str
A string aircraft identifier. For the BlueSky simulator, this has to be
at least three characters.
Returns
-----... | b93caa2866ccb43ab5b9d5fa024b4de800e0445f | 71,465 |
def compute_centroid(coords):
"""Compute the centroid of coordinates.
.. math::
\\mathbf{C} =
\\frac{\\sum_{i=1}^{N}m_i\\mathbf{r}_i}{\\sum_{i=1}^{N}m_i}
Returns
-------
C : `~sknano.core.math.Vector`
The position vector of the centroid coordinates.
"""
C = Vector(np.... | 0b307af3110d3deadc3ce1b19bb8c177849533a1 | 71,466 |
def query_yes_no(question, default="yes"):
"""
Ask a yes/no question using input() and return the answer.
:param question: a string that is presented to the user
:param default: the presumed answer if the user just hits <Enter>.
It must be "yes" (the default), "no" or None (meaning
an an... | 117e0d05811fc7eb80e9e94e08942744c256cef8 | 71,467 |
from .sampler import Sampler
from typing import Tuple
import numpy
def image_compose(
imlist:list,
outsize:Tuple,
bgcolor:list = [255,255,255],
) -> numpy.ndarray:
"""
Compose image from parts
Parameters
----------
imlist : list
List of image parts, each element a 3-elemen... | 71bfc52aca23e52f99bb709ece0465d815a618b7 | 71,468 |
def ff_bin( smiles = 'c1ccccc1O'):
"""
It generates binary string fingerprint value
Output -> '0b0010101...'
"""
mol = Chem.MolFromSmiles( smiles)
fp = AllChem.GetMorganFingerprint(mol,2)
fp_hex = fp.ToBinary().encode("hex")
fp_bin = bin( int( fp_hex, 16))
# print fp_bin
return fp_bin | c94cfa1a24fe6830b07edaa741326fee9707daa1 | 71,469 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.