content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def find_asg_using_amis(ami_ids):
"""
take a list of ami ids and return a dictionary of
launch configs that use them
"""
# ref: return = { ami_id : "lc_arns":[]}
ami_ids = listify(ami_ids)
result = {id: [] for id in ami_ids}
client_asg = boto3.client('autoscaling')
lc = client_asg.d... | 951d20144be55a699911a690ee35405d3e4fa08b | 7,900 |
def tokenize_nmt(text, num_examples=None):
"""Tokenize the English-French dataset."""
source, target = [], []
for i, line in enumerate(text.split('\n')):
if num_examples and i > num_examples:
break
parts = line.split('\t')
if len(parts) == 2:
source.append(par... | f77def3cdd2eee6a9ecc3bb7fa007eccfcd9e8a8 | 7,901 |
def setup_snicar(input_file):
"""Builds impurity array and instances of all classes according to config in yaml file.
Args:
None
Returns:
ice: instance of Ice class
illumination: instance of Illumination class
rt_config: instance of RTConfig class
model_config: inst... | 14fc40bb6c555cf94f8f8c7ddf2133e208b5ee02 | 7,902 |
async def list_model_config(model_name: str):
"""
Lists all the model's configuration.
:param model_name: Model name
:return: List of model's configuration
"""
try:
return ApiResponse(data=dl_service.get_config(model_name))
except ApplicationError as e:
raise e
except Exception:
raise ApplicationError('un... | 8ce01caee8fe7dacc381ea4ed23a5d885ab0da01 | 7,903 |
def signup_post(request):
"""Получаем данные пользователя с формы и заносим их в базу проверяя,
если удачно то предоставляем вход в базу потом дополнительные идентификац"""
mess = "login please"
data = get_post( request )
mail = data.POST['mail']
name = data.POST['name']
captcha = data.POST['captcha']
hash = da... | 22e4a8508849f9c4879c65e3347a0fabf6bffeb8 | 7,904 |
def make_onehot(label, num_classes, axis=-1):
"""
Create one hot tensor based on the input tensor
Args:
label: input tensor, the value must be positive integer and less than num_class
num_classes: the number of class in one hot tensor
axis: The axis to fill (default: -1, a new inner-... | 3329f5f135b1fea383b389012aeeb37ea923cb46 | 7,905 |
def kohn_sham_iteration(
state,
num_electrons,
xc_energy_density_fn,
interaction_fn,
enforce_reflection_symmetry):
"""One iteration of Kohn-Sham calculation.
Note xc_energy_density_fn must be wrapped by jax.tree_util.Partial so this
function can take a callable. When the arguments of this cal... | f016e1d8c6ab9072065183d3fa1d37cfa12eb8ee | 7,906 |
def calculate_reliability(data):
""" Calculates the reliability rating of the smartcab during testing. """
success_ratio = data['success'].sum() * 1.0 / len(data)
if success_ratio == 1: # Always meets deadline
return ("A+", "green")
else:
if success_ratio >= 0.90:
return ("A", "green")
elif success_ratio... | d1c9ad7bba220beeae06c568cfd269aaaebfb994 | 7,907 |
def cache_mat_calc(dra, ddc, dra_err, ddc_err, ra_rad, dc_rad, ra_dc_cor=None,
l_max=1, fit_type="full", num_iter=None):
"""Calculate cache matrix for future use
Parameters
----------
dra/ddc : array of float
R.A.(*cos(Dec.))/Dec. differences
dra_err/ddc_err : array of fl... | 805ecc94165ae1162341abdc7c4dd3557af5f8c4 | 7,908 |
def get_android_replacements():
"""Gets a dictionary of all android-specific replacements to be made."""
replacements = {}
compileSdk = 'compileSdkVersion {}'.format(COMPILE_SDK_VERSION)
targetSdk = 'targetSdkVersion {}'.format(TARGET_SDK_VERSION)
buildToolsVersion = 'buildToolsVersion \'{}\''.form... | e3b78d7ccd897d79db66740d46aa05410dd2a83f | 7,909 |
from typing import List
from typing import Set
from typing import Dict
def process_long_term_idle_users(
slack_data_dir: str,
users: List[ZerverFieldsT],
slack_user_id_to_zulip_user_id: SlackToZulipUserIDT,
added_channels: AddedChannelsT,
added_mpims: AddedMPIMsT,
dm_members: DMMembersT,
z... | 4a372837ed5497117227e18534c91c6f0ce840bf | 7,910 |
def clear_cache():
"""
Clears internal cache. Returns
something that can be given back to restore_cache.
"""
global FS_CACHE
old = FS_CACHE
FS_CACHE = {}
return old | 492513177a70cd663671616e034c6f3b287ceb75 | 7,911 |
import tqdm
def extend_gdf(gdf_disjoint, id_col):
"""
Add duplicates of intersecting geometries to be able to add the constants.
This function adds rows with duplicate geometries and creates the new `id`
column for each of the new rows. This function is called by another function
`complete_disjoi... | 5d6667b67c47125f8668bb6127b4a295fb2d61c9 | 7,912 |
def schedule_news_updates(update_interval:int, update_name:str)->dict:
"""
Functionality:
---------------
Schedules a new news data update
Parameters:
---------------
update_interval: int
The time until the scheduler should update the news dat... | 1e2bf07aae3e2468f1ee0ff119b492820d866460 | 7,913 |
def get_digits(text):
"""
Returns all numeric characters (digits) in string *text* in a new (concatenated) **string**.
Example:
>>> get_digits('Test123')
'123'
>>> int(get_digits('The answer is 42'))
42
:param text: The string to search.
:type text: str, uni... | 78bcd49b74dbdfd7d9f40af3806c2b984adca780 | 7,914 |
def embed_tiles_in_json_sprite(tile_list, as_bytes=True, out_file=None):
"""Make a big rectangle containing the images for a brainsprite.
Parameters:
-----------
tile_list : list
List of 2d square numpy arrays to stick in a mosaic
Returns:
--------
mosaic : np.ndarray
... | 2eca9eb999d69537fac60dfefd0d482576994868 | 7,915 |
import re
def removeUnicode(text):
""" Removes unicode strings like "\u002c" and "x96" """
text = re.sub(r'(\\u[0-9A-Fa-f]+)',r'', text)
text = re.sub(r'[^\x00-\x7f]',r'',text)
return text | f5c8090329ede82ce51601efa463537bba68b63a | 7,916 |
import scipy
def mfcc(tf, n_mfcc, fs, fmin=0.0, fmax=None):
"""
Extract MFCC vectors
Args:
tf : single-channel time-frequency domain signal,
indexed by 'tf'
n_mfcc : number of coefficients
fs : sample rate
fmin : (default 0) minimal frequency in Hz
... | 58769db11aa0633dd846b9d427e6d35a0fff435e | 7,917 |
import logging
def transform(fname, metadata=False):
"""
This function reads a Mission Analysis Orbit file and performs a matrix
transformation on it. Currently only from the Mercury Equatorial frame to
the Earth Equatorial frame.
:param fname: The path to the orbit file.
:type fname: str.
... | ce389f74ba35d3c92a94031563b187a7285ccb5b | 7,918 |
import requests
import json
def query_repository(repo_name, index_uuid, token, display_results=False):
"""
Display the ids ('subjects') of all items indexed in a repository.
:param repo_name: Textual name of repository to query, corresponds to 'name' field in conf file.
:param index_name: Name of ind... | 8a6b4f90374b90504a375c5d44a6dce6f32fb936 | 7,919 |
def power(x1, x2, out=None, where=True, dtype=None):
"""
First array elements raised to powers from second array, element-wise.
Raises each base in `x1` to the positionally-corresponding power in `x2`.
Note:
Numpy arguments `casting`, `order`, `dtype`, `subok`, `signature`, and `extobj` are
... | ecc265e96c36c47177aa96797d355a55f35114d6 | 7,920 |
def _str2bool(s):
"""文字列からboolへの変換"""
return s.lower() in ["true", "t", "yes", "1"] | 877340b7926541a5b8f56cb7f1acd5a54e08a987 | 7,921 |
import random
def _generate_nonce(length=42):
"""
Generate an alpha numeric string that is unique for each request.
Twitter used a 42 character alpha-numeric (case-sensitive) string in the
API documentation. However, they note "any approach which produces a
relatively random alphanumeric string s... | 034c4fee363d47e9af98c0135159f53179d27fdd | 7,922 |
from datetime import datetime
def is_expired(image_id: str) -> bool:
"""
Check whether entry is expired (based on timestamp encoded in the image_id)
"""
ts = expiration(image_id)
now = datetime.now(timezone.utc)
if ts is None:
log.debug("Invalid cache entry ID: %s", image_id)
... | b5f2f08bc42a83ed7b567ab437d54c626dee8a50 | 7,923 |
def int_(value):
"""Validate that the config option is an integer.
Automatically also converts strings to ints.
"""
check_not_templatable(value)
if isinstance(value, int):
return value
if isinstance(value, float):
if int(value) == value:
return int(value)
rai... | f5d5f729a1bbec418f3b270b4e28be2cf9cc7cd6 | 7,924 |
def explode(screen):
"""Convert a string representing a screen
display into a list of lists."""
return [list(row) for row in screen.split('\n')] | a43a9d8c830c4a784bb9c3505c62aaf2077bb732 | 7,925 |
import csv
import glob
import os
def merge_csv_files(directory, out):
"""\
Merges the CSV files in the provided `directory` into one CSV file.
:param str directory: Path where to find the CSV files
:param str out: Resulting file name.
"""
f = open(out, 'w', encoding='utf-8')
writer = csv.... | 4d5066b27b9977161b92061a39a6207040982b41 | 7,926 |
def basic_info(user, keys):
"""Prints a table of basic user information"""
table = formatting.KeyValueTable(['Title', 'Basic Information'])
table.align['Title'] = 'r'
table.align['Basic Information'] = 'l'
table.add_row(['Id', user.get('id', '-')])
table.add_row(['Username', user.get('username... | 805b8e12f531b1c6b31aeca847568cbc1b2e929c | 7,927 |
def iobes_iob(tags):
"""
IOBES -> IOB
"""
new_tags = []
for i, tag in enumerate(tags):
if tag == 'rel':
new_tags.append(tag)
elif tag.split('-')[0] == 'B':
new_tags.append(tag)
elif tag.split('-')[0] == 'I':
new_tags.append(tag)
eli... | 1a2f715edfc37b387944f84c4f149f21a0e86e74 | 7,928 |
def draw_handler(canvas):
"""
Event handler that is responsible for all drawing. It
receives "canvas" object and draws the "Pong" table,
the "moving" ball and the scores of each "Player".
It is also responsible for testing whether the ball
touches/collides with the "gutters" or the "paddles".
... | ad9d5be8bbc1eb1b1612c6bfd35cc774bcacbd7a | 7,929 |
def tf_idf(df, vocab):
"""[summary]
https://towardsdatascience.com/natural-language-processing-feature-engineering-using-tf-idf-e8b9d00e7e76
Args:
docs ([type]): [description]
"""
docs = []
for text in df['text'].tolist():
docs += [text]
vectorizer = TfidfVectorizer(tokeniz... | ef75e51f1d4b69dcf6a5ab908f56eff8a25852f7 | 7,930 |
import os
def setup_checkpoint_dir(cfg, args, phase):
"""Create checkpoint directory
# ROUND2-TODO: let's make this checkpoint director way more involved. Specific to user, to model, to config name, etc.
"""
root_dir = os.path.join(
cfg["checkpoints_dir"], cfg["model"]["name"], args.config_n... | b2a753807106a9b2efee5f8a811852c5e6b764aa | 7,931 |
def get_activation_func(activation):
"""Turns a string activation function name into a function.
"""
if isinstance(activation, string_types):
# Get the activation function.
activation = activation.lower()
if activation == "tanh":
activation_func = tanh
elif activa... | 6cb6fccdacf44c3fc3fac242d69a2494459c1318 | 7,932 |
import os
def number_of_cores():
"""
number_of_cores()
Detect the number of cores in this system.
"""
# Linux, Unix and MacOS:
if hasattr(os, "sysconf"):
if "SC_NPROCESSORS_ONLN" in os.sysconf_names:
# Linux & Unix:
ncpus = os.sysconf("SC_NPROCESSORS_ONLN")
... | ecf479f382015cffdad518a25c4334f5c44dc6fe | 7,933 |
def create_schema(hostname='localhost', username=None, password=None,
dbname=None, port=None, schema_name=None):
"""Create test schema."""
cn = create_cn(hostname, password, username, dbname, port)
with cn.cursor() as cr:
cr.execute('DROP SCHEMA IF EXISTS %s CASCADE' % dbname)
... | ef1b8b77ca1cd88804f0afec9efc24caad3a601d | 7,934 |
def set_color_in_session(intent, session):
""" Sets the color in the session and prepares the speech to reply to the
user.
"""
card_title = intent['name']
session_attributes = {}
should_end_session = False
if 'Color' in intent['slots']:
favorite_color = intent['slots']['Color']['va... | 4783aa36b18fb723441d99a8ffcdfe4b587d2a45 | 7,935 |
def fpath_to_pgn(fpath):
"""Slices the pgn string from file path.
"""
return fpath.split('/')[-1].split('.jpeg')[0] | 1cc6cad60c5356b6c731947a59998117bf15035a | 7,936 |
def convert_to_constant(num):
"""
Convert one float argument to Constant, returning the converted object.
:param float num:
Float number to be converted to Constant
:return:
Float number converted to a Constant object
:rtype: object
"""
return Constant(name=str(num), units... | 111ae55c1446228b23638465c75bd9fa6d3d7043 | 7,937 |
def data_zip(data):
"""
输入数据,返回一个拼接了子项的列表,如([1,2,3], [4,5,6]) -> [[1,4], [2,5], [3,6]]
{"a":[1,2],"b":[3,4]} -> [{"a":1,"b":3}, {"a":2,"b":4}]
:param data: 数组 data
元组 (x, y,...)
字典 {"a":data1, "b":data2,...}
:return: 列表或数组
"""
if isinstance(data, tuple):
... | 31dcaa3905a7d062cfe994543df31f293fdc962a | 7,938 |
def _days_in_leap_and_common_years(i_date, f_date):
"""Return the a tuple with number of days in common and leap years (respectively) between initial and final dates.
"""
iy = i_date.year
fy = f_date.year
days_in_leap = 0
days_in_common = 0
if iy == fy:
# same year
... | f96b6c26fd8e87a543ffa6b6e7ed66144248d752 | 7,939 |
def make_space_kernel(data, background_kernel, trigger_kernel, time,
time_cutoff=None, space_cutoff=None):
"""Produce a kernel object which evaluates the background kernel, and
the trigger kernel based on the space locations in the data, always using
the fixed time as passed in.
:param data: An... | 5c84dfb89340e52e57fb0b28464b18b0487601ea | 7,940 |
import torch
def get_dim_act_curv(args):
"""
Helper function to get dimension and activation at every layer.
:param args:
:return:
"""
if not args.act:
act = lambda x: x
else:
act = getattr(F, args.act)
acts = [act] * (args.num_layers - 1)
dims = [args.feat_dim]
... | 072a54a3a2060598cbbe0fc89efe0be4b7cdc63f | 7,941 |
def debug():
"""
Function to return exported resources with types as dict.
"""
return exported_res_dict | ab32c01534159853445a6f1959654623db93c82f | 7,942 |
def write_charset_executable(mysql_charset_script_name, here):
"""Write to disk as an executable the file that will be used to issue the MySQL
statements that change the character set to UTF-8 -- return the absolute path.
"""
mysql_charset_script = os.path.join(here, mysql_charset_script_name)
if no... | b92ea0e48ccebd267856ababcb714e736fea812c | 7,943 |
import time
def readTemperature(file):
"""
Returns the temperature of the one wire sensor.
Pass in the file containing the one wire data (ds18b20+)
"""
lines = read_temp_raw(file)
while lines[0].strip()[-3:] != "YES":
time.sleep(0.2)
lines = read_temp_raw(file)
equals_pos =... | 3398f287ae98df4b72ff212cdcad1764a9bbe31b | 7,944 |
def layernorm_backward(dout, cache):
"""
Backward pass for layer normalization.
For this implementation, you can heavily rely on the work you've done already
for batch normalization.
Inputs:
- dout: Upstream derivatives, of shape (N, D)
- cache: Variable of intermediates from layernorm_for... | 10603f4c4b78652ae466f83e511477956eae89fb | 7,945 |
def energyAct(
grid, deltaE, xA, yA, zA, xB, yB, zB, temp, eList, i, dimensions):
"""Perform swap or not, based on deltaE value"""
kB = 8.617332e-5 # boltzmann constant, w/ ~eV units
kTemp = kB * temp
if deltaE <= 0: # Swap lowers energy, therefore is favourable,
# so perform swap in grid
grid = performSwap(... | 2380991200c2b3c196b1fea4c4108e82f20a979b | 7,946 |
def lambda_handler(event, context):
"""
Lambda function that transforms input data and stores inital DB entry
Parameters
----------
event: dict, required
context: object, required Lambda Context runtime methods and attributes
Context doc: https://docs.aws.amazon.com/lambda/latest/dg/python-... | 83bba41d28a7b37da6579dfc2641380839f9d785 | 7,947 |
def getModCase(s, mod):
"""Checks the state of the shift and caps lock keys, and switches the case of the s string if needed."""
if bool(mod & KMOD_RSHIFT or mod & KMOD_LSHIFT) ^ bool(mod & KMOD_CAPS):
return s.swapcase()
else:
return s | 4faa2963e96786c5495443382585188b3a6ff119 | 7,948 |
import os
def plot_D_dt_histogram(all_samples, lens_i=0, true_D_dt=None, save_dir='.'):
"""Plot the histogram of D_dt samples, overlaid with a Gaussian fit and truth D_dt
all_samples : np.array
D_dt MCMC samples
"""
bin_heights, bin_borders, _ = plt.hist(all_samples, bins=200, alpha=0.5, den... | f5d8a05c3beea5e9c0b21dcde05a43ce023f728f | 7,949 |
from pathlib import Path
def try_provider(package, provider, domain):
"""Try using a provider."""
downloaded_file = None
data = None
apk_name = f'{package}.apk'
temp_file = Path(gettempdir()) / apk_name
link = find_apk_link(provider, domain)
if link:
downloaded_file = download_file... | e43a6b18a5783722c148a537f21e501a1f4e5928 | 7,950 |
def _get_list(sline):
"""Takes a list of strings and converts them to floats."""
try:
sline2 = convert_to_float(sline)
except ValueError:
print("sline = %s" % sline)
raise SyntaxError('cannot parse %s' % sline)
return sline2 | 2b315b12508638fe603378fdd3127bd814f4313d | 7,951 |
def add_number(partitions, number):
"""
Adds to the partition provided `number` in all its combinations
"""
# Add to each list in partitions add 1
prods = partitions.values()
nKeys = [(1,) + x for x in partitions.keys()]
# apply sum_ones on each partition, and add results to partitions
... | cade1ddbd4002b76fc2652c59fe4f0a9bcdcc9b9 | 7,952 |
import colorsys
def _color_to_rgb(color, input):
"""Add some more flexibility to color choices."""
if input == "hls":
color = colorsys.hls_to_rgb(*color)
elif input == "husl":
color = husl.husl_to_rgb(*color)
color = tuple(np.clip(color, 0, 1))
elif input == "xkcd":
col... | 7b3a502eba4a48dbd9b1e44d278aee58eb1ea22c | 7,953 |
def in_days(range_in_days):
"""
Generate time range strings between start and end date where each range is range_in_days days long
:param range_in_days: number of days
:return: list of strings with time ranges in the required format
"""
delta = observation_period_end - observation_period_star... | f9e77eac3fd151923cb14d05d291a0e362bd11b5 | 7,954 |
from pathlib import Path
from typing import List
import re
def tags_in_file(path: Path) -> List[str]:
"""Return all tags in a file."""
matches = re.findall(r'@([a-zA-Z1-9\-]+)', path.read_text())
return matches | 1071c22ac79f51697b2ed18896aa1d17568ecb2c | 7,955 |
import torch
def pad_to_longest_in_one_batch(batch):
"""According to the longest item to pad dataset in one batch.
Notes:
usage of pad_sequence:
seq_list = [(L_1, dims), (L_2, dims), ...]
item.size() must be (L, dims)
return (longest_len, len(seq_list), dims)
... | 3892b6002ae0f0cb0b6ce4c29128120a8f63237a | 7,956 |
def create_instance(c_instance):
""" Creates and returns the Twister script """
return Twister(c_instance) | acceb844eae8a3c9a8c734e55c4c618f990f1ae0 | 7,957 |
from typing import Type
from typing import Callable
def command_handler(command_type: Type[CommandAPI],
*,
name: str = None) -> Callable[[CommandHandlerFn], Type[CommandHandler]]:
"""
Decorator that can be used to construct a CommandHandler from a simple
function.
... | 1c6634691e366b61043b2c745d43cc2371090200 | 7,958 |
def check_ip_in_lists(ip, db_connection, penalties):
"""
Does an optimized ip lookup with the db_connection. Applies only the maximum penalty.
Args:
ip (str): ip string
db_connection (DBconnector obj)
penalties (dict): Contains tor_penalty, vpn_penalty, blacklist_penalty keys with i... | 2d6e3615d4b0d9b0fb05e7a0d03708856ffcbfef | 7,959 |
import numpy
def scan(fn,
sequences=None,
outputs_info=None,
non_sequences=None,
n_steps=None,
truncate_gradient=-1,
go_backwards=False,
mode=None,
name=None,
options=None,
profile=False):
"""
This function constructs an... | 7ac0b7d106bc2e1642827a2e9f79552eb418a918 | 7,960 |
def stock_analyst(stock_list):
"""This function accepts a list of data P and outputs the best day to
buy(B) and sell(S) stock.
Args:
stock_list: expects a list of stocks as a parameter
Returns:
a string promting to buy stock if one has not bought stock i.e the
value of stock is... | bbb3cd664ba0ea366e8ad6fa369ae3259cf52a02 | 7,961 |
def is_sync_available(admin_id):
"""Method to check the synchronization's availability about networks connection.
Args:
admin_id (str): Admin privileges flag.
"""
return r_synchronizer.is_sync_available() | 712becdc6c9903d41e3d29602bb7dc07987c6867 | 7,962 |
import collections
def on_second_thought(divider):
"""sort the characters according to number of times they appears in given text,
returns the remaining word as a string
"""
unsorted_list = list(unsorted_string)
# characters occurence determines the order
occurence = collections.Counter(un... | 1295a67cf1ebce0f79e49566306eba6add1f2e35 | 7,963 |
def aiohttp_unused_port(loop, aiohttp_unused_port, socket_enabled):
"""Return aiohttp_unused_port and allow opening sockets."""
return aiohttp_unused_port | 9c5d0c1125a7758be2e07a8f8aca6676429a841a | 7,964 |
import os
def os_specific_command_line(command_line):
"""
Gets the operating system specific command string.
:param command_line: command line to execute.
:type command_line: str
"""
current_os = os.environ["TEMPLATE_OS"]
command = "/bin/bash -c '{}'" if current_os.lower() == "linux" els... | 898b97a57841af3c671bf530c6a31460bd1882a7 | 7,965 |
def font_variant(name, tokens):
"""Expand the ``font-variant`` shorthand property.
https://www.w3.org/TR/css-fonts-3/#font-variant-prop
"""
return expand_font_variant(tokens) | 8bac3f0610c7951686504fd843c845d124f34ed6 | 7,966 |
def with_part_names(*part_names):
"""Add part names for garage.parts.assemble.
Call this when you want to assemble these parts but do not want
them to be passed to main.
"""
return lambda main: ensure_app(main).with_part_names(*part_names) | c62d495c2259139b1a9079697bcf784d12e6f9c2 | 7,967 |
def library_view(request):
"""View for image library."""
if request.user.is_authenticated:
the_user = request.user
albums = Album.objects.filter(user=the_user)
context = {'the_user': the_user,
'albums': albums}
return render(request, 'imager_profile/library.html',... | 948d239decfacabf5b3bba05e10739c7856db609 | 7,968 |
def combine_html_json_pbp(json_df, html_df, game_id, date):
"""
Join both data sources. First try merging on event id (which is the DataFrame index) if both DataFrames have the
same number of rows. If they don't have the same number of rows, merge on: Period', Event, Seconds_Elapsed, p1_ID.
:param json... | 4f2aa3948fea4f64ac996f4052101daa556d1038 | 7,969 |
import json
def read_json_file(path):
"""
Given a line-by-line JSON file, this function converts it to
a Python dict and returns all such lines as a list.
:param path: the path to the JSON file
:returns items: a list of dictionaries read from a JSON file
"""
items = list()
with open(... | 15f898faca0dff0ca4b6c73ff31e037d822cf273 | 7,970 |
def get_boss_wage2(employee):
""" Monadic version. """
return bind3(bind3(unit3(employee), Employee.get_boss), Employee.get_wage) | 60524cc219a1c4438d310382aff519ee8ef5a66b | 7,971 |
def keypoint_angle(kp1, kp2):
"""求两个keypoint的夹角 """
k = [
(kp1.angle - 180) if kp1.angle >= 180 else kp1.angle,
(kp2.angle - 180) if kp2.angle >= 180 else kp2.angle
]
if k[0] == k[1]:
return 0
else:
return abs(k[0] - k[1]) | 3feee667bcf767656da6334727b8d502be41d909 | 7,972 |
def get_args_static_distribute_cells():
"""
Distribute ranges of cells across workers.
:return: list of lists
"""
pop_names_list = []
gid_lists = []
for pop_name in context.pop_names:
count = 0
gids = context.spike_trains[pop_name].keys()
while count < len(gids):
... | 42862d47533a8662b26c9875e5f62ceebb91ccec | 7,973 |
import torch
def le(input, other, *args, **kwargs):
"""
In ``treetensor``, you can get less-than-or-equal situation of the two tree tensors with :func:`le`.
Examples::
>>> import torch
>>> import treetensor.torch as ttorch
>>> ttorch.le(
... torch.tensor([[1, 2], [3, ... | fa96a544f7f449daf008c6cf9b68f3760de67487 | 7,974 |
import numpy
def linear_to_srgb(data):
"""Convert linear color data to sRGB.
Acessed from https://entropymine.com/imageworsener/srgbformula
Parameters
----------
data: :class:`numpy.ndarray`, required
Array of any shape containing linear data to be converted to sRGB.
Returns
---... | 01eae0f9a34204498aad86e3a0a38337c7ced919 | 7,975 |
def circuit_to_dagdependency(circuit):
"""Build a ``DAGDependency`` object from a ``QuantumCircuit``.
Args:
circuit (QuantumCircuit): the input circuits.
Return:
DAGDependency: the DAG representing the input circuit as a dag dependency.
"""
dagdependency = DAGDependency()
dagde... | 7356da47f3af1088226af765f83cd43413de0a1f | 7,976 |
def tweets_factory(fixtures_factory):
"""Factory for tweets from YAML file"""
def _tweets_factory(yaml_file):
all_fixtures = fixtures_factory(yaml_file)
return [t for t in all_fixtures if isinstance(t, TweetBase)]
return _tweets_factory | 19d6e7ffe57ec071d324d535458c2263496c109d | 7,977 |
def monte_carlo(ds,duration,n,pval,timevar):
"""
pval: two-tailed pval
"""
x=0
mc = np.empty([ds.shape[1],ds.shape[2],n])
while x<n:
dummy = np.random.randint(0, len(ds[timevar])-duration, size=1) # have to adjust size so total number of points is always the same
mc[:,:,x] = ds[i... | 040aaf1a6a6813095079262446a2226fec8948ee | 7,978 |
def num_crl(wf_n):
"""Function computes the autocorrelation function from given vectors\
and the Discrete Fourier transform
Args:
wf_n(numpy array, complex): Wave function over time
Returns:
numpy array, complex: The wave function complex over time.
numpy array, complex: The au... | fc84cd7184fb04f2725b50439d9b5cfe223e2020 | 7,979 |
def resample_time_series(series, period="MS"):
"""
Resample and interpolate a time series dataframe so we have one row
per time period (useful for FFT)
Parameters
----------
df: DataFrame
Dataframe with date as index
col_name: string,
Identifying the column we will pull out
... | 2e3d2b1cbe4a8a0cc13c33c19fe217364819e31d | 7,980 |
def _timeliness_todo(columns, value, df, dateFormat=None, timeFormat=None):
"""
Returns what (columns, as in spark columns) to compute to get the results requested by
the parameters.
:param columns:
:type columns: list
:param value
:type value: str
:param df:
:type df: DataFrame
... | ed3cc27179faff77323deb6c26822dc93cdc4fd4 | 7,981 |
from typing import Optional
def build_arm(
simulator,
n_elem:int=11,
override_params:Optional[dict]=None,
attach_head:bool=None, # TODO: To be implemented
attach_weight:Optional[bool]=None, # TODO: To be implemented
):
""" Import default parameters (overridable) """
... | 891132a4c133f0d145af5f85c0399954fccc450e | 7,982 |
def check_user(user, pw, DB):
"""
Check if user exists and if password is valid.
Return the user's data as a dict or a string with an error message.
"""
userdata = DB.get(user)
if not userdata:
log.error("Unknown user: %s", user)
return "Unknown user: %s" % user
elif userdat... | 21e8c56c0f747bd105cec31e1cb5aea348b4af44 | 7,983 |
def get_single_response_value(dom_response_list: list, agg_function):
"""
Get value of a single scenario's response.
:param dom_response_list: Single response provided as a list of one term.
:param agg_function: Function to aggregate multiple responses.
:return: Value of such observation.
"""
... | 7a7ef4f24a720a4611c48123061886b6bdb9f2f5 | 7,984 |
def sharpe_ratio(returns, periods=252):
"""
Create the Sharpe ratio for the strategy, based on a
benchmark of zero (i.e. no risk-free rate information).
Args:
returns (list, Series) - A pandas Series representing
period percentage returns.
periods (int.... | b06ef19c5512370ff98217f7fb565c25846b697e | 7,985 |
def is_validated(user):
"""Is this user record validated?"""
# An account is "validated" if it has the `validated` field set to True, or
# no `validated` field at all (for accounts created before the "account
# validation option" was enabled).
return user.get("validated", True) | c1ddfc52a62e71a68798dc07e7576a4ae42aa17f | 7,986 |
def current_chart_provider_monthly():
""" API for monthly provider chart """
mytime = dubwebdb.CTimes("%Y-%m", request.args.get('time_start'),
request.args.get('time_end'))
myids = dubwebdb.Ids(prv_id=sanitize_list(request.args.get('prvid')),
team_id=san... | 36f67b0323be8fc136175fa4f9fb4819b40ebb94 | 7,987 |
def create_round_meander(radius, theta=0, offset=Point()):
"""
Returns a single period of a meandering path based on radius
and angle theta
"""
deg_to_rad = 2 * pi / 360
r = radius
t = theta * deg_to_rad
# The calculation to obtain the 'k' coefficient can be found here:
# ... | c4379ef8f16486e9cdbd3353c5458a6c9523bb2d | 7,988 |
from typing import Dict
from typing import Any
import torch
import sys
from pathlib import Path
import socket
def get_env_info() -> Dict[str, Any]:
"""Get the environment information."""
return {
"k2-version": k2.version.__version__,
"k2-build-type": k2.version.__build_type__,
"k2-with... | 154b233e9f8bc6b16b5540a44df4003b8779d28e | 7,989 |
import pickle
def load_config(path):
"""Loads the config dict from a file at path; returns dict."""
with open(path, "rb") as f:
config = pickle.load(f)
return config | eb12aed2ebdeebacf3041f3e4880c714f99c052c | 7,990 |
from datetime import datetime
def _check_year(clinicaldf: pd.DataFrame, year_col: int, filename: str,
allowed_string_values: list = []) -> str:
"""Check year columns
Args:
clinicaldf: Clinical dataframe
year_col: YEAR column
filename: Name of file
allowed_strin... | c1630b4196733baa6ef12db2990243b1052d01d5 | 7,991 |
def lower_strings(string_list):
"""
Helper function to return lowercase version of a list of strings.
"""
return [str(x).lower() for x in string_list] | 58dcaccbc0f4ce8f22d80922a3ac5da26d7f42b1 | 7,992 |
def AAprime():
"""
>> AAprime()
aaprime and aprimea
"""
aprimeA = dot(transpose(ATable), ATable)
# Aaprime = dot(ATable1, ATable)
return aprimeA | f47d4df43ebcb8348e4a6fd4234b38bd18e92199 | 7,993 |
import os
def normalize_group_path(group, suffix=None):
"""
:param group:
:param suffix:
:return:
"""
group = os.path.join('/', group)
if suffix is not None:
if not group.endswith(suffix):
group = os.path.join(group, suffix.rstrip('/'))
return group | 31b0ef7eb808dce8ea51a0f4edbaec61e5c5cc2c | 7,994 |
import _pickle
import _io
def _load_dataset(data_filename_or_set, comm, verbosity):
"""Loads a DataSet from the data_filename_or_set argument of functions in this module."""
printer = _baseobjs.VerbosityPrinter.create_printer(verbosity, comm)
if isinstance(data_filename_or_set, str):
if comm is No... | 9c3a26a36202b4e8f35c795b7817d3fde8900a0b | 7,995 |
import re
def parse_contact_name(row, name_cols, strict=False, type='person'):
"""Parses a person's name with probablepeople library
Concatenates all the contact name columns into a single string and then attempts to parse it
into standardized name components and return a subset of the name parts that ar... | 315b971344df60d2cbb4f0c4e1d820b37b07ddaf | 7,996 |
def build_operator_attribute_dicts(parameters, n_op, prefix="op_"):
"""
Extracts elements of parameters dict whose keys begin with prefix and generates a list of dicts.
The values of the relevant elements of parameters must be either single values or a list of length n_op, or else
an exception will be r... | 9bae1a83de78e26e20df11cdb42ac6171a63f46f | 7,997 |
import os
import subprocess
def mock_data(rootdir, data_dir):
"""Build mock functional data from available atlases"""
mock_dir = os.path.join(data_dir, 'mock')
if not os.path.exists(mock_dir):
subprocess.run("python setup_mock_data.py".split(), cwd=rootdir)
return mock_dir | 2eed6ba8da9849e099841f61af56f1a982151c66 | 7,998 |
def get_peer_addr(ifname):
"""Return the peer address of given peer interface.
None if address not exist or not a peer-to-peer interface.
"""
for addr in IP.get_addr(label=ifname):
attrs = dict(addr.get('attrs', []))
if 'IFA_ADDRESS' in attrs:
return attrs['IFA_ADDRESS'] | e92906c0c705eb42ec3bedae2959dabcad72f0d2 | 7,999 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.