seed
stringlengths
1
14k
source
stringclasses
2 values
def file_len(fname): """Returns Number of lines of a file""" with open(fname) as f: i = -1 for i, l in enumerate(f): pass return i + 1
bigcode/self-oss-instruct-sc2-concepts
def predict_times_model(times, model): """Predict times alignment from a model object. Parameters ---------- times : 1d array Timestamps to align. model : LinearRegression A model object, with a fit model predicting timestamp alignment. Returns ------- 1d array ...
bigcode/self-oss-instruct-sc2-concepts
import torch def get_recall(SR, GT, threshold=0.5): """ Args: SR: tensor Segmentation Results GT: tensor Ground Truth threshold: the threshold of segmentation Returns: RC: Recall rate """ # Sensitivity == Recall SR = SR > threshold GT = GT == torch.max(G...
bigcode/self-oss-instruct-sc2-concepts
import re def parse_element_string(elements_str, stoich=False): """ Parse element query string with macros. Has to parse braces too, and throw an error if brackets are unmatched. e.g. Parameters: '[VII][Fe,Ru,Os][I]' Returns: ['[VII]', '[Fe,Ru,Os]', '[I]'] e.g.2 Parameters: '...
bigcode/self-oss-instruct-sc2-concepts
import torch def get_flat_params_from(model): """ Get the flattened parameters of the model. Args: model: the model from which the parameters are derived Return: flat_param: the flattened parameters """ params = [] for param in model.parameters(): params.append(pa...
bigcode/self-oss-instruct-sc2-concepts
from typing import List from typing import Tuple from typing import Optional def html_wrap_span( string: str, pairs: List[Tuple[int, int]], css_class: Optional[str] = "accentuate" ) -> str: """Wrap targeted area of Assertion with html highlighting to visualize where the error or warning is targeted ...
bigcode/self-oss-instruct-sc2-concepts
def construct_info_message(module, branch, area, version, build_object): """ Gathers info to display during release Args: module(str): Module to be released branch(str): Branch to be released area(str): Area of module version(str): Release version build_object(:class...
bigcode/self-oss-instruct-sc2-concepts
def erase_special(x): """ Removes special characters and spaces from the input string """ return ''.join([i for i in x if i.isalnum()])
bigcode/self-oss-instruct-sc2-concepts
import tempfile import zipfile def extract_files(file_path, output_dir=None): """ Extracts files from a compressed zip archive. :param str file_path: the path to the input zip archive containing the compressed files. :param str or None output_dir: the path to the directory in which to extract the file...
bigcode/self-oss-instruct-sc2-concepts
def compare_list(list1: list, list2: list) -> bool: """Compare two list and ignore \n at the end of two list.""" while list1[-1] == "\n" or list1[-1] == "": list1.pop() while list2[-1] == "\n" or list2[-1] == "": list2.pop() return list1 == list2
bigcode/self-oss-instruct-sc2-concepts
def datetime_format(date, caller=None): """Convert given datetime.datetime object to a string of appropriate form. Choose the format according to the "caller" arg., which is a string indicating the name of the function calling this function. """ if caller == "corona": return date.s...
bigcode/self-oss-instruct-sc2-concepts
def calc_relative_ratio(rel_pow_low_band, rel_pow_high_band): """Calculate ratio of relative power between two bands. Parameters ---------- rel_pow_low_band : float Relative power of lower band. rel_pow_high_band : float Relative power of higher band. Outputs ------- ra...
bigcode/self-oss-instruct-sc2-concepts
import importlib def get_trainer(cfg, net_G, net_D=None, opt_G=None, opt_D=None, sch_G=None, sch_D=None, train_data_loader=None, val_data_loader=None): """Return the trainer object. Args: cfg (Config): Loaded config object. net_G...
bigcode/self-oss-instruct-sc2-concepts
def complete_out_of_view(to_check_box, im_w, im_h): """ check if the bounding box is completely out of view from the image :param to_check_box: bounding box, numpy array, [x, y, x, y] :param im_w: image width, int :param im_h:image height, int :return: out of view flag, bool """ complete...
bigcode/self-oss-instruct-sc2-concepts
import re def rename_state(rename, src): """ Given a list of (old_str, new_str), replace old_strin src with new_str. :param rename: a list of (old_str, new_str) :param src: code :return: renamed src """ for (old, new) in rename: match = True index = 0 while match: ...
bigcode/self-oss-instruct-sc2-concepts
def validate_cipher_suite_id(cipher_suite_id): """Validates that a CipherSuite conforms to the proper format. Args: cipher_suite_id (int): CipherSuite id. Returns: (int): The original CipherSuite id. """ if not isinstance(cipher_suite_id, int): raise TypeError("CipherSuite...
bigcode/self-oss-instruct-sc2-concepts
import json def trigger_mutation_test(limit): """ Test data for IFTTT trigger bunq_mutation """ result = [{ "created_at": "2018-01-05T11:25:15+00:00", "date": "2018-01-05", "type": "MANUAL", "amount": "1.01", "balance": "15.15", "account": "NL42BUNQ0123456789", ...
bigcode/self-oss-instruct-sc2-concepts
def all_are_none(*args) -> bool: """ Return True if all args are None. """ return all([arg is None for arg in args])
bigcode/self-oss-instruct-sc2-concepts
def default_join(row, join, *elements): """ Joins a set of objects as strings :param row: The row being transformed (not used) :param join: The string used to join the elements :param elements: The elements to join :return: The joined string """ return str(join).join(map(str, elements)...
bigcode/self-oss-instruct-sc2-concepts
def freeze(model): """ Freezes all the parameters in the model Returns ------- Model the model itself """ for param in model.parameters(): param.requires_grad = False model.training = False return model
bigcode/self-oss-instruct-sc2-concepts
def tirar_bijecao(line): """ Retira o número de correspondência das regras. :param line: lista com a regra :return: lista com a regra sem número de correspondência. """ regra_sem_bij = [] for e in line: regra_sem_bij.append(e[:-1]) return regra_sem_bij
bigcode/self-oss-instruct-sc2-concepts
def identity(x): """Return the argument as is.""" return x
bigcode/self-oss-instruct-sc2-concepts
def dec_str_to_int(ch): """function to process a decimal string into an integer.""" return int(ch)
bigcode/self-oss-instruct-sc2-concepts
def partition_all(n): """Partition a collection into sub-collections (lists) of size n.""" def generator(coll): temp = [] for i, item in enumerate(coll, 1): temp.append(item) if not i % n: yield temp temp = [] if temp: y...
bigcode/self-oss-instruct-sc2-concepts
def CONCAT_ARRAYS(*arrays): """ Concatenates arrays to return the concatenated array. See https://docs.mongodb.com/manual/reference/operator/aggregation/concatArrays/ for more details :param arrays: A set of arrays(expressions). :return: Aggregation operator """ return {'$concatArrays': ...
bigcode/self-oss-instruct-sc2-concepts
import re def crush_invalid_field_name(name): """Given a proposed field name, replace banned characters with underscores, and convert any run of underscores with a single.""" if name[0].isdigit(): name = "_%s" % name name = re.sub(r'[^a-z0-9_]', "_", name.lower()) return re.sub(r'__*', "_", na...
bigcode/self-oss-instruct-sc2-concepts
def basis_function(degree, knot_vector, span, t): """Computes the non-vanishing basis functions for a single parameter t. Implementation of Algorithm A2.2 from The NURBS Book by Piegl & Tiller. Uses recurrence to compute the basis functions, also known as Cox - de Boor recursion formula. """ le...
bigcode/self-oss-instruct-sc2-concepts
def gen_user_list_id(user_list_obj): """ Generates the Elasticsearch document id for a UserList Args: user_list_obj (UserList): The UserList object Returns: str: The Elasticsearch document id for this object """ return "user_list_{}".format(user_list_obj.id)
bigcode/self-oss-instruct-sc2-concepts
def get_gamma_distribution_params(mean, std): """Turn mean and std of Gamma distribution into parameters k and theta.""" # mean = k * theta # var = std**2 = k * theta**2 theta = std**2 / mean k = mean / theta return k, theta
bigcode/self-oss-instruct-sc2-concepts
def admins_from_iam_policy(iam_policy): """Get a list of admins from the IAM policy.""" # Per # https://cloud.google.com/appengine/docs/standard/python/users/adminusers, An # administrator is a user who has the Viewer, Editor, or Owner primitive role, # or the App Engine App Admin predefined role roles = [ ...
bigcode/self-oss-instruct-sc2-concepts
import torch def to_tensor(data): """ Convert numpy array to PyTorch tensor. """ return torch.view_as_real(torch.from_numpy(data))
bigcode/self-oss-instruct-sc2-concepts
def pretty_str(label, arr): """ Generates a pretty printed NumPy array with an assignment. Optionally transposes column vectors so they are drawn on one line. Strictly speaking arr can be any time convertible by `str(arr)`, but the output may not be what you want if the type of the variable is not a...
bigcode/self-oss-instruct-sc2-concepts
def merge_duplicate_concepts(concepts): """ NHP has many duplicate ingredients in the raw data. During data preprocessing each unique ingredient string is assigned a unique ID, so duplicate ingredient entries will have the same ID. This function merges those entries into a single concept. :para...
bigcode/self-oss-instruct-sc2-concepts
def dict_factory(cursor, row) -> dict: """Transform tuple rows into a dictionary with column names and values Args: cursor: database cursor row: row Returns: dict: a dictionary containing the column names as keys and the respective values """ output = {} for idx, col in...
bigcode/self-oss-instruct-sc2-concepts
import torch def onehot(y, num_classes): """ Generate one-hot vector :param y: ground truth labels :type y: torch.Tensor :param num_classes: number os classes :type num_classes: int :return: one-hot vector generated from labels :rtype: torch.Tensor """ assert len(y.shape) in [...
bigcode/self-oss-instruct-sc2-concepts
import math def __MtoE(M,e): """Calculates the eccentric anomaly from the mean anomaly. Args: M(float): the mean anomaly (in radians) e(float): the eccentricity Returns: float: The eccentric anomaly (in radians) """ E = M dy = 1 while(abs(dy) > 0.0...
bigcode/self-oss-instruct-sc2-concepts
def identity_grid(grid): """Do nothing to the grid""" # return np.array([[7,5,5,5],[5,0,0,0],[5,0,1,0],[5,0,0,0]]) return grid
bigcode/self-oss-instruct-sc2-concepts
from typing import List def intcode_computer(program: List[int], sum_code: int = 1, multiply_code: int = 2, finish_code: int = 99 ) -> List[int]: """ An Intcode program is a list of integers separated by commas (like 1,0,0,3,9...
bigcode/self-oss-instruct-sc2-concepts
def routepack(value): """Pack a route into a string""" return str(value).replace("/","!")
bigcode/self-oss-instruct-sc2-concepts
def order_pythonic(sentence: str) -> str: """Returns ordered sentence (pythonic). Examples: >>> assert order_pythonic("") == "" >>> assert order_pythonic("is2 Thi1s T4est 3a") == "Thi1s is2 3a T4est" """ return " ".join( sorted(sentence.split(), key=lambda x: "".join(filter(str....
bigcode/self-oss-instruct-sc2-concepts
from typing import Union from typing import List from typing import Set from typing import Counter def list_equal( left: Union[List[Union[str, int]], Set[Union[str, int]]], right: Union[List[Union[str, int]], Set[Union[str, int]]], use_sort=True, ) -> bool: """ 判断列表是否相等,支持具有重复值列表的比较 参考:https:/...
bigcode/self-oss-instruct-sc2-concepts
def check_callbacks(bot, url): """Check if ``url`` is excluded or matches any URL callback patterns. :param bot: Sopel instance :param str url: URL to check :return: True if ``url`` is excluded or matches any URL callback pattern This function looks at the ``bot.memory`` for ``url_exclude`` patter...
bigcode/self-oss-instruct-sc2-concepts
def make_biplot_scores_output(taxa): """Create convenient output format of taxon biplot coordinates taxa is a dict containing 'lineages' and a coord matrix 'coord' output is a list of lines, each containing coords for one taxon """ output = [] ndims = len(taxa['coord'][1]) header = '...
bigcode/self-oss-instruct-sc2-concepts
import re def derive_ip_address(cidr_block, delegate, final8): """ Given a CIDR block string, a delegate number, and an integer representing the final 8 bits of the IP address, construct and return the IP address derived from this values. For example, if cidr_block is 10.0.0.0/16,...
bigcode/self-oss-instruct-sc2-concepts
def get_struct_member_vardecl(struct_type, member_name, declvisitor=None): """Return the type for the member @member_name, of the struct type defined by @struct_type.""" for vardecllist in struct_type.children: assert vardecllist.type == "VarDeclList" for vardecl in vardecllist.children: ...
bigcode/self-oss-instruct-sc2-concepts
def nc_define_var(ncid, metadata): """ Define a new variable in an open netCDF file and add some default attributes. Parameters ---------- ncid: netCDF4.Dataset Handle to an open netCDF file. metadata: dict Bundle containing the information needed to define the variable. ...
bigcode/self-oss-instruct-sc2-concepts
def eval_vehicle_offset(pixel_offset, mx=3.7/780): """ Calculates offset of the vehicle from middle of the lane based on the value of the pixel offset of center of the detected lane from middle of the camera image. The vehicle offset is calculated in meters using the scale factor mx (in meter...
bigcode/self-oss-instruct-sc2-concepts
def dict_from_hash(hashstring): """ From a hashstring (like one created from hash_from_dict), creates and returns a dictionary mapping variables to their assignments. Ex: hashstring="A=0,B=1" => {"A": 0, "B": 1} """ if hashstring is None: return None if len(hashstring) == 0: return {} re...
bigcode/self-oss-instruct-sc2-concepts
def is_compose_project(group_id, artifact_id): """Returns true if project can be inferred to be a compose / Kotlin project """ return "compose" in group_id or "compose" in artifact_id
bigcode/self-oss-instruct-sc2-concepts
def steering2(course, power): """ Computes how fast each motor in a pair should turn to achieve the specified steering. Input: course [-100, 100]: * -100 means turn left as fast as possible, * 0 means drive in a straight line, and * 100 means turn right as fast as po...
bigcode/self-oss-instruct-sc2-concepts
def minmax(dates): """Returns an iso8601 daterange string that represents the min and max datemap.values(). Args: datestrings: [d1, d2, d3,] Returns: ['min_date/max_date',] Example: >>> minmax(['2008-01-01', '2010-01-01', '2009-01-01']) "2008-01-01/2010-01-01" ...
bigcode/self-oss-instruct-sc2-concepts
def horiz_div(col_widths, horiz, vert, padding): """ Create the column dividers for a table with given column widths. col_widths: list of column widths horiz: the character to use for a horizontal divider vert: the character to use for a vertical divider padding: amount of padding to add to eac...
bigcode/self-oss-instruct-sc2-concepts
from bs4 import BeautifulSoup def cleanHTML(raw_html): """ Remove HTML tags """ return BeautifulSoup(raw_html,"lxml").text
bigcode/self-oss-instruct-sc2-concepts
def appendDtectArgs( cmd, args=None ): """Append OpendTect arguments Parameters: * cmd (list): List to which the returned elements will be added * arg (dict, optional): Dictionary with the members 'dtectdata' and 'survey' as single element lists, and/or 'dtectexec' (see odpy.getODSoftwareDir) ...
bigcode/self-oss-instruct-sc2-concepts
def __evaluate_tree(predictor, input): """Function for evaluating a given decision tree on a given input.""" return predictor.evaluate(input)
bigcode/self-oss-instruct-sc2-concepts
import struct def readLong(f): """Read unsigned 4 byte value from a file f.""" (retVal,) = struct.unpack("L", f.read(4)) return retVal
bigcode/self-oss-instruct-sc2-concepts
def tank_geometry(geometry, om_key): """ Returns the IceTop tank geometry object corresponding to a given DOM. """ if om_key.om == 61 or om_key.om == 62: return geometry.stationgeo[om_key.string][0] elif om_key.om == 63 or om_key.om == 64: return geometry.stationgeo[om_key.string][1]...
bigcode/self-oss-instruct-sc2-concepts
def ogrtype_from_dtype(d_type): """ Return the ogr data type from the numpy dtype """ # ogr field type if 'float' in d_type.name: ogr_data_type = 2 elif 'int' in d_type.name: ogr_data_type = 0 elif 'string' in d_type.name: ogr_data_type = 4 elif 'bool' in d_type.n...
bigcode/self-oss-instruct-sc2-concepts
def mniposition_to(mnipoint, affine): """ project the position in MNI coordinate system to the position of a point in matrix coordinate system Parameters ---------- point : list or array The position in MNI coordinate system. affine : array or list The position information of t...
bigcode/self-oss-instruct-sc2-concepts
from typing import List from typing import Tuple def partition_leading_lines( lines: List[str], ) -> Tuple[List[str], List[str]]: """ Returns a tuple of the initial blank lines, and the comment lines. """ for j in range(len(lines)): if lines[j].startswith("#"): break else: ...
bigcode/self-oss-instruct-sc2-concepts
def convert_16_to_8(value): """Scale a 16 bit level into 8 bits.""" return value >> 8
bigcode/self-oss-instruct-sc2-concepts
from datetime import datetime def is_time_in_given_format(time_string, time_format): """Tests whether a time string is formatted according to the given time format.""" try: datetime.strptime(time_string, time_format) return True except ValueError: return False
bigcode/self-oss-instruct-sc2-concepts
def prompt(text): """ Add >>> and ... prefixes back into code prompt("x + 1") # doctest: +SKIP '>>> x + 1' prompt("for i in seq:\n print(i)") '>>> for i in seq:\n... print(i)' """ return '>>> ' + text.rstrip().replace('\n', '\n... ')
bigcode/self-oss-instruct-sc2-concepts
def increment(string): """ for "A", return "B" for "AC", return "AD" After AZ comes `A[`. That's OK for my purposes. """ rest = string[:-1] last = chr(ord(string[-1]) + 1) #print rest+last return rest + last
bigcode/self-oss-instruct-sc2-concepts
def set_carry(self) -> int: """ Set the carry bit. Parameters ---------- self: Processor, mandatory The instance of the processor containing the registers, accumulator etc Returns ------- self.CARRY The carry bit Raises ------ N/A Notes ----- N...
bigcode/self-oss-instruct-sc2-concepts
def read_quota_file(file_quota): """Read the quota information from a file generated with the command 'mmrepquota -j <fileset>.""" fin = open(file_quota,'r') text = fin.readlines() fin.close() # Remove some control characters from the input. text = [line.strip() for line in text] retur...
bigcode/self-oss-instruct-sc2-concepts
def cellsDirs(pos, size): """ Returns all possible directions in a position within a 2D array of given size. """ x, y = pos width, height = size dirs = [] if x > 0: dirs.append([-1,0]) if x < width-1: dirs.append([1,0]) if y > 0: dirs.append([0,-1]) if y < height-1: dirs.append(...
bigcode/self-oss-instruct-sc2-concepts
def _parse_color_string(colors, n=None, r=False, start=0, stop=1): """ Parses strings that are formatted like the following: 'RdBu_r_start=0.8_stop=0.9_n=10' 'viridis_start0.2_r_stop.5_n20' 'Greens_start0_n15' """ if isinstance(colors, str): color_settings = colors.split('_') ...
bigcode/self-oss-instruct-sc2-concepts
def split(str, sep=None, maxsplit=-1): """Return a list of the words in the string, using sep as the delimiter string.""" return str.split(sep, maxsplit)
bigcode/self-oss-instruct-sc2-concepts
def inner_product(L1,L2): """ Inner product between two vectors, where vectors are represented as alphabetically sorted (word,freq) pairs. Example: inner_product([["and",3],["of",2],["the",5]], [["and",4],["in",1],["of",1],["this",2]]) = 14.0 """ sum = 0.0 i = 0 ...
bigcode/self-oss-instruct-sc2-concepts
import asyncio def async_test(loop=None, timeout=None): """ Decorator enabling co-routines to be run in python unittests. :param loop: Event loop in which to run the co-routine. By default its ``asyncio.get_event_loop()``. :param timeout: Test timeout in seconds. """ loop = loop or asyncio.ge...
bigcode/self-oss-instruct-sc2-concepts
def lopen_loc(x): """Extracts the line and column number for a node that may have an opening parenthesis, brace, or bracket. """ lineno = x._lopen_lineno if hasattr(x, "_lopen_lineno") else x.lineno col = x._lopen_col if hasattr(x, "_lopen_col") else x.col_offset return lineno, col
bigcode/self-oss-instruct-sc2-concepts
def factorial(number): """ Factorial Using Recursion Example : 5! Factorial is denoted by ! Factorial(5) : 5 X 4 X 3 X 2 X 1 = 120 """ if number == 0: return 1 else: print(f"{number}*", end=" ") return number * factorial(number-1)
bigcode/self-oss-instruct-sc2-concepts
from typing import Optional def percent(flt: Optional[float]) -> str: """ Convert a float into a percentage string. """ if flt is None: return '[in flux]' return '{0:.0f}%'.format(flt * 100)
bigcode/self-oss-instruct-sc2-concepts
def nd_cross_variogram(x1, y2, x2, y1): """ Inner most calculation step of cross-variogram This function is used in the inner most loop of `neighbour_diff_squared`. Parameters ---------- x, y : np.array Returns ------- np.array """ res = (x1 - x2)*(y1 - y2) return r...
bigcode/self-oss-instruct-sc2-concepts
def is_set(b: int, val: int, v6: bool) -> bool: """Return whether b-th bit is set in integer 'val'. Special case: when b < 0, it acts as if it were 0. """ if b < 0: b = 0 if v6: return val & (1 << (127 - b)) != 0 else: return val & (1 << (31 - b)) != 0
bigcode/self-oss-instruct-sc2-concepts
def get_chromosome_names_in_GTF(options): """ Function to get the list of chromosome names present in the provided GTF file. """ chr_list = [] with open(options.annotation, "r") as GTF_file: for line in GTF_file: if not line.startswith("#"): chr = line.split("\t")[0] ...
bigcode/self-oss-instruct-sc2-concepts
from typing import List def tablinks(tabs: List[str]) -> str: """Adds list of tabs/sections for the reports that are able to be clicked. For every 6 tabs we push them onto a new line. Parameters ---------- tabs : List[str] List of tabs/sections for the reports. Returns ------- st...
bigcode/self-oss-instruct-sc2-concepts
def mash_infusion( target_temp, initial_temp, grain_weight, water_volume, infusion_temp=212 ): """ Get Volume of water to infuse into mash to reach scheduled temperature All temperatures in F. http://howtobrew.com/book/section-3/the-methods-of-mashing/calculations-for-boiling-water-additions ...
bigcode/self-oss-instruct-sc2-concepts
def parse_args(argv): """Parse Alfred Arguments Args: argv: A list of arguments, in which there are only two items, i.e., [mode, {query}]. The 1st item determines the search mode, there are two options: 1) search by `topic` 2) search ...
bigcode/self-oss-instruct-sc2-concepts
def bool_like(value, name, optional=False, strict=False): """ Convert to bool or raise if not bool_like. Parameters ---------- value : object Value to verify name : str Variable name for exceptions optional : bool Flag indicating whether None is allowed stric...
bigcode/self-oss-instruct-sc2-concepts
def import_custom_event(my_module): """Import CustomEvent from my_module.""" return my_module.CustomEvent
bigcode/self-oss-instruct-sc2-concepts
from typing import MutableMapping from typing import Optional from typing import List def extract_dependencies(content: MutableMapping) -> Optional[List[str]]: """ Extract the dependencies from the Cargo.toml file. :param content: The Cargo.toml parsed dictionnary :returns: Packages listed in the dep...
bigcode/self-oss-instruct-sc2-concepts
def identity(obj): """Returns obj.""" return obj
bigcode/self-oss-instruct-sc2-concepts
from typing import Mapping def subdict(d: Mapping, keys=None): """Gets a sub-dict from a Mapping ``d``, extracting only those keys that are both in ``keys`` and ``d``. Note that the dict will be ordered as ``keys`` are, so can be used for reordering a Mapping. >>> subdict({'a': 1, 'b': 2, 'c': 3,...
bigcode/self-oss-instruct-sc2-concepts
import re def validate_name(name, minlength=1, maxlength=30, fieldname='name'): """Validates a name with length and regular expression criteria. Parameters ---------- name : str or QString Name to be validated. minlength : int The minimum length of the name. maxlength : in...
bigcode/self-oss-instruct-sc2-concepts
def strip_mate_id(read_name): """ Strip canonical mate IDs for paired end reads, e.g. #1, #2 or: /1, /2 """ if read_name.endswith("/1") or read_name.endswith("/2") or \ read_name.endswith("#1") or read_name.endswith("#2"): read_name = read_name[0:-3] return read_nam...
bigcode/self-oss-instruct-sc2-concepts
def build_content_type(format, encoding='utf-8'): """ Appends character encoding to the provided format if not already present. """ if 'charset' in format: return format return "%s; charset=%s" % (format, encoding)
bigcode/self-oss-instruct-sc2-concepts
def Inside_triangle(p, a, b, c): """ inside_triangle(p, a, b, c) p: point (x,y) a, b, c: vertices of the triangle (x,y) >>> inside_triangle(p, a, b, c) """ detT = (a[0]-c[0])*(b[1]-c[1]) - (a[1]-c[1])*(b[0]-c[0]) lambda1 = ((b[1]-c[1])*(p[0]-c[0]) - (b[0]-c[0])*(p[1]-c[1])) / detT lambd...
bigcode/self-oss-instruct-sc2-concepts
def clean_spaces(txt): """ Removes multiple spaces from a given string. Args: txt (str): given string. Returns: str: updated string. """ return " ".join(txt.split())
bigcode/self-oss-instruct-sc2-concepts
def process_z_slice_list(img_obj_list, config): """Make sure all members of z_slices are part of io_obj. If z_slices = 'all', replace with actual list of z_slices Parameters ---------- img_obj_list: list list of mManagerReader instances config: obj ConfigReader instance Ret...
bigcode/self-oss-instruct-sc2-concepts
def blur_augment(is_training=True, **kwargs): """Applies random blur augmentation.""" if is_training: prob = kwargs['prob'] if 'prob' in kwargs else 0.5 return [('blur', {'prob': prob})] return []
bigcode/self-oss-instruct-sc2-concepts
import torch def masked_softmax(x, m=None, dim=-1): """ Softmax with mask. :param x: the Tensor to be softmaxed. :param m: mask. :param dim: :return: """ if m is not None: m = m.float() x = x * m e_x = torch.exp(x - torch.max(x, dim=dim, keepdim=True)[0]) if m i...
bigcode/self-oss-instruct-sc2-concepts
def getCoord(percentX, percentY, image_size): """ Returns the width and height coordinates given the percentage of the image size you want percentX - percentage along x axis percentY - percentage along y axis image_size - tuple (width, height) of the total size of the image @return - tuple f...
bigcode/self-oss-instruct-sc2-concepts
import requests from bs4 import BeautifulSoup def scrape_reviews(isbn): """ Scrape reviews from book's Goodreads webpage using BeautifulSoup 4. Return a list of tuples (names,rating,reviews) """ book_page_url = f"https://www.goodreads.com/api/reviews_widget_iframe?did=0&format=html&hide_last_page...
bigcode/self-oss-instruct-sc2-concepts
import re import json def parse_output(s): """Parse a string of standard output text for the "OUTPUT: <JSON>" line and return the parsed JSON object. """ m = re.search(r'^###OUTPUT: (.*)', s, re.MULTILINE) if m is None: return None return json.loads(m.group(1))
bigcode/self-oss-instruct-sc2-concepts
def get_last_conv_layer(keras_model): """ Get last convolution layer name of keras model input: Keras model output: string of the name of the last convolution layer Make sure last convolution layer has "conv" in the name! """ layer_names=[layer.name for layer in keras_model.layers] layer_names.revers...
bigcode/self-oss-instruct-sc2-concepts
def build_completed_questions_feedback(actor_name, quiz_name, course_name, score, feedback): """ Build the feedback when an user has completed the quiz and has failed the quiz. :param actor_name: Name of the user that has completed the quiz. :type actor_name: str :param quiz_name: Name of the quiz....
bigcode/self-oss-instruct-sc2-concepts
def parse_fastq_description(description): """ Parse the description found in a fastq reads header Parameters ---------- description: str A string of the fastq reads description header Returns ------- description_dict: dict A dictionary containing the keys and values fou...
bigcode/self-oss-instruct-sc2-concepts
def convert_alpha_exponent(alpha): """Convert a DFA alpha value to the expected powerlaw exponent. Parameters ---------- alpha : float Alpha value from a detrended fluctuation analysis. Returns ------- exponent : float Predicted aperiodic exponent value, representing a 1/f ...
bigcode/self-oss-instruct-sc2-concepts