seed
stringlengths
1
14k
source
stringclasses
2 values
def format_network_speed(raw_bps=0): """ Formats a network speed test to human readable format """ fmt = ['b/s', 'Kb/s', 'Mb/s', 'Gb/s'] index = 0 speed = raw_bps while speed > 1024: index += 1 speed /= 1024 return "%0.2f %s" % (speed, fmt[index])
bigcode/self-oss-instruct-sc2-concepts
def derivative_from_polycoefficients(coeff, loc): """ Return derivative of a polynomial of the form f(x) = coeff[0] + coeff[1]*x + coeff[2]*x**2 + ... at x = loc """ derivative = 0. for n, c in enumerate(coeff): if n == 0: continue derivative += n*c*loc**(n-...
bigcode/self-oss-instruct-sc2-concepts
def run(result): """Function to test True return""" return True
bigcode/self-oss-instruct-sc2-concepts
def get_probe_hit(tree, gene_info, r, is_gtf=False): """ Given a dict tree (from read_probe_bed) and a GMAP SAM record Go through each exon and find probes that hit it Return: (number of probes hit), (total number of bases overlapping with probes), (genes seen) """ probes_seen = set() genes...
bigcode/self-oss-instruct-sc2-concepts
def firstof(*args, default=None): """ Returns the first value which is neither empty nor None. """ if len(args) == 1: iterable = args[0] else: iterable = args for value in iterable: if value: return value return default
bigcode/self-oss-instruct-sc2-concepts
import functools def _validate_satellite(func): """A decorator that checks to see if the satellite is in the dataset.""" @functools.wraps(func) def wrapper(self, satellite, *args, **kwargs): # First argument has to be satellite if satellite not in self.ds['satellite']: raise In...
bigcode/self-oss-instruct-sc2-concepts
def count_lines(filename): """Count the number of lines in a source file Return a pair (n0, n1), where n0 is the total number of lines, while n1 is the number of non-empty lines """ with open(filename) as f: lines = f.readlines() n0 = len(lines) n1 = 0 for line...
bigcode/self-oss-instruct-sc2-concepts
def concat(str_1: str, str_2: str) -> str: """將兩個字串串接在一起 Args: str_1 (str): 字串 1 str_2 (str): 字串 2 Raises: TypeError: 當任一參數不為 str 時,拋出 TypeError Returns: str: str_1+str_2 """ if not (isinstance(str_1, str) and isinstance(str_2, str)): raise TypeError("錯...
bigcode/self-oss-instruct-sc2-concepts
def right_rotate(n: int, b: int) -> int: """ Right rotate the input by b. :param n: The input. :param b: The rotation factor. :return: The input after applying rotation. """ return ((n >> b) | ((n & 0xffffffff) << (32 - b))) & 0xffffffff
bigcode/self-oss-instruct-sc2-concepts
def unstack_batch(tensor, B): """Reverses stack_batch.""" N = tensor.shape[0] // B return tensor.reshape(B, N, *tensor.shape[1:])
bigcode/self-oss-instruct-sc2-concepts
import datetime as dt def check_date(indate): """Check representations of date and try to force into a datetime.date The following formats are supported: 1. a date object 2. a datetime object 3. a string of the format YYYYMMDD 4. a string of the format YYYYDDD ...
bigcode/self-oss-instruct-sc2-concepts
def tokenize_char(sent): """ Return the character tokens of a sentence including punctuation. """ return list(sent.lower())
bigcode/self-oss-instruct-sc2-concepts
import getpass def get_user_name() -> str: """ Gets the username of the device Returns ------- username : str Username of the device """ return getpass.getuser()
bigcode/self-oss-instruct-sc2-concepts
def quantile(values, p): """ Returns the pth-percentile value >>> quantile([2, 4, 6, 8], 0.25) 4 >>> quantile([3, 2, 6, 4, 8, 5, 7, 1, 9, 11, 10], 0.5) 6 >>> quantile([3, 2, 6, 4, 8, 5, 7, 1, 9, 11, 10], 0.55) 7 >>> quantile([3, 2, 6, 4, 8, 5, 7, 1, 9, 11, 10], 0.75) 9 """ ...
bigcode/self-oss-instruct-sc2-concepts
def InStr(*args): """Return the location of one string in another""" if len(args) == 2: text, subtext = args return text.find(subtext)+1 else: start, text, subtext = args pos = text[start-1:].find(subtext) if pos == -1: return 0 else: r...
bigcode/self-oss-instruct-sc2-concepts
def create_url(controller_ip, endpoint): """Create endpoint url to POST/PUT/GET/DELTE against.""" return 'https://%s:1080/%s' % (controller_ip, endpoint)
bigcode/self-oss-instruct-sc2-concepts
def parse_psipred_file(psipred_output): """ This function parses the psipred output file and returns the secondary structure predicted. """ opened_file = open(psipred_output).readlines() seq = "" for line in opened_file: line = line.strip().split(" ") seq += line[2] ...
bigcode/self-oss-instruct-sc2-concepts
def custom(x,w,lambdafunc=None): """Custom model (for example, for real data fitting). Parameters ---------- x : numpy array (N,), dtype=float Grid points in which the model will be evaluated. N is the number of grid points. w : numpy array (N,), dtype=float Weights used to eval...
bigcode/self-oss-instruct-sc2-concepts
def pep8_filter(line): """ Standard filter for pep8. """ if 'argweaver/bottle.py' in line: return False return True
bigcode/self-oss-instruct-sc2-concepts
import re def sanitize(s): """ Removes characters that are not allowed in macro names. Anything that's not alphanumeric is replaced with underscore. """ return re.sub(r"\W", '_', s)
bigcode/self-oss-instruct-sc2-concepts
def crop_to(image_to_crop, reference_image): """ Crops image to the size of a reference image. This function assumes that the relevant image is located in the center and you want to crop away equal sizes on both the left and right as well on both the top and bottom. :param image_to_crop :param refer...
bigcode/self-oss-instruct-sc2-concepts
def _isbn_has_valid_checksum(identifier): """Determine whether the given ISBN has a valid checksum.""" if len(identifier) == 10: identifier = '978' + identifier numerals = [int(char) for char in identifier] checksum = 0 for i, numeral in enumerate(numerals): weight = 1 if i % 2 == 0...
bigcode/self-oss-instruct-sc2-concepts
def _find_physio(subject, session, bids_path): """Get physilogy data from BIDS dataset.""" physio_path = list( bids_path.glob(f"**/sub-{subject}_ses-{session}*_physio.tsv.gz") ) if physio_path and len(physio_path) == 1: return physio_path[0] else: raise ValueError("No associa...
bigcode/self-oss-instruct-sc2-concepts
def _is_linux_os(rctx): """Returns true if the host operating system is Linux""" return rctx.os.name.lower().startswith("linux")
bigcode/self-oss-instruct-sc2-concepts
import collections def parse_file(path): """ Parse a spikes file: fail hard! If parsing does not work, print offending line and exit(1) returns dict keyed on gid. each value is a list of (spiketimes, the line number, line ) """ fp = open(path, "r") parsed_data = collections.defau...
bigcode/self-oss-instruct-sc2-concepts
def _get_full_customization_args(customization_args, ca_specs): """Populates the given customization_args dict with default values if any of the expected customization_args are missing. """ for ca_spec in ca_specs: if ca_spec.name not in customization_args: customization_args[ca_spec...
bigcode/self-oss-instruct-sc2-concepts
import math def eq141d10(l, sx, a, sum_st, iy, fy, e): """Compression in extreme fibers of box type flexural members AREMA 2018 Section 1.4.1 Table 15-1-11 Row 10 Compression in the extreme fibers of box type welded or bolted flexural members symmetrical about the principal axis midway betwe...
bigcode/self-oss-instruct-sc2-concepts
def alphanumeric(password: str) -> bool: """ The string has the following conditions to be alphanumeric: 1. At least one character ("" is not valid) 2. Allowed characters are uppercase / lowercase latin letters and digits from 0 to 9 3. No whitespaces / underscore :param password: :re...
bigcode/self-oss-instruct-sc2-concepts
def nested_get(dct, keys): """ Gets keys recursively from dict, e.g. nested_get({test: inner: 42}, ["test", "inner"]) would return the nested `42`. """ for key in keys: if isinstance(dct, list): dct = dct[int(key)] else: dct = dct[key] return dct
bigcode/self-oss-instruct-sc2-concepts
def pos_neg(a: int, b: int, negative: bool) -> bool: """Differences in signed digits. Return True if: - negative is True and both a,b < 0. - negative is False and ((a > 0 and b < 0) or (a < 0 and b > 0). Return False otherwise. """ if negative: return (a < 0 and b < ...
bigcode/self-oss-instruct-sc2-concepts
def args_cleanup( args, s ): """ Clean-up the substring s for keys in args Arguments --------- args: The dictionary to be parsed s : Substring to be discarded. e.g. s = '--', then "--record" --> "record" """ if not isinstance( args, dict ) or not isinstan...
bigcode/self-oss-instruct-sc2-concepts
import importlib def import_module(dotted_path): """ Import a dotted module path. Raise ImportError if the import failed. """ return importlib.import_module(dotted_path)
bigcode/self-oss-instruct-sc2-concepts
def make_kms_map(map_string): """Convert a string into a map.""" # The one line version: # dict({tuple(k.split(':')) for k in [i.strip() for i in m.split(',')]}) result = dict() # split string by comma and strip lines = [i.strip() for i in map_string.split(",")] for line in lines: # ...
bigcode/self-oss-instruct-sc2-concepts
def allowed_transitions(states): """ this function takes a set of states and uses it to compute the allowed transitions it assumes the model is acyclic ie. individuals can only transition towards states to the right of it in the list Parameters ---------- states : list a list with t...
bigcode/self-oss-instruct-sc2-concepts
import requests def get_series_name(cfg, series_id): """ Request series information from Opencast. :param series_id: Unique identifier for series :param cfg: Opencast configuration :return: Title of the series """ url = cfg['uri'] + "/api/series/" + series_id r = requests.get(url=url,...
bigcode/self-oss-instruct-sc2-concepts
import contextlib import wave import audioop def read_wave(path): """Reads a .wav file. Takes the path, and returns (PCM audio data, sample rate). """ with contextlib.closing(wave.open(path, 'rb')) as wf: num_channels = wf.getnchannels() assert num_channels == 1 sample_width = wf.getsampwidth() assert sam...
bigcode/self-oss-instruct-sc2-concepts
def calc_simple_profit(orders, kl_pd): """ 计算交易收益,simple的意思是不考虑手续费 :param orders: AbuOrder对象序列 :param kl_pd: 金融时间序列,pd.DataFrame对象 :return: """ all_profit = 0 now_price = kl_pd[-1:].close for order in orders: if order.sell_type == 'keep': # 单子如果还没有卖出,使用now_price计算...
bigcode/self-oss-instruct-sc2-concepts
def decimal_to_octal(decimal: int)->str: """Convert a Decimal Number to an Octal Number.""" if not isinstance(decimal , int): raise TypeError("You must enter integer value") rem , oct , c = 0 , 0 ,0 is_negative = '-' if decimal < 0 else '' decimal = abs(decimal) while decimal > 0: ...
bigcode/self-oss-instruct-sc2-concepts
def rfam_problems(status): """ Create a list of the names of all Rfam problems. """ ignore = {"has_issues", "messages", "has_issue", "id"} problems = sorted(n for n, v in status.items() if v and n not in ignore) return problems or ["none"]
bigcode/self-oss-instruct-sc2-concepts
def preserve_sesam_special_fields(target, original): """ Preserves special and reserved fields. ref https://docs.sesam.io/entitymodel.html#reserved-fields """ sys_attribs = ["_deleted","_hash","_id","_previous","_ts","_updated","_filtered", "$ids", "$children", "$replaced"] for attr in sys_at...
bigcode/self-oss-instruct-sc2-concepts
def unique_edge_list(network): """ Generates an edge list with only unique edges. This removes duplicates resulting from the bidirectional nature of the edges. :param network_simulator.Network network: source network :return: list edge_list: unique set of edges """ edge_list = [] nodes ...
bigcode/self-oss-instruct-sc2-concepts
def reverse_DNA(DNA_string): """ This function takes a DNA string and returns the reverse-complement sequence. It uses the Nucleotides dictionary to change the nucleotides with and iterative for loop. PARAMETERS ---------- DNA_string : string DNA sequence of the FASTA/Q file R...
bigcode/self-oss-instruct-sc2-concepts
import math def calc_rb_max(n_pe, beam_tot_z, beam_num_ptcl): """ Calculate the maximum radius of the plasma bubble Valid in "strong bubble regime", where rb_max*k_pe >> 1. Args: n_pe: number density of the electron plasma beam_tot_z: total length of the drive beam ...
bigcode/self-oss-instruct-sc2-concepts
def get_window_start_times(profileDict): """ Gets the times of the start of the sampling windows used in the profiled run Args: profileDict (dict): Dictionary of values representing an Arm MAP profiled run Returns: List of start times of sampling window """ asse...
bigcode/self-oss-instruct-sc2-concepts
def extreme_points_2(contour): """Returns extreme points of the contour""" extreme_left = tuple(contour[contour[:, :, 0].argmin()][0]) extreme_right = tuple(contour[contour[:, :, 0].argmax()][0]) extreme_top = tuple(contour[contour[:, :, 1].argmin()][0]) extreme_bottom = tuple(contour[contour[:, :,...
bigcode/self-oss-instruct-sc2-concepts
def connect(endpoint=None): """Generate connect packet. `endpoint` Optional endpoint name """ return u'1::%s' % ( endpoint or '' )
bigcode/self-oss-instruct-sc2-concepts
def use_filter(filter, url, input): """Apply a filter function to input from an URL""" output = filter(url, input) if output is None: # If the filter does not return a value, it is # assumed that the input does not need filtering. # In this case, we simply return the input. ...
bigcode/self-oss-instruct-sc2-concepts
import sqlite3 def db_retrieve_all(cursor: sqlite3.Cursor, table: str) -> list: """Get all values of a table.""" ret = cursor.execute(f"SELECT * FROM {table}") return ret.fetchall()
bigcode/self-oss-instruct-sc2-concepts
import struct def _compute_dc42_checksum(data): """Compute checksum DC42 uses to verify sector and tag data integrity. Args: data: data to compute a checksum for. Returns: a 32-bit (big endian) checksum as a 2-byte string. """ def addl_rorl(uint, csum): """Add `uint` to `csum`; 32-bit truncate; 3...
bigcode/self-oss-instruct-sc2-concepts
import re def regex_overlap(text, regex): """ for a list of tokens in text and a regex, match it in the tokens and return a list of booleans denoting which tokens are a part of the match """ overlap = [False for t in text] for m in re.finditer(regex, ' '.join(text)): begin, end = m.span() ...
bigcode/self-oss-instruct-sc2-concepts
def get_product_img_href(product_page_object) -> str: """ Get product image href link from product page-object. :param product_page_object: BeautifulSoup4 page object :return: string representation of product image href """ anchor_element = product_page_object.find("figure", {"class": "offer-th...
bigcode/self-oss-instruct-sc2-concepts
def __number_measurements(a, func_axis=None): """ Calculates the number of measurements of an array from the array and the function axis. """ if func_axis == None: return a.size else: return a.size / a.shape[func_axis]
bigcode/self-oss-instruct-sc2-concepts
def crop_image_to_bbox(img_arr, X_meta): """Given an image array, crops the image to just the bounding box provided.""" shape = img_arr.shape x_min = int(X_meta['x']) x_max = int(X_meta['x'] + X_meta['width']) y_min = int(X_meta['y']) y_max = int(X_meta['y'] + X_meta['height']) retu...
bigcode/self-oss-instruct-sc2-concepts
def grid_case_group(self, group_id): """Get a particular grid case group belonging to a project Arguments: groupId(int): group id Returns: :class:`rips.generated.generated_classes.GridCaseGroup` """ case_groups = self.grid_case_groups() for case_group in case_groups: if...
bigcode/self-oss-instruct-sc2-concepts
import re def lineStartsWithDate(line): """ checks to see if the line starts with a date """ match = re.search("\d\d\d\d\-\d\d\-\d\d", line ) if (re.search("\d\d\d\d\-\d\d\-\d\d", line ) ): return True else: return False
bigcode/self-oss-instruct-sc2-concepts
def version_tuple(version): """ Convert a version string or tuple to a tuple. Will return (major, minor, release) kind of format. """ if isinstance(version, str): return tuple(int(x) for x in version.split('.')) elif isinstance(version, tuple): return version
bigcode/self-oss-instruct-sc2-concepts
def _dso2info(dso): """Return mangled name of DSO info module. eg. 'my.pkg.libs.adso' -> 'my.pkg.libs.adso_dsoinfo' """ parts = dso.split('.') parts[-1] = '{}_dsoinfo'.format(parts[-1]) return '.'.join(parts)
bigcode/self-oss-instruct-sc2-concepts
def accuflux(idxs_ds, seq, data, nodata): """Returns maps of accumulate upstream <data> Parameters ---------- idxs_ds : 1D-array of intp index of next downstream cell seq : 1D array of int ordered cell indices from down- to upstream data : 1D array local values to be acc...
bigcode/self-oss-instruct-sc2-concepts
def topic_exists(client, topic_name): """ Reports if the topic is created Args: client (Kafka Client): The Kafka admin client topic_name (str): the topic name to be checked """ topic_data = client.list_topics(timeout=2) return topic_name in set(t.topic for t in iter(topic_data.to...
bigcode/self-oss-instruct-sc2-concepts
def _from_json(doc): """Invert _to_json()""" if "$numberLong" in doc: return int(doc["$numberLong"]) elif "__nonstring_keys" in doc: nonstring_keys = doc.pop("__nonstring_keys") return {nonstring_keys[k]: v for k, v in doc.items()} else: return doc
bigcode/self-oss-instruct-sc2-concepts
def _change_memo(amount, coins, T, n): """Helper function for num_coin_changes_memo().""" # Base cases. if amount < 0: return 0 if amount == 0: return 1 if n <= 0 and amount > 0: return 0 # Apply memoization. if T[n][amount]: return T[n][amount] # Sum n...
bigcode/self-oss-instruct-sc2-concepts
import re def clean_str(text): """ Apply some standard text cleaning with regular expressions. 1. Remove unicode characters. 2. Combine multiline hyphenated words. 3. Remove newlines and extra spaces. Parameters ---------- text : str Text to clean. Returns ...
bigcode/self-oss-instruct-sc2-concepts
def additionner_deux_nombres(premier_nombre, second_nombre): """ Additionne deux nombres inputs: Deux nombres outputs: Un nombre """ total = premier_nombre + second_nombre return total
bigcode/self-oss-instruct-sc2-concepts
def removeOutlier(df_in, col_name): """ This funtion drops all outliers in a pandas dataframe according to the specified column with the IQR method. Input: - df_in: pandas dataframe that the outliers will be removed from. - col_name: name of the column that the IQR will be calculated...
bigcode/self-oss-instruct-sc2-concepts
def static_params_to_dygraph(model, static_tensor_dict): """Simple tool for convert static paramters to dygraph paramters dict. **NOTE** The model must both support static graph and dygraph mode. Args: model (nn.Layer): the model of a neural network. static_tensor_dict (string): path of wh...
bigcode/self-oss-instruct-sc2-concepts
def accept_peaks_size_width(time, data, peak_inx, index, min_inx, threshold, pfac=0.75): """ Accept each detected peak and compute its size and width. Args: time (array): time, must not be None data (array): the data with teh peaks peak_inx: index of the current peak index: ...
bigcode/self-oss-instruct-sc2-concepts
import base64 def extract_salt(salted_ciphertext: bytes): """ Extract salt and ciphertext from salted ciphertext and returns as a tuple """ encoded_salt, ciphertext = salted_ciphertext.split(b':') salt = base64.urlsafe_b64decode(encoded_salt) return salt, ciphertext
bigcode/self-oss-instruct-sc2-concepts
def get_optimizer_variables(optimizer): """Returns a list of variables for the given `tf.compat.v1.train.Optimizer`. Equivalent to `optimizer.variables()`. Args: optimizer: An instance of `tf.compat.v1.train.Optimizer` which has created variables (typically after a call to `Optimizer.minimize`). Re...
bigcode/self-oss-instruct-sc2-concepts
import datetime def datetime_formatter(key, time_format='%Y/%m/%d %H:%M:%S'): """Create a datetime formatting function This factory creates a function that formats a specified key and with a timestamp value from a dictionary into a string. Parameters ---------- key The dictionary ke...
bigcode/self-oss-instruct-sc2-concepts
def scale_array(arr, s): """Scale an array by s Parameters: 1. array: a numeric array or list 2. s: scaling factor, real number """ return [a*s for a in arr]
bigcode/self-oss-instruct-sc2-concepts
def unwrap_model(model): """ Recursively unwraps a model from potential containers (as used in distributed training). Args: model (`torch.nn.Module`): The model to unwrap. """ # since there could be multiple levels of wrapping, unwrap recursively if hasattr(model, "module"): ret...
bigcode/self-oss-instruct-sc2-concepts
def get_header(results): """Extracts the headers, using the first value in the dict as the template.""" ret = ['name', ] values = next(iter(results.values())) for k, v in values.items(): for metric in v.keys(): ret.append('%s:%s' % (k, metric)) return ret
bigcode/self-oss-instruct-sc2-concepts
def unpack_dataset_joint_variables(dataset, n_dof): """ Unpacks a dataset in the format with examples in rows with joint positions, velocities and accelerations in columns (in that order) Returns matrices q, qv, qa; containing rows of examples for joint positions, velocities and acceleratio...
bigcode/self-oss-instruct-sc2-concepts
def spell_stats(user): """ Get's the player/boss' def, name and str. Useful as it's stored differently between bosses and players in a battle Returns ------- Any float - The defence of the user. str - The name of the account. float - The defence of the account """ ...
bigcode/self-oss-instruct-sc2-concepts
def wordlists(*wl): """ Input is arbitrary number of lists of strings. Output is one dictionary where each string is a key and the count of those strings is the value """ word_dict = {} for i in wl: for x in i: if x in word_dict: word_dict[x] += 1 els...
bigcode/self-oss-instruct-sc2-concepts
import torch def softmax(X): """ Entropy-smoothed max, a.k.a. logsumexp. Solves $max_{p \in \Delta^d} <x, p> - \sum_{i=1}^d p_i \log(p_i)$ along dim=2. :param x: torch.Tensor, shape = (b, n, m) Vector to project :return: torch.Tensor, shape = (b, n) Projected vector """ ...
bigcode/self-oss-instruct-sc2-concepts
import torch def matperm2listperm(matperm): """Converts permutation matrix to its enumeration (list) form. Args: matperm: (..., n, n) Returns: listperm: (..., n) - listperm[t,i] is the index of the only non-zero entry in matperm[t, i, :] """ batch_size = matperm.size(0) n = matperm.s...
bigcode/self-oss-instruct-sc2-concepts
def _warp_dir(intuple, nlevels=3): """ Extract the ``restrict_deformation`` argument from metadata. Example ------- >>> _warp_dir(("epi.nii.gz", {"PhaseEncodingDirection": "i-"})) [[1, 0, 0], [1, 0, 0], [1, 0, 0]] >>> _warp_dir(("epi.nii.gz", {"PhaseEncodingDirection": "j-"}), nlevels=2) ...
bigcode/self-oss-instruct-sc2-concepts
def update_position(dir, x, y): """Returns the updated coordinates depending on the direction of the path""" if dir == 'DOWN': return x, y + 1 elif dir == 'UP': return x, y - 1 elif dir == 'LEFT': return x - 1, y elif dir == 'RIGHT': return x + 1, y
bigcode/self-oss-instruct-sc2-concepts
from typing import Callable from typing import Any def lazy_property(function: Callable) -> Any: """Allows to avoid recomputing a property over and over. The result gets stored in a local var. Computation of the property will happen once, on the first call of the property. All succeeding calls will u...
bigcode/self-oss-instruct-sc2-concepts
def region_mapping(region): """Map the user supplied region to the hostname for the AMP for Endpoints console """ region_map = { "apjc": "console.apjc.amp.cisco.com", "eu": "console.eu.amp.cisco.com", "nam": "console.amp.cisco.com", } return region_map[region.lower()]
bigcode/self-oss-instruct-sc2-concepts
import torch def get_accuracy(outputs, labels): """From Binary cross entropy outputs to accuracy""" mask = outputs >= 0.5 accuracy = 1. - torch.mean(torch.abs(mask.float() - labels)).item() return accuracy
bigcode/self-oss-instruct-sc2-concepts
from typing import Tuple def get_choosen_building( building: Tuple[str, str], choice: str ) -> str: """ Get the specific building that have been selected by the user. Parameters ---------- building: Tuple[str, str] A tuple containing 2 randomly selected buildin...
bigcode/self-oss-instruct-sc2-concepts
def unique_list(input_, key=lambda x:x): """Return the unique elements from the input, in order.""" seen = set() output = [] for x in input_: keyx = key(x) if keyx not in seen: seen.add(keyx) output.append(x) return output
bigcode/self-oss-instruct-sc2-concepts
def pos_neg_split(df): """ Splits DataFrame into two separate positive and negative DataFrames for the creation of two separate models for LDAvis. INPUT: Sentiment-analyzed DataFrame OUTPUT: A positive DataFrame and negative DataFrame """ neg = df[df['Analysis'] == 'Negative'] pos ...
bigcode/self-oss-instruct-sc2-concepts
def collapse_complexes(data, conjugate_flag=False): """Given a list or other iterable that's a series of (real, imaginary) pairs, returns a list of complex numbers. For instance, given this list -- [a, b, c, d, e, f] this function returns -- [complex(a, b), complex(c, d), complex(e, f)] T...
bigcode/self-oss-instruct-sc2-concepts
def _code_in_list(code, codelist): """Tells if `code` is contained in `codelist` Examples: - 401 is not contained in ['3xx', '404', '5xx'] - 404 is contained in ['3xx', '404', '5xx'] - 503 is contained in ['3xx', '404', '5xx'] """ # status codes to exclude exact_codes = [co...
bigcode/self-oss-instruct-sc2-concepts
def reflect_y(x, y, matrix): """Reflect the index horizontally.""" return x, matrix.rows - 1 - y
bigcode/self-oss-instruct-sc2-concepts
async def _pinned(db, community): """Get a list of pinned post `id`s in `community`.""" sql = """SELECT id FROM hive_posts WHERE is_pinned = '1' AND is_deleted = '0' AND community = :community ORDER BY id DESC""" return await db.query_col(sql, commun...
bigcode/self-oss-instruct-sc2-concepts
from typing import List from typing import Dict def get_user_inputs(title: str, captions: List[str], retvals_size: int = 1024) -> Dict[str, str]: """Show text inputs to user and get values from them. Parameters ---------- title : str Popup title. ca...
bigcode/self-oss-instruct-sc2-concepts
def parse_yaml_beam_args(pipeline_args): """Converts yaml beam args to list of args TFX accepts Args: pipeline_args: dict specified in the config.yml Returns: list of strings, where each string is a beam argument """ return ['--{}={}'.format(key, value) for key, value in ...
bigcode/self-oss-instruct-sc2-concepts
def are_you_sure(question: str): """ Loop while asking a Y/N question. Adds str(" (Y/N): ") to the end of the provided question. """ while True: answer = str(input(question + " (Y/N): ")).lower() if answer.startswith("y"): result = True break el...
bigcode/self-oss-instruct-sc2-concepts
def first_string(group): """Return the first value in the group.""" for item in group: if item: return item return ''
bigcode/self-oss-instruct-sc2-concepts
def tensor_to_op_name(tensor_name): """Strips tailing ':N' part from a tensor name. For example, 'dense/kernel:0', which is a tensor name, is converted to 'dense/kernel' which is the operation that outputs this tensor. Args: tensor_name: tensor name. Returns: Corresponding op name. """ parts = ...
bigcode/self-oss-instruct-sc2-concepts
def remove(list_, item): """Removes an item from a list.""" return [i for i in list_ if i != item]
bigcode/self-oss-instruct-sc2-concepts
def _buildSpectrumFromQIisotopes(mz, isotopeDistribution, delta=1.0033550000000009): """ Build a mass spectrum from a QI mz value, and isotopic distribution pattern. :param float mz: m/z of the lightest isotope :param str isotopeDistribution: Hyphenated list of isotopic abundances ordered by 1Da intervals :param ...
bigcode/self-oss-instruct-sc2-concepts
def generate_path(start, ref, nonref, stop): """ Given source, sink, and ref/non-ref nodes enumerate all possible paths """ ref_path = [x for x in [start, ref, stop] if x != "0"] nonref_path = [x for x in [start, nonref, stop] if x != "0"] return [ref_path, nonref_path]
bigcode/self-oss-instruct-sc2-concepts
def grid_from_data(da): """Given a dataset, extract only the grid information. Parameters ---------- da : xarray.DataArray DataArray to extract grid information from. Must have "ocw" conventions, ie 2D lats and lons variables. Returns ------- ds : xarray.Dataset Dat...
bigcode/self-oss-instruct-sc2-concepts
import torch def interpolate_irreg_grid(interpfunc, pos): """Interpolate the funtion Args: interpfunc (callable): function to interpolate the data points pos (torch.tensor): positions of the walkers Nbatch x 3*Nelec Returns: torch.tensor: interpolated values of the function eval...
bigcode/self-oss-instruct-sc2-concepts
def get_cv(m1: float, m2: float) -> float: """Compute coefficient of variation. """ return (m2 - m1**2)**0.5 / m1
bigcode/self-oss-instruct-sc2-concepts