content stringlengths 35 416k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def notify_owner(func):
""" A decorator for mutating methods of property container classes
that notifies owners of the property container about mutating changes.
Args:
func (callable) : the container method to wrap in a notification
Returns:
wrapped method
Examples:
A ``_... | 89f2ca3cdc870b60abef78226a14a4a982c58e24 | 641,745 |
import socket
import time
def check_connection(
ipv4_addr: str,
port: int,
timeout_secs: float = 3.0,
retries: int = 1,
retry_delay: float = 1.0,
raise_error: bool = False) -> bool:
""" Check if remote TCP connection is possible
:param ipv4_addr: remote ipv4 add... | 42ee0574611faf553eb1a0dad95b3731deb764b8 | 641,747 |
def close_time(km,brevet_distance):
"""
input:
km
brevet_distance is one of the standered distances
200,300,400,600,1000 km
output:
Closing time in minutes
"""
## brevet_dict[brevet_distance]=[max_time,min_speed]
brevet_max = { 200:810, 300:1200,400:1620,600:... | b357c8b003df71dda1808af0458cebac8e9cd6c9 | 641,748 |
import re
def remove_url(_text: str) -> str:
"""Reference:
http://www.noah.org/wiki/RegEx_Python#URL_regex_pattern
"""
_text = re.sub(r'http[s]?:\/\/(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\(\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+', '', _text,
flags=re.MULTILINE)
_text = re.sub(r'\s+$', '', _... | 0d55a0af066ba72a6e51e9e0616a6f6c36642884 | 641,749 |
from itertools import islice, repeat, takewhile
from typing import Iterator
def ichunks(array: bytes, chunk_size: int) -> Iterator[bytes]:
""" Split and yield chunks of the given size.
"""
idata = iter(array)
return takewhile(bool, (bytes(islice(idata, chunk_size)) for _ in repeat(None))) | c572e11078d68dc3cd8be7beeb5ddd6165082931 | 641,750 |
def mapped_columns(*column_maps):
"""
Given any number of column_maps
return a list of unique column names
"""
result = set()
for column_map in column_maps:
result |= set(column_map.values())
return list(result) | e354cedd60daa6a22b8d52256c916bf0ef46d4df | 641,751 |
def transform_map(kfun=lambda x: x, vfun=lambda x: x):
"""
Function that takes two functions as arguments and returns
a function that applies those functions over all of the
keys and values in a map and returns the transformed version
of the map.
kfun: function applied to all keys (default iden... | 5302a1ddd70bdc94014700f663ebd91d85b8a567 | 641,752 |
def _compute_offset(page: int, items_per_page: int) -> int:
"""Compute the offset value for pagination.
Args:
page (int): The current page to compute the offset from.
items_per_page (int): Number of items per page.
Returns:
int: The offset value.
"""
return int(int(int(page)... | 6510936de2eb45ede1ac1b68735e68450d84262e | 641,754 |
from typing import Optional
from typing import Tuple
def split_list(csv_string: Optional[str] = None) -> Tuple[str, ...]:
"""Split the given `csv_string`, returning a list of its entries."""
entries = (csv_string or "").split(",")
return tuple(entry for entry in entries if entry.strip()) | 0b7216be3f187251bd69b1cb326595cbb9c8fc7b | 641,755 |
def insertSort(nums):
"""
插入排序:稳定排序
"""
size = len(nums)
for i in range(1, size):
while nums[i] < nums[i-1] and i > 0:
nums[i], nums[i-1] = nums[i-1], nums[i]
i -= 1
return nums | 654cab41c45d87f5a1b38d6b14beb32b1c9b7d95 | 641,756 |
import sys
def get_class( kls, path_adj='/.' ):
"""Returns a class for the given fully qualified class name, *kls*.
Source: http://stackoverflow.com/questions/452969/does-python-have-an-equivalent-to-java-class-forname"""
sys.path.append(sys.path[0]+path_adj)
parts = kls.split('.')
module = ".".join(parts[:-1])... | ae4f6e7933d3f239f219b392fabba2246071f2e0 | 641,757 |
def ls_rindex(ls, val, start=None):
"""
获取list中最后出现元素val的位置
"""
if start is None:
start = len(ls) -1
for i in range(start, -1, -1):
if ls[i] == val:
return i | 9a18e38dd937dd5ac8c1205c102f791d3372e0a1 | 641,758 |
def check_palin(s):
"""
This is `Open-Palm's` function that checks if elements of
a given list of strings `s` is a palindrome or not.
The input `inp` is a tuple containing a single
element.Therefore only the
first (0 th argument) is accessed.
The first argument of the tuple i.e `s[0]`.
s... | e9dfc9de0ba2b8da635148fa554c8868ce18448b | 641,759 |
def _positions(field):
"""Given an index into the puzzle (i.e. a single field, calculate and return
a 3-tuple (row, column, box) of the units the field belongs to.
"""
row = field // 9
column = field % 9
box = (field // 3) % 3 + 3 * ((field // 9) // 3)
return row, column, box | 1ff7da9c5adc95035351af31a8fa9e7f4edace3b | 641,760 |
def second():
"""Second resource
* GET: return "SECOND"
"""
return {'result': u'SECOND'} | e39febeb1feafec3c9f9d29a37bd1347440dac79 | 641,761 |
def intersect(keywords1, keywords2):
"""
:param keywords1: list of kw from model 1
:param keywords2: list of kw from model 2
:return: common keywords list
"""
intersect = set(keywords1) & set(keywords2)
keywords = list(intersect)
return keywords | 22f4e43092e0619e5e2e79454aca6d255dba0bdf | 641,762 |
def S_linear_model_data(_data_list):
"""
Returns linear regression model of data samples
"""
ds = len(_data_list)
if ds < 2:
return -1
r_data = []
x_val, y_val = list(zip(*_data_list))
x_val_sum = sum(x_val)
y_val_sum = sum(y_val)
x_val_power = [i*i ... | b91fbedcb7ae8d6113bd604961d319607cec6432 | 641,763 |
import subprocess
def run_user_command(command):
"""Use subprocess to run the user's command. Returns the STDOUT, STDERR, and the Exit Code as a tuple."""
proc = subprocess.Popen(command,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
... | b0a48f84fdd3bafc1cc26a9239cfb102a0d7036e | 641,764 |
def get_object_instances(predictions, target, confidence):
"""
Return the number of instances of a target class.
"""
targets_identified = [
pred for pred in predictions if pred['label'] == target and float(pred['confidence']) >= confidence]
return len(targets_identified) | a181500085ce2cd496e661f78cc2d54a965ae9bc | 641,765 |
def get_gid_ignore_list(inputfile):
"""Input a file with a list of geneids to ignore when normalizing across taxa
Each line should have 1 geneid on it.
Use '#' at the start of the line for comments
Output a list of geneids to ignore.
"""
# Don't convert GIDs to ints,
# GIDs are not ints for ... | eeb5130bf60e29ce6509adfdf33db0869112b931 | 641,766 |
def create_and(wlk, tree):
"""
Creator for And and other simple attributes. No walking needs to be done,
so simply call the applier function.
"""
result = []
wlk.apply(tree, result)
return [result] | a37be54fff0a01978f93454df44892e732796a30 | 641,767 |
def listify(x):
""" Coerce iterable object into a list or turn a scalar into single element list
>>> listify(1.2)
[1.2]
>>> listify(range(3))
[0, 1, 2]
"""
try:
return list(x)
except:
if x is None:
return []
return [x] | 656074864ae3795f3755a3d16964ea9779486fc3 | 641,768 |
import numpy
def gaussian_psf(fwhm, stampsz=19, deriv=True, shift=[0, 0]):
"""Create Gaussian psf & derivatives for a given fwhm and stamp size.
Args:
fwhm (float): the full width at half maximum
stampsz (int): the return psf stamps are [stampsz, stampsz] in size
deriv (bool): return ... | 621275be666c0c97aa4a353cae9439c85bd63385 | 641,770 |
from bs4 import BeautifulSoup
import re
def parse_course_detail(html):
"""
Use beautifulsoup to get detailed information of one course, then put them
in a dictionary.
"""
soup = BeautifulSoup(html, 'lxml')
table = soup.find_all('span', attrs = {'id': re.compile("^u2(45|54|63|72|81|90)_line\d.?... | c8ad8f6db72133bf8f9bd1dde1d60d094481f45c | 641,772 |
def _regmeta_instance_factory(cls, name, *args, **kwargs):
"""
:param cls(RegisteryMeta): registration meta class
:param name(str): name of class that needs to be instantiated
:param args(Optional(tuple)): instance positional arguments
:param kwargs(Optional(dict)): instance named arguments
:ret... | 37ac0812d13954cfadb487712c45dd397bfc1ae5 | 641,773 |
def strip_extra_whitespace(s):
"""Replace repeating whitespace chars in a string with a single space.
Search for repeating whitespace chars in a string and replace them with
a single space.
Args:
s (str, utf-8): original string to be stripped of whitespace.
Returns:
A string withou... | b959b01cb8a1bf40d7077f5540d8016dc9bcc57c | 641,774 |
def EncodeAName(s):
"""
Handle * characters in MSI atom names
"""
if s.find('auto') == 0:
s = s[4:]
# If the atom name begins with *, then it is a wildcard
if s[:1] == '*': # special case: deal with strings like *7
return 'X' # These have special meaning. Throw away the inte... | 1da5a852fd3416d348c975ae02678aa4bd7d8f0c | 641,775 |
import os
def profiles():
"""This function can also be a variable
Example:
profiles = ["profile1", "profile2"]
"""
demo_profiles = [
"alita",
"lotr",
"test_noexist",
"test_noapps",
"test_badapps",
]
user_profiles = os.getenv("MY_PROFILES", "... | 7e105fbf2cd1b92077e00261d89536f80b4c5bfe | 641,776 |
from typing import Tuple
import ipaddress
def _seperate_ip_netmask(ip: str) -> Tuple[str, str]:
""" convert a 192.168.1.0/24 address to a 192.168.1.0 255.255.255.0 address"""
net = ipaddress.IPv4Network(ip)
return str(net.network_address), str(net.netmask) | be581407b168379051e712393862262a830c4aa8 | 641,777 |
import os
def write_as_ascii(list_dic):
"""
Write all results as text file
"""
n_dic = len(list_dic)
if not os.path.exists('output'):
os.mkdir('output')
for i_dic, dic in enumerate(list_dic):
filename = 'output/Poly-n{0}.txt'.format(dic['n'])
list_col = []
xi =... | d39140281d9a771f77d1634ab585968daf163938 | 641,778 |
def get_admission_rules(data, scope):
"""Get admission control rules."""
args = {}
if scope == 'fed' or scope == 'local':
args["scope"] = scope
rules = data.client.show("admission/rules", "rules", None, **args) # show(self, path, obj, obj_id, **kwargs)
return rules | b9c0fd2fbc7550c560a9c75af1573d4317c99b72 | 641,779 |
import requests
def get(param):
"""
@param Request Parameter
@return String
"""
try:
r = requests.get(f"https://akaneko-api.herokuapp.com/api/{param}").json()
except Exception as e:
raise Exception(f"ERROR: > {e}\n\n\nPlease Contact Raphiel#8922 or Open a Issue in https://gith... | 55203fd310d899bd8c8ee39d8d940600f4599902 | 641,780 |
def acquire(filename):
"""Return a grid of integers by parsing a file."""
grid = []
with open(filename) as f:
for line in f:
grid.append([int(x) for x in line.split()])
return grid | e8d13595e5f134f8312840a87331aa9f7da8f45b | 641,781 |
def determine_well_width_tolerance(mean_width):
"""
Determine the tolerance by which well widths are determined to be nearly equal.
Fitted to a polynomial trend line for the following data of (mean, tolerance) pairs::
(100, 0.11), (60, 0.13), (50, 0.15), (25, 0.25), (5, 0.50), (1, 0.59)
Args:... | f1202993fc09ad2d923e3efedbd51cc2ae39bfcb | 641,782 |
import os
def connect_string():
"""
Retrieves a valid connection string from the environment and
returns it.
"""
try:
connect_string = os.environ["INSTANCE_CONNECTION_NAME"]
except KeyError:
raise KeyError(
"Please set environment variable 'INSTANCE_CONNECTION"
... | 69dcd89a38a3b3d6f2766e20771962f23740935f | 641,783 |
def to_unsigned_byte(num):
"""
Convert given signed byte number to byte number.
:param num: Signed number in range from -128 to 127.
:return: Unsigned byte number in range from 0 to 255.
"""
assert -128 <= num <= 127, 'Value out of range (-128 - 127)!'
ret = num if num >= 0 else (256 + num... | 35e52293399326fa1ef124da4d50e2a5363fcd81 | 641,784 |
def _check_requires(state, node, statespace, constraint):
"""Checks if usage of overflowed statement results in a revert statement"""
instruction = state.get_current_instruction()
if instruction['opcode'] is not "JUMPI":
return False
children = [
statespace.nodes[edge.node_to]
... | bb2e1a5e751f04f7977a411b2f237e8559e42511 | 641,785 |
import string
import random
def generate_random_string(
string_length=88,
chars=string.ascii_lowercase + string.ascii_uppercase + string.digits,
remove_confusing_digits=False):
"""
Generate a random string.
:param string_length:
:param chars:
:param remove_confusing_digits:... | d2ba6bfa407cbe71a8fc65d3350956b1ab51b35a | 641,786 |
def get_engagement_rate_min(selectpicker_id: str) -> int:
"""
Min-Delegate-target of get_engagement_rates_min_max (dac-pattern)
:param selectpicker_id:
:return: int -> min-value of engagement-rate
"""
min_values = {
"1": 0,
"2": 1,
"3": 2,
"4": 3,
"5": 4,... | d9cab14aa84b82cbe6b00d7470185f0353d4c84a | 641,787 |
def total_job_cost(labor, paint_cost):
""" Function that will return the total cost of a job """
return labor + paint_cost | c8bbf29fafcf7f0a4205c9020585e141927c6b97 | 641,788 |
import argparse
def __cli():
"""Command line interface.
:returns: CLI arguments
:rtype: <argparse.Namespace>
"""
desc = "DNA assembly using BASIC on OpenTrons."
parser = argparse.ArgumentParser(description=desc)
# Specific options for collecting settings from command line
subparsers ... | ff88c5dc13ba91e0d78b330c4a495ab9a27ecc7c | 641,789 |
from typing import Counter
def calculate(text_input):
"""
return a dictionary with lowercase letters for keys and counts for values
"""
counter = Counter()
for text in text_input:
counter.update(''.join(c for c in text.lower() if c.isalpha()))
return dict(counter) | 485011f59ff32169f51bc87337fe9d642181f87d | 641,791 |
def encode(batch, tokenizer, max_len):
"""
This function takes in a batch and a tokenizer and outputs encoded batch
"""
return tokenizer.encode_plus(
batch, None, add_special_tokens=True, max_length=max_len, pad_to_max_length=True
) | 395d9af6bbdbe0cf8c8bd90887f43c03b460e636 | 641,792 |
def retrieve_fields(arg: str) -> str:
"""Strip and filter out the empty elements from the string.
:type arg: ``str``
:param arg: The string from which we want to filter out the empty elements.
:return: Filtered out result.
:rtype: ``str``
"""
return ",".join([x.strip() for x in arg.split... | 2cb27d992180003c8c75ac0f5621544c8da8c020 | 641,793 |
def get_cz(mag):
"""
Returns the amount of magnetization along z.
Parameters
----------
mag : ndarray
Magnetization vector.
Returns
-------
magz_a, magz_b : float
Amount of magnetization in state a and b along z.
"""
magz_a = mag[2, 0]
magz_b = mag[5, 0]
... | e1a8625fa02845b4bf6ad7c5bc6b7dcddd823b4f | 641,794 |
import json
def _ConvertConfigParams(config):
"""Converts numeric sequences into comma-separated string representations."""
updatedConfig = {}
# Non-Cloud API expects that pyramiding policy is a JSON string.
if 'pyramidingPolicy' in config:
updatedConfig['pyramidingPolicy'] = json.dumps(config['pyramiding... | 80626ff0ea48c9ce89f6b30f809da2c1d026d4c8 | 641,795 |
def is_array(space, w_obj):
""" Finds whether a variable is an array"""
return space.wrap(w_obj.tp == space.tp_array) | 9c9b027e1d06c531d12383c6e36f9beff1b45fd3 | 641,796 |
import torch
def cho_log_det(cho_C):
"""Compute tensor log determinant of $C$ from cholesky factor.
----
Parameters:
cho_C: lower triangular tensor where cho_C cho_C^T = C
----
Outputs:
C^{-1}
"""
return 2.0 * torch.sum(torch.log(torch.diagonal(cho_C))) | f6152dda48c9e81f305bdb1d1339d5dcc44ab145 | 641,797 |
import string
def make_file_name(song):
"""Returns a valid file name for a song object."""
valid_chars = "-_.() %s%s" % (string.ascii_letters, string.digits)
fname = '{} - {}.mp3'.format(song.name.encode('utf8', 'replace'),
song.artist.name.encode('utf8', 'replace'))
f... | b29f1002a8547a7bce9aa20fc77561828bac766d | 641,798 |
def reflux_mass(P_mass, R):
"""
Calculates the flow rate of reflux.
Parameters
----------
P_mass : float
The mass flow rate of distilliat, [kg/s]
R : float
The reflux number, [dismensionless]
Returns
-------
reflux_mass : float
The flow rate of reflux, [kg/s]
... | c5bf7daa556fcb564ed2bc989a74b2ee7dc1865d | 641,799 |
def get_base_branch(cherry_pick_branch):
"""
return '2.7' from 'backport-sha-2.7'
"""
prefix, sep, base_branch = cherry_pick_branch.rpartition('-')
return base_branch | 5b91a8f3a6cf44306abfff24ba2c771d8c3772c0 | 641,800 |
def planetary_temp(S, A, L=1.0):
"""Calculate the planetary temperature.
SL(1-A) = sT**4
Arguments
---------
S : float
Incident solar energy.
A : float
Planetary albedo.
Keyword Arguments
-----------------
L = 1.0 : float
Normalised stellar luminosity.
"... | 3ba2c791c0dfa0e284bc2a6deff5d2cd6ef859a8 | 641,804 |
import torch
def batch_index_select(x, idx):
"""
:param x: *, n, Dim
:param idx: *, k
:return: *, k , Dim
"""
idx_ = idx.unsqueeze(-1).expand(idx.shape + (x.shape[-1],))
return torch.gather(x, -2, idx_) | ee0c68e683366bc2a887748d289c6ef52223a297 | 641,805 |
def draw_frame(surface, rect, color_fill, color_border, border=1):
"""
Creates and draws a rect with a frame. Returns the inside rect object.
returns a pygame.Rect() object, which is the filled area inside the frame
- surface: the pygame surface to draw this on
- rect: pygame.Rect() object for the o... | 2b37a96beb6d1c4d0aa184e677f6c8528b90193e | 641,806 |
def get_midi_info(pm):
"""Return useful information from a MIDI object."""
if pm.time_signature_changes:
pm.time_signature_changes.sort(key=lambda x: x.time)
first_beat_time = pm.time_signature_changes[0].time
else:
first_beat_time = pm.estimate_beat_start()
tc_times, tempi = pm... | 8423dce0446626edc78e65a5523d57ba449ae867 | 641,807 |
def _eval_expr(expr, ctxt, vars=None):
"""Evaluate the given `Expression` object.
:param expr: the expression to evaluate
:param ctxt: the `Context`
:param vars: additional variables that should be available to the
expression
:return: the result of the evaluation
"""
if... | 20c3fc9d2a8a4f61ea72d6df3474e034c6369d7e | 641,808 |
def obey_support(strategy, support):
"""
Test if strategy obeys its support
"""
for index, value in enumerate(strategy):
if index in support and value <= 0:
return False
elif index not in support and value > 0:
return False
return True | 22f25b3a536a043a5280460e5cb967389fc4001f | 641,809 |
def list_depth(l):
"""Return the depth of the FIRST (0) element of lists inside lists."""
if type(l) is list:
if len(l) > 0:
return 1 + list_depth(l[0])
else:
return 1
else:
return 0 | 2a49332abd42336e8d0e2f009ee1e0c85721276e | 641,810 |
def datetime(anon, obj, field, val):
"""
Returns a random datetime
"""
return anon.faker.datetime(field=field) | 7cd3d19024050f1a2e0d6912ef0824c632e0feb4 | 641,811 |
import argparse
def parse_command_line():
"""
Parse the command line.
Returns:
Namespace: The parsed command line container.
"""
parser = argparse.ArgumentParser()
parser.add_argument("bin", type=argparse.FileType("r"),
help="The new binary to size")
pars... | 6a5f2caad891b1aed340333765bdc625e0fe4124 | 641,812 |
import builtins
def mid(x, y, z=0):
"""Returns the middle value of parameters
>>> mid(7,5,10)
7
"""
a = [x, y, z]
a.remove(builtins.min(a))
a.remove(builtins.max(a))
return a[0] | a7b6417287539ce0bc5cab68db6075acdfa8d1b9 | 641,813 |
def get_auth_user_defaults():
"""Return a dictionary of reasonable defaults for auth users."""
auth_user_defaults = dict(
username = 'testuser',
password = 'password',
first_name = 'Test',
last_name = 'User',
email = 'testuser@colorado.edu'
)
return auth_user_defa... | 7f474639329e7e38ded52fa380e2ee0830a332d7 | 641,814 |
def samples_number(session, Type='Int32', RepCap='', AttrID=1150021, buffsize=0, action=['Get', '']):
"""[Get Number of Samples]
Returns the integer number of complex samples that will be available to Get Data or Get Data Block when the measurement completes.
"""
return session, Type, RepCap, AttrID, bu... | 38c6c9bb46bbe551749821050ef38f224f4b1758 | 641,816 |
def allMatches(source, regex):
"""Return a list of matches for regex in source
"""
pos = 0
end = len(source)
rv = []
match = regex.search(source, pos)
while match:
rv.append(match)
match = regex.search(source, match.end() )
return rv | a7d20a2ea65ce28c0d3dd2cb08bc46b4f94d7030 | 641,817 |
def select_logical(df):
"""
Returns dataframe with object type
Parameters
-----------
df
Pandas data frame with item data
Returns
-----------
col
Pandas dataframe with numeric data
"""
col=df.select_dtypes(include=['bool'])
return col | 5739cecb00217f45feb4b9e198cf482df20bf5e6 | 641,818 |
def type_bibjson(refs_json):
"""Format BibJSON return from list of standard JSON objects."""
refs_bibjson = list()
for rec in refs_json:
bib = dict()
# Add basic reference info
bib.update(type=rec.get('kind'),
year=rec.get('year'),
title=rec.ge... | da018bf2adb70077b87f43e047008c421f6a70cb | 641,819 |
def f(x):
"""判断是否是回数"""
x = str(x)
mid = int(len(x) / 2)
i = 0
while i < mid:
if x[i] != x[-(i + 1)]:
return False
i += 1
return True | 48ea4fd4aef90f8816a0b95a47f9f8a2870e712a | 641,820 |
import io
def readReviews(path):
"""
Function to store reviews in a list buffer.
Arguments
---------
path: location of reviews
Return
---------
list of reviews
"""
# Create an empty buffer to hold all the reviews
reviewBuf = []
# Open the file
with io.open(path,'r') as raw:
for line in raw:
revi... | e349cd18c63d5215e79f68cdfbc89a6a48371bd9 | 641,821 |
import os
def path_join(
filename: str,
path_to_folder: str = "../data/",
) -> str:
"""
os.path.join with default path_to_data.
:param str filename: filename.
:param str path_to_folder: path to the folder where the filename is located.
:return: joined path.
:rtype: str
"""
re... | 22c43950b216cba1c2258c0c037e75babe910368 | 641,822 |
def fy(vy0, n):
"""
Computed by hand
"""
return n*(2*vy0 + 1 -n) / 2 | 0550bb52340601791a1c4b55c8a8a668124afbb1 | 641,823 |
import os
import re
def get_host_release():
"""Helper to return the hosts sanitized RELEASE"""
rel = os.uname()[2]
release = rel.rsplit("-", 1)[0]
if "-STABLE" in rel:
# FreeNAS
release = f"{release}-RELEASE"
elif "-HBSD" in rel:
# HardenedBSD
release = re.sub(r"\W... | 667421d0d2dc09e1cc303a85c9ccb68f3f7e6e71 | 641,824 |
def get_all_group_custom_attributes(group: dict) -> dict:
"""
Returns a list of all the custom attributes in the group
:param group: the group
:return: the list of all custom attributes
"""
custom_attributes_dict: dict = {'name': group.get('name'), 'customAttribute': []}
for raw_custom_attri... | 308f586131cb374db1bda5cc0aa70df5cbd0bb16 | 641,825 |
def unique_id_create(my_df, team=False):
"""Derives a unique ID to allow for merges across different data sources"""
my_df = my_df.copy()
char_list = ["'", ' III', ' II', ' IV', ' V', 'Jr', '\.', '-'] #removed ' '
symbol_dict = dict(zip(char_list, len(char_list)*['']))
if team:
my_df = (my_... | 4711f18019a0fd16906bb6587878d96e05bc45f5 | 641,826 |
def get_fitzpatrick_type(ita):
"""
This function will take a ita value and return the Fitzpatrick skin tone scale
https://arxiv.org/pdf/2104.14685.pdf
:param ita:
:return:
"""
if ita < -50:
return "6"
elif -50 <= ita < -25:
return "5"
elif -25 <= ita < 0:
retu... | d4a205a760c28870911a7b9ed7e3aeafe61158e1 | 641,827 |
def insert_newlines(string: str, every: int = 5) -> str:
"""Returns a string where \\n is inserted between every n words"""
words = string.split()
new_string = ""
for i in range(0, len(words), every):
new_string += " ".join(words[i : i + every]) + "\n"
return new_string | e7eac44e0f02d68333bcbbc65d8a6f504c4d0e0f | 641,829 |
import requests
def twitter_get_friends_json(nickname: str, token: str) -> dict:
"""
Get json with friends by username from twitter.
"""
reqest_url = "https://api.twitter.com/1.1/friends/list.json"
headers = {
'Authorization': 'Bearer {}'.format(token)
}
params = {
'scree... | 2853a80a4707f19014c368ae15e7386838f96c5f | 641,830 |
def get_cam_name(i, min_chars=7):
"""Create formatted camera name from index."""
format_str = '{:0' + str(min_chars) + 'd}'
return 'cam_' + format_str.format(i) | 953446c3cf1b2ab9525931ac02a749e9645d8e47 | 641,831 |
import re
def _extract_year(text: str) -> int:
"""
Extract the year from a PDF file name.
Keyword arguments:
text -- the text to extract the year from
Returns: the year
"""
year_pattern = re.compile(r"\d{4}", re.IGNORECASE)
year = re.search(year_pattern, text)
if year is not Non... | c2b5b31f8ac9c37a6a64bf9a92a27adba1284d59 | 641,832 |
def linear(x, slope=1.0, intercept=0.0):
"""Return a linear function.
x -> slope * x + intercept
"""
return slope * x + intercept | 174269c7e9d970cad60a1f15bc2231f317e7e8fe | 641,833 |
import random
def different_account(account, test_case=None):
"""Randomly choose a non-existant account or keep account."""
if test_case:
if test_case.get("account"):
return "FFFFFFFFF"
else:
return account
else:
return "FFFFFFFFF" if random.random() < 0.1 e... | 19c25746bdc17da845588f3e845e39b4a039181f | 641,834 |
import os
def sirsam_rf(data_sirsam):
"""
Path to SirSam random forest outputs.
"""
return os.path.join(data_sirsam, 'random_forest') | 88d716bcf8e4ba953fb6439c3ef3c7a3b8b401ff | 641,835 |
import numpy
def _arrayToRgba8888(colors):
"""Convert colors from a numpy array using float (0..1) int or uint
(0..255) to uint8 RGBA.
:param numpy.ndarray colors: Array of float int or uint colors to convert
:return: colors as uint8
:rtype: numpy.ndarray
"""
assert len(colors.shape) == ... | c024bd3be76fce0c3016dca0b8e8a26344718a1c | 641,836 |
from functools import reduce
def pipeline(*fns):
"""
five = partial(operator.add, 5)
ten = partial(operator.add, 10)
one = partial(operator.add, 1)
pipeline(five,
ten,
one)(0)
= one(ten(five(0))) => 16
"""
return reduce(lambda f, g: lambda *xs, **ys: g(f(*xs,... | 869e240a1918824da6d3d60a416947fdb93518ab | 641,838 |
def crop_center(array, crop_wh):
"""[summary]
Args:
array ([type]): [description]
crop_wh ([type]): [description]
Returns:
[type]: [description]
"""
_, h, w = array.shape
crop_w, crop_h = crop_wh
assert w >= crop_w
assert h >= crop_h
left = (w - crop_w) // ... | a80b8733ed2237982ca8ac016b80a693a789246b | 641,839 |
def beautify(elem):
"""
function to check if strings are numbers and format them
:param elem:
:return:
"""
# print(elem)
if type(elem) == int: return "$%d$" % elem
if type(elem) == float: return "$%.2f$" % elem
if elem.replace('.', '', 1).isdigit():
# print(elem, "before")
... | 9bae36a6ae9be8efc29553535bbc2ec53fbe8e10 | 641,840 |
import hashlib
def sha512_encode(t):
"""Encoder using SHA512.
>>> sha512_encode("Hola mundo")
'34ddb0edac59e441459e07cf33bd628f53fbbf752141125f069f32081b169f933666c71b2f1b83031da66bc905a1e72af7c6cfd779fc197513639a098f94c641'
"""
s = hashlib.sha512(t)
return s.hexdigest() | 2a005d9bfce688694e582c00434ba7e228ddc185 | 641,841 |
def coroutine(func):
"""
Implementation adapted from https://www.pythonsheets.com/notes/python-asyncio.html
"""
func.__coroutinefunction__ = True
return func | f520ff9b865c0e18c8607cbc3611054fb14adb37 | 641,842 |
def docs(function):
"""Get module and function name and point users to non-functional counter-part.
Gets functions name, splits on "_" and transforms to UpperCase class name.
Redirects users to documentation of non-functional counterpart of `function`.
"""
# removes functional from module
modu... | 2808f1befdbf13d01f34d0b98ec98ea6955c8ace | 641,843 |
def geth_to_cmd(node, datadir, verbosity):
"""
Transform a node configuration into a cmd-args list for `subprocess.Popen`.
Args:
node (dict): a node configuration
datadir (str): the node's datadir
Return:
List[str]: cmd-args list
"""
node_config = [
'nodekeyhex'... | 17b8c8edd8895ef6d8bedd862ed214df16e28159 | 641,844 |
def threeSum(nums):
"""
:type nums: List[int]
:rtype: List[List[int]]
"""
def find_rest(current_sum, nums_start_index, results):
if current_sum == 0 and len(results) == 3:
return results
for num in nums[nums_start_index:]:
if len(results) < 3 and num not in r... | 325a7902ec083ee5f00f361e22a7bf87d099e69e | 641,845 |
import re
def get_words_from_txt_file(txt_path: str) -> list:
""" Return list of words from txt file at specified path """
words = []
with open(txt_path, encoding='utf-8') as file:
for line in file:
try:
for word in line.split():
words.append(word... | 3c1957684d8bfe0e20711b9e63844d64c5806a23 | 641,846 |
def extract_terminal_pathname(url):
"""Extract the last path segment from a URL
"""
return list(filter(None, url.split("/"))).pop() | b3c4e7dddf3d903df54d38f2f9fc6593f2654bb2 | 641,847 |
from typing import Union
from typing import List
def occurrences(obj: Union[int, List], value: int) -> int:
"""Return the number of occurrences of value in obj.
>>> occurrences([[[4, 5], [5]], [3, 5, [[20]]], 3], 5)
3
"""
if isinstance(obj, int):
return 1 if obj == value else 0
else:
... | 867e760e4cb9398e3d29da8c7dfa68b240693692 | 641,848 |
import os
def _getFilePathAndName(path, file) -> str:
"""
Function Description :
_getFilePathAndName : provide string of file name and path location
accept path folder or location of the file and file name as arguments
EXAMPLE ARGS : (path = '/usr/name/', file = 'image.jpg'... | e62beeae22316479d1dbdc806f31c9345ae1e0b9 | 641,851 |
from typing import Any
def resolve_potentially_callable(val: Any) -> Any:
"""
Check if a value is callable, and return its result if so.
Parameters
----------
val:
Value to check.
"""
if callable(val):
return val()
return val | 4faf0ae30eb7a0bef708f64b9b684b6dadd2e6a4 | 641,853 |
def data_to_bin(data):
""" Translates occupied seats to 1, others to 0 """
data = list(data)
to_bin = str.maketrans("L.#","001")
for i in range(len(data)):
data[i] = "".join(data[i])
return [datum.translate(to_bin) for datum in data] | 608628cab28120db2c36f2b483013ba696339053 | 641,854 |
import pickle
def load_pickle(path):
""" Loads a .pickle file
Parameters
----------
path : str
Absolute path to the file
Returns
-------
Object contained in the .pickle file
"""
with open(path, 'rb') as f:
return pickle.load(f) | b840696d71bd7b14749a68c4761ff4ae7aef0a4e | 641,855 |
import gzip
def parse (f):
"""Decompress an epgdb file.
:arg typing.BinaryIO f: epgdb file contents
:return: Uncompressed epgdb file contents
:rtype: typing.BinaryIO
"""
# skip epgdb-specific header
f.read(12)
return gzip.GzipFile(fileobj=f) | b5f1d67189896618a7cfa8fd68eb46419ab5ac5b | 641,856 |
def build_vocab(posts):
"""
Given the training set of posts, constructs the vocabulary dictionary, `tok_to_ix`, that
maps unique tokens to their index in the vocabulary.
"""
tok_to_ix = {}
for post in posts:
tokens = post.split(' ')
for token in tokens:
tok_to_ix.setd... | a3f06c4d8f9427672291b71f7f6d87e870cb7ad1 | 641,857 |
def get_feature_importance_data(data_income, column='Close_x', include_targets=False):
"""
:param data_income:
:param column:
:param include_targets: targets are 'Open_x', 'High_x', 'Low_x' and 'Close_x'
:return: train and test of X and y
"""
data = data_income.copy()
y = data[column]
... | 00b96f8ce08355a0d085c93d62200ac6f024f86e | 641,860 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.