seed
stringlengths
1
14k
source
stringclasses
2 values
def gf_neg(f, p, K): """Negate a polynomial in `GF(p)[x]`. """ return [ -coeff % p for coeff in f ]
bigcode/self-oss-instruct-sc2-concepts
import torch def tvr_loss(y): """Calculate Total Variation Regularization Loss of Generated Image""" loss = torch.sum(torch.abs(y[:, :, :, :-1] - y[:, :, :, 1:])) + torch.sum( torch.abs(y[:, :, :-1, :] - y[:, :, 1:, :]) ) return loss
bigcode/self-oss-instruct-sc2-concepts
def transform_to_factory_kwargs(data, original_kwargs=None, prefix=""): """ Transforms factory data into the correct kwargs to pass to the factory Args: data (dict): dictionary of data from the factory_data file original_kwargs (dict): kwargs passed into the factory function from code ...
bigcode/self-oss-instruct-sc2-concepts
def can_user_perform(user, account_id, action): """ Utility method for checking arbitrary actions are applicable to a specific account for a user. :param user: A dict object representing user :param account: A string representing an AWS account to validate permission for. :param action: A string rep...
bigcode/self-oss-instruct-sc2-concepts
def run_single_identify(run_identify): # pylint: disable=redefined-outer-name """ Fixture to run the identification step for a given sample file which should contain only one cluster, and return the result for that cluster. """ def inner(sample_name): res = run_identify(sample_name) ...
bigcode/self-oss-instruct-sc2-concepts
import re def parseNeighbors(urls): """Parses a urls pair string into urls pair.""" parts = re.split(r'\s+', urls) return parts[0], parts[1]
bigcode/self-oss-instruct-sc2-concepts
def join_lines(strings): """ Stack strings horizontally. This doesn't keep lines aligned unless the preceding lines have the same length. :param strings: Strings to stack :return: String consisting of the horizontally stacked input """ liness = [string.splitlines() for string in strings] ...
bigcode/self-oss-instruct-sc2-concepts
import re def wrap_line(line, breakable_regex, line_cont, base_indent=0, max_width=80, rewrap=False): """Wrap the given line within the given width. This function is going to be exported to be used by template writers in Jinja as a filter. Parameters ---------- line Th...
bigcode/self-oss-instruct-sc2-concepts
def makehist(vals, incr=1, normalize=0): """Makes a histogram for the given vals and returns a dict. Incr is how much each item counts for If normalize is true, then the sum of return values is normalize. """ ret = {} sum = 0 for v in vals: if v not in ret: ret[v] = 0 ...
bigcode/self-oss-instruct-sc2-concepts
def gravity(z, g0, r0): """Relates Earth gravity field magnitude with the geometric height. Parameters ---------- z: ~astropy.units.Quantity Geometric height. g0: ~astropy.units.Quantity Gravity value at sea level. r0: ~astropy.units.Quantity Planet/Natural satellite rad...
bigcode/self-oss-instruct-sc2-concepts
def first(lst): """Return the first element of the given list - otherwise return None""" return lst[0] if lst else None
bigcode/self-oss-instruct-sc2-concepts
from typing import Union import requests def validate_request_success(resp: Union[requests.Response, str]): """ Validate the response from the webhook request """ return not isinstance(resp, str) and resp.status_code in [200, 201]
bigcode/self-oss-instruct-sc2-concepts
from typing import List from typing import Optional import re def filter_list(arr: List[str], pattern: Optional[str] = None) -> List[str]: """Filter a list of strings with given pattern ```python >> arr = ['crossentropy', 'binarycrossentropy', 'softmax', 'mae',] >> filter_list(arr, ".*entropy*") >...
bigcode/self-oss-instruct-sc2-concepts
def prepend_zeros(length, string): """ Prepend zeros to the string until the desired length is reached :param length: the length that the string should have :param string: the string that we should appends 0's to :return: A string with zeros appended """ return "{}{}".format("0" * (length - ...
bigcode/self-oss-instruct-sc2-concepts
def plus_haut(points): """ Trouve le point (xb, yb) le plus en haut à droite, en temps linéaire.""" n = len(points) xb, yb = points[0] for j in range(1, n): xj, yj = points[j] if (yb < yj) or (yb == yj and xb < xj): xb, yb = xj, yj return xb, yb
bigcode/self-oss-instruct-sc2-concepts
import string def build_link_exp_decay(adj, weight, words_map, words, from_index, to_index, max_dist, stopwords, links_to_stopwords=True, self_links=False): """ Builds a link from a given word in the graph to another word at a defined index. The farther the other word, the smaller the edge between them. ...
bigcode/self-oss-instruct-sc2-concepts
def try_decode(obj: bytes, encoding="utf-8"): """ Try decode given bytes with encoding (default utf-8) :return: Decoded bytes to string if succeeded, else object itself """ try: rc = obj.decode(encoding=encoding) except AttributeError: rc = obj return rc.strip()
bigcode/self-oss-instruct-sc2-concepts
def apply_parent_validation(clazz, error_prefix=None): """ Decorator to automatically invoke parent class validation before applying custom validation rules. Usage:: class Child(Parent): @apply_parent_validation(Child, error_prefix="From Child: ") def validate(data): ...
bigcode/self-oss-instruct-sc2-concepts
def mean(mylist): """ function to take the mean of a list Parameters ---------- mylist : list list of numbers to take a mean Returns ------- mean_list : float The mean of the list. Examples -------- >>> mean([1,2,3,4,5,6,7]) 4.0 """ ...
bigcode/self-oss-instruct-sc2-concepts
from functools import reduce def reduce_get(cfg: dict, key: str): """ gets value from dictionary based on flat 'key' provided e.g. instead of dict1["alpha"]["beta"]["gamma"], we do: key = "alpha.beta.gamma" :param cfg: config dictionary :param key: flat key e.g. "alpha.beta.gamma" :return: val...
bigcode/self-oss-instruct-sc2-concepts
def traverse(node, order="pre-order", include_terminal=True, acc=None): """ Parameters ---------- node: NonTerminal or Terminal order: str, default "pre-order" include_terminal: bool, default True acc: list[T] or None, default None T -> NonTerminal or Terminal Returns ------...
bigcode/self-oss-instruct-sc2-concepts
def safe_open(path): """ If the file can be opened, returns a file handle; otherwise None.""" try: return open(path, 'rb') except (IOError, PermissionError, FileNotFoundError): return None
bigcode/self-oss-instruct-sc2-concepts
def getAllReachable1Step(original_nodes): """ return all node, value pairs reachable from any of the pairs in the original nodes in a single step :param original_nodes: a set of node, value, complete_path pairs from which we check what they can reach in 1 step :return: a set of node, value pairs that ca...
bigcode/self-oss-instruct-sc2-concepts
def select_zmws(zmws, min_requested_bases): """ >>> select_zmws([], 0) ([], 0) >>> select_zmws([], 10) ([], 0) >>> select_zmws([('zmw/1', 1), ('zmw/2', 2), ('zmw/3', 5), ('zmw/4', 7), ('zmw/5', 10), ('zmw/6', 15)], 10) (['zmw/1', 'zmw/2', 'zmw/3', 'zmw/4'], 15) >>> select_zmws([('zmw/1',...
bigcode/self-oss-instruct-sc2-concepts
def preprocess(sample): """Preprocess a single sample.""" return sample
bigcode/self-oss-instruct-sc2-concepts
def point_on_rectangle(rect, point, border=False): """ Return the point on which ``point`` can be projecten on the rectangle. ``border = True`` will make sure the point is bound to the border of the reactangle. Otherwise, if the point is in the rectangle, it's okay. >>> point_on_rectangle(Rect...
bigcode/self-oss-instruct-sc2-concepts
def for_teuthology(f): """ Decorator that adds an "is_for_teuthology" attribute to the wrapped function """ f.is_for_teuthology = True return f
bigcode/self-oss-instruct-sc2-concepts
import pickle def loadpfile(path: str) -> list: """ Loads whatever object is contained in the pickle file. Args: path: file path Returns: some object """ return pickle.load(open(path, 'rb'))
bigcode/self-oss-instruct-sc2-concepts
def single_number(nums): """ Given an array of integers, every element appears twice except for one. Find that single one. Note: Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory? Args: nums: list[int] Returns: int "...
bigcode/self-oss-instruct-sc2-concepts
def bin_search(query, data): """ Query is a coordinate interval. Binary search for the query in sorted data, which is a list of coordinates. Finishes when an overlapping value of query and data exists and returns the index in data. """ i = int(round(len(data)/2)) # binary search prep lower, upper = 0, len(data)...
bigcode/self-oss-instruct-sc2-concepts
def _nsec_to_usec_round(nsec: int) -> int: """Round nanoseconds to microseconds""" return (nsec + 500) // 10 ** 3
bigcode/self-oss-instruct-sc2-concepts
def _ord(i): """Converts a 1-char byte string to int. This function is used for python2 and python3 compatibility that can also handle an integer input. Args: i: The 1-char byte string to convert to an int. Returns: The byte string value as int or i if the input was already an ...
bigcode/self-oss-instruct-sc2-concepts
def _compute_temp_terminus(temp, temp_grad, ref_hgt, terminus_hgt, temp_anomaly=0): """Computes the (monthly) mean temperature at the glacier terminus, following section 2.1.2 of Marzeion et. al., 2012. The input temperature is scaled by the given temperature gradient and the elev...
bigcode/self-oss-instruct-sc2-concepts
def featuretype_filter(feature, featuretype): """ Only passes features with the specified *featuretype* """ if feature[2] == featuretype: return True return False
bigcode/self-oss-instruct-sc2-concepts
def as_latex(ordinal): """ Convert the Ordinal object to a LaTeX string. """ if isinstance(ordinal, int): return str(ordinal) term = r"\omega" if ordinal.exponent != 1: term += f"^{{{as_latex(ordinal.exponent)}}}" if ordinal.copies != 1: term += rf"\cdot{as_latex(ord...
bigcode/self-oss-instruct-sc2-concepts
import re def filter_comments(string): """Remove from `string` any Python-style comments ('#' to end of line).""" comment = re.compile(r'(^|[^\\])#.*') string = re.sub(comment, '', string) return string
bigcode/self-oss-instruct-sc2-concepts
def apply_ants_transform_to_point(transform, point): """ Apply transform to a point ANTsR function: `applyAntsrTransformToPoint` Arguments --------- point : list/tuple point to which the transform will be applied Returns ------- tuple : transformed point ...
bigcode/self-oss-instruct-sc2-concepts
import string def remove_punctuation(input_string): """Remove the punctuations in input string. Parameters ---------- input_string : string String to remove punctuations. Returns ------- output_string : string String without punctuations. """ out_st...
bigcode/self-oss-instruct-sc2-concepts
def MigrateUSBPDSpec(spec): """Migrate spec from old schema to newest schema. Args: spec: An object satisfies USB_PD_SPEC_SCHEMA. Returns: An object satisfies USB_PD_SPEC_SCHEMA_V3. """ if isinstance(spec, int): return { 'port': spec } if isinstance(spec, (list, tuple)): return...
bigcode/self-oss-instruct-sc2-concepts
def series_circuit_UA(*args): """ Calculates the total U*A-value for a series circuit of two or more U*A values. Parameters: ----------- UA : float, int, np.ndarray U*A value (heat conductivity) in [W/K] for each part of the series circuit. If given as np.ndarray, all arrays hav...
bigcode/self-oss-instruct-sc2-concepts
def mesh_dual(mesh, cls=None): """Construct the dual of a mesh. Parameters ---------- mesh : :class:`compas.datastructures.Mesh` A mesh object. cls : Type[:class:`compas.datastructures.Mesh`], optional The type of the dual mesh. Defaults to the type of the provided mesh obje...
bigcode/self-oss-instruct-sc2-concepts
import requests import json def site_catalog(site): """ Returns a dictionary of CWMS data paths for a particular site Arguments: site -- cwms site name, example TDDO Returns: json.loads(r.text) -- dictionary of available site data """ url = r'http:...
bigcode/self-oss-instruct-sc2-concepts
def split_node_lists(num_jobs, total_node_list=None, ppn=24): """ Parse node list and processor list from nodefile contents Args: num_jobs (int): number of sub jobs total_node_list (list of str): the node list of the whole large job ppn (int): number of procesors per node Retur...
bigcode/self-oss-instruct-sc2-concepts
def undo_keypoint_normalisation(normalised_keypoints, img_wh): """ Converts normalised keypoints from [-1, 1] space to pixel space i.e. [0, img_wh] """ keypoints = (normalised_keypoints + 1) * (img_wh/2.0) return keypoints
bigcode/self-oss-instruct-sc2-concepts
def output_aws_credentials(awscreds, awsaccount): """ Format the credentials as a string containing the commands to define the ENV variables """ aws_access_key_id = awscreds["data"]["access_key"] aws_secret_access_key = awscreds["data"]["secret_key"] shellenv_access = "export AWS_ACCESS_KEY_ID=%...
bigcode/self-oss-instruct-sc2-concepts
def get_phase_refr_index(wlen): """Get the phase refractive index for ice as a function of wavelength. See: https://wiki.icecube.wisc.edu/index.php/Refractive_index_of_ice#Numerical_values_for_ice or eqn 3 in https://arxiv.org/abs/hep-ex/0008001v1 Parameters ---------- wlen Wavelength ...
bigcode/self-oss-instruct-sc2-concepts
from pathlib import Path def get_github_api_token(tok): """ Fetch github personal access token (PAT) for gist api request using POST Parameters ---------- tok : str PAT if passed as string, else None and will be fetched """ if not tok: tok_path = Path.home() / ".jupyter_to_...
bigcode/self-oss-instruct-sc2-concepts
def squeeze_axes(shape, axes, skip='XY'): """Return shape and axes with single-dimensional entries removed. Remove unused dimensions unless their axes are listed in 'skip'. >>> squeeze_axes((5, 1, 2, 1, 1), 'TZYXC') ((5, 2, 1), 'TYX') """ if len(shape) != len(axes): raise ValueError("...
bigcode/self-oss-instruct-sc2-concepts
def read_padding(fp, size, divisor=2): """ Read padding bytes for the given byte size. :param fp: file-like object :param divisor: divisor of the byte alignment :return: read byte size """ remainder = size % divisor if remainder: return fp.read(divisor - remainder) return b'...
bigcode/self-oss-instruct-sc2-concepts
def extractDetails(remoteException): """Extract the details of an xml-rpc exception error message""" try: details = remoteException.faultString or remoteException.message details = details.split(":", 2)[-1].replace("'>", "").lstrip() except AttributeError: details = str(remoteExcepti...
bigcode/self-oss-instruct-sc2-concepts
def fileopen(fun): """ Open read-only filehandle if first argument is string This function can be used to decorate functions that expect a filehandle as the first argument. If the first argument is a string, it is assumed to be the path to the input file, and the file is opened in read mode. Args:...
bigcode/self-oss-instruct-sc2-concepts
def preprocess_baseline2(segment_df, rush_hour): """ Preprocess the segment data considering the weather and the rush hour Algorithm: Preprocess segment_df to add a new column of rush hour split the dataframe with groupby(segment_start, segment_end, weather, rush_hour) Define the new dataframe ...
bigcode/self-oss-instruct-sc2-concepts
def str_remove(string, index, end_index=None): """Remove a substring from an existing string at a certain from-to index range.""" end_index = end_index or (index + 1) return "%s%s" % (string[:index], string[end_index:])
bigcode/self-oss-instruct-sc2-concepts
def m_coef(h_septum): """ Calculates the specific coefficient for calculation the heigth ligth layer of liquid equation. Parameters ---------- h_septum : float The heigth of drain septum, [m] Returns ------- m_coef : float The specific coefficient for this equation [dimen...
bigcode/self-oss-instruct-sc2-concepts
def get(conn, uri, access_token=None): """ HTTP GET request with an optional authorization header with the access_token """ if access_token: headers = {'authorization': '%s %s' % (access_token['token_type'], access_token['access_token'])} else: headers = {} conn.request('GET', ur...
bigcode/self-oss-instruct-sc2-concepts
def all_true(iterable): """ Helper that returns true if the iterable is not empty and all its elements evaluate to true. """ items = list(iterable) return all(items) if items else False
bigcode/self-oss-instruct-sc2-concepts
import unicodedata import string import re def preprocess_names(name, output_sep=' ', firstname_output_letters=1): """ Function that outputs a person's name in the format <last_name><separator><firstname letter(s)> (all lowercase) >>> preprocess_names("Samuel Eto'o") 'etoo s' >>> pre...
bigcode/self-oss-instruct-sc2-concepts
def get_domain_from_fqdn(fqdn): """ Returns domain name from a fully-qualified domain name (removes left-most period-delimited value) """ if "." in fqdn: split = fqdn.split(".") del split[0] return ".".join(split) else: return None
bigcode/self-oss-instruct-sc2-concepts
def GetPartitionsByType(partitions, typename): """Given a partition table and type returns the partitions of the type. Partitions are sorted in num order. Args: partitions: List of partitions to search in typename: The type of partitions to select Returns: A list of partitions of the type """ ...
bigcode/self-oss-instruct-sc2-concepts
def is_admin(user): """ :param user: :return True, (str): if user is admin :return False, (str): is user is not admin """ if 'isAdmin' in user and user['isAdmin'] is True: return True, None return False, 'user is not authorized'
bigcode/self-oss-instruct-sc2-concepts
from typing import List from typing import Any import collections def _create_ngrams(tokens: List[Any], n: int) -> collections.Counter: """Creates ngrams from the given list of tokens. Args: tokens: A list of tokens from which ngrams are created. n: Number of tokens to use, e.g. 2 for bigrams. Returns...
bigcode/self-oss-instruct-sc2-concepts
def split_group(name): """Split item name containing ``'/'`` into tuple of group/subname. Examples: - an input of ``'foo/bar'`` results in ``('foo', 'bar')`` - an input of ``'foo/bar/baz'`` results in ``('foo/bar', 'baz')`` """ return tuple(reversed([x[::-1] for x in name[::-1].split("/", 1)]...
bigcode/self-oss-instruct-sc2-concepts
import asyncio async def preprocessor(input_data: str): """Simple feature processing that converts str to int""" await asyncio.sleep(0.1) # Manual delay for blocking computation return int(input_data)
bigcode/self-oss-instruct-sc2-concepts
def _power_of_two(value): """Returns whether the given value is a power of two.""" return (value & (value - 1)) == 0
bigcode/self-oss-instruct-sc2-concepts
def snake_to_camel(s: str) -> str: """Convert string from snake case to camel case.""" fragments = s.split('_') return fragments[0] + ''.join(x.title() for x in fragments[1:])
bigcode/self-oss-instruct-sc2-concepts
def _get_norm_procedure(norm, parameter): """ Returns methods description of the provided `norm` Parameters ---------- norm : str Normalization procedure Returns ------- procedure : str Reporting procedures """ if parameter not in ('sample_norm', 'gene_norm'): ...
bigcode/self-oss-instruct-sc2-concepts
from typing import Dict from typing import Union from typing import List import json import base64 def extract_syft_metadata(data: str) -> Dict[str, Union[str, List[str], bytes]]: """ Parse metadata from the syft output string :param data: syft SBOM json string :type data: str :return: dict with ...
bigcode/self-oss-instruct-sc2-concepts
def getMObjectByMDagPath(dagPath): """ Retrieves an MObject from the given MDagPath. :type dagPath: om.MDagPath :rtype: om.MObject """ return dagPath.node()
bigcode/self-oss-instruct-sc2-concepts
from typing import List from typing import Tuple def split_series( series: List, *, reserved_ratio: float = 0.2, test_ratio: float = 0.5, ) -> Tuple[List, List, List]: """ Split a series into 3 parts - training, validation and test. Parameters ---------- series a time seri...
bigcode/self-oss-instruct-sc2-concepts
import datetime def group_datetime(d, interval): """Group datetime in bins.""" seconds = d.second + d.hour * 3600 + d.minute * 60 + d.microsecond / 1000 k = d - datetime.timedelta(seconds=seconds % interval) return datetime.datetime(k.year, k.month, k.day, k.hour, k.minute, k.second)
bigcode/self-oss-instruct-sc2-concepts
import re def regex_match(pattern): """A curried regex match. Gets a pattern and returns a function that expects a text to match the pattern with. >>> regex_match(r"phone:(\d*)")("phone:1234567").group(1) # noqa: W605 '1234567' """ def regex_match_inner(text): return re.match(pattern, ...
bigcode/self-oss-instruct-sc2-concepts
def public(fun, scope=None, cookie=False): """ Functions that allow any client access, including those that haven't logged in should be wrapped in this decorator. :param fun: A REST endpoint. :type fun: callable :param scope: The scope or list of scopes required for this token. :type scope:...
bigcode/self-oss-instruct-sc2-concepts
def flip_second_half_direction(team): """ Flip coordinates in second half so that each team always shoots in the same direction through the match. """ second_half_idx = team.Period.idxmax(2) columns = [c for c in team.columns if c[-1].lower() in ["x", "y"]] team.loc[second_half_idx:, columns] *=...
bigcode/self-oss-instruct-sc2-concepts
import math def fuel_counter(masses): """Function that computes the fuel needed for the input masses. Expected input is required to either be a list/tuple or scalar""" if isinstance(masses, (tuple, list)): return sum(fuel_counter(mass) for mass in masses) return max(int(math.floor(masses / 3) ...
bigcode/self-oss-instruct-sc2-concepts
def shutdown_cost_rule(mod, prj, tmp): """ If no shutdown_cost_rule is specified in an operational type module, the default shutdown fuel cost is 0. """ return 0
bigcode/self-oss-instruct-sc2-concepts
def list_medias(api, lang, **params): # type (ApiClient, str, dict) -> (Iterable[dict]) """List all the medias. Args: api (object): The ApiClient instance used for request. lang (str): the lang. Defaults to english (en). ``**params``: optional dictionary of search p...
bigcode/self-oss-instruct-sc2-concepts
def pseudo_residual_regression(target, output): """Compute the pseudo residual for regression with least square error.""" if target.size() != output.size(): msg = "The shape of target {} should be the same as output {}." raise ValueError(msg.format(target.size(), output.size())) return targ...
bigcode/self-oss-instruct-sc2-concepts
def plural(text, num): """Pluralizer: adds "s" at the end of a string if a given number is > 1 """ return "%s%s" % (text, "s"[num == 1:])
bigcode/self-oss-instruct-sc2-concepts
def get_time_signature(h5,songidx=0): """ Get signature from a HDF5 song file, by default the first song in it """ return h5.root.analysis.songs.cols.time_signature[songidx]
bigcode/self-oss-instruct-sc2-concepts
def hamming_distance(a, b): """ Counts number of nonequal matched elements in two iterables """ return sum([int(i != j) for i, j in zip(a, b)])
bigcode/self-oss-instruct-sc2-concepts
import torch def EER(positive_scores, negative_scores): """Computes the EER (and its threshold). Arguments --------- positive_scores : torch.tensor The scores from entries of the same class. negative_scores : torch.tensor The scores from entries of different classes. Example ...
bigcode/self-oss-instruct-sc2-concepts
def get_tensor_shape(x): """ Get the shape of tensor Parameters ---------- x : tensor type float16, float32, float64, int32, complex64, complex128. Returns ------- list. Examples --------- >>> import tensorlayerx as tlx >>> x_in = tlx.layers.Input((32, 3, ...
bigcode/self-oss-instruct-sc2-concepts
import typing def validate_list(expected, lst: list) -> typing.Union[str, bool]: """ Validate a list against our expected schema. Returns False if the list is valid. Returns error in string format if invalid. """ if not isinstance(lst, list): return "Expected argument of type `%s`, g...
bigcode/self-oss-instruct-sc2-concepts
from typing import Any def get_nested(the_dict: dict, nested_key: str, default: Any = None) -> Any: """ Returns the value of a nested key in an dictorinary Args: the_dict (dict): The dictionary to get the nested value from nested_key (str): The nested key default: The value to be ...
bigcode/self-oss-instruct-sc2-concepts
import re def percent_decode(data): """ Percent decode a string of data. """ if data is None: return None percent_code = re.compile("(%[0-9A-Fa-f]{2})") try: bits = percent_code.split(data) except TypeError: bits = percent_code.split(str(data)) out = bytearray() ...
bigcode/self-oss-instruct-sc2-concepts
def always_do(action): """Returns a policy that always takes the given action.""" def policy(state, rng): return action return policy
bigcode/self-oss-instruct-sc2-concepts
from typing import Sequence def read_containers(text: str) -> Sequence[int]: """ Read the puzzle input into a list of integers representing the container sizes. """ return [int(line) for line in text.split("\n")]
bigcode/self-oss-instruct-sc2-concepts
import random import string def get_job_id(length=8): """Create random job id.""" return "".join(random.choice(string.hexdigits) for x in range(length))
bigcode/self-oss-instruct-sc2-concepts
import math def circle_area(diameter): """Returns the area of a circle with a diameter of diameter.""" return 1/4*math.pi*(diameter**2)
bigcode/self-oss-instruct-sc2-concepts
import warnings def create_gobnilp_settings(score_type, palim=None, alpha=None): """ Creates a string of Gobnilp settings given the allowed arities and parent size. Parameters ---------- score_type : int The scoring function used to learn the network 0 for BDeu or 2 for BIC pa...
bigcode/self-oss-instruct-sc2-concepts
def binary_search(array, item): """function to search for the value in a list Args: array(list): a sorted list of values item: the value to be searched for in the array Returns: the position of the item from the list or a not found """ low = 0 high = len(array) - 1 """whenever a search is ...
bigcode/self-oss-instruct-sc2-concepts
def _axes_to_sum(child, parent): """Find the indexes of axes that should be summed in `child` to get `parent`""" return tuple(child.index(i) for i in child if i not in parent)
bigcode/self-oss-instruct-sc2-concepts
def minimax(val, low, high): """ Return value forced within range """ try: val = int(val) except: val = 0 if val < low: return low if val > high: return high return val
bigcode/self-oss-instruct-sc2-concepts
from typing import Tuple import configparser def read_login() -> Tuple[str, str]: """ read login from file :return: mail & password """ config = configparser.ConfigParser() config.read("login.ini") mail = config.get("LOGIN", "email") password = config.get("LOGIN", "password") r...
bigcode/self-oss-instruct-sc2-concepts
def rom_to_hex(rom): """Convert rom bytearray to hex string.""" return ''.join('{:02x}'.format(x) for x in rom)
bigcode/self-oss-instruct-sc2-concepts
def remove_nipsa_action(index, annotation): """Return an Elasticsearch action to remove NIPSA from the annotation.""" source = annotation["_source"].copy() source.pop("nipsa", None) return { "_op_type": "index", "_index": index, "_type": "annotation", "_id": annotation["_...
bigcode/self-oss-instruct-sc2-concepts
def read_queries(file, interactive=False): """ Return list of reference and generated queries """ query_list = [] with open(file, 'r') as src: for line in src.readlines(): if interactive is True: reference, gen = line.strip('\n').split(",") else: ...
bigcode/self-oss-instruct-sc2-concepts
def _insert_char_at_pos(text, pos, ch): """ Inserts a character at the given position in string. """ return text[:pos] + ch + text[pos:]
bigcode/self-oss-instruct-sc2-concepts
def mk_lst(values, unlst=False): """ while iterating through several type of lists and items it is convenient to assume that we recieve a list, use this function to accomplish this. It also convenient to be able to return the original type after were done with it. """ # Not a list, were not ...
bigcode/self-oss-instruct-sc2-concepts
def image_shape(images): """Check if all image in `images` have same shape and return that shape.""" shape = None for image in images: if not shape: shape = image.shape else: if shape != image.shape: raise ValueError return shape
bigcode/self-oss-instruct-sc2-concepts