seed
stringlengths
1
14k
source
stringclasses
2 values
def get_resource_identifier(iot_finding): """Get resource name from IoT device Defender finding""" resource = iot_finding['nonCompliantResource']['resourceIdentifier'] if list(resource.keys())[0] == "policyVersionIdentifier": return resource["policyVersionIdentifier"]["policyName"] else: ...
bigcode/self-oss-instruct-sc2-concepts
from typing import Optional from typing import Any def ifnone(item: Optional[Any], alt_item: Any) -> Any: """Return ``alt_item`` if ``item is None``, otherwise ``item``.""" return alt_item if item is None else item
bigcode/self-oss-instruct-sc2-concepts
def _clean_dict(my_dict): """ Remove empty entries from dictionary """ return dict((k, v) for k, v in my_dict.iteritems() if v)
bigcode/self-oss-instruct-sc2-concepts
import re def checkIPAddr(ipAddr: str) -> bool: """ Check IP Address Parameters ---------- ipAddr: str IP Address from UI Returns ---------- boolean """ pattern = r'\d{1,3}' lst_ipAddr = ipAddr.split('.') if len(lst_ipAddr) != 4: print('numb...
bigcode/self-oss-instruct-sc2-concepts
def _ScoreRequested(params): """Returns True if match scoring requested, False otherwise.""" return params.has_scorer_spec() and params.scorer_spec().has_scorer()
bigcode/self-oss-instruct-sc2-concepts
def num_unique_objects(df, obj_frequencies): """Total number of unique object ids encountered.""" del df # unused return len(obj_frequencies)
bigcode/self-oss-instruct-sc2-concepts
def is_staff(request): """Returns whether or not the request's user is an authenticated staff member.""" return request.user is not None and request.user.is_staff and request.user.is_authenticated()
bigcode/self-oss-instruct-sc2-concepts
import re def remove_spacing(query: str) -> str: """Take an SQL query string and return with single spaces, except at the beginning and end of the string. """ query = re.sub(r'\s+', ' ', query) query = re.sub(r'(^\s|\s$)', '', query) return query
bigcode/self-oss-instruct-sc2-concepts
from datetime import datetime def changeTimestampToDate(timestamp): """ Méthode permettant de changer un timestamp en date de forme AAAA-MM-JJ-HH-MM-SS :param timestamp: le timestamp à convertir :return: la date obtenue :raises TypeError: Exception levée si le paramètre n'est pas un integer "...
bigcode/self-oss-instruct-sc2-concepts
def two_dec(num: float) -> str: """Format a floating point number with 2 decimal places.""" return "{0:.2f}".format(num)
bigcode/self-oss-instruct-sc2-concepts
def utilization_to_state(state_config, utilization): """ Transform a utilization value into the corresponding state. :param state_config: The state configuration. :type state_config: list(float) :param utilization: A utilization value. :type utilization: number,>=0 :return: The state corres...
bigcode/self-oss-instruct-sc2-concepts
import itertools def basis_labels(n): """ Generate a list of basis labels for `n` qubits, ordered from least to greatest, in big-endian format: ['00..00', '00..01', ..., '11..11'] :param n: :return: A list of strings of length n that enumerate the n-qubit bitstrings :rtype: list ...
bigcode/self-oss-instruct-sc2-concepts
def get_auth_server_info(environ): """ Return some info about the available auth servers. """ auth_server_info = [] auth_servers = environ['tiddlyweb.config'].get('oauth.servers') for server in auth_servers: server_info = auth_servers[server] auth_server_info.append({ ...
bigcode/self-oss-instruct-sc2-concepts
import re def clean_filename(filename): """ Remove non-alphanumeric characters from filenames. *Parameters* filename : str The filename to be sanitized. *Returns* clean : str A sanitized filename that contains only alphanumeric characters and underscores. """ ...
bigcode/self-oss-instruct-sc2-concepts
def get_first(values: list): """ Function that takes in a list and returns the first value (and the .text attribute if it exists), otherwise returns nothing @param values: list that contains 0-many results @returns: the first item of the list or None """ out=None if len(values) > 0: ...
bigcode/self-oss-instruct-sc2-concepts
def function_maker(func): """Wraps a function to return [params, f(params)]""" def f(params): try: r = func(**params) except Exception as e: r = e return [params, r] return f
bigcode/self-oss-instruct-sc2-concepts
from typing import Tuple def extended_euclid(a: int, b: int) -> Tuple[int, int, int]: """ Extended Euclidean Algorithm :param a: integer :param b: integer :return: The gcd of a and b, and x and y such that ax + by = gcd(a, b) """ if a == 0 and b == 0: return 0, 0, 0 equation1...
bigcode/self-oss-instruct-sc2-concepts
def nonterminal_graph_edge_constraints(new_edges, init_source_side): """ Ensure that the new non-terminal rule respects edge constraints: 1. No edges should originate from subtracted part of the graph 2. All edges in the new graph should connect to no more than one distinct node in the subtracte...
bigcode/self-oss-instruct-sc2-concepts
import torch def NEG_INF_DIAG(n, device): """Returns a diagonal matrix of size [n, n]. The diagonal are all "-inf". This is for avoiding calculating the overlapped element in the Criss-Cross twice. """ return torch.diag(torch.tensor(float('-inf')).to(device).repeat(n), 0)
bigcode/self-oss-instruct-sc2-concepts
def count_by_activity(contract_json): """ Given a full JSON contracts dictionary, return a new dictionary of counts by activity. """ by_activity = contract_json['contracts'] activities = by_activity.keys() return dict(zip(activities, [len(by_activity[a]) for a in activities]))
bigcode/self-oss-instruct-sc2-concepts
import random def __randomInt(limit: int) -> int: """ Return a random between 1 and limit """ return random.randrange(1, limit)
bigcode/self-oss-instruct-sc2-concepts
def format_decimal_value(value): """ Format number as string, limiting decimal length based on value Input: - value: Integer or float Output: String containing converted value """ if value > 1: # Format as 3 point decimal for smaller amounts return "{:0.3f}".format(value).r...
bigcode/self-oss-instruct-sc2-concepts
def number_to_20_cen_year(number): """ Convert "1" to "2001", "21" to "2021" etc. :param number: int :return: formatted year """ year = "2000"[:len("2000")-len(str(number))] + str(number) return year
bigcode/self-oss-instruct-sc2-concepts
def strip_query(path): """Strips query from a path.""" query_start = path.find('?') if query_start != -1: return path[:query_start] return path
bigcode/self-oss-instruct-sc2-concepts
def return_chopped_list(inputlist, left_index=0, right_index=64): """Input a list of strings and return a new list of strings that have been sliced by the left and right index values (int). """ newlist = [] for item in inputlist: newlist.append(item[left_index:right_index]) return newlis...
bigcode/self-oss-instruct-sc2-concepts
def get_gender_from_label(gender): """ Method to get the passed gender in XNAT format :param gender: gender selected :return: value accepted by xnat: 'female' or 'male' """ if gender.lower() in ['female', 'f']: return 'female' elif gender.lower() in ['male', 'm']: return 'ma...
bigcode/self-oss-instruct-sc2-concepts
def flatten(l): """ Flatten a list of lists into a plain list :param l: list to flatten (list) :return: list flattened (list) """ return [item for sublist in l for item in sublist]
bigcode/self-oss-instruct-sc2-concepts
def sweep_config_err_text_from_jsonschema_violations(violations): """Consolidate violation strings from wandb/sweeps describing the ways in which a sweep config violates the allowed schema as a single string. Parameters ---------- violations: list of str The warnings to render. Returns...
bigcode/self-oss-instruct-sc2-concepts
def conv19bitToInt32(threeByteBuffer): """ Convert 19bit data coded on 3 bytes to a proper integer (LSB bit 1 used as sign). """ if len(threeByteBuffer) != 3: raise ValueError("Input should be 3 bytes long.") prefix = 0; # if LSB is 1, negative number, some hasty unsigned to signed conversion to do if ...
bigcode/self-oss-instruct-sc2-concepts
def _q_stop(query_seq, q_seq): """ returns the ending python string index of query alignment (q_seq) in the query sequence (query_seq) :param query_seq: string :param q_seq: string :return: integer """ q_seq = q_seq.replace("-", "") q_start = query_seq.find(q_seq) q_stop = q_start ...
bigcode/self-oss-instruct-sc2-concepts
import requests def get_random_quote(quotes_api_url, quotes_api_key): """ Get a random quote from quotes api. """ headers = {"Authorization": "Bearer {}".format(quotes_api_key)} res = requests.get(quotes_api_url + "/quotes/random", headers=headers) data = res.json() return data
bigcode/self-oss-instruct-sc2-concepts
from typing import List from pathlib import Path def get_files(directory: str, extension: str) -> List[str]: """ Get a list of files with a given extension. :param directory: path to directory. :param extension: extension for file filtering - only files with this extension will be preserved. :...
bigcode/self-oss-instruct-sc2-concepts
import re def delete_useless(statement: str) -> str: """ 無駄な移動/計算を相殺、削除 >>> delete_useless("+++--<<>>>") '+>' >>> delete_useless("---++>><<<") '-<' >>> delete_useless(">++++[-][-]") '>[-]' >>> delete_useless(">--[-]++[-]") '>[-]' """ while True: if "<>" in stat...
bigcode/self-oss-instruct-sc2-concepts
def get_min_key(d): """Return the key from the dict with the min value.""" return min(d, key=d.get)
bigcode/self-oss-instruct-sc2-concepts
def standard_event_metrics_to_list(standard_event_results): """ Converting standard event metric results to a list (position of each item is fixed) Argument: standard_event_results (dictionary): as provided by the 4th item in the results of eval_events function Returns: list: Item order: 1...
bigcode/self-oss-instruct-sc2-concepts
def remove_first_word(string): """Remove the first word of the line. :param str string: string :rtype str :return: string without the first word """ return string.split(' ', 1)[1].strip()
bigcode/self-oss-instruct-sc2-concepts
import re def extract_adquisition_rate(line): """Extracts the adquisition rate in Hz from the line of text that is supposed to contain that information. Raises an exception if it is not found. INPUT: line: string, file line containing a number followed by "Hz". OUTPUT: integer. ...
bigcode/self-oss-instruct-sc2-concepts
def get_approving_reviewers(props): """Retrieves the reviewers that approved a CL from the issue properties with messages. Note that the list may contain reviewers that are not committer, thus are not considered by the CQ. """ return sorted( set( message['sender'] for message in props...
bigcode/self-oss-instruct-sc2-concepts
def parseLines(text): """Returns a list of lines from the given text. Understands end-of-line escapes '\\n'""" lines = text.strip().split('\n') esclines = [] esc = False for l in lines: if esc: esclines[-1] = esclines[-1]+l else: esclines.append(l) if...
bigcode/self-oss-instruct-sc2-concepts
from typing import MutableMapping from typing import Any def flatten_dict( d: MutableMapping[str, Any], *, parent_key: str = "", sep: str = "." ) -> dict[str, Any]: """Flatten a nested dictionary by separating the keys with `sep`. :param d: Dictionary to be flattened. :param parent_key: Key-prefix (s...
bigcode/self-oss-instruct-sc2-concepts
def get_varying_levels(df, is_index=True): """Return the name of the levels that are varying in multi index / columns.""" if is_index: levels, names = df.index.levels, df.index.names else: levels, names = df.columns.levels, df.columns.names return [n for l, n in zip(levels, names) if len...
bigcode/self-oss-instruct-sc2-concepts
from typing import List def add(a: List[int], b: List[int]) -> List[int]: """ Adds two lists of bits together. When summing bits, they are added from left to right. For that reason, a reverse range is used to iterate through the bits backwards. The resulting bits are then reversed after addition to ...
bigcode/self-oss-instruct-sc2-concepts
def normalise_value(value): """ Default normalisation of value simply returns the value as is. Custom implementations can normalise the value for various storage schemes. For example, converting datetime objects to iso datetime strings in order to comply with JSON standard. """ return value
bigcode/self-oss-instruct-sc2-concepts
def beta_mean(x,y): """Calculates the mean of the Beta(x,y) distribution Args: x (float): alpha (shape) parameter y (float): beta (scale) parameter Returns: float: A float that returns x/(x+y) """ output = x / (x+y) return output
bigcode/self-oss-instruct-sc2-concepts
def ebs_settings_validator(param_key, param_value, pcluster_config): """ Validate the following cases. Number of EBS volume specified is lower than maximum supported Parameter shared_dir is specified in every EBS section when using more than 1 volume User is not specifying /NONE or NONE as shared_d...
bigcode/self-oss-instruct-sc2-concepts
def get_s3_index_arn(bosslet_config): """ Get arn of the DynamoDB s3 index. Args: bosslet_config (BossConfiguration): target bosslet Returns: (str): """ names = bosslet_config.names dynamo = bosslet_config.session.client('dynamodb') resp = dynamo.describe_table(TableNam...
bigcode/self-oss-instruct-sc2-concepts
def represents_int(s): """Judge whether string s represents an int. Args: s(str): The input string to be judged. Returns: bool: Whether s represents int or not. """ try: int(s) return True except ValueError: return False
bigcode/self-oss-instruct-sc2-concepts
import string import random def random_text(length: int, alph: str = string.ascii_letters + string.digits) -> str: """ Generates random string text :param int length: length of text to generate :param str alph: string of all possible characters to choose from :return str: generated random string of s...
bigcode/self-oss-instruct-sc2-concepts
def select_top_address_candidate(geocode_candidate_response_json): """ Selects the geocoded address candidate with the highest score :param geocode_candidate_response_json: JSON object containing address candidates returned from the ArcGIS Geodcoding API :return: Dict containing address string ...
bigcode/self-oss-instruct-sc2-concepts
def start(producers): """ Take a list of actors and call their "run" function remotely (as in ray so in parallel). The returned object can be used to wait for the completion of the tasks with ray.get. """ return [producer.run.remote() for producer in producers]
bigcode/self-oss-instruct-sc2-concepts
def number_of_nonzero_coef(X, model): """ Calculates the number of non-zero coefficients in a model. Useful for evaluating models with an L1 penalty. Parameters ---------- X : numpy array or pandas dataframe The design or feature matrix. model : sklearn object, or similar Th...
bigcode/self-oss-instruct-sc2-concepts
from typing import List def flatten(list_of_lists: List[List]) -> List: """Reduce a lists of lists to a list, comprehensively >>> assert flatten([[1, 2], [3, 4]]) == [1, 2, 3, 4] Thanks to Alex Martelli at https://stackoverflow.com/a/952952/500942 """ return [item for list_ in list_of_li...
bigcode/self-oss-instruct-sc2-concepts
def is_variable(v): """Returns if input is of variable type.""" return type(v).__name__ == 'Variable'
bigcode/self-oss-instruct-sc2-concepts
def get_args_command_name(layer: int): """Return the specified layer's command name""" return "__layer{layer}_command".format(layer=layer)
bigcode/self-oss-instruct-sc2-concepts
def flux(im): """Total flux of the image (M00)""" return im.sum()
bigcode/self-oss-instruct-sc2-concepts
def get_all_padj_and_log2FoldChange_keys(keys_list: list, identify: str, split: str = '_') -> dict: """ :param keys_list: 最开始的所有的键列表 :param identify:padj和logkey 的标识符 :param split: 键名的分隔符 :return: {"DK_vs_CT_log2FoldChange": "DK_vs_CT"} """ result = {} for i in keys_list: if str(i...
bigcode/self-oss-instruct-sc2-concepts
def roe(net_income, average_equity): """Computes return on equity. Parameters ---------- net_income : int or float Net income average_equity : int or float Average total equity Returns ------- out : int or float Return on equity """ return net_income / a...
bigcode/self-oss-instruct-sc2-concepts
def param_string_to_dict(param_str, delim='|'): """ Reverse of the dict_to_param_string() function. Note that this will not completely rebuild a dict() after being serialised as a param_string: any '=' or {delim} characters get eaten by dict_to_param_string(). :param param_str: str :return: di...
bigcode/self-oss-instruct-sc2-concepts
def move_drift_to_zero(drift_nm, ref_average=10): """ moves to zero the start of the table :param drift_nm: fxyz table :param ref_average: how many frames to average to get zero :return: shifted table """ assert drift_nm.shape[1] == 4 assert drift_nm.shape[0] > 0 drift_ref = drift_nm...
bigcode/self-oss-instruct-sc2-concepts
import re def find_identity_in_list(elements, identities): """Matches a list of identities to a list of elements. Args: elements: iterable of strings, arbitrary strings to match on. identities: iterable of (string, string), with first string being a regular expression, the second string b...
bigcode/self-oss-instruct-sc2-concepts
import math def polar_coordinates_to_cartesian(distance, relative_angle): """Computes relative x and y for give distance and angle. Can be used to convert radar measurements to relative position.""" # Here +ve x is towards the left but the angle is +ve clockwise. return [-1 * distance * math.sin(relat...
bigcode/self-oss-instruct-sc2-concepts
def diff_renorm(image): """Maps image back into [0,1]. Useful for visualising differences""" scale = 0.5/image.abs().max() image = image*scale image += 0.5 return image
bigcode/self-oss-instruct-sc2-concepts
import math def closed_form_solution(grid_size: int) -> int: """Closed form solution for number of routes through a `grid_size`x`grid_size`grid. Using binomial coefficents in Pascal's triangle. """ return math.factorial(2 * grid_size) // math.factorial(grid_size)**2
bigcode/self-oss-instruct-sc2-concepts
def remove_inner_brackets(message: str) -> str: """Remove the inner brackets i.e., [ or ], from a string, outer brackets are kept. Parameters ---------- message: str The string to remove the inner brackets from. Returns ------- str: A new message without any inner brackets....
bigcode/self-oss-instruct-sc2-concepts
def NSEW_2_bounds(cardinal, order=["minx", "miny", "maxx", "maxy"]): """ Translates cardinal points to xy points in the form of bounds. Useful for converting to the format required for WFS from REST style queries. Parameters ---------- cardinal : :class:`dict` Cardinally-indexed poi...
bigcode/self-oss-instruct-sc2-concepts
def _isNumeric(n): """test if 'n' can be converted for use in numeric calculations""" try: b = float(n) return True except: pass return False
bigcode/self-oss-instruct-sc2-concepts
import re def get_valid_filepath(s: str) -> str: """Convert a string to a safe-to-use string for naming file. Parameters ---------- s : str The given strings Returns ------- str The safe string Note ---- Adapated from django get_valid_filename function: h...
bigcode/self-oss-instruct-sc2-concepts
def pyyaml_path_representer(dumper, instance): """Helper method to dump :class:`~pathlib.Path` in PyYAML.""" return dumper.represent_scalar('Path', f'{instance}')
bigcode/self-oss-instruct-sc2-concepts
def eratosthenes_sieve(n): """Return primes <= n.""" def add_prime(k): """Add founded prime.""" primes.append(k) pos = k + k while pos <= n: numbers[pos] = 1 pos += k numbers = [0] * (n + 1) primes = [2] for i in range(3, n + 1, 2): i...
bigcode/self-oss-instruct-sc2-concepts
import torch def jvp_diff(y, x, v): """Computes a jacobian-vector product J v, aka Rop (Right Operation) This is what forward-mode automatic differentiation directly obtains. The result of the operation can be differentiated. Arguments: y (torch.tensor): output of differentiated function x (t...
bigcode/self-oss-instruct-sc2-concepts
def chomp(x): """Remove any trailing line terminator from 'x' and return that.""" if x.endswith("\r\n"): return x[:-2] if x.endswith("\n") or x.endswith("\r"): return x[:-1] return x
bigcode/self-oss-instruct-sc2-concepts
def pad(values, width): """Format a list of values to a certain width""" values = [ str(data) for data in values ] return ''.join([ data + (' ' * (width - len(data))) for data in values ])
bigcode/self-oss-instruct-sc2-concepts
def get_task_pairs(data_list, task): """Get a list of [input path, output dictionary] pairs where each element of the list has at least `task` as a key in the output dictionary. """ task_pairs = [] for input_file, task_dict in data_list: if task in task_dict.keys(): task_pairs.ap...
bigcode/self-oss-instruct-sc2-concepts
import inspect def get_module_name(file_path): """Returns module name or '' for file at `file_path`""" return inspect.getmodulename(file_path) if file_path else ''
bigcode/self-oss-instruct-sc2-concepts
import tempfile def tmpfile (dir=None, prefix="temp", suffix=None): """Return a temporary file.""" return tempfile.mkstemp(suffix=suffix, prefix=prefix, dir=dir)[1]
bigcode/self-oss-instruct-sc2-concepts
def make_rep(req, body=None): """Utility which creates a reply object based on the headers in the request object.""" rep = { 'head': { 'seq': req['head']['seq'] +1, 'cmd': req['head']['cmd'], 'rSeq': req['head']['seq'] }} if body: rep['body'] = body ...
bigcode/self-oss-instruct-sc2-concepts
import ast from typing import Optional def get_context(node: ast.AST) -> Optional[ast.AST]: """Returns the context or ``None`` if node has no context.""" return getattr(node, 'wps_context', None)
bigcode/self-oss-instruct-sc2-concepts
def format_list2(list1, sfmt = '%16s', nfmt = '%16.8e', delimiter = ','): """ format list of numbers or strings to a delimited string. Parameters ---------- list1 : list of numbers and strings List to convert to string sfmt : str string formatter, ie "%16s" nfmt : str ...
bigcode/self-oss-instruct-sc2-concepts
def guidance_UV(index): """Return Met Office guidance regarding UV exposure based on UV index""" if 0 < index < 3: guidance = "Low exposure. No protection required. You can safely stay outside" elif 2 < index < 6: guidance = "Moderate exposure. Seek shade during midday hours, cover up and we...
bigcode/self-oss-instruct-sc2-concepts
def tree_observation_probability(state, observation): """ Measurement model for a single Tree element for the LatticeForest. Returns a probability of the combination (state, observation). """ measure_correct = 0.9 measure_wrong = 0.5*(1-measure_correct) if state != observation: retur...
bigcode/self-oss-instruct-sc2-concepts
def hex_to_dec(val): """Converts hexademical string to integer""" return int(val, 16)
bigcode/self-oss-instruct-sc2-concepts
import re def get_valid_filename(s): """ Return the given string converted to a string that can be used for a clean filename. Remove leading and trailing spaces; convert other spaces to underscores; and remove anything that is not an alphanumeric, dash, underscore, or dot. >>> get_valid_filena...
bigcode/self-oss-instruct-sc2-concepts
def is_json(fname): """ Returns True for string, enclosed with '[' ']', False else """ if str(fname) and (str(fname)[0] == "[") and (str(fname)[-1] == "]"): return True return False
bigcode/self-oss-instruct-sc2-concepts
def ensure_all_mixing_vars_are_in_the_name_dict(mixing_vars, name_dict, ind_var_names): """ Ensures that all of the variables listed in `mixing_vars` are present in `ind_var_names`. Raises a helpful ValueError if...
bigcode/self-oss-instruct-sc2-concepts
def countwhile(predicate, iterable): """ return count of leading characters that satisfy the predicate """ count = 0 for character in iterable: if predicate(character): count += 1 else: break return count
bigcode/self-oss-instruct-sc2-concepts
def auth_str_equal(provided, known): """Constant-time string comparison. :params provided: the first string :params known: the second string :returns: True if the strings are equal. This function takes two strings and compares them. It is intended to be used when doing a comparison for authe...
bigcode/self-oss-instruct-sc2-concepts
import re def get_header(header): """ Extract key parts of image headers from the header of fabio-opened file and return them as a list. A list of wavelength, pixel size, detector distance, the x and y beam center, and exposure time are returned in that order. """ h = header['_array_data.header_contents'] wavele...
bigcode/self-oss-instruct-sc2-concepts
import json def output_fn(predictions, content_type): """Post-process and serialize model output to API response""" print('result:', predictions) res = predictions.cpu().numpy().tolist() return json.dumps(res)
bigcode/self-oss-instruct-sc2-concepts
def slice_at_axis(sl, axis): """ Construct tuple of slices to slice an array in the given dimension. Parameters ---------- sl : slice The slice for the given dimension. axis : int The axis to which `sl` is applied. All other dimensions are left "unsliced". Returns ...
bigcode/self-oss-instruct-sc2-concepts
def unit_range(arr, data_min=None, data_max=None, samples_in='row'): """ Normalize the data to have unit range. Return the normalized data, and the min, and max used. Data is assumed to be in row samples If data is arranged in column samples, use samples_in='col' Computes norm_arr = (arr - d...
bigcode/self-oss-instruct-sc2-concepts
from typing import Tuple def get_file_type(image_path: str) -> Tuple[str, str]: """ Return the image file types. Return ------------ [file_ext, file_type] file_ext: .png, .jpeg, .jpg etc. file_type: this is the MIME file type e.g. image/png """ file_ext = image_path.split(...
bigcode/self-oss-instruct-sc2-concepts
def hyphenate(value, arg): """Concatenate value and arg with hyphens as separator, if neither is empty""" return "-".join(filter(None, [str(value), str(arg)]))
bigcode/self-oss-instruct-sc2-concepts
import inspect def outer_args(skip_self=True) -> dict: """Get the arguments of the func within which this function is called. Args: skip_self (bool): True: skip the argument named `self` False: doesn't skip the argument named `self` """ currframe = inspect.currentframe...
bigcode/self-oss-instruct-sc2-concepts
def numwrap(n, nmin, nmax): """最小値、最大値の範囲内でnの値を返す。 n: 範囲内で調整される値。 nmin: 最小値。 nmax: 最大値。 """ if n < nmin: n = nmin elif n > nmax: n = nmax return n
bigcode/self-oss-instruct-sc2-concepts
def _GenerateMapperConstructor(transformer_class_name): """ Public constructor generation for the mapper. """ code = [ "\n\npublic Mapper({0} parent, DataViewSchema inputSchema) :".format(transformer_class_name), "\nbase(parent.Host.Register(nameof(Mapper)), inputSchema, parent)", ...
bigcode/self-oss-instruct-sc2-concepts
import math def _non_finite(num): """Is this number not finite?""" return math.isnan(num) or math.isinf(num)
bigcode/self-oss-instruct-sc2-concepts
def _FormatProjectIdentifierForTransfers(project_reference, location): """Formats a project identifier for data transfers. Data transfer API calls take in the format projects/(projectName), so because by default project IDs take the format (projectName), add the beginning format to perform data transfer comman...
bigcode/self-oss-instruct-sc2-concepts
import math def offset_point_with_distance_and_bearing(lat, lon, distance, bearing): """ Get the new lat long (in degrees) given current point (lat/lon), distance and bearing returns: new lat/long """ # Earth's radius in meters radius = 6378137 # convert the lat long from degree to radia...
bigcode/self-oss-instruct-sc2-concepts
def domain(x, y, s_w, s_h): """ The function estimates the rectangle that includes the given point. Arguments: x and y coordinates of the point and width and height of the screen Return: integer 0 <= n <= 5 """ if x < s_w / 3: return 0 if y < s_h / 2 else 3 if...
bigcode/self-oss-instruct-sc2-concepts
def _merge(iterable): """Merge multiple items into a single one separating with a newline""" return "\n".join(iterable)
bigcode/self-oss-instruct-sc2-concepts