seed stringlengths 1 14k | source stringclasses 2
values |
|---|---|
def fetch_ref_codon(ref_pos, curr_gene, curr_seq):
""" Fetch codon within gene for given site """
# position of site in gene
within_gene_pos = ref_pos - curr_gene['start'] if curr_gene['strand'] == '+' else curr_gene['end'] - ref_pos
# position of site in codon
within_codon_pos = within_gene_pos % 3
# gene sequence (oriented start to stop)
ref_codon = curr_seq[within_gene_pos-within_codon_pos:within_gene_pos-within_codon_pos+3]
return ref_codon, within_codon_pos | bigcode/self-oss-instruct-sc2-concepts |
import numbers
def _scale(scale):
""" Given a numeric input, return a 2-tuple with the number repeated.
Given a 2-tuple input, return the input
>>> _scale(2)
(2, 2)
>>> _scale((1, 2,))
(1, 2)
>>> _scale('nonsense')
Traceback (most recent call last):
...
TypeError: argument should be a number or a tuple
>>> _scale((1,2,3))
Traceback (most recent call last):
...
ValueError: scale should be a 2-tuple
"""
if isinstance(scale, tuple):
if len(scale) != 2:
raise ValueError('scale should be a 2-tuple')
return scale
elif isinstance(scale, numbers.Real):
return (scale, scale)
else:
raise TypeError('argument should be a number or a tuple') | bigcode/self-oss-instruct-sc2-concepts |
def checkValid(s, row, col):
"""
Returns True if a given cell is valid in a Sudoku puzzle, and
False if not. A cell is valid if the number in that cell is not present
in any of the cells in the same row, or the same column, or the same block.
"""
block_row = row // 3
block_col = col // 3
# Row and Column
# Ignore blank spots
for m in range(9):
if s[row][m] != 0 and m != col and s[row][m] == s[row][col]:
return False
if s[m][col] != 0 and m != row and s[m][col] == s[row][col]:
return False
# Block
for m in range(3):
for n in range(3):
newRow = m + block_row*3
newCol = n + block_col*3
if s[newRow][newCol] != 0 and newRow != row and newCol != col\
and s[newRow][newCol ] == s[row][col]:
return False
return True | bigcode/self-oss-instruct-sc2-concepts |
from typing import Any
def _len(x: Any) -> int:
"""Return len of x if it is iterable, else 0."""
return max(1, len(x)) if isinstance(x, list) else 0 | bigcode/self-oss-instruct-sc2-concepts |
def timedelta_to_seconds(td):
"""
Converts a timedelta to total seconds, including support for microseconds.
Return value is (potentially truncated) integer.
(This is built-in in Python >= 2.7, but we are still supporting Python 2.6 here.)
:param td: The timedelta object
:type td: :class:`datetime.timedelta`
:return: The number of total seconds in the timedelta object.
:rtype: int
"""
if not td:
return None
return (td.microseconds + (td.seconds + td.days * 24 * 3600) * 10**6) / 10**6 | bigcode/self-oss-instruct-sc2-concepts |
def luhn_checksum(num: str) -> str:
"""Calculate a checksum for num using the Luhn algorithm.
:param num: The number to calculate a checksum for as a string.
:return: Checksum for number.
"""
check = 0
for i, s in enumerate(reversed(num)):
sx = int(s)
sx = sx * 2 if i % 2 == 0 else sx
sx = sx - 9 if sx > 9 else sx
check += sx
return str(check * 9 % 10) | bigcode/self-oss-instruct-sc2-concepts |
def test_chess_cell(x, y):
"""
Source https://pythontutor.ru/lessons/ifelse/problems/chess_board/
Condition
Two checkerboard squares are set. If they are painted the same color,
print the word YES, and if in different colors - then NO.
The program receives four numbers from 1 to 8 each, specifying the column number and
line number first for the first cell, then for the second cell.
"""
if x % 2 != 0 and y % 2 != 0: # False if cell white, True if cell black
return True
if x % 2 != 0 and y % 2 == 0:
return False
if x % 2 == 0 and y % 2 != 0:
return False
else:
return True | bigcode/self-oss-instruct-sc2-concepts |
import re
def parse_description(dsc):
"""
Parse the given string into a hash.
The string format is `key: value`,
where key gets converted to upper case
and value extends until a new line.
A special last field `Abstract:` extends until the end of string.
"""
meta, abstract = re.split('abstract:\s*\n*', dsc, flags=re.I)
ret = {'ABSTRACT': abstract}
for line in meta.splitlines():
if ':' in line:
key, value = re.split('\s*:\s*', line, 1)
key = key.upper()
ret[key] = value
return ret | bigcode/self-oss-instruct-sc2-concepts |
def decode(packet):
"""
https://raw.githubusercontent.com/telldus/telldus/master/telldus-core/service/ProtocolOregon.cpp
>>> decode(dict(data=0x201F242450443BDD, model=6701))["data"]["temp"]
24.2
>>> decode(dict(data=0x201F242450443BDD, model=6701))["data"]["humidity"]
45.0
"""
if packet["model"] != 6701:
raise NotImplementedError(
"The Oregon model %i is not implemented." % packet["model"]
)
data = packet["data"]
value = int(data)
value >>= 8
checksum1 = value & 0xFF
value >>= 8
checksum = ((value >> 4) & 0xF) + (value & 0xF)
hum1 = value & 0xF
value >>= 8
checksum += ((value >> 4) & 0xF) + (value & 0xF)
neg = value & (1 << 3)
hum2 = (value >> 4) & 0xF
value >>= 8
checksum += ((value >> 4) & 0xF) + (value & 0xF)
temp2 = value & 0xF
temp1 = (value >> 4) & 0xF
value >>= 8
checksum += ((value >> 4) & 0xF) + (value & 0xF)
temp3 = (value >> 4) & 0xF
value >>= 8
checksum += ((value >> 4) & 0xF) + (value & 0xF)
address = value & 0xFF
value >>= 8
checksum += ((value >> 4) & 0xF) + (value & 0xF)
checksum += 0x1 + 0xA + 0x2 + 0xD - 0xA
if checksum != checksum1:
raise ValueError(
"The checksum in the Oregon packet does not match "
"the caluclated one!"
)
temperature = ((temp1 * 100) + (temp2 * 10) + temp3) / 10.0
if neg:
temperature = -temperature
humidity = (hum1 * 10.0) + hum2
return dict(
packet,
sensorId=address,
data=dict(temp=temperature, humidity=humidity),
) | bigcode/self-oss-instruct-sc2-concepts |
import codecs
def is_ascii_encoding(encoding):
"""Checks if a given encoding is ASCII."""
try:
return codecs.lookup(encoding).name == "ascii"
except LookupError:
return False | bigcode/self-oss-instruct-sc2-concepts |
def _find_idx_without_numerical_difference(df, column1, column2, delta, idx=None, equal_nan=False):
"""
Returns indices which have bigger numerical difference than delta.
INPUT:
**df** (DataFrame)
**column1** (str) - name of first column within df to compare.
The values of df[column1] must be numericals.
**column2** (str) - name of second column within df to compare.
The values of df[column2] must be numericals.
**delta** (numerical) - value which defines whether indices are returned or not
OPTIONAL:
**idx** (iterable, None) - list of indices which should be considered only
**equal_nan** (bool, False) - if True, indices are included where at least value in
df[column1] or df[column2] is NaN
OUTPUT:
**index** (pandas.Index) - index within idx where df[column1] and df[column2] deviates by
at least delta or, if equal_na is True, one value is NaN
"""
idx = idx if idx is not None else df.index
idx_isnull = df.index[df[[column1, column2]].isnull().any(axis=1)]
idx_without_null = idx.difference(idx_isnull)
idx_no_delta = idx_without_null[(
df.loc[idx_without_null, column1] -
df.loc[idx_without_null, column2]).abs().values <= delta]
if equal_nan:
return idx.difference(idx_no_delta)
else:
return idx_without_null.difference(idx_no_delta) | bigcode/self-oss-instruct-sc2-concepts |
def getDomainOnly(url):
"""Return the domain out from a url
url = the url
"""
# print ("getDomainOnly : ", url)
tmp = url.split('.')[-2] + '.' + url.split('.')[-1]
tmp = tmp.split('/')[0]
return tmp | bigcode/self-oss-instruct-sc2-concepts |
import time
def sb_session_login(sb_session, sb_username, sb_password=None):
"""
login in to sb session using the input credentials. Checks to see if
you are already logged in. If no password is given, the password will be
requested through the command prompt.
.. note:: iPython shells will echo your password. Use a Python command
shell to not have your password echoed.
:param sb_session: sciencebase session object
:type sb_session: sciencebasepy.SbSession
:param sb_username: sciencebase username, typically your full USGS email
:type sb_username: string
:param sb_password: AD password
:type sb_password: string
:returns: logged in sciencebasepy.SbSession
"""
if not sb_session.is_logged_in():
if sb_password is None:
sb_session.loginc(sb_username)
else:
sb_session.login(sb_username, sb_password)
time.sleep(5)
return sb_session | bigcode/self-oss-instruct-sc2-concepts |
def subroutine_type(name):
"""Returns type of subroutine, 'setup' or 'teardown' if it has
either of those names, or module setup or teardown, otherwise None."""
lowername = name.lower()
if lowername == 'setup':
subtype = 'global setup'
elif lowername == 'teardown':
subtype = 'global teardown'
elif lowername.startswith('test_'):
subtype = 'test'
elif 'setup_' in lowername or '_setup' in lowername:
subtype = 'setup'
elif 'teardown_' in lowername or '_teardown' in lowername:
subtype = 'teardown'
else:
subtype = None
return subtype | bigcode/self-oss-instruct-sc2-concepts |
def permutation(s):
"""
@s: list of elements, eg: [1,2,3]
return: list of permutations, eg: [[1,2,3], [1,3,2], [2,1,3], [2,3,1], [3,1,2], [3,2,1]]
"""
ret = []
length = len(s)
if length == 0:
return ret
if length == 1:
return [s]
curr = s[0]
for prev in permutation(s[1:]):
for i in range(length):
ret.append(prev[:i] + [curr] + prev[i:])
return ret | bigcode/self-oss-instruct-sc2-concepts |
import torch
def rot90(input_, k=1, axes=(0, 1)):
"""Wrapper of `torch.rot90`
Parameters
----------
input_ : DTensor
Input dense tensor.
k : int, optional
Number of rotation times, by default 1
axes : tuple, optional
The axes in which the input is rotated, by default (0, 1)
"""
return torch.rot90(input_._data, k, dims=axes) | bigcode/self-oss-instruct-sc2-concepts |
import torch
def get_optimizer(model, learning_rate, optimizer_state_dict=None, verbose=False):
"""
Returns an ADAM optimizer attached to the given model
(and stored on the same device).
If optimizer_state_dict is not None, it will fill in the optimizer state.
However, learning_rate will override and saved optimizer state (to allow
you to adjust during training.)
"""
if verbose: print("Building optimizer... ", end='')
optimizer = torch.optim.Adam(model.parameters(), learning_rate)
if optimizer_state_dict:
optimizer.load_state_dict(optimizer_state_dict)
# allow for change in learning rate:
for param_group in optimizer.param_groups:
param_group['lr'] = learning_rate
if verbose: print("Done.")
return optimizer | bigcode/self-oss-instruct-sc2-concepts |
def inc(x):
"""
Returns a number one greater than num.
"""
return x + 1 | bigcode/self-oss-instruct-sc2-concepts |
import requests
def get_latest_release_from_pypi(*, package: str) -> str:
"""Get the latest release of a package on pypi"""
response = requests.get(f"https://pypi.org/pypi/{package}/json").json()
return response["info"]["version"] | bigcode/self-oss-instruct-sc2-concepts |
def filter_to_sentry(event, hint):
"""filter_to_sentry is used for filtering what
to return or manipulating the exception before sending
it off to Sentry (sentry.io)
The 'extra' keyword is part of the LogRecord
object's dictionary and is where the flag
for sending to Sentry is set.
Example use case:
current_app.logger.error(
err_formatted, exc_info=ex, extra={'to_sentry': True})
"""
# By default, we send to sentry
to_sentry = event['extra'].get('to_sentry', True)
if to_sentry:
return event
return None | bigcode/self-oss-instruct-sc2-concepts |
def _capture_callback(x):
"""Validate the passed options for capturing output."""
if x in [None, "None", "none"]:
x = None
elif x in ["fd", "no", "sys", "tee-sys"]:
pass
else:
raise ValueError("'capture' can only be one of ['fd', 'no', 'sys', 'tee-sys'].")
return x | bigcode/self-oss-instruct-sc2-concepts |
def get_new_sol_file(test_nr):
""" Get name of new solution file """
return "test/{0}-new.sol".format(test_nr) | bigcode/self-oss-instruct-sc2-concepts |
import re
def unwrap_wrapped_text(text):
""" Unwraps multi-line strings, but keeps paragraphs separated by
two or more newlines separated by newlines.
"""
result = []
_re_indentation = re.compile(r'^[ \t]*|[ \t]*$', re.MULTILINE)
for paragraph in re.split(r'\n{2,}', text):
paragraph = _re_indentation.sub('', paragraph)
result.append(re.sub(r'\n', ' ', paragraph))
return '\n'.join(result) | bigcode/self-oss-instruct-sc2-concepts |
def test_hindcast_verify_brier_logical(hindcast_recon_1d_ym):
"""Test that a probabilistic score requiring a binary observations and
probability initialized inputs gives the same results whether passing logical
as kwarg or mapping logical before for hindcast.verify()."""
he = hindcast_recon_1d_ym
def logical(ds):
return ds > 0.5
brier_logical_passed_as_kwarg = he.verify(
metric="brier_score",
comparison="m2o",
logical=logical,
dim="member",
alignment="same_verif",
)
brier_logical_mapped_before_and_member_mean = (
he.map(logical)
.mean("member")
.verify(metric="brier_score", comparison="e2o", dim=[], alignment="same_verif")
)
brier_logical_mapped_before_no_member_mean = he.map(logical).verify(
metric="brier_score", comparison="m2o", dim="member", alignment="same_verif"
)
assert (
brier_logical_mapped_before_and_member_mean == brier_logical_passed_as_kwarg
).all()
assert (
brier_logical_mapped_before_no_member_mean == brier_logical_passed_as_kwarg
).all() | bigcode/self-oss-instruct-sc2-concepts |
import re
def could_be_content_page(url: str) -> bool:
"""
Try to guess if the link is a content page.
It's not a perfect check, but it can identify URLs that are obviously not content.
"""
url = url.lower().rstrip('/')
if url.endswith('/signin') or url.endswith('/login') or \
url.endswith('/login-page') or url.endswith('/logout'):
return False
if url.endswith('/my-account') or url.endswith('/my-wishlist'):
return False
if re.search('/(lost|forgot)[_-]password$', url):
return False
if url.endswith('/search') or url.endswith('/archive'):
return False
if url.endswith('/privacy-policy') or url.endswith('/cookie-policy') or \
url.endswith('/terms-conditions'):
return False
if url.endswith('/tos') or re.search('/terms[_-]of[_-](service|use)$', url):
return False
# Yei, it might be a content page
return True | bigcode/self-oss-instruct-sc2-concepts |
def collide_rect(sprite1, sprite2):
"""
**pyj2d.sprite.collide_rect**
Check if the rects of the two sprites intersect.
Can be used as spritecollide callback function.
"""
return sprite1.rect.intersects(sprite2.rect) | bigcode/self-oss-instruct-sc2-concepts |
def compute_image_data_statistics(data_loader):
"""
Return the channel wise mean and std deviation for images loaded by `data_loader` (loads WebDataset defined in `datasets.py`)
"""
mean = 0.
std = 0.
n_samples = 0.
for images, bboxes, labels in data_loader:
batch_samples = images.size(0)
images = images.view(batch_samples, images.size(1), -1)
mean += images.mean(2).sum(0)
std += images.std(2).sum(0)
n_samples += batch_samples
mean /= n_samples
std /= n_samples
return mean, std | bigcode/self-oss-instruct-sc2-concepts |
def int_to_roman(n):
"""
Convert an integer to its standard Roman Numeral representation
"""
V = [1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1]
S = ["M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I"]
out = ""
for val,sym in zip(V,S):
while n >= val:
out += sym
n -= val
return out | bigcode/self-oss-instruct-sc2-concepts |
def _get_module_ver_hash(prov):
"""Get module commit hash, falling back to semantic version, and finally 'UNKNOWN'"""
ver = None
subacts = prov[0].get('subactions')
if subacts:
ver = subacts[0].get('commit')
if not ver:
ver = prov[0].get('service_ver', 'UNKNOWN')
return ver | bigcode/self-oss-instruct-sc2-concepts |
def get_nominal_conc(df, species):
"""
Get the nominal hector concentration for a given species
Parameters
----------
df : Pandas DataFrame
DataFrame containing output from a nominal hector run
species : str
Species to retrieve output for
Return
------
species_df : Pandas DataFrame
Pandas DataFrame containing hector concentration output for the given
species
"""
species = species.upper() # Ensure string is all uppercase
# ensure correct string for atmospheric co2 concentration
if (species == 'CO2'):
species = 'Ca'
species_df = df.loc[df['variable'] == species]
return species_df | bigcode/self-oss-instruct-sc2-concepts |
def gpib_control_ren(library, session, mode):
"""Controls the state of the GPIB Remote Enable (REN) interface line, and optionally the remote/local
state of the device.
Corresponds to viGpibControlREN function of the VISA library.
:param library: the visa library wrapped by ctypes.
:param session: Unique logical identifier to a session.
:param mode: Specifies the state of the REN line and optionally the device remote/local state.
(Constants.GPIB_REN*)
:return: return value of the library call.
:rtype: :class:`pyvisa.constants.StatusCode`
"""
return library.viGpibControlREN(session, mode) | bigcode/self-oss-instruct-sc2-concepts |
def truncate(string: str, width: int, ending: str = "...") -> str:
"""Truncate string to be no longer than provided width. When truncated, add
add `ending` to shortened string as indication of truncation.
Parameters
----------
string: str
String to be truncated.
width: int
Maximum amount of characters before truncation.
ending: str, optional
Indication string of truncation.
Returns
-------
Truncated string.
"""
if not len(string) > width:
return string
length = width - len(ending)
return string[:length] + ending | bigcode/self-oss-instruct-sc2-concepts |
def split_ver_str(ver_str):
"""Split version string into numeric components.
Return list of components as numbers additionally checking
that all components are correct (i.e. can be converted to numbers).
"""
ver_list = []
for c in ver_str.split('.')[0:3]:
if not c.isdecimal():
raise RuntimeError("Malformed version string '{}'. "
"Component '{}' is not an integer."
.format(ver_str, c))
ver_list.append(int(c))
return ver_list | bigcode/self-oss-instruct-sc2-concepts |
import torch
def get_first_idx(numel_per_tensor):
"""Returns the first indices of each tensor in the :ref:`packed tensor <packed>`.
See :ref:`first_idx definition <packed_first_idx>` for more information.
Args:
numel_per_tensor (torch.LongTensor): The number of elements
(vertices, faces, points...) in each unbatched tensor, as a 1D tensor.
Returns:
(torch.LongTensor):
first indices for each unbatched tensor in the packed tensor,
and the last index + 1, as 1D tensor.
Example:
>>> numel_per_tensor = torch.LongTensor([2, 3, 5])
>>> get_first_idx(numel_per_tensor)
tensor([ 0, 2, 5, 10])
"""
output = torch.zeros((numel_per_tensor.shape[0] + 1,), dtype=torch.long,
device=numel_per_tensor.device)
torch.cumsum(numel_per_tensor, dim=0, out=output[1:])
return output | bigcode/self-oss-instruct-sc2-concepts |
def shipping_charge(method, basket, postcode):
"""
Template tag for calculating the shipping charge for a given shipping
method and basket, and injecting it into the template context.
"""
return method.calculate(basket, postcode) | bigcode/self-oss-instruct-sc2-concepts |
import re
def _re_compile(regex):
"""Compile a string to regex, I and UNICODE."""
return re.compile(regex, re.I | re.UNICODE) | bigcode/self-oss-instruct-sc2-concepts |
from io import StringIO
def df_to_csv_string(df):
"""Converts pandas DataFrame to a CSV string."""
out = StringIO()
df.to_csv(out, encoding='utf-8')
return out.getvalue() | bigcode/self-oss-instruct-sc2-concepts |
def left_shift(number, n):
"""
Left shift on 10 base number.
Parameters
----------
number : integer
the number to be shift
n : integer
the number of digit to shift
Returns
-------
shifted number : integer
the number left shifted by n digit
Examples
--------
>>> left_shift(152, 1)
15
>>> left_shift(14589, 3)
14
"""
return number // 10 ** n | bigcode/self-oss-instruct-sc2-concepts |
import math
def calculate_distance(location1, location2):
"""
Calculates the distance between two pairs of lat, long coordinates
using the Haversine formula
Inputs:
location1 - [lat, lon] array with first location
location2 - [lat, lon] array with second location
Outputs:
distance - in kilometers
"""
lat1 = math.radians(abs(location1[0]))
lon1 = math.radians(abs(location1[1]))
lat2 = math.radians(abs(location2[0]))
lon2 = math.radians(abs(location2[1]))
# haversine formula
dlon = lon2 - lon1
dlat = lat2 - lat1
a = math.sin(dlat/2)**2 + math.cos(lat1) * math.cos(lat2) * math.sin(dlon/2)**2
c = 2 * math.asin(math.sqrt(a))
# Radius of earth in kilometers
r = 6371.0
return c * r | bigcode/self-oss-instruct-sc2-concepts |
import re
def rmsp(s):
"""Replace multiple spaces with one.
"""
return re.sub(r"\ +", ' ', s.strip()) | bigcode/self-oss-instruct-sc2-concepts |
def ir(some_value):
""" Rounds and casts to int
Useful for pixel values that cannot be floats
Parameters
----------
some_value : float
numeric value
Returns
--------
Rounded integer
Raises
------
ValueError for non scalar types
"""
return int(round(some_value)) | bigcode/self-oss-instruct-sc2-concepts |
def decibels_to_amplitude_ratio(decibels):
"""The ratio between two amplitudes given a decibel change"""
return 2 ** (decibels/10) | bigcode/self-oss-instruct-sc2-concepts |
import requests
def get_stock_data(symbol, token):
"""Send a request to the API with the symbol and token. Return the stock data we want:
Symbol, Company Name, Current Price"""
url = f"https://cloud.iexapis.com/stable/stock/{symbol}/quote?token={token}"
response = requests.get(url)
if response.status_code != 200:
print(response.text)
return None
all_stock_data = response.json()
name = all_stock_data["companyName"]
symbol = all_stock_data["symbol"]
current_price = all_stock_data["latestPrice"]
stock_data = {"name": name, "symbol": symbol, "current_price": current_price}
return stock_data | bigcode/self-oss-instruct-sc2-concepts |
def handle_exhibition_desc(company: str, desc: str) -> str:
"""
Handles exhibition description special formatting needs.
Returns the updated description.
:param company: company name
:param desc: company description
"""
if company.lower() == "mathworks":
desc = desc.replace(" o ", "\n- ")
if company.lower() == "simulation and data lab neuroscience":
desc = desc.replace("\n•", "\n- ")
return desc | bigcode/self-oss-instruct-sc2-concepts |
import click
def soft_nprocs(soft, nprocs):
"""Reduce the number of ranks to the largest acceptable soft value"""
# If no soft specification given, use -n value
if not soft:
return nprocs
# Filter to values between 1 and nprocs
try:
return max([x for x in soft if 0 < x <= nprocs])
except ValueError:
# pylint: disable=raise-missing-from
raise click.UsageError("No soft values found between 1 and %d" % nprocs) | bigcode/self-oss-instruct-sc2-concepts |
def _IsOverlapping(alert_entity, start, end):
"""Whether |alert_entity| overlaps with |start| and |end| revision range."""
return (alert_entity.start_revision <= end and
alert_entity.end_revision >= start) | bigcode/self-oss-instruct-sc2-concepts |
import torch
def GTA_prop_to_hot(img, n_classes: int, width: int, height: int):
"""
This function turns the output of the network (given in probability format)
into the most likely onehot encoded output.
Args:
img (tensor): The tensor with probabilities.
n_classes (int): Amount of classes in the onehot encoded format.
width (int): Size width of the given tensor.
height (int): Size height of the given tensor.
Returns:
Tensor: In onehot encoded format.
"""
mat = torch.argmax(img, dim=1)
map = torch.zeros((n_classes, height, width), dtype=torch.uint8)
for r in range(height):
for c in range(width):
map[mat[0][r][c]][r][c] = 1
return map | bigcode/self-oss-instruct-sc2-concepts |
import math
def polar2cart(r, x0, y0, theta):
"""Changes polar coordinates to cartesian coordinate system.
:param r: Radius
:param x0: x coordinate of the origin
:param y0: y coordinate of the origin
:param theta: Angle
:return: Cartesian coordinates
:rtype: tuple (int, int)
"""
x = int(x0 + r * math.cos(theta))
y = int(y0 + r * math.sin(theta))
return x, y | bigcode/self-oss-instruct-sc2-concepts |
def binary_search(query, array):
"""
Determine whether the query is in an sorted array.
Return the index of the query if it is present in the array.
If the query is not in the array, return -1
>>> binary_search(4, [1, 2, 3, 4, 5, 6, 7, 8, 9])
3
>>> binary_search(8, [1, 2, 3, 4, 5, 6, 7, 8, 9])
7
>>> binary_search(10, [1, 2, 3, 4, 5, 6, 7, 8, 9])
-1
"""
lo, hi = 0, len(array) - 1
while lo <= hi:
mid = (lo + hi) // 2
if query < array[mid]:
hi = mid - 1
elif query > array[mid]:
lo = mid + 1
else:
return mid
return -1 | bigcode/self-oss-instruct-sc2-concepts |
import torch
def calculate_output_dim(net, input_shape):
"""Calculates the resulting output shape for a given input shape and network.
Args:
net (torch.nn.Module): The network which you want to calculate the output
dimension for.
input_shape (int | tuple[int]): The shape of the input being fed into the
:obj:`net`. Batch dimension should not be included.
Returns:
The shape of the output of a network given an input shape.
Batch dimension is not included.
"""
if isinstance(input_shape, int):
input_shape = (input_shape,)
placeholder = torch.zeros((0,) + tuple(input_shape))
output = net(placeholder)
return output.size()[1:] | bigcode/self-oss-instruct-sc2-concepts |
def markdown_escape_filter(text):
"""Escape special characters in Markdown."""
return text.replace("\\", "\\\\").replace("`", "\\`").replace(
"*", "\\*").replace("_", "\\_").replace("{", "\\{").replace(
"}", "\\}").replace("[", "\\[").replace("]", "\\]").replace(
"(", "\\(").replace(")", "\\)").replace("#", "\\#").replace(
"+", "\\+").replace("-",
"\\-").replace(".", "\\.").replace(
"!", "\\!").replace("|", "\\|") | bigcode/self-oss-instruct-sc2-concepts |
def thousands_separator(value):
"""
千位分隔符
例如传入 1000000000,返回 1,000,000,000
:param value: 需要转换的数字
:return: 格式化后的字符串
"""
return '{:,}'.format(value) | bigcode/self-oss-instruct-sc2-concepts |
from typing import List
import math
def equal_split(s: str, width: int) -> List[str]:
"""
Split the string, each split has length `width` except the last one.
"""
num = int(math.ceil(len(s) / width)) # python3
return [s[i * width: (i + 1) * width] for i in range(num)] | bigcode/self-oss-instruct-sc2-concepts |
def prob1(l):
"""Accept a list 'l' of numbers as input and return a list with the minimum,
maximum, and average of the original list.
"""
ans = []
ans.append(min(l))
ans.append(max(l))
ans.append(float(sum(l))/len(l))
return ans | bigcode/self-oss-instruct-sc2-concepts |
def get_ns_name(uri):
"""
Get the namespace (the namespace is placed before the first '#' character or the last '/' character)
"""
hash_index = uri.find('#')
index = hash_index if hash_index != -1 else uri.rfind('/')
namespace = uri[0: index + 1]
return namespace | bigcode/self-oss-instruct-sc2-concepts |
import struct
def pack_date(date):
"""
Packs a date (assumed to be UTC) as a struct with of 16-bit, unsigned `year`
(big endian), 1 byte `month`, and 1 byte `day`.
"""
return struct.pack("!HBB", date.year, date.month, date.day) | bigcode/self-oss-instruct-sc2-concepts |
from typing import Set
def allocate_mid(mids: Set[str]) -> str:
"""
Allocate a MID which has not been used yet.
"""
i = 0
while True:
mid = str(i)
if mid not in mids:
mids.add(mid)
return mid
i += 1 | bigcode/self-oss-instruct-sc2-concepts |
def _xor(a,b):
"""Return true iff exactly one of and b are true. Used to check
some conditions."""
return bool(a) ^ bool(b) | bigcode/self-oss-instruct-sc2-concepts |
from typing import Any
from typing import get_args
from typing import get_origin
from typing import Literal
def is_str_literal(hint: Any) -> bool:
"""Check if a type hint is Literal[str]."""
args = get_args(hint)
origin = get_origin(hint)
if origin is not Literal:
return False
if not len(args) == 1:
return False
return isinstance(args[0], str) | bigcode/self-oss-instruct-sc2-concepts |
def get_pitch_at_time(genotype, time):
"""given genotype and durk time point, returns pitch being played at that durk point and whether or not pitch ends perfectly on time
Args:
genotype ((int, int)[]): genotype of chromosome, which is list of (pitch, dur)
time (int): time point in durks
Returns:
(int, bool): (pitch, end_on_time) where pitch is [1,21] and end_on_time represents whether or not the pitch ends perfectly at the time point time.
"""
pitch = -9999
dur_running_total = 0
end_on_time = False
for i, (ed, dur) in enumerate(genotype):
dur_running_total += dur
if dur_running_total > time:
pitch = ed
break
elif dur_running_total == time:
pitch = ed
end_on_time = True
break
return (pitch, end_on_time) | bigcode/self-oss-instruct-sc2-concepts |
def _get_source_files(commands):
"""Return a list of all source files in the compilation."""
return list(commands.keys()) | bigcode/self-oss-instruct-sc2-concepts |
def dnode(period):
"""
Orbit nodal precession on each rev. Orbits below GEO move (drift) Westerly
while orbits above GEO move Easterly. Orbits at GEO are stationary, 0 deg drift.
Use siderial day rotation for better accuracy.
Arg:
period [sec]
Return:
node precession (dn) [deg]
"""
return 360 - 360/(23*3600+56*60+4)*period | bigcode/self-oss-instruct-sc2-concepts |
def process_search_term(lookup):
"""
Removes any whitespace from the search string, and replaces them with the appropriate character to pass as a URL
:param lookup:
:return: lookup
"""
lookup = lookup.replace(" ", "+")
return lookup | bigcode/self-oss-instruct-sc2-concepts |
import torch
def check_gpu(gpu):
"""
Fuction takes one argument as boolean and provides support for gpu or cpu selection and print out the current device being used.
Command Line Arguments:
1. GPU as True value that enables GPU support and use cuda for calculation, and False to enable CPU.
Function returns device and print out the device being used, either for trianing or inference.
"""
# If gpu is True gpu is enabled and print out "\nGPU is availabe...". if the gpu didn't exist device switchs to cpu and print out "\nDevice didn't find GPU, using CPU instead"
if gpu:
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
if torch.cuda.is_available():
print("\nGPU is availabe...")
else:
print("\nDevice didn't find GPU, using CPU instead")
else:
print("\nCPU is availabe...")
return torch.device("cpu")
return device | bigcode/self-oss-instruct-sc2-concepts |
import csv
import re
def load_peptides(input_file, peptide_column, column_separator):
"""
Parses the input file and extracts all peptides occuring within the file. Peptide strings
are cleaned (only valid characters retained) and returned as a set.
:param input_file: The file to parse
:param peptide_column: The column header to extract the peptides from.
:param column_separator: The separator used for the columns
:return: A set of strings representing the peptides.
"""
with open(input_file, "r") as input_stream:
csv_reader = csv.DictReader(input_stream, delimiter=column_separator)
peptides = set()
for row in csv_reader:
if peptide_column not in row:
raise Exception("Specified peptide column '" + peptide_column + "' not found in input file.")
sequence = row[peptide_column]
clean_sequence = re.sub("[^A-Z]", "", sequence)
peptides.add(clean_sequence)
return peptides | bigcode/self-oss-instruct-sc2-concepts |
def input_prompt(prompt):
"""
Get user input
"""
return input(prompt) | bigcode/self-oss-instruct-sc2-concepts |
from typing import List
def alphabetical_binary_search(sorted_list: List, search_name: str) -> int:
"""Alphabetical binary search (for study purpuses)
Args:
sorted_list (List): A list of names (must be ordered)
search_name (str): name to search
Returns:
int: found index or -1
"""
lowest_index = 0
highest_index = len(sorted_list) - 1
intermediate_index = highest_index // 2
while lowest_index <= highest_index:
name = sorted_list[intermediate_index]
if search_name == name:
return intermediate_index
if name > search_name:
highest_index = intermediate_index - 1
if name < search_name:
lowest_index = intermediate_index + 1
intermediate_index = (lowest_index + highest_index) // 2
return -1 | bigcode/self-oss-instruct-sc2-concepts |
import torch
def compute_loss(inputs, outputs, criterion, edge_criterion):
"""Compute loss automatically based on what the model output dict contains.
'doc_logits' -> document-label CE loss
'para_logits' -> paragraph-label CE loss
'pare_edge_weights' -> additional edge CE loss
"""
if 'para_logits' in outputs:
loss = criterion(outputs['para_logits'], inputs['para_label'])
loss *= (inputs['para_lengths'] != 0).to(torch.float)
loss = loss.sum()
else:
loss = criterion(outputs['doc_logits'], inputs['label']).sum()
if 'para_edge_weights' in outputs:
edge_loss_lambda = 0.1
edge_loss = edge_criterion(outputs['para_edge_weights'], 1 - inputs['para_label'])
edge_loss *= (inputs['para_lengths'] != 0).to(torch.float)
loss += edge_loss_lambda * edge_loss.sum()
return loss | bigcode/self-oss-instruct-sc2-concepts |
import base64
def decode_base64(input_string: str) -> bytes:
"""Decode an unpadded standard or urlsafe base64 string to bytes."""
input_bytes = input_string.encode("ascii")
input_len = len(input_bytes)
padding = b"=" * (3 - ((input_len + 3) % 4))
# Passing altchars here allows decoding both standard and urlsafe base64
output_bytes = base64.b64decode(input_bytes + padding, altchars=b"-_")
return output_bytes | bigcode/self-oss-instruct-sc2-concepts |
def normalize_extension(extension):
"""
Normalize extension
Converts given extension to canonical format for storage
:param extension: original extension
:return: normalized extension
"""
extension = extension.lower()
exts = dict()
exts['jpg'] = ['jpeg','jpe','jif','jfif','jfi''jp2','j2k','jpx','jpf','jpm']
exts['tif'] = ['tiff']
exts['tar.gz'] = ['tgz']
for canonical, variants in exts.items():
if extension in variants:
extension = canonical
break
return extension | bigcode/self-oss-instruct-sc2-concepts |
def parseTrackLog(line):
"""Parse trackLog line and return important fields: db, year, month, hgsid,
and a list of tracks"""
#### Sample line being processed ####
# [Sun Mar 05 04:11:27 2017] [error] [client ###.###.###.##] trackLog 0 hg38 hgsid_### cytoBandIdeo:1,cloneEndCTD:2
####
splitLine = line.strip().split('trackLog')
prefix = splitLine[0].split()
month = prefix[1]
year = prefix[4].replace("]","")
suffix = splitLine[1].split()
db = suffix[1]
hgsid = suffix[2]
if len(suffix) > 3:
activeTracks = suffix[3]
tracks = activeTracks.split(",")
else:
tracks = []
return db, year, month, hgsid, tracks | bigcode/self-oss-instruct-sc2-concepts |
import re
def getWords(text):
"""From a text input as a string, get the words separated by a space and return it as a list of strings"""
return re.compile('\w+').findall(text) | bigcode/self-oss-instruct-sc2-concepts |
def sqdist(point1, point2, rotmat):
"""
This routine calculates the anisotropic distance between two points
given the coordinates of each point and a definition of the
anisotropy.
This method only consider a single anisotropy senario.
Parameters
----------
point1 : tuple
Coordinates of first point (x1,y1,z1)
point2 : tuple
Coordinates of second point (x2,y2,z2)
rotmat : 3*3 ndarray
matrix of rotation for this structure
Returns
-------
sqdist : scalar
The squared distance accounting for the anisotropy
and the rotation of coordinates (if any).
"""
dx = point1[0] - point2[0]
dy = point1[1] - point2[1]
dz = point1[2] - point2[2]
sqdist = 0.0
for i in range(3):
cont = rotmat[i, 0] * dx + \
rotmat[i, 1] * dy + \
rotmat[i, 2] * dz
sqdist += cont * cont
return sqdist | bigcode/self-oss-instruct-sc2-concepts |
def _is_path_within_scope(scope, fullpath):
"""Check whether the given `fullpath` is within the given `scope`"""
if scope == '/':
return fullpath is not None
fullpath = fullpath.lstrip('/') if fullpath else ''
scope = scope.strip('/')
return (fullpath + '/').startswith(scope + '/') | bigcode/self-oss-instruct-sc2-concepts |
def age_interp(request):
"""Fixture for age_interp flag."""
return request.param | bigcode/self-oss-instruct-sc2-concepts |
def avoids(word, forbidden):
""" Predicate that asks whether word avoids letters in the forbidden string
"""
# Feels like there should be a more efficient way to do this using
# set intersection, but I'll just check the word character by character
for letter in forbidden:
if word.find(letter)!=-1:
return False
return True | bigcode/self-oss-instruct-sc2-concepts |
def get_vocabulary(path_to_vocab):
"""
Return a list of prefixes defining the vocabulary.
"""
vocab = []
with open(path_to_vocab) as f:
for line in f:
line = line.rstrip()
vocab.append(line)
return vocab | bigcode/self-oss-instruct-sc2-concepts |
def b_delta(rewards,states,alpha):
"""
Implements the Resorla-Wagner (delta) learning rule.
V_intial is 0. Note: Null (0 or '0') states are silently skipped.
Returns two dictionaries containing value and RPE timecourses,
for each state.
"""
# Init
s_names = set(states)
V_dict = {}
RPE_dict = {}
for s in s_names:
V_dict[s] = [0.]
RPE_dict[s] = []
for r,s in zip(rewards,states):
## Skip terminal states
if (s == 0) | (s == '0'):
continue
V = V_dict[s][-1]
## the Delta rule:
RPE = r - V
V_new = V + alpha * RPE
## Store and shift V_new to
## V for next iter
V_dict[s].append(V_new)
## Store RPE
RPE_dict[s].append(RPE)
return V_dict, RPE_dict | bigcode/self-oss-instruct-sc2-concepts |
def get_weight_shapes(num_inputs, layer_sizes, num_outputs):
"""
adapted from original tf_model.get_weight_shapes()
to convert from method to function
"""
weight_shapes = []
input_size = num_inputs
for i, layer in enumerate(layer_sizes):
weight_shapes.append((input_size, layer))
weight_shapes.append((layer,))
input_size = layer
weight_shapes.append((input_size, num_outputs))
weight_shapes.append((num_outputs,))
return weight_shapes | bigcode/self-oss-instruct-sc2-concepts |
import warnings
def format_channel_id(ch):
""" Function for formatting an `idelib.dataset.Channel` or `SubChannel`
for display. Renders as only the channel and subchannel IDs (the other
information is shown in the rest of the table).
:param ch: The `idelib.dataset.Channel` or `idelib.dataset.SubChannel`
to format.
:return: A formatted "channel.subchannel" string.
"""
try:
if ch.parent:
return f"{ch.parent.id}.{ch.id}"
else:
return f"{ch.id}.*"
except (AttributeError, TypeError, ValueError) as err:
warnings.warn(f"format_channel_id({ch!r}) raised {type(err).__name__}: {err}")
return str(ch) | bigcode/self-oss-instruct-sc2-concepts |
def _IsBold(weight):
"""Is this weight considered bold?
Per Dave C, only 700 will be considered bold.
Args:
weight: Font weight.
Returns:
True if weight is considered bold, otherwise False.
"""
return weight == 700 | bigcode/self-oss-instruct-sc2-concepts |
def add_attributes(rsrc_id, manifest):
"""Add additional attributes to the manifest."""
proid = rsrc_id[0:rsrc_id.find('.')]
environment = 'prod'
updated = {
'proid': proid,
'environment': environment
}
updated.update(manifest)
return updated | bigcode/self-oss-instruct-sc2-concepts |
def setup_walkers(cfg_emcee, params, level=0.1):
"""Initialize walkers for emcee.
Parameters
----------
cfg_emcee: dict
Configuration parameters for emcee.
params: asap.Parameter object
Object for model parameters.
level: float, optional
Returns
-------
ini_positions: numpy array with (N_walker, N_param) shape
Initial positions of all walkers.
"""
# Initialize the walkers
if cfg_emcee['ini_prior']:
# Use the prior distributions for initial positions of walkers.
return params.sample(nsamples=cfg_emcee['burnin_n_walker'])
return params.perturb(nsamples=cfg_emcee['burnin_n_walker'], level=level) | bigcode/self-oss-instruct-sc2-concepts |
def pack_4_4(x: int, y: int) -> int:
"""Pack two 4-bit values into an
8-bit value.
x and y must be in range 0..15 inclusive.
Result is in range 0..255 inclusive.
"""
assert 0 <= x <= 15
assert 0 <= y <= 15
return (x << 4) | y | bigcode/self-oss-instruct-sc2-concepts |
def _GetLibMetadata(layer):
""" Return a dictionary of library-specific data found in layer."""
globalPrim = layer.GetPrimAtPath('/GLOBAL')
if not globalPrim:
raise Exception("Code generation requires a \"/GLOBAL\" prim with "
"customData to define at least libraryName. GLOBAL prim not found.")
if not globalPrim.customData:
raise Exception("customData is either empty or not defined on /GLOBAL "
"prim. At least \"libraryName\" entries in customData are required "
"for code generation.")
# Return a copy of customData to avoid accessing an invalid map proxy during
# template rendering.
return dict(globalPrim.customData) | bigcode/self-oss-instruct-sc2-concepts |
def build_system_info(platform=None,
platform_type=None,
accel_type=None,
cpu_cores=None,
cpu_type=None,
cpu_sockets=None):
"""Information about the system the test was executed on.
Args:
platform (str): Higher level platform, e.g. aws, gce, or workstation.
platform_type (str): Type of platform, DGX-1, p3.8xlarge, or z420.
accel_type (str, optional): Type of accelerator, e.g. K80 or P100.
cpu_cores (int, optional): Number of physical cpu cores.
cpu_type (str, optional): Type of cpu.
cpu_sockets (int, optional): Number of sockets
Returns:
`dict` with system info.
"""
system_info = {}
if platform:
system_info['platform'] = platform
if platform_type:
system_info['platform_type'] = platform_type
if accel_type:
system_info['accel_type'] = accel_type
if cpu_cores:
system_info['cpu_cores'] = cpu_cores
if cpu_type:
system_info['cpu_type'] = cpu_type
if cpu_type:
system_info['cpu_sockets'] = cpu_sockets
return system_info | bigcode/self-oss-instruct-sc2-concepts |
import re
def strip_spaces(string):
"""Remove white-space from a string
Parameters
----------
string: str
Returns
-------
str
"""
pattern = re.compile(r'\s+')
return re.sub(pattern, '', string) | bigcode/self-oss-instruct-sc2-concepts |
def hexint_parser(arg: str) -> int:
"""Parse a hexadecimal starting with 0x into an integer."""
if not arg.startswith("0x"):
raise Exception("Received non-hex integer where hex expected")
return int(arg, 16) | bigcode/self-oss-instruct-sc2-concepts |
def orbtell(orb):
"""Query current connection read-head position"""
return orb.tell() | bigcode/self-oss-instruct-sc2-concepts |
import random
def random_bbox(config):
"""Generate a random tlhw with configuration.
Args:
config: Config should have configuration including IMG_SHAPES,
VERTICAL_MARGIN, HEIGHT, HORIZONTAL_MARGIN, WIDTH.
Returns:
tuple: (top, left, height, width)
"""
img_shape = config.IMG_SHAPES
img_height = img_shape[0]
img_width = img_shape[1]
maxt = img_height - config.VERTICAL_MARGIN - config.HEIGHT
maxl = img_width - config.HORIZONTAL_MARGIN - config.WIDTH
t = int(random.uniform(config.VERTICAL_MARGIN, maxt))
l = int(random.uniform(config.HORIZONTAL_MARGIN, maxl))
h = config.HEIGHT
w = config.WIDTH
return t, l, h, w | bigcode/self-oss-instruct-sc2-concepts |
from datetime import datetime
def from_epoch(seconds):
"""Given seconds since epoch, return a datetime object
Args:
seconds: Seconds since epoch
Returns:
datetime representation of seconds since epoch
"""
return datetime.utcfromtimestamp(float(seconds)) | bigcode/self-oss-instruct-sc2-concepts |
def _word_feats(words):
"""
NLTK word feature generator for the NaiveBayesClassifier
"""
return dict([(word, True) for word in words]) | bigcode/self-oss-instruct-sc2-concepts |
def build_machine(network=None,
machine_type=None,
preemptible=None,
service_account=None,
boot_disk_size_gb=None,
disks=None,
accelerators=None,
labels=None,
cpu_platform=None,
nvidia_driver_version=None,
enable_stackdriver_monitoring=None):
"""Build a VirtualMachine object for a Pipeline request.
Args:
network (dict): Network details for the pipeline to run in.
machine_type (str): GCE Machine Type string for the pipeline.
preemptible (bool): Use a preemptible VM for the job.
service_account (dict): Service account configuration for the VM.
boot_disk_size_gb (int): Boot disk size in GB.
disks (list[dict]): List of disks to mount.
accelerators (list[dict]): List of accelerators to attach to the VM.
labels (dict[string, string]): Labels for the VM.
cpu_platform (str): The CPU platform to request.
nvidia_driver_version (str): The NVIDIA driver version to use when attaching
an NVIDIA GPU accelerator.
enable_stackdriver_monitoring (bool): Enable stackdriver monitoring
on the VM.
Returns:
An object representing a VirtualMachine.
"""
return {
'network': network,
'machineType': machine_type,
'preemptible': preemptible,
'serviceAccount': service_account,
'bootDiskSizeGb': boot_disk_size_gb,
'disks': disks,
'accelerators': accelerators,
'labels': labels,
'cpuPlatform': cpu_platform,
'nvidiaDriverVersion': nvidia_driver_version,
'enableStackdriverMonitoring': enable_stackdriver_monitoring,
} | bigcode/self-oss-instruct-sc2-concepts |
def copy_event_attributes(ev1, ev2):
"""Copy all attributes from one roxar event to another.
Args:
ev1: roxar event to copy into
ev2: roxar event to copy attributes from
Returns:
An updated version of ev1. Unaltered if the two events are not of same type.
"""
if ev1.type == ev2.type:
for key in ev1.attribute_keys:
ev1[key] = ev2[key]
return ev1 | bigcode/self-oss-instruct-sc2-concepts |
def group_by(object_list, key_function):
"""
Return dictionary of objects grouped by keys returned by
`key_function` for each element in `object_list`.
`object_list` does not need to be sorted.
>>> group_by([1, 2, 3, 4, 5], lambda x: x % 2)
{0: [2, 4], 1: [1, 3, 5]}
"""
groups = dict()
for obj in object_list:
key = key_function(obj)
if key not in groups:
groups[key] = list()
groups[key].append(obj)
return groups | bigcode/self-oss-instruct-sc2-concepts |
def mass_hpa_tail_boom(
length_tail_boom,
dynamic_pressure_at_manuever_speed,
mean_tail_surface_area,
):
"""
Finds the mass of a tail boom structure of a human powered aircraft (HPA), following Juan Cruz's correlations in
http://journals.sfu.ca/ts/index.php/ts/article/viewFile/760/718
Assumes a tubular tail boom of high modules (E > 228 GPa) graphite/epoxy
:param length_tail_boom: length of the tail boom [m]. Calculated as distance from the wing 1/4 chord to the furthest tail surface.
:param dynamic_pressure_at_manuever_speed: dynamic pressure at maneuvering speed [Pa]
:param mean_tail_surface_area: mean of the areas of the tail surfaces (elevator, rudder)
:return: mass of the tail boom [m]
"""
l = length_tail_boom
q = dynamic_pressure_at_manuever_speed
area = mean_tail_surface_area
w_tb = (l * 1.14e-1 + l ** 2 * 1.96e-2) * (1 + ((q * area) / 78.5 - 1) / 2)
return w_tb | bigcode/self-oss-instruct-sc2-concepts |
def find_first2(l, pred1, pred2):
"""
Find first occurrence in list satisfying two-step predicate.
:param l: list.
:param pred1: predicate on the list elements.
:param pred2: predicate on two list elements.
:return: index of first occurrence in list satisfying pred2(l[index-1], l[index])
or pred1(l[0]) if only one elment in the list; length of the list if not found.
"""
length = len(l)
index = length
if length > 0:
if length == 1:
if pred1(l[0]):
index = 0
else:
index = 1
else:
for i in range(1, length):
if pred2(l[i-1], l[i]):
index = i
break
return index | bigcode/self-oss-instruct-sc2-concepts |
from datetime import datetime
def meta_from_pid(product_id):
"""Extract metadata contained in a Landsat Product Identifier."""
meta = {}
parts = product_id.split("_")
meta["product_id"] = product_id
meta["sensor"], meta["correction"] = parts[0], parts[1]
meta["path"], meta["row"] = int(parts[2][:3]), int(parts[2][3:])
meta["acquisition_date"] = datetime.strptime(parts[3], "%Y%m%d")
meta["processing_date"] = datetime.strptime(parts[4], "%Y%m%d")
meta["collection"], meta["tier"] = int(parts[5]), parts[6]
return meta | bigcode/self-oss-instruct-sc2-concepts |
import requests
def check_status(datum):
"""Check that both the url and image link are valid URLs and that the
image link isn't just a redirect.
"""
if requests.get(datum["url"], verify=False).status_code != 200:
return False
get_ = requests.get(datum["image"], verify=False)
if get_.status_code != 200:
return False
if get_.url != datum["image"]:
return False
return True | bigcode/self-oss-instruct-sc2-concepts |
def recursive_find_xml_element( xmlnode, name, _nodes=None ):
"""
recursively finds all XML sub-elements with the name 'name', such as
for nd in recursive_find_xml_element( xmlnode, 'TestList' ):
pass
"""
if _nodes == None:
_nodes = []
for nd in xmlnode:
if nd.tag == name:
_nodes.append( nd )
recursive_find_xml_element( nd, name, _nodes )
return _nodes | bigcode/self-oss-instruct-sc2-concepts |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.