seed
stringlengths
1
14k
source
stringclasses
2 values
def get_attr_resolver(obj_type, model_attr): """ In order to support field renaming via `ORMField.model_attr`, we need to define resolver functions for each field. :param SQLAlchemyObjectType obj_type: :param str model_attr: the name of the SQLAlchemy attribute :rtype: Callable """ retu...
bigcode/self-oss-instruct-sc2-concepts
def openFile(file_path): """Open file in read mode, return file contents""" md_file = open(file_path, 'r') file_contents = md_file.read() md_file.close() return file_contents
bigcode/self-oss-instruct-sc2-concepts
def textarea_to_list(textarea): """ Takes a string and returns list of lines, skipping blank lines """ list_ = textarea.splitlines() return [x.strip() for x in list_ if x.strip() != '']
bigcode/self-oss-instruct-sc2-concepts
def _get_tensors_from_graph(graph, tensors): """Gets the Tensors in `graph` with the name of the tensors in `tensors`. Args: graph: TensorFlow Graph. tensors: List of Tensors. Returns: List of Tensors. """ new_tensors = [] for orig_tensor in tensors: new_tensor = graph.get_tensor_by_name(o...
bigcode/self-oss-instruct-sc2-concepts
def ratioTest(kps1, kps2, matches): """ Take in two sets of keypoints and the set of matches between them Perform ratio test to get best matches (60% threshold) Return surviving matches """ ratioMatches = list() for match in matches: m1, m2 = match if m1.distance < 0.60*m2.di...
bigcode/self-oss-instruct-sc2-concepts
def cel2kel(t): """Converts from Celsius to Kelvin""" return t + 274.2
bigcode/self-oss-instruct-sc2-concepts
import itertools def combinate(listoffiles, combnum): """ Makes a list of tuples with the N choose combnum options Parameters ---------- listoffiles: list list of file names combnum: int combination number (N choose combnum) Returns ------- combinedlist: list ...
bigcode/self-oss-instruct-sc2-concepts
def search(seq, val): """Search location of key in a sorted list. The method searches the location of a value in a list using binary searching algorithm. If it does not find the value, it return -1. Args: seq: A sorted list where to search the value. val: A value to search for. Re...
bigcode/self-oss-instruct-sc2-concepts
def generate_command_argument(hlwm, command, argument_prefix, steps): """ generate the next argument of the command which has the given argument_prefix. This function makes at most 'step' many recursive calls. It returns a list of full arguments starting with the argument_prefix. """ if st...
bigcode/self-oss-instruct-sc2-concepts
def preprocess_prediction_data(text, tokenizer): """ It process the prediction data as the format used as training. Args: text (obj:`str`): The input text. tokenizer(obj: `paddlenlp.data.JiebaTokenizer`): It use jieba to cut the chinese string. Returns: input_ids (obj: `list[in...
bigcode/self-oss-instruct-sc2-concepts
def df_to_records(df): """ Convert pandas DataFrame to table compatible data aka records. If DataFrame is empty keep the columns. :type df: pandas.DataFrame :rtype: list[dict] """ if df.empty: # Return column names in 'records' style. return [{c: None for c in df.columns}] r...
bigcode/self-oss-instruct-sc2-concepts
from datetime import datetime def is_datetime(value): """Checks, if given value is a datetime. :param value: The value to check. :type value: object :returns: True, if value is a datetime (and not a date), false otherwise. :rtype: Boolean >>> from plone.event.utils import is_datetime >>>...
bigcode/self-oss-instruct-sc2-concepts
def find_furthest_room(distances): """Find furthest room from the distances grid.""" return max(max(row) for row in distances)
bigcode/self-oss-instruct-sc2-concepts
import json def pretty_json(data): """Return a pretty formatted json """ data = json.loads(data.decode('utf-8')) return json.dumps(data, indent=4, sort_keys=True)
bigcode/self-oss-instruct-sc2-concepts
import random import string def _generate_password(length=16): """ Generate password of specified length with at least one digit, uppercase letter, and lowercase letter. This is used as the IKEv2 PSK on both sides of the tunnel. """ # Need 1 each: uppercase, lowercase, digit pw_minimum = ...
bigcode/self-oss-instruct-sc2-concepts
def mipmap_size(base_width, base_height, mip_level): """Return mipmap width and height Args: base_width (int): Width of the base image (mip level 0) base_height (int): Height of the base image (mip level 0) mip_level (int): Level of mip to get Returns: tuple(mip_width, mip_...
bigcode/self-oss-instruct-sc2-concepts
def get_examples(section_div, examples_class): """Parse and return the examples of the documentation topic. Parameters ---------- section_div : bs4.BeautifulSoup The BeautifulSoup object corresponding to the div with the "class" attribute equal to "section" in the html doc file. ex...
bigcode/self-oss-instruct-sc2-concepts
def is_hla(chrom): """ check if a chromosome is an HLA """ return chrom.startswith("HLA")
bigcode/self-oss-instruct-sc2-concepts
def _QuoteCpuidField(data): """Add quotes around the CPUID field only if necessary. Xen CPUID fields come in two shapes: LIBXL strings, which need quotes around them, and lists of XEND strings, which don't. @param data: Either type of parameter. @return: The quoted version thereof. """ return "'%s'" % ...
bigcode/self-oss-instruct-sc2-concepts
def swap(x, i, j): """ swap bits i and j of x. """ mask = (1<<i) | (1<<j) m = x&mask if m == 0 or m == mask: return x return x^mask
bigcode/self-oss-instruct-sc2-concepts
def has_shebang_or_is_elf(full_path): """Returns if the file starts with #!/ or is an ELF binary. full_path is the absolute path to the file. """ with open(full_path, 'rb') as f: data = f.read(4) return (data[:3] == '#!/' or data == '#! /', data == '\x7fELF')
bigcode/self-oss-instruct-sc2-concepts
def orientation(a, b, c): """Compute the orientation of c relative to the line AB.""" M = [[a[0] - c[0], a[1] - c[1]], [b[0] - c[0], b[1] - c[1]]] # Return det(M) return M[0][0] * M[1][1] - M[0][1] * M[1][0]
bigcode/self-oss-instruct-sc2-concepts
def F(agents, images_in): """The stacked agent map. Takes a list of agents and a list of images and applies each agent to the corresponding image. Args: agents: List of agents images_in: List of input images Returns: List of output images after applying the agents """ ...
bigcode/self-oss-instruct-sc2-concepts
def to_unicode(obj): """ Converts any string values into unicode equivalents. This is necessary to allow comparisons between local non-unicode strings and the unicode values returned by the api. :param obj: a string to be converted to unicode, or otherwise a dict, list, set which will be recursi...
bigcode/self-oss-instruct-sc2-concepts
from pathlib import Path def check_paths(vtk_src_dir, application_srcs): """ Check that the paths are valid. :param vtk_src_dir: The path to the VTK source. :param application_srcs: The user source files to be scanned for modules. :return: True if paths, files exist. """ ok = True if ...
bigcode/self-oss-instruct-sc2-concepts
import time import asyncio async def wait_host_port(host, port, duration=10, delay=2): """Repeatedly try if a port on a host is open until duration seconds passed from: https://gist.github.com/betrcode/0248f0fda894013382d7#gistcomment-3161499 :param str host: host ip address or hostname :param int p...
bigcode/self-oss-instruct-sc2-concepts
def haspropriety(obj, name): """Check if propriety `name` was defined in obj.""" attr = getattr(obj, name, None) return attr and not callable(attr)
bigcode/self-oss-instruct-sc2-concepts
def match_factory(variable, factories): """Match variable to VariableFactory using rank, name, and units. Args: variable (Variable): Variable to match. factories (VariableFactory or tuple of VariableFactory): VariableFactory to check against. Returns: bool: True if a ma...
bigcode/self-oss-instruct-sc2-concepts
def insertion_sort(array): """ Sort array in ascending order by insertion sort Insertion sort iterates, consuming one input element each repetition, and growing a sorted output list. At each iteration, insertion sort removes one element from the input data, finds the location it belongs within ...
bigcode/self-oss-instruct-sc2-concepts
import torch def validation_loop(model, testloader, criterion): """ Returns test loss and accuracy score of a given torch model. NOTE: divide outputs with the total number of epochs to get the final values. Parameters: model (nn.Module): A torch model ...
bigcode/self-oss-instruct-sc2-concepts
def join_sentences_by_label(grouped_sentences_df, label_col="topic_name", sentence_col="sentence"): """ Function used to join sentences into texts. Sentences are grouped by topics --- **Arguments**\n `grouped_sentences_df` (DataFrame): DataFrame with sentences groped by topics and which contains ...
bigcode/self-oss-instruct-sc2-concepts
def rotate_image(image): """ Rotate an image according to it's EXIF info. """ try: orientation_tag = 274 # 0x0112 exif=dict(image._getexif().items()) if exif[orientation_tag] == 3: image = image.rotate(180, expand=True) elif exif[orientation_tag] == 6: im...
bigcode/self-oss-instruct-sc2-concepts
def replace_token(token, token_replacement, value): """ Replace `token` with `token_replacement` in `value` :param: token: string e.g. : | . :param: token_replacement: string e.g. _ - :param: value: dictionary, list, or str """ if isinstance(value, str): return value.replace(token, ...
bigcode/self-oss-instruct-sc2-concepts
def svm_model(r3d_kpc, n0, r_c, beta, r_s=1.0, gamma=3.0, epsilon=0.0, alpha=0.0): """ Compute a Simplified Vikhlinin model Parameters ---------- - r3d_kpc: array of radius in kpc - r_c : core radius parameter - n_0 : normalization - beta : slope of the profile - r_s : characteris...
bigcode/self-oss-instruct-sc2-concepts
def is_ea(email: str) -> bool: """ Email domain name is "empacad.org" """ eml_domain = email.split('@')[1] if eml_domain == 'empacad.org': return True return False
bigcode/self-oss-instruct-sc2-concepts
def test_acc_formatter(test_acc: float) -> str: """Wrap given test accuracy in a nice text message.""" return f"Test Accuracy: {test_acc}"
bigcode/self-oss-instruct-sc2-concepts
import requests def post_input_form(input_text): """Posts a string as a form field (application/x-www-form-urlencoded) named 'input' to the REST API and returns the response. """ url = 'http://localhost:5000/parse' return requests.post(url, data={'input': input_text})
bigcode/self-oss-instruct-sc2-concepts
def exercise2(n): """ Write a recursive Python function that returns the sum of the first n integers. """ if n > 0: return n + exercise2(n - 1) else: return 0
bigcode/self-oss-instruct-sc2-concepts
def date_parser(dates): """Return list strings in truncated DateTime format ('yyyy-mm-dd'). Args: dates (list): A list containing string values, each value in the (DateTime) format 'yyyy-mm-dd hh:mm:ss'. Return: Example: Input: date_parser(['2019-11-29 12:50:54',...
bigcode/self-oss-instruct-sc2-concepts
def fallback(*candidates): """ :param candidates: :return: First argument which is not None """ for i in candidates: if i is not None: return i
bigcode/self-oss-instruct-sc2-concepts
def _module_dir(lock_filename): """Returns module dir from a full 'lock_filename' path. Args: lock_filename: Name of the lock file, ends with .lock. Raises: ValueError: if lock_filename is ill specified. """ if not lock_filename.endswith(".lock"): raise ValueError( "Lock file name (%s) h...
bigcode/self-oss-instruct-sc2-concepts
def construct_link_dossierbehandelaar_query(graph_uri, bericht): """ Construct a SPARQL query for linking a dossierbehandelaar to a bericht. :param graph_uri: string :param bericht: dict containing properties for bericht :returns: string containing SPARQL query """ q = """ PREFIX e...
bigcode/self-oss-instruct-sc2-concepts
def summer_clearsky(summer_times, albuquerque): """Clearsky irradiance for `sumer_times` in Albuquerque, NM.""" return albuquerque.get_clearsky(summer_times, model='simplified_solis')
bigcode/self-oss-instruct-sc2-concepts
from typing import Dict from typing import Any def build_validation(validator) -> Dict[str, Any]: """Builds and returns a fake validator response object.""" if validator == "lookml": return { "validator": "lookml", "status": "failed", "errors": [ { ...
bigcode/self-oss-instruct-sc2-concepts
def quoteStr(s, addQuotes=False, quoteDouble=False, quoteSingle=True): """ s (str) -- Source string parameter. Options: - addQuotes (bool|str) -- Add quotes around result string (default: False, don't quote). - quoteSingle (bool) -- Quote single quotes ('), default is True. - quoteDouble (bool) ...
bigcode/self-oss-instruct-sc2-concepts
import shlex def parse_bed_track(line): """Parse the "name" field of a BED track definition line. Example: track name=146793_BastianLabv2_P2_target_region description="146793_BastianLabv2_P2_target_region" """ fields = shlex.split(line) # raises ValueError if line is corrupted assert fields[...
bigcode/self-oss-instruct-sc2-concepts
from typing import List def parameter_order(config) -> List[str]: """ Return the order in which the parameters occur in the given dockerfile. This is needed for optimising the order in which the images are built. """ order = list() for line in config.dockerfile: order += [ ...
bigcode/self-oss-instruct-sc2-concepts
import json def read_config(filepath): """ Read the config from a given config file. :param filepath: The path to the config file. :type filepath: str :return: The json deserialized list. :rtype: list """ file = open(filepath, 'r') file_content = file.read() config_list = json...
bigcode/self-oss-instruct-sc2-concepts
def sample_proxs(z, y, step=1): """ computes prox_(step * f)(z) where f(z) = 0.5 * (z - y) ** 2 """ return (z + step * y) / (1 + step)
bigcode/self-oss-instruct-sc2-concepts
def to_dictionary(words): """ Helper function to convert list of words into a dictionary. """ return dict([(word, True) for word in words])
bigcode/self-oss-instruct-sc2-concepts
def get_info_link(content, html=False): """Return info popover link icon""" return ( '<a class="sodar-info-link" tabindex="0" data-toggle="popover" ' 'data-trigger="focus" data-placement="top" data-content="{}" {}>' '<i class="iconify text-info" data-icon="mdi:information"></i>' ...
bigcode/self-oss-instruct-sc2-concepts
def python_format(a, prec, align=''): """Format an array into standard form and return as a string. args: a: the array prec: the precision to output the array to align: anything that can go before the . in python formatting """ format_ = (f' {{:{align}.{prec}E}}' * a.shape[1] + ...
bigcode/self-oss-instruct-sc2-concepts
import re def is_image_set_grouped(pipeline): """ Report if the pipeline will group image sets. Returns **True** if image sets will be grouped. * pipeline: a list where each item is a line from a CellProfiler `*.cppipe` file. """ is_grouped_bool = False for line in pipeline: ...
bigcode/self-oss-instruct-sc2-concepts
import struct def read_uint32(buffer: bytearray) -> int: """ Read an unsigned 32-bit integer, read bytes are consumed. """ res, = struct.unpack('<I', buffer[:4]) del buffer[:4] return res
bigcode/self-oss-instruct-sc2-concepts
import math def atan2(x, y): """Get the arc tangent of x, an angle in radians. The signs of x and y are used to determine what quadrant the angle is in. The range of result values is [-π, π] """ return math.atan2(x, y)
bigcode/self-oss-instruct-sc2-concepts
def get_segment_times(csv_df, breaks=None, no_energy=False, music=False, noise=False): """ Filter an InaSeg output CSV of segmented time ranges. The parameters `no_energy`, `music`, and `noise` are optional bools which filter for the "noEnergy", "music", "noise" labels in segmented time ranges. The...
bigcode/self-oss-instruct-sc2-concepts
from datetime import datetime def is_current(record,year): """ Utility function to check whether a record is valid for the current year. Since records contain different information about dates, as appropriate, there are multiple conditions that must be tested. a) if a record contains only a YEAR,...
bigcode/self-oss-instruct-sc2-concepts
def apply_formatter(formatter, *args, **kwargs): """ Used by QAbstractModel data method Configures a formatter for one field, apply the formatter with the new index data :param formatter: formatter. If can be None/dict/callback or just any type of value :param args: :param kwargs: :return: ...
bigcode/self-oss-instruct-sc2-concepts
from typing import List def readable_list(seq: List[str]) -> str: """ Return a grammatically correct human readable string (with an Oxford comma). All values will be quoted: [foo, bar, baz] becomes "foo," "bar," and "baz" """ # Ref: https://stackoverflow.com/a/53981...
bigcode/self-oss-instruct-sc2-concepts
import re def _grep_prop(filename, prop_name): """ Look for property in file :param filename: path to file and file name. :param prop_name: property to search for in file. :return: property value or None. """ fdata = open(filename, "r").read() obj = re.search("^{0} = ['|\"](.+)['|\"]$"...
bigcode/self-oss-instruct-sc2-concepts
def q_zero(bits=8): """ The quantized level of the 0.0 value. """ return 1 << (bits - 1)
bigcode/self-oss-instruct-sc2-concepts
from typing import Union def object_type(object_ref: Union[type, object]) -> type: """Get type of anything. Args: object_ref (type, object): Object or type Returns: type: Type of given object """ return object_ref if isinstance(object_ref, type) else type(object_ref)
bigcode/self-oss-instruct-sc2-concepts
def _read_params(test_file_name): """Return expected errors, warnings, and return value for test file.""" with open(test_file_name) as f: exp_ret_val = 0 exp_errors = [] exp_warnings = [] for index, line in enumerate(f.readlines()): ret_mark = "// Return:" ...
bigcode/self-oss-instruct-sc2-concepts
from datetime import datetime def date_str_from_datetime_str(datetime_str): """Convert a datetime string to a date string, e.g. 2020-07-04 12:00:00 to 2020-07-04""" try: return datetime.strptime(datetime_str, "%Y-%m-%d %H:%M:%S").strftime("%Y-%m-%d") except ValueError: return datetime_str
bigcode/self-oss-instruct-sc2-concepts
def calculate_max_series(series): """ Calculate the maximum of a series :param series: list of values where we want to know the maximum of. :return max(series): highest value in the series """ assert type(series) is list and len(series) != 0 return max(series)
bigcode/self-oss-instruct-sc2-concepts
from typing import List def parentheses_status_eliminate(string: str) -> str: """Check is expression string has balanced parentheses (using stack elimination). In every iteration, the innermost brackets get eliminated (replaced with empty string). If we end up with an empty string, our initial one was ba...
bigcode/self-oss-instruct-sc2-concepts
def query_transform(context, include_page=False, **kwargs): """ Returns the URL-encoded querystring for the current page, updating the params with the key/value pairs passed to the tag. E.g: given the querystring ?foo=1&bar=2 {% query_transform bar=3 %} outputs ?foo=1&bar=3 {% query_transform ...
bigcode/self-oss-instruct-sc2-concepts
def kequivalent(springs, config): """ Given a list of spring constant values and their configuration, returns the equivalent spring constant """ if config == 'parallel': return sum(springs) elif config == 'series': return 1 / sum((1 / n for n in springs)) else: raise...
bigcode/self-oss-instruct-sc2-concepts
import torch def uncertainty_separation_parametric(mu, var): """Total, epistemic and aleatoric uncertainty based on a parametric (normal) variance measure M = length of input data x, N = number of distributions Args: mu: torch.tensor((M, N)): E(y|x) for M x and N distr. var: torch.t...
bigcode/self-oss-instruct-sc2-concepts
def unset_nth_bit(n: int, i: int) -> int: """ Unset the n-th bit. >>> bin(unset_nth_bit(0b11111111, 0)) '0b11111110' >>> bin(unset_nth_bit(0b11111110, 0)) '0b11111110' """ return n & ~(1 << i)
bigcode/self-oss-instruct-sc2-concepts
def _get_category_bounds(category_edges): """Return formatted string of category bounds given list of category edges""" bounds = [ f"[{str(category_edges[i])}, {str(category_edges[i + 1])})" for i in range(len(category_edges) - 2) ] # Last category is right edge inclusive bounds.appe...
bigcode/self-oss-instruct-sc2-concepts
def rma(data, length): """Rolled moving average Arguments: data {list} -- List of price data length {int} -- Lookback period for rma Returns: list -- RMA of given data """ alpha = 1 / length romoav = [] for i, _ in enumerate(data): if i < 1: romo...
bigcode/self-oss-instruct-sc2-concepts
def numberSeparators(number, separator=' '): """ Adds a separator every 3 digits in the number. """ if not isinstance(number, str): number = str(number) # Remove decimal part str_number = number.split('.') if len(str_number[0]) <= 3: str_number[0] = str_number[0] e...
bigcode/self-oss-instruct-sc2-concepts
def youtube_mocker(mocker): """Return a mock youtube api client""" return mocker.patch("videos.youtube.build")
bigcode/self-oss-instruct-sc2-concepts
def twoNumberSum(array, targetSum): """ twoNumberSum finds the two numbers whose sum is equals to targetSum with the binary search strategy. array: the collection of numbers that can sum the target number. targetSum: the target number to find. returns a list with the two nu...
bigcode/self-oss-instruct-sc2-concepts
def getContinuousRuns(x): """ Given a 1D array, find all of the continuous runs of 1s, and count the numbers with a certain length :param x: 1D array :returns Runs: A frequency distribution dictionary of the form {length:counts} """ Runs = {} (IN_ZEROS, IN_ONES) = (0, 1) stat...
bigcode/self-oss-instruct-sc2-concepts
def ask_value(message): """ Ask user to type some value. Ask again if no answer. Arguments: - message (string): message to display Return (string): value typed by user """ answer = input(message) if answer == '': return ask_valu...
bigcode/self-oss-instruct-sc2-concepts
def get_ip_from_raw_address(raw_address: str) -> str: """ Return IP address from the given raw address. >>> get_ip_from_raw_address('91.124.230.205/30') '91.124.230.205' >>> get_ip_from_raw_address('192.168.1.15/24') '192.168.1.15' """ return raw_address.rsplit('/')[0]
bigcode/self-oss-instruct-sc2-concepts
import math def get_foldrate_at_temp(ref_rate, new_temp, ref_temp=37.0): """Scale the predicted kinetic folding rate of a protein to temperature T, based on the relationship ln(k_f)∝1/T Args: ref_rate (float): Kinetic folding rate calculated from the function :func:`~ssbio.protein.sequence.properties...
bigcode/self-oss-instruct-sc2-concepts
def safeOpen(filename): """Open a utf-8 file with or without BOM in read mode""" for enc in ['utf-8-sig', 'utf-8']: try: f = open(filename, 'r', encoding=enc) except Exception as e: print(e) f = None if f != None: return f
bigcode/self-oss-instruct-sc2-concepts
def get_ip(request): """ Returns ip address or None if the address is in an unexpected format """ ip_address = request.META['REMOTE_ADDR'] return ip_address
bigcode/self-oss-instruct-sc2-concepts
def reduce_next_sentence_label_dimension(batch): """Change next_sentence_labels's shape from (-1, 1) to (-1,). Args: batch: A dictionary mapping keys to arrays. Returns: Updated batch. """ batch['next_sentence_labels'] = batch['next_sentence_labels'][:, 0] return batch
bigcode/self-oss-instruct-sc2-concepts
def binary_search(array, val): """Binary search.""" sorted_array = sorted(array) i = 0 j = len(array) - 1 while i <= j: mid = (i + j) // 2 if sorted_array[mid] == val: return mid if sorted_array[mid] < val: i = mid + 1 else: j = mid...
bigcode/self-oss-instruct-sc2-concepts
def _get_network_layer_sizes(net_params): """Infer the architecture of the simply connected network from the parameters""" dense_params = [p for p in net_params if len(p) > 0] all_dense_layer_sizes = [p[1].size for p in dense_params] dim_in = all_dense_layer_sizes[0] dim_out = all_dense_layer_sizes[...
bigcode/self-oss-instruct-sc2-concepts
from typing import Tuple def convert_to_pixel_coords(location: Tuple[float, float], center_of_image_in_global: Tuple[float, float], center_of_image_in_pixels: Tuple[float, float], resolution: float = 0.1) -> Tuple[int, int]: """ ...
bigcode/self-oss-instruct-sc2-concepts
def params_from_cmd(args): """Extract the parameters for prepare_training_data from the command line and return a dict""" params = { "maps_list": args.maps_list, "xyz_limits": args.xyz_limits, "output_dir": args.output_dir, "slices": args.slices_per_axis, } return params
bigcode/self-oss-instruct-sc2-concepts
def spherical(r_1, r_2, E_1, E_2, vu_1, vu_2, P_guess=None): """Returns the contact parameters for two spheres in contact or for a sphere in contact with a flat surface. In the case of a flat surface, enter None for the radius. Parameters ---------- r_1 : {None, float} Radius of sphere...
bigcode/self-oss-instruct-sc2-concepts
import posixpath def split_entry_ext(path): """Like os.path.splitext, but take off .tar too. Taken from `pip._internal.utils.misc.splitext`. """ base, ext = posixpath.splitext(path) if base.lower().endswith('.tar'): ext = base[-4:] + ext base = base[:-4] return base, ext
bigcode/self-oss-instruct-sc2-concepts
def encode_proto_bytes(val: str) -> bytes: """ Encodes a proto string into latin1 bytes """ return val.encode('latin1')
bigcode/self-oss-instruct-sc2-concepts
def compute_shape(coords, reshape_len=None, py_name=""): """ Computes the 'shape' of a coords dictionary. Function used to rearange data in xarrays and to compute the number of rows/columns to be read in a file. Parameters ---------- coords: dict Ordered dictionary of the dimension na...
bigcode/self-oss-instruct-sc2-concepts
import re def check_uuid(uuid): """Check if the string contains a proper UUID. Supported format: 71769af6-0a39-4242-94be-1f84f04c8a56 """ regex = re.compile( r'^[a-f0-9]{8}-?[a-f0-9]{4}-?4[a-f0-9]{3}-?[89ab][a-f0-9]{3}-?[a-f0-9]{12}\Z', re.I) match = regex.match(uuid) return b...
bigcode/self-oss-instruct-sc2-concepts
def joinstr( sep, *args ): """Join the arguments after converting them to a string""" return sep.join( map( str, args ) )
bigcode/self-oss-instruct-sc2-concepts
def filter_dataframe(df, user=None, begin=None, end=None, rename_columns={}): """Standard dataframe preprocessing filter. This implements some standard and common dataframe preprocessing options, which are used in very many functions. It is likely simpler and more clear to do these yourself on the Dat...
bigcode/self-oss-instruct-sc2-concepts
def tax_input_checker(typed_input): """ Returns true if the input string cannot be converted to a float, and false if otherwise """ try: f = float(typed_input) except ValueError: return False return True
bigcode/self-oss-instruct-sc2-concepts
import random import string def gen_id(value, count=16): """Jinja2 filter to generate a random ID string""" random.seed(value) letters = string.ascii_uppercase return ''.join(random.choice(letters) for i in range(count))
bigcode/self-oss-instruct-sc2-concepts
def check_wide_data_for_blank_choices(choice_col, wide_data): """ Checks `wide_data` for null values in the choice column, and raises a helpful ValueError if null values are found. Parameters ---------- choice_col : str. Denotes the column in `wide_data` that is used to record each ...
bigcode/self-oss-instruct-sc2-concepts
import inspect from typing import Type def is_class(the_class: Type) -> bool: """ Returns true if the object passed is a class :param the_class: the class to pass :return: true if it is a class """ return inspect.isclass(the_class)
bigcode/self-oss-instruct-sc2-concepts
def card_html_id(card): """Return HTML id for element containing given card.""" return f'c{card:02d}'
bigcode/self-oss-instruct-sc2-concepts
import threading def daemon_thread(target, *args, **kwargs): """Makes a daemon thread that calls the given target when started.""" thread = threading.Thread(target=target, args=args, kwargs=kwargs) # NOTE(skudriashev): When the main thread is terminated unexpectedly # and thread is still alive - it wi...
bigcode/self-oss-instruct-sc2-concepts
def _get_var_name(bdd, u): """ Given a variable index u in the BDD, return the variable Name """ var_index = bdd["t_table"][u][0]-1 return bdd["var_order"][var_index]
bigcode/self-oss-instruct-sc2-concepts