seed
stringlengths
1
14k
source
stringclasses
2 values
def elaborateanswer(question): """ Give an elaborate, realitisc and Michael-Palin-like answer to the question `question`. Examples: --------- >>> elaborateanswer("Do you have some cheddar?") 'No.' >>> elaborateanswer("The camembert is indeed runny.") '<Nods.>' """ if questio...
bigcode/self-oss-instruct-sc2-concepts
def convert_shelves(element): """Get the names of all the shelves that hold this book.""" # The shelves for a review are returned in the following format: # # <shelves> # <shelf name="read" exclusive="true"/> # <shelf name="fiction" exclusive="false" review_shelf_id="1234"/> # ...
bigcode/self-oss-instruct-sc2-concepts
def poly(x1, x2, degree=3, gamma=1., r=0.): """ polynomial kernel function Parameters ------------ x1 : numpy array, (..., n) the first input feature vector x2 : numpy array, (..., n) the second input feature vector degree : positive double, default: 3 degree of ...
bigcode/self-oss-instruct-sc2-concepts
def element_with_unique_name(self,name): """Returns the element with unique_name This mehtod extends the powerfactor.Application class. It returns the element with the given unique_name. Args: name: The unique name of the element e.g. 'Netz\\Last.ElmLod' Returns: A powerfactory.Da...
bigcode/self-oss-instruct-sc2-concepts
def _step_to_value(step, num_steps, values): """Map step in performance to desired control signal value.""" num_segments = len(values) index = min(step * num_segments // num_steps, num_segments - 1) return values[index]
bigcode/self-oss-instruct-sc2-concepts
import functools def qutip_callback(func, **kwargs): """Convert `func` into the correct form of a QuTiP time-dependent control QuTiP requires that "callback" functions that are used to express time-dependent controls take a parameter `t` and `args`. This function takes a function `func` that takes `t...
bigcode/self-oss-instruct-sc2-concepts
def isNum(s) -> bool: """ Checks if its a number >>> isNum("1") True >>> isNum("-1.2") True >>> isNum("1/2") True >>> isNum("3.9/2") True >>> isNum("3.9/2.8") True >>> isNum("jazz hands///...") False """ if "/" in str(s): s = s.replace("/", "", 1) ...
bigcode/self-oss-instruct-sc2-concepts
def frames_to_ms(frames: int, fps: float) -> int: """ Convert frame-based duration to milliseconds. Arguments: frames: Number of frames (should be int). fps: Framerate (must be a positive number, eg. 23.976). Returns: Number of milliseconds (rounded to int). ...
bigcode/self-oss-instruct-sc2-concepts
def mapLists(first, second): """ Make a dictionary from two lists with elements of the first as the keys and second as values. If there are more elements in the first list, they are assigned None values and if there are more in the second list, they're dropped. """ index = 0 dict = {} # Read through every index ...
bigcode/self-oss-instruct-sc2-concepts
def format_schema_tf(schema): """Format schema for an Athena table for terraform. Args: schema (dict): Equivalent Athena schema used for generating create table statement Returns: formatted_schema (list(tuple)) """ # Construct the main Athena Schema formated_schema = [] for...
bigcode/self-oss-instruct-sc2-concepts
def add_entities(kb, desc_dict, nlp): """ Adds company entities to KB :param kb: the empty Knowledge Base :param desc_dict: dict with KvK-numbers and SBI-code descriptions of companies :param nlp: the nlp object to retrieve vector of SBI-code description :return: the KB with companies entities ...
bigcode/self-oss-instruct-sc2-concepts
import json def output_json(output): """Return JSON formated string.""" return json.dumps(output, sort_keys=True, indent=2)
bigcode/self-oss-instruct-sc2-concepts
import json def handle_event(ext, body): """Handle an event from the queue. :param ext: The extension that's handling this event. :param body: The body of the event. :return: The result of the handler. """ payload = json.loads(body) return ext.obj.event(author_id=payload['author_id'] or N...
bigcode/self-oss-instruct-sc2-concepts
def title_case(inp_str): """ Transforms the input string to start each word from capital letter Parameters ---------- inp : string string to be changed Returns ------- result : string a string were each word starts from the capital letter """ if isinstance(inp_str, str): ...
bigcode/self-oss-instruct-sc2-concepts
def batch_split(batch_size, max_num): """Split into equal parts of {batch_size} as well as the tail""" if batch_size > max_num: print("Fix the batch size to maximum number.") batch_size = max_num max_range = list(range(max_num)) num_splits = max_num // batch_size num_splits = ( ...
bigcode/self-oss-instruct-sc2-concepts
def seq_matches(seq1, seq2): """ Return True if two sequences of numbers match with a tolerance of 0.001 """ if len(seq1) != len(seq2): return False for i in range(len(seq1)): if abs(seq1[i] - seq2[i]) > 1e-3: return False return True
bigcode/self-oss-instruct-sc2-concepts
def is_far_from_group(pt, lst_pts, d2): """ Tells if a point is far from a group of points, distance greater than d2 (distance squared) :param pt: point of interest :param lst_pts: list of points :param d2: minimum distance squarred :return: True If the point is far from all others. """ ...
bigcode/self-oss-instruct-sc2-concepts
import torch def get_board_tensor(board_str, black_moves): """ function to move from FEN representation to 12x8x8 tensor Note: The rows and cols in the tensor correspond to ranks and files in the same order, i.e. first row is Rank 1, first col is File A. Also, the color to move next occupi...
bigcode/self-oss-instruct-sc2-concepts
import re def unsub_emails(unsub_list, email_list): """ Takes the list of plex user email address and filters out the members of the unsubscribe list. """ excludes = re.split(r",|,\s", unsub_list) email_list = list(set(email_list)^set(excludes)) return email_list
bigcode/self-oss-instruct-sc2-concepts
import re def slice_marc_shorthand(string: str) -> tuple: """ Splits a string and gives a tuple of two elements containing the Main Number and the subfield of a marc shorthand Calls a regex check to make sure the format is corret :param str string: a string describing a marc shorthand, should look lik...
bigcode/self-oss-instruct-sc2-concepts
import socket def createTestSocket(test, addressFamily, socketType): """ Create a socket for the duration of the given test. @param test: the test to add cleanup to. @param addressFamily: an C{AF_*} constant @param socketType: a C{SOCK_*} constant. @return: a socket object. """ skt...
bigcode/self-oss-instruct-sc2-concepts
from pathlib import Path def get_texture_type(image_path): """ Gets the PBR texture type from the filename. :param image_path: Path to the image from which to extract pbr type :return: """ filename = Path(image_path) texture_type = filename.stem.split('_')[-1] return texture_type
bigcode/self-oss-instruct-sc2-concepts
def keyGen(attributes, data): """ Traverses the data and returns the key generated based on the given attributes. **Parameters**: attributes : list A list of attributes which define the key. data : dict The data for which the key has to be generated for. **Retur...
bigcode/self-oss-instruct-sc2-concepts
def ancestors(node): """Return a list of ancestors, starting with the direct parent and ending with the top-level (root) parent.""" result = [] parent = node.getParent() while parent is not None: result.append(parent) parent = parent.getParent() return result
bigcode/self-oss-instruct-sc2-concepts
def calcMitGuideScore(hitSum): """ Sguide defined on http://crispr.mit.edu/about Input is the sum of all off-target hit scores. Returns the specificity of the guide. """ score = 100 / (100+hitSum) score = int(round(score*100)) return score
bigcode/self-oss-instruct-sc2-concepts
def timeout(timeout): """ Condition to be used on Timers. True after the given amount of time has elapsed since this decorator became active. """ def inner(timer, *args, **kwargs): return timer >= timeout return inner
bigcode/self-oss-instruct-sc2-concepts
def check_resource_deleted(error_message): """Create a callable to verify that a resource is deleted. To be used with the :meth:`run` function. The callable will raise an :class:`AssertionError` if the chosen resource is shown as existing in the response given to the callable Args: error_m...
bigcode/self-oss-instruct-sc2-concepts
def getCurvesListWithDifferentCurveName(originalCurveList, origCurve, newCurve): """ Takes in list of curves, curve name to be replaced, and curve name to replace with. Returns a list with the orginal and new curve names switched in the given curve list """ plentifulCurves_wDEPTH = originalCurveLis...
bigcode/self-oss-instruct-sc2-concepts
from typing import Counter def number_of_contacts(records, direction=None, more=0): """ The number of contacts the user interacted with. Parameters ---------- direction : str, optional Filters the records by their direction: ``None`` for all records, ``'in'`` for incoming, and ``'...
bigcode/self-oss-instruct-sc2-concepts
def format_summary(a): """a is a vector of (median, min, max, std).""" return "{0:<6.3g} {3:<6.3g} ({1:.3g} - {2:.3g})".format(*a)
bigcode/self-oss-instruct-sc2-concepts
def get_available_directions(character: dict, columns: int, rows: int) -> list: """ Get the list of available directions. :param character: a dictionary :param columns: an integer :param rows: an integer :precondition: character must be a dictionary :precondition: columns >= 0 :precondi...
bigcode/self-oss-instruct-sc2-concepts
import binascii def crc32(string: str) -> str: """Return the standard CRC32 checksum as a hexidecimal string.""" return "%08X" % binascii.crc32(string.encode())
bigcode/self-oss-instruct-sc2-concepts
def get_slots(intent_request): """ Fetch all the slots and their values from the current intent. """ return intent_request["currentIntent"]["slots"]
bigcode/self-oss-instruct-sc2-concepts
def rossler(x, y, z, a=0.2, b=0.2, c=5.7): """Compute next point in Rossler attractor.""" x_dot = -y - z y_dot = x + a*y z_dot = b + z*(x-c) return x_dot, y_dot, z_dot
bigcode/self-oss-instruct-sc2-concepts
def find_cntrs(boxes): """Get the centers of the list of boxes in the input. Parameters ---------- boxes : list The list of the boxes where each box is [x,y,width,height] where x,y is the coordinates of the top-left point Returns ------- list Centers of each...
bigcode/self-oss-instruct-sc2-concepts
def _is_bazel_external_file(f): """Returns True if the given file is a Bazel external file.""" return f.path.startswith('external/')
bigcode/self-oss-instruct-sc2-concepts
def get_formatted_name(first, middle, last): """Generate a neatly formatted full name""" full_name=f"{first} {middle} {last}" return full_name.title() """this version works for people with middle name but breaks for people with only first and last names"""
bigcode/self-oss-instruct-sc2-concepts
import re from typing import OrderedDict def get_example_sections(example): """Parses a multipart example and returns them in a dictionary by type. Types will be by language to highlight, except the special "__doc__" section. The default section is "html". """ parts = re.split(r'<!-- (.*) -->', ...
bigcode/self-oss-instruct-sc2-concepts
import csv import operator def read_training_history(path, ordering=None): """Read training history from the specified CSV file. Args: path (str): Path to CSV file. ordering (str): Column name to order the entries with respect to or ``None`` if the entries should remain unordered....
bigcode/self-oss-instruct-sc2-concepts
def diff(a, b): """ Takes the difference of two numbers Arguments --------- a : int, float b : int, float Returns ------- d : float difference between a and b """ return a - b
bigcode/self-oss-instruct-sc2-concepts
def _cert_type_from_kwargs(**kwargs): """Return cert type string from kwargs values""" for k in ('admin', 'creator', 'initiator', 'platform'): try: if k in kwargs['user_type'] and kwargs['user_type'][k]: return k except LookupError: if k in kwargs and kwa...
bigcode/self-oss-instruct-sc2-concepts
def readPhraseIndexFromFiles (filenames): """Takes a list of files; reads phrases from them, with one phrase per line, ignoring blank lines and lines starting with '#'. Returns a map from words to the list of phrases they are the first word of.""" phraseIndex = dict() for filename in filenames: ...
bigcode/self-oss-instruct-sc2-concepts
def campaign_news_item_save_doc_template_values(url_root): """ Show documentation about campaignNewsItemSave """ required_query_parameter_list = [ { 'name': 'voter_device_id', 'value': 'string', # boolean, integer, long, string 'description': ...
bigcode/self-oss-instruct-sc2-concepts
def first_plus_last(num: int) -> int: """Sum first and last digits of an integer.""" as_string = str(num) return int(as_string[0]) + int(as_string[-1])
bigcode/self-oss-instruct-sc2-concepts
def extract_name(row): """ Helper function for comparing datasets, this extracts the name from the db name Args: row: row in the dataframe representing the db model Returns: name extracted from agency_name or np.nan """ return row['agency_name'][:row['agency_name']....
bigcode/self-oss-instruct-sc2-concepts
from typing import Dict def __construct_robot_message_subject(serial_number: str, uuid: str) -> Dict[str, str]: """Generates a robot subject for a plate event message. Arguments: serial_number {str} -- The robot serial number. uuid {str} -- The robot uuid. Returns: {Dict[str, str...
bigcode/self-oss-instruct-sc2-concepts
def cap_text(text): """capitalize() upper cases the first letter of a string.""" return text.capitalize()
bigcode/self-oss-instruct-sc2-concepts
import re def get_level(line, indent) : """ Return the level of indentation of a given line """ level = 0 while line.startswith(indent) : line = line[len(indent):] level += 1 if re.match(r"^(\s+)", line) : raise Exception("Syntax Error") return level
bigcode/self-oss-instruct-sc2-concepts
def construct_fasta_entry(host_id, sequence, description=None, wrap=None): """Returns a FASTA-formatted entry for the sequence. Parameters ---------- host_id : int Host ID of target host sequence : iterable If sequence is a list of single characters, the list will be joined ...
bigcode/self-oss-instruct-sc2-concepts
def get_triangular(n: int) -> int: """Get `n`-th triangular number Args: n: Index of triangular number Examples: >>> print(get_triangular(10)) 55 """ return n * (n + 1) // 2
bigcode/self-oss-instruct-sc2-concepts
def sort_bl(p): """Sort a tuple that starts with a pair of antennas, and may have stuff after.""" if p[1] >= p[0]: return p return (p[1], p[0]) + p[2:]
bigcode/self-oss-instruct-sc2-concepts
def round_down(x, n): # type: (int, int) -> int """Round down `x` to nearest `n`.""" return x // n * n
bigcode/self-oss-instruct-sc2-concepts
import torch def normalize(tensor, min=None, max=None): """ Normalize the tensor values between [0-1] Parameters ---------- tensor : Tensor the input tensor min : int or float (optional) the value to be considered zero. If None, min(tensor) will be used instead (default is Non...
bigcode/self-oss-instruct-sc2-concepts
import random import math def GetSample(gan_params): """Get one sample for each range specified in gan_params.""" ret = {} for param_name, param_info in sorted(gan_params.items()): if param_info.is_discrete: v = random.choice(param_info.range) else: assert isinstance(param_info.default, floa...
bigcode/self-oss-instruct-sc2-concepts
def tag_filter(tag_list, base_df): """Search with tags. Args: base_df (DataFrame): Search target. tag_list (list): List of search tag. Returns: (DataFrame): Searched DataFrame. """ result_df = base_df for tag in tag_list: mask = result_df["tag"].apply(lambda x:...
bigcode/self-oss-instruct-sc2-concepts
import json def decode_predictions(preds, top=5): """Decode the prediction of an ImageNet model. # Arguments preds: Numpy tensor encoding a batch of predictions. top: integer, how many top-guesses to return. # Returns A list of lists of top class prediction tuples `(class...
bigcode/self-oss-instruct-sc2-concepts
def get_num(x): """Grab all integers from string. Arguments: *x* (string) -- string containing integers Returns: *integer* -- created from string """ return int(''.join(ele for ele in x if ele.isdigit()))
bigcode/self-oss-instruct-sc2-concepts
def reverse_complement(seq): """Return reverse complement of a dna sequence.""" bases_dict = { 'A': 'T', 'a': 't', 'C': 'G', 'g': 'c', 'G': 'C', 'c': 'g', 'T': 'A', 't': 'a'} return "".join([bases_dict[base] for base in reversed(seq)])
bigcode/self-oss-instruct-sc2-concepts
from typing import Set def config_files() -> Set[str]: """ Return a set of the names of all the PyTorch mypy config files. """ return { 'mypy.ini', 'mypy-strict.ini', }
bigcode/self-oss-instruct-sc2-concepts
import pipes def tokens_to_string(tokens): """ Build string from tokens with proper quoting. :param tokens: list of string tokens :return: space-separated string of tokens """ return ' '.join(map(pipes.quote, tokens))
bigcode/self-oss-instruct-sc2-concepts
def unique_dot_keys(experiment_keys): """ Return the first run of each dot, given all experiments. """ result = list() for key in sorted(experiment_keys): if key[:2] not in map(lambda x: x[:2], result): result.append(key) return(result)
bigcode/self-oss-instruct-sc2-concepts
def _checkFileEndingGeneric(file_: str, ending: str) -> bool: """ generic function that checks if file_ ends with param 'ending' """ return file_.endswith(ending)
bigcode/self-oss-instruct-sc2-concepts
def reformate_path(path): """On certain editors (e.g. Spyder on Windows) a copy-paste of the path from the explorer includes a 'file:///' attribute before the real path. This function removes this extra piece Args: path: original path Returns: Reformatted path """ _path = path....
bigcode/self-oss-instruct-sc2-concepts
def initial_fixation_duration(interest_area, fixation_sequence): """ Given an interest area and fixation sequence, return the duration of the initial fixation on that interest area. """ for fixation in fixation_sequence.iter_without_discards(): if fixation in interest_area: retur...
bigcode/self-oss-instruct-sc2-concepts
def none_are_none(*args) -> bool: """ Return True if no args are None. """ return not any([arg is None for arg in args])
bigcode/self-oss-instruct-sc2-concepts
def get_word_lengths(s): """ Returns a list of integers representing the word lengths in string s. """ return [len(w) for w in s.split()]
bigcode/self-oss-instruct-sc2-concepts
def doc_brief(brief): """format brief for doc-string""" return " {0}\n".format(brief)
bigcode/self-oss-instruct-sc2-concepts
def broadcast_rank(source, target): """Broadcasts source to match target's rank following Numpy semantics.""" return source.reshape((1,) * (target.ndim - source.ndim) + source.shape)
bigcode/self-oss-instruct-sc2-concepts
def longest_substring_with_k_distinct(s, k): """Find the length of the longest substr with less than or equal to k distinct characters. Time: O(n) Space: O(k) >>> longest_substring_with_k_distinct("araaci", 2) 4 >>> longest_substring_with_k_distinct("araaci", 1) 2 >>> longest_subs...
bigcode/self-oss-instruct-sc2-concepts
def sec2hms(seconds): """ return seconds as (hh,mm,ss)""" hr = int(seconds) mn = int((seconds*3600 - hr*3600)/60) sec = seconds*3600 - hr*3600 - mn*60 return [hr, mn, sec]
bigcode/self-oss-instruct-sc2-concepts
from typing import Dict from typing import List import csv def read_temp_csv_data(filepath_temp: str) -> Dict[str, Dict[int, List[float]]]: """Return a mapping from the state to a mapping of the year to yearly data in the format [average temperature, precipitation, wildfire counts]. Currently, the values...
bigcode/self-oss-instruct-sc2-concepts
def replay_args(parser, show_all_task_softmax=True): """This is a helper function of function :func:`parse_cmd_arguments` to add an argument group for options regarding Generative Replay. Args: parser (argparse.ArgumentParser): The argument parser to which the group should be added. ...
bigcode/self-oss-instruct-sc2-concepts
def get_trait_names(clinvar_json: dict) -> list: """ Given a dictionary for a ClinVar record parse the strings for the trait name of each trait in the record, prioritising trait names which are specified as being "Preferred". Return a list of there strings. :param clinvar_json: A dict object contai...
bigcode/self-oss-instruct-sc2-concepts
def init_label_dict(num_classes): """ init label dict. this dict will be used to save TP,FP,FN :param num_classes: :return: label_dict: a dict. {label_index:(0,0,0)} """ label_dict={} for i in range(num_classes): label_dict[i]=(0,0,0) return label_dict
bigcode/self-oss-instruct-sc2-concepts
def convert_string_AE2BE(string, AE_to_BE): """convert a text from American English to British English Parameters ---------- string: str text to convert Returns ------- str new text in British English """ string_new = " ".join([AE_to_BE[w] if w in AE_to_BE.keys() e...
bigcode/self-oss-instruct-sc2-concepts
def order_dict(_dict: dict, reverse: bool=True) -> dict: """ Takes a dictionary and returns it ordered. :param _dict: :class:`dict` :param reverse: :class:`bool` :return: :class:`dict` """ temp_dict = {} unordered_list = [(k, v) for k, v in _dict.items()] ordered_list = sorted(unor...
bigcode/self-oss-instruct-sc2-concepts
import re def replace_string( text, old_string, new_string ): """ Check that `old_string` is in `text`, and replace it by `new_string` (`old_string` and `new_string` use regex syntax) """ # Check that the target line is present if re.findall(old_string, text) == []: raise RuntimeError(...
bigcode/self-oss-instruct-sc2-concepts
def list_api_vs(client, resource_group_name, service_name): """Lists a collection of API Version Sets in the specified service instance.""" return client.api_version_set.list_by_service(resource_group_name, service_name)
bigcode/self-oss-instruct-sc2-concepts
def startswith(text, starts): """Simple wrapper for str.startswith""" if isinstance(text, str): return text.startswith(starts) return False
bigcode/self-oss-instruct-sc2-concepts
def compare_acl(acl1, acl2): """ Compares two ACLs by comparing the role, action and allow setting for every ACE. :param acl1: First ACL :type acl1: dict with role, action as key and allow as value :param acl2: Second ACL :type acl2: dict with role, action as key and allow as value :return:...
bigcode/self-oss-instruct-sc2-concepts
def _reference_expect_copies(chrom, ploidy, is_sample_female, is_reference_male): """Determine the number copies of a chromosome expected and in reference. For sex chromosomes, these values may not be the same ploidy as the autosomes. The "reference" number is the chromosome's ploidy in the CNVkit refe...
bigcode/self-oss-instruct-sc2-concepts
import math def score_feature_vector(feature_vector, probs, cnt_bins, restrict_features): """ For a feature vector, computes its log transformed likelihood ratio with respect to the model. That is, every feature value in the feature vector is evaluated and log of the likelihood ratio is added to the t...
bigcode/self-oss-instruct-sc2-concepts
def removekey(d, key): """This functions returns a copy of a dictionnary with a removed key Parameters: d (dict): dictionnary key: the key that must be deleted Returns: copy of dictionnary d without the key """ r = dict(d) del r[key] return r
bigcode/self-oss-instruct-sc2-concepts
def get_dataset_info(dataset_type): """define dataset_name and its dataroot""" root = '' if dataset_type == 'LEVIR_CD': root = 'path-to-LEVIR_CD-dataroot' # add more dataset ... else: raise TypeError("not define the %s" % dataset_type) return root
bigcode/self-oss-instruct-sc2-concepts
def get_default(dct, key, default=None, fn=None): """Get a value from a dict and transform if not the default.""" value = dct.get(key, default) if fn is not None and value != default: return fn(value) return value
bigcode/self-oss-instruct-sc2-concepts
import re def get_class_name(a_string): """Convert a name string to format: ThisIsAnUnusualName. Take a space delimited string, return a class name such as ThisIsAnUnusualName Here we use this function for instance name. Thus it allows to start with a number """ joint_name = a_string.title().repla...
bigcode/self-oss-instruct-sc2-concepts
def _get_num_contracts(contracts_list, param_name): """ Return the number of simple/default contracts. Simple contracts are the ones which raise a RuntimeError with message 'Argument `*[argument_name]*` is not valid' """ msg = "Argument `*[argument_name]*` is not valid" return sum( ...
bigcode/self-oss-instruct-sc2-concepts
def get_duplicate_indices(words): """Given a list of words, loop through the words and check for each word if it occurs more than once. If so return the index of its first ocurrence. For example in the following list 'is' and 'it' occurr more than once, and they are at indices 0 and 1 so you would ...
bigcode/self-oss-instruct-sc2-concepts
import time def utc_offset(time_struct=None): """ Returns the time offset from UTC accounting for DST Keyword Arguments: time_struct {time.struct_time} -- the struct time for which to return the UTC offset. If Non...
bigcode/self-oss-instruct-sc2-concepts
import requests from bs4 import BeautifulSoup def getBoxscoreURLsFromPlayer(playerId): """ Put in a player id and get all boxscores for that player. - can be updated to specify after which date. """ r = requests.get('https://www.pro-football-reference.com/players/'+ playerId[0] + '/' + p...
bigcode/self-oss-instruct-sc2-concepts
def read_wien2k_G_vectors(filename): """ Read the Wien2K G-vectors and return the vectors - G1 - G2 - G3 In Wien2K the G-vectors are stored in a file with the extension .outputkgen, and are listed under G1 G2 G3 so we need to be looking for lines that start with that content. ...
bigcode/self-oss-instruct-sc2-concepts
def add2(matrix1,matrix2): """ Add corresponding numbers in 2D matrix """ combined = [] for row1,row2 in zip(matrix1,matrix2): tmp = [sum(column) for column in zip(row1,row2)] combined.append(tmp) return combined # Alternativley: # nest the list comprehension for a one line ...
bigcode/self-oss-instruct-sc2-concepts
def nomalize_image(image): """Nomalize image from [0,255] to "[-1, 1]""" image = image / 255.0 image = 2 * (image - 0.5) return image
bigcode/self-oss-instruct-sc2-concepts
def wavelength(frequency, speed=343.2): """Calculate the wavelength l of frequency f given the speed (of sound)""" l = speed/frequency return l
bigcode/self-oss-instruct-sc2-concepts
import uuid def unique_dataset_name(prefix: str = "selenium-dataset"): """ Return a universally-unique dataset name """ return f'{prefix}-{uuid.uuid4().hex[:8]}'
bigcode/self-oss-instruct-sc2-concepts
def make_ignore_f(start_line): """Make an ignore function that ignores bad gg lines""" def ignore(line): """Return false if line is bad""" return not line or ['',''] == line or [start_line,''] == line return ignore
bigcode/self-oss-instruct-sc2-concepts
import json def pj(jdb): """Dumps pretty JSON""" return json.dumps(jdb,sort_keys=True,indent=4)
bigcode/self-oss-instruct-sc2-concepts
def _to_number(val): """ Convert to a numeric data type, but only if possible (do not throw error). >>> _to_number('5.4') 5.4 >>> _to_number(5.4) 5.4 >>> _to_number('-6') -6 >>> _to_number('R2D2') 'R2D2' """ try: if val.is_integer(): # passed as int in float for...
bigcode/self-oss-instruct-sc2-concepts
import hashlib def md5(text): """Returns the md5 hash of a string.""" hash = hashlib.md5() hash.update(text) return hash.hexdigest()
bigcode/self-oss-instruct-sc2-concepts
def divides(d: int, n: int) -> bool: """Return whether d divides n.""" if d == 0: return n == 0 else: return n % d == 0
bigcode/self-oss-instruct-sc2-concepts