seed stringlengths 1 14k | source stringclasses 2
values |
|---|---|
def unslug(_input):
"""Convert slugs back into normal strings"""
return _input.replace('-', ' ').replace('_', ' ') | bigcode/self-oss-instruct-sc2-concepts |
def pages_to_edges(wiki_linked_pages):
"""
Create edges linking to (inbound) and from (outbound) a page
"""
page = wiki_linked_pages["title"]
in_edges = [(in_page, page) for in_page in wiki_linked_pages["inbound_pages"]]
out_edges = [(page, out_page) for out_page in wiki_linked_pages["outbound_p... | bigcode/self-oss-instruct-sc2-concepts |
def create_summary_document_for_es(data):
"""
This function will create document structure appropriate for es
:param data: data to parse
:return: part of document to be inserted into es
"""
results = list()
for k, v in data.items():
results.append({
"name": k,
... | bigcode/self-oss-instruct-sc2-concepts |
import re
def format_indeed_post_date(post_date):
"""
Format a Posted date to a numeric string of the recorded days
Arguments : posted date string
Return : Numeric string
"""
if ("Publiée à l'instant" in post_date) or ("Aujourd'hui" in post_date):
return str(0)
else:
temp... | bigcode/self-oss-instruct-sc2-concepts |
import requests
import json
def post(base_url, action_url, params):
"""
发送post请求
:param base_url:
:param action_url:
:param params:
:return:
"""
full_url = base_url + action_url
# 请求头
headers = {
"Content-type": "application/json",
'Upgrade': 'HTTP/1.1'
}
... | bigcode/self-oss-instruct-sc2-concepts |
def sequence_sum(begin_number, end_number, step):
"""
Goes through a loop and finds the sum of the sequence specified by three integer inputs.
:param begin_number: the starting integer value.
:param end_number: the ending integer value.
:param step: integer of how many numbers to increase each step.... | bigcode/self-oss-instruct-sc2-concepts |
def decompose_column_name(col_name):
"""Returns separate parts of a hobo column name
Argument:
- col_name (str): the column name
Returns:
- tuple: (variable_name, unit_name, serial_text)
"""
x=col_name.split('(')
try:
serial_text=x[1].split(')... | bigcode/self-oss-instruct-sc2-concepts |
def _get_key(dict_like, key):
"""
Examples
--------
>>> a = dict(b=1)
>>> _get_key(a, 'b')
1
>>> _get_key(a, 'c') == ""
True
"""
try:
return dict_like[key]
except KeyError:
return "" | bigcode/self-oss-instruct-sc2-concepts |
import csv
def into_list2(fIn,**kwargs):
"""
Read data from file into a 2D list.
Lines with '#' are not read.
Parameters
----------
fIn : str
Path to input file
delimeter : str (optional)
Delimeter for parsing lines in file. (default is ',')
type : str (optional)
... | bigcode/self-oss-instruct-sc2-concepts |
def w(q2: float, m_parent: float, m_daughter: float) -> float:
"""
Calculates the recoil variable w, which runs from 1 (zero recoil) to the maximum value (depends on daughter).
:param q2: Momentum transfer to the lepton-neutrino system.
:param m_parent: Mass of the parent meson, e.g. the B meson.
:p... | bigcode/self-oss-instruct-sc2-concepts |
def is_valid_project_type(type):
""" Validates supported project types; currently only maven is supported; hopefully gradle in the future """
if not type:
return False
if "maven" != type:
return False
return True | bigcode/self-oss-instruct-sc2-concepts |
def train_test_split(tokenized):
"""Returns a train, test tuple of dataframes"""
train = tokenized.query("category != 'title'")
test = tokenized.query("category == 'title'")
return train, test | bigcode/self-oss-instruct-sc2-concepts |
def scrapeSymbol(soup):
""" Scrapes ICO symbol from ICODrops listing """
li = soup.findAll("li")
for idx, yeah in enumerate(li):
span = yeah.find("span", attrs = { "class" : "grey" })
if span and "Ticker:" in span.text:
# Return only first match
return li[idx] \
.text \
.repl... | bigcode/self-oss-instruct-sc2-concepts |
import torch
def logits_to_label(logits):
"""
Converts predicted logits from extended binary format
to integer class labels
Parameters
----------
logits : torch.tensor, shape(n_examples, n_labels-1)
Torch tensor consisting of probabilities returned by ORCA model.
Examples
---... | bigcode/self-oss-instruct-sc2-concepts |
import random
def get_random_delay(min_time=0.01, max_time=0.1):
"""
Random sleep time between min and max time. Defaults to between 10 and 100ms
:param min_time: minimum time (s)
:param max_time: maximum time (s)
:return: time in seconds
"""
return random.uniform(min_time, max_time) | bigcode/self-oss-instruct-sc2-concepts |
def parse_charoffset(charoffset):
"""
Parse charoffset to a tuple containing start and end indices.
Example:
charoffset = '3-7;8-9'
[[3, 7], [8, 9]]
"""
# try split by ';'
charoffsets = charoffset.split(';')
return [[int(x.strip()) for x in offset.split('-')] for off... | bigcode/self-oss-instruct-sc2-concepts |
def none_to_empty(val):
"""Convert None to empty string.
Necessary for fields that are required POST but have no logical value.
"""
if val is None:
return ""
return val | bigcode/self-oss-instruct-sc2-concepts |
def parse(exc):
"""Takes in an exception and returns the boto
`Message, Code` properties if they exist - else `None, None`
"""
if exc is not None and hasattr(exc, 'response') and exc.response is not None:
error = exc.response.get('Error', {})
code = error.get('Code', None)
message = er... | bigcode/self-oss-instruct-sc2-concepts |
def override(config, overrides):
"""Update a config dictionary with overrides, merging dictionaries.
Where both sides have a dictionary, the override is done recursively.
Where `overrides` contains a value of `None`, the corresponding entry is
deleted from the return value.
.. note:: this does not... | bigcode/self-oss-instruct-sc2-concepts |
def get_most_visible_camera_annotation(camera_data_dict: dict) -> dict:
"""
Get the most visibile camera's annotation.
:param camera_data_dict: Dictionary of form:
{
'CAM_BACK': {'attribute_tokens': ['cb5118da1ab342aa947717dc53544259'],
'bbox_corners': [600.8315617945755,
4... | bigcode/self-oss-instruct-sc2-concepts |
import json
def _to_json(self, fp=None, indent=4):
"""
Converts the object to JSON
:param fp=None: an open file_like object to write the json to.
If it is None, then a string with the JSON
will be returned as a string
:param indent=4: The indentation level des... | bigcode/self-oss-instruct-sc2-concepts |
def give_color_to_direction_static(dir):
"""
Assigns a color to the direction (static-defined colors)
Parameters
--------------
dir
Direction
Returns
--------------
col
Color
"""
direction_colors = [[-0.5, "#4444FF"], [-0.1, "#AAAAFF"], [0.0, "#CCCCCC"], [0.5, "... | bigcode/self-oss-instruct-sc2-concepts |
def onset_attributes_to_onset(o_beat, o_subdiv):
"""
Convert arrays of o_bt and o_sub to o.
- See eq. (1) of the paper.
"""
def o_bt_o_sub_to_o(o_bt, o_sub):
def convert_sub(x):
""" o_sub from its 2's complement representation to exact value."""
return (x + 3) % 7 -... | bigcode/self-oss-instruct-sc2-concepts |
def sanitize(string):
""" sanitize a string before JSON-ize it """
return string.strip().replace("\\", "") # slash replace is only needed on Windows | bigcode/self-oss-instruct-sc2-concepts |
import yaml
def parse_config(config_file):
"""
Helper function to parse the Yaml config file.
Args:
config_file (str): yml configuration file
Returns:
dict: parsed dictionary object
"""
with open(config_file, "rb") as f:
config = yaml.safe_load(f)
return config | bigcode/self-oss-instruct-sc2-concepts |
def convert_index_to_lab(batch, ind2lab):
"""Convert a batch of integer IDs to string labels.
Arguments
---------
batch : list
List of lists, a batch of sequences.
ind2lab : dict
Mapping from integer IDs to labels.
Returns
-------
list
List of lists, same size a... | bigcode/self-oss-instruct-sc2-concepts |
def get_time_field(da):
"""Get name of time coordinate."""
default_time_names = ['time', 'initial_time0_hours']
for d in default_time_names:
if d in da.dims:
return d
raise RuntimeError('Could not deduce time coordinate for given data') | bigcode/self-oss-instruct-sc2-concepts |
def of_type(ts):
"""
>>> of_type({'kind': 'OBJECT', 'name': 'User', 'ofType': None})
'User'
>>> of_type({'kind': 'NON_NULL', 'name': None, 'ofType': {'kind': 'SCALAR', 'name': 'String', 'ofType': None}})
'String'
>>> of_type({"kind": "ENUM", "name": "ProjectState"})
'ProjectState'
"""
... | bigcode/self-oss-instruct-sc2-concepts |
def get_position_from_periods(iteration, cumulative_period):
"""Get the position from a period list.
It will return the index of the right-closest number in the period list.
For example, the cumulative_period = [100, 200, 300, 400],
if iteration == 50, return 0;
if iteration == 210, return 2;
i... | bigcode/self-oss-instruct-sc2-concepts |
def timeStamp(list_time):
"""
Format time stam into `00h00m00s` into the dictionary
:param list_time: float list of time stamp in second
:return format_time: dictionary of format time
"""
format_time = dict()
i = 0
for time in list_time:
m, s = divmod(time, 60)
h, m = div... | bigcode/self-oss-instruct-sc2-concepts |
import torch
def bloom_gelu_forward(x):
"""
Custom bias GELU function. Adapted from Megatron-DeepSpeed code. Here we use a simple implementation (inference) to
make the model jitable.
Args:
x (`torch.tensor`, *required*):
input hidden states
"""
return x * 0.5 * (1.0 + tor... | bigcode/self-oss-instruct-sc2-concepts |
def calc_p_ratio(hps, nhps, total_hps, total_nhps):
"""
Returns a ratio between the proportion hps/nhps to the proportion nhps/hps. The larger proportion will be the
numerator and the lower proportion will be the denominator (and thus the p-ratio>=1).
This corrects for the total_hps/total_nhps imbalance... | bigcode/self-oss-instruct-sc2-concepts |
def state2dict(Primes, State):
"""
Converts the string representation of a state into the dictionary representation of a state.
If *State* is already of type *dict* it is simply returned.
**arguments**
* *Primes*: prime implicants or a list of names
* *State* (str): string representatio... | bigcode/self-oss-instruct-sc2-concepts |
def _get_name(soup) -> str:
"""Get the work name."""
return soup.find(id='work_name').a.contents[-1].strip() | bigcode/self-oss-instruct-sc2-concepts |
def extract_mg_h(sai):
"""
Given an SAI, this find the most general pattern that will generate a
match.
E.g., ('sai', ('name', '?foa0'), 'UpdateTable', ('value', '?foa1'))
will yield: {('name', '?foa0'), ('value', '?foa1')}
"""
return frozenset({tuple(list(elem) + ['?constraint-val%i' % i])... | bigcode/self-oss-instruct-sc2-concepts |
def bool_flag(s):
"""Helper function to make argparse work with the input True and False.
Otherwise it reads it as a string and is always set to True.
:param s: string input
:return: the boolean equivalent of the string s
"""
if s == '1' or s == 'True':
return True
elif s == '0' or s ... | bigcode/self-oss-instruct-sc2-concepts |
def statistics(prediction, ground_truth, beta=1):
"""Computes performance statistics for classifiers.
Parameters
----------
prediction : set
Set of objects predicted to be labeled positive.
ground_truth : set
Set of objects actually labeled positive.
beta : float, optional
... | bigcode/self-oss-instruct-sc2-concepts |
def IsNodeOSL(node):
"""
Determines if the given node has an OSL source type.
"""
return node.GetSourceType() == "OSL" | bigcode/self-oss-instruct-sc2-concepts |
def join_tagblock(tagblock, nmea):
"""
Join a tagblock to an AIVDM message that does not already have a tagblock
"""
if tagblock and nmea:
return "\\{}\\{}".format(tagblock.lstrip('\\'), nmea.lstrip('\\'))
else:
return "{}{}".format(tagblock, nmea) | bigcode/self-oss-instruct-sc2-concepts |
import re
def _parse_minimap_log(log_filename):
"""Parses minimap log file and returns
i string) version, float ii) peak RAM"""
version = ""
RAM = 0.0
try:
logfile = open(log_filename)
except OSError as error:
print("# ERROR: cannot open/read file:", log_filename, error)
... | bigcode/self-oss-instruct-sc2-concepts |
def get_broadcast_shape(x_shape, y_shape, prim_name):
"""
Doing broadcast between tensor x and tensor y.
Args:
x_shape (list): The shape of tensor x.
y_shape (list): The shape of tensor y.
prim_name (str): Primitive name.
Returns:
List, the shape that broadcast between ... | bigcode/self-oss-instruct-sc2-concepts |
def wn2wl(wavenumber):
"""Convert wavenumber (cm-1) to wavelength (um)."""
return 10000 / wavenumber | bigcode/self-oss-instruct-sc2-concepts |
def get_unique_sublist(inlist):
"""return a copy of inlist, but where elements are unique"""
newlist = []
for val in inlist:
if not val in newlist: newlist.append(val)
return newlist | bigcode/self-oss-instruct-sc2-concepts |
def sig_indicator(pvalue):
"""Return a significance indicator string for the result of a t-test.
Parameters
----------
pvalue: float
the p-value
Returns
-------
str
`***` if p<0.001, `**` if p<0.01, `*` if p<0.05, `ns` otherwise.
"""
return (
'***' if p... | bigcode/self-oss-instruct-sc2-concepts |
import socket
def hostname_to_ip(servers):
""" Given (hostname, port) return (ip_address, port)
"""
reply = []
for server, port in servers:
ip_address = socket.gethostbyname(server)
reply.append((ip_address, port))
return reply | bigcode/self-oss-instruct-sc2-concepts |
def next_exon(variant_position, coding_exon_starts):
"""
get location of next coding exon after variant
:param coding_exon_starts: coding exon start positions, Pandas Series.
:param variant_position: chromosomal position, int
:return: chromosomal position of start of next coding exon, int
"""
... | bigcode/self-oss-instruct-sc2-concepts |
def transpose(G):
"""Transpose graph."""
V, E = G; ET = {}
for u in V: ET[u] = []
for u, vs in E.items():
for v in vs: ET[v].append(u)
return (V, ET) | bigcode/self-oss-instruct-sc2-concepts |
from datetime import datetime
def get_week_of_month(year, month, day):
"""
获取指定的某天是某个月中的第几周
周一作为一周的开始
"""
end = int(datetime(year, month, day).strftime("%W"))
begin = int(datetime(year, month, 1).strftime("%W"))
star_date = end - begin + 1
if star_date == 1:
week_of = '# 第一周'
... | bigcode/self-oss-instruct-sc2-concepts |
import math
def numberOfDigits(tickSpacing):
"""Returns the number of digits to display for text label.
:param float tickSpacing: Step between ticks in data space.
:return: Number of digits to show for labels.
:rtype: int
"""
nfrac = int(-math.floor(math.log10(tickSpacing)))
if nfrac < 0:... | bigcode/self-oss-instruct-sc2-concepts |
def IsNumeric(value):
"""
* Determine if string is numeric.
"""
if not isinstance(value, str):
raise Exception('value must be a string.')
try:
valtxt = value
value = int(valtxt)
value = float(valtxt)
return True
except:
return False | bigcode/self-oss-instruct-sc2-concepts |
def get_A_sp_sh_JIS_A_4111(A):
"""太陽熱集熱部の有効集熱面積(IS A 4111)
Args:
A(float): 太陽熱集熱部総面積
Returns:
float: 太陽熱集熱部の有効集熱面積
"""
return A * 0.85 | bigcode/self-oss-instruct-sc2-concepts |
import torch
import math
def relative_position_bucket(relative_position, bidirectional=True, num_buckets=32, max_distance=128):
"""
Adapted from Mesh Tensorflow:
https://github.com/tensorflow/mesh/blob/0cb87fe07da627bf0b7e60475d59f95ed6b5be3d/mesh_tensorflow/transformer/transformer_layers.py#L593
Tran... | bigcode/self-oss-instruct-sc2-concepts |
def add_group(inventory, groupname, hostname=None):
"""Add a group to inventory, optionally add it with hostname."""
all_group = inventory["all"]
group = {}
if hostname:
group["hosts"] = {hostname: {}}
all_group["children"][groupname] = group
return group | bigcode/self-oss-instruct-sc2-concepts |
import re
def alphanum_sort(l):
"""Sort the given list in ascending order the way that humans expect.
i.e For a list l containing `["5", "24", "10"]`, the function sorts it as
`["5", "10", "24"]` instead of `["10", "24", "5"]` as would Python List
sort() method.
"""
# key to use for the sort
... | bigcode/self-oss-instruct-sc2-concepts |
def _format_optname(value):
"""Format the name of an option in the configuration file to a more
readable option in the command-line."""
return value.replace('_', '-').replace(' ', '-') | bigcode/self-oss-instruct-sc2-concepts |
def check_sentence_ending(sentence: str) -> bool:
"""Check if the sentence ends with a full stop.
:param sentence: str - a sentence to check.
:return: bool - True if punctuated correctly with period, False otherwise.
"""
return sentence.endswith(".") | bigcode/self-oss-instruct-sc2-concepts |
def html_escape(t):
"""Convert special HTML characters ('&', '<', '>', '"', "'") in string to HTML-safe sequences.
>>> html_escape('<>"&')
'<>"&'
>>>
"""
html_escape_table = {
"&": "&",
'"': """,
"'": "'",
">": ">",
"<": "&... | bigcode/self-oss-instruct-sc2-concepts |
def sort_index(list):
"""
Return the *indices* of the elements in an array in order from smallest
element to largest, e.g sort_index([3, -1, 1]) gives [1, 2, 0].
"""
x = zip(list, range(0, len(list)))
x = sorted(x, key=lambda x: x[0])
return map(lambda x: x[1], x) | bigcode/self-oss-instruct-sc2-concepts |
def c_to_f(c):
"""
Convert celcius to fahrenheit
"""
return c * 1.8 + 32.0 | bigcode/self-oss-instruct-sc2-concepts |
def format_locations(location : str):
"""
Takes string describing location and returns nicely formatted tuple
:param location: location string in the format 123..1234
:return: location tuple (123, 1234)
"""
return location.split("..") | bigcode/self-oss-instruct-sc2-concepts |
def parm_is_time_dependent(parm):
"""Checks if parm is time-dependent.
"""
return parm.isTimeDependent() | bigcode/self-oss-instruct-sc2-concepts |
def num_swaps(A):
"""Given an array of integers from 0 to N-1, return number of swaps to sort."""
N = len(A)
seen = [False] * N
ct = 0
for i in range(N):
if not seen[i]:
idx = i
num = 0
while not seen[idx]:
num += 1
seen[id... | bigcode/self-oss-instruct-sc2-concepts |
from typing import Optional
from typing import Callable
from typing import Dict
def get_on_fit_config_fn(
lr_initial: float, timeout: Optional[int], partial_updates: bool
) -> Callable[[int], Dict[str, str]]:
"""Return a function which returns training configurations."""
def fit_config(rnd: int) -> Dict[... | bigcode/self-oss-instruct-sc2-concepts |
import torch
def jvp(y, x, v, create_graph=False):
"""Jacobian-vector product dy/dx @ v.
Pass `create_graph=True` to allow backprop on output.
"""
return torch.autograd.grad(y.flatten(), x, v.flatten(),
retain_graph=True,
create_graph=create_graph,
only_inputs =True)[0] | bigcode/self-oss-instruct-sc2-concepts |
def extract_weeks_offset(tokens, end=None, key_tokens=(
'next', 'previous', 'last', 'upcoming', 'past', 'prev')):
"""Extract the number of week offsets needed.
>>> extract_weeks_offset(['next', 'next', 'week'])
(0, ['week'], 2)
>>> extract_weeks_offset(['upcoming', 'Monday'])
(0, ['Monday']... | bigcode/self-oss-instruct-sc2-concepts |
from typing import OrderedDict
def bytes_as_dict(msg):
"""Parse CAM message to OrderedDict based on format /key:val.
Parameters
----------
msg : bytes
Sequence of /key:val.
Returns
-------
collections.OrderedDict
With /key:val => dict[key] = val.
"""
# decode byte... | bigcode/self-oss-instruct-sc2-concepts |
def extend(s, var, val):
"""
Given a dictionary s and a variable and value, this returns a new dict with
var:val added to the original dictionary.
>>> extend({'a': 'b'}, 'c', 'd')
{'a': 'b', 'c': 'd'}
"""
s2 = {a: s[a] for a in s}
s2[var] = val
return s2 | bigcode/self-oss-instruct-sc2-concepts |
def compose_ngrams_regex(emoji_regex):
""" Compose a regex expression to parse out Ngrams
:param emoji_regex: a regular expression that matches emojis
:return: a compiled regular expression that matches ngrams
"""
pattern = '(' + emoji_regex
pattern += r"|(&\S+;)"
pattern += r"|(https?:\/\/\... | bigcode/self-oss-instruct-sc2-concepts |
import pickle
def load_dispatch_results(iteration, year, scenario):
"""Load scenario results"""
with open(f'output/dispatch_plan/uc-results_{iteration}_{year}_{scenario}.pickle', 'rb') as f:
results = pickle.load(f)
return results | bigcode/self-oss-instruct-sc2-concepts |
def isSymbolNumber(command, sortedSymbols):
""" isSymbolNumber checks whether given command has Stock Symbol number and it is in the loaded Stock Symbols. """
return ((len(command.strip()) > 0) and command.strip().isdigit() and int(command.strip()) < len(sortedSymbols)) | bigcode/self-oss-instruct-sc2-concepts |
def matsub(a, b):
"""
Subtracts one array from another.
:param a: (ndarray)
:param b: (ndarray)
:return: (ndarray) product of a - b
"""
return a - b | bigcode/self-oss-instruct-sc2-concepts |
def nested_map(f, obj):
"""Maps `f` recursively inside any dicts/lists/tuples in `obj`.
Args:
f: A function taking a single object as input. f's input must NOT be a
dict, list, or tuple, or any subclass of those.
obj: Either an input object to f or some nested structure of collections
of (c... | bigcode/self-oss-instruct-sc2-concepts |
def intersect_shapes(shapes_a, shapes_b, shapes_b_sindex=None):
"""Find intersections between shapes in two lists
Parameters
----------
shapes_a : list of Shapely geometries
List of geometries to be intersected with those in shapes_b
shapes_b : list of Shapely geometries
List of geo... | bigcode/self-oss-instruct-sc2-concepts |
import re
def match(regEx, text):
"""
Try to match the regular expression @regEx
in the text at @text. If match is found, all occurrences
are returned, otherwise empty list is returned
"""
_regEx = re.compile(regEx)
res = _regEx.search(text)
if res:
return list(res.groups())
else:
return [] | bigcode/self-oss-instruct-sc2-concepts |
def get_energies(filename):
""" Returns a dictionary with heats of formation for each xyz-file.
"""
f = open(filename, "r")
lines = f.readlines()
f.close()
energies = dict()
for line in lines:
tokens = line.split()
xyz_name = tokens[0]
hof = float(tokens[1])
... | bigcode/self-oss-instruct-sc2-concepts |
def str_mask(str):
"""指定文字列をマスク置き換えする Replace the specified character string with a mask
Args:
str (str): 文字列 string
Returns:
str: 置き換え文字列 afeter string
"""
# 1文字以上の入力があれば置き換えする If there is more than one character input, replace it
if len(str) > 0:
ret = '*' * len(str)... | bigcode/self-oss-instruct-sc2-concepts |
def mutlireplace(string, replacements):
"""
Replaces multiple substrings in a string.
Parameters
----------
string : str
The string to be modified.
replacements : dict
A dictionary of the form {old: new}.
"""
for key, value in replacements.items():
string = ... | bigcode/self-oss-instruct-sc2-concepts |
def get_datetime_range(start_date, end_date, time_delta):
"""
:param start_date: (datetime.datetime) First date (included)
:param end_date: (datetime.datetime) Last date (not included)
:param time_delta: (datetime.timedelta) Increment
:returns ([datetime.datetime]) All datetimes from start_date up t... | bigcode/self-oss-instruct-sc2-concepts |
def roc(tests=[]):
""" Returns the ROC curve as an iterator of (x, y)-points,
for the given list of (TP, TN, FP, FN)-tuples.
The x-axis represents FPR = the false positive rate (1 - specificity).
The y-axis represents TPR = the true positive rate.
"""
x = FPR = lambda TP, TN, FP, FN:... | bigcode/self-oss-instruct-sc2-concepts |
def roundToNearest(value, roundValue=1000):
"""
Return the value, rounded to nearest roundValue (defaults to 1000).
Args:
value (float): Value to be rounded.
roundValue (float): Number to which the value should be rounded.
Returns:
float: Rounded value.
"""
if roundValu... | bigcode/self-oss-instruct-sc2-concepts |
def get_mqtt_field(p_message, p_field):
""" Get the given field from a JSON message.
@param p_message: The json message
@param p_field: the 'field_name' to extract
@return: the value of the field or None if missing.
"""
try:
l_ret = p_message[p_field]
except (KeyError, TypeError):
... | bigcode/self-oss-instruct-sc2-concepts |
def _make_constraint_name(tname, *cnames, suffix=''):
"""Returns a constraint name from the given components."""
constraint_name = f'{tname}_' + '_'.join(cnames)
return constraint_name[:63 - len(suffix)] + f'_{suffix}' | bigcode/self-oss-instruct-sc2-concepts |
def xor(stream: bytes, key: int) -> bytes:
"""Apply XOR cipher to ``stream`` with ``key``.
Applying this operation twice decodes ``stream`` back to the initial state.
Parameters
----------
stream: :class:`bytes`
Data to apply XOR on.
key: :class:`int`
Key to use. Type ``u8`` (o... | bigcode/self-oss-instruct-sc2-concepts |
import copy
def mutate_dropped(record, rule):
"""Mutate a record for a "DROPPED" action.
"""
if rule['filters'](record):
r = copy.copy(record)
c = []
if 'column_filters' not in rule:
return None
for column in r['columns']:
c_filters = rule.get('colum... | bigcode/self-oss-instruct-sc2-concepts |
def get_r( x, y = 0, z = 1):
"""Makes r (length between origin and point) for x, y, z
Returns r (scalar or array, depending on inputs)"""
r = ( x **2 + y **2 + z **2 ) **0.5
return r | bigcode/self-oss-instruct-sc2-concepts |
import re
def string_to_float(s: str) -> float:
"""
Double precision float in Fortran file will have form 'x.ydz' or 'x.yDz', this cannot be convert directly to float
by Python ``float`` function, so I wrote this function to help conversion. For example,
:param s: a string denoting a double precision... | bigcode/self-oss-instruct-sc2-concepts |
def time(match, player_num, word_index):
"""A utility function for the time it took player_num to type the word at word_index"""
assert word_index < len(match["words"]), "word_index out of range of words"
assert player_num < len(match["times"]), "player_num out of range of players"
return match["times"]... | bigcode/self-oss-instruct-sc2-concepts |
def parse_po(text):
"""
Parse 'po' format produced by xgettext.
Return a list of (msgid,msgstr) tuples.
"""
messages = []
msgid = []
msgstr = []
in_msgid = False
in_msgstr = False
for line in text.split('\n'):
line = line.rstrip('\r')
if line.startswith('msgid ')... | bigcode/self-oss-instruct-sc2-concepts |
def to_list(item):
"""
Make a list contains item if item is not a list
:param item: item to convert
:return: a list
"""
if item is not None and not isinstance(item, list):
return [item]
return item | bigcode/self-oss-instruct-sc2-concepts |
def for_and_backward(model, batch, maps, optimizer, loss_fn):
"""Does one forward and one backward step, including weight updates, using
the given batch. Returns the loss."""
prediction = model(batch)
loss = loss_fn(prediction, maps)
# Calculate gradients
loss.backward()
# Update model param... | bigcode/self-oss-instruct-sc2-concepts |
import grp
def get_group_grp(gid):
"""get group info
Args:
gid (int): gid of the group
Returns:
grp.struct_group
"""
return grp.getgrgid(gid) | bigcode/self-oss-instruct-sc2-concepts |
import math
def _db2gain(db):
"""Convert 100ths of dB to linear gain."""
return math.pow(10.0, float(db)/1000.0) | bigcode/self-oss-instruct-sc2-concepts |
def parse_is_account_bimodal_response(resp):
"""
Parse a response from RpcIsAccountBimodal.
Returns (True, peer-addr) if the account is bimodal, (False, None)
otherwise.
"""
is_bimodal = resp["IsBimodal"]
ip = resp["ActivePeerPrivateIPAddr"]
if ip.startswith("[") and ip.endswith("]"):
... | bigcode/self-oss-instruct-sc2-concepts |
from typing import List
def get_mask_colors(scene: dict) -> List[List[float]]:
"""
Loads the unique mask colors from the scene dictionary
Parameters
---
scene (dict)
Scene dictionary containing info about the scene
Result
---
List[List[float]]
"""
masks = []
for o... | bigcode/self-oss-instruct-sc2-concepts |
def any2unicode(text, encoding='utf8', errors='strict'):
"""Convert `text` (bytestring in given encoding or unicode) to unicode.
Parameters
----------
text : str
Input text.
errors : str, optional
Error handling behaviour if `text` is a bytestring.
encoding : str, optional
... | bigcode/self-oss-instruct-sc2-concepts |
def bits_to_int(bits):
"""Converts a list of bits into an integer"""
val = 0
for bit in bits:
val = (val << 1) | bit
return val | bigcode/self-oss-instruct-sc2-concepts |
def parse_hex(string):
"""Parse a string as a hexadecimal value."""
return int(string, 16) | bigcode/self-oss-instruct-sc2-concepts |
import torch
def box_xy_to_wh(x):
"""
Converts co-ordinates from (x1, y1, x2, y2) to
(x, y, w, h)
"""
x1, y1, x2, y2 = x.unbind(-1)
x = (x2 + x1)/2
y = (y2 + y1)/2
w = (x2 - x1)
h = (y2 - y1)
return torch.stack([x, y, w, h], dim=-1) | bigcode/self-oss-instruct-sc2-concepts |
def scalar_eq(a, b, precision=0):
"""Check if two scalars are equal.
Keyword arguments:
a -- first scalar
b -- second scalar
precision -- precision to check equality
Returns:
True if scalars are equal
"""
return abs(a - b) <= precision | bigcode/self-oss-instruct-sc2-concepts |
import re
def identify_url(url):
"""Identify from which site a url is.
Return values:
'letras' for 'letras.mus.br'
'vagalume' for 'vagalume.com.br'
'unknown' if not able to identify.
"""
if not isinstance(url, str):
raise ValueError('url is not a string')
url = url.strip()... | 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.