content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def create_observable_df() -> pd.DataFrame: """Create empty observable dataframe Returns: Created DataFrame """ df = pd.DataFrame(data={col: [] for col in OBSERVABLE_DF_COLS}) return df
bd4df4b42115e8ddf74188060412d8a3a0a95437
45,477
def MST(N_mels,sequence_samples,audio_win,audio_hop): """ Return SMel as a keras model Parameters ---------- N_mels : int Number of mel bands sequence_samples : int Number of samples in each input audio_win : int Number of samples in each frame audio_hop : int ...
34a82fcb1bb87181e0a98c1369e960fd4b381395
45,478
def maximum_gap_in_days(col: pd.Series) -> int: """Compute maximum gap in a series of dates (2020-01-01 - 2020-01-02 -> gap = 0 days) :param col: pd.Series of dates :return: greatest gap """ return col.sort_values().diff().max().days - 1
6b8e07d87a19e8df15c74105d98689f942c8c06f
45,479
def get_resource_endpoint(host, hpc_backend): """ Get ssh URI of remote host :param host: host to make url for it :param hpc_backend: hpc_backend integer value according to HPCBackend enum :return: """ # Default SAGA adaptor to ssh adaptor = 'ssh' if helpers.is_localhost(host): ...
c389ed510215ff2c2b15b1e31584d9c8bb05f6ab
45,480
def wrap_function(lib, funcname, restype, argtypes): """Simplify wrapping ctypes functions""" func = lib.__getattr__(funcname) func.restype = restype func.argtypes = argtypes return func
c57334afd98c1571a25af7648c81d7058f26e225
45,481
def get( policy_class=None, return_full_policy_names=True, hierarchical_return=False, adml_language="en-US", return_not_configured=False, ): """ Get a policy value Args: policy_class (str): Some policies are both user and computer, by default all policies ...
f4c76261c9f8e0f34fd12944e8327ac614cb09c1
45,482
def add_graph_nodes(data_graph, root_city, wikicities, root_city_attributes): """ add_graph_nodes adds nodes to a graph and returns the new graph @param data_graph: the current graph @param root_city: the root city @param wikicities: all catched cities @param root_city_attributes: attributes of ...
b8faca149e5a1aa068ba01375789ea1b588dc39e
45,483
def pairwise_distances_euclidean(points): """Return the matrix of pairwise euclidean distances between points. Parameters ---------- points: 2d numpy.array The coordinates of the point, points[0, :] and points[1, :] corresponding to x's and y's respectively. Returns ------- ...
a53d5287b6e6dfc673ced2670b9126a47afe373d
45,485
def check_dtype(h5_dset): """ Checks the datatype of the input HDF5 dataset and provides the appropriate function calls to convert it to a float Parameters ---------- h5_dset : :class:`h5py.Dataset` Dataset of interest Returns ------- func : callable function that w...
438a1655f0c8071f73c5662b2fbc440bedc004b1
45,486
def stdev_fuel_per_hour(iterable): """ >>> round(stdev_fuel_per_hour(clean_data(row_merge(log_rows))), 4) 0.0897 """ return stdev(row.fuel_per_hour for row in iterable)
ec5d99a81820a43a7be110dec89c9dcf9c2f9017
45,487
def stratified_mean_squared_error(observed, predicted, idx, verbose=False): """ Computes the stratified mean squared error (MSE) values. Stratified MSE is computed separately in each bin (cluster) of an observed dependent variable, :math:`\\phi_o`. MSE in the :math:`j^{th}` bin can be computed as: ...
f3e3004680bc38328ed44cbad2e0f6d80f90bfca
45,488
def modify_ldap_config(): """ 修改ldap模块信息 :return: """ try: put_data = request.get_json(force=True) ldap_host = put_data.get("ldap_host") bind_dn = put_data.get("ldap_bind_dn") bind_dn_password = put_data.get("ldap_bind_dn_password") base_dn = put_data.get("l...
0ba7af4d7eddd9ca1fc9a1193e3c44ff33fd5eba
45,490
def gallows(wrong_times): """ This function is to make the gallows, which is based on the times of wrong guess. :param wrong_times: N_TURNS - left_turns :return: The previous 6 steps is to hang man, if N_TURNS > 7, the 7th to the (N_TURNS -1)th look of gallows would be the same as 'g6'. ...
090986fbc42075bc8f0ad93b39bcb740a5adc407
45,491
def create_sorted_poly_list(poly2d_vector:_Poly2DVector): """ Create a SortedPolyList from the values provided in metadata classes of base type _Poly2DVector :param poly2d_vector: :return sorted_poly_list: """ return SortedPolyList(list_generic_poly=[_create_generic_poly(p) for p in poly2d_vect...
dcfedf7bf4189a897f8c721bcd15cfbb51cd8d5e
45,492
def rgb_to_hls(arr): """ fast rgb_to_hls using numpy array """ # adapted from Arnar Flatberg # http://www.mail-archive.com/numpy-discussion@scipy.org/msg06147.html arr = arr.astype("float32") / 255.0 out = np.empty_like(arr) arr_max = arr.max(-1) delta = arr.ptp(-1) arr_min = arr.min(...
2ea069d17eadda15ee2351957a42358a9475cf06
45,493
def shp2geojsonOgr(layer): """Shapefile to Geojson conversion using ogr.""" cmd = 'ogr2ogr -f GeoJSON -t_srs'\ + ' crs:84'\ + ' {layer}.geojson'\ + ' {layer}.shp' cmd = cmd.format(layer=layer) return cmd
a1bbf42d83cf9d26542c02eb1a16da971a7d0a9e
45,494
def gluon_seresnext101_32x4d(pretrained=False, num_classes=1000, in_chans=3, **kwargs): """Constructs a SEResNeXt-101-32x4d model. """ default_cfg = default_cfgs['gluon_seresnext101_32x4d'] model = ResNet( Bottleneck, [3, 4, 23, 3], cardinality=32, base_width=4, use_se=True, num_classes=...
48d7e43c4c8941da0bdc779ec7d97c0c18d91332
45,495
def lut_canonical_potential_edge(potential_edge): """Returns a canonical name of a potential edge, with respect to LUT height. Parameters ---------- potential_edge : str Instantiated name of the potential edge to be canonicized. Returns ------- str A canonical potential edg...
ccae7b98de4aa18a2ffa72c0faf6b0fe7b001db0
45,496
def safe_std(data): """Remove zero std values for ones.""" std = np.std(data, axis=0) return np.array([val if val != 0.0 else 1.0 for val in std])
f1d8676a9460d3235e4b8869ec0223da70c1f61d
45,497
def country_list_nlp(cts): """NLP countries so we can use for vector comparisons""" ct_nlp = [] for i in cts.keys(): nlped = nlp(i) ct_nlp.append(nlped) return ct_nlp
4f7c94c0ecd2d82234881b9d11b67f3e3a6de339
45,498
def is_unique_column(df_column: pd.Series) -> bool: """Check if a column has unique non-empty values. :param df_column: Column of a pandas data frame :return: Boolean encoding if the column has unique values """ return len(df_column.dropna().unique()) == len(df_column)
2da7bb94f445d556a617d98830e5d4418364d0f8
45,499
def profile_edit(request, username, edit_profile_form=EditProfileForm, template_name='userena/profile_form.html', success_url=None, extra_context=None, **kwargs): """ Edit profile. Edits a profile selected by the supplied username. First checks permissions if the user ...
8b318b9e4fc170e1622cc3a0ea37fd0e62c1a356
45,500
def minimal_medium( models: CommunityModelDirectory, min_growth: float = 0.1, threads: int = 1 ) -> pd.DataFrame: """Calculate the minimal medium for a set of community models.""" manifest = models.manifest.view(pd.DataFrame) model_folder = str(models.model_files.path_maker(model_id="blub")).replace( ...
2e23579b05d1102a18dddc30ba1aa088c91d07c5
45,501
def ais_singleiter( y_pred, y_test, prob_pos, sample_budget, g, alpha, known_rows, filter_rows ): """Perform a single AIS iteration of calibration + sampling. Args: y_pred: model predictions (k,) y_test: ground-truth labels for sampled rows (samples,) prob_pos: model scores (k,) ...
c56acbd47c0b04dfc45ce25be97231a80ebbbab2
45,502
def request_user_has_rule_trigger_permission(request, trigger): """ Check that the currently logged-in has necessary permissions on the trigger used / referenced inside the rule. """ if not cfg.CONF.rbac.enable: return True user_db = get_user_db_from_request(request=request) rules_r...
b72be83203f3ae49fb99b939c03b604985401f27
45,503
import collections def dict_update(d, u): """Update dict d based on u recursively.""" for k, v in u.items(): if isinstance(v, collections.Mapping): d[k] = dict_update(d.get(k, {}), v) else: d[k] = v return d
c1228442e280bf14424a9c7abb9dae82d0ee46f0
45,504
import re def soft_break(value, length, process=lambda chunk: chunk): """ Encourages soft breaking of text values above a maximum length by adding zero-width spaces after common delimeters, as well as soft-hyphenating long identifiers. """ delimiters = re.compile(r'([{}]+)'.format(''.join(map(...
66e43db80582ee2fcceb72303adf939dd5ada8f1
45,505
def flip(function): """ Returns a function which behaves like `function` but gets the given positional arguments reversed; keyword arguments are passed through. >>> from brownie.functional import flip >>> def f(a, b): return a >>> f(1, 2) 1 >>> flip(f)(1, 2) 2 """ @wraps(fun...
86fb3cb5a5f60a195a6b71fb77eaefb1aa24706d
45,506
def org_has_prescribing(org_type, org_id): """ Return whether this org has any prescribing data associated with it """ row_grouper = get_row_grouper(org_type) return org_id in row_grouper.offsets
e1f393f3251743d7cc62818831f6a6d7597d4f46
45,507
def get_or_create_experiment(experiment_name: str) -> mlflow.entities.Experiment: """ Returns an existing MLflow experiment if it exists, otherwise it creates a new one. Args: experiment_name (str): The name or ID of the experiment. Returns: mlflow.experiment: The found or created expe...
7bb587119bba792b66945e8a2988893198c08b06
45,508
def data_generator(metric): """ finding gamma for NNC and generating files to train and test data sets :param metric: string of metric name :return: X_train: vector with size of n_train of binary vectors with size of example_size X_test: vector with size of n_test of binary vectors with siz...
a5dc0ccf3c2f0c9db0935dc785705f16516c6569
45,509
def cal_total_variation_loss_v1(logits, gts=None, reduction="mean"): """ :param preds: (N,C,H,W) logits predicted by the model. :param gts: useless arg. :param reduction: specifies how all element-level loss is handled. :return: total_variation_loss """ probs = logits.simgoid() h, w = pr...
e76aec4a908374c61444051346e0d53b9ae2b5b1
45,510
def encode_boolean(value): """ Returns 1 or 0 if the value is True or False. None gets interpreted as False. Otherwise, the original value is returned. """ if value is True: return 1 if value is False or value is None: return 0 return value
4a6442438d3a7e85597ac76d2f48ce44ba505be2
45,511
def is_gauss_sum_separable(n,k): """ Returns true if gauss sum is separble for dirichlet characters mod k calculated for positive integer n Parameters ---------- n : int denotes positive integer for which dirichlet characters are calculated k : int denotes positive intger mod ...
459ca26a8052c57093e94b12ee833febec5b9001
45,512
def get_session(): """ Returns: the trident _SESSION """ return _SESSION
c4f05c57343779baee6f3aaa2c5a7834ea2ada8e
45,513
def clip_by_global_norm(max_norm) -> GradientTransformation: """Clip updates using their global norm. References: [Pascanu et al, 2012](https://arxiv.org/abs/1211.5063) Args: max_norm: the maximum global norm for an update. Returns: An (init_fn, update_fn) tuple. """ def init_fn(_): retu...
084f57223f13314a778ddd4627323a2529fe5e3d
45,514
def random_file_url(company): """ Generate a random image url string. Parameters: company: str The company name for the hostname. Return: str A generated url for an image on the company's host. """ url = "-".join(company.split()) return f"https://{ur...
80989c1a1cc860a66c101196a021adb093382e00
45,515
def validate_sami_id(candidate_sami_id): """Dummy validation function for SAMI IDs, always returns true.""" return True
302df887aeafb7e93437e5103a8e0b77fea72b6e
45,516
def get_binary_column_prob(dataset): """Returns a probability tuples for binary class = True and binary class = False for the binary column in the dataset""" binary_column = dataset.columns_that_are('binary')[0] a_count = 0 not_a_count = 0 for attr_value, class_value in zip(binary_column, da...
8d1c00eb0f930757719505ed032e1513650acd78
45,517
def get_workloads(month): """Calls the same method on the Month model.""" return month.get_workloads()
0b71297c0e244c07e8c832c69037f6b428b60316
45,519
def GetCrypter(secret): """Returns the Keyczar Crypter object returned by the secrets manager instance GetCrypter method.""" return GetSecretsManagerForSecret(secret).GetCrypter(secret)
6806063331a12f85bcaf4f7d57a2bd18fbb25b61
45,520
import copy def resample(image, target, mapping, shape, order=3): """ Resample an image to a target CoordinateMap with a "world-to-world" mapping and spline interpolation of a given order. Here, "world-to-world" refers to the fact that mapping should be a callable that takes a physical coordinate...
b96935c0007fcb818128499861e534216a759dbd
45,521
def roster_details(member_id): """Get the roster details for a particular member Decorators: ROSTER Arguments: member_id {[number]} -- [Id that uniquely identies this member] """ _db = DB() start_time = request.args.get("start_time") end_time = request.args.get("end_time") ...
e1382aeb877c94acc5f70bd84083ca97ec033dd5
45,522
def interpft(x, N): """Interpolates x to n points in Fourier Transform domain """ n = len(x) assert n < N a = jfft.fft(x) nyqst = (n + 1) // 2 z = jnp.zeros(N -n) a1 = a[:nyqst+1] a2 = a[nyqst+1:] b = jnp.concatenate((a1, z, a2)) if n % 2 == 0: b = b.at[nyqst].set(b[n...
572465a3abfaedf27eb765c0654ef956dc1f0e1f
45,523
def price_router(token_in, token_out=usdc, router=None): """ Calculate a price based on Uniswap Router quote for selling one `token_in`. Always uses intermediate WETH pair. """ tokens = [interface.ERC20(token) for token in [token_in, token_out]] router = interface.UniswapRouter(router or ROUTERS...
7c481dfe146432327917123555bcaadffed95400
45,524
def create_esax_time_series(ts_subs, w, per): """ This method creates the eSAX representation for each subsequence and puts them row wise into a dataframe. :param ts_subs: a list of np arrays with the subsequences of the time series :type ts_subs: list of np arrays :param w: word size used for the ...
f271e65bde3b5418f3defd19210d508ce3152a03
45,525
def regex_for_progress(): """ T0:210 /210 B:0 /0 """ return '([0-9].*)\/([0-9].*?)\\r'
2f5230b73ab90ca77e1f1550e141f25265aea844
45,526
def check_penn_treebank_dataset(method): """A wrapper that wraps a parameter checker around the original Dataset(PennTreebankDataset).""" @wraps(method) def new_method(self, *args, **kwargs): _, param_dict = parse_user_args(method, *args, **kwargs) nreq_param_int = ['num_samples', 'num_par...
443f08874f3efc821b1a5a376f0ad2ceb7b5c831
45,527
def _get_all_topic_subscription(topicid): """Gets all of the users subscribed to the topic subscription if you are an admin.""" current_user = get_jwt_identity() if current_user: user = User.query.filter_by(username=current_user).first() if user.is_staff: topic_sub = Topic_Subscr...
22e87a69d34c18bf133bd6da0a91becff008841f
45,528
def get_phase(signal, sample_rate, frame_length=32, frame_shift=8, window_type="hanning", preemphasis=0.0, square_root_window=True): """Compute phase imformation. Args: signal: input speech signal sample_rate: w...
13e7c07370b9c05686f1766ef8a8add8e21bb5e9
45,531
def crossGeneRandom(genea, geneb): """ A crossover startegy where parts of two genes are randomly swapped. 12347 => 14341 54321 52327 Parameters ---------- genea : 1D numpy array An 1D numpy array/list of genes. geneb : 1D numpy array An 1D nu...
60e5bcd72b18e0e723f5ae2054f4b980ea56def4
45,532
def predict(summaries, row) -> tuple: """ Predict the most likely class from inputs: summaries: prepared summaries of dataset row: a row in the dataset for predicting its label (a row of X_test) This function uses the probabilities calculated from each class via the function 'calculate_class_proba...
6e07240fefcb80e4e54a279b11434eb3fb29863a
45,533
import math import bisect import pdb import copy def find_antenna_overlay_for_sector(points_to_cover, center, radius, detection_coverage): """ Find the overlay pattern for antennas so they cover a sector. """ def find_cover(rotated_antenna_pattern,points_to_cover): """ Find the subset of point...
5e6d859cbbef4423f64599adb20545c6fa941db9
45,534
def disable_tls_for(template, port): """ Change a deployment template to disable TLS communications. @param template: deployment template @param port: listening port for Cloudera Manager with TLS disabled @rtype: DeploymentTemplate @return: updated deployment template """ if not templat...
496369113f6ee4ab6df8a43e2ee15a2d0518ac55
45,535
def get_staffline(y_position, extracted_staff_arr): """Gets the staffline of the extracted staff. Args: y_position: The staffline position--the relative number of notes from the 3rd line on the staff. extracted_staff_arr: An extracted staff NumPy array, e.g. `StafflineExtractor.extract_stav...
d4167918907ee93c400e1104ea157fea8d591c96
45,536
def _get_task_info(): """Get task info from Rosetta Code Returns: List of Tuple(task name, task url) """ url = "http://www.rosettacode.org/wiki/Category:Programming_Tasks" soup = get_soup(url) task_tags = soup.find("div", class_="mw-category").find_all("a") task_urls = [] # list of task ...
cc186dfaaf9b40d85421c8ea1e9e59a8b5ab4fa2
45,537
def sample_action(policy, state): """ Samples a policy for an action given the current state. """ choices = np.arange(0, policy.shape[1]) probabilities = policy[state] return np.random.choice(choices, p=probabilities)
afd38b37a4d754acb26cdd0ca5e18a5c596219f0
45,538
def _plot_clusters(estimator, fdata, *, chart=None, fig=None, axes=None, n_rows=None, n_cols=None, labels, sample_labels, cluster_colors, cluster_labels, center_colors, center_labels, center_width, colormap): """Implementation of the plot of the FDataGrid sam...
73de9e0a47f6009addbf84a9fbc43aa7735421c8
45,539
import time def plot(canvas, word, grid, answers): """ called by handle_plot() function draws a box around the word if it is a correct solution """ # pulls data from answers dictionary (iscol, isrev, word_len, x_start, y_start) = answers[word] (x1, y1, square_dim) = find_coord(x_start, y_...
67c504a88d6299d3a7bfe1fa6d529d5652b04957
45,540
def split_flow_into_segments(flow): """Splits the flow into multiple segments where a segment is defined by: data only from endpoint A (request) followed by data only from endpoint B (response). New data from endpoint A initiates a new segment. Returns: list of TcpFlow instances with each instance repre...
a84d4fd5e2a4125e07714f62d422edc147b7f302
45,541
def sigD(jax=True, dtype=np.float32): """ Pauli 'down' matrix. PARAMETERS ---------- jax (bool, default True): Toggles whether a Jax or np array is returned. dtype: the data type of the return value. """ vals = [[0, 0], [1, 0]] D = np.array(vals, dtype=dtype) if jax:...
baca10cdb28de8baade2b8be064f5093d09ed00f
45,542
from re import X def is_clockwise(points): """ Check if the points given forms a clockwise polygon :return: True if the points forms a clockwise polygon """ a = 0 i, j = 0, 0 for i in range(len(points)): j = i + 1 if j == len(points): j = 0 a += points[i][X]*points...
230f9566d45a5abdd5442a2b7f2d7882a1894c9e
45,543
def kl_divergence(p, q): """Standard KL divergence.""" return stats.entropy(p, q)
b0060b117d9c594d761d2d0c3f123b161fdd6090
45,544
def validate_category(value): """Validator for Node#category. Makes sure that the value is one of the categories defined in CATEGORY_MAP. """ if value not in Node.CATEGORY_MAP.keys(): raise ValidationValueError('Invalid value for category.') return True
98ea86f6ca3ba9893efabd3a1a0344c018cd3f75
45,546
def drop_unevaluated_comp(df): """Drop unevaluated compounds from a dataframe.""" df = df[df.index.get_level_values( level=metadata.TREATMENT_GROUP) != metadata.NEGATIVE_CONTROL] df = df[df.index.get_level_values(level=metadata.MOA) != metadata.UNKNOWN] return df
246df0cb2956e5568f1e71c297afc79fe33ac125
45,547
def target_frame(): """Input target frame.""" return 'IAU_ENCELADUS'
34e4fdf51544f8a3d4e9bb43737b717e6d89c417
45,548
def associate_node_id(tr, node=""): """ Returns a dictionary with key 'id' and value as the ID associated with the node string. """ return {"id": tr.get_uml_id(name=node)}
5e6eb1076cdeed9abc8b00d1de60a255f6292dd3
45,549
def record(app, db, s3_location): """Create a record.""" record = { 'title': 'fuu' } record = Record.create(record) record.commit() db.session.commit() return record
dbad6748eedb3930ac25982d3b7905564204eca1
45,550
async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool: """Set up Flipr from a config entry.""" hass.data.setdefault(DOMAIN, {}) coordinator = FliprDataUpdateCoordinator(hass, entry) await coordinator.async_config_entry_first_refresh() hass.data[DOMAIN][entry.entry_id] = coord...
af17c6701258239ac40a086dc83da04efc592285
45,551
def build_api_query(req: ExternalAPIRequest) -> str: """ build_api_query takes a ExternalAPIRequest object and returns a URL with query params """ # if the query options weren't specified, return the url without # adding to it. if not req.q: return req.url base_url = req.url if not ba...
444f4dca6ddf3f68fe23ef00e0d5e5a8aff108cf
45,552
def SET(query): """ Decorator that marks a method as a SET query handler for some variable in the genotype-phenotype interface. The decorator receives as argument the name of the query. For instace, this decorator is applied to the Synapses.set_weights method as @SET("synapses:weights"). """...
fb055d59626988201cdb3686d2ff98c8d9f0a21f
45,553
def get_last_close_str( fmt=ae_consts.COMMON_DATE_FORMAT): """get_last_close_str Get the Last Trading Close Date as a string with default formatting ae_consts.COMMON_DATE_FORMAT (YYYY-MM-DD) :param fmt: optional output format (default ae_consts.COMMON_DATE_FORMAT) """ retur...
03acaebfa8676c88ceffa2f8a0d5f9b9bb2e8f47
45,556
from pathlib import Path import logging import torch def load_grad_z(grad_z_dir=Path("./grad_z/"), train_dataset_size=-1): """Loads all grad_z data required to calculate the influence function and returns it. Arguments: grad_z_dir: Path, folder containing files storing the grad_z values t...
9649b20fc613f3789b32e8cc629b51dbe16c0d3a
45,557
def clause_words(clause_tree): """ Returns the constants in a clause. These will be everything that is not a keyword. """ if clause_tree == []: return [] elif clause_tree[0] == 'func': assert(len(clause_tree) == 3) if clause_tree[2] == []: return [clause_tree[1]] else: return [clause_...
5f72cb17397acb9313db5625afd6b4b073f4172f
45,559
def _reusables(): """Return the reusables object. We use this wrapper because so that functions which use the reusables variable can be pickled. """ return reusables
d2db430b4393761eb5f618dff1c44cc29185a225
45,560
def algo_ration(balls: Balls) -> int: """ Algorithmus: Binäre-Suche mit optimiertem Teilverhältnis mit der ersten Kugel, dann mit Einzelschritten suchen. Teilverhältnis -> Mittlere Anzahl: 0.10 -> 13.43 ; 0.19 -> 10.94 ; 0.20 -> 10.94 ; 0.21 -> 10.96 ; 0.30 -> 12.30 :param balls: Die Kugeln für ...
cae301a84488a23c78ad164f61a7e96393d3201e
45,561
def D50(Stk50, RhoP, Q, C, Eta, W): """ Returns the cut point diameter D50 Parameters ---------- Stk50 : float Stokes number for 50% collection efficiency = 0.23 RhoP : float particle density (g/cm3) Q : float volumetric flow rate (cm3/s) ...
b5b4905ef438862af0355eabd932f453a166a5f7
45,562
def rank_transform(arr: np.ndarray, centered=True) -> np.ndarray: """ Transform a 1-dim ndarray with arbitrary scalar values to an array with equally spaced rank values. This is a nonlinear transform. :param arr: input array :param centered: if the transform should by centered around zero :retu...
40a32abebb0c0bc834726046fe04ab81876cca98
45,563
def getMagic(fileName): """Get file magic.""" mime = magic.Magic(mime=True) mimeType = mime.from_file(fileName) return mimeType
3e39f6d80d494644eb4b1cbd956a2f37ec192083
45,564
import warnings def inspect_out(*args, **kwargs): """Deprecated: Please use inspect_hex()""" warnings.warn("inspect_out() is deprecated; use inspect_hex().", DeprecationWarning) return inspect_hex(*args, **kwargs)
2ef1d5077c62cd815f7ee1b707b461aed7f12129
45,565
import re def get_slurm_queue(): """Get a list of jobs currently in the Slurm queue. """ pattern = ('(?P<job_id>\d+)+\s+(?P<name>[-\w\d_\.]+)\s+(?P<user>[\w\d]+)\s+(?P<group>\w+)' '\s+(?P<account>[-\w]+)\s+(?P<partition>[-\w]+)\s+(?P<time_limit>[-\d\:]+)\s+' '(?P<time_left>[-\d\...
263ab66e0af15653b739bb08d419c58dc896618f
45,566
import importlib def DirDocNode(arg_dir, the_dir): """ This creates a non-clickable node. The text is taken from __doc__ if it exists, otherwise the file name is 'beautifuled'. """ full_module = arg_dir + "." + the_dir try: imported_mod = importlib.import_module(full_module) exce...
478fab481c4fe7c6243127c03d3e39dbec1d03ae
45,567
def is_move_slide_locked(start_hex: tuple, ending_hex: tuple, board_piece_locations: set[tuple]) -> bool: """ A move is 'slide locked' if a piece on a physical board cannot be slid from its current hex to an adjacent, empty hex without having to pick up the moving piece. This function expects start_hex and ...
46479e92d1ad5abe9e9309a4d01c74b236fc9287
45,568
import logging def face_detect(): """ { "faceimage":"img(base64 or url)" } :return: { "similar":1.0, "code":"00000", "errorinfo":"message", "result":true } """ try: face_base64 = request.json face_detect_result = FaceUtils.detect_face(face_ba...
ff9b5d3a4babeb863254e4596cec7567acb189b1
45,569
import traceback def uninstall(): """ Uninstall the Azure Monitor Linux Agent. This is a somewhat soft uninstall. It is not a purge. Note: uninstall operation times out from WAAgent at 5 minutes """ find_package_manager("Uninstall") if PackageManager == "dpkg": OneAgentUninstallCom...
e3db155f4ab4494d792ddc6af733b52573f26e76
45,570
def match_riccati(eq, f, x): """ A function that matches and returns the coefficients if an equation is a Riccati ODE Parameters ========== eq: Equation to be matched f: Dependent variable x: Independent variable Returns ======= match: True if equation is a Riccati ODE, F...
8f3228ad1af3f6777557bb12587d91706db5ce77
45,571
import re def find_nonAscii(text): """ Return the first appearance of a non-ASCII character (in a `Match` object), or `None`. """ regex = re.compile(r'([^\x00-\x7F])+') return re.search(regex, text)
bc299752eab5088214f9e1f62add388bf0721153
45,572
def linear_search(arr, x): """ Performs a linear search :param arr: Iterable of elements :param x: Element to search for :return: Index if element found else None """ l = len(arr) for i in range(l): if arr[i] == x: return i return None
2cb03eef6c9bb1d63df97c1e387e9cbfe703769a
45,573
def _filter(data, scopedData, scopedLogic): """ Filter 'scopedData' using the specified 'scopedLogic' argument. 'scopedData' argument can be: - a manually specified data array; - a JsonLogic rule returning a data array; - a JsonLogic 'var' operation returning part of the data object ...
2cef191bcd39bcf61f6a5d4dadb06c8861dec6ca
45,574
def _parse_age_specific_distribution(df, parameter, parameter_function, age_bins, full_factorial): """Age-specific parameter sampling from a numpy distribution Create a column in the DataFrame for each age bin, and sample from the specified distribution. Modifies the input DataFrame in place. """ ...
b5cb833b0adfcdf288bf616d24e32b5693fbb88e
45,575
import tarfile def generic_tarfile_verify(filepath, method): """ Verify that a tar/tgz/tbz/txz file is valid and working. :param filepath: Filename. :type filepath: str :param method: Tarfile read method. :type method: str """ if smart_is_tarfile(filepath): with tarfile.open(...
a7436d9a21b8fedb97c157aa00bc5154a016cf4c
45,576
def helicsFederateInfoSetCoreType(fi: 'helics_federate_info', coretype: 'int') -> "void": """ """ return _helics.helicsFederateInfoSetCoreType(fi, coretype)
562111a7f0968b7d1da298e5d3914340572b57e4
45,577
def score_hmm_unit_id_shuffle(bst, hmm, n_shuffles=250, normalize=False): """Docstring goes here. Returns ------- scores : array of size (n_events,) shuffled : array of size (n_shuffles, n_events) """ scores = score_hmm_logprob(bst=bst, hmm=hmm, ...
fb4d1cf399b2d9ba4a64ff29bd46d1042c637f50
45,578
def step(grouped_seqs, stop_short=False): """ Generates tuples of lists of rows for every matching keys """ Empty = object() NoMore = object() EmptyVal = [] keys = [Empty] * len(grouped_seqs) vals = [EmptyVal] * len(grouped_seqs) def update(i, gs): try: k, rs = next...
9832db0cde8f1a40869b359ff8f37dc84cf43899
45,581
import copy def get_opencor_algorithm(requested_alg, config=None): """ Get a possibly alternative algorithm that OpenCOR should execute Args: requested_alg (:obj:`Algorithm`): requested algorithm config (:obj:`Config`, optional): configuration Returns: :obj:`Algorithm`: possibly ...
eb827f25b4e4255272d45a0b66c6e21d88aec4ca
45,582
import torch def wassertein_distance(u_x: Tensor, s_x: Tensor, u_y: Tensor, s_y: Tensor, is_target: bool = True, num_iter: int = 10): """ Computer Wassertein distance between two multivariate normal distribution X Y the covariance matrix of Y is assumed to be unit matrix if is_targ...
f96a934b3462f2fc4b7a60402b47bfc1b434e3df
45,583
import torch from typing import Tuple def mask_tokens(inputs: torch.Tensor, tokenizer: PreTrainedTokenizer, args) -> Tuple[torch.Tensor, torch.Tensor]: """Prepares masked tokens inputs/labels for masked language modeling: 80% MASK, 10% random, 10% original.""" if tokenizer.mask_token is None: rai...
51d89a0f1fd5bad33c2cc39722cb1889439ca617
45,584
def to_json(p): """Returns a JSON-compatible dict of a plugin that can be serialized and sent to clients. """ name = (p['vimorg_name'] or p['github_repo_name'] or p['github_vim_scripts_repo_name']) author = (p['vimorg_author'].strip() or p['github_author'].strip()) plugin_manager_us...
8dfd7db473138859c880461090a436cf73a46948
45,585
def sms_in(request): """ sender - the number of the person sending the sms receiver - the number the sms was sent to msgdata - the message """ sender = request.GET.get("sender", None) receiver = request.GET.get("receiver", None) msgdata = request.GET.get("msgdata", None) if sender is...
14156fcbca2d68605187eaa271b42ca6e418438a
45,586
def best_model_based_selector(train_features, test_features, train_similarity_target, test_similarity_target, regressor): """ Function used to select the best model based selector """ model_based_score = 0 scaling_factors = ["0.25*mean", "0.5*mean", "median", "1.25*mean", "1.5*mean"] # scaling_factors = ["0.5*mean"...
98e608fa8ef913306fbf50bb5fe4aaf6f5c28bfd
45,588