seed
stringlengths
1
14k
source
stringclasses
2 values
def find_python_in_context(context): """Find Python executable within the given context. Args: context (ResolvedContext): Resolved context with Python and pip. name (str): Name of the package for Python instead of "python". default (str): Force a particular fallback path for Python exec...
bigcode/self-oss-instruct-sc2-concepts
import click def email_option(help_message, long="--email", short="-e", name="email", required=True): """ Email option standard definition. Use as decorator for commands. """ return click.option( long, short, name, required=required, type=str, help=...
bigcode/self-oss-instruct-sc2-concepts
def shellescapespace(s): """Escape spaces for shell.""" return s.replace(" ", "\\ ")
bigcode/self-oss-instruct-sc2-concepts
def find_level_sections(alts): """ Find pairs of start/finish indicies of consecutive altitudes with the same value. I.e. where an aircraft was in level flight. Parameters ---------- alts: float array An array of altitudes[feet] Returns ------- level_indicies: a list of ind...
bigcode/self-oss-instruct-sc2-concepts
def clean_text(text): """ Remove most punctuation from string and make it lowercase :param text: String :return: String with cleaned up text """ text = text.lower() text = text.replace("!", " ") text = text.replace("?", " ") text = text.replace(";", " ") text = text.replace('"', ...
bigcode/self-oss-instruct-sc2-concepts
def read_hex(field: str) -> int: """Read a hexadecimal integer.""" return int(field, 16) if field != "" else 0
bigcode/self-oss-instruct-sc2-concepts
def bwtc_scaling_factor(order): """Return the appropriate scaling factor for bandwidth to timeconstant converstion for the provided demodulator order. """ scale = 0.0 if order == 1: scale = 1.0 elif order == 2: scale = 0.643594 elif order == 3: scale = 0.509825 e...
bigcode/self-oss-instruct-sc2-concepts
from typing import Any def get_category(parameter_meta: Any, input_name: str, category_key: str = "category", fallback_category: str = "other") -> str: """ :param parameter_meta: A dictionary containing the parameter_meta information. :param input_name: The name of th...
bigcode/self-oss-instruct-sc2-concepts
def remove_start(s: str, start: str): """ Helper function to remove the beginning of a string. :param s: the string to remove the prefix from. :param start: the prefix of the string to remove. :return: s with the start of the string removed. """ assert s.startswith(start) return s[len(st...
bigcode/self-oss-instruct-sc2-concepts
def projects_q(project): """Return the gerrit query selecting all the project in the given list :param project: List of gerrit project name. :type project: list of str :return: gerrit query according to `Searching Changes`_ section of gerrit documentation. :rtype: str .. _Searc...
bigcode/self-oss-instruct-sc2-concepts
def square_to_condensed(i: int, j: int, n: int): """Convert a square matrix position (i, j) to a condensed distance matrix index. Args: i: Index i. j: Index j. n: The dimension of the matrix. See Also: https://stackoverflow.com/questions/13079563/how-does-condensed-distance...
bigcode/self-oss-instruct-sc2-concepts
import textwrap def sample_project_path(tmp_path): """Create a sample project to be cleaned.""" source = """ import pytask @pytask.mark.depends_on("in.txt") @pytask.mark.produces("out.txt") def task_dummy(produces): produces.write_text("a") """ tmp_path.joinpath("task_dummy.py...
bigcode/self-oss-instruct-sc2-concepts
def str_to_bool(val): """ Convert a string representation of truth to True or False True values are 'y', 'yes', or ''; case-insensitive False values are 'n', or 'no'; case-insensitive Raises ValueError if 'val' is anything else. """ true_vals = ['yes', 'y', ''] false_vals = ['no', 'n'] ...
bigcode/self-oss-instruct-sc2-concepts
def transform(subject: int, loop_size: int) -> int: """Transform the ``subject`` in ``loop_size`` steps of a hard-coded algorithm.""" value = 1 for _ in range(loop_size): value *= subject value %= 20201227 return value
bigcode/self-oss-instruct-sc2-concepts
def solidsFluxPembWake(rhop, emf, umf, us): """ Calculates the solids entrainment flux for the surface of a bubbling bed with the bubble wake ejection model of Pemberton and Davidsion (Chem. Eng. Sci., 1986, 41, pp. 243-251). This model is suitable if multiple bubbles coalesce at the surface before ...
bigcode/self-oss-instruct-sc2-concepts
from pathlib import Path def get_test_script() -> Path: """ Returns the full path to a testing script that lives inside of the test suite. :return: """ current = Path(__file__).parent script = current / "script_for_tests.py" assert script.is_file(), f"File {script} not found" return sc...
bigcode/self-oss-instruct-sc2-concepts
import torch def axis_angle_into_quaternion(normalized_axis, angle, device=torch.device("cpu"), dtype=torch.float32): """ Takes an axis-angle rotation and converts into quaternion rotation. https://en.wikipedia.org/wiki/Conversion_between_quaternions_and_Euler_angles :param normalized_axis: Axis of rotation ...
bigcode/self-oss-instruct-sc2-concepts
def for_entities_in(container): """ Receives messages sent to a target inside the specified container. :param container: A container whose entities' messages will be received. """ def filter(target): if target.container == container: return True if target == container: re...
bigcode/self-oss-instruct-sc2-concepts
def execution_time(result): """Return the execution time of a query.""" avail = result.summary().result_available_after cons = result.summary().result_consumed_after return avail + cons
bigcode/self-oss-instruct-sc2-concepts
def determinant(matrix): """ Calculates the determinant of a matrix. matrix is a list of lists whose determinant should be calculated If matrix is not a list of lists, raise a TypeError with the message matrix must be a list of lists If matrix is not square, raise a ValueError with the message ...
bigcode/self-oss-instruct-sc2-concepts
def do_files_to_copy_contain_entry_with_src(files_to_copy, src): """Searches the files to be copied for an entry with src field that matches the given src.""" is_present = False for file_to_copy in files_to_copy: if file_to_copy.src == src: is_present = True break return ...
bigcode/self-oss-instruct-sc2-concepts
from typing import Dict from typing import Tuple def parse_header_and_separator( header: str, separator: str ) -> Dict[str, Tuple[int, int]]: """Parse header and separator and return {field: (start, end)}""" headers = header.split() separators = separator.split() field_to_start_end = {} # type: D...
bigcode/self-oss-instruct-sc2-concepts
import hashlib def get_hash(string, length=8): """ Shortcut for generating short hash strings """ return hashlib.sha1(string.encode("utf-8")).hexdigest()[:length]
bigcode/self-oss-instruct-sc2-concepts
def get_filenames_in_release(manifestdict): """ <Purpose> Get the list of files in a manifest <Arguments> manifestdict: the manifest for the release <Exceptions> TypeError, IndexError, or KeyError if the manifestdict is corrupt <Side Effects> None <Returns> A list of file names """ filenamelist =...
bigcode/self-oss-instruct-sc2-concepts
import re def parse_function_definition(deftxt: str) -> tuple[str, str]: """Parse a function definition""" # Connect multiple lines if so deftxt = re.sub(r'\n\s*', ' ', deftxt, flags=re.M) # Split the definition line to the function name and the variables definition function_name, variables, _ ...
bigcode/self-oss-instruct-sc2-concepts
def _mirrorpod_filter(pod): """Check if a pod contains the mirror K8s annotation. Args: - pod: kubernetes pod object Returns: (False, "") if the pod has the mirror annotation, (True, "") if not """ mirror_annotation = "kubernetes.io/config.mirror" annotations = pod["metadata...
bigcode/self-oss-instruct-sc2-concepts
def _find_clusters(mst_graph, vertices): """Find the cluster class for each vertex of the MST graph. It uses the DFS-like algorithm to find clusters. Args: mst_graph (dict): A non-empty graph representing the MST. vertices (list): A list of unique vertices. Returns: A l...
bigcode/self-oss-instruct-sc2-concepts
def atoi(v): """Convert v to an integer, or return 0 on error, like C's atoi().""" try: return int(v or 0) except ValueError: return 0
bigcode/self-oss-instruct-sc2-concepts
def get_control_latex(model): """ Get the labels for each Hamiltonian. It is used in the method method :meth:`.Processor.plot_pulses`. It is a 2-d nested list, in the plot, a different color will be used for each sublist. """ num_qubits = model.num_qubits num_coupling = model._get_num_co...
bigcode/self-oss-instruct-sc2-concepts
def lr_poly(base_lr, curr_iter, max_iter, warmup_iter=0, power=0.9): """Polynomial-decay learning rate policy. Args: base_lr: A scalar indicates initial learning rate. curr_iter: A scalar indicates current iteration. max_iter: A scalar indicates maximum iteration. warmup_iter: A scalar indicates th...
bigcode/self-oss-instruct-sc2-concepts
def periodic(t, T): """ Returns equivalent time of the first period if more than one period is simulated. :param t: Time. :param T: Period length. """ while t/T > 1.0: t = t - T return t
bigcode/self-oss-instruct-sc2-concepts
from typing import Mapping def has_node(g: Mapping, node, check_adjacencies=True): """Returns True if the graph has given node >>> g = { ... 0: [1, 2], ... 1: [2] ... } >>> has_node(g, 0) True >>> has_node(g, 2) True Note that 2 was found, though it's not a key of ``g...
bigcode/self-oss-instruct-sc2-concepts
from typing import Optional def next_batch(limit: int, offset: int, total: Optional[int]) -> bool: """Is there a next batch of resources?""" if total is None: return True return (total - offset) > 0
bigcode/self-oss-instruct-sc2-concepts
def score(word_list, lm): """ Use LM to calculate a log10-based probability for a given sentence (as a list of words) :param word_list: :return: """ return lm.score(' '.join(word_list), bos=False, eos=False)
bigcode/self-oss-instruct-sc2-concepts
def same_type_and_id(first, second): """Same type and ID""" return type(first) is type(second) and first.id == second.id
bigcode/self-oss-instruct-sc2-concepts
def process_datasets(datasets): """Return a list of datasets provided as a string in GUI input or None if default 'All' is provided. Args: datasets (str): a string with coma-separated datasets names Example: >>> process_datasets("Data1,Data2") ['Data1', 'Data2'] """ ...
bigcode/self-oss-instruct-sc2-concepts
import math def solar_declination(doy): """ Calculate the solar declination for a given day of the year (Allen et al. 1998). Parameters ---------- doy : int Julian day of the year (-). Returns ------- float Solar declination (rad). """ return 0.409 * math...
bigcode/self-oss-instruct-sc2-concepts
def degTohms(ideg): """ Converts degrees to hours:minutes:seconds :param ideg: objects coordinates in degrees :type ideg: float :return: hours:minutes:seconds :rtype: string """ ihours = ideg / 15. hours = int(ihours) + 0. m = 60. * (ihours - hours) minutes = int(m) + 0. ...
bigcode/self-oss-instruct-sc2-concepts
def is_english_word_alpha(word: str) -> bool: """Returns True when `word` is an English word. False otherwise. Args: word: Any given word Examples: >>> is_english_word_alpha("English") True >>> is_english_word_alpha("영원한") False >>> is_english_word_alpha("do...
bigcode/self-oss-instruct-sc2-concepts
from typing import Optional from typing import Sequence import torch def uniform_superposition( num_qubits: int, batch_dims: Optional[Sequence] = None, device: torch.device = torch.device("cpu"), dtype: torch.dtype = torch.complex64, requires_grad: bool = False ): """Create...
bigcode/self-oss-instruct-sc2-concepts
def anyInArray(array, elements): """ 要尋找的任一元素,存在於 array 當中即返回 True,否則返回 False :param array: 被搜尋的陣列 :param elements: 要尋找的元素們 :return: """ for element in elements: if element in array: return True return False
bigcode/self-oss-instruct-sc2-concepts
from pathlib import Path import mimetypes def content_type(path: Path) -> str: """ Guess the content type of *path* from its name. If the type is not guessable, returns the generic type ``application/octet-stream``. """ type, encoding = mimetypes.guess_type(path.name) return type or "appl...
bigcode/self-oss-instruct-sc2-concepts
def sum_digits(n : int) -> int: """ Given a non-negative integer n, return the sum of its digits. Parameters ---------- n : int number to return the sum of Returns ------- int sum of numbers digits """ if n == 0: return 0 x = sum_digits(n // 10) + (...
bigcode/self-oss-instruct-sc2-concepts
from pathlib import Path import shutil def images_path(tmp_path_factory, some_image, n_images: int = 3) -> Path: """ Return a temporary directory that has been prepared with some image files: - img_0.jpg - img_1.jpg - img_2.jpg - ... """ tmp_img_path = tmp_path_factory.mktemp('imgs_dir...
bigcode/self-oss-instruct-sc2-concepts
def from_pcl(infile, outfile): """Convert a pcl file to biom format using the biom package :param infile: String; name of the input tsv or pcl file :param outfile: String; name of the resulting converted biom file External dependencies - biom-format: http://biom-format.org/ """ cmd="bi...
bigcode/self-oss-instruct-sc2-concepts
def parse_vespa_json(data): """ Parse Vespa results to get necessary information. :param data: Vespa results in JSON format. :return: List with retrieved documents """ ranking = [] if "children" in data["root"]: ranking = [hit["fields"]["id"] for hit in data["root"]["children"] if "...
bigcode/self-oss-instruct-sc2-concepts
import random def coding_problem_15(sample_generator): """ Given a stream of elements too large to store in memory, pick a random element from the stream with uniform probability. Example: >>> import random >>> random.seed(0xBADC0FFE) >>> >>> def sample_gen_fun(n): ... for x i...
bigcode/self-oss-instruct-sc2-concepts
def get_algo(mining_pool): """ Retrieves algo when passed mining pool URL. Very often the algo and coin are actually in the POOL URL. Returns: String """ # returns the algorithm string algo = None if mining_pool is not None: x = mining_pool.count('.') if x >=...
bigcode/self-oss-instruct-sc2-concepts
import torch def list2vec(z1_list): """Convert list of tensors to a vector""" bsz = z1_list[0].size(0) return torch.cat([elem.reshape(bsz, -1, 1) for elem in z1_list], dim=1)
bigcode/self-oss-instruct-sc2-concepts
def get_shapes(n_features, n_responses): """ Gets the shapes of the coefficeint and intercept. Parameters ---------- n_features: int Number of features. n_responses: int Number of responses Output ------ coef_shape, intercept_shape coef_shape: tuple Sh...
bigcode/self-oss-instruct-sc2-concepts
def dlr_list(client_session): """ This function returns all DLR found in NSX :param client_session: An instance of an NsxClient Session :return: returns a tuple, the first item is a list of tuples with item 0 containing the DLR Name as string and item 1 containing the dlr id as string. The ...
bigcode/self-oss-instruct-sc2-concepts
def score(word: str): """Calculate a simple "score" for a word for the sake of sorting candidate guesses. For this agent, the score is just the number of distinct letters in the word. For example, "taste" has a score of 4 while "tears" has a score of 5.""" return len(set(word))
bigcode/self-oss-instruct-sc2-concepts
from typing import Dict from typing import Any def prepare_dict_to_print(dict: Dict[str, Any]) -> str: """Helper function to create pretty string to print dictionary. Args: dict (Dict[str, Any]): Arbitrary dictionary. Returns: str: Pretty string to print dictionary. """ sorted_i...
bigcode/self-oss-instruct-sc2-concepts
def _get_geonames_country_url(land): """ returns geonames country url """ geonames_countries = { 'ad': 'https://www.geonames.org/3041565', 'al': 'https://www.geonames.org/783754', 'am': 'https://www.geonames.org/174982', 'at': 'https://www.geonames.org/2782113', '...
bigcode/self-oss-instruct-sc2-concepts
def zot_collections(zot): """ Extracts collections from Zotero API """ collections = zot.collections() return collections
bigcode/self-oss-instruct-sc2-concepts
def normalize(value, min_value, max_value, new_min, new_max): """Normalize a value between new Min and new Max Args: value (string): The actual value min_value (string): The min range max_value (string): The max range new_min (string): The new min range new_max (string):...
bigcode/self-oss-instruct-sc2-concepts
def PNT2TidalOcto_Pv14(XA,beta0PNT=0): """ TaylorT2 0PN Octopolar Tidal Coefficient, v^14 Phasing Term. XA = mass fraction of object beta0PNT = 0PN Octopole Tidal Flux coefficient """ return (5)/(9)*(520+beta0PNT)-(2600*XA)/(9)
bigcode/self-oss-instruct-sc2-concepts
import torch def grad_fun(x_est,y): """ Defines the gradient function for a denoising problem with White Noise. This function demonstrates the use of Pytorch's autograd to calculate the gradient. In this example, the function is equivalent to def grad_fun(x_est,y): return x_est - y ...
bigcode/self-oss-instruct-sc2-concepts
def get_trade_value(x, sum_use, sector, own_production_ratio=0.8): """Function to get the trade value between a certain origin and destination. Parameters - x - row in Origin-Destination dataframe - sum_use - total use in a certain destination - own_production_ratio - Specify how much s...
bigcode/self-oss-instruct-sc2-concepts
from math import sqrt def stats( ls ) : """ Calculate the mean and variance in a list. Returns mean, variance """ if len(ls) <= 0 : return [0.0, 0.0] avg = 1.0 * sum(ls) / len(ls) if len(ls) == 1 : return [avg, 0.0] s = sqrt(1.0*sum( [ (x - avg)**2 for x in ls ]...
bigcode/self-oss-instruct-sc2-concepts
import itertools def variable_product(variables): """Take the Cartesian product of a number of Variables. Args: variables: A sequence of Variables. Returns: A list of lists of Values, where each sublist has one element from each of the given Variables. """ return itertools.product(*(v.values f...
bigcode/self-oss-instruct-sc2-concepts
def name_from_req(req): """Get the name of the requirement""" if hasattr(req, "project_name"): # from pkg_resources, such as installed dists for pip-sync return req.project_name else: # from packaging, such as install requirements from requirements.txt return req.name
bigcode/self-oss-instruct-sc2-concepts
def solution(a: int, b: int, k: int) -> int: """ :return: The number of integers within the range [a..b] that are divisible by k. >>> solution(6, 11, 2) 3 >>> solution(3, 14, 7) 2 """ count = (b - a + 1) // k if b % k == 0: count += 1 return count
bigcode/self-oss-instruct-sc2-concepts
def stations_by_river(stations): """Given list of MonitoringStation objects; returns dictionary mapping river names to a list of MonitoringStation objects, which lie on that river.""" output = {} for station in stations: if station.river not in output: output[station.river] = [stati...
bigcode/self-oss-instruct-sc2-concepts
def get_order(lm): """Return the order of a given SRILM LM.""" order = 0 for line in open(lm): if line.startswith("ngram "): try: n = int(line[len("ngram "):].split('=')[0]) except: n = 0 if n > order: order = n if order and line.startswith("\\"): break retur...
bigcode/self-oss-instruct-sc2-concepts
import warnings def _get_join_params(func_kwargs): """Extract and return any join parameters.""" # remove and save the join kw, if specified (so it doesn't interfere # with other operations and doesn't get sent to the function) join_type = func_kwargs.pop("join", None) if not join_type: re...
bigcode/self-oss-instruct-sc2-concepts
def sel_time(ds, tslice, mean_time=True): """ Get a time slice `tslice` from xarray data object `ds`. If `mean_time` is True, result will be averaged over the time dimension after slicing """ ds_sliced = ds.sel({"time": tslice}) if mean_time is True: return ds_sliced.mean(dim="time") ...
bigcode/self-oss-instruct-sc2-concepts
def _unique_label(previous_labels,label): """Returns a unique name if label is already in previous_labels.""" while label in previous_labels: if label.split('.')[-1].startswith('copy'): label='.'.join(label.split('.')[:-1])+'.copy'+str(eval('0'+label.split('.')[-1][4:])+1) else: ...
bigcode/self-oss-instruct-sc2-concepts
from typing import List def split_mtext_string(s: str, size: int = 250) -> List[str]: """Split the MTEXT content string into chunks of max `size`.""" chunks = [] pos = 0 while True: chunk = s[pos : pos + size] if len(chunk): if len(chunk) < size: chunks.appe...
bigcode/self-oss-instruct-sc2-concepts
def ping(request, s=None): """ Test integration. Returns ------- str String 'pong' """ return 'pong'
bigcode/self-oss-instruct-sc2-concepts
from typing import List def _onemax(x: List[int]) -> float: """onemax(x) is the most classical case of discrete functions, adapted to minimization. It is originally designed for lists of bits. It just counts the number of 1, and returns len(x) - number of ones.. It also works in the continuous case ...
bigcode/self-oss-instruct-sc2-concepts
def read_plain_byte_array_fixed(file_obj, fixed_length): """Read a byte array of the given fixed_length.""" return file_obj.read(fixed_length)
bigcode/self-oss-instruct-sc2-concepts
from typing import Tuple def choices_from_enum(source: type) -> Tuple[Tuple[int, str], ...]: """ Makes tuple to use in Django's Fields ``choices`` attribute. Enum members names will be titles for the choices. :param source: Enum to process. :return: Tuple to put into ``choices`` """ resul...
bigcode/self-oss-instruct-sc2-concepts
def require_any(json, keys): """ Require that the given dict-from-json-object contains at least one of the given keys. """ for k in keys: if k in json: return True return False
bigcode/self-oss-instruct-sc2-concepts
def join_and(value): """ Given a list of strings, format them with commas and spaces, but with 'and' at the end. >>> join_and(['apples', 'oranges', 'pears']) "apples, oranges, and pears" """ # convert numbers to strings value = [str(item) for item in value] if len(value) == 0: ...
bigcode/self-oss-instruct-sc2-concepts
def format_colname(name): """ Convert the column name to a better formatted name """ cmcol = " [cm$^{-2}$]" mag = " [mag]" col_mag = " [cm$^{-2}$ mag$^{-1}$]" dic_pairs = { "AV": "$A(V)$" + mag, "RV": "$R(V)$", "EBV": "$E(B-V)$" + mag, "CAV1": "$C^{A(V)}_1$",...
bigcode/self-oss-instruct-sc2-concepts
from typing import Union def is_integer(n: Union[int, str, float]) -> bool: """Check if the given value can be interpreted as an integer. Args: n (Union[int, str, float]): value to check. Returns: bool: can be the value be interpreted as an integer. """ try: int(n) ex...
bigcode/self-oss-instruct-sc2-concepts
import json def get_json_file(filename): """ The ``get_json_file`` function is a simple helper function that serves to open, load, and return the contents of the JSON file indicated in the input ``filename`` formal parameter. :param filename: A string indicating the location and name of the ...
bigcode/self-oss-instruct-sc2-concepts
def tsum(nums): """Sum an iterable of numbers""" return sum(nums)
bigcode/self-oss-instruct-sc2-concepts
def read_input_from_file(f): """From an open file f, reads each line and processes it, creating the problem input variables. Parameters ---------- f : file Opened input file (with the formatting given in the Mini-Project statement) Returns ------- A : dictionary Dictionary ...
bigcode/self-oss-instruct-sc2-concepts
def _etag_write_match(incoming_etag, server_etag): """ Compare two tiddler etags for a satisfactory match for a PUT or DELETE. This means comparing without the content type that _may_ be on the end. """ incoming_etag = incoming_etag.split(':', 1)[0].strip('"') server_etag = server_etag.split...
bigcode/self-oss-instruct-sc2-concepts
def relpath(repo_path): """Return a relative path to the given path within the repo. The path is relative to the infra/bots dir, where the compile.isolate file lives. """ repo_path = '../../' + repo_path repo_path = repo_path.replace('../../infra/', '../') repo_path = repo_path.replace('../bots/', '') ...
bigcode/self-oss-instruct-sc2-concepts
def snake_to_header(string: str) -> str: """Converts a snake case string to a table header by replacing underscores with spaces and making uppercase. Args: string (str): The snake case string. Returns: str: The header. """ return string.replace('_', ' ').upper()
bigcode/self-oss-instruct-sc2-concepts
def string_to_boolean(string): """ Converts string representations of TRUE/FALSE to an boolean value. :param str string: the string to convert. :return: _result :rtype: bool """ _result = False _string = str(string) if(_string.lower() == 'true' or _string.lower() == 'yes' or ...
bigcode/self-oss-instruct-sc2-concepts
def _verify_non_empty_string(value, field_name): """Ensures that a given proposed field value is a non-empty string. Args: value: proposed value for the field. field_name: string name of the field, e.g. `project`. Returns: The given value, provided that it passed the checks. Raises: ValueError...
bigcode/self-oss-instruct-sc2-concepts
import random import string def get_random_string(k: int = 1) -> str: """Returns a random string of length k. Args: k: Length of a string (default: 1). Returns: A random string. """ return ''.join([random.choice(string.ascii_letters) for _ in range(k)])
bigcode/self-oss-instruct-sc2-concepts
def leakyReLU(x): """ Leaky rectifier transfer function if x > 0, return x ; else return 0.1 * x """ return x * (x > 0) + (.1 * x) * (x < 0)
bigcode/self-oss-instruct-sc2-concepts
from typing import Optional import traceback def format_exc(exc: Optional[int] = None) -> str: """Format a traceback.""" return traceback.format_exc(exc)
bigcode/self-oss-instruct-sc2-concepts
def parse_prot_cntct_line(prot_cntct_line): """Returns a dictionary containing the info from a line of a protein contact report from MOE Usage: parse_prot_cntct_line(prot_cntct_line) where pc_line is a string from a protein contact line from a MOE protein contact report. Returns a d...
bigcode/self-oss-instruct-sc2-concepts
def step_iterator(iterator, input_data=None): """Avanza un iterador un paso, enviándole un valor si es necesario. El iterador *no* debe producir valores 'None' en ninguno de sus pasos. Args: iterator (iterator): Iterador a avanzar. input_data (object): Valor a envíar al iterador. Retur...
bigcode/self-oss-instruct-sc2-concepts
def parse_mappings(mapping_list): """Parse a list of mapping strings into a dictionary. Adapted from neutron_lib.utils.helpers.parse_mappings. :param mapping_list: A list of strings of the form '<key>:<value>'. :returns: A dict mapping keys to values or to list of values. :raises ValueError: Upon ...
bigcode/self-oss-instruct-sc2-concepts
from typing import Any def ensure_one(**kwargs: Any) -> tuple[str, Any]: """Ensures that only one argument is set.""" if sum(value is not None for value in kwargs.values()) != 1: raise ValueError('Must specify exactly one of:', kwargs.keys()) for key, value in kwargs.items(): if value is...
bigcode/self-oss-instruct-sc2-concepts
def calculate_distance(pos1: tuple, pos2: tuple) -> int: """ Taxicab/Manhattan distance """ return abs(pos1[0] - pos2[0]) + abs(pos1[1] - pos2[1])
bigcode/self-oss-instruct-sc2-concepts
def pick_bball_game(p): """ prob_game1 = p prob_game2 = P(make 1+2) + P(make 1+3) + P(make 2+3) + P(make 1+2+3) prob_game2 = p*p*(1-p) + p*(1-p)*p + (1-p)*p*p + p*p*p prob_game2 = p**2 - p**3 + p**2 - p**3 + p**2 - p**3 + p**3 prob_game2 = 3 * p ** 2 - 2 * p ** 3 prob_game1 > prob_game2 ...
bigcode/self-oss-instruct-sc2-concepts
def matching_files(directory, prefix=None, suffix=None, prepend=False): """Get a list of files that start with a specific prefix. Args: directory (pathlib.Path): The directory containing files. prefix (str): A prefix to match filenames against. suffix (str): A suffix (file extension) to ...
bigcode/self-oss-instruct-sc2-concepts
def get_indices(dataset, class_name): """Return indices of class_name in dataset.""" indices = [] for i in range(len(dataset.targets)): if dataset.targets[i] == class_name: indices.append(i) return indices
bigcode/self-oss-instruct-sc2-concepts
def filter_article(event): """ Optionally filters original article text from response. Expects "original_text" and optional "filter_article" fields in event. """ if event.get("filter_article", True): del event["original_text"] return event
bigcode/self-oss-instruct-sc2-concepts
from typing import List def create_questionnaire_response_item(question_id: str, answers: List[dict]) -> dict: """ Create a questionnaire response answer item following the FHIR format (https://www.hl7.org/fhir/questionnaireresponse-definitions.html#QuestionnaireResp...
bigcode/self-oss-instruct-sc2-concepts
def __carta(soup): """ Gets the most read news from the Carta Capital page :param soup: the BeautifulSoup object :return: a list with the most read news from the Carta Capital Page """ news = [] container = soup.find('dd', id='fieldset-maisacessadas-semana') most_read = container.find_a...
bigcode/self-oss-instruct-sc2-concepts
def analysis_get_wavelength(analysis): """Gets the wavelength value of a specific analysis. Parameters ---------- analysis: Any An OpticStudio Analysis. Returns ------- int | str Either the wavelength number, or 'All' if wavelength was set to 'All'. """ wl = analys...
bigcode/self-oss-instruct-sc2-concepts