seed stringlengths 1 14k | source stringclasses 2
values |
|---|---|
def apply_nd(fn, input):
"""
Apply fn whose output only depends on the last dimension values
to an arbitrary n-dimensional input.
It flattens dimensions except the last one, applies fn, and then
restores the original size.
"""
x_size = input.size()
x_flat = input.view(-1, x_size[-1])
... | bigcode/self-oss-instruct-sc2-concepts |
import math
def calculate_distance(p1, p2):
"""
Calculate euclidian distance between two points.
"""
x1, y1, z1 = p1
x2, y2, z2 = p2
return math.sqrt((x2 - x1) ** 2 + (y2 - y1) ** 2 + (z2 - z1) ** 2) | bigcode/self-oss-instruct-sc2-concepts |
def get_download_total(rows):
"""Return the total downloads, and the downloads column"""
headers = rows.pop(0)
index = headers.index('download_count')
total_downloads = sum(int(row[index]) for row in rows)
rows.insert(0, headers)
return total_downloads, index | bigcode/self-oss-instruct-sc2-concepts |
import statistics
def calculate_altitudes_and_speeds(positions, altunits='M'):
"""
calculate the highest, fastest and lowest values for speed and altitude
Args:
positions(list): list of dicts, each dict is a position report
altunits(str): altitude units, default is metres (M)
Returns... | bigcode/self-oss-instruct-sc2-concepts |
def transform_users(response_objects):
""" Strips list of API response objects to return list of group objects only
:param response_objects:
:return: list of dictionary objects as defined in /docs/schema/gsuite.md
"""
users = []
for response_object in response_objects:
for user in respo... | bigcode/self-oss-instruct-sc2-concepts |
import json
def GetErrorMessage(stdout):
"""Extract a message field from JSON output if present."""
try:
return json.loads(stdout)['message']
except (ValueError, KeyError):
return stdout | bigcode/self-oss-instruct-sc2-concepts |
def add_attrs(widget_or_field, attrs, is_replace=True):
"""Add attributes from attrs to widget_or_field
:param widget_or_field: object it can be a widget, field
:param attrs: dict name, value map that contains all the attributes
want to be added
:param is_replace: whether replace the origin value,... | bigcode/self-oss-instruct-sc2-concepts |
def save_csvs(csm, tables_rows):
""" write relational tables to csv files.
tables_rows -- dict {table_name: [rows]} of tables of rows to save"""
written = {}
for table_name in tables_rows:
written[table_name] = csm.write_csv(table_name,
tables_rows[tab... | bigcode/self-oss-instruct-sc2-concepts |
from pathlib import Path
def get_image_path(instance, filename):
"""
callable to define the image upload path according
to the type of object: segment, route, etc.. as well as
the id of the object.
"""
return Path("images", instance.__class__.__name__, str(instance.id), filename) | bigcode/self-oss-instruct-sc2-concepts |
def FilterInstances(instances, service=None, version=None, instance=None):
"""Filter a list of App Engine instances.
Args:
instances: list of AppEngineInstance, all App Engine instances
service: str, the name of the service to filter by or None to match all
services
version: str, the name of the ... | bigcode/self-oss-instruct-sc2-concepts |
def dict_remove_key_safe(d, key, default=None):
"""
removes a key from dict __WITHOUT__ side effects
Returns:
- copy of dict, without key
- value (if it was there)
"""
d = d.copy()
value = d.pop(key, default)
return (d, value) | bigcode/self-oss-instruct-sc2-concepts |
def build_output_type_set(output_type_list, config):
"""Builds set of output types.
Args:
output_type_list: list, possible output image types.
config: dict, user passed parameters.
Returns:
Set of requested output image types.
"""
output_types = set()
for output_type in... | bigcode/self-oss-instruct-sc2-concepts |
def get_valid_example_ids(example_ids, global_ids, incremental = None):
"""func({example_ids}, {global_ids}, bool) -> [valid_identifiers]
Compares the dictionary of a source example with all its possible
identifiers against the dictionary with all the available
documentation identifiers and returns a filte... | bigcode/self-oss-instruct-sc2-concepts |
import json
def jsonify(v, indent=2, sort_keys=True):
"""Turns python object `v` into a pretty printed JSON string
Parameters
----------
v : object
* python object to convert to JSON
indent : int, 2
* number of spaces to indent JSON string when pretty printing
sort_keys : bo... | bigcode/self-oss-instruct-sc2-concepts |
def binarize(a, a_bin, M):
"""Generates binarization constraints for variable a.
Parameters
----------
a : str
Variable to be binarized.
a_bin : str
Identifier of the binarized variable.
M : int
An upper bound on a.
Returns
-------
List[str]
A list h... | bigcode/self-oss-instruct-sc2-concepts |
def interpolate_colors(a, b, bias):
"""takes two RGB tuples and returns a componentwise weighted average"""
return (
int(a[0] * (1 - bias) + b[0] * bias),
int(a[1] * (1 - bias) + b[1] * bias),
int(a[2] * (1 - bias) + b[2] * bias),
) | bigcode/self-oss-instruct-sc2-concepts |
def cluster_info(c, attr=None):
"""Display info of subgraphs in a VertexClustering"""
return {'modularity': c.modularity, 'n': len(c.sizes())} | bigcode/self-oss-instruct-sc2-concepts |
def get_separation_score(results):
"""
For a Solr response, compute the separation score which is derived from the
ratio between the two first Solr scores.
"""
score1 = results[0]['score']
score2 = results[1]['score']
return (1 - score2 / score1) | bigcode/self-oss-instruct-sc2-concepts |
def rm_spaces(filename):
""" Replaces all spaces with underscores in a filename. """
return filename.replace(' ', '_') | bigcode/self-oss-instruct-sc2-concepts |
def apply_backward_euler(Delta_t, u):
""" Apply the backward Euler (fully implicit, first order) time discretization method. """
u_t = (u[0] - u[1])/Delta_t
return u_t | bigcode/self-oss-instruct-sc2-concepts |
def heads(token):
"""
Return the heads of a token, from the root down to immediate head
:param token: spacy token
:return: the heads of the token
"""
hs = []
while token is not token.head:
token = token.head
hs.append(token)
return hs[::-1] | bigcode/self-oss-instruct-sc2-concepts |
def input_format(line):
""" Converts a string into a list of vertices and a point
Receive an entry with this format with
this format '1 1, 3 2, 1 4, 3 4 | 3 3 '
Returns:
list = [(1,1), (3,2), (1,4), (3,4)] and a point = (3,3)
:param line:
:return: list, point
"""
line_strip = li... | bigcode/self-oss-instruct-sc2-concepts |
def base_loss_name_normalizer(name: str) -> str:
"""Normalize the class name of a base BaseLoss."""
return name.lower().replace('loss', '') | bigcode/self-oss-instruct-sc2-concepts |
def unique_hosts_count(rdd):
"""
Return the number of unique origin hosts
return type: int
"""
unique_hosts = rdd.map(lambda line: line.split(' ')[0])
return unique_hosts.distinct().count() | bigcode/self-oss-instruct-sc2-concepts |
def deleteAllInUsed(total, used):
"""
Return the list "total" after removing all appearances of elements in "used".
Parameters
----------
total : list-like of any
The original list from which we want to remove some elements.
used : iterable of any
The elements we want to remove ... | bigcode/self-oss-instruct-sc2-concepts |
def requirements_satisfied(items_counter, requirements):
"""
Checks if items in requirements are present in basket (items_counter)
Args:
items_counter (collections.Counter): items in basket
with number of occurrences
requirements (collections.Counter): items and quantity require... | bigcode/self-oss-instruct-sc2-concepts |
def slash_join(*args):
"""
Joins together strings and guarantees there is only one '/' in between the each string joined.
Double slashes ('//') are assumed to be intentional and are not deduplicated.
"""
def rmslash(path):
path = path[1:] if len(path) > 0 and path[0] == "/" else path
... | bigcode/self-oss-instruct-sc2-concepts |
def get_estimated_max_weight(weight, num_reps):
"""Returns the estimated max weight based on weight and reps."""
estimated_max = weight * (1 + num_reps / 30.0)
return float("{0:.2f}".format(estimated_max)) | bigcode/self-oss-instruct-sc2-concepts |
def unescape_bytes(bytestr):
"""
Returns a variant of the given bytestring that has C escapes replaced
with their ASCII values.
>>> unescape_bytes(b'\\0')
b'\x00'
"""
return bytestr.decode('unicode_escape') | bigcode/self-oss-instruct-sc2-concepts |
def sort_dict(d, reverse=False):
"""
Return sorted dict; optionally reverse sort.
"""
return dict(sorted(d.items(), key=lambda x: x[1], reverse=reverse)) | bigcode/self-oss-instruct-sc2-concepts |
def remove_duplicates(input_features):
"""
Remove duplicate entries from layer list.
:param input_features: A list of layers
:return: Returns a list of unique feature tensors (i.e. no duplication).
"""
feature_name_set = set()
non_duplicate_feature_set = []
for feature in input_features:... | bigcode/self-oss-instruct-sc2-concepts |
def _get_external_id(account_info):
"""Get external id from account info."""
if all(k in account_info for k in ('external_id', 'external_method')):
return dict(id=account_info['external_id'],
method=account_info['external_method'])
return None | bigcode/self-oss-instruct-sc2-concepts |
def steps(distribution):
"""
Returns the steps of given distribution.
Parameters
----------
distribution : array_like
Distribution to retrieve the steps.
Returns
-------
tuple
Distribution steps.
Examples
--------
Uniformly spaced variable:
>>> y = np.... | bigcode/self-oss-instruct-sc2-concepts |
def detectTextTwgoCancelled(frame):
"""Return an empty string if there is no cancelled message in this
text TWGO frame. Otherwise return string with cancellation details.
Args:
frame (dict): Contains a text TWGO frame.
Returns:
(str): '' if there is no cancellation associated
... | bigcode/self-oss-instruct-sc2-concepts |
from typing import Dict
from typing import List
def check_entry_exists(session, entry: Dict, schema_name: str, table: str) -> List[int]:
"""Queries target database for a matching entry.
Generates query dynamically according to the given metadata entry.
A downside of this approach is that the index is not... | bigcode/self-oss-instruct-sc2-concepts |
def get_min_bbox(box_1, box_2):
"""Get the minimal bounding box around two boxes.
Args:
box_1: First box of coordinates (x1, y1, x2, y2). May be None.
box_2: Second box of coordinates (x1, y1, x2, y2). May be None.
"""
if box_1 is None:
return box_2
if box_2 is None:
... | bigcode/self-oss-instruct-sc2-concepts |
import math
def binomial(i, n):
"""Binomial coefficient"""
return math.factorial(n) / float(
math.factorial(i) * math.factorial(n - i)) | bigcode/self-oss-instruct-sc2-concepts |
import re
def get_field(doc: str, name: str):
"""Parse ReST field from document
:param str doc: string of whole document
:param name: name of field excluding the surrounding `:`
:return: value of field
:rtype: str
"""
match = re.search(':{}: (.*)$'.format(name), doc, re.IGNORECASE | re.MU... | bigcode/self-oss-instruct-sc2-concepts |
def extract_entities(openapi_str):
"""
Extract entities from an OpenAPI string, where entities are defines as anything within "```"
:param openapi_str: The OpenAPI str
:type openapi_str: ```str```
:return: Entities
:rtype: ```List[str]```
"""
entities, ticks, space, stack = [], 0, 0, [... | bigcode/self-oss-instruct-sc2-concepts |
def get_topics_by_datatype(bag):
"""
Get all the message types in the bag and their associated topics.
@param bag: bag file
@type bag: rosbag.Bag
@return: mapping from message typename to list of topics
@rtype: dict of str to list of str
"""
topics_by_datatype = {}
for c in bag._g... | bigcode/self-oss-instruct-sc2-concepts |
def find_new_news(excluding_seen_news, existing_news):
"""
Finds new news from the API that is not currently in the list
"""
# https://stackoverflow.com/questions/7271482/getting-a-list-of-values-from-a-list-of-dicts
existing_news_titles = list(map(lambda d: d['title'], existing_news) )
return... | bigcode/self-oss-instruct-sc2-concepts |
def capitalize_string(s: str) -> str:
"""Capitalise all parts of a string divided by "_" or " " """
split = []
for part in s.split("_"):
split.extend(part.split())
return " ".join([part.capitalize() for part in split]) | bigcode/self-oss-instruct-sc2-concepts |
def _check_keys_contain(result_keys, target_keys):
"""Check if all elements in target_keys is in result_keys."""
return set(target_keys).issubset(set(result_keys)) | bigcode/self-oss-instruct-sc2-concepts |
def list(client, user_id, group_id):
"""Get security credentials of user."""
credentials = client.user.credentials.list(
method="GET", userId=user_id, groupId=group_id
)
return credentials | bigcode/self-oss-instruct-sc2-concepts |
def Duffing1D_Hamiltonian(t, u, PARAMETERS = [1, 1]):
"""
Returns Hamiltonian for the Duffing oscillator. PARAMETERS = [alpha, beta]
Functional form: H = 1/2*p_x**2 - alpha*x**2 + beta*x**4), with u = (x, p_x).
Parameters
----------
t : float
Time. (This Hamiltonian is independent of ti... | bigcode/self-oss-instruct-sc2-concepts |
def identity(x, **kwargs):
"""
>>> identity('anything')
'anything'
"""
return x | bigcode/self-oss-instruct-sc2-concepts |
def bounding_box(bw, bh, w, h):
"""
Returns a tuple (new_width, new_height) which has the property
that it fits within box_width and box_height and has (close to)
the same aspect ratio as the original size
"""
new_width, new_height = w, h
if bw and new_width > bw:
new_width = bw
... | bigcode/self-oss-instruct-sc2-concepts |
def identity_filter(data):
"""Return data iterator without any processing"""
return iter(data) | bigcode/self-oss-instruct-sc2-concepts |
def __get_page_component_classname_from_page_data(page_data):
"""Return a generated page component classname from json page data."""
return "{}{}".format(page_data["style"].capitalize(),
str(page_data["id"]).zfill(2)) | bigcode/self-oss-instruct-sc2-concepts |
def remove_job_if_exists(update,context,name):
"""Remove job with given name. Returns whether job was removed."""
current_jobs = context.job_queue.get_jobs_by_name(name)
if not current_jobs:
return False
for job in current_jobs:
job.schedule_removal()
return True | bigcode/self-oss-instruct-sc2-concepts |
import uuid
def get_exec_path(model, model_size, batch_size, batches_per_step, filenames, use_generated_data,
use_tmp_execs):
"""
Return the path to compiled graph based on model parameters
or random name if that was requested by setting an option.
"""
if use_tmp_execs:
r... | bigcode/self-oss-instruct-sc2-concepts |
from typing import List
def serial_order_to_spatial(hole_sequence: List[int],
seq_positions: List[int]) -> List[int]:
"""
Converts a first-phase hole sequence and a list of serial order positions
(at the choice phase) into a list of spatial holes at test.
Args:
hol... | bigcode/self-oss-instruct-sc2-concepts |
def is_constructed(val):
"""Check if a tag represents a "constructed" value, i.e. another TLV"""
return val & 0b00100000 == 0b00100000 | bigcode/self-oss-instruct-sc2-concepts |
def TableResourceToReference(bigquery_messages, resource):
"""Converts a Resource for a table to a TableReference message.
Args:
bigquery_messages: The messages module for the Bigquery API.
resource: the Resource
Returns:
the message
"""
return bigquery_messages.TableReference(
projectId=r... | bigcode/self-oss-instruct-sc2-concepts |
def answer_yn(question=None):
"""Prints a simple yes or no question and returns bool"""
while True:
answer = input(question or 'Are you sure? Y/n').lower()
if answer == '' or answer == 'y' or answer == 'yes':
return True
elif answer == 'n' or answer == 'no':
retur... | bigcode/self-oss-instruct-sc2-concepts |
def is_variant(call):
"""Check if a variant position qualifies as a variant"""
if call == 1 or call == 3:
return True
else:
return False | bigcode/self-oss-instruct-sc2-concepts |
def sort_categories(a, b, categories_list):
"""Sorts a list of dictionaries with category keys according to their
value and order in the categories_list. If not found, alphabetic order is
used.
"""
index_a = categories_list.index(a["category"])
index_b = categories_list.index(b["category"])
... | bigcode/self-oss-instruct-sc2-concepts |
def gen_isempty(gen):
"""
Returns an identical generator and False if it has at least one value, True if it's empty
:param gen: generator, any generator
:return: (generator, Boolean), returns the same generator, and True if empty, False if not
"""
try:
item = next(gen)
def my_generator():
yield item
yi... | bigcode/self-oss-instruct-sc2-concepts |
def rule2columns(rule,lhs,rhs,history,grammar,automaton,w,run,begin=0,end=None):
"""
Given a rule and a bunch of info about run, windows, grammar, etc,
builds a dict for a dataframe for the rule
Dataframe includes how rule probability changed during training,
for each run of Windows
for each t... | bigcode/self-oss-instruct-sc2-concepts |
def logging_lvl_to_kaldi_lvl(lvl: int) -> int:
"""Convert logging level to kaldi level"""
if lvl >= 10:
lvl = max(-3, (lvl - 20) // -10)
else:
lvl = 11 - lvl
return lvl | bigcode/self-oss-instruct-sc2-concepts |
import requests
def retrieve_episode_html(url):
"""Retrieve the HTML for the given episode playlist URL."""
response = requests.get(url)
return response.content | bigcode/self-oss-instruct-sc2-concepts |
def max2(a, b):
"""
Wrapper around the max built-in that is robust to None.
"""
if a and not b:
return a
elif b and not a:
return b
else:
return max(a, b) | bigcode/self-oss-instruct-sc2-concepts |
import re
def string_to_color(s):
"""
Converts color string to tuple.
'10,20,30' - (10,20,30)
Returns None when error.
"""
m = re.match(r"(0|[1-9][0-9]{0,2}),(0|[1-9][0-9]{0,2}),(0|[1-9][0-9]{0,2})", s)
if not m:
return None
a = map(int, m.groups())
if any(map(lambda v: v >... | bigcode/self-oss-instruct-sc2-concepts |
def experiment_pivot_table(experiment_snapshots_df,
per_benchmark_ranking_function):
"""Creates a pivot table according to a given per benchmark ranking, where
the columns are the fuzzers, the rows are the benchmarks, and the values
are the scores according to the per benchmark ra... | bigcode/self-oss-instruct-sc2-concepts |
def get_robot_number_and_alliance(team_num, match_data):
"""Gets the robot number (e.g. the `1` in initLineRobot1) and alliance color."""
team_key = f'frc{team_num}'
for alliance in ['red', 'blue']:
for i, key in enumerate(match_data['alliances'][alliance]['team_keys'], start=1):
if team... | bigcode/self-oss-instruct-sc2-concepts |
def getOutputFormat(seconds):
"""Returns a format string for the given number of seconds with the least leading zeros."""
if seconds < 60:
return "%S"
elif seconds < 3600:
return "%M:%S"
else:
return "%H:%M:%S" | bigcode/self-oss-instruct-sc2-concepts |
def A_tot_wkend_days_init(M, i, t, e):
"""
Initialize number of weekend days worked in the i'th pattern, tour type t,
and weekend type e.
:param M: Model
:param i: weekend worked pattern
:param t: tour type
:param e: weekend type (1=Sun and Sat, 2=Fri and Sat)
:return: number of weekend... | bigcode/self-oss-instruct-sc2-concepts |
def apply_homography_to_point(hmg, x, y, is_matrix=True):
"""Transforms a point (x, y) with a homography hmg.
Args:
hmg: a homography transformation of data type float32. If mode is 'matrix',
it is of shape [3, 3]; otherwise its shape is [8].
x: the x coordinate of the point
y: the y coordinate o... | bigcode/self-oss-instruct-sc2-concepts |
def get_effective_bp(lam_i, lam_f, Nbp):
"""Returns the bandpass values given initial & final wavelengths,
and number of bands"""
return (lam_f/lam_i)**(1./Nbp) - 1. | bigcode/self-oss-instruct-sc2-concepts |
def pdfa2dict(pdfa):
"""Convert PDFA into nested dictionary of the form:
mapping = {
<State>: (<Label>, {
<Action>: {
<State>: <Probability>
}
}
}
Returns: mapping and the start state.
"""
mapping = {}
for s in pdfa.states():... | bigcode/self-oss-instruct-sc2-concepts |
def _coalesce(*args):
""" Returns first non-null argument, or None if all are null. """
return next((a for a in args if a is not None), None) | bigcode/self-oss-instruct-sc2-concepts |
def findall(lst, key, value):
"""
Find all items in lst where key matches value.
For example find all ``LAYER``s in a ``MAP`` where ``GROUP`` equals ``VALUE``
:param list lst: A list of composite dictionaries e.g. ``layers``, ``classes``
:param string key: The key name to search each dictionary in ... | bigcode/self-oss-instruct-sc2-concepts |
def return_label(predicted_probs):
"""
Function that takes in a list of 7 class
probabilities and returns the labels
with probabilities over a certain threshold.
"""
threshold = 0.4
labels = []
classes = ['not toxic', 'toxic', 'severe toxic', 'obscene',
'threat', 'insult',... | bigcode/self-oss-instruct-sc2-concepts |
from typing import Union
from typing import List
def list_of_ints(string: str, delimiter: Union[str, None] = None) -> List[int]:
"""Cast a string to a list of integers.
Args:
string: String to be converted to a list of int's.
delimiter: Delimiter between integers in the string.
De... | bigcode/self-oss-instruct-sc2-concepts |
def incrementMatching(text, matchSet, maxLength=None, n=2):
"""
Adds incrementing n-digit numbers to text until it no longer matches any
entries on matchSet.
"""
if maxLength is not None and len(text) > maxLength:
text = text[0:maxLength]
while text in matchSet:
if text[-n:].isdi... | bigcode/self-oss-instruct-sc2-concepts |
def _power_law_conversion_factor(g, e, e1, e2):
"""Conversion factor between differential and integral flux."""
term1 = e / (-g + 1)
term2 = (e2 / e) ** (-g + 1) - (e1 / e) ** (-g + 1)
return term1 * term2 | bigcode/self-oss-instruct-sc2-concepts |
def timedelta_seconds(timedelta):
"""Returns the total timedelta duration in seconds."""
return (timedelta.total_seconds() if hasattr(timedelta, "total_seconds")
else timedelta.days * 24 * 3600 + timedelta.seconds +
timedelta.microseconds / 1000000.) | bigcode/self-oss-instruct-sc2-concepts |
import time
def W3CDate(tmsecs=None):
""" Return UTC time string according to http://www.w3.org/TR/NOTE-datetime
"""
if not tmsecs:
tmsecs = time.gmtime()
return time.strftime("%Y-%m-%dT%H:%M:%S", tmsecs) + "Z" | bigcode/self-oss-instruct-sc2-concepts |
def _get_spot_surface(image, spot_y, spot_x, radius_yx):
"""Get a subimage of a detected spot in 2 dimensions.
Parameters
----------
image : np.ndarray
Image with shape (y, x).
spot_y : np.int64
Coordinate of the detected spot along the y axis.
spot_x : np.int64
Coordina... | bigcode/self-oss-instruct-sc2-concepts |
def increase(colour, increments):
"""Take a colour and increase each channel by the increments given in the list"""
colour_values = [int(colour[1:3], 16), int(colour[3:5], 16), int(colour[5:], 16)]
output = [min(255, colour_values[0] + increments[0]), min(255, colour_values[1] + increments[1]), min(255, col... | bigcode/self-oss-instruct-sc2-concepts |
from typing import Optional
from datetime import datetime
def check_expiration(expiration_datetime: Optional[datetime]):
"""
Checks if an expiration date was exceeded. Returns true if expired.
"""
return expiration_datetime is not None and datetime.now() >= expiration_datetime | bigcode/self-oss-instruct-sc2-concepts |
def _CheckNoFRIEND_TEST(input_api, output_api):
"""Make sure that gtest's FRIEND_TEST() macro is not used, the
FRIEND_TEST_ALL_PREFIXES() macro from testsupport/gtest_prod_util.h should be
used instead since that allows for FLAKY_, FAILS_ and DISABLED_ prefixes."""
problems = []
file_filter = lambda f: f.Loc... | bigcode/self-oss-instruct-sc2-concepts |
import random
def shuffle_deck(deck):
"""Returns a shuffled deck made up of cards from the given deck"""
# print("\nShuffling the deck!")
shuffled_deck = deck[:]
random.shuffle(shuffled_deck)
return(shuffled_deck) | bigcode/self-oss-instruct-sc2-concepts |
def walk_through_dict(
dictionary, end_fn, max_depth=None, _trace=None, _result=None, **kwargs
):
"""Runs a function at a given level in a nested dictionary.
If `max_depth` is unspecified, `end_fn()` will be run whenever
the recursion encounters an object other than a dictionary.
Parameters
--... | bigcode/self-oss-instruct-sc2-concepts |
def _version_string(version):
"""Convert version from bytes to a string.
Args:
version: version in byte format.
Returns:
Three byte version string in hex format: 0x00 0x00 0x00
"""
return ' '.join('0x{:02x}'.format(ord(b)) for b in version) | bigcode/self-oss-instruct-sc2-concepts |
def quantify(iterable, pred=bool):
"""Return the how many times the predicate is true.
>>> quantify([True, False, True])
2
"""
return sum(map(pred, iterable)) | bigcode/self-oss-instruct-sc2-concepts |
def read_template_source(filename):
"""Read the source of a RiveScript template, returning the Unicode text."""
try: # v0.2.0: Issue #3
with open(filename, 'r', encoding='utf-8') as f:
text = f.read()
except Exception: # v0.2.0: Issue #3
text = '' ... | bigcode/self-oss-instruct-sc2-concepts |
def hamming_distance(m, n):
"""Hamming Distance between two natural numbers is the number of ones
in the binary representation of their xor.
"""
return sum(map(int, bin(m ^ n)[2:])) | bigcode/self-oss-instruct-sc2-concepts |
def load_txt(label_file):
"""Load bounding boxes data from the given label file.
Parameters
label_file: str
Path to label file.
Returns
data: list
List of bounding boxes data.
"""
data = []
with open(label_file) as f:
for line in f:
row = line.st... | bigcode/self-oss-instruct-sc2-concepts |
def remove_dupes(iterable):
"""
Removes duplicate items from iterable object preserving original iterable order
:param iterable: iterable
:return: iterable
"""
unique = set()
new_iter = iterable.__class__()
for item in iterable:
if item not in unique:
new_iter.append... | bigcode/self-oss-instruct-sc2-concepts |
def is_iri(string):
"""
Return True if the given string looks like an IRI, and False otherwise.
Used for finding type IRIs in the schema.
Right now only supports http(s) URLs because that's all we have in our schema.
"""
return string.startswith('http') | bigcode/self-oss-instruct-sc2-concepts |
def _check_and_convert_legacy_input_config_key(key):
"""Checks key and converts legacy input config update to specific update.
Args:
key: string indicates the target of update operation.
Returns:
is_valid_input_config_key: A boolean indicating whether the input key is to
update input config(s).
... | bigcode/self-oss-instruct-sc2-concepts |
def load_metis_part_sol (inputfile):
"""
read metis partition result
"""
lines = [open(inputfile, 'r').read().strip("\n")][0].split('\n')
cut = int( lines[0].split('\t')[1] )
partDict = {}
for line in lines[1:]:
tokens = line.split('\t')
part = int( tokens[0].split(' ')[-1] )
nodes = tokens[1].split(',')... | bigcode/self-oss-instruct-sc2-concepts |
def parseMovie(line):
"""
Parses a movie record in MovieLens format movieId::movieTitle .
"""
fields = line.split("::")
return int(fields[0]), fields[1] | bigcode/self-oss-instruct-sc2-concepts |
import re
def remove_non_numeric (value):
"""
Remove non-numeric characters from value.
:param value: The value to be modified.
:return Numeric value.
"""
return re.sub("[^0-9]", "", value) | bigcode/self-oss-instruct-sc2-concepts |
def with_leading_upper(example):
"""
Changes the leading letter of the text of example `example` to uppercase.
"""
text = example.text
for (i, c) in enumerate(text):
if not c.isspace():
text = text[:i] + text[i].upper() + text[(i + 1):]
break
example.text = text
... | bigcode/self-oss-instruct-sc2-concepts |
import re
def get_int_or_none(value):
"""
>>> get_int_or_none(123)
123
>>> get_int_or_none('123asda')
123
"""
if isinstance(value, int):
return value
try:
return int(re.sub(r'^(\d+)(.*)$', r'\1', value))
except (TypeError, ValueError):
return None | bigcode/self-oss-instruct-sc2-concepts |
def _to_int_or_none(data: str) -> int | None:
"""Convert to an integer or None."""
return int(data) if data else None | bigcode/self-oss-instruct-sc2-concepts |
def build_example_algo_config(
ticker,
timeseries='minute'):
"""build_example_algo_config
helper for building an algorithm config dictionary
:returns: algorithm config dictionary
"""
willr_close_path = (
'analysis_engine/mocks/example_indicator_williamsr.py')
willr_open... | bigcode/self-oss-instruct-sc2-concepts |
def set_pooling_options(opts, pooling_options=None):
"""Set the IPU pooling compilation options for the session.
.. code-block:: python
# Set "poolUseIntrospectiveMapping" flag to "false"
opts = create_ipu_config()
opts = set_pooling_options(opts,
pooling_options={"poolUseIntrospective... | 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.