content
stringlengths
22
815k
id
int64
0
4.91M
def compare_apache_profiles(baseline_file, test_file, threshold=0.5) -> List: """ Compare baseline Apache access log profile against test profile. :param baseline_file: file containing baseline profile :param test_file: file containing test profile :param threshold: percent (in decimal format) diffe...
71,400
async def ping(target: str, count: int = 3, timeout: int = 1000, interval: float = 1.0): """ PING 目标网络, 获取延迟丢包 (备用) 调用 Windows/Linux 系统 PING 命令, 支持 IPv6 :param target: 目标地址 :param count: 发送的回显请求数 :param timeout: 超时时间, Windows 有效 :param interval: Linux 每次 PING 的时隔 :return: """ er...
71,401
def test_kurtosis_elements(): """ Testing symmetry of the elements of the KT As an 4th order tensor, KT has 81 elements. However, due to diffusion symmetry the KT is fully characterized by 15 independent elements. This test checks for this property. """ # two fiber not aligned to planes x = 0, ...
71,402
def prepare_os(conn: OSConnection, params: Dict[str, Any], max_vm_per_node: int = 8) -> None: """prepare openstack for futher usage Creates server groups, security rules, keypair, flavor and upload VM image from web. In case if object with given name already exists, skip preparation part. Don't che...
71,403
def cyclic_sort(nums): """ 0 1 2 3 4 5 [1, 2, 3, 4, 5] ^ [1, 2, 3, 4, 5, 6] ^ """ for i in range(0, len(nums)): while nums[i] != i + 1: j = nums[i] - 1 nums[i], nums[j] = nums[j], nums[i] return nums
71,404
def _remove_older_files_if_exists(): """ Helper method to prevent cache leakage when user attempts to upload another set of files without first transcribing the files already uploaded. """ # remove old data store (if exists) old_uuid = request.cookies.get('uuid', '') if old_uuid is not None ...
71,405
def update_array(g: Graph) -> None: """Used for updating slider of array size""" g.array = generate_array(0, 150, g.array_size) g.labels = [label for label in range(g.array_size)] update_pause(g) set_graph(g)
71,406
def _build_section_path_map(): """ Simple wrapper around Django's low level cache; stores and populates a list of all section urls using the low-level caching framework. """ paths = {} Section = app_settings.get_extending_model() for section in Section.objects.all(): paths[section.f...
71,407
def c_reduced(qc, path, up = False): """ Wrapper function using t_reduced. Implements C-Reduced shift pattern to circuit along a path. Completes circular shift with a depth of 2n + 3 and 4n - 1 CNOT gates when n > 1, where n is the number of connections in the path. qc: the QuantumCircuit object...
71,408
def unfold_arrow(arrow): """Extract a list of types from an arrow type :param arrow: A type, preferably an arrow type :type arrow: :class:`discopy.closed.Ty` :return: A list of the arrow's components, or of the original type :rtype: list """ if isinstance(arrow, Under): return [arr...
71,409
def test_step(X, m_pre, m_fp): """ Test step used for mini-search-validation """ X = tf.concat(X, axis=0) feat = m_pre(X) # (nA+nP, F, T, 1) m_fp.trainable = False emb_f = m_fp.front_conv(feat) # (BSZ, Dim) emb_f_postL2 = tf.math.l2_normalize(emb_f, axis=1) emb_gf = m_fp.div_enc(emb_f) ...
71,410
def calc_sett_rewards(badger, periodStartBlock, endBlock, cycle, unclaimedRewards): """ Calculate rewards for each sett, and sum them """ # ratio = digg_btc_twap(periodStartBlock,endBlock) # diggAllocation = calculate_digg_allocation(ratio) rewardsBySett = {} noRewards = ["native.digg", "exp...
71,411
def load_data(): """ Download the required data used for RTEX classification (if they are not already present) """ Path("data").mkdir(parents=True, exist_ok=True) if not os.path.isdir("data/tags"): print("Downloading image tags ...") gdown.download("https://drive.google.com/uc?id=1nu...
71,412
def get_detector_module_slices(detector): """ Helper function to read data_origin and data_size from the NXdetector_modules in a NXdetector. Returns a list of lists, where each sublist is a list of slices in slow to fast order. Assumes slices are stored in NeXus in slow to fast order. """ #...
71,413
def main(**prepared_args): """ main conversion runner :param prepared_args kwargs: :return: """ conversion_result = None if prepared_args['conversion_type'] == 'csv_to_parquet': conversion_result = converter_csv_to_parquet(prepared_args['source_file_path'], ...
71,414
def write_config(config): """ Writes config to file. Args: config: Configuration to write. """ with open(config_path, "w") as configfile: config.write(configfile)
71,415
def createInvSphere(size:int, file : str): """ Creates a sphere dataset with a density of 0 in the very center and 1 at the corners """ print("Create sphere of size",size,"and save to",file) data = np.zeros((size, size, size), dtype=np.float32) s = size / 2 f = 2 / math.sqrt((s**2) * 3) ...
71,416
def _format_json(data, theme): """Pretty print a dict as a JSON, with colors if pygments is present.""" output = json.dumps(data, indent=2, sort_keys=True) if pygments and sys.stdout.isatty(): style = get_style_by_name(theme) formatter = Terminal256Formatter(style=style) return pygm...
71,417
def test_schemehost_noport80(): """Test.""" u = pytan3.http_client.UrlParser("http://host") assert u.hostname == "host" assert u.port == 80 assert u.scheme == "http"
71,418
def get_tm_session(session_factory: sessionmaker, transaction_manager: TransactionManager) -> Session: """ Get a ``sqlalchemy.orm.Session`` instance backed by a transaction. This function will hook the session to the transaction manager which will take care of committing any changes. - When using ...
71,419
def ensure_safe_threads(threads: int = Inputs.threads) -> None: """Ensures that the number of user supplied threads doesn't exceed system capacity Sets the number of threads to maximum available threads if threads exceed system capacity. Parameters ---------- threads : int Number of thread...
71,420
def get_test_from_anaconda(url): """ Given the URL of an anaconda tarball, return tests """ try: tarball = get_file_from_recipe_url(url) except tarfile.ReadError: return None try: metafile = tarball.extractfile('info/recipe/meta.yaml') except (tarfile.ReadError, KeyE...
71,421
def calculate_reservoir_rate(var, surf_mask, surf_type=None): """Inputs are two maps (var and surf_mask). Whereas there may be scripts that calculate the masked means, this calculates the volume flow rate (ie, not the flux density, but the total flux. This is currently written to only apply to w...
71,422
def get_schedules(filter_params, dbinfo=None, fields=None): """ Helper function to get schedule data for a request. :param filter_params: dict mapping constraint keys with values. Valid constraints are defined in the global ``constraints`` dict. :param dbinfo: optional. If provided, defines (connec...
71,423
async def get_forge_godly_description(message_content: str, message: discord.Message) -> str: """Returns the embed description for the forge_godly event""" user_name_string = 'exhausted' user_name_start = message_content.find(user_name_string) + len(user_name_string) + 1 user_name_end = message_content....
71,424
async def unmoot(unmot): """ For .unmute command, unmute the replied/tagged person """ # Admin or creator check chat = await unmot.get_chat() admin = chat.admin_rights creator = chat.creator # If not admin and not creator, return if not (admin or creator): return await unmot.edit(NO...
71,425
def objective_value(x, w): """Compute the value of a cut. Args: x (numpy.ndarray): binary string as numpy array. w (numpy.ndarray): adjacency matrix. Returns: float: value of the cut """ X = np.outer(x, (1-x)) w_01 = np.where(w != 0, 1, 0) return np.sum(w_01 * X)
71,426
def setEncoding(encoding = None): """ 라이브러리용 엔코딩 설정 함수 기본 엔코딩 정보를 설정한다 인자값 목록 (모든 변수가 반드시 필요): encoding : 문자열 엔코딩 정보 결과값 : 현재 설정된 기본 엔코딩 정보 """ global _default_encoding try: str("dummy", encoding) except: return _default_encoding _default_encoding = encoding or _default_encoding return _defau...
71,427
def build(context): """ Build the current python version """ context.run("python setup.py sdist bdist_wheel --universal")
71,428
def _create_v2_request_with_keyranges( sql, new_binds, keyspace_name, tablet_type, keyranges, not_in_transaction): """Make a request dict from arguments. Args: sql: Str sql with format tokens. new_binds: Dict of bind variables. keyspace_name: Str keyspace name. tablet_type: Str tablet_type. ...
71,429
def generate_meme(image_path, meme_text): """ Generate meme with image and text """ pic = Image.open(image_path).convert("RGBA") pic = pic.resize((600, 300), Image.LANCZOS) background = Image.new("RGBA", (900, 700), "white") Image.Image.paste(background, pic, (150, 200)) draw = ImageDr...
71,430
def shuffle(images, labels): """ Return shuffled data. """ permutation = np.random.permutation(images.shape[0]) return images[permutation], labels[permutation]
71,431
def Linear(input_size, hidden_size, with_bias=True): """tbd""" fan_in = input_size bias_bound = 1.0 / math.sqrt(fan_in) fc_bias_attr = paddle.ParamAttr(initializer=nn.initializer.Uniform( low=-bias_bound, high=bias_bound)) negative_slope = math.sqrt(5) gain = math.sqrt(2.0 / (1 + negative_slop...
71,432
def uuid_mole_index(moles, mole_uuid): """Return the index of the first mole with the specified uuid.""" for i, mole in enumerate(moles): if mole["uuid"] == mole_uuid: return i return None
71,433
def test_blocks(): """ Check transactions in each of a random sample of blocks. Send a request to https://etherchain.org/api/block/:block/tx to get a list of all transactions that occurred in that block. Cross-reference with the transactions in the local block (in mongo). """ c = Crawler.Cr...
71,434
def edge_plate2( plate: int = 384, sigma: Optional[float] = None, spread: Optional[float] = None, invert: Optional[float] = None, randomise_edges: bool = False, ) -> Plate: """ Create a plate with an edge effect. Use a diffusion model to influence edge wells with values beyond the ed...
71,435
def check_if_sent(cursor, database, sensor, relaxation): """ Verify if the notification for given sensor was sent or not within the period specified by relaxation. :param cursor: cursor to database connection :param database: database connection :param sensor: name of the sensor for which the notifi...
71,436
def html_detail_line( fp, dmap, label, resL ): """ Called once per line for detailing a test. The 'label' is the test run id. """ dL = dmap.getDateList() # create a map of the date to the result color hist = {} for fd,rs in resL: day = DateInfoString( fd ) hist[ day ] = ( r...
71,437
def to_timetable(stops_df, stop_times_df, trips_df) -> Timetable: """Convert a pandas timetable to Raptor algorithm datatypes""" # Stations and stops, i.e. platforms stations = Stations() stops = Stops() for s in stops_df.itertuples(): station = Station(s.stop_uic, s.stop_uic) stat...
71,438
def arg_with_type(model: int): """ Some doc in arg_with_type. """
71,439
def syntax_warning(space, msg, fn, lineno, offset): """Raise an applevel SyntaxWarning. If the user has set this warning to raise an error, a SyntaxError will be raised.""" w_msg = space.newtext(msg) w_filename = space.newtext(fn) w_lineno = space.newint(lineno) w_offset = space.newint(offs...
71,440
def shock_analysis(tags): """ Prepare demand and supply shock analysis. See ffsc.interdiction.interdiction_pipeline.py for detailed tags. \b AVAILABLE TOP-LEVEL TAGS: ------------------------- --sds_counterfactual : Prepare Sustainable Development Scenario demand shock analysis. ...
71,441
def cobjects(url='/display/DOCS/REST+Complex+Objects'): """Scrape Cobjects spec.""" print('==> Cobjects', end='') degenerated = {} u_types = set() d_types = {} for name, href in indexer(url): print('.', end='') page = bs(requests.get(BASE + href).text).select('.table-wrap')[0]...
71,442
def pearson_between_feature(X,threshold): """ Computes the Pearson Correlation between each feature and drops the higlhy correlated features Keyword arguments: X -- The feature vectors y -- The target vector threshold -- Threshold value used to decide which features to keep (above the threshold) """ if verbos...
71,443
def bin_concrete_sample(a, temperature, hard = False, eps = 1e-8): """" Sample from the binary concrete distribution """ device = torch.device("cuda" if a.is_cuda else "cpu") U = torch.rand(a.shape) L = Variable(torch.log(U + eps) - torch.log(1. - U + eps)).to(device) X = torch.sigmoid((L + a) / temperature) #...
71,444
def product_update(uuid): """ Product update route :return Endpoint with RESTful pattern # pylint: disable=line-too-long See https://madeiramadeira.atlassian.net/wiki/spaces/CAR/pages/2244149708/WIP+-+Guidelines+-+RESTful+e+HATEOS :rtype flask.Response --- put: sum...
71,445
def configure_func() -> None: """Can raise Exception """ ...
71,446
def test_do_calculate_part_stress_capacitor(subcategory_id, test_attributes): """_do_calculate_part_stress() should return the Capacitor attribute dict with updated values on success.""" test_attributes["category_id"] = 4 test_attributes["subcategory_id"] = subcategory_id _attributes = milhdbk217f._...
71,447
def test_bad_references(mapper): """Check badly formed references""" from pydantic import ValidationError bad_refs = [ {"id": "AAAA", "type": "references", "doi": "10.1234/1234"}, # bad id {"id": "newton1687", "type": "references"}, # missing all fields {"id": "newton1687", "type"...
71,448
def check_procs(procs: Dict[int, Popen]) -> List[bool]: """Checks on the status of running jobs. Args: procs (Dict[int, Popen]): A dictionary where the keys are the worker ids and the values are the process objects Returns: A list of booleans indicating if ...
71,449
def compute_permutation_distance( distance_matrix: np.ndarray, permutation: List[int] ) -> float: """Compute the total route distance of a given permutation Parameters ---------- distance_matrix Distance matrix of shape (n x n) with the (i, j) entry indicating the distance from node...
71,450
def dashboard(request): """ Display applications owned by the current user. Include dependency info in the context! """ if not utils.email_check(request): return HttpResponseRedirect(reverse('profiles_my_profile_detail')) # all apps by this user apps_data = {} for app i...
71,451
def create_bus_trace(net, buses=None, size=5, patch_type="circle", color="blue", infofunc=None, trace_name='buses', legendgroup=None, cmap=None, cmap_vals=None, cbar_title=None, cmin=None, cmax=None, colormap_column="vm_pu"): """ Creates a plotly trace of pandapower bus...
71,452
def test_grdtrack_wrong_kind_of_grid_input(dataarray, dataframe): """ Run grdtrack using grid input that is not as xarray.DataArray (grid) or file. """ invalid_grid = dataarray.to_dataset() assert data_kind(invalid_grid) == "matrix" with pytest.raises(GMTInvalidInput): grdtrack(poin...
71,453
def encrypt(text): """encrypt """ if text is None or not isinstance(text, str): return None return AESCipher.cipher.encrypt(text)
71,454
def fft_convolve(signal, kernel, conv_mode = CONV_MODE.DEFAULT): """ Non batched FFT Convolution. This function performs n-dimensional convolution based on input dimensionality. Parameters ----------- signal: af.Array - An n-dimensional array. kernel: af.Array - A...
71,455
def pick_frames(poses, is_train=True): """Pick valid frames, each ~GAP apart. Since some frames may have invalid poses, we first extract the longest segment we can without a gap larger than GAP (for 'train') We then sample from this longest segment. For 'train', some sampled frames might be invalid,...
71,456
async def info(msg, mobj): """ Return current channel/guild information """ chan = mobj.channel serv = mobj.guild chan_name, serv_name = None, None chan_id, serv_id = 0, 0 if hasattr(chan, 'name'): chan_name = chan.name if hasattr(serv, 'name'): serv_name = serv.name if hasattr(c...
71,457
def test_get_remediation_action(requests_mock): """Tests the armorblox-check-remediation-action command function. Configures requests_mock instance to generate the appropriate get_alert API response, loaded from a local JSON file. Checks the output of the command function with the expected output. "...
71,458
def run_graph(device, input_shape, axes, num_layers, py, scale, train, num_iters): """Run the graph and print its execution time. Args: device: string, the device to run on. input_shape: shape of the input tensor. axes: axes that are to be normalized across. num_layers: number of batc...
71,459
def make_masked_coordinate_tensor(mask, dims=(28, 28, 28)): """Make a coordinate tensor.""" coordinate_tensor = [torch.linspace(-1, 1, dims[i]) for i in range(3)] coordinate_tensor = torch.meshgrid(*coordinate_tensor) coordinate_tensor = torch.stack(coordinate_tensor, dim=3) coordinate_tensor = coo...
71,460
def main(): """Program main entry""" args = command_line_args() if not os.path.exists(args.pcap): print('Input pcap file "{}" does not exist'.format(args.pcap), file=sys.stderr) sys.exit(-1) if os.path.exists(args.csv): print('Output csv file "{}" already exists, ...
71,461
def atleast_2d_col(A): """ Return the input `A` as a 2d column array. """ return atleast_2d(A,'col')
71,462
def f_read_raw_mat_length(filename, data_format='f4'): """f_read_raw_mat_length(filename,data_format='float',end='l') Read length of data """ f = open(filename,'rb') tmp = f.seek(0, 2) bytes_num = f.tell() f.close() if data_format == 'f4': return int(bytes_num / 4) else: ...
71,463
def automl_params_overwrite(params): """Overwrite some training options based on the selected automl mode""" params_copy = params.copy() if params_copy["forecasting_style"].startswith("auto"): params_copy["season_length"] = get_seasonality(params_copy["frequency"], DEFAULT_SEASONALITIES) par...
71,464
def Checkout(name, url, dir): """Checkout the SVN module at url into dir. Use name for the log message.""" print "Checking out %s r%s into '%s'" % (name, LLVM_WIN_REVISION, dir) command = ['svn', 'checkout', '--force', url + '@' + LLVM_WIN_REVISION, dir] if RunCommand(command, fail_hard=False): return i...
71,465
def parse_StatsReq(msg, packet): """ Parse StatReq messages Args: msg: packet: """ # Get type = 16bits # Get flags = 16bits of_stat_req = packet[0:4] ofstat = unpack('!HH', of_stat_req) msg.stat_type = ofstat[0] msg.flags = ofstat[1] start = ...
71,466
def apply_feature( context, entity, feature, values, country=None, start_date=None, end_date=None, comment=None, authority=None, date_formats=[], ): """This is pretty specific to the needs of OFAC/CSL data.""" feature = feature.replace("Digital Currency Address - ", "") ...
71,467
def clearImageFolder(): """Clears the contents of the image folder. """ filelist = listImageFolder() for f in filelist: os.remove('{}/{}'.format(imageFolder, f))
71,468
def test_get_identifiable_applications_success_partner(requests_mock): """ Testing successful HTTP response to get_identifiable_applications as a partner """ test_response = [{"edgeId" : 1}, {"edgeId" : 2}] mock = requests_mock.post(f'{ORCHESTRATOR}/portal/rest/configuration/'\ ...
71,469
def test_list_negative_integer_max_length_1_nistxml_sv_iv_list_negative_integer_max_length_2_2(mode, save_output, output_format): """ Type list/negativeInteger is restricted by facet maxLength with value 6. """ assert_bindings( schema="nistData/list/negativeInteger/Schema+Instance/NISTSchema...
71,470
def test_precmd_handler_runs(): """Test attached precmd handler is executed. If it executes the value in val will change to True. """ # Treat val as a box (list) instead of a variable to get around Pythons # scoping rules. val = [False] def precmd(line): val[0] = True retur...
71,471
def load_message_to_db(message_value: str) -> None: """Loads the consumed messages values to a postgres table to not exceed memory. Args: - message_value: str, the message value consumed from input_topic. Returns: None. """ db = create_engine(DB_URL) connection = db.connect()...
71,472
def plot_rolling_returns_multiple(returns_arr, factor_returns=None, logy=False, ax=None, names_arr=None, extra_bm=0): """ Plots cumulative rolling returns versus some benchmarks'. This is based on https://github.com/quantopian/pyfolio/blob/master/pyfolio/plotting.py, but modified to plot multiple rolli...
71,473
def serve(): # pragma: no cover """Servidor WSGI predeterminado.""" from waitress import serve as server if not CONFIG: init_app() if environ.get("LMS_PORT"): PORT: int = int(environ.get("LMS_PORT")) elif environ.get("PORT"): PORT = int(environ.get("PORT")) else: ...
71,474
def _analyze_gens(gens): """Support for passing generators as `*gens` and `[gens]`. """ if len(gens) == 1 and hasattr(gens[0], '__iter__'): return tuple(gens[0]) else: return tuple(gens)
71,475
def canonical_representation(a, d, DE): """ Canonical Representation. Given a derivation D on k[t] and f = a/d in k(t), return (f_p, f_s, f_n) in k[t] x k(t) x k(t) such that f = f_p + f_s + f_n is the canonical representation of f (f_p is a polynomial, f_s is reduced (has a special denominator...
71,476
def load_protocol_from_csv_file(path, session=None): """ Read a (.csv) paradigm file consisting of values yielding (occurence time, (duration), event ID, modulation) and returns a paradigm instance or a dictionary of paradigm instances Parameters ---------- path: string, path ...
71,477
def get_driver(worker_url=None): """ :rtype: dao.control.worker.provisioning.foreman.ForemanDriver """ module, obj = CONF.worker.provision_driver.rsplit('.', 1) LOG.info('Load %s from %s', obj, module) module = eventlet.import_patched(module) return getattr(module, obj)(worker_url)
71,478
def temporary_credential_file_delete_password(host, user, cred_type): """Remove credential from temporary credential file when OS is Linux.""" if not CACHE_DIR: # no cache is enabled return global TEMPORARY_CREDENTIAL global TEMPORARY_CREDENTIAL_LOCK with TEMPORARY_CREDENTIAL_LOCK: ...
71,479
def test_face_2_vec_works(): """ Testing FaceNet works """ model = Face2Vec() assert_encoder_works(model, 128, data_type='image', image_url='https://www.thestatesman.com/wp-content/uploads/2017/08/1493458748-beauty-face-517.jpg')
71,480
def preparation_time_in_minutes(number_of_layers: int) -> int: """ Args: number_of_layers (int): the number of layers you want to add to the lasagna. Returns: int: how many times you would spend making them. """ return 2 * number_of_layers
71,481
def quicksort(x): """ Describe how you are sorting `x` Goal: First: Select a pivot point. In this case the first bin in the list. Second: Put all of other items in the list ordered arround the pivot variable Third: Recursively do the same to each side of the list Fourth: If the list be...
71,482
def normpath(path): """Returns the fully resolved absolute path to a file. This function will return the absolute path to a file as seen from the directory the script was called from. """ if path and path[0] == '/': return os.path.normpath(path) return os.path.normpath(os.path.join(os....
71,483
def gb_to_mib(gb: Union[int, float]) -> float: """ Gigabyte (Gb) to Mebibyte (MiB) :param gb: Gigabytes (Gb) :return: Mebibytes (MiB) """ return gb * 953.674
71,484
def getPendingUpdate() -> Optional[Tuple]: """Returns a tuple of the path to and version of the pending update, if any. Returns C{None} otherwise. """ try: pendingUpdateFile=state["pendingUpdateFile"] pendingUpdateVersion=state["pendingUpdateVersion"] pendingUpdateAPIVersion=state["pendingUpdateAPIVersion"] or...
71,485
def walk_sources_from_command(command: instances.FilesRelatedCommand, filesystem: Filesystem ) -> Iterator[Tuple[str, str, str]]: """Typical iteration by command settings.""" return walk(command.sources_folder, filesystem, command.branc...
71,486
def can_access_uri_part(context, request, uri_part): """Tell if current user can to access a URI part relative to context.""" assert uri_part is not None traverser = zope.traversing.publicationtraverse.PublicationTraverser() try: view = traverser.traverseRelativeURL(request, context, uri_part) ...
71,487
def get_trainables(): """Get all the trainable variables in the current default session.""" sess = tf.get_default_session() result = {} for tvar in tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES): result[tvar.name] = sess.run(tvar).tolist() return result
71,488
def _encode_entity_id(entity_type, entity_id): """See xidCgiDelimiter = "?xid=" """ return "xid=%s.%s" % (entity_type, entity_id)
71,489
def save_hdf_file(file_path, idata, key_path='entry', overwrite=True): """ Write data to a hdf5 file. Parameters ---------- file_path : str Output file path. idata : array_like Data to be saved. key_path : str Key path to the dataset. overwrite : bool, optio...
71,490
def _create_pdb_atoms_from_cif(cif_atoms, cif_fields, identifier): """ Transform mmCIF atoms into pdb atoms. Parameters ---------- cif_atoms : list of str lines with atoms details in CIF format cif_fields : dict (str : int) key: field name value: index where to look for s...
71,491
def _check_perm_err(errstring): """Check if the error string is a /dev/zfs permission error This error only seems to occur on zfsonlinux (not sure about FreeBSD). Solaris has fine-grained delegated auth for ZFS so errors will be specific to each call """ if errstring == ZFS_ERROR_STRINGS['perme...
71,492
def discard_non_functional_deployments( deployments: SynchronizedDeployments) -> SynchronizedDeployments: # noqa """Discards deployments that were not expired, but are no longer functional, e.g. were cancelled.""" log = get_logger(__name__) all_nodes = [] for nodes in deployments.nodes: ...
71,493
def get_session(): """获取当前用户session""" return request.environ.get('beaker.session')
71,494
def find_average_record(sen_set, voting_dict): """ Input: a set of last names, a voting dictionary Output: a vector containing the average components of the voting records of the senators in the input set Example: >>> voting_dict = {'Klein': [-1,0,1], 'Fox-Epstein': [-1,-1,-1], 'Rav...
71,495
def HTTP_POST_flask_config_general(): """This endpoint expects json of generalConfig. Optional argument 'restart' may be passed. When argument 'restart=true', the device starts automatically with new configuration.""" try: config = request.get_json() dabing.postConfig(config...
71,496
def test_base_estimator_default(): """Assert that GP is the default base estimator.""" trainer = DirectClassifier("LR", n_calls=5, random_state=1) trainer.run(bin_train, bin_test) assert trainer._bo["base_estimator"] == "GP"
71,497
def get_allparams_cleaned_mdl(mydata): """输入是被定位出来的含有出事model内容的mdl列表,称为mydata。输出被正则替换掉全部参数的mdl列表""" # 这一段注释是测试代码,用于验证正则表达式 # pattern = re.compile(r"\'([-]*[0-9.E]*\-*\d*)[+-]*.*?\'") # 这是当初为钟灿写的正则,我现在也看不太懂了。 # for line in mydata: # if "'" in line: # print(line) # print(pattern.findall(line)) ...
71,498
def transformer_ae_small(): """Set of hyperparameters.""" hparams = transformer.transformer_small() hparams.batch_size = 2048 hparams.learning_rate = 0.2 hparams.learning_rate_warmup_steps = 4000 hparams.num_hidden_layers = 3 hparams.hidden_size = 384 hparams.filter_size = 2048 hparams.add_hparam("com...
71,499