content
stringlengths 39
9.28k
| sha1
stringlengths 40
40
| id
int64 8
710k
|
---|---|---|
def _point_to_bytes(point, compressed = True):
""" Point serialisation.
Serialization is the standard one:
- O2 x for even x in compressed form
- 03 x for odd x in compressed form
- 04 x y for uncompressed form
"""
if compressed:
b = point.x.to_bytes(32,'big')
if point.y & 1:
b = b"\x03"+b
else:
b = b"\x02"+b
else:
b = b"\x04"+point.x.to_bytes(32,'big')+point.y.to_bytes(32,'big')
return b
|
1a0c88c894d001354b342b7a2debea2b7299c4b3
| 269,036 |
def command(cmd, *parameters):
"""
Helper function. Prints the gprMax #<cmd>: <parameters>. None is ignored
in the output.
Args:
cmd (str): the gprMax cmd string to be printed
*parameters: one or more strings as arguments, any None values are
ignored
Returns:
s (str): the printed string
"""
# remove Nones
filtered = filter(lambda x: x is not None, parameters)
# convert to str
filtered_str = map(str, filtered)
# convert to list
filtered_list = list(filtered_str)
try:
s = '#{}: {}'.format(cmd, " ".join(filtered_list))
except TypeError as e:
# append info about cmd and parameters to the exception:
if not e.args:
e.args = ('', )
additional_info = "Creating cmd = #{} with parameters {} -> {} failed".format(cmd, parameters, filtered_list)
e.args = e.args + (additional_info,)
raise e
# and now we can print it:
print(s)
return s
|
5e0dbec3daf11708cb5235e2d08cfae88ef27abf
| 684,421 |
def ConfigToNumElectrons(config, ignoreFullD=0, ignoreFullF=0):
""" counts the number of electrons appearing in a configuration string
**Arguments**
- config: the configuration string (e.g. '2s^2 2p^4')
- ignoreFullD: toggles not counting full d shells
- ignoreFullF: toggles not counting full f shells
**Returns**
the number of valence electrons
"""
arr = config.split(' ')
nEl = 0
for i in range(1, len(arr)):
l = arr[i].split('^')
incr = int(l[1])
if ignoreFullF and incr == 14 and l[0].find('f') != -1 and len(arr) > 2:
incr = 0
if ignoreFullD and incr == 10 and l[0].find('d') != -1 and len(arr) > 2:
incr = 0
nEl = nEl + incr
return nEl
|
9e244503f4119a170963851595a24790c04e5911
| 454,573 |
def pipe(*fns):
"""
Given a list of queryset functions as *args, return a new queryset function
that calls each function in turn, passing the return value of each as the
argument to the next.
"""
def piped(queryset):
for fn in fns:
queryset = fn(queryset)
return queryset
return piped
|
a19645ead8eb0cace9b86cb20673844b53f2ee3b
| 575,931 |
def lin_interpolate(x, x0, x1, y0, y1):
"""Linear interpolation formula
Notes
-----
Given two x values and their corresponding y values, interpolate for
an unknown y value at x
Parameters
----------
x : `float`
The x value at which the y value is unknown \n
x0 : `float`
The x value of the first known pair \n
x1 : `float`
The x value of the second known pair \n
y0 : `float`
The y value of the first known pair \n
y1 : `float`
The y value of the second known pair \n
Examples
--------
>>> import gas_dynamics as gd
>>> y = gd.lin_interpolate(x=5, x0=4, x1=6, y0=25, y1=33)
>>> y
29.0
>>>
"""
y = y0 + (x-x0) * (y1-y0)/(x1-x0)
return y
|
53a63536e6fe86668a45b00a57204c648e0d0b8a
| 518,041 |
import math
def x_round(x):
"""Round up time in 15 minutes
"""
return math.ceil(x * 4) / 4
|
88e5d9f36d4a3087682445ea94e835dedced73a0
| 161,779 |
import functools
import operator
def _has_pattern_match(name: str, patterns) -> bool:
"""Check if name matches any of the patterns"""
return functools.reduce(
operator.or_,
map(lambda r: r.search(name) is not None, patterns),
False)
|
1dd6ad54ee35db20b6fcec0495e4c4ef61788aa0
| 697,341 |
def create_input_obj(val, cols_list, input_type=None, condition=False):
"""
Used to generate larger input objects for the query creation e.g., by iterating in a list
Example use: create_input_obj(1, "uid")
Output form: [{"val": uid, "cols": ["uid"], "type": "exact", "condition": True}]
"""
input_obj = {"val": val, "cols": cols_list, "type": input_type, "condition": condition}
return input_obj
|
4184ec72924caf2f9f24c4d69ed3ce67b3e959cc
| 550,898 |
def expand_pv(pv):
""" Returns the LCS Process Variable in full syntax AADDDNNNCMM as a string
where AA is two character area,
DD is device type,
NNN is device number,
C is channel type,
MM is channel number
Returns partial PVs when input string is incomplete.
Argument:
pv(str): LCS PV to expane
"""
# Parse pv
index = 0
# Get AA
if pv[index].isdigit():
if pv[index+1].isdigit():
aa = pv[index:2].zfill(2)
index = 2
else:
aa = pv[0].zfill(2)
index = 1
else:
aa = pv[0:2].upper()
index = 2
# Get DD
dd = pv[index:index+2].upper()
index += 2
# Get NNN
ndx = 0
if index < len(pv):
while index + ndx < len(pv) and pv[index + ndx].isdigit():
ndx += 1
nnn = pv[index: index + ndx].zfill(3)
else:
nnn = ""
# Get C
index += ndx
if index < len(pv):
c = pv[index:index + 1].upper()
index += 1
else:
c = ""
# Get MM
if index < len(pv):
mm = pv[index:].zfill(2)
else:
mm = ""
return aa + dd + nnn + c + mm
|
f41dc8cf20dd55ed1cb0103c42ce67301ec93372
| 666,846 |
def text_getter(obj):
"""
Return the text of an individual DOM node.
Parameters
----------
obj : node-like
A DOM node.
Returns
-------
text : str or unicode
The text from an individual DOM node.
"""
return str(obj.text)
|
1b9e8cb91a9732549e96818492b5413e9c782a73
| 368,413 |
def readlines(filename):
"""
Read a file and return the contents as a list of lines.
Arguments:
filename name of the file to read
Returns:
A list of stripped lines.
"""
with open(filename) as infile:
lines = infile.readlines()
return [l.strip() for l in lines]
|
1ed5d90a9548d6f33eb5f06f821def0c581b3da2
| 517,541 |
def increase_by_1_loop(dummy_list):
"""
Increase the value by 1 by looping through each value in the list
Return
------
A new list containing the new values
Parameters
----------
dummy_list: A list containing integers
"""
secondlist=[]
for i in range(0,len(dummy_list)):
secondlist.append(dummy_list[i]+1)
return secondlist
|
bd4295778fd993372a208b9df4b96040994d2af1
| 203,935 |
def _lower_locale(self, locale):
"""
Converts the given locale string value
to the lower version of it.
:type locale: String
:param locale: The lower locale string value to
be converted.
:rtype: String
:return: The lower locale string value.
"""
# converts the locale to lower, then replaces
# the slashes with underscores and finally returns
# the locale lower (value) to the caller method
locale_lower = locale.lower()
locale_lower = locale_lower.replace("-", "_")
return locale_lower
|
dee74cb9b1472dcb18b3187f3f4954782b51a9e4
| 302,510 |
def _nt_sum(cobj, prop, theta):
"""
Create sum expressions in n-t forms (sum(n[i]*theta**t[i]))
Args:
cobj: Component object that will contain the parameters
prop: name of property parameters are associated with
theta: expression or variable to use for theta in expression
Returns:
Pyomo expression of sum term
"""
# Build sum term
i = 1
s = 0
while True:
try:
ni = getattr(cobj, f"{prop}_coeff_n{i}")
ti = getattr(cobj, f"{prop}_coeff_t{i}")
s += ni * theta**ti
i += 1
except AttributeError:
break
return s
|
7ef4674b27069d2e254ef2cb1839fbc67c571029
| 694,537 |
def dm2skin_getNumberOfNonZeroElements(list):
"""Returns the number of non-zero elements in the given list"""
return int(sum([1 for x in list if x != 0.0]))
|
34d0fe0c1ddcc02895e8bb2ac93db7ffa101aa1b
| 205,751 |
def uniq(seq):
"""Return unique elements in the input collection, preserving the order.
:param seq: sequence to filter
:return: sequence with duplicate items removed
"""
seen = set()
return [x for x in seq if not (x in seen or seen.add(x))]
|
2180b6aac4760d31503a9d4c7f2b3cf528d2a4f2
| 26,267 |
def parse_line_comment(lang, state, keep_tokens=True):
"""
Returns the single-line comment at the beginning of state.line,
otherwise the empty string.
Args:
lang (Language):
Syntax description for the language being parsed.
state (State):
Parser state
keep_tokens (bool, default: True):
If False, comment tokens are filtered out.
If True, comment tokens are preserved.
Returns:
(string, State)
"""
line = state.line
line_comment = lang.line_comment
if line_comment and line.startswith(line_comment):
state.line = ''
i = len(line_comment)
if not keep_tokens:
line_comment = ' ' * i
return line_comment + line[i:], state
else:
return '', state
|
acc224e7723a541b62ae44b347c8bd4fb853467a
| 151,461 |
from typing import List
def piecewise_volume_conversion(
ul: float, sequence: List[List[float]]) -> float:
"""
Takes a volume in microliters and a sequence representing a piecewise
function for the slope and y-intercept of a ul/mm function, where each
sub-list in the sequence contains:
- the max volume for the piece of the function (minimum implied from the
max of the previous item or 0
- the slope of the segment
- the y-intercept of the segment
:return: the ul/mm value for the specified volume
"""
# pick the first item from the seq for which the target is less than
# the bracketing element
i = list(filter(lambda x: ul <= x[0], sequence))[0]
# use that element to calculate the movement distance in mm
return i[1]*ul + i[2]
|
87dc40bd9d09e95081ab6ed49ea550a8e9b59c9e
| 639,514 |
def trace_dispatch(trace, command, func):
"""
Returns a wrapper for ``func`` which will record the dispatch in the trace
log.
"""
def dispatch(event):
func(event)
trace.recordEvent(command, event)
return dispatch
|
4bc8f1915d4583fccbb7ea86081ff4a334404b3d
| 206,169 |
def __collinear(a, b, c, thresh=1e-10):
"""Checks if 3 2D points are collinear."""
x1,y1 = a; x2,y2 = b; x3,y3 = c
return abs(x1*(y2-y3)+x2*(y3-y1)+x3*(y1-y2)) < thresh
|
681e5bd535dfc6cfe113217a10cc46bf741dc069
| 454,063 |
from typing import Counter
def count_repeated(sequence: list, nth_repeated: int) -> str:
"""
>>> sequence = ['Algorithms','Algorithm','Python','Python','The','Python','The']
>>> nth_repeated = 2
>>> print(count_repeated(sequence, nth_repeated))
The
"""
return "" if nth_repeated < 1 else Counter(sequence).most_common()[nth_repeated - 1][0]
|
efbf614677a3d3f71e724a89e64168525035b001
| 96,244 |
def is_valid_service_exploit(e):
"""
Check whether service exploit is valid
"""
if type(e) != list or len(e) != 2:
return False
if type(e[0]) != float or (type(e[1]) != float and type(e[1]) != int):
return False
if e[0] < 0 or e[0] > 1 or e[1] < 0:
return False
return True
|
32498755893b8a7884e0ea6e0170ff3a9dbdcb54
| 284,855 |
def intersect(index, keys):
""" Utility method to compute the intersection of all the sets in index
that correspond to the given keys keys.
Args:
index, hash for format {key -> set()}
keys, list of strings
Returns:
set, the intersection of all the sets in index that correspond to keys.
If there is at least on key that does not exist in index, this
method will return an empty set.
"""
if len(keys) == 0:
return set([])
if keys[0] not in index:
return set([])
output = index[keys[0]]
for i in range(1, len(keys)):
key = keys[i]
if key not in index:
return set([])
output = output.intersection(index[key])
return output
|
3a885e7f3822a5f2c9bcc3e0558d060fc61bf17b
| 669,573 |
def curve(t, acc_t, fast_t, dec_t, slow_t, fast, slow):
"""Returns a speed value between 0 and fast for a given t
t is the time (a float in seconds), from zero at which point acceleration starts
typically t would be incrementing in real time as the door is opening/closing
acc_t is the acceleration time, after which the 'fast' speed is reached
fast_t is the time spent at the fast speed
dec_t is the time spent decelarating from fast to slow
slow_t is the time then spent running at 'slow' speed.
after acc_t + fast_t + dec_t + slow_t, 0.0 is returned
fast is the fast speed, provide a float
slow is the slow speed, provide a float, this is the slow door speed which typically
would take the door to a limit stop switch."""
assert fast > slow > 0.0
duration = acc_t + fast_t + dec_t
full_duration = duration + slow_t
if t >= full_duration:
return 0.0
if t >= duration:
return slow
if t >= acc_t and t <= acc_t + fast_t:
# during fast time, fast should be returned
return fast
# this list must have nine elements describing an acceleration curve from 0.0 to 1.0
c = [0.0, 0.05, 0.15, 0.3, 0.5, 0.7, 0.85, 0.95, 1.0]
# increase from 0.0 to fast during acceleration
if t <= acc_t:
# first calculate an increase from 0.0 to 1.0
# scale acc_t to match the list on the acceleration curve
tacc = t * 8.0 / acc_t # when acc_t = 8, tacc = t
lowindex = int(tacc)
highindex = lowindex + 1
diff = c[highindex] - c[lowindex]
y = diff*tacc + c[lowindex] - diff* lowindex
if y < 0.0:
y = 0.0
# scale 1.0 to be fast
speed = y * fast
return round(speed, 3)
# for the deceleration, treat time in the negative direction
# so rather than a decrease from 1.0 to 0.0, it again looks like
# an increase from 0.0 to 1.0
s = duration - t
if s >= dec_t:
return fast
# scale dec_t to match the list on the acceleration curve
sdec = s * 8.0 / dec_t
lowindex = int(sdec)
highindex = lowindex + 1
diff = c[highindex] - c[lowindex]
y = diff*sdec + c[lowindex] - diff* lowindex
if y < 0.0:
y = 0.0
# 1.0 should become 'fast' and 0.0 should become 'slow'
speed = (fast - slow)*y + slow
return round(speed, 3)
|
646ddccdd8d27d3fc949469868afb1c59ff9b740
| 668,196 |
def filter_key_in_values(rows, key, values):
"""
Return all the `rows` whose value for `key` is in the list `values`.
"""
if isinstance(values, str):
values = [values]
return list(filter(lambda r: r[key] in values, rows))
|
60a4e7a8794640c6a1052b0b2c61b70ed69cc1e3
| 193,793 |
import torch
def squeeze_expand_dim(tensor, axis):
""" helper to squeeze a multi-dim tensor and then
unsqueeze the axis dimension if dims < 4"""
tensor = torch.squeeze(tensor)
if len(list(tensor.size())) < 4:
return tensor.unsqueeze(axis)
else:
return tensor
|
c33b1fd38215e931f4fbe7c386350a4d50f043b4
| 353,014 |
import re
def compile_matcher(regex):
"""Returns a function that takes one argument and returns True or False.
Regex is a regular expression. Empty regex matches everything. There
is one expression: if the regex starts with "!", the meaning of it is
reversed.
"""
if not regex:
return lambda x: True
elif regex == '!':
return lambda x: False
elif regex.startswith('!'):
rx = re.compile(regex[1:])
return lambda x: rx.search(x) is None
else:
rx = re.compile(regex)
return lambda x: rx.search(x) is not None
|
6632de458c4e95f3009d9a01233d144c6b7d5752
| 87,394 |
def _cache_key_func(system, method):
"""Construct cache key for a given system and method pair."""
if not isinstance(method, str):
method = method.__name__
return (f"{type(system).__name__}.{method}", id(system))
|
1016bf0662b08eb05af4cb0d92b8541cbc1e062b
| 377,787 |
import random
def new_episode(client, carla_settings, position, vehicle_pair, pedestrian_pair, set_of_weathers):
"""
Start a CARLA new episode and generate a target to be pursued on this episode
Args:
client: the client connected to CARLA now
carla_settings: a carla settings object to be used
position: start position in the town
vehicle_pair: range of permissible number of vehicles
pedestrian_pair: range of permissible number of pedestrians
set_of_weathers: permissible set of weathers
Returns:
Returns the configuration of the current episode to be used for data collection
"""
# Every time the seeds for the episode are different
number_of_vehicles = random.randint(vehicle_pair[0], vehicle_pair[1])
number_of_pedestrians = random.randint(pedestrian_pair[0], pedestrian_pair[1])
weather = random.choice(set_of_weathers)
carla_settings.set(
NumberOfVehicles=number_of_vehicles,
NumberOfPedestrians=number_of_pedestrians,
WeatherId=weather
)
scene = client.load_settings(carla_settings)
client.start_episode(position)
return scene.map_name, scene.player_start_spots, weather, number_of_vehicles, number_of_pedestrians, \
carla_settings.SeedVehicles, carla_settings.SeedPedestrians
|
d66c1c6409cf6413d4d5851f3f8fd1e510944a58
| 590,515 |
def __getTriangleCentroid(triangle):
"""
Returns the centroid of a triangle in 3D-space
"""
# group the xs, ys, and zs
coordGroups = zip(triangle[0], triangle[1], triangle[2])
centroid = tuple([sum(coordGroup)/3.0 for coordGroup in coordGroups])
return centroid
|
004c8a4d24e20ea223741120748d379cb6d990f8
| 401,638 |
import re
def is_bible_verse(s: str) -> bool:
"""
Does a text contain reference to a part of the Bible?
example: is_bible_verse("text filler blah blah 1 Mark 23: 45-67 ") -> True
"""
re_pattern = r"((?:\d +)?[A-Za-z]+) +(\d\d?) +(\d\d?-\d\d?|\d\d?)(?: +|$)"
s = s.replace(';', ' ').replace(':', ' ')
res = re.findall(re_pattern, s, flags=re.IGNORECASE)
return bool(res)
|
f11f2c3a7ee6d702b870cc63beed0c5739923fe4
| 370,720 |
import math
def vector_coordinates(phi, theta):
""" Returns 3D vector which points to the pixel location inside a sphere. """
return (math.cos(phi) * math.cos(theta), # X
math.sin(phi), # Y
math.cos(phi) * math.sin(theta))
|
05e0ac2242d2e860017ea0420bfc453c53643549
| 551,339 |
def solution(x: int, a: list) -> int:
"""
Finds the earliest time at which a frog can cross a river.
:param x: Number of positions a leaf can fall.
:param a: A list of positions.
:returns: The time which a frog can get from position 0 to position X+1
or -1 if it can never reach it.
>>> solution(5, [1, 3, 1, 4, 2, 3, 5, 4])
6
"""
positions = set(range(1, x + 1))
for time, position in enumerate(a):
positions.discard(position)
if not positions:
return time
else:
return -1
|
29bbc9a17757830cacefc83e214d399c9a536240
| 115,006 |
def remove_sorting_column(player_data_list):
"""Remove sorting qualifier column.
Args:
player_data_list: list with player data
Returns:
player data list with sorting column removed
"""
return [entry[:-1] for entry in player_data_list]
|
34794441e69a6df58b1bdc829ec03e645f3883b2
| 103,526 |
def generate_username(membersuite_object):
"""Return a username suitable for storing in auth.User.username.
Has to be <= 30 characters long. (Until we drop support for
Django 1.4, after which we can define a custom User model with
a larger username field.)
We want to incorporate the membersuite_id in the username.
Those look like this:
6faf90e4-0032-c842-a28a-0b3c8b856f80
That's 36 characters, too long for username. Making the
assumption that those leading digits will always be there in
every ID. Since they're not needed to generate a unique
value, they can go.
After chomping the intro, we're at 27 characters, so we
insert "ms" in the front.
"""
username = "ms" + membersuite_object.membersuite_id[len("6faf90e4"):]
return username
|
6fd3d1afbd37e309582dab39bfd2c76190423118
| 309,422 |
import re
def initials(phrase):
"""
Return a string composed of the first letter of each word in the phrase
"""
return re.sub(r'(?:^| +)(\S)\S*', r'\1', phrase)
|
207262f695584c968244688dce407b2d3be59c4e
| 364,248 |
def gen_node_name_filter(node_names):
"""Generates a drydock compatible node filter using only node names
:param node_names: the nodes with which to create a filter
"""
return {
'filter_set_type': 'union',
'filter_set': [
{
'filter_type': 'union',
'node_names': node_names
}
]
}
|
5472057b4884d696e6167a30b96d57c8abf3019f
| 325,096 |
def middle(t):
"""
Return a new list that doesn't include the first or last elements from the original.
"""
res = t
del(res[0])
del(res[-1])
return res
|
8811c5c5ad99444a2caaad42591d46ccdee6e2d5
| 494,915 |
def set_bit(value, index, high=True):
"""Set the index:th bit of value.
Args:
value (int): Number that will have bit modified.
index (int): Index of bit to set.
high (bool): True (default) = set bit high, False = set bit low
"""
mask = 1 << index
value &= ~mask
if high:
value |= mask
return value
|
1962921fe45a0099ed2c11bc055c35a482accaf1
| 379,534 |
def alignment_params(screen):
"""
Takes a camera screen dictionary as input. Locates all scaffold intersections
and calculates their alignment parameter (distance from left edge * distance
from top edge).
Returns the sum of the alignment parameters and an updated screen showing their positions.
"""
intersections = []
alignment_param = 0
moves = {0:(0,1), 1: (0,-1), 2: (1, 0), 3: (-1, 0)}
for tile in screen:
intersect = True
pos_x, pos_y = tile
if screen[tile] == 35:
for i in range(4):
dx, dy = moves[i]
test_pos = (pos_x + dx, pos_y + dy)
if test_pos not in screen or screen[test_pos] != 35:
intersect = False
break
if intersect:
intersections.append(tile)
alignment_param += pos_x * pos_y
for tile in intersections:
screen[tile] = 48
return screen, alignment_param
|
3344bee1ad0ac0696a9113b536e8eed5445e6578
| 289,775 |
def lagrangeg(mu, r2, tau):
"""Compute 1st order approximation to Lagrange's g function.
Args:
mu (float): gravitational parameter attracting body
r2 (float): radial distance
tau (float): time interval
Returns:
float: Lagrange's g function value
"""
return tau-(1.0/6.0)*(mu/(r2**3))*(tau**3)
|
a9f295e6fdfd966c14126aba46f09903bac18f0a
| 552,883 |
def is_ask_help(text: str) -> bool:
"""
A utility method to tell if the input text is asking for help.
"""
sample_phrases = [
"help", "help me", "i need help", "i'm lost", "i am lost"
]
text = text.strip()
return any(text == phrase for phrase in sample_phrases)
|
994ac984c69b77c869f0f28c5ee77a082e76c909
| 629,353 |
def clean_predictor_name(predictor: str) -> str:
"""Strip-off redundant suffix (e.g. "_enc" or "_bin") from the predictor
name to return a clean version of the predictor
Args:
predictor (str): Description
Returns:
str: Description
"""
return (predictor.replace("_enc", "").replace("_bin", "")
.replace("_processed", ""))
|
1854c7747a0670ee4b40b0d8b7db755f8fced00c
| 580,982 |
def check_ascending(ra, dec, vel, verbose=False):
"""
Check if the RA, DEC and VELO axes of a cube are in ascending order.
It returns a step for every axes which will make it go in ascending order.
:param ra: RA axis.
:param dec: DEC axis.
:param vel: Velocity axis.
:returns: Step for RA, DEC and velocity.
:rtype: int,int,int
"""
if vel[0] > vel[1]:
vs = -1
if verbose:
print("Velocity axis is inverted.")
else:
vs = 1
if ra[0] > ra[1]:
rs = -1
if verbose:
print("RA axis is inverted.")
else:
rs = 1
if dec[0] > dec[1]:
ds = -1
if verbose:
print("DEC axis is inverted.")
else:
ds = 1
return rs, ds, vs
|
89e9fb25eab2e0684d18b0c5123cce831521f03b
| 654,344 |
def hacktoberfest_events(tablerows):
"""This function takes the list of tablerows as input and performs
scraping of required elements as well as stores the scraped data
into a dictionary and returns that dictionary
Args:
tablerows (list): Lis of tablerows of the target elements.
"""
events = {}
for i, tablerow in enumerate(tablerows):
location = tablerow.find("td", {"class": "location"}).text
link = tablerow.find("a")["href"]
name = tablerow.find("td", {"class": "event_name"}).text.strip()
date = tablerow.find("td", {"class": "date is-hidden"}).text.strip()
events[i] = [name, date, location, link]
return events
|
7c1437eaab58bccffc4ff0b59a2d0255f47e746d
| 284,035 |
import re
def is_same_gws(path1, path2):
"""
Check that two paths both start with the same group workspace name.
It's assumed that both paths are both in either the old-style or both
in the new-style format.
:param str path1: The first path
:param str path2: The second path
:returns: True if both paths are in the same group workspace
"""
if path1.startswith('/group_workspaces'):
gws_pattern = r'^/group_workspaces/jasmin2/primavera\d'
elif path1.startswith('/gws'):
gws_pattern = r'^/gws/nopw/j04/primavera\d'
else:
return False
gws1 = re.match(gws_pattern, path1)
gws2 = re.match(gws_pattern, path2)
if not gws1 or not gws2:
return False
return True if gws1.group(0) == gws2.group(0) else False
|
e198bf8449021c8c264ae126d1b5ad9deab77089
| 169,183 |
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
|
f72908c1f3adfc1d37f4760a240f68c66031dc19
| 30,643 |
from typing import Dict
def response_success(response: Dict) -> bool:
"""
Parse a response from a request issued by any botocore.client.BaseClient
to determine whether the request was successful or not.
:param response:
:return: boolean
:raises: KeyError if the response is not an AWS response
"""
# If the response dict is not constructed as expected for an AWS response,
# this should raise a KeyError to indicate something is very wrong.
status_code = int(response["ResponseMetadata"]["HTTPStatusCode"])
if status_code:
# consider 300+ responses to be unsuccessful
return 200 <= status_code < 300
else:
return False
|
467e2e3f8e2279c936d447dda0a499ed4b5792cf
| 64,051 |
def format_datetime_for_google_timestamp(dt):
"""
Formats a datetime for use in a Google API request that expects a timestamp
(e.g.: file watch expiration – https://developers.google.com/drive/api/v3/reference/files/watch#request-body)
Args:
dt (datetime.datetime):
Returns:
int: The datetime formatted as a timestamp for use in a Google API request
"""
# Google expects the timestamp to be in milliseconds, not seconds, hence the '* 1000'
return int(dt.timestamp() * 1000)
|
25512d5c57773a7bfb2e0d67ad39a6c902da75fd
| 287,591 |
def strip_node_name(node_name):
"""Strips off ports and other decorations to get the underlying node name."""
if node_name.startswith("^"):
node_name = node_name[1:]
return node_name.split(':')[0]
|
8a0e3f863e4026f9f996493b839463e6d3772238
| 614,958 |
from typing import Tuple
import re
def parse_hp_condition(hp_condition: str) -> Tuple[int, int, str]:
"""
HPと状態異常を表す文字列のパース
:param hp_condition: '50/200' (現在HP=50, 最大HP=200, 状態異常なし) or '50/200 psn' (状態異常の時)
:return: 現在HP, 最大HP, 状態異常('', 'psn'(毒), 'tox'(猛毒), 'par', 'brn', 'slp', 'frz', 'fnt'(瀕死))
"""
if hp_condition == '0 fnt':
# 瀕死の時は0という表示になっている
# 便宜上最大HP100として返している
return 0, 100, 'fnt'
m = re.match('^(\\d+)/(\\d+)(?: (psn|tox|par|brn|slp|frz|fnt)|)?$', hp_condition)
assert m is not None, f"HP_CONDITION '{hp_condition}' cannot be parsed."
# m[3]は状態異常がないときNoneとなる
return int(m[1]), int(m[2]), m[3] or ''
|
cbe9ec75efbae1b144836cc8129fdc3256e0dccf
| 31,686 |
def get_ORM_instance(ORM_class, session, instance):
"""
Given an ORM class and *either an instance of this class, or the name attribute of an instance
of this class*, return the instance
"""
if isinstance(instance, str):
return session.query(ORM_class).filter(ORM_class.name == instance).one()
else:
return instance
|
5b3427147b6934704b300ec5026254e6bce1e2a6
| 527,236 |
import string
import random
def generate_random(size):
"""Generate random printable string"""
_range = range(size)
_alphabet = string.ascii_uppercase + string.digits + ' _+=\'"~@!#?/<>'
return ''.join(random.choice(_alphabet) for _ in _range)
|
fa326d3d2c6da582e2449780ac9c468ceb418658
| 438,801 |
def DetermineHotlistIssuePosition(issue, issue_ids):
"""Find position of an issue in a hotlist for a flipper.
Args:
issue: The issue PB currently being viewed
issue_ids: list of issue_id's
Returns:
A 3-tuple (prev_iid, index, next_iid) where prev_iid is the
IID of the previous issue in the total ordering (or None),
index is the index that the current issue has in the sorted
list of issues in the hotlist,
next_iid is the next issue (or None).
"""
prev_iid, next_iid = None, None
total_issues = len(issue_ids)
for i, issue_id in enumerate(issue_ids):
if issue_id == issue.issue_id:
index = i
if i < total_issues - 1:
next_iid = issue_ids[i + 1]
if i > 0:
prev_iid = issue_ids[i - 1]
return prev_iid, index, next_iid
return None, None, None
|
7a3d8f95aff29875a97c416139bc918a663b596a
| 257,125 |
def as_ctrait(obj):
""" Convert to CTrait if the object knows how, else raise TraitError.
Parameters
----------
obj
An object that supports conversion to `CTrait`. Refer
documentation for when the object supports this conversion.
Returns
-------
ctrait.CTrait
A CTrait object.
Raises
------
TypeError
If the object does not support conversion to CTrait.
"""
if isinstance(obj, type) and hasattr(obj, 'instantiate_and_get_ctrait'):
return obj.instantiate_and_get_ctrait()
elif not isinstance(obj, type) and hasattr(obj, 'as_ctrait'):
return obj.as_ctrait()
else:
raise TypeError(
"Object {!r} does not support conversion to CTrait".format(obj))
|
bbb4a176f6bcfc57ff31f79e219d836378b77a98
| 553,220 |
def get_upload_location(instance, filename):
"""
This method provides a filename to store an uploaded image.
Inputs:
instance: instance of an Observation class
filename: string
returns:
string:
"""
psr = instance.pulsar.jname
beam = instance.beam
utc = instance.utc.utc_ts.strftime("%Y-%m-%d-%H:%M:%S")
return f"{psr}/{utc}/{beam}/{filename}"
|
2bbf76d02e8b26ec703d5b4047074b3c05957407
| 120,452 |
import math
def selection_policy(node, c_uct):
"""
Given a tree node, determine which
child to move to when performing MCTS;
c_uct: constant for UCT algorithm
"""
if node.is_leaf():
return node
max_child = None
max_val = float('-inf')
total_visit = 1
for edge in node.child_edges:
total_visit += edge.visit_count
# Determine best child to move to according to UCT
for edge in node.child_edges:
if edge.visit_count == 0:
edge_val = 0
else:
edge_val = edge.total_reward / edge.visit_count
edge_val += c_uct * math.sqrt(2 * math.log(total_visit) / (1 + edge.visit_count))
if edge_val > max_val:
max_val = edge_val
max_child = edge.child
return max_child
|
cd19ae5876bdc71fa0083ed4a3c40502b00b4526
| 356,419 |
def wildcard_match(pattern: str, text: str, partial_match: bool = False) -> bool:
"""
Adapted and fixed version from: https://www.tutorialspoint.com/Wildcard-Pattern-Matching
Original by Samual Sam
Wildcards:
'?' matches any one character
'*' matches any sequence of zero or more characters
"""
n = len(text)
m = len(pattern)
# empty pattern
if m == 0:
return n == 0
# i: index into text; j: index into pattern
i, j = 0, 0
text_ptr, pattern_ptr = -1, -1
while i < n:
# as ? used for one character
if j < m and pattern[j] == '?':
i += 1
j += 1
# as * used for one or more character
elif j < m and pattern[j] == '*':
text_ptr = i
pattern_ptr = j
j += 1
# matching text and pattern characters
elif j < m and text[i] == pattern[j]:
i += 1
j += 1
# pattern_ptr is already updated
elif pattern_ptr != -1:
j = pattern_ptr + 1
i = text_ptr + 1
text_ptr += 1
else:
return False
# move along left over * in pattern since they can represent empty string
while j < m and pattern[j] == '*':
j += 1 # j will increase when wildcard is *
# check whether pattern is finished or not
if j == m or partial_match:
return True
return False
|
5248efaee755f8df5fc62d5ef5360d29fadf7016
| 391,097 |
def memory_test(used,total,percentage=25):
"""Tests the sensor used memory against the total memory size.
@param used_memory -- the used memory of the sensor.
@param total_memory -- the total memory of the sensor.
@return -- a string flag
"PASS" if the used memory is 25% or less of the total.
"FAIL" if the used memory is greater than 25% of the total.
"""
if used <= total*(percentage/100):
flag = "PASS"
else:
flag = "FAIL"
return flag
|
ee9b12db33154b525ba06fb36f70f8d817a2b89d
| 276,013 |
import dill as pickle
def load(file, **kwds):
"""load an object that was stored with dill.temp.dump
file: filehandle
mode: mode to open the file, one of: {'r', 'rb'}
>>> dumpfile = dill.temp.dump([1, 2, 3, 4, 5])
>>> dill.temp.load(dumpfile)
[1, 2, 3, 4, 5]
"""
mode = kwds.pop('mode', 'rb')
name = getattr(file, 'name', file) # name=file.name or name=file (if str)
return pickle.load(open(name, mode=mode, **kwds))
|
c334ab5df5c3a254f90a3c6319e305c525eac5ef
| 305,872 |
def getDimensions(self):
"""Gets the number of rows and columns of the map"""
return (self.__numrows__, self.__numcols__)
|
fa56d7ec97ba237fb41cc70bbbb7a2348a621f04
| 25,165 |
def decode_version(packed):
"""Decode packed R version number into a human readable format.
"""
v = packed // 65536
packed %= 65536
p = packed // 256
packed %= 256
s = packed
return (v, p, s)
|
7c4806e84398531256de4cb58a88f81f7f79800f
| 386,334 |
from bs4 import BeautifulSoup
def remove_html_tags(html_doc, lines_concat = True):
""" Remove html tags from input strings
>>> sample_doc = '''<html><head><title>The Dormouse's story</title></head>
... <body><p class="title"><b>A Mad Tea-Party</b></p></body>
... </html>'''
>>> remove_html_tags(sample_doc, False)
"The Dormouse's story\\nA Mad Tea-Party\\n"
>>> remove_html_tags(sample_doc, True)
"The Dormouse's story A Mad Tea-Party"
"""
soup = BeautifulSoup(html_doc, 'html.parser')
text = soup.get_text()
if lines_concat:
text = ' '.join(text.splitlines())
return text
|
c4eed789396794ce98292dc3452d39f2b656a37d
| 417,200 |
def capitalize_each_word(s, delimiter):
"""Capitalize each word seperated by a delimiter
Args:
s (str): The string to capitalize each word in
delimiter (str): The delimeter words are separated by
Returns:
str: The modified string
"""
return delimiter.join([w.capitalize() for w in s.split(delimiter)])
|
c74e17d277ca17d9763e2ca905da13337479fbd6
| 511,469 |
def _GetKeys(data):
"""Get the keys of a H5Dataset or numpy compound data type."""
if hasattr(data, 'keys'):
return set(data.keys())
elif hasattr(data, 'dtype') and data.dtype.names:
return set(data.dtype.names)
else:
return None
|
2dd3e09c1f2bfdfd0e053e6ebb229a2bc6b78967
| 563,786 |
def parse_literal(x):
"""
return the smallest possible data type for a string or list of strings
Parameters
----------
x: str or list
a string to be parsed
Returns
-------
int, float or str
the parsing result
Examples
--------
>>> isinstance(parse_literal('1.5'), float)
True
>>> isinstance(parse_literal('1'), int)
True
>>> isinstance(parse_literal('foobar'), str)
True
"""
if isinstance(x, list):
return [parse_literal(y) for y in x]
elif isinstance(x, (bytes, str)):
try:
return int(x)
except ValueError:
try:
return float(x)
except ValueError:
return x
else:
raise TypeError('input must be a string or a list of strings')
|
14bb312074b06d3b8d5e9e66652050d9247700af
| 630,263 |
def squeeze(data: object) -> object:
"""
Overview:
Squeeze data from tuple, list or dict to single object
Example:
>>> a = (4, )
>>> a = squeeze(a)
>>> print(a)
>>> 4
"""
if isinstance(data, tuple) or isinstance(data, list):
if len(data) == 1:
return data[0]
else:
return tuple(data)
elif isinstance(data, dict):
if len(data) == 1:
return list(data.values())[0]
return data
|
7ed444dcee6e52f9159c7817a2b7d6058bb78ad0
| 478,204 |
def find_prefix(root, prefix):
"""
Checks & returns
1. If the prefix exists in any of the words we added so far
2. If yes, then how may words actually have the prefix
"""
if not root.children:
return (False, 0)
node = root
for char in prefix:
for child in node.children:
if char == child.char:
node = child
# found this char, go to next char in the prefix
break
else:
return (False, 0)
return (True, node.counter)
|
064023317feb5cd380fbabf09e2b2821541dad72
| 161,645 |
def createMotifsDictionary(filename, padding=100):
"""
Storing Motif Information into a dictionary: {chrN: [(start1, stop1), (start2, stop2)..]}
:param filename: # motifs filename
:param padding: # left and right start/stop padding (concerned about peaks 100bp from a known motif)
:return motifDictionary: # used by motifOverLap to find
"""
fh = open(filename, "r")
header = next(fh) # skip over header
motifDict = {}
for line in fh:
linelist = line.strip().split("\t")
#print(linelist)
chr, start, stop = linelist[1], int(linelist[2]), int(linelist[3])
if chr not in motifDict:
motifDict[chr] = []
motifDict[chr].append((start-padding, stop+padding))
#print(motifDict, "\n\n")
return motifDict
|
e80978aef8fc4bfdf6d46eaf8c5e79ba90f1d66b
| 564,006 |
def dumps(blackbird):
"""Serialize a blackbird program to a string.
Args:
blackbird (BlackbirdProgram): a :class:`BlackbirdProgram` object
Returns:
str: the serialized Blackbird program
"""
return blackbird.serialize()
|
f3e8bedcd84d2579c0966f7d4843a626099c25a9
| 649,191 |
from datetime import datetime
def parse_timestamp(time_str):
"""
There are three datetime string formats in eMammal, and some have an empty field.
Args:
time_str: text in the tag ImageDateTime
Returns:
datetime object, error (None if no error)
"""
if time_str == '' or time_str is None:
return '', 'empty or None'
try:
res = datetime.strptime(time_str, '%Y-%m-%dT%H:%M:%S')
return res, None
except Exception:
try:
res = datetime.strptime(time_str, '%Y-%m-%d %H:%M:%S')
return res, None
except Exception:
try:
res = datetime.strptime(time_str, '%m/%d/%Y %H:%M')
return res, None
except:
print('WARNING, time_str cannot be parsed {}.'.format(time_str))
return time_str, 'cannot be parsed {}'.format(time_str)
|
634d47fbcffe72164b62b2f46e80b8504db21b3d
| 55,429 |
def get_fuzzer_benchmark_key(fuzzer: str, benchmark: str):
"""Returns the key in coverage dict for a pair of fuzzer-benchmark."""
return fuzzer + ' ' + benchmark
|
1ad42f2c8c01e63b16855eb7dc9fb5cdb2821ec0
| 508,225 |
def parse_policy(policy):
"""Parses a policy of nested list of tuples and converts them
into a tuple of nested list of lists. Helps with TF serializability."""
op_names = [[name for name, _, _ in subpolicy] for subpolicy in policy]
op_probs = [[prob for _, prob, _ in subpolicy] for subpolicy in policy]
op_levels = [[level for _, _, level in subpolicy] for subpolicy in policy]
return op_names, op_probs, op_levels
|
79df1fdb9825cfbe35ca59e3a2e9700a3bcf26d6
| 602,513 |
def inv_index_map(k):
"""
The inverse index map used mapping the from 1D index to 2D index
Parameters
----------
k : int
1D index.
Returns
-------
i : int
the index in the 2D case.
d : int
the dimension to use for the 2D index.
"""
return k // 2, k % 2
|
fca39108b224794351f2dd4fd647572b8d947070
| 232,499 |
def turn(orient_index, direction):
"""
change the current orientation according to
the new directions
Args:
orient_index (int): index in the orient list for the
current orientations
direction (str): R or L
Returns:
int
"""
if direction == 'R':
orient_index += 1
if orient_index == 4:
orient_index = 0
else:
orient_index -= 1
if orient_index == -1:
orient_index = 3
return orient_index
|
9b781296038d2650bf08f5f5c85757d0763c2511
| 544,006 |
def complement(x):
""" Computes complement of a probability/parameter
Parameters
----------
x : {float, int}
Returns
-------
out : {float, int}
Complement
"""
out = 1 - x
return out
|
8f7221c10081c39a57bf51a5ad40baf423ce98db
| 544,743 |
def getGenomeSegmentGroups(genomeSegmentIterator, contigsExcludedFromGrouping = None) :
"""
Iterate segment groups and 'clump' small contigs together
@param genomeSegmentIterator any object which will iterate through ungrouped genome segments)
@param contigsExcludedFromGrouping defines a set of contigs which are excluded from grouping
(useful when a particular contig, eg. chrM, is called with contig-specific parameters)
@return yields a series of segment group lists
Note this function will not reorder segments. This means that grouping will be suboptimal if small segments are
sparsely distributed among larger ones.
"""
def isGroupEligible(gseg) :
if contigsExcludedFromGrouping is None : return True
return (gseg.chromLabel not in contigsExcludedFromGrouping)
minSegmentGroupSize=200000
group = []
headSize = 0
isLastSegmentGroupEligible = True
for gseg in genomeSegmentIterator :
isSegmentGroupEligible = isGroupEligible(gseg)
if (isSegmentGroupEligible and isLastSegmentGroupEligible) and (headSize+gseg.size() <= minSegmentGroupSize) :
group.append(gseg)
headSize += gseg.size()
else :
if len(group) != 0 : yield(group)
group = [gseg]
headSize = gseg.size()
isLastSegmentGroupEligible = isSegmentGroupEligible
if len(group) != 0 : yield(group)
|
b6e2ebc49d98d02a56feb8983c9e2a684496078a
| 378,506 |
def get_affected_enduse(strategy_vars, name):
"""Get all defined affected enduses of a scenario variable
Arguments
---------
strategy_vars : dict
Dict with all defined strategy variables
name : str
Name of variable to get
Returns
-------
enduses : list
AFfected enduses of scenario variable
"""
try:
for var in strategy_vars:
if var['name'] == name:
enduses = var['enduse']
return enduses
except KeyError: # Not affected enduses defined
enduses = []
return enduses
|
30675c28f615b0e91c1884e858fa449371c235d5
| 572,425 |
def dict_by_class(obj_list):
""" Create a `dict` keyed by class from a list of objects
Args:
obj_list (:obj:`list`) list of objects
Returns:
:obj:`dict`: mapping from object class to list of objects of that class
"""
obj_dict = {}
for obj in obj_list:
cls = obj.__class__
if cls not in obj_dict:
obj_dict[cls] = []
obj_dict[cls].append(obj)
return obj_dict
|
e9fe759a162bdb4119157105c57cb45e5bac4764
| 562,496 |
def density_of_sky_fibers(margin=1.5):
"""Use positioner patrol size to determine sky fiber density for DESI.
Parameters
----------
margin : :class:`float`, optional, defaults to 1.5
Factor of extra sky positions to generate. So, for margin=10, 10x as
many sky positions as the default requirements will be generated.
Returns
-------
:class:`float`
The density of sky fibers to generate in per sq. deg.
"""
# ADM the patrol radius of a DESI positioner (in sq. deg.)
patrol_radius = 6.4/60./60.
# ADM hardcode the number of options per positioner
options = 2.
nskies = margin*options/patrol_radius
return nskies
|
44c8f5c5773471923637146c7aa14b7fb2b95a2e
| 199,093 |
def str_round(num, n):
"""Round a number to n digits and return the result as a string."""
num = round(num, n)
format = "%."+str(max(n, 0))+"f"
return format % num
|
a58ee6ac9bbc37c6f8e438af40ff334ef9356a08
| 296,529 |
import json
def read_secret_file(file_path):
""" Reads the content of the secret file and returns the secret key. """
with open(file_path, 'r') as secret_file:
content = secret_file.read()
obj = json.loads(content)
return obj['secret_key']
print('Secret key faile failed to open!!')
return ''
|
e0a0cc0ad3c9c6342cc157894de5176129aac475
| 84,442 |
def group_names(user):
"""Returns a list of group names for the user"""
return list(user.groups.all().values_list('name', flat=True))
|
5d9147bd176d2fb15e0027bc31330e7b3dce8c71
| 396,823 |
def num_states(spin_str_element):
"""
This function evaluates de spin number string, formatted as s=a/b and
returns the number of states 2*s + 1.
In the table we have three type of strings:
1. spin numbers integers formatted with 1 or 2 characters, e.g s=1, and s=10.
2. spin numbers formatted with 3 characters. e.g. s=3/2.
3. spin numbers formatted with 4 characters. e.g. s=11/2
Parameters
----------
:var spin_str_element: This string class element contains the information
in [88:102], about spin, parity, and
isospin charge.
Returns:
--------
:var states: this integer variable contains the number of states associated
to the `spin_str_element` string
"""
if len(spin_str_element) == 1 or len(spin_str_element) == 2:
states = 2*int(spin_str_element) + 1
return states
elif len(spin_str_element) == 3:
num = int(spin_str_element[0])
den = int(spin_str_element[2])
states = 2*num//den + 1
return states
elif len(spin_str_element) == 4:
num = int(spin_str_element[0:2])
den = int(spin_str_element[3])
states = 2*num//den + 1
return states
else:
return None
|
8c92f10f955a2ca9eb12a895f9a7281b454b3345
| 561,359 |
def merge(source, destination):
"""
Merges 2 dicts recursively.
If leaves are lists, they are extended.
If leaves are ints, floats, strs, they are concatenated
into a string, if the leaves are not the same.
"""
for key, value in source.items():
if isinstance(value, dict):
# get node or create one
node = destination.setdefault(key, {})
merge(value, node)
elif isinstance(value, list):
destination[key] += value
else:
if destination[key] != value:
destination[key] = f'{destination[key]},{value}'
else:
destination[key] = value
return destination
|
7f771e83c5f89fa641fa79f863f4382ac5cc0ead
| 49,610 |
def generateJobName(key):
"""
Transcribe job names cannot contains spaces. This takes in an S3
object key, extracts the filename part, replaces spaces with "-"
characters and returns that as the job-name to use
"""
# Get rid of leading path, and replace [SPACE] with "-"
response = key
if "/" in key:
response = response[1 + key.find('/'):]
response = response.replace(" ", "-")
return response
|
c52cc4d3417f85c55ab69f63016608b0ff4ff7ca
| 693,468 |
def parse_author(a):
"""Parses author name in the format of `Last, First Middle` where
the middle name is sometimes there and sometimes not (and could just be an initial)
Returns: author name as `F. M. Last`
"""
a = a.split(', ')
last = a[0].strip()
fm = a[1].split(' ')
first = fm[0][0] + '.'
if len(fm) > 1:
middle = fm[1][0] + '.'
else:
middle = ''
if not middle == '':
return first + ' ' + middle + ' ' + last
else:
return first + ' ' + last
|
f35a202c21d4b9424abc4516b06b4bca9991a4af
| 393,461 |
import math
def get_distance(x1: int, y1: int, x2: int, y2: int) -> float:
"""
it returns the distance between two points
:param x1: int
:param y1: int
:param x2: int
:param y2: int
:return: float
"""
return math.sqrt(((x1 - x2) ** 2 + (y1 - y2) ** 2))
|
ce3bb0cb85564205b83830b2532713938328c142
| 101,083 |
def find_title_row(table_object):
"""
Searches for the topmost non-empty row.
:param table_object: Input Table object
:type table_object: ~tabledataextractor.table.table.Table
:return: int
"""
for row_index, empty_row in enumerate(table_object.pre_cleaned_table_empty):
if not empty_row.all():
return row_index
|
f2ab697409330a411428c459719aa5d597c9b032
| 257,337 |
def innerHTML(element):
"""
Return the HTML contents of a BeautifulSoup tag.
"""
return element.decode_contents(formatter="html")
|
8ac3686e6aa549abf051ae749b43a74286a6892d
| 444,231 |
import hashlib
def get_typeid(typeinfo):
"""Compute the CallSiteTypeId from a typeinfo string"""
return int.from_bytes(hashlib.md5(typeinfo.encode("ascii")).digest()[:8], "little")
|
bb4a0e24aa549770a1cb6fb0a93612724296acf4
| 389,626 |
def decode_string(string, encoding=None):
"""Decode a string with specified encoding
:type string: str or bytes
:param string: string to decode
:param str encoding: encoding of string to decode
:rtype: str
:return: decoded string
"""
if isinstance(string, str):
return string
if encoding is None:
encoding = 'utf-8'
if isinstance(string, bytes):
return string.decode(encoding)
raise ValueError('invalid string type: {}'.format(type(string)))
|
cb2e65ae8c1db9bdab1c876b9031ee4c108e2e7b
| 307,597 |
def _get_items( # nosec
get_items, items_key, params=None, next_token=None, next_token_key="NextToken"
):
"""
Recursive generic function call which concatenates results.
Returns a list of items from the same items_key in response.
If response contains a next token, get_items is called again, and items are concatenated.
Parameters
----------
get_items : function
function that returns items which may return a next token
items_key : string
key containing items
params : dict
params passed to get_items function
next_token : string
token returned by first get_items call
next_token_key : string
key from get_items response that may contain a next_token
Returns
-------
list
list of items returned by recursive get_items calls
"""
if not params:
params = {}
if next_token:
params[next_token_key] = next_token
response = get_items(**params)
items = response.get(items_key)
next_token = response.get(next_token_key)
if next_token:
items.extend(
_get_items(get_items, items_key, params, next_token, next_token_key)
)
return items
|
4ca53eb6550aaaf03b3d2df7b615e5197c7455c0
| 401,079 |
import requests
def fetch(url):
"""Fetch a URL
Arg:
url: A string in the URL form.
Returns:
The response in text
"""
resp = requests.get(url)
return resp.text
|
56148e3e6b08d85d90fcb3ba01b4d778833fd4ae
| 302,562 |
import math
def find_nproc(n, min_n_per_proc=25):
"""
Find number of processors needed for a given number grid points in WRF.
Parameters
----------
n : int
number of grid points
min_n_per_proc : int, optional
Minimum number of grid points per processor. The default is 25.
Returns
-------
int
number of processors.
"""
if n <= min_n_per_proc:
return 1
else:
return math.floor(n / min_n_per_proc)
|
7671b05298f8b0f982a4017313550941829c8297
| 437,667 |
def eq(a, b):
"""Check for equality between a and b.
Return boolean.
**** args ****
a, b:
python objects on which a test for equality will work
"""
if a == b:
return True
else:
return False
|
67fa355c4eb17fe4458f1f527338aec9b98f5f6d
| 535,016 |
def eval_dist_at_powseries(phi, f):
"""
Evaluate a distribution on a powerseries.
A distribution is an element in the dual of the Tate ring. The
elements of coefficient modules of overconvergent modular symbols
and overconvergent `p`-adic automorphic forms give examples of
distributions in Sage.
INPUT:
- ``phi`` - a distribution
- ``f`` - a power series over a ring coercible into a `p`-adic field
OUTPUT:
The value of ``phi`` evaluated at ``f``, which will be an element in the
ring of definition of ``f``
EXAMPLES::
sage: from sage.modular.btquotients.pautomorphicform import eval_dist_at_powseries
sage: R.<X> = PowerSeriesRing(ZZ,10)
sage: f = (1 - 7*X)^(-1)
sage: D = OverconvergentDistributions(0,7,10)
sage: phi = D(list(range(1,11)))
sage: eval_dist_at_powseries(phi,f)
1 + 2*7 + 3*7^2 + 4*7^3 + 5*7^4 + 6*7^5 + 2*7^7 + 3*7^8 + 4*7^9 + O(7^10)
"""
nmoments = phi.parent().precision_cap()
K = f.parent().base_ring()
if K.is_exact():
K = phi.parent().base_ring()
return sum(a * K(phi.moment(i))
for a, i in zip(f.coefficients(), f.exponents())
if i >= 0 and i < nmoments)
|
ada2a765ad594cd729414b3313a2aa25054cc5d8
| 189,381 |
def xy2i(cx,cy):
"""Translate chess square to integer coordinate"""
x="abcdefgh".index(cx)
y=int(cy)-1
return (7-x)*8+y
|
c7d7772a120384108ddea35c5462cc1db78ea40f
| 414,307 |
def _PickSymbol(best, alt, encoding):
"""Chooses the best symbol (if it's in this encoding) or an alternate."""
try:
best.encode(encoding)
return best
except UnicodeEncodeError:
return alt
|
ccc2289c0258fa4983cc7bf45a6d94d628eb7d13
| 226,387 |
def get_preferred_indices(y_pos, labels, preferred_sensors):
"""Get indices of preferred sensor sets in plot.
Args:
y_pos (list): list of y positions used for sensors in plot.
labels (list-like): sensor set labels associated with y_pos.
preferred_sensors (list-like): preferred sensor sets.
Returns:
indices (list): y positions associated with preferred sets.
"""
labels = list(labels)
indices = []
for sensor in preferred_sensors:
label_idx = labels.index(sensor)
indices.append(y_pos[label_idx])
return indices
|
2e83f1d4ef9dc62be093396d992033e95b5c9561
| 543,993 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.