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-1) return derivative
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_seen = set() base_hit = 0 if is_gtf: r.sID, r.segments = r.chr, r.ref_exons if r.sID not in tree: return 0, 0, set() for e in r.segments: hits = tree[r.sID].find(e.start, e.end) if len(hits) == 0: continue for i,strand,intl in hits: if (strand is None) or (strand==r.strand): probes_seen.add(i) genes_seen.add(gene_info[i]) base_hit += min(e.end,intl.end)-max(e.start,intl.start) return len(probes_seen), base_hit, genes_seen
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 IndexError("Satellite not in dataset, must be one of: " "{}".format(self.ds['satellite'].values)) return func(self, satellite, *args, **kwargs) return wrapper
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 in lines: line = line.strip() if len(line) > 0: n1 += 1 return (n0, n1)
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("錯誤型態") else: return str_1 + str_2
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 Formats 2-4 are all converted into a date object internally. """ if isinstance(indate, dt.datetime): return indate.date() elif isinstance(indate, dt.date): return indate elif isinstance(indate, str): skey = indate.strip() l = len(skey) if l==8: # assume YYYYMMDD dkey = dt.datetime.strptime(skey,"%Y%m%d") return dkey.date() elif l==7: # assume YYYYDDD dkey = dt.datetime.strptime(skey,"%Y%j") return dkey.date() else: msg = "Input value not recognized as date: %s" raise KeyError(msg % indate) else: msg = "Input value not recognized as date: %s" raise KeyError(msg % indate)
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 """ return sorted(values)[int(p * len(values))]
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: return pos + start
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] return seq
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 evaluate integrals by the Gaussian quadrature. lambdafunc: function or None Either supply a function, or leave None if the model of the generated data is not known, in which case x and w are ignored. Returns ------- peq : numpy array (N,), dtype=float Probability density distribution evaluated at grid ponits x. """ if lambdafunc is not None: peq=lambdafunc(x) peq /= sum(w*peq) else: peq=None return peq
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 reference_image :return: image cropped to the size of the reference image """ reference_size = reference_image.size current_size = image_to_crop.size dx = current_size[0] - reference_size[0] dy = current_size[1] - reference_size[1] left = dx / 2 upper = dy / 2 right = dx / 2 + reference_size[0] lower = dy / 2 + reference_size[1] return image_to_crop.crop( box=( int(left), int(upper), int(right), int(lower)))
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 else 3 checksum += weight * numeral return (checksum % 10) == 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 associated physiology file")
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.defaultdict(list) line_idx = 0 for line in fp.readlines(): stripped_line = line.strip() split_items = stripped_line.split() try: gid = int(split_items[0].strip()) time = float(split_items[1].strip()) except: print("Could not parse a line in the file!!!! \n") print(" line: " , line_idx, ": ", stripped_line) print(path) exit(1) #failure line_data = (line_idx, time, stripped_line) parsed_data[gid].append(line_data) line_idx += 1 return parsed_data
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.name] = { 'value': ca_spec.default_value } return customization_args
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 between the webs (l/r)e = math.sqrt(1.105*math.pi/sxx*sqrt(sum(s/t))/ a*math.sqrt(i_yy/(1+mu))) fa_bc = 0.55*fy - 0.55*math.pow(fy,2)/(6.3*math.pow(math.pi,2)*e)* math.pow((l/r)e,2) Args: l (float): distance between points of lateral support for the compression flange, unbraced length [inches] sx (float): section modulus of the box type member about its major axis [inches^3] a (float): total area enclosed within the center lines of the box type member webs and flanges [inches^2] sum_st (float): sum of the ratio width-to-thickness of each flange and ratio of the depth to thickness of each web (neglect any portion of the flange which projects beyond the box section) iy (float): second moment of area of the box type member about its minor axis, [inches^4] Returns: fa_bc (float): allowable compression stress in extreme fibers of box type flexure members Notes: 1. Units in lbs and inches. 2. Poisson's ratio, mu, is taken as 0.3. """ ref_text = "AREMA 2018 Section 1.4.1 Table 15-1-11 Row 10 \n\n" user_input = (f'l = {l:.2f}, Sx = {sx:.2f}, a = {a:.2f}, ' + f'sum_st = {sum_st:.2f}, Iy = {iy:.2f}, Fy = {fy:.1f}, ' + f'E = {e:.1f} \n\n') mu = 0.3 lre = math.sqrt((1.105*math.pi/sx*math.sqrt(sum_st))/ (a*math.sqrt(iy/(1+mu)))) fa_bc = (0.55*fy-0.55*math.pow(fy,2)/ (6.3*math.pow(math.pi,2)*e)*math.pow(lre,2)) text1 = (f'(l/r)e = math.sqrt((1.105*math.pi/sx*math.sqrt(sum_st))/' + f'(a*math.sqrt(iy/(1+mu)))) \n' + f'(l/r)e = math.sqrt((1.105*math.pi/{sx:.2f}*math.sqrt({sum_st:.2f}))/' + f'({a:.2f}*math.sqrt({iy:.2f}/(1+{mu:.2f})))) \n' + f'(l/r)e = {lre:.2f} \n') text2 = (f'fa_bc = (0.55*fy-0.55*math.pow(fy,2)/' + f'(6.3*math.pow(math.pi,2)*e)*math.pow(lre,2)) \n' + f'fa_bc = (0.55*{fy:.1f}-0.55*math.pow({fy:.1f},2)/' + f'(6.3*math.pow(math.pi,2)*{e:.1f})*math.pow({lre:.2f},2)) \n' + f'fa_bc = {fa_bc:.1f}') text = ref_text + user_input + text1 + text2 return fa_bc, text
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: :return: """ if password == "": return False for char in password: if char.isalpha() or char.isdigit(): continue return False return True
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 < 0) return (a > 0 and b < 0) or (a < 0 and b > 0)
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 isinstance( s, str ): raise ValueError( "Wrong input type. args should be type dict and s should be type str. {0:} and {1:} are rather given".format( type( args ), type( str ) ) ) for old_key in list( args ) : new_key = old_key.replace( s, '' ) args[ new_key ] = args.pop( old_key ) return args
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: # split into key/value pairs and store k, v = line.split(":") result[k] = v return result
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 the set of states in the model Returns ---------- list all of the transitions possible as pairs (two-element lists) """ lst = [] for i in range(0, len(states)): for j in range(i+1, len(states)): lst.append([i, j]) return lst
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, auth=(cfg['user'], cfg['password'])) x = r.json() return x['title']
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 sample_width == 2 sample_rate = wf.getframerate() n_frames = wf.getnframes() data = wf.readframes(n_frames) converted = audioop.ratecv(data, sample_width, num_channels, sample_rate, 32000, None) return converted[0], 32000
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计算收益 all_profit += (now_price - order.buy_price) * order.buy_cnt * order.expect_direction else: # 单子如卖出,使用sell_price计算收益 all_profit += (order.sell_price - order.buy_price) * order.buy_cnt * order.expect_direction return all_profit
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: rem = decimal % 8 oct += rem * pow(10 , c) c+=1 decimal //= 8 return f'{is_negative}0o{oct}'
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_attribs: if attr in original: target[attr] = original[attr] return target
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 = [network.network_dict[node] for node in network.nodes()] for node in nodes: adjacents = node.get_adjacents() for adjacent in adjacents: edge = (node.node_id, adjacent) alternate = (adjacent, node.node_id) if edge not in edge_list and alternate not in edge_list: edge_list.append(edge) return edge_list
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 RETURNS ------- The reverse-complement of the DNA_string. """ Nucleotides={"A": "T", "T": "A", "G": "C", "C": "G", "N": "N"} return "".join(Nucleotides[DNA_string[i]] for i in range(len(DNA_string)-1,-1,-1))
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 beam_num_ptcl: number of e- in the drive beam Returns: rb_max: maximum radius of the plasma bubble """ # from Eq. (12) of LBN2017 rb_max = pow(2,7/8.)*pow(beam_num_ptcl/math.pi/n_pe,3/8.)/pow(beam_tot_z,1/8.) return rb_max
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 """ assert isinstance(profileDict, dict) and "samples" in profileDict return profileDict["samples"]["window_start_offsets"]
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[:, :, 1].argmax()][0]) return extreme_left, extreme_right, extreme_top, extreme_bottom
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. return input return output
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; 32-bit rotate right one bit.""" csum += uint # add uint csum &= 0xffffffff # truncate rbit = csum & 0x1 # rotate part 1 (save low-order bit) csum >>= 1 # rotate part 2 (shift right) csum += rbit << 31 # rotate part 3 (prepend old low-order bit) return csum # Loop over all two-byte words in the data and include them in the checksum. checksum = 0 for word_bytes in [data[i:i+2] for i in range(0, len(data), 2)]: word = struct.unpack('>H', word_bytes)[0] # big endian word bytes to native checksum = addl_rorl(word, checksum) # add to checksum # return result as a big-endian 32-bit word. return struct.pack('>I', checksum)
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() i = 0 for j, t in enumerate(text): if begin <= i < end or begin <= i+len(t) < end: overlap[j] = True i += len(t) + 1 return overlap
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-thumb__image"}).find("a", {"class": "lazy"}) return anchor_element.get("data-original")
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']) return img_arr[y_min:y_max, x_min:x_max]
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 case_group.group_id == group_id: return case_group return None
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 accumulated nodata : float, integer nodata value Returns ------- 1D array of data.dtype accumulated upstream data """ # intialize output with correct dtype accu = data.copy() for idx0 in seq[::-1]: # up- to downstream idx_ds = idxs_ds[idx0] if idx0 != idx_ds and accu[idx_ds] != nodata and accu[idx0] != nodata: accu[idx_ds] += accu[idx0] return accu
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.topics.values()))
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 num of ways with coin n included & excluded. T[n][amount] = (_change_memo(amount - coins[n - 1], coins, T, n) + _change_memo(amount, coins, T, n - 1)) return T[n][amount]
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 ---------- text : str Cleaned text. Examples ---------- >>> text = 'I am a \nbad\r\n\tstr-\ning.' >>> print(text) I am a bad str- ing. >>> text = clean_str(text) >>> print(text) I am a bad string. """ # Remove unicode characters. text = text.decode('utf-8') text = re.sub(r'[^\x00-\x7F]+', ' ', text) # Combine multiline hyphenated words. text = re.sub('-[\s]*[\r\n\t]+', '', text, flags=re.MULTILINE) # Remove newlines and extra spaces. text = re.sub('[\r\n\t]+', ' ', text, flags=re.MULTILINE) text = re.sub('[\s]+', ' ', text, flags=re.MULTILINE) return text
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 on. """ q1 = df_in[col_name].quantile(0.25) q3 = df_in[col_name].quantile(0.75) iqr = q3-q1 #Interquartile range fence_low = q1-1.5*iqr fence_high = q3+1.5*iqr df_out = df_in.loc[(df_in[col_name] > fence_low) & (df_in[col_name] < fence_high)] return df_out
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 which locate the saved paramters in static mode. Usualy load by `paddle.static.load_program_state`. Returns: [tensor dict]: a state dict the same as the dygraph mode. """ state_dict = model.state_dict() # static_tensor_dict = paddle.static.load_program_state(static_params_path) ret_dict = dict() for n, p in state_dict.items(): ret_dict[n] = static_tensor_dict[p.name] return ret_dict
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: current index min_inx: index of the previous trough threshold: threshold value pfac: fraction of peak height where its width is measured Returns: time (float): time of the peak height (float): height of the peak (value of data at the peak) size (float): size of the peak (peak minus previous trough) width (float): width of the peak at 0.75*size count (float): zero """ size = data[peak_inx] - data[min_inx] wthresh = data[min_inx] + pfac * size width = 0.0 for k in range(peak_inx, min_inx, -1): if data[k] < wthresh: width = time[peak_inx] - time[k] break for k in range(peak_inx, index): if data[k] < wthresh: width += time[k] - time[peak_inx] break return [time[peak_inx], data[peak_inx], size, width, 0.0], None
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`). Returns: A list of variables which have been created by the `Optimizer`. """ return optimizer.variables()
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 key to format. The corresponding value should be a timestamp. time_format A format string suitable for strftime(). Returns ------- format A factory function that takes a dictionary and returns a string. """ def format(**kwargs): dt = datetime.datetime.fromtimestamp(kwargs[key]) return key + ': ' + dt.strftime(time_format) return format
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"): return unwrap_model(model.module) else: return model
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 accelerations """ q = dataset[:, 0:n_dof] # joint positions qv = dataset[:, n_dof:n_dof * 2] # joint velocities qa = dataset[:, n_dof * 2:] # joint accelerations return q, qv, qa
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 """ # Get user stats for player/boss (as the data is stored differently) try: # Player u_def = user['account']['stats']['defense'] u_name = user['user'].name u_str = user['account']['stats']['strength'] except KeyError: # Boss u_def = user['stats']['defense'] u_name = user['name'] u_str = user['stats']['strength'] return u_def, u_name, u_str
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 else: word_dict[x] = 1 return word_dict
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 """ M, _ = torch.max(X, dim=2) X = X - M[:, :, None] S = torch.sum(torch.exp(X), dim=2) M = M + torch.log(S) return M
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.size(-1) assert matperm.size(-2) == matperm.size(-1) #argmax is the index location of each maximum value found(argmax) # _, argmax = torch.max(matperm, dim=-1, keepdim=False) argmax = torch.argmax(matperm, dim=-1, keepdim=False) # argmax = argmax.view(batch_size, n_objects) return argmax
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) [[0, 1, 0], [0, 1, 0]] """ pe = intuple[1]["PhaseEncodingDirection"][0] return nlevels * [[int(pe == ax) for ax in "ijk"]]
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 use the value stored in the private property.""" attr_name = "_lazy_" + function.__name__ @property # type: ignore def _lazyprop(self): if not hasattr(self, attr_name): setattr(self, attr_name, function(self)) return getattr(self, attr_name) return _lazyprop
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 building. choice: str The valid choice given by the user. Returns ------- building: str The specific building that selected by the user. """ x, y = building return x if '1' == choice else y
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 = df[df['Analysis'] == 'Positive'] return neg, 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)] The returned list is a new list; the original is unchanged. """ # This code was chosen for speed and efficiency. It creates an iterator # over the original list which gets called by izip. (izip() is the same # as the builtin zip() except that it returns elements one by one instead # of creating the whole list in memory.) # It's the fastest method of the 5 or 6 I tried, and I think it is also # very memory-efficient. # I stole it from here: # http://stackoverflow.com/questions/4628290/pairs-from-single-list data_iter = iter(data) if not conjugate_flag: tmp = [complex(r, i) for r, i in zip(data_iter, data_iter)] else: tmp = [complex(r, -1*i) for r, i in zip(data_iter, data_iter)] return tmp
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 = [code for code in codelist if 'x' not in code] if str(code) in exact_codes: return True # classes of status code to exclude class_codes = [code[0] for code in codelist if 'x' in code] if str(code)[0] in class_codes: return True return False
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, community=community)
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. captions : List[str] Names of input fields. retvals_size : int, optional Maximum number of characters that will be retrieved for each field. User may enter more, but only the first `retvals_size` will be returned. (default=1024) Returns ------- Dict[str,str] Dictionary of pairs {caption: response}. Raises ------ RuntimeError When user clicked the Cancel button. """ success, _, _, _, retvals_csv, _ = RPR.GetUserInputs( # type:ignore title, len(captions), ",".join(captions), "", retvals_size) if success: return dict(zip(captions, retvals_csv.split(","))) else: raise RuntimeError('User clicked Cancel.')
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 pipeline_args.items()]
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 elif answer.startswith("n"): result = False break else: pass return result
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 = tensor_name.split(':') if len(parts) == 1: return tensor_name assert len(parts) == 2 return parts[0]
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 float delta: Isotopic mass difference, defaults to :sup:`13`\ C (1.0033550000000009) :returns: Reconstructed mass spectrum as a list of (mass, float) tuples :rtype: list[(float, float),] """ spectrum = list() count = 0 if '-' in isotopeDistribution: for isotope in isotopeDistribution.split(' - '): spectrum.append((mz + (delta * count), float(isotope))) count += 1 else: # No isotopes spectrum.append((mz, 100)) return spectrum
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 Dataset containing grid infromation. """ ds = da.coords.to_dataset() return ds
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 evaluated at pos """ nbatch, nelec, ndim = pos.shape[0], pos.shape[1]//3, 3 return torch.as_tensor(interpfunc(pos.reshape(nbatch, nelec, ndim)))
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