content stringlengths 35 416k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def union_list(cmp_lists):
"""
Get the two or multiple lists' union. Support one empty list.
:param cmp_lists: A list of will do union calculate lists. It must have two list at least.
:return: result: The result of the lists union.
"""
result = list(set().union(*cmp_lists))
return result | 013d7e45a1ea56bcd09fe8ed332d8d69962774fb | 31,923 |
def replace_word(word_array, dict_of_words_to_replace):
"""
Given an array of words, replace any words matching a key in dict_of_words_to_replace with its corresponding
value.
:param word_array: The array of words to check.
:param dict_of_words_to_replace: The dictionary of words to replace paired w... | 5e763a8f0af48b93c0eeeec4414e411dd4e2d69b | 31,924 |
def _get_point_key(match_parse, point):
"""
Obtain the key for the point via reverse engineering
:param match_parse:
:param point:
:return:
"""
_, key_string, _ = str(point.x).split('_')
key = int(key_string)
return key | 0ef34d576e643bd36cc203ccc193964eb0b2e8bb | 31,925 |
def namespaced(obj, tagname, namespace=None):
"""
Utility to create a namespaced tag for an object
"""
namespace = getattr(obj, "namespace", namespace)
if namespace is not None:
tagname = "{%s}%s" % (namespace, tagname)
return tagname | a8cb8133e56768d572d944906252eabc774f9ef0 | 31,927 |
import hashlib
def md5sum(targetfile):
"""md5sum a file. Return the hex digest."""
digest = hashlib.md5()
with open(targetfile, 'rb') as f:
chunk = f.read(1024)
while chunk != "":
digest.update(chunk)
chunk = f.read(1024)
return digest.hexdigest() | 0a599cbdcfcb1061a6577c3db2947f4f08425fae | 31,928 |
def some_data():
"""Return answer to ultimate question."""
return 42 | a920c94720ce71c9d976b0b13437a391ef2414a8 | 31,929 |
import argparse
def parse_arguments():
"""Parse Inference arguments"""
parser = argparse.ArgumentParser()
# Required parameters
parser.add_argument(
"-x",
"--inst-path",
type=str,
required=True,
metavar="PATH",
help="path to the CSR npz or Row-majored ... | daef2538076a1a56fbc588816b30640ad2f80f45 | 31,930 |
def calc_v(v, policy, Rsa, Psas, s:int=0, forgetting_factor=1.0):
"""
์ด๋ฐ ๋ฐฉ์์ ๊ณ์ฐ์ ๋ถ๊ฐ๋ฅํ๋ค. ์๋ํ๋ฉด ๋ฌดํ๋ฃจํ๋ฅผ ๋์ ์๊ธฐ ๋๋ฌธ์ด๋ค.
ํ๋ฅ ์ด ๋ฎ์ ๊ณณ์ด๋ผ๋ ์ ์ฒด์ ๊ฐ๋ฅ์ฑ์ ๋ชจ๋ ๊ณ์ฐํ๋ ์๋ ๋ฐฉ์์ ๋ฐ๋์ ๊ทธ ๋ถ๋ถ์ ๋ค์ด๊ฐ์ผ ํ๊ธฐ ๋๋ฌธ์ ๊ณ์ํด์ ๋ฐ๋ณต์ด ๋๋ค.
ํ๋ฅ ์ Monte Carlo๋ก ๋ฐฉ์์ผ๋ก ๋ฃ๋๋ก ํ๋ฉด ๋์๊ฐ ์ ์์ง ์์๊น?
"""
Gs = 0
for a in range(len(policy[s])): # for๋ฌธ์ด ์๋ ํ๋ฅ ์ ์ํด ์ ํ๋์ด์... | 5095ac0d9eed9e48fa17f9f6bc5e35eabd103327 | 31,932 |
import os
def get_api_keys(filename=None):
""" Mouser API Keys """
# Look for API keys in environmental variables
api_keys = [
os.environ.get('MOUSER_ORDER_API_KEY', ''),
os.environ.get('MOUSER_PART_API_KEY', ''),
]
return api_keys | 92e14f383f2cf7f7b7f01131850b52efa35798e3 | 31,933 |
def check_if_only_decoys(sequences):
"""
Check if the sequences to consolidate are composed only of decoys
"""
only_decoys = True
for sequence in sequences:
if 'decoy' not in sequence.split()[2]:
only_decoys = False
break
return only_decoys | aeb65a261bcea6db80cd7a81b566463ad3d0414f | 31,934 |
import argparse
def parse_args():
"""
args for training.
"""
parser = argparse.ArgumentParser(description='Parse args for training')
parser.add_argument('--data_dir', type=str, help='directory where lmdb data is located')
parser.add_argument('--dataset_str', type=str, help="which datasets to u... | 1df52478a518a17256d36fe1d1d523f237c9504b | 31,937 |
def normalised_cooperation(cooperation, turns, repetitions):
"""
The per-turn normalised cooperation matrix for a tournament of n repetitions.
Parameters
----------
cooperation : list
The cooperation matrix (C)
turns : integer
The number of turns in each round robin.
repetit... | 9d840592df4f538e30cc961aa6a51934a351006c | 31,939 |
import os
def get_kolibri_home():
"""
Return KOLIBRI_HOME environment variable
"""
return os.environ.get('KOLIBRI_HOME') | add4b9330490b228f7a8dd57115f1e9a5b863133 | 31,941 |
import os
def has_extension(filename, ext):
"""Check if filename has given extension.
>>> has_extension("foobar.py", ".py")
True
>>> has_extension("foo.bar.py", ".py")
True
>>> has_extension("foobar.pyc", ".py")
False
This function is case insensitive.
>>> has_extension("FOOB... | 42ae775d185bb26162e00d2a50e6248de096ce66 | 31,942 |
def truncate_string_end(string, length=40):
"""
If a string is longer than "length" then snip out the middle and replace with an
ellipsis.
"""
if len(string) <= length:
return string
return f"{string[:length-3]}..." | d1dfb8ea9ce82fd27777f02b5f01d35c1af4dfa8 | 31,943 |
import requests
import json
def get_todays_percent_change_of_symbol(symbol):
"""
fetch todays change in percent for the given symbol name
:param symbol: ticker name which will be queried
:return: todaysChangePercent
"""
p_auth = "Zay2cQZwZfUTozLiLmyprY4Sr3uK27Vp"
query = """https://api.pol... | 16273218c5197171426071399151ce2c16d6c106 | 31,944 |
import os
def get_hook_dirs():
"""Get hooks directories for pyinstaller.
More info about the hooks:
https://pyinstaller.readthedocs.io/en/stable/hooks.html
"""
return [os.path.dirname(__file__)] | 612cdc8e801b31302f8a78ddcc281b322271e0a8 | 31,946 |
import re
def get_single_junction_overhang(cigar):
"""
Returns the number of reads left/right of a junction as indicated
by the LEFTMOST N in a cigar string. Return -1, -1 for reads that don't span
junctions.
:param cigar: string
:return left: int
:return right: int
"""
cigar_over... | 96331b12ba05eb13ae783aab76589a5556fb1166 | 31,947 |
def s_shape(x, power=1.5, eps=1e-7):
"""Helper function to densify the midle of a cubic Bezier curve"""
return (
1 / (
1 + ((x + eps) / (1 - x + eps)) ** -power
)
) | 09f73f093f80bfafe369c6805c19e2755cf5cee6 | 31,948 |
def intro() -> str:
"""Returns a welcome message as a string.
Returns:
str:
"""
return "\nI am Jarvis, a pre-programmed virtual assistant designed by Mr. Rao\n" \
"You may start giving me commands to execute.\n\n" \
"*Examples*\n\n" \
"*Car Controls*\n" \
... | 527e83bce6cd56282d5452fda942205a11088bd3 | 31,950 |
def get_cpu_temp():
"""Return the CPU temperature as a Celsius float
"""
cpu_temp = 'unknown'
with open("/sys/class/thermal/thermal_zone0/temp", "r") as temp_file:
cpu_temp = float(temp_file.read()) / 1000.0
return cpu_temp | 1d49bb1a4b07781def93c3f3cca0db8322ab80aa | 31,951 |
import requests
def get_rescoped_token(k5token, projectid, region):
"""Get a regional project token - rescoped
Returns:
STRING: Regionally Scoped Project Token
Args:
k5token (TYPE): valid regional token
projectid (TYPE): project id to scope to
region (TYPE): k5 region
... | 4aff45eae6dbbb0a1cef98b2192c36c877446dda | 31,953 |
import uuid
import time
def generate_token():
"""
Generates a unique enough token for users to use as already authenticated
:returns: Hex token
:rtype: str
"""
return uuid.uuid5(namespace=uuid.NAMESPACE_OID, name=time.time().hex()).hex | e13513e342e36635aad3dc66ec2ea48fd71a43c9 | 31,954 |
from typing import Sequence
def get_problem_type_input_args() -> Sequence[str]:
"""Return ``typing.get_args(ProblemTypeInput)``."""
return ("trivial-gcd", "nontrivial-gcd", "trivial-factor", "nontrivial-factor") | 937759fde8ebeb0cf0666f83e7e3741720eac324 | 31,955 |
def strand_to_fwd_prob(strand):
"""Converts strand into a numeric value that RSEM understands.
Args:
strand: string 'forward', 'reverse', 'unstranded'
Returns:
numeric value corresponding the forward strand probability
Raises:
KeyError if strand is not 'forward', 'reverse' or ... | c396296fb5e468bbb152c48156215abedcce2ebe | 31,956 |
def selection_sort(numbs: list) -> list:
"""
Go through the list from left to right and search for the
minimum. Once the minimum is found, swap it with the
element at the end of the array. Repeat the same procedure
on the subarray that goes from the element after 'i' to the
end, until the array ... | 1d1a693a83c30753bb2829a18d7fd65d7f42b90d | 31,957 |
import random
def create_random_secret_key():
"""
็ๆ้ๆบ32ไฝ16่ฟๅถๆฐๅฏ้ฅ
:return:
"""
return ''.join([hex(random.randint(0, 255))[2:].zfill(2) for i in range(32)]) | e0d55e9952a69a1d7129adb45cbdef3aafae6d3c | 31,958 |
import hashlib
def generate_sha256_hash(string_to_hash: str):
"""Return the sha256 hash of the string."""
return hashlib.sha256(f"{string_to_hash}".encode()).hexdigest() | 7691b6ec1939f30cd7f35861abb8cef33feab448 | 31,960 |
def get_novel_id(browser, novel):
"""
return novel's id for drop duplicates
"""
return novel[15:20] | c0ee3520543869990243ca4dba9d165bc95e59f8 | 31,963 |
def reverseSlice(s, size):
"""For 'reversed' slices (slices with negative stride),
return an equivalent slice with positive step. For positive
strides, just return the slice unchanged.
"""
if s.step > 0 or s.step is None:
return s
i = s.start
j = s.stop
k = s.step
if i is No... | dfa10bd90d9c8fda259779608821d63dca88a3eb | 31,964 |
import re
def similar_strings(s1, s2):
"""
Return true if at least half of the words in s1 are also in s2.
>>> assert similar_strings('1 2 3', '2 1 4')
>>> assert not similar_strings('1 2 3', '5 1 4')
"""
w1 = set(re.split(r'\W+', s1))
w2 = set(re.split(r'\W+', s2))
thresh... | c0d11d96e9d55b5774b718ba27f7382ac8460cf5 | 31,968 |
import torch
def to_tensor(data, dtype=None):
"""Convert the data to a torch tensor.
Args:
data (array like): data for the tensor. Can be a list, tuple,
numpy ndarray, scalar, and other types.
dtype (torch.dtype): dtype of the converted tensors.
Returns:
A tensor of d... | d51fe5fcae8a32134eab771b302c08c609dda63a | 31,970 |
def split_pair_insertion_rules(rule: str) -> tuple[str, str]:
"""Split pair insertion rule of the form 'XY -> Z' and return in the form 'XY', 'XZ'."""
mapping = rule.split(" -> ")
return mapping[0], mapping[0][0] + mapping[1] | eb84b743e5b42791d5872e4c7a6ac5d91e98829a | 31,971 |
import fnmatch
def can_analyze_file(include_paths, exclude_paths, path):
"""Glob checker function used to specify or ignore paths and files."""
if include_paths and not any(fnmatch.fnmatch(path, p) for p in include_paths):
return False
if exclude_paths and any(fnmatch.fnmatch(path, p)for p in exc... | abe0eb5d54a07b89b38fa2b065a46b0870e12e8a | 31,972 |
def itoa(value, alphabet, padding=None):
"""
Converts an int value to a str, using the given alphabet.
Padding can be computed as: ceil(log of max_val base alphabet_len)
"""
if value < 0:
raise ValueError("Only positive numbers are allowed")
elif value == 0:
return alphabet[0]
... | 506c9b809651eb8fc0fc3fcf5dc97a56d6350bf7 | 31,973 |
def getOctoList(octoArray):
"""
Converts an array of Octoparts in a list that can be added to a multilistbox
:param octoArray: Array of Octoparts
:type octoArray: list
:return: List that can be added to multilistbox
:rtype: list
"""
tmpList = []
for i in range(0, len(octoArray)):
... | fc731a942e01f5df14db7d1b64e595ba2e3a8f85 | 31,974 |
def emoji_remove_underscope(text: str) -> str:
"""cleans text from underscops in emoji expressions and <> in annotations"""
tokens = []
for token in text.split():
if len(token) > 3 and '_' in token:
token = token.replace('_', ' ')
if token[0] == '<' and token[-1] == '>':
... | 78c767894210c8f7906b7b04c1c897ce3a7cfe05 | 31,976 |
import random
def latent(user):
"""The latent influence of the Poison status effect."""
return random.randint(1, user.stats['Poison Strength'] + 1) | bda0c42bc094b01618a36949faf0664809ce3106 | 31,977 |
import os
def resource(reference, name):
"""Takes the directory part of 'reference' path (usually __file__ of the calling function) and appends 'name'
(a *relative* file path) to obtain full path to a given resource file, located inside the directory tree
of the application source code. Doesn't work in p... | 52279510b3550743c4b0b6efda6e7e4827805fee | 31,978 |
import re
def condense(input_string):
"""
Trims leadings and trailing whitespace between tags in an html document
Args:
input_string: A (possible unicode) string representing HTML.
Returns:
A (possibly unicode) string representing HTML.
Raises:
TypeError: Raised if input... | ee3a73f6d17914eaa2079111c79151833d3648f2 | 31,979 |
import math
def complex_abs_impl(context, builder, sig, args):
"""
abs(z) := hypot(z.real, z.imag)
"""
def complex_abs(z):
return math.hypot(z.real, z.imag)
return context.compile_internal(builder, complex_abs, sig, args) | f5cf9bb164bd89233c2aef6e3201fcb75bef8b37 | 31,980 |
def ExampleObject(request):
"""A DAO class under scrutiny."""
return request.param | f2e6b094d1a6b6e6bca110423f68684cd4e42032 | 31,981 |
def NEST_PROCESS_CUST():
""" generate process customization header"""
return 'Process the customizations' | f8803aad9a45550c2867c4e793dd7b9b96ea5d0b | 31,982 |
import random
def nearest_neighbor(loc, array, size=4):
"""Chooses a random nearest neighbor"""
row = array.shape[0]
col = array.shape[1]
r = loc[0]
c = loc[1]
left1 = (r - 1) % row
right1 = (r +1) % row
down1 = (c - 1) % col
up1 = (c + 1) % col
if size != 4 | size != 8:
... | 7cefd67de55a7eca0c32f0a456f635556ab7fe6b | 31,983 |
def __virtual__():
"""
Only load if requests is successfully imported
"""
return "nagios_rpc" | 8c37ea5e1f1bb6d111b8f74b4061c04d038a5063 | 31,985 |
def addBinary(a, b):
"""
:type a: str
:type b: str
:rtype: str
"""
if a == '0' and b == '0':
return '0'
return bin(int('0b' + a, 2) + int('0b' + b, 2)).lstrip('0b') | 1cecf4ac7ade8a4cd8930e1e8bd8683e5f66dc89 | 31,987 |
def difference(series, d=1):
""" Shift difference series to remove trend """
return series.diff(d).dropna() | 8c31cf1eb230937adaefd9e8aa531ce98b3aedcc | 31,988 |
import base64
import requests
def get_as_base64(url):
"""
Encode the response of a url in base64
Args:
url (str): The API URL to fetch
Returns:
the base64 string encoded
"""
return base64.b64encode(requests.get(url).content) | 5924636566f9b501a5b865e9ce0ba6bc5672dd20 | 31,990 |
def render_command_exception(e):
"""
Return a formatted string for an external-command-related exception.
Parameters:
e: the exception to render
"""
if isinstance(e, OSError):
return 'Details: [Errno {0}] {1}'.format(e.errno, e.strerror)
else:
return 'Details: {0}'.format... | c2dbbaf3b634d41aebfe551064d4b9870f0d4131 | 31,991 |
def _translate(num_time):
"""Translate number time to str time"""
minutes, remain_time = num_time // 60, num_time % 60
str_minute, str_second = map(str, (round(minutes), round(remain_time, 2)))
str_second = (str_second.split('.')[0].rjust(2, '0'), str_second.split('.')[1].ljust(2, '0'))
str_time = s... | af49424d3b9c6dfb660955b604c33e9a31e1c3de | 31,992 |
def basic_word_sim(word1, word2):
"""
Simple measure of similarity: Number of letters in common / max length
"""
return sum([1 for c in word1 if c in word2]) / max(len(word1), len(word2)) | ed9f8b79efefd9cca673f681a976120aaf8e9fe1 | 31,993 |
def getFilename(subject_data):
"""
Given the subject_data field from a row of one of our SpaceFluff dataframes, extract the name of the object being classified
by extracting the 'Filename'|'image'|'IMAGE' field".
To be used with df[column].apply()
@returns {string} filename of the object being cla... | da345d115cbe9e6c93160057a99584d5e0ce3d4a | 31,994 |
def fix_nested_filter(query, parent_key):
"""
Fix the invalid 'filter' in the Elasticsearch queries
Args:
query (dict): An Elasticsearch query
parent_key (any): The parent key
Returns:
dict: An updated Elasticsearch query with filter replaced with query
"""
if isinstanc... | 691f5f39720c8c608ab6e9828da67f625b3849f0 | 31,995 |
import hashlib
def hash_file_at_path(filepath: str, algorithm: str) -> str:
"""Return str containing lowercase hash value of file at a file path"""
block_size = 64 * 1024
hasher = getattr(hashlib, algorithm)()
with open(filepath, "rb") as file_handler:
while True:
data = file_handl... | 6c69ddb0fbb15890fd2d616808e00db04e8b14b3 | 31,996 |
import math
def apparent_to_absolute(d_pc, mag):
"""
Converts apparent magnitude to absolute magnitude, given a distance to the object in pc.
INPUTS
d_pc: Distance to the object in parsecs.
mag: Apparent magnitude.
OUTPUT
absMag: Absolute magnitude.
"""
absMag = mag - 5.0 * math... | 7348730a7d932c8eb55bf5145e17186164d37cb8 | 31,997 |
def get_vocabulary(dataset, min_word_count=0):
"""
Filter out words in the questions that are <= min_word_count and create a vocabulary from the filtered words
:param dataset: The VQA dataset
:param min_word_count: The minimum number of counts the word needs in order to be included
:return:
"""
... | 1ab05b1ba4df9251ce6077f9e3bc20b590bafe93 | 31,998 |
def n_subsystems(request):
"""Number of qubits or modes."""
return request.param | 28ed56cc26e4bfa1d607bf415b3a7611eb030a27 | 31,999 |
def parse_ehdn_info_for_locus(ehdn_profile, locus_chrom, locus_start, locus_end, margin=700, motifs_of_interest=None):
"""Extract info related to a specific locus from an ExpansionHunterDenovo profile.
NOTE: Here "irr" refers to "In-Repeat Read" (see [Dolzhenko 2020] for details).
Args:
ehdn_profi... | 93eec9ae09b03539112dfb6715c2e831293e4036 | 32,000 |
def fixed_data():
"""Description:
Captures specific fixed point method variables
params:
None
returns:
the beta function "f(x) => x inputted by the user"
"""
return input("For the bisection method enter:\nThe beta function: ") | 9dbe3602f513faaf17a6b0e84e5d64ddd045a439 | 32,001 |
import os
def get_project_root():
"""
Returns the project root path.
Starts in current working directory and traverses up until app.yaml is found.
Assumes app.yaml is in project root.
"""
start_path = os.path.abspath('.')
search_path = start_path
while search_path:
app_yaml_pa... | 166b56bb117fd8d8937b0f3d65167a8db59e71e2 | 32,003 |
def preorder_traversal_iterative(root):
"""
Return the preorder traversal of nodes' values.
- Worst Time complexity: O(n)
- Worst Space complexity: O(n)
:param root: root node of given binary tree
:type root: TreeNode or None
:return: preorder traversal of nodes' values
:rtype: list[in... | 202ebfa1e5ebb7a9f2632c66e9b7fe24f0041746 | 32,004 |
def lbm_lbm2grains(lbm_lbm):
"""lbm/lbm -> grains"""
return lbm_lbm * 7000. | 82de5e1a6bfdd9956c8719183d95822bad551c92 | 32,005 |
def reformat_timezone_offset(in_date_string):
"""
Reformats the datetime string to get rid of the colon in the timezone offset
:param in_date_string: The datetime string (str)
:return: The reformatted string (str)
"""
out_data = in_date_string
if ":" == in_date_string[-3:-2]... | 279fbf00ff51f0926f3d284faee66a43327298e4 | 32,006 |
import yaml
def load_config():
"""Load the app configuration file."""
with open('../conf/experiments.yaml', 'r') as config_file:
try:
return yaml.safe_load(config_file)
except yaml.YAMLError as exc:
print(exc) | ee097ac11d078045dabe2dd183a457ec3ebaef38 | 32,007 |
def description_cleanup(s):
"""cleanup a description string"""
if s is None:
return None
s = s.strip('."')
# remove un-needed white space
return ' '.join([x.strip() for x in s.split()]) | c5c907ea74989f9ee0f44364dceca9d34bf5f931 | 32,008 |
def vm_metadata(vm):
""""Get metadata of VM
:param vm: A Nova VM object.
:type vm: *
:return: T.
:rtype: dict(str: *)
"""
return dict(getattr(vm, 'metadata')) | 57a43621ad8d2ba5e7644af2d664a3779725fd14 | 32,009 |
import torch
def block_butterfly(X,nchs):
"""
Block butterfly
"""
ps = nchs[0]
Xs = X[:,:,:,:ps]
Xa = X[:,:,:,ps:]
return torch.cat((Xs+Xa,Xs-Xa),dim=-1) | 2ced2bfc50e41710786eedaf12f9240469b316f7 | 32,010 |
import numpy as np
def find_host_single(galdata, allhal):
"""
find the host halo of the given galaxy.
galdata should have ['x', 'y', 'z'. 'vx', 'vy', 'vz', 'm', 'r']
INCOMPLETE
"""
def dist(data, center):
return np.sqrt(np.square(center['x'] - data['x']) +
... | c194d5a02b4c6faeaf5f0345c62bccc280d42c5d | 32,011 |
import random
def select_starting_point(map):
"""Return at random one possible starting point [row_index, column_index]
"""
starting_points = []
for row_idx, row in enumerate(map):
for col_idx, col in enumerate(row):
if col == 's':
starting_points.append([row_idx, c... | eb7ae107aeba2e846913b85fce73991da08b3565 | 32,012 |
def check_freq(dict_to_check, text_list):
"""
Checks each given word's freqency in a list of posting strings.
Params:
words: (dict) a dict of word strings to check frequency for, format:
{'languages': ['Python', 'R'..],
'big data': ['AWS', 'Azure'...],
..}
... | c36813b876ff62b26c5caecd58dcafdd0bfc6ded | 32,014 |
def parse_package_arg(name, arg):
"""Make a command-line argument string specifing whether and which verison of a package to install.
Args:
name: The name of the package.
arg: True if the package is required, False if the package is not required,
or a string containing a version num... | 360cd93c96ab06f55ef8145b32c7c074d9abf349 | 32,015 |
def fetch_diagnoses(cursor):
""" Returns list of diagnoses """
cursor.execute("""SELECT * FROM diagnosis""")
return cursor.fetchall() | d653451503cdd2dccc96ccd0ad79a4488be88521 | 32,017 |
def factorial(n):
"""
Returns the factorial of a number.
"""
fact = 1.0
if n > 1:
fact = n * factorial(n - 1)
return fact | 7c20382a053cc3609fa041d1920d23b884b8aa0b | 32,018 |
def parse_copy_startup_config_running_config(raw_result):
"""
Parse the 'copy startup-config running-config' command raw output.
:param str raw_result: copy startup-config running-config
raw result string.
:rtype: dict
:return: The parsed result of the copy startup-config running-config:
... | 02f71846d2ba5b80469aac64f586f17eb135513a | 32,020 |
def cache_feed(value):
"""RSS feed caching"""
return value | 8df23b76167b393f0a6e5d3a5c8d639753a74e41 | 32,021 |
def fizzbuzz() -> list:
"""Return Fizz Buzz from 1 to 100.
Return a list of numbers from 1 to 100,
replacing multiples of three with Fizz,
multiples of five with Buzz and
multiples of both with FizzBuzz.
"""
fizzbuzz_list = []
for num in range(1, 101):
if num % 3 == 0 and num % ... | fb068b55a331d836ea2fa68d910714fb242f9318 | 32,022 |
def resolve_newline(data):
"""
Newline problem: Unix platforms puts a \n as terminator, Windows does not
This function resolves this problem once and for all
@data: is a list of strings
"""
if(data[len(data)-1] == ''):
#Newline detected
data = data[:len(data)-1]
return data | 937a3a308aa40d49649a332405f96a4838512a3c | 32,024 |
def get_graph_element_name(elem):
"""Obtain the name or string representation of a graph element.
If the graph element has the attribute "name", return name. Otherwise, return
a __str__ representation of the graph element. Certain graph elements, such as
`SparseTensor`s, do not have the attribute "name... | fa91db4237ba5d89bd475deb1ee04e3307098c93 | 32,025 |
def wallConvection(resistance_conv):
"""This function calculates the resistance value of a convective resi
the input ("resistance_conv" is a dictionary
for example:Ri={"name":"Ri","type":"conv","area":0.25,"hConv":10}
pay attention that the units are as follows: area : m2 h= W/m2.K
the output resist... | 02e56a400b1d93865cac17419ca459724e48a7cb | 32,026 |
def process_comments(source_comment_dict, generator_object):
"""
This function replaces the keys in the source comments that are
function names in the source files into their container id name.
"""
grfn_argument_map = generator_object.function_argument_map
for key in source_comment_dict:
... | 108f1c6a1bfbe8e19bfa4a4a6c43f703a9d8edeb | 32,028 |
def exists_in_frame(frame):
"""
Returns a function that filters summary blob data by requiring it to
exist on a specific *frame*.
"""
def f(summary_data):
born_before = summary_data['born_f'] <= frame
died_after = summary_data['died_f'] >= frame
return summary_data[born_befor... | 392dd2c46488bec90434ce12c92b5f3fde307191 | 32,029 |
def _merge_datadefinition_dicts(tpl, by: str):
"""Merge data_dict or definition dict.
args:
tpl (array-like): Array-like of dicts
by (str): Key to merge on.
"""
try:
out = {"{}".format(by): tpl[0][by]}
except KeyError:
out = dict()
for i, _dict in enumer... | 34f256aeb7b30fa4c8039e1a63b9d2b422359483 | 32,031 |
import hmac
import hashlib
def _sign(key: bytes, msg: str) -> bytes:
"""Perform one round of AWS HMAC signature."""
return hmac.new(key, msg.encode('utf-8'), hashlib.sha256).digest() | 952d75ed63a351fa6a6d527a7e70250f3ea76229 | 32,033 |
import tqdm
def get_unique_value_used(all_sampled_adj_freq):
"""
Description
-----------
Get the set of coordinates for which calculation is need to compute the mean and the standard deviation
Parameters
----------
all_sampled_adj_freq : list
list of sampled adjacency matrice... | c61d21d1e7d85fd2568a4375bd221f59fa0576fb | 32,034 |
def find_attr_in_tree(file, tree, attr):
"""
Given the leaf group inside a hdf5 file walk back the tree to
find a specific attribute
Parameters
-----------
file: h5py.File
Opened h5py file containing data
tree: str
path inside file from which to start looking backwards for... | 598f595bcc7f6196caa7e05a0b5eba7ac82ceaf8 | 32,035 |
def getCriticalElementIdx(puck):
"""Returns the index of the most critical element
:param puck: 2d array defining puckFF or puckIFF for each element and layer
"""
# identify critical element
layermax = puck.max().argmax()
return puck.idxmax()[layermax], layermax | d786775a08b7eedb7c5eeb2fbb6b63a4a2d75d32 | 32,036 |
import os
def remove_files(files, quiet, trial_run):
"""Remove all those files
Print out each file removed, unless quiet is True
Do not actually delete if trial_run is True
"""
dirs = set()
result = os.EX_OK
for a_file in files:
try:
if not trial_run:
i... | 32c8c6fb9e5562a98dc108a171de5e887936e87b | 32,037 |
def _get_proc_stats(filename, prefix, stats_to_collect):
"""
collect status from a /proc/* file
"""
stats = {}
with open(filename) as stream:
lines = stream.readlines()
for line in lines:
words = line.split()
key = words[0].rstrip(":")
value = words[1]
if ... | 5ffa2cabf27bcf980c8a44139a57d3a8ed3372d7 | 32,039 |
import random
def random_rgb():
"""Generate a random RGB pixel"""
return [int(255*random.random()), int(255*random.random()), int(255*random.random())] | 91672d2d5c83b07cf69f8d59eb2dda3dff18eada | 32,040 |
def get_idx(prefix, itf):
"""
Gets the index of an interface string
>>> get_idx('et', 'et12')
12
>>> get_idx('ap', 'ap32')
32
"""
return int(itf[len(prefix) :]) | 0a4b1e49ad6c0a7e9a2a9ae1903480a3bf73d70e | 32,042 |
def split_text(text, list_tuples):
"""
Partage un texte en mots selon les espaces et en prenant en compte les annotations (utile si la fin d'une entitรฉ
annotรฉe ne correspond pas ร un espace).
:param text: texte (string)
:param list_tuples: liste de tuples au format (caractรจre du dรฉbut de l'entitรฉ an... | fe01d111b7eab452414a2575489a7f135568c9e1 | 32,043 |
def dichotomy_grad (f, arg_before, z_e, arg_after, w_0, de, grad):
"""
f : function for f(*in_first,z,*in_after) = w
arg_before, arg_after : f function arguments that come before and after z_e
z_e : firstguess for the value to be tested
w_0: target value for w
de : delta error
grad : gradi... | 4106eea2a0ba9f7600f3cf991db83a09ded0ebfc | 32,044 |
def split_to_and_since_delong(df):
"""Split the frame into time periods that DeLong analyzed and those since his article.
:param df: The frame to split
:return: Tuple with (to_delong, since_delong)
"""
to_delong_index = [d for d in df.index if d.year <= 2004 and d.month < 6]
since_delong_index ... | 9037acca6037ba4888b5ec1b3c8099e0216022d7 | 32,045 |
import logging
def calc_voltage_extremes(volt):
"""This function calculates the extreme values in the ECG data.
This functon takes the volt list as input which is the magnitude
of the ECG data, and finds the extreme values using the max() and
min() values. The max and min values are returned as a tup... | aa6e3fa75c15fdea87052f357b885398dd6adcd4 | 32,046 |
import os
import subprocess
def createSrcTex(md_file, tex_file, references, csl):
"""
"""
try:
if references is not None:
if csl is None:
csl = os.path.join(os.getcwd(), 'american-medical-association.csl')
else:
csl = os.path.join(os.getcwd(... | 2cd8d09d4b217330fae23c75c3d8eab47f12e67d | 32,048 |
import typing
from typing import TypeGuard
import asyncio
def is_async_iterator(obj: typing.Any) -> TypeGuard[typing.AsyncIterator[object]]:
"""Determine if the object is an async iterator or not."""
return asyncio.iscoroutinefunction(getattr(obj, "__anext__", None)) | 160d1dd2d5f1c9d6d2637e6006ae0ef268c7810f | 32,050 |
def age_the_pop(df):
"""
Age population by one year. Get rid of population greater than 100
Parameters
----------
df : pandas DataFrame
survived population
Returns
-------
pop : pandas DataFrame
population aged by one year
"""
df = df.reset_index(drop=False)
... | 08d34a4f4db04a20201e895e8d81fbfc36fd598d | 32,051 |
import argparse
def argparser():
""" Argument parser for the main script """
parser = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter)
# Model settings
ms = parser.add_argument_group('Model settings')
ms.add_argument('--model', type=str, default='vae_experimental', h... | c8e4802188a937d1718768407aa66389105f766b | 32,053 |
def notifications(f):
"""
Decorator for registering a function to serve as notification center. Should accept data dict of incoming
notifications and can decide behavior based on that information.
"""
notifications.__dict__['*notification_center'] = f
return f | 19a42c6a3ea2f854862ae1faf430edb206f09019 | 32,054 |
from typing import List
from typing import Union
import re
def get_special_chars_from_tweet(
tweet_text: str,
) -> List[Union[str, int]]:
"""Extract urls, hashtags and usernames from text of tweet."""
# # Extract urls from text of tweet
tweet_text_urls = re.findall(r"(https?://[^\s]+)", tweet_text)
... | bedfe38cb055729e90396bd29be9fccff68e8488 | 32,055 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.