seed stringlengths 1 14k | source stringclasses 2
values |
|---|---|
def ajoute_virgule(valeur1):
"""Ajoute une virgule, s'il n'y en a pas déjà."""
if valeur1.find(".") == -1:
return valeur1 + "."
else:
return valeur1 | bigcode/self-oss-instruct-sc2-concepts |
def make_profile_mask(ref_2d_profile, threshold=1e-3):
"""Build a mask of the trace based on the 2D profile reference file.
:param ref_2d_profile: the 2d trace profile reference.
:param threshold: threshold value for excluding pixels based on
ref_2d_profile.
:type ref_2d_profile: array[flo... | bigcode/self-oss-instruct-sc2-concepts |
import random
def initialize_hetero_vector(class_, limits):
"""Initializes a heterogeneous vector of type `class_` based on the values
in `limits`.
:param class_: the class into which the final list will be
typecasted into.
:param limits: a list that determines whether an element o... | bigcode/self-oss-instruct-sc2-concepts |
def kpt_flip(kpts, img_shape, flip_pairs, direction):
"""Flip keypoints horizontally or vertically.
Args:
kpts (Tensor): Shape (..., 2)
img_shape (tuple): Image shape.
flip_pairs (list): Flip pair index.
direction (str): Flip direction, only "horizontal" is supported now.
... | bigcode/self-oss-instruct-sc2-concepts |
import struct
def _StToNum(S):
"""
Convert S to a number.
:param S: The (big-endian) bytestring to convert to an integer
:type S: bytes
:return: An integer representation of the bytestring (rightmost chr == LSB)
:rtype: int
"""
return struct.unpack('>L', S)[0] | bigcode/self-oss-instruct-sc2-concepts |
def cleanp(stx):
"""
Simple string cleaner
"""
return stx.replace("(", "").replace(")", "").replace(",", "") | bigcode/self-oss-instruct-sc2-concepts |
def mergeRegions(regions):
"""
Given a list of [(chrom, start, end), ...], merge all overlapping regions
This returns a dict, where values are sorted lists of [start, end].
"""
bar = sorted(regions)
out = dict()
last = [None, None, None]
for reg in bar:
if reg[0] == last[0] and ... | bigcode/self-oss-instruct-sc2-concepts |
def parse_notifier_name(name):
"""Convert the name argument to a list of names.
Examples
--------
>>> parse_notifier_name('a')
['a']
>>> parse_notifier_name(['a','b'])
['a', 'b']
>>> parse_notifier_name(None)
['anytrait']
"""
if isinstance(name, str):
return [name]
... | bigcode/self-oss-instruct-sc2-concepts |
def sqrt_expansion(ceil):
"""
Returns the number of fractions (of the expansion of sqrt(2)) where the
numerator has more digits than the denominator in the first ceil
iterations.
"""
counter = 0
frac = [1, 1]
for _ in range(ceil):
frac = [frac[0] + 2 * frac[1], frac[0] + frac[1]]... | bigcode/self-oss-instruct-sc2-concepts |
def _prune_arg(l, key, extra=0):
"""Removes list entry "key" and "extra" additional entries, if present.
Args:
l (list): The list to prune.
key (object): The list entry to identify and remove.
extra (int): Additional entries after key to prune, if found.
"""
try:
idx = l.index(key)
args = l... | bigcode/self-oss-instruct-sc2-concepts |
from typing import Set
def get_genes_in_overlap(genes, overlap_list) -> Set[str]:
"""Select members from a gene list which are also in a given overlap(second list of genes)
Parameters
----------
genes : list
ordered list of genes from which to select from
overlap_list ... | bigcode/self-oss-instruct-sc2-concepts |
def _get_y_coord(tile):
"""
Return y coordinate of square
"""
return tile[1] | bigcode/self-oss-instruct-sc2-concepts |
def list2dict(
l=['A', 'B', 'C'],
keylist=['a', 'b', 'c']
):
"""
task 0.5.31 && task 0.6.3
implement one line procedure taking a list of letters and a keylist
output should be a dict. that maps them together
e.g. input l=['A', 'B', 'C'] keylist=['a', 'b', 'c'] output={'a':'A', '... | bigcode/self-oss-instruct-sc2-concepts |
def find_selfloop_nodes(G):
"""
Finds all nodes that have self-loops in the graph G.
"""
nodes_in_selfloops = []
# Iterate over all the edges of G
for u, v in G.edges():
# Check if node u and node v are the same
if u == v:
# Append node u to nodes_i... | bigcode/self-oss-instruct-sc2-concepts |
def rerun_probability(n_runs):
"""
Calculates a probability for running another episode with the same
genome.
"""
if n_runs <= 0:
return 1
return 1 / n_runs**2 | bigcode/self-oss-instruct-sc2-concepts |
import random
import decimal
def randdecimal(precision, scale):
"""Generate a random decimal value with specified precision and scale.
Parameters
----------
precision : int
The maximum number of digits to generate. Must be an integer between 1
and 38 inclusive.
scale : int
... | bigcode/self-oss-instruct-sc2-concepts |
def max_transmit_rule(mod, l, tmp):
"""
**Constraint Name**: TxSimple_Max_Transmit_Constraint
**Enforced Over**: TX_SIMPLE_OPR_TMPS
Transmitted power cannot exceed the maximum transmission flow capacity in
each operational timepoint.
"""
return (
mod.TxSimple_Transmit_Power_MW[l, tm... | bigcode/self-oss-instruct-sc2-concepts |
def get_lam_list(self, is_int_to_ext=True):
"""Returns the ordered list of lamination of the machine
Parameters
----------
self : MachineSRM
MachineSRM object
is_int_to_ext : bool
true to order the list from the inner lamination to the extrenal one
Returns
-------
lam_l... | bigcode/self-oss-instruct-sc2-concepts |
def column(matrix, i):
"""
Gets column of matrix.
INPUTS:
Matrix, Int of column to look at
RETURNS:
Array of the column
"""
return [row[i] for row in matrix] | bigcode/self-oss-instruct-sc2-concepts |
def _ensure_extension(filename: str, extension: str):
"""Add the extension if needed."""
if filename.endswith(extension):
return filename
return filename + extension | bigcode/self-oss-instruct-sc2-concepts |
import socket
def have_connectivity(host="8.8.8.8", port=53, timeout=3):
""" Attempt to make a DNS connection to see if we're on the Internet.
From https://stackoverflow.com/questions/3764291/checking-network-connection
@param host: the host IP to connect to (default 8.8.8.8, google-public-dns-a.google.co... | bigcode/self-oss-instruct-sc2-concepts |
def str2list(data):
"""
Create a list of values from a whitespace and newline delimited text (keys are ignored).
For example, this:
ip 1.2.3.4
ip 1.2.3.5
ip 1.2.3.6
becomes:
['1.2.3.4', '1.2.3.5', '1.2.3.6']
"""
list_data = []
for line in data.split('\n'):
line = l... | bigcode/self-oss-instruct-sc2-concepts |
from datetime import datetime
def read_mne_raw_edf_header(edf_obj, **kwargs):
"""
Header extraction function for RawEDF and Raw objects.
Reads the number of channels, channel names and sample rate properties
If existing, reads the date information as well.
Returns:
Header information as d... | bigcode/self-oss-instruct-sc2-concepts |
def formatter(msg, values):
"""Functional form of format on strings"""
return msg.format(**values) | bigcode/self-oss-instruct-sc2-concepts |
from typing import Union
import base64
def read_file_as_b64(path: Union[str, bytes, int]) -> str:
"""Reads a file's contents as binary bytes and encodes it in a base64-string.
Args:
path (Union[str, bytes, int]): binary file path
Returns:
str: file's bytes in base64-encoded string
""... | bigcode/self-oss-instruct-sc2-concepts |
def isstr(s):
"""True if 's' is an instance of basestring in py2, or of str in py3"""
bs = getattr(__builtins__, 'basestring', str)
return isinstance(s, bs) | bigcode/self-oss-instruct-sc2-concepts |
from typing import List
import copy
def insertion_sort(x: List) -> List:
"""Insertion sort compares elements and moves them to their correct position by repeatedly comparing an element
with previous elements in the list until its correct position is located, then moving the element to its correct
position... | bigcode/self-oss-instruct-sc2-concepts |
from typing import Union
import logging
def get_level(level:Union[str,int]) -> str:
"""Return the logging level as a string"""
if isinstance(level, str):
return level.upper()
return logging.getLevelName(level) | bigcode/self-oss-instruct-sc2-concepts |
def set_cur_model(client, model, drawing=None):
"""Set the active model on a drawing.
Args:
client (obj):
creopyson Client
model (str):
Model name.
drawing (str, optional):
Drawing name. Defaults: current active drawing.
Returns:
None
... | bigcode/self-oss-instruct-sc2-concepts |
def G(poisson, young):
"""
Shear Modulus in MPa.
"""
result = young/(2*(1+poisson))
return result | bigcode/self-oss-instruct-sc2-concepts |
from typing import Union
def operacion_basica(a: float, b: float, multiplicar: bool) -> Union[float, str]:
"""Toma dos números (a, b) y un booleano (multiplicar):
- Si multiplicar es True: devuelve la multiplicación entre a y b.
- Si multiplicar es False: devuelve la division entre a y b.
... | bigcode/self-oss-instruct-sc2-concepts |
import math
def is_pentagonal(p: int) -> int:
"""
P = n * (3n - 1) / 2
If P is pentagonal, the above equation will have a positive integer solution
for n. We use the quadratic formula to check if either solution for n is a
positive integer
"""
root = math.sqrt(24 * p + 1)
return root.... | bigcode/self-oss-instruct-sc2-concepts |
def int2uint32(value):
"""
Convert a signed 32 bits integer into an unsigned 32 bits integer.
>>> print(int2uint32(1))
1
>>> print(int2uint32(2**32 + 1)) # ignore bits larger than 32 bits
1
>>> print(int2uint32(-1))
4294967295
"""
return value & 0xffffffff | bigcode/self-oss-instruct-sc2-concepts |
def to_camel_case(snake_case_string):
"""
Convert a string from snake case to camel case.
:param snake_case_string: Snake-cased string to convert to camel case.
:returns: Camel-cased version of snake_case_string.
"""
parts = snake_case_string.lstrip('_').split('_')
return parts[0] + ''.join... | bigcode/self-oss-instruct-sc2-concepts |
def sstate_get_manifest_filename(task, d):
"""
Return the sstate manifest file path for a particular task.
Also returns the datastore that can be used to query related variables.
"""
d2 = d.createCopy()
extrainf = d.getVarFlag("do_" + task, 'stamp-extra-info')
if extrainf:
d2.setVar(... | bigcode/self-oss-instruct-sc2-concepts |
def get_nodes(edges):
"""
Get nodes from list of edges.
Parameters
----------
edges : list
List of tuples (source page, end page).
Returns
-------
list
nodes, not unique
"""
nodes = []
for edge in edges:
nodes += list(edge)
return nodes | bigcode/self-oss-instruct-sc2-concepts |
def t2n(torch_tensor):
"""
Convert torch.tensor to np.ndarray.
"""
return torch_tensor.cpu().detach().numpy() | bigcode/self-oss-instruct-sc2-concepts |
import torch
def build_vertices(corners1:torch.Tensor, corners2:torch.Tensor,
c1_in_2:torch.Tensor, c2_in_1:torch.Tensor,
inters:torch.Tensor, mask_inter:torch.Tensor):
"""find vertices of intersection area
Args:
corners1 (torch.Tensor): (B, N, 4, 2)
corners2... | bigcode/self-oss-instruct-sc2-concepts |
def _get_ips(ips_as_string):
"""Returns viable v4 and v6 IPs from a space separated string."""
ips = ips_as_string.split(" ")[1:] # skip the header
ips_v4, ips_v6 = [], []
# There is no guarantee if all the IPs are valid and sorted by type.
for ip in ips:
if not ip:
continue
... | bigcode/self-oss-instruct-sc2-concepts |
def rmFromList(lst, thing=''):
"""Removes all values matching thing from a list"""
lst = list(lst)
for i in range(len(lst)-1, -1, -1):
if lst[i] == thing:
del lst[i]
return lst | bigcode/self-oss-instruct-sc2-concepts |
import json
import six
import base64
def _base64_encode(dictionary):
"""Returns base64(json(dictionary)).
:param dictionary: dict to encode
:type dictionary: dict
:returns: base64 encoding
:rtype: str
"""
json_str = json.dumps(dictionary, sort_keys=True)
str_bytes = six.b(json_str)
... | bigcode/self-oss-instruct-sc2-concepts |
def to_bytes(string):
"""Convert string to bytes type."""
if isinstance(string, str):
string = string.encode('utf-8')
return string | bigcode/self-oss-instruct-sc2-concepts |
def check_in(position, info_pos_line_pairs):
"""
Check if position corresponds to the starting position of a pair in info_pos_line_pairs
(return pair if found, empty list otherwise)
:param position: list
:param info_pos_line_pairs: list of lists
:return: list
"""
# pos_pair form: [info,... | bigcode/self-oss-instruct-sc2-concepts |
import re
def substitute_and_count(this, that, var, replace=True, count=0):
"""Perform a re substitute, but also count the # of matches"""
(result, ctr) = re.subn(this, that, var, count=count)
if not replace:
return (var, result)
return (result, ctr) | bigcode/self-oss-instruct-sc2-concepts |
def is_valid(x, y, grid, x_max, y_max):
"""Check the bounds and free space in the map"""
if 0 <= x < x_max and 0 <= y < y_max:
return grid[x][y] == 0
return False | bigcode/self-oss-instruct-sc2-concepts |
def decode(data):
"""
Normalize a "compressed" dictionary with special 'map' entry.
This format looks like a way to reduce bandwidth by avoiding repeated
key strings. Maybe it's a JSON standard with a built-in method to
decode it? But since I'm REST illiterate, we decode it manually!
For examp... | bigcode/self-oss-instruct-sc2-concepts |
import torch
def trainGenerator(netG, netD, optimiserG, inputs, targets, loss_func, device, lambdapar):
"""
This function trains the generator
:param netG: The generator network
:param netD: The discriminator network
:param optimiserG: The optimiser for the generator
:param inputs:... | bigcode/self-oss-instruct-sc2-concepts |
from typing import Tuple
from typing import List
def get_moves(
group_position: Tuple[int, int], size: int, neighbors: List[Tuple[int, int]]
):
"""
:param group_position:
:param size:
:param neighbors:
:return: A list of move tuples from group_position to each neighbor
"""
return [(*gr... | bigcode/self-oss-instruct-sc2-concepts |
def exc_msg_str(exception, default="") -> str:
"""
Extract the exception's message, or its str representation, or the default message, in order of
priority.
"""
try:
msg = exception.args[0]
except (AttributeError, IndexError):
msg = None
if not msg or not isinstance(msg, str... | bigcode/self-oss-instruct-sc2-concepts |
def make_album(artist, title):
"""Build a dictionary containing information about an album."""
album_dictionary = {'artist' : artist.title(), 'title' : title.title()}
return album_dictionary | bigcode/self-oss-instruct-sc2-concepts |
def average_list(l1, l2):
"""Return the average of two lists"""
return [(i1 + i2) / 2 for i1, i2 in zip(l1, l2)] | bigcode/self-oss-instruct-sc2-concepts |
def rssf(rr, index, scale=10):
"""Read and scale single to float."""
return float(rr.registers[index]) / scale | bigcode/self-oss-instruct-sc2-concepts |
def distance(point1, point2):
"""
Returns the Euclidean distance of two points in the Cartesian Plane.
>>> distance([3,4],[0,0])
5.0
>>> distance([3,6],[10,6])
7.0
"""
return ((point1[0] - point2[0])**2 + (point1[1] - point2[1])**2) ** 0.5 | bigcode/self-oss-instruct-sc2-concepts |
def factorial(n: int) -> int:
"""Função recursiva para o cálculo fatorial
Args:
n (int): Valor que terá o fatorial calculado
Returns:
int: Fatorial calculado
"""
if n > 1:
return factorial(n - 1) * n
return 1 | bigcode/self-oss-instruct-sc2-concepts |
import requests
import logging
def validate_server(url):
"""
Validates if a konduit.Server is running under the specified url. Returns True if
the server is running, False otherwise.
:param url: host and port of the server as str
:return: boolean
"""
try:
r = requests.get("{}/heal... | bigcode/self-oss-instruct-sc2-concepts |
from typing import List
def print_bitstring(width: int, bitset: List[int]) -> str:
"""Format and print a bitset of a certain width with padding."""
return "".join(map(lambda x: bin(x)[2:].zfill(8)[:width], bitset)) | bigcode/self-oss-instruct-sc2-concepts |
import contextlib
import socket
def tcp_port_connectable(hostname, port):
"""
Return true if we can connect to a TCP port
"""
try:
with contextlib.closing(socket.socket(socket.AF_INET,
socket.SOCK_STREAM)) as sk:
sk.settimeout(5)
... | bigcode/self-oss-instruct-sc2-concepts |
def maxdt(area, shape, maxvel):
"""
Calculate the maximum time step that can be used in the simulation.
Uses the result of the Von Neumann type analysis of Di Bartolo et al.
(2012).
Parameters:
* area : [xmin, xmax, zmin, zmax]
The x, z limits of the simulation area, e.g., the shallow... | bigcode/self-oss-instruct-sc2-concepts |
def get_simulation_attributes(cube):
"""Get model, experiment and mip information."""
model = cube.attributes['model_id']
experiment = cube.attributes['experiment_id']
physics = cube.attributes['physics_version']
run = cube.attributes['realization']
mip = 'r%si1p%s' %(run, physics)
if expe... | bigcode/self-oss-instruct-sc2-concepts |
def _create_python_packages_string(python_packages: list):
"""
Builds the specific string required by Zeppelin images to install Python packages.
:param python_packages: list containing Python package strings
:return: the properly formatted Python packages string
"""
if len(python_packages) == ... | bigcode/self-oss-instruct-sc2-concepts |
import math
def window(outsideLux):
"""Returns the effect of windows on lux."""
if outsideLux > 1:
percent = 1/math.log(outsideLux)
if percent > 100:
percent = 100.0
return outsideLux*percent
else:
return outsideLux / 10.0 | bigcode/self-oss-instruct-sc2-concepts |
def count(input_, condition=lambda x: True):
"""Count the number of items in an iterable for a given condition
For example:
>>>count("abc")
3
>>>count("abc", condition=lambda x: x=="a")
1
"""
return sum(condition(item) for item in input_) | bigcode/self-oss-instruct-sc2-concepts |
from typing import OrderedDict
def format_budgets(budgets, allow_whitespace=False):
"""
Format budget-strings so that they are as short as possible while still distinguishable
Parameters
----------
budgets: List[str]
list with budgets
allow_whitespace: bool
if set to True, wil... | bigcode/self-oss-instruct-sc2-concepts |
import click
def confirm(text):
# type: (str) -> bool
"""Confirm yes/no."""
return click.confirm(text) | bigcode/self-oss-instruct-sc2-concepts |
def pair_reads(r1, r2):
"""
Given bam entries for two ends of the same read (R1/R2) that have
been aligned as if they were single-end reads, set the fields in the
entries so that they are now properly paired.
Args:
r1, r2 (pysam.AlignedSegment): two ends of the same read, both
a... | bigcode/self-oss-instruct-sc2-concepts |
def is_valid_port(port):
"""Checks a port number to check if it is within the valid range
Args:
port - int, port number to check
Returns:
bool, True if the port is within the valid range or False if not
"""
if not isinstance(port, int):
return False
return 1024 < port <... | bigcode/self-oss-instruct-sc2-concepts |
def mask_landsat8_sr(image):
"""Mask clouds and cloud shadows in Landsat surface reflectance image.
Obtained from:
https://developers.google.com/earth-engine/datasets/catalog/LANDSAT_LC08_C01_T2_SR
Parameters
----------
image : ee.Image
Input image (Landsat 8 Surface Reflectance).
... | bigcode/self-oss-instruct-sc2-concepts |
import re
def safe_name(name):
"""Convert an arbitrary string to a standard distribution name
Any runs of non-alphanumeric/. characters are replaced with a single '-'.
"""
return re.sub('[^A-Za-z0-9.]+', '-', name) | bigcode/self-oss-instruct-sc2-concepts |
def deepget(obj, keys):
"""
Deepget is a small function enabling the user to "cherrypick" specific
values from deeply nested dicts or lists. This is useful, if the just one
specific value is needed, which is hidden in multiple hierarchies.
:Example:
>>> import diggrtoolbox as dt
>>... | bigcode/self-oss-instruct-sc2-concepts |
import shutil
def is_travis_installed() -> bool:
"""Return a boolean representing if travis gem is installed."""
return shutil.which("travis") is not None | bigcode/self-oss-instruct-sc2-concepts |
def get_rlz_list(all_rlz_records):
""" Returns list of unique reverse lookup zone files """
# Casting as set() removes duplicates
return list(set([i["zone_file"] for i in all_rlz_records])) | bigcode/self-oss-instruct-sc2-concepts |
def image_scale(img):
"""Retrieves the image cell size (e.g., spatial resolution)
Args:
img (object): ee.Image
Returns:
float: The nominal scale in meters.
"""
return img.projection().nominalScale().getInfo() | bigcode/self-oss-instruct-sc2-concepts |
def has_c19_scope (scopes):
""" Check if the COVID-19 GLIDE number or HRP code is present """
for scope in scopes:
if scope.type == "1" and scope.vocabulary == "1-2" and scope.code.upper() == "EP-2020-000012-001":
return True
elif scope.type == "2" and scope.vocabulary == "2-1" and s... | bigcode/self-oss-instruct-sc2-concepts |
def del_fake_nums(intList, step): #8
"""
Delete fake numbers added by the fake_nums function (only used in decryption)
"""
placeToDelNum = []
for index in range(0, len(intList), step+1):
placeToDelNum.append(index)
newIntList = [item for item in intList]
for index in reversed(placeTo... | bigcode/self-oss-instruct-sc2-concepts |
def preço_final(preço, **kwargs):
"""
Preço final
-----------
Calcula o valor final de um produto.
args
----
preço : float
Preço inicial do produto
**kwargs
--------
imposto : float
Imposto sobre o preço (%)
desconto : float
Desconto... | bigcode/self-oss-instruct-sc2-concepts |
def convert_coordinates(value: str) -> float:
"""Convert coordinates to lat/long."""
if len(value) < 8:
return float(value[0] + "." + value[1:])
return float(value[0:2] + "." + value[2:]) | bigcode/self-oss-instruct-sc2-concepts |
def magnitude(vector):
""" get magnitude (length) of vector """
return (vector[0]**2 + vector[1]**2 + vector[2]**2) ** .5 | bigcode/self-oss-instruct-sc2-concepts |
def add_user(db, meeting_id, user_email, responded=False,busy_times=[]):
"""
@brief addds a user to a specific collection in our mongo database
@param mongo the "meetme" database
@param meeting_id a unique meeting_id, randomly generated and shared across multiple users
attending the ... | bigcode/self-oss-instruct-sc2-concepts |
def is_complete(board: list[list[int]]) -> bool:
"""
Periksa apakah papan (matriks) telah terisi penuh dengan nilai bukan nol.
>>> is_complete([[1]])
True
>>> is_complete([[1, 2], [3, 0]])
False
"""
return not any(elem == 0 for row in board for elem in row) | bigcode/self-oss-instruct-sc2-concepts |
import sympy
def airystressint(XA, XB, YA, YB, P, a, b, E, nu):
"""
Calculate integrals of strain energy values based on an Airy stress function
"""
x1, x2, xa, xb, ya, yb = sympy.symbols("x_1, x_2 x_a x_b y_a y_b")
sigma = sympy.Matrix([
[3 * P / (2 * a**3 * b) * x1 * x2],
[0],
... | bigcode/self-oss-instruct-sc2-concepts |
def dggs_cell_overlap(cell_one: str, cell_two: str):
"""
Determines whether two DGGS cells overlap.
Where cells are of different resolution, they will have different suid lengths. The zip function truncates the longer
to be the same length as the shorter, producing two lists for comparison. If these lis... | bigcode/self-oss-instruct-sc2-concepts |
def groupms_byiconf(microstates, iconfs):
"""
This function takes in a list of microstates and a list of conformer indicies, divide microstates into two groups:
the first one is those contain one of the given conformers, the second one is those contain none of the listed conformers.
"""
ingroup = []... | bigcode/self-oss-instruct-sc2-concepts |
def get_bucket_and_key(s3_path):
"""Get the bucket name and key from the given path.
Args:
s3_path(str): Input S3 path
"""
s3_path = s3_path.replace('s3://', '')
s3_path = s3_path.replace('S3://', '') #Both cases
bucket, key = s3_path.split('/', 1)
return bucket, key | bigcode/self-oss-instruct-sc2-concepts |
def boiler_mode(raw_table, base_index):
""" Convert boiler mode to english """
value = raw_table[base_index]
if value == 4:
return "Summer"
if value == 5:
return "Winder"
return "Unknown" | bigcode/self-oss-instruct-sc2-concepts |
def get_longitude_ref_multiplier(imgMetadata):
"""
Returns the longitude multiplier according to the
Exif.GPSInfo.GPSLongitudeRef EXIF tag contained in the imgMetadata dict.
"""
if imgMetadata['Exif.GPSInfo.GPSLongitudeRef'].value.lower() == 'w':
return -1
return 1 | bigcode/self-oss-instruct-sc2-concepts |
def args_to_string(args):
"""
Transform experiment's arguments into a string
:param args:
:return: string
"""
args_string = ""
args_to_show = ["experiment", "network_name", "fit_by_epoch", "bz_train",
"lr", "decay", "local_steps"]
for arg in args_to_show:
arg... | bigcode/self-oss-instruct-sc2-concepts |
def esc_format(text):
"""Return text with formatting escaped
Markdown requires a backslash before literal underscores or asterisk, to
avoid formatting to bold or italics.
"""
for symbol in ['_', '*', '[', ']', '(', ')', '~', '`', '>', '#', '+', '-', '=', '|', '{', '}', '.', '!']:
text = str... | bigcode/self-oss-instruct-sc2-concepts |
import json
def load_json(filename):
"""Loads a JSON file and returns a dict of its documents."""
docs = {}
with open(filename, encoding="utf-8") as fh:
lines = fh.readlines()
for line in lines:
doc = json.loads(line)
docs[doc["_id"]] = doc
return docs | bigcode/self-oss-instruct-sc2-concepts |
def parse_index_file(filename):
"""Parse index file."""
index = []
for line in open(filename):
index.append(int(line.strip()))
return index | bigcode/self-oss-instruct-sc2-concepts |
def text_tostring(t, default=None, emphasis='emphasis', strong='strong', sup='sup',
fn_anc='fn_anc', fn_sym='fn_sym'):
"""Convert Text object to str.
Mark all styled text with special characters and return str
Example:
>>> t = [('Unmarked text. ', None), ('Text marked "emphasis".', ... | bigcode/self-oss-instruct-sc2-concepts |
import dill
def block_worker(payload):
"""
Worker function used compute pairwise distance/similarity over a whole
block.
"""
similarity, block, serialized, graph = payload
if serialized:
similarity = dill.loads(similarity)
pairs = []
n = len(block)
for i in range(n):
... | bigcode/self-oss-instruct-sc2-concepts |
import glob
def setup_filepaths(data_path, participant_numbers):
"""Set up filepaths for reading in participant .h5 files.
Args:
data_path (str): path to directory containing .h5 files
participant_numbers (list): participant numbers for filepaths
Returns:
list: filepaths to all o... | bigcode/self-oss-instruct-sc2-concepts |
def get_dividing_point(y: list):
"""
找出不同样例的分界点
Args:
y (list): 数据标签
Returns:
int: -1表示全部相同,否则表示分界点
"""
last = y[0]
for i, yi in enumerate(y):
if yi != last:
return i
else:
last = yi
return -1 | bigcode/self-oss-instruct-sc2-concepts |
def parse_imr_line(line):
"""
Parses a line of the IMR csv dataset to tupples
:param line:
:return: ( (label1 (int), label2 (int)), features(list of float) )
"""
sl = line.split(";")
if not sl[1].isdigit():
return
label1 = int(sl[1])
label2 = int(sl[2])
features = map(fl... | bigcode/self-oss-instruct-sc2-concepts |
def _log_level_from_verbosity(verbosity):
"""Get log level from verbosity count."""
if verbosity == 0:
return 40
elif verbosity == 1:
return 20
elif verbosity >= 2:
return 10 | bigcode/self-oss-instruct-sc2-concepts |
def intersects(region1, region2):
"""
Check if two regions intersect.
If regions share an end, they don't intersect unless one of the regions has zero length in which case they do
intersect.
Arguments:
region1 -- a first region.
region2 -- a second region.
Returns True if regions inter... | bigcode/self-oss-instruct-sc2-concepts |
import functools
import operator
def get_confidence(model, tag_per_token, class_probs):
"""
Get the confidence of a given model in a token list, using the class probabilities
associated with this prediction.
"""
token_indexes = [model._model.vocab.get_token_index(tag, namespace = "labels") for tag... | bigcode/self-oss-instruct-sc2-concepts |
def gap_line(x, x0, y0, m):
"""
Return the y-value of the gap at the provided x values given.
Simply computes the function for a line
y = (x - x0) * m + y0
"""
return (x - x0) * m + y0 | bigcode/self-oss-instruct-sc2-concepts |
def normalise_sequence(input_sequence):
"""
Normalise a list or tuple to produce a tuple with values representing the proportion of each to the total of the
input sequence.
"""
return (i_value / sum(input_sequence) for i_value in input_sequence) | bigcode/self-oss-instruct-sc2-concepts |
def replace_all(text, dic):
"""
Replaces all occurrences in text by provided dictionary of replacements.
"""
for i, j in list(dic.items()):
text = text.replace(i, j)
return text | 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.