content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def getclasesbyid_(numid): """ Returns all defined clases by id [number] """ data = get_info_token() user_ = data['User'] rol_ = data['Rol'] data_response = '' if rol_ == 'Professor': try: bool_, data_response = getclassbyid_(data['User'],numid) if bool_: ...
75603f40621f51313863aa8977b71241a31c3d84
30,067
import json def load_versions(): """Load Bioversions data.""" with open(VERSIONS_PATH) as file: return json.load(file)
e5e3b2a3dd4ae17fe6cf6b00700b33e9bc55e6b5
30,068
async def retrieve_document(document_id: str, collection: str) -> dict: """ :param document_id: :param collection: :return: """ document_filter = {"_id": ObjectId(document_id)} if document := await greens.app.state.mongo_collection[collection].find_one(document_filter): return await...
4865acd4e553f651a68d694171c76d609eceff98
30,069
import requests def get_kalliope_poststukken_uit(path, session, from_, to=None, dossier_types=None): """ Perform the API-call to get all poststukken-uit that are ready to be processed. :param path: url of the api endpoint that we want to f...
2976979bfcccd64939e56c2d0874f6d419028b62
30,070
import scipy def lstsq_cholesky( coefs: np.ndarray, result: np.ndarray, ) -> np.ndarray: """Solve OLS problem using a Cholesky decomposition.""" left = coefs.T @ coefs right = coefs.T @ result return scipy.linalg.solve(left, right, assume_a="pos")
08ec0988062daef04b55852d6673fb21031f9a87
30,072
import warnings def _standardize(signals, demean=True, normalize=True, inplace=True, verbose=False): """ Center and norm a given signal (time is along first axis) Attention: this will not center constant signals but will replace these with colums of ones ...
f207af4e0e18f6f9f544a18ae89d0e86fd8ae493
30,075
def bbox_to_poly(bboxes: np.ndarray) -> np.ndarray: """ Expects bboxes in xyxy format. Turns each into a 1D array with 8 entries, every consecutive pair being for one vertex (starting from top left and going around clockwise) Works with single bboxes (shape is (4, )) or multiple bboxes (shape is ...
12a06d343ac5a1f4bd16168bf04dc7e9dfaff4ec
30,076
def waypts_2_pwsplines(wp_traj, dt, degree=1, plot=False): """ Convert a sequence of multi-dimensional sparse waypoints to a sequence of interpolated multi-dimensional waypoints via splines. Parameters ---------- wp_traj: horizon * n_s, a sequence of waypoints. dt: duration of 1 time step o...
b133159e19513fa80a282a71786e5976cad1ab9a
30,077
def _bin_data(aa, bb, bins=10, verbose=False): """ If unbinned data has come in, do something smart with it here. Uses numpy.histogram for binning. bins can be: - int: number of bins - list or array: bin boundaries, from min to max, half open on right, like numpy, when bins=[1, 2, ...
a938cabaa2678a89cb1402d553041d409bfa4967
30,078
import logging def initialize_logger(logger, logger_id, progress_bar=None, log_queue=None): """ Initialize logger for the :class:`pyro.infer.mcmc` module. :param logger: logger instance. :param str logger_id: identifier for the log record, e.g. chain id in case of multiple samplers. :para...
4ea94d0bc1d6d9943cce2097f19256e3524d9521
30,079
def test_meta_plus_classmethod(namespaceable, namespace): """Test using a classmethod in a Namespace, while messing with metaclasses. This might have been purely for coverage of some kind? I forget. """ class Meta(namespaceable, type(namespaceable)): """A throwaway test metaclass.""" wi...
48ed58e8b4a0c68700ee8941087d015b76596c57
30,080
def EncodeConstants(const_dict): """the NPU requires that weights are compressed and bias/scales are 'encoded', both of which are performed by this pass. This pass modifies both the constant dict to contain the post-encoding values of the constants and the IR to adjust buffer types/sizes/accesses so th...
851e080bdf44e6de890fb87a1d2df1c0aefc0bf6
30,081
import collections def count_tweet_shed_words_freq(tweet_text, ind_shed_word_dict, shed_word_ind_dict, shed_words_set): """ Count the frequency of selected Hedonometer words in tweet text. param tweet_text: String of text field of tweet return: dict of shed_word_ind to shed_word_freq mapping...
129130f5b9def7320c6e3dd2d8ef82493d21eb8a
30,082
def parse_date(text): """Return POSIX timestamp obtained from parsing date and time from given date string. Return None if no text given. """ if text: return dateparser.parse(text).timestamp()
6f089096cdd43eb2d0af1db6066e75a6ec6efb09
30,083
def format(table, field, fmt, **kwargs): """ Convenience function to format all values in the given `field` using the `fmt` format string. The ``where`` keyword argument can be given with a callable or expression which is evaluated on each row and which should return True if the conversion shou...
a66e351bca42f8e385d8859db720e86c7e6fac7c
30,084
def colorbias(img, refcolor=np.array([1.,0,0])): """ Compute Color Bias """ img_hsv = skimage.color.rgb2hsv(img) refcolor = skimage.color.rgb2hsv(refcolor.reshape(1,1,3)) # to make it compatible #dH = np.abs(np.sin((img_hsv[...,0] - refcolor[...,0]))) #dS = np.abs(img_hsv[...,1] - refcolor[...,1]) ...
5ab089fd7a72fe647e5da5c62380544b87c41739
30,085
import six import numbers import collections def walk_json(e, dict_fct=i, list_fct=i, num_fct=i, str_fct=i, bool_fct=i, null_fct=i, not_found=not_found_default): """ Go throught a json and call each function accordingly of the element type for each element, the value returned is used for the json output ...
d0c9f57180327b8fca218f3ba4f413b410c2a2da
30,086
def colIm(z): """Returns a colour where log(Im(z)) is represented by hue. This makes it easy to see where Im(z) converges to 0""" h = np.log(z.imag)*pi l = np.clip(0.5+0.05*z.real,0.1,0.9) s = 1 c = hsl2rgb(h,s,l) return c
0ebefac4c7c5355ba735bfa46177b6f267f74cb9
30,087
def gsl_blas_zdotc(*args, **kwargs): """gsl_blas_zdotc(gsl_vector_complex const * X, gsl_vector_complex const * Y, gsl_complex * dotc) -> int""" return _gslwrap.gsl_blas_zdotc(*args, **kwargs)
953a9cd06d0f7a948d625acad9fd8ec8ce31249e
30,088
def random_neighbour(vec,myid,n): """Generates a random binary vector that is 1-bit away (a unit Hamming distance) Args: vec (list or numpy.ndarray): An input vector myid (int): An id of an agent of interest n (int): Number of tasks allocated to a single agent Returns: list...
816115c335e556815ff8ee20ae50ac9b9c9d6f22
30,089
import torch def _degree_of_endstopping(model, block, image, weight_id0, weight_id1, weight_id2): """Passes image to model and records the activations of block. The activations are normalized to be in [0, 1] and then summed over using different weighted masks. Parameters ---------- model : ...
830e8fd5b008fb8d2a852f1f365d3da1ddc24075
30,090
def posts(parsed): """Calculates number of every type of post""" num_t_post = 0 num_corner_post = 0 num_line_post = 0 num_end_post = 0 num_gate_posts = 0 for post in parsed.posts(): if not post.isRemoval: if post.postType == 'tPost': num_t_post += 1 ...
e8c5905a38ab560f0dba595eecf67865efc27121
30,091
def _compute_populations(mvts: pd.DataFrame, label_col_name) -> dict: """ A private method that computes the population corresponding to each class label. :param mvts: The dataframe who class population is of interest. :param label_col_name: The column-name corresponding to the class labels in `mvts`. ...
d47b78d8f30f6cb15c9b98cb13d9fb7c883d62f1
30,092
def plot_avg_sum_capacity_comparison( df: pd.DataFrame, port1: str, port2: str, vessel_type: str ) -> go.Figure: """ Returns a figure for the first chart on the Compare tab. It shows per day comparison between average sum of capacity by applied conditions. :param df: Pandas DataFrame, input data ...
8551fac8720c3d8433a5242c8ea099626a5b6e0c
30,093
def num_neighbours(lag=1): """ Calculate number of neigbour pixels for a given lag. Parameters ---------- lag : int Lag distance, defaults to 1. Returns ------- int Number of neighbours """ win_size = 2*lag + 1 neighbours = win_size**2 - (2*(lag-...
aca8c4e1fdac14cde111a7db2dd274767fc53d5a
30,096
import requests def get_solr_data_recommend(function, reader, rows=5, sort='entry_date', cutoff_days=5, top_n_reads=10): """ :param reader: :param rows: :param sort: :param cutoff_days: :param top_n_reads: :return: """ query = '({function}(topn({topn}, reader:{reader}, {sort} desc...
b7dbf5fc2cd8772532ab98115369199e87e80a3c
30,097
def normalize_key(key): """ Formata a chave para ser utilizada no json. Args: key (string): Campo coletado no scraping dos dados do MEC. Returns: Retorna a sttring formatada para ser utilizada no json. """ aux = key.strip(' :').replace(' ', '_').lower() ...
1065bbbd4d6c435fe9db477ee0f7a047692eaf63
30,098
def line(p0=(0,0), p1=(1,0)): """ p0 p1 o-----------o +--> u """ p0 = np.asarray(p0, dtype='d') p1 = np.asarray(p1, dtype='d') points = np.zeros((2,3), dtype='d') points[0,:p0.size] = p0 points[1,:p1.size] = p1 knots = [0,0,1,1] return NURBS([knots], points)
0abf0688a2e7f84322f56b35796d75497f6f65c2
30,099
def superior(): """a fixture for lake superior""" superior = LakeFactory(lake_name="Lake Superior", abbrev="SU") return superior
db21ff1ffbaf6be91dd8f0907083ee87bc4541de
30,100
def hsv_mask(img, hue_mask, sat_mask, val_mask): """ Returns a binary image based on the mask thresholds :param img: The image to mask :param hue_mask: Tuple of (hue_min, hue_max) :param sat_mask: Tuple of (sat_min, sat_max) :param val_mask: Tuple of (val_min, val_max) :return: Binary image ...
194cb97b42850244b601653551d359b2c42caacd
30,101
def convert_parameter_dict_to_presamples(parameters): """Convert a dictionary of named parameters to the form needed for ``parameter_presamples``. ``parameters`` should be a dictionary with names (as strings) as keys and Numpy arrays as values. All Numpy arrays should have the same shape. Returns (numpy s...
f136c9c795ab4c7023e774866c061b19488cc81f
30,102
def convert_to_rle(annotation, width, height): """Convert complex polygons to COCO RLE format. Arguments: annotation: a dictionary for an individual annotation in Darwin's format Returns: an annotation in encrypted RLE format and a bounding box @author Dinis Gokaydin <d.gokaydin@nationaldrones....
a9562e95817585798164a91ef793841143329dd7
30,103
import socket def getfqdn(name=None): """return (a) local IPv4 or v6 FQDN (Fully Qualified Domain Name) if name is not given, returns local hostname may raise socket.gaierror""" return _getfqdn(socket.AF_UNSPEC, name)
cbebf1e3deda3a095996034b559af8f2ae4692c3
30,104
def create_answer_dict(elem, restrict_elem=None, checkbox=False): """ Construct dict with choices to fulfil form's div attribute :param elem: ElemntTree element :param restrict_elem: name of element which is not included in choice text :param checkbox: boolean flag to work return data for checkbox ...
c87d5d22b3f779f4645263ae18febaa95984d614
30,105
def fasta(file_allname: str): """ 需要传入file_allname的路径 :param file_allname: :return: 返回fasta格式的序列list """ try: # file_allname = input("输入你要分析出的文件,包括后缀名\n") f = open(file_allname).read() fasts = f.split(">") fast_seq = [] index = 0 for fast in fasts:...
bbd03531a7d311c322fdbd66e401788fb6526120
30,106
def ask_version(version): """ interact with user to determine what to do""" upgrades = get_upgrades() latest = get_latest(version, upgrades) answer = False if latest > version: msg = "a new version (%s) is available. You have %s. Upgrade?" % (latest, version) answer = True if raw_inp...
1e6c7c87eeb4e222efd2b952e9d23b7c95275f85
30,107
def format_size(size): """ :param float size: :rtype: str """ size = float(size) unit = 'TB' for current_unit in ['bytes', 'KB', 'MB', 'GB']: if size < 1024: unit = current_unit break size /= 1024 return '{0:.2f}'.format(size).rstrip('0').rstrip('...
95470360fcc34df5a51a7cf354138413b41940aa
30,108
def make_full_block_header_list(block_header): """Order all block header fields into a list.""" return make_short_block_header_list(block_header) + [ block_header.timestamp, block_header.extraData, ]
59bcfdd3cefd3a1b7a8dcaf063964eb27dbafd67
30,109
def rc_seq(seq=""): """Returns the reverse compliment sequence.""" rc_nt_ls = [] rc_dict = { "a": "t", "c": "g", "t": "a", "g": "c", "n": "n", "A": "T", "C": "G", "T": "A", "G": "C", "N": "N" } rc_nt_ls = [rc_dict[seq[i]...
827877a76d4ffbe61e40e4f00641afa4277f3ff5
30,111
def descriptions(path, values): """Transform descriptions.""" if not values: return root = E.descriptions() for value in values: elem = E.description( value['description'], descriptionType=value['descriptionType'] ) set_non_empty_attr(elem, '{xml}lang', value...
34d570f0c2a97616833af5432ed5607413e2af9a
30,112
from typing import Mapping from typing import Union from typing import Sequence from typing import Optional from typing import Any def build_default_region_dataset( metrics: Mapping[FieldName, Union[Sequence[float], TimeseriesLiteral]], *, region=DEFAULT_REGION, start_date="2020-04-01", static: Op...
4c50876817b80ae412a193ba078b7948b7603322
30,113
def load_espnet_model(model_path): """Load an end-to-end model from ESPnet. :param model_path: Path to the model. :type model_path: str :return: The model itself, mapping from subword to index, and training arguments used. :rtype: (torch.nn.Module, dict, dict) """ model, train_...
d9f001a64465547cf27c6d600939e57e9b8f1a19
30,115
from typing import Iterator from typing import Union from typing import Match def full_match(nfa: NFA, text: Iterator[str]) -> Union[Match, None]: """ :param nfa: a NFA :param text: a text to match against :return: match or ``None`` """ text_it = _peek(text, sof='', eof='') curr_states_s...
9cbb30633f648405e193f61f46b5e2dd80fffde0
30,116
def smiles_tokenizer(line, atoms=None): """ Tokenizes SMILES string atom-wise using regular expressions. While this method is fast, it may lead to some mistakes: Sn may be considered as Tin or as Sulfur with Nitrogen in aromatic cycle. Because of this, you should specify a set of two-letter atoms ex...
c31916558fdbeda345a0667b43364f8bff504840
30,117
from typing import Set def merge_parameter_sets(first: Set[ParameterDefinition], second: Set[ParameterDefinition]) -> Set[ParameterDefinition]: """ Given two sets of parameter definitions, coming from different dependencies for example, merge them into a single set """ result: Set[ParameterDefinition]...
4b60ae17eb6e8b1ccd5149517c9d0ae809c33411
30,118
import struct def build_udp_header(src_port, dst_port, length): """Builds a valid UDP header and returns it Parameters: - src_port: A uint16 which will be used as source port for the UDP header - dst_port: A uint16 which will be used as destination port for the ...
d110c19ff38f88bc892ecb52c8203e356a930bab
30,120
def plot_confus_mat(y_true, y_pred, classes_on=None, normalize='true', linewidths=0.02, linecolor='grey', figsize: tuple = (4, 3), ax=None, fp=None, **kwargs): """ by default, normalized by row (true classes) """...
59ef04547b4829d7c3c1049c93fab69faaa3b23d
30,121
async def home(): """ Home endpoint to redirect to docs. """ return RedirectResponse("/docs")
1ebece9db1a86f54ec101037279087065aaa2f0a
30,123
def robust_hist(x, ax=None, **kwargs): """ Wrapper function to `plt.hist` dropping values that are not finite Returns: Axes """ mask = np.isfinite(x) ax = ax or plt.gca() ax.hist(x[mask], **kwargs) return ax
32165e3e5cb796fe941bc0f177606dbc502c61ef
30,124
def base36encode(number, alphabet='0123456789abcdefghijklmnopqrstuvxxyz'): """Convert positive integer to a base36 string.""" if not isinstance(number, (int, long)): raise TypeError('number must be an integer') # Special case for zero if number == 0: return alphabet[0] base36 = '' ...
d670a047d210f1d452d2acde76dc47208be2f4bf
30,126
def pipe(*args, **kwargs): """A source that builds a url. Args: item (dict): The entry to process kwargs (dict): The keyword arguments passed to the wrapper Kwargs: conf (dict): The pipe configuration. Must contain the key 'base'. May contain the keys 'params' or 'path'...
a9fca4149bca2ee50ffe5efcbb67c3066523cdf8
30,127
import six def get_rotation(rotation): """ Return the text angle as float. The returned angle is between 0 and 360 deg. *rotation* may be 'horizontal', 'vertical', or a numeric value in degrees. """ try: angle = float(rotation) except (ValueError, TypeError): isString = is...
7ed0fd31f9a90ddb5743faa8e45e46f0d5cc08bd
30,128
def checkWrite(request): """Check write""" try: _path = request.query_params.get("path") _file = open(_path + "test.txt", "w") _file.write("engine write test") _file.close() return HttpResponse(_path + "test.txt") except ValueError as e: return genericApiExce...
c3d196126c67cc9b8ba5482a4ebb7df778cd1d5e
30,129
def most_seen_creators(event_kind=None, num=10): """ Returns a QuerySet of the Creators that are associated with the most Events. """ return Creator.objects.by_events(kind=event_kind)[:num]
60d4865b56ea2d2ede8cad5123fbaa3f49e72bcd
30,130
def read_lexicon(): """ Returns the dict of {'word': string, 'score': int} represented by lexicon.txt """ return read_dict('resources/lexicon.txt')
69cdf729aabfd42d4e02690cabcd91b1162598aa
30,133
import tqdm def show_erps(Ds, align_window, labels=None, show_sem=True, co_data=None, **kwargs): """ Use plot ERPs on electrode_grid Parameters ---------- Ds: list list of D tensors (electrodes x time x trials) align_window: tuple time before and after stim in se...
988a89af259387796e3735ce9526304591c09131
30,135
def insert_with_key_enumeration(agent, agent_data: list, results: dict): """ Checks if agent with the same name has stored data already in the given dict and enumerates in that case :param agent: agent that produced data :param agent_data: simulated data :param results: dict to store data into :...
d2d653dcff20836c4eaf8cf55b31b1a1209a4ddd
30,136
def parse_condition_code(value, is_day: bool) -> str: """Convert WeatherAPI condition code to standard weather condition.""" if value is None: return None try: condition_code = int(value) if condition_code == 1000: return ATTR_CONDITION_SUNNY if is_day else ATTR_CONDITI...
cd650a27b907f6d0ced7c05bd8aec5a316bf3b42
30,138
def min__to__s(): """Convert minute to second""" return '6.0E+1{kind}*{var}'
2730af2cc79a6c4af6d1b18f79326623c0fd0289
30,139
import html def home(): """Home tab.""" icon = html.I(className="fas fa-home fa-lg", title="Home") return html.Li(html.Span(icon), id="view-info", className="active")
f1771b014b3d0332965b4bb0d74038dfddda8c21
30,140
def score_per_term(base_t, mis_t, special_t, metric): """Computes three distinct similarity scores for each list of terms. Parameters ---------- base_t, mismatch_t special_t: list of str Lists of toponym terms identified as base, mismatch or frequent (special) respectively. metric: str ...
55e5b9b0d9feaa359ab0907b399eb37514dcfacd
30,141
import bisect def _eliminationOrder_OLD(gm, orderMethod=None, nExtra=-1, cutoff=inf, priority=None, target=None): """Find an elimination order for a graphical model Args: gm (GraphModel): A graphical model object method (str): Heuristic method; one of {'minfill','wtminfill','minwidth','wtminwidth','random...
dfe770db099dc65bcba1afb8c2706005dd7bb81d
30,142
import torch def get_pretrain_data_loader(mode, pretrain_data_setting): """Get pre-training loader. Args: mode (str): either "train" or "valid". pretrain_data_setting (dict, optional): pretrain dataset setting. Returns: loader (torch.dataloader): a PyTorch dataloader with all input d...
dc894eb5fb41cf49910568d01a749ebc93aded6d
30,144
def do_simple_math(number1, number2, operator): """ Does simple math between two numbers and an operator :param number1: The first number :param number2: The second number :param operator: The operator (string) :return: Float """ ans = 0 if operator is "*": ans = number1 * nu...
eb745f9c3f3c1e18de30cbe6c564d68c29e39ff4
30,145
def test_global_settings_data(): """Ensure that GlobalSettingsData objects are properly initialized per-thread""" def check_initialized(index): if index == 0: sleep(0.1) with pytest.raises(AttributeError): _global_settings_data.testing_index # pylint: disable=W0104 ...
bd1229bb9150b25c88be621d5af0f8da9cf7327d
30,146
def set_client(client): """ Set the global HTTP client for sdk. Returns previous client. """ global _global_client previous = _global_client _global_client = client return previous
9f29f5491cee42581fb2b0a22edd36a2297754b4
30,147
def readNetAddress(b, hasStamp): """ Reads an encoded NetAddress from b depending on the protocol version and whether or not the timestamp is included per hasStamp. Some messages like version do not include the timestamp. Args: b (ByteArray): The encoded NetAddress. hasStamp (bool)...
7d523c0465039008e0015c075e8282a1aacea000
30,148
def get_all_clouds(session, return_type=None, **kwargs): """ Retrieves details for all available storage clouds. :type session: zadarapy.session.Session :param session: A valid zadarapy.session.Session object. :type return_type: str :param return_type: If this is set to the string 'json', this...
61029884408733398d8e2c3bb52c18ef4e9f83fc
30,149
def _get_account_balances_by_regid(user_regid): """ returns uw_sws.models.Finance object for a given regid """ if user_regid is None: return None return get_account_balances_by_regid(user_regid)
6c81ca23411a415d3551d856a44c44f6377ec1b9
30,150
def make_embed(msg_type='', title=None, icon=None, content=None, msg_colour=None, guild=None, title_url=None, thumbnail='', image='', fields=None, footer=None, footer_icon=None, inline=False): """Returns a formatted discord embed object. Define either a type or a co...
5cdeb5862ffc525160361f760b5530e15d3258c1
30,153
import torch def dynamic_stitch(indices, data): """ Args indices: A list of at least 1 Tensor objects with type int32. data: A list with the same length as indices of Tensor objects with the same type. Returns A Tensor. Has the same type as data. """ dim_0 = in...
6988b400ca1110187643eba932f00103f5f393b6
30,154
def snake(string): """snake_case""" return "_".join(string.split())
6bf99dede918937ad59ec9be14ffade8fadb5794
30,155
def parse_standard_metadata(): """ Gather the standard metadata information from Jenkins and the DBMS. Returns ------- The metadata obtained from Jenkins and the DBMS. Warnings -------- Underlying implementation is hacky right now. """ return {**_parse_jenkins_env_vars(), **_pa...
535bc56eabbdc2d178b448951127adf37af217eb
30,156
def match_all_args(ctx, node, func, args): """Call match_args multiple times to find all type errors. Args: ctx: The abstract context. node: The current CFG node. func: An abstract function args: An Args object to match against func Returns: A tuple of (new_args, errors) where new_args...
88bd473876dd3a286c02330023555dab211336df
30,158
import torch def samples_from_cpprb(npsamples, device=None): """ Convert samples generated by cpprb.ReplayBuffer.sample() into State, Action, rewards, State. Return Samples object. Args: npsamples (dict of nparrays): Samples generated by cpprb.ReplayBuffer.sample() devi...
6775f0eee7544f35e04e6e6fd3096516411dc0e8
30,159
def generateKeys(): """ generates and returns a dictionary containing the original columns names from the LIDAR file as values and the currently used column names as corresponding keys ws_1 : Speed Value.1 dir_1 : Direction Value.1 h_1 : Node RT01 Lidar Height """ keys = {"ws_0" :...
9d0d55c3fdc32ddda46da4a9e876d4ce1ecde25d
30,160
def process_line(line): """Return the syntax error points of line.""" stack = [] for c in line: if c in '([{<': stack.append(c) elif c != closings[stack.pop()]: return points[c] return 0
4ab64c74d89f950cc6c87b7a91addeb29717d74a
30,161
def get_uniprot_homologs(rev=False): """As above, but exclusively uniprot => mouse uniprot""" homologs = {} with open('data/corum_mouse_homologs.txt') as infile: data = [line.strip().split('\t') for line in infile] for line in data: original = line[1].split('|')[1] uniprot = line...
969085375265b90b5501b4b86eaaed3e1c48795f
30,162
import typing def flatten( value: list, levels: typing.Optional[int] = None ) -> list: """Flatten a list. .. code-block:: yaml - vars: new_list: "{{ [1, 2, [3, [4, 5, [6]], 7]] | flatten }}" # -> [1, 2, 3, 4, 5, 6, 7] To flatten only the top level, use the ``leve...
569ccb15f140a517792bc6b5ea962537db0b31f8
30,163
def GetStage(messages): """Returns corresponding GoogleCloudFunctionsV2(alpha|beta)Stage.""" if messages is apis.GetMessagesModule(_API_NAME, _V2_ALPHA): return messages.GoogleCloudFunctionsV2alphaStage elif messages is apis.GetMessagesModule(_API_NAME, _V2_BETA): return messages.GoogleCloudFunctionsV2bet...
3bdb130cf78694b223bd555f6db20e1c687b5552
30,164
def get_general_case_info(adapter, institute_id=None, slice_query=None): """Return general information about cases Args: adapter(adapter.MongoAdapter) institute_id(str) slice_query(str): Query to filter cases to obtain statistics for. Returns: general(dict) """ g...
a5afc2244db59f7a3dd0da55dd4759a57af641a4
30,165
def _normalize_ids(arg, atoms={int, long, str, unicode, NewId}): """ Normalizes the ids argument for ``browse`` (v7 and v8) to a tuple. Various implementations were tested on the corpus of all browse() calls performed during a full crawler run (after having installed all website_* modules) and this one...
1a7b930896a046357474000b8ebc598f70fbba76
30,166
def is_intersection(g, n): """ Determine if a node is an intersection graph: 1 -->-- 2 -->-- 3 >>> is_intersection(g, 2) False graph: 1 -- 2 -- 3 | 4 >>> is_intersection(g, 2) True Parameters ---------- g : networkx DiGraph n : node id R...
415e5154095cd78112ef029b6c4d62c36da0b3b8
30,167
def AxisRotation(p, ang, inplace=False, deg=True, axis='z'): """ Rotates points p angle ang (in deg) about an axis """ axis = axis.lower() # Copy original array to if not inplace if not inplace: p = p.copy() # Convert angle to radians if deg: ang *= np.pi / 180 if axis == ...
1df385b98edb69134849cb052380fb99261f96b2
30,168
from pathlib import Path from typing import List def get_dir_list(path: Path)->List[str]: """ Return directory list """ dir_list = [] paths = Path(path).glob("**/*") for p in paths: if p.is_dir(): dir_list.append(str(p)) return dir_list
a0fe0659ad0175364048be6ef96026584fa6f3ef
30,169
import typing def tokenize(data: typing.Union[str, typing.Sequence[str]]) -> list[str]: """break up string into tokens, tokens can be separated by commas or spaces creates separate tokens for: - "(" or "[" at beginning - ")" or "]" at end """ # break into tokens if isinstance(data, str):...
832343067c8777aa386c0c87c2c4e8202a7cb88f
30,170
def de_comma(string): """Remove any trailing commas >>> de_comma(',fred,,') == ',fred' True """ return string.rstrip(',')
453d615c1fbbef5139d05d6e4510731c969d6a86
30,171
def MakeData(ea, flags, size, tid): """ Create a data item at the specified address @param ea: linear address @param flags: FF_BYTE..FF_PACKREAL @param size: size of item in bytes @param tid: for FF_STRU the structure id @return: 1-ok, 0-failure """ return idaapi.do_data_ex(ea, fla...
ab890848784407bf0ee2864469a5c8874346c5ec
30,172
def get_node_network_receive(cluster_id, ip, start, end, bk_biz_id=None): """获取网络数据 start, end单位为毫秒,和数据平台保持一致 数据单位KB/s """ step = (end - start) // 60 prom_query = f""" max(rate(node_network_receive_bytes_total{{cluster_id="{cluster_id}",job="node-exporter", instance=~"{ ip }:9100"}}[5m])...
9ba68d19c6ca959fd92020f50498d4aa14dfeb58
30,173
def verify_vrrpv3_summary(dut,**kwargs): """ Author: Raghukumar Rampur email : raghukumar.thimmareddy@broadcom.com :param dut: :param interface: :type string or list :param vrid: :type string or list :param vip: :type virtual-ip in string or list :param state: :type vrrp ...
b5d9ae54fc316cadfd8c4d067439b19ecac4c371
30,174
def attributes_restore(node): """Restore previously unlocked attributes to their default state. Args: node (str): Node to restore attributes Returns: bool: False if attribute doesn't exists else True """ attr_name = "attributes_state" base_attr = "{}.{}".format(node, attr_nam...
8c598518d7df1bcc88cbbb3c48d34fecd41b0487
30,175
import pickle def get_actual_data(base, n_run, log_path, subfolders): """ :param base: the sub folder name right before the _DATE_InstanceNumber :param n_run: the INSTANCE number in the subfolder name :param log_path: path to the main log folder containing all the runs of an experiment (e.g. ../data/C...
b9f76b14b90e3c187e19bcd0b8bbbfe865518fe7
30,176
def secs_to_str(secs): """Given number of seconds returns, e.g., `02h 29m 39s`""" units = (('s', 60), ('m', 60), ('h', 24), ('d', 7)) out = [] rem = secs for (unit, cycle) in units: out.append((rem % cycle, unit)) rem = int(rem / cycle) if not rem: break if re...
0918fd72fbaaa0adf8fe75bcb1ef39b4e9aba75b
30,177
def shuffle(xsets, ysets, seed=None): """Shuffle two datasets harmonically Args: x, y: datasets, both of them should have same length Return: (shuffled_x, shuffled_y): tuple including shuffled x and y """ if len(xsets) != len(ysets): raise ValueError np.random.seed(seed=s...
0d07fa7b1d556a5af0bb4f3d174326c756d3d6a7
30,178
import math def get_CL_parameters(file_pointer, class_10_100_1000): """ Function to predict cluster count and mean size by means of clustering Args: file_pointer: string with a file path Returns tuple with( clusters: predicted number of clusters log_me...
498bf2e3b6a1e70808b159e2b630d9cdb8cebc40
30,179
def _nanclean(cube, rejectratio=0.25, boxsz=1): """ Detects NaN values in cube and removes them by replacing them with an interpolation of the nearest neighbors in the data cube. The positions in the cube are retained in nancube for later remasking. """ logger.info('Cleaning NaN values in the c...
154bf994161a932505101ccbe921792e2d3c9f3b
30,180
import json def parseData(filePath): """ Tries to import JSON JobShop PRO file to program :return machineList itinerariesList """ machinesList = [] itinerariesList = [] with open(filePath, 'r', encoding="utf8") as inputfile: # read file from path importedData = json.loads(inputf...
b02471737e320eb35c4c9626c11737952455f18e
30,181
def curve_fit_log(xdata, ydata, sigma): """Fit data to a power law with weights according to a log scale""" # Weights according to a log scale # Apply fscalex xdata_log = np.log10(xdata) # Apply fscaley ydata_log = np.log10(ydata) sigma_log = np.log10(sigma) # Fit linear popt_lo...
f00484c2e520e8060d7cb29ea503170c2e6ff07d
30,182
def get_computed_response_text_value(response): """ extract the text message from the Dialogflow response, fallback: None """ try: if len(response.query_result.fulfillment_text): return response.query_result.fulfillment_text elif len(response.query_result.fulfillment_mes...
fa7410ac4b0ef2c0dea59b0e9d001a7893a56479
30,183
def tmpdir_factory(request): """Return a :class:`_pytest.tmpdir.TempdirFactory` instance for the test session. """ return request.config._tmpdirhandler
cb506efaef55275d30755fc010d130f61b331215
30,184