content
stringlengths 39
9.28k
| sha1
stringlengths 40
40
| id
int64 8
710k
|
---|---|---|
from typing import Any
import pickle
def load_pickle(fpath: str) -> Any:
"""Load an arbitrary object from a pickled format. Note that no safety checking is performed.
Args:
fpath (str): Path to the pickled object to load.
Returns:
Any: The object as hydrated from disk.
"""
with open(fpath, 'rb') as fp:
return pickle.load(fp) | 9e8430d9d37ef62a9e146832a53dedd2c80daed0 | 116,324 |
def _test_exception(exc, func, *data):
"""Validate that func(data) raises exc"""
try:
func(*data)
except exc:
return True
except:
pass
return False | 2ee6926ef9233a78dea7731fab4d05027e4dbdf6 | 259,509 |
def split_num(num, n):
"""
Divide num into m=min(n, num) elements x_1, ...., x_n, where x_1, ..., x_n >= 1 and max_{i,j} |x_i - x_j| <= 1
"""
n = min(num, n)
min_steps = num // n
splits = []
for i in range(n):
if i < num - min_steps * n:
splits.append(min_steps + 1)
else:
splits.append(min_steps)
assert sum(splits) == num
return n, splits | bbe69833b829dea8ca62f1b7646ad53eb8cebc80 | 593,252 |
def fliplr_joints(joints_3d, joints_3d_visible, img_width, flip_pairs):
"""Flip human joints horizontally.
Note:
num_keypoints: K
Args:
joints_3d (np.ndarray([K, 3])): Coordinates of keypoints.
joints_3d_visible (np.ndarray([K, 1])): Visibility of keypoints.
img_width (int): Image width.
flip_pairs (list[tuple()]): Pairs of keypoints which are mirrored
(for example, left ear -- right ear).
Returns:
tuple: Flipped human joints.
- joints_3d_flipped (np.ndarray([K, 3])): Flipped joints.
- joints_3d_visible_flipped (np.ndarray([K, 1])): Joint visibility.
"""
assert len(joints_3d) == len(joints_3d_visible)
assert img_width > 0
joints_3d_flipped = joints_3d.copy()
joints_3d_visible_flipped = joints_3d_visible.copy()
# Swap left-right parts
for left, right in flip_pairs:
joints_3d_flipped[left, :] = joints_3d[right, :]
joints_3d_flipped[right, :] = joints_3d[left, :]
joints_3d_visible_flipped[left, :] = joints_3d_visible[right, :]
joints_3d_visible_flipped[right, :] = joints_3d_visible[left, :]
# Flip horizontally
joints_3d_flipped[:, 0] = img_width - 1 - joints_3d_flipped[:, 0]
joints_3d_flipped = joints_3d_flipped * joints_3d_visible_flipped
return joints_3d_flipped, joints_3d_visible_flipped | c9c4586fd8aa26bd5cd88aaf6f052192b8ef43a9 | 196,712 |
import math
def vector_from_wind_dir(wind_dir_degree, wind_speed=1.0):
"""
Return vector given a wind direction and wind speed
Wind dir = 0.0 -> [0.0,-1.0,0.0]
Wind dir = 90.0 -> [-1.0,0.0,0.0]
Wind dir - Meteorological wind direction
(direction from which wind is blowing)
u -> Zone Velocity (Towards East)
v -> Meridional Velocity (Towards North)
"""
return [
-wind_speed * math.sin(math.radians(wind_dir_degree)),
-wind_speed * math.cos(math.radians(wind_dir_degree)),
0.0,
] | 2d39d6ba5ee80c215c4cd4041a97f435a47289c9 | 518,137 |
def swapaxes(a, axis1, axis2):
"""
Interchange two axes of an array.
Parameters
----------
a : array_like
Input array.
axis1 : int
First axis.
axis2 : int
Second axis.
Returns
-------
a_swapped : ndarray
If `a` is an ndarray, then a view of `a` is returned; otherwise a new
array is created.
See Also
--------
numpy.swapaxes
Availability
--------
Multiple GPUs, Multiple CPUs
"""
return a.swapaxes(axis1, axis2) | bbf8e4688f0d2adac93213efd8a55476a0aeb8e3 | 239,332 |
def parse_parameters(val_type, val):
"""
Helper function to convert a Vasprun parameter into the proper type.
Boolean, int and float types are converted.
Args:
val_type: Value type parsed from vasprun.xml.
val: Actual string value parsed for vasprun.xml.
"""
if val_type == "logical":
return val == "T"
elif val_type == "int":
return int(val)
elif val_type == "string":
return val.strip()
else:
return float(val) | 829432c5f70c2de3ccb9c9de51e49ad3a5f1261f | 531,954 |
import re
def convert_remote_git_to_https(source):
"""
Accepts a source git URL in ssh or https format and return it in a normalized
https format:
- https protocol
- no trailing /
:param source: Git remote
:return: Normalized https git URL
"""
url = re.sub(
pattern=r'[^@]+@([^:/]+)[:/]([^\.]+)',
repl='https://\\1/\\2',
string=source.strip(),
)
return re.sub(string=url, pattern=r'\.git$', repl='').rstrip('/') | 0086b69a3e25992247580b2b7b7004632dde22d2 | 133,347 |
from pathlib import Path
def root_module_path() -> Path:
"""Return absolute root module path.
Returns
-------
:class:`pathlib.Path`
Absolute root module path.
"""
return Path(__file__).resolve().parents[1] | 48986dfde811819ae037318e9f4e2b21300fda25 | 82,386 |
def GetLegacySitelinksForCampaign(campaign_extension_service, campaign_id):
"""Get legacy sitelinks for a campaign.
Args:
campaign_extension_service: The CampaignAdExtensionServiceInterface
instance.
campaign_id: ID of the campaign for which legacy sitelinks are retrieved.
Returns:
The CampaignAdExtension that contains the legacy sitelinks, or None if there
are no legacy sitelinks in this campaign.
"""
# Filter the results for specified campaign id.
campaign_predicate = {
'operator': 'EQUALS',
'field': 'CampaignId',
'values': [campaign_id]
}
# Filter the results for active campaign ad extensions. You may add
# additional filtering conditions here as required.
status_predicate = {
'operator': 'EQUALS',
'field': 'Status',
'values': ['ACTIVE']
}
# Filter for sitelinks ad extension type.
type_predicate = {
'operator': 'EQUALS',
'field': 'AdExtensionType',
'values': ['SITELINKS_EXTENSION']
}
# Create the selector.
selector = {
'fields': ['AdExtensionId', 'DisplayText', 'DestinationUrl'],
'predicates': [campaign_predicate, status_predicate, type_predicate]
}
page = campaign_extension_service.get(selector)[0]
if 'entries' in page and page['entries']:
return page['entries'][0]
else:
return None | eb64480ac29e1e9b6585bb39fc6095a2b7bd5802 | 366,713 |
def mean(s):
"""Returns the arithmetic mean of a sequence of numbers s.
>>> mean([-1, 3])
1.0
>>> mean([0, -3, 2, -1])
-0.5
"""
# BEGIN Question 1
assert len(s) > 0
return sum(s) / len(s)
# END Question 1 | 4ef993046891d480bbb40f1eef49dfa54440f774 | 242,096 |
import six
def validate_hatch(s):
"""
Validate a hatch pattern.
A hatch pattern string can have any sequence of the following
characters: ``\\ / | - + * . x o O``.
"""
if not isinstance(s, six.text_type):
raise ValueError("Hatch pattern must be a string")
unique_chars = set(s)
unknown = (unique_chars -
set(['\\', '/', '|', '-', '+', '*', '.', 'x', 'o', 'O']))
if unknown:
raise ValueError("Unknown hatch symbol(s): %s" % list(unknown))
return s | 4ddf056dab2681759a462005effc4ae5488a4461 | 707,950 |
def get_d_pct(a, b):
"""Percentage difference between two values."""
d = float(abs(a - b))
avg = float((a + b) / 2)
return round(d / avg * 100) | ab181dbd36bdb28ed7fd8643981e41d00c1902d6 | 296,287 |
def get_thumbnail_size(image_size, thumbnail_height):
"""
Computes the size of a thumbnail
:param image_size: original image size
:param thumbnail_height: thumbnail height
:return: thumbnail size tuple
"""
width = round((float(thumbnail_height) / image_size[1]) * image_size[0])
return width, thumbnail_height | 6bd516279677c247adbe673ca47f7bc8ee74e651 | 399,381 |
def list_materials(client, file_=None, material=None):
"""List materials on a part.
Args:
client (obj):
creopyson Client.
`file_` (str, optional):
File name. Defaults is currently active model.
material (str, optional):
Material name pattern.
Wildcards allowed.
Defaults to None is all materials.
Returns:
list: List of materials in the part.
"""
data = {}
if file_ is not None:
data["file"] = file_
else:
active_file = client.file_get_active()
if active_file:
data["file"] = active_file["file"]
if material is not None:
data["material"] = material
return client._creoson_post("file", "list_materials", data, "materials") | bcd70f4003f4b7499bf939f1d3f9810558f6c719 | 634,104 |
def bool2str(x):
"""Return Fortran bool string for bool input."""
return '.true.' if x else '.false.' | a2c5e500e7321cfff7bc3ff7a6d87aea28362a99 | 370,582 |
from typing import Tuple
import math
def to_proper(numerator: int, denominator: int) -> Tuple[int, int]:
"""Converts `numerator` and `denominator` to their simplest ratio.
Examples:
>>> to_proper(7, 28)
(1, 4)
>>> to_proper(-36, 54)
(-2, 3)
>>> to_proper(3, 4)
(3, 4)
>>> to_proper(0, 0)
(0, 0)
"""
if numerator == 0:
if denominator == 0:
return 0, 0
return 0, 1
if denominator == 0:
if numerator > 0:
return 1, 0
return -1, 0
gcd = math.gcd(numerator, denominator)
assert gcd > 0
assert (numerator / gcd).is_integer()
assert (denominator / gcd).is_integer()
sign = numerator * denominator / abs(numerator * denominator)
return int(sign * abs(numerator) / gcd), int(abs(denominator) / gcd) | edd0c3d670cef0ba9c2eb17b4e0920fb2e614d07 | 240,863 |
def optStrajAdvHelp(strajDists, strajCov, r, c3):
""" Computes subtrajectory of a trajectory with maximum coverage cost ratio
Args:
strajDists: list having subtraj-distance pairs of a trajectory.
strajCov: dict storing points of subtrajs.
r (float): guess coverage-cost ratio.
c3 : parameter of greedy algorithm.
Returns:
(subtraj, float) or (None,None).
"""
temp, stra, dista = 0, None, None
for i in range(len(strajDists)):
straj, dist = strajDists[i][0], strajDists[i][1]
cov = strajCov[straj]
if temp < cov - c3 * r * dist:
temp = cov - c3 * r * dist
stra, dista = straj, dist
return (stra, dista) | 6083bfd008418540dc1d14de0883b9e96cc371c2 | 180,260 |
def analysis_nindex_usages(analysis):
"""
Returns a dictionary of namespace usages by name.
'nindex' stands for 'namespace index'.
"""
return analysis.get("nindex_usages", {}) | 55defbe685e793df3a8377f6c030a653626b75db | 410,601 |
def time_to_num(time):
"""
time: a string representing a time, with hour and minute separated by a colon (:)
Returns a number
e.g. time_to_num(9:00) -> 9
time_to_num(21:00) -> 21
time_to_num(12:30) -> 12.5
"""
time_comps = time.split(":")
if int(time_comps[1]) == 0:
return int(time_comps[0])
return int(time_comps[0]) + int(time_comps[1])/60 | 77512320480404d5ea0d3c9490edc41ad3ad114b | 405,601 |
from typing import Any
def isclass(obj: Any) -> bool:
"""Determine if an object is a `class` object
>>> isclass(type)
True
>>> isclass(object)
True
>>> isclass({})
False
"""
return issubclass(type(obj), type) | 69536bc72a03a4a15900279b00e58a2a7e306a34 | 384,243 |
def needs_binary_relocation(m_type, m_subtype):
"""
Check whether the given filetype is a binary that may need relocation.
"""
if m_type == 'application':
if (m_subtype == 'x-executable' or m_subtype == 'x-sharedlib' or
m_subtype == 'x-mach-binary'):
return True
return False | 3abf8ea69201b7fdaa4ab6a104f131ca8add4ea8 | 500,216 |
import re
def _is_edl_hostname(hostname: str) -> bool:
"""
Determine if a hostname matches an EDL hostname.
Args:
hostname: A fully-qualified domain name (FQDN).
Returns:
True if the hostname is an EDL hostname, else False.
"""
edl_hostname_pattern = r'.*urs\.earthdata\.nasa\.gov$'
return re.fullmatch(edl_hostname_pattern, hostname, flags=re.IGNORECASE) is not None | 8251cc40964993fe81587774757da7fa773ba02c | 427,593 |
def split_by_3(x):
"""
Method to separate bits of a 32-bit integer
by 3 positions apart, using the magic bits
https://www.forceflow.be/2013/10/07/morton-encodingdecoding-through-bit-interleaving-implementations/
:param x: 32-bit integer
:return: x with bits separated
"""
# we only look at 21 bits, since we want to generate
# a 64-bit code eventually (3 x 21 bits = 63 bits, which
# is the maximum we can fit in a 64-bit code)
x &= 0x1fffff # only take first 21 bits
# shift left 32 bits, OR with self, and 00011111000000000000000000000000000000001111111111111111
x = (x | (x << 32)) & 0x1f00000000ffff
# shift left 16 bits, OR with self, and 00011111000000000000000011111111000000000000000011111111
x = (x | (x << 16)) & 0x1f0000ff0000ff
# shift left 8 bits, OR with self, and 0001000000001111000000001111000000001111000000001111000000000000
x = (x | (x << 8)) & 0x100f00f00f00f00f
# shift left 4 bits, OR with self, and 0001000011000011000011000011000011000011000011000011000100000000
x = (x | (x << 4)) & 0x10c30c30c30c30c3
# shift left 2 bits, OR with self, and 0001001001001001001001001001001001001001001001001001001001001001
x = (x | (x << 2)) & 0x1249249249249249
return x | c00e614983df0851172087034267417c7928775c | 216,893 |
def rtiOutputFixture(rtiConnectorFixture):
"""
This `pytest fixture <https://pytest.org/latest/fixture.html>`_
creates a session-scoped :class:`rticonnextdds_connector.Output` object
which is returned everytime this fixture method is referred.
The initialized Output object is cleaned up at the end
of a testing session.
``MyPublisher::MySquareWriter`` `datawriter
<https://community.rti.com/static/documentation/connext-dds/5.2.3/doc/api/connext_dds/api_cpp2/classdds_1_1pub_1_1DataWriter.html>`_ in
``test/xml/TestConnector.xml`` `application profile
<https://community.rti.com/rti-doc/510/ndds.5.1.0/doc/pdf/RTI_CoreLibrariesAndUtilities_XML_AppCreation_GettingStarted.pdf>`_
is used for initializing the Output object.
:param rtiConnectorFixture: :func:`rtiConnectorFixture`
:type rtiConnectorFixture: `pytest.fixture <https://pytest.org/latest/builtin.html#_pytest.python.fixture>`_
:returns: session-scoped Output object for testing
:rtype: :class:`rticonnextdds_connector.Output`
"""
return rtiConnectorFixture.getOutput("MyPublisher::MySquareWriter") | 5cc9f6447a0312021cb5e949c09924aefcda49ef | 559,063 |
from datetime import datetime
def now() -> str:
"""String ISO Timestamp of current date"""
return datetime.now().strftime("%Y-%m-%d") | cd506197a440a0ad7217ec71903d7c32c1f414fd | 321,361 |
def convert(number):
"""
Converts a number into string based on rain drops methodj
Pling = if 3 is a factor
Plang = if 5 is a factor
Plong = if 7 is a factor
the number itself if none of the above are factors.
"""
raindrops = ''
r_3 = divmod(number, 3)[1]
r_5 = divmod(number, 5)[1]
r_7 = divmod(number, 7)[1]
if r_3 != 0 and r_5 != 0 and r_7 != 0:
return str(number)
if r_3 == 0:
raindrops += 'Pling'
if r_5 == 0:
raindrops += 'Plang'
if r_7 == 0:
raindrops += 'Plong'
return raindrops | d84685437f623ddbb5b776a5dd0bb92c56fe59d3 | 556,613 |
def easy_or(b1, b2):
"""Takes two booleans and returns their OR"""
return b1 or b2 | 0ebdc18c4431a6a3c5e60f5f373b258e18980f3f | 311,232 |
import io
import json
def load_json_file(json_file):
"""
Load json file
:param json_file: json file path
:return: file content
"""
with io.open(json_file, encoding='utf-8') as f:
json_content = json.load(f)
return json_content | d5eafad4fa5d636e31240a3503699f490cbea5fc | 611,565 |
def parse(entrypoint):
"""
Parse an entrypoint string
Args:
entrypoint (str): The entrypoint string to parse.
Returns:
name (str): The name of the entrypoint
package (str): The package path to access the entrypoint function
func (str): The name of the function
"""
equals = entrypoint.count('=')
colons = entrypoint.count('=')
assert equals == 1 and colons == 1, RuntimeError(
'Invalid entrypoint format: "{}" Expected: '
'"alias = package.module:function"'
.format(entrypoint)
)
name, path = map(str.strip, entrypoint.split('='))
package, func = path.split(':')
return name, package, func | adb22aa44b559dbc833772266b8c19baee86253a | 531,659 |
def around(number):
"""
Truncate a float to the third decimal
"""
if number is not None:
return int(number * 1000) / 1000.
else:
return None | 9f011cf7f7a0b0886aa4bd3a98674e9bb1326200 | 598,778 |
from typing import Callable
from typing import Optional
def inline_try(func: Callable) -> Optional[Exception]:
"""
Try to execute an inline function without throwing an error. Useful when the Exception thrown is trivial.
:param func: A function to call.
:return: None if no exception is thrown or the Exception object thrown.
"""
try:
func()
return None
except Exception as e:
return e | 4e5205f822c4f3243efbdf877a1b652de22b2c8e | 394,064 |
def remove_duplicate_info(data):
"""Convert duplicates information that can be found in other columns, into 'No'.
Args:
data ([pd.DataFrame]): Dataframe to be wrangled.
"""
# replace 'No phone service'
data["MultipleLines"] = data["MultipleLines"].replace({"No phone service": "No"})
# replace 'No internet service'
for col in [
"OnlineSecurity",
"OnlineBackup",
"DeviceProtection",
"TechSupport",
"StreamingTV",
"StreamingMovies",
]:
data[col] = data[col].replace({"No internet service": "No"})
return data | ad4f72ebc3849e0553a65ffb8975052d4eea6828 | 466,322 |
def Sort_Points(x_values, y_values, error):
"""
Combine three arrays and sorts by ascending values of the first.
Args:
x_values (1darray):
Array of x-values. This array is the one which sorting will be based.
Each index of this array is related to the same index value of the other two.
y_values (1darray):
Array of y-values. Each index of this array is related to the same index
value of the other two.
error (1darray):
Array of error values. Each index of this array is related to the same
index value of the other two.
Returns:
x_val (1darray):
x_values array sorted in ascending order.
y_val (1darray):
y_values array sorted based on new index order of x_val.
errors (1darray):
error array sorted based on new index order of x_val.
"""
to_return = []
# If/Else statement to confirm that the arrays are the same length. Print error message if not.
if len(x_values) == len(y_values) == len(error):
for j in range(len(x_values)):
file_point = (((x_values[j])), (y_values[j]), (error[j]))
to_return.append(file_point)
to_return.sort()
x_val = [x[0] for x in to_return]
y_val = [y[1] for y in to_return]
errors = [y[2] for y in to_return]
else:
print('the given arrays are of different lengths')
x_val = False
y_val = False
errors = False
return(x_val, y_val, errors) | 190c6303f5f9c91a7654e65f66795aeae32ffacb | 464,714 |
def format_percent(d, t):
"""
Format a value as a percent of a total.
"""
return '{:.1%}'.format(float(d) / t) | 9c3e871191e2757436c466c2560810b80a7880dc | 618,452 |
import importlib
def _json_convert_from_dict(obj_dict: dict) -> object:
"""
Takes in a dict and returns an object associated with the dict.
The function uses the "__module__" and "__class__" metadata in the dictionary to know which object to create.
Parameters
----------
obj_dict : dict
The object dictionary to convert to an object
Returns
-------
obj : object
The object
"""
if "__class__" in obj_dict and "__module__" in obj_dict:
class_name = obj_dict.pop("__class__")
module_name = obj_dict.pop("__module__")
module = importlib.import_module(module_name)
obj_class = getattr(module, class_name)
obj = obj_class(**obj_dict)
else:
obj = obj_dict
return obj | ddf368f14aaf8aca3f4a534c55d870df1393f3b6 | 541,525 |
import math
def is_prime(k: int) -> bool:
"""
Determine if a number is prime
>>> is_prime(10)
False
>>> is_prime(11)
True
"""
if k < 2 or k % 2 == 0:
return False
elif k == 2:
return True
else:
for x in range(3, int(math.sqrt(k) + 1), 2):
if k % x == 0:
return False
return True | 3d3ee9a33ee4bf8ad85d9bb9f7afa32032f7218b | 372,705 |
def parse_var(s):
"""Returns (key, value) tuple from string with equals sign with the portion before the first equals sign as the key
and the rest as the value.
Args:
s: string to parse
Returns: Tuple of key and value
"""
items = s.split("=")
key = items[0].strip() # we remove blanks around keys, as is logical
value = ""
if len(items) > 1:
# rejoin the rest:
value = "=".join(items[1:])
return key, value | 8e6d63fde980435e84bb1d316ced95fc7ea383bb | 453,273 |
def compare_and_get_name(a, b):
"""
If both a & b have name attribute, and they are
same return the common name.
Else, return either one of the name of a or b,
whichever is present.
Parameters
----------
a : object
b : object
Returns
-------
name : str or None
"""
a_has = hasattr(a, "name")
b_has = hasattr(b, "name")
if a_has and b_has:
if a.name == b.name:
return a.name
else:
return None
elif a_has:
return a.name
elif b_has:
return b.name
return None | d3c2da2a1554d83d9a2b0640a050d209d7919295 | 186,396 |
def forcedir(path):
"""Ensure the path ends with a trailing /
:param path: An FS path
>>> forcedir("foo/bar")
'foo/bar/'
>>> forcedir("foo/bar/")
'foo/bar/'
"""
if not path.endswith('/'):
return path + '/'
return path | 968db047d604eb63cdbd0955a7da20479c40fc6a | 592,183 |
def edge_count(adjList):
"""Compute number of edges in a graph from its adjacency list"""
edges = {}
for id, neigh in enumerate(adjList):
for n in neigh:
edges[max(n, id), min(n, id)] = id
return len(edges) | 760b12e3074d6447d1173e4ac61ef35e91af3d21 | 486,426 |
def is_function(var):
"""
Test if variable is function (has a __call__ attribute)
:return: True if var is function, False otherwise.
:rtype: bol
"""
return hasattr(var, '__call__') | 1cd3d4bb70b1568a60c4f51c04652df12a967292 | 58,362 |
def colon_based_id_to_vep_id(colon_id):
"""Converts a colon-based identifier to VEP compatible one. Example: '15:7237571:C:T' → '15 7237571 . C T'"""
id_fields = colon_id.split(':')
assert len(id_fields) == 4, 'Invalid colon-based identifier supplied (should contain exactly 4 fields)'
return '{} {} . {} {}'.format(*id_fields) | 208b9690f77e015263eb207fce6d2db129a2fae5 | 127,171 |
def search_component(key, CACHET_IDS):
""" Searches the list of componets in cachet for the
component returned from alertmanager. If found it returns the component,
if not 9999 is returned.
"""
return CACHET_IDS.get(key, 9999) | 69eaa484cb4715fd891b43a00c027f3ea0deb3ef | 224,643 |
def transport_degree_factor(
temperature,
deadband_lower=15,
deadband_upper=20,
lower_degree_factor=0.5,
upper_degree_factor=1.6):
"""
Work out how much energy demand in vehicles increases due to heating and cooling.
There is a deadband where there is no increase.
Degree factors are % increase in demand compared to no heating/cooling fuel consumption.
Returns per unit increase in demand for each place and time
"""
dd = temperature.copy()
dd[(temperature > deadband_lower) & (temperature < deadband_upper)] = 0.
dT_lower = deadband_lower - temperature[temperature < deadband_lower]
dd[temperature < deadband_lower] = lower_degree_factor / 100 * dT_lower
dT_upper = temperature[temperature > deadband_upper] - deadband_upper
dd[temperature > deadband_upper] = upper_degree_factor / 100 * dT_upper
return dd | ea5d5128fa985ea566aefe8b0f7b5875878a9838 | 600,331 |
def quick_sort(arr):
"""Sort array of numbers with quicksort."""
if len(arr) == 1:
return arr
if len(arr) > 1:
pivot = arr[0]
left = 1
right = len(arr) - 1
while left <= right:
if arr[left] > pivot and arr[right] < pivot:
arr[left], arr[right] = arr[right], arr[left]
left += 1
right -= 1
elif arr[left] <= pivot and arr[right] < pivot:
left += 1
elif arr[left] > pivot and arr[right] >= pivot:
right -= 1
elif arr[left] <= pivot and arr[right] >= pivot:
left += 1
right -= 1
arr[0], arr[right] = arr[right], arr[0]
divider = right + 1
first = quick_sort(arr[:right])
second = quick_sort(arr[divider:])
return first + [arr[right]] + second
else:
return arr | 9f40258588967247379d50532dd62ec0588365b1 | 18,753 |
def get_text(doc, tag_id, value=False):
"""
beautifulsoup get_text() wrapper
优雅地处理 doc.find() 为 None的情况
:param doc: beautifulsoup doc
:param tag_id: tag id
:param value: 是否取tag中value属性的值
:return:
"""
res = doc.find(id=tag_id)
if res is not None:
if value:
if 'value' in res.attrs:
return res.attrs['value'].strip()
else:
# api.logger.warning('[-] tag: %s has no value attr.' % tag_id)
return ''
else:
return res.get_text()
else:
# api.logger.error('[-] doc has no such tag: %s.' % tag_id)
return '' | 774233ee3b2b53861659f5a22a00f864d9b2efdc | 521,356 |
def divide_lists(lst_numer, lst_denom):
"""
Divides each element of the nested list 'lst_numer' by 'lst_denom'.
The division is done by taking each element of 'lst_numer' and for each
index of that element, dividing the item at that index by the item at the
same index of 'lst_denom'. See example below:
>>> numer = [[1., 2.],
... [3., 4.]]
>>> denom = [0.5, 0.5]
>>> divide_lists(numer, denom)
[[2., 4.], [6., 8.]]
NOTE: It is assumed that each element of 'lst_numer' has the same length
as 'lst_denom' as shown in the dimensions of the arguments below.
Arguments:
lst_numer: nested list of list(dimensions N x M)
lst_denom: list of denominators(dimensions 1 x M)
Returns:
A new list formed by dividing each element of 'lst_numer' by
'lst_denom' according to the division process described above.
"""
indexes = range(len(lst_denom))
return [[n[i] / float(lst_denom[i]) for i in indexes] for n in lst_numer] | d040c159ca79eedfe74b5067affd67d42d928879 | 155,318 |
def calculate_enrichment(coverage_values):
"""Calculate TSS enrichment value for a dataset
Parameters
----------
coverage_values
iterable of tuples (tss_center_depth, flank_depth) per TSS
Returns
-------
float
the TSS enrichment value
"""
tss_depth, flank_depth = (sum(z) for z in zip(*coverage_values))
return tss_depth / flank_depth | 673ee0208dca03e10f92463d5d53c1be73341f0d | 630,244 |
def get_variables_used(string, variable_dict):
"""Returns what variables are used in the given string as a list."""
used_variables = []
for key in variable_dict:
temp_string = string.replace(key, "")
if temp_string != string:
used_variables.append(key)
string = temp_string
return used_variables | 0b242da05640617f8efca9521bbfe61ce17182dc | 110,012 |
from typing import List
from typing import Tuple
def get_range_directives_gatecharacterization(
fit_range_update_directives: List[str],
current_valid_ranges: List[Tuple[float, float]],
safety_voltage_ranges: List[Tuple[float, float]],
dV_stop: float = 0.1,
) -> Tuple[List[str], List[str]]:
"""Determines voltage range directives to update ranges for a subsequent
tuning stage iteration. It checks if the voltage range update directives
determined previously, e.g by a fit class, can be carried out based on the
supplied safety ranges.
Args:
fit_range_update_directives: Directives determined previously, such as
during fitting.
current_valid_ranges: Voltage range swept at previous iteration.
safety_voltage_ranges: Safety range of gate/voltage parameter swept.
dV_stop: Mininmal voltage difference between current and safety ranges
for current ranges to be changed. Default is 100mV.
Returns:
list: Range update directives, e.g. 'x more negative'.
list: Issues encountered, e.g. 'positive safety voltage reached'.
"""
safety_v_range = safety_voltage_ranges[0]
current_v_range = current_valid_ranges[0]
neg_range_avail = abs(current_v_range[0] - safety_v_range[0])
pos_range_avail = abs(current_v_range[1] - safety_v_range[1])
range_update_directives = []
issues = []
for update_directive in fit_range_update_directives:
if update_directive == "x more negative":
if neg_range_avail >= dV_stop:
range_update_directives.append("x more negative")
else:
issues.append("negative safety voltage reached")
elif update_directive == "x more positive":
if pos_range_avail >= dV_stop:
range_update_directives.append("x more positive")
else:
issues.append("positive safety voltage reached")
else:
raise KeyError("Unknown voltage range update directive.")
return range_update_directives, issues | c7b91804140c6b36f1ffae22e633b6512e05957f | 156,589 |
def _get_photos_by_attribute(photos, attribute, values, ignore_case):
"""Search for photos based on values being in PhotoInfo.attribute
Args:
photos: a list of PhotoInfo objects
attribute: str, name of PhotoInfo attribute to search (e.g. keywords, persons, etc)
values: list of values to search in property
ignore_case: ignore case when searching
Returns:
list of PhotoInfo objects matching search criteria
"""
photos_search = []
if ignore_case:
# case-insensitive
for x in values:
x = x.lower()
photos_search.extend(
p
for p in photos
if x in [attr.lower() for attr in getattr(p, attribute)]
)
else:
for x in values:
photos_search.extend(p for p in photos if x in getattr(p, attribute))
return list(set(photos_search)) | 84ac207ff9b5915f0404cf0701d5985e7df2af9b | 506,428 |
def embedded(classes):
"""get embedded property (e-*) names
"""
return [c.partition("-")[2] for c in classes if c.startswith("e-")] | 862c6bd4f9ccbb05330950fbf284760c962da9de | 534,208 |
from typing import Iterator
def second(itr: Iterator[float]) -> float:
"""Returns the second item in an iterator."""
next(itr)
return next(itr) | 74e85436ed9b763f262c94e3898455bd24d75028 | 686,837 |
def palette_name(name, length):
"""Create a palette name like CubeYF_8"""
return '{0}_{1}'.format(name, length) | 1c06b9e6169558c479e3e350c5f2151519cf3ab0 | 266,145 |
def item(self, drive=None, id_=None, path=None):
"""Gets an item given the specified (optional) drive,
(optional) id_, and (optional) path
Args:
drive (str): The drive that you want to use
id_ (str): The id_ of the item to request
path (str): The path of the item to request
Returns:
:class:`ItemRequestBuilder<msgraph.requests.item_request_builder.ItemRequestBuilder>`:
A request builder for an item given a path or id_
"""
if id_ is None and path is None:
raise ValueError("Either 'path' or 'id_' must be specified")
elif id_ is not None and path is not None:
raise ValueError("Only one of either 'path' or 'id_' can be specified")
drive_builder = self.drives[drive] if drive else self.drive
if path:
return drive_builder.item_by_path(path)
elif id_:
return drive_builder.items[id_] | 55f82f55a0ead8557ee9a5b53884259a906d044e | 151,976 |
def minutes_readable(minutes):
"""
convert the duration in minutes to a more readable form
Args:
minutes (float | int): duration in minutes
Returns:
str: duration as a string
"""
if minutes <= 60:
return '{:0.0f} min'.format(minutes)
elif 60 < minutes < 60 * 24:
minutes /= 60
if minutes % 1:
fmt = '{:0.1f} h'
else:
fmt = '{:0.0f} h'
return fmt.format(minutes)
elif 60 * 24 <= minutes:
minutes /= 60 * 24
if minutes % 1:
fmt = '{:0.1f} d'
else:
fmt = '{:0.0f} d'
return fmt.format(minutes)
else:
return str(minutes) | 9115070cb17786cbb866d7849ad2b261ad6652e6 | 571,031 |
def writeConfig(xyTuple):
"""Creates a config file (config.py) and writes 4 values into it
Arguments:
xyTuple: a tuple of structure (xMin, xMax, yMin, yMax)
"""
outfile = open("config.py","w")
outfile.write("X_MIN="+str(xyTuple[0])+"\n")
outfile.write("X_MAX="+str(xyTuple[1])+"\n")
outfile.write("Y_MIN="+str(xyTuple[2])+"\n")
outfile.write("Y_MAX="+str(xyTuple[3]))
outfile.close()
return None | 1c792874e0e07575f37843e133d62b094c33c35f | 405,710 |
def GetArgTypeStr(_n):
"""Function to return the string representation of the PyTango.ArgType value from
its integer code."""
_list = ['Void', 'Boolean', 'Short', 'Long', 'Float', 'Double', 'UShort', 'ULong', 'String', \
'CharArray', 'ShortArray', 'LongArray', 'FloatArray', 'DoubleArray', 'UShortArray', \
'ULongArray', 'StringArray', 'LongStringArray', 'DoubleStringArray', 'DevState', \
'ConstDevState', 'DevVarBooleanArray', 'DevUChar', 'DevLong64', 'DevULong64',\
'DevVarLong64Array', 'DevVarULong64Array', 'Int', 'DevEncoded']
return _list[_n] | 211c8e7013ec92c5758f67b87ff21c987531a1b7 | 130,173 |
def _gen_gce_as_policy(as_params):
"""
Take Autoscaler params and generate GCE-compatible policy.
:param as_params: Dictionary in Ansible-playbook format
containing policy arguments.
:type as_params: ``dict``
:return: GCE-compatible policy dictionary
:rtype: ``dict``
"""
asp_data = {}
asp_data['maxNumReplicas'] = as_params['max_instances']
if 'min_instances' in as_params:
asp_data['minNumReplicas'] = as_params['min_instances']
if 'cool_down_period' in as_params:
asp_data['coolDownPeriodSec'] = as_params['cool_down_period']
if 'cpu_utilization' in as_params and 'target' in as_params[
'cpu_utilization']:
asp_data['cpuUtilization'] = {'utilizationTarget':
as_params['cpu_utilization']['target']}
if 'load_balancing_utilization' in as_params and 'target' in as_params[
'load_balancing_utilization']:
asp_data['loadBalancingUtilization'] = {
'utilizationTarget':
as_params['load_balancing_utilization']['target']
}
return asp_data | 0fba5afeae0967ea37a2077abdcc2d32341795cb | 462,906 |
def eliminate_suffix(v, w):
"""
Removes suffix w from the input word v
If v = uw (u=prefix, w=suffix),
u = v w-1
Parameters:
-----------------------------------
v: str
A (sub)word
w: str
The suffix to remove
Returns:
-----------------------------------
u: str
(sub)word with the suffix removed
"""
u = v.rstrip(w)
return(u) | 5ff4cbfb6e82e20dfe05ef26f4a3503f5d05ab3c | 169,734 |
from typing import Tuple
import re
def check_tvm_version(curr: str, min_req: str) -> bool:
"""Check if the current TVM version satisfies the minimum requirement.
Parameters
----------
curr: str
The current version.
min_req: str
The minimum requirement version.
Returns
-------
check: bool
Return true if the current version satisfies the minimum requirement.
"""
def parse_version(ver_str: str) -> Tuple[Tuple[int, int, int], bool]:
"""Parse TVM version to a tuple-3.
Parameters
----------
ver_str: str
The TVM version string.
Returns
-------
ver: Tuple[Tuple[int, int, int], bool]
(3-way version number, is a release version)
"""
# The release version such as 0.8.0.
tokens = re.search(r"(\d|)\.(\d+)\.(\d+)", ver_str)
if tokens is not None:
return ((int(tokens.group(1)), int(tokens.group(2)), int(tokens.group(3))), True)
# The dev version such as 0.8.dev0 or 0.8.dev94+g0d07a329e.
tokens = re.search(r"(\d|)\.(\d+)\.dev(\d+)\+*.*", ver_str)
if tokens is not None:
return ((int(tokens.group(1)), int(tokens.group(2)), int(tokens.group(3))), False)
raise RuntimeError("Unrecognized TVM version: %s" % ver_str)
curr_ver, curr_rel = parse_version(curr)
req_ver, req_rel = parse_version(min_req)
# Major version.
if curr_ver[0] < req_ver[0]:
return False
if curr_ver[0] > req_ver[0]:
return True
# Miner version.
if curr_ver[1] < req_ver[1]:
return False
if curr_ver[1] > req_ver[1]:
return True
if curr_rel and not req_rel:
# Current version is "release" but the target version is "dev".
return True
if not curr_rel and req_rel:
# Current version is "dev" but the target version is "release".
return False
# Both are "dev" versions.
return curr_ver[2] >= req_ver[2] | f99d7da7212a5c96b186681ceb4b03dc47f2cb26 | 102,432 |
def SLICE(array, n, position=None):
"""
Returns a subset of an array.
See https://docs.mongodb.com/manual/reference/operator/aggregation/slice/
for more details
:param array: Any valid expression as long as it resolves to an array.
:param n: Any valid expression as long as it resolves to an integer.
:param position: Optional. Any valid expression as long as it resolves to an integer.
:return: Aggregation operator
"""
return {'$slice': [array, position, n]} if position is not None else {'$slice': [array, n]} | 98feb51282923b1d4d637695579f2fe3f9654713 | 506,302 |
def decode(value):
"""
Decode UTF8.
:param bytes value: an encoded content
:return: the decoded content
:rtype: str
"""
return value.decode('utf-8') | a276f61138d02939cfc78fe808892b7d8ed3f87e | 583,091 |
def get_action_space(environment_spec):
"""Get action space associated with environment spec.
Args:
environment_spec: EnvironmentSpec object
Returns:
OpenAi Gym action space
"""
return environment_spec.env_lambda().action_space | fa2608782ca69e62cf68c055213f15e8e9da0cfd | 371,120 |
from typing import Tuple
def _calculate_division(
dividend: int,
divisor: int,
max_decimal_places: int = int(1e6)
) -> Tuple[str, str, str]:
"""For given integer `dividend` and `divisor`, calculate the division `dividend / divisor`.
The decimal fraction part is made up of a fixed starting sequence and a recurring cycle.
Example:
1/6 (dividend=1, divisor=6) -> ('0', '1', '6') meaning 0.166666...
"""
integer_part = str(dividend // divisor)
remainder = dividend % divisor
idx = max_decimal_places
decimal_fraction_parts = []
while remainder != 0 and len(decimal_fraction_parts) < max_decimal_places:
remainder *= 10
decimal_place = str(remainder // divisor)
remainder %= divisor
try:
idx = decimal_fraction_parts.index((decimal_place, remainder))
break
except ValueError:
decimal_fraction_parts.append((decimal_place, remainder))
decimal_fraction = ''.join(str(decimal_place) for decimal_place, _ in decimal_fraction_parts)
decimal_fraction_start = decimal_fraction[:idx]
decimal_fraction_recurring_cycle = decimal_fraction[idx:]
return integer_part, decimal_fraction_start, decimal_fraction_recurring_cycle | 6bffaf9291af22709d77f5658622a4c987df21f9 | 238,430 |
def addKwdArgsToSig(sigStr, kwArgsDict):
""" Alter the passed function signature string to add the given kewords """
retval = sigStr
if len(kwArgsDict) > 0:
retval = retval.strip(' ,)') # open up the r.h.s. for more args
for k in kwArgsDict:
if retval[-1] != '(': retval += ", "
retval += str(k)+"="+str(kwArgsDict[k])
retval += ')'
retval = retval
return retval | e859c27c14caaf755aeaaa963d10eb75e99a89f6 | 421,073 |
def x12_270_oneline_message() -> str:
"""A x12 270 transaction in one line without carriage returns/new line characters"""
return '{"x12": "ISA*00* *00* *ZZ*890069730 *ZZ*154663145 *200929*1705*|*00501*000000001*0*T*:~GS*HS*890069730*154663145*20200929*1705*0001*X*005010X279A1~ST*270*0001*005010X279A1~BHT*0022*13*10001234*20200929*1319~HL*1**20*1~NM1*PR*2*UNIFIED INSURANCE CO*****PI*842610001~HL*2*1*21*1~NM1*1P*2*DOWNTOWN MEDICAL CENTER*****XX*2868383243~HL*3*2*22*0~TRN*1*1*1453915417~NM1*IL*1*DOE*JOHN****MI*11122333301~DMG*D8*19800519~DTP*291*D8*20200101~EQ*30~SE*13*0001~GE*1*0001~IEA*1*000010216~"}' | dbaedad04a7d7c888c1c235872f3285f4f830dfd | 405,373 |
def inline(s, fmt):
"""Wrap string with inline escape"""
return "`\u200B{}\u200B`".format(fmt.format(s)) | 3f07a4f55e60c763a10956c9ac52314b6958eca8 | 699,557 |
def nombre_aretes(matrice):
"""Renvoie le nombre d'arêtes dans le graphe"""
nb_aretes = 0
for i in range(len(matrice)):
for j in range(len(matrice)):
if matrice[i][j] == 1:
nb_aretes += 1
return nb_aretes // 2 | 13262de15fd2d5a8018a63e8dabb529169d5c35a | 118,156 |
from typing import Callable
def is_such_at(func: Callable[[str], bool], index: int, text: str) -> bool:
"""
Whether a character at a string is of a certain class.
:param func: a function
:param index: a number indicating which character in the text
:param text: a string
:return: whether it is true
"""
return index < len(text) and func(text[index]) | 41eb6b3fd9076ddfc1bb9a0da515aae1b3d1a905 | 137,890 |
def avg_ci_data(data, axis=0):
"""Average the data along the given dimension, and calculate the 95
percent confidence interval. Return the avg, ci arrays."""
data_avg = data.mean(axis=axis)
data_std = data.std(axis=axis, ddof=1)
data_ci = data_std / data.shape[axis]**0.5 * 1.96
return data_avg, data_ci | 3ebc541d14e7b300f5acde0ff1741e0675a0a103 | 398,426 |
def DeveloperAPI(obj):
"""Annotation for documenting developer APIs.
Developer APIs are lower-level methods explicitly exposed to advanced Ray
users and library developers. Their interfaces may change across minor
Ray releases.
Examples:
>>> @DeveloperAPI
>>> def func(x):
>>> return x
"""
if not obj.__doc__:
obj.__doc__ = ""
obj.__doc__ += (
"\n DeveloperAPI: This API may change across minor Ray releases.")
return obj | e78bc7cecb46e607dec199a300962f8899ed1f3b | 378,608 |
def capitalize_word(word):
"""
Capitalize the first letter of the word.
:param word: a string input.
:return: the word in title form.
"""
return word.title() | 0f5b9dec962717bac2c867551b093f8204a61737 | 558,683 |
def _get_images(container_group):
"""Get all images of a container group. """
containers = container_group.get('containers')
if containers is not None and containers:
images = set([])
for container in containers:
images.add(container['image'])
return ','.join(images)
return None | c7f3fb3ad26beaf543067b0e25b96888bc0412b7 | 142,376 |
import hashlib
def genSha256(file_content):
"""
Generates SHA256 hash of a specific files contents
:parameters:
file_content (str) : all the contents the file as a string
:returns:
SHA256 hash of files content
"""
# generating sha256 hash and returning it
return hashlib.sha256(file_content).hexdigest() | ad5e94299f5bf62425b906fd6fef336dc6c7124d | 386,457 |
def print_verilog_literal(size, value):
"""Print a verilog literal with expicilt size"""
if(value >= 0):
return "%s'd%s" % (size, value)
else:
return "-%s'd%s" % (size, abs(value)) | dcf5cd21a05a19d786e27a9dcd5b29743eeb8dc8 | 125,245 |
def split_path(path, all_paths):
"""Split path into parent and current folder."""
idx = path.rfind('/', 0, -1)
if idx == -1:
return '', path
parent, label = path[0:idx + 1], path[idx+1:-1]
if parent not in all_paths:
return '', path
return parent, label | aff444665545748343108cc9cd47ca916d47e3e7 | 495,868 |
from typing import List
def sequence (lower:int, upper:int) -> List[int]:
"""
generate an integer sequence between two numbers.
"""
seq = [ ]
current = lower
while current <= upper:
seq.append(current)
current += 1
return seq | 6a54c3b1234f108abd0a95fbbf0ab7fcb3d3f7f4 | 661,982 |
def group_bases(dna_seq, step=2):
"""
Group the DNA base from a sequence into groups by length "step"
:return: a list of groups
"""
bases_groups = []
for i in range(0, len(dna_seq), step):
bases_groups.append(dna_seq[i:i + step])
return bases_groups | 579f440c7660cd5a8f1347e74848f4710fec745e | 114,292 |
def non_related_filter(questions_df, non_related_ids):
"""
Splits a questions dataframe between related and non-related discussions,
based on an Ids list of non-related discussions.
:param questions_df:
> A pandas dataframe of stackoverflow questions containing posts Ids;
:param non_related_ids:
> List like object containing Ids of manually filtered non-related
stack overflow discussions;
:return (tuple):
> Two dataframes, one with related discussions and another with
non-related discussions
"""
non_related = questions_df.loc[questions_df.Id.isin(non_related_ids)]
non_related = non_related.fillna(0.0)
related = questions_df.loc[~questions_df.Id.isin(non_related_ids)]
related = related.fillna(0.0)
return related, non_related | b7e64287b2bdb6a8999bcd8e7efd8e2787b991dd | 701,954 |
import functools
def _deepgetattr(obj, name, default=None):
"""Recurses through an attribute chain to get the ultimate value."""
try:
return functools.reduce(getattr, name.split('.'), obj)
except AttributeError:
return default | b03887865b9594cb806bc6bc72c54eba010dcae8 | 71,843 |
def _prop_var(p, n):
"""
Calculate variance of proportion.
var(X/n) = 1/(n^2)var(X) = (npq)/(n^2) = pq/n
"""
return p * (1 - p) / n | f93594904db150c2102fa32cb2d6f9ccfe372e50 | 493,179 |
def square(number):
"""
this function returns a square of a number
"""
result = number ** 2
return result | 10a3dc80d5ab0f709bd393c8956bd67be3ec8746 | 259,861 |
def append(df, entry):
"""
This function adds a new entry in the DataFrame
if the entry timestamp does not exists
Parameters
----------
df: pandas.DataFrame
Fataframe to record
entry: pandas.DataFrame
entry dataframe
Returns
-------
A pandas with the updated DataFrame
"""
if entry.index[0] not in df.index:
return df.append(entry, ignore_index=False)
else:
return df | bdfcf7f7741eec8fccc0680f82e3d516e297c1ed | 83,823 |
from pathlib import Path
def get_readable_header(first_file, second_file):
"""Get the readable names from input files.
We want our eventual final output to include headers so that people
can easily see what versions we're diffing between. This grabs the
files' relevant parts -- which here is /folder/{THIS PART}.extension
for display purposes.
Keyword arguments:
first_file -- the file we're diffing from
second_file -- the file we're diffing to
"""
from_name = Path(first_file).stem
to_name = Path(second_file).stem
return {'old': from_name, 'new': to_name} | 216cc4937e9b0e5749b5fd7bcdcbeeb8d108a914 | 432,823 |
import threading
import functools
def _memoize(f):
"""Memoizing decorator for f, which must have exactly 1 hashable
argument."""
nothing = object() # Unique "no value" sentinel object.
cache = {}
# Use a reentrant lock so that if f references the resulting wrapper we die
# with recursion depth exceeded instead of deadlocking.
lock = threading.RLock()
@functools.wraps(f)
def wrapper(arg):
if cache.get(arg, nothing) is nothing:
with lock:
if cache.get(arg, nothing) is nothing:
cache[arg] = f(arg)
return cache[arg]
return wrapper | a6f89477c8e2c5ac886f0ceb573e7edc9659f8fa | 363,458 |
import ctypes
def c_str(string):
"""
Create ctypes char* from a python string
Parameters:
---------
string : string type
python string
Returns:
---------
str: c_char_p
A char pointer that can be passed to C API
"""
return ctypes.c_char_p(string.encode('utf-8')) | 51ecf57b20aa40e79364dad7cd574948d69248b4 | 553,047 |
import re
def strip_appendix(lines):
"""Remove all code in the appendix."""
p = re.compile(r"#\s*#*\s*Appendix")
for i in range(len(lines) - 1, 0, -1):
if p.match(lines[i], re.IGNORECASE):
return lines[0:i]
raise ValueError("Could not find Appendix") | 4e03d0a2063eb999cfb17679084bc8ec92ac1a13 | 431,243 |
import itertools
def flatten(list_of_iters):
"""flatten
Flattens a list of iterables into a single flat list.
Parameters
----------
list_of_iters : :obj:`iter` of :obj:`iter`
A list of iterables.
Returns
-------
:obj:`generator`
Generates flattened list.
"""
return itertools.chain(*list_of_iters) | cb9a290ecb26fa228872ae2a08889c1f03688e38 | 540,482 |
def issubdict(d1, d2):
"""All keys in `d1` are in `d2`, and corresponding values are equal."""
return all((k in d2 and d1[k] == d2[k]) for k in d1) | 3d61e0ac47cdf3040e9838be64eeb338d16612b9 | 530,272 |
from typing import Union
import ast
from typing import Container
from typing import Tuple
from typing import Set
import itertools
def get_signature_params(
node: Union[ast.FunctionDef, ast.AsyncFunctionDef],
ignore: Container[str] = ("self", "cls"),
) -> Tuple[Set[str], bool]:
"""Get parameters in a function signature.
Parameters
----------
node : Union[ast.FunctionDef, ast.AsyncFunctionDef]
An ast function node
ignore : tuple
Which parameter names to ignore (the default is ("self", "cls"),
which don't need documenting)
Returns
-------
signature_params : Set[str]
ambiguous : bool
"""
signature_params = {
argument.arg
for argument in itertools.chain(node.args.args, node.args.kwonlyargs)
if argument.arg not in ignore
}
ambiguous = node.args.vararg is not None or node.args.kwarg is not None
return signature_params, ambiguous | 6c9dc6071356ef02e29535c086e4722b67dd61b0 | 268,278 |
def get_cluster_range(hsp_list):
"""Take a list of SearchIO HSP objects an return a range from the furthest
5' hsp end to the furthest 3' hsp end.
"""
start = min([x.hit_range[0] for x in hsp_list])
end = max([x.hit_range[1] for x in hsp_list])
assert start < end
return [start, end] | 8aeaa29023433c7bf27bca1137cacc9eb712da7c | 356,685 |
def renumber(num_list,
start=1, step=1, padding=4,
preserve=True, autopad=True):
"""Renumber objects.
Return a new list of integers, plus a padding value, as a tuple.
Arguments:
num_list (list) -- input list of integers
Keyword arguments:
start (int) -- start number for renumbering
step (int) -- step / increment for renumbering
padding (int) -- min number of digits for padding numbers
preserve (bool) -- keep existing numerical values
autopad (bool) -- calc the minimum padding for the number sequence
e.g. 1-500 will need 3-digit padding, so will become 001-500
"""
new_num_list = []
# Calculate padding automatically...
if autopad:
if preserve:
max_num = max(num_list)
else:
max_num = start + (step*(len(num_list)-1))
padding = len(str(max_num))
# Regenerate lists
index = start
if preserve:
for num in num_list:
new_num_int = int(str(num).zfill(padding))
new_num_list.append(new_num_int)
else:
for num in num_list:
new_num_int = int(str(index).zfill(padding))
new_num_list.append(new_num_int)
index += step
return new_num_list, padding | 6c026cf881a7939e7447ef0722a9e37a86cc6a9f | 493,037 |
def moving(boxes, threshold=5e-25):
"""Checks to see if boxes have kinetic energy ie moving"""
for b in boxes:
if b.body.kinetic_energy >= threshold:
return True
return False | 46ee559926a00b7aa7ab5793e9807edca4db8ec8 | 410,648 |
def get_service_from_condition_key(condition_key):
"""Given a condition key, return the service prefix"""
elements = condition_key.split(":", 2)
return elements[0] | a666a784219fa6b260bc28a8f9ca0c465b161473 | 352,151 |
def rbo_score(ground_truth, simulation, p=0.95):
"""
Rank biased overlap (RBO) implementation
http://codalism.com/research/papers/wmz10_tois.pdf
A ranked list comparison metric which allows non-overlapping lists
Inputs:
ground_truth - ground truth data
simulation - simulation data
p - RBO parameter ranging from 0 to 1 that determines how much to overweight the the upper portion of the list
p = 0 means only the first element is considered
p = 1 means all ranks are weighted equally
"""
if simulation is None:
return None
try:
ground_truth = ground_truth.index.tolist()
simulation = simulation.index.tolist()
except:
''
sl, ll = sorted([(len(ground_truth), ground_truth), (len(simulation), simulation)])
s, S = sl
l, L = ll
if s == 0: return 0
# Calculate the overlaps at ranks 1 through s
# (the shorter of the two lists)
x_d = {}
rbo_score = 0.0
for i in range(1, s + 1):
x = L[:i]
y = S[:i]
x_d[i] = len(set(x).intersection(set(y)))
for i in range(1,s+1):
rbo_score += (float(x_d[i])/float(i)) * pow(p, (i-1))
rbo_score = rbo_score * (1 - p)
return rbo_score | eda1d9b678bfbbfff71d493113c09e360b945003 | 142,082 |
def read_a_list_file(input_file_name):
""" Read a text file into a python list.
Args:
input_file_name: full path name of a file containing a list
Returns:
a list that is contained in the file
"""
with open(input_file_name, 'r') as fh:
str_input = fh.read()
return list(str_input.split()) | 1f06add8dd9075ff0ef30e1174de45f6d597e122 | 265,809 |
def clip(img, size, rect):
""" Clip the frame and return the face region
Args:
img: an instance of numpy.ndarray, the image
size: size of the image when performing detection
rect: an instance of dlib.rectangle, the face region
Returns:
numpy.ndarray, the face region
"""
left = int(rect.left() / size[0] * img.shape[1])
right = int(rect.right() / size[0] * img.shape[1])
top = int(rect.top() / size[1] * img.shape[0])
bottom = int(rect.bottom() / size[1] * img.shape[0])
return img[top:bottom, left:right] | dd7929502591827987cefdc4c7c060a1b14759bd | 395,723 |
def is_doc(comment):
"""Test if comment is a C documentation comment."""
return comment.startswith('/**') and comment != '/**/' | 8f08a8ca87e30fc1693558ddfde9707984ea6ad9 | 541,320 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.