seed
stringlengths
1
14k
source
stringclasses
2 values
def current_ratio(current_assets, current_liabilities, inventory = 0): """Computes current ratio. Parameters ---------- current_assets : int or float Current assets current_liabilities : int or float Current liabilities inventory: int or float Inventory Returns ...
bigcode/self-oss-instruct-sc2-concepts
def ci(_tuple): """ Combine indices """ return "-".join([str(i) for i in _tuple])
bigcode/self-oss-instruct-sc2-concepts
def base_point_finder(line1, line2, y=720): """ This function calculates the base point of the suggested path by averaging the x coordinates of both detected lines at the highest y value. :param line1: Coefficients of equation of first line in standard form as a tuple. :param line2: Coefficients of ...
bigcode/self-oss-instruct-sc2-concepts
def expand_var(v, env): """ If v is a variable reference (for example: '$myvar'), replace it using the supplied env dictionary. Args: v: the variable to replace if needed. env: user supplied dictionary. Raises: Exception if v is a variable reference but it is not found in env. """ if len(v...
bigcode/self-oss-instruct-sc2-concepts
from typing import List def is_primary_stressed(syllable: List[str]) -> bool: """ Checks if a syllables is primary stressed or not. :param syllable: represented as a list of phonemes :return: True or False """ return True if any(phoneme.endswith('1') for phoneme in syllable) else False
bigcode/self-oss-instruct-sc2-concepts
def count_bad_pixels_per_block(x, y, bad_bins_x, bad_bins_y): """ Calculate number of "bad" pixels per rectangular block of a contact map "Bad" pixels are inferred from the balancing weight column `weight_name` or provided directly in the form of an array `bad_bins`. Setting `weight_name` and `bad...
bigcode/self-oss-instruct-sc2-concepts
import io def csv_parseln( p_line, delim=',', quote='\"', esc='\\'): """ Given a sample CSV line, this function will parse the line into a list of cells representing that CSV row. If the given `p_line` contains newline characters, only the content present before the first newline character is parsed. ...
bigcode/self-oss-instruct-sc2-concepts
def rechunk_da(da, sample_chunks): """ Args: da: xarray DataArray sample_chunks: Chunk size in sample dimensions Returns: da: xarray DataArray rechunked """ lev_str = [s for s in list(da.coords) if 'lev' in s][0] return da.chunk({'sample': sample_chunks, lev_str: da.coo...
bigcode/self-oss-instruct-sc2-concepts
from typing import List def denormalize_identity(texts: List[str], verbose=False) -> List[str]: """ Identity function. Returns input unchanged Args: texts: input strings Returns input strings """ return texts
bigcode/self-oss-instruct-sc2-concepts
import math def calculate_fuel_requirement_plus(fuel): """Calculates the fuel requirement based on the given fuel mass. (Part 2) Parameters: fuel (int): mass of the fuel Returns: int:Additional fuel required """ add = math.floor(fuel / 3) - 2 if add > 0: return add + ca...
bigcode/self-oss-instruct-sc2-concepts
def assumed_metric(y_true, y_pred, metric, assume_unlabeled=0, **kwargs): """ This will wrap a metric so that you can pass it in and it will compute it on labeled and unlabeled instances converting unlabeled to assume_unlabeled Assumption: label -1 == unlabled, 0 == negative, 1 == positive """ ...
bigcode/self-oss-instruct-sc2-concepts
def _HELP_convert_RMSD_nm2angstrom(RMSD_nm): """ Helpfunction for plot_HEATMAP_REX_RMSD(): convert RMSD values: RMSD_nm -> RMSD_anstrom Args: RMSD_nm (list): rmsd values in nm Returns: RMSD (list) rmsd values in angstrom """ RMSD = [x*10 for x in RMSD_nm] re...
bigcode/self-oss-instruct-sc2-concepts
from pathlib import Path import json def read_features(corpus_folder): """Read the dictionary of each poem in "corpus_folder" and return the list of python dictionaries :param corpus_folder: Local folder where the corpus is located :return: List of python dictionaries with the poems features """ ...
bigcode/self-oss-instruct-sc2-concepts
def static_vars(**kwargs): """ Attach static variables to a function. Usage: @static_vars(k1=v1, k2=k2, ...) def myfunc(...): myfunc.k1... Parameters: **kwargs Keyword=value pairs converted to static variables in decorated function. Returns: decorate """ def decor...
bigcode/self-oss-instruct-sc2-concepts
def flatten(iter_of_iters): """ Flatten an iterator of iterators into a single, long iterator, exhausting each subiterator in turn. >>> flatten([[1, 2], [3, 4]]) [1, 2, 3, 4] """ retval = [] for val in iter_of_iters: retval.extend(val) return retval
bigcode/self-oss-instruct-sc2-concepts
def is_number(s): """ Checks if the variable is a number. :param s: the variable :return: True if it is, otherwise False """ try: # Don't need to check for int, if it can pass as a float then it's a number float(s) return True except ValueError: return False
bigcode/self-oss-instruct-sc2-concepts
import math def cond_loglik_bpd(model, x, context): """Compute the log-likelihood in bits per dim.""" return - model.log_prob(x, context).sum() / (math.log(2) * x.shape.numel())
bigcode/self-oss-instruct-sc2-concepts
import threading def create_thread(func, args): """Creates a thread with specified function and arguments""" thread = threading.Thread(target=func, args=args) thread.start() return thread
bigcode/self-oss-instruct-sc2-concepts
def calculate_stretch_factor(array_length_samples, overlap_ms, sr): """Determine stretch factor to add `overlap_ms` to length of signal.""" length_ms = array_length_samples / sr * 1000 return (length_ms + overlap_ms) / length_ms
bigcode/self-oss-instruct-sc2-concepts
def nothing(text: str, expression: str) -> bool: # pylint: disable=unused-argument """Always returns False""" return False
bigcode/self-oss-instruct-sc2-concepts
import requests def read_build_cause(job_url, build_id): """Read cause why the e2e job has been started.""" api_query = job_url + "/" + str(build_id) + "/api/json" response = requests.get(api_query) actions = response.json()["actions"] cause = None for action in actions: if "_class" i...
bigcode/self-oss-instruct-sc2-concepts
import re def to_valid_filename(filename: str) -> str: """Given any string, return a valid filename. For this purpose, filenames are expected to be all lower-cased, and we err on the side of being more restrictive with allowed characters, including not allowing space. Args: filename (str...
bigcode/self-oss-instruct-sc2-concepts
def shapes(tensors): """Get the static shapes of tensors in a list. Arguments: tensors: an iterable of `tf.Tensor`. Returns: a `list` of `tf.TensorShape`, one for each tensor in `tensors`, representing their static shape (via `tf.Tensor.get_shape()`). """ return [t.get_shape() ...
bigcode/self-oss-instruct-sc2-concepts
def get_4d_idx(day): """ A small utility function for indexing into a 4D dataset represented as a 3D dataset. [month, level, y, x], where level contains 37 levels, and day contains 28, 29, 30 or 31 days. """ start = 1 + 37 * (day - 1) stop = start + 37 return list(range(start, stop, ...
bigcode/self-oss-instruct-sc2-concepts
def cookielaw(request): """Add cookielaw context variable to the context.""" cookie = request.COOKIES.get('cookielaw_accepted') return { 'cookielaw': { 'notset': cookie is None, 'accepted': cookie == '1', 'rejected': cookie == '0', } }
bigcode/self-oss-instruct-sc2-concepts
def calculate_offset(address, base, shadow_base=0): """ Calculates an offset between two addresses, taking optional shadow base into consideration. Args: address (int): first address base (int): second address shadow_base (int): mask of shadow address that is applied to `base` ...
bigcode/self-oss-instruct-sc2-concepts
import yaml def get_yaml_dict(yaml_file): """Return a yaml_dict from reading yaml_file. If yaml_file is empty or doesn't exist, return an empty dict instead.""" try: with open(yaml_file, "r") as file_: yaml_dict = yaml.safe_load(file_.read()) or {} return yaml_dict except FileNotFoundError: return {}
bigcode/self-oss-instruct-sc2-concepts
import math def tand(v): """Return the tangent of x (measured in in degrees).""" return math.tan(math.radians(v))
bigcode/self-oss-instruct-sc2-concepts
def cartesian(coords): """ Convert 2D homogeneus/projective coordinates to cartesian. """ return coords[:, :2]
bigcode/self-oss-instruct-sc2-concepts
def getObjectKey(rpcObject): """Given a rpc object, get a unique key that in the form 'class.id' @type rpcObject: grpc.Message @param rpcObject: Rpc object to get a key for @rtype: str @return: String key in the form <class>.<id> """ objectClass = rpcObject.__class__.__name__ object...
bigcode/self-oss-instruct-sc2-concepts
import calendar def sort_months(months): """Sort a sequence of months by their calendar order""" month_ref = list(calendar.month_name)[1:] return sorted(months, key=lambda month: month_ref.index(month))
bigcode/self-oss-instruct-sc2-concepts
from pathlib import Path import tempfile import venv def create_new_venv() -> Path: """Create a new venv. Returns: path to created venv """ # Create venv venv_dir = Path(tempfile.mkdtemp()) venv.main([str(venv_dir)]) return venv_dir
bigcode/self-oss-instruct-sc2-concepts
def total_seconds(td): """ Return total seconds in timedelta object :param td: timedelta :type td: datetime.timedelta :return: seconds :rtype: float """ return (td.microseconds + (td.seconds + td.days * 86400) * 1000000) / 1000000.0
bigcode/self-oss-instruct-sc2-concepts
import getpass def get_mysql_pwd(config): """Get the MySQL password from the config file or an interactive prompt.""" # Two ways to get the password are supported. # # 1. Read clear-text password from config file. (least secure) # 2. Read password as entered manually from a console prompt. (most s...
bigcode/self-oss-instruct-sc2-concepts
def resolve_attribute(name, bases, default=None): """Find the first definition of an attribute according to MRO order.""" for base in bases: if hasattr(base, name): return getattr(base, name) return default
bigcode/self-oss-instruct-sc2-concepts
def _get_date_and_time_strings(date): """Return string of YYYYMMDD and time in HHMM format for file access.""" y, m, d, h = [str(i) for i in [date.year, date.month, date.day, date.hour]] # add zeros if needed if len(m) == 1: m = '0' + m if len(d) == 1: d = '0' + d if len(h) == 1...
bigcode/self-oss-instruct-sc2-concepts
import typing def format_scopes(scopes: typing.List[str]) -> str: """Format a list of scopes.""" return " ".join(scopes)
bigcode/self-oss-instruct-sc2-concepts
import re def get_size_from_tags(tags): """Searches a tags string for a size tag and returns the size tag. Size tags: spacesuit, extrasmall, small, medium, large, extralarge. """ match = re.search( r'\b(spacesuit|extrasmall|small|medium|large|extralarge)\b', tags ) if match: re...
bigcode/self-oss-instruct-sc2-concepts
def distance_from_camera(bbox, image_shape, real_life_size): """ Calculates the distance of the object from the camera. PARMS bbox: Bounding box [px] image_shape: Size of the image (width, height) [px] real_life_size: Height of the object in real world [cms] """ ## REFERENCE FOR GOPRO ...
bigcode/self-oss-instruct-sc2-concepts
def get_occurences(node, root): """ Count occurences of root in node. """ count = 0 for c in node: if c == root: count += 1 return count
bigcode/self-oss-instruct-sc2-concepts
def snd(tpl): """ >>> snd((0, 1)) 1 """ return tpl[1]
bigcode/self-oss-instruct-sc2-concepts
from pathlib import Path from typing import List def get_regions_data(path: Path) -> List[dict]: """Gets base data for a region in a page. :param path: Path to the region directory. :return: List of dictionaries holding base region data. """ regions = list() for region in sorted(path.glob("....
bigcode/self-oss-instruct-sc2-concepts
def get_members_name(member): """Check if member has a nickname on server. Args: member (Union[discord.member.Member, list]): Info about member of guild Returns: str: User's name, if user doesn't have a nickname and otherwise list: List of names of user's nicknames """ if i...
bigcode/self-oss-instruct-sc2-concepts
def find_layer_idx(model, layer_name): """Looks up the layer index corresponding to `layer_name` from `model`. Args: model: The `keras.models.Model` instance. layer_name: The name of the layer to lookup. Returns: The layer index if found. Raises an exception otherwise. """ ...
bigcode/self-oss-instruct-sc2-concepts
def _start_time_from_groupdict(groupdict): """Convert the argument hour/minute/seconds minute into a millisecond value. """ if groupdict['hours'] is None: groupdict['hours'] = 0 return (int(groupdict['hours']) * 3600 + int(groupdict['minutes']) * 60 + int(groupdict['seco...
bigcode/self-oss-instruct-sc2-concepts
def frame_to_pattern(frame_path): """Convert frame count to frame pattern in an image file path. Args: frame_path (str): Path of an image file with frame count. Returns: str: Path of an image sequence with frame pattern. """ name_list = frame_path.split('.') name_list[-2] = '%...
bigcode/self-oss-instruct-sc2-concepts
import math def visibility(nov, nol, a): """Compute visibility using height-correlated GGX. Heitz 2014, "Understanding the Masking-Shadowing Function in Microfacet-Based BRDFs" Args: nov: Normal dot view direction. nol: Normal dot light direction. a: Linear roughness. Returns: The geometr...
bigcode/self-oss-instruct-sc2-concepts
def flip(res): """flips 'x', 'o' or 'draw'.""" if res == 'x': return 'o' elif res == 'o': return 'x' elif res == 'draw': return 'draw' else: raise RuntimeError("Invalid res: %s" % str(res))
bigcode/self-oss-instruct-sc2-concepts
import math def calculate_tail_correction(box_legth, n_particles, cutoff): """ Calculates the tail correction Parameters ---------- box_legth : float The distance between the particles in reduced units. n_particles : int The number of particles. cutoff : float ...
bigcode/self-oss-instruct-sc2-concepts
def getPdbCifLink(pdb_code): """Returns the html path to the cif file on the pdb server """ file_name = pdb_code + '.cif' pdb_loc = 'https://files.rcsb.org/download/' + file_name return file_name, pdb_loc
bigcode/self-oss-instruct-sc2-concepts
def prep_sub_id(sub_id_input): """Processes subscription ID Args: sub_id_input: raw subscription id Returns: Processed subscription id """ if not isinstance(sub_id_input, str): return "" if len(sub_id_input) == 0: return "" return "{" + sub_id_input.strip...
bigcode/self-oss-instruct-sc2-concepts
def nth_eol(src, lineno): """ Compute the ending index of the n-th line (before the newline, where n is 1-indexed) >>> nth_eol("aaa\\nbb\\nc", 2) 6 """ assert lineno >= 1 pos = -1 for _ in range(lineno): pos = src.find('\n', pos + 1) if pos == -1: return ...
bigcode/self-oss-instruct-sc2-concepts
import requests def get_online_person(params=None, **kwargs) -> bytes: """Get a picture of a fictional person from the ThisPersonDoesNotExist webpage. :param params: params dictionary used by requests.get :param kwargs: kwargs used by requests.get :return: the image as bytes """ r = requests.g...
bigcode/self-oss-instruct-sc2-concepts
def cols_to_count(df, group, columns): """Count the number of column values when grouping by another column and return new columns in original dataframe. Args: df: Pandas DataFrame. group: Column name to groupby columns: Columns to count. Returns: Original DataFrame with ne...
bigcode/self-oss-instruct-sc2-concepts
import math def calcVector(p1,p2): """ calculate a line vector in polar form from two points. The return is the length of the line and the slope in degrees """ dx = p2[0]-p1[0] dy = p2[1]-p1[1] mag = math.sqrt(dx * dx + dy * dy) theta = math.atan2(dy,dx) * 180.0 / math.pi + 90.0 re...
bigcode/self-oss-instruct-sc2-concepts
def striplines(text): """ Remove all leading/trailing whitespaces from lines and blank lines. """ return "\n".join( line.strip() for line in text.splitlines() if len(line.strip()) )
bigcode/self-oss-instruct-sc2-concepts
from datetime import datetime def ms_since_epoch(dt): """ Get the milliseconds since epoch until specific a date and time. Args: dt (datetime): date and time limit. Returns: int: number of milliseconds. """ return (dt - datetime(1970, 1, 1)).total_seconds() * 1000
bigcode/self-oss-instruct-sc2-concepts
import re def slugify(s): """ Simplifies ugly strings into something URL-friendly. >>> print slugify("[Some] _ Article's Title--") some-articles-title """ # "[Some] _ Article's Title--" # "[some] _ article's title--" s = s.lower() # "[some] _ article's_title--" # "[some]___ar...
bigcode/self-oss-instruct-sc2-concepts
import linecache def get_title(notes_path, file_stem): """ Get the title by reading the second line of the .md file """ title = linecache.getline(notes_path + file_stem + '.md', 2) title = title.replace('\n', '') title = title.replace('title: ', '') return title
bigcode/self-oss-instruct-sc2-concepts
from typing import List from typing import Dict from typing import Any def sew_messages_and_reactions( messages: List[Dict[str, Any]], reactions: List[Dict[str, Any]] ) -> List[Dict[str, Any]]: """Given a iterable of messages and reactions stitch reactions into messages. """ # Add all messages wit...
bigcode/self-oss-instruct-sc2-concepts
def get_timing(line: str) -> str: """ Returns the stimulus timing from a line of text grabbed from a .vmrk file. """ return line.split(",")[2]
bigcode/self-oss-instruct-sc2-concepts
def empty_string_check(string, raise_exception=True): """ Simple check to see if the string provided by parameter string is empty. False indicates the string is NOT empty. Parameter raise_exception determines if a ValueError exception should be raised if the string is empty. If raise_exception is False and the str...
bigcode/self-oss-instruct-sc2-concepts
def get_public_key_from_x509cert_obj(x509cert) -> bytes: """ returns a RSA public key object from a x509 certificate object """ return x509cert.public_key()
bigcode/self-oss-instruct-sc2-concepts
import re def cap_case_str(s): """ Translate a string like "foo_Bar-baz whee" and return "FooBarBazWhee". """ return re.sub(r'(?:[^a-z0-9]+|^)(.)', lambda m: m.group(1).upper(), s, flags=re.IGNORECASE)
bigcode/self-oss-instruct-sc2-concepts
def transfer_mac(mac): """Transfer MAC address format from xxxx.xxxx.xxxx to xx:xx:xx:xx:xx:xx""" mac = ''.join(mac.split('.')) rslt = ':'.join([mac[e:e + 2] for e in range(0, 11, 2)]) return rslt
bigcode/self-oss-instruct-sc2-concepts
def make_name(key): """Return a string suitable for use as a python identifer from an environment key.""" return key.replace('PLATFORM_', '').lower()
bigcode/self-oss-instruct-sc2-concepts
def get_crowd_selection_counts(input_id, task_runs_json_object): """ Figure out how many times the crowd selected each option :param input_id: the id for a given task :type input_id: int :param task_runs_json_object: all of the input task_runs from json.load(open('task_run.json')) :type task_r...
bigcode/self-oss-instruct-sc2-concepts
def _GetSupportedApiVersions(versions, runtime): """Returns the runtime-specific or general list of supported runtimes. The provided 'versions' dict contains a field called 'api_versions' which is the list of default versions supported. This dict may also contain a 'supported_api_versions' dict which lists ap...
bigcode/self-oss-instruct-sc2-concepts
def build_hugo_links(links: list) -> list: """ Extens the passed wiki links list by adding a dict key for the hugo link. """ for link in links: link['hugo_link'] = f'[{link["text"]}]({{{{< ref "{link["link"]}" >}}}})' return links
bigcode/self-oss-instruct-sc2-concepts
def _is_digit_power_sum(number: int, power: int) -> bool: """ Returns whether a number is equal to the sum of its digits to the given power """ return number == sum(d ** power for d in map(int, str(number)))
bigcode/self-oss-instruct-sc2-concepts
def get_achievement(dist): """Получить поздравления за пройденную дистанцию.""" # В уроке «Строки» вы описали логику # вывода сообщений о достижении в зависимости # от пройденной дистанции. # Перенесите этот код сюда и замените print() на return. if dist >= 6.5: return 'Отличный результа...
bigcode/self-oss-instruct-sc2-concepts
def support(node): """Get support value of a node. Parameters ---------- node : skbio.TreeNode node to get support value of Returns ------- float or None support value of the node, or None if not available Notes ----- A "support value" is defined as the numeric...
bigcode/self-oss-instruct-sc2-concepts
def merge_sort(sorted_l1, sorted_l2): """ Merge sorting two sorted array """ result = [] i = 0 j = 0 while i < len(sorted_l1) and j < len(sorted_l2): if sorted_l1[i] < sorted_l2[j]: result.append(sorted_l1[i]) i += 1 else: result.append(sorted_l2[...
bigcode/self-oss-instruct-sc2-concepts
def construct_html(search_term, results): """ Given a list of results, construct the HTML page. """ link_format = '<a href="{0.img_url}"><img src="{0.thumb_url}" alt="{0.name}" title="{0.name}"></a>' html_links = '\n'.join([link_format.format(result) for result in results]) html_output = ( ...
bigcode/self-oss-instruct-sc2-concepts
def split_by_comma(s): """ Split a string by comma, trim each resultant string element, and remove falsy-values. :param s: str to split by comma :return: list of provided string split by comma """ return [i.strip() for i in s.split(",") if i]
bigcode/self-oss-instruct-sc2-concepts
def compute_resource_attributes(decos, compute_deco, resource_defaults): """ Compute resource values taking into account defaults, the values specified in the compute decorator (like @batch or @kubernetes) directly, and resources specified via @resources decorator. Returns a dictionary of resource ...
bigcode/self-oss-instruct-sc2-concepts
import glob def get_file_list(file_type): """ Returns a list of all files to be processed :param file_type: string - The type to be used: crash, charges, person, primaryperson, unit :return: array """ return glob.glob("/data/extract_*_%s_*.csv" % file_type)
bigcode/self-oss-instruct-sc2-concepts
def _ns(obj, search): """Makes searching via namespace slightly easier.""" return obj.xpath(search, namespaces={'aws':'http://www.aws.com/aws'})
bigcode/self-oss-instruct-sc2-concepts
def clustering(cloud, tol, min_size, max_size): """ Input parameters: cloud: Input cloud tol: tolerance min_size: minimal number of points to form a cluster max_size: maximal number of points that a cluster allows Output: cluster_indices: a list of list. Each element ...
bigcode/self-oss-instruct-sc2-concepts
def findInEdges(nodeNum, edges, att=None): """ Find the specified node index in either node_i or node_j columns of input edges df. Parameters ---------- nodeNum : int This is the node index not protein index. edges : pandas dataframe Dataframe in which to search for node. R...
bigcode/self-oss-instruct-sc2-concepts
from functools import reduce def deepGetAttr(obj, path): """ Resolves a dot-delimited path on an object. If path is not found an `AttributeError` will be raised. """ return reduce(getattr, path.split('.'), obj)
bigcode/self-oss-instruct-sc2-concepts
def tokenize(sent, bert_tok): """Return tokenized sentence""" return ' '.join(bert_tok.tokenize(sent))
bigcode/self-oss-instruct-sc2-concepts
def get_mask_from_lengths(memory, memory_lengths): """Get mask tensor from list of length Args: memory: (batch, max_time, dim) memory_lengths: array like """ mask = memory.data.new(memory.size(0), memory.size(1)).byte().zero_() for idx, l in enumerate(memory_lengths): mask[id...
bigcode/self-oss-instruct-sc2-concepts
import math def _get_burst_docids(dtd_matrix, burst_loc, burst_scale): """ Given a burst and width of an event burst, retrieve all documents published within that burst, regardless of whether they actually concern any event. :param dtd_matrix: document-to-day matrix :param burst_loc: location of t...
bigcode/self-oss-instruct-sc2-concepts
def split_by_commas(string): """Split a string by unenclosed commas. Splits a string by commas that are not inside of: - quotes - brackets Arguments: string {String} -- String to be split. Usuall a function parameter string Examples: >>> split_by_commas('foo, bar(ba...
bigcode/self-oss-instruct-sc2-concepts
def drop_null_values(df): """ Drop records with NaN values. """ df = df.dropna() return df
bigcode/self-oss-instruct-sc2-concepts
def run_checks(checks): """ Run a number of checks. :param tuple checks: a tuple of tuples, with check name and parameters dict. :returns: whether all checks succeeded, and the results of each check :rtype: tuple of (bool, dict) """ results = {} all_succeeded = True for check, kwar...
bigcode/self-oss-instruct-sc2-concepts
import pickle def read_raw_results(results_file): """ Read the raw results from the pickle file. Parameters: - results_file: the path to the pickle file. Return: - results: a dictionary of objects. """ results = None with open(results_file, 'rb') as f: results = p...
bigcode/self-oss-instruct-sc2-concepts
import calendar def totimestamp(value): """ convert a datetime into a float since epoch """ return int(calendar.timegm(value.timetuple()) * 1000 + value.microsecond / 1000)
bigcode/self-oss-instruct-sc2-concepts
def error_format(search): """ :param search: inputted word :return: bool. Checking every element in the inputted word is in alphabet. """ for letter in search: if letter.isalpha() is False: return True
bigcode/self-oss-instruct-sc2-concepts
import re def from_dms(dms_string): """ Converts a string from sexagesimal format to a numeric value, in the same units as the major unit of the sexagesimal number (typically hours or degrees). The value can have one, two, or three fields representing hours/degrees, minutes, and seconds respective...
bigcode/self-oss-instruct-sc2-concepts
def qualify_name(name_or_qname, to_kind): """ Formats a name or qualified name (kind/name) into a qualified name of the specified target kind. :param name_or_qname: The name to transform :param to_kind: The kind to apply :return: A qualified name like: kind/name """ if '/' in name_or_qn...
bigcode/self-oss-instruct-sc2-concepts
import typing def linear_search(arr: typing.List[int], target: int) -> int: """ Performs a linear search through arr. This is O(N) as worst case the last element in arr will need to be checked :param arr: The sequence of integers :param target: The target number to retrieve the index of. :ret...
bigcode/self-oss-instruct-sc2-concepts
import math def distance(x0, y0, x1, y1): """Return the coordinate distance between 2 points""" dist = math.hypot((x1-x0),(y1-y0)) return dist
bigcode/self-oss-instruct-sc2-concepts
def r_squared(measured, predicted): """Assumes measured a one-dimensional array of measured values predicted a one-dimensional array of predicted values Returns coefficient of determination""" estimated_error = ((predicted - measured)**2).sum() mean_of_measured = measured.sum()/len(m...
bigcode/self-oss-instruct-sc2-concepts
def compute_gcvf(sdam: float, scdm: float) -> float: """ Compute the goodness of class variance fit (GCVF). :param sdam: Sum of squared deviations for array mean (SDAM) :param scdm: Sum of squared class devations from mean (SCDM) :return: GCVF Sources: https://arxiv.org/abs/2005.01653 ...
bigcode/self-oss-instruct-sc2-concepts
def bind(func, *args): """ Returns a nullary function that calls func with the given arguments. """ def noarg_func(): return func(*args) return noarg_func
bigcode/self-oss-instruct-sc2-concepts
def read_fasta(fasta): """ Read the protein sequences in a fasta file Parameters ----------- fasta : str Filename of fasta file containing protein sequences Returns ---------- (list_of_headers, list_of_sequences) : tuple A tuple of corresponding lists of protein desc...
bigcode/self-oss-instruct-sc2-concepts
def get_service_at_index(asset, index): """Gets asset's service at index.""" matching_services = [s for s in asset.services if s.index == int(index)] if not matching_services: return None return matching_services[0]
bigcode/self-oss-instruct-sc2-concepts
def count(pets): """Return count from queryset.""" return pets.count()
bigcode/self-oss-instruct-sc2-concepts