content stringlengths 42 6.51k |
|---|
def getkw(kw, name):
""" function to get a dictionary entry and remove it from the dictionary"""
v = kw.get(name)
if name in list(kw.keys()): del kw[name]
return v |
def angle(val):
"""Convert an integer value to a floating point angle."""
return val * 360. / 2**16 |
def author_list(authors):
"""Convert list of author DB objects to JSON."""
return [{"name": a.name, "email": a.email} for a in authors] |
def end (cave):
"""Indicates whether or not `cave` is 'end'."""
return cave == 'end' |
def get_attr_info(key, convention, normalized):
"""Get information about the MMD fields.
Input
=====
key: str
MMD element to check
convention: str
e.g., acdd or acdd_ext
normalized: dict
a normalized version of the mmd_elements dict (keys are, e.g.,
'personnel>or... |
def htk_int_to_float(value):
""" Converts an integer value (time in 100ns units) to floating
point value (time in seconds)...
"""
return float(value) / 10000000.0 |
def get_words(text):
""" Return a list of dict words """
return text.split() |
def collatz_sequence(n):
"""
Collatz conjecture: start with any positive integer n.Next term is obtained from the previous term as follows:
if the previous term is even, the next term is one half of the previous term.
If the previous term is odd, the next term is 3 times the previous term plus 1.
Th... |
def find_block_mesh_template(current_dir):
"""Create a static files folder for placing files that are not changed across the simulation space
Args:
current_dir (str): Current working directory.
Returns:
block_mesh_template_path (str): full path where the block mesh template exists.
... |
def unprintable(mystring):
"""return only the unprintable characters of a string"""
from string import printable
return ''.join(
character
for character in mystring
if character not in printable
) |
def _mk(bdd, i, l, h):
"""
mk function, will check to see if a node is already created for
a variable, high, low triple. If not, makes one.
"""
#if high and low are the same
if l == h:
return l
#if a node already exists
if (i,l,h) in bdd["h_table"]:
return bdd["h_table"]... |
def find(node, key):
"""Find a node with a given key within a BST."""
# For a balanced BST, this func only takes O(log N); otherwise it's O(N)
if node is None:
return None
if key == node.key:
return node
if key < node.key:
return find(node.left, key)
if key > node.key:
... |
def fgrep(text, term, window=25, with_idx=False, reverse=False):
"""Search a string for a given term. If found, print it with some context.
Similar to `grep -C 1 term text`. `fgrep` is short for faux grep.
Parameters
----------
text: str
Text to search.
term: str
Term to look fo... |
def decrypt(ciphertext, key, cipher):
"""
Using Vignere cipher to decrypt ciphertext.
:param ciphertext: encrypted text to decrypt with given key and given cipher
:param key: the key is appended until it has same length as ciphertext;
each character of the key decides which cipher to us... |
def greedy_cow_transport(cows, limit=10):
"""
Uses a greedy heuristic to determine an allocation of cows that attempts to
minimize the number of spaceship trips needed to transport all the cows. The
returned allocation of cows may or may not be optimal.
The greedy heuristic should follow the fo... |
def _fuel_requirement(mass: int) -> int:
"""Calculates the fuel requirement for a given mass."""
return mass // 3 - 2 |
def remove_none(nums):
"""Get a list without Nones. Input `nums` can be list or tuple."""
return [x for x in nums if x is not None] |
def get_source_with_id(result):
"""Return a document's `_source` field with its `_id` added.
Parameters
----------
result : dict
A document from a set of Elasticsearch search results.
Returns
-------
dict
The document's `_source` field updated with the doc's `_id`.
"""... |
def calcStraightLine(x0, y0, x1, y1):
"""
calculates the slope and the axis intercept of a straight line using to
points in an x, y grid
:Parameters:
x0, y0, x1, y1: float
2 points in an x, y grid
:Returns:
m, b: float
the slope and the axis intercept... |
def euler28(n=1001):
"""Solution for problem 28."""
# For a level of size s (s>1), corners are :
# s*s, s*s-s+1, s*s-2s+2, s*s-3s+3
# Their sum is 4*s*s - 6*s + 6 (3 <= s <= n)
# Writing s = 2*j + 3, sum of corners is
# 16*j*j + 36j + 24
# This sum could be computed in constant time but thi... |
def get_lr(epoch_size, step_size, lr_init):
"""
generate learning rate for each step, which decays in every 10 epoch
Args:
epoch_size(int): total epoch number
step_size(int): total step number in each step
lr_init(int): initial learning rate
Returns:
List, learning r... |
def parse_lambda_config(x):
"""
Parse the configuration of lambda coefficient (for scheduling).
x = "3" # lambda will be a constant equal to x
x = "0:1,1000:0" # lambda will start from 1 and linearly decrease
# to 0 during the first 1000 iterations
... |
def str_or_blank(val) -> str:
"""Return a string or blank for None."""
if val is not None:
return str(val)
else:
return "" |
def create_crumb(title, url=None):
"""
Helper function
"""
if url:
crumb = "> <li><a href='{}'>{}</a></li>".format(url, title)
else:
crumb = '> <li class="active">{}</a>'.format(title)
return crumb |
def ret_int(potential):
"""Utility function to check the input is an int, including negative."""
try:
return int(potential)
except:
return None |
def env_chk(val, fw_spec, strict=True, default=None):
"""
env_chk() is a way to set different values for a property depending
on the worker machine. For example, you might have slightly different
executable names or scratch directories on different machines.
env_chk() works using the principles of ... |
def get_metrics_problem(metrics, problem):
"""
Function:
get_metrics_problem
Description:
From a list of Metrics, returns only those that match with problem.
Input:
- metrics,list: List of Metric objects
- problem,str: Type of problem
O... |
def find_cell_index(x, lower, upper, delta):
"""Find the local index in 1D so that lower + i * delta <= x < lower + (i + 1) * delta.
Arguments
---------
x : float
The target coordinate.
"""
if x < lower or x >= upper:
return None
return int((x-lower)//delta) |
def list_product(some_list):
"""
Returns the product of all the elements in the input list.
"""
product = 1
for element in some_list:
product *= element
return product |
def hex_str(raw: bytes) -> str:
"""
>>> hex_str(b"hello world!")
'68 65 6C 6C 6F 20 77 6F 72 6C 64 21'
"""
encoded = raw.hex().upper()
return " ".join(encoded[i : i + 2] for i in range(0, len(encoded), 2)) |
def break_into_sentences(data_in, exclude_toks=['<SOS>']):
"""
Break a list of tokens into a list of lists, removing EOS tokens and having each list be a standalone sentence
:param data_in: long list of sentences or string of tokens
:param exclude_toks: tokens to skip (like SOS. leave in EOS because we ... |
def create_meta_value(value):
"""
This function is used to to transform the value output of Dobie to meta data value
:param value: provided Dobie value
:return: metadata value
"""
extracted_value = value.replace("+", "plus")
split_value = extracted_value.split(" ")
if len(split_value) ... |
def getJoinRow(csvReader, joinColumn, joinValue):
"""
Look for a matching join value in the given csv filereader and return the row, or None.
This assumes we're walking through the join file in one direction,
so must be sorted on the join column.
csvReader iterator must be wrapped with more_itertool... |
def _parse_snapshots(data, filesystem):
"""
Parse the output of a ``zfs list`` command (like the one defined by
``_list_snapshots_command`` into a ``list`` of ``bytes`` (the snapshot
names only).
:param bytes data: The output to parse.
:param Filesystem filesystem: The filesystem from which to... |
def c2f(celsius):
""" Convert Celcius to Farenheit """
return 9.0/5.0 * celsius + 32 |
def create_legend_panel(workflow_stat):
"""
Generates the bottom level legend panel content.
@param workflow_stat the WorkflowInfo object reference
"""
panel_str ="""
<script type="text/javascript+protovis">
var bc_footerPanel = new pv.Panel()
.width(bc_footerPanelWidth)
.height(bc_footerPanelHeight)
.fillStyle('... |
def check_double_biconditional(x_value, y_value, z_value):
"""This function takes in three list of booleans and computes a double biconditional list.
Args:
x_value = a list of booleans
y_value = a list of booleans
z_value = a list of booleans
Returns:
double_biconditiona... |
def glob_to_sql(string: str) -> str:
"""Convert glob-like wildcards to SQL wildcards
* becomes %
? becomes _
% becomes \%
\\ remains \\
\* remains \*
\? remains \?
This also adds a leading and trailing %, unless the pattern begins with
^ or ends with $
"""
# What's with th... |
def convert_to_str(string):
"""Helper function to catch bytes as strings"""
if type(string) is str:
return string
else:
return bytes.decode(string) |
def split_data_list(list_data, num_split):
""" list_data: list of data items
returning: list with num_split elements,
each as a list of data items
"""
num_data_all = len(list_data)
num_per_worker = num_data_all // num_split
print("num_data_all: %d" % num_data_all... |
def vlan_bitmap_undo(bitmap):
"""convert vlan bitmap to undo bitmap"""
vlan_bit = ['F'] * 1024
if not bitmap or len(bitmap) == 0:
return ''.join(vlan_bit)
bit_len = len(bitmap)
for num in range(bit_len):
undo = (~int(bitmap[num], 16)) & 0xF
vlan_bit[num] = hex(undo)[2]
... |
def GetPosTM_MSA(posTMList, specialProIdxList):# {{{
"""
Get the beginning and end position of the MSA which has TM helices
"""
beg = 9999999999
end = -1
for i in range(len(posTMList)):
if not i in specialProIdxList:
posTM = posTMList[i]
if posTM[0][0] < beg:
... |
def uniquify_in_order(seq):
"""Produces a list with unique elements in the same order as original sequence.
https://stackoverflow.com/questions/480214/how-do-you-remove-duplicates-from-a-list-whilst-preserving-order
"""
seen = set()
seen_add = seen.add
return [x for x in seq if not (x in seen o... |
def remove_quotes(s, l, t):
"""
Helper parse action for removing quotation marks from parsed
quoted strings.
Example::
# by default, quotation marks are included in parsed results
quoted_string.parse_string("'Now is the Winter of our Discontent'") # -> ["'Now is the Winter of our Disco... |
def escape(s):
"""Replace quotes with escaped quotes and line breaks with \n for JSON"""
return s.replace('"', '\\"').replace("\n", "\\n") |
def first_occ(added_symbol, proj):
"""
Computes the first first time "added_symbol" appears for each transaction in "proj"
"""
first = []
a = tuple()
a += (added_symbol,)
processed = proj.get(a[0], [])
if not processed:
return first
last_trans_index = processed[0][0]
fir... |
def get_nonce_bytes(n):
"""BOLT 8 requires the nonce to be 12 bytes, 4 bytes leading
zeroes and 8 bytes little endian encoded 64 bit integer.
"""
return b"\x00"*4 + n.to_bytes(8, 'little') |
def clean_latex_name(label):
""" Convert possible latex expression into valid variable name """
if not isinstance(label,str):
label = str(label)
# -1- Supress \
label = label.replace('\\','')
# -2- Supress '{' .. '}'
label = label.replace('{','')
label = label.replace('}', '')
... |
def total_occurences(s1, s2, ch):
"""(str, str, str) -> int
Precondition: len(ch) == 1
Return the total number of times ch appears in s1 and s2.
>>> total_occurences('red', 'blue', 'u')
1
"""
# total_occurences('Yellow', 'Blue', 'u')
return (s1 + s2).count(ch) |
def sum_sum(lists):
"""Returns total sum for list of lists."""
return sum(sum(x) for x in lists) |
def spike_lmax(S, Q):
"""Maximum spike given a perturbation"""
S2 = S * S
return ((1.0 / Q) + S2) * (1 + (1.0 / S2)) |
def extractNew(data: str):
"""
Data -> just full type (e.g: new MyClass() -> MyClass).
"""
assert type(data) == str
news = set()
for i, c in enumerate(data):
if data[i:i+len('extends')] == 'extends':
rest = []
for j in range(i, len(data)):
if... |
def buildEventString(events):
"""
Function to produce a string representing the event history of a single binary for quick readability.
IN:
events (list of tuples): events output from getEventHistory()
OUT:
eventString (string): string representing the event history of the binary
... |
def _diff_env(a, b):
"""Return difference of two environments dict"""
seta = set([(k, a[k]) for k in a])
setb = set([(k, b[k]) for k in b])
return dict(seta - setb), dict(setb - seta) |
def solution(capacity, items): # O(M * N)
"""
Given the capacity of the knapsack and items specified by weights and values,
return the maximum summarized value of the items that can be fit in the
knapsack.
Example:
capacity = 5, items(value, weight) = [(... |
def IsCustomMetadataHeader(header):
"""Returns true if header (which must be lowercase) is a custom header."""
return header.startswith('x-goog-meta-') or header.startswith('x-amz-meta-') |
def subdivide(R, C, max_size = 36):
"""splits array into subarrays of manageable size"""
def size(y1, x1, y2, x2):
return (y2 - y1 + 1) * (x2 - x1 + 1)
def helper(y1, x1, y2, x2):
nonlocal max_size
if size(y1, x1, y2, x2) <= max_size:
return [(y1, x1, y... |
def check_valid(word, letters):
"""Take a word as a dictionary and checks that is valid.
:param word: Word as a dictionary
:param letters: Letters as a dictionary
:returns: Return False if not valid or deletes performed on letters
"""
curr_min = len(letters) # Minimum erases set to len of lette... |
def check_iterable_item_type(iter_obj):
""" Check if all items within an iterable are the same type.
Args:
iter_obj: iterable object
Returns:
iter_type: type of item contained within the iterable. If
the iterable has many types, a boolean False is returned instead.
... |
def get_boresights(bore_files):
"""
Extract data from five-point boresight files.
@param bore_files : Full paths to the boresight files.
@type bore_files : list
@return: (dict) The keys are::
- X_BW: measured beamwidth in cross-elevation or cross-declination
- DOY: day of year
... |
def minimax_jit(maxing_player, next_depth, worth, alpha, beta):
"""
jit version of the minimax logic.
"""
worth = max(next_depth, worth) if maxing_player else min(next_depth, worth)
if maxing_player:
alpha = max(alpha, worth)
else:
beta = min(beta, worth)
return beta, alpha, ... |
def is_switchport_default(existing):
"""Determines if switchport has a default config based on mode
Args:
existing (dict): existing switcport configuration from Ansible mod
Returns:
boolean: True if access port and access vlan = 1 or
True if trunk port and native = 1 and t... |
def format_arg_value(arg_val):
""" Return a string representing a (name, value) pair.
Examples:
>>> format_arg_value(('x', (1, 2, 3)))
'x=(1, 2, 3)'
"""
arg, val = arg_val
return "%s=%r" % (arg, val) |
def denormalize(column, startvalue, endvalue):
"""
converts [0:1] back with given start and endvalue
"""
normcol = []
if startvalue>0:
if endvalue < startvalue:
raise ValueError("start and endval must be given, endval must be larger")
else:
for elem in column:... |
def deal_new_stack(cards):
"""Return reversed cards."""
cards.reverse()
return cards |
def classify_platform(os_string):
"""
:type os_string: str
:return: str
"""
os_string = os_string.strip()
if os_string == "Windows" or os_string.startswith("IBM"):
return "Windows"
elif os_string == "Mac" or os_string.startswith("APL"):
return "Mac"
elif os_string == "Lin... |
def toX4(x, y=None):
"""
This function is used to load value on Plottable.View
Calculate x^(4)
:param x: float value
"""
return x * x * x * x |
def urljoin(*args):
"""
Joins given arguments into an url. Trailing but not leading slashes are
stripped for each argument.
"""
url = "/".join(map(lambda x: str(x).rstrip('/'), args))
if '/' in args[-1]:
url += '/'
if '/' not in args[0]:
url = '/' + url
url = url.replac... |
def check_ssl(aba, bab):
"""
checks if any matches of valid aba & bab are found
"""
for a in aba:
for b in bab:
if a[0] == b[1] and b[0] == a[1]:
return True
return False |
def get_func_name(func):
"""Get name of a function.
Parameters
----------
func: Function
The input function.
Returns
-------
name: str
The function name.
"""
return func.func_name if hasattr(func, "func_name") else func.__qualname__ |
def validate(data_dict, required, optional, filter_unknown_fields=False):
"""Make sure all required fields are present and all other fields are
optional. If an unknown field is found and filter_unknown_fields is False,
return an error. Otherwise, just filter the field out."""
final = {}
for key in r... |
def calculate_heat_index(temp, hum):
"""
:param temp: temperature in degrees fahrenheit
:param hum: relative humidity as an integer 0-100
:return: heat index
"""
humidity = hum
temperature = float(temp)
c1 = -42.379
c2 = 2.04901523
c3 = 10.14333127
c4 = -0.22475541
c5 = -... |
def format_board_time(dt):
"""
Format a time for the big board
"""
if not dt:
return ''
return '{d:%l}:{d.minute:02}'.format(d=dt) + ' EST' |
def is_edit_mode(request):
"""
Return whether edit mode is enabled; output is wrapped in ``<div>`` elements with metadata for frontend editing.
"""
return getattr(request, "_fluent_contents_edit_mode", False) |
def _get_target_columns(metadata):
"""Given ModelPipeline metadata, construct the list of columns output by
the model's prediction method.
"""
target_cols = []
if metadata['model']['type'] == 'classification':
# Deal with multilabel models, if necessary
if len(metadata['data']['targe... |
def list_data(args, data):
"""List all servers and files associated with this project."""
if len(data["remotes"]) > 0:
print("Servers:")
for server in data["remotes"]:
if server["name"] == server["location"]:
print(server["user"] + "@" + server["location"])
... |
def NewerDataThanExtrapolation(TopLevelInputDir, TopLevelOutputDir, SubdirectoriesAndDataFiles):
"""Find newer data than extrapolation."""
from os.path import exists, getmtime
Newer = []
for Subdirectory, DataFile in SubdirectoriesAndDataFiles:
FinishedFile = "{}/{}/.finished_{}".format(TopLeve... |
def getValue(valOb):
"""
Return the value (for toi attributes it could be the object) of an
attribute.
Arguments: The value object
Returns: The value
"""
if hasattr(valOb, 'value'):
return valOb.value
return valOb |
def is_suspicious(transaction: dict) -> bool:
"""Determine whether a transaction is suspicious."""
return transaction["amount"] >= 900 |
def find(haystack, needle):
"""
>>> find("ll", "hello")
-1
>>> find("", "")
0
>>> find("hello", "ll")
2
>>> find("aaaaabba", "bba")
5
>>> find("bbaaaaaa", "bba")
0
>>> find("aaaaa", "bba")
-1
"""
m = len(haystack)
n = len(needle)
if m < n:
retu... |
def _get_color_end_tex(entity_id: str) -> str:
"""
A message is added after an entity is colorized to assist the pipeline with error recovery.
This allows the pipeline to scan the output of the TeX compiler to detect which entities
were successfully colorized before errors were encountered.
"""
... |
def _get_inner_type(typestr):
""" Given a str like 'org.apache...ReversedType(LongType)',
return just 'LongType' """
first_paren = typestr.find('(')
return typestr[first_paren + 1:-1] |
def _tuple2list(tupl):
"""Iteratively converts nested tuple to nested list.
Parameters
----------
tupl : tuple
The tuple to be converted.
Returns
-------
list
The converted list of lists.
"""
return list((_tuple2list(x) if isinstance(x, tuple) else x for x in tupl)) |
def is_unique_chars_v1(str):
"""
Let N be the string length
List construction: O(N)
Set construction: O(N)
len function: O(1)
=> O(N) time
=> O(N) space
"""
chars = list(str)
unique_chars = set(chars)
return len(chars) == len(unique_chars) |
def dicts_equal(dictionary_one, dictionary_two):
"""
Return True if all keys and values are the same between two dictionaries.
"""
return all(
k in dictionary_two and dictionary_one[k] == dictionary_two[k]
for k in dictionary_one
) and all(
k in dictionary_one and dictionary_... |
def formatTimeString(seconds:int) -> str:
"""
Converts seconds to a string with the format MM:SS.
"""
m, s = divmod(seconds, 60)
return "{:02.0f} minute(s) {:02.0f} seconds".format(m, s) |
def extract_capital_letters(x):
""" Extract capital letters from string """
try:
return "".join([s for s in x if s.isupper()])
except Exception as e:
print(f"Exception raised:\n{e}")
return "" |
def adj_list_to_edges(adj_list):
"""
Turns an adjecency list in a list of edges (implemented as a list).
Input:
- adj_list : a dict of a set of weighted edges
Output:
- edges : a list of weighted edges (e.g. (0.7, 'A', 'B') for an
edge from node A to node B with wei... |
def get_device_sleep_period(settings: dict) -> int:
"""Return the device sleep period in seconds or 0 for non sleeping devices."""
sleep_period = 0
if settings.get("sleep_mode", False):
sleep_period = settings["sleep_mode"]["period"]
if settings["sleep_mode"]["unit"] == "h":
sle... |
def get_strongly_connected_components(edges, num_vertex):
"""
edges: {v: [v]}
"""
from collections import defaultdict
reverse_edges = defaultdict(list)
for v1 in edges:
for v2 in edges[v1]:
reverse_edges[v2].append(v1)
terminate_order = []
done = [0] * num_vertex #... |
def prod2( *args ):
"""
>>> prod2( 1, 2, 3, 4 )
24
>>> prod2(*range(1, 10))
362880
"""
p= 1
for item in args:
p *= item
return p |
def remove_shard_path(path):
""" Remove the workflow name from the beginning of task, input and output names (if it's there).
E.g. Task names {..}/{taskName}/shard-0 => {..}/{taskName}/
"""
if not path:
return None
if "/shard-" in path:
return path.split('/shard-')[0]
return pat... |
def largeGroupPositions(S):
"""
:type S: str
:rtype: List[List[int]]
"""
d={}
result=[]
for i,string in enumerate(S):
if string not in d:
d[string]=[[i]]
else:
if d[string][-1][-1]+1==i:
d[string][-1].append(i)
else:
d[string].append([i])
for key in d:
for i in d[key]:
if len(i) >=3:... |
def block_number(row, column):
"""
Determines the block number in which the given row and column numbers intersects in sudoku
args:
-rows - Row number
-column - Column number
returns: Block number
"""
ele = str(row) + str(column)
skeleton_matrix = [
['00', '01', '02', '10',... |
def merge_hsbk(base, change):
"""Copy change on top of base, except when None."""
if change is None:
return None
return [b if c is None else c for b, c in zip(base, change)] |
def _extract_license_outliers(license_service_output):
"""Extract license outliers.
This helper function extracts license outliers from the given output of
license analysis REST service.
:param license_service_output: output of license analysis REST service
:return: list of license outlier package... |
def pattern_to_regex(pattern):
"""
Convert the CODEOWNERS path pattern into a regular expression string.
"""
orig_pattern = pattern # for printing errors later
# Replicates the logic from normalize_pattern function in Gitlab ee/lib/gitlab/code_owners/file.rb:
if not pattern.startswith('... |
def add_loc_offset(v_d, l, d_s):
"""Compute the real location from the default boxes location v_d and
the scaled offset value l, learned by the network.
Parameters
----------
v_d : float
location of the default box, either v_x or v_y
l : float
scaled offset value as computed by ... |
def remainder(x, y):
"""Difference between x and the closest integer multiple of y.
Return x - n*y where n*y is the closest integer multiple of y.
In the case where x is exactly halfway between two multiples of
y, the nearest even value of n is used. The result is always exact."""
from math import... |
def sanitize_branch_name_for_rpm(branch_name: str) -> str:
"""
rpm is picky about release: hates "/" - it's an error
also prints a warning for "-"
"""
offenders = "!@#$%^&*()+={[}]|\\'\":;<,>/?~`"
for o in offenders:
branch_name = branch_name.replace(o, "")
return branch_name.replace... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.