content stringlengths 35 416k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def get_transaction_data(consumer_id, transactions):
"""
For all transactions related to a consumer, return
a dictionary with the keys being the offer IDs or the
value 'transaction' for non-offer related events.
"""
txn_dict = {}
txn = transactions[transactions["person"] == co... | ca0866968654f0b267d73a17ba972274456aeced | 630,805 |
import requests
def download(url):
"""
:param url: str
Url to get
:return: response
Response of request
"""
return requests.get(url) | f785920d00d2a9c322dfda074362f78fd5923d52 | 630,806 |
def cost(z):
""" Cost function. """
return 0.1 + 0.4 * (4 * z[0])**2 + 0.5 * z[1] | e6fb9a09edd5a330d10cb04e3a6fac8b8c761558 | 630,807 |
import hashlib
def md5_hex(data):
"""
shortcut of hashlib.md5('xxx').hexdigest()
>>> md5_hex('123')
'202cb962ac59075b964b07152d234b70'
"""
return hashlib.md5(data).hexdigest() | b9471304effed6757b2505c7859adb7a342194c2 | 630,808 |
def get_output_jar_paths(version):
"""
Gets the list of output jars, which includes the primary
jep-${version}.jar, the test jar, and the src jars.
"""
return [
'build/java/jep-{0}-sources.jar'.format(version),
'build/java/jep-{0}.jar'.format(version),
'build/java/jep-{0}-tes... | 5ce415a88d544a1ec4c3096130951706e2a34e69 | 630,809 |
def add_files_to_zip(zip_file, base_dir, file_list):
"""Pack a list of files into a zip archive, that is already opened for
writing.
Args:
zip_file: An object representing the zip archive.
base_dir: Base path of all the files in the real file system.
file_list: List of absolute file paths to add. Mus... | 23ef0aa7767bb97d3bef78b0ab87f9d4877cfbd5 | 630,810 |
def prior_probability_of_category_k(k, c, nk):
"""
Function that calculates the prior probability of category k. This is equation 3-4 in [Ande90]_
Parameters
----------
k : int
Category index. For example, k can be 0 or 1 or 2 etc
c : float
Coupling probability. This is the prob... | c60a71bdc1e4a8d87ae82e156c812287f01a79c8 | 630,811 |
def applyCompact(a, cops):
"""
Apply compact ops to string a to create and return string b
"""
result = []
apos = 0
for op in cops:
if apos < op[1]:
result.append(a[apos:op[1]]) # equal
if op[0] == 0:
result.append(op[3])
apos = op[2]
... | 87f2b4daf6d0772cd6cc7789e7b5259eabbbe565 | 630,812 |
import click
def format(text):
"""Format all OK,FAIL,PR,REPO words
:param text: word
:type text: string
:raises Exception: Unknown text
:return: formated click style text
:rtype: string
"""
text = text.lower()
if text == "ok":
return click.style('OK', fg='green', bold... | 2ac991685f3b70615ba9ef253724f200f4c8e79e | 630,813 |
import hashlib
def HashedKey(*args, version=None):
""" BOSS Key creation function
Takes a list of different key string elements, joins them with the '&' char,
and prepends the MD5 hash of the key to the key.
Args (Common usage):
parent_iso (None or 'ISO')
collection_id
experi... | 050fb353beb8779aaf47a86eca2138a1791c9fed | 630,814 |
from datetime import datetime
def parse_date(date_text: str):
"""
Convert a date string into a datetime instance that can be saved as an
SQL DATE.
:param date_text: A timestamp string in "YYYY-MM-DD" format
:return: A datetime object
"""
return datetime.strptime(date_text, '%Y-%m-%d') | 711f216985761cd91c5314d1aaa5a2e3049ac9fe | 630,815 |
def getDuplicateRecord(lines1, lines2):
"""2つのcsv配列を比較し、profile URLが一致するレコードを出力する"""
hit = False
for i in range(0, len(lines1)):
for j in range(0, len(lines2)):
# profileのURLが一致しているか調べる
if (lines1.values[i][1] == lines2.values[j][1]):
hit = True
... | 298b3479c0f20fdba53ddf0981f0e30f2fa9c7e6 | 630,816 |
import requests
import json
def get_token():
"""
Get token for connection.
Parameters
----------
username : string
password : string
Returns
----------
token : string
Token for authentication to the API.
"""
LOGIN_URL = "https://enno-api.herokuapp.com/user/login"... | 5abe489098536496b9d3422a92c3ea9a34c4a855 | 630,817 |
def _ftp_list_dir_windows(url, lines):
"""
:param str url:
:param list[str] lines:
:returns: tuple of lists: (dirs, files). both are absolute urls
:rtype: (list[str],list[str])
"""
dirs, files = [], []
for line in lines:
if not line:
continue
fields = line.sp... | 91a2c9eb84876517f4351245743addce727e578a | 630,818 |
def filter_images(data, split_data):
""" Keep only images that are in some split and have some captions """
all_split_ids = set()
for split_name, ids in split_data.iteritems():
all_split_ids.update(ids)
new_data = []
for img in data:
keep = img['id'] in all_split_ids and len(img['regions']) > 0
if... | 65c7b1765371e6e3875766394de09203e7485837 | 630,819 |
def cmpBoundaryAreas(A,B):
"""
Compares two rectangles and return true if Area(A)>Area(B).
"""
area_A=(A[2]-A[0])*(A[3]-A[1])
area_B=(B[2]-B[0])*(B[3]-B[1])
if area_A>area_B:
return 1
elif area_A==area_B:
return 0
else:
return -1 | 2a5402c54efb6e7dba6c246322d9a0a5e2a0ab05 | 630,821 |
def randaugment(aug=None, is_training=True, **kwargs):
"""Randaugment."""
if aug is None:
aug = []
if is_training:
num_layers = kwargs.get('num_layers', 2)
prob_to_apply = kwargs.get('prob_to_apply', 0.5)
magnitude = kwargs.get('magnitude', None)
num_levels = kwargs.get('num_levels', None)
... | b73b21aab04af4adbec03a6cedbd47e78f60dac4 | 630,822 |
import torch
def adjacency_matrix_to_tensor_representation(W):
""" Create a tensor B[:,:,1] = W and B[i,i,0] = deg(i)"""
degrees = W.sum(1)
B = torch.zeros((len(W), len(W), 2))
B[:, :, 1] = W
indices = torch.arange(len(W))
B[indices, indices, 0] = degrees
return B | 7660f7f442c441df0cd75ec2a04a780a2f5560d8 | 630,823 |
def W2020_2021(number):
"""
The week of the year
Parameters
----------
:param number: A specific number
:type number: int
Returns
-------
:return: week of the year
:Examples:
>>> W200_2021("2020-S35")
"""
if (number == 53):
return "202"+str(number//54)+... | 0116b6f51056cf3dfaa7baaaddd005c45ac186ab | 630,824 |
def properties(mocker):
"""Fixture to handle mocking (get|set)_property calls."""
_mock_get = mocker.patch("ht.pyfilter.operations.zdepth.get_property")
_mock_set = mocker.patch("ht.pyfilter.operations.zdepth.set_property")
class Properties:
"""Fake class for accessing and setting properties."... | 70112f7dcd8d77f784f79eb087ab650f60feeeba | 630,825 |
def change_all_gains(odrv, axis, pct=0.5):
"""
Change all odrive gains by pct factor.
Mia lives here
"""
axis_config = axis.controller.config # shorten that
axis_config.pos_gain = axis_config.pos_gain * pct
axis_config.vel_gain = axis_config.vel_gain * pct
axis_config.vel_integrator_gai... | b431d7b431b024dfadb6147e9296f0ada8293c1f | 630,826 |
def inverse_weight(distance, num=1.0, const=0.1):
"""
权重函数: 距离的逆.
:param distance: 距离
:type distance: float
:param num: 分子
:type num: float
:param const: 常量
:type const: float
:return: 权重值
"""
return num / (distance + const) | 0b7b48245f7b3932233d236219bfebda168cb4a6 | 630,827 |
def make_metric_sorter(focused_metric):
""" Make sure the focused metric is the first one. """
def metric_name_for_sort(name):
if focused_metric == name:
return "!" + name
return name
def sort_key(key):
key, _ = key
return metric_name_for_sort(key)
return s... | 7b4f2d6e648b75093f666408ef14e807676537a7 | 630,828 |
def default_hive_settings():
""" Creates dictionary containing the default hive plot settings
"""
hive_settings = {}
hive_settings['dimension'] = 1000
hive_settings['output_file_path']='hive.svg'
hive_settings['draw_hive_plot'] = True
hive_settings['tick_marks'] = True
hive_settings... | 4a82ce003c2aa11618dac8e6cd720fee1e1da104 | 630,829 |
import os
def _get_hip_info(dir):
"""Search for HIP file upwards starting from dir. """
while dir:
f = os.path.join(dir, 'HIP')
if os.path.isfile(f):
return eval(open(f).read(), globals(), None)
dir = os.path.dirname(dir)
return { } | 5c5395d2226349d41d55324b76696e48e987e858 | 630,830 |
import random
import math
def normal_random(mean = 0.0, variance = 1.0):
"""
Samples from a normal distribution.
:param mean
The mean. Default is 0.0.
:param variance
The variance. Default is 1.0.
"""
while True:
v1 = 2.0 * random.random() - 1.0
... | 32ca649ade857a7d6c941de0c46031097ae85092 | 630,832 |
def increment(number):
"""Increases a given number by 1."""
return number + 1 | 945893837ce097eabe8791b1d15b5d85b21fda04 | 630,833 |
def _is_inside_polygon(x, y, polygon):
"""
Check if the given `x`/`y` coordinate is inside the given `polygon`.
>>> polygon = ((0.0, 0.0), (1.0, 0.0), (1.0, 1.0), (0.0, 1.0))
>>> _is_inside_polygon(0.0, 0.0, polygon)
True
>>> _is_inside_polygon(0.0, 0.5, polygon)
... #... | 3e6883430ea3a42ed8b0b27b62a351a67c60dc92 | 630,834 |
def pad_right(string, chars, filler="0"):
"""
Should be called to pad string to expected length
"""
numchars = chars - len(string)
tail = ""
if numchars > 0:
tail = filler * numchars
return string + tail | e00990d5051541a3dc451859075f330f41ec0c14 | 630,836 |
import logging
def get_logger(logger_name, logger_level, stream=None):
"""Get a logger for the script.
Using stream handler.
# Arguments
logger_name: `str`<br/>
the name of the logger
logger_level: `int`<br/>
the minimial level that trigger the logger.
str... | 153d0c1fe187f796ebfb5da29bd12fd3451cc44d | 630,837 |
def hamming_weight(n):
"""
Calculates the Hamming weight of a positive integer.
The Hamming weight of an integer is defined as the number of
1s in its binary representation.
"""
c = 0
while n:
c += 1
n &= n - 1
return c | 5dcf4a1fafd5bb98b91566abfb615c4412e0e050 | 630,838 |
from typing import List
def left_consec_search(pixel: List[int], bad_pixels: List[List[int]]) -> int:
"""Count number of consecutive bad pixels to the left of this pixel."""
prev_pixel = [pixel[0], pixel[1] - 1]
if (prev_pixel in bad_pixels) or (tuple(prev_pixel) in bad_pixels):
# print("prev_pixe... | 0bb2e383b7381e0721a1cc82c94943887d494cf1 | 630,839 |
def split_plus(line):
"""
Split a line according to the + (plus) sign.
:param line:
:return:
"""
new_line = line.split("+")
return new_line | 4f5cd478cd54124486a77a16dde9f979ec5bc9a9 | 630,840 |
def move_container_nodes(nodes, container):
"""
Remove container resources in the graph by replacing them with their
content. Parents and children are copied over to content.
"""
for c in container:
parents = [x for x in nodes if x.has_child(c) and x != c]
children = [ x for x in c.ge... | 04e92dddda6f047aaeed91cad3293ccd22975578 | 630,841 |
def _crc32(data, crc, table):
"""Calculates the 32-bit CRC value for the provided input bytes.
This computes the CRC values using the provided reversed form CRC table.
"""
crc = ~crc & 0xFFFFFFFF
for byte in data:
index = (crc ^ byte) & 0xFF
crc = (crc >> 8) ^ table[index]
ret... | c0f36d87e7c1e9750828df12735452dc1d67d785 | 630,842 |
def individual_summary_format(filename, summary_dict):
"""
@param filename: the pileup file name, the dict refers to
@param summary_dict: the summary dict of the pileup file
@return: a string that represent the summary dict : pileup_filename\nchange:percentage\tchange:percentage\t...
"""
summ... | c56270f018090903e4a3663c9d7e5b1ffc99e9d6 | 630,843 |
from typing import Union
from typing import Any
def get_keys_containing(obj: Union[dict, Any], key) -> set:
"""
Returns a set with the keys that contain `key`
Example:
.. code-block:: python
from quantify_core.utilities.general import get_keys_containing
dict_obj = {"x0": [1, 2, 3],... | bd608eb3457f49a15ca2a9f73b6b5ffd9fb27491 | 630,844 |
def getScore(predict, target, entity_vocab):
"""
@param:
:predict: (batch_size, seq_len)
:target: (batch_size, seq_len)
@return:
:accuracy: 正确率
:precision: 准确率
:recall: 召回率
:F1 :F值
"""
TP = 0 # 将正类预测为正类数
TN = 0 # 将负类预测为负类数
FN = 0 # 将正类预测为负类数
FP = 0 # 将负类预测为正类数
... | e96572e4cf049a68c2a622efcaa165bebeb786b0 | 630,845 |
def commonLeader(data, i, j):
"""Get the number of common leading elements beginning at data[i] and data[j]."""
l = 0
try:
while l < 255+9 and data[i+l] == data[j+l]:
l += 1
except IndexError:
pass # terminates
return l | 7b724aaff3c62be2fdd37e42677ef51a20c21f5d | 630,846 |
import torch
def assign_sample_weight(labels, weights):
"""
Assign weight for each sample
:param labels:
:param weights:
:return:
"""
return torch.FloatTensor([weights[t] for t in labels]) | ba134b4a558250ea3b01f3a7ac6ed0198c1e778a | 630,847 |
import re
def _validcas(cas):
"""
Validate a CAS Registry Number
See: https://en.wikipedia.org/wiki/CAS_Registry_Number#Format
:param cas: a string to be validated as a CAS Registry Number
:return: bool
"""
test = re.search(r'^\d{2,8}-\d{2}-\d$', cas)
# if format of string does not mat... | 43c7c7edb1ed640475e84f524f4697ed4ba7caab | 630,848 |
def get_plugin_name(plugin):
"""
Return the PyPI name of the given plugin.
"""
return 'taxi-' + plugin | 9002607babc935afe2096d667ed567c3b10e80f3 | 630,849 |
def common_clean_repeat_word(t_str: str) ->str:
"""常规清理连续重复的字。功能暂定,未使用。
t_str: 要清理的字符串。
return: 清理重复值之后的字符串。
"""
list_t_str = list(t_str)
for i in range(1,len(list_t_str))[::-1]:
if list_t_str[i] == list_t_str[i-1]:
list_t_str.pop(i)
return ''.join(list_t_str) | 45ec2e44b589aae38aa0acf40bf817ae38041604 | 630,850 |
import configparser
def load_env_vars(projPath):
"""
Load environment variables
:param projPath: project path
:type projPath: string
"""
environment = configparser.ConfigParser()
try:
environment.read_file(open(projPath+'/src/env/environment.cfg'))
except Exception as e:
print('Failed to load ... | 4d99f77ecbfcdc3c11e6c91f0680c742d00d8039 | 630,851 |
def créer_grille():
"""On génère la grille de coordonnées possibles,en représentant les
coordonnées par des set"""
grille=[]
#On démarre avec la colonne, coords x, qui varie de 100 à 1200 en laissant des
#espaces de 200
for i in range(100,1200,200):
#Puis les lignes, coords y, qui varie ... | 1233c61b700f441d65aa9f2572960242605698ea | 630,852 |
def remove_dup(noteList):
"""
This function removes duplicate notes from a note line, so that the same note is
not played twice on the same bar, in order to allow the other notes to be played.
noteList: A list of length 4 containing valid note sequences
"""
newList = []
for note in noteLi... | 2eba90c54535be13818133e61fa427436d58e4c1 | 630,853 |
def equal_2D_tables(table1, table2, tolerance=1e-6):
"""
This function will compare the values of two python tuples. First, if the values are below
eps which denotes the significance level that we care, no comparison is performed. Next,
False is returned if the different between any elements of the tw... | c79f235d9ff9ae35d2e55b6df0948612ab8ee978 | 630,854 |
from typing import Iterable
from typing import Tuple
def collate_first_dim(batch: Iterable) -> Tuple:
"""
:param batch:
:return:"""
return tuple(zip(*batch)) | 43ada9659d95ab54d565d38f91f422a891962a2e | 630,855 |
def static_candidates(*candidates):
"""Convenience function to provide candidates matching a prefix.
Returns a callable that can be used directly with ``Node.candidates=``.
>>> from cly.parser import Parser
>>> from cly.builder import Grammar, Node
>>> static_candidates('foo', 'bar')(None, 'f')
... | 4e1cb44cfe2a6b5124047c4c7a3b19eea7a405e9 | 630,856 |
def join_cols(cols):
"""Join list of columns into a string for a SQL query"""
return ", ".join([i for i in cols]) if isinstance(cols, (list, tuple, set)) else cols | 1f674411a06ce7365867d147ca4d96e10957ffd5 | 630,857 |
def matchBrackets(string: str):
"""
Separate the contents matching the first set of brackets from the rest of
the input.
"""
rest = string[1:]
inside = "("
while rest != "" and not rest.startswith(")"):
if rest.startswith("("):
(part, rest) = matchBrackets(rest)
... | 6e2dc8f82c9c366381b043f56c0812ec3ad6d552 | 630,858 |
def thrust_bearing(**kwargs):
"""
Analysis for the journal bearing
We only take keyword arguments to avoid problems with order of parameters
Parameters must be specified by name!
Parameters
----------
mu : float
Friction coefficient [-]
V : float
Contact velocit... | b9509fbac024844142e281faf6f260c9cbbc4a79 | 630,859 |
def _getParameterRange(key):
"""
Returns fur's default parameter range as 2-tuple (min, max).
key: fur attribute (string)
"""
if "Density" ==key: return (10000.0, 30000.0)
## geometry attributes (1) for single strand
if "Length" ==key: return (1.00, 5.00)
if "BaseWidth"==key: return ... | c1ae671671c4bf79abe7675b5e6755730f886823 | 630,860 |
def _read_binary_data(fp, size, name, clip=False):
"""Read zero-padded binary data from a file.
Attempts to read `size+1` bytes from filehandle `fp`. If 0 or more than `size`
bytes are read, raises an IOError. Data of any other size is returned to the
caller, followed by enough zero padding to yield `size` byt... | 9c21d1f5e74abd239bd1c6cd1547d31ac2cfdb77 | 630,861 |
def get_list_of_occlusion_positions(heatmap_size_i, occlusion_size_i):
"""generate a list of all occlusion positions with stride 2.
The stride of 2 is something we decided to guarantee reasonable compute time.
Args:
heatmap_size_i: size of heatmap
occlusion_size_i: size of occlusion
... | dd1a3849eff5f64fd7bb71e07fac43163246a325 | 630,863 |
from typing import Counter
def create_vocabulary(text, max_vocab_size = 2000):
""" Create Vocabulary dictionary
Args:
text(str): inout text
max_vocab_size: maximum number of words in the vocabulary
Returns:
word2id(dict): word to id mapping
id2word(dict): id to word mapping... | cded9fd750fd2b778e45ff4565f609f99871187f | 630,864 |
def stop_when_true(test_expr, result_expr, seq):
"""
feed elements into expr until it returns True, returning that element (None otherwise)
:param test_expr: callable of 1 arg that returns True/False
:param result_expr: callable of 1 arg; takes found element from test_expr
and maps it to a fina... | 53c21af40780a41d06619a758cf5b05e8fb6d0d5 | 630,866 |
def get_user_version(conn):
"""Return user_version value."""
result = conn.execute('PRAGMA user_version')
return result.fetchone()[0] | 46c1f4d7f25d3af84014f03491e194ad19cd410d | 630,867 |
import socket
import os
def default_email_address():
"""
Get the hostname and username of the user running this
program. This provides a default email from address.
OUTPUT:
string
EXAMPLES::
sage: sage.server.notebook.sage_email.default_email_address()
'...@...'
"""
... | 2e15ee34fbeb1c5a40d0193328d404fbf4285dc9 | 630,868 |
def tensorize_data(data, kept_columns, numeric_columns, categorical_columns, index_map, feature_bag):
"""Tensorize data so that they can be consumed by Tensorflow dataset API. """
indices_name = f'{feature_bag}_indices'
values_name = f'{feature_bag}_values'
tdata = data.filter(kept_columns, axis=1)
... | d33424b71a8ac5e35c3e0c65f753bd691e978bf8 | 630,869 |
def tupadd(a, b):
"""
Performs a tuple addition of a and b.
Args: a and b can either be 1) scalars (i.e. single coordinate) or 2) elementary tuples
Any argument that is a tuple (assumed elementary; i.e. all its elements are scalars) is unpacked as can be seen
below.
As far as the author knows, this function ca... | c5b42d3bb58da20aaa516f0f3891a8d4fe1a0194 | 630,870 |
from datetime import datetime
def get_stock_mtime(symbol: str, timestamp: int, ser):
"""获取分时数据"""
date_array = datetime.utcfromtimestamp(timestamp)
date = date_array.strftime("%Y%m%d")
df = ser.get_history_transaction_data(symbol, timestamp)
data = []
if len(df):
for i, row in df.iter... | 88913ddcff263c5f27bbf81bc51dd2463a5509b9 | 630,872 |
def remove_orphan_columns(columns):
"""Remove any columns that are full subsets of another column."""
remove = []
for k in columns:
values = columns[k]
if any([all(val in columns[j] for val in values) for j in columns if j != k]):
remove.append(k)
return {k: columns[k] for k... | 29bd5d40160a5a7636e0e51a471aacc2723cb563 | 630,873 |
def as_dict(model):
"""return the model field+values as a dict"""
return {
fld.name: getattr(model, fld.name)
for fld in model._m.fields
} | 274de22502609788a1498d3c142b6bbd645b9ee0 | 630,874 |
def validate1(s, a):
"""validate1(s, a): list comprehension with a.index"""
try:
[a.index(x) for x in s]
return True
except:
return False | 8cace53da5ce67406a629b0e209d5a1085b92582 | 630,875 |
def object_from_args(args):
"""
Turns argparser's namespace into something manageable by an external library.
Args:
args: The result from parse.parse_args
Returns:
A tuple of a dict representing the kwargs and a list of the positional arguments.
"""
return dict(args._get_kwargs... | e48c0a8a49e4fe106d30d37f03c11a07e479cfc3 | 630,876 |
import torch
def prep_observation_for_qnet(tensor, use_amp):
""" Tranfer the tensor the gpu and reshape it into (batch, frame_stack*channels, y, x) """
assert len(tensor.shape) == 5, tensor.shape # (batch, frame_stack, y, x, channels)
tensor = tensor.cuda().permute(0, 1, 4, 2, 3) # (batch, frame_stack, ch... | 5ef7fde51576c34a2a87c91dabdbd0ac39f3c520 | 630,877 |
import numpy as np
def get_column_data(diag_filename):
"""Get all columns of data from a diagnostic file."""
data = None
# Open up the file for reading. Get the names of the columns, as well as a 2D list
# with all the data.
diag_file = open(diag_filename, 'r')
vc_line = 'git'
# Skip... | 7a5480661fc750dc98b2ca7ae2a3a8159538b39a | 630,878 |
def _get_person(rachio):
"""Pull the account info of the person whose access token was provided."""
person_id = rachio.person.getInfo()[1]['id']
return rachio.person.get(person_id)[1] | d67186473a91b805e264dbdb0b61f61938683965 | 630,879 |
def get_storage_blob(bucket, source_folder_name, source_file_name):
"""
Fetches and returns the single source file blob from the buck on
Google Cloud Storage
"""
source_path = source_file_name
if source_folder_name != '':
source_path = f'{source_folder_name}/{source_file_name}'
blob ... | aa84facc8752a591b4f25e3832cb8cff64c498ba | 630,880 |
def usage():
"""Print Usage Statement.
Print the usage statement for running stream.py standalone.
Returns:
msg (str): Usage Statement.
Example:
>>> import stream
>>> msg = stream.usage()
>>> msg
'stream.py usage:\n$ python stream.py "<YOUR_STREAM_URL>"'
"... | 5c39da3129dcfd01f61028808bd27c043508b6b8 | 630,881 |
def two_sum(numbers, target):
"""
Parameters
----------
numbers : list
a list of integers
target : int
the target sum
Returns
list
a list of indices
-------
>>> two_sum([2,7,11,15], 9)
[0, 1]
"""
num_index_map = {}
for idx, num in enumerat... | cdf62b9bb49a8556c1c5a52b442c41445d073c0f | 630,882 |
def _to_camel_case(text: str) -> str:
"""
Convert a text in snake_case format into the CamelCase format
:param text: the text to be converted.
:return: The text in CamelCase format.
"""
return "".join(word.title() for word in text.split("_")) | 9cc3edb514a0351cd4de752132627bf32f5f5ee9 | 630,883 |
def largest_prime_factor(number):
"""
Calculate the largest prime factor of a number
:param number: Number of which largest prime should be found
:return: Integer: largest prime factor
"""
count = 2
while count * count <= number:
if number % count:
count += 1
else... | c6dce3a9ac9497ae4a5a6358111031fd82e58b33 | 630,884 |
def path2Extension(path):
"""Answers the file extension of path.
>>> path2Extension('/xxx/yyy/zzz/Agency_FB-Compressed.ufo')
'ufo'
>>> path2Extension('/xxx/yyy/zzz/Agency_FB-Compressed.TTF')
'ttf'
"""
return path.split('.')[-1].lower() | 625345b0787426f45e11f36a0c499b6cac981029 | 630,885 |
import hashlib
import json
def get_cache_key(args, kwargs):
"""
Returns a cache key from the given kwargs
This is simply a sha256 hexdigest of the keyword arguments
Args:
kwargs (dict): the arguments to build a cache key from
Returns:
str: the cache key
"""
sha = hashlib... | 44bea88164addbeb830d14cdf640e5e31a114d90 | 630,886 |
def text(node):
"""Extract text from an XML node."""
if node is None: return ''
s = ''.join(node.itertext())
return ' '.join(s.split()) | 30dc94cb3785b6553149911dc7696f10c0969dcb | 630,887 |
import functools
def noexit(func):
"""If argparse or arvados_fuse tries to exit, fail the test instead"""
class SystemExitCaught(Exception):
pass
@functools.wraps(func)
def wrapper(*args, **kwargs):
try:
return func(*args, **kwargs)
except SystemExit:
ra... | 70ee600d8200db22e5e8c665671586119bf9285a | 630,888 |
import json
def getAllLineProfile(pathToJson, fileName):
"""
Args:
fileName: name of input admit result file (String)
Retuens:
all information on all identified molecular lines (nested list)
"""
with open(pathToJson + fileName, 'r') as jsonFile:
allResult = json.load(jsonFi... | ae4a0ba0251cbeebe07efa7270ae13bc86a5398e | 630,889 |
from typing import AnyStr
def ensure_bytes(value: AnyStr) -> bytes:
"""Convert text into bytes, and leaves bytes as-is."""
if isinstance(value, bytes):
return value
if isinstance(value, str):
return value.encode('utf-8')
raise TypeError(f"input must be str or bytes, got {type(value).__... | 74c0662b4988e34069b6065bb26f0f9d43af7cc0 | 630,891 |
import re
def is_valid_snaprule_name(snap_rule_name):
"""
Validates a snapshot rule name.
A snapshot rule name identifies a particular volume being attached to
a particular snapshot policy. A valid snapshot rule name should look
like: snaprule-00000001 - It should always start with "rule-" and end... | 3bb81a52cb24a63703bcaaa6a6246a92baccd01d | 630,892 |
import os
import base64
def verify_auth(authorization):
"""Verifies the given authorization header value"""
username = os.environ['AUTH_USERNAME']
password = os.environ['AUTH_PASSWORD']
token = base64.b64encode('{}:{}'.format(username, password).encode())
return authorization == 'Basic ' + token.... | 803bebc757096b6a2af4f00f8aedfeca1daaff43 | 630,893 |
import json
import numpy
import logging
def read_out_model(filename):
"""
Read out previously computed model and its details
:param filename: path to teh stored model
:return: dict with params and dict with training details
"""
with open("{}".format(filename), "r") as input_model:
try:... | f42dc670dd7dee8395b4228b2129fc6be9d10dce | 630,895 |
def card_deck(*cards)->str:
"""turn a list of bootstrap cards into an equally spaced card deck.
Example:
to_html.card_deck(to_html.card("card1"), to_html.card("card2"))
"""
cards = list(cards)
cards = "".join(cards)
return f"""
<div class="card-deck">
{cards}
</div>
""" | 31905ee9ccf8938a4e4c605f8f87a729fd2980db | 630,896 |
def add_suffix(suffix, name):
"""Adds subfix to name."""
return "/".join((name, suffix)) | fd4eb00c0468f39f59bbbce677e56e10c186aea5 | 630,897 |
def get_source_files_count(results, repository):
"""Perform some magic to get number of source files."""
# all metainformations about source files
source_files = results.source_files[repository]
if len(source_files["extensions"]) == 1:
return source_files["count"]
elif "py" in source_files[... | e95f80e403bb236225543bdbab11eacbf2da7020 | 630,898 |
def game(guess, answer):
"""
:type guess: List[int]
:type answer: List[int]
:rtype: int
"""
time = 0
for i in range(0,3):
if guess[i] == answer[i]:
time+=1
return time | a63ad3c9c0c368a9f1025891c1d64e36d78fa0ef | 630,899 |
import uuid
def generate_id():
"""
Generates a random uuid
"""
return uuid.uuid4().hex | c1186d1856297183ad3adf4e5ab1117209241f3a | 630,900 |
from typing import Union
from typing import List
from typing import Tuple
from typing import Iterable
def flatten(lst: Union[List, Tuple]) -> List:
"""Recursive function that flatten a list (of potential `Iterable` objects)."""
if isinstance(lst, Iterable) and not isinstance(lst, (str, bytes)):
return... | f007f78f8b8b1e3bef9ce70550efdbfb8362539c | 630,901 |
from pathlib import Path
def test_data_file(filename):
"""Gets path to a Konfigenetes file"""
return str(Path(__file__).parent / 'test_data' / filename) | 81c72807f37819eabe88996f23a8bb79af8dabf4 | 630,902 |
import re
def strip_ws(string: str):
"""
Strip whitespace off a string and replace all instances of >1 space with a single space.
"""
return re.sub(r'\s+', ' ', string.strip()) | 1410dfbd1a9a30a4351d3fc01962f208401f928e | 630,903 |
def nest(function, n):
"""
fp::nest(f,n) returns the n-fold repeated composition of the function f.
Thus, given the function f, fp::nest returns the identity function
id if n is 0 and otherwise the function
Return f(f(f(f..f(x))))
Note: Function taken from Matlab Mupad DOC
http://www.mathw... | 3ce5eaa73263fb6b540c572986954cd9bd494daf | 630,905 |
def try_lower(string):
# Ask for, forgiveness seems faster, perhaps better :-)
"""Converts string to lower case
Args:
string(str): ascii string
Returns:
converted string
"""
try:
return string.lower()
except Exception:
return string | 7b48401d4aaf4ae5a99b3a2d9ee5869c07726156 | 630,906 |
import tempfile
import os
def _mkfifo(active_fifos={}):
"""
Return a pair of a new fifo' filename and a cleanup function.
"""
fifo_dir = tempfile.mkdtemp()
fifo = os.path.join(fifo_dir, 'fifo')
os.mkfifo(fifo)
def rm():
del active_fifos[fifo]
os.remove(fifo)
os.rmd... | 6324ed223aa64761ab94a9a6d4c79d84923f50e2 | 630,907 |
from pathlib import Path
import random
import string
import subprocess
def extract_tar(tmpdir):
"""
Extract the given TAR archive to a temporary directory
and return the path to allow the TAR archive's contents to be inspected
"""
root_path = Path(tmpdir) / "TARs"
root_path.mkdir(exist_ok=True... | 46fdf238ce40135455cc52e37004490e66417522 | 630,909 |
def concatenate_rounds(rounds1, rounds2):
"""Return a list of rounds that combines `rounds1` and `rounds2`."""
return rounds1 + rounds2 | 5c437693cd6c2b742edf56ed081cc0c3f9dae693 | 630,911 |
import torch
def coco_category_to_topology(coco_category):
"""Gets topology tensor from a COCO category
"""
skeleton = coco_category['skeleton']
K = len(skeleton)
topology = torch.zeros((K, 4)).int()
for k in range(K):
topology[k][0] = 2 * k
topology[k][1] = 2 * k + 1
t... | 719fa758c2e4361e9a5d4c0509fe073f42df8630 | 630,912 |
import sys
def run_as_contextmanager(ctx, fn, *arg, **kw):
"""Run the given function under the given contextmanager,
simulating the behavior of 'with' to support older
Python versions.
"""
obj = ctx.__enter__()
try:
result = fn(obj, *arg, **kw)
ctx.__exit__(None, None, None)
... | bc4c1bc0bdf5d00b080cfbe480c1b6fcdcc9cee9 | 630,913 |
def pluralize_type_designator(designator):
"""
:param designator: the XNAT type name or synonym
:return: the pluralized type designator
"""
if designator == 'analysis':
return 'analyses'
elif designator.endswith('s'):
# No examples of this (yet), but play it safe.
return ... | d564dc991bb005de574bd65c5ad92fc6fac40a87 | 630,914 |
import random
def draw(coups):
"""
Coup aléatoire au chifoumi
pas d'arguments
"""
coup = random.choice(coups)
return coup | d359495674e6aa0305c5f71f346194e376b6b96e | 630,915 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.