seed stringlengths 1 14k | source stringclasses 2
values |
|---|---|
def subhourly_energy_delivered_rule(mod, prj, tmp):
"""
If no subhourly_energy_delivered_rule is specified in an operational type
module, the default subhourly energy delivered is 0.
"""
return 0 | bigcode/self-oss-instruct-sc2-concepts |
def gini_index(data, feature_name):
"""
Calculates the gini index of the feature with the given name.
:param data: the data to analyze
:param feature_name: the name of the feature to anlyze
:return: the gini index of the specified feature
"""
gini_index = 1
for value_count in data... | bigcode/self-oss-instruct-sc2-concepts |
def sum_stats(stats_data):
"""
Summarize the bounces, complaints, delivery attempts and rejects from a
list of datapoints.
"""
t_bounces = 0
t_complaints = 0
t_delivery_attempts = 0
t_rejects = 0
for dp in stats_data:
t_bounces += dp['Bounces']
t_complaints += dp['Com... | bigcode/self-oss-instruct-sc2-concepts |
def epdir(episode: int) -> str:
"""
Returns the episode folder name given an episode number.
:param episode: The episode number
:return: A formatted string of the episode folder name.
"""
return f"ep{episode}" | bigcode/self-oss-instruct-sc2-concepts |
def logistic_map(pop, rate):
"""
Define the equation for the logistic map.
Arguments
---------
pop: float
current population value at time t
rate: float
growth rate parameter values
Returns
-------
float
scalar result of logistic map at time t+1
"""
... | bigcode/self-oss-instruct-sc2-concepts |
import socket
def open_port(host=''):
""" Return a probably-open port
There is a chance that this port will be taken by the operating system soon
after returning from this function.
"""
# http://stackoverflow.com/questions/2838244/get-open-tcp-port-in-python
s = socket.socket(socket.AF_INET, ... | bigcode/self-oss-instruct-sc2-concepts |
import math
def eq2gal(ra,dec):
"""
Convert Equatorial coordinates to Galactic Coordinates in the epch J2000.
Keywords arguments:
ra -- Right Ascension (in radians)
dec -- Declination (in radians)
Return a tuple (l, b):
l -- Galactic longitude (in radians)
b -- Galactic latitude (in radians)
"""
# RA(rad... | bigcode/self-oss-instruct-sc2-concepts |
def lpad(s, l):
""" add spaces to the beginning of s until it is length l """
s = str(s)
return " "*max(0, (l - len(s))) + s | bigcode/self-oss-instruct-sc2-concepts |
def sort_cells_closest(start_cell, cells):
"""
Description:
Returns a sorted list of cells by 'closest' based on the given start cell
Args:
start_cell (tuple): Coordinates (x, y) of the reference cell
cells (list): List of (x, y) tuples that are the cells to compare
Returns:
... | bigcode/self-oss-instruct-sc2-concepts |
def _SplitStep(user_name):
"""Given a user name for a step, split it into the individual pieces.
Examples:
_SplitStep('Transform/Step') = ['Transform', 'Step']
_SplitStep('Read(gs://Foo)/Bar') = ['Read(gs://Foo)', 'Bar']
Args:
user_name: The full user_name of the step.
Returns:
A list repres... | bigcode/self-oss-instruct-sc2-concepts |
from typing import Union
from typing import List
def _get_error_list(_errors: dict) -> Union[List, None]:
"""
This method return a list of errors,
if any exists
:param _errors: Dict of errors
:return: List of errors or None
"""
errors = []
for err in _errors:
errors.append({
... | bigcode/self-oss-instruct-sc2-concepts |
def format_commands(commands):
"""
This function format the input commands and removes the prepend white spaces
for command lines having 'set' or 'delete' and it skips empty lines.
:param commands:
:return: list of commands
"""
return [
line.strip() if line.split()[0] in ("set", "del... | bigcode/self-oss-instruct-sc2-concepts |
import operator
def array_combine(a, b, op=operator.and_, func=lambda x: x):
""" Returns op(func(a), func(b)) if a and b are both not None;
if one is None, then returns func() on the non-None array;
if both are None, then returns None.
"""
if a is not None and b is not None:
return op(func... | bigcode/self-oss-instruct-sc2-concepts |
def serializer_workbook_path() -> str:
""" Path to excel workbook used by serializer tests. """
return 'tests/data/serializer/test.xlsx' | bigcode/self-oss-instruct-sc2-concepts |
def dic_value(input_dic, key, default=None):
"""
Returns the value from the dic. If input_dic is not a dict, or there is no such key, then returns default
"""
if isinstance(input_dic, dict):
value = input_dic.get(key, default)
else:
value = default
return value | bigcode/self-oss-instruct-sc2-concepts |
def list_dict(l):
"""
return a dictionary with all items of l being the keys of the dictionary
"""
d = {}
for i in l:
d[i]=None
return d | bigcode/self-oss-instruct-sc2-concepts |
def train_and_test_partition(inputs, targets, train_part, test_part):
"""
Splits a data matrix (or design matrix) and associated targets into train
and test parts.
parameters
----------
inputs - a 2d numpy array whose rows are the data points, or can be a design
matrix, where rows are t... | bigcode/self-oss-instruct-sc2-concepts |
import struct
def parse_hdr(data):
"""
Parse L2CAP packet
0 1 2 3 4 5 6 7 0 1 2 3 4 5 6 7 0 1 2 3 4 5 6 7 0 1 2 3 4 5 6 7
-----------------------------------------------------------------
| length | channel id |
-------------------------------------... | bigcode/self-oss-instruct-sc2-concepts |
import re
def get_capitalization_pattern(word, beginning_of_sentence=False):
"""Return the type of capitalization for the string.
Parameters
----------
word : str
The word whose capitalization is determined.
beginning_of_sentence : Optional[bool]
True if the word appears at the be... | bigcode/self-oss-instruct-sc2-concepts |
def readout_tbinfo(line):
"""
Builds the dict for tb info from line provided by qemu
"""
split = line.split("|")
tb = {}
tb["id"] = int(split[0], 0)
tb["size"] = int(split[1], 0)
tb["ins_count"] = int(split[2], 0)
tb["num_exec"] = int(split[3], 0)
tb["assembler"] = split[4].repla... | bigcode/self-oss-instruct-sc2-concepts |
from typing import Any
from pathlib import Path
def tmp_path(tmpdir: Any) -> Path:
"""Convert py.path.Local() to Path() objects."""
return Path(tmpdir.strpath) | bigcode/self-oss-instruct-sc2-concepts |
import random
def random_range(n, total):
"""Return a randomly chosen list of n positive integers summing to total.
Each such list is equally likely to occur."""
dividers = sorted(random.sample(range(1, total), n - 1))
return [a - b for a, b in zip(dividers + [total], [0] + dividers)] | bigcode/self-oss-instruct-sc2-concepts |
def file_to_list(file):
"""Take each line of a file, strip it, and append to a list"""
return [line.strip() for line in open(file)] | bigcode/self-oss-instruct-sc2-concepts |
def override(cls):
"""Decorator for documenting method overrides.
Args:
cls: The superclass that provides the overridden method. If this
cls does not actually have the method, an error is raised.
Examples:
>>> from ray.rllib.policy import Policy
>>> class TorchPolicy(Po... | bigcode/self-oss-instruct-sc2-concepts |
import imp
def create_module(problem_data):
"""Creates a new module for storing compiled code.
Parameters
----------
problem_data - dict
Problem data dictionary
Returns
-------
New module for holding compiled code
"""
problem_name = problem_data['problem_name']
module... | bigcode/self-oss-instruct-sc2-concepts |
import torch
def transform_homogeneous(matrices, vertices):
"""Applies batched 4x4 homogenous matrix transformations to 3-D vertices.
The vertices are input and output as as row-major, but are interpreted as
column vectors multiplied on the right-hand side of the matrices. More
explicitly, this funct... | bigcode/self-oss-instruct-sc2-concepts |
def no_cleanup(value, args):
"""Default cleanup function, returns the unchanged value."""
return value | bigcode/self-oss-instruct-sc2-concepts |
from pathlib import Path
import yaml
def loadConfigDict(configNames: tuple):
# pathLib syntax for windows, max, linux compatibility, see https://realpython.com/python-pathlib/ for an intro
"""
Generic function to load and open yaml config files
:param configNames: Tuple containing names of config fil... | bigcode/self-oss-instruct-sc2-concepts |
def is_comment(string):
"""
Find out if line is a comment or line of code
:param string: line to analyze
:return: True if line is a comment
"""
chars = list(string)
if len(chars) <= 0:
return True
if chars[0] == "#":
return True
else:
return False | bigcode/self-oss-instruct-sc2-concepts |
import zipfile
def un_zip(zip_file, uzip_folder=None):
"""Uncompression .zip file
Args:
zip_files: str, zip_file should be file path;
uzip_folder: str, uncompression files name.
Return:
uzip_folder: str, uncompression files name.
"""
assert zip_file[-4:]==".zip", '`zip... | bigcode/self-oss-instruct-sc2-concepts |
def extract_brackets(line):
"""Splits a scroll 'call line' into identifier + suffix."""
ident, _, enil = line[1:].partition("(")
thing, _, _, = enil.rpartition(")")
return ident, thing | bigcode/self-oss-instruct-sc2-concepts |
def input_output01(input):
"""
Expects a list of lists as input,
outputs each sublist in a line comma delimited.
"""
return '\n'.join(','.join(map(str,sl)) for sl in input) | bigcode/self-oss-instruct-sc2-concepts |
def _str_to_bytes(value: str) -> bytes:
"""Convert ``str`` to bytes"""
return value.encode("utf-8") | bigcode/self-oss-instruct-sc2-concepts |
import torch
def ordinal_accuracy(logits, levels, device='cpu', tolerance=0, reduction='mean'):
"""Computes the accuracy with a tolerance for ordinal error.
Parameters
----------
logits : torch.tensor, shape(num_examples, num_classes-1)
Outputs of the CONDOR layer.
levels : torch.tensor,... | bigcode/self-oss-instruct-sc2-concepts |
def rho_top_liq(x_aver_top_mass, rho_lc_x_aver_top, rho_hc_x_aver_top):
"""
Calculates the destiny of liquid at top of column.
Parameters
----------
x_aver_top_mass : float
The average mass concentration at top of column, [kg/kg]
rho_lc_x_aver_top : float
The destiny of low-boill... | bigcode/self-oss-instruct-sc2-concepts |
def euclidian_distance(ptA, ptB):
"""
Returns the shortest path distance between the two Points
"""
if (ptA.X != ptB.X or ptA.Y != ptB.Y):
return ( (ptA.X - ptB.X)**2 + (ptA.Y - ptB.Y)**2 ) ** (1/2)
return 0.0 | bigcode/self-oss-instruct-sc2-concepts |
def make_binder_pair( h1, h2 ):
"""Returns a binder pair from the two hits
A pair has the form:
( binder1, binder2, orientation1, orientation2 )
Where the binders are pssm names typically and the orientation describes
the strand the pssm binds to (true for positive strand).
"""
b1... | bigcode/self-oss-instruct-sc2-concepts |
from typing import Union
from typing import List
def get_corresponding(
value_or_matrix: Union[int, List[List[int]]], row: int, col: int
) -> int:
"""If `value_or_matrix` is a matrix, extract the value in cell specified by
`row` and `col`. If `value_or_matrix` is a scalar, just return it.
"""
if i... | bigcode/self-oss-instruct-sc2-concepts |
import torch
def convert_frequencies_to_mels(f: torch.Tensor) -> torch.Tensor:
"""
Convert f hertz to m mels
https://en.wikipedia.org/wiki/Mel_scale#Formula
"""
return 2595.0 * torch.log10(1.0 + f / 700.0) | bigcode/self-oss-instruct-sc2-concepts |
def strip_line_nums(line):
"""
Strip line numbers from the start of a line.
"""
# Find the end of a number at the start of the line, if there is one.
pos = 0
line = line.strip()
for c in line:
if (not c.isdigit()):
# Don't delete numeric labels.
if (c == ':')... | bigcode/self-oss-instruct-sc2-concepts |
def total_count(expression):
"""
Compute total count library size.
:param expression: Expression count matrix with genes as rows and samples as columns
:return: integer total count library size per sample
"""
return expression.sum(axis=0) | bigcode/self-oss-instruct-sc2-concepts |
def filename_dist(dist):
""" Return the filename of a distribution. """
if hasattr(dist, 'to_filename'):
return dist.to_filename()
else:
return dist | bigcode/self-oss-instruct-sc2-concepts |
def calcul_max(l: list) -> int:
""" returns the sum of the 2 highest elements of l """
_l = list(l)
max1 = max(_l)
_l.remove(max1)
max2 = max(_l)
return max1 + max2 | bigcode/self-oss-instruct-sc2-concepts |
def _s2_st_to_uv(component: float) -> float:
"""
Convert S2 ST to UV.
This is done using the quadratic projection that is used by default for S2. The C++ and Java S2
libraries use a different definition of the ST cell-space, but the end result in IJ is the same.
The below uses the C++ ST definition... | bigcode/self-oss-instruct-sc2-concepts |
def delegate(connection, identity_token, whitelist=None):
"""Returns authentication token and cookies from given X-MSTR-
IdentityToken.
Args:
connection: MicroStrategy REST API connection object
identity_token: Identity token
whitelist: list of errors for which we skip printing erro... | bigcode/self-oss-instruct-sc2-concepts |
def confirm_name(message, name, force=False):
"""Ask the user to confirm the name.
Parameters
----------
message: str
The message to be printed.
name: str
The string that the user must enter.
force: bool
Override confirmation and return True. Default: False.
Returns... | bigcode/self-oss-instruct-sc2-concepts |
def parse_encode_biosample(data):
"""Parse a python dictionary containing
ENCODE's biosample metadata into a dictionary
with select biosample metadata
:param data: python dictionary containing ENCODE' biosample metadata
:type s: dict
:return: dictionary with parsed ENCODE's biosample meta... | bigcode/self-oss-instruct-sc2-concepts |
import json
import hashlib
def hash_dict(nested_dict):
""" Returns hash of nested dict, given that all keys are strings
"""
dict_string = json.dumps(nested_dict, sort_keys=True)
md5_hash = hashlib.md5(dict_string.encode()).hexdigest()
return md5_hash | bigcode/self-oss-instruct-sc2-concepts |
from typing import Union
def milimeter_mercury_to_bars(mm_hg: float, unit: str) -> Union[float, str]:
"""
This function converts mmHg to bar
Wikipedia reference: https://en.wikipedia.org/wiki/Bar_(unit)
Wikipedia reference: https://en.wikipedia.org/wiki/Millimetre_of_mercury
>>> milimeter_mercury... | bigcode/self-oss-instruct-sc2-concepts |
def print_exptree(root):
"""
Print out an expression tree object via recursion.
Args:
root: expression tree (object type)
"""
# Empty tree
if root is None:
return 0
# Leaf node
if root.left is None and root.right is None:
return print(f'-- leaf: {root.data}'... | bigcode/self-oss-instruct-sc2-concepts |
import click
def valid_band(ctx, param, value):
""" Check image band validity (band >= 1)"""
try:
band = int(value)
assert band >= 1
except:
raise click.BadParameter('Band must be integer above 1')
return band | bigcode/self-oss-instruct-sc2-concepts |
import socket
def get_node_ip_address(address="8.8.8.8:53"):
"""Determine the IP address of the local node.
Args:
address (str): The IP address and port of any known live service on the
network you care about.
Returns:
The IP address of the current node.
"""
ip_address, port = address.split(... | bigcode/self-oss-instruct-sc2-concepts |
from typing import Sequence
from typing import List
def indexify(sequence: Sequence, index_source: Sequence) -> List:
"""For the given `sequence`, get the index of each item in the `index_source`"""
return [index_source.index(item) for item in sequence] | bigcode/self-oss-instruct-sc2-concepts |
def _decayed_value_in_linear(x, max_value, padding_center, decay_rate):
"""
decay from max value to min value with static linear decay rate.
"""
x_value = max_value - abs(padding_center - x) * decay_rate
if x_value < 0:
x_value = 1
return x_value | bigcode/self-oss-instruct-sc2-concepts |
import json
def read_json_file(path: str):
"""Read a json file into a dict."""
with open(path, 'r') as f:
data = json.load(f)
return data | bigcode/self-oss-instruct-sc2-concepts |
import string
import random
def generate_session_id(size=32, chars=string.ascii_letters+string.digits):
"""
Generate session id - 32 length string
with ascii letters and digits
"""
return ''.join(random.choices(chars, k=size)) | bigcode/self-oss-instruct-sc2-concepts |
def get_chars(path_to_vocab):
"""
Return the list of all characters found in the vocabulary.
"""
chars = set()
with open(path_to_vocab) as f:
for line in f:
chars.update(line.rstrip())
return chars | bigcode/self-oss-instruct-sc2-concepts |
def fill_nan(df,list):
"""
Fill nan values with either mean or mode
Parameters
----------
df : dataframe
dataframe used for checking and filling nan values
list: list
list of columns to be checked
Returns
-------
df : dataframe
modified dataframe with no nan... | bigcode/self-oss-instruct-sc2-concepts |
def cidade_pais(cidade: str, pais: str) -> str:
"""
-> Devolve o nome da cidade e do seu país formatados
de forma elegante.
:param cidade: O nome da cidade.
:param pais: O nome do país.
:return: Retorna a string -> 'Cidade, País'
"""
return f'{cidade}, {pais}'.title() | bigcode/self-oss-instruct-sc2-concepts |
def create_envs(service_component_name, *envs):
"""Merge all environment variables maps
Creates a complete environment variables map that is to be used for creating
the container.
Args:
-----
envs: Arbitrary list of dicts where each dict is of the structure:
{
<environment... | bigcode/self-oss-instruct-sc2-concepts |
def get_underline(string):
"""
Return an underline string of the same length as `str`.
"""
return "="*len(string) + "\n" | bigcode/self-oss-instruct-sc2-concepts |
def width_multiplier_op(filters: int,
width_multiplier: float,
min_depth: int = 8) -> int:
"""Determine the number of channels given width multiplier"""
return max(int(filters * width_multiplier), min_depth) | bigcode/self-oss-instruct-sc2-concepts |
def get_status(runs):
"""Get the most recent status of workflow for the current PR.
Parameters
----------
runs : list
List of comment objects sorted by the time of creation in decreasing order.
Returns
-------
status : string
The most recent status of workflow.
Can ... | bigcode/self-oss-instruct-sc2-concepts |
from typing import Tuple
from typing import Dict
def parse_options_header(value: str) -> Tuple[str, Dict[str, str]]:
"""Like werkzeug.http.parse_options_header(), but ignores the options."""
return value.partition(';')[0].strip(), {} | bigcode/self-oss-instruct-sc2-concepts |
def backdoor_examples(xs, backdoor, eps):
"""
Inject a backdoor into training examples with norm epsilon.
"""
return xs + backdoor * eps | bigcode/self-oss-instruct-sc2-concepts |
from pathlib import Path
import re
def normalise_nci_symlinks(input_path: Path) -> Path:
"""
If it's an NCI lustre path, always use the symlink (`/g/data`) rather than specific drives (eg. `/g/data2`).
>>> normalise_nci_symlinks(Path('/g/data2/v10/some/dataset.tar')).as_posix()
'/g/data/v10/some/data... | bigcode/self-oss-instruct-sc2-concepts |
def calc_mean(values):
"""Calculates the mean of a list of numbers."""
values_sum = 0
for value in values:
values_sum += value
return values_sum / len(values) | bigcode/self-oss-instruct-sc2-concepts |
from datetime import datetime
def datetime_serializer(obj):
"""Convert a datetime object to its string representation for JSON serialization.
:param obj: datetime
"""
if isinstance(obj, datetime):
return obj.isoformat() | bigcode/self-oss-instruct-sc2-concepts |
def compute_turbulence_intensity(mean_col, std_col):
"""
Compute turbulence intensity
Args:
mean_col(:obj:`array`): array containing the wind speed mean data; units of m/s
std_col(:obj:`array`): array containing the wind speed standard deviation data; units of m/s
Returns:
:ob... | bigcode/self-oss-instruct-sc2-concepts |
def set_pairing_bit_on_device_type(pairing_bit: bool, device_type: int):
"""
Shifts the pairing bit (True = 1, False = 0) 7 bits to the left and adds
the device type
"""
return (pairing_bit << 7) + device_type | bigcode/self-oss-instruct-sc2-concepts |
def bits2str(inp):
"""
Convert a list of bits into a string. If the number of bits is not a
multiple of 8, the last group of bits will be padded with zeros.
"""
bs = [1<<i for i in range(8)]
return ''.join(chr(sum(bv if bit else 0 for bv,bit in zip(bs, inp[i:i+8]))) for i in range(0, len(inp), ... | bigcode/self-oss-instruct-sc2-concepts |
import random
def Ui(lo, hi):
"""Uniformly distributed integer, inclusive limits."""
return random.randint(lo, hi) | bigcode/self-oss-instruct-sc2-concepts |
def get_xpath_for_date_of_available_time_element(day_index: int) -> str:
"""
The element showing date of the available time is found in the div having the xpath:
'/html/body/div[4]/div[2]/div/div[5]/div/div[2]/div[3]/div[N]/span'
^
where N ... | bigcode/self-oss-instruct-sc2-concepts |
def applyOrderDic(order, aDic):
""" Apply order to aList.
An order of the form ["a","b","c"] means that the first element
should be aDic["a"], and so on.
"""
if order==[]:
return aDic.value()
else:
return map(lambda v:aDic[v], order) | bigcode/self-oss-instruct-sc2-concepts |
def _get_set_env_var_command(name, value):
"""Return command to set environment variable on device."""
return ['--env={n}={v}'.format(n=name, v=value)] | bigcode/self-oss-instruct-sc2-concepts |
def make_dict(table, key_col):
"""
Given a 2D table (list of lists) and a column index key_col,
return a dictionary whose keys are entries of specified column
and whose values are lists consisting of the remaining row entries
"""
table_dict = {}
for key in table:
table... | bigcode/self-oss-instruct-sc2-concepts |
from typing import Any
import json
def serialize_json(obj: Any) -> str:
"""Serialize an object to JSON, removing quotes for special strings."""
return json.dumps(obj).replace('"____', "").replace('____"', "") | bigcode/self-oss-instruct-sc2-concepts |
import re
def get_index(part):
"""
check if the part is, e.g [123]
return 123 or None
"""
index = None
match = re.match(r'\[(\d+)\]', part)
if match:
index = int(match.group(1))
return index | bigcode/self-oss-instruct-sc2-concepts |
def _vars_dir_for_saved_model(
saved_model_path # type: str
):
# type: (str) -> str
"""
Args:
saved_model_path: Root directory of a SavedModel on disk
Returns the location of the directory where the indicated SavedModel will
store its variables checkpoint.
"""
return saved_model_path + "/va... | bigcode/self-oss-instruct-sc2-concepts |
from typing import Set
from typing import Callable
from typing import Any
from typing import Dict
def dict_by(keys: Set[str], f: Callable[[str], Any]) -> Dict[str, Any]:
"""Returns a dictionary with keys equal to the supplied keyset. Each value is
the result of applying f to a key in keys.
"""
return {k: f(k... | bigcode/self-oss-instruct-sc2-concepts |
def toX(x, y=None):
"""
This function is used to load value on Plottable.View
:param x: Float value
:return: x
"""
return x | bigcode/self-oss-instruct-sc2-concepts |
from pathlib import Path
def remove_root(file_path: str) -> str:
"""Remove the first directory of a path"""
full_path = Path(file_path)
relative_path = Path(*full_path.parts[1:])
return str(relative_path) | bigcode/self-oss-instruct-sc2-concepts |
import torch
def swish(x):
"""
Simple implementation of Swish activation function
https://arxiv.org/pdf/1710.05941.pdf
"""
return x * torch.sigmoid(x) | bigcode/self-oss-instruct-sc2-concepts |
from pathlib import Path
def get_definitions(base_directory_path):
"""
For given directory return all *_definition.py files in it and its subdirectories.
"""
return Path(base_directory_path).glob('**/*_definition.py') | bigcode/self-oss-instruct-sc2-concepts |
def overplot_lines(ax, linelabels, lineloc):
"""
Overplots emission lines on an already existing plot with axes
Input:
ax: matplolib axis
linelabels: list of latex formatted names for the lines
lineloc: list of wavelengths of the lines (most likely in Ang)
Output:
ax2: re... | bigcode/self-oss-instruct-sc2-concepts |
import re
def remove_chars(text, chars, replace_with=None):
"""
Removes chars from text or replaces them with the input.
Also removes any extra whitespaces which might have been
introduced.
: param text : text upon which the processing is done
: param chars : chars to search fo... | bigcode/self-oss-instruct-sc2-concepts |
def myreadlines(self):
"""Read and return the list of all logical lines using readline."""
lines = []
while True:
line = self.readline()
if not line:
return lines
else:
lines.append(line) | bigcode/self-oss-instruct-sc2-concepts |
def common_superclass_wnid(group_name):
"""
Get WordNet IDs of common superclasses.
Args:
group_name (str): Name of group
Returns:
superclass_wnid (list): List of WordNet IDs of superclasses
"""
common_groups = {
# ancestor_wnid = 'n0000425... | bigcode/self-oss-instruct-sc2-concepts |
def suma_serie(n: int) -> int:
"""Suma los elementos de la serie E_i = i^3 + 5, desde 1 hasta n.
:param n: número de elementos de la serie
:n type: int
:return: suma de los elementos de la serie
:rtype: int
"""
if n == 1:
return 6
else:
return (n ** 3 + 5) + suma_ser... | bigcode/self-oss-instruct-sc2-concepts |
def NonsfiLoaderArch(target):
"""Returns the arch for the nonsfi_loader"""
arch_map = { 'arm32' : 'arm',
'x8632' : 'x86-32',
'mips32' : 'mips32',
}
return arch_map[target] | bigcode/self-oss-instruct-sc2-concepts |
def tree_unflatten(flat):
"""Nest depth-1 tree to nested tree
{'a.b.c': x} -> {'a': {'b': {'c': x}}} """
def recursion(k, v, out):
k, *rest = k.split('.', 1)
if rest:
recursion(rest[0], v, out.setdefault(k, {}))
else:
out[k] = v
d = {}
for k, ... | bigcode/self-oss-instruct-sc2-concepts |
def linear_derivative(z):
"""Linear activation function derivative"""
return 1 | bigcode/self-oss-instruct-sc2-concepts |
def _season_overflow(season, moved_year, now):
"""Pushes illegal seasons ints into the next/previous year."""
if season > 4:
while season > 4:
if moved_year is None:
moved_year = now.year + 1
else:
moved_year += 1
season -= 5
elif ... | bigcode/self-oss-instruct-sc2-concepts |
def get_slope(vector_one, vector_two):
"""Get the slope of a line specified by two vectors"""
return(vector_two[1] - vector_one[1])/(vector_two[0] - vector_one[0]) | bigcode/self-oss-instruct-sc2-concepts |
import itertools
def find_anagrams(word, dictionary):
"""Find all anagrams for a word.
This function only runs as fast as the test for
membership in the 'dictionary' container. It will
be slow if the dictionary is a list and fast if
it's a set.
Args:
word: String of the target word.
... | bigcode/self-oss-instruct-sc2-concepts |
def count_on_screen(screen, wanted):
"""Count occurrences of wanted on the screen."""
return list(screen.values()).count(wanted) | bigcode/self-oss-instruct-sc2-concepts |
def googlenet_params(model_name):
""" Map VGGNet model name to parameter coefficients. """
params_dict = {
# Coefficients: aux_logits, transform_input, blocks, image_size
"googlenet": (True, True, None, 224),
}
return params_dict[model_name] | bigcode/self-oss-instruct-sc2-concepts |
import hashlib
def make_merkle(blob_name: str) -> str:
"""Creates a "merkle" by hashing the blob_name to get a unique value.
"""
m = hashlib.sha256()
m.update(blob_name.encode("utf-8"))
return m.hexdigest() | bigcode/self-oss-instruct-sc2-concepts |
def _get_query_parameters(module_params):
"""Builds query parameter.
:return: dict
:example: {"$filter": Name eq 'template name'}
"""
system_query_param = module_params.get("system_query_options")
query_param = {}
if system_query_param:
query_param = dict([("$" + k, v) for k, v in s... | bigcode/self-oss-instruct-sc2-concepts |
def pipes(stream, *transformers):
"""Pipe several transformers end to end."""
for transformer in transformers:
stream = stream.pipe(transformer)
return stream | 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.