content
stringlengths
39
9.28k
sha1
stringlengths
40
40
id
int64
8
710k
def uniquify(seq, preserve_order=False): """Return sequence with duplicate items in sequence seq removed. The code is based on usenet post by Tim Peters. This code is O(N) if the sequence items are hashable, O(N**2) if not. Peter Bengtsson has a blog post with an empirical comparison of other approaches: http://www.peterbe.com/plog/uniqifiers-benchmark If order is not important and the sequence items are hashable then list(set(seq)) is readable and efficient. If order is important and the sequence items are hashable generator expressions can be used (in py >= 2.4) (useful for large sequences): seen = set() do_something(x for x in seq if x not in seen or seen.add(x)) Arguments: seq -- sequence preserve_order -- if not set the order will be arbitrary Using this option will incur a speed penalty. (default: False) Example showing order preservation: >>> uniquify(['a', 'aa', 'b', 'b', 'ccc', 'ccc', 'd'], preserve_order=True) ['a', 'aa', 'b', 'ccc', 'd'] Example using a sequence of un-hashable items: >>> uniquify([['z'], ['x'], ['y'], ['z']], preserve_order=True) [['z'], ['x'], ['y']] The sorted output or the non-order-preserving approach should equal that of the sorted order-preserving approach output: >>> unordered = uniquify([3, 3, 1, 2], preserve_order=False) >>> unordered.sort() >>> ordered = uniquify([3, 3, 1, 2], preserve_order=True) >>> ordered.sort() >>> ordered [1, 2, 3] >>> int(ordered == unordered) 1 """ try: # Attempt fast algorithm. d = {} if preserve_order: # This is based on Dave Kirby's method (f8) noted in the post: # http://www.peterbe.com/plog/uniqifiers-benchmark return [x for x in seq if (x not in d) and not d.__setitem__(x, 0)] else: for x in seq: d[x] = 0 return d.keys() except TypeError: # Have an unhashable object, so use slow algorithm. result = [] app = result.append for x in seq: if x not in result: app(x) return result
25502efa0931ed161f708ef5056df8e09cb45a39
481,091
def variable_match(series_1, series_2): """ Returns a binary series representing the equality of pairwise elements in two series :param series_1: pd.Series :param series_2: pd.Series :return: pd.Series """ return (series_1 == series_2) * 1
7c2b272513b6512e398060eb4aa4fef448a7e835
260,633
import textwrap def _wrap_docstring(doc): """Helper function to wrap a docstring at 72 characters while maintaining line breaks. """ return "\n".join( ["\n".join(textwrap.wrap(l, subsequent_indent=" ")) for l in doc.split('\n') if l])
3993687d579c532bf5db859213fabeca462591b0
319,216
import calendar def get_month_week_number(day): """ Given a datetime object (day), return the number of week the day is in the current month (week 1, 2, 3, etc) """ weeks = calendar.monthcalendar(day.year, day.month) for week in weeks: if day.day in week: return weeks.index(week)
964499d69f003e5a8c28758b18239307312e5f55
535,523
def quiesce(board, alpha, beta, evaluate): """Search for all moves that would lead to a capture of own piece. A 'quiet' move is one that ends without a chance of capture. Standing pat: In order to allow the quiescence search to stabilize, we need to be able to stop searching without necessarily searching all available captures. In addition, we need a score to return in case there are no captures available to be played. This is done by a using the static evaluation as a "stand-pat" score (the term is taken from the game of poker, where it denotes playing one's hand without drawing more cards). At the beginning of quiescence, the position's evaluation is used to establish a lower bound on the score. This is theoretically sound because we can usually assume that there is at least one move that can either match or beat the lower bound. If the lower bound from the stand pat score is already greater than or equal to beta, we can return the stand pat score (fail-soft) or beta (fail-hard) as a lower bound. Otherwise, the search continues, keeping the evaluated "stand-pat" score as an lower bound if it exceeds alpha, to see if any tactical moves can increase alpha. """ # Get lower bound (standing pat) score stand_pat = evaluate(board) # Check if standing pat score is better than beta. # If so, assume other player would not follow this route if stand_pat >= beta: return beta # Update alpha if standing pat score is better if alpha < stand_pat: alpha = stand_pat # Iterate through legal moves (from the opposing player) for move in board.legal_moves: # Check if moves leads to capture if board.is_capture(move): # Keep iterating until a quiet move is found board.push(move) score = -quiesce(board, -beta, -alpha, evaluate) # Restore the previous position. board.pop() # Cehck if score > beta. If so, oppenent wil not go down this route if score >= beta: return beta # Update alpha if score is best explored option on this path if score > alpha: alpha = score # Return alpha, the best score in this path return alpha
a6dacde30de149d1aff63c01f32db296ffa14c91
129,938
def unzip(l): """Unpacks a list of tuples pairwise to a lists of lists: [('a', 1), ('b', 2)] becomes [['a', 'b'], [1, 2]]""" return zip(*l)
b1dec3ba48d37bef05e56542b5ff6cf2fb267269
444,698
def dict_item_to_string(key, value): """ inputs: key-value pairs from a dictionary output: string 'key=value' or 'key=value1,value2' (if value is a list) examples: 'fmt', 'csv' => 'fmt=csv' or 'r', [124, 484] => 'r=124,484' """ value_string = str(value) if not isinstance(value, list) else ','.join(map(str, value)) return '='.join([key, value_string])
1ad44fd06216feea1ddff4f2b208f605f0f60cff
195,111
def token_is_a(token1, token2): """Returns true if token1 is the same type as or a child type of token2""" if token1 == token2: return True parent = token1.parent while(parent != None): if parent == token2: return True parent = parent.parent return False
8e5e2d1ebdaa7ede4a10d314c8285fea73952726
124,307
import re def scrub_words(text): """Basic cleaning of texts.""" """Taken from https://github.com/kavgan/nlp-in-practice/blob/master/text-pre-processing/Text%20Preprocessing%20Examples.ipynb """ # remove html markup text=re.sub("(<.*?>)","",text) #remove non-ascii and digits text=re.sub("(\\W|\\d)"," ",text) # remove the extra spaces that we have so that it is easier for our split :) Taken from https://stackoverflow.com/questions/2077897/substitute-multiple-whitespace-with-single-whitespace-in-python text=re.sub(' +', ' ', text).strip() return text
ed7224d56b02e10fc683a742f1c1313b2b243c26
65,911
import click from pathlib import Path def _ensure_relative_path(node_subdir: str) -> str: """Checks that the subdir path does not contain parent directory navigator (..), is not absolute, and is not "peekingduck/pipeline/nodes". """ pkd_node_subdir = "peekingduck/pipeline/nodes" if ".." in node_subdir: raise click.exceptions.UsageError("Path cannot contain '..'!") if Path(node_subdir).is_absolute(): raise click.exceptions.UsageError("Path cannot be absolute!") if node_subdir == pkd_node_subdir: raise click.exceptions.UsageError(f"Path cannot be '{pkd_node_subdir}'!") return node_subdir
3de71977a9e0aafd76365a7a305561c7e0b53e63
319,213
def _javaMapToDict(m): """ Converts a java map to a python dictionary. :param m: java map. :return: python dictionary. """ result = {} for e in m.entrySet().toArray(): k = e.getKey() v = e.getValue() result[k] = v return result
4ad45f37b8767bc5fab7b7547f42e47e374e86ba
163,082
def pair(x, y): """Return a function that represents a pair.""" def get(index): if index == 0: return x elif index == 1: return y return get
dddb156489b2fff860471f74fd7829752a31bee5
131,573
def _update_other_results(results, best): """Update the positions and provisional input_sets of ``results`` based on performing the contraction result ``best``. Remove any involving the tensors contracted. Parameters ---------- results : List of contraction results produced by ``_parse_possible_contraction``. best : The best contraction of ``results`` i.e. the one that will be performed. Returns ------- mod_results : The list of modifed results, updated with outcome of ``best`` contraction. """ best_con = best[1] bx, by = best_con mod_results = [] for cost, (x, y), con_sets in results: # Ignore results involving tensors just contracted if x in best_con or y in best_con: continue # Update the input_sets del con_sets[by - int(by > x) - int(by > y)] del con_sets[bx - int(bx > x) - int(bx > y)] con_sets.insert(-1, best[2][-1]) # Update the position indices mod_con = x - int(x > bx) - int(x > by), y - int(y > bx) - int(y > by) mod_results.append((cost, mod_con, con_sets)) return mod_results
d6beeae8734d886e817668abb51b776333ebf2d2
587,852
import yaml def read_vibdata(vib_file): """Reads a yaml file containing the vribational frequencies from a DFT calculation. Parameters ---------- vib_file : (:py:attr:`str`): File name Returns ------- vib_prop : :py:attr:`dict` Dictionary of vibrational freqencies. """ with open(vib_file, 'r') as file: vib_prop = yaml.load(file, Loader=yaml.FullLoader) return vib_prop
31006173c40b9ad5edc27688aaad330bc7335bb9
578,156
def get_property_content(content, prefix): """Add the prefix to each object in the content and return the concatenated string with "," as the separator. Args: content: the list containing property objects prefix: the prefix before dcid, such as "dcs:" Returns: objects separated by comma. For example: "dcs:bio/CWH41_YEAST,dcs:bio/RPN3_YEAST" """ if not content: return None item_list = [] for obj in content: item_list.append(prefix + obj) return ','.join(item_list)
385955f38efdf35519e34fee0334d778335b5681
517,178
def generate_frequency_dict(data): """Generate a dictionary of all symbols (keys) with their number of appearances (values) from data. """ dict_appearances = {} for crrt_char in data: if crrt_char in dict_appearances: dict_appearances[crrt_char] += 1 else: dict_appearances[crrt_char] = 1 return dict_appearances
4ad0bea5b1251f138d240e8db2a805f60c384a61
435,844
def wt_lb_kg(wt): """Converts height from centimeter to squared meter Parameters ---------- wt: double weight in pound Returns ------- double weight in kilogram. Examples -------- >>> wt_lb_kg(200) 90.8 """ return wt * 0.454
a6173dbcfe0361a06b10b00fb3b405e31daca325
392,585
def getFeatureId(feature): """ Return the ID of a feature params: feature -> a feature """ return feature["id"]
8bdccc4166c67d9076f702d03414cb4f3e4e8a48
653,980
from datetime import datetime def get_tm1_time_value_now(use_excel_serial_date: bool = False) -> float: """ This function can be used to replicate TM1's NOW function to return current date/time value in serial number format. :param use_excel_serial_date: Boolean :return: serial number """ # timestamp according to tm1 start_datetime = datetime(1899, 12, 30) if use_excel_serial_date else datetime(1960, 1, 1) current_datetime = datetime.now() delta = current_datetime - start_datetime return delta.days + (delta.seconds / 86400)
fc3154fafe991b517e3464ea783ad6b985ad06de
111,182
def inverty(x, y, **kwargs): """Multiply y by -1""" return x, -y
0feaa5e6dab3a9225ced398a03b6a65b05e769fc
427,247
def align_position2doc_spans(positions, doc_spans_indices, offset=0, default_value=-1, all_in_span=True): """Align original positions to the corresponding document span positions Parameters ---------- positions: list or int A single or a list of positions to be aligned dic_spans_indices: list or tuple (start_position, end_position) offset: int Offset of aligned positions. Sometimes the doc spans would be added after a question text, in this case, the new position should add len(question_text) default_value: int The default value to return if the positions are not in the doc span. all_in_span: bool If set to True, then as long as one position is out of span, all positions would be set to default_value. Returns ------- list: a list of aligned positions """ if not isinstance(positions, list): positions = [positions] doc_start, doc_end = doc_spans_indices if all_in_span and not all([p in range(doc_start, doc_end) for p in positions]): return [default_value] * len(positions) new_positions = [ p - doc_start + offset if p in range(doc_start, doc_end) else default_value for p in positions ] return new_positions
5c4b5755f59e72ddb579b83932ab341e8a9c62d0
467,072
def request_cert(session, domain_name, validation_domain): """Requests a certificate in the AWS Certificate Manager for the domain name Args: session (Session|None) : Boto3 session used to communicate with AWS CertManager If session is None no action is performed domain_name (string) : domain name the certificate is being requested for validation_domain (string) : domain suffix that request validation email will be sent to. Returns: (dict|None) : Dictionary with the "CertificateArn" key containing the new certificate's ARN or None if the session is None """ if session is None: return None client = session.client('acm') validation_options = [ { 'DomainName': domain_name, 'ValidationDomain': validation_domain }, ] response = client.request_certificate(DomainName=domain_name, DomainValidationOptions=validation_options) return response
8a6c5a0eff185d545edfe4a9aba9e4f93f0749ae
159,518
from typing import Iterable def get_components_of_message(data: str) -> Iterable[str]: """Returns the three components (origin, destination, message) of a data packet.""" data_list = data.split(',') origin, destination, message = data_list return origin, destination, message
cc01d0107ef456d8c7d8a9dd0e7c5068e189d665
98,762
def to_upper(string: str) -> str: """ Converts :string: to upper case. Intended to be used as argument converter. Returns ------- :class:`str` String to upper case """ return string.upper()
4decf6692745e9df10666756698e7a443df218f6
506,736
def filter_none(data, split_by_client=False): """This function filters out ``None`` values from the given list (or list of lists, when ``split_by_client`` is enabled).""" if split_by_client: # filter out missing files and empty clients existing_data = [ [d for d in client_data if d is not None] for client_data in data ] existing_data = [client_data for client_data in existing_data if client_data] else: # filter out missing files existing_data = [d for d in data if d is not None] return existing_data
7cc88ecdf7aba245f56598ee1094fed7c1f9f4f7
11,746
import errno def read_no_interrupt(p): """Read from a pipe ignoring EINTR errors. This is necessary because when reading from pipes with GUI event loops running in the background, often interrupts are raised that stop the command from completing.""" try: return p.read() except IOError as err: if err.errno != errno.EINTR: raise
0fed5b7655c73e1611915157a62ce7fbd2d5b379
563,459
import ipaddress def get_prefix_protocol(prefix): """ Takes a network address space prefix string and returns a string describing the protocol Will raise a ValueError if it cannot determine protocol Returns: str: IPv4 or IPv6 """ try: ipaddress.IPv4Network(prefix) return "IPv4" except ipaddress.AddressValueError: try: ipaddress.IPv6Network(prefix) return "IPv6" except ipaddress.AddressValueError: raise ValueError("Prefix invalid")
2aa24198eee51c966388c4e0de3416a4638027f7
124,668
import torch from typing import Sequence def crop(data: torch.Tensor, corner: Sequence[int], size: Sequence[int]) -> torch.Tensor: """ Extract crop from last dimensions of data Args: data: input tensor corner: top left corner point size: size of patch Returns: torch.Tensor: cropped data """ _slices = [] if len(corner) < data.ndim: for i in range(data.ndim - len(corner)): _slices.append(slice(0, data.shape[i])) _slices = _slices + [slice(c, c + s) for c, s in zip(corner, size)] return data[_slices]
2f596db499e3b1d59475477e71a95e8a170242da
23,838
def _dataset_ids_equal(dataset_id1, dataset_id2): """Compares two dataset IDs for fuzzy equality. Each may be prefixed or unprefixed (but not null, since dataset ID is required on a key). The only allowed prefixes are 's~' and 'e~'. Two identical prefixed match >>> 's~foo' == 's~foo' >>> 'e~bar' == 'e~bar' while non-identical prefixed don't >>> 's~foo' != 's~bar' >>> 's~foo' != 'e~foo' As for non-prefixed, they can match other non-prefixed or prefixed: >>> 'foo' == 'foo' >>> 'foo' == 's~foo' >>> 'foo' == 'e~foo' >>> 'foo' != 'bar' >>> 'foo' != 's~bar' (Ties are resolved since 'foo' can only be an alias for one of s~foo or e~foo in the backend.) :type dataset_id1: string :param dataset_id1: A dataset ID. :type dataset_id2: string :param dataset_id2: A dataset ID. :rtype: bool :returns: Boolean indicating if the IDs are the same. """ if dataset_id1 == dataset_id2: return True if dataset_id1.startswith('s~') or dataset_id1.startswith('e~'): # If `dataset_id1` is prefixed and not matching, then the only way # they can match is if `dataset_id2` is unprefixed. return dataset_id1[2:] == dataset_id2 elif dataset_id2.startswith('s~') or dataset_id2.startswith('e~'): # Here we know `dataset_id1` is unprefixed and `dataset_id2` # is prefixed. return dataset_id1 == dataset_id2[2:] return False
a8eec519af5159041f5b81943f4ef0e478170507
268,714
def pie_pct_format(value): """ Determine the appropriate format string for the pie chart percentage label Args: value: value of the pie slice Returns: str: formated string label; if the slice is too small to fit, returns an empty string for label """ return '' if value < 7 else '%.0f%%' % value
ac5e7f15fb12b383cfe99e3579dff9d1e2b84843
599,801
def get_name(model, index: int): """Get the input name corresponding to the input index""" return model.inputs[index]
6620098f8fb99b18a37aed4ca4f8a28f038c8c79
678,497
from typing import Dict def get_opt_value(result_data: Dict, param_name: str) -> float: """A helper function to get parameter value from a result dictionary. Args: result_data: Result data. param_name: Name of parameter to extract. Returns: Parameter value. Raises: KeyError: - When the result does not contain parameter information. ValueError: - When specified parameter is not defined. """ try: index = result_data["popt_keys"].index(param_name) return result_data["popt"][index] except KeyError as ex: raise KeyError( "Input result has not fit parameter information. " "Please confirm if the fit is successfully completed." ) from ex except ValueError as ex: raise ValueError(f"Parameter {param_name} is not defined.") from ex
bc9c50934757f858973c06c2ddf6b0671b7d9740
153,895
import torch def np2torch(array, dtype=None): """ Convert a numpy array to torch tensor convention. If 4D -> [b, h, w, c] to [b, c, h, w] If 3D -> [h, w, c] to [c, h, w] :param array: Numpy array :param dtype: Target tensor dtype :return: Torch tensor """ d = array.ndim perm = [0, 3, 1, 2] if d == 4 else \ [2, 0, 1] if d == 3 else \ [0, 1] tensor = torch.from_numpy(array).permute(perm) return tensor.type(dtype) if dtype else tensor.float()
1651ba975e9854fa8727b4019683cf0828a37d24
548,434
def parse_csv_data(csv_filename:str)->list: """ Functionality: --------------- Takes a csv file and puts the data in a list of strings so that they can be processed later Parameters: --------------- csv_filename : str The name of the file to be open and read from Returns: --------------- data: list The resulting list of strings """ with open(csv_filename, "r") as csv_file: lines = csv_file.readlines() data = [] for line in lines: data.append(line[:-1]) return data
319358a99174c17df8dcdcd6777237bd48be475b
226,714
def journal(record): """ Turn the journal field into a dict composed of the original journal name and a journal id (without coma or blank). :param record: the record. :type record: dict :returns: dict -- the modified record. """ if "journal" in record: # switch journal to object if record["journal"]: record["journal"] = {"name": record["journal"], "ID": record["journal"].replace(',', '').replace(' ', '').replace('.', '')} return record
4714872865967e757bdc6c6e93a78cee1d64ab81
153,251
def binary_string_to_value(binary_string): """ Convert a binary string representing an unsigned int to a value Args: binary_string (str): The string to convert. e.g. "001010010" Returns: (int): the value of the binary string """ return int(binary_string, 2)
075a4d1958ef9a1c409cfda7a7e71d533434f42e
108,335
from typing import List def replace_words_with_prefix_hash(dictionary: List[str], sentence: str) -> str: """ Replace words in a sentence with those in the dictionary based on the prefix match. Intuition: For each word in the sentence, we'll look at successive prefixes and see if we saw them before Algorithm: Store all roots in a set. Then for each word, look at successive prefixes for that word. If we find a prefix that is root, replace the word with that prefix. Otherwise, the prefix will just be the word itself, and we should add that to the final sentence Complexity Analysis: - Time Complexity: O(∑w i2) where wi is the length of the i-th word. We might check every prefix, the i-th of which is O(w_i^2) work. - Space Complexity: O(N) where N is the length of our sentence; the space used by root_set. @param dictionary: List of roots @param sentence: words separated by space to perform replacement on @return: New sentence with replaced words """ root_set = set(dictionary) def replace(word: str) -> str: for x in range(1, len(word)): if word[:x] in root_set: return word[:x] return word return " ".join(map(replace, sentence.split()))
bb46b0dc61eab2be358d44f8fb46782f867e3c30
24,990
def calc_montage_horizontal(border_size, *frames): """Return total[], pos1[], pos2[], ... for a horizontal montage. Usage example: >>> calc_montage_horizontal(1, [2,1], [3,2]) ([8, 4], [1, 1], [4, 1]) """ num_frames = len(frames) total_width = sum(f[0] for f in frames) + (border_size * num_frames + 1) max_height = max(f[1] for f in frames) total_height = max_height + (2 * border_size) x = border_size pos_list = [] for f in frames: y = border_size + (max_height - f[1]) // 2 pos_list.append([x, y]) x += f[0] + border_size result = [[total_width, total_height]] result.extend(pos_list) return tuple(result)
8fe5de84d9b1bff9950690ec99f63e174f2f0d22
701,204
def _get_checksum_algorithm_set(payload_info_list): """Get set of checksum algorithms in use.""" return {d["checksum_algorithm"] for d in payload_info_list}
76c86e66bc5778c6c2a85ccbc681be93ee6504dc
324,665
import socket def ipaddr_str(t): """Pass through a string provided it represents an ip address (not a host name) otherwise raise an exception""" try: socket.inet_aton(t) except socket.error: raise ValueError("IP address string not of the form nnn.nnn.nnn.nnn") return t
364dc5a6599cc3d420a8bbca817fd6a82ce89c2f
411,037
def get_property_name(x: str) -> str: """Return message name of property in proto. Args: x (str): The name of property. Returns: str: Message name of property in proto . """ x_name = x[0].upper() x_name += x[1:] x_name += 'Property' return x_name
1abe7c040a7e64bb4df3a7726e6047492d2b7d2f
302,989
def load_categories(file_name): """ Loads the category index from file. Each category label is the name of a class specified on a separate line. The entry order is the index of the class. """ labels = [] with open(file_name) as f: labels = f.read().splitlines() categories = {} for category in labels: categories[category] = len(categories) return categories
54bcd375c2e5b9d5d9078d6f0a75b9cebce03702
668,891
def supports_ordinals(bv): """ Check whether the BinaryView supports ordinal imports """ return bv.view_type == 'PE'
5a2fb60385361dd958be2c1aee8641838b175f51
234,602
from datetime import datetime def datetime_from_iso8601(date_str): """Convert ISO 8601 datetime string to datetime. See `ISO 8601 (Wikipedia) <https://en.wikipedia.org/wiki/ISO_8601>`_. Parameters ---------- date_str : str Example: 2016-12-11T10:00:00.000Z Return ------ dt : datetime Datetime representation """ date_str = date_str[:-5] # remove milliseconds: '.000Z' return datetime.strptime(date_str, "%Y-%m-%dT%H:%M:%S")
eca77d3a19449a810e6b399d0c876a2db1e1f015
170,923
def mae_expr(gray_only: bool = True) -> str: """Mean Absolute Error string to be integrated in std.Expr. Args: gray_only (bool, optional): If both actual observation and prediction are one plane each. Defaults to True. Returns: str: Expression. """ return 'x y - abs' if gray_only else 'x a - abs y b - abs max z c - abs max'
98098d0412357f98721b4da645dadf9a688ab091
292,230
def struct2spglib(st): """Transform :class:`~pwtools.crys.Structure` to spglib input tuple (cell, coords_frac, znucl). """ return st.get_spglib()
a8d2e08c7e17e507eb9b2992ae834009403bd4e9
671,060
def calc_answer(question, solution): """ Calculate the black and white pegs of a question @param question: The question that is asked @param solution: The secret solution @return: black, white pegs """ q = question.lst() s = solution.lst() r = [] b = w = 0 for i in range(len(q)): if q[i] == s[i]: b += 1 r.append(i) for d in reversed(r): del q[d] del s[d] for i in range(len(q)): for j in range(len(s)): if q[i] == s[j]: w += 1 del s[j] break return b, w
08e06f00c80c0b8a411f82f7b5107c8770dc4b61
438,406
def extract_star_names(file): """Extracts star names from a text file Arguments: file {str} -- the path to the text file Returns: star_names {list} -- a list of star_names from text file """ names = open(file, 'r') star_names = [line[:-1] for line in names.readlines()] return star_names
182a7d101da130b0035d8d18a7ff0b9ae142e4d6
114,222
import torch def l2_norm(input, axis=1): """l2 normalization. Args: input (torch.Tensor): The input tensor. axis (int, optional): Specifies which axis of input to calculate the norm across. Defaults to 1. Returns: Tensor: Tensor after L2 normalization per-instance. """ norm = torch.norm(input, 2, axis, True) output = torch.div(input, norm) return output
850e9c8424b8c315953062e224980ce74611682d
505,263
import re def frame_of(path): """ Get the frame number of a specific image path :param path: :return: frame as int """ frame = re.findall('.+[\._](\d{4,8})\.[A-Za-z]{3,4}', path) if frame and len(frame) == 1: return int(frame[0])
b1604d172deae39772eeea79c753b1c0a58abfca
229,122
def get_reverted_disk_rses_id_name_map(disk_rses_id_name_map): """Revert k:v to v:k""" return {v: k for k, v in disk_rses_id_name_map.items()}
51ea8b84a5d23f365b3e6a182b62ca586dae7009
626,008
def subtraction(a, b): """subtraction: subtracts b from a, return result c""" a = float(a) b = float(b) c = b - a return c
0115222efc08588a12a6fbc1965441b83a7eaff0
699,510
def vector_to_dictionary(theta): """ Unroll all our parameters dictionary from a single vector satisfying our specific required shape. """ parameters = {} parameters["W1"] = theta[:20].reshape((5,4)) parameters["b1"] = theta[20:25].reshape((5,1)) parameters["W2"] = theta[25:40].reshape((3,5)) parameters["b2"] = theta[40:43].reshape((3,1)) parameters["W3"] = theta[43:46].reshape((1,3)) parameters["b3"] = theta[46:47].reshape((1,1)) return parameters
1e945fe5850e90466622df82b0dfe9fe2de6c36f
263,975
def merge_diffs(d1, d2): """ Merge diffs `d1` and `d2`, returning a new diff which is equivalent to applying both diffs in sequence. Do not modify `d1` or `d2`. """ if not isinstance(d1, dict) or not isinstance(d2, dict): return d2 diff = d1.copy() for key, val in d2.items(): diff[key] = merge_diffs(diff[key], val) if key in diff else val return diff
7314ad63a4679308d27bcff956c9b570d89df8a7
684,739
def path_to_filename(path): """ Returns filename from path by keeping after last '\' """ return path.split("\\")[-1]
645751dda77ac572940d4542228e8769b194de7c
410,935
import requests def get_stock_data(stock_symbol, start_date, end_date): """ Make an REST API call to the tiingo API to get historic stock data Parameters ---------- stock_symbol : str US stock market symbol start_date : str yyyy-mm-dd formated date that begins time series end_date : str yyyy-mm-dd formated date that ends the time series returns ------- response : request.response The response object to be parsed """ TIINGO_API_KEY='c391b96b9ea2e55ce48335fc7ab86245f2a41ec2' base_url = f'https://api.tiingo.com/tiingo/daily/{stock_symbol}/prices?' payload = { 'token':TIINGO_API_KEY, 'startDate':start_date, 'endDate':end_date } response = requests.get(base_url, params=payload) return response
c32ac75581622a4694e8dca96ca87311500e09ec
559,883
import torch def logit(p): """ inverse function of sigmoid p -> tensor \in (0, 1) """ return torch.log(p) - torch.log(1 - p)
290d07606aa01c9837bfce6cdd411ec241ec4484
306,898
def is_terminal(depth, board): """ Generic terminal state check, true when maximum depth is reached or the game has ended. """ return depth <= 0 or board.is_game_over()
7678f3861e628b4e284725c52227b6277ff2f645
445,477
def handle_arguments(**mapping): """ Decorator that will remap keyword arguments. Useful to support maya "short" and "long" form for function arguments. ex: `cmds.ls(selection=True)` and `cmds.ls(sl=True)` are equivalent. :param mapping: A mapping of argument short name by their long name. :type mapping: dict[str, str] :return: A decorated function :rtype: callable """ def _deco(func): def _wrapper(*args, **kwargs): kwargs_conformed = {} for attr, alias in mapping.items(): if attr in kwargs: kwargs_conformed[attr] = kwargs.pop(attr) if alias in kwargs: kwargs_conformed[attr] = kwargs.pop(alias) if kwargs: raise NotImplementedError( "Not implemented keyword argument{s}: {keys}".format( s="s" if len(kwargs) > 1 else "", keys=", ".join(kwargs.keys()) ) ) return func(*args, **kwargs_conformed) return _wrapper return _deco
440d67230ae3dd377a6d007234ac1dbda6a4df65
337,949
def _check_boolean(input, name): """Exception raising if input is not a boolean Checks whether input is not ``None`` and if not checks that the input is a boolean. Parameters ---------- input: any The input parameter to be checked name: str The name of the variable for printing explicit errors in ``Exception`` Returns ------- bool Returns the input if all checks pass Raises ------ ValueError If input is None TypeError If input does not have correct type """ if input is None: raise ValueError(f"`{name}` is None") if not ((input is True) or (input is False)): raise TypeError(f"`{name}` must be type {bool} but is " + f"{type(input)}") return input
b9fb435efc9a2b22384f570f0fa5d5462c07a6a9
675,769
def get_chart_size_range(length, padding): """Calculate the chart size range for a given axis based on the length and padding.""" return [length * padding, length * (1 - padding)]
41e57b7f2f4066d14d6c82ef05b84d2ceda3b6f2
235,904
def _reduce_datetimes(row): """Receives a row, converts datetimes to strings.""" row = list(row) for i in range(len(row)): if hasattr(row[i], 'isoformat'): row[i] = row[i].isoformat() return tuple(row)
f6442cb04c2941f7b83271db430802f6decf51d9
385,078
def get_headers(dataframe): """Get the headers name of the dataframe""" return dataframe.columns.values
8276160a185dc1515da5910811b6b021279bc1f0
262,784
def get_category_from_topchart_url(url: str) -> str: """Return the category from an url. Throws an error if the url isn't recognized. """ category = url.split("/")[3] # check category if category not in [ "films", "series", "jeuxvideo", "livres", "bd", "musique", ]: raise Exception( "URL malformed. Check that the url contains a Senscritique Top (not a Survey)." ) return category
f32296ef176e70df0abf39d8391df394db6bc9d2
619,229
def read_lines_from_tar_file(tar_file): """ Read the tar file returning the lines """ txt = tar_file.read() txt = txt.decode('utf-8') return txt.splitlines()
82c702a4c2fcdb9115774c32730a49f1b3280c8c
98,828
def format_car(car): """Given a car dictionary, returns a nicely formatted name.""" return "{} {} ({})".format( car["car_make"], car["car_model"], car["car_year"])
9719c1c1467b5f866a7b285d093e9bb3d3718ea4
526,785
def make_grid(area): """Make orchard grid given required area.""" height = 3 width = (area // height) + 1 return [[1] * width for _ in range(height)]
7c6500c5927ea2ab5b4cc428f37edf0dc451fb2e
338,678
import re def fullmatch(regex, string, flags=0): """Emulate python-3.4 re.fullmatch().""" matched = re.match(regex, string, flags=flags) if matched and matched.span()[1] == len(string): return matched return None
72de0abe5c15dd17879b439562747c9093d517c5
3,374
def list_or_int_or_float_or_str(value): """ Parses the value as an int, else a float, else a string. If the value contains commas, treats it as a list of ints or floats or strings. Also handles None, True, and False. """ if "," in value: return [list_or_int_or_float_or_str(item) for item in value.split(",")] special_vals = { "None": None, "True": True, "False": False } if value in special_vals: return special_vals[value] try: return int(value) except ValueError: try: return float(value) except ValueError: return str(value)
dcbe8aa414925a8771d1e8591e8aa1344ea2b8f3
185,698
def remove_prefix(text: str, prefix: str) -> str: """Remove prefix from string :param str text: Text to remove prefix from :param str prefix: Prefix to remoe :return: Text with prefix removed if present """ if text.startswith(prefix): return text[len(prefix):] return text
c48060c156fc960a769f27151e3cef1549942842
329,110
import torch def gaussian(window_size, sigma): """ Computer Gaussian. """ x = torch.arange(window_size) - window_size // 2 if window_size % 2 == 0: x = x + 0.5 gauss = torch.exp((-x.pow(2.0) / (2 * sigma ** 2))) return gauss / gauss.sum()
7babdf151ffe3b8fef16f076ea31f57140aa385a
312,344
def alphabet_of_cipher(symbols="ABCDEFGHIJKLMNOPQRSTUVWXYZ"): """ Returns the list of characters in the string input defining the alphabet. Notes ===== First, some basic definitions. A *substitution cipher* is a method of encryption by which "units" (not necessarily characters) of plaintext are replaced with ciphertext according to a regular system. The "units" may be characters (ie, words of length `1`), words of length `2`, and so forth. A *transposition cipher* is a method of encryption by which the positions held by "units" of plaintext are replaced by a permutation of the plaintext. That is, the order of the units is changed using a bijective function on the characters' positions to perform the encryption. A *monoalphabetic cipher* uses fixed substitution over the entire message, whereas a *polyalphabetic cipher* uses a number of substitutions at different times in the message. Each of these ciphers require an alphabet for the messages to be constructed from. Examples ======== >>> from sympy.crypto.crypto import alphabet_of_cipher >>> alphabet_of_cipher() ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'] >>> L = [str(i) for i in range(10)] + ['a', 'b', 'c']; L ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c'] >>> A = "".join(L); A '0123456789abc' >>> alphabet_of_cipher(A) ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c'] >>> alphabet_of_cipher() ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'] """ symbols = "".join(symbols) return list(symbols)
e7a7aed5006c35ac2aa42455dd97c1f95a2e2ca6
355,376
def flux_at_edge(X, min_value=0): """Determine if an edge of the input has flux above min_value Parameters ---------- X: tensor or array 2D matrix to evaluate min_value: float Minimum value to trigger a positive result. Returns ------- result: bool Whether or not any edge pixels are above the minimum_value """ return bool(max(X[:, 0].max(), X[:, -1].max(), X[0].max(), X[-1].max()) > min_value)
3cb29f64e6b9cdce0cb987d27af95b828e10475a
86,930
def _build_css_asset(css_uri): """Wrap a css asset so it can be included on an html page""" return '<link rel="stylesheet" href="{uri}" />'.format(uri=css_uri)
450edf9a134ef6ce3f4b47445e3c26d00b41d45a
346,243
def _train_dev_split(X, y, dev_ratio=0.25): """ This function spilts data into training set and development set. """ train_size = int(len(X) * (1 - dev_ratio)) return X[:train_size], y[:train_size], X[train_size:], y[train_size:]
a547cc105e6e89077dd99c43a50a77e6cc527259
641,353
def extract_output(line): """ Extract the index of the tree and the matched tree fragment from a line of Tregex outout. """ line = line.strip() index = None fragment = None for k, c in enumerate(line): if c == ':': index = line[:k] fragment = line[(k+1):].strip() break assert index is not None return int(index), fragment
b47d8d317108d896f8144a29477a4f2d873cd4c1
498,979
def err_func(params, x, y, func, w=None, func_list=None): """ Error function for fitting a function Parameters ---------- params : tuple A tuple with the parameters of `func` according to their order of input x : float array An independent variable. y : float array The dependent variable. func : function A function with inputs: `(x, *params)` w : ndarray A weighting function. Allows emphasizing certain parts of the original function. Should have the same length as x/y. func_list : dict dict of callables, each with it's own set of indices into the params Returns ------- The marginals of the fit to x/y given the params. """ err = y - func(x, *params) if w is not None: err = err * w if func_list is not None: err2 = 0 for f in func_list: this_err = (y - f[0](x, *[params[ii] for ii in f[1]])) if f[2] is not None: this_err = this_err * f[2] err2 = err2 + this_err err = err2 + err return err
421a98fca40ec666ff8843b701e1a59de6576933
380,593
import random def select_random_subgraph(bqm, n): """Select randomly `n` variables of the specified binary quadratic model. Args: bqm (:class:`dimod.BinaryQuadraticModel`): Binary quadratic model (BQM). n (int): Number of requested variables. Must be between 0 and `len(bqm)`. Returns: list: `n` variables selected randomly from the BQM. Examples: This example returns 2 variables of a 4-variable BQM. >>> import dimod >>> bqm = dimod.BQM({}, {'ab': 0, 'bc': 1, 'cd': 2}, 0, 'BINARY') >>> select_random_subgraph(bqm, 2) # doctest: +SKIP ['d', 'b'] """ return random.sample(bqm.linear.keys(), n)
c41823e1e5c664b14e33cc7d9ef26ea5599ae592
426,723
def diff_set(before, after, create_replaced=True): """Compare sets to get additions, removals and replacements Return 3 sets: added -- objects present in second set, but not present in first set removed -- objects present in first set, but not present in second set replaced -- objects that have the same name in both sets, but are different """ removed = before - after added = after - before replaced = set() removed_by_name = {} for element_removed in removed: removed_by_name[element_removed.name] = element_removed for element_added in added: element_removed = removed_by_name.get(element_added.name) if element_removed and create_replaced: replaced.add((element_removed, element_added)) if create_replaced: for (element_removed, element_added) in replaced: removed.discard(element_removed) added.discard(element_added) return (added, removed, replaced)
f61fab8c964c768c57f574061c5e0226de9f2771
101,600
import re def alias_tpl(data): """Generates Mantle alias Output: @"postTime": @"post_time", """ name = data['original_name'] candidates = re.findall(r'(_\w)', name) if not candidates: new_name = data['name'] else: new_name = re.sub(r'_(\w)', lambda x: x.group(1).upper(), name) return '@"{}": @"{}",'.format(new_name, name)
13e42ecffb27018e87acfd1919bb812603c50f4c
93,416
def _append_y(clifford, qubit): """Apply a Y gate to a Clifford. Args: clifford (Clifford): a Clifford. qubit (int): gate qubit index. Returns: Clifford: the updated Clifford. """ x = clifford.table.X[:, qubit] z = clifford.table.Z[:, qubit] clifford.table.phase ^= x ^ z return clifford
ac2429e81590fcdb8f2821154b81165031a5ef26
566,940
def get_null_columns(train, null_threshold=0.4): """ finds columns with null values greater than threshold(default=0.4) returns list of columns to be removed """ missingcol = train.columns[(train.isnull().sum() / train.shape[0]) > null_threshold] return missingcol
7aefb259facdc8c2ae36b78a297e1937732c0e8f
185,262
def turn_psql_url_into_param(postgres_url: str) -> dict: """ >>> turn_psql_url_into_param( ... 'postgres://USERNAME:PASSWORD@URL:PORT/USER?sslmode=SSLMODE') == { ... 'db_user':'USERNAME', 'db_password': 'PASSWORD', 'db_host': 'URL', 'db_port': ... 'PORT', 'db_name': 'USER', 'sslmode': 'SSLMODE'} True >>> turn_psql_url_into_param( ... 'USERNAME:PASSWORD@URL:PORT/USER?sslmode=SSLMODE') Traceback (most recent call last): ... AttributeError: The database URL is not well formated >>> turn_psql_url_into_param( ... 'postgres://USERNAME:PASSWORD@URL:PORT/USER') == { ... 'db_user': 'USERNAME', 'db_password': 'PASSWORD', 'db_host': 'URL', ... 'db_port': 'PORT', 'db_name': 'USER'} True >>> turn_psql_url_into_param("postgresql://") == {} True >>> turn_psql_url_into_param('postgresql://localhost') == {'db_host': ... 'localhost'} True >>> turn_psql_url_into_param('postgresql://localhost:5433') == {'db_host': ... 'localhost', 'db_port': '5433'} True >>> turn_psql_url_into_param('postgresql://localhost/mydb') == {'db_host': ... 'localhost', 'db_name': 'mydb'} True >>> turn_psql_url_into_param('postgresql://user@localhost') == {'db_host': ... 'localhost', 'db_user': 'user'} True >>> turn_psql_url_into_param('postgresql://user:secret@localhost') == { ... 'db_host': 'localhost', 'db_user': 'user', 'db_password': 'secret'} True >>> turn_psql_url_into_param('postgresql://oto@localhost/ther?' ... 'connect_timeout=10&application_name=myapp') == { ... 'db_host': 'localhost', 'db_user': 'oto', 'db_name': 'ther', ... 'connect_timeout': '10', 'application_name': 'myapp'} True """ if not postgres_url.startswith(("postgres://", "postgresql://")): raise AttributeError("The database URL is not well formated") response = {} # Get parameters params_start = postgres_url.rfind("?") if not params_start == -1: params = postgres_url[params_start + 1 :] params = [param.split("=") for param in params.split("&")] for param in params: response[param[0]] = param[1] user_and_db_info = postgres_url[postgres_url.find("://") + 3 : params_start] else: user_and_db_info = postgres_url[postgres_url.find("://") + 3 :] if not user_and_db_info: return response # User information if "@" in user_and_db_info: user_info, db_info = tuple(user_and_db_info.split("@")) user_info = user_info.split(":") response["db_user"] = user_info[0] if len(user_info) > 1: response["db_password"] = user_info[1] else: db_info = user_and_db_info # Database information db_info = db_info.split("/") if len(db_info) > 1: response["db_name"] = db_info[1] url_and_port = db_info[0] url_and_port = url_and_port.split(":") response["db_host"] = url_and_port[0] if len(url_and_port) > 1: response["db_port"] = url_and_port[1] return response
6a25bea1c647e80114828e708f61b04b14c35327
493,431
def intToByte(i): """ int -> byte Determines whether to use chr() or bytes() to return a bytes object. """ return chr(i) if hasattr(bytes(), 'encode') else bytes([i])
e70741a85138e0ef82d828bf46bbce90252707e6
176,836
def split_sentence(s): """ Given a string, [s], split it into sentences. # Arguments * `s` (str) - a string to split. # Returns A list strings representing the sentences of the text. It is guaranteed that each string is non-empty, has at least one whitespace character, and both start and end on non-whitespace characters. """ lines = map(str.strip, s.splitlines()) return list([line for line in lines if line])
c805e4c22e9136cb3d7e07e94a2be2301452c6e3
513,637
def get_curated_date(date): """ remove the seconds etc, e.g., 2018-07-15T16:20:55 => 2018-07-15 """ return date.strip().split('T')[0]
08fc369c7b33612b5460cd6ae155999d50cdd2fe
540,230
def get_docker_base_image_name() -> str: """ Return a base name for docker image. """ base_image_name = "amp" return base_image_name
6b9e6d71e9d530430a1572fbc2f3d80f4aa39b80
550,084
def to_ms(ts): """ Returns an ms-formatted version of the specified tree sequence. """ output = "" for tree in ts.trees(): length = tree.interval[1] - tree.interval[0] output += "[{}]{}\n".format(length, tree.newick()) return output
517ab1bbe1a0d5b2309375564ec7acbbd3f8c91d
493,187
import random def sample_from(weights): """returns i with probability weights[i] / sum(weights)""" total = sum(weights) rnd = total * random.random() # uniform between 0 and total for i, w in enumerate(weights): rnd -= w if rnd <= 0: # return the smallest i such that return i
084cc781ac6dd7ffe0df96bf23dfc00de7d5d4eb
314,839
def clean_multiple_coordsets(protein): """ Deletes all but the first coordinate set of a protein. """ if len(protein.getCoordsets()) > 1: for i in range(len(protein.getCoordsets())): if i == 0: pass else: protein.delCoordset(-1) return protein
70e0c9355394b78331b802c40369b98c74ed75f1
35,127
def hfsym(self, kcn="", xkey="", ykey="", zkey="", **kwargs): """Indicates the presence of symmetry planes for the computation of APDL Command: HFSYM acoustic fields in the near and far field domains (beyond the finite element region). Parameters ---------- kcn Coordinate system reference number. KCN may be 0 (Cartesian), or any previously defined local Cartesian coordinate system number (>10). Defaults to 0. xkey Key for acoustic field boundary condition, as prescribed for the solution, corresponding to the x = constant plane: None - No sound soft or sound hard boundary conditions (default). SSB - Sound soft boundary (pressure = 0). SHB - Sound hard boundary (normal velocity = 0). ykey Key for acoustic field boundary condition, as prescribed for the solution, corresponding to the y = constant plane: None - No sound soft or sound hard boundary conditions (default). SSB - Sound soft boundary (pressure = 0). SHB - Sound hard boundary (normal velocity = 0). zkey Key for acoustic field boundary condition, as prescribed for the solution, corresponding to the z = constant plane: None - No sound soft or sound hard boundary conditions (default). SSB - Sound soft boundary (pressure = 0). SHB - Sound hard boundary (normal velocity = 0). Notes ----- HFSYM uses the image principle to indicate symmetry planes (x, y, or z = constant plane) for acoustic field computations outside the modeled domain. A sound hard boundary condition must be indicated even though it occurs as a natural boundary condition. No menu paths are available for acoustic applications. """ command = f"HFSYM,{kcn},{xkey},{ykey},{zkey}" return self.run(command, **kwargs)
27b4b9b262fc39afe159f7886e8a4a3854e4ef36
511,153
import math def _pad(text, block_size): """ Performs padding on the given plaintext to ensure that it is a multiple of the given block_size value in the parameter. Uses the PKCS7 standard for performing paddding. """ no_of_blocks = math.ceil(len(text)/float(block_size)) pad_value = int(no_of_blocks * block_size - len(text)) if pad_value == 0: return text + chr(block_size) * block_size else: return text + chr(pad_value) * pad_value
d5334e05924c2221c539d92e819e2188074faac8
642,374
def size(price_left=1, price_right=1, vol_left=1, vol_right=1, unit_size_left=1, multiplier_left=1, multiplier_right=1): """Calculate volatility weighted size for each leg of pairs trade Calculate the number of units for each leg of a pairs trade by passing the price of both legs and optionally the share size of one leg and multipliers in the case of futures. Returns a dict with the given arguments and the number of units for each leg. It is often desirable to equate the level of risk for each leg of a pairs trade. This risk depends on both the equity value and the volatility of each leg. For example, suppose a pairs trade consists of two legs. The first leg is long stock ABC, which trades for $100 per share and has a 30-day historical standard deviation of 2%. The second leg is a short position in stock XYZ, which trades for $25 per share and has a standard deviation of 7%. How many shares of each stock should be traded to create a neutral pairs trade? Clearly, if 100 shares of each leg were traded, the risk in one leg would be much greater than the other. So, we want to equate the equity of each leg: abc_shares * abc_price = xyz_shares * xyz_price left_shares * left_price = right_shares * right_price ...where we have arbitrarily defined ABC as the "left" side of the trade. However, the above equation fails to adequately equate the risk in each leg; since the volatility of XYZ is 7% and the volatility of ABC is 2%, sizing the trade based on the above equation would put more risk in the XYZ leg than the ABC leg. So, to equate the risk in each leg, we add a measure of volatility to the prior equation: left_shares * left_price * left_vol = right_shares * right_price * right_vol Compared to the prior equation, this equation reduces the number of shares traded in XYZ, since the risk is larger in each unit of equity for XYZ, because XYZ has higher volatility. Now, suppose that we're comfortable trading 100 shares of ABC and we want to now calculate the quantity of XYZ shares to trade. We can do a simple algebriac manipulation to calculate the number of shares: right_shares = (left_shares * left_price * left_vol) / (right_price * right_vol) = (100 * 100 * 2) / (25 * 7) = 114.28 ..and this can be plugged back into the original equation as a check. In the case of a futures contract, the *notional value* must be calculated in order to volatility-weight each leg: left_units * left_multiplier * left_price * left_vol = right_units * right_multiplier * right_price * right_vol ...where the multiplier is a number used to convert the futures price into the notional value of the futures contract. In the case where both legs are a stock, the multipliers are simply 1. To calculate the number of units for the right leg: left_units = (right_units * right_multiplier * right_price * right_vol) / (left_multiplier * left_price * left_vol) Parameters ---------- price_left, price_right : float The entry prices for each leg of the pair, left and right. vol_left, vol_right : float A measure of volatility for each leg of the pair, left and right. unit_size_left : float The number of units (e.g. shares) that compose the left leg of the pair. Optional, default is 1 unit. multiplier_left, multiplier_right : float Multiplier for each leg of the pair, left and right. The multiplier is a number that translates the asset price into the notional (equity) value of one unit of the asset. In the case of a stock, the mulitplier is simply 1. The multiplier for futures contracts depends on the specifications of the contract. Optional, default is 1. Returns ------- pair_specs : dict Dict with keys multiplier_left, multiplier_right, price_left, price_right, unit_size_left, unit_size_right, vol_left, and vol_right. """ unit_size_right = \ (vol_left * price_left * multiplier_left * unit_size_left) / \ (vol_right * price_right * multiplier_right) pair_specs = dict(vol_left=vol_left, price_left=price_left, multiplier_left=multiplier_left, multiplier_right=multiplier_right, unit_size_left=unit_size_left, vol_right=vol_right, price_right=price_right, unit_size_right=unit_size_right) return pair_specs
9f1752689da25b923093679b130d0a40142d0ca2
136,573
def string_contains_space(string): """ Returns true if string contains space, false otherwise. """ for char in string: if char.isspace(): return True return False
2069afc7679c3b52606ba021f26aba9615ccdd9b
117,349
def _Checksum(sentence): """Compute the NMEA checksum for a payload.""" checksum = 0 for char in sentence: checksum ^= ord(char) checksum_str = '%02x' % checksum return checksum_str.upper()
d3932b8079d0fc78774c825746d46ac569e42e2e
505,578
import time def get_elapsed_time(start_time) -> str: """ Gets nicely formatted timespan from start_time to now """ end = time.time() hours, rem = divmod(end-start_time, 3600) minutes, seconds = divmod(rem, 60) return "{:0>2}:{:0>2}:{:05.2f}".format(int(hours), int(minutes), seconds)
d75a1873254e1b1cc9ffc714e65d3a9ed95e5803
704,297
import json def update_permissions_for_annotation( gc, annotation_id=None, annotation=None, groups_to_add=None, replace_original_groups=True, users_to_add=None, replace_original_users=True): """Update permissions for a single annotation. Parameters ---------- gc : gider_client.GirderClient authenticated girder client instance annotation_id : str girder id of annotation annotation : dict overrides annotation_id if given groups_to_add : list each entry is a dict containing the information about user groups to add and their permission levels. A sample entry must have the following keys - level, int -> 0 (view), 1 (edit) or 2 (owner) - name, str -> name of user group - id, st -> girder id of user group replace_original_groups : bool whether to replace original groups or append to them users_to_add : list each entry is a dict containing the information about user to add and their permission levels. A sample entry must have the following keys - level, int -> 0 (view), 1 (edit) or 2 (owner) - login, str -> username of user - id, st -> girder id of user replace_original_users whether to replace original users or append to them Returns ------- dict server response """ groups_to_add = [] if groups_to_add is None else groups_to_add users_to_add = [] if users_to_add is None else users_to_add if annotation is not None: annotation_id = annotation['_id'] elif annotation_id is None: raise Exception( "You must provide either the annotation or its girder id.") # get current permissions current = gc.get('/annotation/%s/access' % annotation_id) # add or replace as needed if replace_original_groups: current['groups'] = [] current_group_ids = [] else: current_group_ids = [j['id'] for j in current['groups']] if replace_original_users: current['users'] = [] current_user_ids = [] else: current_user_ids = [j['id'] for j in current['users']] for group in groups_to_add: if group['id'] not in current_group_ids: current['groups'].append(group) for user in users_to_add: if user['id'] not in current_user_ids: current['users'].append(user) # now update accordingly # BAD WAY!! -- do NOT do this! # return gc.put('/annotation/%s/access?access=%s' % ( # annotation_id, json.dumps(current))) # PROPER WAY return gc.put('/annotation/%s/access' % annotation_id, data={ 'access': json.dumps(current)})
e4e10862d3d11551197f281200497542a723f947
115,428
from typing import Sequence def false_positive_rate(y_true: Sequence, y_pred: Sequence) -> float: """Calculates the false positive rate binary classification results. Assumes that the negative class is -1. """ assert set(y_true).issubset({1, -1}) assert set(y_pred).issubset({1, -1}) false_positives = 0 true_negatives = 0 for true_label, predicted_label in zip(y_true, y_pred): if true_label == -1 and predicted_label == 1: false_positives += 1 elif true_label == predicted_label == -1: true_negatives += 1 try: return false_positives / (false_positives + true_negatives) except ZeroDivisionError: return 0
8668d01c2628062efef67b04c912ef315d37fa13
62,357
def fillNaToMode(data): """Iterates through NA values and changes them to the mode Parameters: dataset (pd.Dataset): Both datasets Returns: data (pd.Dataset) : Dataset with any NA values in the columns listed changed to the mode """ columns = ["MSZoning", "Functional", "Electrical", "KitchenQual", "Exterior1st", "Exterior2nd"] for column in columns: data[column] = data[column].fillna(data[column].mode()[0]) return data
6d8ec04da66b7463e69fdda3ff6665b3ce2bbde8
632,886
def get_names_probs(predict_output, cat_to_name, class_to_idx): """Return the names and probabilities of the predicted classes Args: predict_output (obj): A ``torch.tensor`` object from typically with 2 tensors cat_to_name (dict): A dictionary containing key to category mapping of each category in the cat_to_name file class_to_idx (dict): Class to id mapping of the train data Returns: tuple: Returns a tuple of ``flower_names`` - Name of the flowers predicted ``flower_probs`` - Probabilities associated with each predicted flower """ idx_to_class = {v: k for k, v in class_to_idx.items()} flower_names = [cat_to_name[idx_to_class[x.item()]] for x in predict_output[1][0]] flower_probs = [x.item() for x in predict_output[0][0]] return flower_names, flower_probs
5b62aa1a98b4391733bcae2c02aa95663edcf11c
270,811