content stringlengths 35 416k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def solution(resources, args):
"""Problem 6 - Version 1
Manually calculate the sum of squares and the square of the sum.
Parameters:
args.number The upper limit of the range of numbers to use
for the calculation (i.e. 1 to args.number)
Return:
(1^2 + 2^2 + ... | d6ead21ac352a96badcc54fe6471655b3d0c23cc | 655,892 |
def semester_year_to_term_key(semester, year):
"""
Convert semester and year to a 4-digit term number
"""
semester = str(semester).strip().lower()
return 1000 + int(year) % 100 * 10 + ["spring", "summer", "fall"].index(semester) * 2 + 4 | f76db3bbaf175c532e519d1edc49d58d2a341000 | 655,893 |
def varName(p, name_space = None):
"""
LEGACY CODE. Use file_management.nameof instead
Return name of the variable as a string
p: variable of any type
name_space: namespace of the variable to use
NOTE: must specify name_space = globals() when calling the function, should not be omitted
... | 17c6ccb8394b8d98d572514268328065de1aad4c | 655,894 |
def message_with_line(cell, message, sourcepos=[[1, 1], [1, 1]]):
"""
Print 'message', along with some of the lines of 'cell'
"""
return f"{message}. Some relevant lines from the cell:\n\n{cell.lines(sourcepos)}" | 3fd9f336af1e90edd0937e8a9ac937e8e533966e | 655,895 |
import pathlib
from typing import Dict
import yaml
def config_parser(file_path: pathlib.Path) -> Dict[int, list]:
"""Opens and parses a `yaml` configuration file.
Uses [PyYAML](https://pyyaml.org) to parse the configuration file.
Args:
file_path (pathlib.Path): The path towards the user's
... | bc6a48e6ed685addc869752bce83cd2d13077188 | 655,896 |
from datetime import datetime
def _is_key_expired(key, expiration_in_days):
"""
Whether or not service account key is expired based on when it was created
and the current time.
Args:
key (dict): API return for a service key
.. code-block:: python
{
... | c0b8c7d06baa65a442830bd382ca78466c8c4ff6 | 655,897 |
def WrapVariable(val, left, right):
"""
* Wrap string variable name in wrapper.
"""
invalid = [var for var in [val, left, right] if not isinstance(var, str)]
if invalid:
raise Exception('The following arguments must be strings: %s.' % ','.join(invalid))
val = left + val if not val.starts... | 2af195fa24ca1d3cc77fcf46f63d4c93cb5e6171 | 655,898 |
def import_schema_to_fc(csv_file, fc_name):
"""convert csv schema from report_fields_to_csv_schema
to a featureclass"""
# assume headers as per output from export_schema_to_csv
# get fc type from csv file line 1
# load the csv file from line 2 for field info
# get field list
# ignore OBJECTI... | 3b18bcf3c4c31dda696f2b25402772892a00d1c2 | 655,899 |
def sharpe_calc(rtrn: float, risk: float, rf: float) -> float:
"""
Calculate the Sharpe Ratio assumed given continuously compounded return.
:param rtrn: Continuously compounded return.
:param risk: Standard deviation of portfolio.
:param rf: Risk free rate of return.
:return: Sharpe Ratio.
"... | 06d0503214e33cf07f1405d7bcce34331aad7e9a | 655,900 |
def _slice_support(the_slice, length):
"""Takes a slice and the length of an object; returns normalized version.
Specifically, corrects start and end for negative indices.
"""
start = the_slice.start
stop = the_slice.stop
step = the_slice.step or 1
#fill in missing values for start and end
... | 72026168b61d67ad4b13125c91326e19906c1608 | 655,901 |
def translate_type(string):
"""Depreciated, Now must be enabled in functions that use it
Too slow to be default, and conversions can lose information
Takes a string and converts it float or a int if possible
"""
# This is way too greedy
try:
if string.isdigit():
return... | 5642eff0b39563eab15b384f6e560608111a91e7 | 655,902 |
import io
import difflib
def generate_or_check(manifest, args, path, func):
"""Generate/check a file with a single generator
Return True if successful; False if a comparison failed.
"""
outfile = io.StringIO()
func(manifest, args, outfile)
generated = outfile.getvalue()
existing = path.r... | 4d4f14551d68047cbe4e0c0e28b21e359d3824c8 | 655,903 |
def get_sentiments(model, x, threshold):
"""Get clusters for a single example. Note that the functions resets the hidden states of the model."""
model.reset_intermediate_vars()
sentiments = []
for x_i in x:
_ = model.forward(x_i.view(1, 1), take_log=False)
sentiments.append(model.select_... | 114fa32ee76be152cf1db26ab7407e0a78b745f7 | 655,904 |
def generate_df_subset(swc_df, vox_in_img_list):
"""Read a new subset of swc dataframe in coordinates in img spacing.
Parameters
----------
swc_df : pd.DataFrame
DataFrame containing information from swc file
vox_in_img_list: list
List of voxels
Returns
-------
df : :cl... | cf9a04c026d4793cf47074706083ec4f8be7dc00 | 655,905 |
import numpy
def run_length_to_mask(
mask_rle: str = "", shape: tuple = (1400, 2100)
) -> numpy.ndarray:
"""
Decode rle encoded mask.
:param mask_rle: run-length as string formatted (start length)
:param shape: (height, width) of array to return
Returns numpy array, 1 - mask, 0 - background
"""
s = mask_... | 7a0d7fa38219b18fb5fa1c9ce759e447ba4f1feb | 655,906 |
def pres_to_elev(inhg):
"""Given a pressure in inHg, determine the altitude (MSL) it normally
occurs at (distance from 29.92)."""
return inhg * 100 | f2c70ed556cd55f0e65b15b0eb67e039ec630a25 | 655,907 |
from itertools import tee
def GC12(sequ):
"""Calculates the GC content average at the 1st and 2nd codon positions.
Args:
sequ (str): DNA sequence
Returns:
int: GC12 value
"""
GC1 = 0
GC2 = 0
sequ = str(sequ)
codon, codon_1 = tee(sequ[i: i + 3] for ... | e64467afe06a31b53b9894567a4d8c5db00992bd | 655,909 |
def get_capi_link_library_name() -> str:
"""Gets the library name of the CAPI shared library to link against."""
return "NPCOMPPythonCAPI" | 0261e0293d4c541642d075dc08210ea3c35fcb1d | 655,910 |
import glob
import re
def _find_weights(ckpt_path, paths=None, start=0):
""" ckpt_path should be format string containing '{epoch}'
>>> paths = ['abc.01.ckpt', 'abc.05.ckpt', 'abc.best.ckpt']
>>> _find_weights('abc.{epoch}.ckpt', paths=paths)
[(0, 'abc.01.ckpt'), (4, 'abc.05.ckpt')
"""
if pat... | c3a0da1576edc11bc599c017225e8400a5521d7a | 655,912 |
def readFASTA(inputfile):
"""Reads a FASTA file and skips the sequence information line with special character removed"""
with open(inputfile, "r") as f:
# remove name line / info line
seq = f.readline()
# read data
seq = f.read()
# remove special character
seq = ... | 2111392e348d28579e16dbe1bde812e7fc88f54c | 655,913 |
import ast
def is_literal(node: ast.AST) -> bool:
"""
Checks for nodes that contains only constants.
If the node contains only literals it will be evaluated.
When node relies on some other names, it won't be evaluated.
"""
try:
ast.literal_eval(node)
except ValueError:
ret... | 87001f4e8112217f3d6552ad95c8417e01e0c9a3 | 655,914 |
import os
import glob
def __get_alljoyn_libs():
"""Gets the complete path to files liballjoyn_java.so and alljoyn.jar.
They are returned as [jar_lib, so_lib] or a warning message is printed
and the return value is []."""
return_value = []
# The source of the libraries is found via an environment variabl... | 0259c544ad9368c5733d7b6140406adbde3a0490 | 655,916 |
def buy(portfolio, ticker, ticker_price, amount):
"""Buys stocks for the bot's portfolio"""
price = ticker_price * amount # ($)
if portfolio['Cash'] > price:
portfolio[ticker] += amount
portfolio['Cash'] -= price
return portfolio
else:
return portfolio | 7ea339ddcedbb1ea2ffd4d39e1ab89edae64147c | 655,917 |
def _format_pep_number(pep_number):
"""
The PEP number as a 4-digit string.
This is the format used by the URLs on python.org.
"""
return str(pep_number).rjust(4, '0') | 2fa00d3fafb2d4e7159a8e5d29f81f71b6352d1d | 655,918 |
import hashlib
def md5sum(fpath):
"""Compute the md5sum hash of the content of a given file."""
blocksize = 65536
hash_md5 = hashlib.md5()
with open(fpath, "rb") as f:
for block in iter(lambda: f.read(blocksize), b""):
hash_md5.update(block)
return hash_md5.hexdigest() | 312811fe577393120fb8b75cebdc6bc07d9c231d | 655,919 |
def field(date, type=None, lead_time=None):
"""Forecast field locator
Maps verification date and lead time off set to file name and
index along file *time_counter*
.. note:: User-specified stub
:param date: The verification date in string format ``'%Y%m%d'``
:param type: Forecast type
:pa... | 273247448a9ad6b92f35741878cb3fbdd6a49a87 | 655,920 |
def checkKeysPerLetter(prevKeyslst, checkKeyslst):
"""
This method will keep the keys that exist in both lists
"""
keys = list(set(prevKeyslst).intersection(checkKeyslst))
return keys | 0b1add82219eb9971f24463b6df12b439e4e1776 | 655,921 |
def grad_descent_step(grad_fns, *args):
"""Computes the gradients block wise.
Args:
grad_fns: The gradient computation functions.
*args: The values of the input variables. (e.g. images and targets).
"""
args = list(args)
# Compute the first iteration
result = grad_fns[0](*args)... | 05ee66f01e93e78484bbaf5c2720743984ae7240 | 655,922 |
import os
import csv
def __init_stance(fname=os.path.join(os.path.dirname(__file__),'data','stance_seeds.txt')):
"""
Initialize the stance keyword list
"""
with open(fname) as f:
reader = csv.reader(f)
header = next(reader)
assert header == ["keyword", "candidate", "stance"]
... | 116a16170ebea9fd1a5b756a95ff4d55d0ef9853 | 655,923 |
def clean_list(lst):
"""
Returns a new but cleaned list.
* None type values are removed
* Empty string values are removed
This function is designed so we only return useful data
"""
newlist = list(lst)
for i in lst:
if i is None:
newlist.remove(i)
if i == ""... | ab71627da03b515fee18c2f2bcc82b45cc0ec0a3 | 655,924 |
def compare_schemas(current: dict, old: dict) -> bool:
"""Returns true if schemas are functionally the same"""
return current == old | 6016a891b48479ef07111aacd2b68cee8be68f16 | 655,925 |
def cache_outputs(cls):
"""
Task class decorator applied to all task classes by default unless they define the attribute 'nocache'::
from waflib import Task
class foo(Task.Task):
nocache = True
If bld.artifacts_cache is defined and if the task instances produces output nodes,
the files will be copied into ... | 95735a21e0b084cd65c8945f0c0298207d6205c6 | 655,926 |
def _get_data(title, func, dest):
"""Populate dest with data from the given function.
Args:
title: The name of the data
func: The function which will return the data
dest: a dict which will store the data
Returns:
dest: The modified destination dict
"""
# Get inter... | d2d4c7374c7216a5150d92f13f3eb7d98391f721 | 655,927 |
def find_holder(card, hands):
"""returns the holder of a given cards"""
holder = -1
for player_num, hand in enumerate(hands):
if card in hand:
holder = player_num
return holder | 8582ff45a0a3c0c9b4cd2a01713a5418172c26dd | 655,928 |
import struct
import hmac
import hashlib
import six
def hotp(key, counter, digits=6):
"""
These test vectors come from RFC-4226
(https://tools.ietf.org/html/rfc4226#page-32).
>>> key = b'12345678901234567890'
>>> for c in range(10):
... hotp(key, c)
'755224'
'287082'
'359152'
... | 0073202eea3fa9339f0f108b7b3e53e72ae7475c | 655,929 |
def _start_end_step(arr):
"""
Return start, end, step if the array is a progression.
"""
if len(arr) == 1:
return (arr[0], arr[0], 1)
elif len(arr) == 2:
return (arr[0], arr[1], arr[1] - arr[0])
elif list(range(arr[0], arr[-1] + 1, arr[2] - arr[1])) == arr:
return (arr[0]... | 1bdc452a6cf4346dc84390d7305567d5d00e798b | 655,930 |
import math
def schwefel_b_function(transposed_decimal_pop_input):
"""Schwefel - B Test Function"""
y = []
for individual in transposed_decimal_pop_input:
schwefel = 0
for idx, xi in enumerate(individual):
schwefel = schwefel + (-xi*(math.sin(math.sqrt(abs(xi)))))
# y... | 8d7af2361e800f8fa4f055a0772e14faaf422aa6 | 655,931 |
import time
def render(payloads):
""" Render multipart/form-data MIME type.
@param payloads: The payload to render according to the MIME type.
@type payloads: Str
@return: The properly rendered payload.
@rtype : String
Note: To understand why we iterate over multipart/formdata like this one... | 491661f22573d9b7157a5c9c243afc28ebf19bc7 | 655,932 |
def _isRunMaskDuplicate(run, lumis, runLumis):
"""
Test whether run and lumi is a subset of one of the
runLumi pairs in runLumis
:param run: integer run number
:param lumi: set of lumis
:param runLumis: list of dictionaries containing run and lumis
"""
for runLumi in runLumis:
if... | 4b17001087175db9325efaa7f7420bc75a6f1e61 | 655,933 |
def fill_zeros(s,n):
"""
Add zeros to a string s until
it reaches length n.
"""
while len(s) < n:
s= ''.join(('0',s))
return s | 0b25353954070668d4bdb3450287b2291008d019 | 655,934 |
from typing import Union
import json
def _parse_doc(doc: Union[str, dict]) -> dict:
"""Parse policy document if necessary.
Args:
doc: Policy document to parse.
Returns:
Parsed policy document.
"""
if isinstance(doc, (str, bytes)):
return json.loads(doc)
return doc | 84bcb1b5eb2d4d106c249f5354ff4eb64cdd85ef | 655,936 |
def reduceby(key, binop, seq, init):
""" Perform a simultaneous groupby and reduction
The computation:
>>> result = reduceby(key, binop, seq, init) # doctest: +SKIP
is equivalent to the following:
>>> def reduction(group): # doctest: +SKIP
... return reduce... | efe74c29ec31d26f8831bd672cc1c2271b1e931a | 655,937 |
def gui_string(title, content, footnote=None, iptnote='', mode='select', isprint=False):
"""
生成GUI界面,默认文本宽度为62字符
:param title: 标题
:param content: 内容
:param footnote: 注脚,如果有
:param iptnote: 最后一行Input后面的提示字符串,可输入默认值
:param mode: 等于select时内容格式为数字加功能,选择,等于其他时,内容格式为说明字符串
:return:
"""
gui = f'|{"":=<60}|\n' # 第一行
... | be86abd19d2f76c9cbfbab29a216ef3e3b2045fb | 655,938 |
import copy
def _sr2ud_fmt(sr_raw_data):
"""
Convert the extracted raw SR data to UD CoNLL format.
Main difference: the contents of the second columns is copied to the third column.
Needed because UD and SR Task data have different semantics for the 2nd and 3rd columns.
- UD: FORM, LEMMA
... | 16811dfb06b0336ef0e5e174f3eb27ccc0280e74 | 655,939 |
def tweets_mentioned_in(user_id, node_collection):
"""notation 9"""
query = {'_id': user_id}
attr = node_collection.find_one(query)
return set(attr['mentioned_in']) | aa2d44b357992e240df03ec654f6ee38fb4fd97d | 655,940 |
import re
def nome_valido(nome):
""" Validando o nome """
return not bool(re.search(r'\d', nome)) | 340cca72e945bf7cadcd69548fc2c9b6cbb8f5cd | 655,943 |
def arrayRatio(numerator,denominator):
"""
Returns the average ratio of numerator to denominator. (e.g. Given
numerator ['123','456'] and denominator ['222','333'], returns 1.043...)
"""
lennum = len(numerator)
lenden = len(denominator)
lenlower = min(lennum,lenden) #finds list with less v... | f637ee30dd7bcfc308a0bc6ee3522d581b975fc0 | 655,944 |
def bubble_sort(arr):
"""
Performs a bubble sort algorithm
- Time complexity: O(n²)
Args:
arr (list): List to sort
Returns:
(list): Sorted list
"""
j = len(arr) - 1
while j >= 0:
i = 0
while i < j:
if arr[i] > arr[i+1]:
te... | 8660f757d282d99d7ded292bc2c526095ea74214 | 655,945 |
def undirected_edge_name(u, v) -> str:
"""
:return The name of an undirected edge as "(u,v)" with u <= v.
"""
u_i, v_i = int(u), int(v)
if u_i > v_i:
u_i, v_i = v_i, u_i
return f"({u_i},{v_i})" | 0ad35c9006ead67393839e6ad9186d01dddc7f7b | 655,946 |
def func_exp(x, a, b, c):
"""Fit an exponential function."""
return a * x + b * x ** 2 + c | 2ed3d47cf8b50cf0fae8e79b6c31b1a83171173f | 655,947 |
def _safe_toint(val):
"""
Try and turn a string into a number, returning -1 if
In this case, I know that valid values will never be -1, so returning that is forcing a failure
:param val:
:return:
"""
try:
return int(val)
except ValueError:
return -1 | 0a17687cc0d9518dff940f123576647d680bab61 | 655,948 |
import requests
from bs4 import BeautifulSoup
import re
def create_ExoMol_tag_array(url, broad_URL):
"""
Create a list of html tags that contain the URLs from which we will later download files
Parameters:
url (string): The ExoMol URL for the webpage that contains download links to all the fi... | 751889e354d5b90b41f55a6dbfb7f78b11c6ff3b | 655,949 |
def needed_to_tuple(var_full, needed):
"""Extract only needed variables to a new tuple."""
return tuple(var for var, n in zip(var_full, needed) if n) | 345717b31d54071b5943d55c51da8437a28dc55e | 655,950 |
def disp_components(modules, module_implements):
"""
For the found modules display them in a form that the user can
copy/paste into their CMakeLists.txt file.
:param modules: The modules.
:param module_implements: Modules implementing other modules.
:return:
"""
res = 'find_package(VTK\... | 11b7629ff5e7daac9bbc1c132af5716763530168 | 655,951 |
from typing import List
def hex_to_rgb(value: str) -> List[float]:
"""Converts hex to normalized rgb colours
Args:
value (str): string of 6 characters representing a hex colour
Returns:
list[float]: rgb color list
"""
value = value.strip("#")
lv = len(value)
rgb_vals = tu... | 0f10086ba88e02a2f59f896c602584b4bef24d84 | 655,953 |
def _compute_colocation_summary_from_dict(name, colocation_dict, prefix=""):
"""Return a summary of an op's colocation stack.
Args:
name: The op name.
colocation_dict: The op._colocation_dict.
prefix: An optional string prefix used before each line of the multi-
line string returned by this fu... | a8cd7b8fc837d9098f84910f832fbc2ebba45ebd | 655,954 |
def _get_function_base_path_from_stack(stack):
"""
Given a stack (in the format as inspect.stack() returns),
construct the path to the function (it may be a top-level in the module or defined in some deeper namespace,
such as a class or another function).
@param stack: The list similar in format to... | c918cdf0ef993aa8223b335dc85375901225e109 | 655,955 |
import json
def printjson(toprint, exception_conversions={}):
"""print anything in json format. Can override printing for custom
types using a dictionary of types to lambda conversion functions.
Examples:
printjson(data)
printjson(data,{sp.DenseSparseMatrix: lambda x: f"matrix = {x}" })
... | 0fe60c63ff5f1ab84bee8fb8af39513bad90f78a | 655,956 |
import optparse
import sys
def ParseOption():
"""Parse command line options."""
parser = optparse.OptionParser()
parser.add_option('--path_to_be_embedded', dest='path_to_be_embedded')
parser.add_option('--constant_name', dest='constant_name')
parser.add_option('--output', dest='output')
(options, unused_... | 9658675872fa39d373cac4b35235cf7438b4b2cd | 655,957 |
def iteritems(obj, **kwargs):
"""Iterate over dict items in Python 2 & 3."""
return (obj.iteritems(**kwargs)
if hasattr(obj, 'iteritems')
else iter(obj.items(**kwargs))) | f35437e0141cd951bd8485e004a9504a823e71ca | 655,958 |
def calculate_handlen(hand):
"""
Returns the length (number of letters) in the current hand.
hand: dictionary (string-> int)
returns: integer
"""
return sum(hand.values()) | 877a3faa981624ab869460d96fabcc8e93623bf1 | 655,960 |
def generate_bond_indices(natoms):
"""
natoms: int
The number of atoms
Finds the array of bond indices of the upper triangle of an interatomic distance matrix, in column wise order
( or equivalently, lower triangle of interatomic distance matrix in row wise order):
[[0,1], [0,2], [1,2], [0,3... | 2484a45c653b027de126713d8b7984551b2a1cd1 | 655,961 |
def health_check():
"""simple health status check page"""
return {"status": "okay"} | a957954489ed0898b749f299aad6c5af9ced7dd4 | 655,962 |
from pathlib import Path
def to_condition(p: Path, ind: int = -1, sep: str = "_") -> list:
"""
converts path into a row for condition dataframe
it assumes that the names of the files have pars separated by "_" or other separator
:param p path to the file
:param ind where in a splited file name to ... | 9b21cf13668256ae3cfbb9d092827705db9d6027 | 655,963 |
from typing import Dict
def _get_labels_dict(label_str: str) -> Dict[str, str]:
"""
Converts CLI input labels string to dictionary format if provided string is valid.
Args:
label_str: A comma-separated string of key-value pairs
Returns:
Dict of key-value label pairs
"""
label... | d3b8024e7692fd281ba03c6f8c03cc69ebcdffa2 | 655,965 |
def make_query_to_get_users_profiles(userIds):
"""Returns a query to retrieve the profile for the indicated list of
user ids
Api info:
parameter name: user_id
values: A comma separated list of user IDs, up to 100 are allowed in a single request.
Notes: You are strongly encouraged to ... | e248b36a7c09381948c9346f4d494754547bb7bd | 655,966 |
def get_env_name_custom_http_headers():
"""Specifies HTTP headers as JSON content, to be injected into responses sent to the browser"""
return "MWI_CUSTOM_HTTP_HEADERS" | 74a5235c79991b0e60d5e1ce09037ffa7027f428 | 655,967 |
import json
def load_metadata(transaction):
"""
Try loading metadata for an item. This is wonky because sometimes data is double encoded
:param transaction: transaction to load metadata for
:return: dict of transaction
"""
try:
# double load the metadata since that occasionally
... | 1c99732c3d52ce05cf117a93a171b2f2744069af | 655,968 |
import os
import shutil
def _backup(filepath):
"""Create a backup of the given file."""
if not os.path.exists(filepath):
return
directory, filename = os.path.split(filepath)
backup_filepath = os.path.join(directory, ".{}.bkp".format(filename))
print("Doing backup from {!r} to {!r}".format(... | 10b327852409133742c5d6f4d88f0d508a67c75f | 655,969 |
import re
import unicodedata
def unicode_normalize(cls, s):
"""Neologd プレ処理"""
pt = re.compile('([{}]+)'.format(cls))
def norm(c):
return unicodedata.normalize('NFKC', c) if pt.match(c) else c
s = ''.join(norm(x) for x in re.split(pt, s))
s = re.sub('-', '-', s)
return s | b8380dc6a38b76c1562ff0f596a42979732c9f5d | 655,971 |
def seconds_to_str( s ):
"""秒转化天 时 分 秒"""
day = s / 86400
hour = ( s % 86400 ) / 3600
minute = ( s % 3600 ) / 60
secs = ( s % 60 )
ret = ''
if day:
ret += '%d天' % day
if hour:
ret += '%d小时' % hour
if minute:
ret += '%d分' % minute
if secs:
ret += '... | 86fc0eaffecf2017b8bf4f6b4dee84fb9f007498 | 655,972 |
import json
def mocked_requests_get(*args, **kwargs):
"""Defines a response suitable for mocking requests responses."""
class MockResponse:
"""Solution cribbed from
https://stackoverflow.com/questions/15753390/how-can-i-mock-requests-and-the-response/28507806#28507806
"""
def _... | 3bb884627a82de6cffee7583f5bd1aa5a5d605b0 | 655,973 |
def get_vendor_maps():
"""The data is based on http://pci-ids.ucw.cz/read/PC/
:return: vendor maps dict
"""
return {"10de": "nvidia",
"102b": "matrox",
"1bd4": "inspur",
"8086": "intel",
"1099": "samsung",
"1cf2": "zte"
} | 00163920c40e8586c9b25dec0143c8d5d8269877 | 655,974 |
def getManifestEtag(manifest):
""" returns Etag hash for manifest"""
return manifest["Etag"] | a493779cc739ba38244885ecfe4e92195a7ee467 | 655,975 |
def _zerocrossings(x):
"""Find indices of zero-crossings in a 1D array.
Parameters
----------
x : np.array
One dimensional data vector.
Returns
-------
idx_zc : np.array
Indices of zero-crossings
Examples
--------
>>> import numpy as np
>>> from yasa.main i... | c5aa962848032d657e012af031f57c10c11688c0 | 655,976 |
import random
def generate_uuid():
"""
<comment-ja>
ランダムなUUIDを生成する
@return: UUID用の16個のバイト要素を持つ配列
</comment-ja>
<comment-en>
Generate UUID
@return: Array UUID
</comment-en>
"""
uuid = []
for _x in range(0, 16):
uuid.append(random.randint(0x00,0xff))
return uu... | 4ff06f115c37805ab9fe010d6ed993ec7dd504db | 655,977 |
from pathlib import Path
def get_new_files(commit, dir):
"""Return new files in commit that are in dir directory"""
files = []
for file in commit.files:
if Path(dir) in Path(file.filename).parents and file.status == "added":
files.append(file)
return files | 0e8d48fc38f1e07dd1eeca0580c12f0e65057427 | 655,978 |
import math
def _datetime_to_timestamp(dt, period, round_up=False):
""" Convert a datetime object to a timestamp measured in simulation periods.
Args:
dt (datetime): Datetime to be converted to a simulation timestamp.
period (int): Length of one time interval in the simulation. (minutes)
... | 023a7e971db655abb04fa7fb53ceb535553ab076 | 655,979 |
import argparse
def get_args():
""" function for getting commandline arguments """
parser = argparse.ArgumentParser()
parser.add_argument('-d', '--daemon', action='store_true',
help="Draai script als daemon")
parser.add_argument('-u', '--url', help="URL van liveblog")
retu... | 624fb3b4ea2f68610bf040b2c40848ed5251f065 | 655,980 |
def list_hasnext(xs):
"""Whether the list is empty or not."""
return len(xs) > 0 | 6b244a979ea129efe7d39e554b9986c76653bfe0 | 655,982 |
def rescale(src_scale, dest_scale, x):
"""Map one number scale to another
For example, to convert a score of 4 stars out of 5 into a percentage:
>>> rescale((0, 5), (0, 100), 4)
80.0
Great for mapping different input values into LED pixel brightnesses!
"""
src_start, src_end = src_scale
... | 4ba97ac516e07b5ed8ae7fee80a80ee4b13b7674 | 655,983 |
import six
def downgrader(version):
"""
A decorator for marking a method as a downgrader to an older
version of a given object. Note that downgrader methods are
implicitly class methods. Also note that downgraders take a
single argument--a dictionary of attributes--and must return a
dictiona... | e136829783f2e002ee741fed7acf210d6235c535 | 655,984 |
def getTelem():
"""
Method to get all telemetry from the Arduino Serial port.
When this is accessed, all data will be displayed for all systems.
All other functions should be executed when this is called.
"""
return ("Still in the makes") | 1741468b4ecf63c5587c6bc74c8eaf65f3644f94 | 655,985 |
from typing import Union
from pathlib import Path
def is_notebook(file: Union[Path, str]) -> bool:
"""Determines whether a file is a notebook file or not.
Args:
file: the file, as either a pathlib.Path object or a filename string.
Returns:
True if notebook file, else False.
"""
i... | 7afc70c8151c2fb18497250d67c29fe2fafac3a5 | 655,986 |
import os
def get_jobfile(cmd, job_name, dep_ids=[], email=False,
sbatch_path='./sbatch/', hours=8):
"""
Create a job file.
adapted from https://github.com/gyyang/olfaction_evolution
Args:
cmd: python command to be execute by the cluster
job_name: str, name of the job ... | dd293e555cb9e8d15a6c3be0464575f508c58d68 | 655,987 |
def extract_major_version(scala_version):
"""Return major Scala version given a full version, e.g. "2.11.11" -> "2.11" """
return scala_version[:scala_version.find(".", 2)] | 9a3fbee2a3962e28dd29b4ddb6870ecd5ca97d1f | 655,988 |
def count_kmers(id,read,k,counts):
"""Count kmer occurrences in a given sequence.
Parameters
----------
id: number of sequence.
read : string
A single DNA sequence.
k : int
The value of k for which to count kmers.
counts : dictionary, {'string': int}
A dictionary of counts ke... | ccd9fc1678f4f5ef7136d7b0339b6322e6745e10 | 655,989 |
def sanitize(message: str) -> str:
"""
Removes backticks (code tag) and linebreaks from a message.
"""
return message.replace('`', '').replace('\n', '') | 79c9c951873ce56151bd05a903f91a269c155196 | 655,990 |
def distLinf(x1, y1, x2, y2):
"""Compute the Linfty distance between two points (see TSPLIB documentation)"""
return int(max(abs(x2 - x1), abs(y2 - y1))) | 9a47b59b139445105ad757c5f2d43f5a0c228be2 | 655,991 |
def get_windows_path_with_slashes(url: str) -> str:
""" idiotic fix for windows (\ --> \\\\)
https://stackoverflow.com/questions/1347791/unicode-error-unicodeescape-codec-cant-decode-bytes-cannot-open-text-file"""
return url.replace('\\', '\\\\') | 36089c68ee1355d6ec8fd4d5d3f7e8c1c0f8fb76 | 655,992 |
import re
def is_special_character(string, i, pattern):
"""
Returns True if the i-th character in the given string is a special
character, False otherwise. The character is *not* a special character if
it is a dot and it is surrounded by two digits, like in "1.23".
>>> is_special_character(["a", ... | 2ed0e5158e469f305b3f359f9c6e923d8c9ef623 | 655,993 |
def calcArea(vertexes):
"""
:param vertexes:
:return Float: Area of the polygon, Positive value means clockwise direction, negative counter-clockwise.
>>> calcArea([Point(0, 0), Point(0, 1), Point(1, 1), Point(1, 0)])
-1.0
>>> calcArea([Point(0, 0), Point(1, 0), Point(1, 1), Point(0, 1)])
... | 813ca2c6e6fa693539307380838fbabdfd881a16 | 655,994 |
def splitDataSet(dataSet, axis, value):
"""
按照给定特征划分数据集
:param dataSet:待划分的数据集
:param axis:划分数据集的特征
:param value:需要返回的特征的值
:return:划分结果列表
"""
retDataSet = []
for featVec in dataSet:
if featVec[axis] == value:
reduceFeatVec = featVec[:axis] # chop out axis use... | fe63e8afe7e7a3684e8b0b284df511ff2ef768f9 | 655,995 |
import sys
import re
def unversioned_platform():
"""Return the unversioned platform string.
Possible return values:
linux, aix, sunos, darwin, win32, cygwin
"""
s = sys.platform
if s == 'powerpc':
return 'darwin'
if s == 'win32' or s == 'os2':
return s
return re... | 1b17628a1d920e0db42cdedffb76ed9ddefd1fba | 655,997 |
def bayesdb_colno_to_variable_names(bdb, population_id, generator_id):
"""Return a dictionary that maps column number to variable name in population."""
cursor = bdb.sql_execute('''
SELECT colno, name FROM bayesdb_variable
WHERE population_id = ?
AND (generator_id IS NULL OR ... | 27d2e1ac9bcebe80ebf83f2d76df7dad8a1fcc8b | 655,998 |
def create_price_table(sqlite3_cursor):
# ZX: Rememeber there are only 5 data types in Sqlite3: text, numeric, integer, real, blob
"""
TRADE DATE (YYYY-MM-DD)
STOCK NAME (30 chars)
REMARKS (8 chars) SUSP - Suspended
CURRENCY (4 chars)
HIGH (7 chars, including decimal point... | 9a5866aa290351af316cd3c7355205a2faeda628 | 655,999 |
import fnmatch
def _fnmatch_lower(name: str | None, pattern: str) -> bool:
"""Match a lowercase version of the name."""
if name is None:
return False
return fnmatch.fnmatch(name.lower(), pattern) | e04d207de691dd3ee5d35dccf88a8c0ed8e5fc3c | 656,000 |
def denormalize_loc(locations, img_height, img_width):
"""convert locations from normalized co-ordinates in range [0,1] back into pixel co-ordinates
Parameters
----------
locations : numpy.ndarray
with two columns (y, x) (not (x, y), because of how array indexing works)
img_height : int
... | e1bcd35052bcfd14880c38c32a1477ded69a4413 | 656,001 |
import sys
import importlib
def get_blueprint_tester(client, blueprint_dir):
"""
Import the test boilerplate from the blueprint directory.
"""
sys.path.append(blueprint_dir)
fixture = importlib.import_module("blueprint_fixture")
return fixture.BlueprintTest(client) | bc0e471b8a4ea13059cac189bc3bbb6519aead47 | 656,002 |
def _string_id(*args):
"""Creates an id for a generic entity, by concatenating the given args
with dots.
Parameters
----------
*args: str
The strings to concatenate
Returns
-------
basestring: an identifier to be used.
"""
def is_valid(entry):
return (
... | b6cef4a7291f25ea72b0de76ea927bee9b86f560 | 656,003 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.