content stringlengths 42 6.51k |
|---|
def logical_rshift(val: int, n: int):
"""Solution by NPE
https://stackoverflow.com/a/5833119
Parameters
----------
val : int
Integer to be right logical shifted
n : int
Number of bits to shift by
Returns
-------
int
Right logically shifted number
... |
def contains_class(class_list, class_match):
""" Determines if the class_match is in the class_list.
Not sure why I didn't just say class_match in class_list but
think that for some reason the BeautifulSoup list didn't support
that or there was somethign else wrong.
:param class_list: A list of HTM... |
def judge_if_legal(s):
"""
:param s: str
:return: True or False
"""
if s.isalpha():
if len(s) == 1:
return True
else:
return False |
def get_args(tp):
"""
Simplified getting of type arguments. Should be replaced with typing.get_args from Python >= 3.8
"""
if hasattr(tp, '__args__'):
return tp.__args__
return () |
def int_to_mode(mode):
"""Returns the string representation in VPP of a given bondethernet mode,
or "" if 'mode' is not a valid id.
See src/vnet/bonding/bond.api and schema.yaml for valid pairs."""
ret = {1: "round-robin", 2: "active-backup", 3: "xor", 4: "broadcast", 5: "lacp"}
try:
retur... |
def convert_to_camel(data):
"""
Convert snake case (foo_bar_bat) to camel case (fooBarBat).
This is not pythonic, but needed for certain situations
"""
components = data.split('_')
return components[0] + "".join(x.title() for x in components[1:]) |
def italic(content):
"""Corresponds to ``*content*`` in the markup.
:param content: HTML that will go inside the tags.
>>> 'i would ' + italic('really') + ' like to see that'
'i would <i>really</i> like to see that'
"""
return '<i>' + content + '</i>' |
def loop_struct_has_non_simd_loop(loop_struct, config):
"""Examine if the leaf node of the loop struct has any non-SIMD loop."""
if "loop" in loop_struct:
if config["under_simd"] == 1:
return 0
else:
return 1
elif "mark" in loop_struct:
mark = loop_struct["mar... |
def zero_correct(dim_over, dim_detc):
"""
This short function calculates the correction for the change
in the location of the origin pixel (the very first, or "0"),
which is applied to the calculation of centroid computed for
a grid that has been downsampled.
"""
factor = dim_over / ... |
def _mul_inv(a, b):
"""Source: https://rosettacode.org/wiki/Chinese_remainder_theorem#Python"""
b0 = b
x0, x1 = 0, 1
if b == 1:
return 1
while a > 1:
q = a // b
a, b = b, a % b
x0, x1 = x1 - q * x0, x0
if x1 < 0:
x1 += b0
return x1 |
def add_kwds(dictionary, key, value):
"""
A simple helper function to initialize our dictionary if it is None and then add in a single keyword if
the value is not None.
It doesn't add any keywords at all if passed value==None.
Parameters
----------
dictionary: dict (or None)
A dictio... |
def dictmask(data, mask, missing_keep=False):
"""dictmask masks dictionary data based on mask"""
if not isinstance(data, dict):
raise ValueError("First argument with data should be dictionary")
if not isinstance(mask, dict):
raise ValueError("Second argument with mask should be dictionary")... |
def get_decade(start_year, end_year):
"""divide the time legnth into decades, return list of 10 years each"""
import numpy as np
all_years = np.arange(int(start_year), int(end_year) + 1)
yr_chunks = [all_years[x: x+10] for x in range(0, len(all_years), 10)]
return yr_chunks |
def parseValue(formatString):
"""Returns the value type of data item from MXElectrix data message.
The value type is taken to be everything before opening bracket [."""
sep = formatString.find("[")
if sep < 0:
return ""
else:
return formatString[:sep] |
def longest_common_substring(s1, s2):
"""Returns longest common substring of two input strings.
see https://en.wikipedia.org/wiki/Longest_common_substring_problem
and https://en.wikibooks.org/wiki/Algorithm_implementation/Strings/Longest_common_substring#Python_3
"""
m = [[0] * (1 + len(s2)) for i ... |
def valid_verify(pwd1, pwd2):
""" verify if both passwords given match each other """
if pwd1 != pwd2:
return "Your passwords didn't match." |
def parse_entity(entity, filter_none=False):
"""
Function creates a dict of object attributes.
Args:
entity (object): object to extract attributes from.
Returns:
result (dict): a dictionary of attributes from the function input.
"""
result = {}
attributes = [attr for attr i... |
def _str_to_list(str_or_list):
"""return a `list` in either case"""
if isinstance(str_or_list, (tuple, list, set)):
return str_or_list
if str(str_or_list) == str_or_list:
return [str_or_list]
raise ValueError(str_or_list) |
def wrap(x, m, M):
"""
Rotate x to fit in range (m, M).
Useful while dealing with angles.
Parameters
----------
x : float
Value.
m : float
Lower bound.
M : float
Upper bound.
"""
diff = M - m
while x > M:
x = x - diff
while x < m:
... |
def signature(t):
"""
Given an Elm type signatue of form:
name : a -> b
or similar, return the 'a -> b' part
Also gets the constructors of a data declaration or the type of an alias
Only works on single-line declarations
"""
if t.startswith('type '):
return t[5:].split(' = '... |
def isNumber(variable):
"""
Returns True if varible is is a number
"""
try:
float(variable)
except TypeError:
return False
return True |
def _transpose_to_columnar(raw_data):
"""Groups the same data together by key.
BEFORE:
[
{ 'product': 'apple', 'price': 10.0 },
{ 'product': 'banana', 'price': 5.0 }
]
AFTER:
{
'product': ['apple', 'banana'],
'price': [10.0, 5.0],
... |
def _ParsePlusMinusList(value):
"""Parse a string containing a series of plus/minuse values.
Strings are seprated by whitespace, comma and/or semi-colon.
Example:
value = "one +two -three"
plus = ['one', 'two']
minus = ['three']
Args:
value: string containing unparsed plus minus values.
Re... |
def add_neighbours(pseudo_ids, pseudo_imgs, mosaic_mode, mosaic, img, id):
""" Takes a batch (N, 101, 101, 3) and list of id's. Adds mosaic data."""
if mosaic_mode not in [1, 2]:
return img
img[:, :, mosaic_mode] = 0.5
name = id[:-4]
# mask_names = ["left", "top", "right", "bottom"]
ma... |
def chi_par(x, A, x0, C):
"""
Parabola for fitting to chisq curve.
"""
return A*(x - x0)**2 + C |
def split_docstring(doc):
"""Split docstring into first line (header) and full body."""
return (doc.split("\n", 1)[0], doc) if doc is not None else ("", "") |
def poly_integral(poly, C=0):
"""Return an list of the integrated polynomial"""
if (not isinstance(poly, list) or
len(poly) == 0 or
not all(isinstance(x, (int, float)) for x in poly) or
not isinstance(C, (int, float))):
return None
ans = [C]
for i in range(len(poly))... |
def _vpres(T):
""" Polynomial approximation of saturated water vapour pressure as
a function of temperature.
Parameters
----------
T : float
Ambient temperature, in Kelvin
Returns
-------
float
Saturated water vapor pressure expressed in mb
See Also
--------
... |
def safe_cast(invar, totype):
"""Performs a "safe" typecast.
Ensures that `invar` properly casts to `totype`. Checks after
casting that the result is actually of type `totype`. Any exceptions raised
by the typecast itself are unhandled.
Parameters
----------
invar
(arbitrary) -- Va... |
def is_variable(expr):
"""
Check if expression is variable
"""
for i in expr:
if i == '(':
return False
return True |
def readlines(fil=None,raw=False):
"""
Read in all lines of a file.
Parameters
----------
file : str
The name of the file to load.
raw : bool, optional, default is false
Do not trim \n off the ends of the lines.
Returns
-------
lines : list
The list ... |
def bubbleSort(array):
"""
input: array
return: sorted array of integers
"""
n = len(array)
for i in range(n):
for j in range(n - i - 1):
if array[j] > array[j + 1]:
array[j], array[j + 1] = array[j + 1], array[j]
return array |
def _created_on_to_timestamp_ms(created_on):
"""
Converts the Message CreatedOn column to a millisecond timestamp value.
CreatedOn is number of 100 nanosecond increments since midnight 0000-01-01.
Output is number of millisecond increments since midnight 1970-01-01.
"""
return created_on / 1000... |
def doi_filter_list(doi_list, params):
""" influx helper adding a doi filter list (faster than array check in influx) """
if doi_list:
filter_string = """
|> filter(fn: (r) => """
i = 0
for doi in doi_list:
filter_string += 'r["doi"] == _doi_nr_' + str(i) + ' ... |
def list_copy(seq_list):
"""copy all the seqs in the list"""
return [s.copy() for s in seq_list] |
def blink(s):
"""Return blinking string."""
return "\033[5;40m{}\033[25m".format(s) |
def _str_eval_first(eval, act, ctxt, x) :
"""Returns the first element of the argument."""
return [x[0]] |
def get_overlapping_arcodes(action_replay_list:list):
"""
input: action_replay_list = [ActionReplayCode, ...]
return [(ActionReplayCode, ActionReplayCode), ...] else None
Get overlapping action replay code in memory. Return couples of arcodes that patch sames memory addresses.
"""
if len(action_... |
def get_formatted_size_MB( totsizeMB ):
"""
Same as :py:meth:`get_formatted_size <howdy.core.get_formatted_size>`, except this operates on file sizes in units of megabytes rather than bytes.
:param int totsizeMB: size of the file in megabytes.
:returns: Formatted representation of that file size.
... |
def to_cartesian(algebraic):
"""Convert algebraic to cartesian
Parameters
----------
algebraic: str
Algebraic coordinate
Returns
-------
tuple
Cartesian coordinate
"""
mapper = {
'A': 1,
'B': 2,
'C': 3,
'D': 4,
'E': 5,
... |
def get_user_id(user_id: str) -> str:
"""
Formats the user_id to a plain format removing any <, < or @
:param user_id: slack id format
:type user_id: str
:return: plain user id
:rtype: str
"""
return user_id.strip("<>@") |
def average_accuracy(outputs, targets, k=10):
"""
Computes the average accuracy at k.
This function computes the average
accuracy at k between two lists of items.
Args:
outputs (list): A list of predicted elements
targets (list): A list of elements that are to be predicted
... |
def is_sysem(title_text: str, description_text: str, requirements_text: str) -> bool:
"""
Indicate if a course is a sophomore seminar.
Parameters
----------
title_text:
Extracted title text from course JSON.
description_text:
Extracted description text from extract_course_info()... |
def first_relationship_that_matches(end_def, end_def_type, end_def_name, relationship_typedefs):
"""
Find the first relationship type that matches the end_def number, type
and name from the provided typedefs.
:param str end_def: Either 'endDef1' or 'endDef2'
:param str end_def_type: The type within... |
def format_funcline(name, mem_usage):
"""Create the output string for a function profile interval."""
start_memory, start_timestamp = mem_usage[0]
end_memory, end_timestamp = mem_usage[-1]
return "FUNC {name} {0:.6f} {1:.4f} {2:.6f} {3:.4f}\n".format(
start_memory,
start_timestamp,
... |
def list_to_string(list, separator = "\t"):
"""
Converts a list of values to a string using SEPARATOR for joints
Args:
list: a list of values to be converted to a string
separator: a separator to be used for joints
Returns:
a string
"""
return separator.join(map(str,... |
def SymbolicConstant(in_str) -> str:
"""
:param in_str:
:return:
"""
# type: "(str) -> str"
in_str = in_str
return in_str |
def comma_space(s):
"""
insert a space after every comma in s unless s ends in a comma
:param s: string to be checked for spaces after commas
:return s: improved string with commas always followed by spaces
:rtype: basestring
"""
k = s.find(',')
if -1 < k < len(s) - 1 and s[k + 1] != " "... |
def options_string_builder(option_mapping, args):
"""Return arguments for CLI invocation of kal."""
options_string = ""
for option, flag in option_mapping.items():
if option in args:
options_string += str(" %s %s" % (flag, str(args[option])))
return options_string |
def DecodeFileRecordSegmentReference(ReferenceNumber):
"""Decode a file record segment reference, return the (file_record_segment_number, sequence_number) tuple."""
file_record_segment_number = ReferenceNumber & 0xFFFFFFFFFFFF
sequence_number = ReferenceNumber >> 48
return (file_record_segment_number,... |
def electrode_distance(latlong_a, latlong_b, radius=100.0):
"""
geodesic (great-circle) distance between two electrodes, A and B
:param latlong_a: spherical coordinates of electrode A
:param latlong_b: spherical coordinates of electrode B
:return: distance
"""
import math
lat1, lon1 = l... |
def descendingOrderCheck(_ordered_list):
"""
Check whether the input list is ordered descending.
:param _ordered_list: The input list that is ordered by descending order
:return: returns true if order of _ordered_list is descending else returns false.
"""
re... |
def vessel_tip_coupling_data_to_str(data_list):
"""A list of vessel tip data elements is converted into a string."""
s = []
for v in data_list:
s.append('VesselTipData(')
s.append(' p = Point(x={}, y={}, z={}),'.format(v.p.x, v.p.y, v.p.z))
s.append(' vertex_id = {},'.format(v.vert... |
def convert_mw_gwh(megawatt, number_of_hours):
""""Conversion of MW to GWh
Input
-----
kwh : float
Kilowatthours
number_of_hours : float
Number of hours
Return
------
gwh : float
Gigawatthours
"""
# Convert MW to MWh
megawatt_hour = megawatt * numbe... |
def unique_activities_from_log(log, name_of_activity):
"""
Returns unique activities from event log.
:param name_of_activity: name of activity.
:param log: event log.
:return: unique activities.
"""
unique_activities = []
for sequence in log:
for activity in sequence:
... |
def kochanekBartelsInterpolator(v0, v1, v2, v3, alpha, tension, continuity, bias):
"""
Kochanek-Bartels interpolator. Allows even better control of the bends in the spline by providing three
parameters to adjust them:
* tension: 1 for high tension, 0 for normal tension and -1 for low tension.
*... |
def read_flash(filename):
"""
Read dataset from FLASH output file
Parameters
----------
filename : string containing file name
Returns
-------
data_attributes : dictionary containing data attributes
block_attributes : dictionary containg block attributes
"""
data_attribut... |
def pyext_coms(platform):
"""Return PYEXTCCCOM, PYEXTCXXCOM and PYEXTLINKCOM for the given
platform."""
if platform == 'win32':
pyext_cccom = "$PYEXTCC /Fo$TARGET /c $PYEXTCCSHARED "\
"$PYEXTCFLAGS $PYEXTCCFLAGS $_CCCOMCOM "\
"$_PYEXTCPPINCFLAGS $SOURCES"
... |
def static_file(file_path):
"""
[This function will help in serving a static_file]
:param file_path [str]: [file path to serve as a response]
"""
return {
"response_type": "static_file",
"file_path": file_path
} |
def countinclude(data, s="sam"):
"""Count how many words occur in a list up to and including the first
occurrence of the word "sam"."""
count = 0
for i in data:
count += 1
if i == s:
break
return count |
def tau(values):
"""
Calculates the Tau value for a list of expression values
:param dist: list of values
:return: tau value
"""
n = len(values) # number of values
mxi = max(values) # max value
if mxi > 0:
t = sum([1 - (x/mxi) for x in values])... |
def checksumStr(data):
"""
Take a NMEA 0183 string and compute the checksum.
@param data: NMEA message. Leading ?/! and training checksum are optional
@type data: str
@return: hexidecimal value
@rtype: str
Checksum is calculated by xor'ing everything between ? or ! and the *
>>> check... |
def _config_for_dimensions(pool_cfg, dimensions_flat):
"""Determines the external scheduler for pool config and dimension set.
Pool's dimensions are matched with each config from top to down. The
last config in the file should be the default one.
"""
if not pool_cfg or not pool_cfg.external_schedulers:
r... |
def make_summary(serialized_data):
"""
Take in a full serialized object, and return dict containing just
the id and the name
Parameter: serialized_data, dict, or list of dicts
Returns: dict, or list of dicts, containing just "name" and "id" key/values.
"""
def summarize_one(data):
... |
def is_arg(args, options):
"""Check if an option is already in the argument list."""
return any(option in args for option in options) |
def read_paragraph_element(element):
"""Returns the text in the given ParagraphElement.
Args:
element: a ParagraphElement from a Google Doc.
"""
text_run = element.get('textRun')
if not text_run:
return ''
return text_run.get('content') |
def api_key_auth(key, required_scopes=None):
"""
Function pointed to by x-apikeyInfoFunc in the swagger security definitions.
"""
if key is not None:
# Pretty much a null implementation.
return {'sub': 'unknown'}
else:
return None |
def get_bool(value: str) -> bool:
"""Get boolean from string."""
if value.upper() in ["1", "T", "TRUE"]:
return True
if value.upper() in ["0", "F", "FALSE"]:
return False
raise ValueError(f"Unable to convert {value} to boolean.") |
def r_to_z(r, a=200., b=1.6):
"""Calculates reflectivity from rain rates using
a power law Z/R relationship Z = a*R**b
Parameters
----------
r : a float or an array of floats
Corresponds to rainfall intensity in mm/h
a : float
Parameter a of the Z/R relationship
... |
def __get_midi_csv(midi_strings):
"""split comma seperated strings into csv file
Arguments:
midi_strings {list} -- list of comma separated strings
Returns:
csv -- midi data in csv format
"""
midi_csv = []
for row in midi_strings:
midi_data = row.split(",")
midi_cs... |
def format_time_str(parse_time) -> str:
"""
Format execution time to be printed out
:param parse_time: Timespan.
:return: Formated string.
"""
hours = int(parse_time / 3600)
minutes = int((parse_time - hours * 3600) / 60)
seconds = int(parse_time % 60)
millis = ... |
def quaternion_canonize(q):
"""Converts a quaternion into a canonic form if needed.
Parameters
----------
q : list
Quaternion as a list of four real values ``[w, x, y, z]``.
Returns
-------
list
Quaternion in a canonic form as a list of four real values ``[cw, cx, cy, cz]``... |
def part2(adapters):
""" Find all possible combination of adapters """
adapters.sort()
adapters.insert(0, 0) # add 0 at start for the wall jolt
adapters.append(max(adapters) + 3) # adding phone's inbuilt adapter
# memoize already visisted node
visited = dict()
def repeat(i):
if i... |
def solution1(rooms):
"""
Solution 1
---
:type rooms: list[list[int]]
:rtype: bool
"""
visited = {0}
def dfs(i):
for key in rooms[i]:
if key not in visited:
visited.add(key)
dfs(key)
dfs(0)
return len(visited) == len(rooms) |
def _get_image_url(photo_item, size_flag=''):
"""
size_flag: string ['']
See http://www.flickr.com/services/api/misc.urls.html for options.
'': 500 px on longest side
'_m': 240px on longest side
"""
url = "http://farm{farm}.staticflickr.com/{server}/{id}_{secret}{size}.jp... |
def get_GiB(x: int):
"""return x GiB."""
return x * (1 << 30) |
def calc_time_cost_function(natom, nkpt, kmax, nspins=1):
"""Estimates the cost of simulating a single iteration of a system"""
costs = natom**3 * kmax**3 * nkpt * nspins
return costs |
def get_rank(scores):
"""
Returns list of (index, value) of scores, sorted by decreasing order.
The order is randomized in case of tie thanks to the key_tie_break function.
"""
return sorted(enumerate(scores), key=lambda t: t[1], reverse=True) |
def pl_winp(a, b):
"""Win probability of player a over b given their PL ratings."""
return a / (a + b) |
def eqn_list_to_dict(eqn_list, reverse=None):
"""Convert a list of Sympy Relational objects to a dictionary.
Most commonly, this will be for converting things like:
[y == a*x + b, z == c*x + d]
to a Python dictionary object with keys corresponding to the left hand side
of the relational objects a... |
def string_to_list(string_in):
""" Converts a string to a list """
list_out = []
for ch in string_in:
list_out.append(ch)
return list_out |
def get_time_in_min(timestamp):
"""
Takes a timestamp, for example 12:00 and splits it, then converts it into minutes.
"""
hours, minutes = timestamp.split(":")
total_minutes = int(hours)*60+int(minutes)
return total_minutes |
def get_block(i, k, T, B):
"""
Get's the ith block of 2^T // B, such that sum(get_block(i) * 2^ki) =
t^T // B
"""
return (pow(2, k) * pow(2, T - k * (i + 1), B)) // B |
def extract_tag(inventory, url):
"""
extract data from sphinx inventory.
The extracted datas come from a C++ project
documented using Breathe. The structure of the inventory
is a dictionary with the following keys
- cpp:class (class names)
- cpp:function (functions or class methods)... |
def format_line_protocol(measurement: str,field: dict,tags: dict={}) -> str:
"""Converts input into influxDB line protocol format.
Args:
measurement (str): This is the overarching "thing" you're monitoring.
field (dict): This is the metric you're collecting for the "thing."
tags (dict, ... |
def parse_spotify_url(url):
"""
Parse the provided Spotify playlist URL and determine if it is a playlist, track or album.
:param url: URL to be parsed
:return tuple indicating the type and id of the item
"""
parsed_url = url.replace("https://open.spotify.com/", "")
item_type = parsed_url.sp... |
def clamp(num):
"""
Return a "clamped" version of the given num,
converted to be an int limited to the range 0..255 for 1 byte.
"""
num = int(num)
if num < 0:
return 0
if num >= 256:
return 255
return num |
def is_terminal(node):
"""Whether a node in primitive tree is terminal.
Args:
node: String, deap.gp.Primitive or deap.gp.Terminal.
Returns:
Boolean.
"""
return isinstance(node, str) or node.arity == 0 |
def parse_csv(columns, line):
"""
Parse a CSV line that has ',' as a separator.
Columns is a list of the column names, must match the number of
comma-separated values in the input line.
"""
data = {}
split = line.split(',')
for idx, name in enumerate(columns):
data[name] = split[... |
def _get_zip_urls(year):
"""Return urls for zip files based on pattern.
Parameters
----------
year : string
4 digit year in string format 'YYYY'.
Returns
-------
dict
"""
suffix = f'oesm{year[2:]}'
code = 4
return {
'national': f'https://www.bls.gov/oes/sp... |
def value_or(value, default):
"""Return Value or Default if Value is None."""
return value if value is not None else default |
def safe_int(string):
""" Utility function to convert python objects to integer values without throwing an exception """
try:
return int(string)
except ValueError:
return None |
def descending_order(num):
"""
Your task is to make a function that can take any non-negative integer as a argument and return it with its digits
in descending order. Essentially, rearrange the digits to create the highest possible number.
:param num: an positive integer.
:return: the integers digit... |
def specified_or_guess(attributes):
"""Without identifier guess the elements to be removed based on markup.
:param attributes: an attribute pair of key and value
"""
if attributes:
return '{}="[^>]*?{}[^>]*?"'.format(*list(attributes.items())[0])
return '' |
def rchop(original_string, substring):
"""Return the given string after chopping of a substring from the end.
:param original_string: the original string
:param substring: the substring to chop from the end
"""
if original_string.endswith(substring):
return original_string[:-len(substring)]... |
def multiply(*args):
"""Returns the multiplication result of random amount of numbers given"""
if not args:
return None
product = 1
for x in args:
product *= x
return product |
def stringify(in_fields, formats):
"""
Arguments:
in_fields -- list of lists to stringify
formats -- list of correspoding formats
"""
olist = []
for entry in in_fields:
new_val = []
for indx, part in enumerate(entry):
if indx >= len(formats):
... |
def convert_to_letters(num):
"""Converts number to string of capital letters in Excel column name
fashion, i.e. 1 -> A, 26 -> Z, 27 -> AA ...."""
string_equiv = ""
while num > 0:
currNum = (num - 1) % 26
num = (num - 1) // 26
string_equiv = chr(currNum + ord("A")) + string_equiv... |
def preprocess_word(word):
"""standardize word form for the alignment task"""
return word.strip().lower() |
def snake_case_to_kebab_case(s):
"""Util method to convert kebab-case fieldnames to snake_case."""
return s.replace("_", "-") |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.