content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def gen_api_url(endpoint): """Construct a Wger API url given the endpoint""" # type: (str) -> str return WGER["host_name"] + WGER["api_ext"] + endpoint
70623f9130b4dbde277a8c15b3f43a5168e4e487
24,600
from typing import Literal def create_inputs( data: np.ndarray, input_type_name: Literal[ "data", "data_one_column", "one_in_one_out_constant", "one_in_one_out", "one_in_batch_out", "sequentions", ], input_type_params: dict, mode: Literal["validate",...
bdb916915d561aa87435c2af5ea2f8b892f3c4b1
24,601
def CDLKICKINGBYLENGTH(df): """ 函数名:CDLKICKINGBYLENGTH 名称:Kicking - bull/bear determined by the longer marubozu 由较长缺影线决定的反冲形态 简介:二日K线模式,与反冲形态类似,较长缺影线决定价格的涨跌。 python API integer=CDLKICKINGBYLENGTH(open, high, low, close) :return: """ open = df['open'] high = df['high'] low =...
e3a0c62627e8b4866580f232b5199570768c5197
24,602
def report_count_table_sort(s1, s2): """ """ # Sort order: Class and scientific name. columnsortorder = [0, 2, 3, 6] # Class, species, size class and trophy. # for index in columnsortorder: s1item = s1[index] s2item = s2[index] # Empty strings should be at the end. if...
cf207e4e8f524e48f99422017b17e643b66a9e78
24,603
import urllib def serch_handler(msg): """ 处理音乐搜索结果 :param msg: 搜索信息 :return: """ # url = 'https://www.ximalaya.com/revision/search?core=all&kw={0}&spellchecker=true&device=iPhone' url = 'https://www.ximalaya.com/revision/search?kw={0}&page=1&spellchecker=false&condition=relation&rows=50&de...
e91620dce4d4b6e7d79ab0e8cbf612322f0248b3
24,604
def random(start: int, end: int) -> int: """Same as `random.randint(start, end)`""" return randint(start, end)
473f27e528d13cdb649b6e6d6e5ba32498a96cc1
24,605
def zero_check(grid): """Take a 2d grid and calculates number of 0 entries.""" zeros = 0 for row in grid: for element in row: if element == 0: zeros += 1 return zeros
0d69a948eef96937f8a5033256c3c4d9f22ce14d
24,606
from typing import List def get_channel_clips(channel: Channel) -> List[Clip]: """ Uses a (blocking) HTTP request to retrieve Clip info for a specific channel. :param channel: A Channel object. :returns: A list of Clip objects. """ clips = [] pagination = "" while True: query = gql.GET_CHANNEL_CLIPS_QUERY...
7b5d5c19b0ac5f7ec665e8e453a529c5556cbadd
24,607
def tensorflow2xp(tf_tensor: "tf.Tensor") -> ArrayXd: # pragma: no cover """Convert a Tensorflow tensor to numpy or cupy tensor.""" assert_tensorflow_installed() if tf_tensor.device is not None: _, device_type, device_num = tf_tensor.device.rsplit(":", 2) else: device_type = "CPU" i...
81bb8bea01e2e108c21022699005cb17cab12f0e
24,608
def __str__(self, indent=0, func_role="obj"): """ our own __str__ """ out = [] out += self._str_signature() out += self._str_index() + [''] out += self._str_summary() out += self._str_extended_summary() out += self._str_param_list('Parameters') out += self._str_options('Options')...
3e55fccb76f8e200ef7e57366c2ccd9609975959
24,609
import os def cmd(): """Return the Juju command There are times when multiple versions of Juju may be installed or unpacked requiring testing. This function leverages two environment variables to select the correct Juju binary. Thus allowing easy switching from one version to another. JUJU_...
88e34da7be521dd62c438033ce54cd9736f4f7b5
24,610
def worker_years_6_download(request): """ 纺织类通信带条件查询,然后下载对应结果文件 :param request: :return: """ return download.worker_years_6_download(request)
2250828132dff114665c4d6b3c4c6eb2a21840ce
24,611
def set_autoscaler_location(autoscaler, is_regional, location): """ Sets location-dependent properties of the autoscaler. """ name = autoscaler['name'] location_prop_name = 'region' if is_regional else 'zone' autoscaler['type'] = REGIONAL_LOCAL_AUTOSCALER_TYPES[is_regional] autoscaler['properties'...
2e663856d4b4d9a3a477de9ce330cc5fe42502a1
24,612
from typing import Dict from typing import Iterable def _define_deformation_axes() -> Dict[str, Iterable[str]]: """Defines object sets for each axis of deformation.""" rgb_objects_dim = {} for a in DEFORMATION_AXES: rgb_objects_dim[a] = [] for v in _DEFORMATION_VALUES: obj_id = f'{v}{a}' # T...
d50384ca1261a312f48f9f6540252fa5f265cf80
24,613
def ldns_rr2buffer_wire_canonical(*args): """LDNS buffer.""" return _ldns.ldns_rr2buffer_wire_canonical(*args)
5012bf22889ab0cd8375750bab8f54ca2ecb0da0
24,614
def get_stretch_factor(folder_name, indices, **kwargs): """ Computes the stretch factor using the (16-50-84) percentile estimates of x0 - x1 for each restframe wavelength assuming orthogonality Parameters: folder_name: folder containing the individual likelihoods and their perc...
17d61ba5205aada23b8f6b6a57c1920770a43408
24,615
def zonal_length(lat, nlon): """ length of zonal 1/nlon segment at latitude lat""" return R_earth * 2*np.pi/nlon * np.cos(lat*np.pi/180)
cf539ec73cae803a187d913c84ef7cb739cf8952
24,616
def map_request_attrs(name_request, **kwargs): """ Used internally by map_request_data. :param name_request: :key nr_id: int :key nr_num: str :key request_entity: str :key request_action: str :key request_type: str :return: """ try: # Use class property values for the...
16b4fbf2023b097956f3fb4a3dd0e3c1a7e1c800
24,617
def create_gw_response(app, wsgi_env): """Create an api gw response from a wsgi app and environ. """ response = {} buf = [] result = [] def start_response(status, headers, exc_info=None): result[:] = [status, headers] return buf.append appr = app(wsgi_env, start_response) ...
73dd8459cbf9b79655137536ff42195ba62c1372
24,618
def Squeeze(parent, axis=-1, name=""): """\ Dimension of size one is removed at the specified position (batch dimension is ignored). :param parent: parent layer :param axis: squeeze only along this dimension (default: -1, squeeze along all dimensions) :param name: name of the output layer...
3c8e6d6292e29d857412db1c74352b02aab99654
24,619
import attrs def parse_namespace(tt): """ <!ELEMENT NAMESPACE EMPTY> <!ATTLIST NAMESPACE %CIMName;> """ check_node(tt, 'NAMESPACE', ['NAME'], [], []) return attrs(tt)['NAME']
70a2f4e0ad0f8f98e38fde1892e9d40a34653af1
24,620
def clean(val, floor, ceiling): """Make sure RH values are always sane""" if val > ceiling or val < floor or pd.isna(val): return None if isinstance(val, munits.Quantity): return float(val.magnitude) return float(val)
6bf2822dc47a0b50cd88f05e2c127d97c5d71c0f
24,621
from typing import Union from typing import List from typing import Tuple def count_swaps_in_row_order(row_order: Union[List[int], Tuple[int]]) -> int: """ Counts the number of swaps in a row order. Args: row_order (Union[List[int], Tuple[int]]): A list or tuple of ints representing the o...
c96fcb26fac03d252918f7cfa1dd3048eaf22320
24,622
def evaluate(ast, env): """Evaluate an Abstract Syntax Tree in the specified environment.""" print(ast) if is_boolean(ast): return ast if is_integer(ast): return ast if is_string(ast): return ast if is_symbol(ast): return env.lookup(ast) if is_list(ast): ...
c9e5da8c9b073f72a2b27bfbb84a7939fbcec134
24,623
from datetime import datetime import json def load_data( assets: tp.Union[None, tp.List[tp.Union[str,dict]]] = None, min_date: tp.Union[str, datetime.date, None] = None, max_date: tp.Union[str, datetime.date, None] = None, dims: tp.Tuple[str, str] = (ds.TIME, ds.ASSET), forward...
83bd4221b92e2697bc79a416d0d5108fdb79ef27
24,624
def create_model(values): """create the model basing on the calculated values. Args: values (dict): values from the get_values_from_path function Raises: ValueError: if the loss function doesnt excist Returns: torch.nn.Module: model the network originally was trained with. ...
9750fa13042572c8ca7a5f81ef73c87134a08431
24,625
def loss(logits, labels): """Calculates the loss from the logits and the labels. Args: logits: Logits tensor, float - [batch_size, NUM_CLASSES]. labels: Labels tensor, int32 - [batch_size]. Returns: loss: Loss tensor of type float. """ loss = tf.reduce_mean( tf.nn.softmax_cross...
5d86168b8cffba3feb822120fd112835593a8d36
24,626
import glob import os def old_get_obs_session(project=None, dss=None, date=None, path='proj'): """ Provides project, station, year and DOY, asking as needed. It follows one of several possible paths to get to the session:: proj - path through /usr/local/projects/<project> hdf5 - path through /usr/...
2a2116b56ba2fa1dadca0564510be202246fc46e
24,627
def create_pattern_neighbors_ca2d(width, height, n_states=2): """ Returns a list with the weights for 'neighbors' and 'center_idx' parameters of evodynamic.connection.cellular_automata.create_conn_matrix_ca1d(...). The weights are responsible to calculate an unique number for each different neighborhood patte...
53ce7cd0afb9f9b590754d299ba2d621489bc4e6
24,628
def by_colname_like(colname, colname_val): """ Query to handle the cases in which somebody has the correct words within their query, but in the incorrect order (likely to be especially relevant for professors). """ def like_clause_constructor(colname, colname_val): """ Helper fu...
256f5e952fdff02f8de44c45b3283013547d0287
24,629
import json def decode_classnames_json(preds, top=5): """ Returns class code, class name and probability for each class amongst top=5 for each prediction in preds e.g. [[('n01871265', 'tusker', 0.69987053), ('n02504458', 'African_elephant', 0.18252705), ... ]] """ if len(preds.shape) != ...
807bed051300801a5e6a92bbc96324a66050f6c0
24,630
import os import json def _GetSupplementalColumns(build_dir, supplemental_colummns_file_name): """Reads supplemental columns data from a file. Args: build_dir: Build dir name. supplemental_columns_file_name: Name of a file which contains the supplemental columns data (in JSON format). Returns:...
f19c12a554ced4107a804badefe117165ef792d5
24,631
import math def prime_decomposition(number): """Returns a dictionary with the prime decomposition of n""" decomposition = {} number = int(number) if number < 2: return decomposition gen = primes_gen() break_condition = int(math.sqrt(number)) while number > 1: current_prime ...
67062c15676e02747385e64e2dc177ea95d48de1
24,632
from typing import Iterable import os import glob import logging def load_10x( celltype: str = "CD8_healthy", exclude_singles: bool = True ) -> pd.DataFrame: """ Load 10x data. Columns of interest are TRA_aa and TRB_aa """ def split_to_tra_trb(s: Iterable[str]): """Split into two lists of...
e40ee234d6d84ac5a61f13d8de3edbb12d932c6c
24,633
def levenshtein(s1, s2): """ Levenstein distance, or edit distance, taken from Wikibooks: http://en.wikibooks.org/wiki/Algorithm_implementation/Strings/Levenshtein_distance#Python """ if len(s1) < len(s2): return levenshtein(s2, s1) if not s1: return len(s2) previous_row = ...
58ef88e60e454fda4b1850cc800f75a1d711a9af
24,634
from typing import Tuple from typing import Optional def configure_mpi_node() -> Tuple[RabbitConfig, Celery]: """Will configure and return a celery app targetting GPU mode nodes.""" log.info("Initializing celery app...") app = _celery_app_mpi # pylint: disable=unused-variable @app.task( n...
bbc1c04ac8372ff8f5478d39d3f210e14b284c51
24,635
def customizations(record): """ Use some functions delivered by the library @type record: record @param record: a record @rtype: record @returns: -- customized record """ record = type(record) # record = author(record) record = convert_to_unicode(record) # record = editor(r...
32e47923e194a5fcb0540d9c2953be8d4dab019e
24,636
def enrichs_to_gv(G, enrich_fhs, ofh, **kwargs): """ Read the next line in each file handle in <enrich_fhs> and parse the significant GO:BP annotation in that line. Then, write the GO:BP annotations, along with the original graph, to a graphviz open file handle <ofh>. Parameters ---------- G : nx.Graph ...
f063f2f2d692a02c383fc25dfd21791f97b0629a
24,637
def _has_letter(pw): """ Password must contain a lowercase letter :param pw: password string :return: boolean """ return any(character.isalpha() for character in pw)
2f8eea521e8ca88001b2ecc3bc2501af8b14bbc8
24,638
import math def closest_power_of_two(n): """Returns the closest power of two (linearly) to n. See: http://mccormick.cx/news/entries/nearest-power-of-two Args: n: Value to find the closest power of two of. Returns: Closest power of two to "n". """ return pow(2, int(math.log(n, 2) + 0.5))
50d78d2a6de4f689ce268a95df97aae72dbd81ac
24,639
def get_product(barcode, locale='world'): """ Return information of a given product. """ return utils.fetch(utils.build_url(geography=locale, service='api', resource_type='product', param...
409cfd2702ee06bab3e02bb446f0ce9d7e284892
24,640
def score(y_true, y_score): """ Evaluation metric """ fpr, tpr, thresholds = roc_curve(y_true, y_score, pos_label = 1) score = 0.4 * tpr[np.where(fpr>=0.001)[0][0]] + \ 0.3 * tpr[np.where(fpr>=0.005)[0][0]] + \ 0.3 * tpr[np.where(fpr>=0.01)[0][0]] return score
b561e3cb3bd84d00c78dbd7e906e682c8758859d
24,641
def divisors(num): """ Takes a number and returns all divisors of the number, ordered least to greatest :param num: int :return: list (int) """ list = [] x = 0 for var in range(0, num): x = x + 1 if num % x == 0: list.append(x) return list
848ed77fa92ae1c55d90a5236f0d9db6ae2f377c
24,642
def files_page(): """Displays a table of the user's files.""" user = utils.check_user(token=request.cookies.get("_auth_token")) if user is None: return redirect(location="/api/login", code=303), 303 return render_template(template_name_or_list="home/files.html", ...
58e627297c2d7b881c18459dc47a012b016cee3d
24,643
def GetCodepage(language): """ Returns the codepage for the given |language|. """ lang = _LANGUAGE_MAP[language] return "%04x" % lang[0]
7c84552d6b2f2747ee8365d89ba29bc7843054b7
24,644
def NumVisTerms(doc): """Number of visible terms on the page""" _, terms = doc return len(terms)
a6b762f314732d90c2371adf9472cf80117adae5
24,645
def replace_inf_price_nb(prev_close: float, close: float, order: Order) -> Order: """Replace infinity price in an order.""" order_price = order.price if order_price > 0: order_price = close # upper bound is close else: order_price = prev_close # lower bound is prev close return ord...
6b3581e31d69236c950a3ad812bb95eebbedcf10
24,646
def get_trend(d): """ Calcuate trend for a frame `d`. """ dv = d.reset_index(drop=True) dv["minutes"] = np.arange(dv.shape[0], dtype=np.float64) covariance = dv.cov() return (((covariance["minutes"]) / covariance.loc["minutes", "minutes"])[d.columns] .rename(lambda cl: "_".join(...
b649e60b8ef74b0a64ec935fde35271b68b0dad7
24,647
def getIpAddress(): """Returns the IP address of the computer the client is running on, as it appears to the client. See also: system.net.getExternalIpAddress(). Returns: str: Returns the IP address of the local machine, as it sees it. """ return "127.0.0.1"
d6aefaa4027a899344c762bc7df5ce40a5dbde4e
24,648
def line(x, y, weights=None, clip=0.25): """Fit a line Args: x (numpy.array): x-values y (numpy.array): y-values clip (float, optional): Fit only first part. Defaults to 0.25. Returns: pandas.Series: fit parameters """ if 0 < clip < 1: clip_int = int(len(x) ...
cfc794095e1b60f608b94d44480cb79ece0af653
24,649
def one_hot(data): """ Using pandas to convert the 'data' into a one_hot enconding format. """ one_hot_table = pd.get_dummies(data.unique()) one_hot = data.apply(lambda x: one_hot_table[x] == 1).astype(int) return one_hot
fed9c171ae5b3bcdb78311afa47017c21e1c4b59
24,650
def update_set(j, n): """Computes the update set of the j-th orbital in n modes Args: j (int) : the orbital index n (int) : the total number of modes Returns: Array of mode indexes """ indexes = np.array([]) if n % 2 == 0: if j < n / 2: indexes = np.a...
c1d91f245710b1e11aa7178db490f050827d5683
24,651
def chunklist(inlist: list, chunksize: int) -> list: """Split a list into chucks of determined size. Keyword arguments: inList -- list to chunk chunkSize -- number of elements in each chunk """ if not isinstance(inlist, list): raise TypeError def __chunkyield() -> list: # ...
1351f0fa2ca208095a35ac0806a625f3227b24ef
24,652
def getLocation(seq, meifile, zones): """ Given a sequence of notes and the corresponding MEI Document, calculates and returns the json formatted list of locations (box coordinates) to be stored for an instance of a pitch sequence in our CouchDB. If the sequence is contained in a single system, only...
18297c74cb867e018e7a4f3147cdd50ba1eb8225
24,653
import warnings def calculate_A0_moving_LE(psi_baseline, psi_goal_0, Au_baseline, Au_goal, deltaz, c_baseline, l_LE, eps_LE): """Find the value for A_P0^c that has the same arc length for the first bay as for the parent.""" def integrand(psi_baseline, Al, deltaz, c ): ...
9a01a8c02aa51db0a675e94bf32d6a4b26a13206
24,654
def create_train_val_set(x_train, one_hot_train_labels): """[summary] Parameters ---------- x_train : [type] [description] y_train : [type] [description] """ x_val = x_train[:1000] partial_x_train = x_train[1000:] y_val = one_hot_train_labels[:1000] partial_y_tr...
dd0b3ca06b3d8bdae8e75284b17eb60ba6bbe36b
24,655
import os import shutil def build_master_and_get_version(): """Checks out the latest master build and creates a new binary.""" if not os.path.exists(TOOL_SOURCE): process.call( 'git clone https://github.com/google/clusterfuzz-tools.git', cwd=HOME) process.call('git fetch', cwd=TOOL_SOURCE) process...
040e1f78e80bb36b1a8323c7590a9db8bbde46e8
24,656
def get_adj_date(time,today): """ """ #print(time,today) if 'month' in time: week_multiplier = 28 elif 'week' in time: week_multiplier = 7 elif 'day' in time: week_multiplier = 1 else: week_multiplier = 0 # Hack! updated from 01.12.2020 # TOD...
930273bc313d241b7f0777290459195c5b4499d4
24,657
def update_dataset_temporal_attrs(dataset: xr.Dataset, update_existing: bool = False, in_place: bool = False) -> xr.Dataset: """ Update temporal CF/THREDDS attributes of given *dataset*. :param dataset: The dataset. :param update_exist...
99bb1a638e275a4788e2bd99122b67d3f0d5b536
24,658
def py_cpu_nms(dets, thresh): """Pure Python NMS baseline.""" x1 = dets[:, 0] y1 = dets[:, 1] x2 = dets[:, 2] y2 = dets[:, 3] scores = dets[:, 4] areas = (x2 - x1 + 1) * (y2 - y1 + 1) ## index for dets order = scores.argsort()[::-1] keep = [] while order.size > 0: i...
78d5b3c672142dc1861a2df11e6f1a4671467fd4
24,659
import itertools def _split_iterators(iterator, n=None): """Split itererator of tuples into multiple iterators. :param iterator: Iterator to be split. :param n: Amount of iterators it will be split in. toolz.peak can be used to determine this value, but that is not lazy. This is basically the same a...
25b9409941eaf958aef755c0124d4aee4a3a67e5
24,660
def get_league_listing(**kwargs): """ Get a list of leagues """ return make_request("GetLeaguelisting", **kwargs)
5b5fb9ee4f06a0ede684f6584fd3af0638c807a4
24,661
async def perhaps_this_is_it( disc_channel: disnake.TextChannel = commands.Param(lambda i: i.channel), large: int = commands.Param(0, large=True), ) -> PerhapsThis: """This description should not be shown Parameters ---------- disc_channel: A channel which should default to the current one - us...
158d9d6b278c5142d13e392becd9df35c2844961
24,662
def maybe_setup_moe_params(model_p: InstantiableParams): """Convert a FeedforwardLayer to a MoE Layer for StackedTransformer.""" if model_p.cls == layers.StackedTransformerRepeated: model_p = model_p.block if model_p.num_experts == 0: return model_p ff_p = model_p.transformer_layer_params_tpl.tr_fflay...
2ba82eb85ca85f8c16b3ee5de2d8ac3edb90275a
24,663
import re def verify_message( message ): """Verifies that a message is valid. i.e. it's similar to: 'daily-0400/20140207041736'""" r = re.compile( "^[a-z]+(-[0-9])?-([a-z]{3})?[0-9]+/[0-9]+" ) return r.match( message )
f25a37a5e3f076a647c0a03c26d8f2d2a8fd7b2e
24,664
def get_all_unicode_chars(): """Get all unicode characters.""" all_unicode_chars = [] i = 0 while True: try: all_unicode_chars.append(chr(i)) except ValueError: break i += 1 return all_unicode_chars
da63b26dd082987937b17fdfffb1219726d9d2c6
24,665
def get_east_asian_width_property(value, binary=False): """Get `EAST ASIAN WIDTH` property.""" obj = unidata.ascii_east_asian_width if binary else unidata.unicode_east_asian_width if value.startswith('^'): negated = value[1:] value = '^' + unidata.unicode_alias['eastasianwidth'].get(negate...
9eb8f70229a6d53faae071b641a39b79d8807941
24,666
def ModifyListRequest(instance_ref, args, req): """Parse arguments and construct list backups request.""" req.parent = instance_ref.RelativeName() if args.database: database = instance_ref.RelativeName() + '/databases/' + args.database req.filter = 'database="{}"'.format(database) return req
fde5a06cde30ed1cf163299dc8ae5f0e826e3f9d
24,667
import sys import locale def output_encoding(outfile=None): """Determine the encoding to use for output written to `outfile` or stdout.""" if outfile is None: outfile = sys.stdout encoding = ( getattr(outfile, "encoding", None) or getattr(sys.__stdout__, "encoding", None) or ...
872f8147a139c3747dda31254cf0a31d397baad7
24,668
from datetime import datetime def day_start(src_time): """Return the beginning of the day of the specified datetime""" return datetime(src_time.year, src_time.month, src_time.day)
2bcc7b136e5cb1e7929e6655daf67b07dbbaa542
24,669
def _construct_corrections_dict(file): """Construct a dictionary of corrections. Given the name of a .ifa corrections file, construct a dictionary where the keys are wavelengths (represented as integers) and the values are measures of the instrument sensitivity (represented as floats). Intensi...
972db28c3609357a0ce742bf6679fbb46b86ef7c
24,670
def get_activation_func(activation_label): """ Returns the activation function given the label Args: activation_label: Name of the function """ if activation_label == 'sigmoid': return tf.nn.sigmoid elif activation_label == 'identity': return tf.identity elif activation_l...
cfa1a46b9c40fe2680bfa49831ed09e222ef3335
24,671
def sim_share( df1, df2, group_pop_var1, total_pop_var1, group_pop_var2, total_pop_var2, ): """Simulate the spatial population distribution of a region using the CDF of a comparison region. For each spatial unit i in region 1, take the unit's percentile in the distribution, and swap the group share wit...
cc7857d6deb81e7224e4e21fe6908376c963169a
24,672
def fixextensions(peeps, picmap, basedir="."): """replaces image names with ones that actually exist in picmap""" fixed = [peeps[0].copy()] missing = [] for i in range(1, len(peeps)): name, ext = peeps[i][2].split(".", 1) if (name in picmap): fixed.append(peeps[i].copy()) ...
d2af911aacea80f7e25cbdde0f5dfad0f1757aee
24,673
def do_divide(data, interval): """ 使用贪心算法,得到“最优”的分段 """ category = [] p_value, chi2, index = divide_data(data, interval[0], interval[1]) if chi2 < 15: category.append(interval) else: category += do_divide(data, [interval[0], index]) category += do_divide(data, [index,...
2e25f913c664dd1cc3d60e4c3f89146b81476e3b
24,674
import json def get_config(key_path='/'): """ Return (sub-)configuration stored in config file. Note that values may differ from the current ``CONFIG`` variable if it was manipulated directly. Parameters ---------- key_path : str, optional ``'/'``-separated path to sub-configurati...
075b3cd021be67c5c2f23203236f839fc47a678b
24,675
import boto3, logging from botocore.exceptions import ClientError def find_cloudtrails(ocredentials, fRegion, fCloudTrailnames=None): """ ocredentials is an object with the following structure: - ['AccessKeyId'] holds the AWS_ACCESS_KEY - ['SecretAccessKey'] holds the AWS_SECRET_ACCESS_KEY - ['SessionToken'] ...
d20d27b3c630c3c8c34a86e41ba05c28eeffa5a3
24,676
def evaluate(sess, logits, loss, labels, img_name, dataset): """ Trains the network Args: sess: TF session logits: network logits """ conf_mat = np.ascontiguousarray( np.zeros((FLAGS.num_classes, FLAGS.num_classes), dtype=np.uint64)) loss_avg = 0 for i in trange(dataset.num_examples()): ...
c8be93950e4f33eeaeea19cc6759cf919373abbf
24,677
def _get_options(): """ Function that aggregates the configs for sumo and returns them as a list of dicts. """ if __mods__['config.get']('hubblestack:returner:sumo'): sumo_opts = [] returner_opts = __mods__['config.get']('hubblestack:returner:sumo') if not isinstance(returner_opt...
3d4d491b12f89501e7f5cdadda1d983676027367
24,678
from typing import Any from typing import Optional def convert_boolean(value: Any) -> Optional[bool]: """Convert a value from the ToonAPI to a boolean.""" if value is None: return None return bool(value)
d479898afe1bb8eaba3615a9e69a7a38637c6ec6
24,679
def Split4(thisBrep, cutters, normal, planView, intersectionTolerance, multiple=False): """ Splits a Brep into pieces using a combination of curves, to be extruded, and Breps as cutters. Args: cutters (IEnumerable<GeometryBase>): The curves, surfaces, faces and Breps to be used as cutters. Any othe...
74009e33a3da88c7d096e6835952014bc8b40ef9
24,680
def generate_passwords_brute_force(state): """ String Based Generation :param state: item position for response :return: """ if state is None: state = [0, 0] k, counter = state password = '' i = counter while i > 0: r = i % base password = alphabet[r] + pa...
11e503e53903c884545c2324e721ebcbad1eb7c2
24,681
from typing import Tuple import ctypes def tparse(instring: str, lenout: int = _default_len_out) -> Tuple[float, str]: """ Parse a time string and return seconds past the J2000 epoch on a formal calendar. https://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/tparse_c.html :param instring: Inp...
33b322062e7756d9bc1d728d9655adafd1c4d989
24,682
def align_decision_ref(id_human, title): """ In German, decisions are either referred to as 'Beschluss' or 'Entscheidung'. This function shall align the term used in the title with the term used in id_human. """ if 'Beschluss' in title: return id_human return id_human.replace('Be...
ac4f584b8e008576816d9a49dba58bc9c9a6dbc4
24,683
def get_headers(soup): """get nutrient headers from the soup""" headers = {'captions': [], 'units': []} footer = soup.find('tfoot') for cell in footer.findAll('td', {'class': 'nutrient-column'}): div = cell.find('div') headers['units'].append(div.text) headers['captions'].append...
5e7772a8830271f800791c75ef7ceecc98aba2bb
24,684
def table2rank(table, transpose=False, is_large_value_high_performance=True, add_averaged_rank=False): """ transform a performance value table to a rank table :param table: pandas DataFrame or numpy array, the table with performance values :param transpose: bool, whether to transpose table (default: Fal...
36b313b8c19f6767690b4ef6d76fcc4b5633865c
24,685
def F_z_i(z, t, r1, r2, A): """ Function F for Newton's method :param z: :param t: :param r1: :param r2: :param A: :return: F: function """ mu = mu_Earth C_z_i = c2(z) S_z_i = c3(z) y_z = r1 + r2 + A * (z * S_z_i - 1.0) / np.sqrt(C_z_i) F = (y_z / C_z_i) ** 1....
ca4af99f8722d8e932f58896120883f09e73fb1a
24,686
from tayph.vartests import typetest import numpy as np from astropy.stats import mad_std def sigma_clip(array,nsigma=3.0,MAD=False): """This returns the n-sigma boundaries of an array, mainly used for scaling plots. Parameters ---------- array : list, np.ndarray The array from which the n-sig...
e62e76c0a92dde4de324a31ecc03968da18de7d3
24,687
def points_distance(xyz_1, xyz_2): """ :param xyz_1: :param xyz_2: :return: """ if len(xyz_1.shape) >= 2: distance = np.sqrt(np.sum((xyz_1 - xyz_2)**2, axis=1)) else: distance = np.sqrt(np.sum((xyz_1 - xyz_2)**2)) return distance
0acc6bf45c03ed554cb13c4375095871dee482fb
24,688
from typing import Optional def ensure_society(sess: SQLASession, name: str, description: str, role_email: Optional[str] = None) -> Collect[Society]: """ Register or update a society in the database. For existing societies, this will synchronise member relations with the given list of ...
49700a80ab23b0f4211c8bf5f0bc2c1d68c2f1cb
24,689
def odd_numbers_list(n): """ Returns the list of n first odd numbers """ return [2 * k - 1 for k in range(1, n + 1)]
2066cf07e926e41d358be0012a7f2a248c5987a7
24,690
def domain_delete(domainName): # noqa: E501 """domain_delete Remove the domain # noqa: E501 :param domainName: :type domainName: str :rtype: DefaultMessage """ return 'do some magic!'
a0865aa2ff4902ac5cf8a8c0ea9eb62e792af56b
24,691
from datetime import datetime def ParseDate(s): """ ParseDate(s) -> datetime This function converts a string containing the subset of ISO8601 that can be represented with xs:dateTime into a datetime object. As such it's suitable for parsing Collada's <created> and <modified> elements. The date must b...
d65e4bb51487d9cb22b910e3dc44e299882600b5
24,692
def kinetic_energy(atoms): """ Returns the kinetic energy (Da*angs/ps^2) of the atoms. """ en = 0.0 for a in atoms: vel = v3.mag(a.vel) en += 0.5 * a.mass * vel * vel return en
8615d61f30f5ded029d1c230346682a040d05e87
24,693
def boxes_intersect(boxes, box): """Determine whether a box intersects with any of the boxes listed""" x1, y1, x2, y2 = box if in_box(boxes, x1, y1) \ or in_box(boxes, x1, y2) \ or in_box(boxes, x2, y1) \ or in_box(boxes, x2, y2): return True return False
b2201e1501a7827b6db8ef63ebf468b3e1839800
24,694
def cumulative_mean_normalized_difference_function(df, n): """ Compute cumulative mean normalized difference function (CMND). :param df: Difference function :param n: length of data :return: cumulative mean normalized difference function :rtype: list """ # scipy method cmn_df = df[...
974c0bdaab0e8872ef746839c8d973604eab6929
24,695
from typing import Iterable def add_spaces_old(spaces: Iterable["zfit.Space"]): """Add two spaces and merge their limits if possible or return False. Args: spaces: Returns: Union[None, :py:class:`~zfit.Space`, bool]: Raises: LimitsIncompatibleError: if limits of the `spaces`...
9d7aced4502b79125f62b4b040fbb6b7aad9d832
24,696
def minimal_subject_transformer(index, minimal_subject, attributes, subject_types, subject_type_is, center, radius): """Construct the JSON object for a MinimalSubject.""" subdomain, type = minimal_subject.subdomain, minimal_subject.type # Gather all the attributes values...
3babc222c508850b8b5bdea551efa8c9e9bc0aa4
24,697
def beta_avg_inv_cdf(y, parameters, res=0.001): """ Compute the inverse cdf of the average of the k beta distributions. Parameters ---------- y : float A float between 0 and 1 (the range of the cdf) parameters : array of tuples Each tuple (alpha_i, beta_i) i...
01c266e21401f6f7ad624151aa40d195c9196453
24,698
def _aprime(pHI,pFA): """recursive private function for calculating A'""" pCR = 1 - pFA # use recursion to handle # cases below the diagonal defined by pHI == pFA if pFA > pHI: return 1 - _aprime(1-pHI ,1-pFA) # Pollack and Norman's (1964) A' measure # formula from Grier 1971 i...
3694dcdbc5da2c12bece51e85988245a60ebe811
24,699