content stringlengths 42 6.51k |
|---|
def get_media_resource_image_path(_, file):
"""
Get the path that a media resource's image should be uploaded to.
Args:
_:
The media resource the image belongs to.
file:
The original name of the file being uploaded.
Returns:
The path that the media resou... |
def calc_overlap3(set_pred, set_gt):
"""
Calculates if the overlap between prediction and
ground truth is enough fora potential True positive
"""
# Length of each and intersection
try:
len_gt = len(set_gt)
len_pred = len(set_pred)
inter = len(set_gt & set_pred)
ov... |
def collision_checker(obstacle_map: list, dx: int, dy: int, verbose: bool) -> int:
""" Lool for tree collisions along the specified path, return the number of collisions
Inputs:
obstacle_map: list - The grid map of obstacles:
'.' represents a clear space
'#' r... |
def jarManifest(target, source, env, for_signature):
"""Look in sources for a manifest file, if any."""
for src in source:
contents = src.get_text_contents()
if contents.startswith("Manifest-Version"):
return src
return '' |
def zigzag(n):
"""
Produce a list of indexes that traverse a matrix of size n * n using the JPEG zig-zag order.
Taken from https://rosettacode.org/wiki/Zig-zag_matrix#Alternative_version.2C_Translation_of:_Common_Lisp
:param n: size of square matrix to iterate over
:return: list of indexes in t... |
def base_integer(val, base=2):
"""Convert base n val as integer to integer."""
assert isinstance(val, str), 'val must be str'
return float(int(val, base)) |
def date_and_notes(s):
"""Parse (birth|death) date and notes; returns a tuple in the
form (date, notes)."""
s = s.strip()
if not s: return (u'', u'')
notes = u''
if s[0].isdigit() or s.split()[0].lower() in ('c.', 'january', 'february',
'march', 'a... |
def samples_to_tensors(paths):
"""Return processed sample data based on the collected paths.
Args:
paths (list[dict]): A list of collected paths.
Returns:
dict: Processed sample data, with keys
* undiscounted_returns (list[float])
* success_history (list[float])
... |
def compose_update(table, fields):
"""Compose update query string for migrated table.
Arguments
---------
table : str
Real table name.
fields : str
List of table fields.
Returns
-------
str
Query string with real table name. However, it can contain placeholders
... |
def in_list(item,List):
"""
Report True if item is in list
"""
try:
i = List.index(item)
return True
except ValueError:
return False |
def parse_res_to_dict(response):
"""
Checks if response is a list.
If it is list, converts it to an object with an 'items' field
that has the list as value. Finally, returns the object
Otherwise, returns response
"""
if type(response) is list:
return { "items": response }
els... |
def format_dollar(value: float) -> str:
"""
Return a proper 2 decimal currency value
:param value: Currency amount
:return: currency value string
"""
return f"{value:0.2f}" |
def average_particle_energy(integrated_energy_flux,integrated_number_flux):
"""Calculate the average particle energy (eV) for output from above function
(only valid if same channel set used for energy and number flux)"""
#Calculate average energy in electron-volts
eavg = (integrated_energy_flux/1.6e-19... |
def print_demon(demon_dict):
"""This will print text describing a new demon"""
output = f"""
Tremble at the sight of {demon_dict["name"].capitalize()}!
Behold, {demon_dict["feature_1"].lower()} and {demon_dict["feature_2"].lower()}.
This {demon_dict["affinity"].lower()} demon has a {demon_dict["aspect"].lower()... |
def _GetSupportedApiVersions(versions, runtime):
"""Returns the runtime-specific or general list of supported runtimes.
The provided 'versions' dict contains a field called 'api_versions'
which is the list of default versions supported. This dict may also
contain a 'supported_api_versions' dict which lists ap... |
def get_service(service):
"""
Get the service name.
If the product attribute it set then use it otherwise use the name
attribute.
"""
if service is None:
name = ''
banner = ''
else:
name = service.attrib.get('product', None)
if name is None:
name... |
def get_column_letter(column_index):
"""
Returns the spreadsheet column letter that corresponds to a given index (e.g.: 0 -> 'A', 3 -> 'D')
Args:
column_index (int):
Returns:
str: The column index expressed as a letter
"""
if column_index > 25:
raise ValueError("Cannot ... |
def getPeriodWinner(homescore, awayscore):
"""
Function to determine periodwinner
"""
if (homescore==awayscore):
return 'draw'
elif (homescore>awayscore):
return 'home'
elif (homescore<awayscore):
return 'away'
else:
return None |
def checkDifferences(new, old):
""" Check the old and new CRC dicts to see if there's been an update
Parameters
new : dict
The most recent CRC openings
old : dict
The previous CRC openings
Returns
CRCUpdates : str
The formatted string in Markdown
"""
CRCUpda... |
def check_device(device):
"""
This function is called to check if a device id is valid.
"""
uuid = device.get('Device-Id')
if not uuid:
return False
return True |
def dot(vec1, vec2):
""" Return the dot product of vec1 and vec2 """
return vec1[0]*vec2[0] + vec1[1]*vec2[1] |
def isWordGuessed(secretWord: str, lettersGuessed: list) -> bool:
"""
secretWord: the word the user is guessing.
lettersGuessed: letters that have been guessed so far
returns: True if all the letters of secretWord are in
lettersGuessed; False otherwise.
"""
return set(lettersGuessed).issup... |
def parse_slice(value):
"""
Parses a `slice()` from string, like `start:stop:step`.
"""
if value:
parts = value.split(':')
if len(parts) == 1:
# slice(stop)
parts = [None, parts[0]]
# else: slice(start, stop[, step])
else:
# slice()
par... |
def get_allowed_tokens_from_config(config, module='main'):
"""Return a list of allowed auth tokens from the application config"""
env_variable_name = 'DM_API_AUTH_TOKENS'
if module == 'callbacks':
env_variable_name = 'DM_API_CALLBACK_AUTH_TOKENS'
return [token for token in config.get(env_varia... |
def _avg_bright(colour):
"""Returns avg brightness of three colours
written by anthony luo
"""
r, g, b = colour
return (r + g + b) / 3 |
def get_config_value(config_dict, key, default=None):
"""Get configuration value or default value from dictionary.
Usable for dictionaries which can also contain attribute 'default'
Order of preference:
* attribute value
* value of 'default' attribute
* value of provided default param
"""
... |
def julian_day(year, month=1, day=1, julian_before=None):
"""Given a calendar date, return a Julian day integer.
Uses the proleptic Gregorian calendar unless ``julian_before`` is
set to a specific Julian day, in which case the Julian calendar is
used for dates older than that.
"""
# Support mo... |
def _xbm(h):
"""X bitmap (X10 or X11)"""
if h.startswith(b'#define '):
return 'xbm' |
def envs_to_exports(envs):
"""
:return: line with exports env variables: export A=B; export C=D;
"""
exports = ["export %s=%s" % (key, envs[key]) for key in envs]
return "; ".join(exports) + ";" |
def zendesk_ticket_url(zendesk_ticket_uri, ticket_id):
"""Return the link that can be stored in zendesk.
This handles the trailing slach being present or not.
"""
# handle trailing slash being there or not (urljoin doesn't).
return '/'.join([zendesk_ticket_uri.rstrip('/'), str(ticket_id)]) |
def CtoFtoC_Conversion(inputTemp, outputTempType, isReturn):
"""This method converts to Celsius if given a Farhaniet and vice versa.
inputTemp = The input temperature value.
outputTempType = Type of output temperature required.
isReturn = Whether output is required in return."""
if outputTe... |
def three_loops(array: list) -> int:
"""
Uses three loops to get the max sum subarray
"""
lenght = len(array)
max_sum = array[0]
for start in range(lenght):
for end in range(start, lenght):
current_sum = sum(array[start : end + 1])
if current_sum > max_sum:
... |
def get_setting_name_and_refid(node):
"""Extract setting name from directive index node"""
entry_type, info, refid = node['entries'][0][:3]
return info.replace('; setting', ''), refid |
def find_first_feature(tree):
"""Finds the first feature in a tree, we then use this in the split condition
It doesn't matter which feature we use, as both of the leaves will add the same value
Parameters
----------
tree : dict
parsed model
"""
if 'split' in t... |
def generate_thumbnail_html(path_to_thumbnail):
"""Generates HTML code for image thumbnail."""
return '<img src="{}">'.format(
path_to_thumbnail
) |
def _priority_key(pep8_result):
"""Key for sorting PEP8 results.
Global fixes should be done first. This is important for things like
indentation.
"""
priority = [
# Fix multiline colon-based before semicolon based.
'e701',
# Break multiline statements early.
'e702'... |
def end_game(_game):
"""
Will show a end game screen and thank the player.
Args:
_game: Current game state
Returns: Returns false to end game loop
"""
print("Thank you for playing")
return False |
def clean_id(post_id: str) -> str:
"""
Fixes the Reddit ID so that it can be used to get a new object.
By default, the Reddit ID is prefixed with something like `t1_` or
`t3_`, but this doesn't always work for getting a new object. This
method removes those prefixes and returns the rest.
:para... |
def dot2d(v0, v1):
"""Dot product for 2D vectors."""
return v0[0] * v1[0] + v0[1] * v1[1] |
def get_error_messages(data):
"""
Get messages (ErrorCode) from Response.
:param data: dict of datas
:return list: Empty list or list of errors
"""
error_messages = []
for ret in data.get("responses", [data]):
if "errorCode" in ret:
error_messages.append(
... |
def func_guard(input_str, chars_to_replace=['*', '/']):
"""
Return a string with chars illegal in variable names replaced.
:param str input_str: string to be replaced.
:param list chars_to_replace: list of illegal chars.
"""
for c in chars_to_replace:
input_str = input_str.replace(c, '_... |
def calculate_nfft(samplerate, winlen):
"""Calculates the FFT size as a power of two greater than or equal to
the number of samples in a single window length.
Having an FFT less than the window length loses precision by dropping
many of the samples; a longer FFT than the window allows zero-padding... |
def unescape_tabs_newlines(s: str) -> str:
"""
Reverses :func:`escape_tabs_newlines`.
See also https://stackoverflow.com/questions/4020539.
"""
if not s:
return s
d = "" # the destination string
in_escape = False
for i in range(len(s)):
c = s[i] # the character being p... |
def isServerAvailable(serverName):
"""Checks to see if the specified OPC-HDA server is defined,
enabled, and connected.
Args:
serverName (str): The name of the OPC-HDA server to check.
Returns:
bool: Will be True if the server is available and can be
queried, False if not.
... |
def bubble_sort_optimized(container = []):
"""
Bubble sort with second optimization.
Description
----------
From wikipedia: This allows us to skip over a lot of the elements,
resulting in about a worst case 50% improvement in comparison count.
Performance cases:
... |
def rotmap(start):
"""
dict[char,char]: Map chars (from start to start+26) to rotated characters.
"""
ints = range(start,start+26)
rots = (
start+i%26 for i in range( 13, 13 +26)
)
return dict( zip( map( chr,ints ),map( chr,rots ) ) ) |
def get_pipeline_version(pipeline_version):
"""pipeline version
"""
if pipeline_version:
return pipeline_version
else:
return "current" |
def awesome_streamlit_hack(filename: str) -> str:
"""We need this when running this file via the 'exec' statement as a part of the
awesome-streamlit.org gallery"""
if filename == "<string>":
return "gallery/notebook_style/notebook_style.py"
return filename |
def relative(tag):
"""
A shortcut method for accessing the namespace of the
XML file; Python 2.7 or later implements
xml.etree.ElementTree.register_namespace(prefix, uri)
for this task.
"""
return r"""{http://purl.org/atom/ns#}%s""" % tag |
def _IsInstanceRunning(instance_info):
"""Determine whether an instance is running.
An instance is running if it is in the following Xen states:
running, blocked, paused, or dying (about to be destroyed / shutdown).
For some strange reason, Xen once printed 'rb----' which does not make any
sense because an ... |
def inverse_gamma_sRGB(ic):
"""Inverse of sRGB gamma function. (approx 2.2)"""
c = ic/255.0
if ( c <= 0.04045 ):
return c/12.92
else:
return pow(((c+0.055)/(1.055)),2.4) |
def nulls(x):
"""
Convert values of -1 into None.
Parameters
----------
x : float or int
Value to convert
Returns
-------
val : [x, None]
"""
if x == -1:
return None
else:
return x |
def document_contains_text(docbody):
"""Test whether document contains text, or is just full of worthless
whitespace.
@param docbody: (list) of strings - each string being a line of the
document's body
@return: (integer) 1 if non-whitespace found in document; 0 if only
whitespac... |
def extension_supported(extension_name, extensions):
"""Determine if nova supports a given extension name.
Example values for the extension_name include AdminActions, ConsoleOutput,
etc.
"""
for extension in extensions:
if extension.name == extension_name:
return True
return... |
def get_input_shapes_map(input_tensors):
"""Gets a map of input names to shapes.
Args:
input_tensors: List of input tensor tuples `(name, shape, type)`.
Returns:
{string : list of integers}.
"""
input_arrays = [tensor[0] for tensor in input_tensors]
input_shapes_list = []
for _, shape, _ in inp... |
def generateNums(function, lower, upper):
"""Apply function to 1-... generating a list of elements within
'lower' and 'upper' limits (inclusive)."""
print("Generating list for function " + function.__name__)
numList = []
i = 0
num = 0
while num <= upper:
num = function(i)
... |
def double_quote(text):
"""double-quotes a text"""
return '"{}"'.format(text) |
def text_from_file(file):
"""
If the 'file' parameter is a file-like object, return its contents as a
string. Otherwise, return the string form of 'file'.
"""
try:
s = file.read()
return s
except AttributeError:
return str(file) |
def get_device_mapping(gpu_id):
"""
Reload models to the associated device.
Reload models to the associated device.
"""
origins = ['cpu'] + ['cuda:%i' % i for i in range(8)]
target = 'cpu' if gpu_id < 0 else 'cuda:%i' % gpu_id
return {k: target for k in origins} |
def tabla(letras):
"""Funcion que se encarga de crear la tabla de codificacion"""
mensaje_cifrado = []
banco = {"F": 'A', "G": 'B', "H": 'C', "I": 'D', "J": 'D', "K": 'E', "L": 'A', "M": 'B', "N": 'C',
"O": 'D', "P": 'E', "Q": 'A', "R": 'B', "S": 'C', "T": 'D', "U": 'E', "V": 'A', "W": 'B',
... |
def convert_bytes(num):
""" This function will convert bytes to MB, GB """
for x in ['bytes', 'KB', 'MB', 'GB', 'TB']:
if num < 1024.0:
return "%3.1f %s" % (num, x)
num /= 1024.0 |
def list_restack(stack, index=0):
"""Returns the element at index after moving it to the top of stack.
>>> x = [1, 2, 3, 4]
>>> list_restack(x)
1
>>> x
[2, 3, 4, 1]
"""
x = stack.pop(index)
stack.append(x)
return x |
def momentOfInertia(m_r_touple_list):
"""
Sample Input [(mass1, radius1), ..., (mass2, radius2)]
Variables:
mass = mass
radius = perpendicular distance from axis of rotation
Usage: the higher the moment of inertia, the more
difficult it is to change the state of the body'... |
def normalize(deg):
"""Adjusts deg between 0-360"""
while deg < 0.0:
deg += 360.0
while deg >= 360.0:
deg -= 360.0
return deg |
def filter_underscores(items: list) -> list:
"""
Filters all items in a list that starts with an underscore
:param items: The items to filter.
:return:The filtered items.
"""
return [item for item in items if not item.split('/')[-1].startswith('_')] |
def _is_message(raw_data):
""" returns the message that occured in a measurement or False """
for identifier in ("high", "low", "cal", "err", "--"):
if identifier in raw_data.lower():
return True
return False |
def bws(t: int, tstart: int, tend: int, alpha: int) -> float:
"""Bounded-window scheduling function.
This function returns 1.0 for `t <= tstart`, 0.0 for `tend <= t`, and
`\lambda^{\alpha}` for `tstart < t < tend`, where `\lambda =
\frac{tend - t}{tend - tstart}`.
"""
# assert 0 <= tstart < te... |
def rules_to_tuples(rules_dicts):
"""
Transform generated rule dicts to tuples
:param rules_dict:
:return:
>>> rulez = [{(('isokoskelo',), ('sinisorsa',)): (0.956, 0.894, 1.013, 0.952)}]
>>> rules_to_tuples(rulez)
[(('isokoskelo',), ('sinisorsa',), 0.956, 0.894, 1.013, 0.952)]
"""
r... |
def sanitize_licenses(detailed_list, license_name) -> list:
"""
This will remove any packages that contain a license that was already verified.
Args:
detailed_list(list): List of the detailed packages generated by PackageList instance.
license_name(str): Name of the license to be checked.
... |
def _s_suffix(num):
"""Simplify pluralization."""
if num > 1:
return 's'
return '' |
def can_monitor(message):
"""
Determine if the user who sent the message is a race monitor.
Returns False if monitor status is indeterminate, e.g. message was sent
by a bot instead of a user.
"""
return message.get('is_monitor', False) |
def get_sign(charge: int) -> str:
"""Get string representation of a number's sign.
Args:
charge (int): The number whose sign to derive.
Returns:
sign (str): either '+', '-', or '' for neutral.
"""
if charge > 0:
return '+'
elif charge < 0:
return '... |
def fillcompanyrow(table, companynumber, window):
"""
:param table:
:param companynumber:
:param window:
:return:
"""
sqlstring = 'SELECT * from Company WHERE ID = ? ; '
try:
# print('fillcompanyrow sqlstring, companynumber =>', sqlstring, companynumber)
com... |
def form_to_grade_assignment(form):
"""Creates a grade dict from an assignment form."""
grade_id = '{student}-{assignment}-{course}'.format(**form)
grade = {'_id': grade_id,
'student': form['student'],
'assignment': form['assignment'],
'course': form['course'],
... |
def __create_input_remove_video_order(orders):
"""remove video order"""
remove_orders = []
for order in orders:
input = {
"TableName": "primary_table",
"Key": {"PK": {"S": order["PK"]}, "SK": {"S": order["SK"]}},
}
remove_orders.append({"Delete": input})
... |
def is_longer(dna1, dna2):
""" (str, str) -> bool
Return True if and only if DNA sequence dna1 is longer than DNA sequence
dna2.
>>> is_longer('ATCG', 'AT')
True
>>> is_longer('ATCG', 'ATCGGA')
False
"""
return len(dna1) > len(dna2) |
def __one_both_closed(x, y, c = None, l = None):
"""convert coordinates to zero-based, both strand, open/closed coordinates.
Parameters are from, to, is_positive_strand, length of contig.
"""
return x - 1, y |
def mgmt_if_entry_table_state_db(if_name):
"""
:param if_name: given interface to cast
:return: MGMT_PORT_TABLE key
"""
return b'MGMT_PORT_TABLE|' + if_name |
def validate_ftp_inputs(server_name, search_path, user_name, passwd):
"""Validate the given input before proceeding with FTP transaction.
Arguments:
server_name : Name of the FTP server where the files to be transfered
search_path : Local folder path which needs to be synced with the given... |
def line_break(text, line_len=79, indent=1):
"""
Split some text into an array of lines.
Enter: text: the text to split.
line_len: the maximum length of a line.
indent: how much to indent all but the first line.
Exit: lines: an array of lines.
"""
lines = [text.rstrip()]
... |
def playlist_json(tracks):
"""Generate a JSON List of Dictionaries for Each Track."""
for i, track in enumerate(tracks):
tracks[i] = {
"title": track[0],
"artist": track[1],
"explicit": track[2],
}
return tracks |
def prod_cart(in_list_1: list, in_list_2: list) -> list:
"""
Compute the cartesian product of two list
:param in_list_1: the first list to be evaluated
:param in_list_2: the second list to be evaluated
:return: the prodotto cartesiano result as [[x,y],..]
"""
_list = []
for element_1 in ... |
def _jce_invert_salt_half(salt_half):
"""
JCE's proprietary PBEWithMD5AndTripleDES algorithm as described in the OpenJDK sources calls for inverting the first salt half if the two halves are equal.
However, there appears to be a bug in the original JCE implementation of com.sun.crypto.provider.PBECipherCore... |
def is_tamil_unicode_value(intx: int):
"""
Quickly check if the given parameter @intx belongs to Tamil Unicode block.
:param intx:
:return: True if parameter is in the Tamil Unicode block.
"""
return (intx >= (2946) and intx <= (3066)) |
def AddEscapeCharactersToPath(path):
""" Function to add escape sequences for special characters in path string. """
return path.replace("(", "\\(").replace(" ", "\\ ").replace(")", "\\)") |
def get_gene_universe( genes_file ):
"""Builds a unique sorted list of genes from gene file"""
if isinstance( genes_file, str ):
genes_file = open( genes_file, 'r' )
return set( [ l.strip() for l in genes_file ] ) |
def get_xmlns_string(ns_set):
"""Build a string with 'xmlns' definitions for every namespace in ns_set.
Args:
ns_set (iterable): set of Namespace objects
"""
xmlns_format = 'xmlns:{0.prefix}="{0.name}"'
return "\n\t".join([xmlns_format.format(x) for x in ns_set]) |
def _integrate(function, Lambda):
""" Performs integration by trapezoidal rule """
# Variable definition for Area
Area = 0
# loop to calculate the area of each trapezoid and sum.
for i in range(1, len(Lambda)):
#the x locations of the left and right side of each trapezpoid
x0 = Lamb... |
def sum_list(nums):
"""
>>> sum_list([1, 2, 3])
6
>>> sum_list([10, 200, 33, 55])
298
"""
idx = 0
total = 0
while idx < len(nums):
total += nums[idx]
idx += 1
return total |
def is_duplicate(title, movies):
"""Returns True if title is within movies list."""
for movie in movies:
if movie.lower() == title.lower():
return True
return False |
def get_periodic_interval(current_time, cycle_length, rec_spacing, n_rec):
"""Used for linear interpolation between periodic time intervals.
One common application is the interpolation of external forcings that are defined
at discrete times (e.g. one value per month of a standard year) to the current
t... |
def sieve_of_eratosthenes(end):
"""Enumerates prime numbers below the given integer `end`.
Returns (as a tuple):
- `is_prime`: a list of bool values.
If an integer `i` is a prime number, then `is_prime[i]` is True.
Otherwise `is_prime[i]` is False.
- `primes`: a list of pri... |
def cpn(prev_list, prev_level, curr_index, curr_div, curr_mod):
""" Calculate previous neighbours """
largest_mod = max(2 * prev_level - 1, 0)
if prev_level == 1:
# No calculation needed, it only has 1 element, and every other element sees it
return prev_list[0]
else:
if curr_div... |
def to_int(n):
"""Converts a string to an integer value. Returns None, if the string cannot be converted."""
try:
return int(n)
except ValueError:
return None |
def repr_args(obj, *args, **kwargs):
"""
Return a repr string for an object with args and kwargs.
"""
typename = type(obj).__name__
args = ['{:s}'.format(str(val)) for val in args]
kwargs = ['{:s}={:s}'.format(name, str(val))
for name, val in kwargs.items()]
return '{:s}({:s})'... |
def get_percentage(old, new):
"""Gets percentage from old and new values
Args:
old (num): old value
new (num): new value
Returns:
number: Percentage, or zero if none
"""
try:
return 100 * (old - new) / old
except ZeroDivisionError:
return 0 |
def import_object(name):
"""Imports an object by name.
import_object('x.y.z') is equivalent to 'from x.y import z'.
>>> import tornado.escape
>>> import_object('os.path') is os.path
True
>>> import_object('os.path.dirname') is os.path.dirname
True
"""
parts = name.split('.')
... |
def _is_closing_message(commit_message: str) -> bool:
"""
Determines for a given commit message whether it indicates that a bug has
been closed by the corresponding commit.
Args:
commit_message: the commit message to be checked
Returns:
whether the commit message closes a bug or no... |
def _parse_incident_energy(incident_energy):
"""Turn command line arguments into proper `info` items for
the `incident_energy`.
"""
if not incident_energy:
return None
incident_energy = incident_energy.lower()
if incident_energy in ('350', '350gev'):
return '350gev'
... |
def returnBackwardsString(random_string):
"""Reverse and return the provided URI"""
return "".join(reversed(random_string)) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.