seed
stringlengths
1
14k
source
stringclasses
2 values
def integerize(num, count): """Calculate and return integer value if result is integer""" calc = num * count calc = int(calc) if calc.is_integer() else calc return calc
bigcode/self-oss-instruct-sc2-concepts
import requests def get_redirected_url(url: str) -> str: """ Given a URL, return the URL it redirects to. Args: url (str) """ r = requests.get(url) return r.url
bigcode/self-oss-instruct-sc2-concepts
def _find_var_dictionary(table, dict_name=None, dict_type=None): ############################################################################### """Find and return a var_dictionary named, <dict_name> in <table>. If not found, return None""" var_dicts = table.find("var_dictionaries") target_dict = None ...
bigcode/self-oss-instruct-sc2-concepts
def return_top(scores, metric, x): """ :param scores: Pandas DataFrame with scores :type scores: Pandas DataFrame :param metric: String value for what score is desired ("Growth Score", "Value Score", "Momentum Score", "Score") :type metric: str :param x: Integer number of top stocks to return ...
bigcode/self-oss-instruct-sc2-concepts
def CollateDeps(deps_content): """ Take the output of deps_utils.GetDepsContent and return a hash of: { submod_name : [ [ submod_os, ... ], submod_url, submod_sha1 ], ... } """ spliturl = lambda x: list(x.partition('@')[0::2]) if x else [None, None] submods = {} # Non-OS-specific DEPS always override OS-...
bigcode/self-oss-instruct-sc2-concepts
def _encode_none(name, dummy0, dummy1, dummy2): """Encode python None.""" return b"\x0A" + name
bigcode/self-oss-instruct-sc2-concepts
def scenegraph_to_json(sg): """ Dump an "SceneGraph" object to a dict that's used for evaluation. The output will be saved as json. Args: sg (SceneGraph): Returns: dict: contains predictions for one image. """ boxes = sg.pred_boxes.tensor.numpy().tolist() # for vg evalu...
bigcode/self-oss-instruct-sc2-concepts
import hashlib def get_md5(file): """Get the md5 checksum of an input file. Arguments --------- file : str Path to file for which compute the checksum. Returns ------- md5 Checksum for the given filepath. Example ------- >>> get_md5('samples/audio_samples/exa...
bigcode/self-oss-instruct-sc2-concepts
def process_mmdet_results(mmdet_results, cat_id=0): """Process mmdet results, and return a list of bboxes. :param mmdet_results: :param cat_id: category id (default: 0 for human) :return: a list of detected bounding boxes """ if isinstance(mmdet_results, tuple): det_results = mmdet_resu...
bigcode/self-oss-instruct-sc2-concepts
def assemble_subpeak_record(subpeak, celltype_activations, sequence): """ Assemble the FASTA record of sequence and activation """ # make the header header ='\t'.join([s for s in subpeak]) header = '>' + header # make the activation string activation = ';'.join([ct+' '+str(score) for (ct,score)...
bigcode/self-oss-instruct-sc2-concepts
from typing import Dict def is_state_nncf(state: Dict) -> bool: """The function to check if sate is the result of NNCF-compressed model.""" return bool(state.get("meta", {}).get("nncf_enable_compression", False))
bigcode/self-oss-instruct-sc2-concepts
def read_split(split_filename): """ Return a list of pdb codes included in the split. """ print('Reading split from file', split_filename) with open(split_filename, 'r') as f: pdbcodes = [t.strip() for t in f.readlines()] return pdbcodes
bigcode/self-oss-instruct-sc2-concepts
def clean_info(package_dict: dict) -> dict: """ Only keep `name` and `home-page` keys. Arguments: package_dict: Package information. Returns: Cleaned-up information. """ return {_: package_dict[_] for _ in ("name", "home-page")}
bigcode/self-oss-instruct-sc2-concepts
def extended_euclidean_algorithm(a, b): # @param ax + by = gcd(a,b) """ Based on the fact that: b % a = b - (b // a) * a\\ gcd(a, b) = gcd(b%a, a) """ if a == 0: return b, 0, 1 gcd, x1, y1 = extended_euclidean_algorithm(b % a, a) x = y1 - (b//a)*x1 y = x1 return (gc...
bigcode/self-oss-instruct-sc2-concepts
def cidade_pais(cidade: str, pais: str, populacao: int = 0) -> str: """ -> Aceita o nome de uma cidade, o nome do país e a população dessa cidade, retorna essas informações formatadas. :param cidade: Nome da cidade. :param pais: Nome do país. :param populacao: Número da população da cidade....
bigcode/self-oss-instruct-sc2-concepts
def string_to_bits(str): """ string_to_bits Function Converts a Pythonic string to the string's binary representation. Parameters ---------- str: string The string to be converted. Returns ------- data: string The binary...
bigcode/self-oss-instruct-sc2-concepts
import torch import math def uniform_binning_correction(x, n_bits=8): """Replaces x^i with q^i(x) = U(x, x + 1.0 / 256.0). Args: x: 4-D Tensor of shape (NCHW) n_bits: optional. Returns: x: x ~ U(x, x + 1.0 / 256) objective: Equivalent to -q(x)*log(q(x)). """ b, c, ...
bigcode/self-oss-instruct-sc2-concepts
def remove_underscore(text): """ Call this on variable names and api endpoints, so that BERT tokenizes names like 'find_place' as 'find place'. """ return text.replace("_", " ")
bigcode/self-oss-instruct-sc2-concepts
def filter_contacts(cmap, threshold=0.2): """Remove low score contacts from contact prediction list. :param cmap: Contact prediction map. :type cmap: :class:`~conkit.core.contactmap.ContactMap` :param threshold: Threshold, defaults to 0.2. :type threshold: float, optional """ cmap.sort('ra...
bigcode/self-oss-instruct-sc2-concepts
def split_seconds(seconds: int) -> dict: """This function converts seconds into a dictionary by splitting seconds without year, month, day, hour, minute and second when possible. :param seconds: seconds that will be converted Example: >>> from phanterpwa.tools import split_seconds >>> ...
bigcode/self-oss-instruct-sc2-concepts
import base64 import json def encode_data(data): """Return a base64 encoded json dump.""" encoded = base64.b64encode( json.dumps(data).encode('utf-8') ) assert len(encoded) < 250 * 1024 return encoded
bigcode/self-oss-instruct-sc2-concepts
import math def getUnitCost(demand: int) -> float: """ Implementation of decreasing unit cost: Unit cost drops as demand/production increases. """ average_fixed_cost = 2.5 weight = 0.75 average_variable_cost = weight*math.log(demand) return average_fixed_cost + average_variable_cost
bigcode/self-oss-instruct-sc2-concepts
from typing import Dict from typing import Union def format_sum_formula(sumform: Dict[str, Union[int, float]], break_after: int = 99) -> str: """ Makes html formated sum formula from dictionary. >>> format_sum_formula({'C': 12, 'H': 6, 'O': 3, 'Mn': 7}) '<html><body>C<sub>12 </sub>H<sub>6 </sub>O<sub>...
bigcode/self-oss-instruct-sc2-concepts
def get_iwp_label_key( iwp_label ): """ Retrieves a key that locates the supplied IWP label within the underlying dataset. The key returned locates the label both temporarly and spatially. Takes 1 argument: iwp_label - IWP label to locate. Returns 1 value: label_key - Tuple identify...
bigcode/self-oss-instruct-sc2-concepts
import yaml def template_params(path): """ Return parameters as dict from a YAML template file. """ with open(path, "r") as file: return yaml.safe_load(file)
bigcode/self-oss-instruct-sc2-concepts
def _mnl_transform_deriv_c(*args, **kwargs): """ Returns None. This is a place holder function since the MNL model has no shape parameters. """ # This is a place holder function since the MNL model has no shape # parameters. return None
bigcode/self-oss-instruct-sc2-concepts
def _pad(slist, n, c=" "): """_pad(slist, n, c=' ') pads each member of string list 'slist' with fill character 'c' to a total length of 'n' characters and returns the concatenated results. strings longer than n are *truncated*. >>> >>> _pad(["this","that","the other"],9," ") 'this tha...
bigcode/self-oss-instruct-sc2-concepts
def _ensure_trailing_slash(url: str) -> str: """Return url guaranteed to end in a slash""" return url if url.endswith("/") else f"{url}/"
bigcode/self-oss-instruct-sc2-concepts
def _scoped_name(name_scope, node_name): """Returns scoped name for a node as a string in the form '<scope>/<node name>'. Args: name_scope: a string representing a scope name, similar to that of tf.name_scope. node_name: a string representing the current node name. Returns A string representing a sc...
bigcode/self-oss-instruct-sc2-concepts
def process_claim(claim): """Convert a claim row into a set of points""" claim_number, details = [i.strip() for i in claim.split('@')] # strip the leading # claim_number = int(claim_number[1:]) coordinates, area = [i.strip() for i in details.split(':')] column, row = [int(i) for i in coordinates...
bigcode/self-oss-instruct-sc2-concepts
import math def num_digits(n): """ Return the number of digits (in base 10) for integer n > 0 """ return int(math.log10(n)) + 1
bigcode/self-oss-instruct-sc2-concepts
def get_best_fuzz(predicted_mem): """Retrieve the best prediction""" y_pred = predicted_mem.argmax(axis=1) return y_pred
bigcode/self-oss-instruct-sc2-concepts
def append_heatmap(tokens, scores, latex, gamma, caption, pad_token, formatting="colorbox", truncate_pad=True): """ Produce a heatmap for LaTeX Format options: colorbox, text""" if gamma != 1: raise NotImplementedError latex += "\n\\begin{figure}[!htb]" for token, score in zip(tokens, sc...
bigcode/self-oss-instruct-sc2-concepts
def total_link_cost(net): """ Compute the total of link costs (volume * costfunction(volume)) over all links at current volumes on those links Parameters: net - Net object as returned by parse_net_file() Return value: total link cost """ return sum([link.volume * link.cost fo...
bigcode/self-oss-instruct-sc2-concepts
def make_grid(x, y, fill: int = 0): """Make a 2x2 list of lists filled with "fill".""" return [[fill for y in range(y)] for _ in range(x)]
bigcode/self-oss-instruct-sc2-concepts
def i8(x): """truncates x to a 8-bit integer""" return x & 0xFF
bigcode/self-oss-instruct-sc2-concepts
def get_las_version(las): """ Get the LAS file format version from an in-memory lasio.LAFile object. There are 3 possible versions (https://www.cwls.org/products/): - LAS 1.2 - LAS 2.0 - LAS 3.0 Args: las (lasio.LASFile): An in-memory lasio.LASFile object Returns:...
bigcode/self-oss-instruct-sc2-concepts
from typing import Sequence from typing import Dict from typing import Any def bind_function_args(argument_names: Sequence[str], *args, **kwargs) -> Dict[str, Any]: """Returns a dict with function arguments.""" outputs = {} for k, val in zip(argument_names, args): outputs[k] = val o...
bigcode/self-oss-instruct-sc2-concepts
from typing import Dict def make_character_dict() -> Dict[str, str]: """Create dict of {character: label, ->} to label smiles characters """ character_dict = {} atoms = ["C", "O", "N", "S", "B", "P", "F", "I", "c", "n", "o", '*', 'Cl', 'Br', 'p', 'b', 'p', 's'] cyclic = list(range(1,1...
bigcode/self-oss-instruct-sc2-concepts
def list_contains_only_xs(lst): """Check whether the given list contains only x's""" for elem in lst: if elem != "X": return False return True
bigcode/self-oss-instruct-sc2-concepts
import json def decode_json(json_string: str) -> dict: """ Takes a message as a JSON string and unpacks it to get a dictionary. :param str json_string: A message, as a JSON string. :return dict: An unverified dictionary. Do not trust this data. """ return json.JSONDecoder().decode(json_string...
bigcode/self-oss-instruct-sc2-concepts
def set_length_units(client, units, file_=None, convert=None): """Set the current length units for a model. This will search the model's available Unit Systems for the first one which contains the given length unit. Args: client (obj): creopyson Client. units (str): ...
bigcode/self-oss-instruct-sc2-concepts
import torch import math def log_sum_exp(a: torch.Tensor, b: torch.Tensor): """ Logsumexp with safety checks for infs. """ if torch.isinf(a): return b if torch.isinf(b): return a if a > b: return math.log1p(math.exp(b - a)) + a else: return math.log1p(math...
bigcode/self-oss-instruct-sc2-concepts
from typing import List from typing import Any from typing import Union from typing import Tuple def isinstances(__obj: List[Any], __class_or_tuple: Union[Any, Tuple[Any]]) -> bool: """Return whether an every element of the list is an instance of a class or of a subclass thereof. A tuple, as in `isinstance(x,...
bigcode/self-oss-instruct-sc2-concepts
def polynomial_power_combinations(degree): """ Combinations of powers for a 2D polynomial of a given degree. Produces the (i, j) pairs to evaluate the polynomial with ``x**i*y**j``. Parameters ---------- degree : int The degree of the 2D polynomial. Must be >= 1. Returns -----...
bigcode/self-oss-instruct-sc2-concepts
def from_cpp(str_msg, cls): """Return a ROS message from a serialized string Parameters ---------- - str_msg: str, serialized message - cls: ROS message class, e.g. sensor_msgs.msg.LaserScan. """ msg = cls() result = msg.deserialize(str_msg) return result
bigcode/self-oss-instruct-sc2-concepts
def ipv4_lstrip_zeros(address): """ The function to strip leading zeros in each octet of an IPv4 address. Args: address: An IPv4 address in string format. Returns: String: The modified IPv4 address string. """ # Split the octets. obj = address.strip().split('.') for ...
bigcode/self-oss-instruct-sc2-concepts
import re def join_lines(src, before, after, sep=" "): """ Remove the newline and indent between a pair of lines where the first ends with ``before`` and the second starts with ``after``, replacing it by the ``sep``. """ before_re = "][".join(before).join("[]") after_re = "][".join(after)....
bigcode/self-oss-instruct-sc2-concepts
def flatten_stmts(stmts): """Return the full set of unique stms in a pre-assembled stmt graph. The flattened list of of statements returned by this function can be compared to the original set of unique statements to make sure no statements have been lost during the preassembly process. Parameters...
bigcode/self-oss-instruct-sc2-concepts
import math def round_sig(number, precision=4): """ Round number with given number of significant numbers - precision Args: number (number): number to round precision (int): number of significant numbers """ if number == 0.0: return number return round(number, precision - ...
bigcode/self-oss-instruct-sc2-concepts
def pairs(k, arr): """Hackerrank Problem: https://www.hackerrank.com/challenges/pairs/problem You will be given an array of integers and a target value. Determine the number of pairs of array elements that have a difference equal to a target value. Args: k (int): The target difference ...
bigcode/self-oss-instruct-sc2-concepts
def find(sexp, *names): """Return the first node in `sexp` whose name is in `names`""" for child in sexp: if child[0] in names: return child
bigcode/self-oss-instruct-sc2-concepts
import json def get_workflow_metadata(metadata_json): """Load workflow metadata from a JSON file. Args: metadata_json (str): Path to file containing metadata json for the workflow. Returns: metadata (dict): A dict consisting of Cromwell workflow metadata information. """ with ope...
bigcode/self-oss-instruct-sc2-concepts
def create_unbroadcast_axis(shape, broadcast_shape): """Creates the reduction axis for unbroadcasting. Args: shape: A list. The shape after the broadcast operation. broadcast_shape: A list. The original shape the array being unbroadcast had. Returns: A list. The axes along which the array needs...
bigcode/self-oss-instruct-sc2-concepts
def check_zeros(counts): """ helper function to check if vector is all zero :param counts: :return: bool """ if sum(counts) == 0: return True else: return False
bigcode/self-oss-instruct-sc2-concepts
def get_nat_orb_occ(lines): """ Find the natural orbital occupations """ nat_occ = [] start = False for line in lines: if start: if line.strip(): nat_occ.append(abs(float(line.split('=')[-1].strip()))) else: break elif line ...
bigcode/self-oss-instruct-sc2-concepts
def are_words_in_word_list( words, word_list, case_sensitive=False, get_score=False, all_must_match=True ): """Checks if word(s) are contained in another word list. The search can be performed with or without case sensitivity. The check words can contain wildcards, e.g. "abc*" to allow a wider range...
bigcode/self-oss-instruct-sc2-concepts
def percentiles_from_counts(counts_dt, percentiles_range=None): """Returns [(percentile, value)] with nearest rank percentiles. Percentile 0: <min_value>, 100: <max_value>. counts_dt: { <value>: <count> } percentiles_range: iterable for percentiles to calculate; 0 <= ~ <= 100 Source: https://stackov...
bigcode/self-oss-instruct-sc2-concepts
def epsi_vapor_bot(Fr_bot): """ Calculates the vapor content of bubble layer at the bottom of column Parameters ---------- Fr_bot : float The Frudo criterion at the bottom of column, [dimensionless] Returns ------- epsi_vapor_bot : float The vapor content of bubble layer ...
bigcode/self-oss-instruct-sc2-concepts
def flatten_double_list(double_list): """ flatten a double list into a single list. """ return [obj for single_list in double_list for obj in single_list]
bigcode/self-oss-instruct-sc2-concepts
def slice_list_to_chunks(lst, n): """ Slice a list into chunks of size n. Args: list int Returns: [list] """ chunks = [lst[x:x+n] for x in range(0, len(lst), n)] return chunks
bigcode/self-oss-instruct-sc2-concepts
def get_age_bracket(school_type): """Return the age structure for different school types.""" age_brackets = { 'primary':[6, 7, 8, 9], 'primary_dc':[6, 7, 8, 9], 'lower_secondary':[10, 11, 12, 13], 'lower_secondary_dc':[10, 11, 12, 13], 'upper_secondary':[14, 15, 16, 17], 'secondary':[10, 11, 12, 13, 14, 1...
bigcode/self-oss-instruct-sc2-concepts
def seq_to_arch(seq, num_nodes): """ Translates given sequential representation of an architecture sampled by the controller to an architecture Arguments: seq: sequential representation of architecture num_nodes: number of nodes in cell including the two input nodes Returns: ...
bigcode/self-oss-instruct-sc2-concepts
def force_tuple(x): """Make tuple out of `x` if not already a tuple or `x` is None""" if x is not None and not isinstance(x, tuple): return (x,) else: return x
bigcode/self-oss-instruct-sc2-concepts
from typing import List from typing import Dict def _build_record_dict(record_strings: List[str]) -> Dict: """ Parse the pbn line by line. When a block section like "Auction" or "Play" is encountered, collect all the content of the block into a single entry :param record_strings: List of string lines...
bigcode/self-oss-instruct-sc2-concepts
def ts_to_vtt(timestamp): """ ts_to_vtt converts timestamp into webvtt times """ hours, seconds = divmod(timestamp, 3600) mins, seconds = divmod(seconds, 60) seconds = round(seconds, 3) return f" {int(hours):02}:{int(mins):02}:{seconds:02}"
bigcode/self-oss-instruct-sc2-concepts
def _node_label(node): """Generate a node label in the format of "support:name" if both exist, or "support" or "name" if either exists. Parameters ---------- skbio.TreeNode node containing support value or name Returns ------- str Generated node label """ lblst ...
bigcode/self-oss-instruct-sc2-concepts
def fetch_tensor(name, ws): """Return the value of a tensor.""" return ws.get_tensor(name).ToNumpy()
bigcode/self-oss-instruct-sc2-concepts
def torch2numpy(img): """ Converts a torch image to numpy format """ if img.dim() == 4: img = img.permute(0, 2, 3, 1).contiguous() elif img.dim() == 3: img = img.permute(1, 2, 0).contiguous() return img.cpu().numpy()
bigcode/self-oss-instruct-sc2-concepts
from typing import Dict import re def str_replace(s: str, replacements: Dict[str, str]) -> str: """Replaces keys in replacements dict with their values.""" for word, replacement in replacements.items(): if word in s: s = re.sub(re.escape(word), replacement, s, flags=re.IGNORECASE) retu...
bigcode/self-oss-instruct-sc2-concepts
def get_bits(num, gen): """ Get "num" bits from gen """ out = 0 for i in range(num): out <<= 1 val = gen.next() if val != []: out += val & 0x01 else: return [] return out
bigcode/self-oss-instruct-sc2-concepts
def GetMangledParam(datatype): """Returns a mangled identifier for the datatype.""" if len(datatype) <= 2: return datatype.replace('[', 'A') ret = '' for i in range(1, len(datatype)): c = datatype[i] if c == '[': ret += 'A' elif c.isupper() or datatype[i - 1] in ['/', 'L']: ret += c....
bigcode/self-oss-instruct-sc2-concepts
def get_feature_class(base_name, workspace): """ Creates a valid ESRI reference to a shapefile or geodatabase feature class base_name: the name of the feature class, without any extension workspace: the name of the folder (for shapefiles) or geodatabase (for gdb feature classes) return: a text strin...
bigcode/self-oss-instruct-sc2-concepts
import signal def signal_to_human(value): """signal_to_human() -- provide signal name based on subprocess return code Args: value (int) - Popen.returncode Returns: Signal name if it exists, otherwise the original value provided """ signals = {getattr(signal, name) * -1 : name for...
bigcode/self-oss-instruct-sc2-concepts
def interpret_bintime(bintime): """If bin time is negative, interpret as power of two. Examples -------- >>> interpret_bintime(2) 2 >>> interpret_bintime(-2) == 0.25 True >>> interpret_bintime(0) Traceback (most recent call last): ... ValueError: Bin time cannot be = 0 ...
bigcode/self-oss-instruct-sc2-concepts
def get_kernel(x, kernel): """ Calculates the kernel size given the input. Kernel size is changed only if the input dimentions are smaller than kernel Args: x: The input vector. kernel: The height and width of the convolution kernel filter Returns: The height and width of new co...
bigcode/self-oss-instruct-sc2-concepts
def pot_LJ_dl(r): """Dimensionless Lenard Jones potential, based on distances""" r = r**-6 # Possibly improves speed u = 4*(r**2 - r) return u
bigcode/self-oss-instruct-sc2-concepts
def fit_model(model, callbacks_list, sequence, outseq, n_epoch): """ Make RAENN model Parameters ---------- model : keras.models.Model RAENN model to be trained callbacks_list : list List of keras callbacks sequence : numpy.ndarray Array LC flux times, values and err...
bigcode/self-oss-instruct-sc2-concepts
def get_named_object(pathspec): """Return a named from a module. """ parts = pathspec.split('.') module = ".".join(parts[:-1]) mod = __import__(module, fromlist=parts[-1]) named_obj = getattr(mod, parts[-1]) return named_obj
bigcode/self-oss-instruct-sc2-concepts
def get_formatted_emg(emg_row): """ :param emg_row: dict [str] one row that represent data from Electromyograph sensor example: ['2018-07-04T17:39:53.743240', 'emg', '-1', '-6', '-9', '-9', '1', '1', '-1', '-2', '2018-07-04T17:39:53.742082'] :return: formatted emg row example: ['2018-07-...
bigcode/self-oss-instruct-sc2-concepts
from typing import OrderedDict def get_companies(dbconnection, args): """ Return an ordered dictionary of information from the company table. The key is the db key """ print('Companies') cursor = dbconnection.cursor() cursor.execute('SELECT * FROM Companies') row = cursor.fetchone() ...
bigcode/self-oss-instruct-sc2-concepts
def code() -> str: """ Example G-code module, a drawing of a crocodile. Please simulate first, before milling. """ return """ G91 G17 G3 X20 Y0 I10 J0 G0 X40 Y0 G3 X6 Y0 I3 J0 G0 X0 Y3 G3 X-3 Y3 I-3 J0 G0 X-40 Y0 G2 X0 Y6 I0 J3...
bigcode/self-oss-instruct-sc2-concepts
import re def remove_none_alphanumeric(string): """ remove non-alphanumeric characters """ pattern = re.compile("[\W_]+", re.UNICODE) return pattern.sub("", string)
bigcode/self-oss-instruct-sc2-concepts
def map_values(map_fn, dictionary): """Returns a dictionary whose values have been transformed by map_fn. """ return {k: map_fn(v) for k, v in dictionary.items()}
bigcode/self-oss-instruct-sc2-concepts
def create_poll(poll_options: list) -> dict: """ Creates a poll of a list of options :param poll_options: :return: """ poll_opts_map = {} for opt in poll_options: poll_opts_map.update({opt.lstrip(" ").rstrip(" "): 0}) return poll_opts_map
bigcode/self-oss-instruct-sc2-concepts
import re def loads(hesciiStr, prefix='x'): """ Takes a hescii-encoded string and returns the utf-8 byte string. Args: hesciiStr: a hescii-encoded string prefix: string used to prefix all encoded hex values. Default 'x' Returns: A utf-8 byte string """ ...
bigcode/self-oss-instruct-sc2-concepts
def _make_package(x): """Get the package name and drop the last '.' """ package = '' for p in x: package += p[0] + p[1] if package and package[-1] == '.': package = package[:-1] return package
bigcode/self-oss-instruct-sc2-concepts
def _conv(n): """Convert a node name to a valid dot name, which can't contain the leading space""" if n.startswith(' '): return 't_' + n[1:] else: return 'n_' + n
bigcode/self-oss-instruct-sc2-concepts
def val_or_none_key(getter_fcn): """Wraps getter_fcn, returning a key that is a tuple of (0 or 1, val) where val=getter_fcn(obj), and the int is 0 if val is None.""" def result_key_fcn(obj): val = getter_fcn(obj) n = 0 if val is None else 1 return n, val return result_key_fcn
bigcode/self-oss-instruct-sc2-concepts
def strip_diagnostics(tracks): """Remove diagnostic information from a tracks DataFrame. This returns a copy of the DataFrame. Columns with names that start with "diag_" are excluded.""" base_cols = [cn for cn in tracks.columns if not cn.startswith('diag_')] return tracks.reindex(columns=base_cols)
bigcode/self-oss-instruct-sc2-concepts
def make_token(name, value=''): """Make a token with name and optional value.""" return {'name': name, 'value': value}
bigcode/self-oss-instruct-sc2-concepts
def convert_frac(ratio): """ Converts ratio strings into float, e.g. 1.0/2.0 -> 0.5 """ try: return float(ratio) except ValueError: num, denom = ratio.split('/') return float(num) / float(denom)
bigcode/self-oss-instruct-sc2-concepts
def k8s_url(namespace, kind, name=None): """ Construct URL referring to a set of kubernetes resources Only supports the subset of URLs that we need to generate for use in kubespawner. This currently covers: - All resources of a specific kind in a namespace - A resource with a specific name ...
bigcode/self-oss-instruct-sc2-concepts
def _pad_vocabulary(vocab, math): """ Pads vocabulary to a multiple of 'pad' tokens. Args: vocab (list): list with vocabulary math (str): Math precision. either `fp_16`, `manual_fp16` or `fp32` Returns: list: padded vocabulary """ if math == "fp16": pad = 8 ...
bigcode/self-oss-instruct-sc2-concepts
def convert_r_groups_to_tuples(r_groups): """ Converts a list of R-Group model objects to R-Group tuples""" return [r_group.convert_to_tuple() for r_group in r_groups]
bigcode/self-oss-instruct-sc2-concepts
import re def domain(url): """Get domain from url. Domain must start with ``http://``, ``https://`` or ``/``. Parameters ---------- url: str URL to parse to extract the domain. Raises ------ ValueError If the URL pattern is invalid. Examples -------- ...
bigcode/self-oss-instruct-sc2-concepts
def scale(x, s): """Scales x by scaling factor s. Parameters ---------- x : float s : float Returns ------- x : float """ x *= s return x
bigcode/self-oss-instruct-sc2-concepts
def pop_sort(pop): """ This function sorts the population based on their fitnesses, using selection sort. pop: The population that are sorted based on their fitnesses. """ for i in range(len(pop)): min_index = i for j in range(i+1, len(pop)): if pop[min_index].fitnes...
bigcode/self-oss-instruct-sc2-concepts
def subverParseClient(s): """return the client name given a subversion string""" return s[1:].split(":")[0]
bigcode/self-oss-instruct-sc2-concepts
import requests def get_all_service_groups(asa): """ This function retrieves all service groups from ASA :param asa: ASA device which to retrieve the objects from ASA :return: Returns list of service objects. """ url = asa.url() + "/api/objects/networkservicegroups" headers = { 'C...
bigcode/self-oss-instruct-sc2-concepts