seed
stringlengths
1
14k
source
stringclasses
2 values
def right_pad(xs, min_len, pad_element): """ Appends `pad_element`s to `xs` so that it has length `min_len`. No-op if `len(xs) >= min_len`. """ return xs + [pad_element] * (min_len - len(xs))
bigcode/self-oss-instruct-sc2-concepts
def get_lids(f): """get identifiers that specify an absolute location (i.e. start with '/')""" lids={} for ns in f.ddef.keys(): lids[ns] = [] structures = f.ddef[ns]['structures'] for id in structures: if id[0] == '/': lids[ns].append(id) return lids
bigcode/self-oss-instruct-sc2-concepts
def real2complex(rfield): """ convert raw qg_model output to complex numpy array suppose input has shape psi(time_step (optional), real_and_imag, ky, kx, z(optional)) """ if rfield.shape[-2]+1 == 2*rfield.shape[-3]: return rfield[...,0,:,:,:]+1j*rfield[...,1,:,:,:] elif rfield.shape[-1]+1 == 2*rfield.shape[-2]: return rfield[...,0,:,:]+1j*rfield[...,1,:,:] else: raise NotImplementedError('Unrecognized field type')
bigcode/self-oss-instruct-sc2-concepts
def point_from_pose(pose): """get the origin point from a pose Parameters ---------- pose : Pose [description] Returns ------- Point, np array of three floats [description] """ return pose[0]
bigcode/self-oss-instruct-sc2-concepts
def strip_spaces(fields): """ Strip spaces and newline characters from a list of strings. Inputs ------ fields : list of strings Returns ------- list : modified input list where the characters ' \n' have been stripped Examples -------- strip_spaces(['hi ', 'zeven 1', 'yo\n']) """ # id(fields[:]) ≠ id(fields). fields[:] creates a new copy to allow # me to edit fields inside the loop (Remember Python passes by reference) # strip out spaces for element in fields[:]: # pop out the first element fields.pop(0) # append the first element back after stripping fields.append(element.strip(' \n')) # \n only needed for last element return fields
bigcode/self-oss-instruct-sc2-concepts
def readable_keyword(s): """Return keyword with only the first letter in title case.""" if s and not s.startswith("*") and not s.startswith("["): if s.count("."): library, name = s.rsplit(".", 1) return library + "." + name[0].title() + name[1:].lower() else: return s[0].title() + s[1:].lower() else: return s
bigcode/self-oss-instruct-sc2-concepts
def _default_bounds(signal): """Create a default list of bounds for a given signal description If no bounds were specified, they default to [0, 0]: ['name', 0, 0, 0, 0] If no bits of the port were picked, the whole port is picked: ['name', x, y, x, y] A signal may use a slice of a port This example uses the 6th and the 7th bits of the 16-bit port: ['example_2_of_16', 15, 0, 7, 6] :param signal can be one of: 'port_name' ['port_name', upper_bound, lower_bound] ['port_name', upper_bound, lower_bound, upper_picked, lower_picked] :return: ['port_name', upper_bound, lower_bound, upper_picked, lower_picked] """ # there's just the name if isinstance(signal, str): return (signal, 0, 0, 0, 0) else: # there's just the name in a list if len(signal) == 1: return signal + [0, 0, 0, 0] # there's the name and bounds if len(signal) == 3: return signal + [signal[1], signal[2]] return signal
bigcode/self-oss-instruct-sc2-concepts
def accept_objects(func): """This decorator can be applied to functions whose first argument is a list of x, y, z points. It allows the function to also accept a list of objects which have x(), y() and z() methods instead.""" def new_func(objects, *args, **kwargs): try: points = [(x, y, z) for x, y, z in objects] except TypeError: points = [(obj.x(), obj.y(), obj.z()) for obj in objects] return func(points, *args, **kwargs) new_func.__name__ = func.__name__ new_func.__doc__ = func.__doc__ return new_func
bigcode/self-oss-instruct-sc2-concepts
def _filter_rows(df, min_ct=0): """Filter out rows with counts less than the minimum.""" row_sums = df.T.sum() filtered_df = df[row_sums >= min_ct] return filtered_df
bigcode/self-oss-instruct-sc2-concepts
def get_last_id(list_of_id, width): """ Gets the last identifier given a list of identifier. :param list_of_id: list of identifier :param width: the width of the identifier. :return: the last identifier. """ last_number = 0 for identifier in list_of_id: if identifier == "": last_number = 0 else: last_number = max(last_number, int(identifier.lstrip('0'))) last = (width - len(str(last_number))) * "0" + str(last_number) return last
bigcode/self-oss-instruct-sc2-concepts
def get_list_by_separating_strings(list_to_be_processed, char_to_be_replaced=",", str_to_replace_with_if_empty=None): """ This function converts a list of type: ['str1, str2, str3', 'str4, str5, str6, str7', None, 'str8'] to: [['str1', 'str2', 'str3'], ['str4', 'str5', 'str6', 'str7'], [], ['str8']] """ final_list =[] if list_to_be_processed is not None and list_to_be_processed is not False and list_to_be_processed != "": for i in range(0, len(list_to_be_processed)): if list_to_be_processed[i] is None or list_to_be_processed[i] is False or list_to_be_processed[i] == "": temp_list = [] else: if list_to_be_processed[i] == "": list_to_be_processed[i] = str_to_replace_with_if_empty temp_list = list_to_be_processed[i].split(char_to_be_replaced) for j in range(0, len(temp_list)): temp_list[j] = temp_list[j].strip() final_list.append(temp_list) return final_list
bigcode/self-oss-instruct-sc2-concepts
import pathlib def get_configuration_path() -> str: """Returns project root folder.""" return str(pathlib.Path(__file__).parent.parent.parent) + '/configuration/conf.ini'
bigcode/self-oss-instruct-sc2-concepts
def try_int(s, *args): """Convert to integer if possible.""" #pylint: disable=invalid-name try: return int(s) except (TypeError, ValueError): return args[0] if args else s
bigcode/self-oss-instruct-sc2-concepts
def datetime_adapter(obj, request): """Json adapter for datetime objects.""" try: return obj.strftime('%d/%m/%Y %H:%M:%S') except: return obj.strftime('%d/%m/%Y')
bigcode/self-oss-instruct-sc2-concepts
def validate_input_data(data): """ Takes in user input data Checks if all the keys are provided Raise key error if a key is missing Returns a validated data in a dict format """ cleaned_data = {} for key in data: if data[key] is None: assert False, key + ' key is missing' else: cleaned_data[key] = data[key] return cleaned_data
bigcode/self-oss-instruct-sc2-concepts
def get_delegated_OTP_keys(permutation, x_key, z_key, num_qubits=14, syndrome_cnots = [[14, 0], [14, 2], [14, 4], [14, 6], [15, 1], [15, 2], [15, 5], [15, 6], [16, 3], [16, 4], [16, 5], [16, 6], [17, 7], [17, 9], [17, 11], [17, 13], [18, 8], [18, 9], [18, 12], [18, 13], [19, 10], [19, 11], [19, 12], [19, 13]]): """ Get delegated, post-processed, classical one-time pad keys for a program Parameters: permutation ([int]): permutation key x_key ([int]): X part of the non-delegated one-time pad key z_key ([int]): Z part of the non-delegated one-time pad key num_qubits (int): number of data qubits syndrome_cnots ([[int,int]]): all cnot gates used to derive error syndromes Returns: delegated_x_key ([int]): classically processed and delegated X part of one-time pad key delegated_z_key ([int]): classically processed and delegated Z part of one-time pad key """ permuted_cnots = [] for gate in syndrome_cnots: permuted_cnots.append([gate[0],permutation.index(gate[1])]) new_x_key = x_key[:] new_z_key = z_key[:] for cnot in permuted_cnots: a = new_x_key[cnot[0]] b = new_z_key[cnot[0]] c = new_x_key[cnot[1]] d = new_z_key[cnot[1]] new_x_key[cnot[0]] = a new_z_key[cnot[0]] = b+d new_x_key[cnot[1]] = a+c new_z_key[cnot[1]] = d #hadamard operator delegation for i in range(num_qubits,num_qubits + int(num_qubits/7*3)): new_x_key[i], new_z_key[i] = new_z_key[i], new_x_key[i] delegated_x_key = [i%2 for i in new_x_key] delegated_z_key = [i%2 for i in new_z_key] return delegated_x_key, delegated_z_key
bigcode/self-oss-instruct-sc2-concepts
import requests def get_user_api_token(logger, username, password): """ Generate iAuditor API Token :param logger: the logger :return: API Token if authenticated else None """ generate_token_url = "https://api.safetyculture.io/auth" payload = "username=" + username + "&password=" + password + "&grant_type=password" headers = { 'content-type': "application/x-www-form-urlencoded", 'cache-control': "no-cache", } response = requests.request("POST", generate_token_url, data=payload, headers=headers) if response.status_code == requests.codes.ok: return response.json()['access_token'] else: logger.error('An error occurred calling ' + generate_token_url + ': ' + str(response.json())) return None
bigcode/self-oss-instruct-sc2-concepts
from typing import List from typing import Any import fnmatch def get_elements_fnmatching(l_elements: List[Any], s_fnmatch_searchpattern: str) -> List[str]: """get all elements with type str which are matching the searchpattern >>> get_elements_fnmatching([], 'a*') [] >>> get_elements_fnmatching(['abc', 'def', 1, None], 'a*') ['abc'] """ if not l_elements: return l_elements ls_results: List[str] = [] for s_element in l_elements: if isinstance(s_element, str): if fnmatch.fnmatch(s_element, s_fnmatch_searchpattern): ls_results.append(s_element) return ls_results
bigcode/self-oss-instruct-sc2-concepts
def resolve_keywords_array_string(keywords: str): """ Transforms the incoming keywords string into its single keywords and returns them in a list Args: keywords(str): The keywords as one string. Sometimes separates by ',', sometimes only by ' ' Returns: The keywords in a nice list """ ret_list = [] if keywords is not None: # first make sure no commas are left keywords = keywords.replace(",", " ") key_list = keywords.split(" ") for key in key_list: key = key.strip() if len(key) > 0: ret_list.append(key) return ret_list
bigcode/self-oss-instruct-sc2-concepts
import re def get_test_keys(data): """Return case keys from report string. Args: data(str): test case results Returns: list[str]: list of report keys """ keys_rules = re.compile('<success>(.*?)</success>') return keys_rules.findall(data)
bigcode/self-oss-instruct-sc2-concepts
def get_return_assign(return_type: str) -> str: """ int foo() => 'int r =' void foo() => '' """ s = return_type.strip() if 'void' == s: return '' return '{} r ='.format(s)
bigcode/self-oss-instruct-sc2-concepts
def get_state_root(spec, state, slot) -> bytes: """ Return the state root at a recent ``slot``. """ assert slot < state.slot <= slot + spec.SLOTS_PER_HISTORICAL_ROOT return state.state_roots[slot % spec.SLOTS_PER_HISTORICAL_ROOT]
bigcode/self-oss-instruct-sc2-concepts
def apply_uv_coverage(Box_uv, uv_bool): """Apply UV coverage to the data. Args: Box_uv: data box in Fourier space uv_bool: mask of measured baselines Returns: Box_uv """ Box_uv = Box_uv * uv_bool return Box_uv
bigcode/self-oss-instruct-sc2-concepts
import torch def box_cxcywh_to_xyxy(x: torch.Tensor): """ Change bounding box format: w --------- xy------- | | | | h | xy | --> | | | | | | --------- -------xy """ x_c, y_c, w, h = x.unbind(1) b = [(x_c - 0.5 * w), (y_c - 0.5 * h), (x_c + 0.5 * w), (y_c + 0.5 * h)] return torch.stack(b, dim=1)
bigcode/self-oss-instruct-sc2-concepts
def validate_extra(value: dict, context: dict = {}) -> dict: """ Default extra validator function. Can be overriden by providing a dotted path to a function in ``SALESMAN_EXTRA_VALIDATOR`` setting. Args: value (str): Extra dict to be validated context (dict, optional): Validator context data. Defaults to {}. Raises: ValidationError: In case data is not valid Returns: dict: Validated value """ return value
bigcode/self-oss-instruct-sc2-concepts
def is_timezone_aware(value): """Check if a datetime is time zone aware. `is_timezone_aware()` is the inverse of `is_timezone_naive()`. :param value: A valid datetime object. :type value: datetime.datetime, datetime.time :returns: bool -- if the object is time zone aware. :raises: TypeError .. versionchanged:: 0.4.0 ``TypeError`` is raised .. versionadded:: 0.3.0 """ if not hasattr(value, 'tzinfo'): message = "'{0}' object is not a valid time." raise TypeError(message.format(type(value).__name__)) return not (value.tzinfo is None or value.tzinfo.utcoffset(value) is None)
bigcode/self-oss-instruct-sc2-concepts
def clear_object_store( securityOrigin: str, databaseName: str, objectStoreName: str ) -> dict: """Clears all entries from an object store. Parameters ---------- securityOrigin: str Security origin. databaseName: str Database name. objectStoreName: str Object store name. """ return { "method": "IndexedDB.clearObjectStore", "params": { "securityOrigin": securityOrigin, "databaseName": databaseName, "objectStoreName": objectStoreName, }, }
bigcode/self-oss-instruct-sc2-concepts
def bytes_to_block(block_size: int, i: int) -> slice: """ Given the block size and the desired block index, return the slice of bytes from 0 to the end of the given block. :param block_size: The block size. :param i: The block index. :return: slice of bytes from 0 to the end of the specified block index. """ return slice(0, block_size * (i + 1))
bigcode/self-oss-instruct-sc2-concepts
def extended_euclid_xgcd(a, b): """ Returns d, u, v = xgcd(a,b) Where d = ua + vb = gcd(a, b) """ s = 0 old_s = 1 t = 1 old_t = 0 r = b old_r = a while r != 0: quotient = old_r // r old_r, r = r, old_r - quotient * r old_s, s = s, old_s - quotient * s old_t, t = t, old_t - quotient * t d, u, v = old_r, old_s, old_t return d, u, v
bigcode/self-oss-instruct-sc2-concepts
def sum_parameters(param): """ Sums the equation parameters which have the same exponent and polynomial term. (a, ni, bi) and (c, ni, bi) become (a + c, ni, bi). Parameters ----------- param: list list of tuples (Ai, ni, Bi) Returns ---------- out: list list of tuples (Ci, ni, Bi). """ # Dictionary of (ni, Bi): Ai Ai = {} for x in param: try: Ai[x[1:]] += x[0] except KeyError: Ai[x[1:]] = x[0] return [(Ai[x], x[0], x[1]) for x in Ai]
bigcode/self-oss-instruct-sc2-concepts
def is_continuation(val): """Any subsequent byte is a continuation byte if the MSB is set.""" return val & 0b10000000 == 0b10000000
bigcode/self-oss-instruct-sc2-concepts
def number_keys(a_dictionary): """Return the number of keys in a dictionary.""" return (len(a_dictionary))
bigcode/self-oss-instruct-sc2-concepts
def true_false_converter(value): """ Helper function to convert booleans into 0/1 as SQlite doesn't have a boolean data type. Converting to strings to follow formatting of other values in the input. Relying on later part of pipeline to change to int. """ if value == "True": return '1' elif value == "False": return '0' else: return value
bigcode/self-oss-instruct-sc2-concepts
def celcius_2_kelvin(x): """Convert celcius to kelvin.""" return x + 273.15
bigcode/self-oss-instruct-sc2-concepts
from typing import Dict from typing import Union from typing import List from typing import Any from functools import reduce def getitems(obj: Dict, items: Union[List, str], default: Any = None) -> Any: """ 递归获取数据 注意:使用字符串作为键路径时,须确保 Key 值均为字符串 :param obj: Dict 类型数据 :param items: 键列表:['foo', 'bar'],或者用 "." 连接的键路径: ".foo.bar" 或 "foo.bar" :param default: 默认值 :return: value """ if not isinstance(obj, dict): raise TypeError('Dict object support only!') if isinstance(items, str): items = items.strip(".").split(".") try: return reduce(lambda x, i: x[i], items, obj) except (IndexError, KeyError, TypeError): return default
bigcode/self-oss-instruct-sc2-concepts
def compute_range(word_size,bits_per_sample): """ Get starting positions in word for groups of bits_per_sample bits. Notes ----- | | **Example:** | | word_size=32 | bits_per_sample=4 | list(compute_range(word_size,bits_per_sample)) | >>> [0, 4, 8, 12, 16, 20, 24, 28] """ return(range(0,word_size,bits_per_sample))
bigcode/self-oss-instruct-sc2-concepts
def convert_to_bool(x) -> bool: """Convert string 'true' to bool.""" return x == "true"
bigcode/self-oss-instruct-sc2-concepts
def _stretch_string(string, length): """Stretch the game title so that each game takes equal space. :param string: the string to stretch :type string: str :param length: the length that the string needs to be stretched to :type length: int :return: the stretched string :rtype: str """ for _ in range(length-len(string)): string += " " return string
bigcode/self-oss-instruct-sc2-concepts
import json def load_json_file(jfile): """ Load json file given filename """ with open(jfile) as handle: j = json.load(handle) return j
bigcode/self-oss-instruct-sc2-concepts
def is_vowel(char: str) -> bool: """ returns True if the character is vowel else False >>> is_vowel('A') True >>> is_vowel('e') True >>> is_vowel('f') False """ vowels = ["A", "E", "I", "O", "U", "a", "e", "i", "o", "u"] # Check for empty string if not char: return False return char[0] in vowels
bigcode/self-oss-instruct-sc2-concepts
def bisect_map(mn, mx, function, target): """ Uses binary search to find the target solution to a function, searching in a given ordered sequence of integer values. Parameters ---------- seq : list or array, monotonically increasing integers function : a function that takes a single integer input, which monotonically decreases over the range of seq. target : the target value of the function Returns ------- value : the input value that yields the target solution. If there is no exact solution in the input sequence, finds the nearest value k such that function(k) <= target < function(k+1). This is similar to the behavior of bisect_left in the bisect package. If even the first, leftmost value of seq does not satisfy this condition, -1 is returned. """ if function([mn]) < target or function([mx]) > target: return -1 while 1: if mx == mn + 1: return mn m = (mn + mx) / 2 value = function([m])[0] if value > target: mn = m elif value < target: mx = m else: return m
bigcode/self-oss-instruct-sc2-concepts
def b(s): """ bytes/str/int/float -> bytes """ if isinstance(s, bytes): return s elif isinstance(s, (str,int,float)): return str(s).encode("utf-8") else: raise TypeError(s)
bigcode/self-oss-instruct-sc2-concepts
def p2q(plist, do_min=1, verb=1): """convert list of p-value to a list of q-value, where q_i = minimum (for m >= i) of N * p_m / m if do min is not set, simply compute q-i = N*p_i/i return q-values in increasing significance (i.e. as p goes large to small, or gets more significant) """ q = plist[:] q.sort() N = len(q) # work from index N down to 0 (so index using i-1) min = 1 for i in range(N,0,-1): ind = i-1 q[ind] = N * q[ind] / i if do_min: if q[ind] < min: min = q[ind] if min < q[ind]: q[ind] = min # and flip results q.reverse() return q
bigcode/self-oss-instruct-sc2-concepts
from pathlib import Path def get_packages(package): """ Return root package and all sub-packages. """ return [str(path.parent) for path in Path(package).glob("**/__init__.py")]
bigcode/self-oss-instruct-sc2-concepts
import base64 def to_base64(full_path): """ Return the base64 content of the file path :param file_path: Path to the file to read :type file_path: str :return: File content encoded in base64 :rtype: str """ with open(full_path, "rb") as bin_file: return base64.b64encode(bin_file.read()).decode("ascii")
bigcode/self-oss-instruct-sc2-concepts
import time def get_timestamp(length=13): """ get current timestamp string >>> len(str(int(get_timestamp(10)))) 10 :param length: length of timestamp, can only between 0 and 16 :return: """ if isinstance(length, int) and 0 < length < 17: return int("{:.6f}".format(time.time()).replace(".", "")[:length]) raise ValueError("timestamp length can only between 0 and 16.")
bigcode/self-oss-instruct-sc2-concepts
def construct_user_data(user=None): """Return dict with user data The returned keys are the bare minimum: username, first_name, last_name and email. No permissions or is_superuser flags! """ user_data = {} for key in ["username", "first_name", "last_name", "email"]: user_data[key] = getattr(user, key) return user_data
bigcode/self-oss-instruct-sc2-concepts
def get_books_by_author(args, books): """ Get books whose author name contains the arguments :param args: args object containing all arguments :param books: A list of book objects read from csv file :return: A dictionary with matched authors' names as key and a list of their book objects as value. """ if not args.author: return None author_book_dict = {} # Create a key value pair for every author that matches the arguments for arg in args.author: for book in books: if arg.lower() in book.author.lower(): if not book.author in author_book_dict.keys(): author_book_dict[book.author] = [] # Fill in the books written by every author in the dictionary for book in books: if book.author in author_book_dict.keys(): author_book_dict[book.author].append(book) return author_book_dict
bigcode/self-oss-instruct-sc2-concepts
def parse_clusters(cluster_file): """ expects one line per cluster, tab separated: cluster_1_rep member_1_1 member 1_2 ... cluster_2_rep member_2_1 member_2_2 ... """ cluster_dict = {} with open(cluster_file) as LINES: for line in LINES: genes = line.strip().split("\t") rep = genes[0] for gene in genes: cluster_dict[gene] = rep return cluster_dict
bigcode/self-oss-instruct-sc2-concepts
def _new_array(ctype, size): """Create an ctypes.Array object given the ctype and the size of array.""" return (size * ctype)()
bigcode/self-oss-instruct-sc2-concepts
import json def to_json(**kwargs): """Convert input arguments to a formatted JSON string as expected by the EE API. """ return {'jsonRequest': json.dumps(kwargs)}
bigcode/self-oss-instruct-sc2-concepts
def _masked_loss(loss, mask, eps=1e-8): """ Average the loss only for the visible area (1: visible, 0: occluded) """ return (loss * mask).sum() / (mask.sum() + eps)
bigcode/self-oss-instruct-sc2-concepts
def _roundn(num, n): """Round to the nearest multiple of n greater than or equal to the given number. EMF records are required to be aligned to n byte boundaries.""" return ((num + n - 1) // n) * n
bigcode/self-oss-instruct-sc2-concepts
import re def _split_by_punctuation(chunks, puncs): """Splits text by various punctionations e.g. hello, world => [hello, world] Arguments: chunks (list or str): text (str) to split puncs (list): list of punctuations used to split text Returns: list: list with split text """ if isinstance(chunks, str): out = [chunks] else: out = chunks for punc in puncs: splits = [] for t in out: # Split text by punctuation, but not embedded punctuation. E.g. # Split: "Short sentence. Longer sentence." # But not at: "I.B.M." or "3.424", "3,424" or "what's-his-name." splits += re.split(r'(?<!\.\S)' + punc + r'\s', t) out = splits return [t.strip() for t in out]
bigcode/self-oss-instruct-sc2-concepts
def filename_from_path(full_path): """ given file path, returns file name (with .xxx ending) """ for i in range(len(full_path)): j = len(full_path) - 1 - i if full_path[j] == "/" or full_path[j] == "\\": return full_path[(j + 1):]
bigcode/self-oss-instruct-sc2-concepts
def type_or_none(default_type): """ Convert the string 'None' to the value `None`. >>> f = type_or_none(int) >>> f(None) is None True >>> f('None') is None True >>> f(123) 123 """ def f(value): if value is None or value == 'None': return None return default_type(value) return f
bigcode/self-oss-instruct-sc2-concepts
import random import string def random_string() -> str: """ Generate a random string """ k = random.randint(5, 10) return ''.join(random.choices(string.ascii_letters + string.digits, k=k))
bigcode/self-oss-instruct-sc2-concepts
def get_dev_raw_data_source(pipeline_builder, raw_data, data_format='JSON', stop_after_first_batch=False): """ Adds a 'Dev Raw Data Source' stage to pipeline_builder and sets raw_data, data_format and stop_after_first_batch properties of that stage. Returns the added stage""" dev_raw_data_source = pipeline_builder.add_stage('Dev Raw Data Source') dev_raw_data_source.data_format = data_format dev_raw_data_source.raw_data = raw_data dev_raw_data_source.stop_after_first_batch = stop_after_first_batch return dev_raw_data_source
bigcode/self-oss-instruct-sc2-concepts
import colorsys import random def random_colors(N, bright=False): """ Generate random colors. To get visually distinct colors, generate them in HSV space then convert to RGB. """ brightness = 1.0 if bright else 0.7 hsv = [(i / N, 1, brightness) for i in range(N)] colors = list(map(lambda c: colorsys.hsv_to_rgb(*c), hsv)) random.shuffle(colors) return colors
bigcode/self-oss-instruct-sc2-concepts
def clean(s): """ Attempt to render the (possibly extracted) string as legible as possible. """ result = s.strip().replace("\n", " ") result = result.replace("\u00a0", " ") # no-break space result = result.replace("\u000c", " ") # vertical tab while " " in result: result = result.replace(" ", " ") return result
bigcode/self-oss-instruct-sc2-concepts
def compute_Obj(Y, A, K): # main objective """ sum_{j=2}^K of (Y_{:,j})^TA(Y_{:,j}) / ((Y_{:,j})^T(Y_{:,j})) """ num, de = 0, 0 for i in range(K-1): num += (Y[:,i+1].T).dot(A.dot(Y[:,i+1])) de += Y[:,i+1].T@Y[:,i+1] return (num / de)
bigcode/self-oss-instruct-sc2-concepts
def indexOfLargestInt(listOfInts): """ return index of largest element of non-empty list of ints, or False otherwise That is, return False if parameter is an empty list, or not a list parameter is not a list consisting only of ints By "largest", we mean a value that is no smaller than any other value in the list. There may be more than one instance of that value. Example: in [7,3,7], 7 is largest By "index", we mean the subscript that will select that item of the list when placed in [] Since there can be more than one largest, we'll return the index of the first such value in those cases, i.e. the one with the lowest index. >>> indexOfLargestInt([]) False >>> indexOfLargestInt('foo') False >>> indexOfLargestInt([3,5,4.5,6]) False >>> indexOfLargestInt([40]) 0 >>> indexOfLargestInt([-90,40,70,80,20]) 3 >>> indexOfLargestInt([10,30,50,20,50]) 2 >>> """ if type(listOfInts)!=list or listOfInts==[]: return False # Now we know there is at least one item in the list. # We make an initial assumption that this item will be the largest. # We then check every other item in the list indexOfMaxSoFar = 0 # the one in position zero is the first candidate # Note: we have to start from 0 because we need to check the type # of element[0] to see if it is an int. Otherwise, we could start from 1 for i in range(0,len(listOfInts)): # all indexes in the list if type(listOfInts[i])!=int: # make sure it is an int return False if listOfInts[i] > listOfInts[indexOfMaxSoFar]: # compare new item indexOfMaxSoFar = i # we have a new candidate # Now we've gone through the entire list. If some other index were that # of a larger int, we would have changed indexOfMaxSoFar to that. So # what we are left with must be the index of the largest one. return indexOfMaxSoFar
bigcode/self-oss-instruct-sc2-concepts
from typing import Optional from pathlib import Path def relative_example_path(example_id: str, data_name: Optional[str] = None): """ Returns the relative path from a train or test directory to the data file for the given example_id and data_name. """ prefix = data_name + "_" if data_name else "" return ( Path(example_id[0]) / example_id[1] / example_id[2] / (prefix + example_id + ".npy") )
bigcode/self-oss-instruct-sc2-concepts
def rshift(val, n): """ Python equivalent to TypeScripts >>> operator. @see https://stackoverflow.com/questions/5832982/how-to-get-the-logical-right-binary-shift-in-python """ return (val % 0x100000000) >> n
bigcode/self-oss-instruct-sc2-concepts
def is_sale(this_line): """Determine whether a given line describes a sale of cattle.""" is_not_succinct = len(this_line.split()) > 3 has_price = '$' in this_line return has_price and is_not_succinct
bigcode/self-oss-instruct-sc2-concepts
import itertools def sparse_dict_from_array(array, magnitude_threshold=0): """Converts a array to a dict of nonzero-entries keyed by index-tuple.""" ret = {} for index_tuple in itertools.product(*(map(range, array.shape))): v = array[index_tuple] if abs(v) > magnitude_threshold: ret[index_tuple] = v return ret
bigcode/self-oss-instruct-sc2-concepts
from typing import Literal import unicodedata def unicode(text: str, *, form: Literal["NFC", "NFD", "NFKC", "NFKD"] = "NFC") -> str: """ Normalize unicode characters in ``text`` into canonical forms. Args: text form: Form of normalization applied to unicode characters. For example, an "e" with accute accent "´" can be written as "e´" (canonical decomposition, "NFD") or "é" (canonical composition, "NFC"). Unicode can be normalized to NFC form without any change in meaning, so it's usually a safe bet. If "NFKC", additional normalizations are applied that can change characters' meanings, e.g. ellipsis characters are replaced with three periods. See Also: https://docs.python.org/3/library/unicodedata.html#unicodedata.normalize """ return unicodedata.normalize(form, text)
bigcode/self-oss-instruct-sc2-concepts
def without_duplicates(args): """ Removes duplicated items from an iterable. :param args: the iterable to remove duplicates from :type args: iterable :return: the same iterable without duplicated items :rtype: iterable :raise TypeError: if *args* is not iterable """ if hasattr(args, '__iter__') and not isinstance(args, str): if args: return type(args)(set(args)) else: return args else: raise TypeError("Expected iterable, got {args_type} insted".format(args_type=type(args)))
bigcode/self-oss-instruct-sc2-concepts
def create_vulnerability_dictionary(qid, title, ip, name, category, severity, solution, diagnosis, consequence): """ Creates a vulnerability dictionary. :param qid: integer Qualys ID of the vulnerability. :param title: string, title of the vulnerability. :param ip: list of IP adresses (strings) affected by vulnerability. :param name: hostname associated to the IP :param category: string, category of vulnerability. :param severity: integer, severity level of the vulnerability. :param solution: string, how to fix the vulnerability. :param diagnosis: string, how the vulnerability was detected. :param consequence: string, consequences of the vulnerability. :return: vulnerability dictionary with the entered values. """ return { 'qid': qid, 'title': title, 'hosts': [{'ip': ip, 'name': name}], 'category': category, 'severity': severity, 'solution': solution, 'diagnosis': diagnosis, 'consequence': consequence, }
bigcode/self-oss-instruct-sc2-concepts
def get_page_text(soup): """Return all paragraph text of a webpage in a single string. """ if soup is None: return '' paragraphs = [para.text for para in soup.select('p')] text = '\n'.join(paragraphs) return text
bigcode/self-oss-instruct-sc2-concepts
import pickle def read_pickle(file_name): """ Reads a data dictionary from a pickled file. Helper function for curve and surface ``load`` method. :param file_name: name of the file to be loaded :type file_name: str :return: data dictionary :rtype: dict """ # Try opening the file for reading try: with open(file_name, 'rb') as fp: # Read and return the pickled file impdata = pickle.load(fp) return impdata except IOError: # Raise an exception on failure to open file raise IOError("File " + str(file_name) + " cannot be opened for reading.")
bigcode/self-oss-instruct-sc2-concepts
def get_appliance_dns( self, ne_id: str, cached: bool, ) -> dict: """Get DNS server IP addresses and domain configurations from Edge Connect appliance .. list-table:: :header-rows: 1 * - Swagger Section - Method - Endpoint * - dns - GET - /resolver/{neId}?cached={cached} :param ne_id: Appliance id in the format of integer.NE e.g. ``3.NE`` :type ne_id: str :param cached: ``True`` retrieves last known value to Orchestrator, ``False`` retrieves values directly from Appliance :type cached: bool :return: Returns dictionary of appliance DNS configuration \n * keyword **domain_search** (`dict`): DNS search domains \n * keyword **1** (`dict, optional`): Primary Domain \n * keyword **self** (`int`): 1 * keyword **domainname** (`str`): Search domain * keyword **2** (`dict, optional`): Secondary Domain \n * keyword **self** (`int`): 2 * keyword **domainname** (`str`): Search domain * keyword **3** (`dict, optional`): Tertiary Domain \n * keyword **self** (`int`): 3 * keyword **domainname** (`str`): Search domain * keyword **nameserver** (`dict`): DNS server \n * keyword **1** (`dict, optional`): Primary DNS server \n * keyword **self** (`int`): 1 * keyword **address** (`str`): IP address of DNS server * keyword **srcinf** (`str`): Source interface * keyword **vrf_id** (`int`): VRF ID number, e.g. ``0`` * keyword **2** (`dict, optional`): Secondary DNS server \n * keyword **self** (`int`): 2 * keyword **address** (`str`): IP address of DNS server * keyword **srcinf** (`str`): Source interface * keyword **vrf_id** (`int`): VRF ID number, e.g. ``0`` * keyword **3** (`dict, optional`): Tertiary DNS server \n * keyword **self** (`int`): 3 * keyword **address** (`str`): IP address of DNS server * keyword **srcinf** (`str`): Source interface * keyword **vrf_id** (`int`): VRF ID number, e.g. ``0`` :rtype: dict """ return self._get("/resolver/{}?cached={}".format(ne_id, cached))
bigcode/self-oss-instruct-sc2-concepts
from pathlib import Path def get_filesize(pathname: Path) -> int: """ Returns the size of a file in bytes. Parameters ---------- pathname : Path Returns ------- int """ return pathname.stat().st_size
bigcode/self-oss-instruct-sc2-concepts
import hashlib def SimpleMerkleRoot(hashes, hash_function=hashlib.sha256): """ Return the "Simple" Merkle Root Hash as a byte blob from an iterable ordered list of byte blobs containing the leaf node hashes. Works by recursively hashing together pairs of consecutive hashes to form a reduced set one level up from the leafs, repeat until we are reduced to a single hash. If list is odd-length, then last element is copied, not hashed. """ def BytesHasher(msgbytes): return hash_function(msgbytes).digest() if len(hashes) == 0: hashes = [ BytesHasher(bytes()) ] # Hash of empty data #line = "" #for h in hashes: # line = line + h.hex() + " " #print(line) if len(hashes) == 1: return hashes[0] reduced = [] ilast = len(hashes) - 1 for i in range(len(hashes))[0::2]: # 0, 2, 4, 6, ... if i < ilast: pre = hashes[i] + hashes[i+1] reduced.append( BytesHasher(pre) ) else: reduced.append(hashes[i]) return SimpleMerkleRoot(reduced, hash_function)
bigcode/self-oss-instruct-sc2-concepts
def round_robin_list(num, to_distribute): """Return a list of 'num' elements from 'to_distribute' that are evenly distributed Args: num: number of elements in requested list to_distribute: list of element to be put in the requested list >>> round_robin_list(5, ['first', 'second']) ['first', 'second', 'first', 'second', 'first'] >>> round_robin_list(3, ['first', 'second']) ['first', 'second', 'first'] >>> round_robin_list(4, ['first', 'second', 'third']) ['first', 'second', 'third', 'first'] >>> round_robin_list(1, ['first', 'second']) ['first'] """ if not to_distribute: return [] quotient = num // len(to_distribute) remainder = num - quotient * len(to_distribute) assignment = to_distribute * quotient assignment.extend(to_distribute[:remainder]) return assignment
bigcode/self-oss-instruct-sc2-concepts
def inline(sconf): """ Return config in inline form, opposite of :meth:`config.expand`. Parameters ---------- sconf : dict Returns ------- dict configuration with optional inlined configs. """ if ( 'shell_command' in sconf and isinstance(sconf['shell_command'], list) and len(sconf['shell_command']) == 1 ): sconf['shell_command'] = sconf['shell_command'][0] if len(sconf.keys()) == int(1): sconf = sconf['shell_command'] if ( 'shell_command_before' in sconf and isinstance(sconf['shell_command_before'], list) and len(sconf['shell_command_before']) == 1 ): sconf['shell_command_before'] = sconf['shell_command_before'][0] # recurse into window and pane config items if 'windows' in sconf: sconf['windows'] = [inline(window) for window in sconf['windows']] if 'panes' in sconf: sconf['panes'] = [inline(pane) for pane in sconf['panes']] return sconf
bigcode/self-oss-instruct-sc2-concepts
import hashlib def md5sum(data): """ Return md5sum of data as a 32-character string. >>> md5sum('random text') 'd9b9bec3f4cc5482e7c5ef43143e563a' >>> md5sum(u'random text') 'd9b9bec3f4cc5482e7c5ef43143e563a' >>> len(md5sum('random text')) 32 """ return hashlib.md5(data).hexdigest()
bigcode/self-oss-instruct-sc2-concepts
def parse_team_stats(stat_obj: dict) -> str: """ Currently, individual team's stats look like this from Dynamo: "Hotshots": { "GA": "25", "GF": "27", "GP": "7", "L": "3", "OTL": "0", "PTS": "8", "SOL": "0", "T": "0", "W": "4" } we turn these into a nice human readable line. :param stat_obj: dict containing a team's stats :return: strified version of this data """ line = "" for stat, val in stat_obj.items(): line += f"{stat}: {val}\t" return line + "\n"
bigcode/self-oss-instruct-sc2-concepts
from typing import List def is_asset_blacklisted(name: str, blacklist: List[str]) -> bool: """ Check whether an asset must be filtered :param name :param blacklist :returns bool """ return any(map(lambda x : name.endswith(x), blacklist))
bigcode/self-oss-instruct-sc2-concepts
def get_body_length(htc_struc, body): """Get the length of a body from htc structure, given string name""" body_contents = htc_struc.get_subsection_by_name(body).c2_def.contents last_key = next(reversed(body_contents)) length = abs(body_contents[last_key].values[-2]) return length
bigcode/self-oss-instruct-sc2-concepts
def get_tcp_udp_port_data(self) -> dict: """Get list of TCP, UDP ports and their applications .. list-table:: :header-rows: 1 * - Swagger Section - Method - Endpoint * - spPortal - GET - /spPortal/tcpUdpPorts :return: Returns dictionary of ports and their corresponding TCP and UDP applications, parent keys are port number \n * keyword **<port_number>** (`dict`): protocol info object \n * keyword **tcp** (`list[dict]`): tcp information \n [`dict`]: protocol information \n * keyword **description** (`str`): port description * keyword **name** (`str`): port name * keyword **udp** (`list[dict]`): udp information \n [`dict`]: protocol information \n * keyword **description** (`str`): port description * keyword **name** (`str`): port name :rtype: dict """ return self._get("/spPortal/tcpUdpPorts")
bigcode/self-oss-instruct-sc2-concepts
def _RemoteSteps(api, app_engine_sdk_path, platform): """Runs the build steps specified in catapult_build/build_steps.py. Steps are specified in catapult repo in order to avoid multi-sided patches when updating tests and adding/moving directories. This step uses the generator_script; see documentation at github.com/luci/recipes-py/blob/master/recipe_modules/generator_script/api.py Use the test_checkout_path property in local tests to run against a local copy of catapult_build/build_steps.py. """ base = api.properties.get('test_checkout_path', str(api.path['checkout'])) script = api.path.join(base, 'catapult_build', 'build_steps.py') args = [ script, '--api-path-checkout', api.path['checkout'], '--app-engine-sdk-pythonpath', app_engine_sdk_path, '--platform', platform or api.platform.name, ] return api.generator_script(*args)
bigcode/self-oss-instruct-sc2-concepts
def ce(actual, predicted): """ Computes the classification error. This function computes the classification error between two lists :param actual : int, float, list of numbers, numpy array The ground truth value :param predicted : same type as actual The predicted value :returns double The classification error between actual and predicted """ return ( sum([1.0 for x, y in zip(actual, predicted) if x != y]) / len(actual))
bigcode/self-oss-instruct-sc2-concepts
async def hello(): """ Returns "hello from service1" """ return 'hello from service1'
bigcode/self-oss-instruct-sc2-concepts
def parsePoint(storedPt): """ Translates a string of the form "{1, 0}" into a float tuple (1.0, 0.0) """ return tuple(float(c) for c in storedPt.strip("{}").split(","))
bigcode/self-oss-instruct-sc2-concepts
def spatial_overlap_conv_3x3_stride_2(p): """ This method computes the spatial overlap of 3x3 convolutional layer with stride 2 in terms of its input feature map's spatial overal value (p). """ return (1 + 2 * (1-p)) / (1 + 4 * (1 - p) * (2 - p))
bigcode/self-oss-instruct-sc2-concepts
def join(*args): """ Return a string composed of the result of applying str() to each one of the given args, separated by spaced, but only if the item exists. Example: >>> join('Hello', False, 1, True, 0, 'world') 'Hello 1 True world' """ strings = [str(arg) for arg in args if arg] return ' '.join(strings)
bigcode/self-oss-instruct-sc2-concepts
from typing import List from typing import Dict def reduce_raw_dict(data: List[Dict[str, str]]) -> List[Dict[str, str]]: """ Initial data cleanup. Filter all logs that deal with accessing a "BernsteinConference" page and that contain "Completed" to remove "Started" duplicates. Further remove "/plugins" to filter loading the PDF viewer load logs. :param data: list containing docker log dictionaries. :return: list containing docker log dictionaries. """ fil_str = "BernsteinConference" fil_dat = list(filter(lambda log_entry: fil_str in log_entry["log"], data)) fil_dat = list(filter(lambda log_entry: "Completed" in log_entry["log"], fil_dat)) fil_dat = list(filter(lambda log_entry: "/plugins" not in log_entry["log"], fil_dat)) return fil_dat
bigcode/self-oss-instruct-sc2-concepts
def build(name, builder): """Wrapper to turn (name, vm) -> val method signatures into (vm) -> val.""" return lambda vm: builder(name, vm)
bigcode/self-oss-instruct-sc2-concepts
def PrepareCorrResults(df): """ Pass it a dataframe, and it returns Pairwise Pearson correlation coefficient values for the entire variables of the datadframe. The first columns of the returned dfCORR contains correlation values of the classvariable versus all other variables. """ dfCORR = df.corr() dfCORR.reset_index(level=0, inplace=True) dfCORR = dfCORR.rename(columns={'index':'Variable'}) return dfCORR
bigcode/self-oss-instruct-sc2-concepts
def full_to_type_name(full_resource_name): """Creates a type/name format from full resource name.""" return '/'.join(full_resource_name.split('/')[-2:])
bigcode/self-oss-instruct-sc2-concepts
def is_shuffle(stage: str) -> bool: """Whether shuffle input. Args: stage: Train, val, test. Returns: Bool value. """ is_sh = {'train': True, 'val': False, 'test': False} return is_sh[stage]
bigcode/self-oss-instruct-sc2-concepts
def _get_item_by_name(cls, name): """ Gets the item from the corresponding class with the indicated name. :param cls: Class / Entity of the item. :param name: Case-insensitive name of the item. :return: The item if there is a match, None otherwise. """ if name: try: return cls.get(cls.name == name.lower()) except cls.DoesNotExist: return None return None
bigcode/self-oss-instruct-sc2-concepts
import six def intersect(*masks): """Return new masks that are the per-layer intersection of the provided masks. Args: *masks: The set of masks to intersect. Returns: The intersection of the provided masks. """ result = {} for mask in masks: for layer, values in six.iteritems(mask): if layer in result: result[layer] *= values else: result[layer] = values return result
bigcode/self-oss-instruct-sc2-concepts
def get_label_dummy_goal(vertex_input): """Get the index of the fictitious dummy goal (last vertex + 1)""" if isinstance(vertex_input, int): v_g = vertex_input + 1 return v_g elif isinstance(vertex_input, list): v_g = vertex_input[-1] + 1 return v_g else: print('Wrong type of input, accepts integer or list') return None
bigcode/self-oss-instruct-sc2-concepts
from typing import Any def is_not(a: Any, b: Any, /) -> bool: """Check if the arguments are different objects.""" return id(a) != id(b)
bigcode/self-oss-instruct-sc2-concepts
import torch def clip_gradient(model, clip_norm=10): """ clip gradients of each parameter by norm """ for param in model.parameters(): torch.nn.utils.clip_grad_norm(param, clip_norm) return model
bigcode/self-oss-instruct-sc2-concepts
import random def split_partition(annotations): """Randomly split annotations into train (80%), dev (10%), and test (10%) sets""" train_annotations = dict() dev_annotations = dict() test_annotations = dict() doc_names = list(annotations.keys()) random.seed(100) #To ensure the shuffle always return the same result (allows reproducibility) random.shuffle(doc_names) split_1 = int(0.8 * len(doc_names)) split_2 = int(0.9 * len(doc_names)) train_doc_names = doc_names[:split_1] dev_doc_names = doc_names[split_1:split_2] test_doc_names = doc_names[split_2:] for doc in train_doc_names: train_annotations[doc] = annotations[doc] for doc in dev_doc_names: dev_annotations[doc] = annotations[doc] for doc in test_doc_names: test_annotations[doc] = annotations[doc] return train_annotations, dev_annotations, test_annotations
bigcode/self-oss-instruct-sc2-concepts
import math def conttogrowth(contrate): """ Convert continuous compounding rate to annual growth """ return math.exp(contrate)
bigcode/self-oss-instruct-sc2-concepts
def Backtracking_linesearch(f, x, lambda_newton, Delta_x,options): """ The goal of this function is to perform a backtracking linesearch to adapt the stepsize t of the Newton step, i.e. prepare a damped Newton step. For this, do the following: 1. Imports and definitions 2. Loop till conditions satisfied The stepsize t is reduced until the condition f(x+t Delta_x) < f(x) + t alpha <grad_f, Delta_x> is satisfied. INPUTS The inputs consist in an objective function f used to check validity of the Hessian approximation as well as an evaluation point x and the Newton decrement lambda_newton. Furthermore, the descent direction Delta_x needs to be pro- vided together with some options on (alpha, beta, tolerances) that feature in backtracking line search algorithms. Name Interpretation Type f The objective function for which the Function handle Armijo optimality condition is to be checked. Calculates the objective values f(x) and f(x+t Delta_x). x The position at which gradients and Matrix [n_exp,n_exp] search directions are evaluated. lambda_newton The Newton decrement quantifying the A positive real number decrease of the objective function in the direction of Delta_x Delta_x Provides the descent direction, for Matrix [n_exp,n_exp] which a reasonable stepsize t is to be determined. The recommended update is then x = x + t Delta x options Tuple containing the values for alpha, Tuple (alpha,beta,max_iter) beta and maximum iterations to arrive at a reasonable stepsize. OUTPUTS The outputs consist in the stepsize t, a real number guaranteeing that Newton updates do not leave the psd cone. Name Interpretation Type t Stepsize for a robust damped Newton Real number in [0,1] update """ """ 1. Imports and definitions ------------------------------------------- """ # i) Import packages # ii) Define auxiliary quantities alpha=options[0] beta=options[1] max_iter=options[2] # iii) Initial function evaluations t=1 f_val_x=f(x) f_val_x_mod=f(x+t*Delta_x) difference=f_val_x_mod-(f_val_x-alpha*t*(lambda_newton**2)) """ 2. Loop till conditions satisfied ------------------------------------ """ # i) Iterate k=1 while difference>0 and k<max_iter: t=beta*t f_val_x_mod=f(x+t*Delta_x) difference=f_val_x_mod-(f_val_x-alpha*t*(lambda_newton**2)) k=k+1 if k==max_iter: t=0 # ii) Assemble solution return t
bigcode/self-oss-instruct-sc2-concepts