content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def verifica_cc(numero):
"""verifica_cc(numero): int -> tuple
Funcao que verifica o numero do cartao, indicando a categoria e a rede emissora"""
numero_final = str(numero)
if luhn_verifica(numero_final) == True:
categor = categoria(numero_final)
rede_cartao = valida_iin(numero_final)
... | f6d3501b8154c05058006575f8aa33c228b9ade6 | 3,642,200 |
def create_security_group(stack, name, rules=()):
"""Add EC2 Security Group Resource."""
ingress_rules = []
for rule in rules:
ingress_rules.append(
SecurityGroupRule(
"{0}".format(rule['name']),
CidrIp=rule['cidr'],
FromPort=rule['from_por... | e4d2b81fc1c3b0b3231725aa8757ea644d2efdf6 | 3,642,201 |
from typing import List
import tqdm
def features_targets_and_externals(
df: pd.DataFrame,
region_ordering: List[str],
id_col: str,
time_col: str,
time_encoder: OneHotEncoder,
weather: Weather_container,
time_interval: str,
latitude: str,
longitude: str,
):
"""
Function that... | c9fc9fc210407ec596facda1bc43952ce9c6b98a | 3,642,202 |
def main(argv=None):
""" Execute the application CLI.
Arguments are taken from sys.argv by default.
"""
args = _cmdline(argv)
config.load(args.config)
results = get_package_list(args.search_term)
results = sorted(results, key=lambda a: sort_function(a[1]), reverse=True)
results_normali... | 1bfa7c6bc8181b32859089b0ac2be8b231882ec5 | 3,642,203 |
def transform_child_joint_frame_to_parent_inertial_frame(child_body):
"""Return the homogeneous transform from the child joint frame to the parent inertial frame."""
parent_joint = child_body.parent_joint
parent = child_body.parent_body
if parent_joint is not None and parent.inertial is not None:
... | 0ab8761ef40101368fb3f2b657c329cd8cf5cf2b | 3,642,204 |
def team_to_repos(api, no_repos, organization):
"""Create a team_to_repos mapping for use in _add_repos_to_teams, anc create
each team and repo. Return the team_to_repos mapping.
"""
num_teams = 10
# arrange
team_names = ["team-{}".format(i) for i in range(num_teams)]
repo_names = ["some-rep... | 390da146c3f96c554f9194f8551a066eec535533 | 3,642,205 |
def box_minus(plus_transform: pin.SE3, minus_transform: pin.SE3) -> np.ndarray:
"""
Compute the box minus between two transforms:
.. math::
T_1 \\boxminus T_2 = \\log(T_1 \\cdot T_2^{-1})
This operator allows us to think about orientation "differences" as
similarly as possible to position... | 838f5e8b4f91450c311c72d4526e4c8fd3c9d6f7 | 3,642,206 |
import struct
def padandsplit(message):
"""
returns a two-dimensional array X[i][j] of 32-bit integers, where j ranges
from 0 to 16.
First pads the message to length in bytes is congruent to 56 (mod 64),
by first adding a byte 0x80, and then padding with 0x00 bytes until the
message length is ... | ea06a3fc91e19ed0dbea6ddcc2ee6d554fb5a40f | 3,642,207 |
import requests
def base_put(url_path, content):
"""
Do a PUT to the REST API
"""
response = requests.put(url=settings.URL_API + url_path, json=content)
return response | dde94c1dba0d8a931a0eae0e8f5ce63d1f5a62a1 | 3,642,208 |
def inverse_rotation(theta: float) -> np.ndarray:
"""
Compute inverse of the 2d rotation matrix that rotates a
given vector by theta without use of numpy.linalg.inv and numpy.linalg.solve.
Arguments:
theta: rotation angle
Return:
Inverse of the rotation matrix
"""
rotation_matri... | 732183f7577969a1ecbbd0ee5ed86342c65991fc | 3,642,209 |
import functools
def _config_validation_decorator(func):
"""A decorator used to easily run validations on configs loaded into dicts.
Add this decorator to any method that returns the config as a dict.
Raises:
ValueError: If the configuration fails validation
"""
@functools.wraps(func)
... | 1a63254e43c2920d6952105d9860138c395cbf2b | 3,642,210 |
import functools
def image_transpose_exif(im):
"""
https://stackoverflow.com/questions/4228530/pil-thumbnail-is-rotating-my-image
Apply Image.transpose to ensure 0th row of pixels is at the visual
top of the image, and 0th column is the visual left-hand side.
Return the original image if unable to... | 4f166ea59c097e4306bd43db7165e56e8d289b6a | 3,642,211 |
import os
def GetFileList(folder, surfixs=".xls,.xlsx"):
""" 遍历文件夹查找所有满足后缀的文件 """
surfix = surfixs.split(",")
if type(folder) == str:
folder = folder.decode('utf-8')
p = os.path.abspath(folder)
flist = []
if os.path.isdir(p):
FindFileBySurfix(flist, p, surfix)
else:
... | 4b4def62c47335474fe2a4b3e4b6bce341e05bf9 | 3,642,212 |
def opt_pore_diameter(elements, coordinates, bounds=None, com=None, **kwargs):
"""Return optimised pore diameter and it's COM."""
args = elements, coordinates
if com is not None:
pass
else:
com = center_of_mass(elements, coordinates)
if bounds is None:
pore_r = pore_diameter(... | f75a7c4246bc2ad096de309795d61afea78f7c3e | 3,642,213 |
def animate_operators(operators, date):
"""Main."""
results = []
failures = []
length = len(operators)
count = 1
for i in operators:
try:
i = i.encode('utf-8')
except:
i = unicode(i, 'utf-8')
i = i.encode('utf-8')
print(i, count, "/",... | d8dd6afdd4a13ab62a4c821bb43050af07fdc455 | 3,642,214 |
import warnings
import os
import json
import time
def random_sampler(vocs, evaluate_f,
executor=None,
output_path=None,
chunk_size=10,
max_samples=100,
verbose=None):
"""
Makes random samples based on vocs
... | ff93cd2fabe3b769975645a7f2335727702a079f | 3,642,215 |
import torch
def get_span_encoding(key, zero_span_rep=None):
"""
Input: document key
Output: all possible span tuples and their encodings
"""
instance = reader.text_to_instance(combined_json[key]["sentences"])
instance.index_fields(model.vocab)
generator = iterator(instances=[instance])
... | feff6b3a31471fe31cd2481d3ffcad5a87107371 | 3,642,216 |
def add_stocks(letter, page, get_last_page=False):
"""
goes through each row in table and adds to df if it is a stock
returns the appended df
"""
df = pd.DataFrame()
res = req.get(BASE_LINK.format(letter, page))
soup = bs(res.content, 'lxml')
table = soup.find('table', {'id': 'Companyli... | ce86ef68a107fbae8d0028486bef8567dc24c43e | 3,642,217 |
def available_parent_amount_rule(model, pr):
"""
Each parent has a limited resource budget; it cannot allocate more than that.
:param ConcreteModel model:
:param int pr: parent resource
:return: boolean indicating whether pr is staying within budget
"""
if model.parent_possible_allocations[... | e1ccc7e9ad4941bfffebefd34217cd58c5bc18e5 | 3,642,218 |
def extract_coords(filename):
"""Extract J2000 coordinates from filename or filepath
Parameters
----------
filename : str
name or path of file
Returns
-------
str
J2000 coordinates
"""
# in case path is entered as argument
filename = filename.split("/")[-1] if ... | 57f0ca79223116caa770a1dbea2eda84df146855 | 3,642,219 |
def exponential(mantissa, base, power, left, right):
"""Return the exponential signal.
The signal's value will be `mantissa * base ^ (power * time)`.
Parameters:
mantissa: The mantissa, i.e. the scale of the signal
base: The exponential base
power: The exponential power
left: Left bound of... | a2fbd76b6426f600d19eb9caeb4edac88dea9a9c | 3,642,220 |
def get_features(features, featurestore=None, featuregroups_version_dict={}, join_key=None, online=False):
"""
Gets a list of features (columns) from the featurestore. If no featuregroup is specified it will query hopsworks
metastore to find where the features are stored. It will try to construct the query ... | 03cfc250bd921b291ac38fce5beddac3144e65ba | 3,642,221 |
def get_flex_bounds(x, samples, nsig=1):
"""
Here, we wish to report the distribution of the subchunks 'sample'
along with the value of the full sample 'x'
So this function will return x, x_lower_bound, x_upper_bound,
where the range of the lower and upper bound expresses
the standard deviation ... | 0fb4120307f61aafce902e92a32c66fd9aad91bf | 3,642,222 |
def _parse_multi_header(headers):
"""
Parse out and return the data necessary for generating ZipkinAttrs.
Returns a dict with the following keys:
'trace_id': str or None
'span_id': str or None
'parent_span_id': str or None
'sampled_str': ... | 2ac3d0cbee196385e970bcc85827c1a467b5bb3b | 3,642,223 |
import numpy
def get_tgimg(img):
"""
处理提示图片,提取提示字符
:param img: 提示图片
:type img:
:return: 返回原图描边,提示图片按顺序用不同颜色框,字符特征图片列表
:rtype: img 原图, out 特征图片列表(每个字), templets 角度变换后的图
"""
imgBW = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
h, w = imgBW.shape
_, imgBW = cv2.threshold(imgBW, 0, 255,
... | 5f48e2b639dd3027e6463b1a99a8b7c13c043f88 | 3,642,224 |
def brand_profitsharing_order_query(self, transaction_id, out_order_no, sub_mchid):
"""查询连锁品牌分账结果
:param transaction_id: 微信支付订单号,示例值:'4208450740201411110007820472'
:param out_order_no: 商户分账单号,只能是数字、大小写字母_-|*@,示例值:'P20150806125346'
:param sub_mchid: 子商户的商户号,由微信支付生成并下发。示例值:'1900000109'
"""
if sub_... | cb1af072f2b4f94f632817baff6cdfea66110873 | 3,642,225 |
def get_controller_from_module(module, cname):
"""
Extract classes that inherit from BaseController
"""
if hasattr(module, '__controller__'):
controller_classname = module.__controller__
else:
controller_classname = cname[0].upper() + cname[1:].lower() + 'Controller'
controller_c... | b450105f6ec38a03fe461c5d9c07c4652da0efd3 | 3,642,226 |
def exp(d: D) -> NumDict:
"""Compute the base-e exponential of d."""
return d.exp() | a4d5baf6bdfadb48add80096bb4d167f01572b69 | 3,642,227 |
def Main(operation, args):
"""Supports 2 operations
1. Consulting the existing data (get)
> get ["{address}"]
2. Inserting data about someone else (certify)
> certify ["{address}","{hash}"]
"""
if len(args) == 0:
Log('You need to provide at least 1 parameter - [address]')... | 0dac2ddb4dc3d259e30f5a3c100a39ff8d7b940d | 3,642,228 |
def get_latest_file_list_orig1(input_list, start_time, num_files):
"""
Return a list of file names, trying to get one from each index file in input_list.
The starting time is start_time and the number of days to investigate is num_days.
"""
out = []
for rind in input_list:
# Create time... | 744b5392d136129a1135cea3ad577817798ef582 | 3,642,229 |
def get_ogheader(blob, url=None):
"""extract Open Graph markup into a dict
The OG header section is delimited by a line of only `---`.
Note that the page title is not provided as Open Graph metadata if
the image metadata is not specified.
"""
found = False
ogheader = dict()
for line in... | 4edd7c5545ddef241ee2bfd5e316e47a336aaa3f | 3,642,230 |
def list_ingredient():
"""List all ingredients currently in the database"""
ingredients = IngredientCollection()
ingredients.load_all()
return jsonify(ingredients=[x.to_dict() for x in ingredients.models]) | d3275dba18922b9f4558f23eedda3ae25d8a25d9 | 3,642,231 |
import re
def ParseSavedQueries(cnxn, post_data, project_service, prefix=''):
"""Parse form data for the Saved Queries part of an admin form."""
saved_queries = []
for i in xrange(1, MAX_QUERIES + 1):
if ('%ssavedquery_name_%s' % (prefix, i)) not in post_data:
continue # skip any entries that are bla... | 5db4ecdf22eb61c1c43914f00042862142664590 | 3,642,232 |
def label_anchors(anchors, anchor_is_untruncated, gt_classes, gt_bboxes, background_id, iou_low_threshold=0.41, iou_high_threshold=0.61):
""" Get the labels of the anchors. Each anchor can be labeled as positive (1), negative (0) or ambiguous (-1). Truncated anchors are always labeled as ambiguous. """
n = anch... | 39dc4d29f5a2491c2f818e7af2c01e1824afff56 | 3,642,233 |
import hashlib
def make_hash_md5(obj):
"""make_hash_md5
Args:
obj (any): anything that can be hashed.
Returns:
hash (str): hash from object.
"""
hasher = hashlib.md5()
hasher.update(repr(make_hashable(obj)).encode())
return hasher.hexdigest() | c8c0f0202f171e2557eba6a3824ac2f9a07dada9 | 3,642,234 |
def fbx_data_bindpose_element(root, me_obj, me, scene_data, arm_obj=None, mat_world_arm=None, bones=[]):
"""
Helper, since bindpose are used by both meshes shape keys and armature bones...
"""
if arm_obj is None:
arm_obj = me_obj
# We assume bind pose for our bones are their "Editmode" pose.... | 9d205cd3c7a0242dbfaad42d1e7f0b9b3b81eb75 | 3,642,235 |
def partitioned_rml_estimator(y, sigma2i, iterations=50):
"""
Implementation of the robust maximum likelihood estimator.
Parameters
----------
y : :py:class:`~numpy.ndarray`, (n_replicates, n_variants)
The variant scores matrix
sigma2i : :py:class:`~numpy.ndarray`, (n_replicates, n_vari... | b4ec6ad8af85cdf29470fa132d7f6008617b3a66 | 3,642,236 |
import math
def inv_kinema_cal_3(JOINT_ANGLE_OFFSET, L, H, position_to_move):
"""逆運動学を解析的に解く関数.
指先のなす角がηになるようなジョイント角度拘束条件を追加して逆運動学問題を解析的に解く
引数1:リンク長さの配列.nd.array(6).単位は[m]
引数2:リンク高さの配列.nd.array(1).単位は[m]
引数3:目標位置(直交座標系)行列.nd.array((3, 1)).単位は[m]
戻り値(成功したとき):ジョイント角度配列.nd.array((6)).単位は[°]
... | 4368c847b9918f3682e2ca0336008af49f0823cf | 3,642,237 |
import time
import os
def get_log_filename(log_directory, device_name, name_prefix=""):
"""Returns the full path of log filename using the information provided.
Args:
log_directory (path): to where the log file should be created.
device_name (str): to use in the log filename
name_prefix (str): ... | 48c0540c9717e54ab4389a2c9f6a5e31696c4595 | 3,642,238 |
def delete_voting(request, slug):
"""Delete voting view."""
if request.method == 'POST':
poll = get_object_or_404(Poll, slug=slug)
if poll.automated_poll and Bug.objects.filter(id=poll.bug.id):
# This will trigger a cascade delete, removing also the poll.
Bug.objects.fil... | bd604104fe17321b7a66a6b742134734d196d8c8 | 3,642,239 |
import time
import requests
def http_delete_request(
portia_config: dict,
endpoint: str,
payload: dict=None,
params: dict=None,
optional_headers: dict=None
) -> object:
"""Makes an HTTP DELETE request.
Arguments:
portia_config {dict} -- Portia's configuration arguments
... | 86096d2fbfd950cafdbb9689f48d7078ed1c545c | 3,642,240 |
from django.contrib.auth import authenticate, login
def http_basic_auth(func):
"""
Attempts to login user with u/p provided in HTTP_AUTHORIZATION header.
If successful, returns the view, otherwise returns a 401.
If PING_BASIC_AUTH is False, then just return the view function
Modified code by... | fd99ce1464acb88bd9f68b6b85233dd44cb81bfd | 3,642,241 |
def stats_to_df(stats_data):
""" Transform Statistical API response into a pandas.DataFrame
"""
df_data = []
for single_data in stats_data['data']:
df_entry = {}
is_valid_entry = True
df_entry['interval_from'] = parse_time(
single_data['interval']['from']).date()
... | d77d3ee46c68c737ce8274458d8564256f8121a7 | 3,642,242 |
def make_risk_metrics(
stocks,
weights,
start_date,
end_date
):
"""
Parameters:
stocks: List of tickers compatiable with the yfinance module
weights: List of weights, probably going to be evenly distributed
"""
if mlfinlabExists:
Var, VaR, CVaR, CD... | 8a24d542a8b7475a66c0c914866ee4225564b8ed | 3,642,243 |
def decrypt(bin_k, bin_cipher):
"""decrypt w/ DES"""
return Crypto.Cipher.DES.new(bin_k).decrypt(bin_cipher) | fa8331b792ae4003c2fc14fd84b2ac82306bc7b2 | 3,642,244 |
import subprocess
def remove_app(app_name, app_path):
"""Remove an application."""
# usage: mbl-app-manager remove [-h] app_name app_path
print("Remove {} from {}".format(app_name, app_path))
command = [MBL_APP_MANAGER, "-v", "remove", app_name, app_path]
print("Executing command: {}".format(comma... | 2d939608db40731ce4c20d0c587a8b99c04d864b | 3,642,245 |
from ucscsdk.mometa.vnic.VnicIScsiLCP import VnicIScsiLCP
from ucscsdk.mometa.vnic.VnicVlan import VnicVlan
def lcp_iscsi_vnic_add(handle, name, parent_dn, addr="derived",
admin_host_port="ANY",
admin_vcon="any", stats_policy_name="global-default",
... | 6d87f8f3adebaa56850dfb14137fe049ff6e01ee | 3,642,246 |
def fixture_ecomax_with_data(ecomax: EcoMAX) -> EcoMAX:
"""Return ecoMAX instance with test data."""
ecomax.product = ProductInfo(model="test_model")
ecomax.set_data(_test_data)
ecomax.set_parameters(_test_parameters)
return ecomax | 4f496342d461eb39e4689ed266471b11bdf3f1f5 | 3,642,247 |
import os
import io
def _get_cached_setup(setup_id):
"""Load a run from the cache."""
cache_dir = config.get_cache_directory()
setup_cache_dir = os.path.join(cache_dir, "setups", str(setup_id))
try:
setup_file = os.path.join(setup_cache_dir, "description.xml")
with io.open(setup_file, ... | 4cb89eab27e0c9a0c5da050a8e2f8b88494ca243 | 3,642,248 |
async def request_get_stub(url: str, stub_for: str, status_code: int = 200):
"""Returns an object with stub response.
Args:
url (str): A request URL.
stub_for (str): Type of stub required.
Returns:
StubResponse: A StubResponse object.
"""
return StubResponse(stub_for=stub_f... | f4c4f9a0610e8d95f920ddee76c4264e23c08283 | 3,642,249 |
import torch
def single_gpu_test(model, data_loader, rescale=True, show=False, out_dir=None):
"""Test with single GPU.
Args:
model (nn.Module): Model to be tested.
data_loader (nn.Dataloader): Pytorch data loader.
show (bool): Whether show results during infernece. Default: False.
... | 0e548186e5909b1a7b72d6fd6ed16c80e233e0b6 | 3,642,250 |
def readAllCarts():
"""
This function responds to a request for /api/people
with the complete lists of people
:return: json string of list of people
"""
# Create the list of people from our data
return[CART[key] for key in sorted(CART.keys())] | 7ec9b25b36c238a6bfae3963482d610ed09d1d75 | 3,642,251 |
import random
import logging
def build_encapsulated_packet(select_test_interface, ptfadapter, tor, tunnel_traffic_monitor):
"""Build the encapsulated packet sent from T1 to ToR."""
_, server_ipv4 = select_test_interface
config_facts = tor.get_running_config_facts()
try:
peer_ipv4_address = [_[... | e7776a602eeb0dbe9bcd8707b71dacfe4ac36338 | 3,642,252 |
def index():
"""
Renders the index page.
"""
return render_template("index.html") | cc7630c3bbaf32c3be705a7205df715f959a5683 | 3,642,253 |
import re
def condense_colors(svg):
"""Condense colors by using hexadecimal abbreviations where possible.
Consider using an abstract, general approach instead of hard-coding.
"""
svg = re.sub('#000000', '#000', svg)
svg = re.sub('#ff0000', '#f00', svg)
svg = re.sub('#00ff00', '#0f0', svg)
... | 413f1d7c69a52384fc21ee6f8eda6f2a63833e66 | 3,642,254 |
import attr
def install_pytest_confirmation():
"""Ask if pytest should be installed"""
return f'{fg(2)} Do you want to install pytest? {attr(0)}' | b81da35d4eb7e755f7780cf0b6da056096613549 | 3,642,255 |
def dense_nopack(cfg, data, weight, bias=None, out_dtype=None):
"""Compute dense without packing"""
debug = True
if debug:
print("bias", bias)
print("data_dtype", data.dtype)
print("weight_dtype", weight.dtype)
print("out_dtype", out_dtype)
if out_dtype is None:
... | 8b7c9101afce8bc6f89f9eca8a103082e2448c9c | 3,642,256 |
def rgb(r=0, g=0, b=0, mode='RGB'):
"""
Convert **r**, **g**, **b** values to a `string`.
:param r: red part
:param g: green part
:param b: blue part
:param string mode: ``'RGB | %'``
:rtype: string
========= =============================================================
mode ... | 563b8fe8273ce4534567687df01cebe79b9f58dc | 3,642,257 |
def load_csv_translations(fname, pfx=''):
"""
Load translations from a tab-delimited file. Add prefix
to the keys. Return a dictionary.
"""
translations = {}
with open(fname, 'r', encoding='utf-8-sig') as fIn:
for line in fIn:
line = line.strip('\r\n ')
if len(lin... | e8b4707fe5eeb0f0f4f4859bd9a5f2272387a022 | 3,642,258 |
def compute_bleu_rouge(pred_dict, ref_dict, bleu_order=4):
"""
Compute bleu and rouge scores.
"""
assert set(pred_dict.keys()) == set(ref_dict.keys()), \
"missing keys: {}".format(set(ref_dict.keys()) - set(pred_dict.keys()))
scores = {}
bleu_scores, _ = Bleu(bleu_order).compute_score(re... | b000f97208fc8254e28ebc85501912e568c7b2d7 | 3,642,259 |
from datetime import datetime
def check_upload_details(study_id=None, patient_id=None):
""" Get patient data upload details """
participant_set = Participant.objects.filter(patient_id=patient_id)
if not participant_set.exists() or str(participant_set.values_list('study', flat=True).get()) != study_id:
... | 6611e9235a6085635e19a9cad8e1920adb757a87 | 3,642,260 |
def crc32c_rev(name):
"""Compute the reversed CRC32C of the given function name"""
value = 0
for char in name:
value ^= ord(char)
for _ in range(8):
carry = value & 1
value = value >> 1
if carry:
value ^= CRC32_REV_POLYNOM
return value | 0aea3d45c0efc136be56bac2ee44ba8e08945de3 | 3,642,261 |
def sils_cut(T,f,c,d,h):
"""solve_sils -- solve the lot sizing problem with cutting planes
- start with a relaxed model
- add cuts until there are no fractional setup variables
Parameters:
- T: number of periods
- P: set of products
- f[t]: set-up costs (on period t)
... | ca689370fe928b38cdd96cdd7b227699f0979a1c | 3,642,262 |
def progressive_fixed_point(func, start, init_disc, final_disc, ratio=2):
"""Progressive fixed point calculation"""
while init_disc <= final_disc * ratio:
start = fixedpoint.fixed_point(func, start, disc=init_disc)
init_disc *= ratio
return start | d46d325bdc3ddb1c5627e231f9659e992a9a0748 | 3,642,263 |
import json
async def create_new_game(redis: Redis = Depends(redis.wrapper.get)):
"""Create a new game with an unique ID."""
game = get_new_game()
handle_score(game)
game_dict = game_to_dict(game)
game_id = token_urlsafe(32)
await redis.set(game_id, json.dumps(game_dict))
return GameState(... | 45de279daba553d4e722f64d0ccb921f90332112 | 3,642,264 |
def _write_reaction_lines(reactions, species_delimiter, reaction_delimiter,
include_TS, stoich_format, act_method_name,
ads_act_method, act_unit, float_format,
column_delimiter, sden_operation,
**kwargs):
"""Writ... | 9787279dee81cd97922657739975c93fcbed8249 | 3,642,265 |
def refines_constraints(storage, constraints):
"""
Determines whether with the storage as basis for the substitution map there is a substitution that can be performed
on the constraints, therefore refining them.
:param storage: The storage basis for the substitution map
:param constraints: The const... | de82087c41d95240ee9d15bd51810b7c5594ef0f | 3,642,266 |
def dot_fp(x, y):
"""Dot products for consistent scalars, vectors, and matrices.
Possible combinations for x, y:
scal, scal
scal, vec
scal, mat
vec, scal
mat, scal
vec, vec (same length)
mat, vec (n_column of mat == length of vec)
Warning: No broadca... | d1bf8bd32727973ebb65ead39921202bfd842973 | 3,642,267 |
def add_one(num: int) -> int:
"""Increment arg by one."""
return num + 1 | 72d8ff69fa5766e813f637f9796753ae51e493b9 | 3,642,268 |
def normalize(data, train_split):
""" Get the standard score of the data.
:param data: data set
:param train_split: number of training samples
:return: normalized data, mean, std
"""
mean = data[:train_split].mean(axis=0)
std = data[:train_split].std(axis=0)
return (data - mean) / std,... | cfc45ac5bd6ae7a30169253a1ae3ed64c1bd1118 | 3,642,269 |
def lemma(name_synsets):
"""
This function return lemma object given the name.
.. note::
Support only English language (*eng*).
:param str name_synsets: name of the synset
:return: lemma object with the given name
:rtype: :class:`Lemma`
:Example:
... | 84a9ae7dbb1679477257ff03557afa75f950a542 | 3,642,270 |
def export_cookies(domain, cookies, savelist=None, sp_domain=None):
"""
Export cookies used for remembered device/other non-session use
as list of Cookie objects. Only looks in jar matching host name.
Args:
domain (str) - Domain to select cookies from
cookies (requests.cookies.Requests... | 7609ac6452ed49dae5cd66f280bbeb4b27b17034 | 3,642,271 |
from typing import Tuple
from typing import OrderedDict
def adaptive_crossover(parents: Tuple[AbstractSolution, AbstractSolution],
variables_number: int,
crossover_pattern: int) -> ChildrenValuesTyping:
"""
Adaptive crossover function.
Crossover is performed ... | 76446c9c35739dddd9bfb797379b44616c552bbd | 3,642,272 |
def get_type_dict(kb_path, dstc2=False):
"""
Specifically, we augment the vocabulary with some special words, one for each of the KB entity types
For each type, the corresponding type word is added to the candidate representation if a word is found that appears
1) as a KB entity of that type,
""... | cd35054505c429cc1ad17eabe1cafb1aa6b38a1f | 3,642,273 |
def parse_time(duration: str, minimum: int = None, maximum: int = None, error_on_exceeded: bool = True) -> int:
"""Function that parses time in a NhNmNs format. Supports weeks, days, hours, minutes and seconds, positive and
negative amounts and max values. Minimum and maximum values can be set (in seconds), and... | 9878d744cd9cc60696d414a31ff121e384e261a9 | 3,642,274 |
import logging
import array
def correl_align(s_orig, align_phases=False,tol=1e-4,indirect_dim='indirect',
fig_title='correlation alignment',signal_pathway = {'ph1':0,'ph2':1},
shift_bounds=False, avg_dim = None, max_shift = 100., sigma=20.,direct='t2',fl=None):
"""
Align transients collected ... | 73235551904db27b639d04a66140d3f07c5dfa3e | 3,642,275 |
def get_fragment_mz_dict(pep, fragments, mod=None):
"""
:param pep:
:param fragments:
:param mod:
:return:
"""
mz_dict = dict()
for each_fragment in fragments:
frag_type, frag_num, frag_charge = rapid_kit.split_fragment_name(each_fragment)
mz_dict[each_fragment] = calc_fr... | ffc79c35111548471a3a98f5999dee013975752d | 3,642,276 |
def merge_dicts(iphonecontrollers, ipadcontrollers):
"""Add ipad controllers to the iphone controllers dict, but never overwrite a custom controller with None!"""
all_controllers = iphonecontrollers.copy()
for identifier, customclass in ipadcontrollers.items():
if all_controllers.get(identifier) is ... | 10638e775d6578e2553ff5b2b47aff8a17051c7e | 3,642,277 |
def perimRect(length,width):
"""
Compute perimiter of rectangle
>>> perimRect(2,3)
10
>>> perimRect(4, 2.5)
13.0
>>> perimRect(3, 3)
12
>>>
"""
return 2*(length+width) | 50fdd92430352f443d313d0931bab50ad5617622 | 3,642,278 |
def h_search(endpoint, query, sort, order, per_page, page):
"""
- Executes search.search and returns a dictionary
of results
`return {headers,status_code,items}`
"""
current_search_params = {
"query": query,
"sort": sort,
"order": order,
"per_page": per_page,
... | 6b0ee993b2baf440f1e6c835a003bebe06dc448a | 3,642,279 |
import asyncio
import traceback
import functools
import inspect
def async_wrapper(fn):
"""
Wraps an async function or generator with a function which runs that generator on the thread's
event loop. The wrapped function requires an 'xloil_thread_context' argument which provides a
callback object to re... | a2929f74d12b153d0cd0720effb618b376bed56f | 3,642,280 |
def add_deprecated_species_alias(registry, ftype, alias_species, species, suffix):
"""
Add a deprecated species alias field.
"""
unit_system = registry.ds.unit_system
if suffix == "fraction":
my_units = ""
else:
my_units = unit_system[suffix]
def _dep_field(field, data):
... | 2782079c908227d11780f66fb2d809b69680a31a | 3,642,281 |
def docker_client():
"""
Return the current docker client in a manner that works with both the
docker-py and docker modules.
"""
try:
client = docker.from_env(version='auto', timeout=3600)
except TypeError:
# On older versions of docker-py (such as 1.9), version isn't a
#... | 7761299ea845577d67815df9fdd98dd74e828454 | 3,642,282 |
import typing
import copy
def bulk_generate_metadata(html_page: str,
description: dict=None,
enable_two_ravens_profiler=False
) -> typing.List[typing.List[dict]]:
"""
:param html_page:
:param description:
:param es_index... | 333d4ce53eac5b7214d516a09c5070b718b7a165 | 3,642,283 |
def add_cals():
"""
Add nutrients from products.
"""
if 'username' in session:
user_obj = users_db.get(escape(session['username']))
calc = Calculator(user_obj.weight, user_obj.height,
user_obj.age, user_obj.gender, user_obj.activity)
food = request.form.... | f052b1d314fa3005f7bcd74b5890dba049bb3827 | 3,642,284 |
def parse(q):
"""http://en.wikipedia.org/wiki/Shunting-yard_algorithm"""
def _merge(output, scache, pos):
if scache:
s = " ".join(scache)
output.append((s, TOKEN_VALUE, pos - len(s)))
del scache[:]
try:
tokens = lex(q)
except Exception as e:
... | 484b240d1ec2cea3cf553bcbac5bef33efd1f74a | 3,642,285 |
def CheckChangeOnUpload(input_api, output_api):
"""Presubmit checks for the change on upload.
The following are the presubmit checks:
* Check change has one and only one EOL.
"""
results = []
results.extend(_CommonChecks(input_api, output_api))
# Run on upload, not commit, since the presubmit bot apparen... | 4791e348cfa7e4e1d25341bf44f8ddb8c8a84d4e | 3,642,286 |
def compute_compression_rate(file: str, zip_archive) -> float:
"""Compute the compression rate of two files.
More info: https://en.m.wikipedia.org/wiki/Data_compression_ratio
:param file: the uncompressed file.
:param zip_archive the same file but compressed.
:returns the compre... | f92f81282b51da253b1f06ad63d72555917b8256 | 3,642,287 |
def set_idc_func_ex(name, fp=None, args=(), flags=0):
"""
Extends the IDC language by exposing a new IDC function that is backed up by a Python function
This function also unregisters the IDC function if 'fp' was passed as None
@param name: IDC function name to expose
@param fp: Python callable tha... | fe3656d7e33285eecc79b497866529e81ff15e64 | 3,642,288 |
from typing import Dict
def get_hidden_plugins() -> Dict[str, str]:
"""
Get the dictionary of hidden plugins and versions.
:return: dict of hidden plugins and their versions
"""
hidden_plugins = get_cache('cache/hidden-plugins.json')
if hidden_plugins:
return hidden_plugins
else:
... | bf4db552411576a4840b72e2e10aab25030d6191 | 3,642,289 |
import time
def wait_for_re_doc(coll, key, timeout=180):
"""Fetch a doc with the RE API, waiting for it to become available with a 30s timeout."""
start_time = time.time()
while True:
print(f'Waiting for doc {coll}/{key}')
results = re_client.get_doc(coll, key)
if results['count'] ... | 0aa70ddd010f2d60ef2340d17ddf94b8660d0f1c | 3,642,290 |
def split_year_from_week(data: pd.DataFrame) -> pd.DataFrame:
"""
Because we have used the partition key as the NFL year, the year/week need to be put into the appropriate columns
"""
data[[Stats.YEAR, Stats.NFL_WEEK]] = data[Stats.YEAR].str.split("/", expand=True)
data[Stats.NFL_WEEK] = data[Stats.... | 52e65d28b3169759e949725b17d159d319514a61 | 3,642,291 |
from .core import Array, from_array
def normalize_index(idx, shape):
"""Normalize slicing indexes
1. Replaces ellipses with many full slices
2. Adds full slices to end of index
3. Checks bounding conditions
4. Replace multidimensional numpy arrays with dask arrays
5. Replaces numpy array... | 63b98679ca435a238682d86124d6a60e81dd1f89 | 3,642,292 |
def relu(data):
"""Rectified linear unit.
.. math::
out = max(x, 0)
Parameters
----------
data : relay.Expr
The input data
Returns
-------
result : relay.Expr
The computed result.
"""
return _make.relu(data) | 3c4602d68ca18a851ed6c24a35c348b1a97a2a4d | 3,642,293 |
def levsim(args):
"""Returns the Levenshtein similarity between two terms."""
term_i, term_j, j = args
return (MLEV_ALPHA * (1 - Levenshtein.distance(term_i, term_j) \
/ max(len(term_i), len(term_j)))**MLEV_BETA, term_j, j) | 5c4c70cbf0c172ac42ad26d15753a18e79fdd1f4 | 3,642,294 |
def retrieve_job_logs(job_id):
"""Retrieve job's logs.
:param job_id: UUID which identifies the job.
:returns: Job's logs.
"""
return JOB_DB[job_id].get('log') | b2759f3af8316272c4f4ef7f63939634a114c0c9 | 3,642,295 |
import sys
def parse_argv():
"""Parses arguments for use with the test launcher.
Arguments are:
1. Working directory.
2. Test runner, `pytest` or `nose`
3. debugSecret
4. debugPort
5. Debugger search path
6. Mixed-mode debugging (non-empty string to enable, empty string to disable)
... | 08ddb56f0fa0d0ef58d5cc3a437037ee2356d1a6 | 3,642,296 |
def _normalize_format(fmt):
"""Return normalized format string, is_compound format."""
if _is_string_or_bytes(fmt):
return _compound_format(sorted(
_factor_format(fmt.lower()))), ',' in fmt
else:
return _compound_format(sorted([_normalize_format(f)[0] for f in... | 30094ec1b00205ae321a53f1bcba3ae250cd740d | 3,642,297 |
def get_cevioai_version() -> str:
"""
CeVIO AIのバージョンを取得します。
Returns
-------
str
CeVIO AIのバージョン
"""
_check_cevioai_status()
return _service_control.host_version | 1186878664776d445402d04251bec140cda3390a | 3,642,298 |
import subprocess
from bs4 import BeautifulSoup
import operator
def get_all_revisions_available(link):
""" List all the revisions availabel for a particular link
"""
svn_username = current_user.svn_username
svn_password = current_user.svn_password
link = link.replace("dllohsr222","10.133.0.222")
... | a531e6bd9e2fb1e7f35af2a4b51e167634f8f4f6 | 3,642,299 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.