seed
stringlengths
1
14k
source
stringclasses
2 values
def message_with_line(cell, message, sourcepos=[[1, 1], [1, 1]]): """ Print 'message', along with some of the lines of 'cell' """ return f"{message}. Some relevant lines from the cell:\n\n{cell.lines(sourcepos)}"
bigcode/self-oss-instruct-sc2-concepts
import pathlib from typing import Dict import yaml def config_parser(file_path: pathlib.Path) -> Dict[int, list]: """Opens and parses a `yaml` configuration file. Uses [PyYAML](https://pyyaml.org) to parse the configuration file. Args: file_path (pathlib.Path): The path towards the user's ...
bigcode/self-oss-instruct-sc2-concepts
from datetime import datetime def _is_key_expired(key, expiration_in_days): """ Whether or not service account key is expired based on when it was created and the current time. Args: key (dict): API return for a service key .. code-block:: python { ...
bigcode/self-oss-instruct-sc2-concepts
def sharpe_calc(rtrn: float, risk: float, rf: float) -> float: """ Calculate the Sharpe Ratio assumed given continuously compounded return. :param rtrn: Continuously compounded return. :param risk: Standard deviation of portfolio. :param rf: Risk free rate of return. :return: Sharpe Ratio. "...
bigcode/self-oss-instruct-sc2-concepts
def _slice_support(the_slice, length): """Takes a slice and the length of an object; returns normalized version. Specifically, corrects start and end for negative indices. """ start = the_slice.start stop = the_slice.stop step = the_slice.step or 1 #fill in missing values for start and end ...
bigcode/self-oss-instruct-sc2-concepts
import io import difflib def generate_or_check(manifest, args, path, func): """Generate/check a file with a single generator Return True if successful; False if a comparison failed. """ outfile = io.StringIO() func(manifest, args, outfile) generated = outfile.getvalue() existing = path.r...
bigcode/self-oss-instruct-sc2-concepts
def generate_df_subset(swc_df, vox_in_img_list): """Read a new subset of swc dataframe in coordinates in img spacing. Parameters ---------- swc_df : pd.DataFrame DataFrame containing information from swc file vox_in_img_list: list List of voxels Returns ------- df : :cl...
bigcode/self-oss-instruct-sc2-concepts
def get_capi_link_library_name() -> str: """Gets the library name of the CAPI shared library to link against.""" return "NPCOMPPythonCAPI"
bigcode/self-oss-instruct-sc2-concepts
import glob import re def _find_weights(ckpt_path, paths=None, start=0): """ ckpt_path should be format string containing '{epoch}' >>> paths = ['abc.01.ckpt', 'abc.05.ckpt', 'abc.best.ckpt'] >>> _find_weights('abc.{epoch}.ckpt', paths=paths) [(0, 'abc.01.ckpt'), (4, 'abc.05.ckpt') """ if pat...
bigcode/self-oss-instruct-sc2-concepts
import ast def is_literal(node: ast.AST) -> bool: """ Checks for nodes that contains only constants. If the node contains only literals it will be evaluated. When node relies on some other names, it won't be evaluated. """ try: ast.literal_eval(node) except ValueError: ret...
bigcode/self-oss-instruct-sc2-concepts
def _format_pep_number(pep_number): """ The PEP number as a 4-digit string. This is the format used by the URLs on python.org. """ return str(pep_number).rjust(4, '0')
bigcode/self-oss-instruct-sc2-concepts
import hashlib def md5sum(fpath): """Compute the md5sum hash of the content of a given file.""" blocksize = 65536 hash_md5 = hashlib.md5() with open(fpath, "rb") as f: for block in iter(lambda: f.read(blocksize), b""): hash_md5.update(block) return hash_md5.hexdigest()
bigcode/self-oss-instruct-sc2-concepts
def clean_list(lst): """ Returns a new but cleaned list. * None type values are removed * Empty string values are removed This function is designed so we only return useful data """ newlist = list(lst) for i in lst: if i is None: newlist.remove(i) if i == ""...
bigcode/self-oss-instruct-sc2-concepts
def compare_schemas(current: dict, old: dict) -> bool: """Returns true if schemas are functionally the same""" return current == old
bigcode/self-oss-instruct-sc2-concepts
def _get_data(title, func, dest): """Populate dest with data from the given function. Args: title: The name of the data func: The function which will return the data dest: a dict which will store the data Returns: dest: The modified destination dict """ # Get inter...
bigcode/self-oss-instruct-sc2-concepts
def _isRunMaskDuplicate(run, lumis, runLumis): """ Test whether run and lumi is a subset of one of the runLumi pairs in runLumis :param run: integer run number :param lumi: set of lumis :param runLumis: list of dictionaries containing run and lumis """ for runLumi in runLumis: if...
bigcode/self-oss-instruct-sc2-concepts
def fill_zeros(s,n): """ Add zeros to a string s until it reaches length n. """ while len(s) < n: s= ''.join(('0',s)) return s
bigcode/self-oss-instruct-sc2-concepts
from typing import Union import json def _parse_doc(doc: Union[str, dict]) -> dict: """Parse policy document if necessary. Args: doc: Policy document to parse. Returns: Parsed policy document. """ if isinstance(doc, (str, bytes)): return json.loads(doc) return doc
bigcode/self-oss-instruct-sc2-concepts
def reduceby(key, binop, seq, init): """ Perform a simultaneous groupby and reduction The computation: >>> result = reduceby(key, binop, seq, init) # doctest: +SKIP is equivalent to the following: >>> def reduction(group): # doctest: +SKIP ... return reduce...
bigcode/self-oss-instruct-sc2-concepts
def arrayRatio(numerator,denominator): """ Returns the average ratio of numerator to denominator. (e.g. Given numerator ['123','456'] and denominator ['222','333'], returns 1.043...) """ lennum = len(numerator) lenden = len(denominator) lenlower = min(lennum,lenden) #finds list with less v...
bigcode/self-oss-instruct-sc2-concepts
def bubble_sort(arr): """ Performs a bubble sort algorithm - Time complexity: O(n²) Args: arr (list): List to sort Returns: (list): Sorted list """ j = len(arr) - 1 while j >= 0: i = 0 while i < j: if arr[i] > arr[i+1]: te...
bigcode/self-oss-instruct-sc2-concepts
def undirected_edge_name(u, v) -> str: """ :return The name of an undirected edge as "(u,v)" with u <= v. """ u_i, v_i = int(u), int(v) if u_i > v_i: u_i, v_i = v_i, u_i return f"({u_i},{v_i})"
bigcode/self-oss-instruct-sc2-concepts
def needed_to_tuple(var_full, needed): """Extract only needed variables to a new tuple.""" return tuple(var for var, n in zip(var_full, needed) if n)
bigcode/self-oss-instruct-sc2-concepts
from typing import List def hex_to_rgb(value: str) -> List[float]: """Converts hex to normalized rgb colours Args: value (str): string of 6 characters representing a hex colour Returns: list[float]: rgb color list """ value = value.strip("#") lv = len(value) rgb_vals = tu...
bigcode/self-oss-instruct-sc2-concepts
def _compute_colocation_summary_from_dict(name, colocation_dict, prefix=""): """Return a summary of an op's colocation stack. Args: name: The op name. colocation_dict: The op._colocation_dict. prefix: An optional string prefix used before each line of the multi- line string returned by this fu...
bigcode/self-oss-instruct-sc2-concepts
import json def printjson(toprint, exception_conversions={}): """print anything in json format. Can override printing for custom types using a dictionary of types to lambda conversion functions. Examples: printjson(data) printjson(data,{sp.DenseSparseMatrix: lambda x: f"matrix = {x}" }) ...
bigcode/self-oss-instruct-sc2-concepts
def iteritems(obj, **kwargs): """Iterate over dict items in Python 2 & 3.""" return (obj.iteritems(**kwargs) if hasattr(obj, 'iteritems') else iter(obj.items(**kwargs)))
bigcode/self-oss-instruct-sc2-concepts
def calculate_handlen(hand): """ Returns the length (number of letters) in the current hand. hand: dictionary (string-> int) returns: integer """ return sum(hand.values())
bigcode/self-oss-instruct-sc2-concepts
def generate_bond_indices(natoms): """ natoms: int The number of atoms Finds the array of bond indices of the upper triangle of an interatomic distance matrix, in column wise order ( or equivalently, lower triangle of interatomic distance matrix in row wise order): [[0,1], [0,2], [1,2], [0,3...
bigcode/self-oss-instruct-sc2-concepts
from pathlib import Path def to_condition(p: Path, ind: int = -1, sep: str = "_") -> list: """ converts path into a row for condition dataframe it assumes that the names of the files have pars separated by "_" or other separator :param p path to the file :param ind where in a splited file name to ...
bigcode/self-oss-instruct-sc2-concepts
from typing import Dict def _get_labels_dict(label_str: str) -> Dict[str, str]: """ Converts CLI input labels string to dictionary format if provided string is valid. Args: label_str: A comma-separated string of key-value pairs Returns: Dict of key-value label pairs """ label...
bigcode/self-oss-instruct-sc2-concepts
def make_query_to_get_users_profiles(userIds): """Returns a query to retrieve the profile for the indicated list of user ids Api info: parameter name: user_id values: A comma separated list of user IDs, up to 100 are allowed in a single request. Notes: You are strongly encouraged to ...
bigcode/self-oss-instruct-sc2-concepts
import json def mocked_requests_get(*args, **kwargs): """Defines a response suitable for mocking requests responses.""" class MockResponse: """Solution cribbed from https://stackoverflow.com/questions/15753390/how-can-i-mock-requests-and-the-response/28507806#28507806 """ def _...
bigcode/self-oss-instruct-sc2-concepts
def getManifestEtag(manifest): """ returns Etag hash for manifest""" return manifest["Etag"]
bigcode/self-oss-instruct-sc2-concepts
from pathlib import Path def get_new_files(commit, dir): """Return new files in commit that are in dir directory""" files = [] for file in commit.files: if Path(dir) in Path(file.filename).parents and file.status == "added": files.append(file) return files
bigcode/self-oss-instruct-sc2-concepts
import math def _datetime_to_timestamp(dt, period, round_up=False): """ Convert a datetime object to a timestamp measured in simulation periods. Args: dt (datetime): Datetime to be converted to a simulation timestamp. period (int): Length of one time interval in the simulation. (minutes) ...
bigcode/self-oss-instruct-sc2-concepts
def list_hasnext(xs): """Whether the list is empty or not.""" return len(xs) > 0
bigcode/self-oss-instruct-sc2-concepts
def rescale(src_scale, dest_scale, x): """Map one number scale to another For example, to convert a score of 4 stars out of 5 into a percentage: >>> rescale((0, 5), (0, 100), 4) 80.0 Great for mapping different input values into LED pixel brightnesses! """ src_start, src_end = src_scale ...
bigcode/self-oss-instruct-sc2-concepts
import six def downgrader(version): """ A decorator for marking a method as a downgrader to an older version of a given object. Note that downgrader methods are implicitly class methods. Also note that downgraders take a single argument--a dictionary of attributes--and must return a dictiona...
bigcode/self-oss-instruct-sc2-concepts
from typing import Union from pathlib import Path def is_notebook(file: Union[Path, str]) -> bool: """Determines whether a file is a notebook file or not. Args: file: the file, as either a pathlib.Path object or a filename string. Returns: True if notebook file, else False. """ i...
bigcode/self-oss-instruct-sc2-concepts
def extract_major_version(scala_version): """Return major Scala version given a full version, e.g. "2.11.11" -> "2.11" """ return scala_version[:scala_version.find(".", 2)]
bigcode/self-oss-instruct-sc2-concepts
def sanitize(message: str) -> str: """ Removes backticks (code tag) and linebreaks from a message. """ return message.replace('`', '').replace('\n', '')
bigcode/self-oss-instruct-sc2-concepts
def distLinf(x1, y1, x2, y2): """Compute the Linfty distance between two points (see TSPLIB documentation)""" return int(max(abs(x2 - x1), abs(y2 - y1)))
bigcode/self-oss-instruct-sc2-concepts
import re def is_special_character(string, i, pattern): """ Returns True if the i-th character in the given string is a special character, False otherwise. The character is *not* a special character if it is a dot and it is surrounded by two digits, like in "1.23". >>> is_special_character(["a", ...
bigcode/self-oss-instruct-sc2-concepts
def calcArea(vertexes): """ :param vertexes: :return Float: Area of the polygon, Positive value means clockwise direction, negative counter-clockwise. >>> calcArea([Point(0, 0), Point(0, 1), Point(1, 1), Point(1, 0)]) -1.0 >>> calcArea([Point(0, 0), Point(1, 0), Point(1, 1), Point(0, 1)]) ...
bigcode/self-oss-instruct-sc2-concepts
def bayesdb_colno_to_variable_names(bdb, population_id, generator_id): """Return a dictionary that maps column number to variable name in population.""" cursor = bdb.sql_execute(''' SELECT colno, name FROM bayesdb_variable WHERE population_id = ? AND (generator_id IS NULL OR ...
bigcode/self-oss-instruct-sc2-concepts
import fnmatch def _fnmatch_lower(name: str | None, pattern: str) -> bool: """Match a lowercase version of the name.""" if name is None: return False return fnmatch.fnmatch(name.lower(), pattern)
bigcode/self-oss-instruct-sc2-concepts
def denormalize_loc(locations, img_height, img_width): """convert locations from normalized co-ordinates in range [0,1] back into pixel co-ordinates Parameters ---------- locations : numpy.ndarray with two columns (y, x) (not (x, y), because of how array indexing works) img_height : int ...
bigcode/self-oss-instruct-sc2-concepts
def _string_id(*args): """Creates an id for a generic entity, by concatenating the given args with dots. Parameters ---------- *args: str The strings to concatenate Returns ------- basestring: an identifier to be used. """ def is_valid(entry): return ( ...
bigcode/self-oss-instruct-sc2-concepts
def only_printable(string): """ Converts to a string and removes any non-printable characters""" string = str(string) return "".join([s for s in string if s.isprintable()])
bigcode/self-oss-instruct-sc2-concepts
def name_class(classname): """Change AMQP class name to Python class name""" return classname.capitalize()
bigcode/self-oss-instruct-sc2-concepts
def calculateFrameTime(speed, ratio): """ Calculates the frame time interval from chopper parameters. Chopper speed in rpm given, but calculations are in Hz. The interval is the time between pulses of chopper 5 because chopper 5 has only 2 slits returns the frame time in s """ speed /=...
bigcode/self-oss-instruct-sc2-concepts
def normalize_order_number(order_number: str) -> int: """ Normalizes Sierra order number """ return int(order_number[2:-1])
bigcode/self-oss-instruct-sc2-concepts
def compose_j(n, Nvec): """ Eq. 4 in Poly Fits Derivation. Routine to compose the j counter from the n values. Can also be used as Eq. 10 with the i counter and the nhat values. inputs: n = list of integer values representing the independent variables' exponents for the...
bigcode/self-oss-instruct-sc2-concepts
from typing import TextIO def open_read_text(filepath: str) -> TextIO: """Open a text file for reading and return a file object.""" return open(filepath, mode="r", encoding="utf-8")
bigcode/self-oss-instruct-sc2-concepts
import inspect def get_default_hook(obj, default_hooks): """Finds the default save/load hook to use with the given object. Follows the Method Resolution Order, i.e., if no hook is registered for the class of the object itself, also searches classes which the object inherits from. Arguments -...
bigcode/self-oss-instruct-sc2-concepts
def resources_to_layout(resources): """Given a `list` of resource object [a,b,c], extract the frame and join them like [[a.frame], [b.frame], [c.frame]]""" res = [] for a in resources: res.append([a.frame]) return res
bigcode/self-oss-instruct-sc2-concepts
def solution(n: int = 10) -> str: """ Returns the last n digits of NUMBER. >>> solution() '8739992577' >>> solution(8) '39992577' >>> solution(1) '7' >>> solution(-1) Traceback (most recent call last): ... ValueError: Invalid input >>> solution(8.3) Traceback ...
bigcode/self-oss-instruct-sc2-concepts
def _get_file_type(fname): """Return the type of a file.""" if fname.endswith('.nii.gz') or fname.endswith('.nii'): return 'NIfTI-1' if fname.endswith('.png'): return 'PNG' if fname.endswith('.jpg'): return 'JPEG' if fname.endswith('.mnc'): return 'MINC' if fname....
bigcode/self-oss-instruct-sc2-concepts
def locale_to_source_path(path): """ Return source resource path for the given locale resource path. Source files for .po files are actually .pot. """ # Comment this for now as js-lingui does not provide .pot files, only .po # Commenting these lines is enough to make it work # if path.endswi...
bigcode/self-oss-instruct-sc2-concepts
from typing import OrderedDict def _translate_reverse_relationships(opts, reverse_relations): """ DRF's `_get_reverse_relationships` uses the `get_accessor_name` method of `ForeignObjectRel` as the key for the relationship. This function replaces those keys with the rel's `name` property. This allows ...
bigcode/self-oss-instruct-sc2-concepts
def display_title(book): """Compute the display title of a book.""" out = book["title"] if book.get("subtitle"): out += f": {book['subtitle']}" if book.get("volume_number") and book.get("fascicle_number"): out += f" (vol. {book['volume_number']['raw']}; fas. {book['fascicle_number']['ra...
bigcode/self-oss-instruct-sc2-concepts
def int_to_str_v2(n: int) -> str: """Convert the given integer into it's string form. Args: n: The integer whose string form to be gotten. Returns: The string form of the given integer. """ if n == 0: return '0' sign, n = ('-', -n) if n < 0 else ('', n) s = [] while n...
bigcode/self-oss-instruct-sc2-concepts
import inspect import re def strip_source_code(method, remove_nested_functions=True): """ Strips the source code of a method by everything that's "not important", like comments. Args: method (Union[callable,str]): The method to strip the source code for (or the source code directly as string). ...
bigcode/self-oss-instruct-sc2-concepts
def hadamard_complex(x_re, x_im, y_re, y_im): """Hadamard product for complex vectors""" result_re = x_re * y_re - x_im * y_im result_im = x_re * y_im + x_im * y_re return result_re, result_im
bigcode/self-oss-instruct-sc2-concepts
def validate_category_or_command_name(name): """ Validates the given category name. Parameters ---------- name : `str` The name of a category or command. Returns ------- name : `str` The validated name. Raises ------ TypeError If `name` ...
bigcode/self-oss-instruct-sc2-concepts
def query_transform(request, **kwargs): """ Merges the existing query params with any new ones passed as kwargs. Note that we cannot simply use request.GET.update() as that merges lists rather than replacing the value entirely. """ updated_query_params = request.GET.copy() for key, value ...
bigcode/self-oss-instruct-sc2-concepts
def get_all_properties(data, **kws): """Get all property definitions from PV data. Parameters ---------- data : list(dict) List of dict, each dict element is of the format: ``{'name': PV name (str), 'owner': str, 'properties': PV properties (list[dict]), 'tags': PV tags (list[dict])}``....
bigcode/self-oss-instruct-sc2-concepts
def mapfmt(fmt: bytes, size: int) -> bytes: """ Changes the type of of a format string from 32-bit to 64-bit. WARNING: doesn't handle strings. Example ------- >>> mapfmt(b'2i 6f') b'2q 6d' """ if size == 4: return fmt return fmt.replace(b'i', b'q').replace(b'f', b'd')
bigcode/self-oss-instruct-sc2-concepts
def get_library_interface_type_name(config): """Get the LibraryInterface type name, based on the service_class_prefix config setting.""" service_class_prefix = config["service_class_prefix"] return f"{service_class_prefix}LibraryInterface"
bigcode/self-oss-instruct-sc2-concepts
import time def parse_sfx_now(input_time: str) -> int: """Parse Signalfx Now into SignalFx API epoch milliseconds :raise: ValueError """ if input_time == "Now": return int(time.time()) * 1000 raise ValueError(f"{input_time} is not Now")
bigcode/self-oss-instruct-sc2-concepts
def readlines(path): """Read a file into a list of lines.""" with open(path) as f: return f.readlines()
bigcode/self-oss-instruct-sc2-concepts
def Vcell_Calc(Enernst, Loss): """ Calculate cell voltage. :param Enernst: Enernst [V} :type Enernst : float :param Loss: loss [V] :type Loss : float :return: cell voltage [V] as float """ try: result = Enernst - Loss return result except TypeError: pr...
bigcode/self-oss-instruct-sc2-concepts
def remove_bots(members): """Removes bots from a list of members""" bots = [] for member in members: if member.bot: bots.append(member) for bot in bots: members.remove(bot) return members
bigcode/self-oss-instruct-sc2-concepts
def to_flags(value): """Return a (flags, ednsflags) tuple which encodes the rcode. *value*, an ``int``, the rcode. Raises ``ValueError`` if rcode is < 0 or > 4095. Returns an ``(int, int)`` tuple. """ if value < 0 or value > 4095: raise ValueError('rcode must be >= 0 and <= 4095') ...
bigcode/self-oss-instruct-sc2-concepts
import pickle def read_as_pickle(path: str): """Read in pickle file.""" with open(f'{path}.pickle', 'rb') as handle: return pickle.load(handle)
bigcode/self-oss-instruct-sc2-concepts
def is_callID_active(callID): """Check if reactor.callLater() from callID is active.""" if callID is None: return False elif ((callID.called == 0) and (callID.cancelled == 0)): return True else: return False
bigcode/self-oss-instruct-sc2-concepts
def build_property_spec(client_factory, type='VirtualMachine', properties_to_collect=None, all_properties=False): """Builds the Property Spec. :param client_factory: Factory to get API input specs :param type: Type of the managed object reference property ...
bigcode/self-oss-instruct-sc2-concepts
def _clean_message(message): """ Cleans a message by removing the 0 bytes from the input message. :param message: The message to be cleaned. :return: str: The cleaned message. """ return message.split('\x00')[0]
bigcode/self-oss-instruct-sc2-concepts
import yaml def get_time_limit(cwl_content: bytes) -> int: """Takes a CWL file contents and extracts cwl1.1-dev1 time limit. Supports only two of three possible ways of writing this. Returns 0 if no value was specified, in which case the default should be used. Args: cwl_content: The con...
bigcode/self-oss-instruct-sc2-concepts
import struct def get_dump_pos(log_file, log_pos, server_id): """ https://dev.mysql.com/doc/internals/en/com-binlog-dump.html 1 [12] COM_BINLOG_DUMP 4 binlog-pos 2 flags 4 server-id string[EOF] binlog-filename """ COM_BINLOG_DU...
bigcode/self-oss-instruct-sc2-concepts
def _check_no_collapsed_axes(fig): """ Check that no axes have collapsed to zero size. """ for panel in fig.subfigs: ok = _check_no_collapsed_axes(panel) if not ok: return False for ax in fig.axes: if hasattr(ax, 'get_subplotspec'): gs = ax.get_subplo...
bigcode/self-oss-instruct-sc2-concepts
import warnings def filtfilt(signal, synapse, dt, axis=0, x0=None, copy=True): """Zero-phase filtering of ``signal`` using the ``synapse`` filter. .. note:: Deprecated in Nengo 2.1.0. Use `.Synapse.filtfilt` method instead. """ warnings.warn("Use ``synapse.filtfilt`` instead", Deprecati...
bigcode/self-oss-instruct-sc2-concepts
from typing import Dict from typing import AnyStr import json def _decode_json_dict(json_dict: Dict[bytes, AnyStr]) -> dict: """ Decode a dict coming from hgetall/hmget, which is encoded with bytes as keys and bytes or str as values, containing JSON values. """ return {k.decode(): json.loads(v) fo...
bigcode/self-oss-instruct-sc2-concepts
import logging def get_instance_group_manager_to_delete(key): """Returns the URL of the instance group manager to delete. Args: key: ndb.Key for a models.InstanceGroupManager entity. Returns: The URL of the instance group manager to delete, or None if there isn't one. """ instance_group_manager = ...
bigcode/self-oss-instruct-sc2-concepts
def _unpack_tensors(reduced, tensor_packer=None): """Unpack tensors if they are packed before all-reduce.""" if tensor_packer: return tensor_packer.unpack(reduced) return reduced
bigcode/self-oss-instruct-sc2-concepts
def instance_to_class(instance, parent): """ Return the name of the class for an instance of inheritance type parent """ return parent + "_" + instance
bigcode/self-oss-instruct-sc2-concepts
def rayleigh_range(w0, k): """ Computes the rayleigh range, which is the distance along the propagation direction of a beam from the waist to the place where the area of cross section is doubled. Args: w0: waist radius of beam k: wave number in the direction of propagation of beam ...
bigcode/self-oss-instruct-sc2-concepts
from pathlib import Path def _check_inputs(filepath, order, compact, flatten): """ This function checks the input arguments to compute() for validity based on descriptions below. Parameters ---------- filepath : Path object Valid path to file containing nucleotide sequence. order ...
bigcode/self-oss-instruct-sc2-concepts
import re def charset_from_headers(headers): """Parse charset from headers. :param httplib2.Response headers: Request headers :return: Defined encoding, or default to ASCII """ match = re.search("charset=([^ ;]+)", headers.get('content-type', "")) if match: charset = match.groups()[0...
bigcode/self-oss-instruct-sc2-concepts
def parse_reqs(file_path): """Parse requirements from file.""" with open(file_path, 'rt') as fobj: lines = map(str.strip, fobj) lines = filter(None, lines) lines = filter(lambda x: not x.startswith("#"), lines) return tuple(lines)
bigcode/self-oss-instruct-sc2-concepts
def calculate_position_part2(infile_path: str) -> int: """ Read input, determine vertical and horizontal position and return the product of the values :param infile_path: file path to input file with instructions separated by newlines :type infile_path: str :return: product of the vertical and horiz...
bigcode/self-oss-instruct-sc2-concepts
def _estimate_geohash_precision(r: int): """ Returns hueristic geohash length for the given radius in meters. :param r: radius in meters """ precision = 0 if r > 1000000: precision = 1 elif r > 250000: precision = 2 elif r > 50000: precision = 3 elif r > 1000...
bigcode/self-oss-instruct-sc2-concepts
def merge_dicts(dict_a, dict_b): """Performs a recursive merge of two dicts dict_a and dict_b, wheras dict_b always overwrites the values of dict_a :param dict_a: the first dictionary. This is the weak dictionary which will always be overwritten by dict_b (dict_a therefore is a default dicti...
bigcode/self-oss-instruct-sc2-concepts
def ensure_list(val): """Converts the argument to a list, wrapping in [] if needed""" return val if isinstance(val, list) else [val]
bigcode/self-oss-instruct-sc2-concepts
def hideCells(notebook): """ Finds the tag 'hide' in each cell and removes it Returns dict without 'hide' tagged cells """ clean = [] for cell in notebook['cells']: try: if 'hide' in cell['metadata']['tags']: pass else: clean.appen...
bigcode/self-oss-instruct-sc2-concepts
from pathlib import Path def parse_pb_name_data(file_name): """Returns data encoded in extraction files, such as datetime or itp id. >>> parse_pb_name_data("2021-01-01__1__0__filename__etc") {'extraction_date': '2021-01-01', 'itp_id': 1, 'url_number': 0, 'src_fname': 'filename'} """ extraction_...
bigcode/self-oss-instruct-sc2-concepts
def _apply_to_sample(func, sample, *args, nest_with_sample=0): """Apply to a sample traversing the nesting of the data (tuple/list). Parameters ---------- func : callable Function to be applied to every sample data object sample : sample object or any nesting of those in tuple/list ...
bigcode/self-oss-instruct-sc2-concepts
def camelcase(s: str) -> str: """Convert snake case to camel case. Example: >>> camelcase("camel_case") 'camelCase' """ parts = iter(s.split("_")) return next(parts) + "".join(i.title() for i in parts)
bigcode/self-oss-instruct-sc2-concepts
def link_regulator(incoming_links: list) -> list: """ Regulates the links coming from Google Search. Input URL: "/url?q=https://www.example.com/SparqlEndpoint&sa=U&ved=2ahUKEwiU" Output URL: "https://www.example.com/SparqlEndpoint" :param incoming_links: List of links to be regulated :return:...
bigcode/self-oss-instruct-sc2-concepts