seed
stringlengths
1
14k
source
stringclasses
2 values
from typing import Optional import click def _get_delimiter(item: str) -> Optional[str]: """ Returns the delimiter found in the item if any. It may raises an error if delimiter starts or ends and item or if there is more than one delimiter in the item. :param item: the item to determine delimiters. ...
bigcode/self-oss-instruct-sc2-concepts
def _route2url(route): """Convert host from openshift route to https:// url""" return f"https://{route['spec']['host']}"
bigcode/self-oss-instruct-sc2-concepts
def search_array_dict(array, id_name, id): """指定キーで配列から検索する - Search from the array with the specified key Args: array (arr): array id_name (str): key id (str): id Returns: dict: array item """ for item in array: if item[id_name] == id: return it...
bigcode/self-oss-instruct-sc2-concepts
def _arg_olen1(dvi, delta): """Optionally signed, length *delta*+1 Read *delta*+1 bytes, returning the bytes interpreted as unsigned integer for 0<=*delta*<3 and signed if *delta*==3.""" return dvi._arg(delta + 1, delta == 3)
bigcode/self-oss-instruct-sc2-concepts
import logging def _read_gold_and_pred(gold_fpath, pred_fpath): """ Read gold and predicted data. :param gold_fpath: the original annotated gold file, where the last 4th column contains the labels. :param pred_fpath: a file with line_number and score at each line. :return: {line_number:label} dict...
bigcode/self-oss-instruct-sc2-concepts
def normalize_tag_name(name_tag): """ docker-py provides "RepoTags", which are strings of format "<image name>:<image tag>" We want to strip off the tag part and normalize the name: some.domain.com/organization/image:tag -> organization/image organization/image:tag -> organiz...
bigcode/self-oss-instruct-sc2-concepts
def find_last_word(s): """Find the last word in a string.""" # Note: will break on \n, \r, etc. alpha_only_sentence = "".join([c for c in s if (c.isalpha() or (c == " "))]).strip() return alpha_only_sentence.split()[-1]
bigcode/self-oss-instruct-sc2-concepts
def get_codon(seq, codon_no, start_offset): """ This function takes a sequece and a codon number and returns the codon found in the sequence at that position """ seq = seq.replace("-","") codon_start_pos = int(codon_no - 1)*3 - start_offset codon = seq[codon_start_pos:codon_start_pos + 3] ...
bigcode/self-oss-instruct-sc2-concepts
def jump_to_match(input_file, regex): """Jump to regex match in file. @param input_file: File object @param regex: Compiled regex object @return: True if successful, False otherwise """ for line in input_file: if regex.match(line): return True return False
bigcode/self-oss-instruct-sc2-concepts
def conjoin_args(args): """ Conjoin from left to right. Args: args (list): [<something> CONJUNCTION] <something> Returns: dict: MongoDB filter """ if len(args) == 1: return args[0] conj = f"${args[1].value.lower()}" return {conj: [args[0], args[2]]}
bigcode/self-oss-instruct-sc2-concepts
def multAll(lst): """Multiplies a list of variables together""" if len(lst) == 0: return 0 out = lst[0] for i in range(1,len(lst)): out *= lst[i] return out
bigcode/self-oss-instruct-sc2-concepts
from typing import Union import ast from typing import List def get_assign_targets(node: Union[ast.Assign, ast.AnnAssign]) -> List[ast.expr]: """ An AnnAssign `target` is a single node. An Assign `targets` is a list of nodes. Example: `a = b = 1` return [ast.Name('a'), ast.Name('b')] ...
bigcode/self-oss-instruct-sc2-concepts
def extract_between(source: str, start: str, end: str) -> str: """Extract all of the characters between start and end. :param source: The input string from which to extract a substring. :param start: The substring that marks the extraction starting place. :param end: The substring that marks the place ...
bigcode/self-oss-instruct-sc2-concepts
import torch from typing import Optional def one_hot(labels: torch.Tensor, num_classes: int, device: Optional[torch.device] = None, dtype: Optional[torch.dtype] = None, eps: Optional[float] = 1e-6) -> torch.Tensor: """Converts an integer label x-D tensor to a one-ho...
bigcode/self-oss-instruct-sc2-concepts
from typing import Iterable from typing import Any from typing import Iterator from typing import Tuple import itertools def pairwise(iterable: Iterable[Any]) -> Iterator[Tuple[Any, Any]]: """Return iterator of overlapping pairs of items from an iterable. Will return an empty iterable if the passed iterable ...
bigcode/self-oss-instruct-sc2-concepts
def normalize_ctu_name(name): """Ensure name is in the normal CTU form.""" return name.title().replace('Ctu', 'CTU').replace('Iot', 'IoT')
bigcode/self-oss-instruct-sc2-concepts
def count_string_dictionary(list_of_strings): """ Count the number of instances in a list and return them in a dictionary where the keys are the strings and the value the number of times it appeared in the list """ to_return = {} for e in list_of_strings: try: to_ret...
bigcode/self-oss-instruct-sc2-concepts
def addright(page, right_page, tx=0): """Adds page (PageObject) on the right side, tx is an addtional offset""" page.mergeTranslatedPage(right_page, page.mediaBox[2] + tx, 0, expand=True) return page
bigcode/self-oss-instruct-sc2-concepts
def get_data_from_pipeline(pipeline, image, coordinates, labels): """ Function defined to apply the data augmentation pipeline and retrive image, bounding boxes coordinates and corresponding class labels. Args: ----- - pipeline: albumentations.Compose Object - image: ndarray, image to be au...
bigcode/self-oss-instruct-sc2-concepts
def Get_Parses(data): """ Reads parses from data, counting number of parses by newlines - sentences: list with tokenized sentences in data - parses: a list of lists containing the split links of each parse [ [[link1-parse1][link2-parse1] ... ] [[link1-parse2][link...
bigcode/self-oss-instruct-sc2-concepts
def get_args_of_function_node(function_node, args_to_ignore): """Extracts the arguments from a function definition. Args: function_node: ast.FunctionDef. Represents a function. args_to_ignore: list(str). Ignore these arguments in a function definition. Returns: list(str...
bigcode/self-oss-instruct-sc2-concepts
import yaml def _import_current_tasks(course, template): """ Render tasks from the course. :param course: Path to the course file :type course: ``str`` :param template: Template environment :type template: :class:`narrenschiff.templating.Template` :return: Tasks as a list of dictionaries ...
bigcode/self-oss-instruct-sc2-concepts
def _extract_gpcrdb_residue_info(residue_html): """ Extracts the relevant info from GPCRdb html entries of residues. Parameters ---------- residue_html : list A list in which each item contains the html lines for one residue. Returns ------- residue_info : list ...
bigcode/self-oss-instruct-sc2-concepts
from pathlib import Path from typing import Union import json def load_json_data(fpath: Path) -> Union[list, dict]: """ Loads a JSON file and returns data. Args: fpath (Path): The path to the file Returns: Union[list, dict]: The data loaded from JSON. """ with open(fpath) as ...
bigcode/self-oss-instruct-sc2-concepts
def instant_name_to_class_name(name): """ This will convert from 'parent_name.child_name' to 'ParentName_ChildName' :param name: str of the name to convert :return: str of the converted name """ name2 = ''.join([e.title() for e in name.split('_')]) return '_'.join([e[0].upper() +...
bigcode/self-oss-instruct-sc2-concepts
from typing import Dict def _is_subscriber(patient_record: Dict): """Returns true if the patient is a subscriber record""" return patient_record.get("hl_segment", {}).get("hierarchical_level_code") == "22"
bigcode/self-oss-instruct-sc2-concepts
import re def alphanum_split(key): """Split the key into a list of [text, int, text, int, ..., text]. Args: key (str): String to split. Returns: list: List of tokens Examples: :: >>> alphanum_split("hello1world27") ['hello', 1, 'world', 27, ''] >>> alphanum_...
bigcode/self-oss-instruct-sc2-concepts
def find_lowest_common_in_paths(path_a, path_b): """Find the element with the smallest height that appears in both given lists. The height of an element here is defined as the maximum over the indices where it occurs in the two lists. For example if path_a = [2, 3, 5] and path_b = [5, 6, 2] then the height of ...
bigcode/self-oss-instruct-sc2-concepts
def marginal_contribution_set(game, player, lower_set): """ Takes a subset of players and a player, transforms them into a higher set c2 and lower set c1 and calculates their marginal contribution based on the implemented payoff function. :param player: An element of self.players :type player: str...
bigcode/self-oss-instruct-sc2-concepts
import torch def get_last_token(t, lengths): """ Grab last hidden activation of each batch element according to `lengths` # ^ (1) ^ (2) ^ (3) >>> t = torch.tensor([[[1],[2],[3]], [[2],[3],[4]], [[3],[4],[5]]]) >>> lengths = torch.tensor([3, 2, 1]) >>> g...
bigcode/self-oss-instruct-sc2-concepts
def decode_to_str(batch_text, max_len=512) : """ Converts bytes string data to text. And truncates to max_len. """ return [ ' '.join(text.decode('utf-8').split()[:max_len]) if isinstance(text, bytes) else text[:max_len] for text in batch_text ]
bigcode/self-oss-instruct-sc2-concepts
def compute_similarity_within_df(df, similarity_metric): """ Compute all pairwise similarities between the columns of df. Args: df (pandas df): size = m x n similarity_metric (string): "pearson" or "spearman" Returns: out_df (pandas df): size = n x n """ # Compute similarity ...
bigcode/self-oss-instruct-sc2-concepts
def get_yt_ids(label_ids, csv): """ Function for getting the youtube IDs for all clips where the specified classes are present :param label_ids: list of label IDs (will most often only contain 1 label) :param csv: path to csv file containing dataset info (i.e. youtube ids and labels) :return: dicti...
bigcode/self-oss-instruct-sc2-concepts
def classic_example_3(sequence_of_sequences, what_to_count, what_to_mutate_into): """ Shows counting and mutating in a sequence of LISTS. -- Counts and returns the number of 'what_to_count' occurrences. -- Mutates those occurrences into the 'what_to_mutate_into'. """ pr...
bigcode/self-oss-instruct-sc2-concepts
def login(client, user, password): """Return the User instance after logging the user in.""" assert client.login(username=user.username, password=password) return user
bigcode/self-oss-instruct-sc2-concepts
def common_prefix(s1, s2): """Return the common prefix of strings s1 and s2.""" prefix = [] for c1, c2 in zip(s1, s2): if c1 != c2: break prefix.append(c1) return ''.join(prefix)
bigcode/self-oss-instruct-sc2-concepts
def getUsername(dn): """Get the uid/cn of the given DN.""" return dn.split(',')[0].split('=')[1]
bigcode/self-oss-instruct-sc2-concepts
import pathlib def has_parent_path(sub_path: pathlib.Path, parent_path: pathlib.Path) -> bool: """Check if sub_path has the specified parent_dir path.""" # sub_path should be longer than parent path if len(sub_path.parts) < len(parent_path.parts): return False for i, part in enumerate(parent_...
bigcode/self-oss-instruct-sc2-concepts
import re def _parse_key(key): """Parse the input key into an int, antpol tuple, or string. Parameters ---------- key : str Input string to parse. Returns ------- out_key : int or tuple or str Parsed key as an int, antpol tuple, or string. """ try: # is k...
bigcode/self-oss-instruct-sc2-concepts
import pytz def local_tzinfo_factory(offset): """ Create a tzinfo object using the offset of the db connection. This ensures that the datetimes returned are timezone aware and will be printed in the reports with timezone information. """ return pytz.FixedOffset(offset)
bigcode/self-oss-instruct-sc2-concepts
def rescale_points(points, scale): """ Take as input a list of points `points` in (x,y) coordinates and scale them according to the rescaling factor `scale`. :param points: list of points in (x,y) coordinates :type points: list of Tuple(int, int) :param scale: scaling factor :type scale: float...
bigcode/self-oss-instruct-sc2-concepts
from typing import List from typing import Counter def get_characters(lang_data: List[str]) -> Counter: """ Return a sorted list of characters in the language corpus. Parameters ---------- lang_data : List[str] A list of all paragraphs Returns ------- characters : Counter ...
bigcode/self-oss-instruct-sc2-concepts
def convert_dotted_str_to_int(dotted_str: str) -> int: """ Convert dotted str into int: - This function takes a dotted str and converts into an int. - Useful in converting version into a number. - Eg: "1.2.3" -> 123 """ return int("".join(dotted_str.split(".")))
bigcode/self-oss-instruct-sc2-concepts
def run_maze(maze: list[list[int]], i: int, j: int, solutions: list[list[int]]) -> bool: """ This method is recursive starting from (i, j) and going in one of four directions: up, down, left, right. If a path is found to destination it returns True otherwise it returns False. Parameters: maz...
bigcode/self-oss-instruct-sc2-concepts
def listify(x): """convert object to a list; if not an iterable, wrap as a list of length 1""" return list(x) if hasattr(x, '__iter__') else [x]
bigcode/self-oss-instruct-sc2-concepts
def _get_rating(mr_val, snt): """ Handle the rating part. :param mr_val: value of the 'customerRating' field. :param snt: sentence string built so far. :return: refined sentence string. """ # if the previous sentence ends with a dot if snt[-1] != ".": beginning = " with" else...
bigcode/self-oss-instruct-sc2-concepts
import json def normalize_nested_dicts(row): """Transform nested dicts into json strings with sorted keys. Args: row (dict): A dictionary to normalize. Returns: dict: A row with nested dicts transformed to json string. """ new_row = {} for key, value in list(row.items()): ...
bigcode/self-oss-instruct-sc2-concepts
def _improve_latex(s): """Improve an OSIRIS-generated latex string using common rules.""" # Descriptive subindexes in roman s2 = s.replace(r"\omega_p", r"\omega_{\mathrm{p}}") s2 = s2.replace("m_e", r"m_{\mathrm{e}}") # "Arbitrary units" in roman s2 = s2.replace("a.u.", r"\mathrm{a.u.}") ret...
bigcode/self-oss-instruct-sc2-concepts
def nextID_in_poly(poly, id): """ Determines the id of the next point on a standard polygon. Parameters ---------- poly :: List of (x,y) tuples Representation of a polygon, with identical first and last vertices. id : Integer Returns ------- Integer """ if id==len(...
bigcode/self-oss-instruct-sc2-concepts
def display_ar(section): """ Show access rights of a section """ res = "" if section.IMAGE_SCN_MEM_READ: res += "R" else: res += "-" if section.IMAGE_SCN_MEM_WRITE: res += "W" else: res += "-" if section.IMAGE_SCN_MEM_EXECUTE: res += "X" el...
bigcode/self-oss-instruct-sc2-concepts
from typing import Tuple def addpair(pair: Tuple[float, float]) -> float: """(a, b) -> a + b """ (v1, v2) = pair return v1 + v2
bigcode/self-oss-instruct-sc2-concepts
def valid_path(path): """ Determine if a path is deemed "valid". This means we are looking for real partitions (not kernel devices) and mounted partitions. :param path: Usually named tuple returned from psutil.disk_partitions() :type path: namedtuple :return: Valid path state :rtype: bool "...
bigcode/self-oss-instruct-sc2-concepts
def read(file_path): """ Read a file and return it's contents. """ with open(file_path) as f: return f.read()
bigcode/self-oss-instruct-sc2-concepts
import json def read_in_config_file(conf_file): """ Read in the JSON configuration file used to make the groupme bot aware of the groups it is in. :param conf_file: The path to the JSON file of configuration information for the groupme bot. :return: The bot_name from the config, the dictionary mapping...
bigcode/self-oss-instruct-sc2-concepts
def get_slug(clip: str) -> str: """ Splits up the URL given and returns the slug of the clip. """ slug = clip.split("/") return slug[len(slug) - 1]
bigcode/self-oss-instruct-sc2-concepts
from typing import Dict def calculate_possibilities(max: int) -> Dict[int, int]: """Calculate the numbers of lucky numbers from 0 to 10**(max - 1)""" possibilities: Dict[int, int] = { 0: 0, 1: 2 } index: int = 2 while index < max: possibilities[index] = 2 * (9 ** (index - 1)) + 8 * possibiliti...
bigcode/self-oss-instruct-sc2-concepts
from typing import Optional def search_divs(term: str, divs: list) -> Optional[list]: """ Searches the provided div tags for the term that we are interested in :param term: String, the search term :param divs: List, div tags that were scraped :return: List of divs or None """ for div in di...
bigcode/self-oss-instruct-sc2-concepts
def change_to_tuples(dict): """ Turns an unitary dictionary into a tuple """ return (list(dict.keys())[0], list(dict.values())[0])
bigcode/self-oss-instruct-sc2-concepts
def cloneRange(rng): """ Make a copy of the given js range; the JS range is decoupled from any changes. @param range a js range to copy @return a full copy of the range """ return rng.cloneRange()
bigcode/self-oss-instruct-sc2-concepts
def get_lower_long_from_trace_id(trace_id): """Returns the lower 8 bytes of the trace ID as a long value, assuming little endian order. :rtype: long :returns: Lower 8 bytes of trace ID """ lower_bytes = trace_id[16:] lower_long = int(lower_bytes, 16) return lower_long
bigcode/self-oss-instruct-sc2-concepts
def default_image_loader(filename, flags, **kwargs): """This default image loader just returns filename, rect, and any flags.""" def load(rect=None, flags=None): return filename, rect, flags return load
bigcode/self-oss-instruct-sc2-concepts
def formatsWritersField(writers_list): """ Formats Writers field for Web app template. """ film_writers="" if writers_list != None: for writer in writers_list: if len(writers_list) == 1 or writer == writers_list[-2]: film_writers = writer elif writer != w...
bigcode/self-oss-instruct-sc2-concepts
def compute_exact_score(predictions, target_lists): """Computes the Exact score (accuracy) of the predictions. Exact score is defined as the percentage of predictions that match at least one of the targets. Args: predictions: List of predictions. target_lists: List of targets (1 or mor...
bigcode/self-oss-instruct-sc2-concepts
def bits2val(bits): """For a given enumeratable bits, compute the corresponding decimal integer.""" # We assume bits are given in high to low order. For example, # the bits [1, 1, 0] will produce the value 6. return sum(v * (1 << (len(bits)-i-1)) for i, v in enumerate(bits))
bigcode/self-oss-instruct-sc2-concepts
def clamp_value(n, minimum, maximum): """ Clamp a value between a min and max :param n: :param minimum: :param maximum: :return: """ return max(minimum, min(n, maximum))
bigcode/self-oss-instruct-sc2-concepts
def boundary_conditions(cells, cell_data, phy_lin, nodes_array, bc_x, bc_y): """Impose nodal point boundary conditions as required by SolidsPy Parameters ---------- cell : dictionary Dictionary created by meshio with cells information. cell_data: dictionary Dictionar...
bigcode/self-oss-instruct-sc2-concepts
def _remove_type_bracket_block_from_args_str(args_str: str) -> str: """ Remove type annotation block bracket from arguments string. Parameters ---------- args_str : str The target arguments string. e.g., 'dict_val: Dict[str, int] == {}' Returns ------- result_str : str ...
bigcode/self-oss-instruct-sc2-concepts
def parse_country_code(country_code): """ Parse country code from URL to determine origin. :param country_code: country code from URL :return: parsed country code """ cc = str(country_code).lower() if cc.lower() == 'edu' or cc.lower() == 'com' or cc.lower() == 'org' or cc.lower() == 'gov': ...
bigcode/self-oss-instruct-sc2-concepts
def _wrap(text, width): """Break text into lines of specific width.""" lines = [] pos = 0 while pos < len(text): lines.append(text[pos:pos + width]) pos += width return lines
bigcode/self-oss-instruct-sc2-concepts
def rename_nfa_states(nfa: dict, suffix: str): """ Side effect on input! Renames all the states of the NFA adding a **suffix**. It is an utility function to be used to avoid automata to have states with names in common. Avoid suffix that can lead to special name like "as", "and",... :param di...
bigcode/self-oss-instruct-sc2-concepts
def join_matrixes(matrix_1, matrix_2, matrix_2_offset): """ Copy matrix 2 onto matrix 1 based on the passed in x, y offset coordinate """ offset_x, offset_y = matrix_2_offset for cy, row in enumerate(matrix_2): for cx, val in enumerate(row): matrix_1[cy + offset_y - 1][cx + offset_x] += ...
bigcode/self-oss-instruct-sc2-concepts
def merge_envelopes(envelopes, extent_type='intersection'): """Return the extent of a list of envelopes. Return the extent of the union or intersection of a list of envelopes :param envelopes: list of envelopes or raster filenames (also mixed) :type envelopes: list, tuple, iterator :param extent_t...
bigcode/self-oss-instruct-sc2-concepts
import random def generate_ascending_array(power): """Generate an array of integers sorted in ascending order.""" A = [] for k in range((2**power)+1): A.append(random.randint(-1000000, 1000000)) return sorted(A)
bigcode/self-oss-instruct-sc2-concepts
import string def format_output(rc, time): """ Formats the output that is used in sending the message to the client, depending on the return code of the command. """ template = string.Template(""" ${greeting}!\n I have finished executing your job. Its return code is `$rc`, which $comment.\n Your command to...
bigcode/self-oss-instruct-sc2-concepts
def elem_to_dict(elem, ns, key_map, value_map={}): """Convert an XML etree.Element to a desired dictionary as specified by the key map and value map. Args: elem (etree.Element): An ancestor element of the tags specified in the key map. ns (string): The namespace to use ...
bigcode/self-oss-instruct-sc2-concepts
def list_to_string(in_list, conjunction): """Simple helper for formatting lists contaings strings as strings. This is intended for simple lists that contain strings. Input will not be checked. :param in_list: List to be converted to a string. :param conjunction: String - conjunction to be used (e....
bigcode/self-oss-instruct-sc2-concepts
def to_bio2(tags): """ Convert the original tag sequence to BIO2 format. If the input is already in BIO2 format, the original input is returned. Args: tags: a list of tags in either BIO or BIO2 format Returns: new_tags: a list of tags in BIO2 format """ new_tags = [] ...
bigcode/self-oss-instruct-sc2-concepts
def execute_request(service, property_uri, request): """Executes a searchAnalytics.query request. Args: service: The webmasters service to use when executing the query. property_uri: The site or app URI to request data for. request: The request to be executed. Returns: An array of response rows....
bigcode/self-oss-instruct-sc2-concepts
def custom_admin_notification(session, notification_type, message, task_id=None): """ Function for implementing custom admin notifications. notifications are stored in session and show to user when user refreshes page. A valid session object must be passed to this function with notification type and me...
bigcode/self-oss-instruct-sc2-concepts
def calculate_product(alist): """ Returns the product of a list of numbers. """ product = 1 for fact in alist: product *= fact return product
bigcode/self-oss-instruct-sc2-concepts
def _get_pgh_obj_pk_col(history_model): """ Returns the column name of the PK field tracked by the history model """ return history_model._meta.get_field( 'pgh_obj' ).related_model._meta.pk.column
bigcode/self-oss-instruct-sc2-concepts
def _parse_query(query): """extract key-value pairs from a url query string for example "collection=23&someoption&format=json" -> {"collection": "23", "someoption": None, "format": "json"} """ parts = [p.split("=") for p in query.split("&")] result = {} for p in parts: if len...
bigcode/self-oss-instruct-sc2-concepts
async def get_modification_stats(db, index_id): """ Get the number of modified otus and the number of changes made for a specific index. :param db: the application database client :type db: :class:`~motor.motor_asyncio.AsyncIOMotorClient` :param index_id: the id of the index to return counts for ...
bigcode/self-oss-instruct-sc2-concepts
def should_show(name, pruning_params): """Whether to show the layer's distribution or not.""" in_whitelist = not pruning_params.white_list or any( e in name for e in pruning_params.white_list) in_blacklist = any(e in name for e in pruning_params.black_list) if pruning_params.white_list and not i...
bigcode/self-oss-instruct-sc2-concepts
def test_case_is_success(test): """Determine if the the test expects a successful parse""" if "results" not in test: return True for result in test["results"]: if "error" in result: return False return True
bigcode/self-oss-instruct-sc2-concepts
def part_2_fuel(pos, list_): """gives the fuel amount for a specific position according to rules of part 2""" fuel = [(abs(pos - i)*(abs(pos-i)+1))/2 for i in list_] return sum(fuel)
bigcode/self-oss-instruct-sc2-concepts
def segments_intersect_or_coincide(a, b, c, d): """Return True if segments intersect or coincide""" def overlapping(): if ((c.x < a.x < d.x) or (c.x < b.x < d.x) or (c.y < a.y < d.y) or (c.y < b.y < d.y) or (c in (a, b)) or (d in (a, b))): return True ...
bigcode/self-oss-instruct-sc2-concepts
def is_variable(x): """ Checks if the provided expression x is a variable, i.e., a string that starts with ?. >>> is_variable('?x') True >>> is_variable('x') False """ return isinstance(x, str) and len(x) > 0 and x[0] == "?"
bigcode/self-oss-instruct-sc2-concepts
def ozip(*optionals): """Zip optional values. Return None if one value or the other is None.""" return None if any(x is None for x in optionals) else tuple(optionals)
bigcode/self-oss-instruct-sc2-concepts
def add_lower(line): """Returns if the upper case string is different from the lower case line Param: line (unicode) Returns: False if they are the same Lowered string if they are not """ line_lower = line.lower() if line != line_lower: return line_lower else...
bigcode/self-oss-instruct-sc2-concepts
def encode_labels(label: str, label2id: dict, other_class: int) -> int: """ Encodes labels with corresponding labels id. If relation is unknown, returns special id for unknown relations""" return label2id.get(label, other_class)
bigcode/self-oss-instruct-sc2-concepts
import torch def check_device(device): """Check torch device validity.""" if isinstance(device, str): device = torch.device(device) if not isinstance(device, torch.device): raise TypeError("Specify device as torch.device or as string : 'cpu','cuda',...") if device.type != 'cpu': ...
bigcode/self-oss-instruct-sc2-concepts
import getpass def secure_input(prompt: str) -> str: """Get secure input without showing it in the command line. Args: prompt (str): The prompt asking the user to input. Returns: str: The secure input. """ return getpass.getpass(prompt + ' ')
bigcode/self-oss-instruct-sc2-concepts
def SplitLines( contents ): """Return a list of each of the lines in the byte string |contents|. Behavior is equivalent to str.splitlines with the following exceptions: - empty strings are returned as [ '' ]; - a trailing newline is not ignored (i.e. SplitLines( '\n' ) returns [ '', '' ], not [ '' ] ).""...
bigcode/self-oss-instruct-sc2-concepts
def scan_for_benchmark_versions(bmkdir): """Scan subdirectories of a benchmark Directory 'bmkdir' to find benchmark versions. Return a sequence containing all benchmark version names.""" srcdir = bmkdir.getChildByName('src') srcdir.scan() return srcdir.getScannedChildren()
bigcode/self-oss-instruct-sc2-concepts
def get_lattice(lattice, alat, rescale = False): """ Compute the lattice vectors. If rescale = True the vectors are expressed in units of the lattice constant. Args: lattice (:py:class:`array`) : array with the lattice vectors. The i-th row represents the i-th lattice vectors in car...
bigcode/self-oss-instruct-sc2-concepts
from typing import BinaryIO def is_real_file(the_input: BinaryIO) -> bool: """ Determine if the file-like object is associated with an actual file. This is mainly to consider suitability for establishment of a numpy.memmap. Parameters ---------- the_input : BinaryIO Returns ------- ...
bigcode/self-oss-instruct-sc2-concepts
def jumlah_deret_geometri(utama: int, rasio_umum: int, jumlah: int) -> int: """ Menghitung jumlah deret geometri >>> jumlah_deret_geometri(1, 2, 10) 1023.0 >>> jumlah_deret_geometri(1, 10, 5) 11111.0 >>> jumlah_deret_geometri(0, 2, 10) 0.0 """ if rasio_umum == 1: # Rumus ...
bigcode/self-oss-instruct-sc2-concepts
def convert_string(*, start='|', newlines=True): """Return a function that can be used as a converter. The default converter ``str`` handles multiline values like :class:`~configparser.ConfigParser`, i.e. preserving newlines but ignoring indentations (because nothing gets realy converted). A conve...
bigcode/self-oss-instruct-sc2-concepts
def _parse_string(s): """Parse a string representation of a tree structure (implementation) Nodes are separated by whitespace, while child lists are enclosed in balanced parentheses. Return value is a tuple of (tree_structure, length_in_characters)""" if '(' not in s: s, _, _ = s.p...
bigcode/self-oss-instruct-sc2-concepts