seed
stringlengths
1
14k
source
stringclasses
2 values
def deploy_command(deb_package, hostname, username = "pasha"): """Command for start deployment on `target_hosts` of package. Args: deb_package (File): Debian package to install hostname (str): host for installation username (str): SSH user for installation process Returns: ...
bigcode/self-oss-instruct-sc2-concepts
def parameter_values(params, **kwargs): """Return a copy of the parameter list, substituting values from kwargs. Usage example:: params = parameter_values(params, stock='GOOG', days_back=300 ) Any parameters not supplied will keep their original value. """ ...
bigcode/self-oss-instruct-sc2-concepts
def gf_TC(f, K): """ Return trailing coefficient of ``f``. **Examples** >>> from sympy.polys.domains import ZZ >>> from sympy.polys.galoistools import gf_TC >>> gf_TC([3, 0, 1], ZZ) 1 """ if not f: return K.zero else: return f[-1]
bigcode/self-oss-instruct-sc2-concepts
import re def utc_offset_string_to_seconds(utc_offset: str) -> int: """match a UTC offset in format ±[hh]:[mm], ±[h]:[mm], or ±[hh][mm] and return number of seconds offset""" patterns = ["^([+-]?)(\d{1,2}):(\d{2})$", "^([+-]?)(\d{2})(\d{2})$"] for pattern in patterns: match = re.match(pattern, utc...
bigcode/self-oss-instruct-sc2-concepts
def output_to_IOB2_string(output): """ Convert Stanford NER tags to IOB2 tags. """ iob2_tags = [] names = [] previous_tag = 'O' for _, tup in enumerate(output): name, tag = tup if tag != 'O': tag = 'E' if tag == 'O': iob2_tags.append(tag) ...
bigcode/self-oss-instruct-sc2-concepts
import ipaddress def get_networks(cidrs): """Convert a comma-separated list of CIDRs to a list of networks.""" if not cidrs: return [] return [ipaddress.ip_interface(cidr).network for cidr in cidrs.split(",")]
bigcode/self-oss-instruct-sc2-concepts
def release_for_relnote(relnote): """ Turn a release note dict into the data needed by GitHub for a release. """ tag = relnote['version'] return { "tag_name": tag, "name": tag, "body": relnote["text"], "draft": False, "prerelease": relnote["prerelease"], }
bigcode/self-oss-instruct-sc2-concepts
import pytz def localized_datetime(naive_dt, timezone_name='America/Los_Angeles'): """Attaches a timezone to a `naive_dt` """ tz = pytz.timezone(timezone_name) dt = tz.localize(naive_dt) return dt
bigcode/self-oss-instruct-sc2-concepts
import re def parse_time_window(window): """ Parse the specified time window and return as (float) minutes, or None if invalid """ regexps = { '^(\d+):?$': lambda match: float(match.group(1)) * 60, '^(\d+):(\d+)$': lambda match: float(match.group(1)) * 60 + float(match.group(2)), '^:(\...
bigcode/self-oss-instruct-sc2-concepts
def sequence(*decorators): """ Helper method which creates a decorator that applies the given sub-decorators. Decorators are applied in reverse order given. @decorator_sequence(dec_1, dec_2, ...) def function(...): ... is equivalent to: @dec_1 @dec_2 ... def function(....
bigcode/self-oss-instruct-sc2-concepts
def then_by_descending(collection, selector, context): """:yaql:thenByDescending To be used with orderBy or orderByDescending. Uses selector to extract secondary sort key (descending) from the elements of the collection and adds it to the iterator. :signature: collection.thenByDescending(selector)...
bigcode/self-oss-instruct-sc2-concepts
def int_or_string(val: str): """ Loads a value from MO into either an int or string value. String is returned if we can't turn it into an int. """ new_s = val.replace(",", "") try: return float(new_s) except ValueError: return val
bigcode/self-oss-instruct-sc2-concepts
from typing import List def add_jupyter_args(run_args: List[str]) -> List[str]: """ Adds `--ip 0.0.0.0` and `--no-browser` options to run args if those are not there yet. Args: run_args: Existing list of run arguments. Returns: Modified list of run arguments. """ run_args...
bigcode/self-oss-instruct-sc2-concepts
def drop_table_sql(name = "small_peptide"): """Generate an SQL statement for droping a table.""" return f"DROP TABLE IF EXISTS {name};"
bigcode/self-oss-instruct-sc2-concepts
def regularise_periapse_time(raw, period): """ Change the periapse time so it would be between 0 and the period """ res = raw if res < 0: res += period if res > period: res -= period return res
bigcode/self-oss-instruct-sc2-concepts
def get_redundant_feature_pairs(feature_distance_series, threshold): """ Expects results from a `feature_distances` func. Returns redundant feature pairs, as determined by passed `threshold` for inter-feature measurement. """ return feature_distance_series[ feature_distance...
bigcode/self-oss-instruct-sc2-concepts
def _get_join_indices(left_table, right_table, join_conditions): """Given the join conditions, return the indices of the columns used in the join.""" left_indices = [] right_indices = [] for cond in join_conditions: for join_col_name in (cond.left_operand, cond.right_operand): left...
bigcode/self-oss-instruct-sc2-concepts
def trim(s): """Removes whitespace, carriage returns, and new line characters.""" s = s.strip().replace("\n", "").replace("\r", "") return s
bigcode/self-oss-instruct-sc2-concepts
def filter_values(function, dictionary): """Filter ``dictionary`` by its values using ``function``.""" return {k: v for k, v in dictionary.items() if function(v)}
bigcode/self-oss-instruct-sc2-concepts
def intersection(l1, l2): """Return intersection of two lists as a new list:: >>> intersection([1, 2, 3], [2, 3, 4]) [2, 3] >>> intersection([1, 2, 3], [1, 2, 3, 4]) [1, 2, 3] >>> intersection([1, 2, 3], [3, 4]) [3] >>> intersec...
bigcode/self-oss-instruct-sc2-concepts
import re def remove_html_a_element_for_dingtalk(s): """ Replace <a ..>xx</a> to xx and wrap content with <div></div>. """ patt = '<a.*?>(.+?)</a>' def repl(matchobj): return matchobj.group(1) return re.sub(patt, repl, s)
bigcode/self-oss-instruct-sc2-concepts
import re def dist_info_name(distribution, version): """Get the correct name of the .dist-info folder""" escaped_name = re.sub(r"[^\w\d.]+", "_", distribution, flags=re.UNICODE) escaped_version = re.sub(r"[^\w\d.]+", "_", version, flags=re.UNICODE) return '{}-{}.dist-info'.format(escaped_name, escaped...
bigcode/self-oss-instruct-sc2-concepts
def repr2(x): """Analogous to repr(), but will suppress 'u' prefix when repr-ing a unicode string.""" s = repr(x) if len(s) >= 2 and s[0] == "u" and (s[1] == "'" or s[1] == '"'): s = s[1:] return s
bigcode/self-oss-instruct-sc2-concepts
def get_fix_string(input_string: str, length: int): """ Transforms input_string to the string of the size length. Parameters ---------- input_string : str input_string length : int length of output_string, if -1 then output_string is the same as input_string Returns ---...
bigcode/self-oss-instruct-sc2-concepts
def get_elements_of_type(xform, field_type): """ This function returns a list of column names of a specified type """ return [f.get('name') for f in xform.get_survey_elements_of_type(field_type)]
bigcode/self-oss-instruct-sc2-concepts
from typing import Sequence from typing import Tuple from typing import Optional import re def find_token( string: bytes, pos: int, tokens: Sequence[bytes] ) -> Tuple[Optional[bytes], int]: """Find the first occurrence of any of multiple tokens.""" pattern = re.compile(b"|".join(re.escape(token) for token...
bigcode/self-oss-instruct-sc2-concepts
def get_heatmap_y_sample_sizes(parsed_mutations, sample_sizes): """Get sample size y axis values of heatmap cells. :param parsed_mutations: A dictionary containing multiple merged ``get_parsed_gvf_dir`` return "mutations" values. :type parsed_mutations: dict :param sample_sizes: A dictionary co...
bigcode/self-oss-instruct-sc2-concepts
def cloudfront_public_lookup(session, hostname): """ Lookup cloudfront public domain name which has hostname as the origin. Args: session(Session|None) : Boto3 session used to lookup information in AWS If session is None no lookup is performed hostname: name ...
bigcode/self-oss-instruct-sc2-concepts
def check_queue(queue, config): """ Check length and policy of a single queue :param queue: Queue form rabbit :param config: Desired queue state :return: length of a queue and lists of warnings and errors """ warnings = [] errors = [] length = queue['messages_ready'] if length >...
bigcode/self-oss-instruct-sc2-concepts
def news_dict(cleaned_articles): """ For the cleaned_articles data, extract only the headline and summary. :param cleaned_articles: List of dictionaries, extract only the target information. :return: dictionary of Headlines to Summary. """ temp_dict = {} for i in cleaned_articles: te...
bigcode/self-oss-instruct-sc2-concepts
import logging def _create_list_of_class_names(view, label_field): """Create list of class names from the label field. Args: view (voxel51 view object) - the voxel51 dataset label_field (str) - label field set in config Returns: class_names (list) """ logging.info("Extrac...
bigcode/self-oss-instruct-sc2-concepts
def _ResolvePortName(args): """Determine port name if one was not specified.""" if args.port_name: return args.port_name if args.protocol == 'HTTPS': return 'https' if args.protocol == 'SSL': return 'ssl' if args.protocol == 'TCP': return 'tcp' return 'http'
bigcode/self-oss-instruct-sc2-concepts
def check_row(board, num_rows, num_cols): """check if any 4 are connected horizontally(in 1 row) returns bool""" won = False for row in range(num_rows): for col in range(num_cols - 3): start = board[row][col] if start == " ": continue won =...
bigcode/self-oss-instruct-sc2-concepts
def chomp_lines(istream): """ Returns a lazy generator of lines without trailing newline characters from the specified input stream. """ return (line.rstrip('\n\r') for line in istream)
bigcode/self-oss-instruct-sc2-concepts
import math import collections def get_number_of_letter_permutations(permute_word): """ Finds the number of permutations of letters in a given word :param permute_word: a word to find permutations of :return: number of permutations of letters in the word """ # find all letter combinations to g...
bigcode/self-oss-instruct-sc2-concepts
import json def load_hash(filepath): """ Load hashes from json file. Parameters ---------- filepath : str path to json file to be loaded Returns ------- dict { str : dict } """ with open(filepath, "r") as f: return json.load(f)
bigcode/self-oss-instruct-sc2-concepts
def _snake_to_dromedary_case(string): """Convert snake_case to dromedaryCase. >>> _snake_to_dromedary_case('snake_case') 'snakeCase' >>> _snake_to_dromedary_case('longer_snake_case_name') 'longerSnakeCaseName' """ words = string.split("_") if len(words) > 1: words[1:] = [w.title...
bigcode/self-oss-instruct-sc2-concepts
import math def rat_from_rtc(rtc_s): """ Turn a real-time clock value into a radio time value Args: rtc_s: real-time-clock in seconds Returns: rat_s: radio time in seconds rat_t: radio time in ticks """ # Updated assumed RAT tick based on RTC value (magic magic) # ...
bigcode/self-oss-instruct-sc2-concepts
def _translate_keyname(inp): """map key names in settings file to key names in HotKeys """ convert = {'Escape': 'Esc', 'Delete': 'Del', 'Return': 'Enter', 'Page_up': 'PgUp', 'Page_down': 'PgDn', 'NUMPAD_ENTER': 'NumEnter'} if inp in convert: out = convert[inp] else: ou...
bigcode/self-oss-instruct-sc2-concepts
from itertools import zip_longest def grouper(n, iterable, fillvalue=None): """ Split an iterable in groups of max N elements. grouper(3, 'ABCDEFG', 'x') --> ABC DEF Gxx """ args = [iter(iterable)] * n if fillvalue: return zip_longest(fillvalue=fillvalue, *args) for chunk in zip_...
bigcode/self-oss-instruct-sc2-concepts
def andGate(a, b): """ Input: a, b Two 1 bit values as 1/0 Returns: 1 if both incoming bits are 1 otherwise 0 """ if a == 1 and b == 1: return 1 else: return 0
bigcode/self-oss-instruct-sc2-concepts
import torch def select_device() -> str: """Selects the device to use, either CPU (default) or CUDA/GPU; assuming just one GPU.""" return "cuda" if torch.cuda.is_available() else "cpu"
bigcode/self-oss-instruct-sc2-concepts
def _normalize_integer_rgb(value: int) -> int: """ Internal normalization function for clipping integer values into the permitted range (0-255, inclusive). """ return 0 if value < 0 else 255 if value > 255 else value
bigcode/self-oss-instruct-sc2-concepts
def count_descendents(graph, root): """ Inputs: A weighted directed acyclic `graph` with positive edge weights and a starting `root` node Let the weight of a path in the graph be the product of the weights of its constituent edges and 0 if the path is trivial with no edges Returns: The sum of the we...
bigcode/self-oss-instruct-sc2-concepts
import re def applyRegexps(text, listRegExp): """ Applies successively many regexps to a text""" # apply all the rules in the ruleset for element in listRegExp: left = element['left'] right = element['right'] r = re.compile(left) text = r.sub(right, text) return text
bigcode/self-oss-instruct-sc2-concepts
def is_multiple(n, divide): """ >>> is_multiple(0, 1) False >>> is_multiple(10, 1) True >>> is_multiple(10, 2) True >>> is_multiple(10, 3) False """ return (0 != n) and (0 == (n % divide))
bigcode/self-oss-instruct-sc2-concepts
import csv def detect(stream): """Returns True if given stream is valid CSV.""" try: csv.Sniffer().sniff(stream, delimiters=',') return True except (csv.Error, TypeError): return False
bigcode/self-oss-instruct-sc2-concepts
from typing import List def rotate90(buttonsIdx: List[int]) -> List[int]: """ Rotate puzzle by 90 degrees counterclockwise. :param buttonsIdx: list with position index for each button and empty cell :returns: list with positions after rotation """ newButtonsIdx = [] for i in buttonsIdx: ...
bigcode/self-oss-instruct-sc2-concepts
def get_equivalence_ratio( p_fuel, p_oxidizer, f_a_st ): """ Simple equivalence ratio function Parameters ---------- p_fuel : float or un.ufloat Partial pressure of fuel p_oxidizer : float or un.ufloat Partial pressure of oxidizer f_a_st : float or un...
bigcode/self-oss-instruct-sc2-concepts
def sv_length(pos, end, chrom, end_chrom, svlen=None): """Return the length of a structural variant Args: pos(int) end(int) chrom(str) end_chrom(str) svlen(int) Returns: length(int) """ if chrom != end_chrom: return int(10e10) if svlen: ...
bigcode/self-oss-instruct-sc2-concepts
def sampling(generate_data, nb_samples): """ Generates nb_samples from generate_data :param generate_data: Function that takes takes an integer n and samples from a synthetic distribution. Returns an array of n samples. :param nb_samples: Number of samples to generate :retu...
bigcode/self-oss-instruct-sc2-concepts
def identity(x, name=None): """Returns a tensor with the same content as the input tensor. # Arguments x: The input tensor. name: String, name for the variable to create. # Returns A tensor of the same shape, type and content. """ return x.copy(name=name)
bigcode/self-oss-instruct-sc2-concepts
import math def same_padding(in_dim, kernel_dim, stride_dim): """ Calculates the output dimension and also the padding required for that dimension. :param in_dim: Width/Height of Input :param kernel_dim: Width/Height of Kernel :param stride_dim: Vertical/Horizontal Stride """ output_dim = ...
bigcode/self-oss-instruct-sc2-concepts
def parameters_equal(a, b): """Compares two parameter instances Checks full name, data, and ranges. Does not consider the comment. :return: True or False :raises: ValueError if both inputs are no parameter instances """ if (not b.v_is_parameter and not a.v_is_parameter): ...
bigcode/self-oss-instruct-sc2-concepts
def binary_string(number: int) -> str: """Number to binary string :param number: some number (an integer) to turn into a binary string :return: Some string which is the binary string :rtype: str .. doctest:: python >>> binary_string(200) '11001000' >>> binary_string(10) ...
bigcode/self-oss-instruct-sc2-concepts
def get_ytid2labels(segment_csv): """ compute the mapping (dict object) from youtube id to audioset labels. """ with open(segment_csv) as F: lines = F.read().split('\n') lines = [l for l in lines if len(l) > 0 and l[0] != '#'] ytid2labels = {l.split(',')[0]: l.split('"')[-2] for l in li...
bigcode/self-oss-instruct-sc2-concepts
def get_bind_addr(conf, default_port=None): """Return the host and port to bind to.""" return (conf.bind_host, conf.bind_port or default_port)
bigcode/self-oss-instruct-sc2-concepts
def _part(f): """ Return a character representing a partly-filled cell with proportion `f` (rounded down to width of nearest available character). """ return [" ", "▏", "▎", "▍", "▌", "▋", "▊", "▉", "█"][int(9*f)]
bigcode/self-oss-instruct-sc2-concepts
def join_infile_path(*paths): """ Join path components using '/' as separator. This method is defined as an alternative to os.path.join, which uses '\\' as separator in Windows environments and is therefore not valid to navigate within data files. Parameters: ----------- *paths: all str...
bigcode/self-oss-instruct-sc2-concepts
def get_latlon_from_cube(cube): """Return domain covered by cube, taking into account cell boundaries :param cube: target cube :return: tuple(lat_max, lat_min, lon_max, lon_min, nlat, nlon) """ for latlon in ['latitude', 'longitude']: if not cube.coord(latlon).has_bounds(): cube...
bigcode/self-oss-instruct-sc2-concepts
def trapezoid(poly, lower, upper): """Calculate trapezoid slice from two polynomial evaluations and step size""" lower_value = poly.evaluate(lower) upper_value = poly.evaluate(upper) return (upper - lower) * ((lower_value + upper_value)/2.0)
bigcode/self-oss-instruct-sc2-concepts
def set_dict_indices(my_array): """Creates a dictionary based on values in my_array, and links each of them to an index. Parameters ---------- my_array: An array (e.g. [a,b,c]) Returns ------- my_dict: A dictionary (e.g. {a:0, b:1, c:2}) """ my_dict = {} i = 0 ...
bigcode/self-oss-instruct-sc2-concepts
def get_day_of_the_week_number_from_datetime(datetime_obj) -> int: """Does what the function title states.""" return datetime_obj.weekday()
bigcode/self-oss-instruct-sc2-concepts
import logging def setup_logging(args): """Setup logging for the application""" log = logging.getLogger(__package__) log.setLevel(args.loglevel) # disable root logger handlers root_logger = logging.getLogger() root_logger.handlers = [] # set log output destination if args.logfile: ...
bigcode/self-oss-instruct-sc2-concepts
def count(val, iterable): """ Counts how many times a value (val) occurs in an iterable, excluding `None` :param val: The value to be counted :param iterable: values to be counted over :type iterable: iterable :return: the count of values :rtype: int """ return sum(1 for x ...
bigcode/self-oss-instruct-sc2-concepts
def format_metrics(metrics, split): """Formats metrics for logging. Args: metrics: Dictionary with metrics. split: String indicating the KG dataset split. Returns: String with formatted metrics. """ result = '\t {} MR: {:.2f} | '.format(split, metrics['MR']) result += 'MRR: {:.3f} | '.format(m...
bigcode/self-oss-instruct-sc2-concepts
def word_count(review_str)->int: """ count number of words in a string of reviews """ return len(review_str.split())
bigcode/self-oss-instruct-sc2-concepts
def _kl_normal_loss(mean, logvar, storer=None): """ Calculates the KL divergence between a normal distribution with diagonal covariance and a unit normal distribution. Parameters ---------- mean : torch.Tensor Mean of the normal distribution. Shape (batch_size, latent_dim) where ...
bigcode/self-oss-instruct-sc2-concepts
import torch def index2points(points, idx): """Construct edge feature for each point Parameters ---------- points: (batch_size, num_dims, num_points) idx: (batch_size, num_points) or (batch_size, num_points, k) Returns ------- edge_features: (batch_size, num_dims, num_points) or (bat...
bigcode/self-oss-instruct-sc2-concepts
from typing import IO def read_line(in_fd: IO[str]) -> str: """ Reads a single line from a file in bytes mode :param in_fd: Input file descriptor :return: The line (from in_fd current position), without EOL """ result = [] while True: # Ignore the first line read_char = in...
bigcode/self-oss-instruct-sc2-concepts
def compute_Cp(T,Cv,V,B0,beta): """ This function computes the isobaric heat capacity from the equation: :math:`Cp - Cv = T V beta^2 B0` where *Cp,Cv* are the isobaric and isocoric heat capacities respectively, *T* is the temperature, *V* the unit cell volume, *beta* the volumetric thermal...
bigcode/self-oss-instruct-sc2-concepts
def _architecture(target): """Returns architecture for current active target, e.g. i386, x86_64, armv7""" return target.GetTriple().split('-', 1)[0]
bigcode/self-oss-instruct-sc2-concepts
import torch def _tokenize_str(string, char_tensor=None): """ Parses a utf-8 encoded string and assigns to ByteTensor char_tensor. If no char_tensor is provide one is created. Typically used internally by `tokenize_str_batch`. """ if char_tensor is None: char_tensor = torch.ByteTensor(len(string.encode())) f...
bigcode/self-oss-instruct-sc2-concepts
import logging def is_encoded_image_spec(tensor_spec): """Determines whether the passed tensor_spec speficies an encoded image.""" if hasattr(tensor_spec, 'data_format'): # If tensor_spec is an ExtendedTensorSpec, use the data_format to check. return (tensor_spec.data_format is not None) and ( ten...
bigcode/self-oss-instruct-sc2-concepts
def colour_linear_interpolation(col_a, col_b, t): """ Linearly interpolates between two colours. """ col = tuple([a + (b - a) * t for a, b in zip(col_a, col_b)]) return col
bigcode/self-oss-instruct-sc2-concepts
def is_valid_instant(x): """ Returns true iff x is a well-shaped concrete time instant (i.e. has a numeric position). """ try: return hasattr(x, "inTimePosition") and len(x.inTimePosition) > 0 and \ len(x.inTimePosition[0].numericPosition) > 0 except TypeError: return ...
bigcode/self-oss-instruct-sc2-concepts
def truncate_val(val, lower_bound, upper_bound): """Truncate val to be in the range [lower_bound, upper_bound].""" val = max(val, lower_bound) val = min(val, upper_bound) return val
bigcode/self-oss-instruct-sc2-concepts
def _access(*args, **kargs): """Assume access to the path is allowed.""" return True
bigcode/self-oss-instruct-sc2-concepts
def write(file, lines): """ Write file from an array """ with open(file, 'w') as f: bytes_ = f.write('\n'.join(lines[0:]) + '\n') return bytes_
bigcode/self-oss-instruct-sc2-concepts
def getQuestionLabels(task_question_answer_labels, task_uuid): """ Gets a list of question labels under the same task uuid """ series = task_question_answer_labels[task_question_answer_labels["quiz_task_uuid"] == task_uuid] return series["question_label"].unique().tolist()
bigcode/self-oss-instruct-sc2-concepts
def cli_cosmosdb_gremlin_database_throughput_migrate(client, resource_group_name, account_name, database_name, ...
bigcode/self-oss-instruct-sc2-concepts
def contrib_xref(contrib_tag, ref_type): """ Given a contrib tag, look for an xref tag of type ref_type directly inside the contrib tag """ aff_tags = [] for child_tag in contrib_tag: if ( child_tag and child_tag.name and child_tag.name == "xref" ...
bigcode/self-oss-instruct-sc2-concepts
from typing import List import random import itertools def get_model_nncf_cat() -> List: """Test helper for getting cartesian product of models and categories. Returns: List: Returns a combination of models with their nncf support for each category. """ model_support = [ ("padim", Fal...
bigcode/self-oss-instruct-sc2-concepts
def get_hyperhdr_device_id(server_id: str, instance: int) -> str: """Get an id for a HyperHDR device/instance.""" return f"{server_id}_{instance}"
bigcode/self-oss-instruct-sc2-concepts
def strict_forall(l, f): """Takes an iterable of elements, and returns (True, None) if f applied to each element returns True. Otherwise it returns (False, e) where e is the first element for which f returns False. Arguments: - `l`: an iterable of elements - `f`: a function that applies...
bigcode/self-oss-instruct-sc2-concepts
import pyclbr def is_handler_subclass(cls, classnames=("ViewHandler", "APIHandler")): """Determines if ``cls`` is indeed a subclass of ``classnames`` This function should only be used with ``cls`` from ``pyclbr.readmodule`` """ if isinstance(cls, pyclbr.Class): return is_handler_subclass(cls....
bigcode/self-oss-instruct-sc2-concepts
def create_label_column(row) -> str: """ Helper function to generate a new column which will be used to label the choropleth maps. Function used to label missing data (otherwise they will show up on the map as "-1 SEK"). Parameters ---------- row : Returns ------- str C...
bigcode/self-oss-instruct-sc2-concepts
import pathlib def derive_filepath(filepath, append_string='', suffix=None, path=None): """Generate a file path based on the name and potentially path of the input file path. Parameters ---------- filepath: str of pathlib.Path Path to file. append_string: str String to app...
bigcode/self-oss-instruct-sc2-concepts
def gather_pages(pdfs: list) -> list: """ Creates a list of pages from a list of PDFs. Args: pdfs (list): List of PDFs to collate. Returns: list: List of pages from all passed PDFs. """ output = [] for pdf in pdfs: for page in pdf.pages: output.append(pa...
bigcode/self-oss-instruct-sc2-concepts
import torch def create_alternating_binary_mask(features, even=True): """ Creates a binary mask of a given dimension which alternates its masking. :param features: Dimension of mask. :param even: If True, even values are assigned 1s, odd 0s. If False, vice versa. :return: Alternating binary mask ...
bigcode/self-oss-instruct-sc2-concepts
def parse_none(*args): """Return tuple of arguments excluding the ones being None.""" return tuple(arg if arg is not None else "" for arg in args)
bigcode/self-oss-instruct-sc2-concepts
def remove_dupes(items): """ make sure no item appears twice in list i.e. filter for any duplicates """ clean = [] for i in items: if not i in clean: clean.append(i) return clean
bigcode/self-oss-instruct-sc2-concepts
def wordList(fname = 'dictionaryWords.txt'): """Generate list of possible words from the passed file.""" wordlist = [] with open(fname, 'r') as fin: for word in fin: word = word.rstrip() ; wordlist.append(word) return wordlist
bigcode/self-oss-instruct-sc2-concepts
def calc_electrons_from_photons(photons, quantum_efficiency): """ Calculate the number of electrons generated by incident photons. Returns ------- int : no units, a number of electrons """ return int(photons * quantum_efficiency)
bigcode/self-oss-instruct-sc2-concepts
def _gutenberg_simple_parse(raw_content): """Clean a project Gunteberg file content.""" content = raw_content # *** START OF THIS PROJECT GUTENBERG EBOOK THE RED BADGE OF COURAGE *** starts = [ '*** START OF THIS PROJECT GUTENBERG EBOOK', '***START OF THE PROJECT GUTENBERG EBOOK', '*** START O...
bigcode/self-oss-instruct-sc2-concepts
def counter_mean(counter): """Takes the mean of a collections.Counter object (or dictionary).""" mean = 0. total = 0. for k, v in counter.items(): if k <= 0: k = 200 mean += k * v total += v return mean / total
bigcode/self-oss-instruct-sc2-concepts
import torch def quat_conj(Q): """ Returns the conjugate of the given quaternion Parameters ---------- Q : Tensor the (4,) or (N,4,) quaternion tensor Returns ------- Tensor the (4,) or (N,4,) conjugate quaternion tensor """ return Q * torch.tensor([-1, -1, -...
bigcode/self-oss-instruct-sc2-concepts
def xauth(auth): """Expand authentication token >>> xauth(None) >>> xauth(('user', 'pass')) ('user', 'pass') >>> xauth('user:pass') ('user', 'pass') >>> xauth('apikey') ('apikey', '') """ if auth is None or isinstance(auth, tuple): return auth else: u, _, p ...
bigcode/self-oss-instruct-sc2-concepts
import json def _get_codes(error_response_json): """Get the list of error codes from an error response json""" if isinstance(error_response_json, str): error_response_json = json.loads(error_response_json) error_response_json = error_response_json.get("error") if error_response_json is None: ...
bigcode/self-oss-instruct-sc2-concepts
def get_channel_id(data: dict) -> str: """Return channel id from payload""" channel = data['channel'] return channel
bigcode/self-oss-instruct-sc2-concepts