seed
stringlengths
1
14k
source
stringclasses
2 values
import math def factors(n): """ Returns the list of n's factors --param n : int --return list """ if n < 1: return [] elif n in {1,2,3}: temp = set() temp.add(1) temp.add(n) return list(temp) else: temp = set() temp.add(1) ...
bigcode/self-oss-instruct-sc2-concepts
import json def _schema(**vals): """Default schema.""" data = dict( id='a-b-c-d-e', date="2016-08-23 15:03:49.178000", layout="grid", name="testlayout", modules=[], ) data.update(**vals) return json.dumps(data)
bigcode/self-oss-instruct-sc2-concepts
def temp_cache_pos_file(temp_folder, temp_cache_pos_filename): """Create a file path to for the cached part-of-speech (POS) file.""" return temp_folder.join(temp_cache_pos_filename)
bigcode/self-oss-instruct-sc2-concepts
import requests def get_interlanguage_links(page_title, endpoint='en.wikipedia.org/w/api.php', redirects=1): """The function accepts a page_title and returns a dictionary containing the title of the page in its other languages page_title - a string with the title of the page on Wikipedia endp...
bigcode/self-oss-instruct-sc2-concepts
def in_seconds(days=0, hours=0, minutes=0, seconds=0): """ Tiny helper that is similar to the timedelta API that turns the keyword arguments into seconds. Most useful for calculating the number of seconds relative to an epoch. >>> in_seconds() 0 >>> in_seconds(hours=1.5) 5400 >>> in_sec...
bigcode/self-oss-instruct-sc2-concepts
from typing import List from typing import Optional def response_detect_blocking_messages( text: str, blocking_messages: List[str] ) -> Optional[str]: """Method to check whether any of blocking messages appears in the response text. :param text: response text :param blocking_messages: list of pot...
bigcode/self-oss-instruct-sc2-concepts
import time def TimeoutExpired(epoch, timeout, _time_fn=time.time): """Checks whether a timeout has expired. """ return _time_fn() > (epoch + timeout)
bigcode/self-oss-instruct-sc2-concepts
def get_bool(value: str) -> bool: """Get boolean from string.""" if value.upper() in ["1", "T", "TRUE"]: return True if value.upper() in ["0", "F", "FALSE"]: return False raise ValueError(f"Unable to convert {value} to boolean.")
bigcode/self-oss-instruct-sc2-concepts
def linne() -> list: """ Returns the linnean Taxonomy: species, genus, family, order, class, phylum, kingdom """ return ['species', 'genus', 'family', 'order', 'class', 'phylum', 'kingdom']
bigcode/self-oss-instruct-sc2-concepts
def initialize_hyper_parameters(layer_acts, learning_rate): """ Initialize parameters for different levels of the network Arguments: layer_acts -- python array (list) containing the activation functions of each layer in the network learning_rate -- float value used as constant for gradient descent ...
bigcode/self-oss-instruct-sc2-concepts
import requests def get_token(username: str, pw: str, filehost: str = "securefileshare.wales.nhs.uk") -> dict: """ Fetch Bearer token for securefileshare Parameters ---------- username: str pw: str filehost: str Returns ------- dict Diction...
bigcode/self-oss-instruct-sc2-concepts
def avg(lst: list) -> float: """return the average of a list. Preconditions: - all items in lst are ins or floats. """ return sum(lst) / len(lst)
bigcode/self-oss-instruct-sc2-concepts
def _Boolean(value): """Returns a string indication whether a value is true ("truthy"). Args: value: Any value. Returns: String indicating whether the value is true. """ return '*' if value else '-'
bigcode/self-oss-instruct-sc2-concepts
def _intsqrt(v): """Compute int squareroot floor""" c = 0 while c**2 <= v: c += 1 return c - 1
bigcode/self-oss-instruct-sc2-concepts
def and_join(strings): """Join the given ``strings`` by commas with last `' and '` conjuction. >>> and_join(['Korea', 'Japan', 'China', 'Taiwan']) 'Korea, Japan, China, and Taiwan' :param strings: a list of words to join :type string: :class:`collections.abc.Sequence` :returns: a joined string...
bigcode/self-oss-instruct-sc2-concepts
def get_file_name(file_name: str, at: int = -1, split: str = '/') -> str: """ Extracts fileName from a file. Example: get_file_name('/a/b/file_dir/my_file.csv') -> 'my_file' get_file_name('/a/b/file_dir/my_file.csv',at=-2) -> 'file_dir' :param file_name: :param at: fetch name after...
bigcode/self-oss-instruct-sc2-concepts
def limit_issues(issues, limit_len=100000): """Limit the number of issues saved in our DB.""" sorted_issues = sorted(issues, key=lambda x: x['updated_at'], reverse=True) return sorted_issues[:limit_len]
bigcode/self-oss-instruct-sc2-concepts
import glob def expand_file_pattern(pattern): """ use glob to find all files matching the pattern Parameters ---------- pattern : str unix bash shell like search pattern Returns ------- list list of file names matching the pattern """ assert pattern is...
bigcode/self-oss-instruct-sc2-concepts
import itertools def all_neighbors(graph, node): """ Returns all of the neighbors of a node in the graph. If the graph is directed returns predecessors as well as successors. Parameters ---------- graph : NetworkX graph Graph to find neighbors. node : node The node whose nei...
bigcode/self-oss-instruct-sc2-concepts
def dashes(i=1, max_n=12, width=1): """ Dashes for matplotlib. Parameters ---------- i : int, optional Number of dots. The default is 1. max_n : int, optional Maximal Number of dots. The default is 12. width : float, optional Linewidth. The default is 1. Returns...
bigcode/self-oss-instruct-sc2-concepts
def timeseries_train_test_split(X, y, test_size): """ Perform train-test split with respect to time series structure """ # get the index after which test set starts test_index = int(len(X)*(1-test_size)) X_train = X.iloc[:test_index] y_train = y.iloc[:test_index] X_test = X...
bigcode/self-oss-instruct-sc2-concepts
def fontawesome(icon_name, size=""): """ Generate fontawesome syntax for HTML. Usage: {% fontawesome "iconname" %} {% fontawesome "iconname" "size" %} Size values are: lg, 2x, 3x, 4x, 5x """ if len(size) > 0: size = "fa-%s" % size return '<i class="fa fa-%s %s"></i...
bigcode/self-oss-instruct-sc2-concepts
def ask_confirmation(message, yes = 'y', no = 'n', default = False): """ Ask user to confirm something. Ask again if answer other than expected. Arguments: - message (string): message to print (e.g. "Are you sure?") - yes (string): expected value if user confirms - no (s...
bigcode/self-oss-instruct-sc2-concepts
def match_substructures(mol, substructures): """ This function checks if a molecule contains any of the provided substructures. Parameters ---------- mol : Chem.rdchem.Mol An RDKit molecule. substructures: list List of substructures as RDKit molecules. Returns ------- ...
bigcode/self-oss-instruct-sc2-concepts
def _to_time(integ, frac, n=32): """Return a timestamp from an integral and fractional part. Parameters: integ -- integral part frac -- fractional part n -- number of bits of the fractional part Retuns: timestamp """ return integ + float(frac)/2**n
bigcode/self-oss-instruct-sc2-concepts
import math def negative_binomial(x, k, p): """ Evaluate the negative binomial distribution b*(x; k, p) as defined in the textbook. Equivalent to finding the probability of coin flip x to be the k-th head when the probability of getting a head on any one coin flip is p. Found with the equation (...
bigcode/self-oss-instruct-sc2-concepts
import hashlib def sha224hash(text): """Takes in text and returns the sha224 hash""" hash = hashlib.sha224() hash.update(text.encode("utf-8")) return hash.hexdigest()
bigcode/self-oss-instruct-sc2-concepts
def get_alias_names(meta_data): """Returns the list of configured alias names.""" if len(meta_data) <= 0 or 'alias' not in meta_data: return None aliases = meta_data['alias'] if isinstance(aliases, list): # If the alias meta data is a list, ensure that they're strings return list...
bigcode/self-oss-instruct-sc2-concepts
def simplify(seq, drop_zero): """ Combine coefficients of terms with the same variable and optionally drop zero weights and sum up terms without a variable. """ elements = [] seen = {} rhs = 0 for co, var in seq: if co == 0: continue if var is None: ...
bigcode/self-oss-instruct-sc2-concepts
import json def read_json(filename: str): """Read a json file and return data as a dict object""" print('Reading json file ' + filename + '...') f = open(filename, 'r') Instance = json.load(f) f.close() print('Done') return Instance
bigcode/self-oss-instruct-sc2-concepts
def Porcentagem(p, v): """ Retorna a porcentagem de um valor p: porcento v: valor """ return p * v / 100
bigcode/self-oss-instruct-sc2-concepts
def ImportModule(moduleName): """ A convenience method for importing the given module name. @param moduleName: the name of the module to attempt to import @type moduleName: C{str} @return: A reference to the module object that can be queried, introspected, or instantiated. @rtype: C{module}...
bigcode/self-oss-instruct-sc2-concepts
from typing import Optional from typing import List from typing import Tuple def is_valid_atom_index(index: int, coordinates: Optional[dict] = None, existing_indices: Optional[List[int]] = None, ) -> Tuple[bool, str]: """ Check whether an...
bigcode/self-oss-instruct-sc2-concepts
from operator import add def top_five_urls(rdd): """ Return a rdd only with the top 5 url's with more requests by descending order. return type: pyspark.rdd.PipelinedRDD """ urls_rdd = rdd.map(lambda line: line.split('"')[1].split(' ')[1]) count_rdd = urls_rdd.map(lambda url...
bigcode/self-oss-instruct-sc2-concepts
def str_bool(s: str) -> bool: """Converts string ('0' or '1') to boolean""" return s == '1'
bigcode/self-oss-instruct-sc2-concepts
def encode(self, inputs, label): """ Encodes the input into the latent space.""" return self.sess.run(self.z_mean, feed_dict={self.x: inputs, self.y: label})
bigcode/self-oss-instruct-sc2-concepts
import torch from typing import Tuple def get_pair_embedding( pair_info: torch.Tensor, embedding: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor]: """ We are working with N pairs, the k'th pair is (a_k,b_k). Args: - pair_info: (N,6) array representing (bi,hi,wi, bj,hj,wj) ...
bigcode/self-oss-instruct-sc2-concepts
def TabSpacer(number_spaces, string): """Configuration indentation utility function.""" blank_space = ' ' return (blank_space * number_spaces) + string
bigcode/self-oss-instruct-sc2-concepts
def iroot(a, b): """Function to calculate a-th integer root from b. Example: iroot(2, 4) == 2 Parameters: a: int Root power b: int Number to calculate root from Returns: result: int Integer a-th root of b """ if b < 2: ...
bigcode/self-oss-instruct-sc2-concepts
def get_values_matching_key(doc, key): """ Returns iterator of values in 'doc' with the matching 'key'. """ def _get_values(doc, key): if doc is not None: if key in doc: yield doc[key] for z in doc.items(): v = z[1] if isi...
bigcode/self-oss-instruct-sc2-concepts
import ast def redis_hgetall(duthost, db_id, key): """ Get all field name and values for a given key in given redis dataabse :param duthost: DUT host object :param db_id: ID of redis database :param key: Redis Key :return: A dictionary, key is field name, value is field value """ cmd =...
bigcode/self-oss-instruct-sc2-concepts
def angle2NDE(angle): """ Converts an angle in degrees from an East due North coordinate system to a North due East coordinate system Calling this function again will convert it back, since: x = angle2NDE(angle2NDE(x)) Arguments: angle: [float] angle to be converted in degrees. Returns: ...
bigcode/self-oss-instruct-sc2-concepts
def get_hostlist_by_range(hoststring, prefix='', width=0): """Convert string with host IDs into list of hosts. Example: Cobalt RM would have host template as 'nid%05d' get_hostlist_by_range('1-3,5', prefix='nid', width=5) => ['nid00001', 'nid00002', 'nid00003', 'nid00005'] "...
bigcode/self-oss-instruct-sc2-concepts
def fib(n): """ Finding the Fibonacci sequence with seeds of 0 and 1 The sequence is 0,1,1,2,3,5,8,13,..., where the recursive relation is fib(n) = fib(n-1) + fib(n-2) :param n: the index, starting from 0 :return: the sequence """ n = n//1 if n>=1 else 0 # ensure n is non-negative integer if n>1: ...
bigcode/self-oss-instruct-sc2-concepts
def delta_encode_values(df, total, scale=100): """Convert a dataframe from acres to delta-encoded integer scalar values, where original values are first scaled. This can be used to express percent where scale = 100. Values are packed into a caret-delimited string with 0 values omitted, e.g., '<bas...
bigcode/self-oss-instruct-sc2-concepts
def celsius2kelvin(celsius): """ Convert temperature in degrees Celsius to degrees Kelvin. :param celsius: Degrees Celsius :return: Degrees Kelvin :rtype: float """ return celsius + 273.15
bigcode/self-oss-instruct-sc2-concepts
def create_variable(df, name, label, label_map, default_value=0): """ Create a new variable (column) in the specified dataframe. The label of this variable will be appended the global label map. Parameters ---------- df : pandas DataFrame dataframe to add variable/column to name...
bigcode/self-oss-instruct-sc2-concepts
from typing import List def parse_dns(dns: bytes) -> List[bytes]: """Parse the output of grab_dns, returning a list of parsed values that we would like to search. :param dns: Output of grab_dns :type dns: bytes :return: A list of parsed values (Record Name, CNAME, A (HOST)) :rtype: List[bytes] ...
bigcode/self-oss-instruct-sc2-concepts
import re def normalise(s): """ Tokenize on parenthesis, punctuation, spaces and American units followed by a slash. We sometimes give American units and metric units for baking recipes. For example: * 2 tablespoons/30 mililiters milk or cream * 2 1/2 cups/300 grams all-purpose flour ...
bigcode/self-oss-instruct-sc2-concepts
import re def fix_empty_methods(source): """ Appends 'pass' to empty methods/functions (i.e. where there was nothing but a docstring before we removed it =). Example: .. code-block:: python # Note: This triple-single-quote inside a triple-double-quote is also a # pyminifier self...
bigcode/self-oss-instruct-sc2-concepts
import collections def _sort_almost_sorted(almost_sorted_deque, key): """ Sort a deque like that where only the first element is potentially unsorted and should probably be last and the rest of the deque is sorted in descending order. :param collections.deque almost_sorted_deque: The deque of size n...
bigcode/self-oss-instruct-sc2-concepts
def poi_vs_all(true_pep_iz, prep_result): """ true_pep_iz refers to the full set of all peptides. This function returns remapped values of true_pep_iz such that each peptide that is from a POI keeps its true_pep_i whereas all other peptides are remapped to class 0, ie "OTHER" """ df = prep...
bigcode/self-oss-instruct-sc2-concepts
import json def dumps( data ): """Serializes the incoming object as a json string""" return json.dumps( data )
bigcode/self-oss-instruct-sc2-concepts
def load(fl, normalise=False): """ load airfoil args: fl (str): filename kwargs: normalise (bool): flag determining whether the airfoil is normalised to unit length returns: [(x,y),...] airfoil point coordinates """ d = [] print("loading airfoil %s" % ...
bigcode/self-oss-instruct-sc2-concepts
def list_uniq(seq, key=None): """ Removes duplicate elements from a list while preserving the order of the rest. >>> uniq([9,0,2,1,0]) [9, 0, 2, 1] The value of the optional `key` parameter should be a function that takes a single argument and returns a key to test the uniqueness. ...
bigcode/self-oss-instruct-sc2-concepts
def neighbor_equality(w1, w2): """ Test if the neighbor sets are equal between two weights objects Parameters ---------- w1 : W instance of spatial weights class W w2 : W instance of spatial weights class W Returns ------- Boolean Notes ----- Only se...
bigcode/self-oss-instruct-sc2-concepts
def svg_from_file(pathname): """ Read SVG string from a file """ f = open(pathname, 'r') svg = f.read() f.close() return(svg)
bigcode/self-oss-instruct-sc2-concepts
def atom_to_csv(self): """Return Atom as a comma-separated string of its properties.""" return f"{self.chain},{self.atomid},{self.resid},{self.icode},{self.name}"
bigcode/self-oss-instruct-sc2-concepts
def drag_force(c_d,A,rho,v): """ Calculate drag force given c_d,A,rho,v: rho -> density of fluid A -> Frontal area c_d -> Drag coefficient v -> Velocity of bicycle """ return 0.5*c_d*rho*A*v**2
bigcode/self-oss-instruct-sc2-concepts
import time def try_until(func, count=1, sleep=0.5): """ Tries to execute the specified function a number of times. @param func callable to execute @param count number of times to try (default 1) @param sleep seconds to sleep after failed attempts, if any (defaul...
bigcode/self-oss-instruct-sc2-concepts
def docker_mem_used(container_id): """ Bytes of memory used from the docker container. Note: If you have problems with this command you have to enable memory control group. For this you have to add the following kernel parameters: `cgroup_enable=memory swapaccount=1`. See: https://docs.docker.com/e...
bigcode/self-oss-instruct-sc2-concepts
import six def create_mashup_dict(image_meta): """ Returns a dictionary-like mashup of the image core properties and the image custom properties from given image metadata. :param image_meta: metadata of image with core and custom properties """ def get_items(): for key, value in six....
bigcode/self-oss-instruct-sc2-concepts
def get_wind_degrees(value): """ Returns the wind direction in degrees from a dict containing degrees and direction """ try: new_value = float(value['degrees']) except (TypeError, KeyError): return value return new_value
bigcode/self-oss-instruct-sc2-concepts
def strip_hash_bookmark_from_url(url): """Strip the hash bookmark from a string url""" return (url or '').split('#')[0]
bigcode/self-oss-instruct-sc2-concepts
def get_adjacents(i, j, matrix): """given a matrix and a couple of indices finds indexes of points adjacent to given input Args: i ([int]): [index of row] j ([int]): [index of column] matrix ([numpy array]): [matrix of measurements] Returns: [list]: [list of adjacent in...
bigcode/self-oss-instruct-sc2-concepts
from typing import Optional def get_fullname(namespace: Optional[str], name: str) -> str: """ Constructs a fullname from a namespace and a name. """ if namespace: return namespace + "." + name else: return name
bigcode/self-oss-instruct-sc2-concepts
def to_sense_key(syn): """ Returns the sense key for the given synset. @param syn - Synset @return Corresponding sense key as string """ return syn.lemmas()[0].key()
bigcode/self-oss-instruct-sc2-concepts
def generate_exploit() -> str: """This function returns the payload that will print `hacked`. Our payload should cause `run.py` to print out `hacked`. Warnings: 1. `run.py` should print `hacked`, and the testing will be case *sensitive* 2. This time, `run.py` must NOT crash Returns: ...
bigcode/self-oss-instruct-sc2-concepts
import re def parse_logs(response): """ Parses the travis log. :params response: text from the ci log :return: dict that contains error information """ start = "FAILURE: Build failed with an exception." end = "BUILD FAILED" # capture the substring between two strings capture_error ...
bigcode/self-oss-instruct-sc2-concepts
def can_import(name): """Attempt to __import__ the specified package/module, returning True when succeeding, otherwise False""" try: __import__(name) return True except ImportError: return False
bigcode/self-oss-instruct-sc2-concepts
def _find(root: dict, word: str) -> dict: """Find the node after following the path in a trie given by {word}. :arg root: Root of the trie. :arg word: A word. :returns: The node if found, {} otherwise. """ node = root for char in word: if char not in node: return {} ...
bigcode/self-oss-instruct-sc2-concepts
import re def all_matches(iterable, pattern): """ Get all of the items that match a pattern. Args: iterable (Iterable[str]) pattern (str or regular expression) Returns: List[str] """ result = [] for string in iterable: match = re.search(pattern, string) ...
bigcode/self-oss-instruct-sc2-concepts
def diff(a1, a2, shift): """ Compute the diff after shifting array a2 by shift """ if len(a1) != len(a2): raise ValueError("Diff, input arrays must be same length, got {} and {}".format(len(a1), len(a2))) return a1[:(-shift)] - a2[shift:]
bigcode/self-oss-instruct-sc2-concepts
from typing import Optional import random def make_monster_name(is_titan: Optional[bool] = False) -> str: """ Generate a normal boss's name Parameters ---------- is_titan : bool If the boss is a titan Returns ------- str The name of the boss """ # Boss is a t...
bigcode/self-oss-instruct-sc2-concepts
def string_concatenator(string1, string2): """Combines strings together by adding them and returning the combination as an output. Parameters ---------- string1 : string String that will be added to another string. string2 : string String that will be added to anot...
bigcode/self-oss-instruct-sc2-concepts
def first_choice_counts(A,P): """ Return list giving first-choice counts, in decreasing order by count """ count = { } for a in A: count[a] = 0 for ballot in P: if len(ballot)>0: a = ballot[0] count[a] += P[ballot] L = [ (count[a],a) for a in A ] L...
bigcode/self-oss-instruct-sc2-concepts
import itertools def flatten(param_groups): """ Flattens out a pair of list of lists representing a param_group into a single list :param param_groups: The group to flatten :return: The flattened list """ return itertools.chain(*param_groups)
bigcode/self-oss-instruct-sc2-concepts
from typing import Tuple def split_markdown_front_matter(text: str) -> Tuple[str, str]: """ Return a tuple of (front matter, markdown body) strings split from a ``text`` string. Each can be an empty string. This is used when security advisories are provided in this format. """ lines = text.spl...
bigcode/self-oss-instruct-sc2-concepts
def check_input(s): """ This function checks the input is in correct format or not :param s: The input string of each row :return: (bool) If the input format is correct """ for i in range(len(s)): if i % 2 == 1 and s[i] != ' ': return True elif len(s) != 7: return True elif i % 2 == 0 and s[i].isalpha...
bigcode/self-oss-instruct-sc2-concepts
def season(month_number): """ Возвращает название сезона по номеру месяца. :param month_number: номер месяца. :return: строка с названием сезона. """ if month_number in [1, 2, 12]: return 'Winter' elif 3 <= month_number <= 5: return 'Spring' elif 6 <= month_number <= 8: ...
bigcode/self-oss-instruct-sc2-concepts
def decimal_to_string(fnum, no_dec=0): """ Convert a decimal to a string with no_dec decimal places """ res = '' if no_dec == 0: res = str(int(fnum)) else: res = str(round(fnum, no_dec)) return res
bigcode/self-oss-instruct-sc2-concepts
import six def str2list(s): """Returns the string `s` as a list of lines, split by \n""" return s.strip().split('\n') if isinstance(s, six.string_types) else s
bigcode/self-oss-instruct-sc2-concepts
def default_mutation_stength(param): """ Returns the default mutation strength for a parameter. Based on http://www.iue.tuwien.ac.at/phd/heitzinger/node27.html. """ return (param.upper_bound - param.lower_bound) / 10
bigcode/self-oss-instruct-sc2-concepts
def parse_bucket_blob_from_gs_link(path): """Utility to split a google storage path into bucket + blob name. Args: path (str): A string of google cloud storage path (must have gs:// prefix) Returns: (str, str): A tuple of (bucket name, blob name) """ if not path.startswith('gs://')...
bigcode/self-oss-instruct-sc2-concepts
from pathlib import Path import pickle def my_piclke_dump(var, file_name): """ This function saves 'var' in a pickle file with the name 'file_name'. We use the folder 'Pickles' to save all the pickles. Example: file_name = "test" x = 4 var = x my_piclke_dump(var, file_name) :para...
bigcode/self-oss-instruct-sc2-concepts
def cumret(ts): """Calculate cumulative returns for input time series :ts: Time series :returns: Cumulative returns """ return ((ts + 1).cumprod() - 1) * 100
bigcode/self-oss-instruct-sc2-concepts
def get_input_nodes(node): """ Get input nodes of node. Args: node (NodeGraphQt.BaseNode). Returns: list[NodeGraphQt.BaseNode]. """ nodes = {} for p in node.input_ports(): for cp in p.connected_ports(): n = cp.node() nodes[n.id] = n retur...
bigcode/self-oss-instruct-sc2-concepts
def cut_to_pages(h, pgsz): """Cut each data block to pages. Args: h (list): response from `asaloader.ihex.padding_space`. pgsz (int): page size, e.g. 256, 512. Returns: list: data pages """ res = [] for sect in h: sect_addr = sect['address'] sect...
bigcode/self-oss-instruct-sc2-concepts
def apply_diagnostic_inflation(cov_pop_burden_df, param_df, index): """Inflates the target_pop in df Inputs: cov_pop_burden_df - a df with the column 'target_pop' param_df - a df of parameters, must contain the columns 'inflation_factor' index - a string that is one of the i...
bigcode/self-oss-instruct-sc2-concepts
def get_argnames(func): """Get the argument names from a function.""" # Get all positional arguments in __init__, including named # and named optional arguments. `co_varnames` stores all argument # names (including local variable names) in order, starting with # function arguments, so only grab `co...
bigcode/self-oss-instruct-sc2-concepts
def convert_listlike_cols_to_str(df, list_cols, convert_nan=False, nanreplacement = "[]"): """ Convert listlike values in pandas DataFrame to stringlists. Writing a DataFrame to excel and csv raises errors due to presence of listlike or arraylike data. Here, all listlike and arraylike data is converted to ...
bigcode/self-oss-instruct-sc2-concepts
def calculate_percent(numerator, denominator): """Return percentage value, round to 2 digits precision. Parameters: numerator (int): parts of the whole denominator (str): the whole Returns: float: percentage value rounded (00.00) """ percent = (numerator / denominator) * 10...
bigcode/self-oss-instruct-sc2-concepts
from typing import OrderedDict def list_tag_attributes(attributes): """rewrite JATS list-type attribute as an HTML class attribute""" if "list-type" in attributes: list_type_class_map = OrderedDict( [ ('list-type="alpha-lower"', 'class="list list--alpha-lower"'), ...
bigcode/self-oss-instruct-sc2-concepts
import torch def l2_normalize(tensor): """Return tensor / l2_norm(tensor).""" l2_norm = torch.norm(tensor, p=2) tensor /= l2_norm return tensor
bigcode/self-oss-instruct-sc2-concepts
def combo(iter_1, iter_2): """ Assume both iterables has same length combo([1, 2, 3], 'abc') Output: [(1, 'a'), (2, 'b'), (3, 'c')] """ combo_list = [] for x in range(len(iter_1)): tupl = iter_1[x], iter_2[x] combo_list.append(tupl) return combo_list
bigcode/self-oss-instruct-sc2-concepts
def _safe_indexing(X, indices): """Return items or rows from X using indices. copy of sklearn utils safe_indexing with handling of slice as well Allows simple indexing of lists or arrays. Parameters ---------- X : array-like, sparse-matrix, list, pandas.DataFrame, pandas.Series. ...
bigcode/self-oss-instruct-sc2-concepts
import sqlite3 def execute_sql(dbfile,query,params=None): """Execute SQL against a SQLite file Args: dbfile: SQLite database file query: SQL query params: sequence of parameters Returns: list of matching rows """ conn=sqlite3.connect(dbfile) conn.row_f...
bigcode/self-oss-instruct-sc2-concepts
from typing import List def add_bcc(cmd: List[int]): """Compute BCC (= Block Checking Charactor) and append to command sequence. Returns: list of binary data with BCC code. """ check: int = 0x00 for b in cmd: check = check ^ b cmd.append(check) return cmd
bigcode/self-oss-instruct-sc2-concepts
import time def gmtime2ams(unixtime): """Converts float unix time to GMT time in format '2011-12-11 09:00:21.555'""" msec = int((unixtime%1)*1000) tm = time.gmtime(int(unixtime)) s = time.strftime("%Y-%m-%d %H:%M:%S", tm) return s + (".%03d"%msec)
bigcode/self-oss-instruct-sc2-concepts
def BuildSt(st): """Organizes information in a single standard_timings.StandardTiming object. Args: st: A standard_timings.StandardTiming object. Returns: A dictionary of standard timings information. """ return { 'X resolution': st.x_resolution, 'Ratio': st.xy_pixel_ratio, 'Freque...
bigcode/self-oss-instruct-sc2-concepts