content stringlengths 42 6.51k |
|---|
def get_command_from_state(state):
"""
This method gets appropriate command name for the state specified. It
returns the command name for the specified state.
:param state: The state for which the respective command name is required.
"""
command = None
if state == 'present':
command ... |
def average(values):
"""Computes the arithmetic mean of a list of numbers.
>>> print(average([20, 30, 70]))
40.0
"""
return sum(values) / len(values) |
def sdi(data):
""" Given a hash { 'species': count } , returns the SDI
>>> sdi({'a': 10, 'b': 20, 'c': 30,})
1.0114042647073518"""
from math import log as ln
def p(n, N):
""" Relative abundance """
if n is 0:
return 0
else:
return (floa... |
def check(s):
"""
:param s:str. the input of letters
:return: bool.
"""
if len(s) == 7 and len(s.split(' ')) == 4:
for unit in s.split(' '):
if unit.isalpha():
return True |
def c2c2DMO(X, choice="NIHAO"):
"""
The ratio between the baryon-influenced concentration c_-2 and the
dark-matter-only c_-2, as a function of the stellar-to-halo-mass
ratio, based on simulation results.
Syntax:
c2c2DMO(X,choice='NIHAO')
where
X: M_star / M_vir (float or arra... |
def from_sieve(l: list) -> list:
""" Takes a sieve, a sequence of boolean elements whose index is some type of number -- e.g. a prime number -- if it is set to 'True', and returns that list of numbers. """
p=list()
for i, val in enumerate(l):
if val: p.append(i)
return p |
def repeat(n, f):
"""Returns a list with the results of invoking f() n times"""
return [f() for i in range(n)] |
def limit_folded_from_limit_max(limit, maximum):
"""
Testdata: (-6, -1, 2, 5, 10) or (0, 5, 8, 11, 16)
yield 2 * 2 - (-1) = 5 or 2 * 8 - 5 = 11
"""
return 2.0 * maximum - limit |
def all_bases(obj):
"""
Return all the class to which ``obj`` belongs.
"""
def _inner(thing, bases=None):
bases = bases or set()
if not hasattr(thing, "__bases__"):
thing = thing.__class__
for i in thing.__bases__ or []:
bases.add(i)
bases = b... |
def square_and_multiply(a: int, power: int, modulo: int) -> int:
"""
Fast technique for exponentiation of a base to a power with a modulo
:param a:
:param power:
:param modulo:
:return:
"""
result = 1
while power > 0:
if (power & 1) == 1:
result = (result * a) % ... |
def remove_legends(content):
"""Remove redundant legends"""
content = content.replace('summary="Legends"', 'summary="Legends" style="display:none"')
return content |
def _get_info(info, tag):
"""
get value from info vcf field
"""
return next((value.split("=")[1] for value in info.split(";") if value.startswith(tag)), None) |
def update_val(old, new):
"""Utility function to use in set_speed
"""
if new > old:
return old + 1
else:
return old - 1 |
def make_color_tuple(color):
"""
turn something like "#000000" into 0,0,0
or "#FFFFFF into "255,255,255"
"""
R = color[1:3]
G = color[3:5]
B = color[5:7]
R = int(R, 16)
G = int(G, 16)
B = int(B, 16)
return R, G, B |
def get_record(raw_item, record_level):
"""
Dig the items until the target schema
"""
if not record_level:
return raw_item
record = raw_item
for x in record_level.split(","):
record = record[x]
return record |
def init_states(batch_size, num_lstm_layer, num_hidden):
"""
Return name and shape of init states of LSTM network.
"""
init_c = [("l%d_init_c" % l, (batch_size, num_hidden)) for l in range(num_lstm_layer)]
init_h = [('l%d_init_h' % l, (batch_size, num_hidden)) for l in range(num_lstm_layer)]
... |
def list_to_nested_dict(lst):
"""
[1,2,3,4] -> {1:{2:{3:4}}}
"""
if len(lst) > 1:
return {lst[0]: list_to_nested_dict(lst[1:])}
else:
return lst[0] |
def energy_dist_params(pesgrp_num, pes_param_dct, hot_enes_dct, label_dct):
""" set values to determine input parameters for handling
energy distributions in MESS calculations
maybe just call this before the writer and pass to make_pes_str
"""
if pes_param_dct is not None:
# Grab ... |
def filter_list(services, ignore_list):
""" Removes items in services that are mentioned to be removed (located in ignore_list)
Args:
services: list of running services
ignore_list: list of services that are supposed to be ignored (mentioned in engine_config.py)
Returns:
List of fi... |
def whitespace_tokenize(text):
"""Runs basic whitespace cleaning and splitting on a piece of text."""
text = text.strip()
tokens = text.split()
return tokens |
def is_synonym(row):
"""
tests if the if id and the current name id differ, which indicates a synonym
"""
return 'CurrentNameID' in row and (row['IF-ID'] != row['CurrentNameID']) |
def compute_sub(guard_str):
"""
Given a guard, return its sub-guards
"""
parens = []
sub = []
for i in range(len(guard_str)):
if guard_str[i] == '(':
parens.append(i)
if guard_str[i] == ')':
j = parens.pop()
g = guard_str[j:i... |
def gcs_url_for_backup_directory(backup_bucket_name, fuzzer_name,
project_qualified_target_name):
"""Build GCS URL for corpus backup directory.
Returns:
A string giving the GCS URL.
"""
return 'gs://%s/corpus/%s/%s/' % (backup_bucket_name, fuzzer_name,
... |
def create_error(request, status, code='', title='', detail=''):
"""creates a JSON API error - http://jsonapi.org/format/#errors
"status" - The HTTP status code applicable to this problem,
expressed as a string value.
"code" - An application-specific error code, expressed as a
s... |
def countGOassociations(validTerms, gafDict):
"""
Counts the number of genes associated with at least one of the provided GO terms.
Parameters
----------
validTerms : set
A set of GO terms. Should include the GO id of interest and all of its children.
gafDict : dict
A dic... |
def direction_to_tuple(direction):
"""Returns the tuple coordinate offset from the start
hexagon given a certain direction"""
return {
'n' : (0, -1),
'ne' : (1, -1),
'se' : (1, 0),
's' : (0, 1),
'sw' : (-1, 1),
'nw' : (-1, 0)
}[direction] |
def is_task(obj):
"""Check whether an object looks like a task."""
return hasattr(obj, "_run_task") |
def _bit_count(value):
"""Returns number of bits set.
"""
count = 0
while value:
value &= value - 1
count += 1
return count |
def sizeof_fmt(size, suffix='B'):
"""Get human readable file size.
Args:
size (int): File size.
suffix (str): Suffix. Default: 'B'.
Return:
str: Formated file siz.
"""
for unit in ['', 'K', 'M', 'G', 'T', 'P', 'E', 'Z']:
if abs(size) < 1024.0:
return f'{... |
def get_prospective_location(location, velocity, time):
"""Calculate the final location and velocity based on the one at time 0"""
return [l + v * time for l, v in zip(location, velocity)] |
def bigint_to_int(mtime):
"""Convert bytearray to int
"""
if isinstance(mtime, bytes):
return int.from_bytes(mtime, 'little', signed=True)
return mtime |
def dh1080_b64decode(s):
"""A non-standard base64-encode."""
b64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"
buf = [0] * 256
for i in range(64):
buf[ord(b64[i])] = i
L = len(s)
if L < 2:
raise ValueError
for i in reversed(range(L - 1)):
if bu... |
def calculate_id_digit(numbers, weights):
"""
Calculation validation digits for cpf and cnpj for
validate_individual_identifiers function
"""
multiply = [int(num) * weight for num, weight in zip(numbers, weights)]
total = sum(multiply)
remainder = total % 11
if remainder < 2:
... |
def replace_facilities(f):
""" We replace activity, feature descriptions with standardized phrases to
describe those (for consistency). """
exists = [
'picnic', 'trail', 'day use', 'beach', 'fishing', 'lake', 'hiking']
for word in exists:
if word in f:
return word
rep... |
def hex_to_udec(hex_str):
"""
Function returns decimal equivalent to hexadecimal value
"""
return int(hex_str, 16) |
def snakeify(uin):
"""Converts text to snake_case"""
out = ""
repeated = False
spacing = (" ", "_", "-")
for ind, i in enumerate(uin):
if i not in "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_- ":
continue
elif i in spacing:
if repeated:
... |
def csv_args(value):
"""Parse a CSV string into a Python list of strings.
Used in command line parsing."""
return list(map(str, value.split(","))) |
def _split_tags(tags_field):
"""Split a tag string and return a set of tag IDs.
Empty tags and duplicates are filtered out.
"""
return set(filter(None, (tag.strip() for tag in tags_field.split(",")))) |
def make_title(raw_input):
"""Capitalize and strip"""
return raw_input.title().strip() |
def coarsen_indices(byte_indices, size):
"""Convert a byte-level shuffle pattern to a coarser one.
Given `size`, which is a number of bytes, convert an `N`-length
shuffle pattern list to an `N/size`-length one that describes the
pattern at the level of those "words."
If the pattern is not aligned ... |
def bitfill(num):
"""Fills a number of bits with 1.
Args:
num (int): The number of bits to fill.
Returns:
int: The filled bits.
"""
return sum(2 ** i for i in range(num)) |
def select_raw(request, view, redirect, *args, **kwargs):
"""Sends a raw response, that is the parameters passed to the
select function that is mentioned in corresponding stubout.Set
"""
return {
'request': request,
'view': view,
'redirect': redirect,
'args': args,
'kwargs': kwarg... |
def read_torrent_file(filepath):
"""Reads torrent file from filesystem and returns its contents."""
f = open(filepath, 'rb')
contents = f.read()
f.close()
return contents |
def absxy_to_tilexy(xtile, ytile, zoom, abs_x, abs_y):
"""Convert absolute x,y coordinates to tile x,y coordinates."""
return (abs_x - xtile * 256, abs_y - ytile * 256) |
def get_output_subfolder(only_filename, limit_examples, limit_classes):
"""
Returns: subfolder name for records
"""
if only_filename is not None:
return 'only-{}'.format(only_filename)
elif limit_examples is not None and limit_classes is not None:
return 'limit-{}-classes-{}'.format(... |
def parseInput(input):
"""
Converts an input string of integers into an array of integers.
"""
return [int(num) for num in input.split(',')] |
def generate_x_rotation_seq(N):
"""
returns a sequence of multiples of 90 degrees rotation around x-axis for a conformation \
generated by ``make_circular_chain``. For example for ``N=12`` the output is ``[1, 1, 2, 1]``
:param N: number of beads
:type N: int
:return: ``[1,1,2,1,2,1,2,... |
def num_to_chars(num):
"""Return a string like 'AB' when given a number like 28."""
num -= 1
s = ""
while num >= 0:
s = chr(ord("A") + (num % 26)) + s
num = num // 26 - 1
return s |
def get_variables(interface1, interface2, interface3):
"""Create and return a dictionary of test variables.
:param interface1: Name of an interface.
:param interface2: Name of an interface.
:param interface3: Name of an interface.
:type interface1: string
:type interface2: string
:type inte... |
def user_event_week_top_voted(msg):
""" week top voted """
isclick = msg['MsgType'] == 'event' \
and msg['Event'] == 'CLICK' and msg['EventKey'] == 'WEEK_TOP_VOTED'
iscmd = msg['MsgType'] == 'text' and \
(msg['Content'].lower() == '2' \
or msg['Content'].lower() == 'wtv' \
... |
def parse_values_to_remove(options):
"""Manual parsing of remove arguments.
:param options: list of arguments following --remove argument
:return: dictionary containing key paths with values to be removed
:rtype: dict
EXAMPLE: {'identity.username': [myname],
'identity-feature-enabled.... |
def convert_y_domain(mpl_plot_bounds, mpl_max_y_bounds):
"""Map y dimension of current plot to plotly's domain space.
The bbox used to locate an axes object in mpl differs from the
method used to locate axes in plotly. The mpl version locates each
axes in the figure so that axes in a single-plot figure... |
def NameMatch(comp):
"""
Summary : This functions compares a list to name with
typo handling
Parameters : comparison list
Return : Boolean
"""
for item in comp:
try:
item = item.lower()
except:
continue
if item == 'name':... |
def pack_bits( longbits ):
"""Crunch a 64-bit int (8 bool bytes) into a bitfield."""
byte = longbits & (0x0101010101010101)
byte = (byte | (byte>>7)) & (0x0003000300030003)
byte = (byte | (byte>>14)) & (0x0000000f0000000f)
byte = (byte | (byte>>28)) & (0x00000000000000ff)
return byte |
def canUnlockAll(boxes):
"""
You have n number of locked boxes in front of you.
Each box is numbered sequentially from 0 to n - 1 and
each box may contain keys to the other boxes.
Write a method that determines if all the boxes can be opened.
Prototype: def canUnlockAll(boxes)
boxes is a l... |
def get_pymol_color(color):
"""Return the PyMOL color corresponding to a Kinemage color name."""
color_list = {
# Color names defined in the KiNG source that aren't included in a
# standard PyMOL installation are listed here with the names of
# (approximately) equivalent PyMOL named col... |
def hackerrank_in_string(s):
"""Hackerrank Problem: https://www.hackerrank.com/challenges/hackerrank-in-a-string/problem
Args:
s (str): String to check to see if Hackerrank is contained in it
Returns:
str: Return "YES" or "NO" based on whether we find hackerrank in the string or not
""... |
def _bin2bcd(value):
"""Convert a binary value to binary coded decimal.
:param value: the binary value to convert to BCD. (required, no default)
"""
return value + 6 * (value // 10) |
def _sort_torrents(ctx, torrent_list, sort_type):
""" Sorts torrents by a specific sort pattern.
:param click.Context ctx: The calling clicks current context
:param torrent_list: A list of torrent items to sort
:type torrent_list: List[torvend.items.Torrent]
:param str sort_type: The type of sort t... |
def to_fahrenheit(temp):
"""
Converts a temperature in celsius to fahrenheit.
"""
return (temp * 1.8) + 32 |
def clear_fat_content(profiles):
"""
from all 'fat content' mesurments take the most recent one to display
it in 'compare profiles' window
"""
list_of_values = list()
sorted_profiles = list()
for prof in profiles:
if prof['GENDER'] != 'male':
if prof['FAT_CONTENT... |
def patch_dict(patch_dict_no_envelop):
"""A patch represented as a dictionary."""
return {"operations": [patch_dict_no_envelop]} |
def _get_test_name_path(testcase):
"""To reduce cognitive complexity"""
test_name = ""
backup_fspath = None
if testcase.get("name"):
test_name = testcase.get("name").split(".")[-1]
if testcase.get("classname"):
test_name = testcase.get("classname").split(".")[-1] + "." + test_name
... |
def gcd(a, b):
""" Euclid's algotith implementation. Source: https://en.wikipedia.org/wiki/Greatest_common_divisor"""
while(b):
a, b = b, a % b
return a |
def _clamp(value: float, v_min: float, v_max: float) -> float:
"""Clamps the value into the range [v_min, v_max].
e.g., _clamp(50, 20, 40) returns 40.
v_min should be less or equal to v_max. (v_min <= v_max)
"""
if not v_min < v_max:
raise ValueError("v_min is the lower bound, which should ... |
def factorial(n: int) -> int:
"""Return n! (0! is 1)."""
if n <= 1:
return 1
result = 2
for x in range(3, n + 1):
result *= x
return result |
def organizar(arquivo):
"""
Organiza os itens de um arquivo em uma lista.
:param arquivo: Arquivo a ser organizado em uma lista.
"""
lista = list()
for linha in arquivo:
dado = linha.split(';')
dado[1] = dado[1].replace('\n', '')
lista.append(dado[:])
return lista |
def VD_531(delta_P, delta_S, n, FA = 0):
"""
5.3.1 Load factor and additional bolt load up to
the opening limit
---
delta_P : Elastic resiliance of the clamped parts
for concentric loading
delta_S : Elastic resiliance of the bolt
n : Load introduction factor
... |
def count_in_list(lst: list) -> int:
"""
Function that should be counted in list
"""
cnt = 0
for i in range(len(lst)):
for j in range(len(lst[0])):
if lst[i][j] == 1:
cnt += 1
return cnt |
def class_counts(rows, labels):
"""
Counts the number of each type of example in a dataset.
:param rows: array of samples
:param labels: rows data labels.
:return: a dictionary of label -> count.
"""
counts = {cls: 0 for cls in set(labels)} # a dictionary of label -> count.
for idx, x i... |
def hamacher_product(a, b):
"""The hamacher (t-norm) product of a and b.
computes (a * b) / ((a + b) - (a * b))
Args:
a (float): 1st term of hamacher product.
b (float): 2nd term of hamacher product.
Raises:
ValueError: a and b must range between 0 and 1
Returns:
f... |
def calculate_limited_tax(yearly, tax_rate, deduction, frequency):
"""
Calculate the tax for CPP and EI (individually) and determine the how much is deducted per period
Param: yearly: (float)
Yearly Income
Param: tax_rate: (float)
The rate that the yearly income is taxed at
Param: d... |
def trap(h, y1, y2):
""" h is defined as (b-a) in which a and b are the limits of integration """
return h * (y1+y2)/2 |
def buildPopup(template, nodeId, dateString, title, args):
"""Interpolate relevant values into the popup HTML.
template -- HTML template to use for the popup
nodeId -- the node this popup is for
dateString -- the dates represented by the popup, in string form
args -- any additional values from data... |
def fatorial(num):
"""
Calcula o fatorial
:param num: Informe o numero do fatorial
:return: Ele retorna o resultado
"""
fat = 1
if num == 0:
return fat
for i in range(1, num + 1, 1):
fat *= i
return fat |
def _AnomalySegmentSeries(change_points):
"""Makes a list of data series for showing segments next to anomalies.
Args:
change_points: A list of find_change_points.ChangePoint objects.
Returns:
A list of data series (lists of pairs) to be graphed by Flot.
"""
# We make a separate series for each anom... |
def unique_vals(rows, column_number):
"""Find the unique values from a column in a dataset based on column number"""
return set([row[column_number] for row in rows]) |
def find_allowed_ph4(item_dict):
"""Function to find allowed ph4"""
# Create the out list to return
out_list = []
# Loop through the keys - except unused
for item in item_dict:
if item == "unused":
continue
out_list.extend(item_dict[item])
return list(set(out... |
def error(resp, noise):
"""Return relative error (%) of noise with respect to resp."""
return 100*abs((noise-resp)/resp) |
def mode(nums):
"""Return most-common number in list.
For this function, there will always be a single-most-common value;
you do not need to worry about handling cases where more than one item
occurs the same number of times.
>>> mode([1, 2, 1])
1
>>> mode([2, 2, 3, 3, 2])
... |
def rk4(x,t,tau,derivsRK,**kwargs):
"""
Runge-Kutta integrator (4th order). Calling format derivsRK(x,t,**kwargs).
Inputs:
x current value of dependent variable
t independent variable (usually time)
tau step size (usually timestep)
derivsRK ri... |
def get_obstacle_coordinates(obstacles):
"""return locations of obstacles"""
obst_coords = []
for obstacle in obstacles:
for z in obstacle.z_list:
obst_coords.append([obstacle.x, obstacle.y,z])
return obst_coords |
def progress_days(days: list) -> int:
"""Find the number of progress days."""
progress = 0
for index, day in enumerate(days):
if index+1 < len(days):
progress += 1 if day < days[index+1] else 0
return progress |
def without_key(d, key):
"""Return a copy of dict `d` with `key` removed."""
d2 = d.copy()
d2.pop(key)
return d2 |
def normalise_number(a):
""" Split the power part of a number and its float value normalised to 1
Example
-------
>>> normalise_number(1.433364345e9)
(0.1433364345, 10)
>>> normalise_number(14e-6)
(0.13999999999999999, -4)
>>> normalise_number(-14e-6)
(-0.13999999999999999, -4)"""... |
def _equal(values, expected_values):
"""Equal two dicts."""
return set(values.keys()) not in set(
set(values.keys()) ^ set(expected_values.keys())
) |
def list_from_env(env_value):
"""Convert environment variable to list."""
if isinstance(env_value, str):
env_value = [u for u in env_value.split(',') if u]
return env_value |
def ping(host):
"""Pings a host and returns true if the host exists.
"""
import os
import platform
ping_str = "-n 1" if platform.system().lower() == "windows" else "-c 1"
return os.system("ping " + ping_str + " " + host) == 0 |
def set_intercept_file_chooser_dialog(enabled: bool) -> dict:
"""Intercept file chooser requests and transfer control to protocol clients.
When file chooser interception is enabled, native file chooser dialog is not shown.
Instead, a protocol event `Page.fileChooserOpened` is emitted.
Parameters
--... |
def map_nested(v, f):
"""
Maps a function to all values (and keys if dictionaries exist in the data
structure) of a given iterable. This function generates a new data
structure with the mapping applied.
"""
if isinstance(v, list):
return [map_nested(item, f) for item in v]
elif is... |
def read_positive_integer_custom(text, position):
"""Read a number starting from the given position, return it and the first
position after it in a tuple. If there is no number at the given position
then return None.
"""
if position >= len(text) or (not text[position].isdigit()):
return ("",... |
def iterable(obj):
"""Return boolean of whether obj is iterable"""
try:
iter(obj)
except TypeError:
return False
return True |
def mod(n, size):
"""Returns the position of a cell based on modulo arithmetic"""
size -= 1
if n < 0:
return size
elif n > size:
return 0
return n |
def remove_prefix(utt, prefix):
"""
Check that utt begins with prefix+" ", and then remove.
Inputs:
utt: string
prefix: string
Returns:
new utt: utt with the prefix+" " removed.
"""
try:
assert utt[: len(prefix) + 1] == prefix + " "
except AssertionError as e:
... |
def _digraph_to_graph(digraph, prime_node_mapping):
"""Convert digraph to a graph.
:param digraph: A directed graph in the form
{from:{to:value}}.
:param prime_node_mapping: A mapping from every
node in digraph to a new unique and not in digraph node.
:return: A symmetric graph in the f... |
def create_dictionary(domain, url, http_status, categories, datetime_list, author, title, ingress, text, images, captions):
"""Returns a dictionary containing the scraped data from the website, given as parameters.
Parameters:
domain - The domain of the media source
url - The website url as a s... |
def get_token_audience(token):
"""Retrieve the token's intended audience
According to the openid-connect spec `aud` may be a string or a list:
http://openid.net/specs/openid-connect-basic-1_0.html#IDToken
Args:
token (dict): The user's decoded bearer token
Returns:
list[str]: ... |
def _versionTuple(versionString):
"""
Return a version string in 'x.x.x' format as a tuple of integers.
Version numbers in this format can be compared using if statements.
"""
if not isinstance(versionString, str):
raise ValueError("version must be a string")
if not versionString.count("... |
def palindrome_permutation(input_string):
"""Check if it is a permutation of a palindrome."""
input_string = input_string.lower().replace(' ', '')
letters = {}
for letter in input_string:
if letter in letters:
letters[letter] += 1
else:
letters[letter] = 1
if... |
def lst_helper(
l: list
) -> list:
"""convenience"""
return list(map(str, l)) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.