content
stringlengths
39
14.9k
sha1
stringlengths
40
40
id
int64
0
710k
def _index_to_sequence(i, dim_list): """ For a matrix entry with index i it returns state it corresponds to. In particular, for dim_list=[2]*n it returns i written as a binary number. Parameters ---------- i : int Index in a matrix. dim_list : list of int List of dimensions...
18b6a077db38efd0dad027d129737e7d60621d6f
656,729
import math def y_ticks(max_y): """ Computes aesthetically pleasing y-axis tick marks for specified max value Note:: will always include y=0 as the minimum value returns list of y values and scaling factor """ log_max = math.log10(max_y) m_log_y = math.floor(log_max) # log of ...
00e1716f6db86389db0b16a27c62d7fd24d5ef3f
656,730
import torch def to_bitmask(M): """ Returns the bitmask sparse format of matrix 'M' :param M: original weight matrix M """ wmb = (M != 0).float() data = M[torch.nonzero(M, as_tuple=True)] return wmb, data
a9e44b91effe07fa3aa4b99bec97794dc5e9ec58
656,733
def vec_sum(a): """ Computes the inner sum of a vector Parameters ---------- a: list[] A vector of scalar values Returns ------- scalar The sum of the elements in the vector """ return sum(a)
9fe0d0bc36b08e38fc118f8af05cc7e1fc642fa4
656,736
import types import functools import inspect def _is_unbound_self_method(core_callable): """Inspects a given callable to determine if it's both unbound, and the first argument in it's signature is `self`""" if isinstance(core_callable, types.MethodType): return False if isinstance(core_callable, ...
b403dd8da2d26ce2870a30c51d92322ec3e79dff
656,737
def extract_epoch(filename): """ Get the epoch from a model save string formatted as name_Epoch:{seed}.pt :param str: Model save name :return: epoch (int) """ if "epoch" not in filename.lower(): return 0 epoch = int(filename.lower().split("epoch_")[-1].replace(".pt", "")) retur...
23be1634bd2350c0b560cf1fb7b59198668b7e02
656,740
def align_bitext_to_ds(bitext, ds): """ Return a subset of bitext that's aligned to ds. """ bitext_dict = dict([(src, (ind, tgt)) for ind, (src, tgt) in enumerate(bitext)]) new_bitext = [] for entry in ds: en_sent = entry[2] ind, tgt_sent = bitext_dict[en_sent] new_bitext...
1e534ac49d607966f72ee660f5b5677f08fa5833
656,751
import calendar def get_month_name(month): """gets the month full name from the calendar.""" # print(calendar.month_abbr[month]) # to print the month appreviated name return calendar.month_name[month]
8c88b1c330efa7d278279f463ccb093b7448c5d5
656,753
def filter_sequences(df, lower_bound, upper_bound, grouping_col='hadm_id'): """ Filters sequences so that only those that are between lower_bound and upper_bound remain Parameters ---------- df: object data on which to operate on lower_bound: int lower bound to discard upper_...
72dad7d3b91863d49cddaedc1fe9c582cb0d417d
656,754
def supportScalar(location, support, ot=True): """Returns the scalar multiplier at location, for a master with support. If ot is True, then a peak value of zero for support of an axis means "axis does not participate". That is how OpenType Variation Font technology works. >>> supportScalar({}, {})...
66df5e8325c1e5f94ee745497cb7a3e9500bad5b
656,758
def get_history_score(history): """ Calculate the history score given a list of pass/fail booleans. Lower indices represent the most recent entries. """ if len(history) == 0: return 0.0 score = 1.0 for index, good in enumerate(history): if not good: score -= 0.5 /...
dadd1922251d8fe03191bdbb1a3b66630f52bd2f
656,759
def date_specificity(date_string): """Detect date specificity of Zotero date string. Returns 'ymd', 'ym', or 'y' string. """ length = len(date_string) if length == 10: return 'ymd' elif length == 7: return 'ym' elif length == 4: return 'y' return None
4828146d43b4d3447b0f9ca014722d4d7a9ff015
656,760
def ignore(path, ignores): """ If the full path of a file in pivt is equal to the full path of an element in the ignore list then we return True because we do not want that full path in the list created by walk_root. :param path: Full path to a file in the pivt directory :param ignores: A list ...
ac6b5584c25867759a5c67c267887fb2428ed2ec
656,761
def get_stream_info_string(stream): """ Returns (compact) string with stream information. """ name = stream.name() hostname = stream.hostname() source_id = stream.source_id() uid = stream.uid() return '{}@{}[{}][{}]'.format(name, hostname, source_id, uid)
bd33fe631834b38553a08e28a637c2d3a186d82d
656,762
def implements(implementor, implementee): """ Verifies that the implementor has the same methods and properties as the implementee. __XXX__ classes are excluded. For the purposes of method comparison, arguemtn order is importent. >>> class Implementor(object): ... foo = 1 ... def ...
cf8400d82e9e26d2cf93f5ef27edf789ff591771
656,763
def _clean_scale(scale): """Cleanup a 'scaling' string to be matplotlib compatible. """ scale = scale.lower() if scale.startswith('lin'): scale = 'linear' return scale
5e67783ae6f8b9df704c3b2e7f68dcd3b6c9e47d
656,764
import string import random def random_pwd_generator(length, additional_str=''): """Generate random password. Args: length: length of the password additional_str: Optional. Input additonal string that is allowed in the password. Default to '' empty string. Returns:...
5d61022fe7b1a362f4d7a163997129d9c5a4e4bf
656,767
def get_summary_html_name(prj): """ Get the name of the summary HTML file for provided project object :param peppy.Project prj: a project object to compose a summary HTML file name for :return str: name of the summary HTML file """ fname = prj.name if prj.subproject is not None: fna...
132cfa1ec06f0ce6b559ae82ddfb8676b123a0a5
656,770
def calculate_metrics(array_sure, array_possible, array_hypothesis): """ Calculates precision, recall and alignment error rate as described in "A Systematic Comparison of Various Statistical Alignment Models" (https://www.aclweb.org/anthology/J/J03/J03-1002.pdf) in chapter 5 Args: array_sure: ...
ccbcb76a5d34d79c44cc665849fabaa2ed674fe5
656,772
import torch def loss_creator(config): """Constructs the Torch Loss object. Note that optionally, you can pass in a Torch Loss constructor directly into the TorchTrainer (i.e., ``TorchTrainer(loss_creator=nn.BCELoss, ...)``). Args: config: Configuration dictionary passed into ``TorchTrainer`...
a3aa7f8d6b6ac295f6adc883ce86c894134a7366
656,774
def matscalarMul(mat, scalar): """Return matrix * scalar.""" dim = len(mat) return tuple( tuple( mat[i][j] * scalar for j in range(dim) ) for i in range(dim) )
55a64773b3cef94b5edd8237ea4e50a01226d150
656,775
import re def slice(text, length=100, offset = 0, last_word=True): """ Slice a string. """ text = text[offset:] if len(text) <= length or not last_word: return text[:length] return re.sub('(\s+\S+\s*)$', '', text[:length])
49702f1a5161c2865d088cd5d208b247e6943fde
656,776
def pack_namedtuple_base_class(name: str, index: int) -> str: """Generate a name for a namedtuple proxy base class.""" return "namedtuple_%s_%d" % (name, index)
33950d4c318182247d160ded0849b8c6cdcac50a
656,779
def add_project(conn, project): """ Create a new project into the projects table :param conn: :param project: :return: project id """ sql = ''' INSERT INTO projects(name, begin_date, end_date) VALUES(?,?,?) ''' cur = conn.cursor() cur.execute(sql, project) ...
910ad085316498381f59df0a2004487196696ec0
656,780
def from_file(filename, level="(not set)"): """Load test cases from file, return as list of dicts. Puzzle should be formatted as a string on a single line. See puzzle.latinsquare.from_string. Trailing whitespace is stripped. Args: filename: File to read. One line per puzzle. level: Lab...
94b60fd8f7d99bf541c107b5d4f55118611ad58c
656,781
def get_type(array): """Return type of arrays contained within the dask array chunks.""" try: datatype = type(array._meta) # Check chunk type backing dask array except AttributeError: datatype = type(array) # For all non-dask arrays return datatype
d4ca1bf300bf5a322bc76a9bc1e2c1213d8dcd50
656,783
def extract_tensors(tf_graph): """ Get input, initial state, final state, and probabilities tensor from the graph :param loaded_graph: TensorFlow graph loaded from file :return: Tuple (tensor_input,tensor_initial_state,tensor_final_state, tensor_probs) """ tensor_input = tf_graph.get_tensor_by_n...
8c6974ad723317f758388de3a93584c254c23732
656,784
from typing import Dict from typing import List def get_spot_request_ids_from_response(response: Dict) -> List[str]: """ Return list of all spot request ids from AWS response object (DescribeInstances) """ spot_request_ids = [] for reservation in response['Reservations']: for inst in ...
a6810adaebc033f5dcf57d1a59d3ea7f181dba2b
656,786
from typing import Dict import inspect def get_available_class(module, class_name) -> Dict[str, type]: """Search specified subclasses of the given class in module. :param module: The module name :type module: module :param class_name: the parent class :type class_name: type :return: A dict ma...
4e7a901296a2b75dc9cced045b77cc887c00c627
656,787
from typing import Any def is_real_float(candidate: Any) -> bool: """ Checks if the given `candidate` is a real `float`. An `integer` will return `False`. Args: candidate (Any): The candidate to test. Returns: bool: Returns `True` if the `candidate` is a real float; otherwise `False....
e5a93a3f082bbdd1f0e386eb678948d8a254f103
656,789
def char_from_number(number): """ Converts number to string by rendering it in base 26 using capital letters as digits """ base = 26 rval = "" if number == 0: rval = 'A' while number != 0: remainder = number % base new_char = chr(ord('A') + remainder) rval = n...
570093a691439d2eed141eeaea982abf8f40b4f9
656,795
def human_readable_bytes(value, digits= 2, delim= "", postfix=""): """Return a human-readable file size. """ if value is None: return None chosen_unit = "B" for unit in ("KiB", "MiB", "GiB", "TiB"): if value > 1000: value /= 1024 chosen_unit = unit els...
f455087c124dd26df68d3404a2bf96fd0f24efb7
656,796
def validate_num_results(request): """ A utility for parsing the requested number of results per page. This should catch an invalid number of results and always return a valid number of results, defaulting to 25. """ raw_results = request.GET.get('results') if raw_results in ['50', '100']: ...
83a0ef8849ffc1c1c990036c1ae9fe33aa07a4cb
656,797
def estimate_probability(word, previous_n_gram, n_gram_counts, n_plus1_gram_counts, vocabulary_size, k=1.0): """ Estimate the probabilities of a next word using the n-gram counts with k-smoothing Args: word: next word previous_n_gram: A sequence of words of len...
69d680ef3f833a823d3773293dd595c5530d809c
656,798
def mini_batch_size_update(mini_batch_size, gpu_count): """Increase mini-batch size to accommodate more than 1 GPU.""" if gpu_count <= 1: return mini_batch_size elif gpu_count > 1: return mini_batch_size * gpu_count
9bcbad73bfc6adfbda3cc4fb03e741eee01f5699
656,808
import pickle def load_pixel_corner_lookup(filename): """ Returns (lons, lats, corners), the pickeled objects created by save_pixel_corner_lookup. Equivalent to the arguments returned by read_official_corner_lut. """ with open(filename, 'rb') as f: obj = pickle.load(f) return obj
ff74990edd326c771d991bd6f8a526e247c06d9f
656,809
def binlist(n, width=0): """ Return list of bits that represent a non-negative integer. n -- non-negative integer width -- number of bits in returned zero-filled list (default 0) """ return list(map(int, list(bin(n)[2:].zfill(width))))
bc25337e8a6edd0406c15c5b095ae7d13b4fa6b5
656,811
def andSearch(inverseIndex, query): """ Input: an inverse index, as created by makeInverseIndex, and a list of words to query Output: the set of all document ids that contain _all_ of the specified words """ docIds = set() for q in query: if q in inverseIndex: if not docIds: ...
04d31d96ba072d943a98b965f6f3abf589c532ed
656,813
def extract_split_timing_info(fn): """ Group lines by benchmark iteration, starting from migrad until after the forks have been terminated. """ with open(fn, 'r') as fh: lines = fh.read().splitlines() bm_iterations = [] start_indices = [] end_indices = [] for ix, line in en...
ad599a56323fca12427c2f3a5e19394575703909
656,814
import torch def create_verts_index(verts_per_mesh, edges_per_mesh, device=None): """ Helper function to group the vertex indices for each mesh. New vertices are stacked at the end of the original verts tensor, so in order to have sequential packing, the verts tensor needs to be reordered so that the ...
6ac55d2b5bf1c2b323026b8de4a2c59ab064d38f
656,817
def extract_mean_ci_score(rec): """ Parameters ---------- rec : dict Audio recording record. Returns ------- Mean cacaophony index as float or -1 if it could not be found. """ ci = -1.0 try: caco_id = rec['additionalMetadata']['analysis']['cacoph...
16770d67baa8fd1894fc19fa3a3f4f688d858f2e
656,818
def destagger(data, dim, new_coord, rename=True): """ Destagger WRF output data in given dimension by averaging neighbouring grid points. Parameters ---------- data : xarray dataarray input data. dim : str destaggering dimension. new_coord : array-like new coordinate...
4ff4750b916f71208cf910d60c56c98179ddb130
656,819
def points_at(links, other): """Whether any of the links points at the other""" return any(_.points_at(other) for _ in links)
52b8663d2d5c3b5cafe899b8e5e63055a6969470
656,820
def convert_to_list(input, _type=int, _default_output=None): """ Converts the input to a list if not already. Also performs checks for type of list items and will set output to the default value if type criteria isn't met Args: input: input that you are analyzing to convert to list of type ...
dd7a520bd263922164369483a3beebe8ccb4af7c
656,821
def calc_channel_current(E, sigma, A): """ Calculate channel current """ I = E * sigma * A return I
1602bdaf37599d48361decb214a9f9e426c97d22
656,822
def _make_bin_midpoints(bins): """Get midpoints of histogram bins.""" return (bins[:-1] + bins[1:]) / 2
67bea58555588488321f9f7443da7355bb58f3f4
656,828
import pathlib def get_relpath(src, dst): """ Returns the relative path from ``src`` to ``dst`` Args: src (``pathlib.Path``): the source directory dst (``pathlib.Path``): the destination directory Returns: ``pathlib.Path``: the relative path """ # osrc = src ups =...
87a11a909920d6da8ffc3b66519eb0762e04403d
656,829
from typing import Optional def validate_ref_component_optional(ref_component: Optional[int]) -> Optional[int]: """ Validates the reference to a component of an object. :param ref_component: The reference to a component of the object. :return: The validated reference to a component. """ if re...
ae2257375b97766e2310c11d8e638cfb6cbdb34c
656,830
import math def format_bytes(bytes): """ Get human readable version of given bytes. Ripped from https://github.com/rg3/youtube-dl """ if bytes is None: return 'N/A' if type(bytes) is str: bytes = float(bytes) if bytes == 0.0: exponent = 0 else: exponent ...
b541f7ba67faaff44578b2791a13577494f1228a
656,837
def _get_object_presentation(obj_dict): """Returns one of object possible presentation: - display_name - title - name - slug if Nothing is presented in serrialized object than it will return `{tytle}_{id}` presentation. """ keys = ("display_name", "title", "name", "slug") for key in keys: if o...
456497d6e2b76c5d4a85cf882e6a01085eca4202
656,838
def distinct(not_distinct_list: list): """ Returns a list with no duplicate elements """ return list(set(not_distinct_list))
87dfa260b7882e28ada5803db30f12275968f44d
656,840
def add_vector(vector, increment, mod = False, bounds = (0, 0)): """ Adds two 2D vectors and returns the result can also do modular arithmitic for wrapping """ result = [0, 0] result[0] = vector[0] + increment[0] result[1] = vector[1] + increment[1] if mod: result[0] = resu...
b83c1a4e3c024f0e4fc67286c6f9e46b48555358
656,844
def addHtmlBreaks(s, isXhtml=True): """Replace all returns by <br/> or <br>.""" tag = {True:'<br/>\n', False:'<br>\n'}[isXhtml] return s.replace('\n',tag)
dc4fb9d39fc7a2fba8d8c795c3c8394630358425
656,849
from typing import Iterable import itertools def xor_cipher(string: Iterable[str], key: Iterable[str]) -> str: """XOR шифр :param string: Шифруемый/расшифровываемый текст :type string: Iterable[str] :param key: Ключ :type key: Iterable[str] :return: Текст после шифровки/дешифровки :rtype:...
b9d37fef58c80e827a04d36b4551a8af4cd82633
656,850
def read_words(words_file): """ (file open for reading) -> list of str Return a list of all words (with newlines removed) from open file words_file. Precondition: Each line of the file contains a word in uppercase characters from the standard English alphabet. """ f = open(words_file) ...
ff110f45e02fc48049f3d4180b093a72771e098e
656,851
def diff(list1, list2): """ Returns the list of entries that are present in list1 but not in list2. Args: list1 A list of elements list2 Another list of elements Returns: A list of elements unique to list1 """ diffed_list = [] for item in list1: if item not in list2: diffed_list....
0a8cb8f9d2962591df6b46abb6c48c57f121492c
656,854
def agg_across_entities(entity_lists_by_doc): """ Return aggregate entities in descending order by count. """ if not entity_lists_by_doc or len(entity_lists_by_doc) == 0: return [] result_set = {} for doc_id in entity_lists_by_doc.keys(): cur_list = entity_lists_by_doc[doc_id] ...
ff0981630098d999c75e5efc1818c2c788a0a240
656,856
def GetMosysPlatform(config): """Get the name of the mosys platform for this board. cros_config_schema validates there is only one mosys platform per board. This function finds and prints the first platform name. Args: config: A CrosConfig instance. Returns: An exit status (0 for success, 1 for fa...
7011c72846cba8347c2e6c1455daed0961abba7b
656,859
def get_operations(product_id): """Get ProductImageCreate operations Parameters ---------- product_id : str id for which the product image will be created. Returns ------- query : str variables: dict """ query = """ mutation ProductImageCreate($product: ID!,...
895e5b20dacf8883712a00d605778cc9ac22efa5
656,861
def _fabric_intent_map_name(fabric_name, intent_map): """Fabric intent map name. :param fabric_name: string :param intent_map: string AR intent map name :return: string """ return '%s-%s' % (fabric_name, intent_map)
08c10285e128bba1a6f2cff531f1973ae623b11c
656,868
def get_score_list(lines, start_index=0): """ :param start_index: Optional index where to start the score checking. :param lines: List of lines containing binary numbers. :return: List of scores for each line index, score is +1 for '1' and -1 for '0' e.g. line '101' gets score [1, -1, 1] an...
fc648f26a78e3614f024b257e54a6025f4341c76
656,869
def getFingerPrintOnCount(A): """ Input: Iterable having boolean values 0 or 1 Output: Count of number of 1 found in A """ count = 0 for i in A: if(i == 1): count += 1 return count
d5cfebcd440826c0502b46e0cc75cc434efb1c7b
656,870
def mix(color1, color2, pos=0.5): """ Return the mix of two colors at a state of :pos: Retruns color1 * pos + color2 * (1 - pos) """ opp_pos = 1 - pos red = color1[0] * pos + color2[0] * opp_pos green = color1[1] * pos + color2[1] * opp_pos blue = color1[2] * pos + color2[2] * opp_pos ...
62a6c6edd3c69aec77fc0674171c3f49a5cc4de5
656,873
import inspect def is_mod_function(mod, fun): """Checks if a function in a module was declared in that module. http://stackoverflow.com/a/1107150/3004221 Args: mod: the module fun: the function """ return inspect.isfunction(fun) and inspect.getmodule(fun) == mod
ab6d5c9e0d08be21057b41ce447be60b6bef1ad9
656,875
def fill_matrix(matrix: list[list[int]]): """ Return a new list of lists (matrix) where inner lists all have the same length. Inner lists that are short elements have the element 0 added. """ result = [] lengths = [len(row) for row in matrix] maxlen = max(lengths) for (i, row) in enumera...
19f97a46f7e2d7cc0b656a30def55451f7fa0d23
656,878
from typing import Tuple def all_subclasses(cls: type) -> Tuple[type, ...]: """All subclasses of a class. From: http://stackoverflow.com/a/17246726/2692780 """ subclasses = [] for subclass in cls.__subclasses__(): subclasses.append(subclass) subclasses.extend(all_subclasses(subcla...
6e5d77854a540e59f657f02e28576409e366739c
656,879
def milli_2_readadble(msecs): """Function: milli_2_readadble Description: Converts milliseconds into days, hours, minutes and seconds. Returns values with appropriate tags. Arguments: (input) msecs -> Milliseconds. """ data = msecs / 1000 seconds = data % 60 data /= 60...
b3d7137b8987321d161b1c8a51e89330a6c15387
656,882
def macTolist(hexMac): """ converts hex MAC string to list :param hexMax: MAC address to convert (string) :returns: list of MAC address integers """ return [int(i,16) for i in hexMac.split('-')]
bb0215987590f062d90e9354a519e29f6c809869
656,886
def reaction_splitter(reaction): """ Args: reaction (str) - reaction with correct spacing and correct reaction arrow `=>` Returns (list): List of compounds in the reaction Example: >>>reaction_splitter("c6h12o6 + 6o2 => 6h2o + 6co2") ['c6h12o6', '6o2', '6h2o...
cd20e8a3e0f15b236d49834b864513f7bbdb99e5
656,888
def expand_iupac(base: str, fill_n: bool=False) -> (str): """ Expand the IUPAC base :param base: the IUPAC base to expand :param fill_n: should we fill N or leave it empty :return: a string with all the primary bases that are encoded by the IUPAC bases """ if base =...
4e8f53ffddceca0eacacd8b7c1a70d22965ff3e3
656,890
def size(self): """ Return the size or length of the linked list. """ size = 0 node = self.head while node: size += 1 node = node.next return size
5d5f1ba5c385946ede96c6a503f310d12af91e7a
656,893
def to_loxone_level(level): """Convert the given HASS light level (0-255) to Loxone (0.0-100.0).""" return float((level * 100) / 255)
9004c0eaa2ade4c664d30a0c79288d2f11a1362a
656,894
def _getfield(history, field): """ Return the last value in the trace, or None if there is no last value or no trace. """ trace = getattr(history, field, []) try: return trace[0] except IndexError: return None
b81339c94f53aa757e25a115dc0068cb38a58dc9
656,895
import re def pct_arg_to_int(arg): """Parse a numeric string that represents a percentage in units of 0.1%. 1000 == 100%""" pat = re.compile("[0-9]{4,4}$") m = pat.match(arg) if m is None: raise ValueError(f"Invalid percent string: {arg!r}") pct = int(m.group(0)) if pct < 0 or pct > 1...
f398377e23b0bbe82b0eb8da05960ef70020f72d
656,899
import pathlib def themes_dir() -> pathlib.Path: """Return the directory where the themes are located.""" here = pathlib.Path(__file__).parent return here.joinpath('themes')
b7a9868387abe572af6babe9fa0120346914381c
656,900
from math import cos, pi, sqrt def linear_dist_sphere(radius: float, surf_dist: float, depth_a: float, depth_b: float) -> float: """ The purpose of this function is to find the actual, linear distance between the hypocenter of and earthquake and the bottom of a fracking well. It's a more general proble...
3439798e11805e5b6d60530211248d8df66cd9a5
656,901
def is_maximum_in_period(cube): """Check if cube contains maximum values during time period.""" for cell_met in cube.cell_methods: if cell_met.method == 'maximum' and 'time' in cell_met.coord_names: return True
5e8253e0ffc97f085fc72263e55cc3afae76b23d
656,904
def tuple_slice(tup, start, end): """get sliced tuple from start and end.""" return tup[start:end]
edea6d09bb017b8aa588855186e3543db35477e2
656,906
def defaultModel(t, alpha=3.0, beta=None): """ See ebisu's defaultModel function documentation. Note: This app's init_model function provides default alpha=2 instead of alpha=3.0, but it's a small difference, and this function goes with default alpha=3.0. """ if beta is None: beta =...
91609d34a239fefd2c17967da2ef145be25cf237
656,910
def reorder_coefficients(occupations, coefficients): """ Reorder the coefficients according to occupations. Occupated orbitals will be grouped at the beginning non occupied will be attached at the end :param occupations: list on integers (0 or 1) or list of Boolean :param coefficients: dictionary ...
f998f1a518c61e07a2d38124416aa43b224ff323
656,913
import io def _load_vectors(filename, head_n=None, open_encoding='utf-8'): """ 装载前N个词向量 :param filename: :param head_n: head n word vectors will be loaded :return: dict, {word: str => vector: float list} """ line_count = 0 data = {} try: fin = io.open(filename, 'r', encodin...
5744ac0d5922c6755f93e6896e47f1b240bac833
656,915
def profit(initial_capital, multiplier): """Calculate the profit based on multiplier factor. :param initial_capital: Initial amount of capital :type initial_capital: float :param multiplier: Multiplying factor :type multiplier: float :return: Profit :rtype: float """ return initi...
c47305991f9b66963248d329eef5bd1164dc28c0
656,916
def colors_objects() -> dict: """ Age of Empires II object colors for minimap. Credit for a list of objects goes to: https://github.com/happyleavesaoc/aoc-mgz. :rtype: dict """ food = (150, 200, 150) return { # FOOD 48: food, # BOAR 59: food, # BERRY BU...
09f543f5efa1d72c4f753a4c7e2aeb16ef5299eb
656,924
from typing import Optional def get_restore_path(restore_path: Optional[str] = None) -> Optional[str]: """Gets the path containing checkpoints from a previous calculation. Args: restore_path: path to checkpoints. Returns: The path or None if restore_path is falsy. """ if restore_path: ckpt_res...
31353578c602e2384c041ae96f01a15467302ec3
656,925
def get_manual_flags(level="all"): """Returns a list of content flags from the qualitative coding manual available at http://www2.psych.ubc.ca/~psuedfeld/MANUAL.pdf. Valid `level` inputs are: ["all", 1, 2, 3, 4, 5]. Other inputs will return an empty list.""" flags_for_1 = ["absolutely", "all",...
279075dff0036691ace32c7c8ffd56242448cedb
656,926
import math def bin_width_of_dec(num): """ >>> bin_width_of_dec(255) 8 >>> bin_width_of_dec(256) 9 """ return int(math.ceil(math.log(num + 1, 2)))
f71812bcc8e9206a113f152a8562fb4691ecfcbf
656,930
def in_range(x: int, minimum: int, maximum: int) -> bool: """ Return True if x is >= minimum and <= maximum. """ return (x >= minimum and x <= maximum)
4e3cb7808d0756e65da618dc141cf54ccd55447d
656,931
def pop(trace, instructions, reg): """Pop one item off the stack into reg""" instructions.append({"trace": trace, "op": "pop", "reg": reg}) return instructions
76b2a1e9370f228c8e438bf9778434d78a22c0f0
656,934
def modify_extra_section(yaml_content): """Modifies extra's section of the yaml_content. Args: yaml_content (str): Text representing yaml content Returns: [str]: yaml_content with extra's section modified """ yaml_content["extra"]["recipe-maintainers"] = ["prabhakk-mw", "diningPhil...
680717a8c5778598567a97f7f1bc82d38ae52499
656,935
def model_cs_id_list(cursor, model_name): """Get a list of ``cs_id``'s for a model in a NEPC database. Parameters ---------- cursor : cursor.MySQLCursor A MySQLCursor object. See return value ``cursor`` of :func:`.connect`. model_name : str Name of a model in the NEPC MySQL database...
6999ae8bb719bf71050bcc4cfa3f174670cef283
656,939
def reject_none(dict_obj: 'dict') -> 'dict': """Remove the item whose value is `None`""" return {k: v for k, v in dict_obj.items() if v is not None}
ec466e6d9d3f069d116ecfc90a314bf35ea99768
656,941
def mention_channel_by_id(channel_id): """ Mentions the channel by it's identifier. Parameters ---------- channel_id : `int` The channel's identifier. Returns ------- channel_mention : `str` """ return f'<#{channel_id}>'
ad827f59a1faf9a0a5c625460308085390208940
656,943
def to_sg(plato): """ Convert from plato to specific gravity """ return 1 + (plato / (258.6 - ((plato / 258.2) * 227.1)))
84892322d2289e93e48d73a724b1d4c2a5d6f185
656,944
def parse_version(version_string): """ Parse the version from a string The format handled is "<major>.<minor>.<patch>-<date> <commit>" Args: version_string: the version string to parse Returns: A 3-tuple of numbers: (<major>, <minor>, <patch>) """ # Remove commit from version...
903780f7b2fc2abd3ec78bcadf96b39252ec49bb
656,947
def _format_pval(p_value): """Helper function for formatting p-value.""" if p_value < 0.0001: return 'p < 0.0001' else: return 'p = {:5.4f}'.format(p_value)
3c78573f314bb1a0db55f7ae20540ac44ab359c1
656,956
import torch def covariance_diff_biased(X, Xk, SigmaHat, Mask, scale=1.0): """ Second-order loss function, as described in deep knockoffs manuscript :param X: input data :param Xk: generated knockoffs :param SigmaHat: target covariance matrix :param Mask: masking the diagonal of Cov(X,Xk) :par...
9c632769c09f05dceecccce71d91a95980917927
656,964
import torch import math def cal_GauProb(mu, sigma, x): """ Return the probability of "data" given MoG parameters "mu" and "sigma". Arguments: mu (BxGxC) - The means of the Gaussians. sigma (BxGxC) - The standard deviation of the Gaussians. x (BxC) - A batch of data ...
3237d9dbc89968804dfe66722ef62f86f5000c4d
656,970
def _lowercase_kind(value): """Ensure kind is lowercase with a default of "metric" """ if isinstance(value, dict): kind = value.get("kind", "metric").lower() # measure is a synonym for metric if kind == "measure": kind = "metric" value["kind"] = kind return value
8270b084cf8d14b62e8a9e20d5e4443756855e09
656,971
import torch def zdot(x1, x2): """Finds the complex-valued dot product of two complex-valued vectors. Args: x1 (Tensor): The first input vector. x2 (Tensor): The second input vector. Returns: The dot product of x1 and x2, defined as sum(conj(x1) * x2) """ return torch.su...
786ba11ff793bd8e5d05e5b53fcd74c969b81f5a
656,972
def reswrite(self, fname="", cflag="", **kwargs): """Appends results data from the database to a results file. APDL Command: RESWRITE Parameters ---------- fname File name and directory path (248 characters maximum, including the characters needed for the directory path). A...
b209b77fcffd451927327d52214209049236f805
656,974