seed
stringlengths
1
14k
source
stringclasses
2 values
def listminus(L1, L2): """In : L1 : list or set L2 : list or set Out: List of items in L1 that are not in L2. Helper for min_dfa and bash_1. Implements subtraction (L1 - L2). """ return [x for x in L1 if x not in L2]
bigcode/self-oss-instruct-sc2-concepts
from typing import List from typing import Optional def str_replace(s: str, old: List[str], new: Optional[List[str]] = None) -> str: """Replaces occurences of all strings in *old* by the corresponding ones in *new*. If None is passed in new, *old* are simply removed fromm *s*""" if new is None: new = ['']...
bigcode/self-oss-instruct-sc2-concepts
def precision(cm): """ Return precision. :param cm: Confusion matrix. :return: Value of precision. """ return float(cm[1, 1]) / (cm[1, 1] + cm[0, 1])
bigcode/self-oss-instruct-sc2-concepts
def get_window_g_value(window): """For windows based on SimpleGlazingSystems, returns the g-value. Otherwise, an exception is thrown. """ assert hasattr(window.Type.Layers[0].Material, 'GValue'), \ "SimpleGlazingSystem required" assert len(window.Type.Layers) == 1, "SimpleGlazingSystem requi...
bigcode/self-oss-instruct-sc2-concepts
def crop(image, startX, startY, endX, endY): """ Crop an image :param image: Image to be cropped :param startX: Starting X coord :param startY: Starting Y coord :param endX: Ending X coord :param endY: Ending Y coord :return: Cropped image """ cropped = image[startY:endY, startX...
bigcode/self-oss-instruct-sc2-concepts
from typing import List from typing import Dict def csv_to_list(data: List[List], fields: List[str]) -> List[Dict[str, str]]: """ Converts the raw csv column to a list of dicts with the specified field names """ return list(dict(zip(fields, f)) for f in data if f)
bigcode/self-oss-instruct-sc2-concepts
def tokenise_text_col(df, text_col="text", suffix="_tokens", return_col_name = False): """ wrapper function for a list comprehenshion that tokenises a text column in df, returning df with a new column containing tokenised text Args: df: dataframe with text data text_col: column with tex...
bigcode/self-oss-instruct-sc2-concepts
import requests def download_file(url: str, prefix=""): """Download file by streaming and writing to file. Args: url: download url. prefix: prefix for output file. """ local_filename = url.split("/")[-1] with requests.get(url, stream=True) as r: r.raise_for_status() ...
bigcode/self-oss-instruct-sc2-concepts
import fnmatch def getLabels(source, path): """Get all labels for given path :param source: Labels definition :type path: dict :param path: File full path :type path: string :return: Labels :rtype: list[string] """ result = [] for label, patterns in source.items(): ...
bigcode/self-oss-instruct-sc2-concepts
def stream_element_handler(element_name, usage_restriction = None): """Method decorator generator for decorating stream element handler methods in `StreamFeatureHandler` subclasses. :Parameters: - `element_name`: stream element QName - `usage_restriction`: optional usage restriction: "initi...
bigcode/self-oss-instruct-sc2-concepts
def normalize_host(host): """Normalize a host string.""" return host.lower()
bigcode/self-oss-instruct-sc2-concepts
import json from pathlib import Path def load_test_data(filename: str) -> list: """Utility function to load JSON files from 'test_data'""" json_file_path = ( Path(__file__).parent.joinpath("test_data").joinpath(filename).resolve() ) if not json_file_path.exists(): raise RuntimeError(f...
bigcode/self-oss-instruct-sc2-concepts
def get_selec(tab, selec_tab, name_selec='name', thresh_selec='thresh', op_selec='op', type_selec='type', sel_tag_col='sel'): """ fonction to set a select flag (column) to tab data Parameters --------------- tab: astropy table data to process selec_tab: astropy table tab of selecti...
bigcode/self-oss-instruct-sc2-concepts
def get_pairs(word): """ Return set of symbol pairs in a word. Word is represented as tuple of symbols (symbols being variable-length strings). """ pairs = set() prev_char = word[0] for char in word[1:]: pairs.add((prev_char, char)) prev_char = char pairs = set(pairs) ...
bigcode/self-oss-instruct-sc2-concepts
def make_pure_python(obj): """ Take dict object which can include either dict or numpy scalars or Python scalars, and convert to pure Python. """ if isinstance(obj, dict): for key, val in obj.items(): obj[key] = make_pure_python(val) return obj elif hasattr(obj, 'item...
bigcode/self-oss-instruct-sc2-concepts
def app_config(app_config): """Customize application configuration.""" app_config[ 'FILES_REST_STORAGE_FACTORY'] = 'invenio_s3.s3fs_storage_factory' app_config['S3_ENDPOINT_URL'] = None app_config['S3_ACCESS_KEY_ID'] = 'test' app_config['S3_SECRECT_ACCESS_KEY'] = 'test' return app_config
bigcode/self-oss-instruct-sc2-concepts
def filter_images(piclists): """ Filter the image lists to remove the "False" and "path=None" items :param piclists: A list of list of Picture_infos namedtuple :return: The same lists, but filtered """ for i, piclist in enumerate(piclists): piclist = [j for j in piclist if type(j) != boo...
bigcode/self-oss-instruct-sc2-concepts
from pathlib import Path def get_path_as_str(path: Path) -> str: """ Get the given path as a string. :param path: a Path :return: a str """ return str(path)
bigcode/self-oss-instruct-sc2-concepts
def _build_name_index_tuples(name, index_max): """return list of tuples [(N, 'nameN')] of the size indexMax""" def build_name(tup): return tup[1] + str(tup[0]) names = index_max * [name] names = map(build_name, enumerate(names)) return list(enumerate(names))
bigcode/self-oss-instruct-sc2-concepts
from string import punctuation from unicodedata import category, normalize def standardize(ds): """Remove interpunctuation and whitespaces from a string.""" ss = ''.join(s for s in normalize('NFD', ''.join(ds.split())) if category(s) != 'Mn') manually = (('“', '"'), ('”', '"'), ("(TM)", "...
bigcode/self-oss-instruct-sc2-concepts
from pathlib import Path def ed_append(filename, string): """ appends string to the end of the file. If the file does not exist, a new file is created with the given file name. The function returns the number of characters written to the file. :param filename: file to be manipulated :param str...
bigcode/self-oss-instruct-sc2-concepts
import re def filter_data_genes(counts, filter_genes): """ Filter the input matrix of counts to keep only the genes given as input. :param counts: matrix of counts (genes as columns) :param filter_genes: list of genes to keep :return: the filtered matrix of counts """ genes_to_keep = l...
bigcode/self-oss-instruct-sc2-concepts
def get_next_super_layer(layer_dependency_graph, super_nodes, current_layer): """ Return the immediate next super layer of current layer. :param layer_dependency_graph: dependency graph of the model :param super_nodes: list of all super nodes :param current_layer: the layer whose next super layer n...
bigcode/self-oss-instruct-sc2-concepts
import torch def batchify_image(input): """Promotes the input tensor (an image or a batch of images) to a 4D tensor with three channels, if it is not already. Strips alpha channels if present. """ if input.ndim == 2: input = input[None] if input.ndim == 3: input = input[None] ...
bigcode/self-oss-instruct-sc2-concepts
def is_position_valid(position, password): """Check if position is valid for password.""" return 0 <= position < len(password) and password[position] is None
bigcode/self-oss-instruct-sc2-concepts
import unicodedata def remove_diacritics(raw_text: str) -> str: """ >>> raw_text = "Montréal, über, 12.89, Mère, Françoise, noël, 889, اِس, اُس" >>> remove_diacritics(raw_text) 'Montreal, uber, 12.89, Mere, Francoise, noel, 889, اس, اس' """ nfkd_form = unicodedata.normalize("NFKD", raw_text) ...
bigcode/self-oss-instruct-sc2-concepts
def xl_col_to_name(col, col_abs=False): """Convert a zero indexed column cell reference to a string. Args: col: The cell column. Int. col_abs: Optional flag to make the column absolute. Bool. Returns: Column style string. """ col_num = col if col_num < 0: rais...
bigcode/self-oss-instruct-sc2-concepts
import six import re def check_if_error_message_equal(formatted_msg, unformatted_msg): """ Helper assertion for testing that a formatted error message matches the expected unformatted version of that error. """ # Replace all `{}` style substitutions with `.*` so that we can run a regex # on th...
bigcode/self-oss-instruct-sc2-concepts
import re def check_url_protocol(url): """Ensures a given url has the http:// protocl.""" if re.compile('http://').match(url) == None: url = 'http://' + url return url else: return url
bigcode/self-oss-instruct-sc2-concepts
import re def is_doi(str): """ check if a string is a valid DOI @param str: str to check @type str: str @return: True if DOI @rtype: bool """ doi_regex = re.compile('\\b(10[.][0-9]{4,}(?:[.][0-9]+)*\/(?:(?!["&\'<>])\S)+)\\b') return True if doi_regex.match(str) else False
bigcode/self-oss-instruct-sc2-concepts
def compute_jaccard_similarity_score(x, y): """ Jaccard Similarity J (A,B) = | Intersection (A,B) | / | Union (A,B) | """ intersection_cardinality = len(set(x).intersection(set(y))) union_cardinality = len(set(x).union(set(y))) return intersection_cardinality / float(union_cardinality)
bigcode/self-oss-instruct-sc2-concepts
def format_polygon_line(indiviual_points): """ Given a list of coordinates [lat1, long1, lat2, long2, lat3, long3, ...], create a string with longitude latitude couples separated by commas, and enclosed in parentheses, ex: '(long1 lat1, long2 lat2, long3 lat3, ...)' :param indiviual_points: a list o...
bigcode/self-oss-instruct-sc2-concepts
def get_image_uri(region_name): """Return object detection algorithm image URI for the given AWS region""" account_id = { "us-east-1": "811284229777", "us-east-2": "825641698319", "us-west-2": "433757028032", "eu-west-1": "685385470294", "eu-central-1": "813361260812", ...
bigcode/self-oss-instruct-sc2-concepts
def removeSpacesAndTabs(data): """ Remove all tabs and spaces. >>> removeSpacesAndTabs("a Sting With Spaces") 'aStingWithSpaces' >>> removeSpacesAndTabs("a\tSting\tWith\tTabs") 'aStingWithTabs' """ return data.replace(" ", "").replace("\t", "")
bigcode/self-oss-instruct-sc2-concepts
def sort_string(text: str) -> str: """Sort string punctuation, lowercase and then uppercase.""" return ''.join(sorted([x for x in text], key=str.swapcase))
bigcode/self-oss-instruct-sc2-concepts
def strip_matching(from_str, char): """Strip a char from either side of the string if it occurs on both.""" if not char: return from_str clen = len(char) if from_str.startswith(char) and from_str.endswith(char): return from_str[clen:-clen] return from_str
bigcode/self-oss-instruct-sc2-concepts
def find_all_starts(seq): """Find the starting index of all start codons in a lowercase seq""" # Initialize array of indices of start codons starts = [] # Find index of first start codon (remember, find() returns -1 if not found) i = seq.find('atg') # Keep looking for subsequence incrementing ...
bigcode/self-oss-instruct-sc2-concepts
def ns_to_ms(nanos, rounding=True, decimals=3): """ Converts nanoseconds to milliseconds, with optional rounding. :param nanos: A numeric value of nano seconds :param rounding: Whether to apply rounding (default is 3 decimal places) :param decimals: The amount of decimal places to round to :ret...
bigcode/self-oss-instruct-sc2-concepts
def decompose_valuefmt(valuefmt): """Returns a tuple of string parts extracted from valuefmt, and a tuple of format characters.""" formats = [] parts = valuefmt.split('%') i = 1 while i < len(parts): if parts[i].startswith('s') or parts[i].startswith('d'): formats.append(part...
bigcode/self-oss-instruct-sc2-concepts
import platform def is_linux() -> bool: """ :return: True if running on Linux. False otherwise. """ return platform.system().lower() == 'linux'
bigcode/self-oss-instruct-sc2-concepts
def refractive_index_broadband_vapour(sigma): """ Parameters ---------- sigma : {float, numpy.array}, unit=µm-1 vacuum wavenumber, that is the reciprocal of the vacuum wavelength Returns ------- n_ws : {float, numpy.array} refractive index for standard moist air at sea leve...
bigcode/self-oss-instruct-sc2-concepts
def clean_brackets( string, brackets=(("(", ")"),), ): """Removes matching brackets from the outside of a string Only supports single-character brackets """ while len(string) > 1 and (string[0], string[-1]) in brackets: string = string[1:-1] return string
bigcode/self-oss-instruct-sc2-concepts
def remove_sound_descriptions(subs): """ Removes phrases that are enclosed with square brackets in the subtitles, for example [KNOCKING ON DOOR] :param subs: :return: """ for sub in subs: if '[' in sub.text and ']' in sub.text: t = sub.text sub.text = t[:t.index('...
bigcode/self-oss-instruct-sc2-concepts
def stringOfList(list, sep=" "): """ Convert a list of items to a string of items, separated by sep """ result = "" for it in list: result += sep + str(it) return result
bigcode/self-oss-instruct-sc2-concepts
def get_keys_from_osm_json(osm_json): """ Obtain all keys from queried OSM results, and do not include repeated elements. Parameters ---------- osm_json : JSON Returns ------- List """ osm_keys = [] for element in osm_json['elements']: keys = list(element["tags"].k...
bigcode/self-oss-instruct-sc2-concepts
from typing import List def _reGlue(words: List[str]) -> str: """Helper function to turn a list of words into a string""" ret = "" for i in range(len(words)): ret += words[i] + " " ret = ret.strip() return ret
bigcode/self-oss-instruct-sc2-concepts
from typing import MutableMapping from contextlib import suppress def delete_recursive_dictionary_keys(dct_to_change: MutableMapping, list_of_keys_to_remove: list) -> MutableMapping: """ Removes the specified keys from the specified dict. Args: dct_to_change: Dictionary to modify list_of_k...
bigcode/self-oss-instruct-sc2-concepts
def generate_community_tags_scores(database, community): """ This function generates the most important terms that describe a community of similar documents, alongside their pagerank and in-degree scores. """ # Get all intersecting nodes of the speficied community, # ranked by their in-degree (...
bigcode/self-oss-instruct-sc2-concepts
import re def _remove_assignment_id(s): """Remove the trailing (xxxxx) from a Canvas assignment name.""" return re.sub(r" +\(\d+\)$", "", s)
bigcode/self-oss-instruct-sc2-concepts
from typing import List def find_common_name_for_boxes(boxes: List[str]) -> str: """ A brute-force solution for finding two boxes where the difference in box names is limited to a single character. Returns the common characters in the box names. The algorithm just loops through the boxes and comp...
bigcode/self-oss-instruct-sc2-concepts
import torch def f1_loss(y_true: torch.Tensor, y_pred: torch.Tensor, is_training=False) -> torch.Tensor: """ Calculate F1 score. Can work with gpu tensors FROM https://gist.github.com/SuperShinyEyes/dcc68a08ff8b615442e3bc6a9b55a354 The original implementation is written by Michal Haltuf on Kaggle. ...
bigcode/self-oss-instruct-sc2-concepts
def bounding_box(patches): """ Return the bounding box of the given patches """ mins = [float('inf'), float('inf')] maxs = [-float('inf'), -float('inf')] for patch in patches: shape = patches[patch]['shape'] min_pos = [min(shape.bbox[i], shape.bbox[i + 2]) for i in range(2)] ...
bigcode/self-oss-instruct-sc2-concepts
def distance_between_notes(first_note, second_note): """ returns distance between two notes, as a number of half-tones""" notes = ['C', 'C#', 'D', 'D#', 'E', 'F', 'F#', 'G', 'G#', 'A', 'A#', 'B'] first_index = notes.index(first_note) second_index = notes.index(second_note) distance = second_index - ...
bigcode/self-oss-instruct-sc2-concepts
def is_window_in_area(window, area): """ Checks if a window is within an area. To determine whether a window is within an area it checks if the x and y of the window are within that area. This means a window can "hang out" of an area but still be considered to be in the area. Args: win...
bigcode/self-oss-instruct-sc2-concepts
import re def get_year_from_cmip(filename): """ Given a file name, assuming its a cmip file, return the start and end year """ p = r'\d{6}-\d{6}\.nc' s = re.search(pattern=p, string=filename) if not s: raise ValueError("unable to match file years for {}".format(filename)) start, e...
bigcode/self-oss-instruct-sc2-concepts
import math def _doy_fraction(doy): """Fraction of the DOY in the year (Eq. 50) Parameters ---------- doy : scalar or array_like of shape(M, ) Day of year. Returns ------- array_like DOY fraction [radians]. """ return doy * (2.0 * math.pi / 365)
bigcode/self-oss-instruct-sc2-concepts
def split_grads_by_size(threshold_size, device_grads): """Break gradients into two sets according to tensor size. Args: threshold_size: int size cutoff for small vs large tensor. device_grads: List of lists of (gradient, variable) tuples. The outer list is over devices, the inner list is over indi...
bigcode/self-oss-instruct-sc2-concepts
def module_cache_path(ctx): """Returns the Clang module cache path to use for this rule.""" return ctx.genfiles_dir.path + "/_objc_module_cache"
bigcode/self-oss-instruct-sc2-concepts
def parse_volume_bindings(volumes): """ Parse volumes into a dict. :param volumes: list of strings :return: dict """ def parse_volume(v): if ':' in v: parts = v.split(':') if len(parts) > 2: hp, cp, ro = parts[0], parts[1], parts[2] ...
bigcode/self-oss-instruct-sc2-concepts
def _get_totals_row(slocgroup): """Returns the row for TOTALS.""" totallines = slocgroup.totallines def average(key): total = totallines(key) return total / len(slocgroup.filenamesToSlocInfos) return ['TOTALS', totallines('code'), average('codeperc'), totallines...
bigcode/self-oss-instruct-sc2-concepts
def read_relative_operator_basenames(task): """ Read list of relative operators basenames. Returns: (list) : list of relative operators basenames """ relative_operator_filename = "relative_operators.dat" # read list of unit tensors relative_operator_stream = open(relative_operator_fil...
bigcode/self-oss-instruct-sc2-concepts
from typing import Sequence from typing import List def averaged_knots_constrained( n: int, p: int, t: Sequence[float]) -> List[float]: """ Returns an averaged knot vector from parametrization vector `t` for a constrained B-spline. Args: n: count of control points - 1 p: degree ...
bigcode/self-oss-instruct-sc2-concepts
from typing import Callable from typing import Tuple from typing import Any from typing import Dict from warnings import warn def format_errwarn(func: Callable[[], Tuple[Any, Dict, Dict]]): """ Wraps a function returning some result with dictionaries for errors and warnings, then formats those errors and ...
bigcode/self-oss-instruct-sc2-concepts
def create_fold_names(model_name:str, n_splits=5) -> list: """ List comprehension that creates the folder names. Parameters ---------- `model_name` : `str`\n Model name. `n_splits` : `int`, `optional`\n Number of splits used for kfold cross validation, by default 5 Returns ...
bigcode/self-oss-instruct-sc2-concepts
import logging def parse_time_window(timewindow): """ Args: timewindow (str, optional): time window for plot. Must be in format: 'YYYY-MM-DD:YYYY-MM-DD' Returns: list:str containing starting and ending times """ return_list = [] try: parts = timewindow.split(":") ...
bigcode/self-oss-instruct-sc2-concepts
def ValidJsIdentifier(x): """Returns True if x is valid javascript identifier.""" # This is just an approximation if not x: return False nodash = x.replace('_', 'a') return nodash.isalnum() and nodash[0].isalpha()
bigcode/self-oss-instruct-sc2-concepts
def _SnakeToCamelString(field_name): """Change a snake_case string into a camelCase string. Args: field_name: str, the string to be transformed. Returns: str, the transformed string. """ parts = field_name.split('_') if not parts: return field_name # Handle field_name with leading '_'s by c...
bigcode/self-oss-instruct-sc2-concepts
def _latest_report_info_dir(bucket): """Returns a GCS URL to the latest report info for the given bucket.""" return 'gs://{0}/latest_report_info/'.format(bucket)
bigcode/self-oss-instruct-sc2-concepts
def parse_dir(save_dir): """Parses the save directory to get only the directory (without the file name) to save the pictures to :param save_dir: save directory string :return: save directory string without the file name """ dir_list = save_dir.split('/') dir = '' if len(dir_list) == 1: ...
bigcode/self-oss-instruct-sc2-concepts
def coordinate_of_sequence(sequence): """ ___0__1__2__3__4__ 4| 1 2 3 4 5 3| 6 7 8 9 10 2| 11 12 13 14 15 1| 16 17 18 19 20 0| 21 22 23 24 25 """ y = 4 - ((sequence - 1) // 5) x = (sequence - 1) % 5 return x, y
bigcode/self-oss-instruct-sc2-concepts
def _mod_name_key(typ): """Return a (__module__, __name__) tuple for a type. Used as key in Formatter.deferred_printers. """ module = getattr(typ, '__module__', None) name = getattr(typ, '__name__', None) return (module, name)
bigcode/self-oss-instruct-sc2-concepts
def normalize_query_param(query_param): """Normalize query parameter to lower case""" return query_param.lower() if query_param else None
bigcode/self-oss-instruct-sc2-concepts
def y_n_to_bool(str_arg): """Convert Rinnai YN to Bool""" if str_arg == "Y": return True return False
bigcode/self-oss-instruct-sc2-concepts
def signature_for_type_name(type_name): """Determine the JNI signature for a given single data type. This means a one character representation for primitives, and an L<class name>; representation for classes (including String). """ if type_name == "void": return "V" elif type_name == ...
bigcode/self-oss-instruct-sc2-concepts
import pytz from datetime import datetime def convert_unix_ts(timestamp, timezone = "Europe/Berlin"): """Utility function to help converting flespi utc unix time output to human readable. Parameters: ----------- timestamp: int Unix time generated py flespi platform. timezone: str ...
bigcode/self-oss-instruct-sc2-concepts
import json def dump_args(args: tuple, kwargs: dict) -> str: """Util to make hashable function arguments.""" return json.dumps(args) + json.dumps(kwargs, sort_keys=True)
bigcode/self-oss-instruct-sc2-concepts
import click def _call_in_source(dag, method_name, message, kwargs=None): """ Execute method on each task.source in dag, passing kwargs """ kwargs = kwargs or {} files = [] results = [] for task in dag.values(): try: method = getattr(task.source, method_name) e...
bigcode/self-oss-instruct-sc2-concepts
import itertools def unpack_fields(fields): """ Flattens the given fields object into a flat list of fields. Parameters ---------- fields : (list | dict) List or dict that can contain nested tuples and None as values and column names as keys (dict). Returns ------- li...
bigcode/self-oss-instruct-sc2-concepts
import re def _sanitize_query(query: str) -> str: """ Remove some invalid characters from the query Parameters ---------- query : str A search query to be sanitized Returns ------- str A sanitized query """ query = re.sub(r'\s+', ' ', query) return query
bigcode/self-oss-instruct-sc2-concepts
from typing import Tuple from typing import List def _get_lie_algebra(segment_sign: Tuple[int, int, int], radius: float) -> List[Tuple[float, float, float]]: """ Gets the Lie algebra for an arcline path. :param segment_sign: Tuple of signs for each segment in the arcline path. :pa...
bigcode/self-oss-instruct-sc2-concepts
def rst_link_filter(text, url): """Jinja2 filter creating RST link >>> rst_link_filter("bla", "https://somewhere") "`bla <https://somewhere>`_" """ if url: return "`{} <{}>`_".format(text, url) return text
bigcode/self-oss-instruct-sc2-concepts
def update_show_clade_defining(switches_value): """Update ``show_clade_defining`` variable in dcc.Store. This should be set to True when the clade defining mutations switch is switched on, and False when it is turned off. It is None at application launch. :param switches_value: ``[1]`` if the clad...
bigcode/self-oss-instruct-sc2-concepts
def get_sum(path, tree): """ Returns the sum of all the numbers in the path for the given tree. """ pathsum = 0 for i, row in enumerate(tree): pathsum += row[path[i]] return pathsum
bigcode/self-oss-instruct-sc2-concepts
def hash_shard(word): """Assign data to servers using Python's built-in hash() function.""" return 'server%d' % (hash(word) % 4)
bigcode/self-oss-instruct-sc2-concepts
def push_row(matrix, row): """Pushes row with index row to the bottom of the matrix, and shifts all other rows up""" return [matrix[i] for i in range(len(matrix)) if i != row] + [matrix[row]]
bigcode/self-oss-instruct-sc2-concepts
import collections def are_lists_equal(list1, list2): """ Checks whether two lists are equal (contain exactly the same elements). Using Counter data structure allows duplicates to be considered i.e. [1, 1, 2] != [1, 2]. :param list1: the first list. :param list2: the second list. :return: tru...
bigcode/self-oss-instruct-sc2-concepts
def read_installer(myinstaller, log): """ reads the text of the current installer script and returns it as a string """ log.info(f"Reading current installer from {myinstaller}...") with open(myinstaller, "r") as f: text = f.read() log.info(f"\t=> found {len(text)} characters") return...
bigcode/self-oss-instruct-sc2-concepts
def requires_reload(action, plugins): """ Returns True if ANY of the plugins require a page reload when action is taking place. """ return any(p.get_plugin_class_instance().requires_reload(action) for p in plugins)
bigcode/self-oss-instruct-sc2-concepts
from typing import Union from pathlib import Path def file_variations( filename: Union[str, Path], # The original filename to use as a base. extensions: list, ) -> list: # list of Paths """Create a variation of file names. Generate a list of variations on a filename by replacing the extension with ...
bigcode/self-oss-instruct-sc2-concepts
def compile(self): """Compile TokenNode.""" return "%s" % self.tok
bigcode/self-oss-instruct-sc2-concepts
def to_sorted_subfloats(float_string): """Convert string of floats into sorted list of floats. This function will first remove the "TSH" and turn the string of floats into the list of floats and sort them from smaller to larger. Args: float_string (str): A string begin with "TSH" and followed ...
bigcode/self-oss-instruct-sc2-concepts
def get_hash(example): """Get hash of content field.""" return {"hash": hash(example["content"])}
bigcode/self-oss-instruct-sc2-concepts
def f2odds(f): """Convert fraction B117 to odds ratio B117/other.""" return f/(1-f)
bigcode/self-oss-instruct-sc2-concepts
def scale_between(minval, maxval, numStops): """ Scale a min and max value to equal interval domain with numStops discrete values """ scale = [] if numStops < 2: return [minval, maxval] elif maxval < minval: raise ValueError() else: domain = maxval - minval ...
bigcode/self-oss-instruct-sc2-concepts
def progress_bar_width(p): """Compute progress bar width.""" p = int(p) return 15.0 + p * 0.85
bigcode/self-oss-instruct-sc2-concepts
def binomial_coefficient(n: int, k: int) -> int: """ Since Here we Find the Binomial Coefficient: https://en.wikipedia.org/wiki/Binomial_coefficient C(n,k) = n! / k!(n-k)! :param n: 2 times of Number of nodes :param k: Number of nodes :return: Integer Value >>> binomial_coefficient(4, ...
bigcode/self-oss-instruct-sc2-concepts
def _files(*paths): """Files for PyDoIt (It doesn't allow pathlib2, only str or pathlib).""" return [str(x) for x in paths]
bigcode/self-oss-instruct-sc2-concepts
def read_article(article_location): """ Read article's filtered context. :param article_location: The article's file location. :type article_location: str :return: The context of file. :rtype: str """ article_text = '' with open(article_location, 'r', encoding='utf-8') as file: ...
bigcode/self-oss-instruct-sc2-concepts
def ndim(x): """Returns the number of exes in a tensor, as an integer.""" dims = x.get_shape()._dims if dims is not None: return len(dims) return None
bigcode/self-oss-instruct-sc2-concepts
def _slice(index, i, nneighbors, lim): """ A partir de l'indice `index`, renvoie les `nneighbors` indices suivants dans la dimension `i` (y compris `index`, qui est le premier élément de la liste). Si certains des indices calculés sont supérieurs à `lim` dans la dimension `i`, renvoie une liste...
bigcode/self-oss-instruct-sc2-concepts