seed
stringlengths
1
14k
source
stringclasses
2 values
def get_ray_num(file_path): """ extract the ray's number from it's file name Parameters: file_path : string: full path to ray file Returns: num :string : the number corresponding to the ray """ filename = file_path.split('/')[-1] num = filename[3:-3] return num
bigcode/self-oss-instruct-sc2-concepts
def stats_file_keys(gene_number): """Return fiels in stats file, ordered, as a list of string""" return [ 'popsize', 'genenumber', 'generationnumber', 'diversity', ] + ['viabilityratio' + str(i) for i in range(gene_number) ] + ['viabilityratioDB'...
bigcode/self-oss-instruct-sc2-concepts
def knight_amount(board_state, player): """ Returns amount of knights the player has """ board = board_state knight_amt = 0 for row in board: for column in row: if player == 1 and column == "k": knight_amt += 1 elif player == 0 and column == "K": ...
bigcode/self-oss-instruct-sc2-concepts
def enum(**named_values): """Creates an enum type.""" return type('Enum', (), named_values)
bigcode/self-oss-instruct-sc2-concepts
def assign_pre_id_to_inner_nodes(phylo_tree): """ Replace the name of the inner nodes of a given phylogenetic tree with its preorder number in the tree. """ idx = 0 for node in phylo_tree.find_clades(terminal=False, order='preorder'): node.name = '%d' % (idx) idx += 1 ...
bigcode/self-oss-instruct-sc2-concepts
def get_column_names(path_to_test, key_to_infer): """ Get a list containing the names of the columns in your table minus the column that you want to infer. =Parameters= path_to_test: Path where your test.csv is saved. key_to_infer: The name of the column that you want to infer. """ with ...
bigcode/self-oss-instruct-sc2-concepts
def list_of_lists_to_md_table(rows): """Convert a list (rows) of lists (columns) to a Markdown table. The last (right-most) column will not have any trailing whitespace so that it wraps as cleanly as possible. Based on solution provided by antak in http://stackoverflow.com/a/12065663 CC-BY-SA 4.0 ...
bigcode/self-oss-instruct-sc2-concepts
def read_lines(file_path): """ Read lines from the file and return then as a list. """ lines = [] with open(file_path, 'r', encoding='utf8') as asm_file: lines = asm_file.readlines() return lines
bigcode/self-oss-instruct-sc2-concepts
import random def between(min_wait, max_wait): """ Returns a function that will return a random number between min_wait and max_wait. Example:: class MyUser(User): # wait between 3.0 and 10.5 seconds after each task wait_time = between(3.0, 10.5) """ return lambda...
bigcode/self-oss-instruct-sc2-concepts
def _recolumn(tmy3_dataframe): """ Rename the columns of the TMY3 DataFrame. Parameters ---------- tmy3_dataframe : DataFrame inplace : bool passed to DataFrame.rename() Returns ------- Recolumned DataFrame. """ # paste in the header as one long line raw_columns...
bigcode/self-oss-instruct-sc2-concepts
def get_insertion_excess(cigar): """Return excess insertions over deletions. Using pysam cigartuples sum all insertions and softclips (operation 1 and 4) minus sum of all deletions (operation 2) """ return sum([l for o, l in cigar if o in [1, 4]]) - sum([l for o, l in cigar if o == 2])
bigcode/self-oss-instruct-sc2-concepts
def merge_pred_gt_boxes(pred_dict, gt_dict=None): """ Merge data from precomputed and ground-truth boxes dictionaries. Args: pred_dict (dict): a dict which maps from `frame_idx` to a list of `boxes` and `labels`. Each `box` is a list of 4 box coordinates. `labels[i]` is a lis...
bigcode/self-oss-instruct-sc2-concepts
def _bop_and(obj1, obj2): """Boolean and.""" return bool(obj1) and bool(obj2)
bigcode/self-oss-instruct-sc2-concepts
def b2h(num, suffix='B'): """Format file sizes as human readable. https://stackoverflow.com/a/1094933 Parameters ---------- num : int The number of bytes. suffix : str, optional (default: 'B') Returns ------- str The human readable file size string. Ex...
bigcode/self-oss-instruct-sc2-concepts
def indent(string_in: str, tabs: int = 0): """Returns the str intended using spaces""" return str(" " * tabs) + string_in
bigcode/self-oss-instruct-sc2-concepts
def no_error_check(func_name, result, func, args): """Nothing special""" return args
bigcode/self-oss-instruct-sc2-concepts
import re def br_with_n(text): """ Replace br with \n """ return re.sub(r'<br.*?>','\n', text, flags=re.IGNORECASE)
bigcode/self-oss-instruct-sc2-concepts
def S_M_to_mS_cm(CTM_S_M): """ Seabird eq: ctm [mS/cm] = ctm [S/m] * 10.0 """ ctm_mS_cm = CTM_S_M * 10.0 return ctm_mS_cm
bigcode/self-oss-instruct-sc2-concepts
import _ast def Dict(keys=(), values=()): """Creates an _ast.Dict node. This represents a dict literal. Args: keys: A list of keys as nodes. Must be the same length as values. values: A list of values as nodes. Must be the same length as values. Raises: ValueError: If len(keys) != len(values). ...
bigcode/self-oss-instruct-sc2-concepts
from datetime import datetime def format_iso_date(d): """ If the parameter is datetime format as iso, otherwise returns the same value """ if type(d) is datetime: return d.isoformat() return d
bigcode/self-oss-instruct-sc2-concepts
def local_scheme(version: str) -> str: # pylint: disable=unused-argument """Skip the local version (eg. +xyz) to upload to Test PyPI""" return ""
bigcode/self-oss-instruct-sc2-concepts
def cmp_dicts(dict1, dict2): """ Returns True if dict2 has all the keys and matching values as dict1. List values are converted to tuples before comparing. """ result = True for key, v1 in dict1.items(): result, v2 = key in dict2, dict2.get(key) if result: v1, v2 = (t...
bigcode/self-oss-instruct-sc2-concepts
def breaklines(s, maxcol=80, after='', before='', strip=True): """ Break lines in a string. Parameters ---------- s : str The string. maxcol : int The maximum number of columns per line. It is not enforced when it is not possible to break the line. Default 80. af...
bigcode/self-oss-instruct-sc2-concepts
def sum_digits(n): """Recursively calculate the sum of the digits of 'n' >>> sum_digits(7) 7 >>> sum_digits(30) 3 >>> sum_digits(228) 12 """ """BEGIN PROBLEM 2.4""" return n % 10 + (0 if n < 10 else sum_digits(n // 10)) """END PROBLEM 2.4"""
bigcode/self-oss-instruct-sc2-concepts
import re def escape(pathname: str) -> str: """Escape all special characters.""" return re.sub(r"([*?[\\])", r"[\1]", pathname)
bigcode/self-oss-instruct-sc2-concepts
import requests from bs4 import BeautifulSoup import re def get_apps_ids(play_store_url): """Scrape play store to gather App IDs. Returns a list of App IDs Keyword arguments: play_store_url -- URL from a Play Store Search :rtype: list """ page = requests.get(play_store_url) soup = Bea...
bigcode/self-oss-instruct-sc2-concepts
import yaml def read_config(path): """ Load the yaml file into a dictionary. """ with open(path) as f: return yaml.load(f, Loader=yaml.FullLoader)
bigcode/self-oss-instruct-sc2-concepts
import re def normalizeName(name): """Transforms a name to deal with common misspellings.""" # Only use the first of several names. oneName = name.split(' ', 1)[0].lower() REPLACEMENTS = [ ['y$', 'a'], # Szczęsny = Szczęsna ['i$', 'a'], # Nowicki = Nowicka ['ę', 'e'], ['ą', 'a'], ['ó', '...
bigcode/self-oss-instruct-sc2-concepts
def join_query_keys(keys): """Helper to join keys to query.""" return ",".join(["\"{}\"".format(key) for key in keys])
bigcode/self-oss-instruct-sc2-concepts
def defaultparse(wordstags, rightbranching=False): """A default parse to generate when parsing fails. :param rightbranching: when True, return a right branching tree with NPs, otherwise return all words under a single constituent 'NOPARSE'. >>> print(defaultparse([('like','X'), ('this','X'), ('example', 'NN'),...
bigcode/self-oss-instruct-sc2-concepts
def string_to_int(string): """ Problem 7.1 convert a string to an integer, without using `int` """ negative = string[0] == '-' if negative: string = string[1:] idx = 0 output = 0 while idx < len(string): low = ord(string[idx]) - ord('0') output = (output * 1...
bigcode/self-oss-instruct-sc2-concepts
def apply_LLD(spectrum, LLD=10): """ Applies a low level discriminator (LLD) to a channel. Parameters: ----------- spectrum : vector The spectrum LLD : int The channel where the low level discriminator is applied Returns: -------- spectrum : vecto...
bigcode/self-oss-instruct-sc2-concepts
def wants_json_resp(request): """ Decide whether the response should be in json format based on the request's accept header. Code taken from: http://flask.pocoo.org/snippets/45/ """ best = request.accept_mimetypes.best_match(['application/json', '...
bigcode/self-oss-instruct-sc2-concepts
def route_business_logic(logicFn): """ Decorates a function to indicate the business logic that should be executed after security checks pass. :param logicFn: The business logic function to assign. :return: The decorated function. """ def decorator(fn): fn.route_business_logic = logicFn...
bigcode/self-oss-instruct-sc2-concepts
def _schema_sql_to_bq_compatibility( schema_dict: dict ) -> dict: """ Convert sql schema to be compatible with the bq ui. Args: schema_dict: column name-sql column type as key-value pairs e.g. {'uid': 'STRING', 'clicks': 'INTEGER'} Returns: schema_dict: column name-sql ...
bigcode/self-oss-instruct-sc2-concepts
def nodes_within_bounds(indices, bounds): """ nodes_within_bounds filters a set of indices to those that are within the bounding box :param indices: a set of indices :param bounds: upper bounds for each axis, implicit minimum at 0 :return: filtered indices within bounds """ filtered = set() ...
bigcode/self-oss-instruct-sc2-concepts
def _GetRegionalGetRequest(client, health_check_ref): """Returns a request for fetching the existing health check.""" return (client.apitools_client.regionHealthChecks, 'Get', client.messages.ComputeRegionHealthChecksGetRequest( healthCheck=health_check_ref.Name(), project=heal...
bigcode/self-oss-instruct-sc2-concepts
import logging def get_logger(name=None): """Return a logger to use""" return logging.getLogger("dandi" + (".%s" % name if name else ""))
bigcode/self-oss-instruct-sc2-concepts
def _divide_if_possible(x, y): """ EXAMPLES:: sage: from sage.combinat.free_module import _divide_if_possible sage: _divide_if_possible(4, 2) 2 sage: _.parent() Integer Ring :: sage: _divide_if_possible(4, 3) Traceback (most recent call last): ...
bigcode/self-oss-instruct-sc2-concepts
def make_progress_bar_text(percentage: float, bar_length: int = 2) -> str: """ Get the progress bar used by seasonal challenges and catalysts and more Translations: "A" -> Empty Emoji "B" -> Empty Emoji with edge "C" -> 1 Quarter Full Emoji "D" -> 2 Quarter Full Emoji ...
bigcode/self-oss-instruct-sc2-concepts
import copy def offset_bonds(bonds, offset): """ Offset all of the numbers in the bonds array by value offset; useful for adding molecules to a system that's already established because the bond arrays start at 0. For a system with N atoms, all indices in the new molecule to be added's bonds ...
bigcode/self-oss-instruct-sc2-concepts
def get_primitive_matrix_by_centring(centring): """Return primitive matrix corresponding to centring.""" if centring == "P": return [[1, 0, 0], [0, 1, 0], [0, 0, 1]] elif centring == "F": return [[0, 1.0 / 2, 1.0 / 2], [1.0 / 2, 0, 1.0 / 2], [1.0 / 2, 1.0 / 2, 0]] elif centring == "I": ...
bigcode/self-oss-instruct-sc2-concepts
def _get_children(heap, idx): """Get the children index-value of the input index.""" length = len(heap) idx_left = 2 * idx + 1 val_left = heap._idx2val(idx_left) if idx_left < length else None idx_right = idx_left + 1 val_right = heap._idx2val(idx_right) if idx_right < length else None retur...
bigcode/self-oss-instruct-sc2-concepts
def load_metadata_for_docs(conn_meta, query, split_metadata=False): """ loads the metadata for documents @param conn_meta: connection to the database which includes PubMed metadata @param query: the query to contain metadata (must project pmid and metadata) @param split_metadata: if true the metadat...
bigcode/self-oss-instruct-sc2-concepts
import getpass def password(name, default=None): """ Grabs hidden (password) input from command line. :param name: prompt text :param default: default value if no input provided. """ prompt = name + (default and ' [%s]' % default or '') prompt += name.endswith('?') and ' ' or ': ' wh...
bigcode/self-oss-instruct-sc2-concepts
def getPatternPercentage(df, column, pattern): """This function counts the number of df[column] which have the given pattern and returns the percentage based on the total number of rows.""" found = df.apply(lambda x: True if(isinstance(x[column], str) and x[column].startswith(pattern)) else False, axis=1).sum() r...
bigcode/self-oss-instruct-sc2-concepts
import tempfile,gzip def gunzip_string(string): """ Gunzip string contents. :param string: a gzipped string :return: a string """ with tempfile.NamedTemporaryFile() as f: f.write(string) f.flush() g = gzip.open(f.name,'rb') return g.read()
bigcode/self-oss-instruct-sc2-concepts
def truncate_latitudes(ds, dp=10, lat_dim="lat"): """ Return provided array with latitudes truncated to specified dp. This is necessary due to precision differences from running forecasts on different systems Parameters ---------- ds : xarray Dataset A dataset with a latitude dimen...
bigcode/self-oss-instruct-sc2-concepts
def RenamePredicate(e, old_name, new_name): """Renames predicate in a syntax tree.""" renames_count = 0 if isinstance(e, dict): if 'predicate_name' in e and e['predicate_name'] == old_name: e['predicate_name'] = new_name renames_count += 1 # Field names are treated as predicate names for funct...
bigcode/self-oss-instruct-sc2-concepts
import pipes def get_command_quoted(command): """Return shell quoted command string.""" return ' '.join(pipes.quote(part) for part in command)
bigcode/self-oss-instruct-sc2-concepts
def divide_into_chunks(array, chunk_size): """Divide a given iterable into pieces of a given size Args: array (list or str or tuple): Subscriptable datatypes (containers) chunk_size (int): Size of each piece (except possibly the last one) Returns: list or str or tuple: ...
bigcode/self-oss-instruct-sc2-concepts
def remove_italics(to_parse: str) -> str: """ A utility function for removing the italic HTML tags. Parameters ---------- to_parse: str The string to be cleaned. Returns ------- str The cleaned string. """ return to_parse.replace("<i>", "").replace("</i>", "")
bigcode/self-oss-instruct-sc2-concepts
def km_to_meters(kilometers): """ >>> km_to_meters(1) 1000.0 >>> km_to_meters(0) 0.0 >>> km_to_meters(-1) Traceback (most recent call last): ValueError: Argument must be not negative >>> km_to_meters([1, 2]) Traceback (most recent call last): TypeError: Invalid argument type ...
bigcode/self-oss-instruct-sc2-concepts
def find_index(to_search, target): """Find the index of a value in a sequence""" for index, value in enumerate(to_search): if value == target: return index return -1
bigcode/self-oss-instruct-sc2-concepts
def get_available_difficulties(metadata_record): """Gets the difficulty levels that are present for a song in a metadata record.""" levels = [] for key, value in metadata_record['metadata']['difficulties'].items(): if value == True or value == 'True': levels.append(key) return levels
bigcode/self-oss-instruct-sc2-concepts
import math def _map_tile_count(map_size: int, lod: int) -> int: """Return the number of map tiles for the given map. Args: map_size (int): The base map size in map units lod (int): The LOD level for which to calculate the tile count Returns: int: The number of tiles in the given...
bigcode/self-oss-instruct-sc2-concepts
from pathlib import Path def delta_path(input_base_path: Path, item_path: Path, output_base_path: Path) -> Path: """ Removes a base path from an item, and appends result to an output path. Parameters ---------- input_base_path : Path The sub Path to be removed from item_path. item_pat...
bigcode/self-oss-instruct-sc2-concepts
def mean_hr_bpm(num_beats, duration): """Average heart rate calculation This is a simple function that converts seconds to minutes and divides the total number of beats found by the total minutes in the strip. :param num_beats: a single integer of the number of total beats in a strip :param durati...
bigcode/self-oss-instruct-sc2-concepts
def is_pdb(datastr): """Detect if `datastr` if a PDB format v3 file.""" assert isinstance(datastr, str), \ f'`datastr` is not str: {type(datastr)} instead' return bool(datastr.count('\nATOM ') > 0)
bigcode/self-oss-instruct-sc2-concepts
def findall(sub, string): """ >>> text = "Allowed Hello Hollow" >>> tuple(findall('ll', text)) (1, 10, 16) """ index = 0 - len(sub) o = [] if not sub in string: return [] while True: try: index = string.index(sub, index + len(sub)) except: ...
bigcode/self-oss-instruct-sc2-concepts
def similar_exact(a, b): """Exact comparison between `a` and `b` strings.""" return a == b
bigcode/self-oss-instruct-sc2-concepts
def make_wget(urls): """Download multiple URLs with `wget` Parameters ---------- urls : list A list of URLs to download from """ return 'wget -c {}'.format(' '.join(urls))
bigcode/self-oss-instruct-sc2-concepts
def text2hex(text): """ Takes in a string text, returns the encoded text in hex.""" hex_string = " ".join(format(ord(x), "x") for x in text) return hex_string
bigcode/self-oss-instruct-sc2-concepts
def isascii(c): """Check if character c is a printable character, TAB, LF, or CR""" try: c = ord(c) # convert string character to decimal representation except TypeError: # it's already an int? (Py3) pass return 32 <= c <= 127 or c in [9, 10, 13]
bigcode/self-oss-instruct-sc2-concepts
def _format_syslog_config(cmd_ret): """ Helper function to format the stdout from the get_syslog_config function. cmd_ret The return dictionary that comes from a cmd.run_all call. """ ret_dict = {"success": cmd_ret["retcode"] == 0} if cmd_ret["retcode"] != 0: ret_dict["message"...
bigcode/self-oss-instruct-sc2-concepts
def get_versions(cfmclient): """ Function takes input cfmclient type object to authenticate against CFM API and queries versions API to return the version number of the system represented by the CFCMclient object Current supported params are :param cfmclient: object of type CFMClient :return: l...
bigcode/self-oss-instruct-sc2-concepts
import re def matching_segment_range(segments, regexp, invert=False): """Returns a range object that yields the indices of those segments that match 'regexp' from all segments that are returned by function 'segment_data'. Args: segments (list): List of segments as returned by function ...
bigcode/self-oss-instruct-sc2-concepts
def _is_equal_mne_montage(montage_a, montage_b, verbose="info"): """ compare two mne montages for identity""" # fall through for msgs when verbose=True attrs_a = sorted(montage_a.__dict__.keys()) attrs_b = sorted(montage_b.__dict__.keys()) if not attrs_a == attrs_b: if verbose: ...
bigcode/self-oss-instruct-sc2-concepts
def get_std_color(client, color_type): """Get one of Creo's standard colors. Args: client (obj): creopyson Client. color_type (str): Color type. Valid values: letter, highlight, drawing, background, half_tone, edge_highlight, dimmed, error, warnin...
bigcode/self-oss-instruct-sc2-concepts
import torch def bth2bht(t: torch.Tensor) -> torch.Tensor: """Transpose the 2nd and 3rd dim of a tensor""" return t.transpose(1, 2).contiguous()
bigcode/self-oss-instruct-sc2-concepts
def epoch_span_overlap(span1, span2): """Find the overlap between two epoch spans. Args: span1 (tuple of Time): Range of epochs in increasing order. span2 (tuple of Time): Range of epochs in increasing order. Returns: overlap_range (tuple of Time or None): Overlapping epoch range o...
bigcode/self-oss-instruct-sc2-concepts
def _flatten(obj_to_vars): """ Object section is prefixed to variable names except the `general` section [general] warning = red >> translates to: warning = red [panel] title = white >> translates to: panel_title = white """ all_vars = dict() for obj, vars_ in obj_t...
bigcode/self-oss-instruct-sc2-concepts
from typing import Dict from typing import Any def marker_smoothing_exceptions(all_exceptions: Dict[str, Any], trial_name: str, marker_name: str) -> Dict[str, Any]: """Given all exceptions (all_exceptions) return just the ones for the specified marker (marker_name) and trial (trial_name).""" trial_excepti...
bigcode/self-oss-instruct-sc2-concepts
def clip_point(xmin, ymin, xmax, ymax, x, y): """Clips the point (i.e., determines if the point is in the clip rectangle). Parameters ---------- xmin, ymin, xmax, ymax, x, y : float Returns ------- bool `True`, if the point is inside the clip rectangle; otherwise, `Fals...
bigcode/self-oss-instruct-sc2-concepts
def get_fixed_hyperparams(parser): """ Hyperparameters that remain fixed across all experiments """ parser.add_argument('--pred_logvar_domain', type=bool, default=True) parser.add_argument('--use_l2_sigma_reg', type=bool, default=True) parser.add_argument('--dataset', type=str, default='imagenet_bboxes'...
bigcode/self-oss-instruct-sc2-concepts
from typing import List def get_lower_from_list(upper_array_items: List[str]) -> List[str]: """ Convert a list/tuple objects to lower case character and return it. """ return list(map(lambda x: x.lower(), upper_array_items))
bigcode/self-oss-instruct-sc2-concepts
def format_date(date): """Converts date to string in d. m. Y format.""" return date.strftime('%d. %m. %Y').lower()
bigcode/self-oss-instruct-sc2-concepts
def epsg_string_to_epsg(epsg_string: str) -> int: """From a string of the form 'EPSG:${code}' return the epsg code as a integer Raise a ValueError if the epsg_string cannot be decoded """ epsg_string = epsg_string.lower() epsg_string = epsg_string.strip() epsg_string = epsg_string.replac...
bigcode/self-oss-instruct-sc2-concepts
def sl(c, s, l): """ This accountancy function computes straight line depreciation for an asset purchase for cash with a known life span and salvage value. c = historical cost or price paid (1000) s = the expected salvage proceeds at disposal l = expected useful life of the fixed asset Ex...
bigcode/self-oss-instruct-sc2-concepts
import re def natural_sort(iterable): """Sort an iterable by https://en.wikipedia.org/wiki/Natural_sort_order.""" def _convert(text): return int(text) if text.isdigit() else text.lower() def _alphanum_key(key): return [_convert(c) for c in re.split("([0-9]+)", key)] return sorted(it...
bigcode/self-oss-instruct-sc2-concepts
def std_ver_major_uninst_valid_known(request): """Return a value that is a correctly formatted representation of a known major version number.""" return request.param
bigcode/self-oss-instruct-sc2-concepts
def minimumDeletions(s: str) -> int: """Return minimum number of deletions to make 's' balanced, i.e. no 'b' comes before 'a' in string consisting of just 'a's and 'b's.""" deletions = 0 countOfBs = 0 for c in s: if c == 'a' and countOfBs > 0: # Only need to delete 'b' if it co...
bigcode/self-oss-instruct-sc2-concepts
import copy def dc(o): """ Some of the testing methods modify the datastructure you pass into them. We want to deepcopy each structure so one test doesn't break another. """ return copy.deepcopy(o)
bigcode/self-oss-instruct-sc2-concepts
import re def cleantext(text): """ Custom function to clean enriched text :param text(str): Enriched ytext from Ekstep Content. :returns: Cleaned text. """ replace_char = [ "[", "]", "u'", "None", "Thank you", "-", "(", ")", ...
bigcode/self-oss-instruct-sc2-concepts
def get_after(end_cursor): """ Get the "after" portion of the pagination query """ return 'after: "{}", '.format(end_cursor) if end_cursor else ""
bigcode/self-oss-instruct-sc2-concepts
def _and(queries): """ Returns a query item matching the "and" of all query items. Args: queries (List[str]): A list of query terms to and. Returns: The query string. """ if len(queries) == 1: return queries[0] return f"({' '.join(queries)})"
bigcode/self-oss-instruct-sc2-concepts
def proto_check(proto): """Checks if protocol is TCP or UDP Parameters ---------- proto: int The protocol number in the FCN/CN message Returns ------- The protocol name if TCP/UDP else returns nothing """ # Check for TCP if proto == 6: return 'tcp' # Ch...
bigcode/self-oss-instruct-sc2-concepts
def common_replacements(setting, item): """Maps keys to values from setting and item for replacing string templates. """ return {"$name": setting.lower(), "$setting": setting, "$prettyname": item.py_name, "$doc_str": item.doc_str}
bigcode/self-oss-instruct-sc2-concepts
def loadStopWords(filename) : """ loads a Set of stopwords from a standard file input : file path containing stop words (format expected is one word per line) return : lines : a set of words """ lines = [] with open(filename,"r") as fileHandle: for line in fileHandle.readlines() : line...
bigcode/self-oss-instruct-sc2-concepts
import pkg_resources def get_resource_bytes(path): """ Helper method to get the unicode contents of a resource in this repo. Args: path (str): The path of the resource Returns: unicode: The unicode contents of the resource at the given path """ resource_contents = pkg_resourc...
bigcode/self-oss-instruct-sc2-concepts
def first_match(predicate, list): """ returns the first value of predicate applied to list, which does not return None >>> >>> def return_if_even(x): ... if x % 2 is 0: ... return x ... return None >>> >>> first_match(return_if_even, [1, 3, 4, 7]) 4 ...
bigcode/self-oss-instruct-sc2-concepts
def split_data(msg, expected_fields): """ Helper method. gets a string and number of expected fields in it. Splits the string using protocol's data field delimiter (|#) and validates that there are correct number of fields. Returns: list of fields if all ok. If some error occured, returns None """ count=0 List=...
bigcode/self-oss-instruct-sc2-concepts
def load_synapses_tsv_data(tsv_path): """Load synapse data from tsv. Args: tsv_path (str): path to the tsv synapses data file Returns: list of dicts containing each data for one synapse """ synapses = [] with open(tsv_path, "r", encoding="utf-8") as f: # first line is d...
bigcode/self-oss-instruct-sc2-concepts
import torch def softplus(x): """Alias for torch.nn.functional.softplus""" return torch.nn.functional.softplus(x)
bigcode/self-oss-instruct-sc2-concepts
def _index_name(self, name): """ Generate the name of the object in which to store index records :param name: The name of the table :type name: str :return: A string representation of the full table name :rtype: str """ return '_{}_{}'.format(self._name, name)
bigcode/self-oss-instruct-sc2-concepts
from typing import OrderedDict import torch def transfer_data_to_numpy(data_map: dict) -> dict: """ Transfer tensors in data_map to numpy type. Will recursively walk through inner list, tuple and dict values. Args: data_map (dict): a dictionary which contains tensors to be transferred Return...
bigcode/self-oss-instruct-sc2-concepts
from typing import Dict from typing import Any def time_crop_or_pad_intensity_helper(metadata: Dict[str, Any]) -> float: """ Computes intensity of a transform that consists of temporal cropping or padding. For these types of transforms the intensity is defined as the percentage of video time that has ...
bigcode/self-oss-instruct-sc2-concepts
import pickle def load_pickle(filepath_to_load): """Load pickle file""" with open(filepath_to_load, "rb") as inp: return pickle.load(inp)
bigcode/self-oss-instruct-sc2-concepts
def _flattenText(elem): """ Returns the text in an element and all child elements, with the tags removed. """ text = "" if elem.text is not None: text = elem.text for ch in elem: text += _flattenText(ch) if ch.tail is not None: text += ch.tail return t...
bigcode/self-oss-instruct-sc2-concepts
import math def distance(x1, y1, x2, y2, x0, y0): """Calculate distance from a point x0, y0 to a line defined by x1, y1 and x2, y2""" num = (y2 - y1) * x0 - (x2 - x1) * y0 + x2 * y1 - y2 * x1 den = math.sqrt((y2 - y1) ** 2 + (x2 - x1) ** 2) return float(num) / float(den)
bigcode/self-oss-instruct-sc2-concepts