content stringlengths 35 416k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
import os
def get_cache_env():
"""Get basic cache config from environment variables."""
host = os.environ.get("HYPERGLASS_CACHE_HOST")
port = os.environ.get("HYPERGLASS_CACHE_PORT")
db = os.environ.get("HYPERGLASS_CACHE_DB")
for i in (host, port, db):
if i is None:
raise Looku... | 33834e218734022cc13f95308536eea80e64c83e | 655,658 |
import os
def get_qibuild_cmake_files():
""" Get QiBuild CMake Files """
res = list()
cmake_dest = 'share/cmake'
for (root, _dirs, filenames) in os.walk('cmake'):
rel_root = os.path.relpath(root, 'cmake')
if rel_root == ".":
rel_root = ""
rel_filenames = [os.path.jo... | 0c64e1d7e5194f7af80f77cfe3bc94eefeb5c49d | 655,659 |
def averaging(imgIn,imgOut,Rp=0.0):
"""
averaging input and reconstruction
"""
# Rp = [0,1], ratio of propagating how much input to reconstruction
# Rp = 1/0 for maximully/minimumaly passing
average = (Rp*imgIn+(1-Rp)*imgOut)/2
return average | 4e34e49d6cd2d8a731527a81ac938490528227bf | 655,660 |
def extract_job_fields(tags):
"""Extracts common job's metric fields from TaskResultSummary.
Args:
tags (list of str): list of 'key:value' strings.
"""
tags_dict = {}
for tag in tags:
try:
key, value = tag.split(':', 1)
tags_dict[key] = value
except ValueError:
pass
spec_name... | 0ce1884061673156c33ff6f2d4b990b80ddf459e | 655,661 |
def replace_string(text, replacements=None, whitespace=True):
"""A wrapper around str.replace where replacements is a dictionary:
original_string -> replacement_string
whitespace=True surounds the replacement with whitespaces.
"""
if not replacements:
return text
for ori, rpl in repl... | b1dae4d846c8b589ace8496dd73d7a2d4a2efc7b | 655,662 |
import functools
def r_to_s(func):
"""Decorator method for Workbench methods returning a str"""
@functools.wraps(func)
def wrapper(*args, **kwargs):
"""Decorator method for Workbench methods returning a str"""
class ReprToStr(str):
"""Replaces a class __repr__ with it's strin... | 176ef95ffb2d4789c86229d9cfd52cbfdfd63215 | 655,663 |
def attrname(obj, lower_name):
"""Look up a real attribute name based on a lower case (normalized)
name."""
for name in dir(obj):
if name.lower() == lower_name:
return name
return lower_name | 7b76084a358939902727c3b3747a179c1faaf71e | 655,664 |
def is_builtin_type(obj) -> bool:
"""
检查 obj 是否基础类型
"""
return isinstance(obj, (int, str, float, bool)) or obj is None | c379954e957d78523c880dd56fab2a58b84fa6a3 | 655,665 |
def get_domain(url: str, /) -> str:
"""Get domain from an url"""
return url.split('//')[-1].split('/')[0].split('?')[0] | 5e05257585346fa257b2f481aa8d04c32943ae65 | 655,666 |
def rectangles_intersect(rect1, rect2):
"""Returns True if two rectangles intersect."""
return all([(rect1[1][i] >= rect2[0][i]) and
(rect2[1][i] >= rect1[0][i]) for i in range(2)]) | 2428a4caead68340093933f443d27fb8afc0de43 | 655,668 |
def option(*args, **kwds):
"""decorator to provide an argparse option to a method."""
def _decorator(func):
_option = (args, kwds)
if hasattr(func, 'options'):
func.options.append(_option)
else:
func.options = [_option]
return func
return _decorator | cc1789b1bcd1ccd317fcf4491d4ea6a0332ab172 | 655,670 |
from typing import Any
def typename(o: Any) -> str:
"""Return the full name (including module) of the type of o.
>>> typename(5)
'int'
>>> typename('text')
'str'
>>> typename(np.array([1]))
'numpy.ndarray'
"""
# https://stackoverflow.com/a/2020083
name: str = o.__class__.__qualname__
module =... | 19f983b68fd294e1614bef26c21d7c795796467a | 655,671 |
import math
def get_notches(poly):
"""
Determine the number of notches in a polygon object and calculate
normalized notches of polygon
Based on:
"Measuring the Complexity of Polygonal Objects"
(Thomas Brinkhoff, Hans-Peter Kriegel, Ralf Schneider, Alexander Braun)
http:... | 2abf20139de82f529d611d8d5f93f95bded77c7b | 655,672 |
def null_count(df):
"""
Check a dataframe for nulls and return the number of missing values
"""
# Example Input (df = pd.DataFrame):
# > | column 0 | column 1 | column 2 |
# > | ----------- | ----------- | ----------- |
# > | NaN | 9 | 10 |
# > | 4 ... | ce7628f74d532b4c93ddb73ea55becd6f9c0d316 | 655,673 |
def fib(n: int) -> int:
"""
Cache the results of previous fib calls so that
so when you need them again, you can look them up
instead of needing to compute again for the nth time.
The maxsize property indicates how many of the most recent calls
of the function it is decorating should be cached.... | 6a62b121698ea34151a4906f04cc3c2d287ebd26 | 655,674 |
import csv
def csv_quaternions(filename):
"""extracts all the quaternions from the csv file"""
w_values = []
x_values = []
y_values = []
z_values = []
with open(filename) as data_file:
odom_data = csv.reader(data_file)
for row in odom_data:
w = float(row[0])
... | 9eaf43ccb5e916be82607b6db13eda6387812beb | 655,676 |
def round(addr: int, align: int, up: bool = False) -> int:
"""Round an address up or down based on an alignment.
Args:
addr: the address
align: the alignment value
up: Whether to round up or not
Returns:
The aligned address
"""
if addr % align == 0:
return ... | 0b77bd25d66a5522fb3dd568cc6f6ce0fedbd59c | 655,677 |
def is_group(message) -> bool:
"""Whether message was sent at a group."""
# See "type" at https://core.telegram.org/bots/api#chat.
return 'group' in message.chat.type | 38b719acadb132243b98af0bb95b7e33c47320a2 | 655,678 |
def is_not_excluded_type(file, exclude_types):
"""Return False if file type excluded, else True"""
if exclude_types:
for exclude_type in exclude_types:
if file.lower().endswith(exclude_type.lower()):
return False
return True | 6b4392c9662b55d211207a98b16c3c846558215d | 655,680 |
def importName(modulename, name):
"""
Imports a named object from a module in the context of this function,
which means you should use fully qualified module paths.
Returns None on failure.
This function is from http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/52241
"""
module = __im... | 40d3159ecd066d0b90d0eda8d8455aecc94f2696 | 655,681 |
from functools import wraps
def consumer(func):
"""A decorator, advances func to its first yield point when called.
"""
@wraps(func)
def wrapper(*args, **kw):
gen = func(*args, **kw)
gen.next()
return gen
return wrapper | 331fe56003c14bf9ad89664e74ae92723f797d56 | 655,684 |
def solution2(candidates, target):
"""
candidates.sort()
same idea as solution2, remove numbers bigger than target ealier
"""
candidates.sort()
def fn(candidates, target):
ans = set()
for n in candidates:
newTarget = target - n
if newTarget > 0:
... | ad111e9a7e3c1add789ec680fe04e8a0f26225de | 655,685 |
from typing import Optional
from pathlib import Path
def default_network_output_paths(
network_name: str,
general_output: Optional[Path],
branches_output: Optional[Path],
nodes_output: Optional[Path],
parameters_output: Optional[Path],
):
"""
Determine default network output paths.
"""... | b98f495361688e8961b00178995d4df182151ee6 | 655,686 |
def parse_filters(filter_list):
"""[will remove = from list items and return just the filter that we can work with]
Args:
filter_list ([list]): [filter list that we need to extract filters from]
Returns:
[List]: [the new filter list after we extract it]
"""
if filter_list:
... | 0abf7cb2d0fbefcf8bd644c50788e97be83d309e | 655,687 |
def excel_to_python(command_string):
"""
Returns the python equivalent of many excel formula names
"""
d = {
'SUM' : 'np.sum',
'AVERAGE' : 'np.mean',
'MAX' : 'np.max',
'MIN' : 'np.min',
'MEDIAN' : 'np.median',
'MODE' :... | e60d16f871a9d145306e365b28655687e1421c46 | 655,688 |
def dict_to_list(d_dict):
"""
converts a dictionary from a hdf5 file to a list
"""
for k, v in d_dict.items():
if isinstance(v, dict):
d_dict[k] = [
d_dict[k][str(i)]
for i in range(len(d_dict[k]))]
else:
d_dict[k] = list(d_dict[k])... | e9022fb76e4b031160aa35076cb2030fc11fc69a | 655,689 |
def get_end_pos(cls, start_pos, dimensions, left=False, up=False):
"""
calculate the end position if were to build an array of items
:param cls: Type
:param start_pos: (int, int)
:param dimensions: (int, int)
:param left: bool: default builds rightward
:param up: bool: default builds downwar... | a03b45f7137e835a8709da933a7a7e4f509f8569 | 655,690 |
def find_out_of_order_packet_indices(packet_ns):
"""
Return indices of packets which have apparently arrived out-of-order.
Specifically: return indices of any packet number which was less than the
previous packet number. For example, for the list of packet numbers:
0, 1, 2, 3, 5, 4, 6, 7.
re... | 67401aba9e62d999368027dc5479c4f4932dafc4 | 655,691 |
import base64
def base64_encode(s):
"""Encode a URL-safe string.
:type s: six.text_type
:rtype: six.text_type
"""
# urlsafe_b64encode() returns six.binary_type so need to convert to
# six.text_type, might as well do it before stripping.
return base64.urlsafe_b64encode(s).decode('utf-8').... | e63ce1c901c1f8822807a2da2d69544ec75e4fd5 | 655,695 |
def resultIsSuccess(res):
"""
JSON-decoded stake pool responses have a common base structure that enables
a universal success check.
Args:
res (dict): The freshly-decoded-from-JSON response.
Returns:
bool: True if result fields indicate success.
"""
try:
return res[... | 760c7e2ab210b6c972392e4b32eae6402f9759bc | 655,696 |
def ProgbarLoggerConfig(argument_parser):
"""
Set CLI arguments
:param argument_parser: argument parser
:type argument_parser: ```ArgumentParser```
:returns: argument_parser
:rtype: ```ArgumentParser```
"""
argument_parser.description = """Callback that prints metrics to stdout.
Raise... | 7d38d432b5db6d6f3c21c040d1e4eb1df3a638f9 | 655,697 |
def _render_minimal_module_py() -> str:
"""Render the contents for an arbitraty Python module.
:return: Module contents as text.
"""
return 'print("Hello Production!")' | ffe2d7660416981090be8277ca32f3adbe601b93 | 655,698 |
def first_day(nda):
"""Returns the First Day"""
fd = nda[-1]
return fd | 0ef3302cdfcabd278504ca9dd2416d5747eaa273 | 655,699 |
def _create_array_rec(dimensions: int, sizes: list, initialization_value: int = 0) -> list:
"""Auxiliary recursive function for creating a new matrix consisting on lists of lists.
This method assumes that the parameters were previously validated.
:param int dimensions: the number of dimensions to create. ... | 37720873d6d0e65ea48ac95bd86e3a1924f7c92d | 655,700 |
import torch
def GP_kernel_transform(x, GP_kernel_mapping_covar_identification):
"""
performs transformation of covariates to enable Gaussian Process models to also do Bayesian optimization for
integer and categorical variables. The transformation is part of the solution described in this paper:
E.C. ... | 5922b85005558dc0092b44ff0a7f2d0bdd36d3ae | 655,702 |
def _extract(dct, keys):
""" Helper function to extract a list of keys from a dict and return these
in a new dict.
"""
tmp = {}
for key in keys:
try:
tmp[key] = dct.pop(key)
except KeyError:
pass
return tmp | 7a84561ec958896745bfdeeecf46440aea414986 | 655,703 |
import argparse
def parse_args():
"""Read prediction CLI args passed on script start"""
parser = argparse.ArgumentParser()
# default arg for image load directory
parser.add_argument("path_to_image", type = str, help = "path to an image to predict")
parser.add_argument("checkpoint", type = str... | db375e59ef28519c7a4a738cce378f1184034efd | 655,704 |
def get_reference_file(hparam, dataset_source, idx):
"""
get reference files
"""
reference_files = []
reference_feats = []
for _ in range(hparam.batch_size):
if hasattr(dataset_source, "X"):
reference_files.append(dataset_source.X.collected_files[idx][0])
else:
... | 77f489c975440d71647e3eb09f70666fa053e491 | 655,705 |
def subtree_ids(treeview, x, level=0):
"""
Return a list of tuples containing the ids and levels for *x* and every element below it in the Treeview *treeview*.
The level of *x* is 0, children of *x* are 1, and so forth.
"""
id_list = list()
id_list.append((x, level))
for y in treeview.get_c... | b637a0bba5ca3aff9dfa1665984b7cd4cd56790d | 655,706 |
import csv
def get_models_durability(durability_csv_file):
"""Загрузить прочность объектов из csv-файла"""
models_durability = {}
with open(durability_csv_file) as stream:
reader = csv.reader(stream, delimiter=';')
for row in reader:
models_durability[row[0]] = int(row[1])
... | aa0e72cd44e6199991246b7d3c8cbe5a29810bab | 655,707 |
def mwcontext(func):
"""Helper decorator for checking if the message is in context of the
main window. Class that uses this to wrap its message handlers must
have a GetMainWindow method that returns a reference to the MainWindow
instance that owns the object.
@param funct: callable(self, msg)
"... | c7d4e1cae6e75ac28c9d8cc06fcc0f8154a002f9 | 655,708 |
def nbr_virgule(s):
""" Compte le nombre de virgule dans un mot"""
n = 0
for k in s:
if k == ',':
n+=1
return n | 016061f37933f96e104c087decf5eb4d9dbe9bd0 | 655,709 |
def get_interval(value, intervals):
"""
Returns the index of the interval the value lies in.
:param value: Value for which to find the interval.
:param intervals: List or tuple of interval with values which represent the upper boundary of each interval.
The first interval starts at 0 and ends ar th... | 1207fa3c07c03472d14b55b8c55ed8dc35502b1e | 655,710 |
def comma_code(items):
""" Combines list into a string of the form item1, item2, and item 3
Args:
items (list): List of strings
Returns:
string: list items combined into a string
"""
item_len = len(items)
if item_len == 0:
return ''
elif item_len == 1:
r... | b15f6d064648de5155732aa5e9d0ca2ec4979ba5 | 655,712 |
def merge_feat_df(df, feat_temp_df, zero_fill_cols = None, zero_fill_prefix = None):
"""
Helper function to perform joining between output dataframe and temporary feature dataframes.
:param df_out: pd.DataFrame of user-week level features
:param feat_temp_df: pd.DataFrame of new features to be appended,... | 844b526173744ff572c781707bef775af4c2d9f2 | 655,713 |
def ignore_escape(path: str) -> str:
"""
Escape a path appropriately for a docker ignore file.
"""
special_chars = "\\*?[]"
return "".join("\\" + ch if ch in special_chars else ch for ch in path) | 221f010eaf08782aa06bc718a96765635c696366 | 655,714 |
def __get_fn(array, fn_2d, fn_3d):
"""
Decide whether or not the given array is really 2D or 3D, and return the corresponding function.
"""
if hasattr(array, 'axistags'):
assert array.channels == 1, \
"Can't handle multi-channel data. " \
"(Your image has {} channels.)".format(array.channels)
time_index ... | 126f2c38b371190d569ef375790e4414270d0e1d | 655,715 |
def set_status(parameters):
"""Set status for a sample.
:param parameters: Collected parameters for a sample
:returns: string
"""
status = "N/A"
if 'rounded_read_count' in parameters.keys() and 'ordered_amount' in parameters.keys():
if parameters['rounded_read_count'] >= parameter... | fa9db760905333ac6b8e570cd81b6c5d6bd13f28 | 655,717 |
def seperate_ds_belief_disbelief(in_lyrs):
"""
Takes a list of prepared dempster shafer list
elements and seperates into two seperate lists,
one for belief, one for disbelief.
"""
belief_list, disbelief_list = [], []
for lyr in in_lyrs:
typ = lyr[2]
# seperate
... | a8ff42995222bfef580641581afbdd402030e9e8 | 655,718 |
import time
def month_and_year_to_epoch(month_no, year):
""" Convert a month and year to the epoch time for the first second of
said month. """
month_str = str(month_no)
if len(month_str) == 1:
month_str = "0"+month_str
date_and_time = "01."+month_str+"."+str(year)+" 00:00:01"
pattern ... | 31541427f14aebe443abfa4910d409e36152899d | 655,719 |
def group_multiples(links):
"""Join links by comma if more than one.
>>> from collections import namedtuple
>>> Link = namedtuple("Link", ["text"])
>>> artists = [Link("IU"), Link("Sungha Jung")]
>>> group_multiples(artists)
'IU, Sungha Jung'
"""
return ", ".join([link.text.strip() for ... | 773b94398722fe9b7a57520377861fb1ff57befb | 655,720 |
def extract(row):
"""
Separate an array into columns
"""
return tuple(row.features_scaled.toArray().tolist()) | b7761b91f691218009af50666207d02e432c0e8e | 655,721 |
import os
def get_prefix(client, message):
"""Function to pass to bot initializer for dynamic prefixes.
"""
prefix = os.getenv('WHOLESOME_PREFIX')
if not message.guild:
# no prefix necessary in DMs
prefix = ''
return prefix | c2bd9314bfcd6484c5a32409dd6109ad834f233b | 655,723 |
import re
def executable_script(src_file, gallery_conf):
"""Validate if script has to be run according to gallery configuration
Parameters
----------
src_file : str
path to python script
gallery_conf : dict
Contains the configuration of Sphinx-Gallery
Returns
-------
... | 918e633634ee83e899992ced8ba0ba3a93a57531 | 655,724 |
def read_key(keyfilename):
"""鍵ファイルの読み込み"""
f1 = open(keyfilename, "r")
lines = f1.readlines()
"""最初の1行から2つの値を読み込む"""
flds = lines[0].split(",")
return (int(flds[0]), int(flds[1])) | 4169d03248a74f9ffdc1514126ac1132571fe708 | 655,725 |
from typing import Dict
from typing import Any
from typing import Sequence
def get_nested(data: Dict[str, Any], keys: Sequence[str]) -> Any:
"""
Get a value from a nested dictionary.
Args:
data (Dict[str, Any]): The dictionary to get the value from.
keys (Sequence[str]): The keys to get t... | 965b720cc3bb22d5fcd5fe9ba0565a3980ffe46f | 655,726 |
def to_int(text):
"""
extract digits from text
"""
return ''.join([char for char in text if char.isdigit()]) | c791dd4d2057d658ad96beeafd31e7e9767324ea | 655,727 |
def lerp(input1, input2, mask):
"""Lerp between two values based on a 0-1 mask value.
When mask is 0, return input1. When mask is 1, return input2.
Otherwise blend between the two."""
return ((1 - mask) * input1) + (mask * input2) | 4cc241659fa577b84fb0bed87a0d3f36643b7fb8 | 655,728 |
import socket
def is_ipv6_available():
"""Check if IPv6 is available.
:Return: `True` when an IPv6 socket can be created.
"""
try:
socket.socket(socket.AF_INET6)
except (socket.error, AttributeError):
return False
return True | 31097b955cb34e85f06af965fb55ddd49233faee | 655,729 |
import time
def timeit(func):
"""Decorator to time a single run of a task"""
def wrapper(*arg, **kw):
t0 = time.time()
res = func(*arg, **kw)
t1 = time.time()
res.elapsed = (t1 - t0)
if not res.desc:
res.desc = func.__name__
return res
return wra... | aca09db65848d89e57c70068ef21a874b8d9a0fc | 655,730 |
import math
def build_plot(graph):
"""
Build plot using graph
"""
plot = []
for degree in graph:
plot.append([math.log(degree), math.log(graph[degree])])
return plot | 3b8be7f70e7a3a5dcd100ddcae2286e2e19cdb9d | 655,731 |
def bacon_strategy(score, opponent_score, margin=8, num_rolls=5):
"""This strategy rolls 0 dice if that gives at least MARGIN points,
and rolls NUM_ROLLS otherwise.
"""
def beacon(x):
return 1+abs(x//10 - x%10)
bacon_opponent = beacon(opponent_score)
if bacon_opponent >= margin:
... | addbf72b5b9a78cb1862755aae97be262247d629 | 655,734 |
def get_P_Elc_game_standby(P_Elc_game_standby_measured):
"""待機時の消費電力を計算する
Parameters
----------
P_Elc_game_standby_measured : float
待機時の平均消費電力(実測値), W
Returns
----------
P_Elc_game_standby : float
稼働時消費電力, W
"""
P_Elc_game_standby = P_Elc_game_standby_m... | efb5b7b0fed8b815e4cb7b2017f34f29e55d153f | 655,735 |
def norm1(x):
"""Normalize to the unit sphere."""
return x / x.square().sum(axis=-1, keepdims=True).sqrt().clamp(1e-12) | 43037999a96fc14e6d3fb801fd29a85b277c8988 | 655,736 |
def locked():
"""
Locking decorator.
"""
def wrap(f):
"""
Returns a wrapped function
"""
def new_function(self, *args, **kwargs):
"""
Executes the decorated function in a locked context
"""
lock = kwargs.get('lock', True)
... | 31fde9910eaaac092bfca57d658f3e0eacbfdf7b | 655,737 |
from unittest.mock import Mock
def mock_config() -> Mock:
"""Returns the configuration mock object."""
mock_config = Mock()
mock_config.host = "mock_host"
mock_config.url = "mock_url"
mock_config.session.get = "mock_get"
mock_config.session.post = "mock_post"
return mock_config | 19bacfc45a21fab7c693f129123ac2bc1cacb744 | 655,738 |
from typing import Dict
from pathlib import Path
import os
import json
def get_config() -> Dict:
""" Get Config Json"""
with open(str(Path(
__file__).parent.parent) + os.sep + "conf" + os.sep + "conf.json",
'r') as fp:
return json.load(fp) | c82aa0dd72a98f71ce712c1f908f814fc3ac4308 | 655,739 |
import os
def P(path):
"""expand ~ and $ in the path"""
if path is None:
return None
else:
return os.path.expanduser(os.path.expandvars(path)) | 700f8870773a634254d55a45cd2a014454a02bf8 | 655,740 |
def bb_get_instr_max_width(basic_block):
"""Get maximum instruction mnemonic width
"""
asm_mnemonic_max_width = 0
for instr in basic_block:
if len(instr.mnemonic) > asm_mnemonic_max_width:
asm_mnemonic_max_width = len(instr.mnemonic)
return asm_mnemonic_max_width | f45116b0d413b422c9499b745a40f4467a6c0f43 | 655,741 |
def parse_syscall(syscall):
"""Creates list of infos contained in a syscall
# syscall entries:
# 0 - event_number
# 1 - event_time
# 2 - cpu
# 3 - user_uid
# 4 - process_name
# 5 - thread_id
# 6 - event_direction: > start syscall with with params listed below < return
# 7 - even... | 9b388f929a68ba3831c60fdd10876141dc124bd0 | 655,742 |
def has_series(event) -> bool:
"""
Check if the event belongs to a series.
:param event:
:type event: dict
:rtype: bool
"""
return "series" in event and event["series"]["id"] | ef21a0a0800aa581e06c54e313c34dea977ae2ef | 655,743 |
def dd_start_value_map_nb(record, ts):
"""`map_func_nb` that returns start value of a drawdown."""
return ts[record['start_idx'], record['col']] | 0919da2945765d4f156401747a688f646fca2746 | 655,744 |
def bool_to_one_or_zero(value):
"""
Converts a boolean value into an integer
:param value: A boolean value
:type value: bool
:return: 1 or 0
:rtype: int
"""
return 1 if value else 0 | 9c4ab81998f6d11717bc375ae86ec221b5180ac7 | 655,745 |
def per_form_un(number):
"""
works out, for the lattice parameters of t-LLZO, defects per cubic cm
args:
number (float): defect per formula unit
returns:
per_cubic_cm: defect per cubic cm
"""
per_unit_cell = number * 8
per_cubic_angstrom = per_unit_cell / (13.003 * 13.003 * ... | 8ba9565b208346acd9c3a5801f4b6e94cfac89e4 | 655,746 |
import random
def find_trigram(vocab, pair=False):
"""Find random set of related words in the vocab dictionary.
If a valid pair is passed, return the third word in the trigram.
Otherwise, randomly choose and return a key pair from the dictionary.
"""
if pair in vocab:
return random.choice... | 69cf3ce9c78cb42280c60a9bf1e683c31d9e4731 | 655,747 |
def rewrite(C, alpha, w):
"""
Parameters
==========
C: CosetTable
alpha: A live coset
w: A word in `A*`
Returns
=======
rho(tau(alpha), w)
Examples
========
>>> from sympy.combinatorics.fp_groups import FpGroup, CosetTable, define_schreier_generators, rewrite
>>>... | 695e22442a995a403510d328794e0686545c6289 | 655,748 |
def get_package_version(packages, package):
"""
Get version of installed package.
:param packages: installed packages and versions, keyed by package
name
:type packages: dict of str or unicode => str or unicode
:param package: Package name
:type package: str or unicode
:return: Package ... | 6dc3374d246d25124d8d9fb5098a0af5ac625e0e | 655,749 |
def get_means_of_booleans(data, boolean_cols):
""" Put boolean_cols of the data in a uniform format and
compute the mean per customer.
Parameters
----------
data: The DataFrame.
boolean_cols: array-like of column names with boolean values to
process.
Returns
-------
Dat... | 8bf9d213a53f6388444da1ffb6e3835bc67164f1 | 655,750 |
def get_hetionet_mapping(mapping_file, metaedge="CtD"):
"""
Compound::DB00997 CtD Disease::DOID:184
"""
drug_to_do_ids = {}
f = open(mapping_file)
header = f.readline()
#m = len("Compound::")
#n = len("Disease::")
for line in f:
words = line.strip().split("\t")
... | 799f8c5a459d842f8610641d00914f7c6299278a | 655,752 |
def get_lib_name(lib):
"""Returns the name of a library artifact, eg. libabc.a -> abc
Args:
lib (File): A library file
Returns:
str: The name of the library
"""
# NB: The suffix may contain a version number like 'so.1.2.3'
libname = lib.basename.split(".", 1)[0]
if libname... | 0f41fd3cfeb4b5a7f03fceeed0fc6fcea79b9b61 | 655,753 |
def generate_key(action, path_or_id, settings=None, default=" (default)"):
""" generate_key: generate key used for caching
Args:
action (str): how video is being processed (e.g. COMPRESSED or DOWNLOADED)
path_or_id (str): path to video or youtube_id
settings (dict): setti... | 1dd2cf43254ecf198673bb28d183937c804d6a30 | 655,754 |
import json
def post_data():
"""
POST /data
Endpoint for posting mocked data
"""
return json.loads('{"success":true, "message":"Data created (but not really)" }') | 8143bd454c55677c5ceabed2cce942bbf6f1b48e | 655,756 |
def calculate_avg_delay_wait(avg_delays):
"""
Calculate average delay or waiting value.
"""
avg_delays_dict = {}
for lambda_rate, avg_delay_list in avg_delays.items():
avg_value = sum(avg_delay_list) / len(avg_delay_list)
avg_delays_dict[lambda_rate] = avg_value
return avg_delays... | 88542ff894c17d4bd9be17dee606ec77adc9ed8d | 655,757 |
def parse_filesystems(f_systems, tag_key, tag_val):
"""Parse filesystems by tag."""
tmp_fsystems = []
for f_system in f_systems:
if f_system['Lifecycle'] == 'AVAILABLE':
for tag in f_system['Tags']:
if ((tag['Key'] == tag_key) and (tag['Value'] == tag_val)):
... | 57d3f51f68b13ae9358f6c48c01dbc7611290c7d | 655,758 |
import struct
def bytes_to_int(byte_stream):
"""Convert bytes to integer"""
return struct.unpack(">L", byte_stream)[0] | a480466573f689706b6d5ae4049b7604f9f590ee | 655,759 |
import torch
def get_linear_rewinding_schedule_with_warmup(optimizer, num_warmup_steps, num_training_steps, prune_start_step, prune_end_step, rewind_interval, last_epoch=-1):
"""Return linear decay schedule with warmup with learning rate rewinding"""
def pruning_lr_lambda(current_step: int):
prune_int... | 767b0db6e53fcb9a0bc807703e1832ea055a3751 | 655,760 |
def factorial(n):
""" Naive computation of factorial(n) with products. Not recursive."""
if n <= 0: return 1.0
else:
f = 1.0
for i in range(2, n+1):
f *= i
return float(f) | 320c1343688844a50b65c4e856eaeb6293c19758 | 655,762 |
def net_unpack(data,
# Map IP version number to PGSQL src/include/utils/inet.h.
fmap = {
2: 4,
3: 6,
}
):
"""
net_unpack(data)
Unpack Postgres' inet/cidr data structure.
"""
family, mask, is_cidr, size = data[:4]
return (fmap[family], mask, data[4:]) | 3a3b4a2a114720580129cbfb3918acd68a2ccc59 | 655,763 |
def lowerleft_iou(box1, box2):
""" Compute the Intersection-Over-Union of two given boxes.
Args:
box1: array of 4 elements [cx, cy, width, height].
box2: same as above
Returns:
iou: a float number in range [0, 1]. iou of the two boxes.
"""
x0 = max(box1[0]... | d91bda161625d4ae4ecc4c4def55803fdbc29f17 | 655,764 |
import requests
import json
def get_pushshift_submissions(query, sub):
"""
Retrieves Reddit submissions matching query term over a given interval
Parameters
----------
query : str
Query term to match in the reddit submissions
sub : str
Submission match query
Returns
-------
... | 5f29854d90f0cd568cc525164ef25bbf6a2b2c50 | 655,765 |
import requests
import six
def fabricate_200():
"""
Returns an HTTP response with ``status_code`` 200 and empty JSON contents.
This is used when the Client has ``ignore_conn_err=True``, so that backend responses can be
spoofed to minimize execution-halting errors.
Returns
-------
:class:... | 4a7157a8eaf5a474ef13874fc573f018783ddd5f | 655,766 |
from datetime import datetime
def millisecondToHumanstr(milliseconds):
""" Returns human readable time duration from milliseconds.
HH:MM:SS:MMMM
Parameters:
milliseconds (str,int): time duration in milliseconds.
"""
milliseconds = int(milliseconds)
r = datetime.utcfromtime... | eaf3fac3d78ae9eaf8a2b9bcbcea2e8df1aa1dfc | 655,767 |
from typing import List
from typing import Dict
def letter_combinations(digits: str) -> List[str]:
"""
:param digits:
:return:
>>> letter_combinations('23')
['ad', 'ae', 'af', 'bd', 'be', 'bf', 'cd', 'ce', 'cf']
"""
digit_map: Dict[str, str] = {
'2': 'abc',
'3': 'def',
... | a201150f32358b56da3dc6b0b4744077ad012579 | 655,768 |
import hashlib
import base64
def id_token_hash(value, hashfunc=hashlib.sha256):
"""
Inspired from oauthlib
"""
digest = hashfunc(value.encode()).digest()
left_most = len(digest) // 2
return base64.urlsafe_b64encode(digest[:left_most]).decode().rstrip("=") | 66e91e21ccea606e3ab6a1f3444d98a77ec78ea6 | 655,769 |
def _test_rast(h):
"""Sun raster file"""
if h.startswith(b'\x59\xA6\x6A\x95'):
return 'rast' | 510b8088fd1aa29926fa8ec740241acc7643ed62 | 655,770 |
def _MakeIndexesListIntoYaml(indexes_list):
"""Converts list of yaml statements about datastore indexes into a string."""
statements = ['indexes:']
for index in indexes_list:
statements += index.ToYaml()
return '\n'.join(statements) + '\n' | 089fa54358c14ed58b0bb3ceee6726f8948936be | 655,772 |
def fix_deployment(fn):
# NOTE(ikhudoshyn): Remove this once new deployment model
# get adopted.
# New DB schema for Deployment was introduced in
# https://github.com/openstack/rally/
# commit/433cf080ea02f448df1ce33c620c8b30910338cd
# yet old one is used over the codebase.
# This dec... | 7bad1b4e11bb8737f41a27782c5833e9f26f61e3 | 655,773 |
def filter_float(value):
"""
Filter given float value.
:param value: given value
:type value: float
:return: filtered version of value
"""
if isinstance(value, (float, int)):
return value
return None | 214c580029e2d6ffced2a035725c52619ff8ab5d | 655,774 |
def invert_for_next(current):
"""
A helper function used to invert
the orientation indicator of the
next panel based on the current panel
i.e. if a parent is horizontal a
child panel must be vertical
:param current: Current parent
orientation
:type current: str
:return: child... | e97ce13f368cdd795fec7e9f045a7f1a7892b35a | 655,775 |
def merge_station_subloc(station_dbase,station_subloc,default_z):
"""Merge BayDeltaSCHISM station database with subloc file, producing the union of all stations and sublocs including a default entry for stations with no subloc entry
Parameters
----------
station_dbase : DataFrame
This should... | adfd7435f326897aa99977630fe65d0d92c1a6aa | 655,776 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.