seed
stringlengths
1
14k
source
stringclasses
2 values
import torch def compute_similarity_transform(S1: torch.Tensor, S2: torch.Tensor) -> torch.Tensor: """ Computes a similarity transform (sR, t) in a batched way that takes a set of 3D points S1 (B, N, 3) closest to a set of 3D points S2 (B, N, 3), where R is a 3x3 rotation matrix, t 3x1 translation, s ...
bigcode/self-oss-instruct-sc2-concepts
import re def _process_text(text): """Remove URLs from text.""" # Matches 'http' and any characters following until the next whitespace return re.sub(r"http\S+", "", text).strip()
bigcode/self-oss-instruct-sc2-concepts
def pchange(x1, x2) -> float: """Percent change""" x1 = float(x1) x2 = float(x2) return round(((x2 - x1) / x1) * 100., 1)
bigcode/self-oss-instruct-sc2-concepts
def _get_instance_id_from_arn(arn): """ Parses the arn to return only the instance id Args: arn (str) : EC2 arn Returns: EC2 Instance id """ return arn.split('/')[-1]
bigcode/self-oss-instruct-sc2-concepts
def check_categories(categories_str, category_list): """ Check if at least one entry in category_list is in the category string :param categories_str: Comma-separated list of categories :param category_list: List of categories to match :return: """ req = False if isinstance(categories_st...
bigcode/self-oss-instruct-sc2-concepts
def isIsomorphic(s,t): """ Given two strings s and t, determine if they are isomorphic. Two strings s and t are isomorphic if the characters in s can be replaced to get t. All occurrences of a character must be replaced with another character while preserving the order of characters. No two characte...
bigcode/self-oss-instruct-sc2-concepts
def nextpow2(i: int) -> int: """returns the first P such that 2**P >= abs(N)""" return i.bit_length()
bigcode/self-oss-instruct-sc2-concepts
import re def short_urs(upi, taxid): """ Create a truncated URS. This basically strips off the leading zeros to produce a shorter identifier. It will be easier for people to copy and use. """ name = "{upi}_{taxid}".format(upi=upi, taxid=taxid) return re.sub("^URS0+", "URS", name)
bigcode/self-oss-instruct-sc2-concepts
from pathlib import Path def get_suffix(path: Path) -> str: """Extracts full extension (as in everything after the first dot in the filename) from Path :param path: Original Path obj :return: String representation of full filename extension """ return f".{'.'.join(path.name.split('.')[1:])}"
bigcode/self-oss-instruct-sc2-concepts
import six import functools def command_aware_wraps(f): """ Decorator passing the command attribute of the wrapped function to the wrapper This needs to be used by decorators that are trying to wrap clicmd decorated command functions. """ additional = () if hasattr(f, 'command'): addi...
bigcode/self-oss-instruct-sc2-concepts
def set_parameter_requires_grad(model, requires_grad=False): """https://pytorch.org/tutorials/beginner/finetuning_torchvision_models_tutorial.html""" for param in model.parameters(): param.requires_grad = requires_grad return None
bigcode/self-oss-instruct-sc2-concepts
def encode(data): """ Encode string to byte in utf-8 :param data: Byte or str :return: Encoded byte data :raises: TypeError """ if isinstance(data, bytes): return data elif isinstance(data, str): return str.encode(data) else: return bytes(data)
bigcode/self-oss-instruct-sc2-concepts
import math def get_lng_lat_coord(origin_lnglat, xy_pt): """ Get the (lng, lat) from a given eucledian point (x,y). The origin point is given by origin_lnglat in (longitude, latitude) format. We assume (x,y) is "x" kilometers along longitude from the origin_lnglat, and "y" kilometers along the lat...
bigcode/self-oss-instruct-sc2-concepts
def sqrt(x): """Return square root of x""" return x ** (0.5)
bigcode/self-oss-instruct-sc2-concepts
def _preamble(layout='layered'): """Return preamble and begin/end document.""" if layout == 'layered': layout_lib = 'layered' elif layout == 'spring': layout_lib = 'force' else: raise ValueError( 'Unknown which library contains layout: {s}'.format(s=layout)) docum...
bigcode/self-oss-instruct-sc2-concepts
def isdistinct(seq): """ All values in sequence are distinct >>> isdistinct([1, 2, 3]) True >>> isdistinct([1, 2, 1]) False >>> isdistinct("Hello") False >>> isdistinct("World") True """ if iter(seq) is seq: seen = set() seen_add = seen.add for item ...
bigcode/self-oss-instruct-sc2-concepts
def buffer_polygon(ft): """Applies a buffer to a polygon""" return ft.buffer(-30, 1)
bigcode/self-oss-instruct-sc2-concepts
def _make_list(obj): """Returns list corresponding to or containing obj, depending on type.""" if isinstance(obj, list): return obj elif isinstance(obj, tuple): return list(obj) else: return [obj]
bigcode/self-oss-instruct-sc2-concepts
def _str_to_bool(string: str) -> bool: """ XML only allows "false" and "true" (case-sensitive) as valid values for a boolean. This function checks the string and raises a ValueError if the string is neither "true" nor "false". :param string: String representation of a boolean. ("true" or "false") ...
bigcode/self-oss-instruct-sc2-concepts
def str_to_enum(name): """Create an enum value from a string.""" return name.replace(" ", "_").replace("-", "_").upper()
bigcode/self-oss-instruct-sc2-concepts
from typing import Sequence import torch from typing import List def accum_grads(grads: Sequence[Sequence[torch.Tensor]]) -> List[torch.Tensor]: """ Compute accumulated gradients Parameters ---------- grads : Sequence[Sequence[torch.Tensor]] List of gradients on all previous tasks Re...
bigcode/self-oss-instruct-sc2-concepts
from bs4 import BeautifulSoup import requests def world_covid19_stats(url: str = "https://www.worldometers.info/coronavirus") -> dict: """ Return a dict of current worldwide COVID-19 statistics """ soup = BeautifulSoup(requests.get(url).text, "html.parser") keys = soup.findAll("h1") values = s...
bigcode/self-oss-instruct-sc2-concepts
import string import re def stemmer(word): """Return leading consonants (if any), and 'stem' of word""" consonants = ''.join([c for c in string.ascii_lowercase if c not in 'aeiou']) word = word.lower() match = re.match(f'([{consonants}]+)?([aeiou])(.*)', word) if match: p1 = match.gro...
bigcode/self-oss-instruct-sc2-concepts
def ascending(list: list) -> bool: """ Check if a list is in ascending ordering :rtype: bool :param list: a non empty list to check :return: if the list is in ascending order """ for i in range(len(list) - 1): if list[i] < list[i + 1]: return True return False
bigcode/self-oss-instruct-sc2-concepts
def _get_dependencies(dependencies): """Method gets dependent modules Args: dependencies (dict): dependent modules Returns: list """ mods = [] for key, val in dependencies.items(): mods.append(val['package']) return mods
bigcode/self-oss-instruct-sc2-concepts
def add_additonal_datetime_variables(df): """Adding variables derived from datetime: dropoff_month, *_week_of_year, *_day_of_year, *_day_of_month, *_weekday, *_is_weekend, *_hour""" print("adding additonal datetime variables") do_dt = df.dropoff_datetime.dt as_cat = lambda x: x.astype('category')...
bigcode/self-oss-instruct-sc2-concepts
def get_read_stop_position(read): """ Returns the stop position of the reference to where the read stops aligning :param read: The read :return: stop position of the reference where the read last aligned """ ref_alignment_stop = read.reference_end # only find the position if the reference e...
bigcode/self-oss-instruct-sc2-concepts
def player_table_variable_add(df, player_id, pos, year, player_name): """Adds specific variables as columns in a dataframe""" df = df.copy() df['player_id'] = player_id df['pos'] = pos df['year'] = year df['player_name'] = player_name return df
bigcode/self-oss-instruct-sc2-concepts
def avg(l): """Returns the average of a list of numbers Parameters ---------- l: sequence The list of numbers. Returns ------- float The average. """ return(sum(l) / float(len(l)))
bigcode/self-oss-instruct-sc2-concepts
import math def sum_log_scores(s1: float, s2: float) -> float: """Sum log odds in a numerically stable way.""" # this is slightly faster than using max if s1 >= s2: log_sum = s1 + math.log(1 + math.exp(s2 - s1)) else: log_sum = s2 + math.log(1 + math.exp(s1 - s2)) return log_sum
bigcode/self-oss-instruct-sc2-concepts
def get_types(field): """ Returns a field's "type" as a list. :param dict field: the field :returns: a field's "type" :rtype: list """ if 'type' not in field: return [] if isinstance(field['type'], str): return [field['type']] return field['type']
bigcode/self-oss-instruct-sc2-concepts
def rescale_time(temporal_network, new_t0, new_tmax): """Rescale the time in this temporal network (inplace). Parameters ========== temporal_network : :mod:`edge_lists` or :mod:`edge_changes` new_t0 : float The new value of t0. new_tmax : float The new value of tmax. Re...
bigcode/self-oss-instruct-sc2-concepts
def tokenize_char(sent): """ Tokenize a string by splitting on characters. """ return list(sent.lower())
bigcode/self-oss-instruct-sc2-concepts
def unordlist(cs): """unordlist(cs) -> str Takes a list of ascii values and returns the corresponding string. Example: >>> unordlist([104, 101, 108, 108, 111]) 'hello' """ return ''.join(chr(c) for c in cs)
bigcode/self-oss-instruct-sc2-concepts
def get_force_datakeeper(self): """ Generate DataKeepers to store by default results from force module Parameters ---------- self: VarLoadFlux object Returns ------- dk_list: list list of DataKeeper """ dk_list = [] return dk_list
bigcode/self-oss-instruct-sc2-concepts
def is_vararg(param_name): """ Determine if a parameter is named as a (internal) vararg. :param param_name: String with a parameter name :returns: True iff the name has the form of an internal vararg name """ return param_name.startswith('*')
bigcode/self-oss-instruct-sc2-concepts
import random def shuffle(liste): """ brief: choose randomly in the given liste Args: tab :a list of values, raise Exception if not Returns: the value selected randomly Raises: ValueError if input tab is not a list """ if not(isinstance(liste, list)): raise ...
bigcode/self-oss-instruct-sc2-concepts
def populate_cells(worksheet, bc_cells=[]): """ Populate a worksheet with bc_cell object data. """ for item in bc_cells: if item.cellref: worksheet[item.cellref].value = item.value else: worksheet.cell( row=item.row_num, column=item.col_num, value=...
bigcode/self-oss-instruct-sc2-concepts
def get_query_types(query_list): """ This function is used to parse the query_ticket_grouping_types string from the app.config :param query_list: the string to parse into ticketType groupingType pairs for querying Securework ticket endpoint :return: List of json objects. Each json entry is a ticketType...
bigcode/self-oss-instruct-sc2-concepts
def lastLetter (s): """Last letter. Params: s (string) Returns: (string) last letter of s """ return s[-1]
bigcode/self-oss-instruct-sc2-concepts
from typing import List import itertools import random def get_separators( space_count: int, sep_count: int, padding_count: int, shuffle: bool ) -> List[str]: """Create a list of separators (whitespaces) Arguments: space_count : minimum number of spaces to add between workds (before padding) sep...
bigcode/self-oss-instruct-sc2-concepts
import time def get_signature(user_agent, query_string, client_ip_address, lang): """ Get cache signature based on `user_agent`, `url_string`, `lang`, and `client_ip_address` """ timestamp = int(time.time()) / 1000 signature = "%s:%s:%s:%s:%s" % \ (user_agent, query_string, client_ip_...
bigcode/self-oss-instruct-sc2-concepts
def is_typed_tuple(tpl: object, obj_type: type, allow_none: bool = False, allow_empty: bool = True) -> bool: """ Check if a variable is a tuple that contains objects of specific type. :param tpl: The variable/list to check :param obj_type: The type of objects that the tuple should contain (for the chec...
bigcode/self-oss-instruct-sc2-concepts
def get_chain_offsets(chainlist, chainlength, chainpadding): """Generates chain offsets :param chainlist: Sorted list of chain letters :param chainlength: chain length dictionary :param chainpadding: chain padding dictionary :return: dictionary of chain offsets """ chainoffset = {} for ...
bigcode/self-oss-instruct-sc2-concepts
import copy def _set_name(dist, name): """Copies a distribution-like object, replacing its name.""" if hasattr(dist, 'copy'): return dist.copy(name=name) # Some distribution-like entities such as JointDistributionPinned don't # inherit from tfd.Distribution and don't define `self.copy`. We'll try to set ...
bigcode/self-oss-instruct-sc2-concepts
def rayleigh_Z(n, r): """ Compute rayligh Z statistic :param n: sample size :param r: r-value (mean vector length) """ return n * (r**2)
bigcode/self-oss-instruct-sc2-concepts
from bs4 import BeautifulSoup from typing import List from typing import Dict def get_author_names_from_grobid_xml(raw_xml: BeautifulSoup) -> List[Dict[str, str]]: """ Returns a list of dictionaries, one for each author, containing the first and last names. e.g. { "first": first, ...
bigcode/self-oss-instruct-sc2-concepts
def insight_dataframe(dataframe, dataframe_name): """Summary of the shape of a dataframe and view of the first 5 rows of the dataframe Parameters: dataframe (DataFrame): The dataframe we want to analyse dataframe_name (str) : Name of the dataframe Returns: str:Returning summary of the da...
bigcode/self-oss-instruct-sc2-concepts
def pr(x): """ Display a value and return it; useful for lambdas. """ print(x) return x
bigcode/self-oss-instruct-sc2-concepts
def default_window(win_id): """return default config for one window""" win = {} win['win_id'] = win_id win['mfact'] = 0.55 win['nmaster'] = 1 win['layout'] = 'horizontal' win['zoomed'] = False win['num_panes'] = 1 win['last_master_pane_id'] = None win['last_non_mas...
bigcode/self-oss-instruct-sc2-concepts
def Euclidean_Distance(x,y,Boundaries = 'S',Dom_Size=1.0): """ Euclidean distance between positions x and y. """ d = len(x) dij = 0 #Loop over number of dimensions for k in range(d): # Compute the absolute distance dist = abs( x[k] - y[k] ) #Extra condition for periodic BCs: if Boundaries == 'P' o...
bigcode/self-oss-instruct-sc2-concepts
import re def _GetRcData(comment, rc_path, rc_data, pattern=None): """Generates the comment and `source rc_path` lines. Args: comment: The shell comment string that precedes the source line. rc_path: The path of the rc file to source. rc_data: The current comment and source rc lines or None. patt...
bigcode/self-oss-instruct-sc2-concepts
def inconsistent_typical_range_stations(stations): """Given list of stations, returns list of stations with inconsistent data""" inconsiststations = [] for i in stations: if i.typical_range_consistent() == False: inconsiststations.append(i) return inconsiststations
bigcode/self-oss-instruct-sc2-concepts
def intersection(u, v): """Return the intersection of _u_ and _v_. >>> intersection((1,2,3), (2,3,4)) [2, 3] """ w = [] for e in u: if e in v: w.append(e) return w
bigcode/self-oss-instruct-sc2-concepts
import re def get_title(name): """ Use a regular expression to search for a title. Titles always consist of capital and lowercase letters, and end with a period. """ title_search = re.search(" ([A-Za-z]+)\.", name) if title_search: return title_search.group(1) return ""
bigcode/self-oss-instruct-sc2-concepts
def importName(modulename, name): """ Import a named object from a module in the context of this function. """ try: module = __import__(modulename, globals(), locals(), [name]) except ImportError: return None return getattr(module, name)
bigcode/self-oss-instruct-sc2-concepts
def module_equals(model1, model2): """Check if 2 pytorch modules have the same weights """ for p1, p2 in zip(model1.parameters(), model2.parameters()): if p1.data.ne(p2.data).sum() > 0: return False return True
bigcode/self-oss-instruct-sc2-concepts
def diff(data: list[int]) -> list[int]: """Calculate the difference between numeric values in a list.""" previous = data[0] difference = [] for value in data[1:]: difference.append(value - previous) previous = value return difference
bigcode/self-oss-instruct-sc2-concepts
def plot_histograms(ax, prng, nb_samples=10000): """Plot 4 histograms and a text annotation.""" params = ((10, 10), (4, 12), (50, 12), (6, 55)) for a, b in params: values = prng.beta(a, b, size=nb_samples) ax.hist(values, histtype="stepfilled", bins=30, alpha=0.8, density=True) # Add a s...
bigcode/self-oss-instruct-sc2-concepts
import json def _extract_multi_block_from_log(log_content, block_name): """ Extract multiple data blocks from a simultaneous REFL1D fit log. The start tag of each block will be [block_name]_START and the end tag of each block will be [block_name]_END. :param str log_content: strin...
bigcode/self-oss-instruct-sc2-concepts
def strip_path_prefix(path, prefix): """ Strip a prefix from a path if it exists and any remaining prefix slashes. Args: path: The path string to strip. prefix: The prefix to remove. Returns: The stripped path. If the prefix is not present, this will be the same as the input. ...
bigcode/self-oss-instruct-sc2-concepts
def developer_token() -> str: """The developer token that is used to access the BingAds API""" return '012345679ABCDEF'
bigcode/self-oss-instruct-sc2-concepts
def centerCropImage(img, targetSize): """ Returns a center-cropped image. The returned image is a square image with a width and height of `targetSize`. """ # Resize image while keeping its aspect ratio width, height = img.size if height < targetSize: print(str(height) + " height < targetSiz...
bigcode/self-oss-instruct-sc2-concepts
def get_string_between_nested(base, start, end): """Extracts a substring with a nested start and end from a string. Arguments: - base: string to extract from. - start: string to use as the start of the substring. - end: string to use as the end of the substring. Returns: - The substring if found...
bigcode/self-oss-instruct-sc2-concepts
def convert_str_color_to_plt_format(txt): """ Converts an rgb string format to a tuple of float (used by matplotlib format) Parameters ---------- txt : str a string representation of an rgb color (used by plotly) Returns ------- A tuple of float used by matplotlib format E...
bigcode/self-oss-instruct-sc2-concepts
async def get_ltd_product_urls(session): """Get URLs for LSST the Docs (LTD) products from the LTD Keeper API. Parameters ---------- session : `aiohttp.ClientSession` Your application's aiohttp client session. See http://aiohttp.readthedocs.io/en/stable/client.html. Returns ---...
bigcode/self-oss-instruct-sc2-concepts
def tochar(v): """Check and convert value to a character""" if isinstance(v, str) and len(v) == 1: return v else: raise ValueError('Expected a character, but found %s' % v)
bigcode/self-oss-instruct-sc2-concepts
def convert_list_to_sql_tuple(filter_list): """ This function takes a list and formats it into a SQL list that can be used to filter on in the WHERE clause. For example, ['a', 'b'] becomes ('a', 'b') and can be applied as: SELECT * FROM table WHERE column IN ('a', 'b'). Note that any pre-formatting on...
bigcode/self-oss-instruct-sc2-concepts
def transform_keyword(keywords): """ Transform each keyword into a query string compatible string """ keywordlist = [] for keyword in keywords: keywordlist.append(keyword.lower().replace(" ", "+")) return keywordlist
bigcode/self-oss-instruct-sc2-concepts
def average_daily_peak_demand(peak_usage: float, peak_hrs: float = 6.5) -> float: """ Calculate the average daily peak demand in kW :param peak_usage: Usage during peak window in kWh :param peak_hrs: Length of peak window in hours """ return peak_usage / peak_hrs
bigcode/self-oss-instruct-sc2-concepts
import re def herbarium(image_file): """Map the image file name to a herbarium.""" image_file = str(image_file) if image_file == 'nan': return '' image_file = image_file.upper() parts = re.split(r'[_-]', image_file) return parts[1] if parts[0] == 'TINGSHUANG' else parts[0]
bigcode/self-oss-instruct-sc2-concepts
def range_addition(n, updates): """ LeetCode 370: Range Addition Assume you have a list `[0] * n` and are given k update operations. Each operation is represented as a triplet `[start_index, end_index, increment]`, which adds increment to each element of subarray A[start_index ... end_index] (start...
bigcode/self-oss-instruct-sc2-concepts
async def get_message(ctx, message:int): """ Returns a previous message for a given channel and location (relative to context). Parameters: ctx (context): Passthrough for context from command. message (int): Location of message relative to sent command. Returns: Message: The me...
bigcode/self-oss-instruct-sc2-concepts
def parse_event_data(event): """Parses Event Data for S3 Object""" s3_records = event.get('Records')[0].get('s3') bucket = s3_records.get('bucket').get('name') key = s3_records.get('object').get('key') data = {"Bucket": bucket, "Key": key} return data
bigcode/self-oss-instruct-sc2-concepts
def _check_symmetry(matrix): """ Checks whether a matrix M is symmetric, i.e. M = M^T. By @t-kimber. Parameters ---------- matrix : np.array The matrix for which the condition should be checked. Returns ------- bool : True if the condition is met, False otherwise. ...
bigcode/self-oss-instruct-sc2-concepts
from typing import Tuple import math def calc_differential_steering_angle_x_y(wheel_space: int, left_displacement: float, right_displacement: float, orientation: float) -> Tuple[float, float, float]: """ Calculate the next orientation, x and y values of a two-wheel ...
bigcode/self-oss-instruct-sc2-concepts
import itertools def concat(*iterables): """ :param iterables: the iterables to concatenate :return: the concatenated list :rtype: list """ return list(itertools.chain(*iterables))
bigcode/self-oss-instruct-sc2-concepts
import time import calendar def format_time(time_str, format): """ This will take a time from Jira and format it into the specified string. The time will also be converted from UTC to local time. Jira time format is assumed to be, "YYYY-MM-DDTHH:MM:SS.ssss+0000". Where "T" is the literal charact...
bigcode/self-oss-instruct-sc2-concepts
def _get_row_partition_type_tensor_pairs_tail(partition): """Gets a row partition type tensor pair for the tail. If value_rowid is defined, then it is used. Otherwise, row_splits are used. Args: partition: a RowPartition. Returns: A list of (row_partition_type, row_partition_tensor) pairs. """ ...
bigcode/self-oss-instruct-sc2-concepts
import math def compute_perfect_tree(total): """ Determine # of ways complete tree would be constructed from 2^k - 1 values. This is a really subtle problem to solve. One hopes for a recursive solution, because it is binary trees, and the surprisingly simple equation results from the fact that it ...
bigcode/self-oss-instruct-sc2-concepts
def get_choices(query): """Get a list of selection choices from a query object.""" return [(str(item.id), item.name) for item in query]
bigcode/self-oss-instruct-sc2-concepts
import math def power_sum( pdb_lst ): """ take a list of powers in dBm, add them in the linear domain and return the sum in log """ sum_lin = 0 for pdb in pdb_lst: sum_lin += 10**(float(pdb)/10)*1e-3 return 10*math.log10(sum_lin/1e-3)
bigcode/self-oss-instruct-sc2-concepts
def interval_intersection(interval1, interval2): """Compute the intersection of two open intervals. Intervals are pairs of comparable values, one or both may be None to denote (negative) infinity. Returns the intersection if it is not empty. >>> interval_intersection((1, 3), (2, 4)) (2, 3) ...
bigcode/self-oss-instruct-sc2-concepts
from typing import Union def is_true(val: Union[str, int]) -> bool: """Decide if `val` is true. Arguments: val: Value to check. Returns: True or False. """ value = str(val).strip().upper() if value in ("1", "TRUE", "T", "Y", "YES"): return True return False
bigcode/self-oss-instruct-sc2-concepts
def humanize_bytes( num: float, suffix: str = "B", si_prefix: bool = False, round_digits: int = 2 ) -> str: """Return a human friendly byte representation. Modified from: https://stackoverflow.com/questions/1094841/1094933#1094933 Args: num: Raw bytes suffix: String to append s...
bigcode/self-oss-instruct-sc2-concepts
import math def boiling_point(altitude): """ Get the boiling point at a specific altitude https://www.omnicalculator.com/chemistry/boiling-point-altitude :param float altitude: Altitude in feet (ft) :return: The boiling point in degF :rtype: float """ pressure = 29.921 * pow((1 - 0....
bigcode/self-oss-instruct-sc2-concepts
def get_usa_veh_id(acc_id, vehicle_index): """ Returns global vehicle id for USA, year and index of accident. The id is constructed as <Acc_id><Vehicle_index> where Vehicle_index is three digits max. """ veh_id = acc_id * 1000 veh_id += vehicle_index return veh_id
bigcode/self-oss-instruct-sc2-concepts
import calendar def to_unix_timestamp(timestamp): """ Convert datetime object to unix timestamp. Input is local time, result is an UTC timestamp. """ if timestamp is not None: return calendar.timegm(timestamp.utctimetuple())
bigcode/self-oss-instruct-sc2-concepts
import platform def is_platform_arm() -> bool: """ Checking if the running platform use ARM architecture. Returns ------- bool True if the running platform uses ARM architecture. """ return platform.machine() in ("arm64", "aarch64") or platform.machine().startswith( "armv"...
bigcode/self-oss-instruct-sc2-concepts
def get_content(html_soup): """ Extracts text content of the article from content Input : Content in BeautifulSoup format Output : Text content of the article """ html_soup.find('figure').extract() content = html_soup.find('div', attrs = {"class" : "entry-content"}).get_text() return con...
bigcode/self-oss-instruct-sc2-concepts
import yaml def read_radial_build(file_): """ Loads the radial build YAML file as a Python dictionary Parameters ---------- file_ : str The radial build file path Returns ------- radial_build : list A Python dictionary storing the tokamak radial build data """ ...
bigcode/self-oss-instruct-sc2-concepts
def strip_module_names(testcase_names): """Examine all given test case names and strip them the minimal names needed to distinguish each. This prevents cases where test cases housed in different files but with the same names cause clashes.""" result = list(testcase_names) for i, testcase in enumerat...
bigcode/self-oss-instruct-sc2-concepts
def text_to_lowercase(text): """Set all letters to lowercase""" return text.lower()
bigcode/self-oss-instruct-sc2-concepts
def safe_compare(val1, val2): """ Compares two strings to each other. The time taken is independent of the number of characters that match. :param val1: First string for comparison. :type val1: :class:`str` :param val2: Second string for comparison. :type val2: :class:`str` :returns: ...
bigcode/self-oss-instruct-sc2-concepts
def loess_abstract(estimator, threshold, param, length, migration_time, utilization): """ The abstract Loess algorithm. :param estimator: A parameter estimation function. :type estimator: function :param threshold: The CPU utilization threshold. :type threshold: float :param param: The safe...
bigcode/self-oss-instruct-sc2-concepts
def construct_backwards_adjacency_list(adjacency_list): """ Create an adjacency list for traversing a graph backwards The resulting adjacency dictionary maps vertices to each vertex with an edge pointing to them """ backwards_adjacency_list = {} for u in adjacency_list: for v in adjacency_list[u...
bigcode/self-oss-instruct-sc2-concepts
import math def law_of_cosines(a, b, angle): """ Return the side of a triangle given its sides a, b and the angle between them (Law of cosines) """ return math.sqrt( a**2 + b**2 - 2*a*b*math.cos(math.radians(angle)) )
bigcode/self-oss-instruct-sc2-concepts
def normalize_confusion_matrix(confusion_matrix_dict: dict, normalize_index: int = 0) -> dict: """ normalize a confusion matrix; :param confusion_matrix_dict: dict, a confusion matrix, e.g., {('a', 'a'): 1, ('a', 'b'): 2, ('b', 'a'): 3, ('b', 'b'): 4}; :param normalize_index: int, [0, 1], the p...
bigcode/self-oss-instruct-sc2-concepts
def is_nested_list(l): """ Check if list is nested :param l: list :return: boolean """ return any(isinstance(i, list) for i in l)
bigcode/self-oss-instruct-sc2-concepts
def get_db_collections(db): """ db.collection_names() DeprecationWarning: collection_names is deprecated. Use list_collection_names instead. """ # return db.collection_names() return db.list_collection_names()
bigcode/self-oss-instruct-sc2-concepts