content stringlengths 42 6.51k |
|---|
def find_first(searched, vec):
"""return the index of the first occurence of item in vec"""
for i, item in enumerate(vec):
if searched == item:
return i
return -1 |
def get_funcobj(func):
"""
Return an object which is supposed to have attributes such as graph and
_callable
"""
if hasattr(func, '_obj'):
return func._obj # lltypesystem
else:
return func |
def get_set_intersection(list_i, list_j):
""" Get the intersection set
Parameters
----------
list_i, list_j: list
two generic lists
Returns
-------
intersection_set: set
the intersection of list_i and list_j
"""
set_i = set(list_i)
set_j = set(list_j)
intersection_set = set_i.intersection(set_j)
return intersection_set |
def list_to_space_str(s, cont=('{', '}')):
"""Convert a set (or any sequence type) into a string representation
formatted to match SELinux space separated list conventions.
For example the list ['read', 'write'] would be converted into:
'{ read write }'
"""
l = len(s)
str = ""
if l < 1:
raise ValueError("cannot convert 0 len set to string")
str = " ".join(s)
if l == 1:
return str
else:
return cont[0] + " " + str + " " + cont[1] |
def apply_transform(coords, trans):
"""transform coordinates according"""
coords = [((x - trans[0]) / trans[1], (y - trans[3]) / trans[5]) for x, y in coords]
return coords |
def calc_target_angle(mean_bolds, median_angles):
"""
Calculates a target angle based on median angle parameters of
the group.
Parameters
----------
mean_bolds : list (floats)
List of mean bold amplitudes of the group
median_angles : list (floats)
List of median angles of the group
Returns
-------
target_angle : float
Calculated target angle of the given group
"""
import numpy as np
if(len(mean_bolds) != len(median_angles)):
raise ValueError('Length of parameters do not match')
X = np.ones((len(mean_bolds), 2))
X[:,1] = np.array(mean_bolds)
Y = np.array(median_angles)
B = np.linalg.inv(X.T.dot(X)).dot(X.T).dot(Y)
target_bold = X[:,1].min()
target_angle = target_bold*B[1] + B[0]
return target_angle |
def is_valid_furl(furl):
"""Is the str a valid FURL or not."""
if isinstance(furl, str):
if furl.startswith("pb://") or furl.startswith("pbu://"):
return True
else:
return False
else:
return False |
def format_includes(includes: list) -> str:
"""Format includes into the argument expected by GCC"""
return " ".join([f"-I{path}" for path in includes]) |
def get_color(node, color_map):
"""
Gets a color for a node from the color map
Parameters
--------------
node
Node
color_map
Color map
"""
if node in color_map:
return color_map[node]
return "black" |
def extrae_coords_atomo(res,atomo_seleccion):
""" De todas las coordenadas atomicas de un residuo, extrae las de un atomo particular
y devuelve una lista con las X, Y y Z de ese atomo."""
atom_coords = []
for atomo in res.split("\n"):
if(atomo[12:16] == atomo_seleccion):
atom_coords = [ float(atomo[30:38]), float(atomo[38:46]), float(atomo[46:54]) ]
return atom_coords |
def read_file(input_data):
"""
Function reads the input signal data and filters it to check if given input lines are valid.
If some element in read line is invalid, the function will raise an Error
:param input_data: single string read from standard input
:return: single list of five strings with filtered and validated values
"""
parameter_list = ['' for _ in range(5)]
parameter = input_data.split()
for _ in range(len(parameter)):
parameter_list[_] = parameter[_]
dl_ul = parameter_list[0]
bts = parameter_list[1]
ms = parameter_list[2]
signal_strength = parameter_list[3]
signal_quality = parameter_list[4]
# checking if DL/UL
dl_ul_list = ['DL', 'UL']
if dl_ul not in dl_ul_list:
raise ValueError("Invalid data")
# checking BTS validity
bts_list = ['S0', 'N1', 'N2', 'N3', 'N4', 'N5', 'N6']
if bts not in bts_list:
raise ValueError("Invalid BTS")
# checking MS validity
for _ in ms:
if _ not in "1234567890qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM":
raise ValueError("Invalid MS")
# signal strength filtering
if signal_strength == 'missing':
pass
elif signal_strength == '':
raise ValueError("Invalid signal value")
elif int(signal_strength) not in range(-95, -44):
raise ValueError("Signal strength out of range")
if bts.startswith('N') and dl_ul == 'UL':
raise ValueError("Impossibruuuuu")
# signal quality filtering
if signal_quality == '':
parameter_list[4] = '5'
elif int(signal_quality) in range(0, 6):
pass
else:
raise ValueError("Signal quality value out of range")
return parameter_list |
def basecount(seq):
"""Count the frequencies of each bases in sequence"""
freq = {}
for base in seq:
if base in freq:
freq[base] += 1
else:
freq[base] = 1
return freq |
def size_of_row_in_file(row):
"""
Returns the approximate amount of bytes originally used to represent the
given row in its CSV file. It assumes the delimiter uses only one byte.
I also ignores quotes (-2 bytes) around escaped cells if they were
originally present.
I also don't think that it counts 16 bit chars correctly.
"""
a = max(0, len(row) - 1)
a += sum(len(cell) for cell in row)
return a |
def filter_languages(project_list, languages_set):
"""
Filter the project list to contain only the
languages in the languages_set
"""
filtered_projects = []
for project in project_list:
if project["repository_language"] in languages_set:
filtered_projects.append(project)
return filtered_projects |
def split_kv(text_pair, sep):
"""Helper."""
try:
key, value = text_pair.split(sep, 1)
except TypeError:
return None, text_pair
except ValueError:
return None, text_pair
if not key:
return None, None
return key, value |
def score(board, n):
"""
Calculate score.
Inputs:
board, a list of dictionaries.
n, an int.
Returns: an int.
"""
return sum(k for row in board for k, v in row.items() if not v) * n |
def residueCenterAtomList(resName):
"""
Creates a list of atom names that constitutes the 'residue center'
"""
names = {}
names["GLU"] = ["OE1", "OE2"]
names["ASP"] = ["OD1", "OD2"]
names["HIS"] = ["CG" , "ND1", "CD2", "NE2", "CE1"]
names["CYS"] = ["SG"]
names["TYR"] = ["OH"]
names["SER"] = ["OG"]
names["THR"] = ["OG1"]
names["LYS"] = ["NZ"]
names["ARG"] = ["CZ"]
names["GLN"] = ["OE1", "NE2"]
names["ASN"] = ["OD1", "ND2"]
names["TRP"] = ["NE1"]
names["N+ "] = ["N"]
names["C- "] = ["O", "OXT"]
if resName in names:
return names[resName]
else:
return [] |
def categorize_by_mortality(hurricanes):
"""Categorize hurricanes by mortality and return a dictionary."""
mortality_scale = {0: 0,
1: 100,
2: 500,
3: 1000,
4: 10000}
hurricanes_by_mortality = {0:[],1:[],2:[],3:[],4:[],5:[]}
for cane in hurricanes:
num_deaths = hurricanes[cane]['Deaths']
if num_deaths == mortality_scale[0]:
hurricanes_by_mortality[0].append(hurricanes[cane])
elif num_deaths > mortality_scale[0] and num_deaths <= mortality_scale[1]:
hurricanes_by_mortality[1].append(hurricanes[cane])
elif num_deaths > mortality_scale[1] and num_deaths <= mortality_scale[2]:
hurricanes_by_mortality[2].append(hurricanes[cane])
elif num_deaths > mortality_scale[2] and num_deaths <= mortality_scale[3]:
hurricanes_by_mortality[3].append(hurricanes[cane])
elif num_deaths > mortality_scale[3] and num_deaths <= mortality_scale[4]:
hurricanes_by_mortality[4].append(hurricanes[cane])
elif num_deaths > mortality_scale[4]:
hurricanes_by_mortality[5].append(hurricanes[cane])
return hurricanes_by_mortality |
def to_hsl(color: tuple) -> tuple:
"""Transforms a color from rgb space to hsl space.
Color must be given as a 3D tuple representing a point in rgb space.
Returns a 3D tuple representing a point in the hsl space.
Saturation and luminance are given as floats representing percentages
with a precision of 2. Hue is given as an angle in degrees between
0 and 360 degrees with a precision of 0.
"""
rf = color[0] / 255
gf = color[1] / 255
bf = color[2] / 255
maximum = max(rf, gf, bf)
minimum = min(rf, gf, bf)
delta = maximum - minimum
l = (maximum + minimum) / 2
s = 0 if delta == 0 else delta / (1 - abs(2 * l - 1))
if delta == 0:
h = 0
elif maximum == rf:
h = 60 * (((gf - bf) / delta) % 6)
elif maximum == gf:
h = 60 * ((bf - rf) / delta + 2)
else: # max is bf
h = 60 * ((rf - gf) / delta + 4)
return (round(h), round(s, 2), round(l, 2)) |
def is_duplicate(s):
"""
Return True if the string 'Possible Duplicate is in string s or False, otherwise.'
:param s:
:return:
"""
return 'Possible Duplicate:' in s |
def lengthOfLongestSubstring(s):
"""
:type s: str
:rtype: int
"""
n= len(s)
longest_substr=""
max_length= 0
for i in range(n):
seen={}
current_length=0
for j in range(i,n):
substr=s[i:j+1]
if s[j] in seen:
break
seen[s[j]]=True
current_length+=1
if current_length>max_length:
max_length=current_length
longest_substr=substr
# print(longest_substr)
return max_length |
def is_device(lib_name):
"""return true if given name is associated with a device"""
return lib_name.endswith(".device") |
def get_last_name(full_name: str) -> str:
"""Get the last name from full name.
Args:
full_name: The full official name.
Return:
The last name in title case format.
"""
return full_name.split(' ')[-1].title() |
def feuler(f, t, y, dt):
"""
Forward-Euler simplest possible ODE solver - 1 step.
:param f: function defining ODE dy/dt = f(t,y), two arguments
:param t: time
:param y: solution at t
:param dt: step size
:return: approximation of y at t+dt.
"""
return y + dt * f(t, y) |
def length_error_message(identifier, min_length=None, max_length=None):
"""Build length error message."""
additional = []
if min_length:
additional.append('at least length {}'.format(min_length))
if max_length:
additional.append('at most length {}'.format(max_length))
body = ', '.join(additional)
message = '{} identifier input must {}.'.format(identifier, body)
return message |
def weight_to_duro(weight, boardside=True):
"""
Takes a weight in KG and returns an appropriate duro bushing.
"""
bushings = [78, 81, 85, 87, 90, 93, 95, 97]
if not boardside:
weight -= 5
weight -= 40
if weight < 0:
weight = 0
approx_duro = ((weight) ** 0.66 ) + 79
duro = min(bushings, key=lambda x:abs(x-approx_duro))
return str(duro) + 'a' |
def job_id_from_reponse(text):
"""Return a string representation of integer job id from the qsub response to stdout"""
#
# The output from SGE is of the form
# "Your job 3681 ("TEST") has been submitted"
# Your job-array 4321.1-3:1 ("wrfpost") has been submitted
#
job_id = text.split(' ')[2]
if "." in job_id:
# job was an array job
job_id = job_id.split('.')[0]
return job_id |
def validate_cli(cli_string, expect=[], reject=[], ignore=[], retval=0, *args, **kwargs):
"""
Used to mock os.system with the assumption that it is making a call to 'conda-build'.
Args:
cli_string: The placeholder argument for the system command.
expect: A list of strings that must occur in the 'cli_string' arg.
reject: A list of strings that cannot occur in the 'cli_string' arg.
ignore: Don't validate the CLI_STRING if one of these strings is contained in it.
retval: The mocked value to return from 'os.system'.
Returns:
retval
"""
if not any ({term in cli_string for term in ignore}):
for term in expect:
assert term in cli_string
for term in reject:
assert term not in cli_string
return retval
return 0 |
def replace_text(text, variables):
"""
Replace some special words in text to variable from dictionary
@param text: raw text
@param variables: dictionary of variables for replace
"""
for name, value in variables.items():
text = text.replace('#%s#' % name, str(value))
return text |
def fib_recursiva(number):
"""Fibonnaci recursiva."""
if number < 2:
return number
return fib_recursiva(number - 1) + fib_recursiva(number - 2) |
def diff_two_lists(first, second):
"""Create new list with diffs between two other lists."""
assert len(first) == len(second)
return [x - y for x, y in zip(first, second)] |
def kolmogorov_53(k, k0=50):
"""
Customizable Kolmogorov Energy spectrum
Returns the value(s) of k0 * k^{-5/3}
Parameters
----------
k: array-like, wavenumber: convention is k= 1/L NOT 2pi/L
k0: float, coefficient
Returns
-------
e_k: power-law spectrum with exponent -5/3 for a given k and k0
"""
e_k = k0 * k ** (-5. / 3)
return e_k |
def get_tag_groups_names(tag_groups: list) -> list:
"""
Returns the tag groups as a list of the groups names.
Args:
tag_groups: list of all groups
Returns:
The tag groups as a list of the groups names
"""
# tag_groups is a list of dictionaries, each contains a tag group name and its description
results = []
if len(tag_groups) > 0:
for group in tag_groups:
tag_group_name = group.get('tag_group_name', '')
if tag_group_name:
results.append(tag_group_name)
return results |
def get_refresh_delay(elapsed: float) -> float:
"""Returns delay to wait for to store info.
The main goal of this method is to avoid to have too low resolution
in the very fast benchmarks, while not having gigantic log files
in the very slow benchmarks.
Parameters
----------------------------
elapsed: float
The amoount of time that has elapsed so far.
Returns
----------------------------
Amount of time to be waited before next log entry.
"""
if elapsed < 0.01:
return 0
if elapsed < 0.1:
return 0.00001
if elapsed < 1:
return 0.01
if elapsed < 10:
return 0.1
if elapsed < 60:
return 1
if elapsed < 60*10:
return 30
if elapsed < 60*60:
return 60
return 60*3 |
def convert_16bit_pcm_to_byte(old_value: int) -> int:
"""Converts PCM value into a byte."""
old_min = -32768 # original 16-bit PCM wave audio minimum.
old_max = 32768 # original 16-bit PCM wave audio max.
new_min = 0 # new 8-bit PCM wave audio min.
new_max = 255 # new 8-bit PCM wave audio max.
byte_value = int((((old_value - old_min) * (new_max - new_min)) /
(old_max - old_min)) + new_min)
return byte_value |
def _parse_size(size_str):
"""Parses a string of the form 'MxN'."""
m, n = (int(x) for x in size_str.split('x'))
return m, n |
def json_authors_to_list(authors):
"""
Take JSON formatted author list from CrossRef data and convert to string in the same format as the search.
"""
match_authors = []
for author in authors:
try:
given = author['given']
except:
given = ''
try:
family = author['family']
except:
family = ''
match_authors.append(given+'+'+family)
return match_authors |
def _calc_prob_from_all(prob):
"""This can be used to detect insects when ldr is not available."""
return prob['z'] * prob['temp_strict'] * prob['v'] * prob['width'] |
def parse_int_set(nputstr=""):
"""Return list of numbers given a string of ranges
http://thoughtsbyclayg.blogspot.com/2008/10/parsing-list-of-numbers-in-python.html
"""
selection = set()
invalid = set()
# tokens are comma separated values
tokens = [x.strip() for x in nputstr.split(',')]
for i in tokens:
try:
# typically tokens are plain old integers
selection.add(int(i))
except:
# if not, then it might be a range
try:
token = [int(k.strip()) for k in i.split('-')]
if len(token) > 1:
token.sort()
# we have items seperated by a dash
# try to build a valid range
first = token[0]
last = token[len(token)-1]
for x in range(first, last+1):
selection.add(x)
except:
# not an int and not a range...
invalid.add(i)
# Report invalid tokens before returning valid selection
# print "Invalid set: " + str(invalid)
return selection |
def getextension(filename):
"""
uses file name to get extension
:param filename:
:return:
"""
a = filename.rfind('.')
return filename[a:] |
def get_key_from_dimensions(dimensions):
"""
Get a key for DERIVED_UNI or DERIVED_ENT.
Translate dimensionality into key for DERIVED_UNI and DERIVED_ENT
dictionaries.
"""
return tuple(tuple(i.items()) for i in dimensions) |
def get_first_guess_coordinates_product(commands):
"""Get result of multiplying a final horizontal position by a final depth
received by straightforward approach;
commands(list of list[direction(str), steps(int)]): instructions"""
hor = 0
dep = 0
for com in commands:
if com[0] == "up":
dep -= com[1]
elif com[0] == "down":
dep += com[1]
else:
hor += com[1]
return hor * dep |
def duration_to_str(duration):
"""Converts a timestamp to a string representation."""
minutes, seconds = divmod(duration, 60)
hours, minutes = divmod(minutes, 60)
days, hours = divmod(hours, 24)
duration = []
if days > 0: duration.append(f'{days} days')
if hours > 0: duration.append(f'{hours} hours')
if minutes > 0: duration.append(f'{minutes} minutes')
if seconds > 0 or len(duration) == 0: duration.append(f'{seconds} seconds')
return ', '.join(duration) |
def is_sequence(obj):
"""Check if object has an iterator
:param obj:
"""
return hasattr(obj, '__iter__') |
def sol(mat, m, n):
"""
Traverse column from the end if 1 is the value increase counter
else switch to next row
"""
c = 0
j = n-1
i = 0
while i < m and j > -1:
if mat[i][j] == 1:
c = i
j-=1
else:
i+=1
return c |
def fibonacci(n):
"""
:param n:
:return: return the n-th Fibonacci number
"""
if n in (0,1):
return n
return fibonacci(n-2)+fibonacci(n-1) |
def jwt_get_username_from_payload_handler(payload):
"""
Override this function if username is formatted differently in payload
"""
return payload.get('username') |
def check_size(fsize, minsize):
"""Ensure that the filesize is at least minsize bytes.
@param fsize the filesize
@param minsize the minimal file size
@return fsize >= minsize
"""
if fsize < minsize:
print("Input file too small: %i instead of at least %i bytes." % (
fsize, minsize))
return fsize >= minsize |
def get_size(bytes):
"""
Convert Bytes into Gigabytes
1 Gigabytes = 1024*1024*1024 = 1073741824 bytes
"""
factor = 1024 ** 3
value_gb = bytes / factor
return value_gb |
def apply_gain_x2(x, AdB):
"""Applies A dB gain to x^2 """
return x*10**(AdB/10) |
def get_request_attribute(form_data, key, default=''):
"""
"""
if key not in form_data:
return ''
return form_data[key] |
def hexinv(hexstring):
"""
Convenience function to calculate the inverse color (opposite on the color wheel).
e.g.: hexinv('#FF0000') = '#00FFFF'
Parameters
----------
hexstring : str
Hexadecimal string such as '#FF0000'
Returns
-------
str
Hexadecimal string such as '#00FFFF'
"""
if hexstring[0]=='#': hexstring=hexstring.lstrip('#')
hexcolor=int(hexstring,16)
color_comp=0xFFFFFF^hexcolor
hexcolor_comp="#%06X"%color_comp
return hexcolor_comp |
def IS_STR(v):
"""Check if the given parameter is an instance of ``str``."""
return isinstance(v, str) |
def str_to_id(string, block):
"""Converts a string to a tuple-based id
Args:
string (str): Length is N*block, where each block is an int with leading zeros.
block: Length of each block. Each block is an int with leading zeros.
>>> str_to_id('000003000014000005', block=6)
(3, 14, 5)
"""
if len(string) % block != 0:
raise Exception('String length not a multiple of block={}'.format(block))
num_blocks = len(string) // block
return tuple([int(string[i*block: (i+1)*block]) for i in range(num_blocks)]) |
def pretty_string(name_list):
""" Make a string from list of some names
:param name_list: list of names [name#0, name#1, ...]
:return: string in format:
-name#0
-name#1
"""
output_string = ''
for s in name_list:
output_string += '\n -' + s
return output_string |
def _get_symbolic_filepath(dir1: str, dir2: str, file_name: str) -> str:
"""
Transform a path like:
/Users/saggese/src/...2/amp/vendors/first_rate/utils.py
into:
$DIR1/amp/vendors/first_rate/utils.py
"""
file_name = file_name.replace(dir1, "$DIR1")
file_name = file_name.replace(dir2, "$DIR2")
return file_name |
def check_in_org(entry, orgs):
"""
Obtain the organization from the entry's SSL certificate.
Determine whether the org from the certificate is in the provided list of orgs.
"""
if "p443" in entry:
try:
value = entry["p443"]["https"]["tls"]["certificate"]["parsed"]["subject"]["organization"]
except KeyError:
return False
for org in orgs:
if org in value:
return True
return False |
def map_init(interface, params):
"""Intialize random number generator with given seed `params.seed`."""
import numpy as np
import random
np.random.seed(params['seed'])
random.seed(params['seed'])
return params |
def create_incremented_string(forbidden_exprs, prefix = 'Dummy', counter = 1):
"""This function takes a prefix and a counter and uses them to construct
a new name of the form:
prefix_counter
Where counter is formatted to fill 4 characters
The new name is checked against a list of forbidden expressions. If the
constructed name is forbidden then the counter is incremented until a valid
name is found
Parameters
----------
forbidden_exprs : Set
A set of all the values which are not valid solutions to this problem
prefix : str
The prefix used to begin the string
counter : int
The expected value of the next name
Returns
----------
name : str
The incremented string name
counter : int
The expected value of the next name
"""
assert(isinstance(forbidden_exprs, set))
nDigits = 4
if prefix is None:
prefix = 'Dummy'
name_format = "{prefix}_{counter:0="+str(nDigits)+"d}"
name = name_format.format(prefix=prefix, counter = counter)
counter += 1
while name in forbidden_exprs:
name = name_format.format(prefix=prefix, counter = counter)
counter += 1
forbidden_exprs.add(name)
return name, counter |
def normalize(chromosome):
"""Make all probabilities sum to one."""
total = sum(chromosome.values())
return {card: probability / total for card, probability in chromosome.items()} |
def base36encode(number, alphabet='0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ'):
"""Converts an integer to a base36 string."""
if not isinstance(number, int):
raise TypeError('number must be an integer')
base36 = ''
sign = ''
if number < 0:
sign = '-'
number = -number
if 0 <= number < len(alphabet):
return sign + alphabet[number]
while number != 0:
number, i = divmod(number, len(alphabet))
base36 = alphabet[i] + base36
return sign + base36 |
def inner_vertices(ver_dic, edg_dic):
"""
makes a list of inner vertex indeces
"""
inner=[]
for ind in ver_dic:
if len([k for (k, v) in edg_dic.items() if v.count(ind)==1])>1:
inner.append(ind)
return inner |
def join(r_zero, r_one):
""" Take(x, y, w, [h]) squares """
if not r_zero:
return r_one
if not r_one:
return r_zero
if not r_zero and not r_one:
return None
if len(r_zero) == 3:
r_zero = (r_zero[0], r_zero[1], r_zero[2], r_zero[2])
if len(r_one) == 3:
r_one = (r_one[0], r_one[1], r_one[2], r_one[2])
x_one = min(r_zero[0], r_one[0])
x_two = max(r_zero[0] + r_zero[2], r_one[0] + r_one[2])
y_one = min(r_zero[1], r_one[1])
y_two = max(r_zero[1] + r_zero[3], r_one[1] + r_one[3])
return (x_one, y_one, x_two - x_one, y_two - y_one) |
def manhattan_cost(curr, end):
"""
Estimates cost from curr (x0,y0) to end (x1,y1) using Manhattan
distance.
"""
curr_x, curr_y = curr
end_x, end_y = end
return abs(curr_x-end_x) + abs(curr_y-end_y) |
def get_lines_for(identifier, module_lines, block_type):
"""
Extract a Python value definition (list, tuple, dict) in Python code
(such as the settings file), and return its content as a list of strings.
Return an empty list if not found.
"""
delimiters_for = {
str: ('', '\n'),
list: ('[', ']'),
tuple: ('(', ')'),
dict: ('{', '}'),
}
start_symbol, stop_symbol = delimiters_for[block_type]
try:
start = module_lines.index('%s = %s' % (identifier, start_symbol))
stop = module_lines.index(stop_symbol, start)
value_lines = module_lines[start:stop + 1]
return [line.strip() for line in value_lines]
except ValueError:
return [] |
def get_prefered_quotation_from_string(string):
"""
Tries to determin the quotation (`"` or `'`) used in a given string.
`"` is the default and used when no quotations are found or
the amount of `"` and `'` are equal
"""
return "'" if string.count("'") > string.count('"') else '"' |
def get_connection_name(connection_id, friend_list):
"""
Given a mutual friends' ID, check the given list of Facebook friends and extract the name.
:param connection_id: Connection's (mutual friend) Facebook ID.
:type connection_id: str
:param friend_list: List of Facebook friends.
:type friend_list: list of pynder.models.friend.Friend
:return: Friend's name.
:rtype: str
"""
for friend in friend_list:
if connection_id == friend.facebook_id:
return friend.name
return '' |
def _clip(n: float) -> float:
"""
Helper function to emulate numpy.clip for the specific
use case of preventing math domain errors on the
acos function by "clipping" values that are > abs(1).
e.g. _clip(1.001) == 1
_clip(-1.5) == -1
_clip(0.80) == 0.80
"""
sign = n / abs(n)
if abs(n) > 1:
return 1 * sign
else:
return n |
def validate_month(value):
"""
Function to validate the zodiac sign month
Args:
value (str): zodiac sign month to be validated
Raises:
(ValueError): Raise ValueError if the zodiac sign month invalid
Return:
value (str): valid zodiac sign month
"""
month = ""
try:
month = int(value)
except ValueError:
raise ValueError("Month must be an integer")
if month < 1 or month > 12:
raise ValueError("Month out of range")
return value |
def Unindent(string, spaces=2):
"""
Returns string with each line unindented by 2 spaces. If line isn't indented, it stays the same.
>>> Unindent(" foobar")
'foobar\\n'
>>> Unindent("foobar")
'foobar\\n'
>>> Unindent('''foobar
... foobar
... foobar''')
'foobar\\nfoobar\\nfoobar\\n'
"""
newstring = ''
lines = string.splitlines()
for line in lines:
if line.startswith(spaces*' '):
newstring += (line[spaces:] + "\n")
else:
newstring += (line + "\n")
return newstring |
def find_first_slice_value(slices, key):
"""For a list of slices, get the first value for a certain key."""
for s in slices:
if key in s and s[key] is not None:
return s[key]
return None |
def _to_str(val):
"""Safe conversion."""
if val.strip() == "":
return None
return val.strip() |
def soloList(data, index):
"""convert all values in a index in a list to a single list"""
x = []
for i in data:
x.append(i[index])
return x |
def get_factors(n):
"""Return a list of the factors of a number n.
Does not include 1 or the number n in list of factors because they're used for
division questions.
"""
factors = []
for i in range(2, n):
if n % i == 0:
factors.append(i)
return factors |
def hidden_vars(vrs):
"""Slice dictionary `vrs`, keeping keys matching `_*`."""
return {k: v for k, v in vrs.items()
if k.startswith('_')} |
def cc_colors(coord, lighness=0):
"""Predefined CC colors."""
colors = {
"A": ["#EA5A49", "#EE7B6D", "#F7BDB6"],
"B": ["#B16BA8", "#C189B9", "#D0A6CB"],
"C": ["#5A72B5", "#7B8EC4", "#9CAAD3"],
"D": ["#7CAF2A", "#96BF55", "#B0CF7F"],
"E": ["#F39426", "#F5A951", "#F8BF7D"],
"Z": ["#000000", "#666666", "#999999"],
}
return colors[coord[:1]][lighness] |
def create_json_from_stories(stories_and_location):
""" Convert the preprocessed stories into a list of dictionaries. This will help us with making
the 3d visualizations """
stories = []
for story, location, link, geo_coordinates, category, img_url, summary in stories_and_location:
story_dict = {}
story_dict["title"] = story
story_dict["locations"] = location
story_dict["link"] = link
story_dict["geo_coordinates"] = geo_coordinates
story_dict["category"] = category
story_dict["img_url"] = img_url
story_dict["summary"] = summary
stories.append(story_dict)
return stories |
def ctoa(character: str) -> int:
"""Find the ASCII value of character.
Uses the ord builtin function.
"""
code = ord(character)
return code |
def _solve_dependencies(dependencies, all_members=None):
"""Solve a dependency graph.
:param dependencies: dependency dictionary. For each key, the value is
an iterable indicating its dependencies.
:param all_members: If provided
:return: list of sets, each containing independent task only dependent of the
previous set in the list.
"""
d = dict((key, set(value)) for key, value in dependencies.items())
if all_members:
d.update({key: set() for key in all_members if key not in d})
r = []
while d:
# values not in keys (items without dep)
t = set(i for v in d.values() for i in v) - set(d.keys())
# and keys without value (items without dep)
t.update(k for k, v in d.items() if not v)
# can be done right away
r.append(t)
# and cleaned up
d = dict(((k, v - t) for k, v in d.items() if v))
return r |
def clean_completion_name(name: str, char: str) -> str:
"""Clean the completion name, stripping bad surroundings
1. Remove all surrounding " and '. For
"""
if char == "'":
return name.lstrip("'")
if char == '"':
return name.lstrip('"')
return name |
def single_l1(value_1, value_2):
""" compute L1 metric """
return abs(value_1 - value_2) |
def un_pad(word):
"""
Removes additional padding from string
:param word: <string>
:return: string after removing padding from it <string>
"""
padding_length = ord(word[len(word) - 1:])
un_padded_word = word[:-padding_length]
return un_padded_word |
def make_symmetry_matrix(upper_triangle):
"""
Make a symmetric matrix from a list of integers/rationals.
"""
length = len(upper_triangle)
if length not in (3, 6, 10):
raise ValueError("the length of the coxeter diagram must be 3 or 6 or 10.")
if length == 3:
a12, a13, a23 = upper_triangle
return [[1, a12, a13],
[a12, 1, a23],
[a13, a23, 1]]
if length == 6:
a12, a13, a14, a23, a24, a34 = upper_triangle
return [[1, a12, a13, a14],
[a12, 1, a23, a24],
[a13, a23, 1, a34],
[a14, a24, a34, 1]]
if length == 10:
a12, a13, a14, a15, a23, a24, a25, a34, a35, a45 = upper_triangle
return [[1, a12, a13, a14, a15],
[a12, 1, a23, a24, a25],
[a13, a23, 1, a34, a35],
[a14, a24, a34, 1, a45],
[a15, a25, a35, a45, 1]] |
def scale_reader_decrease(provision_decrease_scale, current_value):
"""
:type provision_decrease_scale: dict
:param provision_decrease_scale: dictionary with key being the
scaling threshold and value being scaling amount
:type current_value: float
:param current_value: the current consumed units or throttled events
:returns: (int) The amount to scale provisioning by
"""
scale_value = 0
if provision_decrease_scale:
for limits in sorted(provision_decrease_scale.keys(), reverse=True):
if current_value > limits:
return scale_value
else:
scale_value = provision_decrease_scale.get(limits)
return scale_value
else:
return scale_value |
def flat(_list):
""" [(1,2), (3,4)] -> [1, 2, 3, 4]"""
res = []
for item in _list:
res.extend(list(item))
return res |
def rk4(y, f, t, h):
"""Runge-Kutta RK4"""
k1 = f(t, y)
k2 = f(t + 0.5*h, y + 0.5*h*k1)
k3 = f(t + 0.5*h, y + 0.5*h*k2)
k4 = f(t + h, y + h*k3)
return y + h/6 * (k1 + 2*k2 + 2*k3 + k4) |
def id_mapping(IDs1, IDs2, uniq_ref_only=True, IDs2_sorted=False):
"""
Mapping IDs2 to IDs1. IDs1 (ref id) can have repeat values, but IDs2 need
to only contain unique ids.
Therefore, IDs2[rv_idx] will be the same as IDs1.
Parameters
----------
IDs1 : array_like or list
ids for reference.
IDs2 : array_like or list
ids waiting to map.
Returns
-------
RV_idx : array_like, the same length of IDs1
The index for IDs2 mapped to IDs1. If an id in IDs1 does not exist
in IDs2, then return a None for that id.
"""
idx1 = sorted(range(len(IDs1)), key=IDs1.__getitem__)
if IDs2_sorted:
idx2 = range(len(IDs2))
else:
idx2 = sorted(range(len(IDs2)), key=IDs2.__getitem__)
RV_idx1, RV_idx2 = [], []
i, j = 0, 0
while i < len(idx1):
if j == len(idx2) or IDs1[idx1[i]] < IDs2[idx2[j]]:
RV_idx1.append(idx1[i])
RV_idx2.append(None)
i += 1
elif IDs1[idx1[i]] == IDs2[idx2[j]]:
RV_idx1.append(idx1[i])
RV_idx2.append(idx2[j])
i += 1
if uniq_ref_only: j += 1
elif IDs1[idx1[i]] > IDs2[idx2[j]]:
j += 1
origin_idx = sorted(range(len(RV_idx1)), key=RV_idx1.__getitem__)
RV_idx = [RV_idx2[i] for i in origin_idx]
return RV_idx |
def start_of_chunk(prev_tag, tag, prev_type, type_):
"""Checks if a chunk started between the previous and current word.
Args:
prev_tag: previous chunk tag.
tag: current chunk tag.
prev_type: previous type.
type_: current type.
Returns:
chunk_start: boolean.
"""
chunk_start = False
if tag == 'B': chunk_start = True
if tag == 'S': chunk_start = True
if prev_tag == 'E' and tag == 'E': chunk_start = True
if prev_tag == 'E' and tag == 'I': chunk_start = True
if prev_tag == 'S' and tag == 'E': chunk_start = True
if prev_tag == 'S' and tag == 'I': chunk_start = True
if prev_tag == 'O' and tag == 'E': chunk_start = True
if prev_tag == 'O' and tag == 'I': chunk_start = True
if tag != 'O' and tag != '.' and prev_type != type_:
chunk_start = True
return chunk_start |
def get_compound_type(compound_types):
"""Returns mcf value format of the typeOf property for a compound.
This is applied to the 'Type' entry of each row of drugs_df.
Args:
compound_types: string of comma separated list of type values
Returns:
If the compound is of a drug type, then typeOf value should be dcs:Drug
Otherwise the typeOf should be dcid:ChemicalCompound
If the list contains both drug types and non drug types, then the typeOf
should be dcid:ChemicalCompound,dcid:Drug
"""
drug_types = ['Drug', 'Drug Class', 'Prodrug']
types = set()
for compound_type in compound_types.split(','):
compound_type = compound_type.replace('"', '').strip()
if compound_type in drug_types:
types.add('dcid:Drug')
else:
types.add('dcid:ChemicalCompound')
if len(types) == 2:
return 'dcs:ChemicalCompound,dcs:Drug'
return types.pop() |
def containsAny(str, set):
""" Check whether sequence str contains ANY of the items in set. """
return 1 in [c in str for c in set] |
def determine_pos_neu_neg(compound):
"""
Based on the compound score, classify a sentiment into positive, negative, or neutral.
Arg:
compound: A numerical compound score.
Return:
A label in "positive", "negative", or "neutral".
"""
if compound >= 0.05:
return 'positive'
elif compound < 0.05 and compound > -0.05:
return 'neutral'
else:
return 'negative' |
def first_dup(s):
"""
Find the first character that repeats
in a String and return that character.
:param s:
:return:
"""
for char in s:
if s.count(char) > 1:
return char
return None |
def binary_search_iterative(arr, val, start, end):
"""searches arr for val.
Parameters:
arr (array): array to search.
val (type used in array): value to search for in arr.
Returns:
(int) : index of val in arr if val is found.
Otherwise returns -1 if val cannot be found in arr.
"""
#while the size of the search space is greater than 0
while start <= end:
mid = ((end - start) // 2) + start
if arr[mid] == val:
#we found what we want. Yay!
return mid
elif arr[mid] > val:
#search bottom half of search space
end = mid - 1
elif arr[mid] < val:
#search top half of search space
start = mid + 1
#couldn't find the value
return -1 |
def _normalize_image_location_for_db(image_data):
"""
This function takes the legacy locations field and the newly added
location_data field from the image_data values dictionary which flows
over the wire between the registry and API servers and converts it
into the location_data format only which is then consumable by the
Image object.
:param image_data: a dict of values representing information in the image
:return: a new image data dict
"""
if 'locations' not in image_data and 'location_data' not in image_data:
image_data['locations'] = None
return image_data
locations = image_data.pop('locations', [])
location_data = image_data.pop('location_data', [])
location_data_dict = {}
for l in locations:
location_data_dict[l] = {}
for l in location_data:
location_data_dict[l['url']] = {'metadata': l['metadata'],
'status': l['status'],
# Note(zhiyan): New location has no ID.
'id': l['id'] if 'id' in l else None}
# NOTE(jbresnah) preserve original order. tests assume original order,
# should that be defined functionality
ordered_keys = locations[:]
for ld in location_data:
if ld['url'] not in ordered_keys:
ordered_keys.append(ld['url'])
location_data = []
for loc in ordered_keys:
data = location_data_dict[loc]
if data:
location_data.append({'url': loc,
'metadata': data['metadata'],
'status': data['status'],
'id': data['id']})
else:
location_data.append({'url': loc,
'metadata': {},
'status': 'active',
'id': None})
image_data['locations'] = location_data
return image_data |
def reformat(formula):
"""Add spaces around each parens and negate and split the formula."""
formula = ''.join(f' {i} ' if i in '~()' else i for i in formula)
return formula.split() |
def _get_percentage_difference(measured, base):
"""Return the percentage delta between the arguments."""
if measured == base:
return 0
try:
return (abs(measured - base) / base) * 100.0
except ZeroDivisionError:
# It means base and only base is 0.
return 100.0 |
def repo_name(url):
"""Normalize repository name from git url."""
data = url.rstrip('/').split('/')[-2:]
return '__'.join(data) |
def make_word_groups(vocab_words):
"""
:param vocab_words: list of vocabulary words with a prefix.
:return: str of prefix followed by vocabulary words with
prefix applied, separated by ' :: '.
This function takes a `vocab_words` list and returns a string
with the prefix and the words with prefix applied, separated
by ' :: '.
"""
vocab_words.reverse()
prefix = vocab_words.pop()
new_list = [prefix]
vocab_words.reverse()
for i in range(len(vocab_words)):
new_list.append(prefix + vocab_words[i])
# print(new_list)
return " :: ".join(new_list) |
def get_by_dotted_path(d, path, default=None):
"""
Get an entry from nested dictionaries using a dotted path.
Example:
>>> get_by_dotted_path({'foo': {'a': 12}}, 'foo.a')
12
"""
if not path:
return d
split_path = path.split('.')
current_option = d
for p in split_path:
if p not in current_option:
return default
current_option = current_option[p]
return current_option |
def get_id(record):
"""Get the Id out of a VPC record.
Args:
record
A VPC record returned by AWS.
Returns:
The VPC's ID.
"""
return record["VpcId"] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.