seed stringlengths 1 14k | source stringclasses 2
values |
|---|---|
import re
def is_mac_address(mac):
"""
Test for valid mac address
:type mac: ``str``
:param mac: MAC address in the form of AA:BB:CC:00:11:22
:return: True/False
:rtype: ``bool``
"""
if re.search(r'([0-9A-F]{2}[:]){5}([0-9A-F]){2}', mac.upper()) is not None:
return True
else:
return False | bigcode/self-oss-instruct-sc2-concepts |
import json
def create_label(name, color, repos, session, origin):
"""
Creates label
:param name: name of the label
:param color: color of the label
:param repos: repository where label is created
:param session: session for communication
:param origin: repository where the label came from
:return: message code 200 (int)
"""
for repo in repos:
if(repo != origin):
data = {"name": name, "color": color}
json_data = json.dumps(data)
r = session.post("https://api.github.com/repos/"+repo+"/labels", json_data)
return "200" | bigcode/self-oss-instruct-sc2-concepts |
def num_leading_spaces(str):
""" Return the number of leading whitespaces of given string """
for i, c in enumerate(str):
if c != ' ': return i
return len(str) | bigcode/self-oss-instruct-sc2-concepts |
def memoize(f):
"""A simple memoize decorator for functions."""
cache= {}
def memf(*x):
if x not in cache:
cache[x] = f(*x)
return cache[x]
return memf | bigcode/self-oss-instruct-sc2-concepts |
import json
def parse_json_file(file_path: str):
"""utility method to read a json file and return json object
Parameters
----------
file_path : str
full path to json file that needs to be parsed
Returns
-------
[type]
json object parsed from the file
"""
with open(file_path, "r") as f:
json_data = json.load(f)
return json_data | bigcode/self-oss-instruct-sc2-concepts |
def to_int(x):
"""Convert bytes to an integer."""
return int(x.hex(), 16) | bigcode/self-oss-instruct-sc2-concepts |
from typing import OrderedDict
def custom_sort_exps(exps):
"""
Sort the experiments according to JIRA LCLSECSD-210
Active first, OPS next and then descending run period/alphabetical within that run period
"""
# Python's sort is stable; so we sort multiple times lowest attr first
exps = OrderedDict(sorted(exps.items(), key=lambda x : x[1]["name"]))
# print( [ v["name"] for k, v in exps.items() ] )
exps = OrderedDict(sorted(exps.items(), key=lambda x : x[1]["name"][-2:], reverse=True))
exps = OrderedDict(sorted(exps.items(), key=lambda x : not x[1].get("instrument", "") == "OPS"))
exps = OrderedDict(sorted(exps.items(), key=lambda x : not x[1].get("is_active", False)))
return exps | bigcode/self-oss-instruct-sc2-concepts |
def _match_some(regexes, line, n_line, n_col):
"""Match patterns in order. Returns a tuple of match and token type or
raises SyntaxError."""
for regex, token in regexes:
match = regex.match(line, n_col)
if match is not None:
return match, token
error = "No rules to match input (does not conform this grammar) \n"
error += "At line %d, column %d" % (n_line, n_col)
error += "\n\t%s" % line
error += "\n" if line[-1] != "\n" else ""
error += "\t" + "_" * (n_col - 1) + "/\\" + "_" * (len(line) - n_col - 2)
raise SyntaxError(error) | bigcode/self-oss-instruct-sc2-concepts |
def seconds_for_analysis(duration, measurement_type, selector):
"""Get duration for specified measurement type and selector."""
if measurement_type in duration:
data = duration[measurement_type]
if selector in data:
return data[selector].duration_seconds
return 0 | bigcode/self-oss-instruct-sc2-concepts |
def duplicates_checker(source, new):
"""
Checking for duplicates in existing list of contacts
"""
for item in source:
if new == item['phone']:
return False
return True | bigcode/self-oss-instruct-sc2-concepts |
def _multiplot_interval(from_date, to_date, points):
"""
Computes the size of the interval between points in a multiplot.
:return: the multiplot interval size.
:rtype: ``float``
"""
if points < 2:
return 0.0
return (to_date - from_date) / (points - 1) | bigcode/self-oss-instruct-sc2-concepts |
def wma(df, price, wma, n):
"""
The Weighted Moving Average calculates a weight for each value in the series.
The more recent values are assigned greater weights. The Weighted Moving
Average is similar to a Simple Moving average in that it is not cumulative,
that is, it only includes values in the time period (unlike an Exponential
Moving Average). The Weighted Moving Average is similar to an Exponential
Moving Average in that more recent data has a greater contribution to the
average.
Parameters:
df (pd.DataFrame): DataFrame which contain the asset price.
price (string): the column name of the price of the asset.
wma (string): the column name for the n-day weighted moving average results.
n (int): the total number of periods.
Returns:
df (pd.DataFrame): Dataframe with n-day weighted moving average of the asset calculated.
"""
def wa(x):
return sum([(i + 1) * p for i, p in enumerate(x)]) / (n * (n + 1) / 2)
df[wma] = df[price].rolling(window=n).apply(lambda x: wa(x), raw=True)
return df | bigcode/self-oss-instruct-sc2-concepts |
def recurse_combine(combo_items: list, idx: int = 0) -> list:
"""Recursively expands 'combo_items' into a list of permutations.
For example recurse_combine([[A, B, C], [D, E], [F]]) returns
[[A, D, F], [A, E, F], [B, D, F], [B, E, F], [C, D, F], [C, E, F]]
"""
result = []
if idx < len(combo_items):
recurse_result = recurse_combine(combo_items, idx + 1)
for item in combo_items[idx]:
for sub_item in recurse_result:
sub_result = [item]
sub_result.extend(sub_item)
result.append(sub_result)
if len(recurse_result) == 0:
result.append([item])
return result | bigcode/self-oss-instruct-sc2-concepts |
def _ask_yes_no(prompt: str) -> bool:
"""Simple function that prompts user until they answer 'y' or 'n'"""
answer = input(prompt).lower()
while answer not in ("y", "n"):
answer = input("Please enter 'y' or 'n': ").lower()
if answer == "y":
return True
else:
return False | bigcode/self-oss-instruct-sc2-concepts |
def to_upper(string):
""":yaql:toUpper
Returns a string with all case-based characters uppercase.
:signature: string.toUpper()
:receiverArg string: value to uppercase
:argType string: string
:returnType: string
.. code::
yaql> "aB1c".toUpper()
"AB1C"
"""
return string.upper() | bigcode/self-oss-instruct-sc2-concepts |
def linspace(a, b, num_chunks):
"""Returns equidistant steps in [a, b] whose number matches num_chunks."""
assert isinstance(num_chunks, int) and num_chunks > 0, 'Number of chunks must be a natural number!'
h = (b - a) / num_chunks
return [a + i * h for i in range(num_chunks + 1)] | bigcode/self-oss-instruct-sc2-concepts |
def safe_hasattr(item: object, member: str) -> bool:
"""Safe version of ``hasattr()``."""
try:
# some sketchy implementation (like paste.registry) of
# __getattr__ cause hasattr() to throw an error.
return hasattr(item, member)
except Exception:
return False | bigcode/self-oss-instruct-sc2-concepts |
import fnmatch
def _get_pprint_include_names(table):
"""Get the set of names to show in pprint from the table pprint_include_names
and pprint_exclude_names attributes.
These may be fnmatch unix-style globs.
"""
def get_matches(name_globs, default):
match_names = set()
if name_globs: # For None or () use the default
for name in table.colnames:
for name_glob in name_globs:
if fnmatch.fnmatch(name, name_glob):
match_names.add(name)
break
else:
match_names.update(default)
return match_names
include_names = get_matches(table.pprint_include_names(), table.colnames)
exclude_names = get_matches(table.pprint_exclude_names(), [])
return include_names - exclude_names | bigcode/self-oss-instruct-sc2-concepts |
def _recall(conf_mat):
"""
Compute the recall score, i.e. the ratio of true positives to true positives and false negatives.
Answers the question: "Which share of the pixels that are actually slum was identified by the model as such?"
:param conf_mat: Confusion matrix produced by conf_mat().
:return: Recall score, ranging from 0 to 1.
"""
# print('recall: ', conf_mat['tp'], conf_mat['tn'], conf_mat['fp'], conf_mat['fn'])
if conf_mat['tp'] + conf_mat['fn'] == 0:
recall = 0
else:
recall = conf_mat['tp'] / (conf_mat['tp'] + conf_mat['fn'])
return recall | bigcode/self-oss-instruct-sc2-concepts |
def recursive_lookup(dict_object, keys):
"""
Given a dict object and list of keys, nest into those keys.
Raises KeyError if the path isn't found.
>>> recursive_lookup({'foo': 1}, ['foo'])
1
>>> recursive_lookup({'foo': {'bar': 1}}, ['foo'])
{'bar': 1}
>>> recursive_lookup({'foo': {'bar': 1}}, ['foo', 'bar'])
1
"""
if not keys or not isinstance(keys, list):
raise ValueError('Keys must be a non-empty list!')
if len(keys) == 1:
return dict_object[keys[0]]
else:
return recursive_lookup(dict_object[keys[0]], keys[1:]) | bigcode/self-oss-instruct-sc2-concepts |
def get_table_id(current_page, objects_per_page, loop_counter):
"""
Calculate correct id for table in project page. This function is used only for pagination purposes.
"""
return ((current_page - 1) * objects_per_page) + loop_counter | bigcode/self-oss-instruct-sc2-concepts |
def get_kp_labels(bands_node, kpoints_node=None):
"""
Get Kpoint labels with their x-positions in matplotlib compatible format.
A KpointsData node can optionally be given to fall back to if no labels
are found on the BandsData node. The caller is responsible for ensuring
the nodes match. This should be the case if you take the kpoints from
the input and the bands from the
output of a calculation node.
:param BandsData bands_node:
The BandsData node will be searched labels first
:param KpointsData kpoints_node:
The optional KpointsData node will be searched only if no labels are
present on the BandsData node. No consistency checks are performed.
:return: (kpx, kpl), the x-coordinates and text labels
:rtype: tuple(list[int], list[unicode])
:raises AttributeError: if neither of the given nodes have a labels
attribute
"""
kplabs = None
kpx = []
kpl = []
try:
kplabs = bands_node.labels
except AttributeError as err:
if kpoints_node:
kplabs = kpoints_node.labels
else:
raise err
if kplabs:
kpx = [i[0] for i in kplabs]
kpl = [i[1] for i in kplabs]
for i, kpoints in enumerate(kpl):
if kpoints == 'G':
kpl[i] = r'$\Gamma$'
return kpx, kpl | bigcode/self-oss-instruct-sc2-concepts |
def IndexOfMin(inputList):
"""
Return the index of the min value in the supplied list
"""
assert(len(inputList) > 0)
index = 0
minVal = inputList[0]
for i, val in enumerate(inputList[1:]):
if val < minVal:
minVal = val
index = i + 1
return index | bigcode/self-oss-instruct-sc2-concepts |
def filter_profile(data, profile):
"""
Take a dataframe after it has been processed by merge_data, and a profile
and returns a filtered dataframe of players with that profile. Valid profiles
are 'long_inaccurate', 'long_accurate', 'short_inaccurate', 'short_inaccurate'.
"""
player_aggregates = data[data['Date'] == '2019-08-25']
if profile == 'long_inaccurate':
acc_thresh = 55
dist_thresh = 300
criteria = (player_aggregates['Distance'] > dist_thresh) & (player_aggregates['Accuracy (%)'] < acc_thresh)
elif profile == 'long_accurate':
acc_thresh = 65
dist_thresh = 300
criteria = (player_aggregates['Distance'] > dist_thresh) & (player_aggregates['Accuracy (%)'] > acc_thresh)
elif profile == 'short_inaccurate':
acc_thresh = 60
dist_thresh = 290
criteria = (player_aggregates['Distance'] < dist_thresh) & (player_aggregates['Accuracy (%)'] < acc_thresh)
elif profile == 'short_accurate':
acc_thresh = 70
dist_thresh = 280
criteria = (player_aggregates['Distance'] < dist_thresh) & (player_aggregates['Accuracy (%)'] > acc_thresh)
else:
return 'Error: enter valid profile'
filtered = player_aggregates[criteria]
result = data[data['Player Name'].isin(filtered['Player Name'])]
return result | bigcode/self-oss-instruct-sc2-concepts |
def mat_like_array(start, end, step=1):
"""
Generate a matlab-like array start:end
Subtract 1 from start to account for 0-indexing
"""
return list(range(start-1, end, step)) | bigcode/self-oss-instruct-sc2-concepts |
def rotate(pos, vel, matrix):
"""
Rotate.
Applies the rotation `matrix` to a set of particles positions `pos` and
velocities `vel`
Parameters
----------
pos : `np.ndarray`, shape = (N_part, 3)
Positions of particles
vel : `np.ndarray`, shape = (N_part, 3)
Velocities of particles
matrix : `np.ndarray`
Rotation matrix, with shape (3, 3)
Returns
-------
pos_rot : `np.ndarray`, shape = (N_part, 3)
Rotated, positions of particles
vel_rot : `np.ndarray`, shape = (N_part, 3)
Rotated, velocities of particles
"""
pos_rot = pos @ matrix
vel_rot = vel @ matrix
return pos_rot, vel_rot | bigcode/self-oss-instruct-sc2-concepts |
def generate_public(private, generator, modulus):
"""Calculates the public Diffie-Hellman key given g, p, and the private key"""
return pow(generator, private, modulus) | bigcode/self-oss-instruct-sc2-concepts |
import base64
def custom_jinja2_filter(string):
"""encodes a string using base64 schema"""
return base64.b64encode(string.encode("UTF-8")).decode("UTF-8") | bigcode/self-oss-instruct-sc2-concepts |
def assume_role_response_to_session_kwargs(assume_role_resp):
"""Convert assume role response to kwargs for boto3.Session
Also useful for creating AWS credentials file.
"""
return dict(aws_access_key_id=assume_role_resp['Credentials']['AccessKeyId'],
aws_secret_access_key=assume_role_resp['Credentials']['SecretAccessKey'],
aws_session_token=assume_role_resp['Credentials']['SessionToken'], ) | bigcode/self-oss-instruct-sc2-concepts |
def join_ints(*ints):
"""Given a list of ints, return a underscore separated strings with them.
>>> join_ints(1, 2, 3)
'1_2_3'
"""
return '_'.join(map(str, ints)) | bigcode/self-oss-instruct-sc2-concepts |
import math
def make_multiple(x, number):
""" Increases x to be the smallest multiple of number """
return int(math.ceil(float(x) / float(number)) * number) | bigcode/self-oss-instruct-sc2-concepts |
def zones2list(zones, type="power"):
"""Convert zones Strava response into a list
Parameters
----------
zones : dict
Strava API zones response
type : {"power", "heart_rate"}
Returns
-------
y : list
Zones boundaries with left edge set to -1 and right to 10000
"""
y = list(map(lambda x: x['min'], zones[type]["zones"]))
y[0] = -1
y.append(10000)
return y | bigcode/self-oss-instruct-sc2-concepts |
def retrieve_commands(commands):
"""
Retrieve context needed for a set of commit actions
"""
config_commands = commands['config']
support_commit = commands.get('support_commit')
config_verify = commands['config_verification']
return (config_commands, support_commit, config_verify) | bigcode/self-oss-instruct-sc2-concepts |
import re
def RemoveFrameShiftsFromAlignment(row_ali, col_ali, gap_char="-"):
"""remove frame shifts in an alignment.
Frameshifts are gaps are 1, 2, 4, or 5 residues long.
>>> RemoveFrameShiftsFromAlignment("ABC-EFG", "AB-DEFG")
('ABEFG', 'ABEFG')
Arguments
---------
row_ali : string
Alignment string of row.
col_ali : string
Alignment string of column.
gap_char : string
Gap character to identify aligments.
Returns
-------
new_row_ali : string
New alignment string for row
new_col_ali : string
New aligment string for column
"""
match_string = "[^%s]%s+[^%s]" %\
(gap_char, gap_char, gap_char)
positions = []
for x in re.finditer(match_string, row_ali):
positions.append((x.start() + 1, x.end() - 1))
for x in re.finditer(match_string, col_ali):
positions.append((x.start() + 1, x.end() - 1))
positions.sort()
# cut and paste new alignment
new_row_ali = []
new_col_ali = []
a = 0
for first, last in positions:
if (last - first) % 3:
new_row_ali.append(row_ali[a:first])
new_col_ali.append(col_ali[a:first])
a = last
new_row_ali.append(row_ali[a:])
new_col_ali.append(col_ali[a:])
return "".join(new_row_ali), "".join(new_col_ali) | bigcode/self-oss-instruct-sc2-concepts |
async def headers_middleware(req, handler):
"""
Middleware that adds the current version of the API to the response.
"""
resp = await handler(req)
resp.headers["X-Virtool-Version"] = req.app["version"]
resp.headers["Server"] = "Virtool"
return resp | bigcode/self-oss-instruct-sc2-concepts |
def loantovalue(purchaseprice, financedamount):
"""Return ratio of financed amount to purchase price.
:param purchaseprice: Contract price of property.
:type purchaseprice: double
:param financedamount: Amount of money borrowed.
:type financedamount: double
:return: double
"""
return financedamount / purchaseprice | bigcode/self-oss-instruct-sc2-concepts |
def squeeze(array):
"""Return array contents if array contains only one element.
Otherwise, return the full array.
"""
if len(array) == 1:
array = array[0]
return array | bigcode/self-oss-instruct-sc2-concepts |
def to_label(name, capitalize=True):
"""Converts `name` into label by replacing underscores by spaces. If
`capitalize` is ``True`` (default) then the first letter of the label is
capitalized."""
label = name.replace("_", " ")
if capitalize:
label = label.capitalize()
return label | bigcode/self-oss-instruct-sc2-concepts |
from functools import reduce
from typing import cast
def cast_schema(df, schema):
"""Enforce the schema on the data frame.
Args:
df (DataFrame): The dataframe.
schema (list): The simple schema to be applied.
Returns:
A data frame converted to the schema.
"""
spark_schema = schema.to_spark()
# return spark_session.createDataFrame(df.rdd, schema=spark_schema)
return reduce(cast,
spark_schema.fields,
df.select(*spark_schema.fieldNames())) | bigcode/self-oss-instruct-sc2-concepts |
def get_social_auths_for_user(user, provider=None):
"""Get UserSocialAuths for given `user`
Filter by specific `provider` if set
Returns a QuerySet of UserSocialAuth objects
"""
social_users = user.social_auth
if provider is None:
social_users = social_users.all()
else:
social_users = social_users.filter(
provider=provider
)
return social_users | bigcode/self-oss-instruct-sc2-concepts |
def get_sub_series(sub_cats):
""" Gets the series IDs of all the subseries that are in UTC time
associated with a given load balancing station """
series = []
for category in sub_cats['category']['childseries']:
if "UTC time" in category['name']:
series.append(category['series_id'])
return series | bigcode/self-oss-instruct-sc2-concepts |
from typing import Union
from pathlib import Path
def guess_format(filename: Union[str, Path]):
"""
Guess the output format from a given filename and return the corrected format.
Any names not in the dict get passed through.
"""
extension = str(filename).rsplit(".", 1)[-1].lower()
format_map = {
"gtiff": "GTiff", "geotiff": "GTiff", "geotif": "GTiff", "tiff": "GTiff", "tif": "GTiff",
"nc": "netCDF", "netcdf": "netCDF",
}
return format_map.get(extension, extension.upper()) | bigcode/self-oss-instruct-sc2-concepts |
def sub(num1, num2):
"""
Subtract two numbers
"""
return num1 - num2 | bigcode/self-oss-instruct-sc2-concepts |
import re
def remove_links(text: str) -> str:
"""
Removes links from a text.
Args:
text (:obj:`str`):
Text to process.
Returns:
:obj:`str`:
Text without links.
"""
# add empty character between two paragraph html tags to make processing easier
text = re.sub('</p><p>', '</p> <p>', text)
#return re.sub('http[s]*[:]*[\/]*[a-z0-9./-]*', '', text, flags=re.MULTILINE)
return re.sub(r"http\S+", "", text) | bigcode/self-oss-instruct-sc2-concepts |
from typing import List
def _validate_counts(counts: List[int]) -> bool:
"""
Validates the counts parameter.
Parameters
----------
counts : List[integers]
A list of counts.
Raises
------
TypeError
The ``counts`` parameter is not a list or one of the elements of this
list is not an integer.
ValueError
One of the counts is a negative integer.
Returns
-------
is_valid : boolean
``True`` if counts is valid, ``False`` otherwise.
"""
is_valid = False
if isinstance(counts, list):
for count in counts:
if isinstance(count, int):
if count < 0:
raise ValueError('Counts cannot be negative integers.')
else:
raise TypeError('Counts have to be integers.')
else:
raise TypeError('The counts parameter has to be a list of integers.')
is_valid = True
return is_valid | bigcode/self-oss-instruct-sc2-concepts |
def get_max_width(text_array):
"""Get the maximum width of a bunch of rows of text."""
width = 0
# Figure out the maximum width
for row in text_array:
if len(row) > width:
width = len(row)
return width | bigcode/self-oss-instruct-sc2-concepts |
import torch
def generate_proposals(anchors, offsets, method="YOLO"):
"""
Generate all proposals from anchors given offsets.
@Params:
-------
anchors (tensor):
Tensor of shape [B, A, H', W', 4] returned by `generate_anchors()`. Anchors are
parameterized by the coordinates (x_tl, y_tl, x_br, y_br).
offsets (tensor):
Transformations of the same shape as anchors, [B, A, H', W', 4], that will be
used to convert anchor boxes into region proposals. The formula the transformation applied
from offsets[b, a, h, w] = (tx, ty, th, tw) to anchors[b, a, h, w] = (x_tl, y_tl, x_br, y_bt)
will be different according to `method`:
method == "YOLO": # Assume values in range
cx_p = cx_a + tx # `tx` in range [-0.5, 0.5]
cy_p = cy_a + ty # `ty` in range [-0.5, 0.5]
w_p = w_a * e^tw # `tw` in range [-inf, +inf]
h_p = h_a * e^th # `th` in range [-inf, +inf]
method == "FasterRCNN": # Assume values in range
cx_p = cx_a + tx * w_a # `tx` in range [-inf, +inf]
cy_p = cy_a + ty * h_a # `ty` in range [-inf, +inf]
w_p = w_a * e^tw # `tw` in range [-inf, +inf]
h_p = h_a * e^th # `th` in range [-inf, +inf]
method (string):
Indicate which transformation to apply, either "YOLO" or "FasterRCNN"
@Returns:
-------
proposals (tensor):
Region proposals, tensor of shape [B, A, H', W', 4], represented by the coordinates of
(x_tl, y_tl, x_br, y_br).
"""
assert method in ["YOLO", "FasterRCNN"], "Invalid method, either `YOLO` or `FasterRCNN`!"
# 1. Convert anchors from (x_tl, y_tl, x_br, y_br) to (cx, cy, w, h)
anchors_xywh = torch.zeros_like(anchors)
anchors_xywh[..., :2] = anchors[..., 2:] / 2. + anchors[..., :2] / 2.
anchors_xywh[..., 2:] = anchors[..., 2:] - anchors[..., :2]
# 2. Apply transformation
proposals_xywh = torch.zeros_like(anchors)
if method == "YOLO":
proposals_xywh[..., :2] = anchors_xywh[..., :2] + offsets[..., :2]
proposals_xywh[..., 2:] = anchors_xywh[..., 2:] * torch.exp(offsets[..., 2:])
else:
proposals_xywh[..., :2] = anchors_xywh[..., :2] + anchors_xywh[..., 2:] * offsets[..., :2]
proposals_xywh[..., 2:] = anchors_xywh[..., 2:] * torch.exp(offsets[..., 2:])
# 3. Convert proposals from (cx, cy, w, h) back to (x_tl, y_tl, x_br, y_br)
proposals = torch.zeros_like(proposals_xywh)
proposals[..., :2] = proposals_xywh[..., :2] - proposals_xywh[..., 2:] / 2.
proposals[..., 2:] = proposals_xywh[..., :2] + proposals_xywh[..., 2:] / 2.
return proposals | bigcode/self-oss-instruct-sc2-concepts |
def constrain(value, lowest, highest):
"""Test whether `value` is within the range `(highest, lowest)`.
Return `value` if it is inside the range, otherwise return
`highest` if the value is *above* the range or `lowest` it the value
is *below* the range.
>>> constrain(-1, 2, 5)
2
>>> constrain(1, 2, 5)
2
>>> constrain(0, 2, 5)
2
>>> constrain(2, 2, 5)
2
>>> constrain(3, 2, 5)
3
>>> constrain(5, 2, 5)
5
>>> constrain(6, 2, 5)
5
>>> constrain(10, 2, 5)
5
"""
return min(highest, max(value, lowest)) | bigcode/self-oss-instruct-sc2-concepts |
def first(mention):
""" Compute the first token of a mention.
Args:
mention (Mention): A mention.
Returns:
The tuple ('first', TOKEN), where TOKEN is the (lowercased) first
token of the mention.
"""
return "first", mention.attributes["tokens"][0].lower() | bigcode/self-oss-instruct-sc2-concepts |
def convert_velocity(val, old_scale="km/h", new_scale="m/s"):
"""
Convert from a velocity scale to another one among km/h, and m/s.
Parameters
----------
val: float or int
Value of the velocity to be converted expressed in the original scale.
old_scale: str
Original scale from which the angle value will be converted.
Supported scales are km/h or m/s.
new_scale: str
New scale from which the angle value will be converted.
Supported scales are km/h or m/s.
Raises
-------
NotImplementedError if either of the scales are not one of the requested
ones.
Returns
-------
res: float
Value of the converted velocity expressed in the new scale.
"""
# Convert from 'old_scale' to m/s
if old_scale == 'm/s':
temp = val
elif old_scale == 'km/h':
temp = val * 3.6
else:
raise AttributeError(
f'{old_scale} is unsupported. km/h and m/s are supported')
# and from m/s to 'new_scale'
if new_scale == 'm/s':
result = temp
elif new_scale == 'km/h':
result = temp / 3.6
else:
raise AttributeError(
f'{new_scale} is unsupported. km/h and m/s are supported')
return result | bigcode/self-oss-instruct-sc2-concepts |
import calendar
def get_month_dispatch_intervals(year, month):
"""Get all dispatch interval IDs for a given month"""
days = range(1, calendar.monthrange(year, month)[1] + 1)
intervals = range(1, 289)
return [f'{year}{month:02}{d:02}{i:03}' for d in days for i in intervals] | bigcode/self-oss-instruct-sc2-concepts |
from pkg_resources import iter_entry_points
def mock_iter_entry_points_factory(data, mocked_group):
"""Create a mock iter_entry_points function."""
def entrypoints(group, name=None):
if group == mocked_group:
for entrypoint in data:
yield entrypoint
else:
for x in iter_entry_points(group=group, name=name):
yield x
return entrypoints | bigcode/self-oss-instruct-sc2-concepts |
def isprime(number):
"""
Check if a number is a prime number
number:
The number to check
"""
if number == 1:
return False
for i in range(2, int(number**0.5) + 1):
if number % i == 0:
return False
return True | bigcode/self-oss-instruct-sc2-concepts |
def import_class_by_path(class_path):
"""Import a class by its <module>.<name> path.
Args:
class_path: <module>.<name> for a class.
Returns:
Class object for the given class_path.
"""
classname = class_path.split('.')[-1]
modulename = '.'.join(class_path.split('.')[0:-1])
mod = __import__(modulename, fromlist=[classname])
return getattr(mod, classname) | bigcode/self-oss-instruct-sc2-concepts |
def avg(l):
"""Returns the average of a list of numbers."""
if not l:
return None
return sum(l)/len(l) | bigcode/self-oss-instruct-sc2-concepts |
import re
def clean_str(text: str) -> str:
"""
Args:
text: A unicode string
Returns:
str: lowercased, sans punctuation, non-English letters
"""
RE_PREPROCESS = r'\W+|\d+'
text = re.sub(
RE_PREPROCESS,
' ',
text.lower()
)
text = re.sub(r"[^A-Za-z0-9(),!?\'\`]", " ", text)
text = re.sub(r"\'s", " \'s", text)
text = re.sub(r"\'ve", " \'ve", text)
text = re.sub(r"n\'t", " n\'t", text)
text = re.sub(r"\'re", " \'re", text)
text = re.sub(r"\'d", " \'d", text)
text = re.sub(r"\'ll", " \'ll", text)
text = re.sub(r"\s{2,}", " ", text)
return text | bigcode/self-oss-instruct-sc2-concepts |
def NetworkSetSFANodeClass(sfa_node_class, network):
"""Replaces the field sfa_node_class of all layers with a specific node class.
This function is useful, for example, to transform an SFA network into a PCA network. """
for i, layer in enumerate(network.layers):
layer.sfa_node_class = sfa_node_class
return network | bigcode/self-oss-instruct-sc2-concepts |
import math
import random
def optimizar(dominio, temperatura = 10e32, tasa_enfriamiento = 0.95):
"""Algoritmo de optimización estocástica simulated annealing.
Entradas:
dominio (Dominio)
Un objeto que modela el dominio del problema que se quiere aproximar.
temperatura (float/int)
Temperatura inicial del algoritmo, se recomienda un número alto
tasa_enfriamiento (float)
Porcentaje de enfriamiento de la temperatura durante cada iteración, el valor
por defecto es 0.95, lo que indica una tasa de enfriamiento del 5%.
Salidas:
(estructura de datos) Estructura de datos según el dominio, que representa una
aproximación a la mejor solución al problema.
"""
sol = dominio.generar()
costo = dominio.fcosto(sol)
while temperatura > 0.01:
solTemp = dominio.vecino(sol)
costoTemp = dominio.fcosto(solTemp)
p = math.exp(-abs(costoTemp-costo)/temperatura)
pAzar = random.uniform(0, 1)
if (costoTemp < costo) or (pAzar <= p):
sol = solTemp
costo = costoTemp
temperatura *= tasa_enfriamiento
return sol | bigcode/self-oss-instruct-sc2-concepts |
import torch
def collate_fn(samples):
"""
collate_fn for SequentialMNIST.
Args:
samples: a list of samples. Each item is a (imgs, nums) pair. Where
- imgs: shape (T, 1, C, H, W)
- nums: shape (T, 1)
And len(samples) is the batch size.
Returns:
A tuple (imgs, nums). Where
- imgs: shape (T, B, C, H, W)
- nums: shape (T, B)
"""
imgs, nums = zip(*samples)
# (T, B, C, H, W)
imgs = torch.cat(imgs, dim=1)
# (T, B)
nums = torch.cat(nums, dim=1)
return imgs, nums | bigcode/self-oss-instruct-sc2-concepts |
def utf8_encode(s: str) -> bytes:
"""Encodes a string with utf-8 and returns its byte sequence.
Invalid surrogates will be replaced with U+FFFD.
Args:
s: A string to encode with utf-8.
Returns:
A utf-8 encoded byte sequence.
"""
s = s.encode("utf-16", "surrogatepass").decode("utf-16", "replace")
return s.encode("utf-8", "strict") | bigcode/self-oss-instruct-sc2-concepts |
def subdirs(folderpath, pattern="*"):
"""
returns all sub folders in a given folder matching a pattern
"""
return [f for f in folderpath.glob(pattern) if f.is_dir()] | bigcode/self-oss-instruct-sc2-concepts |
def extract_keywords(lst_dict, kw):
"""Extract the value associated to a specific keyword in a list of
dictionaries. Returns the list of values extracted from the keywords.
Parameters
----------
lst_dict : python list of dictionaries
list to extract keywords from
kw : string
keyword to extract from dictionary
"""
lst = [di[kw] for di in lst_dict]
return lst | bigcode/self-oss-instruct-sc2-concepts |
def flatten_dict(input_dict):
"""Returns flattened dictionary given an input dictionary with maximum depth
of 2
Args:
input_dict (dict): `str → number` key-value pairs, where value can be a
number or a dictionary with `str → number` key-value paris.
Returns:
dict: Flattened dictionary with underscore-separated keys if
`input_dict` contained nesting
"""
output_dict = dict()
for key, value in input_dict.items():
if isinstance(value, dict):
for subkey, subvalue in value.items():
output_dict[f"{key}_{subkey}"] = subvalue
else:
output_dict[key] = value
return output_dict | bigcode/self-oss-instruct-sc2-concepts |
import re
def remove_vowels(string=''):
"""
Removes the vowels from the given string.
According to the rules the letters A, E, I, O, U are considered vowels.
:param string: The input to remove vowels from
:return: The given string without vowels
"""
return re.sub('a|e|i|o|u|y', '', string, flags=re.IGNORECASE) | bigcode/self-oss-instruct-sc2-concepts |
def header_check(file):
"""Checks whether the file has a header or not.
Parameters
----------
file : str
Filename or filepath of file to check
Returns
-------
int
1 if header is present 0 if not
"""
with open(file, "r", encoding="utf-8") as to_check:
result = to_check.read(1).isalpha()
return int(result) | bigcode/self-oss-instruct-sc2-concepts |
def build_parms(args):
"""Helper function to parse command line arguments into dictionary
input: ArgumentParser class object
output: dictionary of expected parameters
"""
readDir=args.dir
outdir=args.outdir
parms = {"readDir":readDir,
"outdir":outdir}
return(parms) | bigcode/self-oss-instruct-sc2-concepts |
import re
def strip_config_header(config):
"""Normalize items that should not show up in IOS-XR compare_config."""
config = re.sub(r"^Building config.*\n!! IOS.*", "", config, flags=re.M)
config = config.strip()
config = re.sub(r"^!!.*", "", config)
config = re.sub(r"end$", "", config)
return config.strip() | bigcode/self-oss-instruct-sc2-concepts |
def get_item_relative_limit(page, per_page):
"""Get the maximum possible number of items on one page."""
return per_page | bigcode/self-oss-instruct-sc2-concepts |
def p1(range_max, factor_list):
"""Problem 1
If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23.
Find the sum of all the multiples of 3 or 5 below 1000.
"""
range_min = 0
sum_multiples = 0
for num in range(range_max):
if num % factor_list[0] == 0:
sum_multiples = sum_multiples + num
elif num % factor_list[1] == 0:
sum_multiples = sum_multiples + num
# print(num)
print("Summation of multiples is: %g" % sum_multiples)
return sum_multiples | bigcode/self-oss-instruct-sc2-concepts |
import re
def regex_search_list(data, regex):
"""
Allows you to search across a list with regex returns True if any match in the list.
:param data: The element to search
:param regex: The regex search string
:return: True if any elements match, false if none match
"""
# Create the data into a list if it isn't already
if type(data) is not list:
data = [data]
for d in data:
if re.search(regex, d):
return True
return False | bigcode/self-oss-instruct-sc2-concepts |
from typing import Union
def convert_strike(strike: Union[int, float]) -> Union[int, float]:
"""
Convert the type of the strike to an integer if it is an integer or float to 2 points if it is a float
Note
----
This is only a type conversion
"""
if (strike - int(strike)) == 0:
return int(strike)
else:
return round(strike, 2) | bigcode/self-oss-instruct-sc2-concepts |
def string_is_equal_case_insensitive(subject: str, value: str) -> bool:
"""Case insensitive string is equal"""
return subject.strip().lower() == value.strip().lower() | bigcode/self-oss-instruct-sc2-concepts |
def find_odd_occurred_number_sol2(nums):
"""
You are given an array of repeating numbers. All numbers repeat in even way, except for
one. Find the odd occurring number.
- This solution takes less space.
- More details: https://youtu.be/bMF2fG9eY0A
- Time: O(len(nums))
- Space: worst: O(len(nums))
"""
values = set()
for value in nums:
if value in values:
values.remove(value)
else:
values.add(value)
return next(iter(values)) | bigcode/self-oss-instruct-sc2-concepts |
from typing import List
def route_ranks(scores: List[float]) -> List[int]:
"""
Compute the rank of route scores. Rank starts at 1
:param scores: the route scores
:return: a list of ranks for each route
"""
ranks = [1]
for idx in range(1, len(scores)):
if abs(scores[idx] - scores[idx - 1]) < 1e-8:
ranks.append(ranks[idx - 1])
else:
ranks.append(ranks[idx - 1] + 1)
return ranks | bigcode/self-oss-instruct-sc2-concepts |
def transformer(y, func=None):
"""Transforms target variable and prediction"""
if func is None:
return y
else:
return func(y) | bigcode/self-oss-instruct-sc2-concepts |
import torch
def split_stack(x, split_sizes, split_dim, stack_dim):
"""Split x along dimension split_dim and stack again at dimension stack_dim"""
t = torch.stack(torch.split(x, split_sizes, dim=split_dim), dim=stack_dim)
return t | bigcode/self-oss-instruct-sc2-concepts |
import re
def parse_int_sprintf_pattern(patt):
"""Parses the integer sprintf pattern and returns a function that can
detect whether a string matches the pattern.
Args:
patt: a sprintf pattern like "%05d", "%4d", or "%d"
Returns:
a function that returns True/False whether a given string matches the
input numeric pattern
"""
# zero-padded: e.g., "%05d"
zm = re.match(r"%0(\d+)d$", patt)
if zm:
n = int(zm.group(1))
def _is_zero_padded_int_str(s):
try:
num_digits = len(str(int(s)))
except ValueError:
return False
if num_digits > n:
return True
return len(s) == n and s[:-num_digits] == "0" * (n - num_digits)
return _is_zero_padded_int_str
# whitespace-padded: e.g., "%5d"
wm = re.match(r"%(\d+)d$", patt)
if wm:
n = int(wm.group(1))
def _is_whitespace_padded_int_str(s):
try:
num_digits = len(str(int(s)))
except ValueError:
return False
if num_digits > n:
return True
return len(s) == n and s[:-num_digits] == " " * (n - num_digits)
return _is_whitespace_padded_int_str
# tight: "%d"
if patt == "%d":
def _is_tight_int_str(s):
try:
return s == str(int(s))
except ValueError:
return False
return _is_tight_int_str
raise ValueError("Unsupported integer sprintf pattern '%s'" % patt) | bigcode/self-oss-instruct-sc2-concepts |
import re
def getSender(email):
"""
Returns the best-guess sender of an email.
Arguments:
email -- the email whose sender is desired
Returns:
Sender of the email.
"""
sender = email['From']
m = re.match(r'(.*)\s<.*>', sender)
if m:
return m.group(1)
return sender | bigcode/self-oss-instruct-sc2-concepts |
def signed2unsigned(value, width=32):
""" convert a signed value to it's 2 complement unsigned
encoding """
if value >= 0:
return int(value)
else:
return int(value + 2**(width) ) | bigcode/self-oss-instruct-sc2-concepts |
import struct
def read_binary(fileObj, byteType='uint8', size=1):
"""A helper function to readin values from a binary file
Parameters:
-----------
fileObj : object
a binary file object
byteType : string, optional, default 'uint8'
the type of readin values
size : int, optional
the number of bytes to readin. Default is 1.
Returns:
--------
out : a value or a tuple of values or a string
the readout value from the bytes
"""
typeNames = {
'int8': ('b', struct.calcsize('b')),
'uint8': ('B', struct.calcsize('B')),
'int16': ('h', struct.calcsize('h')),
'uint16': ('H', struct.calcsize('H')),
'int32': ('i', struct.calcsize('i')),
'uint32': ('I', struct.calcsize('I')),
'int64': ('q', struct.calcsize('q')),
'uint64': ('Q', struct.calcsize('Q')),
'float': ('f', struct.calcsize('f')),
'double': ('d', struct.calcsize('d')),
'char': ('s', struct.calcsize('s'))}
if size == 1:
return struct.unpack(typeNames[byteType][0], fileObj.read(typeNames[byteType][1]))[0]
elif size > 1:
return struct.unpack(typeNames[byteType][0] * size, fileObj.read(typeNames[byteType][1] * size))
else:
return None | bigcode/self-oss-instruct-sc2-concepts |
def is_external_plugin(module_path):
"""
Returns true when the given module is an external plugin.
Implementation note: does a simple check on the name to see if it's
not prefixed with "kolibri.". If so, we know it's not an internal plugin.
"""
return not module_path.startswith("kolibri.") | bigcode/self-oss-instruct-sc2-concepts |
def intersect(lst1, lst2):
"""intersection of two lists
"""
lst3 = [value for value in lst1 if value in lst2]
return lst3 | bigcode/self-oss-instruct-sc2-concepts |
from typing import Dict
def prettify_data_filtering_rule(rule: Dict) -> Dict:
"""
Prettify the data filtering rule to be compatible to our standard.
Args:
rule: The profile rule to prettify
Returns: rule dictionary compatible to our standards.
"""
pretty_rule = {
'Name': rule.get('@name')
}
if isinstance(rule.get('application'), dict) and 'member' in rule['application']:
pretty_rule['Application'] = rule['application']['member']
if isinstance(rule.get('file-type'), dict) and 'member' in rule['file-type']:
pretty_rule['File-type'] = rule['file-type']['member']
if 'direction' in rule:
pretty_rule['Direction'] = rule['direction']
if 'alert-threshold' in rule:
pretty_rule['Alert-threshold'] = rule['alert-threshold']
if 'block-threshold' in rule:
pretty_rule['Block-threshold'] = rule['block-threshold']
if 'data-object' in rule:
pretty_rule['Data-object'] = rule['data-object']
if 'log-severity' in rule:
pretty_rule['Log-severity'] = rule['log-severity']
if 'description' in rule:
pretty_rule['Description'] = rule['description']
return pretty_rule | bigcode/self-oss-instruct-sc2-concepts |
def identity(x):
"""Identity activation function. Input equals output.
Args:
x (ndarray): weighted sum of inputs.
"""
return x | bigcode/self-oss-instruct-sc2-concepts |
def _recipe_name(raw_configuration):
"""
Given a raw repository configuration, returns its recipe name.
:param raw_configuration: configuration as returned by the SCRIPT_NAME_GET
groovy script.
:type raw_configuration: dict
:return: name of the recipe ("format")
"""
name = raw_configuration['recipeName'].split('-')[0].title()
if name == 'Maven2':
name = 'Maven'
return name | bigcode/self-oss-instruct-sc2-concepts |
import itertools
def color_repeats(n=1):
"""Set up a cycle through default Plotly colors, repeating each n times"""
color_list = (
["#1f77b4"] * n # muted blue
+ ["#ff7f0e"] * n # safety orange
+ ["#2ca02c"] * n # cooked asparagus green
+ ["#d62728"] * n # brick red
+ ["#9467bd"] * n # muted purple
+ ["#8c564b"] * n # chestnut brown
+ ["#e377c2"] * n # raspberry yogurt pink
+ ["#7f7f7f"] * n # middle gray
+ ["#bcbd22"] * n # curry yellow-green
+ ["#17becf"] * n # blue-teal
)
return itertools.cycle(color_list) | bigcode/self-oss-instruct-sc2-concepts |
def pybb_editable_by(post, user):
"""
Check if the post could be edited by the user.
"""
return post.is_editable_by(user) | bigcode/self-oss-instruct-sc2-concepts |
def mean_squared_error_loss(inputs, targets):
""" 平方差损失
Examples:
>>> i = torch.randn(3, 5)
>>> t = torch.randn(3, 5)
# 与官方结果比较
>>> my_ret = mean_squared_error_loss(i, t)
>>> official_ret = F.mse_loss(i, t, reduction='none')
>>> assert torch.allclose(my_ret, official_ret, atol=1e-5)
Args:
inputs: [B, N]
targets: same shape as inputs
Returns:
[B, N]
"""
return (inputs - targets).pow(2.0) | bigcode/self-oss-instruct-sc2-concepts |
def _get_cost (route, solution, dists):
"""
This method is used to calculate the total distance
associated to a route, once the sequence of its nodes
has been changed using the 2-OPT algorithm.
:param route: The interested route.
:param solution: The nodesin the order in which they are visited.
:param dists: The matrix of distances between nodes.
:return: The total distance.
"""
cnode, cost = route.source.id, 0
for node in solution:
cost += dists[cnode, node.id]
cnode = node.id
cost += dists[cnode, route.depot.id]
return cost | bigcode/self-oss-instruct-sc2-concepts |
def no_data_extractor(node, user):
"""Dummy function that collects no data for the NodeDataRegistry."""
return [] | bigcode/self-oss-instruct-sc2-concepts |
def camel_case_from_underscores(string):
"""generate a CamelCase string from an underscore_string."""
components = string.split('_')
string = ''
for component in components:
string += component[0].upper() + component[1:]
return string | bigcode/self-oss-instruct-sc2-concepts |
def easy_helloname(a):
"""Takes in a string representing a name and returns a new string saying hello in a very specific format, e.g., if the name is 'Dave', it should return 'Hello, Dave!'"""
return 'Hello, {}!'.format(a) | bigcode/self-oss-instruct-sc2-concepts |
import mimetypes
def _GuessMimeType(magic_obj, file_name):
"""Guess a file's mimetype base on its extension and content.
File extension is favored over file content to reduce noise.
Args:
magic_obj: A loaded magic instance.
file_name: A path to the file.
Returns:
A mime type of |file_name|.
"""
mime_type, _ = mimetypes.guess_type(file_name)
if not mime_type:
mime_type = magic_obj.file(file_name)
return mime_type | bigcode/self-oss-instruct-sc2-concepts |
def convert_headers_to_environ(headers):
"""
Converts HTTP headers into WSGI environ variables.
"""
return {
'HTTP_' + key.replace('-', '_').upper(): value.strip()
for key, value in headers.items()
} | bigcode/self-oss-instruct-sc2-concepts |
def expand_iterable(choices):
"""
Expands an iterable into a list. We use this to expand generators/etc.
"""
return [i for i in choices] if hasattr(choices, "__iter__") else None | bigcode/self-oss-instruct-sc2-concepts |
def int2list(num,listlen=0,base=2):
"""Return a list of the digits of num, zero padding to produce a list of length at least listlen, to the given base (default binary)"""
digits = []; temp = num
while temp>0:
digits.append(temp % base)
temp = temp // base
digits.extend((listlen-len(digits))*[0])
return digits | bigcode/self-oss-instruct-sc2-concepts |
def rate(e0, e1, n0, n1, nr, p):
"""
This equation is solved for p to determine the convergence rate when the
reference solution is used to measure the error.
y(p) = 0 determines the convergence rate.
e0, n0 : Error and grid number for grid "0"
e1, n1 : Error and grid number for grid "1"
nr : Reference grid number
p : Convergence rate to solve for
"""
h0 = 0.5 ** (n0 * p)
h1 = 0.5 ** (n1 * p)
hr = 0.5 ** (nr * p)
y = e0 * (h1 - hr) - e1 * (h0 - hr)
return y | bigcode/self-oss-instruct-sc2-concepts |
from typing import Iterable
from typing import Hashable
from typing import Counter
def major_vote(all_votes: Iterable[Iterable[Hashable]]) -> Iterable[Hashable]:
"""
For the given iterable of object iterations, return an iterable of the most common object at each position of the
inner iterations.
E.g.: for [[1, 2], [1, 3], [2, 3]] the return value would be [1, 3] as 1 and 3 are the most common objects
at the first and second positions respectively.
:param all_votes: an iterable of object iterations
:return: the most common objects in the iterations (the major vote)
"""
return [Counter(votes).most_common()[0][0] for votes in zip(*all_votes)] | bigcode/self-oss-instruct-sc2-concepts |
def get_embedded(result_object, link_relation):
"""
Given a result_object (returned by a previous API call), return
the embedded object for link_relation. The returned object can be
treated as a result object in its own right.
'result_object' a JSON object returned by a previous API call.
The link relation of the embedded object must have been specified
when the result_object was originally requested. May not be None.
'link_relation' the link relation for which href is required. May
not be None.
Returns None if the embedded object does not exist.
"""
# Argument error checking.
assert result_object is not None
assert link_relation is not None
result = None
embedded_object = result_object.get('_embedded')
if embedded_object:
result = embedded_object.get(link_relation)
return result | bigcode/self-oss-instruct-sc2-concepts |
def make_album(artist, title, tracks=0):
"""Build a dictionary containing information about an album."""
album_dict = {
'artist': artist.title(),
'title': title.title(),
}
if tracks:
album_dict['tracks'] = tracks
return album_dict | 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.