content
stringlengths
39
14.9k
sha1
stringlengths
40
40
id
int64
0
710k
def trunc(text: str, max_len: int): """ Truncate a string to a maximum length """ return text[:max_len - 3] + '...' if len(text) > max(3, max_len) else text
b73263558aab3c5ce3242d68b57b9f0bd1eac9ce
568,090
def split(text, splitter): """ Split a string """ return text.split(splitter)
9ffba46528f33cded037a136dd44503e94160794
568,093
import yaml import collections import codecs def load_yaml(filename): """ load yaml file and return dict, order in the file is reserved :param filename: input filename """ yaml.add_constructor(yaml.resolver.BaseResolver.DEFAULT_MAPPING_TAG, lambda loader, node: collection...
935d121d664e58a9517dbe94c3c14d951dd578af
568,099
def swap_bits(original): """This function reverses the bit order for a single byte.""" original &= 0xFF reverse = 0 for _ in range(8): reverse <<= 1 reverse |= original & 1 original >>= 1 return reverse
8238bbaec2c921dda2965e7baaae0e40ca33fbbd
568,102
import click def bold(msg: str) -> str: """ Return a string wrapped in bold. """ return click.style(str(msg), bold=True)
9230f4dcafed1d80f6ca3c3513ab42fb16589461
568,104
def revnum_to_revref(rev, old_marks): """Convert an hg revnum to a git-fast-import rev reference (an SHA1 or a mark)""" return old_marks.get(rev) or b":%d" % (rev + 1)
af42c95d250d2cf6ef14521104c0c01d8dfed4e2
568,105
def pair_sum_in_array(array, x): """Check whether there is a pair of numbers in sorted array with sum = x.""" l = 0 r = len(array) - 1 while l < r: if array[l] + array[r] == x: return True elif array[l] + array[r] < x: l += 1 else: r -= 1 r...
86c7c52e054ac2b2f2e59ffb3559be2f385ecec0
568,108
def reverse_line(line: list) -> list: """ Takes a line of edges [(p0, p1), (p1, p2) ... (pn_m_1, pn)] and returns [(pn, pn_m_1), ... (p1, p0)], where the p's are (x, y) in map coordinates. Parameters ---------- line : list List of edges (p0, p1), where p0, p1 in R^2 Returns ---...
2b487510f636131559ab3e79a04abeb0213a24c3
568,112
def flipped_bits_64(length): """Produces a 1-bit bitmask of given length. >>> flipped_bits_64(3) 7 >>> flipped_bits_64(1) 1 >>> bin(flipped_bits_64(68)) '0b1111111111111111111111111111111111111111111111111111111111111111' """ return 2 ** min(length, 64) - 1
04a6f3c13f27ae4e6fa299b467c05a2dce46a218
568,114
def label_merge(current, fingerprint, new): """ Merge label dicts, and apply fingerprint Args: current -- current label object fingerprint -- fringerprint of current label object new -- request labels Returns: Merged Dict of labels """ labels ...
638fa7494598bec0ecc35b2e3cba17f41b7c03d7
568,117
import logging def get_loglevel(name): """Return the numeric correspondent of a logging level name.""" try: return getattr(logging, name.upper()) except AttributeError: raise ValueError('Invalid log level: {}'.format(name))
cc4e38134c1b56a9cbb13682b42b75441a7b63f4
568,118
import math import struct def ulp(x): """Return the value of the least significant bit of a float x, such that the first float bigger than x is x+ulp(x). Then, given an expected result x and a tolerance of n ulps, the result y should be such that abs(y-x) <= n * ulp(x). The results from this funct...
3675441d5bffc6072dff715b05b5d1391d167a3d
568,121
def search(g, v): """ Find all nodes that can be reached from v in the graph g. Returns a dictionary 'reached' such that reached.keys() are all nodes that can be reached from v and reached[u] is the predecessor of u in the search. Running time: O(# nodes + # edges) More specifically, O(# e...
99a26d6c23c95c33f4d6d6064d7bb5a63d2874bd
568,124
import fractions import math def reverse_bessel_polynomials(n, x): """Reverse Bessel polynomials. .. math:: \\theta_{n}(x) = \\sum_{k=0}^{n} \\frac{(n+k)!}{(n-k)!k!} \\frac{x^{n-k}}{2^k} """ ret = 0 for k in range(n + 1): c = fractions.Fraction( math.factorial(n + k),...
1564591cbb98301fc7c82e210ce1519399dcd3d3
568,125
def los_train(df): """ Calculates length of stay (admission to discharge) for the training dataset Adds len_stay to dataset Parameters ---------- df : main dataset Returns ------- df : main dataset """ df['len_stay'] = (df['DischDateHospProvSpell'] - df['StartDateH...
1985d4e5846d3504dac2778bff6c600d4120ae16
568,128
import math def block32_ceil_num_bytes(curr_len): """Returns the number of bytes (n >= curr_len) at the next 32-bit boundary""" num_blks = float(curr_len) / 4.0 num_blks_pad = int( math.ceil( num_blks )) num_bytes_pad = num_blks_pad * 4 return num_bytes_pad
4cd257aaee029479cfcad605aa6ab4f4ca6ba0f3
568,131
def argospm_package_name(pkg): """Gets argospm name of an IPackage. Args: pkg (IPackage): The package to get the name of. Returns: str: Package name for argospm """ to_return = pkg.type if pkg.from_code and pkg.to_code: to_return += "-" + pkg.from_code + "_" + pkg.to_co...
54f9224222091ccb5bcef5255be8e3cd6c6ab209
568,133
def policy_evaluation(policy, V, mdp, k=20): """Calculate the value function following a policy""" R, T, gamma = mdp.R, mdp.T, mdp.gamma # For horizon k for i in range(k): # For each state for s in mdp.states: V[s] = R(s) + gamma * sum([p * V[s] for (p, s1) in T(s, policy[s])...
31b449b6a91ba11060ef7fac4bb4cfacf6643bac
568,137
def computeLogSubTicks(ticks, lowBound, highBound): """Return the sub ticks for the log scale for all given ticks if subtick is in [lowBound, highBound] :param ticks: log10 of the ticks :param lowBound: the lower boundary of ticks :param highBound: the higher boundary of ticks :return: all the ...
87c04bc67b3db2cb83ebbc6ea5b2230561958422
568,141
import pathlib def find_full_path(root_directories, relative_path): """ Given a relative path, search and return the full-path from provided potential root directories (in the given order) :param root_directories: potential root directories :param relative_path: the relative path to find ...
8f30020becc72786820ef0a08a098355f7f5c80d
568,142
def as_list(x): """ Try to convert argument to list and return it. Useful to implement function arguments that could be scalar values or lists. """ try: return list(x) except TypeError: return list([x])
d3b8047209f63c86af47d0ebdd862def88d1f77f
568,145
def exception_redirect(new_exception_class, old_exception_class=Exception, logger=None): """ Decorator to replace a given exception to another Exception class, with optional exception logging. >>> >>> class MyException(Exception): ... pass >>> >>> @exception_redirect(MyException) .....
bef002fc5cf15ebc1517fd1ea9ca78fb2b4be3eb
568,146
def standard_score(x): """Standard Score The standard score, z-score, the distance from the mean scaled by the standard deviation. This scaling is useful for interpretation purposes as well. Parameters ---------- x : pandas.Series """ return((x-x.mean())/x.std())
1acdb233d6b532d5bb676e3f819ea1a626c02471
568,150
def check_seasonal_anime(anime: str, all_anime: list) -> bool: """ Function to check whether the anime is being aired this season. Horrible subs only keeps the torrent files of the anime in the current season only, on the nyaa.si website. :param anime: Name of the anime to check. :param all_anim...
776b118577a553d90932d9ef920f01192088ab22
568,151
def slurp(fn): """ Read text file into a string. """ f = open(fn) s = f.read() f.close() return s
c4b92fa2690a6fe01ef5e64d4f0d964ecc013d66
568,152
def get_checkpoints_elo(filename): """Get checkpoint epoch from its filename""" return int(filename.replace('_', '.').split('.')[-2])
015104304974be23b43acbc125267185bd833158
568,154
def ackermann(m_arg=0, n_arg=0): """Ackermann function is defined recursively by: ackermann(0,n) = n+1 ackermann(m,0) = ackermann(m-1,1) ackermann(m,n) = ackermann(m-1, ackermann(m, n-1)) for n,m > 0 """ # Model a function stack with a list, then # evaluate innermost ackermann function fir...
e073e138369790a43933d8858a519437210affed
568,155
def move_right(loc): """increments the location for rightward movement. """ return (loc[0] + 1, loc[1])
3b4d2fa17873973012bdab61fe8fcb4b000507e6
568,157
import torch def square_distance(pcd1, pcd2): """ Squared distance between any two points in the two point clouds. """ # via https://discuss.pytorch.org/t/fastest-way-to-find-nearest-neighbor-for-a-set-of-points/5938/13 r_xyz1 = torch.sum(pcd1 * pcd1, dim=2, keepdim=True) # (B,N,1) r_xyz2 = t...
9f4a7a6eb87b2267a1083f61ea17d9e8196a24c6
568,158
import csv def read_csv_to_list(data_file, delimiter=',', header=False): """ Reads file of values; did not use np.loadtxt because can have floats and strings @param data_file: name of delimiter-separated file with the same number of entries per row @param delimiter: string: delimiter between column va...
e12fb43282de4460a6b0f6de502104c6d6fbe954
568,160
import torch def to_one_hot(input: torch.Tensor, num_classes: int) -> torch.Tensor: """ Converts a given tensor to a one hot encoded tensor :param input: (torch.Tensor) Class number tensor :param num_classes: (int) Number of classes :return: (torch.Tensor) One hot tensor """ one_hot = torc...
396fb31104ab1157ccc51b9629ae1664a47b3326
568,171
def sort_items(items): """Sort the items in the list in ascending order""" return sorted(items)
d93f664ece7ea17b17d0a9dae1df3ca90891508b
568,173
import re def clean_ticker(ticker): """ Cleans a ticker for easier use throughout MoneyTree Splits by space and only keeps first bit. Also removes any characters that are not letters. Returns as lowercase. >>> clean_ticker('^VIX') 'vix' >>> clean_ticker('SPX Index') 'spx' """ ...
32d5bf305170e7f22a3ab075b266697a472f6ac4
568,177
def TFloat(val): """Checks if the given value is a float. """ return isinstance(val, float)
dc215fb8cc6c035b53db736fafab6eab62be0f68
568,181
def rearrange_data(xml_dict: dict, key_name): """ Converts a list of Python dictionary into just dictionary with key_name as the key name """ new_dict = {} # .values always return an array even for single item, so we get the first element dict_value = list(xml_dict.values())[0] for d in dict...
00e565a09ae951e201adcad91a3a7c3bc4127b6a
568,190
def PercentileRow(array, p): """Selects the row from a sorted array that maps to percentile p. p: float 0--100 returns: NumPy array (one row) """ rows, cols = array.shape index = int(rows * p / 100) return array[index,]
8cb837b146419c8ef79919529bbe8b3da7321ccf
568,191
def count_characters(file): """Count the number of characters in a text file. Args: file (str): Path of a fext file. Returns: int: Return number of characters in a text file. """ with open(file) as f: lines = f.readlines() return len(''.join([l for l in lines]))
2df34244087e603b69afe5993f2a21f171491104
568,192
import math def range_min_query(tree, query_low, query_high, low, high, pos): """ Query range on list input using its segment tree. tree: segment tree of list input low: range begin of input list high: range end of input list query_low: query range begin in input list query_high: query ra...
77c6e671512427345e04f41ce386b2ee8f7e417d
568,196
import ast def parse_values(values_string): """ Args: values_string: A Python-syntax string representing a list of strings. Returns: The list of strings, sorted. If parsing fails, returns None. """ values = ast.literal_eval(values_string) if isinstance(values, list): va...
2452f20c9030644490c6e017401c50a1c50c962f
568,199
def get_compiler_version(ctx): """Get the compiler version. Args: ctx: Rule context. Returns: String: Version string. """ return ctx.toolchains["@io_tweag_rules_haskell//haskell:toolchain"].version
087b0740545e3c6e862122aaa125387ca6c598f1
568,200
def add_parser(repos): """Adds a parser entry so that your addition shows up as conda skeleton my_repo And also provides the arguments that your parser accepts. """ my_repo = repos.add_parser( "my_repo", help=""" Create recipe skeleton for packages hosted on my-repo.org ...
687356a71d9839ce4cc30247b92ed01c42ea9bb6
568,201
from typing import Dict from typing import Any import random def add_noise_to_dict_values(dictionary: Dict[Any, float], noise_param: float) -> Dict[Any, float]: """ Returns a new dictionary with noise added to every key in ``dictionary``. The noise is uniformly distributed within ``noise_param`` percent ...
a767579d475f188a02fd43ec1d95e05091e5bb20
568,207
def torusGrad(x,y,z,rin,rout): """Return the derivatives of the Torus surface function with origin tangent to outer surface.""" dfdz = 4*(rin+rout+z)*(2*rin*(rout+z)+2*rout*z+x**2+y**2+z**2) dfdy = 4*y*(2*rin*(rout+z)+2*rout*z+x**2+y**2+z**2) dfdx = 4*x*(-rin**2+(rin+rout+z)**2+rout**2+x**2+y**2) ...
ccf2bdf90707a499845953643055765a0375be51
568,212
def recall(prediction, target, tolerance=0.07): """ Calculates the recall of a prediction, given the target. Arguments: prediction {list/NumPy Array} -- List of timings of predicted beats, in seconds. target {list/NumPy Array} -- List of timings of a...
c6bdb74aafa2ee552643b3056c023d844293583e
568,213
def to_repr(obj): """ Returns the result of calling repr() on `obj`. """ return repr(obj)
e42518cb369a539d2f00fbc45a921540403370e3
568,216
def get_max_inputs() -> int: """ Return maximum number of MIDI inputs. Returns ------- max_inputs : int Maximum number of MIDI inputs. """ max_inputs = RPR.GetMaxMidiInputs() # type:ignore return max_inputs
211ac1f926793e48267186ec46981170dafd7f1e
568,220
def safecolname(name): """ Given a CSV column name, return a name safe for use as an attribute name. Guards against dots in column names, and empty column names. """ name = name.strip() if not name: name = "empty_" name = name.replace(".", "_") return name
f414d3196a8bd3ba1b5b815444e5c21d90112a07
568,221
def key_number_to_key_name(key_number): """Convert a key number to a key string. Parameters ---------- key_number : int Uses pitch classes to represent major and minor keys. For minor keys, adds a 12 offset. For example, C major is 0 and C minor is 12. Returns ------- ...
d2b25291a5f6fd8c3d8ada50fa49fa8ed576657b
568,222
def checkRows(board: list) -> bool: """ Returns True if there is no repeating numbers in the rows. """ for row in board: numbersRow = row.replace('*', '').replace(' ', '') if len(numbersRow) != len(set(numbersRow)): return False return True
9b9817ee6a4b8ff86ccc6faa542be28e0b4f1fbe
568,226
def profit_map_to_sorted_list(profit_map, num_limit): """ Returns sorted descending list from profit map of names to values """ return sorted( [(name, profit) for name, profit in profit_map.items()], key=lambda x: x[1], reverse=True )[:num_limit]
9de35b7187424706be53a1f5eb0f2a05c6fe75cd
568,229
def break_chains(structure, m_id=0): """ Break the specified structure into its chains. In case the specified structure has multiple models, only the first one is returned. Parameters ---------- structure : Bio.PDB.Structure The structure to be broken into its chaines. m_id : i...
ba59ad00d9264bad4031e63ea62a16e073583267
568,230
def process_preamble(tok): """ process_preamble : list -> dict process_preamble(l) goes over the list l searching for the POMDP prb information and fills in a dictionary structure with that info. Preamble lines are removed from l (destructively). The returned dictionary includes the fields:...
916cfde57ff97474721247c79e3fb333b3756822
568,231
def get_audio_length(length): """ Get audio length from seconds to human easy readable format. hh:mm:ss --in case that is longer than a hour, otherwise-- mm:ss Arguments: :param length: integer -- audio length in seconds :return: string """ minutes, seconds = divmod(length,...
8f3dcfb4c16e930a02e124517b6e0ceb2868d145
568,233
def format_string(string, metadata, output_extension="", sanitizer=lambda s: s): """ Replaces any special tags contained in the string with their metadata values. Parameters ---------- string: `str` A string containing any special tags. metadata: `dict` Metadata in standard...
5bfb070b5ce156ced57b7707ad0ccc5e1d0a4684
568,234
def merge_options(global_conf, local_conf, key, *, keep_list_order=False): """Merge the conf using override: local conf is prioritary over global. If keep_list_order is True, list are merged global+local. Might have duplicate. If false, duplication are removed. """ global_keyed_conf = global_conf.g...
5bd6f1f1bece1bee8f05ada5c0b5f32a0a22f931
568,236
def _section(level, title, content, level_chr='=~'): """Output a ReST formatted heading followed by the content.""" return title + '\n' + level_chr[level] * len(title) + '\n\n' + content
b17f3371e272721857000c175b420fd5b0fff82e
568,237
def add_breaks(instring, above, below): """ Add line breaks before and after some text Input: instring -- text inside the breaks. above -- number of blank lines above the text below -- number of blank lines below the text Returns string with breaks added. """ outstr = '...
75c98a17c869f766e94c1959b7ee96b107c09589
568,243
def readable_yield(num, suffix="B"): """Return a human readable string of yield using si/metric prefixes Parameters ---------- num : int (or float) Integer of total number of bases suffix : str String to append to si/metric prefixes ['', 'k', 'M', 'G', 'T', 'P', 'E', 'Z', 'Y'] Re...
424e035090436f44a74dc983b179bc6ab765bec8
568,247
def is_two_words(w): """ Returns: True if w is 2 words sep by 1 or more spaces. A word is a string with no spaces. So this means that 1. The first characters is not a space (or empty) 2. The last character is not a space (or empty) 3. There is at least one space in the middle ...
792ccacd55bec9f7e44988b5c5342a11bbdac3a1
568,248
def _mock_login(*args, **kwargs): """Mocked login method.""" return True
df30ed0a2665a7e2de46041c800c74b458a5a39f
568,251
import math def MaxLevelRowCol(tile_size, max_wid, max_ht): """ w == h == 256 -> (0, 0, 0) w == h == 512 -> (1, 1, 1) w == h == 1024 -> (2, 2, 2) Args: max_wid, max_ht: maxWidth,maxHeight tile_size: w/h of a tile in pixels (must be ^2 and square) Returns: (max_level, max_row, max_col): maximum...
fdace592f0f3b149d099b8ad48f829bb054c1511
568,252
import re def cleanup_translation(input_str): """Cleans a translation for identity comparison. Removes superfluous whitespace. """ whitespace = re.compile('\s{2,}') cleaned_str = whitespace.sub(' ', input_str) return cleaned_str
4622c55323fe7fc8828a42cf56d962c5aea785e1
568,255
import importlib def get_class(class_name): """returns the class type for a given class name. Expects a string of type `module.submodule.Class`""" module = class_name[: class_name.rindex(".")] cls = class_name[class_name.rindex(".") + 1:] return getattr(importlib.import_module(module), cls)
d74dc38017af5cefe36562bec07cd34fa2ce7804
568,258
def dBm_to_watt(p_dBm): """ Convert power in units of dBm into Watt """ return 1e-3 * 10 ** (p_dBm / 10)
cacfaae7f1d41a102f8c5beab3db452d31c7c1c9
568,260
import re import threading def get_active_threads_name_with_prefix(prefix: str): """ Retrieves the threads name that starts with `prefix` and are active. """ prefix_regex = re.compile(f"^{prefix}") return [thread.name for thread in threading.enumerate() if prefix_regex.match(thread.name)]
dbcbb2ae1d652b9409a145e4a7cf8c20f9708ea5
568,261
def numeric_impute(data, num_cols, method): """ Performs numerical data imputaion based on the given method Inputs: data - (DataFrame) dataset with missing numeric values num_cols - (set) numeric column names method - (str) imputation type...
10b97e85f0ca8799ed7d50ffacbc0d3803f168c4
568,263
def is_player(xml_obj): """Return true if the XML object has a Player tag""" return xml_obj.tag == "Player"
3558dc0ba2bf5706e39a18f696f7ad57d04c1f98
568,268
def is_namedtuple(cls: type) -> bool: """Determines if a class is built from typing.NamedTuple.""" return ( isinstance(cls, type) and issubclass(cls, tuple) and hasattr(cls, '_fields') and hasattr(cls, '__annotations__'))
b3e6f0c6b6b531c4eceba202933bee7fe9895614
568,269
def get_account_info(connection_string): """Get Account info from a connection string.""" account_name = connection_string.split(";")[1].split("=")[-1] account_key = connection_string.split(";")[2].replace("AccountKey=", "") return (account_name, account_key)
1046e9bac30216052c16e693fa878abe3bd78b5b
568,270
def key_split(s): """ >>> key_split('x-1') 'x' >>> key_split('x-1-2-3') 'x' >>> key_split(('x-2', 1)) 'x' >>> key_split(None) 'Other' """ if isinstance(s, tuple): return key_split(s[0]) try: return s.split('-', 1)[0] except: return 'Other'
72e8a0df4658acf66f21b1e6cb7be116672581e4
568,273
def dict_to_numpy(fold_dict, main_data): """Given a dict representing the indices from the dataset each set (LUVT) has, return numpy arrays containing the rows from the dataset for each such set. """ LX = main_data['X'][fold_dict['L']] Ly = main_data['y'][fold_dict['L']] UX = main_dat...
1837550c64e1f7ff9b575ef540d46f152c1dabcb
568,279
def read_bed_coords(bed_file, seq_len): """Return BED regions as a list of coordinate tuples, extended to a specified length.""" seqs_coords = [] for line in open(bed_file): a = line.split() chrm = a[0] start = int(float(a[1])) end = int(float(a[2])) # determine sequence limits mid = (...
84ed9694bc5ea918e3b49a4fb07c5b128180c5e2
568,281
def _nx_to_dnx_layout(center, scale): """ This function translates a center and a scale from the networkx convention, [center - scale, center + scale]^dim, to the dwave_networkx convention, [center, center-scale] x [center, center+scale]^(dim-1). Returns ------- dnx_center : float The t...
9b01f66c38b25520be5d73b1038bf1bd238aa584
568,284
def dict_subtract(a, b): """Return the part of ``a`` that's not in ``b``.""" return {k: a[k] for k in set(a) - set(b)}
10303cff3939eecd04a87b92134ecd5a5dac204b
568,285
def estimate_u_value(d_i): """ Estimate U-value (in W/mK) depending on inner pipe diameter d_i. Estimation based on values by: U-values: C. Beier, S. Bargel, C. Doetsch, LowEx in der Nah- und Fernwaerme. Abschlussbericht, 2010. Parameters ---------- d_i : float Inner diameter of pip...
4cba9f0c0c7d10c3e26420b0acc9b840c7f2e798
568,289
def unrationalize(fraction): """Return a floating point representation of the input rational fraction string""" (numerator, denominator) = fraction.split("/") return float(numerator)/float(denominator)
981905d81be458b6d48758f0d779f92bb13739dc
568,292
def get_fee(tx): """ Takes tx object and returns the transaction fee in satoshis """ outputs = [output['value'] for output in tx['out']] try: inputs = [input['prev_out']['value'] for input in tx['inputs']] except KeyError: # This happens when there's a coinbase transaction inputs...
0d4423988c49a387436a5aa9e06e525f5aab4b9f
568,293
def get_image_frames_2d(img, regions, regionlist=None): """Split out the arrays for the serial_overscan, parallel_overscan, and imaging regions Parameters ---------- img : `ImageF` Image Data regions : `dict` Bounding boxes for the regions regionlist : `list` or `None` N...
73d70bcea8e46bcbc981fd41db6a317c6e073091
568,295
from typing import List def contains_negative(span: List[int], offset: int) -> bool: """ Checks if a recombined span contains negative values. """ for idx in span: if idx - int(offset) < 0: return True return False
c9f77c40ff1ba7d1cc7cee366e614c749a53f030
568,297
def calc_density(temp, salt): """ Compute density of sea water according to Fofonoff, N.P. & Millard, R.C. (1983). "Algorithms for Computation of Fundamental Properties of Seawater". Unesco Techical Papers in Marine Science. :param temp: Temperature in degrees Celcius :param salt: Salinity in P...
c6fabfe74669323dc33e1964dc03aad85ce2f2c3
568,299
import string import random def random_str(size=16, possible=string.ascii_letters + string.digits): """ Returns a random string from the possible characters. """ return "".join(random.choice(possible) for _ in range(size))
bcdf886b473eaf22434fa7da056a239f4df74861
568,300
def carrier_consumption_max_constraint_rule( backend_model, carrier, node, tech, timestep ): """ Set maximum carrier consumption for demand, storage, and transmission techs. .. container:: scrolling-wrapper .. math:: \\boldsymbol{carrier_{con}}(loc::tech::carrier, timestep) \\geq ...
9b9b42abf5fcefdbd5513ae77b0e92ff41e9edca
568,301
import functools def union_of_non_none_sets(sets): """ Helper function, takes a list of [set or None] and returns the union of all non-None elements. """ return functools.reduce(lambda x, y: x.union(y), filter(lambda z: z is not\ None, se...
666a71b8ed2e36f5060b900f3cd1140d8cd36f80
568,302
def get_board(size): """Returns an n by n board""" board = [0]*size for ix in range(size): board[ix] = [0]*size return board
f16a10a7ba327c5893855540d5ce21283ecae6bb
568,304
def get_index(idx_list1, idx_list2, idx_list3): """Function to get index list Function 'get_index' returns the common value between the 3 different lists Args: idx_list1 (list): list of indexes (integer) idx_list2 (list): list of indexes (integer) idx_list3 (list): list of indexes ...
0c80377a6e9204fdbde08cd7c0c5f155c18e56c1
568,305
def capacity_cost_rule(mod, g, p): """ The capacity cost of projects of the *gen_ret_lin* capacity type is its net capacity (pre-specified capacity minus retired capacity) times the per-mw fixed cost for each of the project's operational periods. """ return mod.GenRetLin_Capacity_MW[g, p] * mod....
ad7dac79d69c40ee9c69e605f20237c67392415b
568,307
from itertools import chain, repeat import _locale def _group_lengths(grouping): """Convert a localeconv-style grouping into a (possibly infinite) iterable of integers representing group lengths. """ if not grouping: return [] elif grouping[-1] == 0 and len(grouping) >= 2: return ...
8bd025bfeef7cb906168f87e94404140eae5d86a
568,309
def check_input_dir(indir): """ Check that the given indir doesn't have a trailing `/`. Possibly useless if better way to handle this in Python. Parameters ---------- indir: str or path A string or path that might (or not) end with a `/` Returns ------- indir: str or path ...
d942057b44ff9a36768919238f633e4cf77be464
568,314
def escape(str): """Precede all special characters with a backslash.""" out = '' for char in str: if char in '\\ ': out += '\\' out += char return out
732893d6ece7ed3ca1cfc1e0fca5eee873458dfe
568,315
import collections def builtin_mode(s): """Mode of a sequence.""" sv = s.simplify().value c = collections.Counter(sv) return c.most_common(1)[0][0]
fc7878d9241b9b6f63cb1d5215b9c40ff600578e
568,316
def file_type(file_name): """ Returns the file type from a complete file name If the file doesn't have a file type, return "file" """ if "." not in file_name: return "file" return file_name.split(".")[-1]
9162629739ccce609a06e4d3ac8d79a42a8f8011
568,317
import torch def sort_boxes(boxes, labels): """Sort boxes and labels by area in descending order.""" box_areas = (boxes[:, 2] - boxes[:, 0]) * (boxes[:, 3] - boxes[:, 1]) _, box_inds = torch.sort(box_areas, descending=True) boxes = boxes[box_inds, :] labels = labels[box_inds] return boxes, lab...
ef2d4bb6e7778860cb18501017a022fef1b0beb0
568,318
def _filter_by_day_of_week(data, day_start, day_end): """Filter data by day of week to get: day_start <= data.index.dayofweek <= day_end It follows from the above that day_start should be <= day_end. Note from the Pandas documentation that Monday = 0, Sunday = 6: https://pandas.pydata.org/pand...
5d9ae40a586e34347248b85583ee47a3e83348a1
568,321
import requests import yaml def hosted_assemblies(string='all'): """Get prefixes of hosted datasets from BTK API.""" btk = "https://blobtoolkit.genomehubs.org/api/v1/search/%s" % string response = requests.get(btk) hosted = set() if response.ok: data = yaml.full_load(response.text) ...
4b27685a205637cf6bd793d2c8968c0ca790f5ad
568,325
def lte(value, arg): """Returns a boolean of whether the value is less than or equal to the argument. """ return value <= int(arg)
9e9848c3a1d0aae2dbe3bbfc29f1722b019e4143
568,329
def parse_colon_speparated_lines(lines): """ @summary: Helper function for parsing lines which consist of key-value pairs formatted like "<key>: <value>", where the colon can be surrounded by 0 or more whitespace characters @return: A dictionary containing key-value pairs of the ...
1eff191668c832d5f2e5fa17edb2bcb0acd2394d
568,330
def update_key_value(contents, key, old_value, new_value): """ Find key in the contents of a file and replace its value with the new value, returning the resulting file. This validates that the old value is constant and hasn't changed since parsing its value. Raises a ValueError when the key cannot...
1caec09ed7a98bb254ff7d3b7ec981f8c84c7253
568,331
import binascii def decode_domain(encoded_domain): """Return a domain from hex.""" return binascii.unhexlify(encoded_domain).decode('idna')
3d61d3f7b9cf2f181caac5e8e155dba810a7ab21
568,332
import math def get_param_score(param, max_value, weight=1): """Return paramater score given its current value, max value and parameter weight.""" return (math.log(1 + param) / math.log(1 + max(param, max_value))) * weight
e614f2f27bc354c1fa1e9ba7a8bb0025bb4aac9f
568,336
def causal_parents(node, graph): """ Returns the nodes (string names) that are causal parents of the node (have the edge type "causes_or_promotes"), else returns empty list. Parameters node - name of the node (string) graph - networkx graph object """ node_causal_parents = [] if list(gr...
95607b55687237645c0bc2fcf40e07b51e1aedae
568,339