content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def _select_by_property(peak_properties, pmin, pmax): """ Evaluate where the generic property of peaks confirms to an interval. Parameters ---------- peak_properties : ndarray An array with properties for each peak. pmin : None or number or ndarray Lower interval boundary for `p...
12fda9525334d8a2a50e1a4785587dbbb0a70f00
19,855
def from_period_type_name(period_type_name: str) -> PeriodType: """ Safely get Period Type from its name. :param period_type_name: Name of the period type. :return: Period type enum. """ period_type_values = [item.value for item in PeriodType] if period_type_name.lower() not in period_type_...
97feb3bd1f18c1752ba4510628411f23ea77acb1
19,856
import random import string def randomInt(length=4, seed=None): """ Returns random integer value with provided number of digits >>> random.seed(0) >>> randomInt(6) 874254 """ if seed is not None: _ = getCurrentThreadData().random _.seed(seed) choice = _.choice ...
3d37b6410337271c6798cb1b3542189fcdd04226
19,857
import re def matchatleastone(text, regexes): """Returns a list of strings that match at least one of the regexes.""" finalregex = "|".join(regexes) result = re.findall(finalregex, text) return result
1e0775413189931fc48a3dc82c23f0ffe28b333e
19,858
def safe_string_equals(a, b): """ Near-constant time string comparison. Used in order to avoid timing attacks on sensitive information such as secret keys during request verification (`rootLabs`_). .. _`rootLabs`: http://rdist.root.org/2010/01/07/timing-independent-array-comparison/ """ if le...
6253b747061dfdc82a533b103009f0ab469a76ef
19,859
def DFS_complete(g): """Perform DFS for entire graph and return forest as a dictionary. forest maps each vertex v to the edge that was used to discover it. (Vertices that are roots of a DFS tree are mapped to None.) :param g: a Graph class object :type g: Graph :return: A tuple of dicts summar...
7cf500d204b70cbcb9cedf33dda42cb2b717e162
19,860
def get_keys(mapping, *keys): """Return the values corresponding to the given keys, in order.""" return (mapping[k] for k in keys)
e3b8bdbdff47c428e4618bd4ca03c7179b9f4a2b
19,861
def accents_dewinize(text): """Replace Win1252 symbols with ASCII chars or sequences needed when copying code parts from MS Office, like Word... From the book "Fluent Python" by Luciano Ramalho (O'Reilly, 2015) >>> accents_dewinize('“Stupid word • error inside™ ”') '"Stupid word - error inside(TM) ...
d34a4cd694b4d713ac7b207680e26d7c79f2b957
19,862
def spiral_trajectory(base_resolution, spiral_arms, field_of_view, max_grad_ampl, min_rise_time, dwell_time, views=1, phases=None, ordering='lin...
b7acf7a14835e63e1f2524a5ac7dd67d16a4eba7
19,863
def total_examples(X): """Counts the total number of examples of a sharded and sliced data object X.""" count = 0 for i in range(len(X)): for j in range(len(X[i])): count += len(X[i][j]) return count
faf42a940e4413405d97610858e13496eb848eae
19,864
def convert_and_save(model, input_shape, weights=True, quiet=True, ignore_tests=False, input_range=None, filename=None, directory=None): """ Conversion between PyTor...
00305f6d9a163b61a963e04e810a8d3808403d23
19,865
def no_afni(): """ Checks if AFNI is available """ if Info.version() is None: return True return False
fc10292bc69ca5996a76227c3bbbd5855eb2520e
19,866
def delta_eta_plot_projection_range_string(inclusive_analysis: "correlations.Correlations") -> str: """ Provides a string that describes the delta phi projection range for delta eta plots. """ # The limit is almost certainly a multiple of pi, so we try to express it more naturally # as a value like pi/2 or ...
3b36d65a3223ca2989ad9607fc2b15b298b1c709
19,867
def has_content_in(page, language): """Fitler that return ``True`` if the page has any content in a particular language. :param page: the current page :param language: the language you want to look at """ if page is None: return False return Content.objects.filter(page=page, languag...
6207583ad110aa098b5f556ad7a13b1b5218a1d3
19,871
def public_encrypt(key, data, oaep): """ public key encryption using rsa with pkcs1-oaep padding. returns the base64-encoded encrypted data data: the data to be encrypted, bytes key: pem-formatted key string or bytes oaep: whether to use oaep padding or not """ if isinstance(key, str): key = key.en...
7310a0d408deff30efad2c961518261187a89dbf
19,872
def newton_method(f, x_init = 0, epsilon = 1e-10): """ Newton Raphson Optimizer ... Parameters --- f: Function to calculate root for x_init(optional) : initial value of x epsilon(optional): Adjustable precision Returns --- x: Value of root """ prev_value = x_init +...
5801d5f908e30551c321eaf0ec8dfbf42869e005
19,873
def create_preference_branch(this, args, callee): """Creates a preference branch, which can be used for testing composed preference names.""" if args: if args[0].is_literal: res = this.traverser.wrap().query_interface('nsIPrefBranch') res.hooks['preference_branch'] = args[0]...
6e6cc013b9d6c645a6a94087fe63b3a186582003
19,874
def circle( gdf, radius=10, fill=True, fill_color=None, name="layer", width=950, height=550, location=None, color="blue", tooltip=None, zoom=7, tiles="OpenStreetMap", attr=None, style={}, ): """ Convert Geodataframe to geojson and plot it. Parameters ...
d2f2e066c2f6988f950ffce6a7655b60c91c3cec
19,875
import traceback def no_recurse(f): """Wrapper function that forces a function to return True if it recurse.""" def func(*args, **kwargs): for i in traceback.extract_stack(): if i[2] == f.__name__: return True return f(*args, **kwargs) return func
cce02b5e8fff125040e457c66c7cc9c344e209cb
19,876
from typing import List import pandas from typing import Tuple def get_tap_number(distSys: SystemClass, names: List[str]) -> pandas.DataFrame: """ Get the tap number of regulators. Args: distSys : An instance of [SystemClass][dssdata.SystemClass]. names : Regulators names Returns: ...
a780b151670f261656d938ec48a5ac684c8c9d6d
19,877
def status(app: str) -> dict: """ :param app: The name of the Heroku app in which you want to change :type app: str :return: dictionary containing information about the app's status """ return Herokron(app).status()
f5251469c8388edf885ac9e4ae502549f0092703
19,878
def GetIPv4Interfaces(): """Returns a list of IPv4 interfaces.""" interfaces = sorted(netifaces.interfaces()) return [x for x in interfaces if not x.startswith('lo')]
01fc53160b01e3322af8d18175fde0011d87d127
19,879
def merge_dicts(source, destination): """ Recursively merges two dictionaries source and destination. The source dictionary will only be read, but the destination dictionary will be overwritten. """ for key, value in source.items(): if isinstance(value, dict): # get node or creat...
dea2d01f2cdf42c38daee8589abcc69a3f82e5c8
19,880
def create_hive_connection(): """ Create a connection for Hive :param username: str :param password: str :return: jaydebeapi.connect or None """ try: conn = jaydebeapi.connect('org.apache.hive.jdbc.HiveDriver', hive_jdbc_url, ...
48ac2859c9ceec9129d377f722ff96786a1c9552
19,881
def main(): """ The main function to execute upon call. Returns ------- int returns integer 0 for safe executions. """ print('Hello World') return 0
077df89bc009a12889afc6567bfd97abdb173411
19,882
def brightness(image, magnitude, name=None): """Adjusts the `magnitude` of brightness of an `image`. Args: image: An int or float tensor of shape `[height, width, num_channels]`. magnitude: A 0-D float tensor or single floating point value above 0.0. name: An optional string for name of...
52e3016dce51bd5435e2c4085aa0a4d50b9c3502
19,883
def sitemap_xml(): """Sitemap XML""" sitemap = render_template("core/sitemap.xml") return Response(sitemap, mimetype="text/xml")
12d954b7f3c88f10e694e0aa1998699322a5602b
19,884
def get_CM(): """Pertzの係数CMをndarrayとして取得する Args: Returns: CM(ndarray[float]):Pertzの係数CM """ # pythonは0オリジンのため全て-1 CM = [0.385230, 0.385230, 0.385230, 0.462880, 0.317440,#1_1 => 0_0 0.338390, 0.338390, 0.221270, 0.316730, 0.503650, 0.235680, 0.235680, 0.24128...
434bab68e2aa434a79a53dd91a4932e631a6367c
19,885
def remove_sleepEDF(mne_raw, CHANNELS): """Extracts CHANNELS channels from MNE_RAW data. Args: raw - mne data strucutre of n number of recordings and t seconds each CHANNELS - channels wished to be extracted Returns: extracted - mne data structure with only specified channels """ extra...
7bb04810676a127742d391c518fc505bf7568aac
19,886
from datetime import datetime import pytz def save_email_schedule(request, action, schedule_item, op_payload): """ Function to handle the creation and edition of email items :param request: Http request being processed :param action: Action item related to the schedule :param schedule_item: Schedu...
3a14e11a195bcf96ac132d2876e61ce52f0b8ccd
19,887
def slice( _data: DataFrame, *rows: NumericOrIter, _preserve: bool = False, base0_: bool = None, ) -> DataFrame: """Index rows by their (integer) locations Original APIs https://dplyr.tidyverse.org/reference/slice.html Args: _data: The dataframe rows: The indexes ...
a58d2ae140d1e441100f7f71587588b93ecaa7b4
19,888
def get_random_color(): """ Get random color :return: np.array([r,g,b]) """ global _start_color, _color_step # rgb = np.random.uniform(0, 25, [3]) # rgb = np.asarray(np.floor(rgb) / 24 * 255, np.uint8) _start_color = (_start_color + _color_step) % np.array([256, 256, 256]) rgb = np.a...
3c9596f264e75c064f76a56d71e06dbe55669936
19,889
def get_client_ip(request): """ Simple function to return IP address of client :param request: :return: """ x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR') if x_forwarded_for: ip = x_forwarded_for.split(',')[0] # pylint: disable=invalid-name else: ip = reque...
976755d296127a42de5b6d7c39bfc9a607b273ee
19,890
def entropy(wair,temp,pres,airf=None,dhum=None,dliq=None,chkvals=False, chktol=_CHKTOL,airf0=None,dhum0=None,dliq0=None,chkbnd=False, mathargs=None): """Calculate wet air entropy. Calculate the specific entropy of wet air. :arg float wair: Total dry air fraction in kg/kg. :arg float te...
4cd0b53bdf549a0f53d2543e693f6b179a0f0915
19,891
def get_list_item(view, index): """ get item from listView by index version 1 :param view: :param index: :return: """ return var_cache['proxy'].get_list_item(view, index)
bcb1db741a87bc2c12686ade8e692449030eb9cf
19,892
def interquartile_range_checker(train_user: list) -> float: """ Optional method: interquatile range input : list of total user in float output : low limit of input in float this method can be used to check whether some data is outlier or not >>> interquartile_range_checker([1,2,3,4,5,6,7,8,9,10]...
29eba79cef5c91e491250780ed3fb7ca74d7cace
19,893
def make_linear_colorscale(colors): """ Makes a list of colors into a colorscale-acceptable form For documentation regarding to the form of the output, see https://plot.ly/python/reference/#mesh3d-colorscale """ scale = 1.0 / (len(colors) - 1) return [[i * scale, color] for i, color in enum...
dabd2a2a9d6bbf3acfcabcac52246048332fae73
19,894
def background(image_size: int, level: float=0, grad_i: float=0, grad_d: float=0) -> np.array: """ Return array representing image background of size `image_size`. The image may have an illimination gradient of intensity `I` and direction `grad_d`. The `image_size` is in pixels. `grad_i` expected to be ...
7fc6d34ec02752604024746e707f70a82ad61450
19,895
def mapTypeCategoriesToSubnetName(nodetypecategory, acceptedtypecategory): """This function returns a name of the subnet that accepts nodetypecategory as child type and can be created in a container whose child type is acceptedtypecategory. Returns None if these two categories are the same (i...
c9a31c571807cd2592340ce685b1f130f99da156
19,896
def sorted_unique(series): """Return the unique values of *series*, correctly sorted.""" # This handles Categorical data types, which sorted(series.unique()) fails # on. series.drop_duplicates() is slower than Series(series.unique()). return list(pd.Series(series.unique()).sort_values())
3da88962171acd15f3af020ff056afb66d284425
19,897
import json def create_query_from_request(p, request): """ Create JSON object representing the query from request received from Dashboard. :param request: :return: """ query_json = {'process_type': DVAPQL.QUERY} count = request.POST.get('count') generate_tags = request.POST.get('genera...
4936376d6d900ca20d2ea9339634d0a7d90ebc2e
19,898
from typing import List from typing import Any def create_cxr_transforms_from_config(config: CfgNode, apply_augmentations: bool) -> ImageTransformationPipeline: """ Defines the image transformations pipeline used in Chest-Xray datasets. Can be used for other types of ...
9d16e844291a69d4b82681c4cdcc48f5a1b3d67f
19,899
def is_compiled_with_npu(): """ Whether paddle was built with WITH_ASCEND_CL=ON to support Ascend NPU. Returns (bool): `True` if NPU is supported, otherwise `False`. Examples: .. code-block:: python import paddle support_npu = paddle.device.is_compiled_with_npu() "...
54bf625843a098bfee93d8c1ac5b79bd562602fe
19,900
def odd_occurrence_parity_set(arr): """ A similar implementation to the XOR idea above, but more naive. As we iterate over the passed list, a working set keeps track of the numbers that have occurred an odd number of times. At the end, the set will only contain one number. Though the worst...
57f9362e05786724a1061bef07e49635b1b2b142
19,901
import time def larmor_step_search(step_search_center=cfg.LARMOR_FREQ, steps=200, step_bw_MHz=5e-3, plot=False, shim_x=cfg.SHIM_X, shim_y=cfg.SHIM_Y, shim_z=cfg.SHIM_Z, delay_s=1, gui_test=False): """ Run a stepped search through a range of frequencies to find the highest signal response Used to find...
647d67a491cf787dbc092a621c9ba5ad8097b21e
19,902
from typing import Optional def get_role_tempalte(context: Optional[str] = None, name: Optional[str] = None, opts: Optional[pulumi.InvokeOptions] = None) -> AwaitableGetRoleTempalteResult: """ Use this data source to access information about an existing resource. ...
edc2bdaba9f287995f6c4323a4acb45935be02e4
19,903
from sklearn.metrics import roc_curve, roc_auc_score def threshold_xr_via_auc(ds, df, res_factor=3, if_nodata='any'): """ Takes a xarray dataset/array of gdv likelihood values and thresholds them according to a pandas dataframe (df) of field occurrence points. Scipy roc curve and auc is generated to p...
6415b7aa7298c7d2bf6488d5c9f0834facbd4300
19,904
def kd_or_scan(func=None, array=None, extra_data=None): """Decorator to allow functions to be call with a scan number or kd object """ if func is None: return partial(kd_or_scan, array=array, extra_data=extra_data) @wraps(func) def wrapper(scan, *args, **kwargs): # If scan number given...
8eda0c54717293f57cd817f20a6f008abae6b825
19,905
def matching_intervals(original: DomainNode, approx: DomainNode, conf: float) -> bool: """ Checks if 2 intervals match in respect to a confidence interval.""" # out_of_bounds = (not matching_bounds(original.domains[v], approx.domains[v], conf) for v in original.variables) # return not any(out_of_bounds) ...
bb2540872d0406b88551ec5b3a9ef28fbc39d366
19,906
def _make_label_sigmoid_cross_entropy_loss(logits, present_labels, split): """ Helper function to create label loss Parameters ---------- logits: tensor of shape [batch_size, num_verts, num_labels] present_labels: tensor of shape [batch_size, num_verts, num_labels]; labels of labelled verts spl...
290364255222f20ef864636ef2ac8df51599a587
19,907
import copy def _merge_meta(base, child): """Merge the base and the child meta attributes. List entries, such as ``indexes`` are concatenated. ``abstract`` value is set to ``True`` only if defined as such in the child class. Args: base (dict): ``meta`` attribute from the base...
ba219b8091244a60658bee826fbef5003d3f7883
19,908
from typing import Dict from typing import Any def _parse_quotes(quotes_dict: Dict[str, Dict[str, Dict[str, Any]]]) -> "RegionalQuotes": """ Parse quote data for a :class:`~.DetailedProduct`. :param quotes_dict: """ quotes: RegionalQuotes = RegionalQuotes() for gsp, payment_methods in quotes_dict.items(): ...
82ea906391b5e3d23a40619eefc19eaa353e18bc
19,909
def train_validation(train_df, valid_df, epochs=100, batch_size=512, plot=False, nn_args={}): """ Wrapper for training on the complete training data and evaluating the performance on the hold-out set. Parameter: ------------------- train_df: df, train df...
7dffa50d427c0e74fe4f6e6a8ff1e0198304de2a
19,910
import warnings import inspect def bootstrap_compute( hind, verif, hist=None, alignment="same_verifs", metric="pearson_r", comparison="m2e", dim="init", reference=["uninitialized", "persistence"], resample_dim="member", sig=95, iterations=500, pers_sig=None, compute...
1a419d129419d15276f21f6f09bbd613a8e662da
19,912
def description_for_number(numobj, lang, script=None, region=None): """Return a text description of a PhoneNumber object for the given language. The description might consist of the name of the country where the phone number is from and/or the name of the geographical area the phone number is from. Th...
d67d53528c99c8b3ce6323c7e4eb5170603660c1
19,913
def _construct_new_particles(samples, old_particles): """Construct new array of particles given the drawing results over the old particles. Args: + *samples* (np.ndarray): NxM array that contains the drawing results, where N is number of observations and M number of part...
ec511554074f637466d47d24c449eda8a263100e
19,914
def trunc(x, y, w, h): """Truncates x and y coordinates to live in the (0, 0) to (w, h) Args: x: the x-coordinate of a point y: the y-coordinate of a point w: the width of the truncation box h: the height of the truncation box. """ return min(max(x, 0), w - 1), min...
3edecdfbd9baf24f8b4f3f71b9e35a222c6be1ea
19,915
def exact_match(true_labels, predicts): """ exact_match This is the most strict metric for the multi label setting. It's defined as the percentage of samples that have all their labels correctly classified. Parameters ---------- true_labels: numpy.ndarray of shape (n_samples, n_target...
ebcc1d6ce96ff8b5933e16ce69f5e143e371bf28
19,917
def dimred3(dat): """convenience function dimensionally reduce input data, each row being an element in some vector space, to dimension 3 using PCA calcualted by the SVD""" return dimred(dat, 3)
5151ee8bb0e8bcfe6dbb1633d95e9b355714ae35
19,918
def render_orchestrator_registrations( driver: Driver = None, collab_id: str = None, project_id: str = None ): """ Renders out retrieved registration metadata in a custom form Args: driver (Driver): A connected Synergos driver to communicate with the selected orchestrator. ...
14a84029ff20a09d2c8c6e41007827f96fb35f60
19,919
def check_nan(data, new_data): """checks if nan values are conserved """ old = np.isnan(data) new = np.isnan(new_data) if np.all(new == old): return True else: return False
d1dafaadd6e37848aa147b6714cce74f6097e074
19,920
def Var(poly, dist=None, **kws): """ Element by element 2nd order statistics. Args: poly (chaospy.poly.ndpoly, Dist): Input to take variance on. dist (Dist): Defines the space the variance is taken on. It is ignored if ``poly`` is a distribution. Ret...
6ec5e867ed7287f90584e0c134d29b8daf4f9b9c
19,921
def op_par_loop_parse(text): """Parsing for op_par_loop calls""" loop_args = [] search = "op_par_loop" i = text.find(search) while i > -1: arg_string = text[text.find('(', i) + 1:text.find(';', i + 11)] # parse arguments in par loop temp_args = [] num_args = 0 # parse each op_arg_dat ...
826bb5cd58e4b34846419fc47977caa73fd5573c
19,922
def bin_to_hex(bin_str: str) -> str: """Convert a binary string to a hex string. The returned hex string will contain the prefix '0x' only if given a binary string with the prefix '0b'. Args: bin_str (str): Binary string (e.g. '0b1001') Returns: str: Hexadecimal string zero...
0f44311a600a7b5eac52d3716db4b116302c97ac
19,923
def exp_value_interpolate_bp(prod_inst, util_opti, b_ssv_sd, k_ssv_sd, epsilon_ssv_sd, b_ssv, k_ssv, epsilon_ssv, b_ssv_zr, k_ssv_zr, epsilon_ssv_zr, states_vfi_dim, shocks_vfi_dim): """interpolate va...
e8d698834186efa779bbd81b042e9cf4caa1276a
19,924
from typing import Union from typing import List def remove_non_protein( molecule: oechem.OEGraphMol, exceptions: Union[None, List[str]] = None, remove_water: bool = False, ) -> oechem.OEGraphMol: """ Remove non-protein atoms from an OpenEye molecule. Parameters ---------- molecule: oe...
6afa4df25cbcf504b2ac06325a3e89291e9a0e4f
19,925
import json def configure_connection(instance, name='eventstreams', credentials=None): """Configures IBM Streams for a certain connection. Creates an application configuration object containing the required properties with connection information. Example for creating a configuration for a Streams inst...
5f263af94590e7237e27dc90f2e502b952d010fc
19,926
def setup(app): """ Any time a python class is referenced, make it a pretty link that doesn't include the full package path. This makes the base classes much prettier. """ app.add_role_to_domain("py", "class", truncate_class_role) return {"parallel_read_safe": True}
69660fd86216dfe0a5642b0885dbdb0704ce8ffc
19,927
def transects_to_gdf(transects): """ Saves the shore-normal transects as a gpd.GeoDataFrame KV WRL 2018 Arguments: ----------- transects: dict contains the coordinates of the transects Returns: ----------- gdf_all: gpd.GeoDataFrame ...
a2e1c517a7d4d86618a08da07459686fa947d597
19,928
def deduce_final_configuration(fetched_config): """ Fills some variables in configuration based on those already extracted. Args: fetched_config (dict): Configuration variables extracted from a living environment, Returns: dict: Final configuration from live environment. """ final_c...
30d21a8eb0bd1d282dbd127551e55fc7061e82ed
19,929
def total_benchmark_return_nb(benchmark_value: tp.Array2d) -> tp.Array1d: """Get total market return per column/group.""" out = np.empty(benchmark_value.shape[1], dtype=np.float_) for col in range(benchmark_value.shape[1]): out[col] = returns_nb.get_return_nb(benchmark_value[0, col], benchmark_value...
74d2924031dc4f0251b346555bc473d8d225453d
19,930
def young_modulus(data): """ Given a stress-strain dataset, returns Young's Modulus. """ yielding = yield_stress(data)[0] """Finds the yield index""" yield_index = 0 for index, point in enumerate(data): if (point == yielding).all(): yield_index = index ...
f41d4c358ae58760055d72e0364a3f79b7258512
19,931
def generateODTableDf(database: pd.DataFrame, save: bool = True) -> pd.DataFrame: """生成各区间OD表相关的数据集 Args: database (pd.DataFrame): 经初始化的原始数据集 save (bool, optional): 是否另外将其保存为csv文件. Defaults to True. Returns: pd.DataFrame: 各区间OD表相关的数据集 """ table4OD: np.ndarray = fetchTable4O...
9660d1c604e0f3514bb9a168ef91b3f29d7ba8b9
19,932
import typing def check_datatype(many: bool): """Checks if data/filter to be inserted is a dictionary""" def wrapper(func): def inner_wrapper(self, _filter={}, _data=None, **kwargs): if _data is None: # statements without two args - find, insert etc if many: # statements...
c5300507936db04b2ae5e4190421cc354f6ac2d4
19,933
def login(): """Login Page""" if request.cookies.get('user_id') and request.cookies.get('username'): session['user_id'] = request.cookies.get('user_id') session['username'] = request.cookies.get('username') update_last_login(session['user_id']) return render_template('main/index....
e8f02d520c5913e8d8d2c99d1a98b9c546a9a220
19,934
def _get_index_train_test_path(split_num, train = True): """ Method to generate the path containing the training/test split for the given split number (generally from 1 to 20). @param split_num Split number for which the data has to be generated @param train Is true if the ...
201ac816085211b1f6500e2b84d5e9b293dd8c2e
19,935
def mock_socket() -> MagicMock: """A mock websocket.""" return MagicMock(spec=WebSocket)
a3b8e53d2c929566e2bc9419cfb1d56ca3f25032
19,936
def gen_device(dtype, ip, mac, desc, cloud): """Convenience function that generates devices based on they type.""" devices = { # sp1: [0], sp2: [ 0x2711, # SP2 0x2719, 0x7919, 0x271A, 0x791A, # Honeywell SP2 0x2720, # SP...
07c9ff4ee594bf0c94aa95efc05f63306811e996
19,938
def parse_multi_id_graph(graph, ids): """ Parse a graph with 1 to 3 ids and return individual graphs with their own braced IDs. """ new_graphs = '' LEVEL_STATE.next_token = ids[0] pid1 = LEVEL_STATE.next_id() split1 = graph.partition('({})'.format(ids[1])) text1 = combine_bolds(split...
3dc693e359573ec1a2e71400856e0383653a5533
19,941
def param_to_secopt(param): """Convert a parameter name to INI section and option. Split on the first dot. If not dot exists, return name as option, and None for section.""" sep = '.' sep_loc = param.find(sep) if sep_loc == -1: # no dot in name, skip it section = None opt...
7d7e2b03cb67ed26d184f85f0328236674fa6497
19,945
from typing import List from typing import Dict import json def load_contracts( web3: web3.Web3, contracts_file: str, contracts_names: List[str] ) -> Dict[str, web3.contract.Contract]: """ Given a list of contract names, returns a dict of contract names and contracts. """ res = {} with open(co...
6f6c47c5742de0c61eddacfd9358b6d86eefb525
19,946
import logging def removecandidate(_id=''): """ Remove a candidate from the candidate list Use with the lexcion's identifiers /removecandidate?identifier=katt..nn.1 """ lexicon = request.args.get('lexicon', C.config['default']) lexconf = lexconfig.get_lexiconconf(lexicon) try: ...
55d9cfede364a35e44cf44b597653de598867d55
19,947
def svn_log_entry_dup(*args): """svn_log_entry_dup(svn_log_entry_t log_entry, apr_pool_t pool) -> svn_log_entry_t""" return _core.svn_log_entry_dup(*args)
223e7aa1dbf890eae3c5aa86a08cac287ce796c8
19,949
from typing import IO from io import StringIO def input_stream() -> IO: """Input stream fixture.""" return StringIO( """mask = XXXXXXXXXXXXXXXXXXXXXXXXXXXXX1XXXX0X mem[8] = 11 mem[7] = 101 mem[8] = 0""" )
6e9e65754478b0ff69d220f683140675d3f6efdc
19,950
def get_lr_scheduler(optimizer: Optimizer, cfg: CfgNode, start_epoch: int = 0): """Returns LR scheduler module""" # Get mode if cfg.TRAIN.LOSS.TYPE in ["categorical_crossentropy", "focal_loss"]: mode = "min" else: raise NotImplementedError if cfg.TRAIN.SCHEDULER.TYPE == "ReduceLROn...
59bbb672ac74fcc0331e5cba5bd722ce41049a5d
19,951
async def create_and_open_pool(pool_name, pool_genesis_txn_file): """ Creates a new local pool ledger configuration. Then open that pool and return the pool handle that can be used later to connect pool nodes. :param pool_name: Name of the pool ledger configuration. :param pool_genesis_txn_file...
eb05893870ff1b8928391c0e748d21b9eb8aef66
19,952
def rotate_char(c, n): """Rotate a single character n places in the alphabet n is an integer """ # alpha_number and new_alpha_number will represent the # place in the alphabet (as distinct from the ASCII code) # So alpha_number('a')==0 # alpha_base is the ASCII code for the first letter of ...
b1259722c7fb2a60bd943e86d87163866432539f
19,953
def subset_language(vocabulary, vectors, wordlist, N=32768): """ Subset the vocabulary/vectors to those in a wordlist. The wordlist is a list arranged in order of 'preference'. Note: we hope the vocabulary is contained in the wordlist, but it might not be. N is the number of words we require. If...
17c5718134f25f1ef7b6ed8fb0086fc1f45d058b
19,954
def compile_subject(*, subject_id, date_of_birth, sex): """Compiles the NWB Subject object.""" return Subject(subject_id=subject_id, date_of_birth=date_of_birth, sex=sex)
86fc69318cfac98f44b11fa4f4c2a47423da317d
19,955
from typing import Any def circulation(**kwargs: Any) -> str: """Url to get :class:`~pymultimatic.model.component.Circulation` details.""" return _CIRCULATION.format(**kwargs)
021d28b92cfac9a69723796d2ee29f53dc16039d
19,956
def split_parentheses(info): """ make all strings inside parentheses a list :param s: a list of strings (called info) :return: info list without parentheses """ # if we see the "(" sign, then we start adding stuff to a temp list # in case of ")" sign, we append the temp list to the new_info ...
37006936d52abe31e6d5e5d264440ab4950d874b
19,957
from typing import Optional from typing import Callable import inspect def event( name: Optional[str] = None, *, handler: bool = False ) -> Callable[[EventCallable], EventCallable]: """Create a new event using the signature of a decorated function. Events must be defined before handlers can be registered...
ce7821bbe67c3c776f8dfa4b69a4bed25ab814e3
19,958
import re def add_target_to_anchors(string_to_fix, target="_blank"): """Given arbitrary string, find <a> tags and add target attributes""" pattern = re.compile("<a(?P<attributes>.*?)>") def repl_func(matchobj): pattern = re.compile("target=['\"].+?['\"]") attributes = matchobj.group("...
4650dcf933e9b6e153646c6b7f3535881e4db1f8
19,960
def calcInvariants(S, R, gradT, with_tensor_basis=False, reduced=True): """ This function calculates the invariant basis at one point. Arguments: S -- symmetric part of local velocity gradient (numpy array shape (3,3)) R -- anti-symmetric part of local velocity gradient (numpy array shape (3,3)) ...
2ce8407843947c4f7c9779d061971822707f147e
19,961
def with_uproot(histo_path: str) -> bh.Histogram: """Reads a histogram with uproot and returns it. Args: histo_path (str): path to histogram, use a colon to distinguish between path to file and path to histogram within file (example: ``file.root:h1``) Returns: bh.Histogram: his...
c03e7c7054a550769c23c904892c0c327b2bcafa
19,962
def slide5x5(xss): """Slide five artists at a time.""" return slidingwindow(5, 5, xss)
56374e53384d2012d2e6352efcd0e972ff3d04bf
19,963
def compute_consensus_rule( profile, committeesize, algorithm="fastest", resolute=True, max_num_of_committees=MAX_NUM_OF_COMMITTEES_DEFAULT, ): """ Compute winning committees with the Consensus rule. Based on Perpetual Consensus from Martin Lackner Perpetual Voting: Fairness in Long...
0dd12aa8faab485a62cdeccfaf87385df85b0b7f
19,964
def addcron(): """ { "uid": "张三", "mission_name": "定时服务名字", "pid": "c3009c8e62544a23ba894fe5519a6b64", "EnvId": "9d289cf07b244c91b81ce6bb54f2d627", "SuiteIdList": ["75cc456d9c4d41f6980e02f46d611a5c"], "runDate": 1239863854, "interval": 60, "alwaysS...
87aca95b6486bbbd9abd9277aa3e2eb39b7bbdad
19,965
def dict_expand(d, prefix=None): """ Recursively expand subdictionaries returning dictionary dict_expand({1:{2:3}, 4:5}) = {(1,2):3, 4:5} """ result = {} for k, v in d.items(): if isinstance(v, dict): result.update(dict_expand(v, prefix=k)) else: result[k]...
842503eaffca7574f127b731216b5f5b10ddf86f
19,966
def parse_config_list(config_list): """ Parse a list of configuration properties separated by '=' """ if config_list is None: return {} else: mapping = {} for pair in config_list: if (constants.CONFIG_SEPARATOR not in pair) or (pair.count(constants.CONFIG_SEPARATOR) != 1): raise Valu...
12ab7dc51420196a60ef027ea606a837da3b1b59
19,967