seed
stringlengths
1
14k
source
stringclasses
2 values
import re def get_read_group(list_of_names): """Extracts the correct group name for the group containing the read_id""" for name in list_of_names: if re.search(r'Read_\d+$', name): return name
bigcode/self-oss-instruct-sc2-concepts
def reloc_exit_patch(patch_data, relocs, start_address): """Relocate a piece of 6502 code to a given starting address.""" patch_data = bytearray(patch_data) for i in relocs: address = patch_data[i] + (patch_data[i + 1] << 8) + start_address patch_data[i] = address & 0xFF patch_data[i...
bigcode/self-oss-instruct-sc2-concepts
def fingerprints_as_string(fingerprints): """ Method to formatting fingerprints list to human readable string value :param fingerprints: fingerprints set as list :type fingerprints: list :return: fingerprints set as string :rtype: str """ all_fingerprints_string = [] # loop all fin...
bigcode/self-oss-instruct-sc2-concepts
import math def haversine(lat1,lon1,lat2,lon2,radius=6371000.0): """ Haversine function, used to calculate the distance between two points on the surface of a sphere. Good approximation for distances between two points on the surface of the Earth if the correct local curvature is used and the points are ...
bigcode/self-oss-instruct-sc2-concepts
def no_blending(rgba, norm_intensities): """Just returns the intensities. Use in hill_shade to just view the calculated intensities""" assert norm_intensities.ndim == 2, "norm_intensities must be 2 dimensional" return norm_intensities
bigcode/self-oss-instruct-sc2-concepts
def feature_fixture(request): """Return an entity wrapper from given fixture name.""" return request.getfixturevalue(request.param)
bigcode/self-oss-instruct-sc2-concepts
def _filter_cols(dataset, seed): """Mapping function. Filter columns for batch. Args: dataset: tf.data.Dataset with several columns. seed: int Returns: dataset: tf.data.Dataset with two columns (X, Y). """ col_y = f'image/sim_{seed}_y/value' return dataset['image/encoded'], dataset[col_y]
bigcode/self-oss-instruct-sc2-concepts
def find_sum(inputs, target): """ given a list of input integers, find the (first) two numbers which sum to the given target, and return them as a 2-tuple. Return None if the sum could not be made. """ for i in inputs: if i < target // 2 + 1: if target - i in inputs: ...
bigcode/self-oss-instruct-sc2-concepts
import inspect def is_static_method(klass, name: str) -> bool: """ Check if the attribute of the passed `klass` is a `@staticmethod`. Arguments: klass: Class object or instance to check for the attribute on. name: Name of the attribute to check for. Returns: `True` if the...
bigcode/self-oss-instruct-sc2-concepts
from typing import Union def astuple(i, argname: Union[str, None]) -> tuple: """ Converts iterables (except strings) into a tuple. :param argname: If string, it's used in the exception raised when `i` not an iterable. If `None`, wraps non-iterables in a single-item tuple, and no exception...
bigcode/self-oss-instruct-sc2-concepts
def ms_to_hours(ms): """Convert milliseconds to hours""" return round(ms / 60.0 / 60.0 / 1000.0, 2)
bigcode/self-oss-instruct-sc2-concepts
def org_add_payload(org_default_payload): """Provide an organization payload for adding a member.""" add_payload = org_default_payload add_payload["action"] = "member_added" return add_payload
bigcode/self-oss-instruct-sc2-concepts
def cchunkify(lines, lang='', limit=2000): """ Creates code block chunks from the given lines. Parameters ---------- lines : `list` of `str` Lines of text to be chunkified. lang : `str`, Optional Language prefix of the code-block. limit : `int`, Optional The maxi...
bigcode/self-oss-instruct-sc2-concepts
def exist_unchecked_leafs(G): """Helper function for hierachical hill climbing. The function determines whether any of the leaf nodes of the graph have the attribute checked set to False. It returns number of leafs for which this is the case. Args: G (nx.DirectedGraph): The directed graph to be...
bigcode/self-oss-instruct-sc2-concepts
def num_edges(graph): """Returns the number of edges in a ProgramGraph.""" return len(graph.edges)
bigcode/self-oss-instruct-sc2-concepts
import tempfile def simple_net_file(num_output): """Make a simple net prototxt, based on test_net.cpp, returning the name of the (temporary) file.""" f = tempfile.NamedTemporaryFile(mode='w+', delete=False) f.write("""name: 'testnet' force_backward: true layer { type: 'DummyData' name: 'data' top...
bigcode/self-oss-instruct-sc2-concepts
import re def get_fortfloat(key, txt, be_case_sensitive=True): """ Matches a fortran compatible specification of a float behind a defined key in a string. :param key: The key to look for :param txt: The string where to search for the key :param be_case_sensitive: An optional boolean whether to sea...
bigcode/self-oss-instruct-sc2-concepts
def option_namespace(name): """ArgumentParser options namespace (prefix of all options).""" return name + "-"
bigcode/self-oss-instruct-sc2-concepts
def is_verb(tok): """ Is this token a verb """ return tok.tag_.startswith('V')
bigcode/self-oss-instruct-sc2-concepts
def get_fuel_required(module_mass: float) -> float: """Get the fuel required for a module. Args: module_mass: module mass Returns: fueld required to take off """ return int(module_mass / 3.0) - 2.0
bigcode/self-oss-instruct-sc2-concepts
def uniq(xs): """Remove duplicates in given list with its order kept. >>> uniq([]) [] >>> uniq([1, 4, 5, 1, 2, 3, 5, 10]) [1, 4, 5, 2, 3, 10] """ acc = xs[:1] for x in xs[1:]: if x not in acc: acc += [x] return acc
bigcode/self-oss-instruct-sc2-concepts
def lang(name, comment_symbol, multistart=None, multiend=None): """ Generate a language entry dictionary, given a name and comment symbol and optional start/end strings for multiline comments. """ result = { "name": name, "comment_symbol": comment_symbol } if multistart is no...
bigcode/self-oss-instruct-sc2-concepts
def listify(item) -> list: """ If given a non-list, encapsulate in a single-element list. """ return item if isinstance(item, list) else [item]
bigcode/self-oss-instruct-sc2-concepts
import copy def copy_original_exchange_id(data): """Copy each exchange id to the field ``original id`` for use in writing ecospold2 files later.""" for ds in data: for exc in ds['exchanges']: exc['original id'] = copy.copy(exc['id']) return data
bigcode/self-oss-instruct-sc2-concepts
def _strip_wmic_response(wmic_resp): """Strip and remove header row (if attribute) or call log (if method).""" return [line.strip() for line in wmic_resp.split('\n') if line.strip() != ''][1:]
bigcode/self-oss-instruct-sc2-concepts
import sympy def render(expr, lhs=""): """ Puts $ at the beginning and end of a latex expression. lhs : if we want to render something like: $x = 3 + 5$, set the left hand side here """ left = "$$" if lhs: left = "$$%s =" % lhs return ''.join([left, sympy.latex(expr), "$$...
bigcode/self-oss-instruct-sc2-concepts
def compress_name(champion_name): """To ensure champion names can be searched for and compared, the names need to be reduced. The process is to remove any characters not in the alphabet (apostrophe, space, etc) and then convert everything to lowercase. Note that reversing this is non-trivial, ther...
bigcode/self-oss-instruct-sc2-concepts
def createDatas(*models): """Call createData() on each Model or GeometryModel in input and return the results in a tuple. If one of the models is None, the corresponding data object in the result is also None. """ return tuple([None if model is None else model.createData() for model in models])
bigcode/self-oss-instruct-sc2-concepts
def _create_source_file(source, tmp_path): """Create a file with the source code.""" directory = tmp_path / "models" directory.mkdir() source_file = directory / "models.py" source_file.write_text(source) return source_file
bigcode/self-oss-instruct-sc2-concepts
def __top_frond_left(dfs_data): """Returns the frond at the top of the LF stack.""" return dfs_data['LF'][-1]
bigcode/self-oss-instruct-sc2-concepts
def link_cmd(path, link): """Returns link creation command.""" return ['ln', '-sfn', path, link]
bigcode/self-oss-instruct-sc2-concepts
import ntpath import posixpath def as_posixpath(location): """ Return a posix-like path using posix path separators (slash or "/") for a `location` path. This converts Windows paths to look like posix paths that Python accepts gracefully on Windows for path handling. """ return location.replac...
bigcode/self-oss-instruct-sc2-concepts
def flag_greens_on_set(func): """Decorator to signal Green's functions are now out of date.""" def setter_wrapper(obj, value): retval = func(obj, value) obj._uptodate = False return retval return setter_wrapper
bigcode/self-oss-instruct-sc2-concepts
def _auth_header(module): """Generate an authentication header from a token.""" token = module.params.get('auth')['access_token'] auth_header = { 'Authorization': 'Bearer {}'.format(token) } return auth_header
bigcode/self-oss-instruct-sc2-concepts
import uuid def _replace_substrings(code, first_char, last_char): """Replace the substrings between first_char and last_char with a unique id. Return the replaced string and a list of replacement tuples: (unique_id, original_substring) """ substrings = [] level = 0 start = -1 for i...
bigcode/self-oss-instruct-sc2-concepts
import re def get_set(srr_rar_block): """ An SRR file can contain re-creation data of different RAR sets. This function tries to pick the basename of such a set. """ n = srr_rar_block.file_name[:-4] match = re.match("(.*)\.part\d*$", n, re.I) if match: return match.group(1) else: return n
bigcode/self-oss-instruct-sc2-concepts
def intersect2D(segment, point): """ Calculates if a ray of x->inf from "point" intersects with the segment segment = [(x1, y1), (x2, y2)] """ x, y = point #print(segment) x1, y1 = segment[0] x2, y2 = segment[1] if (y1<=y and y<y2) or (y2<=y and y<y1): x3 = x2*(y1-y)/(y1...
bigcode/self-oss-instruct-sc2-concepts
def _get_reserved_field(field_id, reserved_fields): """Returns the desired reserved field. Args: field_id: str. The id of the field to retrieve. reserved_fields: list(fields). The reserved fields to search. Returns: The reserved field with the given `field_id`. Raises: ValueError: `field_id` ...
bigcode/self-oss-instruct-sc2-concepts
import math def sigmoid(x): """Sigmoid function f(x)=1/(1+e^(-x)) Args: x: float, input of sigmoid function Returns: y: float, function value """ # for x which is to large, the sigmoid returns 1 if x > 100: return 1.0 # for x which is very small, the sigmoid r...
bigcode/self-oss-instruct-sc2-concepts
def connect_the_dots(pts): """given a list of tag pts, convert the point observations to poly-lines. If there is only one pt, return None, otherwise connect the dots by copying the points and offseting by 1, producing N-1 line segments. Arguments: - `pts`: a list of point observations of the f...
bigcode/self-oss-instruct-sc2-concepts
import base64 def encode_photo(filepath): """ encode photo to text :param filepath: file encoded :return: encoded text """ with open(filepath, mode="rb") as f: return base64.encodebytes(f.read()).decode("utf-8")
bigcode/self-oss-instruct-sc2-concepts
def rotate_list(l): """ Rotate a list of lists :param l: list of lists to rotate :return: """ return list(map(list, zip(*l)))
bigcode/self-oss-instruct-sc2-concepts
def segwit_scriptpubkey(witver, witprog): """Create a segwit locking script for a given witness program (P2WPKH and P2WSH).""" return bytes([witver + 0x50 if witver else 0, len(witprog)] + witprog)
bigcode/self-oss-instruct-sc2-concepts
from typing import Union from typing import List def parse_setup(options: Union[List, str]) -> str: """Convert potentially a list of commands into a single string. This creates a single string with newlines between each element of the list so that they will all run after each other in a bash script. ...
bigcode/self-oss-instruct-sc2-concepts
import unicodedata def is_printable(char: str) -> bool: """ Determines if a chode point is printable/visible when printed. Args: char (str): Input code point. Returns: True if printable, False otherwise. """ letters = ('LC', 'Ll', 'Lm', 'Lo', 'Lt', 'Lu') numbers =...
bigcode/self-oss-instruct-sc2-concepts
def convert_secret_hex_to_bytes(secret): """ Convert a string secret to bytes. """ return int(secret, 16).to_bytes(32, byteorder="big")
bigcode/self-oss-instruct-sc2-concepts
from typing import Counter def count_items(column_list): """ Function count the users. Args: column_list: The data list that is doing to be iterable. Returns: A list with the item types and another list with the count values. """ item_types = [] count_items = [] ...
bigcode/self-oss-instruct-sc2-concepts
def get_brief_description(description): """Get brief description from paragraphs of command description.""" if description: return description[0] else: return 'No description available.'
bigcode/self-oss-instruct-sc2-concepts
def needs_reversal(chain): """ Determine if the chain needs to be reversed. This is to set the chains such that they are in a canonical ordering Parameters ---------- chain : tuple A tuple of elements to treat as a chain Returns ------- needs_flip : bool Whether or...
bigcode/self-oss-instruct-sc2-concepts
def bulleted_list(items, max_count=None, indent=2): """Format a bulleted list of values.""" if max_count is not None and len(items) > max_count: item_list = list(items) items = item_list[: max_count - 1] items.append("...") items.append(item_list[-1]) line_template = (" " * ...
bigcode/self-oss-instruct-sc2-concepts
def _maybe_list_replace(lst, sublist, replacement): """Replace first occurrence of sublist in lst with replacement.""" new_list = [] idx = 0 replaced = False while idx < len(lst): if not replaced and lst[idx:idx + len(sublist)] == sublist: new_list.append(replacement) replaced = True idx...
bigcode/self-oss-instruct-sc2-concepts
def PrintHtml(log): """Prints a log as HTML. Args: log: a Log namedtuple. """ def Tag(tag, cls, value): return '<%s class="%s">%s</%s>' % (tag, cls, value, tag) classes = ['filename', 'date', 'log'] line = ' '.join([Tag('span', cls, value) for cls, value in zip(classes, log)]) print(Tag('div', 'l...
bigcode/self-oss-instruct-sc2-concepts
def get_max_offset_supported(atten): """Get maximum supported offset for given attenuation""" if atten >= 0.1: return (-8, +8) else: return (-2, +2)
bigcode/self-oss-instruct-sc2-concepts
def log_likelihood_from(*, chi_squared: float, noise_normalization: float) -> float: """ Returns the log likelihood of each model data point's fit to the dataset, where: Log Likelihood = -0.5*[Chi_Squared_Term + Noise_Term] (see functions above for these definitions) Parameters ---------- chi_...
bigcode/self-oss-instruct-sc2-concepts
def rename_fields(columns, data): """Replace any column names using a dict of 'old column name': 'new column name' """ return data.rename(columns=columns)
bigcode/self-oss-instruct-sc2-concepts
def _user_is_admin_for(user, org): """ Whether this user is an administrator for the given org """ return org.administrators.filter(pk=user.pk).exists()
bigcode/self-oss-instruct-sc2-concepts
def drive_list(service, parent_id): """ List resources in parent_id """ query = "trashed=false and '%s' in parents" % parent_id response = service.files().list(q=query).execute() if response and 'items' in response and response['items']: return response['items'] return []
bigcode/self-oss-instruct-sc2-concepts
def _new_or_old_field_property(prop, new_field, old_field, old_priority): """ Get the given property on the old field or the new field, with priority given to a field of the user's choosing. Arguments: prop -- a string of the requested property name old_field -- the old field as a Field instance new_fiel...
bigcode/self-oss-instruct-sc2-concepts
import re def sanitize( word: str, chars=['.', ",", "-", "/", "#"], check_mongoengine=True) -> str: """Sanitize a word by removing unwanted characters and lowercase it. Args: word (str): the word to sanitize chars (list): a list of characters to remove check_mo...
bigcode/self-oss-instruct-sc2-concepts
def add_space_to_parentheses(string: str): """ :param string: Must be a string :return: string with space before '(' and after ')' """ return string.replace('(', ' (').replace(')', ') ')
bigcode/self-oss-instruct-sc2-concepts
def cast_type(cls, val, default): """Convert val to cls or return default.""" try: val = cls(val) except Exception: val = default return val
bigcode/self-oss-instruct-sc2-concepts
def is_insertion(row): """Encodes if the indel is an insertion or deletion. Args: row (pandas.Series): reference seq (str) at index 'ref' Returns: is_insertion (int): 0 if insertion, 1 if deletion """ is_insertion = 0 if row["ref"] == "-": is_insertion = 1 ret...
bigcode/self-oss-instruct-sc2-concepts
import textwrap def unindent(text: str) -> str: """Remove indentation from text""" return textwrap.dedent(text).strip()
bigcode/self-oss-instruct-sc2-concepts
def get_error_res(eval_id): """Creates a default error response based on the policy_evaluation_result structure Parameters: eval_id (String): Unique identifier for evaluation policy Returns: PolicyEvalResultStructure object: with the error state with the given id """ return { ...
bigcode/self-oss-instruct-sc2-concepts
import string import random def gen_random_string(n=24): """Returns a random n-length string, suitable for a password or random secret""" # RFC 3986 section 2.3. unreserved characters (no special escapes required) char_set = string.ascii_letters + string.digits + "-._~" return "".join(random.choices(...
bigcode/self-oss-instruct-sc2-concepts
def query_adapter(interface, request, context=None, view=None, name=''): """Registry adapter lookup helper If view is provided, this function is trying to find a multi-adapter to given interface for request, context and view; if not found, the lookup is done for request and context, and finally only fo...
bigcode/self-oss-instruct-sc2-concepts
from typing import Optional def _rename_list( list1: list[str], method: str, list2: Optional[list[str]] = None ) -> list[str]: """Renames multiple list items following different methods. Method can be "consecutive" to rename identical consecutive items with increasing number or "fuse" to fuse with th...
bigcode/self-oss-instruct-sc2-concepts
def ping(request): """ Simple resource to check that server is up. """ return 'pong'
bigcode/self-oss-instruct-sc2-concepts
def null_count(df): """This functions returns the number of null values in a Dataframe""" NullSum = df.isnull().sum().sum() return NullSum
bigcode/self-oss-instruct-sc2-concepts
def type_factor(NT, NP, SC=30.0): """ NT - Number of planet types in area NP - Number of planets in area SC - a number used to scale how bad it is to differ from the optimal number of planet types. Lower number means less bad Returns a number between 0.0 and 1.0 indicating how good the rati...
bigcode/self-oss-instruct-sc2-concepts
def compute_long_chain(number): """Compute a long chain Arguments: number {int} -- Requested number for which to compute the cube Returns: int -- Value of the cube/long chain for the given number """ return number * number * number
bigcode/self-oss-instruct-sc2-concepts
def get_markers_to_contigs(marker_sets, contigs): """Get marker to contig mapping :param marker_sets: Marker sets from CheckM :type marker_sets: set :param contigs: Contig to marker mapping :type contigs: dict :return: Marker to contigs list mapping :rtype: dict """ marker2contigs =...
bigcode/self-oss-instruct-sc2-concepts
def _IsAnomalyInRef(change_point, ref_change_points): """Checks if anomalies are detected in both ref and non ref build. Args: change_point: A find_change_points.ChangePoint object to check. ref_change_points: List of find_change_points.ChangePoint objects found for a ref build series. Returns: ...
bigcode/self-oss-instruct-sc2-concepts
def _sum(op1, op2): """Sum of two operators, allowing for one of them to be None.""" if op1 is None: return op2 elif op2 is None: return op1 else: return op1 + op2
bigcode/self-oss-instruct-sc2-concepts
def eyr_valid(passport): """ Check that eyr is valid eyr (Expiration Year) - four digits; at least 2020 and at most 2030. :param passport: passport :return: boolean """ return len(passport['eyr']) == 4 and 2020 <= int(passport['eyr']) <= 2030
bigcode/self-oss-instruct-sc2-concepts
def ParseWorkflow(args): """Get and validate workflow from the args.""" return args.CONCEPTS.workflow.Parse()
bigcode/self-oss-instruct-sc2-concepts
def file_to_ints(input_file): """ Input: A file containing one number per line Output: An int iterable Blank lines and lines starting with '#' are ignored """ ints = [] with open(input_file) as f: for line in f.readlines(): line = line.strip() if line and not ...
bigcode/self-oss-instruct-sc2-concepts
def feature_to_tpm_dict(feature_to_read_count, feature_to_feature_length): """Calculate TPM values for feature feature_to_read_count: dictionary linking features to read counts (float) feature_to_feature_length: dictionary linking features to feature lengths (float) Return value: dictionary linking fe...
bigcode/self-oss-instruct-sc2-concepts
def remove_stopwords(texts, stop_words): """ Parameters: - `texts` a list of documents - `stop_words` a list of words to be removed from each document in `texts` Returns: a list of documents that does not contain any element of `stop_words` """ return [[w...
bigcode/self-oss-instruct-sc2-concepts
def get_mapping_pfts(mapping): """Get all PFT names from the mapping.""" pft_names = set() for value in mapping.values(): pft_names.update(value["pfts"]) return sorted(pft_names)
bigcode/self-oss-instruct-sc2-concepts
def encode(token): """Escape special characters in a token for path representation. :param str token: The token to encode :return: The encoded string :rtype: str """ return token.replace('\\', '\\\\').replace('/', '\\/')
bigcode/self-oss-instruct-sc2-concepts
def build_window_title(paused: bool, current_file) -> str: """ Returns a neatly formatted window title. :param bool paused: whether the VM is currently paused :param current_file: the name of the file to display :return str: a neatly formatted window title """ return f"EightDAD {'(PAUSED)' ...
bigcode/self-oss-instruct-sc2-concepts
def mph_to_kph(mph): """Convert mph to kph.""" return mph * 1.609
bigcode/self-oss-instruct-sc2-concepts
def sort_hand(hand, deck): """Returns a hand of cards sorted in the index order of the given deck""" sorted_hand = [] for i in deck: for card in hand: if i == card: sorted_hand.append(card) return sorted_hand
bigcode/self-oss-instruct-sc2-concepts
def get_read_count_type(line): """ Return the count number and read type from the log line """ data = line.rstrip().split(":") count = data[-1].strip() type = data[-3].lstrip().rstrip() return count, type
bigcode/self-oss-instruct-sc2-concepts
def read_text_file(path_to_file): """ Read a text file and import each line as an item in a list. * path_to_file: the path to a text file. """ with open(path_to_file) as f: lines = [line.rstrip() for line in f] return lines
bigcode/self-oss-instruct-sc2-concepts
import requests def load_text_lines_from_url(url): """Load lines of text from `url`.""" try: response = requests.get(url) response.raise_for_status() content = response.text.split("\n") return [x.strip() for x in content if len(x.strip()) > 0] except requests.RequestExcepti...
bigcode/self-oss-instruct-sc2-concepts
def x10(S: str, n: int): """change float to int by *10**n Args: S (str): float n (int, optional): n of float(S)*10**n (number of shift). Returns: int: S*10**n """ if "." not in S: return int(S) * 10**n return int("".join([S.replace(".", ""), "0" * (n - S[::-1].f...
bigcode/self-oss-instruct-sc2-concepts
def inverter_elementos(iteravel): """ Inverte os elementos dentro de um tuplo. :param iteravel: tuplo :return: tuplo Exemplo: >>> tpl = ("a1", "b3") >>> inverter_elementos(tpl) ("1a", "3b") """ res = () for e in iteravel: res += (e[::-1],) return res
bigcode/self-oss-instruct-sc2-concepts
def scrapeints(string): """Extract a series of integers from a string. Slow but robust. readints('[124, 56|abcdsfad4589.2]') will return: [124, 56, 4589, 2] """ # 2012-08-28 16:19 IJMC: Created numbers = [] nchar = len(string) thisnumber = '' for n, char in enumerate(string)...
bigcode/self-oss-instruct-sc2-concepts
def vm_ready_based_on_state(state): """Return True if the state is one where we can communicate with it (scp/ssh, etc.) """ if state in ["started", "powered on", "running", "unpaused"]: return True return False
bigcode/self-oss-instruct-sc2-concepts
def get_utm_zone(lat,lon): """A function to grab the UTM zone number for any lat/lon location """ zone_str = str(int((lon + 180)/6) + 1) if ((lat>=56.) & (lat<64.) & (lon >=3.) & (lon <12.)): zone_str = '32' elif ((lat >= 72.) & (lat <84.)): if ((lon >=0.) & (lon<9.)): z...
bigcode/self-oss-instruct-sc2-concepts
def counters(stats): """ Count all_sentences all_questions all_questions_with_ans & all_corrects :param stats: list(quintet) :rtype int, int, int, int :return: all_sentences, all_questions, all_questions_with_ans, all_corrects """ # Initialization of counters. all_sentences = 0 all_que...
bigcode/self-oss-instruct-sc2-concepts
import torch def define_device(device_name): """ Define the device to use during training and inference. If auto it will detect automatically whether to use cuda or cpu Parameters ---------- device_name : str Either "auto", "cpu" or "cuda" Returns ------- str Eith...
bigcode/self-oss-instruct-sc2-concepts
from collections import Counter def most_common(words, n=10): """ Returnes the most common words in a document Args: words (list): list of words in a document n (int, optional): Top n common words. Defaults to 10. Returns: list: list of Top n common terms """ bow = Co...
bigcode/self-oss-instruct-sc2-concepts
def num_items() -> int: """The number of candidate items to rank""" return 10000
bigcode/self-oss-instruct-sc2-concepts
import json def json_dumps(json_obj, indent=2, sort_keys=True): """Unified (default indent and sort_keys) invocation of json.dumps """ return json.dumps(json_obj, indent=indent, sort_keys=sort_keys)
bigcode/self-oss-instruct-sc2-concepts
def nonSynonCount(t): """ count the number of nonsynon labels in the transcript annotations. """ count = 0 for a in t.annotations: for l in a.labels: if l == 'nonsynon': count += 1 return count
bigcode/self-oss-instruct-sc2-concepts
def _make_socket_path(host: str, display: int, screen: int) -> str: """ Attempt to create a path to a bspwm socket. No attempts are made to ensure its actual existence. The parameters are intentionally identical to the layout of an XDisplay, so you can just unpack one. Parameters: host --...
bigcode/self-oss-instruct-sc2-concepts
def strip_unsupported_schema(base_data, schema): """ Strip keys/columns if not in SCHEMA """ return [ {key: value for key, value in place.items() if key in schema} for place in base_data ]
bigcode/self-oss-instruct-sc2-concepts