seed
stringlengths
1
14k
source
stringclasses
2 values
import math def _flat_hex_coords(centre, size, i): """ Return the point coordinate of a flat-topped regular hexagon. points are returned in counter-clockwise order as i increases the first coordinate (i=0) will be: centre.x + size, centre.y """ angle_deg = 60 * i angle_rad = math.pi / 180...
bigcode/self-oss-instruct-sc2-concepts
import requests def make_get_request(uri: str, payload): """ Function to make a GET request to API Endpoint :param uri: :param payload: :return: """ response = requests.get(uri, payload) if response.status_code != 200: return None else: return response.json()
bigcode/self-oss-instruct-sc2-concepts
def has_two_adjacent(password): """Check if the password contains a pair of adjacent digits""" last_char = None num_adjacent = 0 for char in password: if char == last_char: num_adjacent += 1 else: if num_adjacent == 1: return True las...
bigcode/self-oss-instruct-sc2-concepts
import torch def dot(A, B, dim=-1): """ Computes the dot product of the input tensors along the specified dimension Parameters ---------- A : Tensor first input tensor B : Tensor second input tensor dim : int (optional) dimension along the dot product is computed (...
bigcode/self-oss-instruct-sc2-concepts
from typing import Union def check_prefix(prefix: Union[str, tuple, list], content: str): """Determines whether or not the prefix matches the content. Parameters ---------- prefix : Union[str, tuple, list] The affix that appears at the beginning of a sentence. content : str The s...
bigcode/self-oss-instruct-sc2-concepts
def _account_data(cloud): """Generate the auth data JSON response.""" claims = cloud.claims return { 'email': claims['email'], 'sub_exp': claims['custom:sub-exp'], 'cloud': cloud.iot.state, }
bigcode/self-oss-instruct-sc2-concepts
def _determine_start(lines): """ Determines where the section listing all SMART attributes begins. :param lines: the input split into lines. :type lines: list[str] :return: the index of the first attribute. :rtype: int """ cnt = 0 for idx, val in enumerate(lines): if lines[...
bigcode/self-oss-instruct-sc2-concepts
def specificrulevalue(ruleset, summary, default=None): """ Determine the most specific policy for a system with the given multiattractor summary. The ruleset is a dict of rules, where each key is an aspect of varying specificity: - 2-tuples are the most specific and match systems with that summary. ...
bigcode/self-oss-instruct-sc2-concepts
def rotate90_point(x, y, rotate90origin=()): """Rotates a point 90 degrees CCW in the x-y plane. Args: x, y (float): Coordinates. rotate90origin (tuple): x, y origin for 90 degree CCW rotation in x-y plane. Returns: xrot, yrot (float): Rotated coordinates. """ # Translate ...
bigcode/self-oss-instruct-sc2-concepts
def is_dict(value): """Checks if value is a dict""" return isinstance(value, dict)
bigcode/self-oss-instruct-sc2-concepts
def get_ordinal_suffix(number): """Receives a number int and returns it appended with its ordinal suffix, so 1 -> 1st, 2 -> 2nd, 4 -> 4th, 11 -> 11th, etc. Rules: https://en.wikipedia.org/wiki/Ordinal_indicator#English - st is used with numbers ending in 1 (e.g. 1st, pronounced first) ...
bigcode/self-oss-instruct-sc2-concepts
import hashlib def unique_hash(input_str: str) -> str: """Uses MD5 to return a unique key, assuming the input string is unique""" # assuming default UTF-8 return hashlib.md5(input_str.encode()).hexdigest()
bigcode/self-oss-instruct-sc2-concepts
def show_price(price: float) -> str: """ >>> show_price(1000) '$ 1,000.00' >>> show_price(1_250.75) '$ 1,250.75' """ return "$ {0:,.2f}".format(price)
bigcode/self-oss-instruct-sc2-concepts
def format_title(title, first_title): """ Generates the string for a title of the example page, formatted for a 'sphinx-gallery' example script. Parameters ---------- title : string The title string. first_title : boolean Indicates whether the title is the first title of the ...
bigcode/self-oss-instruct-sc2-concepts
import torch def get_saliency(interpreter, inputs, target): """ Perform integrated gradient for saliency. """ # define saliency interpreter # interpreter = captum.attr.Saliency(net) attribution = interpreter.attribute(inputs, target) attribution = torch.squeeze(attribution) return torch.su...
bigcode/self-oss-instruct-sc2-concepts
import collections def parse_gtid_range_string(input_range): """Converts a string like "uuid1:id1-id2:id3:id4-id5, uuid2:id6" into a dict like {"uuid1": [[id1, id2], [id3, id3], [id4, id5]], "uuid2": [[id6, id6]]}. ID ranges are sorted from lowest to highest""" # This might be called again for a value...
bigcode/self-oss-instruct-sc2-concepts
import string def _clean_string(s): """Clean up a string. Specifically, cleaning up a string entails 1. making it lowercase, 2. replacing spaces with underscores, and 3. removing any characters that are not lowercase letters, numbers, or underscores. Parameters ---------- s: s...
bigcode/self-oss-instruct-sc2-concepts
def frontiers_from_time_to_bar(seq, bars): """ Convert the frontiers in time to a bar index. The selected bar is the one which end is the closest from the frontier. Parameters ---------- seq : list of float The list of frontiers, in time. bars : list of tuple of floats The b...
bigcode/self-oss-instruct-sc2-concepts
def split_int(i, p): """ Split i into p buckets, such that the bucket size is as equal as possible Args: i: integer to be split p: number of buckets Returns: list of length p, such that sum(list) = i, and the list entries differ by at most 1 """ split = [] n = i / p # min ...
bigcode/self-oss-instruct-sc2-concepts
def findNthFibonnachiNumberIterative(n: int) -> int: """Find the nth fibonacchi number Returns: int: the number output """ if n <= 2: return 1 first, second = 0, 1 while n-1: third = first + second first = second second = third n -= 1 return...
bigcode/self-oss-instruct-sc2-concepts
def load_factor(ts, resolution=None, norm=None): """ Calculate the ratio of input vs. norm over a given interval. Parameters ---------- ts : pandas.Series timeseries resolution : str, optional interval over which to calculate the ratio default: resolution of the input ti...
bigcode/self-oss-instruct-sc2-concepts
def construct_iscsi_bdev(client, name, url, initiator_iqn): """Construct a iSCSI block device. Args: name: name of block device url: iSCSI URL initiator_iqn: IQN name to be used by initiator Returns: Name of created block device. """ params = { 'name': name,...
bigcode/self-oss-instruct-sc2-concepts
def min_interp(interp_object): """ Find the global minimum of a function represented as an interpolation object. """ try: return interp_object.x[interp_object(interp_object.x).argmin()] except Exception as e: s = "Cannot find minimum of tthe interpolation object" + str(interp_object....
bigcode/self-oss-instruct-sc2-concepts
def hasSchema(sUrl): """ Checks if the URL has a schema (e.g. http://) or is file/server relative. Returns True if schema is present, False if not. """ iColon = sUrl.find(':'); if iColon > 0: sSchema = sUrl[0:iColon]; if len(sSchema) >= 2 and len(sSchema) < 16 and sSchema.islower...
bigcode/self-oss-instruct-sc2-concepts
def check_knight_move(lhs, rhs): """check_knight_move checks whether a knight move is ok.""" col_diff = abs(ord(lhs[0]) - ord(rhs[0])) row_diff = abs(int(lhs[1]) - int(rhs[1])) return (col_diff == 2 and row_diff == 1) or (col_diff == 1 and row_diff == 2)
bigcode/self-oss-instruct-sc2-concepts
def remove(self): """Remove this node. @return: self """ self.parent.remove_creator(self) return self
bigcode/self-oss-instruct-sc2-concepts
from datetime import datetime def timestamp_ddmmyyyyhhmmss_to_ntp(timestamp_str): """ Converts a timestamp string, in the DD Mon YYYY HH:MM:SS format, to NTP time. :param timestamp_str: a timestamp string in the format DD Mon YYYY HH:MM:SS :return: Time (float64) in seconds from epoch 01-01-1900. ...
bigcode/self-oss-instruct-sc2-concepts
def read_file(file, delimiter): """Reads data from a file, separated via delimiter Args: file: Path to file. delimiter: Data value separator, similar to using CSV. Returns: An array of dict records. """ f = open(file, 'r') lines = f.readlines() records = [] for line in lines: ...
bigcode/self-oss-instruct-sc2-concepts
import csv def readAIAresponse(csvFile): """Obtains the SDO/AIA responses from a .csv file. Parameters ---------- csvFile : str The .csv file with the SDO/AIA responses in it. First line should be labels for each column as a comma seperated string, e.g. row1=['logt, A94, A171']. ...
bigcode/self-oss-instruct-sc2-concepts
def get_pickle_file_path(file_name, target, folder): """ Returns a path to a saved file Parameters ---------- file_name: str name of the saved file target: str name of target column folder: str name of the folder file is saved in Returns ------- path to ...
bigcode/self-oss-instruct-sc2-concepts
def model_zero(x, k, y0, y1): """ One-compartment first-order exponential decay model :param x: float time :param k: float rate constant :param y0: float initial value :param y1: float plateau value :return: value at time point """ return y0 - (k * x)
bigcode/self-oss-instruct-sc2-concepts
def concatenate_codelines(codelines): """ Compresses a list of strings into one string. """ codeline = "" for l in codelines: codeline = codeline + l return codeline
bigcode/self-oss-instruct-sc2-concepts
from typing import Any def to_pipeline_params(params: dict[str, Any], step_prefix: str): """Rename estimator parameters to be usable an a pipeline. See https://scikit-learn.org/stable/modules/compose.html#pipeline. """ return {"{0}__{1}".format(step_prefix, key): value for key, value in params.items(...
bigcode/self-oss-instruct-sc2-concepts
def toutf8(ustr): """Return UTF-8 `str` from unicode @ustr This is to use the same error handling etc everywhere if ustr is `str`, just return it """ if isinstance(ustr, str): return ustr return ustr.encode("UTF-8")
bigcode/self-oss-instruct-sc2-concepts
def RemoveUppercase(word): """Remove the uppercase letters from a word""" return word.lower()
bigcode/self-oss-instruct-sc2-concepts
def plural(count=0): """Return plural extension for provided count.""" ret = 's' if count == 1: ret = '' return ret
bigcode/self-oss-instruct-sc2-concepts
def degreeDays(dd0, T, Tbase, doy): """ Calculates degree-day sum from the current mean Tair. INPUT: dd0 - previous degree-day sum (degC) T - daily mean temperature (degC) Tbase - base temperature at which accumulation starts (degC) doy - day of year 1...366 (integer) OUT...
bigcode/self-oss-instruct-sc2-concepts
def obj_to_dict(obj, *args, _build=True, _module=None, _name=None, _submodule=None, **kwargs): """Encodes an object in a dictionary for serialization. Args: obj: The object to encode in the dictionary. Other parameters: _build (bool): Whether the object is to be built on de...
bigcode/self-oss-instruct-sc2-concepts
def identity(x): """x -> x As a predicate, this function is useless, but it provides a useful/correct default. >>> identity(('apple', 'banana', 'cherry')) ('apple', 'banana', 'cherry') """ return x
bigcode/self-oss-instruct-sc2-concepts
def epoch2checkpoint(_epoch: int) -> str: """ Args: _epoch: e.g. 2 Returns: _checkpoint_name: e.g. 'epoch=2.ckpt' """ return f"epoch={_epoch}.ckpt"
bigcode/self-oss-instruct-sc2-concepts
def ED(first, second): """ Returns the edit distance between the strings first and second.""" if first == '': return len(second) elif second == '': return len(first) elif first[0] == second[0]: return ED(first[1:], second[1:]) else: substitution = 1 + ED(first[1:], se...
bigcode/self-oss-instruct-sc2-concepts
def remove_slash(path: str) -> str: """Remove slash in the end of path if present. Args: path (str): Path. Returns: str: Path without slash. """ if path[-1] == "/": path = path[:-1] return path
bigcode/self-oss-instruct-sc2-concepts
def chk_chng(src_flist,dst_flist): """ Returns unchanged file list and changed file list Accepts source file list and dsetination file list""" uc_flist = [] c_flist = [] for files in src_flist: if files in dst_flist: uc_flist.append(files) else: c_flist.ap...
bigcode/self-oss-instruct-sc2-concepts
def cnn_estimate(inputs, network, est_fn): """ Estimated labelf by the trained cnn network Inputs ====== inputs: np.ndarray The test dataset network: lasagne.layers The trained cnn network Output ====== label_est: np.ndarray The estimated labels """ ...
bigcode/self-oss-instruct-sc2-concepts
def _can_append_long_entry(e, f): """True if f is a FATDirEntry that can follow e. For f to follow e, f and e must have the same checksum, and f's ordinal must be one less than e""" return ( f.LDIR_Chksum == e.LDIR_Chksum and f.long_name_ordinal() + 1 == e.long_name_ordinal() )
bigcode/self-oss-instruct-sc2-concepts
def get_declared_licenses(license_object): """ Return a list of declared licenses, either strings or dicts. """ if not license_object: return [] if isinstance(license_object, str): # current, up to date form return [license_object] declared_licenses = [] if isinstan...
bigcode/self-oss-instruct-sc2-concepts
import math def to_acres(km2): """ square KM to acres """ if math.isnan(km2): return 0 return round(km2 * 247.11)
bigcode/self-oss-instruct-sc2-concepts
def extract_transcript_sequences(bed_dic, seq_dic, ext_lr=False, full_hits_only=False): """ Given a dictionary with bed regions (region ID -> BED row) and a sequence dictionary (Sequence ID -> sequence), extract the BED region sequences a...
bigcode/self-oss-instruct-sc2-concepts
import random def getRandomColor(colorsList): """Returns a random color from <colorsList> or OFF""" if len(colorsList) > 0: return colorsList[random.randint(0, len(colorsList)-1)] return 0, 0, 0
bigcode/self-oss-instruct-sc2-concepts
from typing import Union def uri_from_details(namespace: str, load_name: str, version: Union[str, int], delimiter='/') -> str: """ Build a labware URI from its details. A labware URI is a string that uniquely specifies a labware definition. :returns str: The URI...
bigcode/self-oss-instruct-sc2-concepts
def npm_download_url(namespace, name, version, registry='https://registry.npmjs.org'): """ Return an npm package tarball download URL given a namespace, name, version and a base registry URL. For example: >>> expected = 'https://registry.npmjs.org/@invisionag/eslint-config-ivx/-/eslint-config-ivx-0...
bigcode/self-oss-instruct-sc2-concepts
import bisect def find_le(a, x): """Find the rightmost value of A which is less than or equal to X.""" i = bisect.bisect_right(a, x) if i: return a[i-1] return None
bigcode/self-oss-instruct-sc2-concepts
def get_status_color(status): """Return (markup) color for test result status.""" colormap = {"passed": {"green": True, "bold": True}, "failed": {"red": True, "bold": True}, "blocked": {"blue": True, "bold": True}, "skipped": {"yellow": True, "bold": True}} r...
bigcode/self-oss-instruct-sc2-concepts
def date_month(date): """Find the month from the given date.""" return date.month
bigcode/self-oss-instruct-sc2-concepts
def packages(package_helper): """Return the list of specified packages (i.e. packages explicitely installed excluding dependencies)""" return package_helper.specified_packages()
bigcode/self-oss-instruct-sc2-concepts
def _kron(vec0,vec1): """ Calculates the tensor product of two vectors. """ new_vec = [] for amp0 in vec0: for amp1 in vec1: new_vec.append(amp0*amp1) return new_vec
bigcode/self-oss-instruct-sc2-concepts
def get_container_name(framework): """Translate the framework into the docker container name.""" return 'baseline-{}'.format({ 'tensorflow': 'tf', 'pytorch': 'pyt', 'dynet': 'dy' }[framework])
bigcode/self-oss-instruct-sc2-concepts
def _merge_temporal_interval(temporal_interval_list): """ Merge the temporal intervals in the input temporal interval list. This is for situations when different actions have overlap temporal interval. e.g if the input temporal interval list is [(1.0, 3.0), (2.0, 4.0)], then [(1.0, 4.0)] will be returne...
bigcode/self-oss-instruct-sc2-concepts
def datetimeToReadable(d, tz): """Returns datetime as string in format %H:%M %m/%d/%Y %d datetime object %returns string of object in readable format.""" return d.astimezone(tz).strftime("%H:%M %m/%d/%Y")
bigcode/self-oss-instruct-sc2-concepts
def _default_call_out_of_place(op, x, **kwargs): """Default out-of-place evaluation. Parameters ---------- op : `Operator` Operator to call x : ``op.domain`` element Point in which to call the operator. kwargs: Optional arguments to the operator. Returns -------...
bigcode/self-oss-instruct-sc2-concepts
import uuid def gen_id() -> str: """Generate new Skybell IDs.""" return str(uuid.uuid4())
bigcode/self-oss-instruct-sc2-concepts
def wrap_list(list_, idx): """Return value at index, wrapping if necessary. Parameters ---------- list_ : :class:`list` List to wrap around. idx : :class:`int` Index of item to return in list. Returns ------- :class:`list` element Item at given index, index will...
bigcode/self-oss-instruct-sc2-concepts
from typing import Tuple def get_tensor_dimensions(n_atom_types : int, n_formal_charge : int, n_num_h : int, n_chirality : int, n_node_features : int, n_edge_features : int, parameters : dict) -> Tuple[list, list, list, list, int]: """ Returns dimensions for...
bigcode/self-oss-instruct-sc2-concepts
def djb2(s: str) -> int: """ Implementation of djb2 hash algorithm that is popular because of it's magic constants. >>> djb2('Algorithms') 3782405311 >>> djb2('scramble bits') 1609059040 """ hash = 5381 for x in s: hash = ((hash << 5) + hash) + ord(x) return hash & ...
bigcode/self-oss-instruct-sc2-concepts
def parse_variable_field(field, re_dict): """Function takes a MARC21 field and the Regex dictgroup and return a list of the subfields that match the Regex patterns. Parameters: field -- MARC21 field re_dict -- Regular Expression dictgroup """ output = [] if field is None or re_dict is N...
bigcode/self-oss-instruct-sc2-concepts
from pathlib import Path from textwrap import dedent def _commands(fds_file: Path) -> str: """Return the commands for PBS job scheduler.""" return dedent( f""" # run fds in parallel mpiexec -np $MPI_NP fds_mpi {fds_file.name} """.rstrip() )
bigcode/self-oss-instruct-sc2-concepts
def is_private(attribute): """Return whether an attribute is private.""" return attribute.startswith("_")
bigcode/self-oss-instruct-sc2-concepts
import re def single_line_conversion(line): """ converts a single line typedef to a using statement, preserving whitespace """ components = re.split('\s', line) name = components[-1][:-1] #last item, drop the trailing space typedef_index = 0 for c in components: if c == 'typedef': break typ...
bigcode/self-oss-instruct-sc2-concepts
import random import string def random_lc_alphanumeric_string(length): """Return random lowercase alphanumeric string of specified length.""" return ''.join(random.choice(string.ascii_lowercase + string.digits) for ii in range(length))
bigcode/self-oss-instruct-sc2-concepts
def neg_pt(pt, curve): """Negate a point. Args: pt (tuple(int, int)): Point (x, y). Use (None, None) for point at infinity. curve (tuple(int, int, int)): (a, b, n) representing the Elliptic Curve y**2 = x**3 + a*x + b (mod n). Returns: tuple(int, int): Point -pt. ""...
bigcode/self-oss-instruct-sc2-concepts
import json def json_to_dict(file_json): """Create dictionary from json file.""" with open(file_json) as infile: mydict = json.load(infile) return mydict
bigcode/self-oss-instruct-sc2-concepts
import click def get_help_msg(command): """get help message for a Click command""" with click.Context(command) as ctx: return command.get_help(ctx)
bigcode/self-oss-instruct-sc2-concepts
def flatten_bands(bands): """ Flatten the bands such that they have dimension 2. """ flattened_bands = bands.clone() bands_array = bands.get_bands() flattened_bands.set_bands(bands_array.reshape(bands_array.shape[-2:])) return flattened_bands
bigcode/self-oss-instruct-sc2-concepts
def check_same_keys(d1, d2): """Check if dictionaries have same keys or not. Args: d1: The first dict. d2: The second dict. Raises: ValueError if both keys do not match. """ if d1.keys() == d2.keys(): return True raise ValueError("Keys for both the dictionaries ...
bigcode/self-oss-instruct-sc2-concepts
import re def _MarkOptional(usage): """Returns usage enclosed in [...] if it hasn't already been enclosed.""" # If the leading bracket matches the trailing bracket its already marked. if re.match(r'^\[[^][]*(\[[^][]*\])*[^][]*\]$', usage): return usage return '[{}]'.format(usage)
bigcode/self-oss-instruct-sc2-concepts
def keep_type(adata, nodes, target, k_cluster): """Select cells of targeted type Args: adata (Anndata): Anndata object. nodes (list): Indexes for cells target (str): Cluster name. k_cluster (str): Cluster key in adata.obs dataframe Returns: list: Selected cells....
bigcode/self-oss-instruct-sc2-concepts
from datetime import datetime def ticks_from_datetime(dt: datetime): """Convert datetime to .Net ticks""" if type(dt) is not datetime: raise TypeError('dt must be a datetime object') return (dt - datetime(1, 1, 1)).total_seconds() * 10000000
bigcode/self-oss-instruct-sc2-concepts
import toml def toml_files(tmp_path): """Generate TOML config files for testing.""" def gen_toml_files(files={'test.toml': {'sec': {'key': 'val'}}}): f_path = None for name, config in files.items(): f_path = tmp_path / name with open(f_path, 'w') as f: ...
bigcode/self-oss-instruct-sc2-concepts
import csv def readCSV(filename): """ Reads the .data file and creates a list of the rows Input filename - string - filename of the input data file Output data - list containing all rows of the csv as elements """ data = [] with open(filename, 'rt', encoding='utf8') ...
bigcode/self-oss-instruct-sc2-concepts
import re def is_phone_number(text,format=1): """ Checks if the given text is a phone number * The phone must be for default in format (000)0000000, but it can be changed Args: text (str): The text to match (optional) format (int): The number of the phone format that you want to check...
bigcode/self-oss-instruct-sc2-concepts
def hamming_weight(x): """ Per stackoverflow.com/questions/407587/python-set-bits-count-popcount It is succint and describes exactly what we are doing. """ return bin(x).count('1')
bigcode/self-oss-instruct-sc2-concepts
def _is_pronoun (mention) : """Check if a mention is pronoun""" components=mention.split() if components[1]=="PRON" : return True return False
bigcode/self-oss-instruct-sc2-concepts
def swap_clips(from_clip, to_clip, to_clip_name, to_in_frame, to_out_frame): """ Swaping clips on timeline in timelineItem It will add take and activate it to the frame range which is inputted Args: from_clip (resolve.mediaPoolItem) to_clip (resolve.mediaPoolItem) to_clip_name ...
bigcode/self-oss-instruct-sc2-concepts
def _price_dish(dish): """ Computes the final price for ordering the given dish, taking into account the requested quantity and options. Args: dish (dict): KB entry for a dish, augmented with quantity and options information. Returns: float: Total price for ordering the requested q...
bigcode/self-oss-instruct-sc2-concepts
import unicodedata def get_character_names(characters, verbose=False): """Print the unicode name of a list/set/string of characters. Args: characters (list/set/string): a list, string or set of characters. verbose (bool): if set to True, the output will be printed Returns: (dict)...
bigcode/self-oss-instruct-sc2-concepts
import time def parse_time(epoch_time): """Convert epoch time in milliseconds to [year, month, day, hour, minute, second]""" date = time.strftime('%Y-%m-%d-%H-%M-%S', time.gmtime(epoch_time/1000)) return [int(i) for i in date.split('-')]
bigcode/self-oss-instruct-sc2-concepts
import typing import math def isanan(value: typing.Any) -> bool: """Detect if value is NaN.""" return isinstance(value, float) and math.isnan(value)
bigcode/self-oss-instruct-sc2-concepts
def fix_public_key(str_key): """eBay public keys are delivered in the format: -----BEGIN PUBLIC KEY-----key-----END PUBLIC KEY----- which is missing critical newlines around the key for ecdsa to process it. This adds those newlines and converts to bytes. """ return ( str_key ...
bigcode/self-oss-instruct-sc2-concepts
def _error_string(error, k=None): """String representation of SBMLError. Parameters ---------- error : libsbml.SBMLError k : index of error Returns ------- string representation of error """ package = error.getPackage() if package == "": package = "core" templa...
bigcode/self-oss-instruct-sc2-concepts
def powmod(x, k, MOD): """ fast exponentiation x^k % MOD """ p = 1 if k == 0: return p if k == 1: return x while k != 0: if k % 2 == 1: p = (p * x) % MOD x = (x * x) % MOD k //= 2 return p
bigcode/self-oss-instruct-sc2-concepts
def remove_trail_idx(param): """Remove the trailing integer from a parameter.""" return "_".join(param.split("_")[:-1])
bigcode/self-oss-instruct-sc2-concepts
import re def get_qdyn_compiler(configure_log): """Return the name the Fortran compiler that QDYN was compiled with""" with open(configure_log) as in_fh: for line in in_fh: if line.startswith("FC"): m = re.search(r'FC\s*:\s*(.*)', line) if m: ...
bigcode/self-oss-instruct-sc2-concepts
import re def is_ipv4(ip): """Checks if the ip address is a valid ipv4 address including CIDR mask.""" regex = r'^(\d+)[.](\d+)[.](\d+)[.](\d+)[/](\d+)$' pattern = re.compile(regex) return pattern.search(ip) is not None
bigcode/self-oss-instruct-sc2-concepts
def get_categories_info(categories_id, doc): """Get object name from category id """ for cate_infor in doc['categories']: if categories_id == cate_infor['id']: return cate_infor['name'] return None
bigcode/self-oss-instruct-sc2-concepts
def is_unique_corr(x): """Check that ``x`` has no duplicate elements. Args: x (list): elements to be compared. Returns: bool: True if ``x`` has duplicate elements, otherwise False """ return len(set(x)) == len(x)
bigcode/self-oss-instruct-sc2-concepts
def getImageLink(url, img_url, caption): """ Converts a URL to a Markdown image link. """ return "[![{caption}]({img_url} =16x16)]({url})".format( caption=caption, img_url=img_url, url=url )
bigcode/self-oss-instruct-sc2-concepts
def get_chars_from_guesses(guesses): """ gets characters from guesses (removes underscores), removes duplicates and sorts them in an array which is returned. example guess: "__cr_" """ guesses_copy = guesses.copy() guesses_copy = "".join(guesses_copy) return sorted("".join(set(guesses_copy.r...
bigcode/self-oss-instruct-sc2-concepts
def computeAbsPercentageError(true, predicted): """ :param true: ground truth value :param predicted: predicted value :return: absolute percentage error """ return abs((true - predicted) / true) * 100
bigcode/self-oss-instruct-sc2-concepts
def lines(a, b): """Return lines in both a and b""" l1 = a.splitlines() l2 = b.splitlines() s1 = set(l1) s2 = set(l2) l = [i for i in s1 if i in s2] return l
bigcode/self-oss-instruct-sc2-concepts
def check_campus(department_name, department_dict, val): """ Returns the campus/college the given 'department_name' is in depending on the value of the 'val' parameter @params 'department_name': The full name of the department to search for 'department_dict': The dictionary of departm...
bigcode/self-oss-instruct-sc2-concepts