content stringlengths 35 416k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
import copy
def dpart_1(f, x, p, h=0.001):
"""
Calcula la derivada parcial de f en el punto x, en la coordenada p
"""
x1 = copy.deepcopy(x)
x2 = copy.deepcopy(x)
x1[p] -= h
x2[p] += h
return (f(x2) - f(x1))/(2*h) | 3703079005f3a8778085de05d1edc5ed252f8c3f | 638,563 |
import json
def get_traffic(reddit, target_subreddit):
"""Save a subreddit's traffic as json file"""
traffic = reddit.subreddit(target_subreddit).traffic();
with open("traffic.json", 'w') as file:
file.write(json.dumps(traffic));
return traffic; | ed65efe674fc2fbe21c54d68b4120a3ee895a449 | 638,564 |
import base64
def encode_base64(input_bytes: bytes, urlsafe: bool = False) -> str:
"""Encode bytes as an unpadded base64 string."""
if urlsafe:
encode = base64.urlsafe_b64encode
else:
encode = base64.b64encode
output_bytes = encode(input_bytes)
output_string = output_bytes.decode... | 65f9c091e4e4c3f0cf2f18f226e3c2a61b384d79 | 638,565 |
def cleanupElements(this_root): # called from schedule()
"""Given the root of the xml tree, this goes through the courses and removes any elements that don't have info about meeting times, then returns the revised root"""
for course in this_root.findall('Course'):
for element in course:
if ... | c1dd21a430b12a643efb6668d41adb308fd631d6 | 638,566 |
def factorial(num):
"""
The factorial of a number.
On average barely quicker than product(range(1, num))
"""
# Factorial of 0 equals 1
if num == 0:
return 1
# if not, it is the product from 1...num
product = 1
for integer in range(1, num + 1):
product *= integer
... | bdbe091570fa328ede28d0c750334960046308d5 | 638,568 |
def defuzz_centroid(fset):
"""
Defuzzification using centroid (`center of gravity`) method.
Parameters
----------
fset : dictionary, length M
Fuzzy set
Returns
-------
center : float,
center of gravity
"""
# check for input type
if not isinstance(fset,... | 555574394d1231112489c11bb3b44054712488af | 638,569 |
def columnise(rows, padding=2):
"""Print rows of entries in aligned columns."""
strs = []
maxwidths = {}
for row in rows:
for i, e in enumerate(row):
se = str(e)
nse = len(se)
w = maxwidths.get(i, -1)
if nse > w:
maxwidths[i] = nse... | eb4f31f63f51254f449590006cc77f9af7c65d70 | 638,570 |
import torch
def normalize(scan: torch.Tensor) -> torch.Tensor:
""" Normalization to [0, 1] """
s_min, s_max = scan.min(), scan.max()
return (scan - s_min) / (s_max - s_min) | 1b7e00a45b982ff721b433b6c91314617d1b30a8 | 638,571 |
def ID_to_int(s_id):
"""
Converts a string id to tuple
falls back to assuming ID is an Int if it can't process
Assumes string IDs are of form "[chars]-[int]" such as mp-234
"""
if isinstance(s_id, str):
return (s_id.split("-")[0], int(str(s_id).split("-")[-1]))
elif isinstance(s_id, ... | 74a99fb1dbd1cee285507dd255c7f21a1b45be70 | 638,572 |
def data_population(in_data, headers=None):
"""Convert a list of lists into a list of dicts associating each
cell with its column header and row
:param data: two dimensional list of data
:param fields: column headers
:return: JSON representation of rows
"""
headers = headers or in_data[0]
... | aa28a3b90724d11b3fdcd78aaf6efccac4eef176 | 638,573 |
def version():
""" Is there a better way to have some unique source for the version?
Should investigate.
"""
return "0.3.1" | e6bf78972602f395d951c457cca558c1711eee79 | 638,574 |
def quicksort(lst):
"""quicksort with filter and lambda"""
if not lst:
return lst
else:
pivot, *rest = lst
return (
quicksort(list(filter(lambda x: x < pivot, rest)))
+ [pivot] +
quicksort(list(filter(lambda x: x >= pivot, rest)))
) | 3378e89efeb971cd5e0ea8407afbf208d5ccfc04 | 638,575 |
def get_area_covered(tile_name, tile_size):
"""
The function that calculates the area covered in a image
param: tile_name: The name of the tile, from which we get the height
param: tile_size: The size of the tile, from which we calculate the total area
"""
def get_current_res(height):
re... | b010075a5aa6663ccce8edbccbdaa684a932ce7f | 638,576 |
import os
def file_exists(path_to_file):
"""
:param path_to_file: path to file which needs to be checked
:return: True, if file exists
"""
return os.path.exists(path_to_file) | e445c19f8c287ab62c9b3521d5ffef4dd3ab2a46 | 638,577 |
import subprocess
import os
def git_root(*args):
"""
Returns the root path of the git repository (without trailing slash).
Any additional (and optional) arguments will be appended to the path
Examples
----------
> git_root()
/home/user/my_repo
> git_root('dir1', 'file')
/... | 3b57f3ced297cfaf16b82c521a42aa991645e198 | 638,578 |
import re
def remove_ansi_escape_sequence(string):
"""Remove ansi escape sequence.
https://stackoverflow.com/questions/14693701/how-can-i-remove-the-ansi-escape-sequences-from-a-string-in-python
"""
ansi_escape = re.compile(r"\x1B(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~])")
return ansi_escape.sub("", stri... | abeed60b0ed980c0015579e00ba28ec6fcdcfe3a | 638,579 |
import copy
def two_sum_search(h, targets):
"""
two_sum_search checks each value in h to see if two numbers in h
reach one of the target values in the target list.
"""
final_set = copy.deepcopy(targets)
for t in targets:
for x in h:
if t-x in h:
final_set.... | e875c3bbc0dee595ad64cbb1340f31503fa86004 | 638,580 |
def locked(client, message):
"""Check if the user has been command-locked."""
if getattr(client, 'ongoing_commands', False) is not False:
return message.author.id in client.ongoing_commands[message.channel.id]
return True | ea7f26a6ee6ad371a64eb23cba8a0401d91cb11a | 638,581 |
def tkeo(a):
"""
Calculates the TKEO of a given recording by using 2 samples.
See Li et al., 2007
Arguments:
a --- 1D numpy array.
Returns:
1D numpy array containing the tkeo per sample
"""
# Create two temporary arrays of equal length, shifted 1 sample to the right
# and left and squared:
i ... | bd53cace1ae1e6b0aa99aaed22b1a33c573265bd | 638,582 |
def Mj_from_spt(x):
"""
Lepine Mj to SpT relationship (Lepine et al. 2013, Equation 23, page 24)
:param x: numpy array, SpT
:return:
"""
return 5.680 + 0.393*x + 0.040*x**2 | f26c1169173fcecc0ff9161903ca6339f1c907bc | 638,583 |
def _CheckEnum(value, name, values=None):
"""Checks whether value is a member of the set of values given.
Args:
value: The value to check.
name: The name of the value, to use in error messages.
values: The iterable of possible values.
Returns:
The checked value.
Raises:
ValueError: If the... | c18e91bd7a83b0a8e604b51940c18dfb16346ede | 638,584 |
import hashlib
def generate_hashed_slug(slug, limit=63, hash_length=6):
"""
Generate a unique name that's within a certain length limit
Most k8s objects have a 63 char name limit. We wanna be able to compress
larger names down to that if required, while still maintaining some
amount of legibility... | e466a2ba31c81b3961e8ff7215ce51a71c44acd5 | 638,585 |
def get_background_genes_file(filepath):
"""
Get background genes from local file for null-hypothesis formulation.
"""
gene_list = []
with open(filepath) as file_gene:
for line in file_gene:
gene_list.append(line.strip())
return gene_list | 7498bcc40897359bc02b4a6c924aaf8056f05209 | 638,586 |
def traverse(obj, callback=None):
"""
walks a nested dict/list recursively
:param obj:
:param callback:
:return:
"""
if isinstance(obj, dict):
value = {k: traverse(v, callback) for k, v in obj.items()}
elif isinstance(obj, list):
value = [traverse(elem, callback) for ele... | 0e1edf930f25030d297c3275ad5bd0fb3a42aa48 | 638,587 |
def uch_leung(us, ut):
"""
Choking velocity based on Equation 6 from Leung [2]_. All parameters must
be in units of ft/s or in units of m/s.
Parameters
----------
us : float
Solids velocity [ft/s or m/s]
ut : float
Terminal velocity of a single particle [ft/s or m/s]
Re... | 1455ba7f3a1ba45a4c722d6b2619de7ef630d3e2 | 638,588 |
import json
def pretty_json(dict_like_object: dict):
"""Taken from https://www.tensorflow.org/tensorboard/text_summaries"""
json_dict = json.dumps(dict_like_object, indent=2)
return "".join("\t" + line for line in json_dict.splitlines(True)) | a6809e564f6443c0be8fbbb816216131b422eab5 | 638,589 |
def year(yearin):
""" asks for the users birth year and adds the digits together and checks if it's a master or not.
If not convert the input to digits and return the sum of the digits."""
# Tests for inputs greater than or equal 13, since no months exists above 12
if len(yearin) == 4:
pass
... | c1194feca308c105ec00be00d8eb7c8686f9f50e | 638,590 |
def is_windows_path(path):
"""Checks if the path argument is a Windows platform path."""
return '\\' in path or ':' in path or '|' in path | 88d856751744f0400bd4db09013492215b363c2a | 638,591 |
def highlight(s):
"""
Возвращает CSS-свойство для заливки фона, в зависимости от содержимого ячейки
"""
if s == 'Участвует':
return "background: #00FA9A"
elif s == 'Недоступен':
return "background: #FA8072"
return None | 388cee45c2ee160cd4fa5c95822fa717e4283a68 | 638,592 |
import pipes
import subprocess
def run(cmd):
"""
Run a shell command
"""
cmd = [pipes.quote(c) for c in cmd]
cmd = " ".join(cmd)
cmd += "; exit 0"
# print("Running {} in {}".format(cmd, os.getcwd()))
try:
output = subprocess.check_output(cmd,
... | ad26e3956a73921d3f204220f73d23c64f6483aa | 638,593 |
def parse_int(strng):
"""
In this kata we want to convert a string into an integer. The strings simply represent the numbers in words.
Examples:
"one" => 1
"twenty" => 20
"two hundred forty-six" => 246
"seven hundred eighty-three thousand nine hundred and nineteen" => 783919
Additional N... | c2ce29795e7ec718cd21837c2ab1a0af3e35d45c | 638,595 |
from operator import truth
def cleanBlockQuotedText(text,joiner=' '):
"""This is an internal utility which takes triple-
quoted text form within the document and returns
(hopefully) the paragraph the user intended originally."""
return text
L=filter(truth,map(_lineClean, split(text, '\n')))
re... | eff17bfbfe38c4dd8b9a1bd36fe18ea82a5542b7 | 638,596 |
from typing import Union
def count_even(obj: Union[list, int]) -> int:
"""
Return the number of even numbers in obj or sublists of obj
if obj is a list. Otherwise, if obj is a number, return 1
if it is an even number and 0 if it is an odd number.
>>> count_even(3)
0
>>> count_even(16)
... | 8d757d7004c11ac77eb85bbc37fd7b3c9e6c4798 | 638,597 |
from unittest.mock import Mock
def set_url_hash(*args, **kwargs):
"""This is added for `anvil_extras`. for some reason it is not in the anvil documentation."""
return Mock() | c9519ccc97040673d79287c98ce6e8dd71986a63 | 638,598 |
def cubicRealRoot(a, b, c, d):
"""
Calculates the real roots of cubic equation. Note: returns only the _real_ roots!
Code as found at http://www.josechu.com/ecuaciones_polinomicas/
"""
twoonethird = 2.0**(1.0 / 3.0)
delta = (-2.0 * b * b * b + 9.0 * a * b * c - 27.0 * a * a * d + ((4.0 * (-b * b... | ce9c74b7d3caf497879c6dfaa2f84e313d213f5c | 638,599 |
from datetime import datetime
def local_to_utc(dtime, zoneinfo=None):
"""Convert local time to UTC time"""
if dtime.tzinfo is not None:
return dtime - dtime.utcoffset()
year, month, day = dtime.year, dtime.month, dtime.day
hour, minute = dtime.hour, dtime.minute
return datetime(year, mont... | deecb91452234a04749fe82f90ae27a9d70148df | 638,601 |
def choices_help_text(choices):
"""Return a clear text for choices.
Args:
choices: list of tuples (value, label)
Returns:
a text in the form:
enum1: label1
enum2: label2
"""
choises_str = ('{enum}: {label}'.format(enum=choice[0], label=choice[1]) for choice... | 67fd67f9e2af7d9ad96de4cea057ac2f992539b7 | 638,602 |
def _shape(tensor):
"""Get the shape of a tensor as an int list."""
return tensor.get_shape().as_list() | 94c17b3def7466a7c24bff542d2455beefd55df3 | 638,603 |
def tipo(inpt, keep_module: bool = True) -> str:
"""
Return the name of an object's type
params:
keep_module
If set to False, the name of the class will be returned without any explicit reference to package nesting
"""
if isinstance(inpt, type):
inpt = str(inpt)
if ke... | 3773e6a51e77b1eb53eb2010f1b5a9407c7bde26 | 638,607 |
import logging
def validate_table_policy(table_policy, table_id):
"""
Checks for public IAM members in a BigQuery table IAM policy.
"""
# Create the public users list to reference when creating new members.
public_users = ["allAuthenticatedUsers", "allUsers"]
# Create our new bindings
bi... | 02eb220891a06c30dc2cd859a76fb883d917bbb3 | 638,608 |
def get_paths(corpus, x, y):
"""
Get the paths that connect x and y in the corpus
:param corpus: the corpus' resource object
:param x: x
:param y: y
:return:
"""
x_to_y_paths = corpus.get_relations(x, y)
y_to_x_paths = corpus.get_relations(y, x)
paths = {corpus.get_path_by_id(pat... | 1828e3e873d57cc6133834bc9b00c480a46a6860 | 638,609 |
def recur_fibo(n):
"""递归函数
输出斐波那契数列"""
if n <= 1:
return n
else:
return (recur_fibo(n - 1) + recur_fibo(n - 2)) | 777f744b0f1c4de03a467eec875f69d0b5b1043e | 638,610 |
def replace_corrupted_instruction(script, instruction_index):
"""
Return the copy of a script with the command (JMP or NOP) of a given instruction replaced.
"jmp" -> "nop"
"nop" -> "jmp"
"""
# Copy the script and get the instruction by index.
new_script = script.copy()
instruction = s... | 583f3cdd3dc7a05d232e2c87825c3e166b253535 | 638,611 |
import json
def define_config():
"""import config file(conf.json)"""
with open("./conf.json", 'r') as conf:
config = json.load(conf)[0] # load config dict
config['project']['bom'] = \
config['BOM'][config['project']['bom']] # set bom format
return config['project'] | e089c7d18b636421079b0e53a212bb58e5bb8ba5 | 638,612 |
def edit_distance(chars, other_chars):
"""
编辑距离
:param chars: 字符串
:param other_chars: 另一个字符串
:return: 编辑距离值
"""
w, h = len(chars), len(other_chars) # 计算出长和宽
array = [[0 for _ in range(h + 1)] for _ in range(w + 1)] # 初始化
for i in range(w + 1):
for j in range(h + 1):
... | 71f50a1410c393d1b3e5d439dfec27a2822ee184 | 638,614 |
def conform_to_argspec(args,kwargs,argspec):
"""Attempts to take the arguments in arg and kwargs and return only those which can be used
by the argspec given."""
regargs, varargs, varkwargs, defaults = argspec
N = len(regargs)
# shallow copy arguments
newargs = list(args)
newkwargs = kwa... | a957fde947a7a1fce9b648aec8aa3eabdd5e89b2 | 638,615 |
import hashlib
import time
def mk_version(version):
"""
Genera el tag de versión.
:param version: Str de la versión
:return:
"""
if len(version) == 0:
exit()
version = version.strip().lower()
if '.' in version or '-' in version or len(version) < 3:
raise Exception('N... | f39c4f54600a2ccf4d644e323f78715b42c69cb9 | 638,616 |
def _create_index(parsed_lib, lib_file_name):
"""Creates a dataframe that will provide an index based on pin count"""
p_dict = {"part_name": [], "pin_count": [], "location": [], "alias": []}
for part in parsed_lib.parts:
p_dict["part_name"].append(part.name)
p_dict["pin_count"].append(len(... | 171e801f39bb2ca7a3b722d7b832112d366278eb | 638,617 |
def property_name(property, index):
# type: (str, int) -> str
"""The Freshdesk API is currently pretty broken: statuses are customizable
but the API will only tell you the number associated with the status, not
the name. While we engage the Freshdesk developers about exposing this
information throug... | 7683195d97697d6566a0f84a340d3cd1ce8c7704 | 638,618 |
from datetime import datetime
def commit_datetime_string(dt: datetime):
"""
Return a string representation for a commit's timestamp.
Args:
dt: datetime object with tzinfo
Returns:
string representation (should be localized)
"""
return dt.strftime("%c %z") | 0e5a1ba69bd185029c175413e0cade9af5933bc3 | 638,619 |
import click
import os
def click_option_config(f):
"""Add config option to command."""
return click.option(
'--config',
type=click.Path(exists=True, resolve_path=True),
default=os.path.expanduser('~/.substra'),
help='Config path (default ~/.substra).')(f) | 9df72a62ee7e4c1b009bfea44ad1f4feb1c4addb | 638,620 |
import argparse
def get_args():
"""
Returns the user arguments.
"""
p = argparse.ArgumentParser(description="Word combination generator.")
p.add_argument("input", type=str, help="string to generate combinations")
p.add_argument("-p", "--pool", type=str, default="", dest="pool",
h... | ca1cc1c52cfaff62724b268d9cce4f6bd7018f92 | 638,622 |
import copy
def get_settings(settings_module):
"""
Get a copy of the settings (upper-cased variables) declared in the given settings module.
:param settings_module: A settings module
:type settings_module: module
:return: Dict of settings
:rtype: dict[str, object]
"""
return copy.deep... | e9cc00c69a8a963ec9dfdb99a2f5759c91083f1f | 638,623 |
import re
def get_domain(long_url: str) -> str:
"""
Takes in a url and gets the top level domain,
e.g. ``https://lmao-d.f.foo.rutgers.edu/lmao.php?thing=true`` becomes ``rutgers.edu``
:param long_url: The URL from which to extract the domain
"""
protocol_location = long_url.find('://')
b... | 431ebd227693244dcfc802b42941c4518282ed84 | 638,624 |
def is_contains_chinese(strs: str):
"""检验是否含有中文字符"""
for _char in strs:
if "\u4e00" <= _char <= "\u9fa5":
return True
return False | f6423c5650aec7ae5fe3315d399fe3e13711e2d0 | 638,626 |
from typing import List
import sys
def snapshot_prompt(snapshots: List[dict]) -> dict:
"""Prompt's the user for an item to select from the items passed. Item is expected to support the Item protocol."""
for i, snap in enumerate(snapshots):
print(f"{i}) Id: {snap['SnapshotId']}, VolumeId: {snap['Volume... | 7642b824c6bb7a728eb566a8be5e84222089ca33 | 638,627 |
import random
def generate(number_of_seeds, seed=None):
"""Uses pythons random integer generator to create a set of unique random
seeds.
Parameters
----------
number_of_seeds : int
number of seeds to generate.
seed : int, optional
The random seed to intialize the generator wit... | 3dce8df5d7d2d645a1734e58dcd10cd01ee2af02 | 638,629 |
import re
def ParseSyslogNGConfMultiHomed(txt, WorkspaceID):
"""
Returns a search to extract facilities and severities for the specified
workspace for syslog-ng format
"""
facility_search = r'^filter f_(?P<facility>.*?)_' + WorkspaceID + '_oms.*?level\((?P<severities>.*?)\)'
return re.compile(... | 050868832259954a69591cf174a2a48842e41a69 | 638,630 |
import json
import copy
def normalize(statement):
"""Make all IAM statements consistent.
>>> s = normalize({'Effect': 'allow', 'Resource': '*', 'Action': 's3:*'})
>>> s['Effect']
'Allow'
>>> s['Resource']
['*']
>>> s['Action']
['s3:*']
"""
if isinstance(statement, str):
... | 158e24e89e2e25f06fe5b868c365a354820868f6 | 638,631 |
def _parse_class_name(value):
"""_parse_class_name
There's got to be a better way to do this.
"""
def _extract_name(name):
return name[8 : name.find(">") - 1]
name = str(value)
tmp = name.find("<class '")
if tmp > -1:
# it is a type
name = _extract_name(name)
e... | d3fc6f5f3aa13c960f5b05bf8bd080a68a8f6404 | 638,632 |
import sys
def get_next_peak(opened_file):
"""
Reads in the next line of the bed and returns the next peak's information
Args: opened_file = an already open input .bed file handle
Returns: a tuple with the following information (in order) or None
chromosome number as a string e.g. "chr1",
... | b54bc54c14480bd074f370b14c3a6a319cfe1101 | 638,633 |
def normalize_images(images):
"""Normalize image values."""
return images.float().div_(255.0).mul_(2.0).add_(-1) | e5d2b9a08b8667f96da8e4f24efb645ddc74d464 | 638,634 |
def build_activation(cls, features=None):
"""Build an activation function with parameters."""
if hasattr(cls, 'GIVE_N_FEATURES'):
return cls(features=features)
else:
return cls() | 010949c068c99fd9a3e636f81defb951f4889ae8 | 638,635 |
import time
def wait_for_task(task, timeout=300):
"""
Wait for a task to complete
"""
timeout_time = time.time() + timeout
timedout = True
while time.time() < timeout_time:
if task.info.state == 'success':
return (True, task.info.result)
if task.info.state == 'error... | 30c1e8e589246c2da0e42850638e59e304e0688c | 638,636 |
from importlib import import_module
def get_code(path):
"""
Given "core.utils:get_code", imports the module "core.utils" and returns
"get_code" from it.
"""
module_name, member_name = path.split(':')
module = import_module(module_name)
return getattr(module, member_name) | 6f9b64e3d8c488f467355663fde0e220864c6256 | 638,637 |
def plotkin_bound_asymp(delta,q):
"""
Computes the asymptotic Plotkin bound for the information rate,
provided `0 < \delta < 1-1/q`.
EXAMPLES::
sage: plotkin_bound_asymp(1/4,2)
1/2
"""
r = 1-1/q
return (1-delta/r) | 28232c7672d39f235216823ecd2dfff1fb2be76e | 638,638 |
import math
def ceiling(x, y):
"""
Returns number rounded up, away from zero, to the nearest multiple
of significance. For example, if you want to avoid using pennies in
your prices and your product is priced at $4.42, use the formula
ceiling(4.42,0.05) to round prices up to the nearest nickel.
... | 5d79ce3e91c48123c612cc91b55a0737caa96105 | 638,639 |
def filterSongs(data, filters=[]):
"""Filter the songs according to the passed filters.
In the passed filters the first element is artist.
The second element is album."""
# In some cases the data can be None, then just return
if data is None:
return data
new_tuple = []
rest = []
... | 041628107e4a6173f804c1942d05bb0c6b935146 | 638,640 |
import random
def create_random_list(number_in_list):
"""Function to generate a random list."""
return [(random.randint(1, 21) * 5) for _ in range(number_in_list)] | a7d0828ce24aca1e591108dcfe83f82ad0c45f17 | 638,641 |
def map_dtype_name_to_pixel_type(dtype_name):
"""
Performs mapping of ndarray underlying data type to
proper pixel data type
:param: dtype_name: name of data type representation
of underlying np.ndarray
:return: String representing the correct pixel data type
"""
if dtype_name == 'float1... | 763a36ff1fb02abf820cb9e5462809c210309867 | 638,642 |
import re
def is_valid_file_category_id(category_id):
"""
Validates a file lifecycle category ID, also known as the categories "category-ext-name".
A valid category ID should look like: category-00000001 - It should
always start with "category-" and end with 8 hexadecimal characters in lower
case.... | 75b074120fbdd612814a140f056163486a09ade3 | 638,643 |
def normalize_severity_at_baseline(mean_pre_test_treatment, maximum_on_clinical_scale):
"""Normalizes the pre-test scores in order to include them in the SAOB analysis.
Parameters
----------
mean_post_test_treatment: float
Mean score after the treatment.
maximum_on_clinical_sca... | 436076c60bfa26c49cec298c562074f9e5c6fa15 | 638,644 |
def get_base_by_color(base):
"""
Get color based on a base.
- Uses different band of the same channel.
:param base:
:return:
"""
if base >= 250.0:
return 'A'
if base >= 180.0:
return 'G'
if base >= 100.0:
return 'C'
if base >= 30.0:
return 'T'
... | d72ba141b4d87d11b6c471d73ec05fb90b3f2ee3 | 638,645 |
import ipaddress
def _calculate_address_pool(addrmask, ipv6=False):
"""
Return a pool of addresses contained in the network.
@param addrmask: Network in IP/mask format.
@return: A list of ip addresses
"""
if ipv6:
netobj = ipaddress.IPv6Network(addrmask, strict=False)
else:
... | 3fb1b60324e47e38c2f74caf9f47d02dcb30cb9f | 638,646 |
def _must_be_updated(today_date, last_modification, allowed_age):
"""
:param today_date: Today's date.
:type today_date: datetime.date
:param last_modification: Date of file's last modification.
:type last_modification: datetime.date
:param allowed_age: Maximum age allowed between today and last... | ba555bf7a80eb5a8ad489fff5154693621a75767 | 638,648 |
def get_attr(attrs, key):
""" Get the attribute that corresponds to the given key"""
path = key.split('.')
dict_ = attrs
for part in path:
if part.isdigit():
part = int(part)
# Let it raise the appropriate exception
dict_ = dict_[part]
return dict_ | 83cafcdf7af76f81cd3ff07d90f9f846c320fdf9 | 638,649 |
import os
import sys
def check_path_with_msg(this_path):
"""
If the specified path exists on the file system, return True.
If it does not exist print a message to stdout and return False.
"""
try:
if not(os.path.exists(this_path)):
sys.stdout.write('path not found: {}\n'.format... | 70069ca2852053c37eadbeabfff0a75a19c7141c | 638,650 |
import argparse
def command_line_interface():
""" Manages to take the available Zork program options as
command line arguments """
parser = argparse.ArgumentParser(description='The Zork CLI')
parser.add_argument(
'-v',
'--verbose',
dest='verbose',
action='store_tr... | b3a36c8e35167007adde92fbf3557b34ede00279 | 638,651 |
import threading
def _in_thread(func, *args, **kwargs):
"""Execute func(*args, **kwargs) after dt seconds. Helper for tests."""
def _f():
func(*args, **kwargs)
t = threading.Thread(target=_f, name='/*/*')
t.setDaemon(True)
t.start()
return t | 128cf213aff0c6a55cde9c94372b95323dbdc9ef | 638,652 |
import inspect
def extract_module_name(obj, full=False):
"""
Get the name of a module for an object.
"""
properties = inspect.getmembers(obj)
for name, value in properties:
if name == '__module__':
if full:
return value.split('.')[-1]
else:
... | e1742628b19e0e961496016e53ee484e9aff8aae | 638,653 |
def product_first_image_alt(product):
"""
Returns main product image alt for seo
"""
all_images = product.images.all()
alt_text =all_images[0].alt if all_images else ''
return alt_text | d747cc6027b074754934126884fa35ebe123d001 | 638,656 |
def stripFilename(fname):
""" Strip the path and extension from the filename. """
return str(fname).split("\\")[-1].split(".")[0] | a382fc89cca21dfe3bd0d7380f3e90653f508ba6 | 638,657 |
import math
def decantor(z):
"""Inverse Cantor"""
w = math.floor(math.sqrt(8 * z + 1) / 2 - 0.5)
t = ((w + 1) * w) / 2
y = z - t
x = w - y
return int(x), int(y) | 1f26eed41926aea81be6e476064f5ad7ae43b418 | 638,658 |
def clean_headers(hdr_tuples, invalid_hdrs=None):
"""
Given a list of header tuples, filters out tuples with empty header names
or in the specified invalid header names list.
"""
if hdr_tuples is None:
return list()
clean_tuples = list()
for entry in hdr_tuples:
if not entry[... | 509bbbbf1e9dd55ac751a5e436446964678a1e65 | 638,659 |
def max(raw_metric):
"""
.. note:: Deprecated use `longMax`, `doubleMax' instead
"""
return {"type": "max", "fieldName": raw_metric} | 3e6c937c029e5e59677bc2c902c4e14db5750d5c | 638,660 |
def flatten_batch(x):
"""
Flattens a batch of arrays to one dimension.
Args:
x (numpy.ndarray): A batch of arrays to be flattened.
Returns:
numpy.ndarray, a flattened one dimension array.
"""
return x.reshape(x.shape[0], -1) | dcd6ac8d50269f695e5df75c9b0eb25da04ddc41 | 638,661 |
import os
def model(filename):
"""
The path to model artifacts.
Your algorithm should write all final model artifacts to this directory.
Amazon SageMaker copies this data as a single object in compressed tar
format to the S3 location that you specified in the CreateTrainingJob
request. If mul... | 318cf48af1793d00497b349bf1061673c24c4be0 | 638,662 |
def scale_vector(v, s):
"""
vector scales
v: list
s: int
return: list
"""
return map(lambda x: x*s, v) | 842254aaa2cacc22736706ac9e6596fd2c54d816 | 638,663 |
import copy
def sfilter(obj, blacklist):
"""
Helper function to deep copy a dict, and pop elements off.
"""
ret = copy.deepcopy(obj)
for el in blacklist:
ret.pop(el)
return ret | f07bfe81e6b880109d54b4f38445ee51b122ba27 | 638,664 |
def generate_lhs_tokens(distribution, rng):
"""Generate a set of tokens to build production rules for."""
# Iteration order over a set is apparently non-deterministic, so use a list instead...
tokens = []
token_pool = list(distribution.keys())
token_probabilities = list(distribution.values())
wh... | c5d8498260f02c4a19021f8736a466a7b9f94106 | 638,666 |
def _split_groups(active_groups):
""" Function to perform a binary tree search test on our sample. """
size_chosen_instance = len(active_groups[1])
middle = size_chosen_instance//2
# split the first active group in two equal size groups and then remove the instance from the list of active groups
tes... | c0de0825b84ab42b7a4047b36962dff3fe5ec674 | 638,667 |
def Likelihood(evidence, hypo):
"""Computes the likelihood of the evidence assuming the hypothesis is true.
Args:
evidence: a tuple of (number of heads, number of tails)
hypo: float probability of heads
Returns:
probability of tossing the given number of heads and tails with a
... | 6a0f1ae160a3b0b24b522d5dc0a645d2d39ff1cc | 638,668 |
def check_permissions(required_permission, payload):
""" Check if required permission exists in the verified token's payload.
Parameters:
required_permission (string|list):
A string describing the type of permission.
e.g: get:drinks, post:drinks, ['get:drinks', '... | 814405147d1864b8dac1895d56bd0a72fa453def | 638,669 |
def make_fixed(x, prec):
"""Convert a Float to a fixed-point big integer"""
offset = x.exp+prec
if offset >= 0:
return x.man << offset
else:
return x.man >> (-offset) | 0ae4330c145d1966c188dc552fa306116fcacfd1 | 638,670 |
import subprocess
def systemd_unitdir():
"""Return the official systemd unit dir path."""
cmd = 'pkg-config systemd --variable=systemdsystemunitdir'.split()
try:
return subprocess.check_output(cmd).decode().strip()
except (OSError, subprocess.CalledProcessError):
return "/lib/systemd/s... | 4c687d7615944f21740ce0a8f7f43b12c70cf9f4 | 638,671 |
def detect_publisher(fstring):
""" Detect the publisher of a html file by searching for unique strings
:param fstring: document HTML or XML text
:type: byte string
:returns: publisher name as a unique string
"""
if b'<meta name="dc.Identifier" scheme="doi" content="10.1021/' in fstring:
... | cc79505a3e514cb7aa631483e7da6d18b1f14ba4 | 638,672 |
def round_to_two_places(num):
"""Return the given number rounded to two decimal places.
>>> round_to_two_places(3.14159)
3.14
"""
# Replace this body with your own code.
# ("pass" is a keyword that does literally nothing. We used it as a placeholder
# because after we begin a code bloc... | 822a768208a871ce0d7e01d9bfdf64c49233f2bc | 638,675 |
def _make_dictnames(tmp_arr, offset=0):
"""
Helper function to create a dictionary mapping a column number
to the name in tmp_arr.
"""
col_map = {}
for i,col_name in enumerate(tmp_arr):
col_map.update({i+offset : col_name})
return col_map | 7bdd5222446a6c47ad547103be4c07dda0c93d4e | 638,676 |
import shlex
import subprocess
def run_cmd(cmd: str) -> int:
"""
Executes command and return the returncode of the executed command.
Redirects stderr of the executed command to stdout.
Args:
cmd: command to execute.
Returns:
output: child process returncode after the command has... | 66dac3ebb7ffbf64261fea3f9cef420dbf7fdc75 | 638,677 |
def get_ids(df_cat, prd_col, cli_col):
"""
Obtain Client and Produtct IDs positions
Parameters
----------
df_cat: pandas Data Frames
Representation of df_long, with prd_col and cli_col as categories.
prd_col: str
Name of the column containing the ProductIDs.
cli_col: str
... | 74f2bbda27e0335a18a04fa9fe7250b05ce2c5a7 | 638,678 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.