content
stringlengths
39
14.9k
sha1
stringlengths
40
40
id
int64
0
710k
def rec_fact(num): """rec_fact(int) -> int Recursive function which takes an integer and computes the factorial. >>> rec_fact(4) # 4*3*2*1 = 24 24 """ if not isinstance(num, int): raise TypeError("Must be a positive int") if num == 0: return 1 return num * rec_fact(nu...
636b81145ac424c1d680bb95470c91773d37e7bd
592,776
def generate_baseline(_iterable, window_length): """Generate a sliding baseline of an iterable Creates a list of sliding baselines for the iterable. e.g. if you pass in a list of len==5 with a baseline length of 2, we will generate: [ [elem0 (first element), elem1, elem2], [elem1, elem2...
88369760d6689948dc70ba248834be68e275e1af
592,778
def date_to_filename(base_path, raw_date_string): """ given some date like MONTH/DAY/YEAR, make a filename like base_path/YEAR/MONTH/DAY.md """ raw_date_string = raw_date_string[:-1] month, day, year = raw_date_string.split("/") relative_path = "{}/{}/{}.md".format(year, month, day) return b...
70445e19a5aedfe69690a8e04af47941ce0fb25b
592,779
def convert_progress_bar(value): """ Converts float value in database to progress percentage use in progress bar. Args: value (float): The float value that you want to convert Returns: float: The converted value that will use in progress bar. """ if type(value) is not float: ...
4546b4ca2c709ab6a442583eb550c50d1e9f4b98
592,780
def collatz(n): """ The Collatz sequence generating function: f(n) = (1/2)n if n is even, or 3n + 1 if n is odd """ return int(n / 2) if n % 2 == 0 else 3*n + 1
58b68c63f17c72a1097a49456be5135ed85c48b4
592,781
def spline_grid_from_range(spline_size, spline_range, round_to=1e-6): """ Compute spline grid spacing from desired one-sided range and the number of activation coefficients. Args: spline_size (odd int): number of spline coefficients spline_range (float): one-side...
0e5a100e644786a33ba92172d2b0ccaf6ef4971c
592,789
import unicodedata def utf8toascii(text): """ Converts UTF8 text to ASCII """ return unicodedata.normalize('NFKD',text).encode('ascii','ignore').decode('ascii')
656be6b5ca80f2628392289f36dbabecbf7014bc
592,790
import pickle def save_object(obj, filename): """ Write object as a pickle Args: obj: any object filename: output file """ with open(filename, 'wb') as output: pickle.dump(obj, output, pickle.HIGHEST_PROTOCOL) return 0
d7cee695fef5e3f599876d1c5bc1c2d63204b291
592,794
def resolve(parent, name): """Resolve a wildcard glob and return first result.""" return list(parent.glob(name))[0]
459db1309d35b15638d15d89c9d9c2e6cd54c964
592,806
def findFirstOfMonth(date): """change date to the first of the following month. If the date already is the first of the month, no change""" if date[2] == 1: return date date[2] = 1 date[1] += 1 if date[1] > 12: date[1] = 1 date[0] += 1 return date
cb86e884a41a3adc22f9347ad1f56d9016814008
592,808
def get_post_dominator_sets(cfg): """Computes the set of post-dominating nodes for each node in the graph. A node i is post-dominated by another node j if every path from i to the exit includes j. Args: cfg: The control flow graph to compute the post domination matrix for. Returns: A dict with the p...
741947c069b6e4c1a1298220cd56dac806ed5653
592,810
import statistics def graphprot_predictions_get_median(predictions_file): """ Given a GraphProt .predictions file, read in site scores and return the median value. >>> test_file = "test-data/test.predictions" >>> graphprot_predictions_get_median(test_file) 0.571673 """ # Site scores ...
94178f384663e8a9c0dbcee6eff9aefaf1f36f9b
592,813
import torch def masked_precision(input, target, nodata=None): """Calculates classification precision for a batch of images. Parameters ---------- input : tensor, shape (B, 1, H, W) batch of images with predicted classes target : tensor, shape (B, 1, H, W) batch of images with target ...
6e45ed174c40235ea38c0ba0523c2ddbc83e590f
592,814
def read_input_files(input_file: str) -> list[str]: """ Extracts a map area from the input file. The map area is a list of rows where each row is a string representation of that particular row. """ with open(input_file) as input_fobj: area = [line.strip() for line in input_fobj] retu...
cbf0aedf88586c1885b1e88bb3115e7ad1c45798
592,815
def A_real_dist(Q_distcooler, Kt_real_dist, deltaT_diff_dist): """ Calculates the real heatransfer area. Parameters ---------- Q_distcooler : float The heat load of distilliat cooler, [W] , [J/s] deltaT_diff_dist : float The coefficient difference of temperatures, [degrees celciu...
80bff68f54a5ec1094207e295fa0195c6c2e6c75
592,819
from pathlib import Path def get_home_dir() -> Path: """Determine the current user's home directory. :return: The current user's home directory :rtype: ~pathlib.Path """ return Path.home()
97e357e475adbccc3306aa45f70ba9bb8cfaa0e8
592,820
def parse_season_day_period(time_id): """Returns the season, day and period value from an id Argument -------- time_id : int An integer representing the interval count Returns ------- tuple A tuple of ``(season, period)`` Notes ----- time_id = (168 * (season - 1...
c193c0f2f60a366a857f14fc736769ed8aaa747e
592,825
import six def _unindexed_properties(ndb_model): """Return list of unindexed properties for the ndb Model.""" properties = [] for name, prop in six.iteritems(ndb_model._properties): if not prop._indexed: properties.append(name) return properties
cbc6442a4768d8a362fdc9dd3293fd7131e8f6da
592,827
def isEven(x): """ Returns True if number x is even :param x: :return: """ if x % 2 == 0: return True else: return False
01bad482c4d91e1572dc4e73f8d741b1fe6b5d9d
592,832
def get_mode(operation, i): """ >>> get_mode(101, 0) 1 >>> get_mode(1, 0) 0 >>> get_mode(1101, 0) 1 >>> get_mode(1001, 0) 0 >>> get_mode(1101, 1) 1 >>> get_mode(1001, 1) 1 """ if len(str(operation)) > i + 2: mode = int(str(operation)[-i-3]) el...
e5e2571c090c32176a6adc5f4370bd349268522b
592,836
def find_lowest_template(curr_node, d): """Function to find the lowest (most general) substructure/reaction rule in the tree. Parameters ---------- curr_node: ehreact.diagram.diagram.Node Node for which to find the lowest template. d: ehreact.diagram.diagram.Diagram Hasse diagram....
ea587ef33eb2d8f90ce92799d2b38482afd9e875
592,838
def decode(s): """ Run length decoding (str) -> str >>> decode('1B5W1B4W') 'BWWWWWBWWWW' """ ret = '' sizeStr = '' for ch in s: if ch.isalpha(): if sizeStr: ret += ch * int(sizeStr) sizeStr = '' else: sizeSt...
6f092db0a6ab5058abe2165a6adb227b7865c097
592,840
def check(row): """ This function is used to check if any illegal format exists. :param row: str, containing 4 letters with spaces between. :return: True, if format correct. False, if illegal format. """ # Check the length. if len(row) != 7: return False # Check whether the letters and spaces are in right ord...
0b5525a0fa576cdffc9190ae1c348e02042ee531
592,843
import torch def normalize_rgb(raw_rgb, scaled_sigmoid): """Normalizes raw RGB values from the network. Args: raw_rgb: [R, S, 3] tf.float32. Raw RGB values. scaled_sigmoid: Whether to apply scaled sigmoid. Returns: rgb: [R, S, 3] tf.float32. Normalized RGB values. """ # E...
0bf193dc5984d4971dec94893a198c0d278af46c
592,844
def get_subgraph(graph, center, radius=1): """ Extract a subgraph around center Params: graph an igraph Graph object center label or id of center node radius (int) Maximum unweighted distance of neighbors to include """ neighbors = {graph.vs.find(center).index} # Expa...
7e5ac0888c23d7d421aa63c20e0e9b3f31d0a286
592,848
def recvall(s, n): """Receive n bytes from a socket, or fail.""" rv = bytearray() while n > 0: d = s.recv(n) if not d: raise IOError('Unexpected end of stream') rv.extend(d) n -= len(d) return rv
2b63ae172dd6f7e2877fdb5db05d11282c7563c0
592,849
def __get_version(versions, build_version, is_version): """Evaluates entered build_version and returns if supported Args: version: A dictionary containing a list of supported build version. build_version: The user entered build_version. is_version: Boolean: Whether the provided build...
89485b3a47cf5014c867db139c0806fa7b7585ae
592,851
def get_configurations(client, db_rid=None, name=None, type_name=None, status="active", company_identifier=None, serial_number=None, verbose=False): """ :param client: Pass the authorised connectwise client object :type client: Object :param db_rid: Configuration ID :type db_rid: Integer :param...
b88d825e6e362164a705808cbb964a9048e56a38
592,853
def validateData(response): """validates that NASA API response returned data Args: response (Dict): custom response from API Returns: Boolean: True is data was returned False otherwise """ """ this is NASA's service response when they have no data for the day { "code": 404, ...
15acf5aad7416b95007d01357b4e59aa840645b6
592,855
import re def find_substring_or_regex_in_lines(substr, lines): """Return True iff substr can be found in any line of lines.""" prog = re.compile(substr) return any(prog.search(line) for line in lines)
e7202064a863b19b5cc38e6a0b11ccb9ba205144
592,861
import collections from pathlib import Path def create_uniprot2interpro_dict(filepath, uniprot_ac_list): """ Creates a dictionary mapping UniProt ACs to InterPro domains. Parameters ---------- filepath : the file path to a (filtered) InterPro map file. uniprot_ac_list : list A list of...
a0e498d90f6adf302681f94db050f1bc953c4885
592,863
def _format_authors(paper): """Format the first three authors of a paper, append 'et al.' in case there is more than 3.""" if paper.author is not None: author = " & ".join(paper.author[:3]) if len(paper.author) > 3: author = author + ", et al." else: author = "-" ...
3b90337823d9336f93f3ff1bf099a6c962b8fb17
592,865
def abs_cap(val, max_abs_val=1): """ Returns the value with its absolute value capped at max_abs_val. Particularly useful in passing values to trignometric functions where numerical errors may result in an argument > 1 being passed in. Args: val (float): Input value. max_abs_val (fl...
f461c4f819fd1d7856aa0e9ac07bd2f25c75176a
592,867
def sort_dict_by_value(inputdict): """Sort a dictionary by its values Args: inputdict: The dictionary to sort (inputdict) Returns: items: The dictionary sorted by value (list) """ items = [(v, k) for k, v in inputdict.items()] items.sort() items.reverse() items = [k for...
ea551e9ac25f2de5b253e592bf39f66f375d9249
592,871
import urllib3 import re def _request_exc_message(exc): """ Return a reasonable exception message from a :exc:`request.exceptions.RequestException` exception. The approach is to dig deep to the original reason, if the original exception is present, skipping irrelevant exceptions such as `urll...
ad4ed8a70b8a19607a19d7f1345d0e1c3da11b6a
592,873
def split_address(addr): """Split an address into path and filename. """ addrlist = addr.split('/') return ('/'.join(addrlist[0:-1]), addrlist[-1])
5c41dce5faf6d127cc198316ffbeac200d3d9d74
592,875
import re def is_area_chair_from(role): """ Compute if the role description corresponds to a area chair, and also return the track(s) in which they are an area chair Usually, ACs have 'Meta Reviewer" in their role description, e.g. "committee:Summarization:Meta Reviewer" """ if 'Meta Revi...
74019ef0669e75e01b392a81d07acec213ed99b4
592,879
def clip_data(x_s, y_s): """ In the case that there are different number of iterations across learning trials, clip all trials to the length of the shortest trial. Parameters: x_s - A list of lists of total timesteps so far per seed. y_s - A list of lists of ...
c8622fb254caea39f1e47e26332d89ca35a445b8
592,884
from typing import Union def _IsOptional(cls: type) -> bool: """If the cls looks like an Optional[Any] type.""" return (hasattr(cls, '__origin__') # pylint: disable=comparison-with-callable and cls.__origin__ == Union and len(cls.__args__) == 2 and cls.__args__[1] == type(N...
35fa6da98f56acc8c8fb5d529a720a58016c3209
592,890
def _passes_plus_germline(rec): """Check if a record passes filters (but might be germline -- labelled with REJECT). """ allowed = set(["PASS", "REJECT"]) filters = [x for x in rec.filter.keys() if x in allowed] return len(filters) > 0
a048dc30d5e4fa616bee44dc3aaff46ced11ce9a
592,894
def var_is_rare(variant_data, threshold): """Check if variant is rare, as defined by the passed cutoff :param variant_data: A GeminiRow for a single variant. :type variant_data: GeminiRow. :param threshold: Allele frequency rarity threshold. :type threshold: float. :returns: bool -- True or Fal...
b08871a0033de0b5511e63d1d69e15fdbaa1750c
592,896
def is_subset(l1, l2): """Checks whether list l1 is a subset of list l2""" for x in l1: if x not in l2: return False return True
8189d161947b95097887e5df234dd1c71b3b71a3
592,902
def pyfqn(obj) -> str: """ Get the fully-qualified name (FQN) of an object's type. :param obj: the object :return: the fully-qualified type name """ return f"{obj.__class__.__module__}.{obj.__class__.__name__}"
5c5157b256f993fa7c0d8e6b3f5a0579b9fec3b4
592,904
def allnamesequal(name: list) -> bool: """ Verify all names are equal. Parameters ---------- name : list of strings all the names Returns ------- all : bool True if all the names are equal, False otherwise """ return all(n == name[0] for n in name[1:])
4c32ddd1b4f1c697f2a5406fe559777c79646304
592,908
def unique(items): """ Python's equivalent of MATLAB's unique (legacy) :type items: list :param items: List to operate on :return: list """ found = set([]) keep = [] for item in items: if item not in found: found.add(item) keep.append(item) retur...
624f272b0536308d3935171af6fd921d21e4498b
592,909
import pkg_resources def names(namespace): """Return extension names without loading the extensions.""" return [entry.name for entry in pkg_resources.iter_entry_points(namespace)]
2a65bf9869c5abd6e7e6a9d66bce9418176a1591
592,912
def dict_to_list(dict, header): """ Convert a dictionary into a list in the order specified by the header. Args: dict (dict): dictionary containing data from an API request header (str): list of fieldnames present in the data Returns: list: contents of dictionary in the order s...
f99dbfed8cced6a14194a932e9a48a5a15aba2b3
592,915
def camelcase(inp): """ Convert input into CamelCase variable """ return ''.join(i for i in inp.title() if not i.isspace())
7b1a52fd1fa8cc97e4ce5703ec6f00a2d375be56
592,916
import re def get_package(fname): """ get the package this java file is in """ with open(fname, "r", errors = "ignore") as infile: lines = infile.readlines(); for line in lines: m = re.search('package\s+(.+?);', line); if m is not None: package =...
a955c8200d2b2684f0795a4e0fbb2e6da85b4397
592,918
def volmesh_vertex_lift(volmesh, vkey, target_xyz, hfkeys): """Duplicates and lifts a vertex, then creates cells using the vertex halffaces and the duplicated vertex. Parameters ---------- volmesh : VolMesh A volmesh object representing a polyhedral force diagram. vkey : int The key...
a835e19167c15f914ff7e41d0bc811b797044c7a
592,920
def dictToStyleText(style_dict): """ Convert a dictionary into an SVG/CSS style attribute """ style = '' for key in style_dict: style += "%s:%s;" % (key, style_dict[key]) return style
d2f3c281ae133f1523aac93493321f59e2939158
592,921
def find_subclasses_recursive(baseclass, subclasses = None): """ Find subclasses recursively. `subclasses` should be a set into which to add the subclasses """ if subclasses is None: subclasses = set() if not isinstance(baseclass, type): raise ValueError('Need a class, but received: ...
4ca182064e40c7529c8e762a9e404bafc0490a84
592,922
def chmod(mode, file_name, options=""): """ Applies the chmod command. :type mode: string :param mode: New mode of the destination. Typical examples are: a+r to give read permissions to everyone, a+rx to give execution and read permissions to any user, etc. :type file_name: string :param f...
630fc0845dd1d9275c540c15cf23255f06e90b96
592,924
def spectrum_statistics(zipped_data): """ calculates highest intensity and sum of intensities Parameters ---------- zipped_data: tuple tuple of data containing intensities and masses Returns ------- tuple highest intensities and sum of intensities """ high...
ea499eb7ac1b467660a63e6e3ca68ecb931baac3
592,926
def COL_DISTINF(col1, col2): """ Computes inf-distance between two RGB vectors, i.e. = max(abs(r), abs(g), abs(b)) """ r, g, b = (col1[i] - col2[i] for i in range(0, 3)) return max(abs(r), abs(g), abs(b))
7edad3a3425c9795d220e79219137a13d8befd92
592,927
def to_camel(string: str) -> str: """ Converts string to camel-case format. :param string: string to be camel-cased :return: camel-cased string """ words = string.split('_') return ''.join(words[0] + word.capitalize() for word in words[1:])
28a5240d0955088599538c9ba094e62892295ba9
592,929
def cube(a: int) -> int: """Function to cube a number""" return a ** 3
52c5934209f25676d4f9e85814ea7837dd532daa
592,931
import pickle import base64 import json def im2json(im): """Convert a Numpy array to JSON string""" imdata = pickle.dumps(im) print(len(base64.b64encode(imdata).decode('ascii'))) jstr = json.dumps({"body": base64.b64encode(imdata).decode('ascii')}) return jstr
5fe6cdcac7d23e8a46a915ce2ee79c928cb65715
592,932
import random def Seed(seed=None): """Seed random for reproducible command sequences. Args: seed: optional long int input for random.seed. If none is given, one is generated. Returns: The given or generated seed. """ if not seed: random.seed() seed = random.getrandbits(64) ran...
a854f1f7a39e400ba504ea48c3bac6cdd93abc15
592,933
def get_terminal_title(editor): """ Return the terminal title, e.g.: "filename.py (/directory) - Pyvim" """ eb = editor.current_editor_buffer if eb is not None: return '%s - Pyvim' % (eb.location or '[New file]', ) else: return 'Pyvim'
576544bf269a9daea7b7caee67a218940b51cfed
592,934
def bbox_to_pos(bbox, mode): """Convert a bounding box to an x-y position Parameters ---------- bbox : list Bounding box from pdf_reader layout object, which is a list of four floats [x0, y0, x1, y1] mode : str Options are combinations of top/center/bottom and right/center/l...
b1d83760cab88709b885d861ad8df3ebfe7ac9ea
592,936
def array_to_concatenated_string(array): """DO NOT MODIFY THIS FUNCTION. Turns an array of integers into a concatenated string of integers separated by commas. (Inverse of concatenated_string_to_array). """ return ",".join(str(x) for x in array)
723894055c5549deb528f791bedb0b0bf464db19
592,940
def remove_trailing_slash(ze_url): """Remove the trailing slash""" if ze_url and ze_url[-1] == '/': ze_url = ze_url[:-1] return ze_url
f46390dabd1e5ca0c1f3c09798c420d4af5c201e
592,942
def _public_pca_ht_path(subpop: str) -> str: """ Get public pca loadings path. :param subpop: Can be empty ("") -> global, "eas" or "nfe" :return: Path to release Table """ subpop = f".{subpop}" if subpop else "" return f"gs://gnomad-public/release/2.1/pca/gnomad.r2.1.pca_loadings{subpop}.h...
0f50fce2bca3df50fa16e4dce88e36e46ebe82a2
592,944
from pathlib import Path def get_ods_dir(directory=Path.home()): """Get path to save downloads, create if it does not exist. Keyword arguments: directory -- Path to save downloads (defaults to user home path) """ folder_path = Path(directory) if not folder_path.is_dir(): print("\nCrea...
f2beaca0eb7d4f31adc3b1857f6cffbb8e370424
592,945
def apply_label(node): """Return label of apply node.""" return node.op.__class__.__name__
bd3b20f744440771375678b25269bf24071780ac
592,948
import math def std_polar(rho, phi): """ To standardize a polar variable. By standard form, it means :math:`\\rho>0, -\\pi<\\phi<\\pi`. :param rho: Real number :param phi: Real number :return: ``rho``, ``phi`` """ if rho < 0: rho = -rho phi += math.pi while phi < -math...
318abf92571760b7ba86c88d86b675c22e8740eb
592,950
def letter_to_color(letter): """ Transfer a letter into a color A corresponds to red. B corresponds to yellow. C corresponds to green. D corresponds to blue. :param letter: an input letter :type letter: string :return: a color :rtype: string """ if letter == "A": return "rgb(...
a9cace283661d8a3dd488e4daa56619b257648e1
592,951
def mag2flux(mag,zp=25): """ Convert magnitude to flux """ f = 10**(2/5*(zp-mag)) return f
48d535aa643ab6d03d558b75ba9340ed23f80a50
592,952
def make_samples_dict(sample_ids): """helper function for get_sample_pairs() - dict of sample id with r1/r2 value pairs as [str, str]""" samples_dict = {} for sample_id in sample_ids: samples_dict[sample_id] = ["", ""] return samples_dict
2cc25d1c0acd6969a39e305a613aaff75122314c
592,955
def auto_downsample_ratio(h, w): """ Automatically find a downsample ratio so that the largest side of the resolution be 512px. """ return min(512 / max(h, w), 1)
8ce7c9961d895aac9812c62672708486c1d2d047
592,957
import time def update_stats(stats, start_time, step_result): """Update stats: write summary and accumulate statistics.""" (_, step_loss, step_predict_count, step_summary, global_step, step_word_count, batch_size, grad_norm, learning_rate) = step_result # Update statistics stats["step_time"] += (time.time...
c9de1a6fa88f5000a913de39ed8536d1c9e555fb
592,958
def pop(queue, max_count): """Pop multiple items from queue.""" result = [] for _ in range(max_count): if len(queue) == 0: return result result.append(queue.pop()) return result
5f08e8af71e2f6c3c86a904998bf0b8407cafbdc
592,959
def computeE(k): """Return the energy of a given k-vector.""" return (k[0]*k[0] + k[1]*k[1] + k[2]*k[2]) / 2.0
09acc6e4ea1fc75e466c0bdbba04c781eeec1c65
592,960
def num_from_str(s): """Return a number from a string.""" try: return int(s) except ValueError: try: return float(s) except ValueError: raise ValueError( 'Can not convert the string "' + s + '" into a numeric value.' )
37d7e623c7d888247c0469f029a0e75908b2febd
592,962
def merger(chat_df, message_df, handle_df, attachment_df, chat_message_join_df, message_attachment_join_df): """ Merges the given dataframes to create a single master dataframe containing all information. Assumes all dataframes have had their conflicting columns renamed via conflict_rename :param chat_d...
9f28e219748a8756da15d3cd27a90d12938867d9
592,963
def equal_time_obj(t1, t2): """ Takes two datetime.time objects and returns true if they are identical in HH:mm format. seconds and microseconds are ignored. """ # truncate time to hour and minutes only; remove seconds and microseconds t1_trunc = t1.replace(second=0, microsecond=0) t2_trunc...
25087a1081a386bb334ac47ef6b60e8bf53dd838
592,964
def base_pair(seq): """ Return the two RNA strands (as a tuple) represented by the given string of one-letter codes. The code is as follows (this is not a standard, and was created because I needed a way to indicate wobble pairs): Output Input 5' 3' ===== ====== A A ...
cb9bf6e0700650d95a8a26f21a6fc4a2201dcfb3
592,970
import torch def cos_similarity(a: torch.Tensor, b: torch.Tensor, eps=torch.tensor(3.5e-4)): """ Args: a: (torch.tensor) Matrix containing speaker representation vectors. (N x embedding_dim) b: (torch.tensor) Matrix containing speaker representation vectors. (N x embedd...
00eda32991a3ab85f727cfc4e238dddb6ce75a5a
592,973
def get_type(a): """ Extract a's type. First, try to extract a's class name. If this is unsuccessful, return type(a). The session below illustrates differences between type(a) nad get_type(a) for standard classes, instances of user-defined classes, and class objects (new style and classic class...
0dbb990a950f68879514fb3dfb7b9381c1dd3383
592,974
def _year_range(m): """Helper function to construct a range of years from a regex.""" return (m.group(1), m.group(2))
60e37e74dbadf20e9787046e80866896c38064c2
592,975
from typing import Union from typing import Callable import inspect def is_unbound_method(func: Union[Callable[..., object], staticmethod, classmethod] ) -> bool: """ Methods and nested function will have a different __qualname__ than __name__ (See PEP-3155). >>> class A: .....
52ab789ddad45657d9fb3f4bdb02d9db3339985c
592,976
def int_to_bool_list(number: int, byte_like: bool = False, reverse: bool = False): """ Convert Integer to List of Booleans. This function converts an integer to a list of boolean values, where the most significant value is stored in the highest point of the list. That is, a...
53f8b3134e020a730947a725e88047400ddec75a
592,977
from io import StringIO def get_content(sandbox): """ Get content from config, replace some errors :param sandox: it is config from loading file config (*.cfg) :type sandox: ConfigParser :rparam content: correct content of config file :rtype conent: str """ buff = StringIO() sand...
bc1f4351729bc0603cf8496a3f3d1941b65f2469
592,978
import re def _pattern_as_asterisk(pattern): """ Replace recurring %D (D: character) in the datetime pattern to asterisk. """ return re.sub("(\\%\D)+", "*", pattern)
653f6757acaf5ba81e1c2f3d0c15aa89abba4df8
592,985
import _datetime import pytz def now() -> _datetime.datetime: """Similar to datetime.datetime.utcnow, but tz-aware.""" # return from_datetime(datetime.datetime.utcnow().replace(tzinfo=pytz.utc)) return _datetime.datetime.utcnow().replace(tzinfo=pytz.utc)
70dca1f7baeff4ee9e8655c01c7d1646048f0175
592,988
def attr_populated(obj, attr): """Return True if attr was populated in obj from source JSON.""" return not not getattr(obj, '_populated_' + attr, False)
5a37a1c07c0aaa87409fbc7fe0a8298c0e266859
592,990
def climatology_check(temperature, interpMNTemp, interpSDTemp, sigmaFactor=5.0): """ temperature: Float for temperature interpMNTemp: interpolated temperature from climatology file interpSDTemp: interpolated standard deviation from climatology file sigmaFactor: tolerated deviation from climatological temperat...
3faae843a43c2938ed2adea33b3dd3919ba6583b
592,991
def RSI(price_col, length=14): """ Calculate the Relative Strength Index :param price_col: A series of prices :param length: Window length :return: A series of RSI """ delta = price_col.diff() dup, ddown = delta.copy(), delta.copy() dup[dup < 0] = 0 ddown[ddown > 0] = 0 rolup...
eb99e5bc02146788ea46e57eef1d0dd62377a21f
592,992
def full_swagger_name(sname: str) -> str: """ takes any full swagger name, either def or ref, and only returns the name part :param sname: string containing a swagger name for some object :return: a return with just the name, no other bits """ base_parts = sname.split("/") return base_parts[...
56cc2019f4cdb3f0689871b29a350e19c3281fd5
593,000
def bits2byte(arr_str, n=8): """ Convert bits back to byte :param arr_str: string with the bit array :type arr_str: str :param n: number of bits to separate the arr string into :type n: int :return rle: :type rle: list """ rle = [] numbers = [arr_str[i:i + n] for i in range(0, ...
4916bea3a6faa4e35ea06414e86adac31ce0b61b
593,004
def parse_txt_hyperparams(txtfile): """ Parse hyperparameters from a txt file. Args: txtfile (str): Path for the hyperparameter txt file. Return: hyperparams (dict): Hyperparameter names and values. """ dtypes = { 'num_hidden_layer': int, 'hidden_dim...
797abf2162b26451c53186a07fa3f9a674b8d8e9
593,006
def calculate_dates_and_durations(start=None, end=None, duration=None): """ Calculates Start Date, End Date or Duration from the other two known's Rule is: If all Given Data is not none, then calculate end date from start and duration, if two are known, then calculate the third from them if less...
0cf890fea5b84ed13c5680c6b5fdea5f4107fa34
593,007
def get_redundant_codewords(codeword: int, bit_width: int=4, bit_shift: int=0): """ Takes in a desired codeword and generates the redundant codewords. Example A: Codeword = 5 -> '101' bit_width = 4 -> '0101' bit_shift = 0 -> xxxx0101 The function should return all combinatio...
7719befdcdbaacca793bc6c7a960687f36551b48
593,010
def selection_sort(lst): """Selection sort algorithm.""" for i in range(len(lst) - 1): lowest_idx = i for j in range(i + 1, len(lst)): if lst[lowest_idx] > lst[j]: lowest_idx = j lst[i], lst[lowest_idx] = lst[lowest_idx], lst[i] return lst
222ae2b2c0eb87b37a7f011be0bb0b1af6fad916
593,012
from typing import List import random def _get_random_costs(n_instants: int, items_per_instant: int, cost_dim: int) -> List[List[List[float]]]: """Generates the list of items costs randomly. """ weights: List[List[List[float]]] = [[] for _ in range(n_instants)] for t in weights: for _ in range...
b774a5cf0b7d8a2f42c1b7d97a37139f11c177c7
593,016
def remove_stop_words(s): """ Removes (English) stop words from the given string. """ stopwords = 'a', 'the' words = [word for word in s.split() if word.lower() not in stopwords] # Join remaining words and remove whitespace. return ' '.join(words)
e4b1ff0fc57174a2181fa68e6e00e7a207c8b71d
593,018
def d_tanh(z): """The derivative of np.tanh. z should be a float or np.array.""" return 1.0 - z**2
c21b1681924b485f0e2f311b4d77814110f184c8
593,021
def list_concat(lists): """ Joins given list of lists into a single list """ final_list = [] for sublist in lists: final_list.extend(sublist) return final_list
2fb097c235de120516d12fb453e18c4f42e8e9b8
593,023
def show_post(post_id: int) -> str: """Show the post with the given id.""" return f'Post {post_id}'
5ce273828d9d27a6d9e63baf2959307a558c2c2f
593,025