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.sh...
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...
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: ...
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 ...
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...
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 == "": ...
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']] "...
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 miss...
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]]): """ ...
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=" +...
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(['ab...
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 """ ...
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) ...
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...
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 ...
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 Ob...
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 bl...
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...
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 ...
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' ...
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'...
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]...
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: ...
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: retur...
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...
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 signific...
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_f...
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()).re...
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] = ge...
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 object...
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()...
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 ...
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 retu...
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...
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(...
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....
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 ...
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 "" ...
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] =...
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 exa...
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,...
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...
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 ...
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 ...
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 o...
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']) ['fi...
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_co...
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).hexdig...
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 read...
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 p...
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 gi...
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 pr...
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 a...
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 "/plugin...
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 ...
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: retur...
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 ...
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('...
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 shu...
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 con...
bigcode/self-oss-instruct-sc2-concepts