seed
stringlengths
1
14k
source
stringclasses
2 values
import re def is_number_regex(s): """ Returns True is string is a number. """ if re.match("^\d+?\.\d+?$", s) is None: return s.isdigit() return True
bigcode/self-oss-instruct-sc2-concepts
def list_all_tables(conn, table_type=None): """Return a list with names of all tables in the database.""" if table_type is not None: sql_query = ( "show full tables where TABLE_TYPE = '{}';" .format(table_type)) else: sql_query = 'show full tables;' cursor = conn....
bigcode/self-oss-instruct-sc2-concepts
def _is_authenticated_query_param(params, token): """Check if message is authentic. Args: params (dict): A dict of the HTTP request parameters. token (str): The predefined security token. Returns: bool: True if the auth param matches the token, False if not. """ return para...
bigcode/self-oss-instruct-sc2-concepts
def nohits_tag_from_conf(conf_file): """ Construct a 'nohits' tag from a fastq_screen conf file The 'nohits' tag is a string of '0' characters, with the number of zeroes equal to the number of 'DATABASE' lines in the conf file. For example: if there are 3 genomes in the file then the 'nohi...
bigcode/self-oss-instruct-sc2-concepts
def fetch_cols(fstream, split_char=','): """ Fetch columns from likwid's output stream. Args: fstream: The filestream with likwid's output. split_car (str): The character we split on, default ',' Returns (list(str)): A list containing the elements of fstream, after splitting at...
bigcode/self-oss-instruct-sc2-concepts
import re def get_event_id_from_url(event_url): """ :param event_url: chronotrack url (str) :return: event id contained in url, None if not present (int) """ event_regex = re.compile("event-([0-9]+)") match = event_regex.search(event_url) if match: return match.group(1) else: ...
bigcode/self-oss-instruct-sc2-concepts
import requests from bs4 import BeautifulSoup import re def get_opera_extension(extension_url): """ Get the file url, extension name and the version of the Opera extension """ response = requests.get(extension_url) html = response.text s = BeautifulSoup(html, "lxml") extension_version = s...
bigcode/self-oss-instruct-sc2-concepts
def flat_dict(od, separator='_', key=''): """ Function to flatten nested dictionary. Each level is collapsed and joined with the specified seperator. :param od: dictionary or dictionary-like object :type od: dict :param seperator: character(s) joining successive levels :type seperator: str...
bigcode/self-oss-instruct-sc2-concepts
def isModerator(forum, user): """Determines whether the given user is a moderator of this forum or not.""" if not forum.moderators: return False if not user: return False for mod in forum.moderators: if mod.user_id() == user.user_id(): return True return False
bigcode/self-oss-instruct-sc2-concepts
from typing import List import glob def get_scripts_from_bin() -> List[str]: """Get all local scripts from bin so they are included in the package.""" return glob.glob("bin/*")
bigcode/self-oss-instruct-sc2-concepts
def parse_singleline_row(line, columns): """ Parses a single-line row from a "net use" table and returns a dictionary mapping from standardized column names to column values. `line` must be a single-line row from the output of `NET USE`. While `NET USE` may represent a single row on multiple ...
bigcode/self-oss-instruct-sc2-concepts
from typing import Sequence def mean(s: Sequence[float]) -> float: """Return the mean of a sequence of numbers""" return sum(s) / len(s)
bigcode/self-oss-instruct-sc2-concepts
def get_bb_center(obj): """Return center coordinates of object bounding box.""" ((x0, y0, z0), (x1, y1, z1)) = obj.GetBoundingBox() xc = (x0 + x1)/2 yc = (y0 + y1)/2 return xc, yc
bigcode/self-oss-instruct-sc2-concepts
def merge_l_t(l, lt): """ Merge a list of tuples lt, each of three values into three lists l. For example: [('a', 'b', 'c'), ('a', 'd', 'e')] -> [['a', 'a'], ['b', 'd'], ['c', 'e']] """ for t in lt: l[0].append(t[1]) l[1].append(t[2]) l[2].append(t[0]) return l
bigcode/self-oss-instruct-sc2-concepts
import socket import time def read_server_and_port_from_file(server_connection_info): """ Reads the server hostname and port from a file, which must contain 'hostname port'. Sleeps if the file doesn't exist or formatting was off (so you can have clients wait for the server to start running.) ...
bigcode/self-oss-instruct-sc2-concepts
import posixpath def join_uri(bucket, *key_paths): """ Compose a bucket and key into an S3 URI. The handling of the components of the key path works similarly to the os.path.join command with the exception of handling of absolute paths which are ignored. :param bucket: Bucket name :param key_path...
bigcode/self-oss-instruct-sc2-concepts
def resultproxy_to_dict(resultproxy): """ Converts SQLAlchemy.engine.result.ResultProxy to a list of rows, represented as dicts. :param resultproxy: SQLAlchemy.engine.result.ResultProxy :return: rows as dicts. """ d, a = {}, [] for rowproxy in resultproxy: # rowproxy.items() retu...
bigcode/self-oss-instruct-sc2-concepts
def server_side(connection, window_info, kwargs): """never allows a signal to be called from WebSockets; this signal can only be called from Python code. This is the default choice. >>> # noinspection PyShadowingNames ... @signal(is_allowed_to=server_side) ... def my_signal(window_info, arg1=None):...
bigcode/self-oss-instruct-sc2-concepts
import ntpath import posixpath def isabs_anywhere(filename): """Is `filename` an absolute path on any OS?""" return ntpath.isabs(filename) or posixpath.isabs(filename)
bigcode/self-oss-instruct-sc2-concepts
def list_to_str(block, delim=", "): """ Convert list to string with delimiter :param block: :param delim: :return: list_str """ list_str = "" for b in block: # print("processing:", block) if len(list_str) > 0: list_str = list_str + delim list_str = li...
bigcode/self-oss-instruct-sc2-concepts
def pal_draw_condition_2(slope): """ Second draw condition of polygonal audience lines. The slope of the lines must be zero or positive Parameters ---------- slope : float Slope of the polygonal audience line. Returns ------- condition_2 : bool True if condition has...
bigcode/self-oss-instruct-sc2-concepts
import re def validate_fqdn(fqdn): """Checks a given string if it's a valid FQDN""" fqdn_validation = re.match( '(?=^.{4,253}$)(^((?!-)[a-zA-Z0-9-]{1,63}(?<!-)\.)+[a-zA-Z]{2,63}$)', fqdn, ) if fqdn_validation is None: return False else: return True
bigcode/self-oss-instruct-sc2-concepts
from typing import OrderedDict def names_to_abbreviations(reporters): """Build a dict mapping names to their variations Something like: { "Atlantic Reporter": ['A.', 'A.2d'], } Note that the abbreviations are sorted by start date. """ names = {} for reporter_key,...
bigcode/self-oss-instruct-sc2-concepts
def get_subgrids(kgrids, params): """Returns subkgrids of multiple given sources """ sub_params = {} sub_summ = {} for source in kgrids: sub_params[source] = kgrids[source].get_params(params=params) sub_summ[source] = kgrids[source].get_summ(params=params) return sub_summ, sub_...
bigcode/self-oss-instruct-sc2-concepts
from pathlib import Path def fullpath(path_or_str=''): """ Path: Expand path relative to current working directory. Accepts string or pathlib.Path input. String can include '~'. Does not expand absolute paths. Does not resolve dots. """ path = Path(path_or_str).expanduser() if not path.is_...
bigcode/self-oss-instruct-sc2-concepts
from decimal import Decimal import datetime import six def is_protected_type(obj): """Determine if the object instance is of a protected type. Objects of protected types are preserved as-is when passed to force_text(strings_only=True). """ return isinstance(obj, six.integer_types + (type(None), f...
bigcode/self-oss-instruct-sc2-concepts
import math def calc_vo2(distance, time): """Calculate VO2 max based on a race result. Taken from Daniels and Gilbert. See, for example: * http://www.simpsonassociatesinc.com/runningmath1.htm * "The Conditioning for Distance Running -- the Scientific Aspects" Parameters ---------- distan...
bigcode/self-oss-instruct-sc2-concepts
from typing import OrderedDict def dict_sort(in_dict: dict)-> OrderedDict: """ sort dict by values, 给字典排序(依据值大小) Args: in_dict: dict, eg. {"游戏:132, "旅游":32} Returns: OrderedDict """ in_dict_sort = sorted(in_dict.items(), key=lambda x:x[1], reverse=True) return OrderedDict(i...
bigcode/self-oss-instruct-sc2-concepts
def mc_to_float(value): """ Convert from millicents to float Args: value: millicent number Returns: value in float """ return float(value) / (100 * 1000)
bigcode/self-oss-instruct-sc2-concepts
def get_exploding_values(list_of_values: list) -> tuple: """ This function will determine which value is the largest in the list, and will return a tuple containing the information that will have the largest percentage within the pie chart pop off. :param list_of_values: :return: A tuple of 'exp...
bigcode/self-oss-instruct-sc2-concepts
import string def safe_string(unsafe_str, replace_char="_"): """ Replace all non-ascii characters or digits in provided string with a replacement character. """ return ''.join([c if c in string.ascii_letters or c in string.digits else replace_char for c in unsafe_str])
bigcode/self-oss-instruct-sc2-concepts
def arraylike(thing): """Is thing like an array?""" return isinstance(thing, (list, tuple))
bigcode/self-oss-instruct-sc2-concepts
def IssueIsInHotlist(hotlist, issue_id): """Returns T/F if the issue is in the hotlist.""" return any(issue_id == hotlist_issue.issue_id for hotlist_issue in hotlist.items)
bigcode/self-oss-instruct-sc2-concepts
from typing import Type from typing import Any import types from typing import List import inspect def get_all_subclasses_in_module( parent_class: Type[Any], module: types.ModuleType, exclude_private: bool = True, exclude_abstract: bool = False) -> List[Type[Any]]: """Returns all classes derived fro...
bigcode/self-oss-instruct-sc2-concepts
def tag(*tags): """Decorator to add tags to a test class or method.""" def decorator(obj): if len(getattr(obj, '__bases__', [])) > 1: setattr(obj, 'tags', set(tags).union(*[ set(base.tags) for base in obj.__bases__ if hasattr(base, 'tags') ...
bigcode/self-oss-instruct-sc2-concepts
def _round_pow_2(value): """Round value to next power of 2 value - max 16""" if value > 8: return 16 if value > 4: return 8 if value > 2: return 4 return value
bigcode/self-oss-instruct-sc2-concepts
def restricted(func): """ A decorator to confirm a user is logged in or redirect as needed. """ def login(self, *args, **kwargs): # Redirect to login if user not logged in, else execute func. if not self.current_user: self.redirect("/login") else: ...
bigcode/self-oss-instruct-sc2-concepts
def binary_search_2(arr, elem, start, end): """ A method to perform binary search on a sorted array. :param arr: The array to search :param elem: The element to search :param start: start position from where to start searching :param end: start position till where to search :return: The in...
bigcode/self-oss-instruct-sc2-concepts
def get_data_from_epochs(epochs): """ epochs: mne.Epochs returns np array of shape (nb_epochs, sampling_rate*epoch_length) """ return epochs.get_data().squeeze()
bigcode/self-oss-instruct-sc2-concepts
def product_from_branch(branch): """ Return a product name from this branch name. :param branch: eg. "ceph-3.0-rhel-7" :returns: eg. "ceph" """ if branch.startswith('private-'): # Let's just return the thing after "private-" and hope there's a # product string match somewhere in...
bigcode/self-oss-instruct-sc2-concepts
def pollution_grade(aqi: int) -> int: """Translate aqi levels to pollution grade.""" if aqi <= 50: return 0 elif 50 < aqi <= 100: return 1 elif 100 < aqi <= 150: return 2 elif 150 < aqi <= 200: return 3 elif 200 < aqi <= 300: return 4 else: return 5
bigcode/self-oss-instruct-sc2-concepts
def test_create_dataframe(data_frame, list_of_col): """ Testing whether a dataframe satisfy the following conditions: The DataFrame contains only the columns that you specified as the second argument. The values in each column have the same python type There are at least 10 rows in the DataFrame. ...
bigcode/self-oss-instruct-sc2-concepts
def maybe_coeff_key(grid, expr): """ True if `expr` could be the coefficient of an FD derivative, False otherwise. """ if expr.is_Number: return True indexeds = [i for i in expr.free_symbols if i.is_Indexed] return any(not set(grid.dimensions) <= set(i.function.dimensions) for i in index...
bigcode/self-oss-instruct-sc2-concepts
import re def row_skipper(file): """ Count how many rows are needed to be skipped in the parsed codebook. Parameters: file (character): File name of the parsed codebook Returns: count: The number of lines to be skipped """ with open(file, 'r') as codebook: count = 0 ...
bigcode/self-oss-instruct-sc2-concepts
def select_year(movie_list:list, year:int): """ Select movies filmed in a specific year and returns a list of tuples (name, location) """ n_year_movies = [] for movie in movie_list: if year in movie: n_year_movies.append((movie[0],movie[-1])) print(f"Selected {len(n_year_movi...
bigcode/self-oss-instruct-sc2-concepts
import ast def robust_literal_eval(val): """Call `ast.literal_eval` without raising `ValueError`. Parameters ---------- val : str String literal to be evaluated. Returns ------- Output of `ast.literal_eval(val)', or `val` if `ValueError` was raised. """ try: retu...
bigcode/self-oss-instruct-sc2-concepts
def hasattr_explicit(cls, attr): """Returns if the given object has explicitly declared an attribute""" try: return getattr(cls, attr) != getattr(super(cls, cls), attr, None) except AttributeError: return False
bigcode/self-oss-instruct-sc2-concepts
def link_is_valid(link_info, query_words, mode="all"): """ Tests if a link is valid to keep in search results, for a given query :param link_info: a dict with keys "url" and "text" :param query_words: a list of query words :param mode: can be "all" (default), or "any" :return: True or False ...
bigcode/self-oss-instruct-sc2-concepts
def error_list (train_sents, test_sents, radius=2): """ Returns a list of human-readable strings indicating the errors in the given tagging of the corpus. :param train_sents: The correct tagging of the corpus :type train_sents: list(tuple) :param test_sents: The tagged corpus :type test_sen...
bigcode/self-oss-instruct-sc2-concepts
def pascal_case_to_snake_case(input_string): """ Converts the input string from PascalCase to snake_case :param input_string: (str) a PascalCase string :return: (str) a snake_case string """ output_list = [] for i, char in enumerate(input_string): if char.capitalize() == char: # if ...
bigcode/self-oss-instruct-sc2-concepts
def to_dict(d): """ Convert EasyDict to python dict recursively. Args: d (EasyDict): dictionary to convert Returns: dict """ d = d.copy() for k, v in d.items(): if isinstance(d[k], dict): d[k] = to_dict(d[k]) return dict(d)
bigcode/self-oss-instruct-sc2-concepts
from pathlib import Path def get_file_size_in_bytes_3(file_path): """ Get size of file at given path in bytes""" # get file object file_obj = Path(file_path) # Get file size from stat object of file size = file_obj.stat().st_size return size
bigcode/self-oss-instruct-sc2-concepts
from typing import List import re def get_assignees(content: str) -> List[str]: """Gets assignees from comment.""" regex = r"\+([a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+)" matches = re.findall(regex, content) return [m for m in matches]
bigcode/self-oss-instruct-sc2-concepts
def unpad_list(listA, val=-1): """Unpad list of lists with which has values equal to 'val'. Parameters ---------- listA : list List of lists of equal sizes. val : number, optional Value to unpad the lists. Returns ------- list A list of lists without the padding...
bigcode/self-oss-instruct-sc2-concepts
def decode_outputs(probs, inds, decoder): """ Decode from network probabilities and compute CER Arguments: probs: Tensor of character probabilities inds: List of character indices for ground truth decoder: instance of a Decoder Returns: Tuple of (ground truth transcript,...
bigcode/self-oss-instruct-sc2-concepts
from typing import Tuple def _get_ds_file_offset( parm_start: int, span: Tuple[int, int], inclusive: bool = False ) -> Tuple[int, int]: """Get the file offsets for the parameter. :param parm_start: The start position of the parm. :param span: The span of the parm data. :param inclusive: Whether t...
bigcode/self-oss-instruct-sc2-concepts
def _join_tokens_to_string(tokens, master_char_set): """Join a list of string tokens into a single string.""" token_is_master = [t[0] in master_char_set for t in tokens] ret = [] for i, token in enumerate(tokens): if i > 0 and token_is_master[i - 1] and token_is_master[i]: ret.append(u" ") ret.app...
bigcode/self-oss-instruct-sc2-concepts
def parse_games_wins(r): """ Used to parse the amount of games won by a team. """ return int(r.get("wedWinst", 0))
bigcode/self-oss-instruct-sc2-concepts
def _num_two_factors(x): """return number of times x is divideable for 2""" if x <= 0: return 0 num_twos = 0 while x % 2 == 0: num_twos += 1 x //= 2 return num_twos
bigcode/self-oss-instruct-sc2-concepts
def isaudio(file: str)->bool: """ test whether param file is has a known ending for audio formats :param file: str :return: bool """ audio_files = ["mp3", "aac", "ogg", "m4a"] end = file.rsplit(".", 1)[-1] return True if end in audio_files else False
bigcode/self-oss-instruct-sc2-concepts
def choose_gc_from_config(config): """Return a (GCClass, GC_PARAMS) from the given config object. """ if config.translation.gctransformer != "framework": # for tests config.translation.gc = "marksweep" # crash if inconsistent classes = {"marksweep": "marksweep.MarkSweepGC", ...
bigcode/self-oss-instruct-sc2-concepts
import re def format_kwargs(string, *args): """Return set or dict (optional) of keyword arguments ({keyword}) in provided text""" keywords = {x.strip('{}') for x in re.findall(r'((?<!{){(?!{).*?(?<!})}(?!}))', string)} if args and args[0] == "dict": return {sub: "" for sub in keywords} return ...
bigcode/self-oss-instruct-sc2-concepts
import random def randcolor(mode): """Makes a random color for the given mode""" ri = lambda v: random.randint(0, v) if mode == 'L': return ri(255) elif mode == '1': return ri(1) elif mode == 'I': return ri(2**23-1) elif mode == 'F': return random.random() e...
bigcode/self-oss-instruct-sc2-concepts
def merge_lists(two_d_list): """Merges a 2d array into a 1d array. Ex: [[1,2],[3,4]] becomes [1,2,3,4]""" # I know this is a fold / reduce, but I got an error when I tried # the reduce function? return [i for li in two_d_list for i in li]
bigcode/self-oss-instruct-sc2-concepts
def char(int): """ CHAR int outputs the character represented in the ASCII code by the input, which must be an integer between 0 and 255. """ return chr(int)
bigcode/self-oss-instruct-sc2-concepts
def to_port(port_str): """ Tries to convert `port_str` string to an integer port number. Args: port_str (string): String representing integer port number in range from 1 to 65535. Returns: int: Integer port number. Raises: ValueError: If `port_str` ...
bigcode/self-oss-instruct-sc2-concepts
def get_best_alignment(record_list): """ Get the best alignment from a list of alignments. The best alignment has the lowest distance to the reference. If more than one alignment has the minimum distance, then the first one in the list is returned. :param record_list: List of records. :return: Bes...
bigcode/self-oss-instruct-sc2-concepts
def isAdditivePrimaryColor(color): """ return True if color is a string equal to "red", "green" or "blue", otherwise False >>> isAdditivePrimaryColor("blue") True >>> isAdditivePrimaryColor("black") False >>> isAdditivePrimaryColor(42) False >>> """ return ( (color == "r...
bigcode/self-oss-instruct-sc2-concepts
def map_attributes(properties, filter_function): """Map properties to attributes""" if not isinstance(properties, list): properties = list(properties) return dict( map( lambda x: (x.get("@name"), x.get("@value")), filter(filter_function, properties), ) )
bigcode/self-oss-instruct-sc2-concepts
def checking_features(columns:list, lst_features:list) -> bool: """ Parameters: * columns [list]: list of columns in the dataframe. * lst_features [list]: list of required features. Return: True/False [bool]: If all / not all the required features are in the dataframe. """ if all([feat in columns f...
bigcode/self-oss-instruct-sc2-concepts
def _Delta(a, b): """Compute the delta for b - a. Even/odd and odd/even are handled specially, as described above.""" if a+1 == b: if a%2 == 0: return 'EvenOdd' else: return 'OddEven' if a == b+1: if a%2 == 0: return 'OddEven' else: return 'EvenOdd' return b - a
bigcode/self-oss-instruct-sc2-concepts
import difflib def diff_files(filename1, filename2): """ Return string with context diff, empty if files are equal """ with open(filename1) as file1: with open(filename2) as file2: diff = difflib.context_diff(file1.readlines(), file2.readlines()) res = "" for line in diff: ...
bigcode/self-oss-instruct-sc2-concepts
def min_list(lst): """ A helper function for finding the minimum of a list of integers where some of the entries might be None. """ if len(lst) == 0: return None elif len(lst) == 1: return lst[0] elif all([entry is None for entry in lst]): return None return min([entr...
bigcode/self-oss-instruct-sc2-concepts
def inherit_params( new_params, old_params): """Implements parameter inheritance. new_params inherits from old_params. This only does the top level params, matched by name e.g., layer0/conv is treated as a param, and not layer0/conv/kernel Args: new_params: the params doing the inheriting ol...
bigcode/self-oss-instruct-sc2-concepts
def tabescape(unescaped): """ Escape a string using the specific Dovecot tabescape See: https://github.com/dovecot/core/blob/master/src/lib/strescape.c """ return unescaped.replace(b"\x01", b"\x011")\ .replace(b"\x00", b"\x010")\ .replace(b"\t", b"\x01t")\ ...
bigcode/self-oss-instruct-sc2-concepts
import re def header_anchor(text, level): """ Return a sanitised anchor for a header. """ # Everything lowercase sanitised_text = text.lower() # Get only letters, numbers, dashes, spaces, and dots sanitised_text = "".join(re.findall("[a-z0-9-\\. ]+", sanitised_text)) # Remove multip...
bigcode/self-oss-instruct-sc2-concepts
import re def parse_show_dhcp_server(raw_result): """ Parse the 'show dhcp-server' command raw output. :param str raw_result: vtysh raw result string. :rtype: dict :return: The parsed result of the show ntp trusted-keys command \ in a dictionary of the form: :: { ...
bigcode/self-oss-instruct-sc2-concepts
def list_to_err(errs): """convert list of error strings to a single string :param errs: list of string errors :type errs: [str] :returns: error message :rtype: str """ return str.join('\n\n', errs)
bigcode/self-oss-instruct-sc2-concepts
def gcd(a, b): """ Greatest common divisor (greatest common factor) Notes --------- Euclidean algorithm: a > b > r_1 > r_2 > ... > r_n a = b*q + r b = r_1*q_1 + r_2 ... r_n-1 = r_n*q_n gcd(a,b) = gcd(b,r) gcd(a,0) = a """ while b != 0: a, b = b, a % ...
bigcode/self-oss-instruct-sc2-concepts
def group_device_names(devices, group_size): """Group device names into groups of group_size. Args: devices: list of strings naming devices. group_size: int >= 1 Returns: list of lists of devices, where each inner list is group_size long, and each device appears at least once in an inner list....
bigcode/self-oss-instruct-sc2-concepts
import time def gmtime_for_datetime(dt): """ Pass in a datetime object, and get back time.gmtime """ return time.gmtime(time.mktime(time.strptime(dt.strftime("%Y-%m-%d %H:%M:%S"), "%Y-%m-%d %H:%M:%S"))) if dt is not None else None
bigcode/self-oss-instruct-sc2-concepts
def is_palindrome(s): """ Check whether a string is a palindrome or not. For example: is_palindrome('aba') -> True is_palindrome('bacia') -> False is_palindrome('hutuh') -> True Parameters ---------- s : str String to check. Returns ------- bool ...
bigcode/self-oss-instruct-sc2-concepts
def suffix(n: int) -> str: """Return number's suffix Example: 1 -> "st" 42 -> "nd" 333 -> "rd" """ return "th" if 11 <= n <= 13 else {1: "st", 2: "nd", 3: "rd"}.get(n % 10, "th")
bigcode/self-oss-instruct-sc2-concepts
def switch_string_to_numeric(argument): """ Switch status string to numeric status (FLAT - POOR: 0, POOR - POOR TO FAIR = 1, FAIR TO GOOD - EPIC = 2) """ switcher = { "FLAT": 0, "VERY POOR": 0, "POOR": 0, "POOR TO FAIR":1, "FAIR":1, "FAIR TO GOOD":2, ...
bigcode/self-oss-instruct-sc2-concepts
def get_printable_banner(input_str=None): """ Returns a string that when printed shows a banner with the given string in the center. Args: input_str: str. Any string of moderate length roughly less than 30 that you want placed inside a pound/hashtag (#) banner. Returns:...
bigcode/self-oss-instruct-sc2-concepts
def weight_combination(entropy, contrast, visibility, alpha1, alpha2, alpha3): """ Combining the entropy, the contrast and the visibility to build a weight layer :param entropy: The local entropy of the image, a grayscale image :param contrast: The local contrast of the image, a grayscale image :pa...
bigcode/self-oss-instruct-sc2-concepts
def mk_inclusion_filter(include=(), key=None): """ Creates a function to perform inclusion filtering (i.e. "filter-in if x is in include list") :param include: a list-like of elements for an inclusion filter :param key: None (default), a callable, or a hashable. If * None, the filter will be det...
bigcode/self-oss-instruct-sc2-concepts
def map256(vals): """ Map dictionary key values to a 0-255 range. Your input dictionary will have a smaller range than 0-256. For instance you may have 49-91. The return dictionary will contain keys 0, 255 and some values in between. The point is to normalize the span of the input acrouss and 8-bit...
bigcode/self-oss-instruct-sc2-concepts
def _calc_tstop(n_bins, bin_size, t_start): """ Calculates the stop point from given parameters. Calculates the stop point `t_stop` from the three parameters `n_bins`, `bin_size`, `t_start`. Parameters ---------- n_bins : int Number of bins bin_size : pq.Quantity Size o...
bigcode/self-oss-instruct-sc2-concepts
import requests def goa_calmgr(user_request, verbose=False): """ Query the GOA galmgr API Parameters user_request: Search request URL string, it should not contain 'calmgr' \ Return request_xml: Query result in XML format """ response = requests.get( 'https://arc...
bigcode/self-oss-instruct-sc2-concepts
def camel_case_to_under_score(x): """ CamelCase --> camel_case :param x: (str) The CamelCase string to be converted to pep8. :return: (str) The formatted pep8 string. lower case upper case prefixed with underscore. """ string = '' x = str(x) for i,...
bigcode/self-oss-instruct-sc2-concepts
def _datesplit(timestr): """ Split a unit string for time into its three components: unit, string 'since' or 'as', and the remainder """ try: (units, sincestring, remainder) = timestr.split(None, 2) except ValueError: raise ValueError(f'Incorrectly formatted date-time unit_strin...
bigcode/self-oss-instruct-sc2-concepts
import requests import json def move_hosts_to_new_group(platform, key, client, group): """ Move hosts defined by a filter to a new group, specified by group ID. :param platform: URL of the RiskSense platform to be queried. :type platform: str :param key: API Key. :type key: ...
bigcode/self-oss-instruct-sc2-concepts
def get_bollinger_bands(rm, rstd): """Return upper and lower Bollinger Bands.""" upper_band = rm + 2 * rstd lower_band = rm - 2 * rstd return upper_band, lower_band
bigcode/self-oss-instruct-sc2-concepts
import calendar def timestamp_from_datetime(dt): """ Returns a timestamp from datetime ``dt``. Note that timestamps are always UTC. If ``dt`` is aware, the resulting timestamp will correspond to the correct UTC time. >>> timestamp_from_datetime(datetime.datetime(1970, 1, 1, 0, 20, 34, 500000)) ...
bigcode/self-oss-instruct-sc2-concepts
def _parse_bond_line( line ): """Parse an AMBER frcmod BOND line and return relevant parameters in a dictionary. AMBER uses length and force constant, with the factor of two dropped. Here we multiply by the factor of two before returning. Units are angstroms and kilocalories per mole per square angstrom.""" tm...
bigcode/self-oss-instruct-sc2-concepts
def _find_code_cell_idx(nb, identifier): """ Find code cell index by provided ``identifier``. Parameters ---------- nb : dict Dictionary representation of the notebook to look for. identifier : str Unique string which target code cell should contain. Returns ------- ...
bigcode/self-oss-instruct-sc2-concepts
def _get_QActionGroup(self): """ Get checked state of QAction """ if self.checkedAction(): return self.actions().index(self.checkedAction()) return None
bigcode/self-oss-instruct-sc2-concepts
import time def seconds_per_run(op, sess, num_runs=50): """Number of seconds taken to execute 'op' once on average.""" for _ in range(2): sess.run(op) start_time = time.time() for _ in range(num_runs): sess.run(op) end_time = time.time() time_taken = (end_time - start_time) / num_runs return t...
bigcode/self-oss-instruct-sc2-concepts
def to_pandas(modin_obj): """Converts a Modin DataFrame/Series to a pandas DataFrame/Series. Args: obj {modin.DataFrame, modin.Series}: The Modin DataFrame/Series to convert. Returns: A new pandas DataFrame or Series. """ return modin_obj._to_pandas()
bigcode/self-oss-instruct-sc2-concepts