seed
stringlengths
1
14k
source
stringclasses
2 values
def splitOut(aa): """Splits out into x,y,z, Used to simplify code Args: aa - dictionary spit out by Returns: outkx, outky, outkz (numpy arrays) - arrays of the x, y, and values of the points """ outkx = aa['x'][::3] outky = aa['x'][1::3] outkz = aa['x'][2::3] return outkx, outky, outkz
bigcode/self-oss-instruct-sc2-concepts
def unwrap_cdata(value): """Remove CDATA wrapping from `value` if present""" if value.startswith("<![CDATA[") and value.endswith("]]>"): return value[9:-3] else: return value
bigcode/self-oss-instruct-sc2-concepts
import pkgutil def get_all_modules(package_path): """Load all modules in a package""" return [name for _, name, _ in pkgutil.iter_modules([package_path])]
bigcode/self-oss-instruct-sc2-concepts
def GetDeviceNamesFromStatefulPolicy(stateful_policy): """Returns a list of device names from given StatefulPolicy message.""" if not stateful_policy or not stateful_policy.preservedState \ or not stateful_policy.preservedState.disks: return [] return [disk.key for disk in stateful_policy.preservedState.disks.additionalProperties]
bigcode/self-oss-instruct-sc2-concepts
def replace_tabs(string: str, tab_width: int = 4) -> str: """Takes an input string and a desired tab width and replaces each \\t in the string with ' '*tab_width.""" return string.replace('\t', ' '*tab_width)
bigcode/self-oss-instruct-sc2-concepts
def closestsites(struct_blk, struct_def, pos): """ Returns closest site to the input position for both bulk and defect structures Args: struct_blk: Bulk structure struct_def: Defect structure pos: Position Return: (site object, dist, index) """ blk_close_sites = struct_blk.get_sites_in_sphere(pos, 5, include_index=True) blk_close_sites.sort(key=lambda x:x[1]) def_close_sites = struct_def.get_sites_in_sphere(pos, 5, include_index=True) def_close_sites.sort(key=lambda x:x[1]) return blk_close_sites[0], def_close_sites[0]
bigcode/self-oss-instruct-sc2-concepts
from typing import Any import inspect def compare_attributes(obj1: Any, obj2: Any, *, ignore_simple_underscore: bool = False) -> bool: """Compares all attributes of two objects, except for methods, __dunderattrs__, and, optionally, _private_attrs. Args: obj1 (Any): First object to compare. obj2 (Any): Second object to compare. ignore_simple_underscore (:class:`bool`, optional): If ``True``, attributes starting with a single `_` won't be compared. Defaults to ``False`` (compares attributes starting with a single `_`, but not with two). Returns: :class:`bool`: ``True`` if obj1.X == obj2.X for all X (according to the criteria at the function description); ``False`` otherwise. Examples: .. testsetup:: * from serpcord.utils.model import compare_attributes .. doctest:: >>> class A: ... pass >>> a, b, c = A(), A(), A() >>> a.x = 5; a.y = 6; a.z = 7 >>> b.x = 5; b.y = 7; b.z = 7 >>> c.x = 5; c.y = 6; c.z = 7 >>> compare_attributes(a, b) # they differ in one attribute (y) False >>> compare_attributes(a, c) # all attributes are equal True """ for k1, v1 in inspect.getmembers(obj1): if k1.startswith("__") or (not ignore_simple_underscore and k1.startswith("_")): continue is_v1_method = inspect.ismethod(v1) for k2, v2 in filter(lambda k: k and k[0] == k1, inspect.getmembers(obj2)): if is_v1_method != inspect.ismethod(v2): # one is a method and the other isn't? return False if not is_v1_method and v1 != v2: return False return True
bigcode/self-oss-instruct-sc2-concepts
def _updated_or_published(mf): """ get the updated date or the published date Args: mf: python dictionary of some microformats object Return: string containing the updated date if it exists, or the published date if it exists or None """ props = mf['properties'] # construct updated/published date of mf if 'updated' in props: return props['updated'][0] elif 'published' in props: return props['published'][0] else: return None
bigcode/self-oss-instruct-sc2-concepts
from pathlib import Path def is_file(path: Path) -> bool: """ Return true if the given path is a file, false otherwise. :param path: a Path :return: a bool """ return path.is_file()
bigcode/self-oss-instruct-sc2-concepts
def dict2str(d): """Pretty formatter of a dictionary for one-line logging.""" return str(sorted(d.items()))
bigcode/self-oss-instruct-sc2-concepts
def retrieve_min_max_from_path(path): """looks for min and max float in path Args: path (str): folder path Returns: (float, float) retrieved min and max values """ path = path.replace("\\", "") path = path.replace("/", "") return float(path.split("_")[-2]), float(path.split("_")[-1])
bigcode/self-oss-instruct-sc2-concepts
def type_unpack(type): """ return the struct and the len of a particular type """ type = type.lower() s = None l = None if type == 'short': s = 'h' l = 2 elif type == 'bool': s = 'c' l = 1 elif type == 'ushort': s = 'H' l = 2 elif type == 'int': s = 'i' l = 4 elif type == 'uint': s = 'I' l = 4 elif type == 'long': s = 'l' l = 4 elif type == 'ulong': s = 'L' l = 4 elif type == 'float': s = 'f' l = 4 elif type == 'double': s = 'd' l = 8 else: raise TypeError('Unknown type %s' % type) return ('<' + s, l)
bigcode/self-oss-instruct-sc2-concepts
def get_unicode_code_points(string): """Returns a string of comma-delimited unicode code points corresponding to the characters in the input string. """ return ', '.join(['U+%04X' % ord(c) for c in string])
bigcode/self-oss-instruct-sc2-concepts
def as_markdown(args): """ Return args configs as markdown format """ text = "|name|value| \n|-|-| \n" for attr, value in sorted(vars(args).items()): text += "|{}|{}| \n".format(attr, value) return text
bigcode/self-oss-instruct-sc2-concepts
def ndbi(swir, red, nir, blue): """ Converts the swir, red, nir and blue band of Landsat scene to a normalized difference bareness index. Source: Zao and Chen, "Use of Normalized Difference Bareness Index in Quickly Mapping Bare from TM/ETM+", IEEE Conference Paper, 2005 DOI: 10.1109/IGARSS.2005.1526319 :param swir: numpy.array, shortwave infrared band :param red: numpy.array, red band :param nir: numpy.array, near infrared band :param blue: numpy.array, blue band :return: normal difference bareness index """ # bareness index components x = (swir + red) - (nir + blue) y = (swir + red) + (nir + blue) # prevent division by zero error y[y == 0.0] = 1.0 # bareness index img = x / y img[y == 1.0] = 0.0 # clip range to normal difference img[img < -1.0] = -1.0 img[img > 1.0] = 1.0 return img
bigcode/self-oss-instruct-sc2-concepts
import torch def reg_binary_entropy_loss(out): """ Mean binary entropy loss to drive values toward 0 and 1. Args: out (torch.float): Values for the binary entropy loss. The values have to be within (0, 1). Return: torch.float for the loss value. """ return torch.mean(-out * torch.log(out) - (1 - out) * torch.log(1 - out))
bigcode/self-oss-instruct-sc2-concepts
def get_hyperion_unique_id(server_id: str, instance: int, name: str) -> str: """Get a unique_id for a Hyperion instance.""" return f"{server_id}_{instance}_{name}"
bigcode/self-oss-instruct-sc2-concepts
def getModel(tsinput): """ This is the wrapper function for all profile models implemented in the runInput package. Parameters ---------- tsinput : :class:`.tsinput` A TurbSim input object. Returns ------- profModel : A subclass of :class:`.profModelBase` The appropriately initialized 'profile model' object specified in `tsinput`. """ # This executes the sub-wrapper function (defined below) specified # in the tsinput-object (input file WINDPROFILETYPE line) return eval('_' + tsinput['WindProfileType'].lower() + '(tsinput)')
bigcode/self-oss-instruct-sc2-concepts
from typing import Union from typing import Collection from typing import Set def split_csp_str(val: Union[Collection[str], str]) -> Set[str]: """Split comma separated string into unique values, keeping their order.""" if isinstance(val, str): val = val.strip().split(",") return set(x for x in val if x)
bigcode/self-oss-instruct-sc2-concepts
def identity(*args): """ Always returns the same value that was used as its argument. Example: >>> identity(1) 1 >>> identity(1, 2) (1, 2) """ if len(args) == 1: return args[0] return args
bigcode/self-oss-instruct-sc2-concepts
import pathlib from typing import Optional def latest_checkpoint_update(target: pathlib.Path, link_name: str) -> Optional[pathlib.Path]: """ This function finds the file that the symlink currently points to, sets it to the new target, and returns the previous target if it exists. :param target: A path to a file that we want the symlink to point to. :param link_name: This is the name of the symlink that we want to update. :return: - current_last: This is the previous target of the symlink, before it is updated in this function. If the symlink did not exist before or did not have a target, None is returned instead. """ link = pathlib.Path(link_name) if link.is_symlink(): current_last = link.resolve() link.unlink() link.symlink_to(target) return current_last link.symlink_to(target) return None
bigcode/self-oss-instruct-sc2-concepts
def isTIFF(filename: str) -> bool: """Check if file name signifies a TIFF image.""" if filename is not None: if(filename.casefold().endswith('.tif') or filename.casefold().endswith('.tiff')): return True return False
bigcode/self-oss-instruct-sc2-concepts
from typing import Dict def dataset_is_authoritative(dataset: Dict) -> bool: """Check if dataset is tagged as authoritative.""" is_authoritative = dataset.get("isAuthoritative") if is_authoritative: return is_authoritative["value"] == "true" return False
bigcode/self-oss-instruct-sc2-concepts
def max_farmers(collection): # pragma: no cover """Returns the maximum number of farmers recorded in the collection""" max_farmers = 0 for doc in collection.find({}).sort([('total_farmers',-1)]).limit(1): max_farmers = doc['total_farmers'] return max_farmers
bigcode/self-oss-instruct-sc2-concepts
import hashlib import pathlib def calculate_file_hash(file_path): """ Calculate the hash of a file on disk. We store a hash of the file in the database, so that we can keep track of files if they are ever moved to new drives. :param file_path: :return: """ block_size = 65536 hasher = hashlib.sha1() p = pathlib.Path(file_path) if p.exists(): with p.open('rb') as f: buf = f.read(block_size) while len(buf) > 0: hasher.update(buf) buf = f.read(block_size) return hasher.hexdigest() else: return None
bigcode/self-oss-instruct-sc2-concepts
def word_fits_in_line(pagewidth, x_pos, wordsize_w): """ Return True if a word can fit into a line. """ return (pagewidth - x_pos - wordsize_w) > 0
bigcode/self-oss-instruct-sc2-concepts
from typing import Dict from typing import Any def create_gyre_prefix(gyre_comb: Dict[str, Any]) -> str: """ Creates a GYRE run prefix to use for the given combination of GYRE parameter values. These prefixes should be unique within one MESA run, but can be repeated across multiple, separate, MESA runs. This also needs to be deterministic, reguardless of the fact that the dict passed in is unordered. >>> create_gyre_prefix({"a": 2, "c": 3, "b": "hi"}) 'gyre_a_2__b_hi__c_3__' """ name = "gyre_" for key in sorted(gyre_comb.keys()): name += key + "_" + str(gyre_comb[key]) + "__" return name
bigcode/self-oss-instruct-sc2-concepts
def findAllInfectedRelationships(tx): """ Method that finds all INFECTED relationships in the data base :param tx: is the transaction :return: a list of relationships """ query = ( "MATCH (n1:Person)-[r:COVID_EXPOSURE]->(n2:Person) " "RETURN ID(n1) , r , r.date , r.name , ID(n2);" ) results = tx.run(query).data() return results
bigcode/self-oss-instruct-sc2-concepts
import typing def is_same_classmethod( cls1: typing.Type, cls2: typing.Type, name: str, ) -> bool: """Check if two class methods are not the same instance.""" clsmeth1 = getattr(cls1, name) clsmeth2 = getattr(cls2, name) return clsmeth1.__func__ is clsmeth2.__func__
bigcode/self-oss-instruct-sc2-concepts
import socket import pickle def send_packet(sock, pack): """ Send a packet to remote socket. We first send the size of packet in bytes followed by the actual packet. Packet is serialized using cPickle module. Arguments --------- sock : Destination socket pack : Instance of class Packet. """ if pack is None or (sock is None or type(sock) != socket.socket): return # Nothing to send pack_raw_bytes = pickle.dumps(pack) dsize = len(pack_raw_bytes) sock.sendall(dsize.to_bytes(4, byteorder="big")) sock.sendall(pack_raw_bytes) return True
bigcode/self-oss-instruct-sc2-concepts
import torch def get_all_indcs(batch_size, n_possible_points): """ Return all possible indices. """ return torch.arange(n_possible_points).expand(batch_size, n_possible_points)
bigcode/self-oss-instruct-sc2-concepts
def N_STS_from_N_SS(N_SS, STBC): """ Number of space-time streams (N_{STS}) from number of spatial streams (N_{SS}), and the space-time block coding (STBC) used. The standard gives this a table (20-12), but it's just addition! """ return N_SS + STBC
bigcode/self-oss-instruct-sc2-concepts
def num_grid_points(d, mu): """ Checks the number of grid points for a given d, mu combination. Parameters ---------- d, mu : int The parameters d and mu that specify the grid Returns ------- num : int The number of points that would be in a grid with params d, mu Notes ----- This function is only defined for mu = 1, 2, or 3 """ if mu == 1: return 2*d + 1 if mu == 2: return 1 + 4*d + 4*d*(d-1)/2. if mu == 3: return 1 + 8*d + 12*d*(d-1)/2. + 8*d*(d-1)*(d-2)/6.
bigcode/self-oss-instruct-sc2-concepts
from datetime import datetime import time def get_end_date_of_schedule(schedule): """Return the end date of the provided schedule in ISO 8601 format""" currenttime = datetime.today() endtime = datetime( currenttime.year, currenttime.month, currenttime.day, schedule['end-hour'], schedule['end-minute']) # manually create ISO8601 string because of tz issues with Python2 ts = time.time() utc_offset = ((datetime.fromtimestamp( ts) - datetime.utcfromtimestamp(ts)).total_seconds()) / 3600 offset = str(int(abs(utc_offset * 100))).zfill(4) sign = "+" if utc_offset >= 0 else "-" return endtime.strftime("%Y-%m-%dT%H:%M:%S{sign}{offset}".format(sign=sign, offset=offset))
bigcode/self-oss-instruct-sc2-concepts
def get_uncert_dict(res): """ Gets the row and column of missing values as a dict Args: res(np.array): missing mask Returns: uncertain_dict (dict): dictionary with row and col of missingness """ uncertain_dict = {} for mytuple in res: row = mytuple[0] col = mytuple[1] if uncertain_dict.get(row): uncertain_dict[row].append(col) else: uncertain_dict[row] = [col] return uncertain_dict
bigcode/self-oss-instruct-sc2-concepts
def _and(*args): """Helper function to return its parameters and-ed together and bracketed, ready for a SQL statement. eg, _and("x=1", "y=2") => "(x=1 AND y=2)" """ return " AND ".join(args)
bigcode/self-oss-instruct-sc2-concepts
from typing import Dict def load_lookup_from_csv(csv_source: str, count: int) -> Dict[str, int]: """ From Dino, feature extraction utils Load a lookup dictionary, mapping string to rank, from a CSV file. Assumes the CSV to be pre-sorted. :param csv_source: Source data filepath :param count: number of strings to load :return: dictionary mapping strings to rank """ lookup_dict: Dict[str, int] = dict() rank: int = 0 with open(csv_source, 'r') as fd: line = next(fd) try: while rank < count: if line.startswith("#"): line = next(fd) continue lookup_dict[line.strip().split(',')[-1]] = rank rank += 1 line = next(fd) except StopIteration: raise RuntimeError(f"Not enough entries in file. Expected at least {count}, max is {rank}.") return lookup_dict
bigcode/self-oss-instruct-sc2-concepts
def get_edges(mapping): """ Returns the sorted edge list for topology. :param mapping: Process-to-node mapping :return: Topology edge list """ proc_map = mapping.mapping edges = mapping.process_graph.edges(data=True) return sorted([(min(proc_map[u], proc_map[v]), max(proc_map[u], proc_map[v]), data['weight']) for u, v, data in edges])
bigcode/self-oss-instruct-sc2-concepts
import random import string def get_shipping_details_response(order_id, address_id): """ Creates a json response for a shipping details request. :param order_id: ID for the transaction. :param address_id: Address ID received from Vipps. :return: A json response for a shipping details request. """ shipping_details = { "addressId": address_id, "orderId": order_id, "shippingDetails": [ { "isDefault": "N", "priority": 1, "shippingCost": 30.0, "shippingMethod": "postNord", "shippingMethodId": "".join(random.choices(string.ascii_lowercase + string.digits, k=6)) }, { "isDefault": "Y", "priority": 2, "shippingCost": 30.0, "shippingMethod": "Posten", "shippingMethodId": "".join(random.choices(string.ascii_lowercase + string.digits, k=6)) } ] } return shipping_details
bigcode/self-oss-instruct-sc2-concepts
def fillgaps_time(ds, method='cubic', max_gap=None): """ Fill gaps (nan values) across time using the specified method Parameters ---------- ds : xarray.Dataset The adcp dataset to clean method : string Interpolation method to use max_gap : numeric Max number of consective NaN's to interpolate across Returns ------- ds : xarray.Dataset The adcp dataset with gaps in velocity interpolated across time See Also -------- xarray.DataArray.interpolate_na() """ ds['vel'] = ds.vel.interpolate_na(dim='time', method=method, use_coordinate=True, max_gap=max_gap) if hasattr(ds, 'vel_b5'): ds['vel_b5'] = ds.vel.interpolate_na(dim='time', method=method, use_coordinate=True, max_gap=max_gap) return ds
bigcode/self-oss-instruct-sc2-concepts
def predict1(payload): """ Define a hosted function that echos out the input. When creating a predict image, this is the function that is hosted on the invocations endpoint. Arguments: payload (dict[str, object]): This is the payload that will eventually be sent to the server using a POST request. Returns: payload (dict[str, object]): The output of the function is expected to be either a dictionary (like the function input) or a JSON string. """ print('Predict 1!') return payload
bigcode/self-oss-instruct-sc2-concepts
def signtest_data(RNG,n,trend=0): """ Creates a dataset of `n` pairs of normally distributed numbers with a trend towards the first half of a pair containing smaller values. If `trend` is zero, this conforms with the null hypothesis. """ return [( RNG.normal(size=size)-trend, RNG.normal(size=size) ) for size in RNG.randint(15,21,size=n) ]
bigcode/self-oss-instruct-sc2-concepts
import re def finditer_with_line_numbers(pattern, input_string, flags=0): """ A version of 're.finditer' that returns '(match, line_number)' pairs. """ matches = list(re.finditer(pattern, input_string, flags)) if not matches: return [] end = matches[-1].start() # -1 so a failed 'rfind' maps to the first line. newline_table = {-1: 0} for i, m in enumerate(re.finditer(r'\n', input_string), 1): # don't find newlines past our last match offset = m.start() if offset > end: break newline_table[offset] = i # Failing to find the newline is OK, -1 maps to 0. for m in matches: newline_offset = input_string.rfind('\n', 0, m.start()) line_number = newline_table[newline_offset] yield m, line_number
bigcode/self-oss-instruct-sc2-concepts
import csv def read_employees(csv_file_location): """ Convert csv file to dictionary. Receives a CSV file as a parameter and returns a list of dictionaries from that file. """ csv.register_dialect("empDialect", skipinitialspace=True, strict=True) employee_file = csv.DictReader( open(csv_file_location), dialect="empDialect") employee_list = [] for data in employee_file: employee_list.append(data) return employee_list
bigcode/self-oss-instruct-sc2-concepts
def drop_irrelevant_practices(df, practice_col): """Drops irrelevant practices from the given measure table. An irrelevant practice has zero events during the study period. Args: df: A measure table. practice_col: column name of practice column Returns: A copy of the given measure table with irrelevant practices dropped. """ is_relevant = df.groupby(practice_col).value.any() return df[df[practice_col].isin(is_relevant[is_relevant == True].index)]
bigcode/self-oss-instruct-sc2-concepts
import codecs def encode_endian(text, encoding, errors="strict", le=True): """Like text.encode(encoding) but always returns little endian/big endian BOMs instead of the system one. Args: text (text) encoding (str) errors (str) le (boolean): if little endian Returns: bytes Raises: UnicodeEncodeError LookupError """ encoding = codecs.lookup(encoding).name if encoding == "utf-16": if le: return codecs.BOM_UTF16_LE + text.encode("utf-16-le", errors) else: return codecs.BOM_UTF16_BE + text.encode("utf-16-be", errors) elif encoding == "utf-32": if le: return codecs.BOM_UTF32_LE + text.encode("utf-32-le", errors) else: return codecs.BOM_UTF32_BE + text.encode("utf-32-be", errors) else: return text.encode(encoding, errors)
bigcode/self-oss-instruct-sc2-concepts
def features_axis_is_np(is_np, is_seq=False): """ B - batch S - sequence F - features :param d: torch.Tensor or np.ndarray of shape specified below :param is_seq: True if d has sequence dim :return: axis of features """ if is_np: # in case of sequence (is_seq == True): (S, F) # in case of sample: (F) return 0 + is_seq else: # in case of sequence: (B, S, F) # in case of sample: (B, F) return 1 + is_seq
bigcode/self-oss-instruct-sc2-concepts
def parse_args(args): """Parses and validates command line arguments Args: args (argparse.Namespace): Pre-paresed command line arguments Returns: bool: verbose flag, indicates whether tag frequency dictionary should be printed bool: sandbox flag, indicates whether Evernote API calls should be made against the production or sandbox environment str: name of the file the tag cloud image should be saved to int: width of the tag cloud image int: height of the tag cloud image file: mask file to use when generating the tag cloud str: font file to use when generating the tag cloud int: maximum number of tags to include in the tag cloud int: ratio of horizontal tags in the tag cloud int: the impact of tag frequency (as opposed to tag ranking) on tag size str: the name of a matplotlib colormap to use for tag colors (see https://matplotlib.org/examples/color/colormaps_reference.html for available colormaps) str: the Evernote API authentication token Raises: ValueError: if numeric parameters have an invalid value """ image_width_height = args.imageSize.split("x") if len(image_width_height) != 2: raise ValueError("invalid imageSize [%s] format, expected format is <width>x<height>", args.imageSize) image_width, image_height = int(image_width_height[0]), int(image_width_height[1]) if image_width not in range(10, 10000): raise ValueError("invalid imageSize.width [%d], imageSize.width must be between 10 and 9999", image_width) if image_height not in range(10, 10000): raise ValueError("invalid imageSize.height [%d], imageSize.height must be between 10 and 9999", image_height) if args.maxTags not in range(1, 1000): raise ValueError("invalid maxTags [%d], maxTags must be between 1 and 999", args.maxTags) if args.horizontalTags < 0 or args.horizontalTags > 1 : raise ValueError("invalid horizontalTags [%f], horizontalTags must be between 0 and 1", args.horizontalTags) if args.tagScaling < 0 or args.tagScaling > 1: raise ValueError("invalid tagScaling [%f], tagScaling must be between 0 and 1", args.horizontalTags) font_file = None if args.fontFile == None else args.fontFile.name return args.verbose, args.sandbox, args.imageFile.name, image_width, image_height, args.maskFile, font_file, args.maxTags, args.horizontalTags, args.tagScaling, args.tagColorScheme, args.evernoteAuthToken
bigcode/self-oss-instruct-sc2-concepts
def _extract_prop_set(line): """ Extract the (key, value)-tuple from a string like: >>> 'set foo = "bar"' :param line: :return: tuple (key, value) """ token = ' = "' line = line[4:] pos = line.find(token) return line[:pos], line[pos + 4:-1]
bigcode/self-oss-instruct-sc2-concepts
import torch def depth_map_to_locations(depth, invK, invRt): """ Create a point cloud from a depth map Inputs: depth HxW torch.tensor with the depth values invK 3x4 torch.tensor with the inverse intrinsics matrix invRt 3x4 torch.tensor with the inverse extrinsics matrix Outputs: points HxWx3 torch.tensor with the 3D points """ H,W = depth.shape[:2] depth = depth.view(H,W,1) xs = torch.arange(0, W).float().reshape(1,W,1).to(depth.device).expand(H,W,1) ys = torch.arange(0, H).float().reshape(H,1,1).to(depth.device).expand(H,W,1) zs = torch.ones(1,1,1).to(depth.device).expand(H,W,1) world_coords = depth * (torch.cat((xs, ys, zs), dim=2) @ invK.T[None]) @ invRt[:3,:3].T[None] + invRt[:3,3:].T[None] return world_coords
bigcode/self-oss-instruct-sc2-concepts
def list_to_quoted_delimited(input_list: list, delimiter: str = ',') -> str: """ Returns a string which is quoted + delimited from a list :param input_list: eg: ['a', 'b', 'c'] :param delimiter: '|' :return: eg: 'a'|'b'|'c' """ return f'{delimiter} '.join("'{0}'".format(str_item) for str_item in input_list)
bigcode/self-oss-instruct-sc2-concepts
def plugin(plugin_without_server): """ Construct mock plugin with NotebookClient with server registered. Use `plugin.client` to access the client. """ server_info = {'notebook_dir': '/path/notebooks', 'url': 'fake_url', 'token': 'fake_token'} plugin_without_server.client.register(server_info) return plugin_without_server
bigcode/self-oss-instruct-sc2-concepts
import typing import pathlib import glob def _get_paths(patterns: typing.Set[pathlib.Path]) -> typing.Set[pathlib.Path]: """Convert a set of file/directory patterns into a list of matching files.""" raw = [ pathlib.Path(item) for pattern in patterns for item in glob.iglob(str(pattern), recursive=True) ] files = [p for p in raw if not p.is_dir()] output = files + [ child for p in raw for item in glob.iglob(f"{p}/**/*", recursive=True) if p.is_dir() and not (child := pathlib.Path(item)).is_dir() ] return set(output)
bigcode/self-oss-instruct-sc2-concepts
def _attr2obj(element, attribute, convert): """ Reads text from attribute in element :param element: etree element :param attribute: name of attribute to be read :param convert: intrinsic function (e.g. int, str, float) """ try: if element.get(attribute) is None: return None elif element.get(attribute) == '': return None return convert(element.get(attribute)) except Exception: None
bigcode/self-oss-instruct-sc2-concepts
def create_cercauniversita(conn, cercauni): """ Create a new person into the cercauniversita table :param conn: :param cercauni: :return: cercauni id """ sql = ''' INSERT INTO cercauniversita(id,authorId,anno,settore,ssd,fascia,orcid,cognome,nome,genere,ateneo,facolta,strutturaAfferenza) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?) ''' cur = conn.cursor() cur.execute(sql, cercauni) return cur.lastrowid
bigcode/self-oss-instruct-sc2-concepts
def get_item_from_user(message, lst): """ Gets a valid index from a user to get an item from lst. The user is shown `message` and the range of valid indices, in the form of "Valid indices inclusive between 0 and max_index". The user is asked until a valid item was chosen. Args: message: The message to show the user before asking for index lst: the list to choose from Returns: The chosen index """ idx = -1 while idx == -1: try: # get an input from the user print(message) val = input(f"Valid indices inclusive between 0 and {len(lst) - 1}\n") # try to parse it as an int idx = int(val) # try to extract the action, this will throw if out of bounds item = lst[idx] # if it was no int or is out of bounds, remind the user what is to do # and reset idx except (ValueError, IndexError): idx = -1 print( "Please enter an integer value between inclusive " f"0 and {len(lst) - 1}" ) return idx
bigcode/self-oss-instruct-sc2-concepts
def cauchy_cooling_sequence(initial_t, it): """ Calculates the new temperature per iteration using a cauchy progression. Parameters ---------- initial_t : float initial temperature it: int actual iteration Returns -------- tt: float new temperature """ tt = initial_t/(1+it) return tt
bigcode/self-oss-instruct-sc2-concepts
def is_end(word, separator): """Return true if the subword can appear at the end of a word (i.e., the subword does not end with separator). Return false otherwise.""" return not word.endswith(separator)
bigcode/self-oss-instruct-sc2-concepts
def _reconstruct_path(target_candidate, scanned): """ Reconstruct a path from the scanned table, and return the path sequence. """ path = [] candidate = target_candidate while candidate is not None: path.append(candidate) candidate = scanned[candidate.id] return path
bigcode/self-oss-instruct-sc2-concepts
import string def query_to_url(query, search_type, size): """convert query to usuable url Args: query (str): search query by user search_type (str): Search type (choice) size (int): number of items to query Returns: (str) the url for search """ # remove bad string & convert txt -> search keys query = query.translate(str.maketrans('', '', string.punctuation)) query = query.replace(" ", "+") # get the correct mapping mapping = {"All Fields": "", "Title": "title", "Abstract": "abstract"} search_type = mapping[search_type] #return the url return f"https://arxiv.org/search/?query={query}&searchtype={search_type}&abstracts=show&order=&size={size}"
bigcode/self-oss-instruct-sc2-concepts
from pathlib import Path def read_polymer(filename: Path) -> tuple[dict, str]: """Read polymer structure information from a file The polymer is represented by a dict of rules and a polymer structer. Args: filename (Path): path to the input file. Returns: dict: rules str: initial polymer structure Examples: >>> read_polymer(Path("test_data/day_14.data"))[0]['CH'] 'B' >>> read_polymer(Path("test_data/day_14.data"))[1] 'NNCB' """ with filename.open("r") as file: poly_template, rules_raw = file.read().split("\n\n") rules = {} for line in rules_raw.strip().split("\n"): start, end = line.strip().split(" -> ") rules[start] = end return rules, poly_template
bigcode/self-oss-instruct-sc2-concepts
def query_phantoms(view, pids): """Query phantoms.""" return view.query_phantoms(pids)
bigcode/self-oss-instruct-sc2-concepts
def get_positive_passages(positive_pids, doc_scores, passage_map): """ Get positive passages for a given grounding using BM25 scores from the positive passage pool Parameters: positive_pids: list Positive passage indices doc_scores: list BM25 scores against the query's grounding for all passages passage_map: dict All passages mapped with their ids Returns: positive_passage_pool """ scores = [(i, score) for (i, score) in doc_scores if i in positive_pids] top_scores = sorted(scores, key=lambda x: x[1], reverse=True) top_n_passages = [ {"psg_id": ix, "score": score, "title": passage_map[ix]["title"], "text": passage_map[ix]["text"]} for ix, score in top_scores ] return top_n_passages
bigcode/self-oss-instruct-sc2-concepts
def lire_mots(nom_fichier): """fonction qui récupère la liste des mots dans un fichier paramètre - nom_fichier, de type chaine de caractère : nom du fichier contenant les mots (un par ligne) retour : liste de chaine de caractères """ liste_mots = [] # le tableau qui contiendra les lignes with open(nom_fichier, encoding="UTF-8") as f: # on ouvre le fichier ligne = f.readline() # une variable temporaire pour récupérer la ligne courante dans le fichier f while ligne != "": liste_mots.append(ligne.strip()) # on rajoute la ligne courante dans le tableau ligne = f.readline() # on récupère la ligne suivante return liste_mots
bigcode/self-oss-instruct-sc2-concepts
from typing import List def _hyphens_exists_next_line( line_splitted_list: List[str], next_line_idx: int) -> bool: """ Get the boolean value of whether there are multiple hyphen characters on the next line. Parameters ---------- line_splitted_list : list of str A list containing line-by-line strings. next_line_idx : int Next line index. Returns ------- result_bool : bool If exists, True will be set. """ if len(line_splitted_list) < next_line_idx + 1: return False next_line_str: str = line_splitted_list[next_line_idx] is_in: bool = '----' in next_line_str if is_in: return True return False
bigcode/self-oss-instruct-sc2-concepts
def get_data(dataset): """Get features and targets from a specific dataset. Parameters ---------- dataset : Dataset object dataset that can provide features and targets Returns ------- features : arrary features in the dataset targets : array 1-d targets in the dataset """ handle = dataset.open() data = dataset.get_data(handle, slice(0, dataset.num_examples)) features = data[0] targets = data[1] dataset.close(handle) return features, targets
bigcode/self-oss-instruct-sc2-concepts
def _gen_perm_Numpy(order, mode): """ Generate the specified permutation by the given mode. Parameters ---------- order : int the length of permutation mode : int the mode of specific permutation Returns ------- list the axis order, according to Kolda's unfold """ tmp = list(range(order - 1, -1, -1)) tmp.remove(mode) perm = [mode] + tmp return perm
bigcode/self-oss-instruct-sc2-concepts
def contains_duplicate(nums: list[int]) -> bool: """Returns True if any value appears at least twice in the array, otherwise False Complexity: n = len(nums) Time: O(n) Space: O(n) Args: nums: array of possibly non-distinct values Examples: >>> contains_duplicate([1,2,3,1]) True >>> contains_duplicate([1,2,3,4]) False >>> contains_duplicate([1,1,1,3,3,4,3,2,4,2]) True """ """ALGORITHM""" ## INITIALIZE VARS ## # DS's/res nums_set = set() for num in nums: if num not in nums_set: nums_set.add(num) else: return True else: return False
bigcode/self-oss-instruct-sc2-concepts
def depth_bonacci_rule(depth): """rule for generating tribonacci or other arbitrary depth words Args: depth (int): number of consecutive previous words to concatenate Returns: lambda w: w[-1] + w[-2] + ... + w[-(depth+1)] For example, if depth is 3, you get the tribonacci words. (there is already a tribonacci and quadbonacci words method) """ return lambda w: "".join(w[-1:-depth-1:-1])
bigcode/self-oss-instruct-sc2-concepts
import re def compile_patterns(patterns): """Compile a list of patterns into one big option regex. Note that all of them will match whole words only.""" # pad intent patterns with \b (word boundary), unless they contain '^'/'$' (start/end) return re.compile('|'.join([((r'\b' if not pat.startswith('^') else '') + pat + (r'\b' if not pat.endswith('$') else '')) for pat in patterns]), re.I | re.UNICODE)
bigcode/self-oss-instruct-sc2-concepts
def cli(ctx): """Get the list of all data tables. Output: A list of dicts with details on individual data tables. For example:: [{"model_class": "TabularToolDataTable", "name": "fasta_indexes"}, {"model_class": "TabularToolDataTable", "name": "bwa_indexes"}] """ return ctx.gi.tool_data.get_data_tables()
bigcode/self-oss-instruct-sc2-concepts
def _function_iterator(graph): """Iterate over the functions in a graph. :rtype: iter[str] """ return ( node.function for node in graph )
bigcode/self-oss-instruct-sc2-concepts
def ms_energy_stat(microstates): """ Given a list of microstates, find the lowest energy, average energy, and highest energy """ ms = next(iter(microstates)) lowerst_E = highest_E = ms.E N_ms = 0 total_E = 0.0 for ms in microstates: if lowerst_E > ms.E: lowerst_E = ms.E elif highest_E < ms.E: highest_E = ms.E N_ms += ms.count total_E += ms.E*ms.count average_E = total_E/N_ms return lowerst_E, average_E, highest_E
bigcode/self-oss-instruct-sc2-concepts
import json def check_role_in_retrieved_nym(retrieved_nym, role): """ Check if the role in the GET NYM response is what we want. :param retrieved_nym: :param role: the role we want to check. :return: True if the role is what we want. False if the role is not what we want. """ if retrieved_nym is None: return False nym_dict = json.loads(retrieved_nym) if "data" in nym_dict["result"]: temp_dict = json.loads(nym_dict["result"]["data"]) if "role" in temp_dict: if not temp_dict["role"] == role: return False else: return True return False
bigcode/self-oss-instruct-sc2-concepts
def _do_get_features_list(featurestore_metadata): """ Gets a list of all features in a featurestore Args: :featurestore_metadata: metadata of the featurestore Returns: A list of names of the features in this featurestore """ features = [] for fg in featurestore_metadata.featuregroups.values(): features.extend(fg.features) features = list(map(lambda f: f.name, features)) return features
bigcode/self-oss-instruct-sc2-concepts
def vector_dot(xyz, vector): """ Take a dot product between an array of vectors, xyz and a vector [x, y, z] **Required** :param numpy.ndarray xyz: grid (npoints x 3) :param numpy.ndarray vector: vector (1 x 3) **Returns** :returns: dot product between the grid and the (1 x 3) vector, returns an (npoints x 1) array :rtype: numpy.ndarray """ if len(vector) != 3: raise Exception( "vector should be length 3, the provided length is {}".format( len(vector) ) ) return vector[0]*xyz[:, 0] + vector[1]*xyz[:, 1] + vector[2]*xyz[:, 2]
bigcode/self-oss-instruct-sc2-concepts
def filter_leetify(a, **kw): """Leetify text ('a' becomes '4', 'e' becomes '3', etc.)""" return a.replace('a','4').replace('e','3').replace('i','1').replace('o','0').replace('u','^')
bigcode/self-oss-instruct-sc2-concepts
import ast def eval_string(string): """automatically evaluate string to corresponding types. For example: not a string -> return the original input '0' -> 0 '0.2' -> 0.2 '[0, 1, 2]' -> [0,1,2] 'eval(1+2)' -> 3 'eval(range(5))' -> [0,1,2,3,4] Args: value : string. Returns: the corresponding type """ if not isinstance(string, str): return string if len(string) > 1 and string[0] == '[' and string[-1] == ']': return eval(string) if string[0:5] == 'eval(': return eval(string[5:-1]) try: v = ast.literal_eval(string) except: v = string return v
bigcode/self-oss-instruct-sc2-concepts
def convolution(image, kernel, row, column): """ Apply convolution to given image with the kernel and indices. :param image: image that will be convolved. :param kernel: kernel that will be used with convolution. :param row: row index of the central pixel. :param column: row index of the central pixel. :return: the convolved pixel value. """ value = 0 for i in range(2, -1, -1): for j in range(2, -1, -1): row_index = row - (i - 1) col_index = column - (j - 1) value += image[row_index][col_index] * kernel[i][j] if value < 0: value = 0 elif value > 255: value = 255 return int(value)
bigcode/self-oss-instruct-sc2-concepts
def token_to_char_position(tokens, start_token, end_token): """Converts a token positions to char positions within the tokens.""" start_char = 0 end_char = 0 for i in range(end_token): tok = tokens[i] end_char += len(tok) + 1 if i == start_token: start_char = end_char return start_char, end_char
bigcode/self-oss-instruct-sc2-concepts
def flatten_image(image): """ Flat the input 2D image into an 1D image while preserve the channels of the input image with shape==[height x width, channels] :param image: Input 2D image (either multi-channel color image or greyscale image) :type image: numpy.ndarray :return: The flatten 1D image. shape==(height x width, channels) :rtype: numpy.ndarry """ assert len(image.shape) >= 2, "The input image must be a 2 Dimensional image" if len(image.shape) == 3: image = image.reshape((-1, image.shape[2])) elif len(image.shape) == 2: image = image.reshape((-1, 1)) return image
bigcode/self-oss-instruct-sc2-concepts
def split_fqdn(fqdn): """ Unpack fully qualified domain name parts. """ if not fqdn: return [None] * 3 parts = fqdn.split(".") return [None] * (3 - len(parts)) + parts[0:3]
bigcode/self-oss-instruct-sc2-concepts
from typing import Union from pathlib import Path import json def read_json(path: Union[str, Path]): """ Read a json file from a string path """ with open(path) as f: return json.load(f)
bigcode/self-oss-instruct-sc2-concepts
def add_arrays(arr1, arr2): """ Function to adds two arrays element-wise Returns the a new array with the result """ if len(arr1) == len(arr2): return [arr1[i] + arr2[i] for i in range(len(arr1))] return None
bigcode/self-oss-instruct-sc2-concepts
def strip_commands(commands): """ Strips a sequence of commands. Strips down the sequence of commands by removing comments and surrounding whitespace around each individual command and then removing blank commands. Parameters ---------- commands : iterable of strings Iterable of commands to strip. Returns ------- stripped_commands : list of str The stripped commands with blank ones removed. """ # Go through each command one by one, stripping it and adding it to # a growing list if it is not blank. Each command needs to be # converted to an str if it is a bytes. stripped_commands = [] for v in commands: if isinstance(v, bytes): v = v.decode(errors='replace') v = v.split(';')[0].strip() if len(v) != 0: stripped_commands.append(v) return stripped_commands
bigcode/self-oss-instruct-sc2-concepts
def __merge2sorted__(arr1, arr2): """ Takes two sorted subarrays and returns a sorted array """ m, n = len(arr1), len(arr2) aux_arr = [None] * (m + n) p1 = 0 p2 = 0 c = 0 while p1 < m and p2 < n: if arr1[p1] < arr2[p2]: aux_arr[c] = arr1[p1] p1 += 1 else: aux_arr[c] = arr2[p2] p2 += 1 c += 1 if p1 == m: # arr1 exhausted while p2 < n: aux_arr[c] = arr2[p2] p2 += 1 c += 1 elif p2 == n: # arr2 exhausted while p1 < m: aux_arr[c] = arr1[p1] p1 += 1 c += 1 return aux_arr
bigcode/self-oss-instruct-sc2-concepts
from typing import Dict from typing import Any def userinfo_token( token_subject: str, token_idp: str, token_ssn: str, ) -> Dict[str, Any]: """ Mocked userinfo-token from Identity Provider (unencoded). """ return { 'iss': 'https://pp.netseidbroker.dk/op', 'nbf': 1632389572, 'iat': 1632389572, 'exp': 1632389872, 'amr': ['code_app'], 'mitid.uuid': '7ddb51e7-5a04-41f8-9f3c-eec1d9444979', 'mitid.age': '55', 'mitid.identity_name': 'Anker Andersen', 'mitid.date_of_birth': '1966-02-03', 'loa': 'https://data.gov.dk/concept/core/nsis/Substantial', 'acr': 'https://data.gov.dk/concept/core/nsis/Substantial', 'identity_type': 'private', 'idp': token_idp, 'dk.cpr': token_ssn, 'auth_time': '1632387312', 'sub': token_subject, 'aud': '0a775a87-878c-4b83-abe3-ee29c720c3e7', 'transaction_id': 'a805f253-e8ea-4457-9996-c67bf704ab4a', }
bigcode/self-oss-instruct-sc2-concepts
def homo_line(a, b): """ Return the homogenous equation of a line passing through a and b, i.e. [ax, ay, 1] cross [bx, by, 1] """ return (a[1] - b[1], b[0] - a[0], a[0] * b[1] - a[1] * b[0])
bigcode/self-oss-instruct-sc2-concepts
from unittest.mock import call def get_local_jitter(sound, min_time=0., max_time=0., pitch_floor=75., pitch_ceiling=600., period_floor=0.0001, period_ceiling=0.02, max_period_factor=1.3): """ Function to calculate (local) jitter from a periodic PointProcess. :param (parselmouth.Sound) sound: sound waveform :param (float) min_time: minimum time value considered for time range (t1, t2) (default: 0.) :param (float) max_time: maximum time value considered for time range (t1, t2) (default: 0.) NOTE: If max_time <= min_time, the entire time domain is considered :param (float) pitch_floor: minimum pitch (default: 75.) :param (float) pitch_ceiling: maximum pitch (default: 600.) :param (float) period_floor: the shortest possible interval that will be used in the computation of jitter, in seconds (default: 0.0001) :param (float) period_ceiling: the longest possible interval that will be used in the computation of jitter, in seconds (default: 0.02) :param (float) max_period_factor: the largest possible difference between consecutive intervals that will be used in the computation of jitter (default: 1.3) :return: value of (local) jitter """ # Create a PointProcess object point_process = call(sound, 'To PointProcess (periodic, cc)', pitch_floor, pitch_ceiling) local_jitter = call(point_process, 'Get jitter (local)', min_time, max_time, period_floor, period_ceiling, max_period_factor) return local_jitter
bigcode/self-oss-instruct-sc2-concepts
def anchor_ctr_inside_region_flags(anchors, stride, region): """Get the flag indicate whether anchor centers are inside regions.""" x1, y1, x2, y2 = region f_anchors = anchors / stride x = (f_anchors[:, 0] + f_anchors[:, 2]) * 0.5 y = (f_anchors[:, 1] + f_anchors[:, 3]) * 0.5 flags = (x >= x1) & (x <= x2) & (y >= y1) & (y <= y2) return flags
bigcode/self-oss-instruct-sc2-concepts
def position_is_escaped(string, position=None): """ Checks whether a char at a specific position of the string is preceded by an odd number of backslashes. :param string: Arbitrary string :param position: Position of character in string that should be checked :return: True if the character is escaped, False otherwise """ escapes_uneven = False # iterate backwards, starting one left of position. # Slicing provides a sane default behaviour and prevents IndexErrors for i in range(len(string[:position]) - 1, -1, -1): if string[i] == '\\': escapes_uneven = not escapes_uneven else: break return escapes_uneven
bigcode/self-oss-instruct-sc2-concepts
def select_column_values(df, col_name="totale_casi", groupby=["data"], group_by_criterion="sum"): """ :param df: pandas dataFrame :param col_name: column of interest :param groupby: column to group by (optional) data. :param group_by_criterion: how to merge the values of grouped elements in col_name. Only sum supported. :return: a list of of values """ if groupby is not None: if group_by_criterion == "sum": return df.groupby(by=groupby)[col_name].sum().reset_index()[col_name].values else: return RuntimeWarning else: return list(df[col_name])
bigcode/self-oss-instruct-sc2-concepts
def normalize_min_max(x, x_min, x_max): """Normalized data using it's maximum and minimum values # Arguments x: array x_min: minimum value of x x_max: maximum value of x # Returns min-max normalized data """ return (x - x_min) / (x_max - x_min)
bigcode/self-oss-instruct-sc2-concepts
def get_orientation_from(pose): """ Extract and convert the pose's orientation into a list. Args: pose (PoseStamped): the pose to extract the position from Returns: the orientation quaternion list [x, y, z, w] """ return [pose.pose.orientation.x, pose.pose.orientation.y, pose.pose.orientation.z, pose.pose.orientation.w]
bigcode/self-oss-instruct-sc2-concepts
import string def index_to_column(index): """ 0ベース序数をカラムを示すアルファベットに変換する。 Params: index(int): 0ベース座標 Returns: str: A, B, C, ... Z, AA, AB, ... """ m = index + 1 # 1ベースにする k = 26 digits = [] while True: q = (m-1) // k d = m - q * k digit = string.ascii_uppercase[d-1] digits.append(digit) if m <= k: break m = q return "".join(reversed(digits))
bigcode/self-oss-instruct-sc2-concepts
def _listen_count(opp): """Return number of event listeners.""" return sum(opp.bus.async_listeners().values())
bigcode/self-oss-instruct-sc2-concepts
import math def distance(point1, point2): """ Calculates distance between two points. :param point1: tuple (x, y) with coordinates of the first point :param point2: tuple (x, y) with coordinates of the second point :return: distance between two points in pixels """ return math.sqrt(math.pow(point1[0] - point2[0], 2) + math.pow(point1[1] - point2[1], 2))
bigcode/self-oss-instruct-sc2-concepts
from typing import List from typing import Set def scan_polarimeter_names(group_names: List[str]) -> Set[str]: """Scan a list of group names and return the set of polarimeters in it. Example:: >>> group_names(["BOARD_G", "COMMANDS", "LOG", "POL_G0", "POL_G6"]) set("G0", "G6") """ result = set() # type: Set[str] for curname in group_names: if (len(curname) == 6) and (curname[0:4] == "POL_"): result.add(curname[4:6].upper()) return result
bigcode/self-oss-instruct-sc2-concepts
def get_project_folders(window): """Get project folder.""" data = window.project_data() if data is None: data = {'folders': [{'path': f} for f in window.folders()]} return data.get('folders', [])
bigcode/self-oss-instruct-sc2-concepts
import textwrap def dedented_lines(description): """ Each line of the provided string with leading whitespace stripped. """ if not description: return [] return textwrap.dedent(description).split('\n')
bigcode/self-oss-instruct-sc2-concepts