content stringlengths 42 6.51k |
|---|
def _dat_str(day, month, year):
"""Create date string
"""
dd = int(day)
if dd < 10:
sd = '0' + str(dd)
else:
sd = str(dd)
mm = int(month)
if mm < 10:
sm = '0' + str(mm)
else:
sm = str(mm)
sy = str(int(year))
return sd + '.' + sm... |
def nonsmall_diffs(linelist1, linelist2, small=0.0):
"""
Return True if line lists differ significantly; otherwise return False.
Significant numerical difference means one or more numbers differ (between
linelist1 and linelist2) by more than the specified small amount.
"""
# embedded funct... |
def _model_name(name):
"""
Extracts the main component of a model, removes
suffixes such ``Classifier``, ``Regressor``, ``CV``.
@param name string
@return shorter string
"""
if name.startswith("Select"):
return "Select"
if name.startswith("Nu"):
... |
def bytes_to_string(bytes):
"""Converts number of bytes to a string. Based on old code here:
http://dev.jmoiron.net/hg/weechat-plugins/file/tip/mp3.py
Uses proc-like units (capital B, lowercase prefix). This only takes a
few microseconds even for numbers in the terabytes.
"""
units = ['B'... |
def fib(n):
"""This function returns the nth Fibonacci numbers."""
i = 0 # variable i = the first fibonacci number
j = 1 # variable j = the second fibonacci number
n = n - 1 # variable n = n - 1
while n >= 0: # while n is greater than 0
i, j = j, i + j # 0, 1 = 1, 0 + 1
n = n - 1 # we want the script... |
def qte(lne):
"""Quotes the given string"""
return "'" + lne + "'" |
def arithmetic_sum_n(a_1, d, n):
"""Calculate the sum of an arithmetic series.
Parameters:
a_1 The first element of the series
d The difference between elements
n The number of elements in the series to sum
Return:
The sum of n numbers in the arithmetic seri... |
def measure(function, xs, ys, popt, weights):
"""
measure the quality of a fit
"""
m = 0
n = 0
for x in xs:
try:
if len(popt) == 2:
m += (ys[n] - function(x, popt[0], popt[1]))**2 * weights[n]
elif len(popt) == 3:
m += (ys[n] - func... |
def get_matching_entities_in_inning(entry, inning, entities):
"""
Method to get matching entities in an inning with the summary
:param entry:
:param inning:
:param entities:
:return:
"""
plays = entry["play_by_play"]
entities_in_inning = set()
for top_bottom in ["top", "bottom"]:... |
def cleanLocals(locals_dict) :
"""
When passed a locals() dictionary, clean out all of the hidden keys and return
"""
return dict((k,v) for (k,v) in locals_dict.items() if not k.startswith("__") and k != "self") |
def _unresr_input(endfin, pendfin, pendfout, mat,
temperatures=[293.6], sig0=[1e10], iprint=False,
**kwargs):
"""Write unresr input.
Parameters
----------
endfin : `int`
tape number for input ENDF-6 file
pendfin : `int`
tape number for input P... |
def _self_updating_js(ident):
"""Create JS code for a Callback that keeps a 1d CDS selection up to date"""
return """
// Define a callback to capture errors on the Python side
function callback(msg){
console.log("Python callback returned unexpected message:", msg)
}
c... |
def generate_attributes(num_replications, num_global_memory_banks=32):
"""
Generates the kernel attributes for the global memory. They specify in which
global memory the buffer is located. The buffers will be placed using a
round robin scheme using the available global memory banks and the number of
... |
def clean_name(_name):
"""Remove unsupported characters from field names.
Converts any "desirable" seperators to underscore, then removes all
characters that are unsupported in Python class variable names.
Also removes leading numbers underscores.
Arguments:
_name {str} -- Initial field na... |
def data_error(campo, msg):
"""
Metodo que retona o dict padrao de error para o validade_data
campo: nome do campo com erro
msg: Mensagem do error.
return: Retorna um dict
"""
data = {
"error_message": {
campo: [msg]
}
}
return data |
def filterMatches(matches, prevKeypoints, currKeypoints, threshold=30):
"""
This function discards matches between consecutive frames based on the
distance between keypoints, which has to be below a certain threshold,
and based on the fact whether their scale increases (keypoints that
don't increase in scale... |
def get_prefix4WOA18(input):
"""
Convert WOA18 variable name string into the prefix used on files
"""
d = {
'temperature': 't',
'salinity': 's',
'phosphate': 'p',
'nitrate':'n',
'oxygen':'o',
'silicate':'i',
}
return d[input] |
def gen_addrmap(regmap):
"""
Collect all addresses as keys to the addrmap dict. Values are the names.
"""
addrmap = dict()
for key, item in regmap.items():
if "base_addr" in item:
addr = item["base_addr"]
aw = item["addr_width"]
addri = int(str(addr), 0)
... |
def foundInErrorMessages(message):
"""validate if the message is found in the error messages
Args:
message (String): message to find
Returns:
bool: found in the error messages
"""
return message in [
"2001: NO EXISTEN REGISTROS EN LA CONSULTA"
] |
def midi_filter(midi_info):
"""Return True for qualified midi files and False for unwanted ones"""
if midi_info['first_beat_time'] > 0.0:
return False
elif midi_info['num_time_signature_change'] > 1:
return False
elif midi_info['time_signature'] not in ['4/4']:
return False
r... |
def midpointint(f,a,b,n):
"""This function takes in a function and 3 integer parameters representing
an interval and the number of subintervals to be made in that interval
and returns the approximate value of the integral of the given function
in the given interval """
h = (b-a)/float(n)
... |
def replace_conditional(record: dict, field: str, value: str, replacement: str):
"""
Function to conditionally replace a value in a field.
Parameters
----------
record : dict
Input record.
field : str
Key of field to be conditionally altered.
value : str
Value to ide... |
def strbool(val):
"""
Create bool object from string. None is returned if input is not
derterminable.
@param val: the string to check.
@type val: str
@return: True/False/None.
@rtype: bool
"""
try:
return bool(int(val))
except:
val = val.lower()
if val ... |
def table(title, headers, data_node):
"""
Returns a dictionary representing a new table element. Tables
are specified with two main pieces of information, the headers
and the data to put into the table. Rendering of the table is
the responsibility of the Javascript in the resources directory.
... |
def get_alert_queries(entities: list) -> list:
""" create the value for the Prometheus query parameter based on the entities
This is also very rudimentary and must probably adapted to each ones use case.
"""
instance_entities = [e for e in entities if e["type"] == "instance"]
if instance_entities:
... |
def set_payment_id_to_tx_extra_nonce(payment_id):
"""
Sets payment ID to the extra
:param payment_id:
:return:
"""
return b"\x00" + payment_id |
def is_empty(value):
""" Check whether value is empty """
if (type(value) == str and value.strip() == "") or (type(value) == list and len(value) == 0):
return(True)
else:
return(False) |
def _curl_https_get_code(host):
"""
Create a curl command for a given host that outputs HTTP status code.
"""
return (
'/opt/mesosphere/bin/curl '
'-s -o /dev/null -w "%{{http_code}}" '
'https://{host}'
).format(host=host) |
def _get_expected_types(keyword_type, scope_type):
"""
Get the actual type of the keyword based on the defined keyword types, and
the scope type that is only useful when the defined type is 'inherited'.
"""
if keyword_type == 'inherited':
assert scope_type is not None, ("Scope type should n... |
def is_valid_git_sha1(hash):
"""check if a string is a valid git sha1 string
Input:
hash: string to validate
Output:
True if the string has 40 characters and is an hexadecimal number, False
otherwise.
"""
if len(hash) != 40:
return False
try:
value = int(hash, 16)... |
def transformTernary(string, location, tokens):
"""Evaluates a ParseResult as a ternary expression"""
# pylint: disable=eval-used
return eval(str(tokens[2]) +" if " + str(tokens[0]) + " else " + str(tokens[4])) |
def _union(xval, iunion, ix):
"""helper method for ``filter``"""
import numpy as np
if xval:
if iunion:
iunion = np.union1d(iunion, ix)
else:
pass
return iunion |
def build_all_reduce_device_prefixes(job_name, num_tasks):
"""Build list of device prefix names for all_reduce.
Args:
job_name: 'worker', 'ps' or 'localhost'.
num_tasks: number of jobs across which device names should be generated.
Returns:
A list of device name prefix strings. Each element spells ... |
def get_validations(action_id):
"""
Stub to return validations
"""
return [{
'id': '43',
'action_id': '12345678901234567890123456',
'validation_name': 'It has shiny goodness',
'details': 'This was not very shiny.'
}] |
def next_batch(targ_capacity, curr_capacity, num_up_to_date, batch_size,
min_in_service):
"""Return details of the next batch in a batched update.
The result is a tuple containing the new size of the group and the number
of members that may receive the new definition (by a combination of
... |
def tap_up(tap, max_tap):
"""
Go to the next upper tap position
"""
if tap + 1 <= max_tap:
return tap + 1
else:
return tap |
def get_per_dial_emb_file_path(data_dir: str, image_id: int,
ext: str = 'npz') -> str:
"""
Call as get_npz_file_path(data_dir=data_dir, image_id=image_id)
:param data_dir:
:param image_id:
:param ext:
:return:
"""
file_path = f"{data_dir}/{str(image_id)}.{e... |
def rttm2simple(rttm:list) -> list:
"""
Convert rttm-like list to a simple hypothesis list compatible with simple DER library
Parameters
----------
rttm: list
List of strings
Returns
----------
list
List of tuples containing unique ID, start and end time in sec... |
def _upper_case_first_letter(name):
"""
Function that convert first character of name to UPPER case
:param name: String which first character will be converted to UPPER case
:return: String with first character in UPPER case
"""
indices = set([0])
return "".join(c.upper() if i in indices els... |
def generator(self, arg, *args, **kwargs):
"""Just return the first arg as the results. Ignores any other params"""
# print 'generator: {}'.format(arg)
return arg |
def _render_sources(dataset, tables):
"""Render the source part of a query.
Args:
dataset: the data set to fetch log data from.
tables: the tables to fetch log data from.
Returns:
a string that represents the from part of a query.
"""
return "FROM " + ", ".join(
["... |
def get_uuid(data):
"""Returns the Universally unique identifier (UUID) of a managed object.
It is expressed in the format of object type:object ID. For example, if a controller's
object type number is "207" and the controller ID is "0A", the UUID is "207:0A".
The UUID is often needed for quer... |
def clamp(min, max, value):
"""Restricts a number to be within a range.
Also works for other ordered types such as Strings and Dates"""
if max < min:
raise ValueError(
"\
min must not be greater than max in clamp(min, max, value)"
)
if value > max:
return max... |
def _validate_requirements(requirements):
"""
Validate the requirements.
Args:
requirements(list): List of requirements
Returns:
List of strings of invalid requirements
"""
invalid_requirements = []
for requirement in requirements:
invalid_params = []
if not... |
def pull_service_id(arn):
"""
pulls the ecs service id from the full arn
"""
return arn.split('service/', 1)[-1] |
def getBaseUrl(serverType, serverFqdn, serverPort):
"""Return the base url of the a server based on the protocol and port
it is running on."""
# dict mapping SOAP server type to protocol
type2ProtoDict = {'GSI': 'https',
'gsi': 'https',
'SSL': 'https',
... |
def get_symlink_command(from_file, dest):
"""Returns a symlink command.
:param from_file:
:param dest:
"""
return 'ln -sf %s %s' % (from_file, dest) |
def infer_angular_variance_spherical(var_r, phi_c, var_q_min):
"""Calculate angular variance given properties of a beam with quadratic phase corrected by a lens.
The lens which removes the spherical component has focal length f = -k*var_r/(2*phi_c). This means that -phi_c is the
phase of the quadratic comp... |
def codepipeline_approval(message):
"""Uses Slack's Block Kit."""
console_link = message['consoleLink']
approval = message['approval']
pipeline_name = approval['pipelineName']
action_name = approval['actionName']
approval_review_link = approval['approvalReviewLink']
expires = approval['expir... |
def mask_to_list(mask):
"""Converts the specfied integer bitmask into a list of
indexes of bits that are set in the mask."""
size = len(bin(mask)) - 2 # because of "0b"
return [size - i - 1 for i in range(size)
if mask & (1 << size - i - 1)] |
def range_overlap(a_min, a_max, b_min, b_max):
"""
Check, if ranges [a_min, a_max] and [b_min, b_max] overlap.
"""
return (a_min <= b_max) and (b_min <= a_max) |
def table_score(person, table):
"""
Returns score of table based on personal preferences and table data.
see test() in score.py for more information.
"""
table_person = set(table['person'])
friend = set(person.get('friend', [])).intersection(table_person)
acquaintance = set(person.get('acq... |
def gcd(a, b):
"""Compute the greatest common divisor of a and b"""
while b > 0:
a, b = b, a % b
return a |
def str_candset(candset, names=None):
"""
nicely format a single committee
"""
if names is None:
namedset = [str(c) for c in candset]
else:
namedset = [names[c] for c in candset]
return "{" + ", ".join(map(str, namedset)) + "}" |
def format_date_c19(date_in):
"""
Formats "m/d/y" to "yyyymmdd"
"""
month, day, year = date_in.split('/')
return '20%s%02i%02i' % (year, int(month), int(day)) |
def compare_names(namepartsA, namepartsB):
"""Takes two name-parts lists (as lists of words) and returns a score."""
complement = set(namepartsA) ^ set(namepartsB)
intersection = set(namepartsA) & set(namepartsB)
score = float(len(intersection))/(len(intersection)+len(complement))
return score |
def _column_tup_to_str(ind):
"""
Convert tuple of MultiIndex to string.
Parameters
----------
ind : tuple
ind[0]: either 'sleep' or 'activity'
ind[1]: int that is the day number
ind[2]: bool, True being light, False being dark
Returns
-------
output : str
... |
def pkcs7_pad(data: bytes, blocksize: int = 16) -> bytes:
"""
Implements PKCS7 padding
:param data: The data to pad
:param blocksize: The block size to calculate padding based on
:return: Padded data
"""
d = bytearray(data)
padding_len = blocksize - len(d) % blocksize
d.extend(paddin... |
def as_float(val):
"""
Tries to convert a string to an float.
Returns None if string is empty
"""
try:
return(float(val))
except ValueError:
return(None) |
def interpret_string_as_boolean(str_value):
"""
Tries to interpret string a boolean. Raises a Value error upon failure.
"""
if str_value in ("TRUE", "True", "true", "1"):
return True
elif str_value in ("False", "FALSE", "false", "0"):
return False
else:
raise ValueError(f... |
def bubble_sort(array, length: int = 0):
"""
:param array: the array to be sorted.
:param length: the length of array.
:return: sorted array.
>>> import random
>>> array = random.sample(range(-50, 50), 100)
>>> bubble_sort(array) == sorted(array)
True
>>> import string
>>> array ... |
def levenshtein_distance(lhs, rhs):
"""Return the Levenshtein distance between two strings."""
if len(lhs) > len(rhs):
rhs, lhs = lhs, rhs
if not lhs:
return len(rhs)
prev = range(len(rhs) + 1)
for lidx, lch in enumerate(lhs):
curr = [lidx + 1]
for ridx, rc... |
def new_state(current_state, direction):
"""
Calculates new heading from current heading and relative direction.
"""
new_axis = (current_state['axis']+1) & 1
multiplier = -1 if current_state['axis'] == 0 and direction == 1 or \
current_state['axis'] == 1 and direction == -1 el... |
def generate_parameter_field_number(parameter, used_indexes, field_name_suffix=""):
"""Get unique field number for field corresponding to this parameter in proto file.
If field number is not stored in metadata of parameter, get the next unused integer value.
"""
field_name_key = f"grpc{field_name_suffi... |
def fixdate(longdate):
""" Many podcasts use a super long date format that I hate. This will
cut them down to a simple format. Here's the original:
"Mon, 08 Jul 2019 00:00:00 -0800"
"""
tdate = longdate.split(" ")
months = {"JAN" : "01", "FEB" : "02", "MAR" : "03", "APR" : "04",
... |
def emptyCoords():
"""Returns a unit square camera with LL corner at the origin."""
return [[(0.0, 0.0), (0.0, 0.0), (0.0, 0.0)]] |
def percentile(sorted_values, p):
"""Calculate the percentile using the nearest rank method.
>>> percentile([15, 20, 35, 40, 50], 50)
35
>>> percentile([15, 20, 35, 40, 50], 40)
20
>>> percentile([], 90)
Traceback (most recent call last):
...
ValueError: Too few data points (0... |
def cast_list(*elements) -> list:
"""this method transform everything in a list, ex:\n
cast_list("a","b") returns: ["a","b"]\n
cast_list([1,2]) returns: [1,2]\n"""
# when * is used all the arguments will be passed as tuple
# means just one element were passed as arg
if len(elements) == 1:
... |
def _select_entries_param(list, param):
"""Takes a list of logfile_entry objects and returns a sub set of it.
The sub set includes a entries that have a source attribute that occurs in the param argument.
Positional arguments:
list -- a list of logfile_entry objects
param -- a list of strings, representing ... |
def intersect(t1, t2):
"""Assumes t1 and t2 are tuples
Returns a tuple containing elements that are in
both t1 and t2"""
result = ()
for e in t1:
if e in t2:
result += (e,)
return result |
def get_index_of_tuple(list_of_tuple, index_of_tuple, value):
""" Determine how far through the list to find the value.
If the value does not exist in the list, then return the
length of the list.
Args:
list_of_tuple: a list of tuples i.e. [(index1, index2, index3)]
index_of_tuple_1: whi... |
def create_bzip2(archive, compression, cmd, verbosity, interactive, filenames):
"""Create a BZIP2 archive."""
cmdlist = [cmd, 'a']
if not interactive:
cmdlist.append('-y')
cmdlist.extend(['-tbzip2', '-mx=9', '--', archive])
cmdlist.extend(filenames)
return cmdlist |
def human_int(s):
"""Returns human readable time rounded to the second."""
s = int(round(s))
if s <= 60:
return '%ds' % s
m = s/60
if m <= 60:
return '%dm%02ds' % (m, s%60)
return '%dh%02dm%02ds' % (m/60, m%60, s%60) |
def azLimit(az):
"""Limits azimuth to +/- 180"""
azLim = (az + 180) % 360
if azLim < 0:
azLim = azLim + 360
return azLim - 180 |
def clamp(val, minval, maxval):
"""Clamps the given value to lie between the given `minval` and `maxval`"""
return min(max(val, minval), maxval) |
def _flatten_list(this_list: list) -> list:
"""
Flatten nested lists.
:param this_list: List to be flattened
:return: Flattened list
"""
return [item for sublist in this_list for item in sublist] |
def get_res_num(line):
"""get residue number from line starting with ATOM"""
return int(line[22:26]) |
def ansicolored(string, colour):
"""
Show a colour output in the absence of termcolor
"""
colormap = {
'pink': '\033[95m',
'blue': '\033[94m',
'green': '\033[92m',
'yellow': '\033[93m',
'red': '\033[91m',
'end': '\033[0m',
}
return colormap.get(col... |
def preTagProc(word):
"""Preprocessing before tagging"""
# tagger tags almost everything as NE if it's in capitals
if len(word) > 1 and word.isupper():
word = word.lower()
return word |
def valid_exception(error):
"""There are certain Exceptions raised that indicate successful authorization.
This method will return True if one of those Exceptions is raised
"""
VALID_EXCEPTIONS = [
'DryRunOperation',
# S3
'NoSuchCORSConfiguration',
'ServerSideEncryptionCo... |
def largest_permutation(k, arr):
"""Hackerrank Problem: https://www.hackerrank.com/challenges/largest-permutation/problem
You are given an unordered array of unique integers incrementing from 1. You can swap any two elements a limited
number of times. Determine the largest lexicographical value array that ... |
def fake_gauss_2(num_list):
"""Fake Gauss v3"""
a = num_list[0]
b = num_list[-1]
return int(b * (a + b)/2) |
def intersect(left, right):
""":yaql:intersect
Returns set with elements common to left and right sets.
:signature: left.intersect(right)
:receiverArg left: left set
:argType left: set
:arg right: right set
:argType right: set
:returnType: set
.. code::
yaql> set(0, 1, 2)... |
def MAE_dust_caponi(wavelengths, formulation="libya25"):
"""class defining dust Mass Absorption Efficiency (MAE) for several dust sources according to
Caponi et al. 2017 """
MAE400_AAE = {
# PM2.5
# Sahara
'libya25': (110., 4.1),
'marocco25': (90., 2.6),
'alger... |
def decode_text(text):
"""Decode a given text string to an Unicode string.
If `text` can't be decoded to a common encoding, it will be decoded to UTF-8
passing the "replace" options.
"""
for enc in ('utf-8', 'iso-8859-15', 'iso-8859-1', 'ascii'):
try:
return text.decode(enc)
... |
def validVer(ver):
"""
This helper function validates Android version code.
It must be an integer but Google didn't say it must be positive only:
https://developer.android.com/guide/topics/manifest/
manifest-element.html#vcode
"""
if ver is None or not isinstance(ver, int):
retur... |
def line_value(line):
"""Return the value associated with a line (series of # and . chars)"""
val = 0
for char in line:
val <<= 1
val += char == "#"
return val |
def remove_first_slash_from(resource_path):
"""
Some REST API calls are written to have resource path without the '/' in the beginning, so this removes it
:param resource_path: e.g. /1/0/1
:return: Resource path without the first '/'
"""
if resource_path[0] == '/':
return resource_path[1... |
def format_read_request(address):
""" Format a read request for the specified address.
:param address: address at which to read date from the FPGA.
:return: formatted request.
"""
if address >= 2**(4 * 8):
raise ValueError(f'Address {address} is too large (max 4 bytes).')
if address < 0... |
def _has_exclude_patterns(name, exclude_patterns):
"""Checks if a string contains substrings that match patterns to exclude."""
for p in exclude_patterns:
if p in name:
return True
return False |
def get_ratio_hard(our_percentage):
"""
Return value is between 0 and 20: 0 -> 20; 0.5 -> 1; 1 -> 0
"""
return 100**(0.5 - our_percentage) * (1 - our_percentage) * 2 |
def get_current_valid_edges(current_nodes, all_edges):
"""
Returns edges that are present in Cytoscape:
its source and target nodes are still present in the graph.
"""
valid_edges = []
node_ids = {n['data']['id'] for n in current_nodes}
for e in all_edges:
if e['data']['source'] in ... |
def get_number_of_auctions_to_run(q: int,
t: int,
lmbda: int) -> int:
"""
Summary line.
Extended description of function.
Parameters
----------
q: description
t: description
lmbda: description
Returns
-------
... |
def tag_nocolor(tag):
"""
Removes the color information from a Finder tag.
"""
return tag.rsplit('\n', 1)[0] |
def is_valid_pbc(pbc):
""" Checks pbc parameter """
values = ['none', 'mol', 'res', 'atom', 'nojump', 'cluster', 'whole']
return pbc in values |
def get_exitcode(return_code):
"""
Calculate and return exit code from a return code
:param return_code: code in os.wait format
:return: a tuple (signal, exit code)
"""
signal = return_code & 0x00FF
exitcode = (return_code & 0xFF00) >> 8
return signal, exitcode |
def getHOGBlocks(rect, blocksizes, stride=1.0):
"""Returns a set of blocks (rects), with the given (fractional) stride among blocks"""
x0, y0, x1, y1 = rect[:4]
ret = []
for b in blocksizes:
ss = int(b*stride)
for y in range(y0, y1+1, ss):
if y+b-1 > y1: break
for... |
def count_all(a, b):
"""Count all occurrence of a in b"""
return len([1 for w in b if w == a]) |
def symbol_type(symbol: str) -> str:
"""Determines the type of the asset the symbol represents.
This can be 'STOCK', 'CRYPTO', or 'OPTION'
"""
if len(symbol) > 6:
return "OPTION"
elif symbol[0] == "@" or symbol[:2] == "c_":
return "CRYPTO"
else:
return "STOCK" |
def is_proxy(obj):
""" Return True if `obj` is an array proxy
"""
try:
return obj.is_proxy
except AttributeError:
return False |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.