seed
stringlengths
1
14k
source
stringclasses
2 values
def mmedian(lst): """ get the median value """ sortedLst = sorted(lst) lstLen = len(lst) if lstLen==0: return 0.0 index = (lstLen - 1) // 2 if (lstLen % 2): return sortedLst[index] else: return (sortedLst[index] + sortedLst[index + 1])/2.0
bigcode/self-oss-instruct-sc2-concepts
def _format_spreadsheet_headers(token): """ Return formatted authorization headers for further interactions with spreadsheet api. """ return { "Authorization": f"Bearer {token}" }
bigcode/self-oss-instruct-sc2-concepts
import re def getFilename(name): """Get a filename from given name without dangerous or incompatible characters.""" # first replace all illegal chars name = re.sub(r"[^0-9a-zA-Z_\-\.]", "_", name) # then remove double dots and underscores while ".." in name: name = name.replace('..', '.') while "__" in name: name = name.replace('__', '_') # remove a leading dot or minus if name.startswith((".", "-")): name = name[1:] return name
bigcode/self-oss-instruct-sc2-concepts
from pathlib import Path def _get_old_file(new_file: Path) -> Path: """Return the same file without the .new suffix""" assert new_file.name.endswith('.new') # noqa return new_file.with_name(new_file.stem)
bigcode/self-oss-instruct-sc2-concepts
def xor_fixed_buffers(buf1, buf2): """ Creates XOR buffered string from two hex string buffers :param buf1: hex encoded string :param buf2: hex encoded string :return: xor hex encoded string """ # Convert hex to bytearray decoded_hex_buf1 = bytearray.fromhex(buf1) decoded_hex_buf2 = bytearray.fromhex(buf2) # XOR by byte xor_buf = bytearray(len(decoded_hex_buf1)) for i in range(len(xor_buf)): xor_buf[i] = decoded_hex_buf1[i] ^ decoded_hex_buf2[i] # Convert back to hex string xor_buf = bytes(xor_buf).hex() return xor_buf
bigcode/self-oss-instruct-sc2-concepts
def previous(some_list, current_index): """ Returns the previous element of the list using the current index if it exists. Otherwise returns an empty string. """ try: return some_list[int(current_index) - 1] # access the previous element except: return ''
bigcode/self-oss-instruct-sc2-concepts
def get_truck(client, truck_id): """ returns the truck specified. :param client: The test client to make the request with :param truck_id: The id of the truck to find :return: truck with id=id """ return client.get(f'/api/trucks/{truck_id}')
bigcode/self-oss-instruct-sc2-concepts
def ros_service_response_cmd(service, result, _id=None, values=None): """ create a rosbridge service_response command object a response to a ROS service call :param service: name of the service that was called :param result: boolean return value of service callback. True means success, False failure. :param _id: if an ID was provided to the call_service request, then the service response will contain the ID :param values: dict of the return values. If the service had no return values, then this field can be omitted (and will be by the rosbridge server) """ command = { "op": "service_response", "service": service, "result": result } if _id: command["id"] = _id if values: command["values"] = values return command
bigcode/self-oss-instruct-sc2-concepts
def escapeAttrJavaScriptStringDQ(sText): """ Escapes a javascript string that is to be emitted between double quotes. """ if '"' not in sText: chMin = min(sText); if ord(chMin) >= 0x20: return sText; sRet = ''; for ch in sText: if ch == '"': sRet += '\\"'; elif ord(ch) >= 0x20: sRet += ch; elif ch == '\n': sRet += '\\n'; elif ch == '\r': sRet += '\\r'; elif ch == '\t': sRet += '\\t'; else: sRet += '\\x%02x' % (ch,); return sRet;
bigcode/self-oss-instruct-sc2-concepts
def center_scale_to_corners(yx, hw): """Convert bounding boxes from "center+scale" form to "corners" form""" hw_half = 0.5 * hw p0 = yx - hw_half p1 = yx + hw_half return p0, p1
bigcode/self-oss-instruct-sc2-concepts
from typing import Union def get_error_message(traceback: str) -> Union[str, None]: """Extracts the error message from the traceback. If no error message is found, will return None. Here's an example: input: Traceback (most recent call last): File "example_code.py", line 2, in <module> import kivy ModuleNotFoundError: No module named 'kivy' output: ModuleNotFoundError: No module named 'kivy' """ error_lines = traceback.splitlines() return error_lines[-1]
bigcode/self-oss-instruct-sc2-concepts
def read(filepath, readfunc, treant): """Read data from a treant Args: filepath: the filepath to read from readfunc: the read callback treant: the treant to read from Returns: the data """ return readfunc(treant[filepath].abspath)
bigcode/self-oss-instruct-sc2-concepts
import re def is_project_issue(text): """ Issues/pull requests from Apache projects in Jira. See: https://issues.apache.org/jira/secure/BrowseProjects.jspa#all >>> is_project_issue('thrift-3615') True >>> is_project_issue('sling-5511') True >>> is_project_issue('sling') False >>> is_project_issue('project-8.1') False Special cases: >>> is_project_issue('utf-8') False >>> is_project_issue('latin-1') False >>> is_project_issue('iso-8858') False """ return bool(re.match(r''' (?!utf-) # Some special cases... (?!latin-) (?!iso-) \w+-\d+$ ''', text, re.VERBOSE | re.UNICODE))
bigcode/self-oss-instruct-sc2-concepts
def read_input(fpath): """ Read the global input file. Args: fpath (str): Path to the input file to read. Returns: list """ with open(fpath, 'r') as f: return [line.strip() for line in f.readlines()]
bigcode/self-oss-instruct-sc2-concepts
def _cell_fracs_sort_vol_frac_reverse(cell_fracs): """ Sort cell_fracs according to the order of increasing idx and decreasing with vol_frac. Parameters ---------- cell_fracs : structured array The output from dagmc.discretize_geom(). A sorted, one dimensional array, each entry containing the following fields: :idx: int The volume element index. :cell: int The geometry cell number. :vol_frac: float The volume fraction of the cell withing the mesh ve. :rel_error: float The relative error associated with the volume fraction. The array must be sorted with respect to both idx and cell, with cell changing fastest. Returns ------- cell_fracs : structured array Sorted cell_fracs. """ # sort ascending along idx and vol_frac # ndarray.sort can't sort using desending sequence. # Multiply the vol_frac to -1.0 to sort the vol_frac in reverse order. cell_fracs['vol_frac'] *= -1.0 cell_fracs.sort(order=['idx', 'vol_frac']) cell_fracs['vol_frac'] *= -1.0 return cell_fracs
bigcode/self-oss-instruct-sc2-concepts
import math def fromSpherical(r, theta, phi): """ convert spherical coordinates to 3-d cartesian coordinates """ return r*math.sin(theta)*math.cos(phi), r*math.sin(theta)*math.sin(phi), r*math.cos(theta)
bigcode/self-oss-instruct-sc2-concepts
import torch def cross_product_matrix(v): """skew symmetric form of cross-product matrix Args: v: tensor of shape `[...,3]` Returns: The skew symmetric form `[...,3,3]` """ v0 = v[..., 0] v1 = v[..., 1] v2 = v[..., 2] zero = torch.zeros_like(v0) mat = torch.stack([ zero, -v2, v1, v2, zero, -v0, -v1, v0, zero], dim=-1).view(list(v0.shape)+[3, 3]) return mat
bigcode/self-oss-instruct-sc2-concepts
def is_generator(iterable): """ Check if an iterable is a generator. Args: iterable: Iterable. Returns: boolean """ return hasattr(iterable, '__iter__') and not hasattr(iterable, '__len__')
bigcode/self-oss-instruct-sc2-concepts
import inspect def caller(n=1): """Return the name of the calling function n levels up in the frame stack. >>> caller(0) 'caller' >>> def f(): ... return caller() >>> f() 'f' """ return inspect.getouterframes(inspect.currentframe())[n][3]
bigcode/self-oss-instruct-sc2-concepts
import collections def parse_result_ranks(stream): """Reads a results stream: one line per item, expected format: ``qid, iter, docno, rank, sim, run_id``. The output data structure is a dict indexed by (tid, docno) and the values are ranks. """ ranks = collections.defaultdict(int) for i, l in enumerate(stream): tid, _, docno, rank, _, _ = l.strip().split() ranks[(tid, docno)] = int(rank) return ranks
bigcode/self-oss-instruct-sc2-concepts
def getFormURL(form_id): """ Return a form URL based on form_id """ return 'https://docs.google.com/forms/d/%s/viewform' % (form_id, )
bigcode/self-oss-instruct-sc2-concepts
import unicodedata def to_ascii(s): """ Translates the string or bytes input into an ascii string with the accents stripped off. """ if isinstance(s, bytes): s = s.decode('utf-8') return ''.join((c for c in unicodedata.normalize('NFD', s) if unicodedata.category(c) != 'Mn'))
bigcode/self-oss-instruct-sc2-concepts
import torch def rejoin_props(datasets): """ Rejoin properties from datasets into one dictionary of properties. Args: datasets (list): list of smaller datasets Returns: new_props (dict): combined properties """ new_props = {} for dataset in datasets: for key, val in dataset.props.items(): if key not in new_props: new_props[key] = val continue if type(val) is list: new_props[key] += val else: new_props[key] = torch.cat([ new_props[key], val], dim=0) return new_props
bigcode/self-oss-instruct-sc2-concepts
def _l_str_ ( self ) : """Self-printout of line: (point, direction) >>> line = ... >>> print line """ return "Line3D(%s,%s)" % ( self.beginPoint() , self.direction() )
bigcode/self-oss-instruct-sc2-concepts
def get_mesh_texture(bsp, mesh_index: int) -> str: """Returns the name of the .vmt applied to bsp.MESHES[mesh_index]""" mesh = bsp.MESHES[mesh_index] material_sort = bsp.MATERIAL_SORT[mesh.material_sort] texture_data = bsp.TEXTURE_DATA[material_sort.texture_data] return bsp.TEXTURE_DATA_STRING_DATA[texture_data.name_index]
bigcode/self-oss-instruct-sc2-concepts
def verify_askingto_by_verify_y(actor, x, y, ctxt) : """Updates the actor for y to x and then verifies that action.""" y.update_actor(x) return ctxt.actionsystem.verify_action(y, ctxt)
bigcode/self-oss-instruct-sc2-concepts
def create_document(bookmark): """Creates a Document (a dict) for the search engine""" return { "id": str(bookmark.id), "title": bookmark.title or "", "notes": bookmark.notes or "", "tags": ", ".join([tag.name for tag in bookmark.tags]), }
bigcode/self-oss-instruct-sc2-concepts
def bytes_find_single(x: bytes, sub: int, start: int, end: int) -> int: """Where is the first location of a specified byte within a given slice of a bytes object? Compiling bytes.find compiles this function, when sub is an integer 0 to 255. This function is only intended to be executed in this compiled form. Args: x: The bytes object in which to search. sub: The subsequence to look for, as a single byte specified as an integer 0 to 255. start: Beginning of slice of x. Interpreted as slice notation. end: End of slice of x. Interpreted as slice notation. Returns: Lowest index of match within slice of x, or -1 if not found. Raises: ValueError: The sub argument is out of valid range. """ if sub < 0 or sub > 255: raise ValueError("byte must be in range(0, 256)") if start < 0: start += len(x) if start < 0: start = 0 if end < 0: end += len(x) if end < 0: end = 0 if end > len(x): end = len(x) index = start while index < end: if x[index] == sub: return index index += 1 return -1
bigcode/self-oss-instruct-sc2-concepts
import csv def get_data_X_y(data_dir, X=[], y=[]): """Read the log file and turn it into X/y pairs.""" with open(data_dir + 'driving_log.csv') as fin: next(fin) log = list(csv.reader(fin)) for row in log: if float(row[6]) < 20: continue # throw away low-speed samples X += [row[0].strip(), row[1].strip(), row[2].strip()] #using center, left and right images y += [float(row[3]), float(row[3]) + 0.3, float(row[3]) - 0.3] #add a small angle to the left camera and subtract a small angle from the right camera return X, y
bigcode/self-oss-instruct-sc2-concepts
def sigfig(number, places): """ Round `number` to `places` significant digits. Parameters: number (int or float): A number to round. places (int): The number of places to round to. Returns: A number """ # Passing a negative int to round() gives us a sigfig determination. # Example: round(12345, -2) = 12300 ndigits = -int(len(str(abs(number)).split('.')[0]) - places) return round(number, ndigits)
bigcode/self-oss-instruct-sc2-concepts
from datetime import datetime def read_time_stamp (out): """Reads timestamp from a file provided. Format: time.time()""" st_hd = open(out, 'r') st = st_hd.read() st_hd.close() stamp = datetime.fromtimestamp(float(st)).strftime('%Y-%m-%d %H:%M:%S') return(stamp)
bigcode/self-oss-instruct-sc2-concepts
import json def load_characters(path_to_backup): """ Characters are saved in a json file. Read and return the saved content as a Python dict. """ with open(path_to_backup, 'r') as content: try: return json.loads(content.read()) except json.JSONDecodeError: pass
bigcode/self-oss-instruct-sc2-concepts
import hashlib def file_hash(filename): """ Hash the contents of the specified file using SHA-256 and return the hash as a string. @param filename The filename to hash the contents of @return String representing the SHA-256 hash of the file contents """ hasher = hashlib.sha256() with open(filename, 'rb') as infp: while True: data = infp.read(8192) if not data: break hasher.update(data) return hasher.hexdigest()
bigcode/self-oss-instruct-sc2-concepts
def unionRect(rect1, rect2): """Return the smallest rectangle in which both input rectangles are fully enclosed. In other words, return the total bounding rectangle of both input rectangles. """ (xMin1, yMin1, xMax1, yMax1) = rect1 (xMin2, yMin2, xMax2, yMax2) = rect2 xMin, yMin, xMax, yMax = (min(xMin1, xMin2), min(yMin1, yMin2), max(xMax1, xMax2), max(yMax1, yMax2)) return (xMin, yMin, xMax, yMax)
bigcode/self-oss-instruct-sc2-concepts
def build_synthethic_iid_datasets(client_data, client_dataset_size): """Constructs an iterable of IID clients from a `tf.data.Dataset`. The returned iterator yields a stream of `tf.data.Datsets` that approximates the true statistical IID setting with the entirety of `client_data` representing the global distribution. That is, we do not simply randomly distribute the data across some fixed number of clients, instead each dataset returned by the iterator samples independently from the entirety of `client_data` (so any example in `client_data` may be produced by any client). Args: client_data: a `tff.simulation.ClientData`. client_dataset_size: the size of the `tf.data.Dataset` to yield from the returned dataset. Returns: A `tf.data.Dataset` instance that yields iid client datasets sampled from the global distribution. """ global_dataset = client_data.create_tf_dataset_from_all_clients() # Maximum of shuffle of 10,000 items. Limited by the input dataset. global_dataset = global_dataset.shuffle( buffer_size=10000, reshuffle_each_iteration=True) global_dataset = global_dataset.repeat(None) # Repeat forever return global_dataset.window(client_dataset_size)
bigcode/self-oss-instruct-sc2-concepts
def is_int(s: str) -> bool: """Test if string is int Args: s (str): Input String Returns: bool: result of test """ try: int(s) return True except ValueError: return False
bigcode/self-oss-instruct-sc2-concepts
from pathlib import Path def _new_file(file: Path) -> Path: """Return the same file path with a .new additional extension.""" return file.with_suffix(f"{file.suffix}.new")
bigcode/self-oss-instruct-sc2-concepts
def get_users_preferred_timezone(user, service): """ Determines the users preferred timezone by checking what timezone they use for their primary google calendar :param user: Django User object for the user whose calendar is being accessed :return: A string representation of the timezone: - "Etc/GMT+8" """ primary_calendar = service.calendarList().get(calendarId='primary').execute() return primary_calendar['timeZone']
bigcode/self-oss-instruct-sc2-concepts
def split_string(command:str, character:str): """ Split incoming command on a character args: command: string that's the command. character: the character on which the command should be split. Returns: Array with at least length 2 containing the split command. """ items = command.split(character) if len(items) == 1: items.append("") return items
bigcode/self-oss-instruct-sc2-concepts
def offset_stopword(rank, nb_lemmas_in_stopwords): """Offset word frequency rankings by a small amount to take into account the missing ranks from ignored stopwords""" return max(1, rank - nb_lemmas_in_stopwords)
bigcode/self-oss-instruct-sc2-concepts
def compute_loss(criterion, outputs, labels, batch_size): """ Helper function to compute the loss. Since this is a pixel-wise prediction task we need to reshape the output and ground truth tensors into a 2D tensor before passing it in to the loss criterion. Args: criterion: pytorch loss criterion outputs (pytorch tensor): predicted labels from the model labels (pytorch tensor): ground truth labels batch_size (int): batch size used for training Returns: pytorch tensor for loss """ loss_out = outputs.transpose(1, 3) \ .contiguous() \ .view([batch_size * 128 * 128, 2]) loss_lab = labels.transpose(1, 3) \ .contiguous() \ .view([batch_size * 128 * 128, 2]) return criterion(loss_out, loss_lab)
bigcode/self-oss-instruct-sc2-concepts
def poly_smooth(x: float, n: float = 3) -> float: """Polynomial easing of a variable in range [0, 1]. Args: x (float): variable to be smoothed n (float, optional): polynomial degree. Defaults to 3. Returns: float: _description_ """ if x > 1: return 1 if x < 0: return 0 if x < 0.5: return pow(2, n - 1) * pow(x, n) return 1 - pow(-2 * x + 2, n) / 2
bigcode/self-oss-instruct-sc2-concepts
import re def del_tokens_len_one(text: str) -> str: """Delete tokens with length = 1. This is kind of a basic stopword filtering. """ text = re.sub('(\s)\w(\s)',' ',text) return text
bigcode/self-oss-instruct-sc2-concepts
from typing import Callable from typing import Iterable from typing import Tuple from typing import List def split(predicate: Callable, iterable: Iterable) -> Tuple[List, List]: """ Splits the iterable into two list depending on the result of predicate. Parameters ---------- predicate: Callable A function taking an element of the iterable and return Ture or False iterable: Iterable Returns ------- (positives, negatives) """ positives, negatives = [], [] for item in iterable: (positives if predicate(item) else negatives).append(item) return positives, negatives
bigcode/self-oss-instruct-sc2-concepts
from typing import List def _entity_report(entity_name: str, messages: List[str]) -> List[str]: """ Serializes the messages of a given entity to the Report It generates a list that translates as: + entity + message one + message two""" return [f' + {entity_name}'] + [f' + {message}' for message in messages]
bigcode/self-oss-instruct-sc2-concepts
def make_preterminal(label, word): """returns a preterminal node with label for word""" return [label, word]
bigcode/self-oss-instruct-sc2-concepts
def isVariable(name, dataset): """ Determines if given string is an existing variable name for a variable in dataset. This helper function returns True if the given name is a valid name of a variable in the Tecplot file, False otherwise. Arguments: name -- the string that we are testing if it corresponds to a variable name or not dataset -- the tecplot.data.dataset class in which "name" must be a variable name Returns: True/False depending on whether name is a valid variable name in dataset """ try: # if name is not a valid variable name, exception is thrown (or it returns None) var = dataset.variable(name) if var is None: return False return True except: return False
bigcode/self-oss-instruct-sc2-concepts
def fgrep(text, term, window=25, with_idx=False, reverse=False): """Search a string for a given term. If found, print it with some context. Similar to `grep -C 1 term text`. `fgrep` is short for faux grep. Parameters ---------- text: str Text to search. term: str Term to look for in text. window: int Number of characters to display before and after the matching term. with_idx: bool If True, return index as well as string. reverse: bool If True, reverse search direction (find last match rather than first). Returns ------- str or tuple[int, str]: The desired term and its surrounding context. If the term isn't present, an empty string is returned. If with_idx=True, a tuple of (match index, string with text) is returned. """ idx = text.rfind(term) if reverse else text.find(term) if idx == -1: res = '' else: res = text[max(idx-window, 0):idx+window] return (idx, res) if with_idx else res
bigcode/self-oss-instruct-sc2-concepts
import re def fix_gitlab_links(base_url, text): """ Fixes gitlab upload links that are relative and makes them absolute """ matches = re.findall('(\[[^]]*\]\s*\((/[^)]+)\))', text) for (replace_string, link) in matches: new_string = replace_string.replace(link, base_url + link) text = text.replace(replace_string, new_string) return text
bigcode/self-oss-instruct-sc2-concepts
def get_objlist(*, galaxy_catalog, survey, star_catalog=None, noise=None): """ get the objlist and shifts, possibly combining the galaxy catalog with a star catalog Parameters ---------- galaxy_catalog: catalog e.g. WLDeblendGalaxyCatalog survey: descwl Survey For the appropriate band star_catalog: catalog e.g. StarCatalog noise: float Needed for star catalog Returns ------- objlist, shifts objlist is a list of galsim GSObject with transformations applied. Shifts is an array with fields dx and dy for each object """ objlist, shifts = galaxy_catalog.get_objlist(survey=survey) if star_catalog is not None: assert noise is not None res = star_catalog.get_objlist( survey=survey, noise=noise, ) sobjlist, sshifts, bright_objlist, bright_shifts, bright_mags = res else: sobjlist = None sshifts = None bright_objlist = None bright_shifts = None bright_mags = None return { 'objlist': objlist, 'shifts': shifts, 'star_objlist': sobjlist, 'star_shifts': sshifts, 'bright_objlist': bright_objlist, 'bright_shifts': bright_shifts, 'bright_mags': bright_mags, }
bigcode/self-oss-instruct-sc2-concepts
import re def clean_newline(text: str) -> str: """Filter newlines. Arguments: text: The text to be filtered. Returns: The filtered text. """ return re.sub("\n", "", text)
bigcode/self-oss-instruct-sc2-concepts
import copy def thrift_to_dict(thrift_inst, update_func=None): """convert thrift instance into a dict in strings :param thrift_inst: a thrift instance :param update_func: transformation function to update dict value of thrift object. It is optional. :return dict: dict with attributes as key, value in strings """ if thrift_inst is None: return None gen_dict = copy.copy(thrift_inst).__dict__ if update_func is not None: update_func(gen_dict, thrift_inst) return gen_dict
bigcode/self-oss-instruct-sc2-concepts
def sum_reduce(iter, params): """ Sums the values for each key. This is a convenience function for performing a basic sum in the reduce. """ buf = {} for key, value in iter: buf[key] = buf.get(key, 0) + value return buf.items()
bigcode/self-oss-instruct-sc2-concepts
def _totalUniqueWords(dataset, index): """ Given a dataset, compute the total number of unique words at the given index. GIVEN: dataset (list) list of lists, where each sublist is a document index (int) index in dataset to count unique words RETURN: unique_words (int) total number of unique words in dataset """ all_words = list() for d in dataset: words = d[index].split(" ") all_words.extend(words) unique_words = len(set(all_words)) return unique_words
bigcode/self-oss-instruct-sc2-concepts
from typing import Dict from typing import List def get_parents(class_name: str, parent_mapping: Dict[str, List[str]]) -> List[str]: """ Recursively resolve all parents (ancestry) of class_name :param class_name: class to resolve :param parent_mapping: mapping of class_name -> parents :return: List[str], list of parent classes """ parents: List[str] = parent_mapping[class_name] for parent in parent_mapping[class_name]: parents = [*parents, *get_parents(parent, parent_mapping)] return parents
bigcode/self-oss-instruct-sc2-concepts
import re def matching(value, pattern, casesensitive=True): """ Filter that performs a regex match :param value: Input source :type value: str :param pattern: Regex Pattern to be matched :return: True if matches. False otherwise :rtype: bool """ flags = re.I if not casesensitive else 0 return re.match(str(pattern), str(value), flags) is not None
bigcode/self-oss-instruct-sc2-concepts
def collate_fn(batch): """Pack batch""" return tuple(batch)
bigcode/self-oss-instruct-sc2-concepts
import six def get_members(group): """Get a list of member resources managed by the specified group. Sort the list of instances first by created_time then by name. """ resources = [] if group.nested(): resources = [r for r in six.itervalues(group.nested()) if r.status != r.FAILED] return sorted(resources, key=lambda r: (r.created_time, r.name))
bigcode/self-oss-instruct-sc2-concepts
def get_albums(tracks): """ Returns a dict where: key: album_id value: list of track ids """ albums = {} for _,row in tracks.iterrows(): album = row['album'][1:-1] if album != '' and album != 'None': if album in albums: albums[album].append(row['track_id']) else: albums[album] = [row['track_id']] return albums
bigcode/self-oss-instruct-sc2-concepts
import re def has_spdx_text_in_analysed_file(scanned_file_content): """Returns true if the file analysed by ScanCode contains SPDX identifier.""" return bool(re.findall("SPDX-License-Identifier:?", scanned_file_content))
bigcode/self-oss-instruct-sc2-concepts
def clamp_tensor(tensor, minimum, maximum): """ Supports sparse and dense tensors. Returns a tensor with values clamped between the provided minimum and maximum, without modifying the original tensor. """ if tensor.is_sparse: coalesced_tensor = tensor.coalesce() coalesced_tensor._values().clamp_(minimum, maximum) return coalesced_tensor else: return tensor.clamp(minimum, maximum)
bigcode/self-oss-instruct-sc2-concepts
def extract_picard_stats(path): """ Extract relevant information from picard wgs or size stats file. This is assumed to be for a single sample and that there will only be two lines in the "METRICS CLASS" section, which is the only section we'll extract. No effort is made to convert strings to numbers for the stat values. Args: path (str): path to the picard wgs stats file Returns: dict: keys as stat names and the values as stat values """ with open(path) as statsf: split_lines = [] keep_line = False for line in statsf: if keep_line: split_lines.append(line.strip().split("\t")) # if we see metrics label, set flag to start collecting data if line.startswith("## METRICS CLASS"): keep_line = True # stop at first empty line, though in practice we expect this # to happen after exactly 2 lines read if keep_line and not line.strip(): break # expecting only 2 lines, header row and values row stats = dict(zip(split_lines[0], split_lines[1])) return stats
bigcode/self-oss-instruct-sc2-concepts
def canAcceptVassal(masterTeam, vassalTeam, bAtWar): """ Returns True if <vassalTeam> can become a vassal of <masterTeam>. Pass True for <bAtWar> to test for capitulation and False to test for peaceful vassalage. """ if masterTeam.getID() == vassalTeam.getID(): return False if masterTeam.isAVassal() or vassalTeam.isAVassal(): return False if masterTeam.isAtWar(vassalTeam.getID()) != bAtWar: return False # master must possess tech return masterTeam.isVassalStateTrading()
bigcode/self-oss-instruct-sc2-concepts
def unpack_bytes(word): """Unpacks a 32 bit word into 4 signed byte length values.""" def as_8bit_signed(val): val = val & 0xff return val if val < 128 else val - 256 return (as_8bit_signed(word), as_8bit_signed(word >> 8), as_8bit_signed(word >> 16), as_8bit_signed(word >> 24))
bigcode/self-oss-instruct-sc2-concepts
def lowerBound(sortedCollection, item, key=lambda x: x): """ Given a sorted collection, perform binary search to find element x for which the following holds: item > key(x) and the value key(x) is the largest. Returns index of such an element. """ lo = 0 hi = len(sortedCollection) while lo < hi: mid = (lo + hi) // 2 if item > key(sortedCollection[mid]): lo = mid + 1 else: hi = mid return lo - 1
bigcode/self-oss-instruct-sc2-concepts
def gt_pseudophase(g): """ Return pseudophased genotype call. Parameters ---------- g : str Genotype call. Returns ------- str Pseudophased genotype call. Examples -------- >>> from fuc import pyvcf >>> pyvcf.pseudophase('0/1') '0|1' >>> pyvcf.pseudophase('0/0:34:10,24') '0|0:34:10,24' """ l = g.split(':') l[0] = l[0].replace('/', '|') return ':'.join(l)
bigcode/self-oss-instruct-sc2-concepts
def get_users(user_file_path): """read usernames from file.""" user_file = open(user_file_path) users = user_file.readlines() user_file.close() return users
bigcode/self-oss-instruct-sc2-concepts
def transform( event, settings ): """ Takes a pipeline event and transforms it to pipeline event containing an array of payloads """ adapters = settings.adapters() payloads = [] for index in range( 0, len( adapters ) ): outputter = settings.outputters[ index ] if not outputter.passthru: output = adapters[ index ].dumps( event['record'] ) else: output = adapters[ index ].dumps( event['message'] ) payloads.append( output ) return { 'bookmark': event['bookmark'], 'payloads': payloads }
bigcode/self-oss-instruct-sc2-concepts
def _strip_predicate(s): """Remove quotes and _rel suffix from predicate *s*""" if s.startswith('"') and s.endswith('"'): s = s[1:-1] elif s.startswith("'"): s = s[1:] if s[-4:].lower() == '_rel': s = s[:-4] return s
bigcode/self-oss-instruct-sc2-concepts
import math def cosine_annealing_lr( iteration: int, num_iterations: int, initial_lr: float, final_lr: float, ): """ Cosine annealing NO restarts Args: iteration: current iteration num_iterations: total number of iterations of coine lr initial_lr: learning rate to start final_lr: learning rate to end Returns: float: learning rate """ return final_lr + 0.5 * (initial_lr - final_lr) * (1 + \ math.cos(math.pi * float(iteration) / float(num_iterations)))
bigcode/self-oss-instruct-sc2-concepts
from typing import Union def expand_fine_modality_questions( answer: str, matched_word: str, modality: Union[None, str] ): """Create new questions for fine modality task with given information. Args: answer: Original answer to the question matched_word: The keyword which labeled the original question as fine_modality modality: name of the scan type present in original question. Returns: dict of generated questions including the original question """ binary, categorical = {}, {} if modality == "ct": modality = "ct scan" if modality == "pet": modality = "pet scan" if answer in ["yes", "no"]: if matched_word == "iv_contrast": binary["was iv_contrast given to the patient?"] = answer elif matched_word == "gi_contrast": binary["was gi_contrast given to the patient?"] = answer if ("t1" in matched_word) and answer == "yes": binary["is this a t1_weighted image?"] = "yes" binary["is this a t2_weighted image?"] = "no" binary["is this a flair image?"] = "no" if ("t1" in matched_word) and answer == "no": binary["is this a t1_weighted image?"] = "no" if ("t2" in matched_word) and answer == "yes": binary["is this a t1_weighted image?"] = "no" binary["is this a t2_weighted image?"] = "yes" binary["is this a flair image?"] = "no" if ("t2" in matched_word) and answer == "no": binary["is this a t2_weighted image?"] = "no" if ("flair" in matched_word) and answer == "yes": binary["is this a t1_weighted image?"] = "no" binary["is this a t2_weighted image?"] = "no" binary["is this a flair image?"] = "yes" if ("flair" in matched_word) and answer == "no": binary["is this a flair image?"] = "no" if (matched_word == "contrast") and modality: binary[f"is this a noncontrast {modality}?"] = ( "no" if answer == "yes" else "yes" ) binary[f"was the {modality} taken with contrast?"] = ( "yes" if answer == "yes" else "no" ) if (matched_word == "noncontrast") and modality: binary[f"is this a noncontrast {modality}?"] = ( "yes" if answer == "yes" else "no" ) binary[f"was the {modality} taken with contrast?"] = ( "no" if answer == "yes" else "yes" ) else: if matched_word == "contrast": categorical["what type of contrast did this patient have?"] = answer if ("t1" in answer) or ("t2" in answer) or ("flair" in answer): categorical["is this a t1_weighted, t2_weighted, or flair image?"] = answer categorical["is this image modality t1, t2, or flair?"] = answer if "t1" in answer: binary["is this a t1_weighted image?"] = "yes" elif "t2" in answer: binary["is this a t2_weighted image?"] = "yes" elif "flair" in answer: binary["is this a flair image?"] = "yes" else: binary["is this a t1_weighted image?"] = "no" binary["is this a t2_weighted image?"] = "no" binary["is this a flair image?"] = "no" return {"binary": binary, "categorical": categorical}
bigcode/self-oss-instruct-sc2-concepts
def _parse_volumes_param(volumes): """Parse volumes details for Docker containers from blueprint Takes in a list of dicts that contains Docker volume info and transforms them into docker-py compliant (unflattened) data structures. Look for the `volumes` parameters under the `run` method on [this page](https://docker-py.readthedocs.io/en/stable/containers.html) Args: volumes (list): List of { "host": { "path": <target path on host> }, "container": { "bind": <target path in container>, "mode": <read/write> } } Returns: dict of the form { <target path on host>: { "bind": <target path in container>, "mode": <read/write> } } if volumes is None then returns None """ if volumes: return dict([ (vol["host"]["path"], vol["container"]) for vol in volumes ]) else: return None
bigcode/self-oss-instruct-sc2-concepts
from typing import Dict from typing import Optional def role_has_tag(role: Dict, key: str, value: Optional[str] = None) -> bool: """ Checks a role dictionary and determine of the role has the specified tag. If `value` is passed, This function will only return true if the tag's value matches the `value` variable. :param role: An AWS role dictionary (from a boto3 get_role or get_account_authorization_details call) :param key: key of the tag :param value: optional value of the tag :return: """ for tag in role.get("Tags", []): if tag.get("Key") == key: if not value or tag.get("Value") == value: return True return False
bigcode/self-oss-instruct-sc2-concepts
def get_datasets(datasets=''): """Gets the list of dataset names. Args: datasets: A string of comma separated dataset names. Returns: A list of dataset names. """ return [d.strip() for d in datasets.split(',')]
bigcode/self-oss-instruct-sc2-concepts
import functools def synchronized(obj): """ This function has two purposes: 1. Decorate a function that automatically synchronizes access to the object passed as the first argument (usually `self`, for member methods) 2. Synchronize access to the object, used in a `with`-statement. Note that you can use #wait(), #notify() and #notify_all() only on synchronized objects. # Example ```python class Box(Synchronizable): def __init__(self): self.value = None @synchronized def get(self): return self.value @synchronized def set(self, value): self.value = value box = Box() box.set('foobar') with synchronized(box): box.value = 'taz\'dingo' print(box.get()) ``` # Arguments obj (Synchronizable, function): The object to synchronize access to, or a function to decorate. # Returns 1. The decorated function. 2. The value of `obj.synchronizable_condition`, which should implement the context-manager interface (to be used in a `with`-statement). """ if hasattr(obj, 'synchronizable_condition'): return obj.synchronizable_condition elif callable(obj): @functools.wraps(obj) def wrapper(self, *args, **kwargs): with self.synchronizable_condition: return obj(self, *args, **kwargs) return wrapper else: raise TypeError('expected Synchronizable instance or callable to decorate')
bigcode/self-oss-instruct-sc2-concepts
import logging def _set_root_logger(loglevel=logging.INFO): """ Setup the root logger. Parameters ---------- loglevel: int, optional The log level to set the root logger to. Default :attr:`logging.INFO` Returns ------- :class:`logging.Logger` The root logger for Faceswap """ rootlogger = logging.getLogger() rootlogger.setLevel(loglevel) return rootlogger
bigcode/self-oss-instruct-sc2-concepts
def _recurse_binary_exponentiation(num, power): """ Recursively calculate num**power quickly (via binary exponentiation). Helper function. We did parameter checks before so that we don't have to do them inside every recursive call. """ if power == 1: return num num_squared = num * num if power % 2 == 0: # power was even return _recurse_binary_exponentiation(num_squared, power // 2) else: # power was odd return num * _recurse_binary_exponentiation(num_squared, power // 2)
bigcode/self-oss-instruct-sc2-concepts
from datetime import datetime def today(tz=None) -> datetime: """get datetime of today (no time info)""" now = datetime.now(tz) return datetime(year=now.year, month=now.month, day=now.day)
bigcode/self-oss-instruct-sc2-concepts
def _GetGetRequest(client, health_check_ref): """Returns a request for fetching the existing health check.""" return (client.apitools_client.healthChecks, 'Get', client.messages.ComputeHealthChecksGetRequest( healthCheck=health_check_ref.Name(), project=health_check_ref.project))
bigcode/self-oss-instruct-sc2-concepts
import six def exact_filter(query, model, filters): """Applies exact match filtering to a query. Returns the updated query. Modifies filters argument to remove filters consumed. :param query: query to apply filters to :param model: model object the query applies to, for IN-style filtering :param filters: dictionary of filters; values that are lists, tuples, sets, or frozensets cause an 'IN' test to be performed, while exact matching ('==' operator) is used for other values """ filter_dict = {} if filters is None: filters = {} for key, value in six.iteritems(filters): if isinstance(value, (list, tuple, set, frozenset)): column_attr = getattr(model, key) query = query.filter(column_attr.in_(value)) else: filter_dict[key] = value if filter_dict: query = query.filter_by(**filter_dict) return query
bigcode/self-oss-instruct-sc2-concepts
def filter_dose_by_individual_species(doses, species): """Filter out relevent doses by the species name If it does find doses with the specific species name, it returns a list of these. If it doesn't find any doses with the specific species name, it returns None. :param doses: A list of dose objects :type list: :param species: :type string: :returns: either None or a list of dose objects """ relevant_doses = [] for dose in doses: if dose.individual_species.species_name == species.species_name: relevant_doses.append(dose) return relevant_doses
bigcode/self-oss-instruct-sc2-concepts
def check_bit(val, n): """ Returns the value of the n-th (0 index) bit in given number """ try: if val & 2**n: return 1 else: return 0 except TypeError: return -1
bigcode/self-oss-instruct-sc2-concepts
def getAccurateFocalLengths(imageSize, focalLength, sensorSize): """ Parameters: image size x,y (pixels), focalLength (mili meters), sensorSize x,y (meters) Focal length listed on the image exif is unitless... We need focal length in pixels / meters. Therefore, we scale the exif focal length by number of pixels per meter on the actual CCD sensor. """ w_s = sensorSize[0] # in meters h_s = sensorSize[1] w_i = imageSize[0] # in pixels h_i = imageSize[1] f = focalLength / 1000.0 # milimeters to meters focalLengthPixelsPerMeter = (w_i / w_s * f, h_i / h_s * f) return focalLengthPixelsPerMeter
bigcode/self-oss-instruct-sc2-concepts
import base64 def base_64_encode(key, secret): """encodes key and secret in base 64 for the auth credential""" conversion_string = "{}:{}".format(key, secret).encode('ascii') auth_credential = base64.b64encode(conversion_string) auth_credential = auth_credential.decode() return auth_credential
bigcode/self-oss-instruct-sc2-concepts
from pathlib import Path def get_or_create_path(path_string, parents=True): """ Get path object from string, create if non-existing""" p = Path(path_string) if not p.exists(): p.mkdir(parents=parents) return p
bigcode/self-oss-instruct-sc2-concepts
def no_duplicates(seq): """ Remove all duplicates from a sequence and preserve its order """ # source: https://www.peterbe.com/plog/uniqifiers-benchmark # Author: Dave Kirby # Order preserving seen = set() return [x for x in seq if x not in seen and not seen.add(x)]
bigcode/self-oss-instruct-sc2-concepts
import secrets def draft_conv_key() -> str: """ Create reference for a draft conversation. """ return secrets.token_hex(10)
bigcode/self-oss-instruct-sc2-concepts
def _errmsg(argname, ltd, errmsgExtra=''): """Construct an error message. argname, string, the argument name. ltd, string, description of the legal types. errmsgExtra, string, text to append to error mssage. Returns: string, the error message. """ if errmsgExtra: errmsgExtra = '\n' + errmsgExtra return "arg '%s' must be %s%s" % (argname, ltd, errmsgExtra)
bigcode/self-oss-instruct-sc2-concepts
def replace_chars(string, chars=r':\/|<>?*"', replacement=''): """ Return `string` with any char in the `chars` replaced by `replacement`. Defaults to replace problematic/invalid chars for filenames/paths. """ for c in string: if c in chars: string = string.replace(c, replacement) return string
bigcode/self-oss-instruct-sc2-concepts
import string import secrets def code_verifier(length: int = 128): """ Return a cryptographically random string as specified in RFC7636 section 4.1 See https://datatracker.ietf.org/doc/html/rfc7636#section-4.1 :param length: length of the generated string, minimum 43, maximum 128. Defaults to 128 :return: """ vocab = string.ascii_letters + '-._~0123456789' return ''.join([secrets.choice(vocab) for _ in range(length)])
bigcode/self-oss-instruct-sc2-concepts
def crop(image, rectangle): """ Crop out input image's fragment specified by the rectangle. :param image: input image :param rectangle: rectangle, which indicates cropped area :return: cropped original image fragment """ x, y, w, h = rectangle return image[y:y + h, x:x + w]
bigcode/self-oss-instruct-sc2-concepts
def lookup_newsletter_recipients(resource): """ Callback function to look up the recipients corresponding to a distribution list entry (in this instance: send all newsletters to orgs) Args: the (filtered) resource Returns: a list of pe_ids of the recipients """ if resource.tablename == "cr_shelter": rows = resource.select(["organisation_id$pe_id"], as_rows=True) return [row.org_organisation.pe_id for row in rows] elif resource.tablename == "org_organisation": rows = resource.select(["pe_id"], as_rows=True) return [row.pe_id for row in rows] else: return []
bigcode/self-oss-instruct-sc2-concepts
def lex_tokenize(tokenized_sentence): """Returns a list of lexes from a given tokenizer.TokenizedSentence instance. Each lex is represented as a 3-tuples of (start, end, token).""" return [(lex.begin, lex.end, lex.text) for (token, lex) in tokenized_sentence.as_pairs()]
bigcode/self-oss-instruct-sc2-concepts
def ensure_list(config): """ ensure_list Ensure that config is a list of one-valued dictionaries. This is called when the order of elements is important when loading the config file. (The yaml elements MUST have hyphens '-' in front of them). Returns config if no exception was raised. This is to keep the same format as ensure_dictionary, and allowed possible config file repairs in the future without breaking the API. """ if not isinstance(config, list): raise TypeError("config is not a list. Did you forget some '-' "+ "in your configuration file ?\n" + str(config)) for element in config: if isinstance(element, str): continue if not isinstance(element, dict): raise ValueError("Parsing error in the configuration file.\n" + str(element)) if len(element) != 1: raise ValueError("Parsing error in the configuration file.\n" + str(element)) return config
bigcode/self-oss-instruct-sc2-concepts
from datetime import datetime def json_serial(obj): """JSON serializer for objects not serializable by default json code""" # yyyy-MM-dd'T'HH:mm:ss.SSS strict_date_hour_minute_second_millis if isinstance(obj, datetime): tz_string = "Z" serial = "%s.%03d" % ( obj.strftime("%Y-%m-%dT%H:%M:%S"), int(obj.microsecond / 1000)) return serial raise TypeError("Type not serializable")
bigcode/self-oss-instruct-sc2-concepts
def generate_source(email): """Generate a source code to be used in links inside an email""" return u"ev_{date}_{uuid}".format( date=email.created_at.strftime('%Y%m%d'), uuid=email.uuid)
bigcode/self-oss-instruct-sc2-concepts
from pathlib import Path def make_save_path(save_path, net_name, net_number, epochs): """make a unique save path for model and checkpoints, using network architecture, training replicate number, and number of epochs""" save_path = Path(save_path).joinpath( f'trained_{epochs}_epochs', f'net_number_{net_number}') if not save_path.is_dir(): save_path.mkdir(parents=True, exist_ok=True) stem = f'{net_name}_trained_{epochs}_epochs_number_{net_number}' save_path = save_path.joinpath(stem) return save_path
bigcode/self-oss-instruct-sc2-concepts
def alter_board(board, player, cell): """Alter board string for player input""" board = list(board) # enter player letter in supplied cell board[cell - 1] = player return ''.join(board)
bigcode/self-oss-instruct-sc2-concepts
import torch def cov(m, rowvar=False): """Estimate a covariance matrix given data. Covariance indicates the level to which two variables vary together. If we examine N-dimensional samples, `X = [x_1, x_2, ... x_N]^T`, then the covariance matrix element `C_{ij}` is the covariance of `x_i` and `x_j`. The element `C_{ii}` is the variance of `x_i`. Args: m: A 1-D or 2-D array containing multiple variables and observations. Each row of `m` represents a variable, and each column a single observation of all those variables. rowvar: If `rowvar` is True, then each row represents a variable, with observations in the columns. Otherwise, the relationship is transposed: each column represents a variable, while the rows contain observations. Returns: The covariance matrix of the variables. """ if m.dim() > 2: raise ValueError('m has more than 2 dimensions') if m.dim() < 2: m = m.view(1, -1) if not rowvar and m.size(0) != 1: m = m.t() # m = m.type(torch.double) # uncomment this line if desired fact = 1.0 / (m.size(1) - 1) m -= torch.mean(m, dim=1, keepdim=True) mt = m.t() # if complex: mt = m.t().conj() return fact * m.matmul(mt).squeeze()
bigcode/self-oss-instruct-sc2-concepts
def process_notebook_name(notebook_name: str) -> str: """Processes notebook name :param notebook_name: Notebook name by default keeps convention: [3 digit]-name-with-dashes-with-output.rst, example: 001-hello-world-with-output.rst :type notebook_name: str :returns: Processed notebook name, 001-hello-world-with-output.rst -> 001. hello world :rtype: str """ return ( notebook_name[:3] + "." + " ".join(notebook_name[4:].split(".")[0].split("-")[:-2]) )
bigcode/self-oss-instruct-sc2-concepts