content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def vec_moderates(vec, minv, maxv, inclusive=1): """return a integer array where values inside bounds are 1, else 0 if inclusive, values will also be set if they equal a bound return error code, new list success: 0, list error : 1, None""" if not vec: return 1, None i...
65696ba3d4cb8c43e231a4aae1c8cef83351fb07
32,300
def SideInfo(version_index, channel_mode, raw_data=None): """SideInfo(version_index, channel_mode, raw_data) -> object Return an object representing MPEG layer 3 side info, based on the given parameters. The class of the object varies based on the MPEG version and channel mode (only applicable fields are present, and...
af554b0b6ebc4c33846881b27c02fb648d82b5ca
32,301
def datetimeConvertor(date, month, year, time, timezone): """ Converts raw date/time data into an object of datetime class. """ Date = date + "/" + monthnumberSwap(month) + "/" + year Time = time + " " + timezone return dt.datetime.strptime(Date + " " + Time, "%d/%m/%Y %H:%M:%S %z")
a83e873ee9b9aa1737fffc61c80aa9204305d3fb
32,302
import pathlib def dump_gone(aspect_store: dict, indent=False) -> bool: """Not too dry ...""" return _dump(aspect_store, pathlib.Path('gone.json'), indent)
14df4567d0ffc80f9764afa50c725bc1d178e031
32,303
def loss_fn(params, model, data): """ Description: This is MSE loss function, again pay close attention to function signature as this is the function which is going to be differentiated, so params must be in its inputs. we do not need to vectorize this function as it is written with batching co...
cddd29becee4ce047b086130c7ce8cea114cb914
32,304
import copy def lufact(A): """ lufact(A) Compute the LU factorization of square matrix A, returning the factors. """ n = A.shape[0] L = eye(n) # puts ones on diagonal U = copy(A) # Gaussian elimination for j in range(n-1): for i in range(j+1,n): L[i,j] = U[i,j] / U[j,j] # row multiplier U[i,...
e04c20ede47019789e00dc375b84efa931fe2e1f
32,305
def get_city(msg): """ 提取消息中的地名 """ # 对消息进行分词和词性标注 words = posseg.lcut(msg) # 遍历 posseg.lcut 返回的列表 for word in words: # 每个元素是一个 pair 对象,包含 word 和 flag 两个属性,分别表示词和词性 if word.flag == 'ns': # ns 词性表示地名 return word.word return None
017f910090291fdc77cc22ce4bc3fc3699c2981b
32,306
from IPython.display import SVG import os def render_model(cobra_model, background_template=None, custom_css=None, figure_id=None, hide_unused=None, hide_unused_cofactors=None, inactive_alpha=1., figsize=None, label=None, fontsize=None, default_flux_width=2.5, flux_d...
3283bec0e30ce520ee3048f4526cc825d6aebb51
32,307
import logging def handle_config_defaults(config, num_params_fn): """Resolve dependencies within `config`. In particular, set hidden_size (if -1) according to num_params and make the embedding sizes default to the hidden size. Also, handle budgeting: if hidden_size is not provided (it is -1), but num_params ...
f72388bd0e425e65b0254527f2762ea88738ed8a
32,308
def get_cycle_time(string): """ Extract the cycle time text from the given string. None if not found. """ return _search_in_pattern(string, CYCLE_TIME_PATTERN, 1)
6d41a9f4b04f90b4a5a8d7892398bc080d41e519
32,309
async def async_unload_entry(hass: HomeAssistant, config_entry: ConfigEntry) -> bool: """Unload a config entry.""" unload_ok = await hass.config_entries.async_unload_platforms( config_entry, PLATFORMS ) hass.data[DOMAIN].pop(config_entry.entry_id, None) if not hass.data[DOMAIN]: has...
6e4bf924e6e04d03cc30de3a6d4b2f713dd05b32
32,310
import os def showFileOrFolder(pathUrl): """ Send the binary content of a file on the X drive """ #showRequest(pathUrl, request) pathLocal = abfBrowse.getLocalPath("X/"+pathUrl) print(" serving", os.path.basename(pathLocal)) if os.path.isdir(pathLocal): return f"directory index of...
fe0c88531e4f5ad571901ea16bde11fb1ba6b587
32,311
from typing import Union def get_scale_factor(unit: Union[str, float]) -> float: """ Get how many pts are in a unit. :param unit: A unit accepted by fpdf.FPDF :return: The number of points in that unit :raises FPDFException """ if isinstance(unit, (int, float)): return float(unit) ...
c95429436b96f883e5fcfe3b1680a9f35c5f27e3
32,312
def r2_score(y_true,y_pred): """Calculate the coefficient of determination.""" assert len(y_true)==len(y_pred) rss = sum_square_residuals(y_true,y_pred) tss = total_sum_squares(y_true) return 1 - rss/tss
7d2eba54db3d5682ec0ed22b5c09a65cf1e34e27
32,313
def give_name(fname): """ return name.csv """ if fname[:len( AUX_FILE) ] != AUX_FILE: # hide file # renaming with correct extension if fname[ -4: ]!= '.csv': if fname.find('.') > -1: fname = fname[: fname.find('.')]+'.csv' else: fname += '.csv'...
55f6241b7a57d7611fe2db1731d909bb5b4186ac
32,314
def categorize(document): """Categorize a document. Categorizes a document into the following categories [business, entertainment, politics, sport, tech]. Takes a string object as input and returns a string object. """ doc = clean(document) vector = doc2vec_model.infer_vector(doc.split(' '...
a085e08e7e8b7ff31e68a536e973b5131540e481
32,315
def delete_intent(token, aiid, intent_name): """Delete an Intent""" return fetch_api( '/intent/{aiid}?intent_name={intent_name}', token=token, aiid=aiid, intent_name=intent_name, method='delete' )
198ed90b176c2f08c3c681dfbb5deea52cfbcfa4
32,316
def report_all(df_select): """ report all values to a defined template """ if len(df_select) == 0: report_all = 'No similar events were reported on in online media' else: report_all = """ Similar events were reported on in online media. Below we provide a tabulated s...
d0e5f06416a467d7578f4748725301638b33d1bb
32,317
import urllib def get_filename_from_headers(response): """Extract filename from content-disposition headers if available.""" content_disposition = response.headers.get("content-disposition", None) if not content_disposition: return None entries = content_disposition.split(";") name_entry...
d4c54c3d19d72f2813e2d1d4afde567d0db0e1af
32,318
def names(as_object=False, p5_connection=None): """ Syntax: ArchiveIndex names Description: Returns the list of names of archive indexes. Return Values: -On Success: a list of names. If no archive indexes are configured, the command returns the string "<empty>" """ met...
1b1d00d70730b79ccab25e5ca101f752ad49cc1c
32,319
def regionvit_base_w14_224(pretrained=False, progress=True, **kwargs): """ Constructs the RegionViT-Base-w14-224 model. .. note:: RegionViT-Base-w14-224 model from `"RegionViT: Regional-to-Local Attention for Vision Transformers" <https://arxiv.org/pdf/2106.02689.pdf>`_. The required input ...
63983c4fe9cb5ed74e43e1c40b501f50fbaead56
32,320
import collections def create_executor_list(suites): """ Looks up what other resmoke suites run the tests specified in the suites parameter. Returns a dict keyed by suite name / executor, value is tests to run under that executor. """ memberships = collections.defaultdict(list) test_membe...
c9150b14ba086d9284acb2abdcd4592e7803a432
32,321
def calculate_great_circle(args): """one step of the great circle calculation""" lon1,lat1,lon2,lat2 = args radius = 3956.0 x = np.pi/180.0 a,b = (90.0-lat1)*(x),(90.0-lat2)*(x) theta = (lon2-lon1)*(x) c = np.arccos((np.cos(a)*np.cos(b)) + (np.sin(a)*np.sin(b)*np.co...
f0832b984382b2cd2879c40ab1249d68aacddd69
32,322
def divide(x,y): """div x from y""" return x/y
74adba33dfd3db2102f80a757024696308928e38
32,323
def execute(compile_state: CompileState, string: StringResource) -> NullResource: """ Executes the string at runtime and returns Null""" compile_state.ir.append(CommandNode(string.static_value)) return NullResource()
4785d9a527982eb723d120f47af2915b6b830795
32,324
import torch def fakeLabels(lth): """ lth (int): no of labels required """ label=torch.tensor([]) for i in range(lth): arr=np.zeros(c_dims) arr[0]=1 np.random.shuffle(arr) label=torch.cat((label,torch.tensor(arr).float().unsqueeze(0)),dim=0) return label
a2ffb4a7ff3b71bc789181130bc6042ff184ac9c
32,325
def load_canadian_senators(**kwargs): """ A history of Canadian senators in office.:: Size: (933,10) Example: Name Abbott, John Joseph Caldwell Political Affiliation at Appointment Liberal-Conservative Pro...
42ae6a455d3bed11275d211646ee6acd2da505b6
32,326
def _get_md5(filename): """Return the MD5 checksum of the passed file""" data = open(filename, "rb").read() r = md5(data) return r.hexdigest()
c86943841a1f8f8e296d82818c668c197f824373
32,327
def implements(numpy_func_string, func_type): """Register an __array_function__/__array_ufunc__ implementation for Quantity objects. """ def decorator(func): if func_type == "function": HANDLED_FUNCTIONS[numpy_func_string] = func elif func_type == "ufunc": HANDL...
ec0d843798c4c047d98cd9a76bcd862c3d5339e8
32,328
def r2(data1, data2): """Return the r-squared difference between data1 and data2. Parameters ---------- data1 : 1D array data2 : 1D array Returns ------- output: scalar (float) difference in the input data """ ss_res = 0.0 ss_tot = 0.0 mean = sum(data1) / l...
d42c06a5ad4448e74fcb1f61fa1eed1478f58048
32,329
from typing import IO def fio_color_hist_fio(image_fio): """Generate a fileIO with the color histogram of an image fileIO :param image_fio: input image in fileIO format :type image_fio: fileIO :return: color histogram of the input image in fileIO format :rtype: fileIO """ image_fio.seek(0...
13c10cce5dc9bfa17d19a4b2f486fb7b34bcb176
32,330
def store_list(request, user_id): """ Verify user has the access to enlist store. """ logger.debug('calling store.views.store_list()') user_name = request.user.username menu = MenuService.new_user_menu(request.user) context = { 'menu':menu, 'page_title': 'Profile', ...
a6e17acb2ddba850f84d12ae1db9ceca0f83958f
32,331
def lattice2d_fixed_env(): """Lattice2DEnv with a fixed sequence""" seq = 'HHHH' return Lattice2DEnv(seq)
664b6b411a47018c460b09909ccb29c033bae2e5
32,332
import time import logging def expected_full( clr, view_df=None, smooth_cis=False, aggregate_smoothed=False, smooth_sigma=0.1, aggregate_trans=False, expected_column_name="expected", ignore_diags=2, clr_weight_name='weight', chunksize=10_...
5f387c71f059cd942ff1ff4b6cdb6a59e91ef85b
32,333
def nmgy2abmag(flux, flux_ivar=None): """ Conversion from nanomaggies to AB mag as used in the DECALS survey flux_ivar= Inverse variance oF DECAM_FLUX (1/nanomaggies^2) """ lenf = len(flux) if lenf > 1: ii = np.where(flux>0) mag = 99.99 + np.zeros_like(flux) mag[ii] = 22....
5f65a06049955b4ddfe235d6fc12ae5726089b0f
32,334
def rnn_decoder(dec_input, init_state, cell, infer, dnn_hidden_units, num_feat): """Decoder for RNN cell. Given list of LSTM hidden units and list of LSTM dropout output keep probabilities. Args: dec_input: List of tf.float64 current batch size by number of features matrix tensors input to the decod...
215691ac8b3191da46d01a17fd37e2be08174640
32,335
import torch def l1_loss(pre, gt): """ L1 loss """ return torch.nn.functional.l1_loss(pre, gt)
c552224b3a48f9cde201db9d0b2ee08cd6335861
32,336
def run_tnscope(align_bams, items, ref_file, assoc_files, region=None, out_file=None): """Call variants with Sentieon's TNscope somatic caller. """ if out_file is None: out_file = "%s-variants.vcf.gz" % utils.splitext_plus(align_bams[0])[0] if not utils.file_exists(out_file)...
a7e82dc94a9166bde47ad43dab2c778b2f7945d6
32,337
def get_product(product_id): """ Read a single Product This endpoint will return a product based on it's id """ app.logger.info("Request for product with id: %s", product_id) product = Product.find(product_id) if not product: raise NotFound("product with id '{}' was not found.".forma...
e9ee42be5f586aa0bbe08dfa5edefbd3b0bbc5d7
32,338
import re import string def aips_bintable_fortran_fields_to_dtype_conversion(aips_type): """Given AIPS fortran format of binary table (BT) fields, returns corresponding numpy dtype format and shape. Examples: 4J => array of 4 32bit integers, E(4,32) => two dimensional array with 4 columns and 32 rows....
772bd75ff2af92cede5e5dac555662c9d97c544a
32,339
def account_list(): """获取账户列表""" rps = {} rps["status"] = True account_list = query_account_list(db) if account_list: rps["data"] = account_list else: rps["status"] = False rps["data"] = "账户列表为空" return jsonify(rps)
3ab704e96cbf2c6548bf39f51a7f8c6f77352b6c
32,340
def sample_points_in_range(min_range, max_range, origin, directions, n_points): """Sample uniformly depth planes in a depth range set to [min_range, max_range] Arguments --------- min_range: int, The minimum depth range max_range: int, The maximum depth range origin: tensor(shape=(4, 1),...
6cc33a77e58a573315caf51b907cd881029e7ea1
32,341
from typing import Counter def normalize(vectorOrCounter): """ normalize a vector or counter by dividing each value by the sum of all values """ normalizedCounter = Counter() if type(vectorOrCounter) == type(normalizedCounter): counter = vectorOrCounter total = float(counter.totalC...
8d4cb0f8be4e7c6eeaba6b49d5a84b024f2c91b9
32,342
def IsStringInt(string_to_check): """Checks whether or not the given string can be converted to an int.""" try: int(string_to_check) return True except ValueError: return False
75d83ce78fca205457d4e4325bca80306f248e08
32,343
import os import codecs def read(*parts): """ Build an absolute path from *parts* and return the contents of the resulting file. Assume UTF-8 encoding. """ here = os.path.abspath(os.path.dirname(__file__)) with codecs.open(os.path.join(here, *parts), 'rb', 'utf-8') as f: return f.read...
76346f4c016e9a053c25f0478a46f94813da2812
32,344
import torch import math def build_ewc_posterior(data_handlers, mnet, device, config, shared, logger, writer, num_trained, task_id=None): """Build a normal posterior after having trained using EWC. The posterior is constructed as described in function :func:`test`. Args: ...
dd04d235a36516ea600eec154f5a8952ee6ea889
32,345
def get_roc_curve(y_gold_standard,y_predicted): """ Computes the Receiver Operating Characteristic. Keyword arguments: y_gold_standard -- Expected labels. y_predicted -- Predicted labels """ return roc_curve(y_gold_standard, y_predicted)
b522ee6566004ec97781585be0ed8946e8f2889e
32,346
def get_image_unixtime2(ibs, gid_list): """ alias for get_image_unixtime_asfloat """ return ibs.get_image_unixtime_asfloat(gid_list)
2c5fb29359d7a1128fab693d8321d48c8dda782b
32,347
def create_sql_query(mogrify, data_set_id, user_query): """ Creates a sql query and a funtion which transforms the output into a list of dictionaries with correct field names. >>> from tests.support.test_helpers import mock_mogrify >>> query, fn = create_sql_query(mock_mogrify, 'some-collection', Q...
ac56dd8b89da7554111f4e285eb9511fbdef5ced
32,348
def patch_hass(): """ Patch the Hass API and returns a tuple of: - The patched functions (as Dict) - A callback to un-patch all functions """ class MockInfo: """Holds information about a function that will be mocked""" def __init__(self, object_to_patch, function_name, autospec=F...
400bb38ca7f00da3b1a28bc1ab5c2408be2931c9
32,349
def compute_coherence_values(dictionary, corpus, texts, limit, start=2, step=3): """ Compute c_v coherence for various number of topics Parameters: ---------- dictionary : Gensim dictionary corpus : Gensim corpus texts : List of input texts limit : Max num of topics Returns: ----...
009f637b7ff1d92514711ca5566f2c2c7ee307b0
32,350
def parallax_angle(sc, **kw) -> DEG: """Compute parallax angle from skycoord. Parameters ---------- sc: SkyCoord ** warning: check if skycoord frame centered on Earth Returns ------- p: deg parallax angle """ return np.arctan(1 * AU / sc.spherical.distance)
0d84a98cae93828d1166008fe3d654668a4a178e
32,351
def formatting_dates(dates_list): """ Formatting of both the start and end dates of a historical period. dates = [period_start_date, period_end_date]""" new_dates = dates_list # Change all "BCE" into "BC": for index1 in range(len(new_dates)): if " BCE" not in new_dates[index1]: ...
174617ad0a97c895187f8c1abe7e6eb53f59da6f
32,352
from datetime import datetime def exp_days_f(cppm_class, current_user): """ User's password expiration and check force change password function. 1. Calculates days to expiry password for particular user 2. Checks change password force checkbox. Returns: exp_days: Number of days unt...
e0f014fe4813dd70fd733aa2ed2fa4f06105c2f0
32,353
def isinteger(x): """ determine if a string can be converted to an integer """ try: a = int(x) except ValueError: return False except TypeError: return False else: return True
b39530a79c39f0937a42335587f30bed26c6ce0a
32,354
import os def get_economic_parameters(): """ Extracts and returns the parameters for the economic model This function returns a dictionary with all parameters needed to run the economic model. Returns ------- pars_dict : dictionary contains the values of all economic parameters ...
a2b3630ba67f8430c27476ce97d31361342b656a
32,355
import sys import json import math def recommend(docs_path, dict_path, use_fos_annot=False, pp_dict_path=None, np_dict_path=None, lda_preselect=False, combine_train_contexts=True): """ Recommend """ test = [] train_mids = [] train_texts = [] train_foss = [] tra...
5f5ecefb77a639fa36879b930775b4597be32933
32,356
import hashlib def _get_hash(x): """Generate a hash from a string, or dictionary.""" if isinstance(x, dict): x = tuple(sorted(pair for pair in x.items())) return hashlib.md5(bytes(repr(x), "utf-8")).hexdigest()
c47f96c1e7bfc5fd9e7952b471516fbf40470799
32,357
def wrap_arr(arr, wrapLow=-90.0, wrapHigh=90.0): """Wrap the values in an array (e.g., angles).""" rng = wrapHigh - wrapLow arr = ((arr-wrapLow) % rng) + wrapLow return arr
e07e8916ec060aa327c9c112a2e5232b9155186b
32,358
def task_fail_slack_alert(context): """ Callback task that can be used in DAG to alert of failure task completion Args: context (dict): Context variable passed in from Airflow Returns: None: Calls the SlackWebhookOperator execute method internally """ if ENV != "data": re...
392d5f3b1df21d8dbe239e700b7ea0bd1d44c49f
32,359
def largest_negative_number(seq_seq): """ Returns the largest NEGATIVE number in the given sequence of sequences of numbers. Returns None if there are no negative numbers in the sequence of sequences. For example, if the given argument is: [(30, -5, 8, -20), (100, -2.6, 88, -40, -...
b7326b3101d29fcc0b8f5921eede18a748af71b7
32,360
def align_quaternion_frames(target_skeleton, frames): """align quaternions for blending src: http://physicsforgames.blogspot.de/2010/02/quaternions.html """ ref_frame = None new_frames = [] for frame in frames: if ref_frame is None: ref_frame = frame else: ...
7c8d6f4bacfb3581dc023504b94d2fba66c5e875
32,361
import math def do_round(precision=0, method='common'): """ Round the number to a given precision. The first parameter specifies the precision (default is ``0``), the second the rounding method: - ``'common'`` rounds either up or down - ``'ceil'`` always rounds up - ``'floor'`` always rou...
3e2b4c6c842ca5c3f60951559a815f27cc8edd19
32,362
import torch def scale_invariant_signal_distortion_ratio(preds: Tensor, target: Tensor, zero_mean: bool = False) -> Tensor: """Calculates Scale-invariant signal-to-distortion ratio (SI-SDR) metric. The SI-SDR value is in general considered an overall measure of how good a source sound. Args: pred...
2ec9e4d3cbd0046940974f8d7bae32e230da63ed
32,363
import json from datetime import datetime def is_token_valid(): """Check whether the stored token is still valid. :returns: A bool. """ try: with open('/tmp/tngcli.txt', 'r') as file: for line in file: payload = json.loads(line) except: return Fal...
2574245a38a02bdba7b2fee8f5dff807b128316f
32,364
def DB_getQanswer(question): """ Calls the function in the database that gets the question answer to the input question. """ return DB.get_question_answer(question)
8afb32f1e8b39d3ff89b3c9fe02a314099a416ef
32,365
def _state_senate_slide_preview(slug): """ Preview a state slide outside of the stack. """ context = make_context() resp = _state_senate_slide(slug) if resp.status_code == 200: context['body'] = resp.data return render_template('slide_preview.html', **context) else: ...
c9139df85745feca150fd22591e85165969952de
32,366
def tensor_network_tt_einsum(inputs, states, output_size, rank_vals, bias, bias_start=0.0): # print("Using Einsum Tensor-Train decomposition.") """tensor train decomposition for the full tenosr """ num_orders = len(rank_vals)+1#alpha_1 to alpha_{K-1} num_lags = len(states) batch_size = tf.shape(in...
b9cabf2e76e3b18d73d53968b4578bedc3d7bb7e
32,367
from .observable.case import case_ from typing import Callable from typing import Mapping from typing import Optional from typing import Union def case( mapper: Callable[[], _TKey], sources: Mapping[_TKey, Observable[_T]], default_source: Optional[Union[Observable[_T], "Future[_T]"]] = None, ) -> Observab...
3ecc790a3e6e7e30e4f0a34e06dbfc9e2875388c
32,368
from typing import Tuple import json def group_to_stats(request, project_id) -> Tuple: """ Combining the same actions for grouping data for chart """ filters = json.loads(request.query_params.get('filters', '{}')) # date time, issue type, method group_by = request.query_params.get('groupBy', 'hou...
7a27fa180fd0e1bf059d11bd7995cdea0a85c6cf
32,369
def build_delete(table, where): """ Build a delete request. Parameters ---------- table : str Table where query will be directed. where: iterable The list of conditions to constrain the query. Returns ------- str Built query. """ sql_q = "DELETE " ...
1f065b5905b6c7af4e19863ae48e228358278f06
32,370
def filter_resources_sets(used_resources_sets, resources_sets, expand_resources_set, reduce_resources_set): """ Filter resources_set used with resources_sets defined. It will block a resources_set from resources_sets if an used_resources_set in a subset of a resources_set""" resources_expand = [expand_...
2ecd752a0460fff99ecc6b8c34ed28782e848923
32,371
def get_index_base(): """获取上海及深圳指数代码、名称表""" url_fmt = 'http://quotes.money.163.com/hs/service/hsindexrank.php?host=/hs/service/' url_fmt += 'hsindexrank.php&page={page}&query=IS_INDEX:true;EXCHANGE:CNSE{ex}&fields=no,SYMBOL,NAME&' url_fmt += 'sort=SYMBOL&order=asc&count={count}&type=query' one_big_i...
4639e94d9412967c0a5403a5e49fc43c8033c40b
32,372
def merge_list_of_dicts(old, new, key): """ Merge a list of dictionary items based on a specific key. Dictionaries inside the list with a matching key get merged together. Assumes that a value for the given key is unique and appears only once. Example: list1 = [{"name": "one", "data": "stuff"...
a56c0b3476ea67d6b77126a34c14005aad345cfa
32,373
from masci_tools.util.schema_dict_util import read_constants, eval_simple_xpath from masci_tools.util.schema_dict_util import evaluate_text, evaluate_attribute from masci_tools.util.xml.common_functions import clear_xml def get_kpoints_data_max4(xmltree, schema_dict, logger=None, convert_to_angstroem=True): """ ...
23001a430e8cb1b2434fce7de67e5249f345806c
32,374
def permission_required_on_object( perm, object_getter, login_url=None, handle_access_error=None, raise_exception=False ): """ Decorator for views that checks whether a user has a particular permission enabled, redirecting to the log-in page if necessary. If the raise_exception parameter is given th...
08c6544f2e9fdd60b4b16f162c1d0ab06e2c2a0e
32,375
def contains_badwords(string): """ Return whether a string contains bad words """ return any([x in string for x in bad_words])
499e338599441e24845a19ba8504a77bd7838d8e
32,376
from os.path import join def get_cluster_info(metadata, consensus_subjects=None): """ Construct cluster centroids and tractograms in MNI space from test session so can run `match_clusters` Identify `consensus_subject` for the test session n_clusters using `metadata['algorithm']`. The consensus su...
3262456326bc4a4e98ced48955347072e71d258b
32,377
import logging def probe_all_devices(driver_config_fname): """ Acquiring states of all devies, added to config. States could be: alive - device is working in normal mode and answering to modbus commands in_bootloader - device could not boot it's rom disconnected - a dummy-record in...
ee3e3b1e1f47011fb9dee04077406c170c82e537
32,378
def _learn_individual_mixture_weights(n_users, alpha, multinomials, max_iter, tol, val_mat, prior_strength, num_proc): """ Learns the mixing weights for each individual user, uses multiple-processes to make it faster. :param n_users: Int, total number of users. :param alpha: prior (learned through glob...
7ee9020685ec8fc0538ce4695fcefedc6280d55e
32,379
def banana(cls): """ A decorator for a class that adds the ability to create Permissions and Handlers from their Checks. """ cls.__checks = set() # Basically tell checks that we are the class, not a medium to pass things through cls.__banana = True cls_annotations = cls.__dict__.get("_...
6392d5a7e029dca556c92f4d7546fb6f76078858
32,380
def residual_v2_conv( kernel_size: int, stride: int, depth: int, is_deconv: bool, add_max_pool: bool, add_bias: bool, is_train: bool, input_op: tf.Tensor, name: str = None, ) -> tf.Tensor: """Creates a residual convolution in the style of He et al. April 2016. This is the second...
63d7589caed876ed9b0d3617442e6d676555c791
32,381
def dump_cups_with_first(cups: list[int]) -> str: """Dump list of cups with highlighting the first one :param cups: list of digits :return: list of cups in string format """ dump_cup = lambda i, cup: f'({cup})' if i == 0 else f' {cup} ' ret_val = ''.join([dump_cup(i, cup) for i, cup in enumerat...
5fe4111f09044c6afc0fbd0870c2b5d548bd3c1a
32,382
def init(strKernel, iKernelPar=1, iALDth=1e-4, iMaxDict=1e3): """ Function initializes krls dictionary. |br| Args: strKernel (string): Type of the kernel iKernelPar (float): Kernel parameter [default = 1] iALDth (float): ALD threshold [default = 1e-4] iMaxDict (int): Max...
652e0c498b4341e74bcd30ca7119163345c7f2cc
32,383
def prune_scope(): """Provides a scope in which Pruned layers and models can be deserialized. For TF 2.X: this is not needed for SavedModel or TF checkpoints, which are the recommended serialization formats. For TF 1.X: if a tf.keras h5 model or layer has been pruned, it needs to be within this scope to b...
64569464611640ac5c13cbb0bf41c3f7ba16424a
32,384
import platform import subprocess import os import shutil def _find_chrome(user_given_executable=None): """ Finds a Chrome executable. Search Chrome on a given path. If no path given, try to find Chrome or Chromium-browser on a Windows or Unix system. Parameters ---------- - `user_given_exec...
41e00f7cb3de662c88abfddf09fd27991448639d
32,385
import re def is_valid_br_cnpj(cnpj): """ Accept an string parameter cnpj and Check if is brazilian CNPJ valid. Return True or False """ # Extract dots, stroke, slash cnpj = re.sub('[.|\-/|/]', '', str(cnpj)) # if does not contain numerical characters if not re.match(r'^\d{14}$',...
f41f9814cfef7d75e287834ac2a5514d03cd8fdb
32,386
def get_supported_locales(): """ Returns a list of Locale objects that the Web Interfaces supports """ locales = BABEL.list_translations() locales.append(Locale("en")) sorted_locales = sorted(locales, key=lambda x: x.language) return sorted_locales
3068889d0c7888b23f207d3397e0aec58418cef2
32,387
from typing import Optional from pathlib import Path import site def get_pipx_user_bin_path() -> Optional[Path]: """Returns None if pipx is not installed using `pip --user` Otherwise returns parent dir of pipx binary """ # NOTE: using this method to detect pip user-installed pipx will return # N...
ccf9b886af41b73c7e2060704d45781938d8e811
32,388
def _normalize_int_key(key, length, axis_name=None): """ Normalizes an integer signal key. Leaves a nonnegative key as it is, but converts a negative key to the equivalent nonnegative one. """ axis_text = '' if axis_name is None else axis_name + ' ' if key < -length o...
9b58b09e70c20c9ac5ee0be059333dd5058802ef
32,389
def create_interview_in_jobma(interview): """ Create a new interview on Jobma Args: interview (Interview): An interview object """ client = get_jobma_client() url = urljoin(settings.JOBMA_BASE_URL, "interviews") job = interview.job first_name, last_name = get_first_and_last_name...
36834c0e6557627a52a179b9d8529d5693cc92cb
32,390
def get_solutions(N, K, W_hat, x): """ Get valid indices of x that sum up to S """ # Scalar form of y = W_hat * x S = scalar(W_hat @ x) # print(f'Scalar value = {S}') solutions = [] for partition in sum_to_S(S, K): if len(set(partition)) == len(partition) and max(partition) < N: ...
6de6b0f77070b40f6e0028009f9b96264f6daa64
32,391
def get_actual_order(geometry, order): """ Return the actual integration order for given geometry. Parameters ---------- geometry : str The geometry key describing the integration domain, see the keys of `quadrature_tables`. Returns ------- order : int If `order...
876c9a70418de7d4768ab0234abb86bf676884c0
32,392
def getcwd(*args,**kw): """getcwd() -> path Return a unicode string representing the current working directory.""" return __BRYTHON__.brython_path
1d0e9491a2a35b326ec87314887fb1dede23c927
32,393
def sample_graph(B, logvars, n_samp): """ Generate data given B matrix, variances """ p = len(logvars) N = np.random.normal(0, np.sqrt(np.exp(logvars)), size=(n_samp, p)) return (np.linalg.inv(np.eye(p) - B.T)@N.T).T
2e798035bcb807e670ff9b9f4a39236ffe6b1157
32,394
def rotate_ne_rt(n, e, ba): """ Rotates horizontal components of a seismogram. The North- and East-Component of a seismogram will be rotated in Radial and Transversal Component. The angle is given as the back-azimuth, that is defined as the angle measured between the vector pointing from the statio...
c374ad762e122b519698bd1c199e2aa773e295cb
32,395
def pwgen(pw_len=16): """ Generate a random password with the given length. Allowed chars does not have "I" or "O" or letters and digits that look similar -- just to avoid confusion. """ return get_random_string(pw_len, 'abcdefghjkmnpqrstuvwxyz' 'ABCDEFGH...
747bb049ad3cca47d3898f0ea6b52108938aa2b2
32,396
import os import subprocess import warnings def run_zeopp(structure: Structure) -> dict: """Run zeopp with network -ha -res (http://www.zeoplusplus.org/examples.html) to find the pore diameters Args: structure (Structure): pymatgen Structure object Returns: dict: pore analysis result...
1cecb39ce4350e86076dc59a0cea2525b51bd4d0
32,397
import requests from bs4 import BeautifulSoup def get_property_data(sch=""): """Get property id and return dictionary with data Attributes: sch: property id """ property_url = "http://ats.jeffco.us/ats/displaygeneral.do?sch={0}".format(sch) r = requests.get(property_url) property_page = ...
d7a0f462340c75d14f00a1712923988b415258fb
32,398
import os def sanitize_fname(fname): """ Ensures that fname is a path under the current working directory. """ root_dir = os.getcwd() return opath.join( bytes(root_dir, encoding='ascii'), opath.normpath( b'/' + fname).lstrip(b'/'))
3aae8a62effce58152f722032615aa33468b8239
32,399