seed
stringlengths
1
14k
source
stringclasses
2 values
def text_to_word_sequence(text, filters='!"#$%&()*+,-./:;<=>?@[\\]^_`{|}~\t\n', lower=True, split=" "): """Converts a text to a sequence of words (or tokens). # Arguments text: Input text (string). filters: Sequence of characters to filter out....
bigcode/self-oss-instruct-sc2-concepts
def get_grants(df): """Get list of grant numbers from dataframe. Assumptions: Dataframe has column called 'grantNumber' Returns: set: valid grant numbers, e.g. non-empty strings """ print(f"Querying for grant numbers...", end="") grants = set(df.grantNumber.dropna()) print...
bigcode/self-oss-instruct-sc2-concepts
from typing import Optional from pathlib import Path def join_paths(path1: Optional[str] = "", path2: Optional[str] = "") -> str: """ Joins path1 and path2, returning a valid object storage path string. Example: "/p1/p2" + "p3" -> "p1/p2/p3" """ path1 = path1 or "" path2 = path2 or "" # co...
bigcode/self-oss-instruct-sc2-concepts
import struct def seq_to_bytes(s): """Convert a sequence of integers to a *bytes* instance. Good for plastering over Python 2 / Python 3 cracks. """ fmt = "{0}B".format(len(s)) return struct.pack(fmt, *s)
bigcode/self-oss-instruct-sc2-concepts
def parse_int_ge0(value): """Returns value converted to an int. Raises a ValueError if value cannot be converted to an int that is greater than or equal to zero. """ value = int(value) if value < 0: msg = ('Invalid value [{0}]: require a whole number greater than or ' 'equal t...
bigcode/self-oss-instruct-sc2-concepts
import string def remove_punct(value): """Converts string by removing punctuation characters.""" value = value.strip() value = value.translate(str.maketrans('', '', string.punctuation)) return value
bigcode/self-oss-instruct-sc2-concepts
import pickle def default_model_read(modelfile): """Default function to read model files, simply used pickle.load""" return pickle.load(open(modelfile, 'rb'))
bigcode/self-oss-instruct-sc2-concepts
def _variant_genotypes(variants, missing_genotypes_default=(-1, -1)): """Returns the genotypes of variants as a list of tuples. Args: variants: iterable[nucleus.protos.Variant]. The variants whose genotypes we want to get. missing_genotypes_default: tuple. If a variant in variants doesn't have ...
bigcode/self-oss-instruct-sc2-concepts
import struct def byte(number): """ Converts a number between 0 and 255 (both inclusive) to a base-256 (byte) representation. Use it as a replacement for ``chr`` where you are expecting a byte because this will work on all versions of Python. Raises :class:``struct.error`` on overflow. :param number:...
bigcode/self-oss-instruct-sc2-concepts
import random def generate_events(grid_size, event_type, probability, event_max): """ Generate up to 'number' of events at random times throughout the night. Return events as a list of lists containing the event type and time grid index at which the event occurs. Example ------- >>> events = ...
bigcode/self-oss-instruct-sc2-concepts
def last(inlist): """ Return the last element from a list or tuple, otherwise return untouched. Examples -------- >>> last([1, 0]) 0 >>> last("/path/somewhere") '/path/somewhere' """ if isinstance(inlist, (list, tuple)): return inlist[-1] return inlist
bigcode/self-oss-instruct-sc2-concepts
from typing import Any import pickle def get_papers_pickle(filename: str) -> dict[str, Any]: """retrive papers (dict format) from file in folder data/papers""" with open(f"data/papers/{filename}", 'rb') as papers_file: return pickle.load(papers_file)
bigcode/self-oss-instruct-sc2-concepts
import requests from bs4 import BeautifulSoup def get_article(url): """ Gets article content from URL Input : URL of article Output : Content in BeautifulSoup format """ r = requests.get(url) html_soup = BeautifulSoup(r.content, 'lxml') return html_soup
bigcode/self-oss-instruct-sc2-concepts
def _convert_from_european_format(string): """ Conver the string given in the European format (commas as decimal points, full stops as the equivalent of commas), e.g. 1,200.5 would be written as 1.200,5 in the European format. :param str string: A representation of the value as a string :return...
bigcode/self-oss-instruct-sc2-concepts
import torch def box_iou(boxes1, boxes2): """Compute IOU between two sets of boxes of shape (N,4) and (M,4).""" # Compute box areas box_area = lambda boxes: ((boxes[:, 2] - boxes[:, 0]) * (boxes[:, 3] - boxes[:, 1])) area1 = box_area(boxes1) area2 = box_area(boxes2) ...
bigcode/self-oss-instruct-sc2-concepts
import requests def fetch_json(uri): """Perform an HTTP GET on the given uri, return the results as json. If there is an error fetching the data, raise an exception. Args: uri: the string URI to fetch. Returns: A JSON object with the response. """ data = requests.get(uri) ...
bigcode/self-oss-instruct-sc2-concepts
def my_method2(o): """ This is anoooother doctring of a method living inside package1. Why? Just because I wanted to have more than one. Parameters ---------- o : int Note that this parameter should be a string because it wanted to be different. Returns ------- Five...
bigcode/self-oss-instruct-sc2-concepts
import requests def authenticate_with_refresh_token(client_id, redirect_uri, refresh_token): """Get an access token with the existing refresh token.""" try: url = 'https://api.tdameritrade.com/v1/oauth2/token' headers = { 'Content-Type': 'application/x-www-form-urlencoded' ...
bigcode/self-oss-instruct-sc2-concepts
def root_center(X, root_idx=0): """Subtract the value at root index to make the coordinates center around root. Useful for hip-centering the skeleton. :param X: Position of joints (NxMx2) or (NxMx3) :type X: numpy.ndarray :param root_idx: Root/Hip index, defaults to 0 :type root_idx...
bigcode/self-oss-instruct-sc2-concepts
def getOperands(inst): """ Get the inputs of the instruction Input: - inst: The instruction list Output: - Returns the inputs of the instruction """ if inst[0] == "00100": return inst[3], inst[4] else: return inst[2], inst[3]
bigcode/self-oss-instruct-sc2-concepts
def checkfile(findstring, fname): """ Checks whether the string can be found in a file """ if findstring in open(fname).read(): #print(findstring, "found in", fname) return True return False
bigcode/self-oss-instruct-sc2-concepts
def crop_region(image, region): """Crops a singular region in an image Args: image (image): A numpy image region (dict): A dictionary containing x1, y1, x2, y2 Returns: image: The cropped image """ return image[ region["y1"]:region["y2"], region["x1"]:region["x2"] ]
bigcode/self-oss-instruct-sc2-concepts
from typing import Sequence import random def sample_coins(coin_biases: Sequence[float]) -> int: """Return integer where bits bias towards 1 as described in coin_biases.""" result = 0 for i, bias in enumerate(coin_biases): result |= int(random.random() < bias) << i return result
bigcode/self-oss-instruct-sc2-concepts
import inspect def get_wrapped_source(f): """ Gets the text of the source code for the given function :param f: Input function :return: Source """ if hasattr(f, "__wrapped__"): # has __wrapped__, going deep return get_wrapped_source(f.__wrapped__) else: # Returning ...
bigcode/self-oss-instruct-sc2-concepts
def pad_sentences(sentences,padding_word="<PAD/>"): """ 填充句子,使所有句子句子长度等于最大句子长度 :param sentences: :param padding_word: :return: padded_sentences """ sequence_length=max(len(x) for x in sentences) padded_sentences=[] for i in range(len(sentences)): sentence=sentences[i] ...
bigcode/self-oss-instruct-sc2-concepts
def get_util2d_shape_for_layer(model, layer=0): """ Define nrow and ncol for array (Util2d) shape of a given layer in structured and/or unstructured models. Parameters ---------- model : model object model for which Util2d shape is sought. layer : int layer (base 0) for whic...
bigcode/self-oss-instruct-sc2-concepts
from typing import Any def is_of_type_by_str(value: Any, type_str: str): """ Check if the type of ``value`` is ``type_str``. Parameters ---------- value: any a value type_str: str the expected type of ``value``, given as a str Examples -------- >>> is_of_type_by_...
bigcode/self-oss-instruct-sc2-concepts
def default(base, deft): """Return the deft value if base is not set. Otherwise, return base""" if base == 0.0: return base return base or deft
bigcode/self-oss-instruct-sc2-concepts
def points_to_svgd(p, close=True): """ convert list of points (x,y) pairs into a closed SVG path list """ f = p[0] p = p[1:] svgd = 'M%.4f,%.4f' % f for x in p: svgd += 'L%.4f,%.4f' % x if close: svgd += 'z' return svgd
bigcode/self-oss-instruct-sc2-concepts
def __nnc_values_generator_to_list(self, generator): """Converts a NNC values generator to a list.""" vals = [] for chunk in generator: for value in chunk.values: vals.append(value) return vals
bigcode/self-oss-instruct-sc2-concepts
import re def camel_to_snake_case(in_str): """ Convert camel case to snake case :param in_str: camel case formatted string :return snake case formatted string """ return '_'.join(re.split('(?=[A-Z])', in_str)).lower()
bigcode/self-oss-instruct-sc2-concepts
def get_collection_fmt_desc(colltype): """Return the appropriate description for a collection type. E.g. tsv needs to indicate that the items should be tab separated, csv comma separated, etc... """ seps = dict( csv='Multiple items can be separated with a comma', ssv='Multiple items...
bigcode/self-oss-instruct-sc2-concepts
from typing import Callable def interpolator(source_low: float, source_high: float, dest_low: float = 0, dest_high: float = 1, lock_range=False) -> Callable[[float], float]: """ General interpolation function factory :param source_low: Low input value :param ...
bigcode/self-oss-instruct-sc2-concepts
import struct def of_slicer(remaining_data): """Slice a raw bytes into OpenFlow packets""" data_len = len(remaining_data) pkts = [] while data_len > 3: length_field = struct.unpack('!H', remaining_data[2:4])[0] if data_len >= length_field: pkts.append(remaining_data[:length...
bigcode/self-oss-instruct-sc2-concepts
def ne(value, other): """Not equal""" return value != other
bigcode/self-oss-instruct-sc2-concepts
def type_match(haystack, needle): """Check whether the needle list is fully contained within the haystack list, starting from the front.""" if len(needle) > len(haystack): return False for idx in range(0, len(needle)): if haystack[idx] != needle[idx]: return False return ...
bigcode/self-oss-instruct-sc2-concepts
def get_range(xf, yf, low, high): """Gets the values in a range of frequencies. Arguments: xf: A list of frequencies, generated by rfftfreq yf: The amplitudes of frequencies, generated by rfft low: Lower bound of frequency to capture high: Upper bound of frequency to capture ...
bigcode/self-oss-instruct-sc2-concepts
import pickle def pickle_load(path): """Un-pickles a file provided at the input path Parameters ---------- path : str path of the pickle file to read Returns ------- dict data that was stored in the input pickle file """ with open(path, 'rb') as f: return...
bigcode/self-oss-instruct-sc2-concepts
from typing import Any import json def is_json_serializable(obj: Any) -> bool: """Check if the object is json serializable Args: obj (Any): object Returns: bool: True for a json serializable object """ try: json.dumps(obj, ensure_ascii=False) return True except: return False
bigcode/self-oss-instruct-sc2-concepts
def shortest_path(g, start, goal): """ Complete BFS via MIT algorith g -> Graph represented via Adjacency list (Dict of sets) start -> start vertex goal -> end vertex Returns shortests path from start to goal """ # level will contains shortest path for each vertex to start level = {sta...
bigcode/self-oss-instruct-sc2-concepts
import re def fix_links(chunk, tag2file): """Find and fix the the destinations of hyperlinks using HTML or markdown syntax Fix any link in a string text so that they can target a different html document. First use regex on a HTML text to find any HTML or markdown hyperlinks (e.g. <a href="#sec1"> or ...
bigcode/self-oss-instruct-sc2-concepts
def is_numeric(value): """Test if a value is numeric.""" return isinstance(value, int) or isinstance(value, float)
bigcode/self-oss-instruct-sc2-concepts
def value_of(column): """value_of({'S': 'Space Invaders'}) -> 'Space Invaders'""" return next(iter(column.values()))
bigcode/self-oss-instruct-sc2-concepts
import six import json import zlib import base64 def send_request(req_url, req_json={}, compress=False, post=True, api_key=None): """ Sends a POST/GET request to req_url with req_json, default to POST. Returns: The payload returned by sending the POST/GET request formatted as a dict. """ # Get the...
bigcode/self-oss-instruct-sc2-concepts
import re def isEndStoryText(string): """ Return True if reach the end of stories. """ match = re.search(r'^\*\*\*', string) if match == None: r = False else: r = True return r
bigcode/self-oss-instruct-sc2-concepts
def depth(obj): """ Calculate the depth of a list object obj. Return 0 if obj is a non-list, or 1 + maximum depth of elements of obj, a possibly nested list of objects. Assume: obj has finite nesting depth @param int|list[int|list[...]] obj: possibly nested list of objects @rtype: int ...
bigcode/self-oss-instruct-sc2-concepts
def example(self): """Get and cache an example batch of `inputs, labels` for plotting.""" result = getattr(self, '_example', None) if result is None: # No example batch was found, so get one from the `.train` dataset result = next(iter(self.train)) # And cache it for next time self._example = resu...
bigcode/self-oss-instruct-sc2-concepts
from typing import List def _get_name_matches(name: str, guess_words: List[str]) -> int: """ Return the number of common words in a str and list of words :param name: :param guess_words: :return: number of matches """ matches = sum(word in name for word in guess_words) return matches
bigcode/self-oss-instruct-sc2-concepts
def repo_url_to_full_name(url): """Convert a repository absolute URL to ``full_name`` format used by Github. Parameters ---------- url : str URL of the repository. Returns ------- url : str Full name of the repository accordingly with Github API. """ return "/".join(u...
bigcode/self-oss-instruct-sc2-concepts
def calculate_variance(n, p): """ Calculate the sample variance for a binominal distribution """ return p * (1 - p) / n
bigcode/self-oss-instruct-sc2-concepts
def _arguments_str_from_dictionary(options): """ Convert method options passed as a dictionary to a str object having the form of the method arguments """ option_string = "" for k in options: if isinstance(options[k], str): option_string += k+"='"+str(options[k])+"'," ...
bigcode/self-oss-instruct-sc2-concepts
def transpose(matrix): """ Takes transpose of the input matrix. Args: matrix: 2D list Return: result: 2D list """ result = [[matrix[col][row] for col in range(len(matrix))] for row in range(len(matrix[0])) ] return result
bigcode/self-oss-instruct-sc2-concepts
from typing import Optional from typing import Dict from typing import Any import jinja2 def merge_template(template_filename: str, config: Optional[Dict[str, Any]]) -> str: """Load a Jinja2 template from file and merge configuration.""" # Step 1: get raw content as a string with open(template_filename) a...
bigcode/self-oss-instruct-sc2-concepts
def anonymise_max_length_pk(instance, field): """ Handle scenarios where the field has a max_length which makes it smaller than the pk (i.e UUID). """ if hasattr(field, "max_length") and field.max_length and len(str(instance.pk)) > field.max_length: return str(instance.pk)[:field.max_length]...
bigcode/self-oss-instruct-sc2-concepts
import torch from typing import List def _decode(loc: torch.Tensor, priors: torch.Tensor, variances: List[float]) -> torch.Tensor: """Decode locations from predictions using priors to undo the encoding we did for offset regression at train time. Args: loc:location predictions for loc layers. Shap...
bigcode/self-oss-instruct-sc2-concepts
def wrap_argument(text): """ Wrap command argument in quotes and escape when this contains special characters. """ if not any(x in text for x in [' ', '"', "'", '\\']): return text else: return '"%s"' % (text.replace('\\', r'\\').replace('"', r'\"'), )
bigcode/self-oss-instruct-sc2-concepts
def filter_dict(pred, d) : """Return a subset of the dictionary d, consisting only of the keys that satisfy pred(key).""" ret = {} for k in d : if pred(k) : ret[k] = d[k] return ret
bigcode/self-oss-instruct-sc2-concepts
import json def df_to_dict(df, orient='None'): """ Replacement for pandas' to_dict which has trouble with upcasting ints to floats in the case of other floats being there. https://github.com/pandas-dev/pandas/issues/12859#issuecomment-208319535 see also https://stackoverflow.com/questions/37897527...
bigcode/self-oss-instruct-sc2-concepts
def create_data_model(distancematrix): """ Create a dictionary/data model Parameters: distancematrix (float[][]): array of distances between addresses Returns: dictionary: data model generated """ # initiate ORTools data = {} data['distance_matrix'] = distancematrix ...
bigcode/self-oss-instruct-sc2-concepts
def read_scores_into_list(scores_file): """ Read in scores file, where scores are stored in 2nd column. """ scores_list = [] with open(scores_file) as f: for line in f: cols = line.strip().split("\t") scores_list.append(float(cols[1])) f.closed assert scores_...
bigcode/self-oss-instruct-sc2-concepts
def fields(cursor): """ Given a DB API 2.0 cursor object that has been executed, returns a dictionary that maps each field name to a column index, 0 and up. """ results = {} for column, desc in enumerate(cursor.description): results[desc[0]] = column return results
bigcode/self-oss-instruct-sc2-concepts
def introspection_email(request): """Returns the email to be returned by the introspection endpoint.""" return request.param if hasattr(request, 'param') else None
bigcode/self-oss-instruct-sc2-concepts
def submat(M,i,j): """ return a copy of matrix `M` whitout row `i` and column `j` """ N = M.copy() N.row_del(i) N.col_del(j) return N
bigcode/self-oss-instruct-sc2-concepts
import json def parse_data_file(data_path): """ Parse data file with benchmark run results. """ with open(data_path, "r") as fp: content = fp.read() data = json.loads(content) return data
bigcode/self-oss-instruct-sc2-concepts
import re def splitTypeName(name): """ Split the vendor from the name. splitTypeName('FooTypeEXT') => ('FooType', 'EXT'). """ suffixMatch = re.search(r'[A-Z][A-Z]+$', name) prefix = name suffix = '' if suffixMatch: suffix = suffixMatch.group() prefix = name[:-len(suffix)] ret...
bigcode/self-oss-instruct-sc2-concepts
from typing import Dict def stream_error(e: BaseException, line: str) -> Dict: """ Return an error `_jc_meta` field. """ return { '_jc_meta': { 'success': False, 'error': f'{e.__class__.__name__}: {e}', 'line': line.strip() ...
bigcode/self-oss-instruct-sc2-concepts
def import_object(name): """Function that returns a class in a module given its dot import statement.""" name_module, name_class = name.rsplit('.', 1) module = __import__(name_module, fromlist=[name_class]) return getattr(module, name_class)
bigcode/self-oss-instruct-sc2-concepts
def is_numeric(value): """ check whether a value is numeric (could be float, int, or numpy numeric type) """ return hasattr(value, "__sub__") and hasattr(value, "__mul__")
bigcode/self-oss-instruct-sc2-concepts
def has_extension(filepath, extensions): """Check if file extension is in given extensions.""" return any(filepath.endswith(ext) for ext in extensions)
bigcode/self-oss-instruct-sc2-concepts
def to_basestring(s): """Converts a string argument to a byte string. If the argument is already a byte string, it is returned unchanged. Otherwise it must be a unicode string and is encoded as utf8. """ if isinstance(s, bytes): return s return s.encode('utf-8')
bigcode/self-oss-instruct-sc2-concepts
def cross(str_a, str_b): """Cross product (concatenation) of two strings A and B.""" return [a + b for a in str_a for b in str_b]
bigcode/self-oss-instruct-sc2-concepts
def getKeyNamePath(kms_client, project_id, location, key_ring, key_name): """ Args: kms_client: Client instantiation project_id: str - location: str - key_ring: str - key_name: str - Returns: key_name: str - 'projects/YOUR_GCLOUD_PROJECT/locations/YOUR_LOCATION/keyR...
bigcode/self-oss-instruct-sc2-concepts
def num_pos(y_test): """ Gets number of positive labels in test set. :param y_test: Labels of test set :type nb_points: `np.array` :return: number of positive labels :rtype: `int` """ if y_test == []: return 0 else: return sum(y_test)
bigcode/self-oss-instruct-sc2-concepts
def location(C,s,k): """ Computes the location corresponding to the k-value along a segment of a polyline Parameters ---------- C : [(x,y),...] list of tuples The coordinates of the polyline. s : int The index of a segment on polyline C. Must be within [0,n-2] k : float ...
bigcode/self-oss-instruct-sc2-concepts
import re def matchLettersAndNumbersOnly(value): """Match strings of letters and numbers.""" if re.match('^[a-zA-Z0-9]+$', value): return True return False
bigcode/self-oss-instruct-sc2-concepts
import math def haversine_distance(origin, destination): """ Haversine formula to calculate the distance between two lat/long points on a sphere """ radius = 6371.0 # FAA approved globe radius in km dlat = math.radians(destination[0]-origin[0]) dlon = math.radians(destination[1]-origin[1]) a = math.sin(dl...
bigcode/self-oss-instruct-sc2-concepts
from pathlib import Path from typing import Union import hashlib import re def insert_hash(path: Path, content: Union[str, bytes], *, hash_length=7, hash_algorithm=hashlib.md5): """ Insert a hash based on the content into the path after the first dot. hash_length 7 matches git commit short references ...
bigcode/self-oss-instruct-sc2-concepts
def build_dataservices_by_publisher_query() -> str: """Build query to count dataservices grouped by publisher.""" return """ PREFIX dct: <http://purl.org/dc/terms/> PREFIX dcat: <http://www.w3.org/ns/dcat#> SELECT ?organizationNumber (COUNT(DISTINCT ?service) AS ?count) FROM <https://dataservices.fellesdatakata...
bigcode/self-oss-instruct-sc2-concepts
async def get_action(game_state, message: str, possible_actions: list) -> int: """ Helper function used to get action from player for current state of game. :param game_state: GameState object with all game data inside :param message: string with message for player :param possible_actions: list with...
bigcode/self-oss-instruct-sc2-concepts
def human_file_size(bytes_): """ Formats the value like a 'human-readable' file size (i.e. 13 KB, 4.1 MB, 102 bytes, etc.). """ try: bytes_ = float(bytes_) except (TypeError, ValueError, UnicodeDecodeError): return '0 bytes' def filesize_number_format(value): return ...
bigcode/self-oss-instruct-sc2-concepts
def square(file_index, rank_index): """Gets a square number by file and rank index.""" return rank_index * 8 + file_index
bigcode/self-oss-instruct-sc2-concepts
from typing import Tuple def file_name_to_parts(image_file_name) -> Tuple[str, str, int]: """ Given the `file_name` field in an iMerit annotation, return the dataset name, sequence id and frame number. """ parts = image_file_name.split('.') dataset_name = parts[0] seq_id = parts[1].split('...
bigcode/self-oss-instruct-sc2-concepts
import collections def trainval_log_statistic(trainval_log): """ Args: trainval_log (dict): output of function: read_trainval_log_file :return: e.g.: >>> result = { >>> 'total_epoch': 100, >>> 'last_top-1_val_accuracy': 0.87, >>> 'last_top-2_val_accuracy': 0.95, ...
bigcode/self-oss-instruct-sc2-concepts
import hashlib def sha256_encode(text): """ Returns the digest of SHA-256 of the text """ _hash = hashlib.sha256 if type(text) is str: return _hash(text.encode('utf8')).digest() elif type(text) is bytes: return _hash(text).digest() elif not text: # Generally for cal...
bigcode/self-oss-instruct-sc2-concepts
def is_current_or_ancestor(page, current_page): """Returns True if the given page is the current page or is an ancestor of the current page.""" return current_page.is_current_or_ancestor(page)
bigcode/self-oss-instruct-sc2-concepts
def buildVecWithFunction(da, func, extra_args=()): """ Construct a vector using a function applied on each point of the mesh. Parameters ========== da : petsc.DMDA The mesh structure. func: function Function to apply on each point. extra_args: tuple extra para...
bigcode/self-oss-instruct-sc2-concepts
def _clean_sambam_id(inputname: str) -> str: """Sometimes there are additional characters in the fast5 names added on by albacore or MinKnow. They have variable length, so this attempts to clean the name to match what is stored by the fast5 files. There are 5 fields. The first has a variable length. ...
bigcode/self-oss-instruct-sc2-concepts
import json def validate_invoking_event(event): """Verify the invoking event has all the necessary data fields.""" if 'invokingEvent' in event: invoking_event = json.loads(event['invokingEvent']) else: raise Exception('Error, invokingEvent not found in event, aborting.') if 'resultToke...
bigcode/self-oss-instruct-sc2-concepts
import math def get_oversized(length): """ The oddeven network requires a power-of-2 length. This method computes the next power-of-2 from the *length* if *length* is not a power-of-2 value. """ return 2 ** math.ceil(math.log2(length))
bigcode/self-oss-instruct-sc2-concepts
def is_set(obj) -> bool: """Checks if the given object is either a set or a frozenset.""" return isinstance(obj, (set, frozenset))
bigcode/self-oss-instruct-sc2-concepts
def _csv_dict_row(user, mode, **kwargs): """ Convenience method to create dicts to pass to csv_import """ csv_dict_row = dict(kwargs) csv_dict_row['user'] = user csv_dict_row['mode'] = mode return csv_dict_row
bigcode/self-oss-instruct-sc2-concepts
def divide(a, b): """Divide two numbers and return the quotient""" #Perform the division if the denominator is not zero if b != 0: quotient = round(a/b, 4) print("The quotient of " + str(a) + " and " + str(b) + " is " + str(quotient) + ".") return str(a) + " / " + str(b) + " = " + st...
bigcode/self-oss-instruct-sc2-concepts
import math def Euclidean_distance(x,y): """ Given two vectors, calculate the euclidean distance between them. Input: Two vectors Output: Distance """ D = math.sqrt(sum([(a-b)**2 for a,b in zip(x,y)])) return D
bigcode/self-oss-instruct-sc2-concepts
from typing import Tuple def neighbors(depths: list[list[int]], x: int, y: int) -> list[Tuple[int, int]]: """Generate the list of neighboring points for the given point""" max_x = len(depths[0]) max_y = len(depths) result = [] for _x, _y in [(x - 1, y), (x + 1, y), (x, y - 1), (x, y + 1)]: ...
bigcode/self-oss-instruct-sc2-concepts
import re def capitalise_chi(value): """CHI at the start of shelfmarks should always be capitalised.""" return re.sub(r'(?i)^chi\.', 'CHI.', value)
bigcode/self-oss-instruct-sc2-concepts
def copy_doc(source): """Copy the docstring from another function (decorator). The docstring of the source function is prepepended to the docstring of the function wrapped by this decorator. This is useful when inheriting from a class and overloading a method. This decorator can be used to copy th...
bigcode/self-oss-instruct-sc2-concepts
import string def ishex(hexstr): """Checks if string is hexidecimal""" return all(char in string.hexdigits for char in hexstr)
bigcode/self-oss-instruct-sc2-concepts
def build_ig_bio(part_of_day, sky_cond, sky_emoji, temp_feel): """Builds IG bio.""" return f"Back page of the internet.\n\nI look up this {part_of_day} and the Toronto sky looks like {sky_cond}{sky_emoji}.\nKinda feels like {temp_feel}\u00b0C."
bigcode/self-oss-instruct-sc2-concepts
def _get_num_to_fold(stretch: float, ngates: int) -> int: """Returns the number of gates to fold to achieve the desired (approximate) stretch factor. Args: stretch: Floating point value to stretch the circuit by. ngates: Number of gates in the circuit to stretch. """ return int(roun...
bigcode/self-oss-instruct-sc2-concepts
import re def lreplace(pattern, sub, string): """ Replaces 'pattern' in 'string' with 'sub' if 'pattern' starts 'string'. """ return re.sub('^%s' % pattern, sub, string)
bigcode/self-oss-instruct-sc2-concepts