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.cursor() cursor.execute(sql_query) return [name for (name, _) in cursor]
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 params.get('auth') == token
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 'nohits' tag will look like '000'. """ ndatabases = 0 with open(conf_file,'r') as conf: for line in conf: if line.startswith("DATABASE\t"): ndatabases += 1 return '0' * ndatabases
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 split_char. """ return fstream.readline().strip().split(split_char)
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: return None
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.findAll("dd")[2].text extension_name = re.findall(r"details\/(.*)\/", extension_url)[0] file_url = f"https://addons.opera.com/extensions/download/{extension_name}/" return file_url, extension_name, extension_version
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 :param key: concatenated keys :type key: str :returns: unnested dictionary :rtype: dict """ return {str(key).replace(' ','_') + separator + str(k) if key else k : v for kk, vv in od.items() for k, v in flat_dict(vv, separator, kk).items() } if isinstance(od, dict) else {key:od}
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 lines, `line` must be a whole row on a single line. `columns` must be a list of `NetUseColumn` objects that correctly parses `string`. """ return {column.name: column.extract(line) for column in columns}
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.) :return: tuple containing hostname and port :rtype: Tuple """ while True: try: with open(server_connection_info, 'r') as f: (hostname, port) = f.readline().split(' ') port = int(port) if hostname == socket.gethostname(): hostname = 'localhost' return (hostname, port) except (ValueError, FileNotFoundError) as e: time.sleep(1) continue
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_paths: Components of the key path. :return: S3 URI string """ # strip any leading slashes bucket = bucket[1:] if bucket.startswith('/') else bucket key_paths = [path[1:] if path.startswith('/') else path for path in key_paths] return 's3://{}'.format(posixpath.join(bucket, *key_paths))
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() returns an array like [(key0, value0), (key1, value1)] for column, value in rowproxy.items(): # build up the dictionary d = {**d, **{column: value}} a.append(d) return a
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): ... # noinspection PyUnresolvedReferences ... print(window_info, arg1) """ return False
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 = list_str + str(b) return list_str
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 passed, otherwise False. """ if slope < 0: return False else: return True
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, data_list in reporters.items(): for data in data_list: abbrevs = data["editions"].keys() # Sort abbreviations by start date of the edition sort_func = lambda x: str(data["editions"][x]["start"]) + x abbrevs = sorted(abbrevs, key=sort_func) names[data["name"]] = abbrevs sorted_names = OrderedDict(sorted(names.items(), key=lambda t: t[0])) return sorted_names
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_params
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_absolute(): path = Path.cwd().resolve()/path return path
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), float, Decimal, datetime.datetime, datetime.date, datetime.time))
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 ---------- distance : float Race distance in meters. time : float Race result in seconds. Returns ------- vo2_max : float Estimated VO2 max. """ minutes = time/60.0 velocity = distance/minutes percent_max = (0.8 + 0.1894393*math.exp(-0.012778*minutes) + 0.2989558*math.exp(-0.1932605*minutes)) vo2 = (-4.60 + 0.182258*velocity + 0.000104*pow(velocity, 2)) return vo2/percent_max
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(in_dict_sort)
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 'exploding' values for a pie chart. """ exploding_values = [0.0 for value in list_of_values] largest_value = list_of_values[0] pop_out_index = 0 # iterate through the list of values and find the index that contains the largest value. for i, value in enumerate(list_of_values): if value > largest_value: largest_value = value pop_out_index = i # set the popout value exploding_values[pop_out_index] = 0.1 return tuple(exploding_values)
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 from parent_class in the module. Args: parent_class: Class object from which the subclasses must be derived. module: Module to scan for subclasses. exclude_private: If True, do not include private classes. exclude_abstract: If True, do not include abstract classes. Returns: Subclasses of parent_class defined in the module. """ subclasses = [] for name, member in inspect.getmembers(module): if (inspect.isclass(member) and (not exclude_abstract or not inspect.isabstract(member)) and (not exclude_private or not name.startswith("_")) and issubclass(member, parent_class)): subclasses.append(member) return subclasses
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') ])) elif hasattr(obj, 'tags'): obj.tags = obj.tags.union(tags) else: setattr(obj, 'tags', set(tags)) return obj return decorator
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: func(self, *args, **kwargs) return login
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 index at which the element is found, -1 if not found """ if start <= end: mid = int((start + end) / 2) if arr[mid] == elem: return mid elif elem < arr[mid]: return binary_search_2(arr, elem, start, mid - 1) else: return binary_search_2(arr, elem, mid + 1, end) else: return -1
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 there. return branch[8:] # probably not gonna work for "stream" branches :( parts = branch.split('-', 1) return parts[0]
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. Input: pandas dataframe, a list of column names Output: True or False """ temp = list(data_frame) for i in temp: if i not in list_of_col: return False if len(data_frame) < 10: return False for i in range(len(temp)): prev_type = type(data_frame[temp[i]][0]) for j in range(1, len(data_frame)): if type(data_frame[temp[i]][j]) != prev_type: return False prev_type = type(data_frame[temp[i]][j]) return True
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 indexeds)
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 for line in codebook: count += 1 if re.search('(NAME)[\t]+(SIZE)[\t]+(DESCRIPTION)[\t]+(LOCATION)', line): count -= 1 break return count
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_movies)} movies/shows filmed in {year}.") return n_year_movies
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: return ast.literal_eval(val) except ValueError: return val
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 If <mode> is "all", will return True if all query words are be present in either url or text. If <mode> is "any", will return True if any of the query words are be present in either url or text. """ if not link_info["url"].startswith("http"): return False if mode == "all": combiner = all elif mode == "any": combiner = any else: combiner = all result = combiner( [ word in link_info["url"] or link_info["text"] and word in link_info["text"].lower() for word in query_words ] ) return result
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_sents: list(tuple) :param radius: How many tokens on either side of a wrongly-tagged token to include in the error string. For example, if radius=2, each error string will show the incorrect token plus two tokens on either side. :type radius: int """ hdr = (('%25s | %s | %s\n' + '-'*26+'+'+'-'*24+'+'+'-'*26) % ('left context', 'word/test->gold'.center(22), 'right context')) errors = [hdr] for (train_sent, test_sent) in zip(train_sents, test_sents): for wordnum, (word, train_pos) in enumerate(train_sent): test_pos = test_sent[wordnum][1] if train_pos != test_pos: left = ' '.join('%s/%s' % w for w in train_sent[:wordnum]) right = ' '.join('%s/%s' % w for w in train_sent[wordnum+1:]) mid = '%s/%s->%s' % (word, test_pos, train_pos) errors.append('%25s | %s | %s' % (left[-25:], mid.center(22), right[:25])) return errors
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 the char is already capitalized if i == 0: output_list.append(char.lower()) # the first char is only made lowercase else: output_list.append('_') output_list.append(char.lower()) # other capital chars are prepended with an underscore else: output_list.append(char) output = ''.join(output_list) return output
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 values. Examples -------- Remove the padding values of a list of lists. >>> from dbcollection.utils.pad import unpad_list >>> unpad_list([[1,2,3,-1,-1],[5,6,-1,-1,-1]]) [[1, 2, 3], [5, 6]] >>> unpad_list([[5,0,-1],[1,2,3,4,5]], 5) [[0, -1], [1, 2, 3, 4]] """ # pad list with zeros in order to have all lists of the same size assert isinstance(listA, list), 'Input must be a list. Got {}, expected {}' \ .format(type(listA), type(list)) if isinstance(listA[0], list): return [list(filter(lambda x: x != val, l)) for i, l in enumerate(listA)] else: return list(filter(lambda x: x != val, listA))
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, decoded transcript, CER) """ ground_truth = decoder.process_string(decoder.convert_to_string(inds), remove_repetitions=False) decoded_string = decoder.decode(probs) cer = decoder.cer(ground_truth, decoded_string) / float(len(ground_truth)) return ground_truth, decoded_string, cer
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 to include the start and end chars. :return: The file offsets for the parameter. """ extra_offset = 0 if inclusive else 1 return parm_start + span[0] + extra_offset, parm_start + span[1] - extra_offset
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.append(token) return "".join(ret)
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", "statistics": "marksweep.PrintingMarkSweepGC", "semispace": "semispace.SemiSpaceGC", "generation": "generation.GenerationGC", "hybrid": "hybrid.HybridGC", "markcompact" : "markcompact.MarkCompactGC", } try: modulename, classname = classes[config.translation.gc].split('.') except KeyError: raise ValueError("unknown value for translation.gc: %r" % ( config.translation.gc,)) module = __import__("pypy.rpython.memory.gc." + modulename, globals(), locals(), [classname]) GCClass = getattr(module, classname) return GCClass, GCClass.TRANSLATION_PARAMS
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 keywords
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() elif mode == 'RGB': return (ri(255), ri(255), ri(255)) elif mode == 'RGBA': return (ri(255), ri(255), ri(255), ri(255)) else: assert 1 == 0, 'invalid mode %s' % (mode)
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` could not be converted to integer in range from 1 to 65535. """ try: port_int = int(port_str) except ValueError: raise ValueError("argument must represent an integer number") if port_int<1 or port_int>65535: raise ValueError("argument must be an integer in range from 1 to 65535") return port_int
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: Best record in `record_list`. """ best_alignment = record_list[0] for alignment in record_list[1:]: if alignment.compare(best_alignment) < 0: best_alignment = alignment return best_alignment
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 == "red" ) or (color == "green" ) or (color == "blue") )
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 for feat in lst_features]): return True else: return False
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: res += line # pylint: disable=consider-using-join return res
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([entry for entry in lst if entry is not None])
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 old_params: the params to be inherited Returns: inherited_params: old_params that were inherited trainable_params: new_params that were not inherited """ inherited_params = {} trainable_params = {} for param in new_params.keys(): if param in old_params: inherited_params[param] = old_params[param] else: trainable_params[param] = new_params[param] return inherited_params, trainable_params
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")\ .replace(b"\n", b"\x01n")\ .replace(b"\r", b"\x01r")
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 multiple spaces sanitised_text = "-".join(sanitised_text.split()) return sanitised_text
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: :: { 'pools': [ { 'pool_name': 'CLIENTS-VLAN60', 'start_ip': '192.168.60.10', 'end_ip': '192.168.60.250', 'netmask': '255.255.255.0', 'broadcast': '192.168.60.255', 'prefix_len': '*', 'lease_time': '1440', 'static_bind': 'False', 'set_tag': '*', 'match_tag': '*' } ], 'options': [ { 'option_number': '15', 'option_name': '*', 'option_value': 'tigerlab.ntl.com', 'ipv6_option': 'False', 'match_tags': '*' }, { 'option_number': '*', 'option_name': 'Router', 'option_value': '192.168.60.254', 'ipv6_option': 'False', 'match_tags': '*' }, ] } """ dhcp_dynamic_re = ( r'(?P<pool_name>[\w_\-]+)' r'\s+(?P<start_ip>[\d\.:]+)' r'\s+(?P<end_ip>[\d\.:]+)' r'\s+(?P<netmask>[\d\.*]+)' r'\s+(?P<broadcast>[\d\.*]+)' r'\s+(?P<prefix_len>[\w\*/]+)' r'\s+(?P<lease_time>[\d]+)' r'\s+(?P<static_bind>True|False)' r'\s+(?P<set_tag>[\w\*]+)' r'\s+(?P<match_tag>[\w\*]+)' ) dhcp_options_re = ( r'\n(?P<option_number>[\d\*]+)' r'\s+(?P<option_name>[\w\*]+)' r'\s+(?P<option_value>[\w_\-\.]+)' r'\s+(?P<ipv6_option>True|False)' r'\s+(?P<match_tags>[\w\*]+)' ) result = {} pools_list = [] options_list = [] for output in re.finditer(dhcp_dynamic_re, raw_result): dhcp_dynamic = output.groupdict() pools_list.append(dhcp_dynamic) result['pools'] = pools_list for output in re.finditer(dhcp_options_re, raw_result): dhcp_options = output.groupdict() options_list.append(dhcp_options) result['options'] = options_list assert result return result
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 % b return 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. If len(devices) % group_size = 0 then each device will appear exactly once. Raises: ValueError: group_size > len(devices) """ num_devices = len(devices) if group_size > num_devices: raise ValueError('only %d devices, but group_size=%d' % (num_devices, group_size)) num_groups = ( num_devices // group_size + (1 if (num_devices % group_size != 0) else 0)) groups = [[] for i in range(num_groups)] for i in range(0, num_groups * group_size): groups[i % num_groups].append(devices[i % num_devices]) return groups
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 Is the string input a palindrome. """ if len(s) == 1: return True else: return s[0] == s[-1] and is_palindrome(s[1:-1])
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, "GOOD":2, "VERY GOOD":2, "GOOD TO EPIC":2, "EPIC":2 } # get() method of dictionary data type returns # value of passed argument if it is present # in dictionary otherwise second argument will # be assigned as default value of passed argument return switcher.get(argument, "nothing")
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: banner: str. A banner comprised of ascii pound symbols (#) and the given string in the center. """ if type(input_str) is not str: input_str = str(input_str) ninput = len(input_str) nhash = max(4+ninput, 36) nshort1 = (nhash - ninput - 2) // 2 nshort2 = nhash - ninput - 2 - nshort1 banner = '\n' + '#'*nhash + \ '\n' + '#'*nshort1 + f' {input_str} ' + '#'*nshort2 + \ '\n' + '#'*nhash return banner
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 :param visibility: The visibility of the image, a grayscale image :param alpha1: The weight of the local entropy, a float within [0, 1] :param alpha2: The weight of the local contrast, a float within [0, 1] :param alpha3: The weight of the visibility, a float within [0, 1] :return: Weight map of the image, a grayscale image """ weight = entropy**alpha1 * contrast**alpha2 * visibility**alpha3 return weight
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 determined by: x in include * callable, the filter will be determined by: key(x) in include * hashable, the filter will be determined by: x[key] in include :return: a filter function (a function that returns True or False) >>> filt = mk_inclusion_filter(include=[2, 4]) >>> filter(filt, [1, 2, 3, 4, 2, 3, 4, 3, 4]) [2, 4, 2, 4, 4] >>> filt = mk_inclusion_filter(include=[2, 4], key='val') >>> filter(filt, [{'name': 'four', 'val': 4}, {'name': 'three', 'val': 3}, {'name': 'two', 'val': 2}]) [{'name': 'four', 'val': 4}, {'name': 'two', 'val': 2}] >>> filt = mk_inclusion_filter(include=[2, 4], key=2) >>> filter(filt, [(1, 2, 3), (1, 2, 4), (2, 7, 4), (1, 2, 7)]) [(1, 2, 4), (2, 7, 4)] >>> filt = mk_inclusion_filter(include=[2, 4], key=lambda x: x[0] * x[1]) >>> filter(filt, [(1, 2, 'is 2'), (2, 2, 'is 4'), (2, 3, 'is 6'), (1, 4, 'is 4')]) [(1, 2, 'is 2'), (2, 2, 'is 4'), (1, 4, 'is 4')] """ include = set(include) if key is None: def filter_func(x): return x in include else: if callable(key): def filter_func(x): return key(x) in include else: def filter_func(x): return x[key] in include return filter_func
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 value range. Attributes: * vals - a dictionary with intergers between 0-255 as keys Returns: * dictionary with keys between 0-255 whose values are the keys from the input dictionary """ bottomOffset = min(vals.keys()) steps = 255.0/(max(vals.keys())-bottomOffset) returnDict = {} for k in vals.keys(): returnKey = int((k-bottomOffset) * steps) returnDict[returnKey] = k return returnDict
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 of bins t_start : pq.Quantity Start time Returns ------- t_stop : pq.Quantity Stopping point calculated from given parameters. """ if n_bins is not None and bin_size is not None and t_start is not None: return t_start.rescale(bin_size.units) + n_bins * bin_size
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://archive.gemini.edu/calmgr/' + user_request, ) try: response.raise_for_status() except requests.exceptions.HTTPError as exc: print('goa_calmgr: request failed: {}'.format(response.text)) raise exc else: request_xml = response.content if verbose: print(response.url) # print(response.text) return request_xml
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, v in enumerate(x): if i == 0 or v.islower(): string += v else: string += '_' string += v return string.lower()
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_string:' f' {timestr}') if sincestring.lower() not in ['since', 'as']: raise ValueError(f"No 'since' or 'as' in unit_string:" f" {timestr}") return units.lower(), sincestring.lower(), remainder
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: str :param client: ID of the client to be used. :type client: int :param group: ID of the group you are moving the hosts into. :type group: int :return: A list of all hosts returned by the API. :rtype: list """ success = False # Assemble the URL for the API call url = platform + "/api/v1/client/" + str(client) + "/host/group/move" # Define the header for the API call header = { "x-api-key": key, "content-type": "application/json" } # Define the filters to be used in your query. In this case we are filtering # for hosts with a hostname of my.hostname.com. Update to reflect your # network conditions. filters = [ { "field": "hostName", "exclusive": False, "operator": "EXACT", "value": "my.hostname.com" # UPDATE THIS FILTER AS DESIRED } # You can stack multiple filters here, to further narrow your results, # just as you can in the UI. ] # Define the body for your API call. Specifies the filter(s) to use to identify the hosts # that you would like moved, and the group to move them to. body = { "filterRequest": { "filters": filters # This uses the filter(s) defined above. }, "targetGroupId": group } # Send your request to the API. response = requests.post(url, headers=header, data=json.dumps(body)) # If request is reported as successful... if response and response.status_code == 200: success = True else: print("There was an error updating the hosts from the API.") print(f"Status Code Returned: {response.status_code}") print(f"Response: {response.text}") return success
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)) 1234.5 """ return calendar.timegm(dt.utctimetuple()) + (dt.microsecond / 1000000.0)
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.""" tmp = line.split() params = {} params['smirks'] = tmp[0] params['k'] = str(2*float(tmp[1])) params['length'] = tmp[2] return params
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 ------- int Code cell index by provided ``identifier``. Notes ----- Assertion will be raised if ``identifier`` is found in several code cells or isn't found at all. """ import_cell_idx = [ idx for idx, cell in enumerate(nb["cells"]) if cell["cell_type"] == "code" and identifier in cell["source"] ] assert len(import_cell_idx) == 1 return import_cell_idx[0]
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 time_taken
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