content stringlengths 35 416k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
import numpy
def bytscl(array, maxv=None, minv=None, top=255, nan=False):
"""
Replicates the bytscl function available within IDL
(Interactive Data Language, EXELISvis).
Scales all values of array in the range
(minv <= value <= maxv) to (0 <= scl_value <= top).
:param array:
A numpy a... | 45b17cfdb22acbef15efcb3d824ee0c08e9d5be0 | 47,641 |
def resolve_from_path(path):
"""Resolve a module or object from a path of the form x.y.z."""
modname, field = path.rsplit(".", 1)
mod = __import__(modname, fromlist=[field])
return getattr(mod, field) | fffda7518a78c72a441547116f2b33ed459adb05 | 47,642 |
import math
def svo_angle(mean_allocation_self, mean_allocation_other):
"""
Calculate a person's social value orientation angle (based on the slider measure).
params: A mean allocation to self and a mean allocation to other, based on the six primary items of the SVO slider
returns: The person's socia... | 0b3f39309c44d6e3fee893debb54ef00786d321e | 47,643 |
def power(base_int: int, power_int: int) -> int:
"""
Returns base raised to the power.
Parameters:
first (int) : First Integer
second (int) : Second Integer
"""
return base_int ** power_int | 826d227998bb1c7782682037af3e3b6b84948c5a | 47,644 |
def validate_mp_xy(fits_filenames, control_dict):
""" Quick check for frequently made errors in MP XY entries in control dict.
:param fits_filenames:
:param control_dict:
:return: 2-tuple, (mp_xy_files_found, mp_xy_values_ok). [2-tuple of booleans, both True if OK]
"""
mp_location_filenames = [m... | 2d129eae8e7fed9f6a11ae4d5bc2a2e285c1f694 | 47,645 |
def search_link_when(page_offset):
"""When function factory."""
def _inner(search_dict):
p = search_dict['_pagination']
if page_offset < 0 and p.prev_page is None:
return False
elif page_offset > 0 and p.next_page is None:
return False
else:
re... | d138a08a8efe1881a4687af730c1c85e137c952a | 47,646 |
import uuid
def GetRandomUUID():
"""Generates a random UUID.
Returns:
str: the UUID.
"""
return str(uuid.uuid4()) | a1984535b67775c31235979f315f8e46f1fdd53b | 47,647 |
def get_hosts(path, url):
"""
Creates windows host file config data
:param path:
:param url:
:return: string
"""
info = """
# host for %%path%%
127.0.0.1\t%%url%%
""".replace("%%url%%", url).replace("%%path%%", path)
return info | 5e606c6dd36706f5c0fe1e492143231c4bd229ee | 47,648 |
def boom(iterable, target: int) -> str:
"""Find the target in iterable.
Return 'Boom!' if found.
Return f"there is no {target} in the list"
"""
for number in iterable:
if str(target) in str(number):
return "Boom!"
return f"there is no {target} in the list" | 2161ad0e165180cc54649a0078c9899f65bcb714 | 47,649 |
def _normalized_import_cycle(cycle_as_list, sort_candidates):
"""Given an import cycle specified as a list, return a normalized form.
You represent a cycle as a list like so: [A, B, C, A]. This is
equivalent to [B, C, A, B]: they're both the same cycle. But they
don't look the same to python `==`. S... | 328046069999c8f3f960cc526b277a21c7daab5d | 47,650 |
def expand_features_and_labels(x_feat, y_labels):
"""
Take features and labels and expand them into labelled examples for the
model.
"""
x_expanded = []
y_expanded = []
for x, y in zip(x_feat, y_labels):
for segment in x:
x_expanded.append(segment)
y_expanded.... | 5cd5dbe18285fdcbc633809cd95dde17e32dd82b | 47,651 |
def rle(seq):
""" Create RLE """
run = []
run.append(seq[0])
howmany = 1
for index in range(1, len(seq)):
if seq[index] == run[-1]:
howmany += 1
elif seq[index] != run[-1] and howmany != 1:
run.append(str(howmany))
howmany = 1
run.appen... | 9b333dcc92fa51b2261b8167da9ef6375e022792 | 47,652 |
def pl_max(pos_list):
"""Solution to exercise R-7.11.
Implement a function, with calling syntax max(L), that returns the max-
imum element from a PositionalList instance L containing comparable
elements.
"""
max_val = pos_list.first().element()
for element in pos_list:
if element > ... | 2e4f0c3dbb3984245dcde819a91c0e2f425b30b0 | 47,653 |
def add_extension(file_name, ext='py'):
"""
adds an extension name to the file_name.
:param file_name: <str> the file name to check for extension.
:param ext: <str> add this extension to the file name.
:return: <str> file name with valid extension.
"""
if not file_name.endswith(ext):
... | 123a8a01c70cd3bf98f189c9582796fcdfa97ee3 | 47,654 |
def drop_empty(df):
"""Removes rows with empty values from dataframe"""
new_df = df.dropna(axis=0)
result = set(df.index).symmetric_difference(set(new_df.index))
if len(result) == 0:
print("No empty rows found")
else:
print("\nIndexes removed from data because of missing data:\n",
... | 5ad672c1cd6980cdd5d96e5506dcfa912331b509 | 47,655 |
def join_rsc_table_captions(document):
"""Add wrapper tag around Tables and their respective captions
Arguments:
document {[type]} -- [description]
"""
for el in document.xpath('//div[@class="table_caption"]'):
next_el = el.getnext()
if next_el.tag == 'div' and next_el.attrib['c... | 5cc717fedafbe11a83d3a7da82616d942eb4d052 | 47,656 |
def largest_number_of_edges():
"""Solution to exercise R-14.2.
If G is a simple undirected graph with 12 vertices and 3 connected com-
ponents, what is the largest number of edges it might have?
---------------------------------------------------------------------------
Solution:
-------------... | f4c6f4bb7144058bb8c323e0c8584dcff1be7507 | 47,658 |
def get_url_with_query_params(request, location, **kwargs):
"""
Returns link to given location with query params.
Usage:
get_url_with_query_params(request, location, query_param1=value1, query_param2=value2)
returns:
http(s)://host/location/?query_param1=value1&query_param2=value2&...
"""
... | 350003c0c86ff80db5f70ba16de6d86edadbf6e4 | 47,659 |
def is_hex_digit(char):
"""Checks whether char is hexadecimal digit"""
return '0' <= char <= '9' or 'a' <= char <= 'f' | 172ae4a57bd77e7e33237bec77831417e961babd | 47,660 |
def is_valid_term(iterms):
""" Checks if term is correct """
cterms = ['Angle', 'Proper-Dih.', 'Improper-Dih.', 'LJ-14', 'Coulomb-14', 'LJ-(SR)', 'Coulomb-(SR)', 'Coul.-recip.', 'Position-Rest.', 'Potential', 'Kinetic-En.', 'Total-Energy', 'Temperature', 'Pressure', ' Constr.-rmsd', 'Box-X', 'Box-Y', ' Box-Z', 'Volum... | 882570c2865aedd3698317153a974a92d9966f1c | 47,661 |
import os
def list_dir(path) -> str:
"""list all files/directories under given directory path
encapsulation for system function.
"""
return os.listdir(path) | a500a828a74b6db64574806887c115aaccf91815 | 47,663 |
import socket
def get_ip(domain):
"""
获取ip
:param domain:
:return:
"""
ip = socket.getaddrinfo(domain, "http")[0][4][0]
return ip | e9e9186debebbf885bd284abc65346b65b0117b8 | 47,664 |
def is_valid_optimizer(optimizer):
"""
Checks if optimizer is valid or not
"""
# If the optimizer is None returning False
if not optimizer:
return False
try:
# Calling the get_optimizer method to details of the optimizer
optimizer_details = optimizer.get_optimizer()
... | 6e45704c2663b8bc8deed47bb6e31cd4d316d516 | 47,665 |
def subtracttime(d1, d2):
"""Return the difference in two dates in seconds"""
dt = max(d1, d2) - min(d1, d2)
return 86400 * dt.days + dt.seconds | bae7668ef9b593c7ebe072d789e1b298f81cda3e | 47,667 |
def _unary_op(fn):
"""Wrapper that restricts `fn` to have the correct signature."""
def unary_op_wrapper(x, name=None):
return fn(x, name=name)
return unary_op_wrapper | 5fa43c8495b2ad1cdc7e815e2fe7220917da59ad | 47,670 |
def removeWords(answer):
"""Removes specific words from input or answer, to allow for more leniency."""
words = [' town', ' city', ' island', ' badge', 'professor ', 'team ']
answer = answer.lower()
for word in words:
answer = answer.replace(word, '')
return answer | 088debb26571dc31415591e5026972b057987229 | 47,671 |
def process_cabin(df):
"""Process the Cabin column into pre-defined 'bins'
Usage
------
train process_cabin(train)
"""
df["Cabin_type"] = df["Cabin"].str[0]
df["Cabin_type"] = df["Cabin_type"].fillna("Unknown")
df = df.drop('Cabin',axis=1)
return df | 2c8585b158908a8ab0749142ec0e2ea1b22f3089 | 47,672 |
def get_device_properties(node, device_index=1):
"""Return a tuple with (motor_device, resolution, joint_parameters)
Parameters
----------
node: (str, node)
The joint node that contains the device to extract properties from
index: int
Use 1 for device and 2 for device2
"""
i... | 1921ae114338aa102c8e6ddbb932715cac1ff937 | 47,673 |
def _adjust_n_months(other_day, n, reference_day):
"""Adjust the number of times a monthly offset is applied based
on the day of a given date, and the reference day provided.
"""
if n > 0 and other_day < reference_day:
n = n - 1
elif n <= 0 and other_day > reference_day:
n = n + 1
... | e7a46f8923fb57985e3f32a1130f34e703a58627 | 47,674 |
def mcf_to_boe(mcf=0, conversion_factor=6):
"""Converts mcf to barrels of oil equivalent using the standard 6 mcf/boe conversion factor."""
return (mcf/conversion_factor) | e7f7b984ec0e537512cf2b926c72c25c83a3507b | 47,675 |
def symp_h_ratio(counts_coords):
"""example_meyers_demo.yaml from SEIRcity v2"""
return [0.00070175, 0.00070175, 0.04735258, 0.16329827, 0.25541833] | 03d1f010d91e56bb91233dc17dafb0d493c1381f | 47,677 |
def check_won (grid):
"""return True if a value>=32 is found in the grid; otherwise False"""
for i in range(4):
for j in range(4):
if grid[i][j] >= 32:
return True
return False | f93751aa8073bc3e1b3965bd598a17f0c98da967 | 47,680 |
import re
def any_char_matches(substring: str, mainString: str):
"""Scans the string for any matches a certain pattern.
Parameters
----------
substring : str
The string that is used to find matches from `mainString`.
mainString : str
The `mainstring` which contains the original s... | b0db76f9f7ed34cd45ba118c758944afbb7b0090 | 47,681 |
def getDens(mCM):
"""
return density based on type(mCM['dens'])
mCM['dens'] can be a number or a function
Parameters:
mCM, multi-component material dictionary - see init
"""
if type(mCM['dens']) in [float, int]:
dens = mCM['dens']
else:
dens = mCM['dens'](mCM)
... | 60e6baa70f5c6cd90cf4578bd9f348e947d18979 | 47,683 |
def parse_sqlplus_arg(database):
"""Parses an sqlplus connection string (user/passwd@host) unpacking the user, password and host.
:param database: sqlplus-like connection string
:return: (?user, ?password, ?host)
:raises: ValueError
when database is not of the form <user>/<?password>@<host>
... | 51bb3304458d4b3d3a69c694b13066e1d713a272 | 47,685 |
def is_palindrome(input_string):
"""
Checks if a string is a palindrome.
:param input_string: str, any string
:return: boolean, True if palindrome else False
>>> is_palindrome("madam")
True
>>> is_palindrome("aabb")
False
>>> is_palindrome("race car")
False
>>> is_palindrom... | 165df98dd983a2d84ad30bafbb70168d9599bd8d | 47,687 |
import codecs
import base64
def convert_r_hash_hex(r_hash_hex):
""" convert_r_hash_hex
>>> convert_r_hash_hex("f9e328f584da6488e425a71c95be8b614a1cc1ad2aedc8153813dfff469c9584")
'+eMo9YTaZIjkJacclb6LYUocwa0q7cgVOBPf/0aclYQ='
"""
r_hash = codecs.decode(r_hash_hex, 'hex')
r_hash_b64_bytes = ba... | 8980e43ff4f30e69e9cfc0ed7427f787ea97d701 | 47,688 |
import re
def contains_curse(sometext):
"""
Checks a particular string to see if it contains any
NSFW type words. curse words, things innapropriate
that you might find in lyrics or quotes
:param sometext: some text
:type sometext: Str
:returns: a boolean stating whether we have a curse word or not
:rtype:... | e979fec6ba2cd88191dde304445416129a7f5049 | 47,690 |
def get_bib_blocks(content, start_character="@", delim=("{", "}")):
"""
returns all bib blocks (entries enclosed by the specified delimiters)
start_character will look backwards from the start of the block for this character
the result will be a tuple of two strings: from start character to start of the... | 9fac62c99e4c508adfa8de06887edc3fc1ae46cb | 47,692 |
def stiefel_dimension(dim_n, dim_p):
"""Return the dimension of a Stiefel manifold St(1, p)^n.
in general, dim St(d, p)^m = mdp - .5 * md(d + 1)
hence here, dim St(1, p)^n = np - n = n(p - 1)
"""
return dim_n * (dim_p - 1) | dca23894cf806fec59fabb1a2bf41a838d94e809 | 47,694 |
def _create_data_folder(path, source="NSRDB", year="2017"):
"""Create data folder
Args:
Returns:
bool: True
"""
TIMESERIES_DIR = path / "raw" / source / "timeseries" / year
META_DIR = path / "raw" / source / "meta" / year
TIMESERIES_DIR.mkdir(exist_ok=True, parents=True)
META_DIR... | 02c6e32b924968a01549e65600fcc3ba0ed3db78 | 47,695 |
def drop_id_prefixes(item):
"""Rename keys ending in 'id', to just be 'id' for nested dicts.
"""
if isinstance(item, list):
return [drop_id_prefixes(i) for i in item]
if isinstance(item, dict):
return {
'id' if k.endswith('id') else k: drop_id_prefixes(v)
for k, v... | 6fc752fa49771a0fc6e7e28e889cf29941a95a10 | 47,696 |
def minindex(A):
"""Return the index of the minimum entry in a list. If there are
multiple minima return one."""
return min((a, i) for i, a in enumerate(A))[1] | 999d9a10f0f62f01d37085efb0b14928b36cf530 | 47,697 |
import argparse
def parse_arguments():
"""
:return:
"""
parser = argparse.ArgumentParser(description='Resource-summary')
parser.add_argument('--cpu-task', action='store_true')
parser.add_argument('--gpu-task', action='store_true')
parser.add_argument('--dataset-batch', action='store_true')... | 0fee5c64c457904ea8836dd549cf7f5565c7b22e | 47,699 |
def getDescendantsTopToBottom(node, **kwargs):
"""
Return a list of all the descendants of a node,
in hierarchical order, from top to bottom.
Args:
node (PyNode): A dag node with children
**kwargs: Kwargs given to the listRelatives command
"""
return reversed(node.listRelatives(... | bc7a7fb1ca1ab362943f024c3dd50ce40cfc0ab5 | 47,701 |
import argparse
def CommandLine():
"""Setup argparser object to process the command line"""
cl = argparse.ArgumentParser(description="Cover a sidewalk with drops. 2018 by Paul H Alfille")
cl.add_argument("M",help="Number mash squares on side",type=int,nargs='?',default=100)
cl.add_argument("D",help="D... | d9e3314695478d539d0db089c331ed42164b5c19 | 47,702 |
import string
import random
def random_string_generator(size=4, chars=string.ascii_lowercase + string.digits):
"""[Generates random string]
Args:
size (int, optional): [size of string to generate]. Defaults to 4.
chars ([str], optional): [characters to use]. Defaults to string.ascii_lowercase... | 617e20acd54f218f65f98d89b976efc1bebc095a | 47,703 |
import torch
def cross_entropy(targ, pred):
"""
Take the cross-entropy between predicted and target.
Args:
targ (torch.Tensor): target
pred (torch.Tensor): prediction
Returns:
diff (torch.Tensor): cross-entropy.
"""
targ = targ.to(torch.float)
fn = torch.nn.BCELoss... | 22f06a7caf58710208131620bbc773d968e3f910 | 47,705 |
def Z_short(omega):
"""This function exists because it has a descriptive name, but it
just takes `omega` as an argument and returns 0.
"""
return 0 | fe47f2742c715acbfa7c2cc0bb362d1ce0ccc76b | 47,706 |
def merge1(a, b):
"""
:param a:
:param b:
:return:
"""
print("a : ", a)
print("b : ", b)
res = list()
a_idx = b_idx = 0
while a_idx < len(a) and b_idx < len(b):
if a[a_idx] < b[b_idx]:
res.append(a[a_idx])
a_idx += 1
else:
res.a... | 95ad2ee7da910a93f9e44d1b13527d6c6f52714a | 47,708 |
import torch
def tilted_loss(y_pred, y, q=0.5):
"""
Loss function used to obtain quantile `q`.
Parameters:
- y_pred: Predicted Value
- y: Target
- q: Quantile
"""
e = (y - y_pred)
return q * torch.clamp_min(e, 0) + (1-q) * torch.clamp_min(-e, 0) | f43ebdee74ebe10776685634859628222a9bc9ce | 47,712 |
def generate_panel_arrays(nx, ny, panel_size, indentation, offset_x, offset_y):
"""Generate a rectangular array of nx-by-ny panels of the same panel_size
nx, ny: int, how many panels do you want in X-axis and Y-axis.
panel_size: (int, int), dimension of the panels
offset_x, offset_y: int, move around... | 4613b6d038856aca927f33b1bf60e8a3f6449406 | 47,713 |
def data_to_category_counts(df):
"""
Extracts opportunity category counts for each NAICS code.
"""
return (
df.groupby(['Opportunity_NAICS', 'Opportunity__r.Category__c'])
.count()
.iloc[:,0]
.to_frame()
.rename(columns={df.columns[0]: 'Count'})
.reset_ind... | fa57218d5a6f439789cb7e013892df09c8207a07 | 47,714 |
def add_zero(nb):
"""Converts a number to a string and adds a '0' if less than 10.
:Parameters:
* **nb** (:obj:`float`): Number to be converted to a string.
:Example:
>>> pycof.add_zero(2)
... '02'
:Returns:
* :obj:`str`: Converted number qs a string.
"""
if nb... | 754d21a11a818293ddd03d287ef992af3c89f0f4 | 47,715 |
import pandas
import numpy
def price_mean(trades: pandas.DataFrame) -> numpy.float64:
"""
Get the mean price of all the trades.
Args:
trades: dataFrame of trades
"""
return trades.price.mean() | 885db38ff811e2c1f79b8720e5bf435a006c853e | 47,716 |
import re
def resolve_query_res(query):
"""
Extracts resource name from ``query`` string.
"""
# split by '(' for queries with arguments
# split by '{' for queries without arguments
# rather full query than empty resource name
return re.split('[({]', query, 1)[0].strip() or query | 9f5395c8dd416643c5d8460e0fbec2f83037e4fb | 47,717 |
def calculate_plane_point(plane, point):
"""Calculates the point on the 3D plane for a point with one value missing
:param plane: Coefficients of the plane equation (a, b, c, d)
:param point: 3D point with one value missing (e.g. [None, 1.0, 1.0])
:return: Valid point on the plane
"""
a, b, c,... | c086e5181a9d595af5a0ef493a221f2166e71423 | 47,718 |
import time
import sys
def populate(db, source):
"""Populate database table annotations with disease informations."""
cur = db.cursor()
timestart = time.time()
i = 0
j = 0
with open(source) as file:
next(file) # skip header
for line in file:
# remove \t and \n from... | c64f803fd300bf1d1ee7c4f6af8a168279033311 | 47,719 |
def revert(vocab, indices):
"""Convert word indices into words
"""
return [vocab.get(i, 'X') for i in indices] | 457831d28d26c68b19a07585f0d4de9fe31b0203 | 47,720 |
def getSnpIndicesWithinGeneWindow(snp_chrom,snp_pos,gene_chrom,gene_start,gene_stop=None,window=0):
"""
computes for a given gene, a boolean vector indicating which SNPs are close to the gene
input:
snp_chrom : chromosomal position [F]
snp_pos : position [F]
gene_chrom : gene... | 1a87e20b8744c9d28e26bd189f7bdaa056238a2b | 47,722 |
import math
def scalarToVector(magnitude, angle):
"""
Converts a speed and vector into a vector array [x, y, z]
X is horizontal magnitude, Y is vertical magnitude, and Z is magnitude in/out of screen
arg magnitude - the magnitude of the vector
arg angle - the direction in radians of the vector
Returns an ar... | 4d82caed233a3b4df07ff42536fcffa8643e94bf | 47,724 |
def getKey(dictionary: dict, input_value):
"""A bit of web help - the useful function to find a key using a value (different workflow to common one)"""
retKey = None
for key, value in dictionary.items():
if input_value == value:
retKey = key
break
return retKey | 395de560ea200c8d5fe88d85a0d366400772e20f | 47,725 |
def getPositiveCoordinateRangeOverlap(uStart1, uEnd1, uStart2, uEnd2):
"""@return: If the two coordinate ranges overlap on the same strand
returns the overlap range. If no overlap it returns None.
"""
if uEnd1 < uStart2 or uEnd2 < uStart1:
return None
l = [ uStart1, uEnd1, uStart2, uEnd2 ]
... | 4151a034bd582b0345e537562e3e72fda90f6b7a | 47,728 |
import subprocess
import platform
def subprocess_execute(cmd, cwd=None):
"""
执行命令返回结果
:param cmd: 命令
:return: 返回输出
"""
res = subprocess.Popen(
cmd,
shell=True,
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
cwd=cwd
)... | c56b10dfef619cf13b6f33c2169e692efd9481f4 | 47,730 |
def get_home():
"""Default API path"""
return "To access the API, navigate to /api/robots" | 55a122e43710bd234566df96606fe8541014c5a5 | 47,731 |
def exec_no_show(filepath, globals=None, locals=None):
"""
exec a file except for plt.show
"""
if globals is None:
globals = {}
globals.update(
{
"__file__": filepath,
"__name__": "__main__",
}
)
with open(filepath) as file:
block = fil... | 9dc02ddfe417d21bc0c8c27b8438c0a352d85882 | 47,732 |
def set_email_reply(email_from, email_to, email_cc, email_subject, html_body, attachments):
"""Set the email reply from the given details.
Args:
email_from: The email author mail.
email_to: The email recipients.
email_cc: The email cc.
html_body: The email HTML body.
Returns:... | bab25139011ceab32f5aa92e14da4f58fd6f98c3 | 47,734 |
def inventory_file_path():
"""
This method returns standard inventory file path
"""
return 'data/inventory.json' | fe2e2d606c628c100e6c347217bf1a0784e4a252 | 47,735 |
from typing import Counter
def term_freq(tokens: list[str]) -> dict:
"""
Takes in a list of tokens (str) and return a dictionary of term frequency of each token
"""
term_count = Counter(tokens)
n = len(tokens)
return {term: count/n for term, count in term_count.items()} | 0567a08e9050d030b8411f662e4afb8560e525be | 47,736 |
def find_loop(operation_list):
"""
Идем последовательно по списку операций, запоминаем:
последнюю позицию до цикла, сумму к этому моменту и
список последовательно выполненыех команд
"""
positions_set = set()
positions_list = []
sum = 0
position = 0
while True:
if position... | c5ebc1701c7ac9ba926ce8722510bc0bd9b74492 | 47,737 |
def parseChoices(optString):
"""
The option string is basically our "recipe".
Example:
"time=Q4 2014 dimensions=[time,age,industry] geo="K000000001 obs=obs_col"
"""
time = None # assumed.
geo = None # ...
obs = None # .
dimensions = []
# Look for optional "time=" ... | de3c33e15b7a411e23247521bab8af2cc767558a | 47,738 |
def get_dict_query_field(dict_field_name: str, sub_field: str):
"""Generate django query key for searching a nested json feild"""
return dict_field_name + "__" + sub_field.replace(".", "__") | 112951293b6545483883515eeb6922a4b205e47e | 47,739 |
def test_arr():
"""Array indexing."""
return """
var arr: [u8] = {1, 2, 3, 4};
fn main() {
{dest} = arr[3];
}
""" | 9712634b9e23061aaca9518cf073c518f04fbcbb | 47,740 |
from typing import Any
from typing import Callable
def lazy(func: Any) -> Callable:
"""A lazy function is one that expects its arguments to be unparsed"""
func.lazy = True
return func | 98b219bf0099089d27cd579b11e9ebfeabef3817 | 47,741 |
def stag_temperature_ratio(M, gamma):
"""Stagnation temperature / static temperature ratio.
Arguments:
M (scalar): Mach number [units: dimensionless].
gamma (scalar): Heat capacity ratio [units: dimensionless].
Returns:
scalar: the stagnation temperature ratio :math:`T_0 / T` [unit... | 0677524c97a245d93f9eac33c6be885819ed14e5 | 47,742 |
def get_max_depth(es, *, index):
"""Find max depth of root lineage."""
body = {
"id": "max_nested_value",
"params": {"path": "lineage", "field": "node_depth"},
}
res = es.search_template(index=index, body=body)
max_depth = res["aggregations"]["depths"]["max_depth"]["value"]
retur... | 33eb318bcf20fb656b84edb349ff840ebefe07b0 | 47,743 |
def compute_gender(last_gender: str,
top_gender_male: int,
top_gender_female: int,
top_gender_7_days: str):
"""Computes the gender type of a visitor using a majority voting rule."""
def majority_voting(lst):
return max(set(lst), key=lst.count)
... | 387f04fae4b593de54894eeac017b7fe124706c9 | 47,744 |
import re
def address_group(address, group_name=None):
"""
Return part of address upto group_name
:param address: str hdf address
:param group_name: str name of group
:return: reduced str
"""
if group_name is None:
names = address.replace('\\', '/').split('/')
return '/'.jo... | eaebf034e5716f1653ffe112d73109f5a8850e65 | 47,745 |
def combine_dicts(d_tracker, d_return):
"""combines dictionaries"""
# grab new unique keys (sites) in d_return
ls_new_sites = [x for x in d_tracker.keys() if x not in d_return.keys()]
# if new sites are found
if ls_new_sites:
# iteratively add sites to d_tracker
for new_site in ... | 76c2994223d6334168a77837ce2632d1829c9251 | 47,746 |
def provide_user_with_service_type(each_func_name):
# Input for Service Type
"""IaaS, FaaS, {IaaS, FaaS}(default)"""
mixture_pragma = "IaaS, FaaS, {IaaS, FaaS}(default)"
func_service = input(
f"{each_func_name} configuration : " f"service type - {mixture_pragma}:\n "
)
func_service = ... | 674269fbbb8ff539a4c3233bf285027307ae2bbc | 47,749 |
import hashlib
def get_signature(sign_param):
"""
jsapi_ticket签名
签名生成规则如下:参与签名的字段包括noncestr(随机字符串), 有效的jsapi_ticket, timestamp(时间戳), url(当前网页的URL,不包含#及其后面部分) 。对所有待签名参数按照字段名的ASCII 码从小到大排序(字典序)后,使用URL键值对的格式(即key1=value1&key2=value2…)拼接成字符串string1。这里需要注意的是所有参数名均为小写字符。对string1作sha1加密,字段名和字段值都采用原始值,不进行URL 转义。... | 4f37a13d855c4cd72bf5d14603518513e009450c | 47,751 |
import sys
def _osx_mode(n):
"""
fstat(2) on UNIX sockets on OSX return different mode bits depending on
which side is being inspected, so zero those bits for comparison.
"""
if sys.platform == 'darwin':
n &= ~int('0777', 8)
return n | ba545be74cee563fe5f9c50332832dedf73a0dad | 47,752 |
import requests
import shutil
def download_file(download_URL, filename):
"""Download file from CURL url using request.
download_URL: """
with requests.get(download_URL, stream=True) as r:
with open(filename, 'wb') as f:
shutil.copyfileobj(r.raw, f)
return filename | 23f542674a776a640aeb5c1d7952c14b5cb09c33 | 47,753 |
from datetime import datetime
def parse_timestamp(timestamp: str):
"""
Parse a timestamp returned by discord
This is not a reliable method at all, and if you need an accurate and safe way to read properties that use this
function, it is advised that you checkout the dateutil or arrow libraries for th... | 49c7300df8d18821cc98ff2770a93e7d119c54af | 47,754 |
def is_pos_int(num_str):
"""
Args:
num_str (str): The string that is checked to see if it represents a positive integer (not 0)
Returns:
bool
Examples:
>>> is_pos_int("25.6")
False
>>> is_pos_int("-25.6")
False
>>> is_pos_int("0")
False
... | e5c827026a68955c22d5105de2fe601ba609d0e1 | 47,756 |
from typing import Iterable
def _not_none_count(sequence: Iterable) -> int:
"""
A helper function for counting the number of non-`None` entries in a sequence.
:param sequence: the sequence to look through.
:return: the number of values in the sequence that are not `None`.
"""
return sum(1 for... | 82fe58ef458245655feba4c0d82c1160dbfba525 | 47,757 |
import numpy
import pandas
def dx_accuracy(cm):
"""dx_accuracy return model performance metrics in a Pandas dataframe
cm: sklearn confusion matrix object
"""
# turn this in to a function that takes the confusion matrix based
FP = numpy.sum(cm, axis=0) - numpy.diag(cm)
FN = numpy.sum(cm... | f49d7cf3ce6b6bdf111b19738e5ab312365eea48 | 47,758 |
def get_task_parameter(task_parameters, name):
"""Get task parameter.
Args:
task_parameters (list): task parameters.
name (str): parameter name.
Returns:
Task parameter
"""
for param in task_parameters:
param_name = param.get('name')
if param_name == name:
... | 12fe7e38dd74c92b8042efd8f6e77404b7ef9c66 | 47,759 |
import math
def simple_project(latitiude: float) -> float:
"""
Projects a point to its corrected latitude for the rhumbline calculations.
:param latitiude: A float in radians.
:return: The projected value in radians.
"""
return math.tan(math.pi / 4 + latitiude / 2) | 9e1c530b11b6c1203a486f078a756f27b19a5603 | 47,760 |
def str2byte(content):
""" compile str to byte """
return content.encode("utf-8") | 77197318672b9424f8071d2f730efeb7075c4fa8 | 47,761 |
def sort_group_connected(group):
"""Sort by number of connected contacts"""
return - group.get_nb_connected_contacts() | 2c3dd44db42ba72b7a7843417ce2365e99827f01 | 47,762 |
import torch
def reps_dot(sent1_reps: torch.Tensor, sent2_reps: torch.Tensor) -> torch.Tensor:
"""
calculate representation dot production
:param sent1_reps: (N, sent1_len, reps_dim)
:param sent2_reps: (N, sent2_len, reps_dim)
:return: (N, sent1_len, sent2_len)
"""
return torch.bmm(sent1_r... | ce8790433820f573b7c8c5ccd1f388abd917f513 | 47,765 |
def create_encode_state_fn(vae, measurements_to_include):
"""
Returns a function that encodes the current state of
the environment into some feature vector.
"""
# Turn into bool array for performance
measure_flags = ["steer" in measurements_to_include,
"throttle" in... | cfd9894a29e2b8ac6d2399dd59f17546d9626cea | 47,767 |
def headers_to_table(markdown_headers, notebook_name):
"""Produces a markdown table of contents from markdown headers.
This function uses a two pass solution to turn markdown headers into a
table of contents. The first pass strips one # from every header and the
second pass turns all remaining # into s... | 3e1e05ad310056baf7167a6d4eb0f1eb4b4ea5d0 | 47,768 |
import time
def expires_header(duration):
"""Takes a number of seconds and turns it into an expires header"""
return time.strftime("%a, %d-%b-%Y %T GMT",
time.gmtime(time.time() + duration)) | d81a89ed617f2d0544ff2b9ad9c7e5f9e27394f1 | 47,769 |
def replace_by(value, VR, action,
default_name="John Doe",
default_date="18000101",
default_datetime="180001010000.000000",
default_time="0000.000000",
default_text="anon",
default_code="ANON",
default_age="000M",
... | 95139886417123c5678eaad1855edbff06087585 | 47,770 |
import requests
from bs4 import BeautifulSoup
def get_content(url):
"""
函数说明:获取章节内容
Parameters:
url - 下载连接(string)
Returns:
texts - 章节内容(string)
"""
req = requests.get(url=url)
req.encoding = 'GBK' #转化为GBK编码
bf = BeautifulSoup(req.text,features='html.parser')
tex... | 4214bdd9e951caf27cf801137241a8dbaf222618 | 47,772 |
def _field_update(op, path, value):
"""Return a dictionary for a field operation
:param op: *add*, *replace* or *test*
:param path: Path of field
:param value: Field value
:return: dict
"""
return {
"op": op,
"path": "/fields/{}".format(path) if "/fields/" not in path else p... | 8f1b4841828f04119ca21e86b5d0eb43273ce01e | 47,773 |
import re
def verificador_dui_el_salvador(dui):
"""
función que verifica si una cdena ingresada corresponde a un número válido
de un documento único de identidad de El Salvador incluyendo una expresión
regular para verificar el formato y la operación del número verificador
que es el último dígito.... | 6bacc9a31cdc5b289341ff82171c661e08154ff9 | 47,775 |
from typing import Dict
from typing import Any
def to_sanitized_dict(args) -> Dict[str, Any]:
"""Sanitized serialization hparams"""
if type(args) in [dict]:
d = args
else:
d = vars(args)
valid_types = [bool, int, float, str, dict]
items = {}
for k, v in d.items():
if ty... | c4cec6f6761ff12f84b3f1d2be97ac7e96f329f8 | 47,776 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.