seed
stringlengths
1
14k
source
stringclasses
2 values
def get_durations(bpm): """ Function that generate a dictionary containing the duration in seconds of various rhythmic figures. :param bpm: beat per minutes :return: rhythmic dictionary """ beat_time = 60 / bpm return { '1': beat_time * 4, '2': beat_time * 2, '4'...
bigcode/self-oss-instruct-sc2-concepts
def _before_each(separator, iterable): """Inserts `separator` before each item in `iterable`. Args: separator: The value to insert before each item in `iterable`. iterable: The list into which to intersperse the separator. Returns: A new list with `separator` before each item in `iterabl...
bigcode/self-oss-instruct-sc2-concepts
def response_plain_text(output, endsession): """ create a simple json plain text response """ return { 'outputSpeech': { 'type': 'PlainText', 'text': output }, 'shouldEndSession': endsession }
bigcode/self-oss-instruct-sc2-concepts
def part_a(puzzle_input): """ Calculate the answer for part_a. We need to build a list since we do not know where 2017 will end up. Args: puzzle_input (list): Formatted as the provided input from the website. Returns: string: The answer for part_a. """ steps = int(''.join(...
bigcode/self-oss-instruct-sc2-concepts
def hr_size(num, suffix="B") -> str: """ Human-readable data size From https://stackoverflow.com/a/1094933 :param num: number of bytes :param suffix: Optional size specifier :return: Formatted string """ for unit in " KMGTPEZ": if abs(num) < 1024.0: return "%3.1f%s%s"...
bigcode/self-oss-instruct-sc2-concepts
import json def metadata_dict_to_json(clean_metadata_dict): """ Returns structured JSON from input dictionary --------------------------------------------- input: dictionary of file metadata output: clean metadata json """ clean_metadata_json = json.dumps(clean_metadata_dict) return c...
bigcode/self-oss-instruct-sc2-concepts
def template_url( url_template: str, state_machine_name: str, label: str, ) -> str: """ Templates a URL for an external service. Adds the label and state machine to a url that contains placeholders in the format `<label>` or '<state_machine>'. """ return url_template.replace( ...
bigcode/self-oss-instruct-sc2-concepts
import re def camel_case_to_underscore(name): """ This function camel_case_to_underscores a Camel Case word to a underscore word """ temp = re.sub('(.)([A-Z][a-z]+)', r'\1_\2', name) return re.sub('([a-z0-9])([A-Z])', r'\1_\2', temp).lower()
bigcode/self-oss-instruct-sc2-concepts
def _is_not_lparen_and_rparen(lparens, rtok): """Tests if an RPAREN token is matched with something other than a plain old LPAREN type. """ # note that any([]) is False, so this covers len(lparens) == 0 return rtok.type == "RPAREN" and any(x != "LPAREN" for x in lparens)
bigcode/self-oss-instruct-sc2-concepts
def cw(u, v): """ Returns True if v is to the right of u, that is, the shortest rotation from u to v is cw, turn right False otherwise """ return ((u[0] * v[1] - u[1] * v[0]) < 0)
bigcode/self-oss-instruct-sc2-concepts
def total_seconds(td): """ Return the total number of seconds contained in the duration as a float """ return (float(td.microseconds) + (td.seconds + td.days * 24 * 3600) * 10**6) / 10**6
bigcode/self-oss-instruct-sc2-concepts
def sum_digits(n): """Sum all the digits of n. >>> sum_digits(10) # 1 + 0 = 1 1 >>> sum_digits(4224) # 4 + 2 + 2 + 4 = 12 12 >>> sum_digits(1234567890) 45 """ sum = 0 while n > 0: sum += n%10 # mod will give the last digit n = n//10 #removes last digit return...
bigcode/self-oss-instruct-sc2-concepts
def getChunkPartition(chunk_id): """ return partition (if any) for the given chunk id. Parition is encoded in digits after the initial 'c' character. E.g. for: c56-12345678-1234-1234-1234-1234567890ab_6_4, the partition would be 56. For c-12345678-1234-1234-1234-1234567890ab_6_4, the partition ...
bigcode/self-oss-instruct-sc2-concepts
import pickle def pickle_stream(sklearn_model): """Returns a byte stream containing a pickled Scikit-Learn model """ return pickle.dumps(sklearn_model)
bigcode/self-oss-instruct-sc2-concepts
import json import requests def add_role_to_cloudcheckr(env, admin_api_key, account_name, role_arn): """ Uses the cross-account role created by the cloud formation stack to add it to CloudCheckr. Uses the edit_credential Admin API call. """ if role_arn is None: print("Role Arn from Cloudformation stack was no...
bigcode/self-oss-instruct-sc2-concepts
def get_duplicates(iterable): """Return a set of the elements which appear multiple times in iterable.""" seen, duplicates = set(), set() for elem in iterable: if elem in seen: duplicates.add(elem) else: seen.add(elem) return duplicates
bigcode/self-oss-instruct-sc2-concepts
from pathlib import Path import re def namelist_exists(fn: Path, nml: str) -> bool: """ Determines if a namelist exists in a file. Does not check for proper format / syntax. """ pat = re.compile(r"^\s*&(" + nml + ")$") with fn.open("rt") as f: for line in f: if pat.match(...
bigcode/self-oss-instruct-sc2-concepts
def Get_LonghurstProvinceName4Num(input): """ Get full Longhurst Province for given number """ LonghurstProvinceDict = { 'ALSK': 'AlaskaDownwellingCoastalProvince', 'ANTA': 'AntarcticProvince', 'APLR': 'AustralPolarProvince', 'ARAB': 'NWArabianUpwellingProvince', ...
bigcode/self-oss-instruct-sc2-concepts
def byteswap(*arrays): """ Swapping of bytes for provided arrays. Notes ----- arr.newbyteorder('S') swaps dtype interpretation, but not bytes in memory arr.byteswap() swaps bytes in memory, but not dtype interpretation arr.byteswap(True).newbyteorder('S') completely swaps both Referenc...
bigcode/self-oss-instruct-sc2-concepts
def deduplicate(stix_obj_list): """Deduplicate a list of STIX objects to a unique set. Reduces a set of STIX objects to unique set by looking at 'id' and 'modified' fields - as a unique object version is determined by the combination of those fields Note: Be aware, as can be seen in the implementa...
bigcode/self-oss-instruct-sc2-concepts
def _io_similar(lhs, rhs): """ Returns True if @lhs and @rhs have the same signature, false otherwise. Note that this does not check the identity of the underlying ports, just their names and types. That is, the following holds args = dict(...) x = IO(**args) y = IO(**args) ...
bigcode/self-oss-instruct-sc2-concepts
def num_bytes(byte_tmpl): """Given a list of raw bytes and template strings, calculate the total number of bytes that the final output will have. Assumes all template strings are replaced by 8 bytes. >>> num_bytes([0x127, "prog_bytes"]) 9 """ total = 0 for b in byte_tmpl: if i...
bigcode/self-oss-instruct-sc2-concepts
import csv import logging def get_function_signature(hex_signature): """ Requests the function signature from the CSV file based on the hex_signature to get the text_signature Args: hex_signature: the 4-byte signature of the function as hex value (a string starting with 0x) Returns: sign...
bigcode/self-oss-instruct-sc2-concepts
import json def cancel_reply(id_, solver_name): """A reply saying a problem was canceled.""" return json.dumps({ "status": "CANCELLED", "solved_on": "2013-01-18T10:26:00.020954", "solver": solver_name, "submitted_on": "2013-01-18T10:25:59.941674", "type": "ising", ...
bigcode/self-oss-instruct-sc2-concepts
def globalOutgassing(Fmod_out, Q, m): """ This function will calculate the outgassing flux (equation S9). Inputs: Fmod_out - the modern Earth's outgassing rate [mol C yr-1] Q - pore space heat flow relative to modern Earth [dimensionless] m - scaling parameter [dimensi...
bigcode/self-oss-instruct-sc2-concepts
def _create_arguments_dictionary(parameter_extractors, environment, context): """Creates a dictionary of arguments (to pass to an action function) using the parameters and the parameter_extractor_mapping as a guide and extracts the values from environment and context. Arguments: parameter_extractors ...
bigcode/self-oss-instruct-sc2-concepts
def _get_overlap(word1, word2): """ Returns the length of the overlap between word1 and word2. The number of letters from the end of word1 that match the beginning of word2. """ max_overlap = min(len(word1), len(word2)) max_found = 0 for size in range(1, max_overlap+1): suffix = wor...
bigcode/self-oss-instruct-sc2-concepts
def get_attribute_element(attributes, element: str, enum): """ Constructs an Emum object of a given attribute :rtype: FastEnum :type enum: FastEnum :type attributes: XML attributes :param attributes: XML attributes of a certain XML node :param elment: A String :param enum: The Enum objec...
bigcode/self-oss-instruct-sc2-concepts
def normalise(value: float, current_min: float, current_max: float, intended_min: float, intended_max: float) -> float: """ Function used to normalise a value to fit within a given range, knowing its actual range. Uses standard MinMax normalisation. :param value: Value to be normalised :param curr...
bigcode/self-oss-instruct-sc2-concepts
def _patched_computation_module(module, compute_list, compute_fn): """ Patch the module to compute a module's parameters, like FLOPs. Calls compute_fn and appends the results to compute_list. """ ty = type(module) typestring = module.__repr__() class ComputeModule(ty): orig_type = ...
bigcode/self-oss-instruct-sc2-concepts
def is_letter(c): """ Checks if the given character is a letter. :param c: The character to test. :return: True if the character is a letter, False otherwise. """ return 'A' <= c <= 'Z' or 'a' <= c <= 'z'
bigcode/self-oss-instruct-sc2-concepts
def convert_timedelta(duration): """converts date.timedelta object into hours and minutes string format HH:MM""" seconds = duration.seconds hours = seconds // 3600 if hours < 10: hours = "0" + str(hours) else: hours = str(hours) minutes = (seconds % 3600) // 60 if minutes < 1...
bigcode/self-oss-instruct-sc2-concepts
def get_combined_domain(X1, X2): """ Returns a list of the unique elements in two list-like objects. Note that there's a lot of ways to make this function, but given how the rest of the rank-turbulence divergence function is structured, it's nice to have this self-contained version. Parameters ...
bigcode/self-oss-instruct-sc2-concepts
def get_unique_from_list(source_list, compare_list): """ Extract unique entries from list. Compare source_list to compare_list and return entries from source_list and not in compare_list. Parameters ---------- source_list : list Input list to compare to base list compare_list :...
bigcode/self-oss-instruct-sc2-concepts
def guess_encoding(path): """Sample a file, seeing if the platform-dependent encoding works, and trying latin_1 if it doesn't. A more robust solution would be to use the chardet library, but we want to try and keep this dependency-free.""" try: e = None with open(path, new...
bigcode/self-oss-instruct-sc2-concepts
import math def crowding_replacement(random, population, parents, offspring, args): """Performs crowding replacement as a form of niching. This function performs crowding replacement, which means that the members of the population are replaced one-at-a-time with each of the offspring. A random sa...
bigcode/self-oss-instruct-sc2-concepts
import math def my_log(num): """ Floors the log function :param num: the number :return: log(num) floored to a very low number """ if num == 0.0: return -9999999999 return math.log(num)
bigcode/self-oss-instruct-sc2-concepts
def get_name(node): """Return name of node.""" return node.get('name')
bigcode/self-oss-instruct-sc2-concepts
import jinja2 def render_template(path: str, data: dict) -> str: """ Renders a template with given data. Parameters ---------- path: str Path to the template data: The provided data for rendering Returns ------- template: str Rendered template """ ...
bigcode/self-oss-instruct-sc2-concepts
import shutil def _termsize(fallback=(80, 24)): """ Returns the terminal size, or the fallback if it can't be retrieved""" try: columns, rows = shutil.get_terminal_size(fallback=fallback) except: return fallback return columns, rows
bigcode/self-oss-instruct-sc2-concepts
import re def format_companies(company): """ Format the selected company so that the API can find relevant articles. """ # Remove junk at the end of the names if company[-6:] == ", Inc.": return re.sub(r' ', "-", company[:-6]) if company[-5:] == ", Inc": return re.sub(r' ', "-...
bigcode/self-oss-instruct-sc2-concepts
def prop_finally(printer, ast): """Prints a finally property "<> ...".""" prop_str = printer.ast_to_string(ast["prop"]) return f'<>{prop_str}'
bigcode/self-oss-instruct-sc2-concepts
from typing import Set import ipaddress def parse_ipa4(data: str) -> Set[str]: """ parse 'ip -o -4 a' output """ res = set() # 26: eth0 inet 169.254.207.170/16 for line in data.split("\n"): line = line.strip() if line: _, dev, _, ip_sz, *_ = line.split() ...
bigcode/self-oss-instruct-sc2-concepts
def mag_zeropoint(filter_name): """ Given a filter name, return the number of photons per square centimeter per second which a star of zero'th magnitude would produce above the atmosphere. We assume that the star has a spectrum like Vega's. The numbers are pre-calculated and we just pick the approp...
bigcode/self-oss-instruct-sc2-concepts
def bibser2bibstr(bib=u'', ser=u''): """Return a valid bib.series string.""" ret = bib if ser != u'': ret += u'.' + ser return ret
bigcode/self-oss-instruct-sc2-concepts
from typing import List def strseq_startswith(seq_a: List[str], seq_b: List[str], start_index: int, case_insensitive=True) -> bool: """Test if seqA is starts with seqB""" if len(seq_a) - start_index < len(seq_b): return False if case_insensitive: for i in range(len(seq_b)): if...
bigcode/self-oss-instruct-sc2-concepts
def is_whitespace(char): """ Checks if the character is a whitespace Parameters -------------- char: str A single character string to check """ # ord() returns unicode and 0x202F is the unicode for whitespace if char == " " or char == "\t" or char == "\r" or char == "\n" or or...
bigcode/self-oss-instruct-sc2-concepts
def pass_sources_list_filter(incident, sources_list): """Checks whether the event sources of the incident contains at least one of the sources in the sources list. Args: incident (dict): The incident to check sources_list (list): The list of sources from the customer Returns: bool....
bigcode/self-oss-instruct-sc2-concepts
def custom_sort(str_list, alphabet): """ Sort a list of strings by a specified alphabetical order. Params ------ str_list: list[str] List of strings to be sorted. alphabet: str Case sensitive alphabetical order for sort. Returns ------- Sorted list[str] acco...
bigcode/self-oss-instruct-sc2-concepts
def check_compatibility(selected_usb_size: int, iso_rec_size: str) -> bool: """ Function to test whether or not the usb is large enough for selected ISO :param:string: selected_usb_size pointer to selected usb device size :param:int: iso_rec_size recommended size selected ISO needs :return: true if ...
bigcode/self-oss-instruct-sc2-concepts
def chart_title(statistic, chat, start_date, end_date): """Return title for chart displaying statistic (given as string).""" return '{statistic} in "{subject}" ({start_date} - {end_date})'.format( statistic=statistic, subject=chat.subject, start_date=start_date.Format('%d/%m/%Y'), ...
bigcode/self-oss-instruct-sc2-concepts
def greatest_common_divisor(a, b): """[ Summary: Returns the largest number which divides integers 'a' and 'b'. If 'b' is equal to 0 then 'a' is returned. Arguments calculated as absolute value. Implements Euclid's algorithm; https://en.wikipedia.org/wiki/Euclidean_algorithm#Implementations]...
bigcode/self-oss-instruct-sc2-concepts
def find_base_style(masters): """Find a base style shared between all masters. Return empty string if none is found. """ if not masters: return "" base_style = (masters[0].name or "").split() for master in masters: style = master.name.split() base_style = [s for s in styl...
bigcode/self-oss-instruct-sc2-concepts
def isalphadigit_(s): """ Return ``True`` if ``s`` is a non-empty string of alphabetic characters or a non-empty string of digits or just a single ``_`` EXAMPLES:: sage: from sage.repl.preparse import isalphadigit_ sage: isalphadigit_('abc') True sage: isalphadigit_('12...
bigcode/self-oss-instruct-sc2-concepts
def is_music(f): """ returns if path, f, is a music file """ music_exts = ['mp3','flac','wav','ogg','wma','aiff','aac','ra','dsd','dsf'] return f.split('.')[-1] in music_exts
bigcode/self-oss-instruct-sc2-concepts
def _get_paths(config_dict): """Return a list of all paths referenced by the config dict.""" return_list = [ config_dict["diag_table"], config_dict["data_table"], config_dict["forcing"], config_dict["initial_conditions"], ] patch_files = config_dict.get("patch_files", [])...
bigcode/self-oss-instruct-sc2-concepts
def df_has_data(data) -> bool: """Return True if `data` DataFrame has data.""" return data is not None and not data.empty
bigcode/self-oss-instruct-sc2-concepts
def get_shap_values(model_manager, direct_id, target=None): """Get the SHAP values of features. Args: model_manager: ModelManager, an object containing all prediction models direct_id: the identifier of the patient's related entry in the target entity (e.g., the admission id). ...
bigcode/self-oss-instruct-sc2-concepts
import torch def cross_entropy(log_probs, classes, reduce='mean'): """ Computes the categorical cross-entropy loss. Args: log_probs: tensor, shape(n_samples, n_classes) log probabilities over possible classes for each sample. classes: tensor of int, shape(n_classes) ...
bigcode/self-oss-instruct-sc2-concepts
def to_float(value): """Transforms the Crystal-specific float notation into a floating point number. """ base, exponent = value.split("**") base = int(base) exponent = int("".join(exponent.split())) return pow(base, exponent)
bigcode/self-oss-instruct-sc2-concepts
def get_cmd(chk): """ Assemble the correct "packet-tracer" command based on the "proto" value. TCP/UDP use source/destination ports, ICMP uses type/code, and other protocols use neither. Returns a valid "packet-tracker" command that can be issued to an ASA without further modification. """ ...
bigcode/self-oss-instruct-sc2-concepts
def corr_naam(name): """convert name used in program to model name and back Note: all names must be unique! """ names = (("techtaak", 'techtask'), ("programma", 'procproc')) for name1, name2 in names: if name == name1: return name2 if name == name2: return na...
bigcode/self-oss-instruct-sc2-concepts
def no_nulls_test(df): """Checks that all elements are not null""" return df.isnull().values.sum() == 0
bigcode/self-oss-instruct-sc2-concepts
from typing import Callable from typing import Dict import inspect def get_input_type_dict(func: Callable) -> Dict[str, type]: """ Returns a dict like {argname: type} for given function inputs Examples: >>> @dataclass >>> class Base: >>> ... >>> @dataclass >>> c...
bigcode/self-oss-instruct-sc2-concepts
def polynomial(coefficients): """ Create a polynomial from the given list of coefficients. For example, if the coefficients are [1, 0, 3, 5], then the polynomial returned is P(t) = t^3 + 3t + 5 If the coefficients are [3, 2, -2, 9, 4, 0, 1, 0], then the polynomial returned is P(t) = 3t^7 + 2t^6 - 2t^5 + 9t^...
bigcode/self-oss-instruct-sc2-concepts
import copy def regularize(l): """ If necessary mix in a small prior for regularization. """ epsilon=1e-3 l=copy.copy(l) for i in range(0,len(l)): if l[i]==0: l[i]=epsilon return l
bigcode/self-oss-instruct-sc2-concepts
def get_dim(edgelist): """Given an adjacency list for a graph, returns the number of nodes in the graph. """ node_dict = {} node_count = 0 for edge in edgelist: p, q = edge[ :2] if p not in node_dict: node_dict[p] = True node_count += 1 if q not in...
bigcode/self-oss-instruct-sc2-concepts
async def root(): """Basic Hello World.""" return {"message": "Hello Hello World"}
bigcode/self-oss-instruct-sc2-concepts
import math def angle_on_plane(plane, vec1, vec2): """ Return the angle between two vectors projected onto a plane. """ plane.normalize() vec1 = vec1 - (plane * (vec1.dot(plane))) vec2 = vec2 - (plane * (vec2.dot(plane))) vec1.normalize() vec2.normalize() # Determine the angle ang...
bigcode/self-oss-instruct-sc2-concepts
import socket def target_encrypted(target_ip: str) -> bool: """ Checks if the target is using encryption :param target_ip: Target IP running the server :type target_ip: str :return: True or false :rtype: bool """ s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect((tar...
bigcode/self-oss-instruct-sc2-concepts
def binboolflip(item): """ Convert 0 or 1 to False or True (or vice versa). The converter works as follows: - 0 > False - False > 0 - 1 > True - True > 1 :type item: integer or boolean :param item: The item to convert. >>> binboolflip(0) False >>> binboolflip(False) ...
bigcode/self-oss-instruct-sc2-concepts
def get_way_points(relation): """ Get way points of OSM relation. @param relation: OSM relation as dictionary. @return: List of way points (OSM node ids). >>> relation_id = 660162 >>> relation = get_relation_by_id(relation_id) >>> way_points = get_way_points(relation) """ return [...
bigcode/self-oss-instruct-sc2-concepts
import string def strip_punctuation(headline): """ Remove all punctuation from a headline to return only the words. :param headline: raw headline :return: parsed headline """ table = headline.maketrans({key: None for key in string.punctuation}) headline = headline.translate(table) ret...
bigcode/self-oss-instruct-sc2-concepts
def select_scan_no_qc(scans_meta): """Select a scan from available scans in case there is not an available QC. Args: scans_meta: DataFrame containing the metadata for images to choose among Returns: DataFrame row containing selected scan """ # We choose the first scan (not containi...
bigcode/self-oss-instruct-sc2-concepts
def pad_sentence(sentence, window_len, lsl, rsl, mask): """ :param sentence: Sentence to pad :param window_len: The ammount of tokens in the desired sentence :param lsl: (left-side length) The current token count to the left of the central token :param rsl: (right-side length) The current token coun...
bigcode/self-oss-instruct-sc2-concepts
def create_file(repo, path, message, content): """Create a file in a github repository using Github's content create API: https://developer.github.com/v3/repos/contents/#create-a-file Will create the file at the specified path under a given repo and use the provided commit message. Content should be ...
bigcode/self-oss-instruct-sc2-concepts
def get_published_branch_id(database): """Return the IDs of the published-branch courses.""" collection = 'modulestore.active_versions' projection = {'versions.published-branch': 1, '_id': 0} cursor = database[collection].find({}, projection) published_branch_ids = [] for result in cursor: ...
bigcode/self-oss-instruct-sc2-concepts
def longest_consecutive_sequence(seq: str, char: str) -> int: """Return length of the longest consecutive sequence of `char` characters in string `seq`.""" assert len(char) == 1 longest = 0 current_streak = 0 for c in seq: if c == char: current_streak += 1 else: ...
bigcode/self-oss-instruct-sc2-concepts
def status(category, values, suffix=""): """Return status in human-readable format.""" size = len(values) pluralization = "" if size == 1 else "s" return "* Found {} {}{} {}.".format(size, category, pluralization, suffix)
bigcode/self-oss-instruct-sc2-concepts
def index_to_alg(cnt): """ Convert a bit index to algebraic notation """ column = "abcdefgh" [int(cnt % 8)] rank = "12345678" [int(cnt // 8)] return column + rank
bigcode/self-oss-instruct-sc2-concepts
import csv def get_file_entry_names(path): """Get the names of all entries in the food dictionary or a log file. :param path: A string of the food dictionary or log file pathname. :returns: A list of the entry names associated with each entry in the food dictionary or a log file. """ entry_names...
bigcode/self-oss-instruct-sc2-concepts
def pair_distance(cluster_list, idx1, idx2): """ Helper function that computes Euclidean distance between two clusters in a list Input: cluster_list is list of clusters, idx1 and idx2 are integer indices for two clusters Output: tuple (dist, idx1, idx2) where dist is distance between cluster_l...
bigcode/self-oss-instruct-sc2-concepts
def cropRect(rect, cropTop, cropBottom, cropLeft, cropRight): """ Crops a rectangle by the specified number of pixels on each side. The input rectangle and return value are both a tuple of (x,y,w,h). """ # Unpack the rectangle x, y, w, h = rect # Crop by the specified value x += cropLeft y += cropTop w ...
bigcode/self-oss-instruct-sc2-concepts
def Rels_attach(self, rel): """ Inserts *rel* into *self*, performing additional necessary bindings. Return value: *rel.target_part* (or *rel.target_ref*, if *rel.is_external*). """ self[rel.rId] = rel if rel.is_external: return rel.target_ref target = rel.target_part self._target_parts_by_rId[rel...
bigcode/self-oss-instruct-sc2-concepts
def get_columns_to_drop(year): """ Returns a list of strings indicating which columns to drop for the data in the given year :param year: the year of the data :return: a list of which columns to drop for the given year; "us" is always dropped """ cols_to_drop = ["us"] # Always drop "us"...
bigcode/self-oss-instruct-sc2-concepts
from typing import Any def is_chars(obj: Any) -> bool: """Check if an object is one of the built-in character types. The built-in data types representing characters in Python 3 are: str, bytes, bytearray Arguments: obj: object to be checked Returns: True if the object is an ...
bigcode/self-oss-instruct-sc2-concepts
def is_top_down(lines): """ Return `True` if dates in the given lines go in an ascending order, or `False` if they go in a descending order. If no order can be determined, return `None`. The given `lines` must be a list of lines, ie. :class:`~taxi.timesheet.lines.TextLine`, :class:`taxi.timesheet.lines....
bigcode/self-oss-instruct-sc2-concepts
def _get_quote_indices(line, escaped): """ Provides the indices of the next two quotes in the given content. :param str line: content to be parsed :param bool escaped: unescapes the string :returns: **tuple** of two ints, indices being -1 if a quote doesn't exist """ indices, quote_index = [], -1 fo...
bigcode/self-oss-instruct-sc2-concepts
import random import itertools def random_tuple_list(lst1, lst2, lb=1): """ Generate a random list of tuples (x,y) where x is in lst1 and y is in lst2 """ len_lst1 = len(lst1) len_lst2 = len(lst2) k = random.randint(lb,max(len_lst1,len_lst2)) return random.sample(list(itertools.product...
bigcode/self-oss-instruct-sc2-concepts
def create_email_field_dict(field_name, field_type, field_value, field_displayed_text, is_allow_create_indicator, is_href, is_editable, ...
bigcode/self-oss-instruct-sc2-concepts
def inflate(size, margin, mul=1): """ Increase size (a size or rect) by mul multiples of margin margin's items are interpreted as those of a CSS margin. If size is a 4-tuple, its "sides" are moved outwards by the corresponding items of margin; if it is a 2-tuple, it is treated as if it were a rect ...
bigcode/self-oss-instruct-sc2-concepts
from typing import TextIO import csv def parse_chanjo_sexcheck(handle: TextIO): """Parse Chanjo sex-check output.""" samples = csv.DictReader(handle, delimiter='\t') for sample in samples: return { 'predicted_sex': sample['sex'], 'x_coverage': float(sample['#X_coverage']), ...
bigcode/self-oss-instruct-sc2-concepts
import socket def bind(port, socket_type, socket_proto): """Try to bind to a socket of the specified type, protocol, and port. This is primarily a helper function for PickUnusedPort, used to see if a particular port number is available. For the port to be considered available, the kernel must support ...
bigcode/self-oss-instruct-sc2-concepts
def count_occurances(comment, word): """ A helper function to get the number of words in a comment. """ comment = comment.replace('?', ' ') comment = comment.replace('.', ' ') comment = comment.replace('-', ' ') comment = comment.replace('/', ' ') a = comment.split(" ") count = 0 ...
bigcode/self-oss-instruct-sc2-concepts
import random def choose_random_elements(_list, num_elements=5000): """ Choose a certain number of elements from given list randomly and return the original list without the chosen elements as well as a list of the chosen elements. :param _list: list with elements to be chosen from :param num_...
bigcode/self-oss-instruct-sc2-concepts
import json def get_secret_dict(service_client, arn, stage, token=None): """Gets the secret dictionary corresponding for the secret arn, stage, and token This helper function gets credentials for the arn and stage passed in and returns the dictionary by parsing the JSON string Args: service_clie...
bigcode/self-oss-instruct-sc2-concepts
def assertVolumesEqual(test, first, second): """ Assert that two filesystems have the same contents. :param TestCase test: A ``TestCase`` that will be the context for this operation. :param Volume first: First volume. :param Volume second: Second volume. """ first = first.get_filesy...
bigcode/self-oss-instruct-sc2-concepts
import pickle def read_pkl(pkl_filename): """Loads pickle file.""" with open(pkl_filename, "rb") as pkl_file: return pickle.load(pkl_file)
bigcode/self-oss-instruct-sc2-concepts
import math def AMS(s, b, br=10.0): """ Approximate Median Significance defined as: AMS = sqrt( 2 { (s + b + b_r) log[1 + (s/(b+b_r))] - s} ) where b_r = 10, b = background, s = signal, log is natural logarithm """ radicand = 2 *( (s+b+br) * math.log (1.0...
bigcode/self-oss-instruct-sc2-concepts
from pathlib import Path def relative_path_for(provided_path: Path, root_path: Path) -> Path: """ Return relative path to root is provided path is on root_path, If not return the provided path Parameters ---------- provided_path : Path absolute or relative path root_path : Path ...
bigcode/self-oss-instruct-sc2-concepts