content stringlengths 42 6.51k |
|---|
def array_reverse(input_list):
"""
Reverses the elements of the list to demonstrate a linear algorithm of reversing an array of things.
:param input_list A list of objects to be reversed.
:return A returned version/copy of the list.
"""
array_len = len(input_list)
i = 0;
output_list ... |
def cse_ticker_to_webmoney(cse_ticker: str):
"""
Parameters:
cse_ticker - cse ticker name
Returns:
webmoney_ticker - ticker that can be looked up in webmoney
"""
return f"{cse_ticker}:CNX" |
def _item_type(item):
"""Indicate to the ODF reader the type of the block or text."""
tag = item['tag']
style = item.get('style', None)
if tag == 'p':
if style is None or 'paragraph' in style:
return 'paragraph'
else:
return style
elif tag == 'span':
i... |
def point_to_segment_orientation(segment, point):
"""Returns True if `point` is clockwise oriented in regards of `segment`"""
xp, yp = point
((x0, y0), (x1, y1)) = segment
cross_product = (x1 - xp) * (y0 - yp) - (x0 - xp) * (y1 - yp)
return cross_product > 0 |
def deduplicate(mylist):
"""Remove duplicates while otherwise maintaining order"""
return list(dict.fromkeys(mylist)) |
def is_convergence_error(error_code):
"""Return True if the error code indicates a convergence error."""
return error_code in {119, 120, 121, 122} |
def apk(actual, predicted, k=3):
"""
Source: https://github.com/benhamner/Metrics/blob/master/Python/ml_metrics/average_precision.py
"""
if len(predicted) > k:
predicted = predicted[:k]
score = 0.0
num_hits = 0.0
for i, p in enumerate(predicted):
if p in actual and p not in p... |
def convert_TriMap_to_SelectedLEDs( best_led_config ):
""" Returns a lookup dict of the selected LEDs.
"""
d = {}
for tri_num in best_led_config:
for led_num in best_led_config[tri_num]:
d[led_num] = True
return d |
def rle(seq):
""" Create RLE """
run = []
run.append(seq[0])
howmany = 1
for index in range(1, len(seq)):
if seq[index] == run[-1]:
howmany += 1
elif seq[index] != run[-1] and howmany != 1:
run.append(str(howmany))
howmany = 1
run.appen... |
def pad_truncate_list(x_list, maxlen):
"""
pad and truncate input to maxlen based on trucating and padding strategy
:param x_list:e.g. [1,10,3,5,...]
:return:result_list:a new list,length is maxlen
"""
result_list=[0 for i in range(maxlen)]
length_input=len(x_list)
if length_input>maxlen... |
def palindrome_5(word_1: str, word_2: str) -> bool:
"""
O(n^2)
:param word_1:
:param word_2:
:return: if is or not a palindrome
"""
word_1_list = list(word_1)
word_2_list = list(word_2)
word_1_list.sort()
word_2_list.sort()
pos = 0
matches = True
while pos < len(... |
def filter_properties(properties, message):
"""
Move properties that have "message" in their description out of "properties"
into "removed_properties"
"""
filtered_properties = []
removed_properties = []
for property in properties:
if message in property["description"]:
r... |
def extract_hashtags(tweet):
""" (str) -> list of str
Precondition: 1 <= len(tweet) <= 140
Return a list of string containing all of the unique hashtags in the tweet.
>>> extract_hashtags('I love #autumn, #Fall and want to #fall')
['autumn', 'Fall', 'fall']
>>> extract_hashtags('... |
def to_bytes(number, length=None, endianess='big'):
"""Will take an integer and serialize it to a string of bytes.
Python 3 has this, this is originally a backport to Python 2, from:
http://stackoverflow.com/a/16022710/15677
We use it for Python 3 as well, because Python 3's builtin version
need... |
def get_channels(channels_file): # pragma: no cover
"""Returns the authorized channels your channels config file."""
try:
with open(channels_file, "r") as channels_file:
return [line.strip() for line in channels_file.readlines()]
except IOError:
return [] |
def countHostBits(binaryString):
""" This will calculate the number of host bits in the mask
"""
# count the number of 0s in the subnet string
return binaryString.count('0') |
def ek_WT_RPR(cell):
"""
Returns the WT-RPR reversal potential (in mV) for the given integer index
``cell``.
"""
reversal_potentials = {
1: -87.4,
2: -92.1,
3: -96.1,
4: -93.1,
5: -106.1
}
return reversal_potentials[cell] |
def Linspace(start, stop, n):
"""Makes a list of n floats from start to stop.
Similar to numpy.linspace()
"""
return [start + (stop-start) * float(i)/(n-1) for i in range(n)] |
def subplots_number(nts):
"""
Determine the number and distribution of the subplots when representing the scatterplot Sp_targetvs Sp_decoys
based on precursor nucleotide lengths
"""
lengths = len(nts)
if lengths <= 4:
rows, columns = 2, 2
elif 5 <= lengths <= 6:
rows, columns... |
def human2bytes(s):
"""
>>> human2bytes('1M')
1048576
>>> human2bytes('1G')
1073741824
"""
symbols = ('Byte', 'KiB', 'MiB', 'GiB', 'T', 'P', 'E', 'Z', 'Y')
import re
num = re.findall(r"[0-9\.]+", s)
assert (len(num) == 1)
num = num[0]
num = float(num)
for i, n in enum... |
def __create_help_description(indent, options, long_descriptions):
"""
Create a description that is shown for the help option.
:param indent: How much to indent the description.
:type indent: str
:param options: The available options.
:type options: list
:param long_descriptions: Long descr... |
def str2intlist(s, repeats_if_single=None, strict_int=True):
"""Parse a config's "1,2,3"-style string into a list of ints.
Also handles it gracefully if `s` is already an integer, or is already a list
of integer-convertible strings or integers.
Args:
s: The string to be parsed, or possibly already an (lis... |
def _TransformOperationType(metadata):
"""Extract operation type from metadata."""
if 'operationType' in metadata:
return metadata['operationType']
elif 'graph' in metadata:
return 'WORKFLOW'
return '' |
def get_required_distance(W, sigma_det, wav):
"""
Calculate the propagation distance required to satisfy sampling conditions.
:param W: approximate feature size [m]
:param sigma_det: propagated plane (detector) pixel size [m]
:param wav: source wavelength [m]
:returns zreq: required distance ... |
def column_letter_to_number(column_letter):
"""
Converts letter to integer
:param column_letter: String that represents a column in spreadsheet/Excel styling
:return: Integer that represents column_letter
"""
# https://stackoverflow.com/questions/7261936/convert-an-excel-or-spreadsheet-
# c... |
def _font_size(rack_size):
"""
Font size (for a draft)
"""
if rack_size <= 32:
return '100'
elif rack_size > 32 and rack_size <= 42:
return '75'
else:
return '50' |
def _pack_geom_into_dict(lgt, hgt, dx, dy, ch, th, orad, irad, cang, crad,
omaj, ominr, imaj, iminr, i1loc):
"""Return a dictionary for geometric data."""
geo = {
"length": lgt,
"height": hgt,
"dx": dx,
"dy": dy,
"chord": ch,
"thi... |
def longest_common_sub_sequence(a, b):
"""
http://www.geeksforgeeks.org/
dynamic-programming-set-4-longest-common-subsequence/
"""
def get_max(x, y):
"""
if lengths are the same, return the lexicographically earliest
"""
if len(x) == len(y):
return min(x, ... |
def dayDiff(newdate, olddate):
"""Return number of days between usec dates"""
return int(round((newdate - olddate) / float(86400000000))) |
def _realname(name):
"""Basically a filter to get the 'real' name of a node"""
if name == 'master':
return 'saltmaster'
else:
return name |
def is_leap_year(year):
"""
Helper function for get_timestamp.
:param year: The year.
:returns True if the year is a leap year.
"""
year = int(year)
if(year%400) ==0:
leap=1
elif (year%100) == 0:
leap = 0
elif (year%4) == 0:
leap = 1
else:
leap = 0
return leap |
def createMotionDataDict(labels,data):
"""Creates an array of motion capture data given labels and data.
Parameters
----------
labels : array
List of marker position names.
data : array
List of xyz coordinates corresponding to the marker names in `labels`.
Indices of `data` correspond to frames i... |
def create_set_state_payload(context: str, state: int):
"""Create and return "setState" dictionary to send to the Plugin Manager.
Args:
context (str): An opaque value identifying the instance's action you want to modify.
state (int): A 0-based integer value representing the state of an action w... |
def name_indexes(name):
"""
Return indexes of name.
"""
indexes = name.split('.')
if len(indexes) == 0:
indexes = []
else:
indexes = indexes[1:]
return [ int(i) for i in indexes ] |
def parse(query: str) -> str:
"""
Parse URL query into correct SQL syntax.
:param query: SQL query pulled from URL argument.
:return: Parsed query converted to valid SQL syntax.
"""
query_split = query.split("+")
return " ".join(query_split) |
def cast_vals_to_set(d: dict):
"""Maps the values of a nested dictionary to a set of strings."""
for key, value in d.items():
if isinstance(value, dict):
cast_vals_to_set(value)
else:
d[key] = set(value)
return d |
def fits_column_format(format):
"""Convert a FITS column format to a human-readable form.
Parameters
----------
format : :class:`str`
A FITS-style format string.
Returns
-------
:class:`str`
A human-readable version of the format string.
Examples
--------
>>> f... |
def hex_nring(npix):
"""
For a hexagonal layout with a given number of pixels, return the
number of rings.
"""
test = npix - 1
nrings = 1
while (test - 6 * nrings) >= 0:
test -= 6 * nrings
nrings += 1
if test != 0:
raise RuntimeError(
"{} is not a vali... |
def parse_fragment(fragment_string):
"""Takes a fragment string nd returns a dict of the components"""
fragment_string = fragment_string.lstrip('#')
try:
return dict(
key_value_string.split('==')[0].split('=')
for key_value_string in fragment_string.split('&')
)
... |
def get_dict_column(column, dict_list):
""" Return data dictionary for search column
"""
for d in dict_list:
if d['column'] == column:
return d |
def fieldName(name):
"""return acceptable field name from string
"""
Fname = name[0:8] # Correct length <9
for char in ['.', ' ', ',', '!', '@', '#', '$', '%', '^', '&', '*']:
if char in Fname:
Fname = Fname.replace(char, "_")
return Fname |
def reflect(data, num_bits):
"""Reflect a number by bit positions."""
reflection = 0x0
for bit in range(num_bits):
if data & 0x1:
reflection = reflection | (1 << (num_bits - 1 - bit))
data = data >> 1
return reflection |
def sum_series(n, a=0, b=1):
"""TO RETURNS THE nth VALUE OF THE SUM_SERIES."""
# 0, 1, 1, 2, 3, 5, 8, 13, 21
sum = [a, b]
if n < 0:
print('The number cannot be negative.')
return('The number cannot be negative.')
elif n > 999:
print('The number is too big. Please enter a numb... |
def typeof(variate):
"""
Detect the type of a variable.
"""
var_type = None
if isinstance(variate, int):
var_type = 'int'
elif isinstance(variate, str):
var_type = 'str'
elif isinstance(variate, float):
var_type = 'float'
elif isinstance(variate, list):
va... |
def _tryConvertToInt(s):
"""
Try convert value from `s` to int.
Returns:
int(s): If the value was successfully converted, or `s` when conversion
failed.
"""
try:
return int(s)
except ValueError:
return s |
def multiply_factors(l):
"""
Multiplies discovered prime factors of n
Returns: int
"""
v = 1
for x in l:
v *= x
return v |
def euclid(val0, val1):
""" Compute greatest common divisor using Euclid algorithm """
if val1 == 0:
return val0
return euclid(val1, val0 % val1) |
def _gr_remove_ ( graph , remove ) :
"""Remove points that do not satisfy the criteria
>> graph = ...
>>> graph.remove ( lambda s : s[0]<0.0 )
"""
old_len = len ( graph )
removed = []
for point in graph :
if remove ( *graph [ point ] ) :
removed.append ( point )
... |
def f(N1, N2, Vg1, Vg2, Ec1, Ec2, Cg1, Cg2, Ecm, e):
"""
Parameters
----------
N1 : Int
Number of electrons on dot 1.
N2 : Int
Number of electrons on dot 1.
Vg1 : Float
Voltage on gate 1.
Vg2 : Float
Voltage on gate 2.
Ec1 : Float
Charging energy ... |
def longest_common_substring(s1,s2):
"""Returns longest common substring of two sequences."""
# Make sure that s1 is the shorter one
if len(s1) > len(s2):
# If s1 was shorter, then switch sequence order
s1, s2 = s2, s1
# Start with the entire sequence and shorten
substr_len = len(s1) # D... |
def expScale(initVal, exp):
"""
Applies an exponent exp to a value initVal and returns value.
Will work whether initVal is positive or negative or zero.
"""
val = initVal
if val > 0:
val = val ** exp
if val < 0:
val *= -1
val = val ** exp
val *= -1
return ... |
def step_select(seq,step):
"""
Given a sequence select return a new sequence containing every
step'th item from the original.
"""
if seq:
return [x for i,x in enumerate(seq)
if i % step == 0]
else:
return seq |
def _is_str(candidate):
"""Returns whether a value is a string."""
return isinstance(candidate, str) |
def clip_black_by_luminance(color, threshold):
"""If the color's luminance is less than threshold, replace it with black.
color: an (r, g, b) tuple
threshold: a float
"""
r, g, b = color
if r+g+b < threshold*3:
return (0, 0, 0)
return (r, g, b) |
def calc_idf_two(docs):
"""Calculates the df scores based on the corpus"""
terms = set()
for doc in docs:
for term in doc:
terms.add(term)
idf = {}
for term in terms:
term_count = 0
doc_count = 0
for doc in docs:
doc_count += 1
... |
def leading_digit(x):
"""Get the first digit in a positive number
Args:
x (float): POSITIVE float
Returns:
int: one digit from 1 to 9
"""
# loop until you get the leading digit
while x >= 10:
x //= 10
return x |
def gen_section(items, override=None, section='', sep='=', ident=0):
"""generate a section's content"""
ret_list = []
if section:
ret_list += ['\n%s[%s]' % (' '*ident*2, section)]
if items:
if isinstance(items, (tuple, list)) or (override in {list, tuple}):
for d in items:
... |
def empty_as_none(v):
"""Convert empty string into null"""
if (not v) and (v == ''):
return None
else:
return v |
def name_matches(texnode, names):
"""
Returns True if `texnode`'s name is on one of the names in `names`.
"""
if hasattr(texnode, 'name') and texnode.name in names:
return True
else:
return False |
def strip(lines):
"""
Strip whitespace from input lines
"""
return [x.strip() for x in lines] |
def extract_suff_from_keywords(keywords, given_arglist, separator=""):
"""Extract list of keywords starting with a suffix
assuming they all start with a string belonging to
a given list of args.
Attributes
keywords: list of str
Input keywords to analyse
given_arglist: list o... |
def is_isbn_or_key(word):
"""
"""
isbn_or_key = 'key'
if len(word) == 13 and word.isdigit():
isbn_or_key = 'isbn'
short_word = word.replace('-', '')
if '-' in word and len(short_word) == 10 and short_word.isdigit:
isbn_or_key = 'isbn'
return isbn_or_key |
def remove_blank(x):
"""creating a function to remove the empty words"""
if(x != ""):
return(x) |
def get_strand_word(hsp_hit_frame):
"""Take a frame (for a translation of a DNA sequence) and return 'plus' or
'minus' depending on which strand the frame corresponds to.
"""
if hsp_hit_frame > 0:
return 'plus'
else:
return 'minus' |
def count_motif(motifs):
"""Count the number of nucleotides (4 types: ACGT) column wise from a motifs matrix.
Args:
motifs (list): list of DNA strings, stack to constitute of the motifs matrix in genome.
Returns:
Dictionary, the count of each nucleotides in each column of the motifs matrix... |
def bubble_sort(items):
"""Sort given items by swapping adjacent items that are out of order, and
repeating until all items are in sorted order.
Running time: O(n**2) because it passes through n/2 (on average) elements
n-1 times, which simplifies to n elements n times, n**2
Memory usage: O(1), a... |
def apk(actual, predicted, k=10):
"""
Computes the average precision at k.
This function computes the average prescision at k between two lists of
items.
Parameters
----------
actual : list
A list of elements that are to be predicted (order doesn't matter)
predicted : list
... |
def pair(a, b):
"""Holds a pair of points. Gets appended to the list of used points."""
if a < b:
return str(a) + "-" + str(b)
else:
return str(b) + "-" + str(a) |
def ipc_ok_response(resp_data):
"""Make OK response."""
response = ("ok", resp_data)
return response |
def _coverage_copts(configuration):
"""Returns `swiftc` compilation flags for code converage if enabled.
Args:
configuration: The default configuration from which certain compilation
options are determined, such as whether coverage is enabled. This object
should be one obtained from a rule's `c... |
def output_impedance(session, Type='Real64', RepCap='', AttrID=1250004, buffsize=0, action=['Get', '']):
"""[Output Impedance <real64>]
Sets/Gets the output impedance on the specified channel.
Valid values are 0.0, 50.0 and 75.0 Ohms. A value of 0.0 indicates that the instrument is connected to a high impe... |
def ping(data_type, event_type, ping_data=None):
"""
Construct a 'PING' message to send either a 'PING_REQUEST' or 'PING_RESPONSE' to the server.
:param data_type: int the RTMP datatype.
:param event_type: int the type of message you want to send (PING_REQUEST = 6 or PING_RESPONSE = 7).
:param ping_... |
def concat_shift_indices(n, shift):
"""Returns the concat expression of the bits at shift (shift).
Args:
n: An integer, the number of bits in the bit-string
shift: An integer, the nested shift we're at.
"""
concats = [f"shl_{shift}_0"]
for i in range(1, n):
rhs = concats[i - 1]
concat = ["(co... |
def Extract_Deltas_from_Eigenvalues(l, Q, R):
""" Maps eigenvalues to delta values. """
return 2 - 2.0 / R * l * Q |
def green(msg: str) -> str:
"""Return green string in rich markup"""
return f"[green]{msg}[/green]" |
def get_lonlat_list(location):
"""Helper to return a list of lonlat tuples of coordinates in a location"""
lonlat_list = []
if hasattr(location, "lon") and hasattr(location, "lat"):
lonlat_list.append((location.lon, location.lat))
if hasattr(location, "point"):
lonlat_list.append((locati... |
def maskify(cc: str) -> str:
"""Returns masked string."""
keep = cc[-4:]
return "#"*(len(cc)-len(keep)) + keep |
def get_column(desthead, headrow):
"""
Search the display column heads in headrow
:return: the colmun's number in headrow, so that dispaly the required values in html
"""
dest_column_numbers = []
m = len(desthead)
n = 0
while n != m:
i = 0
for j in headrow:
i... |
def normalize_classname(classname):
"""Ensure the dot separated class name (zinc reported class not found may use '/' separator)"""
return classname.replace("/", ".") |
def isBool(value):
"""
Helper function to detect if a value is boolean
"""
if value != "":
if isinstance(value, bool):
return True
else:
return False
else:
return False |
def parse_modes(params, mode_types=None, prefixes=''):
"""Return a modelist.
Args:
params (list of str): Parameters from MODE event.
mode_types (list): CHANMODES-like mode types.
prefixes (str): PREFIX-like mode types.
"""
# we don't accept bare strings because we don't want to ... |
def parse_distance(distance):
"""parse comma delimited string returning (latitude, longitude, meters)"""
latitude, longitude, meters = [float(n) for n in distance.split(',')]
return (latitude, longitude, meters) |
def num2row(num: int):
"""
Get the alpha column string from the index.
- 1 -> A
- 26 -> Z
- 27 -> AA
- 52 -> AZ
- etc
"""
if num < 1:
raise ValueError("Cannot convert num to column, num is too small.")
col = ""
while True:
if num > 26:
num, r = div... |
def add_tesla_checksum(msg_id, msg):
"""Calculates the checksum for the data part of the Tesla message"""
checksum = ((msg_id) & 0xFF) + int((msg_id >> 8) & 0xFF)
for i in range(0, len(msg), 1):
checksum = (checksum + ord(msg[i])) & 0xFF
return checksum |
def mapPoint(number, start1, stop1, start2, stop2):
"""
This method maps the number number between start2 and stop2 with the same ratio it had between start1 and start2.
@:param number: is the mapped number
@:param start1: is the lowest value of the range in which number is
@:param stop1: is the hig... |
def camelize(snake_case: str) -> str:
"""this_case_word -> ThisCaseWord"""
parts = snake_case.split("_")
if not parts:
return snake_case
if any(x == "" for x in parts):
raise ValueError(
f"Can't camelize {snake_case}."
" It probably contains several consecutive un... |
def checkBcv(bcv):
"""Check that a bcv is valid.
Valid syntax:
BBCCVV
BBCCVV-vv
BBCCVV-ccvv
BBCCVV-BBccvv
"""
if len(bcv) == 6:
return True
elif len(bcv) == 9:
return bcv[4:6] < bcv[7:9]
elif len(bcv) == 11:
return bcv[2:4] < bcv[7:9] o... |
def all_same(items):
"""Takes list and checks if all the elements in said list are the same, returning True if so"""
return all(map(lambda x: x == items[0], items)) |
def filter_color(color):
"""
jinja2 template filter for color conversion to CSS text
:param color: color as 3/4 items tuple/list, or as hex color like '#aabbcc' or 'aabbcc'
:return: :str: css color
"""
if (type(color) is list) or (type(color) is tuple):
rgb = [str(int(x)) for x in color... |
def int2base(x, base, width=0):
"""
Method to convert an int to a base
Source: http://stackoverflow.com/questions/2267362
"""
import string
digs = string.digits + string.ascii_uppercase
assert(2 <= base <= len(digs))
digits, negtive = '', False
if x <= 0:
if x == 0:
... |
def getAliasString(emailList):
"""
Function to extract and return a list (String, comma separated)
of Mamga aliases from provided email list
"""
# Gosh, this wants to be a function of module MailServer
toAlias = ''
for toAdd in emailList:
toA = toAdd.split('@molten-magma.com... |
def GetNameForCustom(custom_cpu, custom_memory_mib, ext=False):
"""Creates a custom machine type name from the desired CPU and memory specs.
Args:
custom_cpu: the number of cpu desired for the custom machine type
custom_memory_mib: the amount of ram desired in MiB for the custom machine
type instance... |
def bfs_shortest_path(graph, start, end):
""" a generic bfs search algo
"""
def _bfs_paths(graph, start, end):
# bfs using a generator. should return shortest path if any for an iteration
queue = [(start, [start])]
while queue:
(vertex, path) = queue.pop(0)
f... |
def populate_usr_pref_dict(user_pref_lst : list, shows : list):
"""
Pass in list of user preferences [show, rating] and list of shows.
Return dictionary with show as key and rating as value and list of shows not found.
"""
dictionary = {}
not_found = []
for row in user_pref_lst:
if row[0] i... |
def serialize_tipo_inmueble(tipo_inmueble):
"""
// '#/components/schemas/tipoInmueble'
"""
if tipo_inmueble:
return {
"clave": tipo_inmueble.codigo,
"valor": tipo_inmueble.tipo_inmueble,
}
return {"clave":"OTRO","valor":"No aplica"} |
def idna_encode(string):
"""Encode a string as ASCII using IDNA so that it is a valid part of a URI
See RFC3490.
:param string: str
:returns: ASCII string
"""
return string.encode('idna').decode('ascii') |
def is_triangular(k):
"""
k, a positive integer
returns True if k is triangular and False if not
"""
#YOUR CODE HERE
i = 0
currentSum = 0
while currentSum < k:
i += 1
currentSum += i
if k == currentSum:
return True
return False |
def list_bins(l, bins):
"""Takes some list l and breaks it up into bins"""
n = float(len(l)) / bins
return [l[int(n * i):int(n * (i + 1))] for i in range(bins)] |
def j2HasProfilometries(platePluggings):
"""Return true if a plate has profilometry measurements
@param[in] platePluggings, list of plate plugging dictionaries (as returned by utils.getPluggingDict)
"""
profs = [len(x.profilometries) for x in platePluggings]
return sum(profs) > 0 |
def accum(s):
""" The parameter of accum is a string which includes only
letters from a..z and A..Z.
"""
output = ""
for i in range(len(s)):
output += (s[i] * (i+1)) + "-"
return output.title()[:-1] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.