seed
stringlengths
1
14k
source
stringclasses
2 values
import math def translate_key(key): """ Translate from MIDI coordinates to x/y coordinates. """ vertical = math.floor(key / 16) horizontal = key - (vertical * 16) return horizontal, vertical
bigcode/self-oss-instruct-sc2-concepts
def naniži(vrijednost): """Pretvaranje vrijednosti koja nije n-torka u 1-torku.""" return vrijednost if isinstance(vrijednost, tuple) else (vrijednost,)
bigcode/self-oss-instruct-sc2-concepts
import math def calculate_fov(zoom, height=1.0): """Calculates the required FOV to set the view frustrum to have a view with the specified height at the specified distance. :param float zoom: The distance to calculate the FOV for. :param float height: The desired view height at the specified ...
bigcode/self-oss-instruct-sc2-concepts
from typing import Counter def avg_dicts(*args): """ Average all the values in the given dictionaries. Dictionaries must only have numerical values. If a key is not present in one of the dictionary, the value is 0. Parameters ---------- *args Dictionaries to average, as positiona...
bigcode/self-oss-instruct-sc2-concepts
def first_ok(results): """Get the first Ok or the last Err Examples -------- >>> orz.first_ok([orz.Err('wrong value'), orz.Ok(42), orz.Ok(3)]) Ok(42) >>> @orz.first_ok.wrap >>> def get_value_rz(key): ... yield l1cache_rz(key) ... yield l2cache_rz(key) ... yield get_...
bigcode/self-oss-instruct-sc2-concepts
def add1(num): """Add one to a number""" return num + 1
bigcode/self-oss-instruct-sc2-concepts
def chomp(string): """ Simple callable method to remove additional newline characters at the end of a given string. """ if string.endswith("\r\n"): return string[:-2] if string.endswith("\n"): return string[:-1] return string
bigcode/self-oss-instruct-sc2-concepts
def subtract(datae): """Subtracts two fields Parameters ---------- datae : list List of `np.ndarray` with the fields on which the function operates. Returns ------- numpy.ndarray Subtracts the second field to the first field in `datae`. Thought to process a list of ...
bigcode/self-oss-instruct-sc2-concepts
import itertools def flatten(list_of_lists): """ Takes an iterable of iterables, returns a single iterable containing all items """ return itertools.chain(*list_of_lists)
bigcode/self-oss-instruct-sc2-concepts
import time def timer(function): """Decorator for timer functions Usage: @timer def function(a): pass """ def wrapper(*args, **kwargs): start = time.time() result = function(*args, **kwargs) end = time.time() print(f"{function.__name__} took: {end -...
bigcode/self-oss-instruct-sc2-concepts
def add_default_module_params(module_parameters): """ Adds default fields to the module_parameters dictionary. Parameters ---------- module_parameters : dict Examples -------- >> module = add_default_module_params(module) Returns ------- module_parameters : dict ...
bigcode/self-oss-instruct-sc2-concepts
def yesno(value): """Converts logic value to 'yes' or 'no' string.""" return "yes" if value else "no"
bigcode/self-oss-instruct-sc2-concepts
def str2bool(val): """ converts a string to a boolean value if a non string value is passed then following types will just be converted to Bool: int, float, None other types will raise an exception inspired by https://stackoverflow.com/questions/15008758/ ...
bigcode/self-oss-instruct-sc2-concepts
def _find_text_in_file(filename, start_prompt, end_prompt): """ Find the text in `filename` between a line beginning with `start_prompt` and before `end_prompt`, removing empty lines. """ with open(filename, "r", encoding="utf-8", newline="\n") as f: lines = f.readlines() # Find the star...
bigcode/self-oss-instruct-sc2-concepts
import math def refraction_angle( theta1, index2, index1=1.0): """ Determine the exit angle (theta2) of a beam arriving at angle theta1 at a boundary between two media of refractive indices index1 and index2. The angle of refraction is determined by Snell's law, sin theta1 /...
bigcode/self-oss-instruct-sc2-concepts
def region_key(r): """ Create writeable name for a region :param r: region :return: str """ return "{0}_{1}-{2}".format(r.chr, r.start, r.end)
bigcode/self-oss-instruct-sc2-concepts
from pathlib import Path def _read_lark_file() -> str: """Reads the contents of the XIR Lark grammar file.""" path = Path(__file__).parent / "xir.lark" with path.open("r") as file: return file.read()
bigcode/self-oss-instruct-sc2-concepts
def outliers_detect_iqr(s, factor=1.5): """ Detects outliers in a pandas series using inter-quantile ranges Parameters ---------- s : pandas.core.series.Series Pandas Series for which the outliers need to be found factor : int iqr factor used for outliers Returns -----...
bigcode/self-oss-instruct-sc2-concepts
import bisect def compute_previous_intervals(I): """ For every interval j, compute the rightmost mutually compatible interval i, where i < j I is a sorted list of Interval objects (sorted by finish time) """ # extract start and finish times start = [i.left for i in I] finish = [i.right...
bigcode/self-oss-instruct-sc2-concepts
def read_bytes(filename, offset, number): """ Reads specific bytes of a binary file. :param filename: path to file :type filename: string :param offset: start reading at offset :type offset: integer :param number: number of bytes :type number: integer ...
bigcode/self-oss-instruct-sc2-concepts
def combine_roi_and_cav_mask(roi_mask, cav_mask): """ Combine ROI mask and CAV mask Parameters ---------- roi_mask : torch.Tensor Mask for ROI region after considering the spatial transformation/correction. cav_mask : torch.Tensor Mask for CAV to remove padded 0. Returns ...
bigcode/self-oss-instruct-sc2-concepts
def pname(name, levels=None): """ Return a prettified taxon name. Parameters ---------- name : str Taxon name. Returns ------- str Prettified taxon name. Examples -------- .. code:: python3 import dokdo dokdo.pname('d__Bacteria;p_...
bigcode/self-oss-instruct-sc2-concepts
def create_parameter(model, parameter_id, value, constant=True, units="dimensionless"): """ Creates new parameter for libsbml.Model. It is not necessary to assign the function to a value. The parameter is automatically added to the input model outside of the function. Parameters ---------- ...
bigcode/self-oss-instruct-sc2-concepts
def datetime_to_string(datetime): """convert a datetime object to formatted string Arguments: datetime {datetime} Returns: [string] -- formatted datetime string """ return "/".join([str(datetime.day), str(datetime.month), str(datetime.year)])
bigcode/self-oss-instruct-sc2-concepts
import re def extract_options(text, key): """Parse a config option(s) from the given text. Options are embedded in declarations like "KEY: value" that may occur anywhere in the file. We take all the text after "KEY: " until the end of the line. Return the value strings as a list. """ regex = ...
bigcode/self-oss-instruct-sc2-concepts
from typing import Union def map_value( x: Union[int, float], in_min: Union[int, float], in_max: Union[int, float], out_min: Union[int, float], out_max: Union[int, float] ) -> float: """Maps a value from an input range to a target range. Equivalent to Arduino's `map` function. Args: x: t...
bigcode/self-oss-instruct-sc2-concepts
def _get_workflow_input_parameters(workflow): """Return workflow input parameters merged with live ones, if given.""" if workflow.input_parameters: return dict(workflow.get_input_parameters(), **workflow.input_parameters) else: return workflow.get_input_parameters()
bigcode/self-oss-instruct-sc2-concepts
def autocov(v, lx): """ Compute a lag autocovariance. """ ch = 0 for i in range(v.shape[0]-lx): for j in range(v.shape[1]): ch += v[i][j]*v[i+lx][j] return ch/((v.shape[0]-lx)*v.shape[1])
bigcode/self-oss-instruct-sc2-concepts
def compute_score(segment, ebsd): """ Compute Dice measure (or f1 score) on the segmented pixels :param segment: segmented electron image (uint8 format) :param ebsd: speckle segmented out of the ebsd file (uint8 format) :return: Dice score """ segmented_ebsd = ebsd >= 128 segmented_se...
bigcode/self-oss-instruct-sc2-concepts
def get_graphlist(gg, l=None): """Traverse a graph with subgraphs and return them as a list""" if not l: l = [] outer = True else: outer = False l.append(gg) if gg.get_subgraphs(): for g in gg.get_subgraphs(): get_graphlist(g, l) if outer: retu...
bigcode/self-oss-instruct-sc2-concepts
def heads(l): """ Returns all prefixes of a list. Examples -------- >>> heads([0, 1, 2]) [[], [0], [0, 1], [0, 1, 2]] """ return map(lambda i: l[:i], range(len(l) + 1))
bigcode/self-oss-instruct-sc2-concepts
def list_subtract(a, b): """Return a list ``a`` without the elements of ``b``. If a particular value is in ``a`` twice and ``b`` once then the returned list then that value will appear once in the returned list. """ a_only = list(a) for x in b: if x in a_only: a_only.remove(...
bigcode/self-oss-instruct-sc2-concepts
def _patsplit(pat, default): """Split a string into an optional pattern kind prefix and the actual pattern.""" if ':' in pat: kind, val = pat.split(':', 1) if kind in ('re', 'glob', 'path', 'relglob', 'relpath', 'relre'): return kind, val return default, pat
bigcode/self-oss-instruct-sc2-concepts
def indent_level(level:int): """Returns a string containing indentation to the given level, in spaces""" return " " * level
bigcode/self-oss-instruct-sc2-concepts
import difflib def diff(a, b): """A human readable differ.""" return '\n'.join( list( difflib.Differ().compare( a.splitlines(), b.splitlines() ) ) )
bigcode/self-oss-instruct-sc2-concepts
import time def CreatePastDate(secs): """ create a date shifted of 'secs' seconds respect to 'now' compatible with mysql queries Note that using positive 'secs' you'll get a 'future' time! """ T=time.time()+time.timezone+secs tup=time.gmtime(T) #when="%d-%d-%d %d:%d:%d"%(tup[0],tup[1],tup[2],tup[...
bigcode/self-oss-instruct-sc2-concepts
def decompose(field): """ Function to decompose a string vector field like 'gyroscope_1' into a tuple ('gyroscope', 1) """ field_split = field.split('_') if len(field_split) > 1 and field_split[-1].isdigit(): return '_'.join(field_split[:-1]), int(field_split[-1]) return field, None
bigcode/self-oss-instruct-sc2-concepts
def build_path(tmp_path_factory): """Provides a temp directory with various files in it.""" magic = tmp_path_factory.mktemp('build_magic') file1 = magic / 'file1.txt' file2 = magic / 'file2.txt' file1.write_text('hello') file2.write_text('world') return magic
bigcode/self-oss-instruct-sc2-concepts
def run_model(model, X_train, y_train, X_test, y_test, params): # pylint: disable=too-many-arguments """Train the given model on the training data, and return the score for the model's predictions on the test data. Specify parameters of the model with the provided params. Args: model (callable): ...
bigcode/self-oss-instruct-sc2-concepts
def user_agrees(prompt_message: str) -> bool: """Ask user a question and ask him/her for True/False answer (default answer is False). :param prompt_message: message that will be prompted to user :return: boolean information if user agrees or not """ answer = input(prompt_message + ' [y/N] ') re...
bigcode/self-oss-instruct-sc2-concepts
def get(yaml_config, key_path, default_value=None): """ Get a value in a yaml_config, or return a default value. :param yaml_config: the YAML config. :param key: a key to look for. This can also be a list, looking at more depth. :param default_value: a default value to return in case th...
bigcode/self-oss-instruct-sc2-concepts
def error_margin_approx(z_star, sigma, n): """ Get the approximate margin of error for a given critical score. Parameters ---------- > z_star: the critical score of the confidence level > sigma: the standard deviation of the population > n: the size of the sample Returns ------- The approximate margin o...
bigcode/self-oss-instruct-sc2-concepts
def find_user(collection, elements, multiple=False): """ Function to retrieve single or multiple user from a provided Collection using a dictionary containing a user's elements. """ if multiple: results = collection.find(elements) return [r for r in results] else: return coll...
bigcode/self-oss-instruct-sc2-concepts
def extract_name_and_id(user_input): """Determines if the string user_input is a name or an id. :param user_input: (str): input string from user :return: (name, id) pair """ name = id = None if user_input.lower().startswith('id:'): id = user_input[3:] else: name = user_input...
bigcode/self-oss-instruct-sc2-concepts
def selection_sort(integer_list): """ The selection sort improves on the bubble sort by making only one exchange for every pass through the list. In order to do this, a selection sort looks for the largest value as it makes a pass and, after completing the pass, places it in the proper location. As wi...
bigcode/self-oss-instruct-sc2-concepts
def minsort(lst): """ Sort list using the MinSort algorithm. >>> minsort([24, 6, 12, 32, 18]) [6, 12, 18, 24, 32] >>> minsort([]) [] >>> minsort("hallo") Traceback (most recent call last): ... TypeError: lst must be a list """ # Check given parameter data type. if...
bigcode/self-oss-instruct-sc2-concepts
import logging def possible_int(arg): """Attempts to parse arg as an int, returning the string otherwise""" try: return int(arg) except ValueError: logging.info(f'failed to parse {arg} as an int, treating it as a string') return arg
bigcode/self-oss-instruct-sc2-concepts
def find_two_sum(arr, target): """ Finds the two (not necessarily distinct) indices of the first two integers in arr that sum to target, in sorted ascending order (or returns None if no such pair exists). """ prev_map = {} # Maps (target - arr[i]) -> i. for curr_idx, num in enumerate(arr): ...
bigcode/self-oss-instruct-sc2-concepts
import ast def read_data_from_txt(file_loc): """ Read and evaluate a python data structure saved as a txt file. Args: file_loc (str): location of file to read Returns: data structure contained in file """ with open(file_loc, 'r') as f: s = f.read() return ast.l...
bigcode/self-oss-instruct-sc2-concepts
import math def bounding_hues_from_renotation(hue, code): """ Returns for a given hue the two bounding hues from *Munsell Renotation System* data. Parameters ---------- hue : numeric *Munsell* *Colorlab* specification hue. code : numeric *Munsell* *Colorlab* specification ...
bigcode/self-oss-instruct-sc2-concepts
def get_div_winners(df_sim): """Calculate division winners with summarised simulation data :param df_sim: data frame with simulated scores summarised by iteration :return: data frame with division winners per iteration """ return ( df_sim .sort_values(by=['tot_wins', 'tot_pts'], ascending=[False, Fal...
bigcode/self-oss-instruct-sc2-concepts
def _construct_version(major, minor, patch, level, pre_identifier, dev_identifier, post_identifier): """Construct a PEP0440 compatible version number to be set to __version__""" assert level in ["alpha", "beta", "candidate", "final"] version = "{0}.{1}".format(major, minor) if patch: version +=...
bigcode/self-oss-instruct-sc2-concepts
def channel_parser(channel): """Parse a channel returned from ipmitool's "sol info" command. Channel format is: "%d (%x)" % (channel, channel) """ chan, xchan = channel.split(' (') return int(chan)
bigcode/self-oss-instruct-sc2-concepts
def find_col(table, col): """ Return column index with col header in table or -1 if col is not in table """ return table[0].index(col)
bigcode/self-oss-instruct-sc2-concepts
import torch def loss_fn(outputs, labels): """ Compute the cross entropy loss given outputs from the model and labels for all tokens. Exclude loss terms for PADding tokens. Args: outputs: (Variable) dimension batch_size*seq_len x num_tags - log softmax output of the model labels: (Var...
bigcode/self-oss-instruct-sc2-concepts
def get_taskToken(decision): """ Given a response from polling for decision from SWF via boto, extract the taskToken from the json data, if present """ try: return decision["taskToken"] except KeyError: # No taskToken returned return None
bigcode/self-oss-instruct-sc2-concepts
from typing import OrderedDict def broadcast_variables(*variables): """Given any number of variables, return variables with matching dimensions and broadcast data. The data on the returned variables will be a view of the data on the corresponding original arrays, but dimensions will be reordered and ...
bigcode/self-oss-instruct-sc2-concepts
def chunkFair(mylist, nchunks): """ Split list into near-equal size chunks, but do it in an order like a draft pick; they all get high and low indices. E.g. for mylist = [0,1,2,3,4,5,6], chunkFair(mylist,4) => [[0, 4], [1, 5], [2, 6], [3]] """ chunks = [None]*nchunks for i in range(nchunks): ...
bigcode/self-oss-instruct-sc2-concepts
def unionRect(rect1, rect2): """Determine union of bounding rectangles. Args: rect1: First bounding rectangle, expressed as tuples ``(xMin, yMin, xMax, yMax)``. rect2: Second bounding rectangle. Returns: The smallest rectangle in which both input rectangles are fully ...
bigcode/self-oss-instruct-sc2-concepts
import math def inverse_sigmoid(y): """A Python function for the inverse of the Sigmoid function.""" return math.log(y / (1 - y))
bigcode/self-oss-instruct-sc2-concepts
import math def image_entropy(img): """ calculate the entropy of an image """ hist = img.histogram() hist_size = sum(hist) hist = [float(h) / hist_size for h in hist] return -sum([p * math.log(p, 2) for p in hist if p != 0])
bigcode/self-oss-instruct-sc2-concepts
def strip_alias_prefix(alias): """ Splits `alias` on ':' to strip off any alias prefix. Aliases have a lab-specific prefix with ':' delimiting the lab name and the rest of the alias; this delimiter shouldn't appear elsewhere in the alias. Args: alias: `str`. The alias. Returns: ...
bigcode/self-oss-instruct-sc2-concepts
from datetime import datetime import pytz def read_gpvtg(sentence, timestamp, do_print=False): """ Read and parse GPVTG message""" values = sentence.split('*')[0].split(',') result = {} # Linux timestamp try: result['linux_stamp'] = int(timestamp) except: result['linux_stamp']...
bigcode/self-oss-instruct-sc2-concepts
def COUNT_DISTINCT(src_column): """ Builtin unique counter for groupby. Counts the number of unique values Example: Get the number of unique ratings produced by each user. >>> sf.groupby("user", ... {'rating_distinct_count':tc.aggregate.COUNT_DISTINCT('rating')}) """ return ("__builtin__count__disti...
bigcode/self-oss-instruct-sc2-concepts
def clamp(value, minimumValue, maximumValue): """clamp the value between the minimum and the maximum value :param value: value to clamp :type value: int or float :param minimumValue: minimum value of the clamp :type minimumValue: int or float :param maximumValue: maximum value of the clamp ...
bigcode/self-oss-instruct-sc2-concepts
def check_for_url_proof_id(id, existing_ids = None, min_id_length = 1, max_id_length = 21): """Returns (True, id) if id is permissible, and (False, error message) otherwise. Since we strip the id, you should use the returned one, not the original one""" id = id.strip() # maybe this is too restrictive,...
bigcode/self-oss-instruct-sc2-concepts
def is_equal_1d(ndarray1, ndarray2, showdiff=False, tolerance=0.000001): """ Whether supplied 1d numpy arrays are similar within the tolerance limit? Parameters ---------- ndarray1 : numpy.ndarray[float64, ndim=1] First array supplied for equality with `ndarray2`. ndarray2 : numpy...
bigcode/self-oss-instruct-sc2-concepts
def sort_and_uniq(linput): # @ReservedAssignment """ Función que elimina datos repetidos. :param linput: Lista :type linput: list :return: Lista modificada :rtype: list """ output = [] for x in linput: if x not in output: output.append(x) output.sort() ...
bigcode/self-oss-instruct-sc2-concepts
import asyncio def swait(co): """Sync-wait for the given coroutine, and return the result.""" return asyncio.get_event_loop().run_until_complete(co)
bigcode/self-oss-instruct-sc2-concepts
def get_indexes(table, col, v): """ Returns indexes of values _v_ in column _col_ of _table_. """ li = [] start = 0 for row in table[col]: if row == v: index = table[col].index(row, start) li.append(index) start = index + 1 return li
bigcode/self-oss-instruct-sc2-concepts
import json def load_json(filename): """Load a json file as a dictionary""" try: with open(filename, 'rb') as fid: data = json.load(fid) return data, None except Exception as err: return None, str(err)
bigcode/self-oss-instruct-sc2-concepts
def determine_Cd(w_10): """ Determining the wind speed drag coefficient Following Large & Pond (1981) https://doi.org/10.1175/1520-0485(1981)011%3C0324:OOMFMI%3E2.0.CO;2 """ return min(max(1.2E-3, 1.0E-3 * (0.49 + 0.065 * w_10)), 2.12E-3)
bigcode/self-oss-instruct-sc2-concepts
def pack(timestamp, temp, accel_data, gyro_data, magnet_data=None): """ 最新位置情報データを辞書化する。 引数: timestamp 時刻 temp 気温(float) accel_data 加速度データ(辞書) gyro_data 角速度データ(辞書) magnet_data 磁束密度データ(辞書):オプション 戻り値: 最新位置情報データ群(辞書) """ return_dict = {'a...
bigcode/self-oss-instruct-sc2-concepts
import torch def lengths_to_mask(lengths, max_len): """ This mask has a 1 for every location where we should calculate a loss lengths include the null terminator. for example the following is length 1: 0 0 0 0 0 0 The following are each length 2: 1 0 0 0 0 3 0 0 0 0 if max_len is ...
bigcode/self-oss-instruct-sc2-concepts
def check_line(line): """Check that: * a line has nine values * each val has length 1 * each val is either digital or "-" * digital values are between 1 and 9 """ vals = line.split() if not len(vals) == 9: return False for val in vals: if not len(val) == 1: ...
bigcode/self-oss-instruct-sc2-concepts
import six def collect_ancestor_classes(cls, terminal_cls=None, module=None): """ Collects all the classes in the inheritance hierarchy of the given class, including the class itself. If module is an object or list, we only return classes that are in one of the given module/modules.This wi...
bigcode/self-oss-instruct-sc2-concepts
def bin2hex(binbytes): """ Converts a binary string to a string of space-separated hexadecimal bytes. """ return ' '.join('%02x' % ord(c) for c in binbytes)
bigcode/self-oss-instruct-sc2-concepts
import torch def calc_f1_micro(predictions, labels): """ Calculate f1 micro. Args: predictions: tensor with predictions labels: tensor with original labels Returns: f1 score """ preds = predictions.max(1)[1].type_as(labels) true_positive = torch.eq(labels, preds)....
bigcode/self-oss-instruct-sc2-concepts
def flatten(t): """ Helper function to make a list from a list of lists """ return [item for sublist in t for item in sublist]
bigcode/self-oss-instruct-sc2-concepts
def get_html_header() -> str: """Helper to get a HTML header with some CSS styles for tables."" Returns: A HTML header as string. """ return """<head> <style> table { font-family: arial, sans-serif; border-collapse: colla...
bigcode/self-oss-instruct-sc2-concepts
import glob def found_with_glob(value): """ Check if at least one file match the given glob expression. :param value: glob expression """ for _ in glob.glob(value): return True return False
bigcode/self-oss-instruct-sc2-concepts
import shutil def get_path_to_executable(executable): """ Get path to local executable. :param executable: Name of executable in the $PATH variable :type executable: str :return: path to executable :rtype: str """ path = shutil.which(executable) if path is None: raise ValueErro...
bigcode/self-oss-instruct-sc2-concepts
def _direction_to_index(direction): """Map direction identifier to index. """ directions = {-1: 0, 0: slice(None), 1: 1, '<=': 0, '<=>': slice(None), '>=': 1} if direction not in directions: raise RuntimeError('Unknown direction "{:d}".'.format(direction)) return directions[direction]
bigcode/self-oss-instruct-sc2-concepts
import requests import warnings def check_pypi_module(module_name, module_version=None, raise_on_error=False, warn_on_error=True): """ Checks that module with given name and (optionally) version exists in PyPi repository. :param module_name: name of module to look for in PyPi :param module_version: (...
bigcode/self-oss-instruct-sc2-concepts
def postprocess_chain(chain, guard_solutions): """ This function post-processes the chains generated by angrop to insert input to pass the conditions on each gadget. It takes two arguments: chain - the ropchain returned by angrop guard_solutions - the required inputs to satisfy the gadget c...
bigcode/self-oss-instruct-sc2-concepts
def _parse_top_section(line): """ Returns a top-level section name ("PATH", "GEM", "PLATFORMS", "DEPENDENCIES", etc.), or `None` if the line is empty or contains leading space. """ if line == "" or line[0].isspace(): return None return line
bigcode/self-oss-instruct-sc2-concepts
def remove_line_break_escapes(value): """ removes line break escapes from given value. it replaces `\\n` with `\n` to enable line breaks. :param str value: value to remove line break escapes from it. :rtype: str """ return value.replace('\\n', '\n')
bigcode/self-oss-instruct-sc2-concepts
def _get_id(name): """Gets id from a condensed name which is formatted like: name/id.""" return name.split("/")[-1]
bigcode/self-oss-instruct-sc2-concepts
def extract_endpoints(data): """ Turn the dictionary of endpoints from the config file into a list of all endpoints. """ endpoints = [] for nodetype in data: for interval in data[nodetype]: for api in data[nodetype][interval]: endpoints += ( da...
bigcode/self-oss-instruct-sc2-concepts
import json import requests def getListOfPositions(position_name : str): """ Retrives all Microsoft publicily listed positions with name `position_name` by sending POST to Microsoft career endpoint. Args: position_name (str): Name of the position Returns: ...
bigcode/self-oss-instruct-sc2-concepts
def test_savestate(neuron_instance): """Test rxd SaveState Ensures restoring to the right point and getting the right result later. Note: getting the right result later was a problem in a prior version of NEURON, so the continuation test is important. The issue was that somehow restoring from a Sa...
bigcode/self-oss-instruct-sc2-concepts
def ask(message, options, allow_empty=False, help=None) -> str: """Ask user for input Parameters ---------- message : str Message. options : dict ``{command: description}`` mapping. allow_empty : bool Allow empty string as command. help : str If provided, add...
bigcode/self-oss-instruct-sc2-concepts
import random def random_payload_shuffled_bytes(random_payload_bytes): """ Fixture that yields the randomly generated payload bytes but shuffled in a random order. """ return random.sample(random_payload_bytes, len(random_payload_bytes))
bigcode/self-oss-instruct-sc2-concepts
from typing import Optional def greeting(name: Optional[str] = None) -> str: """Says hello given an optional name. NOTE: `Optional` is just a convenience. It's equivalent to `Union[str, None]`. """ if name: return f"Hello {name}!" else: return "Hello you!"
bigcode/self-oss-instruct-sc2-concepts
import math def ecliptic_longitude_radians(mnlong, mnanomaly): """Returns ecliptic longitude radians from mean longitude and anomaly correction.""" return math.radians((mnlong + 1.915 * math.sin(mnanomaly) + 0.020 * math.sin(2 * mnanomaly)) % 360)
bigcode/self-oss-instruct-sc2-concepts
def buff_internal_eval(params): """Builds and evaluates BUFF internal energy of a model in parallelization Parameters ---------- params: list Tuple containing the specification to be built, the sequence and the parameters for model building. Returns ------- model.bude_score...
bigcode/self-oss-instruct-sc2-concepts
from typing import Dict from typing import Any def countdown( element: Dict[str, Any], all_data: Dict[str, Dict[int, Dict[str, Any]]] ) -> Dict[str, Any]: """ Countdown slide. Returns the full_data of the countdown element. element = { name: 'core/countdown', id: 5, # Countdown ...
bigcode/self-oss-instruct-sc2-concepts
def is_csv_accepted(request): """ Returns if csv is accepted or not :return: True if csv is accepted, False otherwise """ return request.args.get('format') == "csv"
bigcode/self-oss-instruct-sc2-concepts
def can_copy(user, plan): """ Can a user copy a plan? In order to copy a plan, the user must be the owner, or a staff member to copy a plan they own. Any registered user can copy a template. Parameters: user -- A User plan -- A Plan Returns: True if the User has p...
bigcode/self-oss-instruct-sc2-concepts
import pickle def load_classifcation_metrics_pkl(classification_pkl): """Load a classificationMetrics pickle file""" with open(classification_pkl, 'rb') as fh: cm_h = pickle.load(fh) return cm_h
bigcode/self-oss-instruct-sc2-concepts