seed
stringlengths
1
14k
source
stringclasses
2 values
import socket def is_ipv4_address(addr): """ Check if an address is a valid IPv4 address Note that something like '1.1.1' is considered to be valid. Because '1.1.1' can be abbreviation of '1.1.1.0' """ try: socket.inet_aton(addr) return True except (socket.error, ValueErr...
bigcode/self-oss-instruct-sc2-concepts
def double_to_single_callable(application): """ Transforms a double-callable ASGI application into a single-callable one. """ async def new_application(scope, receive, send): instance = application(scope) return await instance(receive, send) return new_application
bigcode/self-oss-instruct-sc2-concepts
from typing import Iterable def build_dataset_name(estimate: int, years: Iterable) -> str: """Produce a nicely formatted dataset name.""" unique_years = sorted(set(years)) if len(unique_years) > 1: years_range = f'{min(unique_years)}–{max(unique_years)}' else: years_range = unique_year...
bigcode/self-oss-instruct-sc2-concepts
from typing import Optional def get_duration(duration: Optional[float]) -> float: """Return 0 if the given duration is negative else, return the duration. >>> get_duration(None) 0 >>> get_duration(-10) 0 >>> get_duration(12) 12.0 """ if duration is None or float(duration) < 0: ...
bigcode/self-oss-instruct-sc2-concepts
def letter_only(guess, abc): """ Checks if the player's guess is a single ASCII letter only. :param abc: the alphabet used in the proverbs :type abc: str :param guess: the player's guess :type guess: str :return: True | False :rtype: bool """ if len(guess) == 1 and guess.upper()...
bigcode/self-oss-instruct-sc2-concepts
def klGaussian(mean_1, mean_2, sig2=1.): """Kullback-Leibler divergence for Gaussian distributions.""" return ((mean_1 - mean_2) ** 2) / (2 * sig2)
bigcode/self-oss-instruct-sc2-concepts
def generic( target, namespace, pass_cond=None, message="deserialization object", default=None): """Deserialize object similarly to keras .get. Parameters ---------- target : object target deserialization object. namespace : object namespace to search in. Keywor...
bigcode/self-oss-instruct-sc2-concepts
import socket def handle_udp_send(data: bytes, sock: socket.socket, ip: str, port: int) -> int: """Handle sending a datagram. This mainly exists so we can make a partial of it. Args: data (bytes): Message payload to send. sock (...
bigcode/self-oss-instruct-sc2-concepts
def get_prefix(headword, length): """ Return the prefix for the given headword, of length length. Note that the procedure implemented here is the result of reverse engineering, since no official specification has been published by Kobo so far. YMMV. :param headword: the headword string ...
bigcode/self-oss-instruct-sc2-concepts
def eqrr(registers, a, b, c): """(equal register/register) sets register C to 1 if register A is equal to register B. Otherwise, register C is set to 0.""" registers[c] = int(registers[a] == registers[b]) return registers
bigcode/self-oss-instruct-sc2-concepts
def oi_to_args(issues): """ Return a set containing all arguments in the list of open issues.""" res = set() for i in issues: res &= set(i.arguments) return res
bigcode/self-oss-instruct-sc2-concepts
def to_int(value: str | None) -> int | None: """Safely convert string value to int.""" if value is None: return None try: return int(value) except (ValueError, TypeError): return None
bigcode/self-oss-instruct-sc2-concepts
def smart_truncate(text, limit=100, suffix='...'): """ Truncates a text to the end of the last word before reaching `limit`, and adds `suffix` to the end. Since it is using Python's slicing, negative values work, too. :param text: <str> :param limit: <int> :param suffix: <str> :ret...
bigcode/self-oss-instruct-sc2-concepts
import torch def get_flat_weights(model): """Gets all model weights as a single flat vector.""" return torch.cat([p.data.view(-1, 1) for p in model.parameters()], 0)
bigcode/self-oss-instruct-sc2-concepts
def _get_ftype_from_filename(fn, ext_unit_dict=None): """ Returns the boundary flowtype and filetype for a given ModflowFlwob package filename. Parameters ---------- fn : str The filename to be parsed. ext_unit_dict : dictionary, optional If the arrays in the file are specif...
bigcode/self-oss-instruct-sc2-concepts
import string def entry_point_name_to_identifier(entry_point_name): """Transform an entry point name into an identifier suitable for inclusion in a PyPI package name.""" try: entry_point_name.encode('ascii') ascii_name = entry_point_name except UnicodeEncodeError: ascii_name = ...
bigcode/self-oss-instruct-sc2-concepts
def get_accounts(how_many=10): """Return list of account names.""" return [f'account-{i}' for i in range(how_many)]
bigcode/self-oss-instruct-sc2-concepts
import re def standardizeLocation(s, dic): """ Standardize Locations Args: s: string to standardie dic: dictionary key= pattern, value = to replace with Returns: string: standardized string or not match original string """ for loc in dic: if re.sea...
bigcode/self-oss-instruct-sc2-concepts
def get_descriptive_adjectives(tree, gender): """ Returns a list of adjectives describing pronouns for the given gender in the given dependency tree. :param tree: dependency tree for a document, output of **generate_dependency_tree** :param gender: 'male' or 'female', defines which pronouns to search f...
bigcode/self-oss-instruct-sc2-concepts
def confirm(prompt): """ Get user confirmation from standard input. Parameters ---------- prompt: str The message to show. Returns ------- True or false depending on whether the user has answered with yes or no. """ answer = '' while answer.lower() != 'y' and answer....
bigcode/self-oss-instruct-sc2-concepts
import torch def get_latent_embedding(model, data_loader, num_classes, device): """ Computes the latent embedding, i.e. z for each element of a dataset. The corresponding z values are directly organized by classes, such that they can readily be used for visualization purposes later. Parameters: ...
bigcode/self-oss-instruct-sc2-concepts
def numerical_filter(df, filter_): """ Compute an boolean condition setting which rows of DataFrame `df` should remain based on the numerical filter defined in the dict `filter_`. :param df: Pandas DataFrame containing core data :param filter_: Dictionary defining the filters :return: condition...
bigcode/self-oss-instruct-sc2-concepts
def listAppend(list:list,appendObj): """Syntatic sugar. This appends the obj to the list and returns it.""" if appendObj: list.append(appendObj); return appendObj
bigcode/self-oss-instruct-sc2-concepts
import torch def GlobalAvgPooling(x): """ Input: (batch, channels, height, weight) Output: mean, (batch, channels) """ b, c, h, w = x.shape x = x.view(b, c, h*w) mean = torch.mean(x, dim=2) return mean
bigcode/self-oss-instruct-sc2-concepts
def epc_calc_hdr(reg_dict): """ Returns True if high dynamic range is enabled, False otherwise Parameters ---------- reg_dict : dict The dictionary that contains all the register information Returns ---------- bool True if HDR enabled, false otherwise """ hdr_en...
bigcode/self-oss-instruct-sc2-concepts
def get_image_urls(post): """Returns a list of URLs for all images in a scraped Post object""" image_urls = {key: val for key, val in post.flat_json_dict.items() if "display_url" in key} return list(set(image_urls.values()))
bigcode/self-oss-instruct-sc2-concepts
from typing import Callable def _get_runname( func: Callable) -> str: """Return run name from function. Args: func (Callable): target function. Return: runname (str): run name string. """ return '.'.join([func.__module__, func.__name__])
bigcode/self-oss-instruct-sc2-concepts
def get_failed_conditions(conditions): """Get a comma separated string for the conditions that failed.""" if conditions is None: return '' return ', '.join([c.condition.name for c in conditions if not c.nominal])
bigcode/self-oss-instruct-sc2-concepts
def get_uniprot_secondaries(uniprot_result): """ Get secondary accession identifiers from UniProt text result :param uniprot_result: :return: """ accession_lines = [l for l in uniprot_result.split('\n') if l.startswith('AC')] secondaries = [] for ac_line in accession_lines: secon...
bigcode/self-oss-instruct-sc2-concepts
import yaml def read_config(yaml_in): """ Convert YAML config file into dictionary """ with open(yaml_in) as f: return yaml.safe_load(f)
bigcode/self-oss-instruct-sc2-concepts
def clean_missing_exports_long(exports, fill_na_value=0): """Clean the exports data in long format by removing records with missing product code and then filling missing values with fill_na_value (which is 0 by default). """ return (exports.dropna(subset=['product_code']) .fillna(...
bigcode/self-oss-instruct-sc2-concepts
def transit_x_axis_intercept(px: float, py: float, ox: float, oy: float) -> float: """Given an object at position px, py and an observer as ox, oy this returns the value on the x axis of the transit line.""" x = px + py * (ox - px) / (py - oy) return x
bigcode/self-oss-instruct-sc2-concepts
import re def truncate(text, words=25): """Remove tags and truncate text to the specified number of words.""" return ' '.join(re.sub('(?s)<.*?>', ' ', text).split()[:words])
bigcode/self-oss-instruct-sc2-concepts
def count_distinct(collection, key, exclude=None): """Get the number of distinct values for key in the specified database collection""" values = collection.distinct(key) if exclude is not None and exclude in values: values.remove(exclude) return len(values)
bigcode/self-oss-instruct-sc2-concepts
def make_qs(listname: list) -> str: """Create a list of '?'s for use in a query string. This is a convenience function that will take a list and return a string composed of len(list) queston marks joined by commas for use in an sql VALUES() clause. Args: listname: The...
bigcode/self-oss-instruct-sc2-concepts
import re def filter_text(text): """ Filter out retweet-prefix, urls, html-codes, hashtags, handles, and extra whitespaces :param text: a string :return: cleaned text """ return re.sub( r'(RT @\S+:)|(RT)|(https?:\S+)|(&\S+;)|(@\S+)|(#\S+)', '', text )
bigcode/self-oss-instruct-sc2-concepts
from pathlib import Path def create_hdf_dir(experiment_dir: Path, create_on_work: bool = False) -> Path: """ Create a directory in which the HDF results files for an HSR experiment can be stores and return the Path to the directory. .. attention:: Unless you are working on the MPI-IS cluster ...
bigcode/self-oss-instruct-sc2-concepts
def requires_replacement(changeset): """Return the changes within the changeset that require replacement. Args: changeset (list): List of changes Returns: list: A list of changes that require replacement, if any. """ return [r for r in changeset if r["ResourceChange"].get( ...
bigcode/self-oss-instruct-sc2-concepts
import sqlite3 from typing import List def get_columns(conn: sqlite3.Connection) -> List[str]: """Get column names in the order just like it is returned from the DB. :param conn: Connection to the database :type conn: sqlite3.Connection :return: A list of column names in the database. :rtype: Lis...
bigcode/self-oss-instruct-sc2-concepts
import math def round_repeats(repeats, global_params): """Round number of filters based on depth multiplier.""" multiplier = global_params.depth_coefficient if not multiplier: return repeats return int(math.ceil(multiplier * repeats))
bigcode/self-oss-instruct-sc2-concepts
def get_spawn_weight(mod, tags): """ Calculates the spawn weight of the given mod for the given tags. Parameters ---------- mod : DatRecord The mod to calculate the spawn weight for. tags : list[str] List of applicable tag identifiers. Returns ------- int C...
bigcode/self-oss-instruct-sc2-concepts
def humantime(ms): # Docstring """ Converts timespan in milliseconds to a humanly readable string. -------------- ms : int or float Time in milliseconds -------------- Examples : >>> humantime(194159) '3 min, 14 sec, 159 ms' """ time_dict = {'ms' : ...
bigcode/self-oss-instruct-sc2-concepts
import torch def calculate_dihedrals(p, alphabet): """Converts the given input of weigths over the alphabet into a triple of dihederal angles Args: p: [BATCH_SIZE, NUM_ANGLES] alphabet: [NUM_ANGLES, NUM_DIHEDRALS] Returns: [BATCH_SIZE, NUM_DIHEDRALS] """ sins = torch.s...
bigcode/self-oss-instruct-sc2-concepts
def find_pivot_index(nums): """ Suppose a sorted array A is rotated at some pivot unknown to you beforehand. (i.e., 0 1 2 4 5 6 7 might become 4 5 6 7 0 1 2). Find the minimum element. NOTE: The array will not contain duplicates. """ min_num = nums[0] pivot_index = 0 left = 0 right =...
bigcode/self-oss-instruct-sc2-concepts
def s3_md5(s3key, blocksize=65536): """Hexadecimal md5 hash of a file stored in Amazon S3""" return s3key.etag.strip('"').strip("'")
bigcode/self-oss-instruct-sc2-concepts
def all_type(dataframe): """ Find all availble EV connector types in column ['EV Connector Types'] Attributes -------------------------- dataframe: DataFrame The DataFrame to deal Return -------------------------- type_dict: dict A list of all availible connector types ...
bigcode/self-oss-instruct-sc2-concepts
def find_prefix_cols(df, prefix): """List all df columns with the given prefix.""" sel = [colname.startswith(prefix) for colname in df.columns] return df.columns[sel]
bigcode/self-oss-instruct-sc2-concepts
import re def get_static_pattern(static_url_prefix): """Builds a regular expression we can use to find static asset references that start with the given static URL prefix. Used for finding static dependencies inside JS and CSS files and for rewriting static references in compiled assets. """ ...
bigcode/self-oss-instruct-sc2-concepts
import ast def chromosomesInCluster(hotspots): """ Determine chromosomes in a hotspots file :param hotspots: str Hotspots filename :return: dict Chromosomes and first last positions within the chromosomes in the cluster """ chromosomes = dict(); with open(hotspots, 'r') ...
bigcode/self-oss-instruct-sc2-concepts
def find_end_paren(function_code: str, start: int): """ Find the end location given a starting parenthesis location :param function_code: :param start: :return: """ parentheses = [] for i, character in enumerate(function_code[start:]): if character == "(": parentheses...
bigcode/self-oss-instruct-sc2-concepts
def rgb2hex(r: int, g: int, b: int) -> str: """ Convert rgb values to a hex code. """ return '{:02x}{:02x}{:02x}'.format(r, g, b)
bigcode/self-oss-instruct-sc2-concepts
def get_version_without_patch(version): """ Return the version of Kili API removing the patch version Parameters ---------- - version """ return '.'.join(version.split('.')[:-1])
bigcode/self-oss-instruct-sc2-concepts
def snaps_to_hydroobject(gdf, datamodel, method, tolerance=0.001, dtype=bool): """ Check if geometries snap to HydroObject Parameters ---------- gdf : ExtendedGeoDataframe ExtendedGeoDataFrame, typically a layer in a HyDAMO datamodel class datamodel : HyDAMO HyDAMO datamodel cla...
bigcode/self-oss-instruct-sc2-concepts
def pretty_kwargs(kwargs): """pretty prints the keyword arguments in a string """ return ", ".join([ f"{key}={repr(value)}" for key, value in kwargs.items() ])
bigcode/self-oss-instruct-sc2-concepts
def divceil(divident, divisor): """Integer division with rounding up""" quot, r = divmod(divident, divisor) return quot + int(bool(r))
bigcode/self-oss-instruct-sc2-concepts
from typing import Dict def collect_dataset(input_file: str) -> Dict: """Read and parse lines from dataset files Args: input_file (str): path to input file Returns: Dict: return dict of dataset """ dataset = {} lcount = 0 with open(input_file, "r", encoding="latin-1") as ...
bigcode/self-oss-instruct-sc2-concepts
def is_odd(number): """Return True if number is odd, else False.""" return number % 2 != 0
bigcode/self-oss-instruct-sc2-concepts
def add_four(num): """Add four to num""" return num + 4
bigcode/self-oss-instruct-sc2-concepts
from typing import List from typing import Dict from typing import Any from typing import ChainMap def combine_dictionaries(dicts: List[Dict[str, Any]]) -> Dict[str, Any]: """Merge a list of dictionaries into a single dictionary. Where there are collisions the first value in the list will be set as this ...
bigcode/self-oss-instruct-sc2-concepts
import hashlib def compute_md5_hash(string): """Gets md5 digest from a string.""" md5_hash = hashlib.md5() # noqa: S303, W291 md5_hash.update(string.encode('utf-8')) return md5_hash.hexdigest()
bigcode/self-oss-instruct-sc2-concepts
def accuracy(gold, cand): """Compute fraction of equivalent pairs in two sequences.""" return sum(a == b for a, b in zip(gold, cand)) / len(gold)
bigcode/self-oss-instruct-sc2-concepts
def getStatusWord(status): """Returns the status word from the status code. """ statusWord = 'owned' if status == 0: return 'wished' elif status == 1: return 'ordered' return statusWord
bigcode/self-oss-instruct-sc2-concepts
def IDM_parameters(*args): """Suggested parameters for the IDM/MOBIL.""" # time headway parameter = 1 -> always unstable in congested regime. # time headway = 1.5 -> restabilizes at high density cf_parameters = [35, 1.3, 2, 1.1, 1.5] # note speed is supposed to be in m/s # note last 3 paramete...
bigcode/self-oss-instruct-sc2-concepts
def tohex(s): """Convert a string to hexadecimal""" return ''.join([hex(ord(c))[2:].zfill(2) for c in s])
bigcode/self-oss-instruct-sc2-concepts
def filename_from_url(url): """ Similar to Django slugify http://stackoverflow.com/questions/295135/turn-a-string-into-a-valid-filename-in-python :param url: url to convert :return: a valid filename """ filename = "".join(i for i in url if i not in "\/:*?<>|") return filename
bigcode/self-oss-instruct-sc2-concepts
def to_unicode(data_str: bytes, encoding: str) -> str: """Convert a str object to unicode using the encoding given Characters that cannot be converted will be converted to ``\\ufffd`` (the unicode replacement character). """ return data_str.decode(encoding, "replace")
bigcode/self-oss-instruct-sc2-concepts
def add(*args: float) -> float: """Returns the sum of all input arguments.""" return sum(args)
bigcode/self-oss-instruct-sc2-concepts
def _format_host_port_alias(host, port, alias): """Format a host, port, and alias so it can be used for comparison or display.""" if alias: return f"{alias}@{host}:{port}" return f"{host}:{port}"
bigcode/self-oss-instruct-sc2-concepts
def channelparse(channel, cachedjson): """Get json data for a specific channel.""" if channel in cachedjson: channeldata = cachedjson[channel] return channeldata, cachedjson return False
bigcode/self-oss-instruct-sc2-concepts
def read_file(file): """Reads Whatsapp text file into a list of strings""" x = open(file, 'r', encoding='utf-8') # Opens the text file into variable x but the variable cannot be explored yet y = x.read() # By now it becomes a huge chunk of string that we need to separate line by line content = y.split...
bigcode/self-oss-instruct-sc2-concepts
def lowercase_subset(A, B): """Check that A is a subset of B when case is ignored.""" set_a = set([a.lower() for a in A]) set_b = set([b.lower() for b in B]) return set_a.issubset(set_b)
bigcode/self-oss-instruct-sc2-concepts
import re def extract_keywords(text, keywords): """Extracts keywords from text. Args: text (str): Text from which the keywords will be extracted. keywords (list): Keywords to look for. Returns: list: All keywords found in text. """ # Construct an alternative regex patter...
bigcode/self-oss-instruct-sc2-concepts
def __similarity(s1, s2, ngrams_fn, n=3): """ The fraction of n-grams matching between two sequences Args: s1: a string s2: another string n: an int for the n in n-gram Returns: float: the fraction of n-grams matching """ ngrams1, ngr...
bigcode/self-oss-instruct-sc2-concepts
import string def integerToLetter(i) -> str: """Returns letter sequence string for integer i.""" # William Chapman, Jorj McKie, 2021-01-06 ls = string.ascii_uppercase m = int((i - 1) / 26) # how many times over n = (i % 26) - 1 # remainder str_t = "" for _ in range(0, m + 1): st...
bigcode/self-oss-instruct-sc2-concepts
import numbers def is_number(x): """Test if `x` is a number.""" return isinstance(x, numbers.Number)
bigcode/self-oss-instruct-sc2-concepts
def to_bool(bool_str): """Parse a boolean environment variable.""" return bool_str.lower() in ("yes", "true", "1")
bigcode/self-oss-instruct-sc2-concepts
def license(_): """Return the contents of the LICENSE.txt file.""" with open('LICENSE.txt') as flicense: return flicense.read()
bigcode/self-oss-instruct-sc2-concepts
import re def split_camel(word): """ Separate any words joined in Camel case fashion using a single space. >>> split_camel('esseCarthaginienses') 'esse Carthaginienses' >>> split_camel('urbemCertimam') 'urbem Certimam' """ m = re.match('[a-z]+[A-Z][a-z]', word) if m: _, end...
bigcode/self-oss-instruct-sc2-concepts
def add_python_snippet(txt: str, expandable: bool = True): """ Add a python snippet. :param txt: A string object. :param expandable: If true, puts code in <details></details> syntax. :return: Python string markdown syntax. """ md_str = f"\n```python\n{txt}\n```" if expandable: ...
bigcode/self-oss-instruct-sc2-concepts
def field_verbose_name(value, field): """ Django template filter which returns the verbose name of an object's, model's or related manager's field. """ if hasattr(value, "model"): value = value.model return value._meta.get_field(field).verbose_name.title()
bigcode/self-oss-instruct-sc2-concepts
def base_url(skin, variables): """ Returns the base_url associated to the skin. """ return variables['skins'][skin]['base_url']
bigcode/self-oss-instruct-sc2-concepts
import hashlib def _get_hash(data): """Compute the sha256 hash of *data*.""" hasher = hashlib.sha256() hasher.update(data) return hasher.hexdigest()
bigcode/self-oss-instruct-sc2-concepts
from typing import Union import torch def get_scalar_vl(x: Union[torch.Tensor, float]) -> float: """ Helper function to always return either a float no matter the input. Args: x: The object to get the float from Returns: flt: The valuea s a float """ if isinstance(x, torch.Ten...
bigcode/self-oss-instruct-sc2-concepts
def is_related(field): """ Return True if the given field definition is a ForeignKey, OneToOneField, or ManyToManyField. >>> is_related(('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '100'})) False >>> is_related(('django.db.models.fields.related.ForeignKey', [], {'r...
bigcode/self-oss-instruct-sc2-concepts
import time def wait_for(condition, max_tries=60): """Wait for a condition to be true up to a maximum number of tries """ cond = False while not cond and max_tries > 1: try: cond = condition() except Exception: pass time.sleep(1) max_tries -= 1 ...
bigcode/self-oss-instruct-sc2-concepts
def get_size_to_render(plugin_config): """Get size to render an image.""" height = plugin_config.get("height", -1) width = plugin_config.get("width", -1) return height, width
bigcode/self-oss-instruct-sc2-concepts
def _get_element_from_list_with_delay(item_list, element, delay): """ A little util for faking delay of data stream. e.g. ``` l = [] get = generate_delay(l, 3) for i in range(10): print get(i) ``` prints 0 0 0 1 2 3 4 5 6 :param item_list list: list of items :param ...
bigcode/self-oss-instruct-sc2-concepts
def is_level_correct(level): """Checking that insert level is correct ("EASY", "MEDIUM", "HARD")""" levels = ["EASY", "MEDIUM", "HARD"] if level in levels: return True else: return False
bigcode/self-oss-instruct-sc2-concepts
def get_alert(paramalertLS, paramalertLQ, parampopLS, parampopLQ, hazbinLS=[1., 10., 100.], popbinLS=[100, 1000, 10000], hazbinLQ=[10., 100., 1000.], popbinLQ=[100, 1000, 10000]): """ Get alert levels Args: paramalertLS (float): Hazard statistic of preferred landslide mo...
bigcode/self-oss-instruct-sc2-concepts
import math import random def interim_move_helper(stats, c): """ Function to return a key for the interim move helper :param stats: List of stats :param c: Exploration parameter :return: Function for interim move helper to use as a key """ top = math.log(sum(stat[0] for stat in stats)) ...
bigcode/self-oss-instruct-sc2-concepts
def make_terms_from_string(s): """turn string s into a list of unicode terms""" u = s return u.split()
bigcode/self-oss-instruct-sc2-concepts
def requires(*methodList): """ Optional decorator for shard functions to list any dependencies. If a shard uses methods it does not provide/import, it should declare them using this function or by setting the __requiresMethods attribute manually. If this attribute is not present, it wi...
bigcode/self-oss-instruct-sc2-concepts
def _convert_tensor_base(tensor_data): """Convert tensor object to dict.""" tensor_data_dict = { 'dtype': tensor_data.dtype, 'shape': tensor_data.shape, 'data_size': tensor_data.data_size } return tensor_data_dict
bigcode/self-oss-instruct-sc2-concepts
def get_qual_name(o, lower=False): """ Returns the qualified name of an object o. """ if not isinstance(o, type): o = o.__class__ if lower: return o.__qualname__.lower() else: return o.__qualname__
bigcode/self-oss-instruct-sc2-concepts
def _CreateAptPkgRepo(messages, repo_name): """Create an apt repo in guest policy. Args: messages: os config guest policy api messages. repo_name: repository name. Returns: An apt repo in guest policy. """ return messages.PackageRepository( apt=messages.AptRepository( uri='http:/...
bigcode/self-oss-instruct-sc2-concepts
def _get_defines(header): """ Returns list of define statements Parameters ---------- header : str CppHeader Returns ------- defines : list List of define directive strings """ defines = [] for inc in header.defines: defines.append(f'#define {inc}') ...
bigcode/self-oss-instruct-sc2-concepts
def get_hertz(reg, key): """Returns the hertz for the given key and register""" return int(reg * 2 ** (key / 12))
bigcode/self-oss-instruct-sc2-concepts
def cpf_int_validation(cpf: int) -> bool: """ Validation CPF integer. Args: cpf (int): CPF. Returns: bool: If CPF real True else False. """ clean_cpf = str(cpf).zfill(11) digito = {} digito[0] = 0 digito[1] = 0 a = 10 total = 0 for c in range(0, 2): ...
bigcode/self-oss-instruct-sc2-concepts
import math def parent(level, idx): """ Return the parent of a given healpix pixel (in nested format) :param level: Resolution level :param idx: Index at the given level :return: Tuple (lvl, idp) including the level and the index of the parent pixel """ assert idx < 12 * 2 ** (2 * level) ...
bigcode/self-oss-instruct-sc2-concepts
from typing import List import re def _split_strip_string(string: str) -> List[str]: """Split the string into separate words and strip punctuation.""" string = re.sub(r"[!()*+\,\-./:;<=>?[\]^_{|}~]", " ", string) string = re.sub(r"[\'\"\`]", "", string) return re.sub( r"([A-Z][a-z]+)", r" \1"...
bigcode/self-oss-instruct-sc2-concepts