seed
stringlengths
1
14k
source
stringclasses
2 values
def comma_join(items, stringify=False): """ Joins an iterable of strings with commas. """ if stringify: return ', '.join(str(item) for item in items) else: return ', '.join(items)
bigcode/self-oss-instruct-sc2-concepts
import math def polar_to_cartesian(r, theta, r_ref=0.0, theta_ref=0.0): """ Helper function to convert polar coordinates to Cartesian coordinates (relative to a defined reference point). :Parameters: r: float Radial distance of point from origin. theta: float Angular bearing...
bigcode/self-oss-instruct-sc2-concepts
from pathlib import Path def make_paths_absolute(value: str, workdir: Path = Path.cwd()) -> str: """ Detect if value is a relative path and make it absolut if so. :param value: Parameter value from arguments :param workdir: Path to workdir. Default: CWD :return: """ if "../" in value and (...
bigcode/self-oss-instruct-sc2-concepts
from typing import Dict import math def position_distance(a: Dict[str, float], b: Dict[str, float]) -> float: """Compute the distance between two positions.""" return math.sqrt((a['x'] - b['x'])**2 + (a['y'] - b['y'])**2 + (a['z'] - b['z'])**2)
bigcode/self-oss-instruct-sc2-concepts
def fix_strength(val, default): """ Assigns given strength to a default value if needed. """ return val and int(val) or default
bigcode/self-oss-instruct-sc2-concepts
def get_refs_from_soup(soup): """get_refs_from_soup. Returns a list of `<cite>` tags from the passed BeautifulSoup object. :param soup: BeautifulSoup object (parsed HTML) """ return soup.find_all('cite', recursive=True)
bigcode/self-oss-instruct-sc2-concepts
def get_target_value(data_frame, target_type): """ Get the value of a specific target from the engineered features pandas data frame. :param data_frame: The engineered features pandas data frame. :param target_type: The name of the prediction target. :return: The prediction target value. """ ...
bigcode/self-oss-instruct-sc2-concepts
import string def filename_from_string(text): """Produces a valid (space-free) filename from some text""" text = text.lower() valid_chars = "-_." + string.ascii_letters + string.digits return ''.join(c for c in text if c in valid_chars)
bigcode/self-oss-instruct-sc2-concepts
from pathlib import Path from typing import List def read_tabular_data(filename: Path) -> List[List[float]]: """Reads a tabular data file, skipping comment lines. Args: filename (Path): The full path of the file to be read Returns: List[List[float]]: The file contents, with comment lines...
bigcode/self-oss-instruct-sc2-concepts
def _tile_url(tile_format, x, y, zoom): """Build S3 URL prefix The S3 bucket is organized {tile_format}/{z}/{x}/{y}.tif Parameters ---------- tile_format : str One of 'terrarium', 'normal', 'geotiff' zoom : int zoom level x : int x tilespace coordinate y : int ...
bigcode/self-oss-instruct-sc2-concepts
def parse_opcode(token): """Extract the opcode and the mode of all params""" opcode = token % 100 modes = [0, 0, 0, 0] if token > 100: for (i, mode) in enumerate(str(token)[-3::-1]): modes[i] = int(mode) return opcode, modes
bigcode/self-oss-instruct-sc2-concepts
def _desc_has_possible_number_data(desc): """Returns true if there is any possible number data set for a particular PhoneNumberDesc.""" # If this is empty, it means numbers of this type inherit from the "general desc" -> the value # "-1" means that no numbers exist for this type. if desc is None: ...
bigcode/self-oss-instruct-sc2-concepts
import pickle def load_pickle(path): """ Load object from path :param path: path to pickle file :type path: str :return: object """ with open(path, 'rb') as f: obj = pickle.load(f) return obj
bigcode/self-oss-instruct-sc2-concepts
def has_dtypes(df, items): """ Assert that a DataFrame has ``dtypes`` Parameters ========== df: DataFrame items: dict mapping of columns to dtype. Returns ======= df : DataFrame """ dtypes = df.dtypes for k, v in items.items(): if not dtypes[k] == v: ...
bigcode/self-oss-instruct-sc2-concepts
def parse_filename(filename): # time_tag=TIME_INFOLDER_TAG, # time_fmt=TIME_INFILE_FMT, # ): """Parse Hive and RPi number from filename. Filename e.g.: raw_hive1_rpi1_190801-000002-utc.jpg """ prefix, hive_str, rpi_str, t_str = filename.split("_") ...
bigcode/self-oss-instruct-sc2-concepts
def do_steps_help(cls_list): """Print out the help for the given steps classes.""" for cls in cls_list: print(cls.help()) return 0
bigcode/self-oss-instruct-sc2-concepts
def bbox_to_pptx(left, bottom, width, height): """ Convert matplotlib bounding box format to pptx format Parameters ---------- bottom : float left : float width : float height : float Returns ------- left, top, width, height """ return left, bottom-height, width, heig...
bigcode/self-oss-instruct-sc2-concepts
def get_ids(cls, inherit=None): """Function that returns all the IDs to use as primary key For a given class, this function will check for the _ids parameter and call itself recursively on the given class' base classes to append all other required IDs, thus generating the list of parameters to use as ...
bigcode/self-oss-instruct-sc2-concepts
import itertools def createListWord(n): """Creates the list of word with size n on the alphabet {1,2,3,4}.""" temp = [''.join(x) for x in itertools.product('1234', repeat=n)] L = [int(y) for y in temp] return L
bigcode/self-oss-instruct-sc2-concepts
def build_group_id(ad, desc_list, prettify=(), force_list=(), additional=None): """ Builds a Group ID from information found in the descriptors. It takes a number of descriptor names, invokes and then concatenates their result (converted to string) to from a group ID. Additional parameters can be passe...
bigcode/self-oss-instruct-sc2-concepts
import random def tirage_uniforme(min, max): """ Renvoie un nombre décimal (float) choisi de manière (pseudo)aléatoire et uniforme de l'intervalle \[``min`` ; ``max``\[. Arguments: min (float): Un nombre réel. max (float): Un nombre réel. """ return random.uniform(min, max)
bigcode/self-oss-instruct-sc2-concepts
def greet(greeting, name): """Returns a greeting Args: greeting (string): A greet word name (string): A persons name Returns: string -- A greeting with a name """ return f'{greeting} {name}'
bigcode/self-oss-instruct-sc2-concepts
def _is_parameter_for(name, container, docmap): """ @rtype: C{boolean} @return: True if C{name} is the name of a parameter for the routine C{container}, given the DocMap C{docmap}. """ if docmap is None or not docmap.has_key(container): return 0 container_doc = docmap.get(container) if c...
bigcode/self-oss-instruct-sc2-concepts
def is_lvm(name): """ Check if device is marked as an lvm """ if "lvm" in name: return True return False
bigcode/self-oss-instruct-sc2-concepts
def place_figures(figures): """Generate LaTeX code for figure placement. Parameters ---------- figures : list List holding LaTeX code of individual figures to be placed in document. Returns ------- latex : str LaTeX code for figure alignment. """ latex = '' num_...
bigcode/self-oss-instruct-sc2-concepts
import random def scramble_word(word: str) -> str: """Return a scrambled version of the word.""" return ''.join(random.sample(word, k=len(word)))
bigcode/self-oss-instruct-sc2-concepts
def _get_node_name_prefix(node_name): """ Returns the node name prefix, without phase character or trailing whitespaces. """ wows_name = node_name.strip() return wows_name[:-1]
bigcode/self-oss-instruct-sc2-concepts
def file_requires_unicode(x): """ Return whether the given writable file-like object requires Unicode to be written to it. """ try: x.write(b'') except TypeError: return True else: return False
bigcode/self-oss-instruct-sc2-concepts
def get_type_name(value_type): """Returns the name of the given type.""" return value_type.__name__
bigcode/self-oss-instruct-sc2-concepts
def runge_kutta_fourth_xy(rhs, h, x, y): """ Solves one step using a fourth-order Runge-Kutta method. RHS expects both x and y variables. Moin, P. 2010. Fundamentals of Engineering Numerical Analysis. 2nd ed. Cambridge University Press. New York, New York. :param rhs: "Right-hand Side" of the equa...
bigcode/self-oss-instruct-sc2-concepts
def ptbunescape(token): """Unescape brackets in a single token, including PTB notation.""" if token in ('', '#FRONTIER#', None): return None elif token == '-LCB-': return '{' elif token == '-RCB-': return '}' elif token == '-LSB-': return '[' elif token == '-RSB-': return ']' return token.replace('-LRB...
bigcode/self-oss-instruct-sc2-concepts
def mean(list): """ Calcula a média de um vetor de números. Args: list (list): vetor de números Returns: (float) média dos números """ return sum(list) / len(list)
bigcode/self-oss-instruct-sc2-concepts
def parse_config(configfile): """Parse the config file 'configfile' and return the parsed key-value pairs as dict""" return {k:v for k,v in map(lambda x: x.strip().split('='), filter(lambda x: not x.strip().startswith('#'), (line for line in open(configfile))))}
bigcode/self-oss-instruct-sc2-concepts
def parse_id(string): """Returns the UUID part of a string only.""" return string.split('/')[-1]
bigcode/self-oss-instruct-sc2-concepts
def formalize_bbox(_im_summary): """ Extract bboxes from all classes and return a list of bbox. Each element of the list is in the form: [x1, y1, x2, y2, class_id, score]. The returned list is sorted descendingly according to score. """ boxes = [] # each element: x, y, w, h, class_id, score ...
bigcode/self-oss-instruct-sc2-concepts
def row_full(row, puzzle): """ Takes a row number, and a sudoku puzzle as parameter Returns True if there is no empty space on the row ReturnsFalse if otherwise """ for col in range(0, 9): if puzzle[row][col] == -1: return False return True
bigcode/self-oss-instruct-sc2-concepts
def collect_families_from_instances(instances, only_active=False): """Collect all families for passed publish instances. Args: instances(list<pyblish.api.Instance>): List of publish instances from which are families collected. only_active(bool): Return families only for active insta...
bigcode/self-oss-instruct-sc2-concepts
def isvlan(value): """Checks if the argument is a valid VLAN A valid VLAN is an integer value in the range of 1 to 4094. This function will test if the argument falls into the specified range and is considered a valid VLAN Args: value: The value to check if is a valid VLAN Returns: ...
bigcode/self-oss-instruct-sc2-concepts
def parse(utxo, offset=0): """ Parses a given serialized UTXO to extract a base-128 varint. :param utxo: Serialized UTXO from which the varint will be parsed. :type utxo: hex str :param offset: Offset where the beginning of the varint if located in the UTXO. :type offset: int :return: The extrac...
bigcode/self-oss-instruct-sc2-concepts
def _list_readline(x): """Given a list, returns a readline() function that returns the next element with each call. """ x = iter(x) def readline(): return next(x) return readline
bigcode/self-oss-instruct-sc2-concepts
import random import string def random_string(nlen): """Create random string which length is `nlen`.""" return "".join([random.choice(string.ascii_lowercase) for _ in range(nlen)])
bigcode/self-oss-instruct-sc2-concepts
def match_word(encoded_word, words_list): """ Find first probably correct word based on list of words and given encoded word. """ results = [] for word in words_list: #skip all items with different first and last char if word[0] != encoded_word[0] or word[-1] != encoded_word[-1]:...
bigcode/self-oss-instruct-sc2-concepts
def extract_meta_from_keys(keys, prefix): """Extract metadata contained in a key's name. Parameters ---------- keys : list of strings prefix : string Returns ------- meta : string """ return next(k[len(prefix):] for k in keys if k.startswith(prefix))
bigcode/self-oss-instruct-sc2-concepts
def ChannelFirst(arr): """Convert a HWC array to CHW.""" ndim = arr.ndim return arr.swapaxes(ndim - 1, ndim - 2).swapaxes(ndim - 2, ndim - 3)
bigcode/self-oss-instruct-sc2-concepts
import torch def exp(x): """ The exponential link function given by $$ y = e^{x} $$ """ return torch.exp(x)
bigcode/self-oss-instruct-sc2-concepts
def get_linef(fp, line_no): """'fp' should be (readable) file object. Return the line content at line_no or an empty line if there is less lines than line_no. """ fp.seek(0) for line in fp: line_no -= 1 if line_no == 0: return line return ''
bigcode/self-oss-instruct-sc2-concepts
def make_1024_list() : """ Generates a list of 1024 strings of numbers in the format "XXXX", filled with zeros before the number. It is here to translate integers into the format used in the dataset (+1 because the list starts at "0001"). :return: returns a list of 1024 strings """ list = [] for x in ran...
bigcode/self-oss-instruct-sc2-concepts
import collections def longest_path(current_state): """Find longest possible path from the current state to the final state Args: current_state: StateForGraphs The state at the beginning of the search; the root of the tree. Returns: The maximum number of steps that can be use...
bigcode/self-oss-instruct-sc2-concepts
def get_topic_key(project_name, topic): """ Get the topic key for a project name and a topic :param project_name: project name :param topic: topic :return: topic key """ return f"{project_name}/{topic}"
bigcode/self-oss-instruct-sc2-concepts
def nvl(*args): """ SQL like coelesce / redshift NVL, returns first non Falsey arg """ for arg in args: try: if arg: return arg except ValueError: if arg is not None: return arg return args[-1]
bigcode/self-oss-instruct-sc2-concepts
def parseFields(fields, output): """ Take a string of fields encoded as key1=value1,key2=value2,... and add the keys and values to the output dict""" for field in fields.split('|'): key, value = field.split('=') try: value = int(value) except: pass output[key] = value return output
bigcode/self-oss-instruct-sc2-concepts
def to_camel_case(snake_str): """ Transforms a snake_case string into camelCase. Parameters ---------- snake_str : str Returns ------- str """ parts = snake_str.split("_") # We capitalize the first letter of each component except the first one # with the 'title' method ...
bigcode/self-oss-instruct-sc2-concepts
def to_bytes(s, encoding="utf-8"): """Convert a text string (unicode) to bytestring, i.e. str on Py2 and bytes on Py3.""" if type(s) is not bytes: s = bytes(s, encoding) return s
bigcode/self-oss-instruct-sc2-concepts
from typing import List from typing import Counter def top_k_frequent_bucket_sort(nums: List[int], k: int) -> List[int]: """Given a list of numbers, return the the top k most frequent numbers. Solved using buckets sort approach. Example: nums: [1, 1, 1, 2, 2, 3], k=2 output: [1, 2] ...
bigcode/self-oss-instruct-sc2-concepts
import re def increment(s): """ look for the last sequence of number(s) in a string and increment """ lastNum = re.compile(r'(?:[^\d]*(\d+)[^\d]*)+') m = lastNum.search(s) if m: next = str(int(m.group(1))+1) start, end = m.span(1) s = s[:max(end-len(next), start)] + next + s[en...
bigcode/self-oss-instruct-sc2-concepts
def _check_delimiter(output_filename, delim=None): """Detect delimiter by filename extension if not set""" if output_filename and (delim is None): delimiters = {"tsv": "\t", "csv": ","} delim = delimiters[output_filename.rsplit(".", 1)[-1].lower()] assert delim, "File output delimiter no...
bigcode/self-oss-instruct-sc2-concepts
from typing import Counter def precision_recall_f1(prediction, ground_truth): """ This function calculates and returns the precision, recall and f1-score Args: prediction: prediction string or list to be matched ground_truth: golden string or list reference Returns: floats of (...
bigcode/self-oss-instruct-sc2-concepts
from bs4 import BeautifulSoup import requests def fetch_page(url, method, **kwargs) -> BeautifulSoup: """Execute request for page and return as soup""" ret = requests.request(method, url, **kwargs) if ret.status_code != 200: raise Exception(f"Page {url} returned {ret.status_code}") return Be...
bigcode/self-oss-instruct-sc2-concepts
def on_off(image, w, h, threshold=128): """ Black and white (no greyscale) with a simple threshold. If the color is dark enough, the laser is on! """ result = [] for row in image: result_row = [] for pixel in row: # We draw black, so 255 is for dark pixels ...
bigcode/self-oss-instruct-sc2-concepts
def get_init(order): """Return initial guess for fit parameters.""" lambda_guess = [1.0] coeff_guess = [0.0] * (2 * order) return lambda_guess + coeff_guess
bigcode/self-oss-instruct-sc2-concepts
def get_caller_name(caller): """Find the name of a calling (i.e. observed) object. Args: caller: The observed object which is calling an observer. Returns: The name of the caller. If the caller is a function we return that function's .__name__. If the caller is a bound method we re...
bigcode/self-oss-instruct-sc2-concepts
def wc(q,mc2,B): """ Calculate the electron gyrofrequency q is the charge in multiples of the fundamental mc2 is the particle rest mass in MeV B is the magnetic field magnitude in nT """ cof = 89.8755311 res = cof*q*B/mc2 return res
bigcode/self-oss-instruct-sc2-concepts
from typing import Union from typing import List from typing import Tuple def deduplicate(x: Union[List, Tuple]): """Remove duplicates in a list or tuple; preserves original order.""" return type(x)(dict.fromkeys(x))
bigcode/self-oss-instruct-sc2-concepts
def sizeof(bsObj): """ Size of BotSense object in bytes. Size is contextual by object type. """ return bsObj.__sizeof__()
bigcode/self-oss-instruct-sc2-concepts
def extract_variable_index_and_name(string): """Takes a string of the form variable_name[index] and returns the variable_name, and index. The method will return a `ValueError` if the string does not contain a valid set of access brackets, or if the string contains multiple bracket accessors. P...
bigcode/self-oss-instruct-sc2-concepts
async def start_entry() -> dict: """Create a mock start_entry object.""" return { "id": "start_entry_1", "race_id": "race_1", "startlist_id": "startlist_1", "bib": 1, "name": "name names", "club": "the club", "scheduled_start_time": ("2021-08-31T12:00:00")...
bigcode/self-oss-instruct-sc2-concepts
def myfunc(_a, _b): """Add two numbers.""" return _a + _b
bigcode/self-oss-instruct-sc2-concepts
def is_one_to_one(table): """A staticmethod that takes a codon table as a dictionary and returns True if it represents a One-To-One genetic code and False otherwise. A one-to-one code is defined as a code in which every amino acid is represented with exactly one codon. This defines an unamb...
bigcode/self-oss-instruct-sc2-concepts
def mex(L): """Return the minimum excluded value of a list""" L = set(L) n = 0 while n in L: n += 1 return n
bigcode/self-oss-instruct-sc2-concepts
def _get_magnitude(string): """ Get the magnitude of the smallest significant value in the string :param str string: A representation of the value as a string :returns: The magnitude of the value in the string. e.g. for 102, the magnitude is 0, and for 102.03 it is -2 :rtype: int """ split_...
bigcode/self-oss-instruct-sc2-concepts
def __get_pivots(diameter, x, y): """ Get the x-intercepts and y-intercepts of the circle and return a list of pivots which the coin lies on. """ pivots = [] radius = diameter / 2 sqval = radius**2 - y**2 if sqval > 0: # no imaginary numbers! sqrt = sqval**(0.5) piv...
bigcode/self-oss-instruct-sc2-concepts
def create_filename(lecture_num, title): """ Create a filename from a title string. Converts spaces to dashes and makes everything lowercase Returns: lecture filename """ return "lecture-{:02d}{}.md".format(int(lecture_num), "" if not title else '-' + title.lower().replace(" ", "-"))
bigcode/self-oss-instruct-sc2-concepts
def get_line(s3_autoimport): """Build a list of relevant data to be printed. Args: s3_autoimport (S3ProjectImport): instance of S3 autoimport Returns: list(str): list of relevant data to be printed """ return "\t".join( [ str(s3_autoimport.id), ...
bigcode/self-oss-instruct-sc2-concepts
def FindPhaseByID(phase_id, phases): """Find the specified phase, or return None""" for phase in phases: if phase.phase_id == phase_id: return phase return None
bigcode/self-oss-instruct-sc2-concepts
def dataToString(var, data): """Given a tuple of data, and a name to save it as returns var <- c(data) """ #convert data to strings d = [str(d) for d in data] return "%s <- c(%s)" % (var, ",".join(d))
bigcode/self-oss-instruct-sc2-concepts
def alt_ternary_handle(tokens): """Handle if ... then ... else ternary operator.""" cond, if_true, if_false = tokens return "{if_true} if {cond} else {if_false}".format(cond=cond, if_true=if_true, if_false=if_false)
bigcode/self-oss-instruct-sc2-concepts
def extract_volume_number(value): """Extract the volume number from a string, returns None if not matched.""" return value.replace("v.", "").replace("v .", "").strip()
bigcode/self-oss-instruct-sc2-concepts
def get_full_exception_name(exception: Exception) -> str: """Get the full exception name i.e. get sqlalchemy.exc.IntegrityError instead of just IntegrityError """ module = exception.__class__.__module__ if module is None or module == str.__class__.__module__: return exception.__class__.__nam...
bigcode/self-oss-instruct-sc2-concepts
def prettyTimeDelta (seconds): """ Pretty-print seconds to human readable string 1d 1h 1m 1s """ seconds = int(seconds) days, seconds = divmod(seconds, 86400) hours, seconds = divmod(seconds, 3600) minutes, seconds = divmod(seconds, 60) s = [(days, 'd'), (hours, 'h'), (minutes, 'm'), (se...
bigcode/self-oss-instruct-sc2-concepts
def _convert_snake_to_pascal(snake_case_string: str) -> str: """ Convert a string provided in snake_case to PascalCase """ return ''.join(word.capitalize() for word in snake_case_string.split('_'))
bigcode/self-oss-instruct-sc2-concepts
def read_file_str(file_path: str) -> str: """ Read the target file string. Parameters ---------- file_path : str Path of target file. Returns ------- file_str : str The target string read. """ with open(file_path, mode='r', encoding='utf-8') as f: file_s...
bigcode/self-oss-instruct-sc2-concepts
def getHlAtt(app, n, highlights, isSlot): """Get the highlight attribute and style for a node for both pretty and plain modes. Parameters ---------- app: obj The high-level API object n: int The node to be highlighted highlights: set|dict The nodes to be highlighted. ...
bigcode/self-oss-instruct-sc2-concepts
def dir_tree_find(tree, kind): """Find nodes of the given kind from a directory tree structure Parameters ---------- tree : dict Directory tree. kind : int Kind to find. Returns ------- nodes : list List of matching nodes. """ nodes = [] if isinstan...
bigcode/self-oss-instruct-sc2-concepts
def intToDBaseTuple(x, dim, D): """ Transfer a integer to a base-D fixed-length tuple of digits. Parameters ---------- x : int A positive integer to be transformed into base-D. dim : int The length of digit tuple as the output. D : int The base of the digit tuple. ...
bigcode/self-oss-instruct-sc2-concepts
def list_product(num_list): """Multiplies all of the numbers in a list """ product = 1 for x in num_list: product *= x return product
bigcode/self-oss-instruct-sc2-concepts
def lin_interp(x, x0, x1, y0, y1): """ Simple helper function for linear interpolation. Estimates the value of y at x by linearly interpolating between points (x0, y0) and (x1, y1), where x0 <= x < x1. Args: x: Float. x-value for which to esrimate y x0: Float. x-value of point 0 ...
bigcode/self-oss-instruct-sc2-concepts
def output_size(W, F, P, S): """ https://adventuresinmachinelearning.com/convolutional-neural-networks-tutorial-in-pytorch/ :param W: width in :param F: filter diameter :param P: padding :param S: stride :return:width out """ return (W-F+2*P)/S + 1
bigcode/self-oss-instruct-sc2-concepts
import torch def out_degree(adjacency: torch.Tensor) -> torch.Tensor: """Compute out-degrees of nodes in a graph. Parameters ---------- adjacency Adjacency matrix. Shape: :math:`(N_{nodes},N_{nodes})` Returns ------- torch.Tensor Nodewise out-degree tensor. ...
bigcode/self-oss-instruct-sc2-concepts
def is_fasta_file_extension(file_name): """ Check if file has fasta extension Parameters ---------- file_name : str file name Returns ------- bool True if file has fasta extension, False otherwise """ if file_name[-4:] == ".fna": return True elif file_name[-4:] == ".faa": return True elif file_nam...
bigcode/self-oss-instruct-sc2-concepts
from typing import Union def _get_remainder(code: Union[list, int]) -> int: """Calculate remainder of validation calculations. :param Union[list, int] code: input code :return: remainder of calculations :rtype: int :raises TypeError: if code is not a list or an integer """ # raise an exc...
bigcode/self-oss-instruct-sc2-concepts
def _is_group(token): """ sqlparse 0.2.2 changed it from a callable to a bool property """ is_group = token.is_group if isinstance(is_group, bool): return is_group else: return is_group()
bigcode/self-oss-instruct-sc2-concepts
import warnings def force_connect(client): """ Convenience to wait for a newly-constructed client to connect. Taken from pymongo test.utils.connected. """ with warnings.catch_warnings(): # Ignore warning that "ismaster" is always routed to primary even # if client's read preferenc...
bigcode/self-oss-instruct-sc2-concepts
def unescape(st): """ Unescape special chars and return the given string *st*. **Examples**: >>> unescape('\\\\t and \\\\n and \\\\r and \\\\" and \\\\\\\\') '\\t and \\n and \\r and " and \\\\' """ st = st.replace(r'\"', '"') st = st.replace(r'\n', '\n') st = st.replace(r'\r', '\r...
bigcode/self-oss-instruct-sc2-concepts
import torch def batch_project(xyz_tensor, K): """ Project a point cloud into pixels (u,v) given intrinsic K [u';v';w] = [K][x;y;z] u = u' / w; v = v' / w :param the xyz points :param calibration is a torch array composed of [fx, fy, cx, cy] ------- :return u, v grid tensor in image coord...
bigcode/self-oss-instruct-sc2-concepts
def format_sig(name, args, retv): """ Format method signature with Javap's method definition style. Arguments are: name of method, list of argument types, and type of return value. >>> format_sig('getSomeValue', ['int', 'java.lang.String'], 'org.mydomain.myapp.SomeData[]') u'org.mydomain.myapp....
bigcode/self-oss-instruct-sc2-concepts
import collections def GetTurnStats(game_results): """Returns a histogram of game lengths (in rounds played).""" hist = collections.Counter() for game_result in game_results: hist[game_result.num_rounds_played] += 1 return hist
bigcode/self-oss-instruct-sc2-concepts
def _ParseIssueReferences(issue_ref_list): """Parses a list of issue references into a tuple of IDs added/removed. For example: [ "alpha:7", "beta:8", "-gamma:9" ] => ([ "7", "8" ], [ "9" ]) NOTE: We don't support cross-project issue references. Rather we just assume the issue reference is within the same pro...
bigcode/self-oss-instruct-sc2-concepts
import base64 def write_to_data_uri(s): """ Writes to a uri. Use this function to embed javascript into the dash app. Adapted from the suggestion by user 'mccalluc' found here: https://community.plotly.com/t/problem-of-linking-local-javascript-file/6955/2 """ uri = ( ('data:;base64...
bigcode/self-oss-instruct-sc2-concepts
def cart2(list1: list, list2: list) -> list: """Cartesian product of two lists. :param list list1: input list 1 :param list list2: input list 2 :return: a new list contains all Cartesian products of the two lists. :rtype: list >>> cart2(['a','b'], [1,2]) [['a',1],['a',2],['b',...
bigcode/self-oss-instruct-sc2-concepts
def get_sentences(docs, min_words): """ Given a set of documents we extract all sentences that pass a minimum word threshold ARGS: docs(list of Documents), min_words(int) Returns: sentences(list of Sentences) """ sentences = [] [sentences.extend(doc.get_filtered_sentences(min_words)) for doc...
bigcode/self-oss-instruct-sc2-concepts